dorkos 0.111.0 → 0.114.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 (192) hide show
  1. package/core-extensions/hello-world/index.ts +2 -2
  2. package/dist/bin/cli.js +13549 -1698
  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-BKzqcz_A.js → AboutPage-mErbIY0l.js} +1 -1
  6. package/dist/client/assets/{ActivityErrorState-BXOZg9ve.js → ActivityErrorState-AlI4F82u.js} +1 -1
  7. package/dist/client/assets/{ActivityPage-CFN2MEAV.js → ActivityPage-CHUqb-8c.js} +1 -1
  8. package/dist/client/assets/{ActivityRow-CujXx04u.js → ActivityRow-Baqdr6cP.js} +1 -1
  9. package/dist/client/assets/AdapterIcon-C_fBZXHQ.js +1 -0
  10. package/dist/client/assets/{AdapterSetupWizard-3Bt9HEWF.js → AdapterSetupWizard-BL70qy2J.js} +2 -2
  11. package/dist/client/assets/{AgentRequestCard-CAaBGC0L.js → AgentRequestCard-CcMh6JyE.js} +3 -3
  12. package/dist/client/assets/{AppearancePage-BEe-Gssu.js → AppearancePage-t9SnSRs-.js} +1 -1
  13. package/dist/client/assets/{AttentionSignalRow-Cp0AJs73.js → AttentionSignalRow-jlgWaSSd.js} +1 -1
  14. package/dist/client/assets/{BaseTanStackRouterDevtoolsPanel-B-iktbLX-CN1iW2cB.js → BaseTanStackRouterDevtoolsPanel-B-iktbLX-DHr_AhUv.js} +3 -3
  15. package/dist/client/assets/{BlintzCanvas-B7qs2dxW.js → BlintzCanvas-Bq4e7n__.js} +1 -1
  16. package/dist/client/assets/{CanvasCsvContent-DiB5zXOC.js → CanvasCsvContent-OR226CLS.js} +2 -2
  17. package/dist/client/assets/CanvasFileContent-BejM-9Wg.js +2 -0
  18. package/dist/client/assets/CanvasModel3dContent-BD-eCVsX.js +2 -0
  19. package/dist/client/assets/{CodeMirrorDiff-BJhflpbC.js → CodeMirrorDiff-D7BWMOim.js} +1 -1
  20. package/dist/client/assets/{CodeMirrorEditor-SkdXRKSN.js → CodeMirrorEditor-BodwsIG7.js} +1 -1
  21. package/dist/client/assets/{CommitmentList-DsEn6iK1.js → CommitmentList-YVb3yTvO.js} +1 -1
  22. package/dist/client/assets/{CommitmentsPage-W5h0GjRr.js → CommitmentsPage-DL_jJQbw.js} +1 -1
  23. package/dist/client/assets/{ConnectionAccessLists-DVFqelmV.js → ConnectionAccessLists-BPsgToSR.js} +1 -1
  24. package/dist/client/assets/{ConnectionsPage-CZhSh2mO.js → ConnectionsPage-D7vlYnjf.js} +2 -2
  25. package/dist/client/assets/{ConventionPage-DcDBP-vR.js → ConventionPage-BR7I3AdE.js} +3 -3
  26. package/dist/client/assets/{ExtensionPageRoute-mKN8Jqyx.js → ExtensionPageRoute-CzXGvVRm.js} +2 -2
  27. package/dist/client/assets/{FloatingTanStackRouterDevtools-CqogiFob-CGXG-x9g.js → FloatingTanStackRouterDevtools-CqogiFob-BV3h0rFa.js} +1 -1
  28. package/dist/client/assets/HandlePage-B33P0oh0.js +1 -0
  29. package/dist/client/assets/{HeartbeatPage-DFf7Udem.js → HeartbeatPage-CfjZuvtQ.js} +1 -1
  30. package/dist/client/assets/{LexicalField-vJ284m2H.js → LexicalField-Cc6wFZAZ.js} +2 -2
  31. package/dist/client/assets/{ManagesPage-mDuaA2JT.js → ManagesPage-BxHSb65X.js} +1 -1
  32. package/dist/client/assets/{Marketplace-BoiupH2Z.js → Marketplace-EgG6JmBG.js} +4 -4
  33. package/dist/client/assets/{MarketplaceSourcesView-krw9hUyu.js → MarketplaceSourcesView-D9kq9hl6.js} +1 -1
  34. package/dist/client/assets/{McpAppFrame-DmHduNgp.js → McpAppFrame-6zxszx9A.js} +2 -2
  35. package/dist/client/assets/{McpSigninBody-DoY09n4J.js → McpSigninBody-DBWSc6bm.js} +1 -1
  36. package/dist/client/assets/{Model3dViewer-BZEdR7-9.js → Model3dViewer-CgeJ2v-F.js} +1 -1
  37. package/dist/client/assets/NamePage-MfybpnwN.js +1 -0
  38. package/dist/client/assets/NewDirectMessageMenu-BnBO4aGI.js +1 -0
  39. package/dist/client/assets/{NotificationsPage-CybW1eIb.js → NotificationsPage-C5aRITCd.js} +1 -1
  40. package/dist/client/assets/{OpenMeshSwitch-DrmjsCDY.js → OpenMeshSwitch-UKMQeS7-.js} +2 -2
  41. package/dist/client/assets/{OperatorIdentityForm-byU2FeSU.js → OperatorIdentityForm-DH2au7QU.js} +1 -1
  42. package/dist/client/assets/{PermissionsPage-CP3kbqyJ.js → PermissionsPage-BgLLmdg2.js} +1 -1
  43. package/dist/client/assets/{PersonalityPopover-BLsjgaum.js → PersonalityPopover-vLDfndfo.js} +1 -1
  44. package/dist/client/assets/PhotoPage-BgyB3B2_.js +1 -0
  45. package/dist/client/assets/{PreviewRefusedNotice-fTN8MJ1h.js → PreviewRefusedNotice-Dh3SCC_A.js} +1 -1
  46. package/dist/client/assets/{PromptSuggestionChips-BZOaY5Tx.js → PromptSuggestionChips-EO_0zbzq.js} +1 -1
  47. package/dist/client/assets/{ReportsToPopover-B6JvfRt3.js → ReportsToPopover-C9Ceg1AW.js} +1 -1
  48. package/dist/client/assets/{RoomSurface-BM0QO_av.js → RoomSurface-B8ec3_at.js} +8 -8
  49. package/dist/client/assets/{RoomsPage-B-NOCLXC.js → RoomsPage-pPw8vrsB.js} +1 -1
  50. package/dist/client/assets/{RunsOnPopover-D1jQQatj.js → RunsOnPopover-CJoSj8w7.js} +1 -1
  51. package/dist/client/assets/RuntimeSetupDialog-Cqn_Grel.js +1 -0
  52. package/dist/client/assets/SessionsPage-BASybh9v.js +1 -0
  53. package/dist/client/assets/{SkillsPage-CPTFjEUe.js → SkillsPage-DL0909et.js} +1 -1
  54. package/dist/client/assets/{TasksPage-BRUqs3v5.js → TasksPage-BwUW6dia.js} +1 -1
  55. package/dist/client/assets/{ToolsPage-C25kL822.js → ToolsPage-C3xfGWdb.js} +2 -2
  56. package/dist/client/assets/{TopologyGraph-of6Cp5Kj.js → TopologyGraph-D7Ik1Xt6.js} +1 -1
  57. package/dist/client/assets/{TourHost-zwSilkjm.js → TourHost-Db0fxAXo.js} +1 -1
  58. package/dist/client/assets/{UnlinkDialog-BgwHAqdW.js → UnlinkDialog-TTK5Z_QD.js} +1 -1
  59. package/dist/client/assets/{WidgetErrorCard-BQwrR6PJ.js → WidgetErrorCard-D--KcgW1.js} +24 -29
  60. package/dist/client/assets/_shell-CGWsN6Gs.js +88 -0
  61. package/dist/client/assets/{_shell._home-BkP0NafS.js → _shell._home-CzpVyTzo.js} +1 -1
  62. package/dist/client/assets/{_shell._home.activity-BO_2ciGK.js → _shell._home.activity-BbWquOK0.js} +1 -1
  63. package/dist/client/assets/_shell._home.index-Cg0nRFMN.js +3 -0
  64. package/dist/client/assets/_shell._home.tasks-BpoOVihw.js +1 -0
  65. package/dist/client/assets/{_shell._home.workspaces-B34Uk1SP.js → _shell._home.workspaces-DVF1rM3t.js} +1 -1
  66. package/dist/client/assets/_shell.channels-CCGSs0Bn.js +10 -0
  67. package/dist/client/assets/{_shell.connections-BNbeBrxQ.js → _shell.connections-0_34lXIQ.js} +1 -1
  68. package/dist/client/assets/{_shell.feedback-requests-B71l48KB.js → _shell.feedback-requests-C6alx2ox.js} +1 -1
  69. package/dist/client/assets/_shell.marketplace-Dp-p8E3V.js +1 -0
  70. package/dist/client/assets/_shell.marketplace_.sources-SN2Fb1eb.js +1 -0
  71. package/dist/client/assets/{_shell.session-ybAc0bwn.js → _shell.session-Bt3jdQdD.js} +15 -15
  72. package/dist/client/assets/_shell.team-BIwJNdkd.js +28 -0
  73. package/dist/client/assets/_shell.x._extensionId-Bjn-MKsP.js +1 -0
  74. package/dist/client/assets/_shell.x._extensionId_._-Bjn-MKsP.js +1 -0
  75. package/dist/client/assets/{agent-browser-Cs8abkZs.js → agent-browser-CO5haI5Y.js} +1 -1
  76. package/dist/client/assets/{banner-CU2Nh3Kv.js → banner-Dh5mO27l.js} +2 -2
  77. package/dist/client/assets/{card-BTgwskmX.js → card-CKZCX8ol.js} +1 -1
  78. package/dist/client/assets/{file-DlQX-hKl.js → file-CMPbZedq.js} +1 -1
  79. package/dist/client/assets/{file-exclamation-point-Dg2iCyPM.js → file-exclamation-point-emLeXvmw.js} +1 -1
  80. package/dist/client/assets/file-text-9a0DChCq.js +6 -0
  81. package/dist/client/assets/{find-latest-widget-fence-BGiexm6r.js → find-latest-widget-fence--3kWMT1F.js} +3 -3
  82. package/dist/client/assets/{git-branch-Dq_w3Iyx.js → git-branch-hfu8isLA.js} +1 -1
  83. package/dist/client/assets/{heart-Bp14wOx6.js → heart-SRafwnSd.js} +1 -1
  84. package/dist/client/assets/{highlighted-body-KPVGNVTW-kD1HK_wk.js → highlighted-body-KPVGNVTW-Dxwd3mxT.js} +1 -1
  85. package/dist/client/assets/index-3GDQSKet.js +1 -0
  86. package/dist/client/assets/{index-BA-nPsLw.js → index-BB18IeC2.js} +1 -1
  87. package/dist/client/assets/index-BBQMqcO_.js +1 -0
  88. package/dist/client/assets/{index-CcV9S7cO.js → index-BDfoFNcA.js} +1 -1
  89. package/dist/client/assets/{index-DNglWRBB.js → index-BNn3-chz.js} +1 -1
  90. package/dist/client/assets/{index-Dm53S0up.js → index-BRGOMmOM.js} +1 -1
  91. package/dist/client/assets/{index-5OyUurJr.js → index-BTXBESRm.js} +1 -1
  92. package/dist/client/assets/{index-B8R78Nnj.js → index-BTreBsWa.js} +2 -2
  93. package/dist/client/assets/{index-kHXlTLUx.js → index-BUVKya1M.js} +8 -8
  94. package/dist/client/assets/{index-aDNEGBTK.js → index-BYp9xcmS.js} +1 -1
  95. package/dist/client/assets/{index-DnmtTIUB.js → index-BokDvdOG.js} +1 -1
  96. package/dist/client/assets/{index-BxrZwUJp.js → index-C3xuhmPa.js} +2 -2
  97. package/dist/client/assets/{index-B6_ikFYj.js → index-C4nEz6I-.js} +1 -1
  98. package/dist/client/assets/{index-Dr-0P6rd.js → index-C63bLSO4.js} +267 -262
  99. package/dist/client/assets/{index-Cc280M3V.js → index-C7BTAdSc.js} +1 -1
  100. package/dist/client/assets/{index-knGXyHhh.js → index-CAlXjm0N.js} +1 -1
  101. package/dist/client/assets/index-CTxEG5rD.js +1 -0
  102. package/dist/client/assets/{index-gu2JYnOq.js → index-CbFo-7kM.js} +1 -1
  103. package/dist/client/assets/{index-DKlxz3u7.js → index-Ch41JOI2.js} +1 -1
  104. package/dist/client/assets/{index-BxUoa3yn.js → index-CkknQ52Q.js} +5 -5
  105. package/dist/client/assets/{index-C-DN0Vg_.js → index-Cow815Qa.js} +1 -1
  106. package/dist/client/assets/{index-DO6a5Hey.js → index-Cp7oifSs.js} +1 -1
  107. package/dist/client/assets/{index--3UwFg2s.js → index-CpYs0Lli.js} +1 -1
  108. package/dist/client/assets/{index-C99173Ze.js → index-D0Nd2LA-.js} +1 -1
  109. package/dist/client/assets/{index-BeBmUxo_.js → index-D67aFWxz.js} +1 -1
  110. package/dist/client/assets/index-DFEF2MFy.css +1 -0
  111. package/dist/client/assets/{index-CAhJGlSW.js → index-DIlV08Vw.js} +1 -1
  112. package/dist/client/assets/{index-BHsZlKfx.js → index-DLNwEM2Q.js} +1 -1
  113. package/dist/client/assets/{index-PxSRtDpP.js → index-DLZi_nae.js} +1 -1
  114. package/dist/client/assets/{index-LszRbEbX.js → index-DRqEM5Wb.js} +1 -1
  115. package/dist/client/assets/{index-B0OZehWe.js → index-DX-j3Ul0.js} +1 -1
  116. package/dist/client/assets/{index-CKCMjqcu.js → index-DX7V94qe.js} +1 -1
  117. package/dist/client/assets/{index-C_uYJzKi.js → index-D_Wc_qTa.js} +3 -3
  118. package/dist/client/assets/{index-DW6zqLoM.js → index-DdsKmfEH.js} +1 -1
  119. package/dist/client/assets/{index-DHUToGjI.js → index-DmTI5Hye.js} +1 -1
  120. package/dist/client/assets/{index-DKQDBIWq.js → index-YswfjpmW.js} +1 -1
  121. package/dist/client/assets/{index-DSPs6GF4.js → index-g_5oOlG6.js} +1 -1
  122. package/dist/client/assets/{index-DS-thlE8.js → index-iD0epmn3.js} +1 -1
  123. package/dist/client/assets/{index-CDWsIVX7.js → index-lJc8v0Z3.js} +1 -1
  124. package/dist/client/assets/index-t7gsOfUI.js +1 -0
  125. package/dist/client/assets/kickoff-xkt4LpIP.js +3 -0
  126. package/dist/client/assets/{layers-B0oCOfxz.js → layers-Cy8Tme6i.js} +1 -1
  127. package/dist/client/assets/{lightbulb-D80IzMqz.js → lightbulb-tNm7gLYi.js} +1 -1
  128. package/dist/client/assets/{markdown-content-aNzh-54y.js → markdown-content-CoK3F0c0.js} +1 -1
  129. package/dist/client/assets/{mention-pill-BxMK0xuY.js → mention-pill-Bgs_yujj.js} +1 -1
  130. package/dist/client/assets/{message-square-off-D-CJXmTq.js → message-square-off-CF2Bzen3.js} +1 -1
  131. package/dist/client/assets/{owner-notice-BkrTEMDm.js → owner-notice-cgCWG4hG.js} +1 -1
  132. package/dist/client/assets/{package-CoTlAnXZ.js → package-DE8sQpId.js} +1 -1
  133. package/dist/client/assets/{page-container-CPxW5T9E.js → page-container-BoXmmBSs.js} +1 -1
  134. package/dist/client/assets/{paperclip-Cj1P85mz.js → paperclip-IgDeVFea.js} +1 -1
  135. package/dist/client/assets/{radio-DICkTr_p.js → radio-BzTkFBDD.js} +1 -1
  136. package/dist/client/assets/{room-files-source-BywWQPBN.js → room-files-source-CIIDTSTA.js} +2 -2
  137. package/dist/client/assets/{rotate-ccw-clock-cx5RyP4l.js → rotate-ccw-clock-CGcSqHnk.js} +1 -1
  138. package/dist/client/assets/{rotate-cw-DrGRGSwy.js → rotate-cw-DaduzRfP.js} +1 -1
  139. package/dist/client/assets/{scroll-area-XlDz8u4m.js → scroll-area-DW0-Liri.js} +1 -1
  140. package/dist/client/assets/{search-x-LIKnWE64.js → search-x-Sme5ElYi.js} +1 -1
  141. package/dist/client/assets/{shield-x-DioB6qH_.js → shield-x-Bh5xap8N.js} +1 -1
  142. package/dist/client/assets/{soul-file-C7YgkNET.js → soul-file-NcuTUIiB.js} +1 -1
  143. package/dist/client/assets/{table-P4N5xQn2.js → table-BEtvgYmW.js} +1 -1
  144. package/dist/client/assets/{use-connector-management-pgVHbXoO.js → use-connector-management-Cohvs7jD.js} +1 -1
  145. package/dist/client/assets/{use-delete-binding-DxEiOjjh.js → use-delete-binding-C19umm_i.js} +1 -1
  146. package/dist/client/assets/{use-dev-links-BImQrE6g.js → use-dev-links-DRnLdl--.js} +1 -1
  147. package/dist/client/assets/{use-external-adapter-catalog-D8KHMSZU.js → use-external-adapter-catalog-BOn9aj72.js} +1 -1
  148. package/dist/client/assets/use-full-activity-feed-BpQANbns.js +1 -0
  149. package/dist/client/assets/use-is-below-desktop-5LlietdR.js +1 -0
  150. package/dist/client/assets/{use-jump-back-in-D9tBJ4v5.js → use-jump-back-in-CkFErfWY.js} +3 -3
  151. package/dist/client/assets/{use-mesh-topology-DBeqzUoy.js → use-mesh-topology-CIsDeAY0.js} +1 -1
  152. package/dist/client/assets/use-panel-tab-placements-AFrWTQ0a.js +1 -0
  153. package/dist/client/assets/use-pending-read-Dol8yvIx.js +1 -0
  154. package/dist/client/assets/{use-personality-commit-Gfoi__sT.js → use-personality-commit-fUtuc2lC.js} +1 -1
  155. package/dist/client/assets/{use-promo-activation-Bv1gnqKq.js → use-promo-activation-Dxt-1yuT.js} +3 -3
  156. package/dist/client/assets/{use-pulse-freshness-SFRdnugS.js → use-pulse-freshness-DRRM5Hza.js} +1 -1
  157. package/dist/client/assets/{use-room-follow-claim-Cf20JiJ_.js → use-room-follow-claim-huRfaa4e.js} +1 -1
  158. package/dist/client/assets/{use-roving-tab-list-3Pb7ps4E.js → use-roving-tab-list-BZIBAGgJ.js} +1 -1
  159. package/dist/client/assets/{use-session-canvas-BaXuEhw8.js → use-session-canvas-CZIsr9qL.js} +4 -4
  160. package/dist/client/assets/{use-session-diagnostics-7xxJ6zQQ.js → use-session-diagnostics-C41hV7rK.js} +4 -4
  161. package/dist/client/assets/{use-unclaimed-chats-D4k-EK_f.js → use-unclaimed-chats-BMlFQ2v1.js} +1 -1
  162. package/dist/client/index.html +2 -2
  163. package/dist/server/index.js +123677 -118335
  164. package/dist/server/index.js.map +2 -2
  165. package/package.json +7 -8
  166. package/dist/client/assets/AdapterIcon-BdM7K69W.js +0 -1
  167. package/dist/client/assets/CanvasFileContent-CDNfnWMW.js +0 -2
  168. package/dist/client/assets/CanvasModel3dContent-C7EINmuq.js +0 -2
  169. package/dist/client/assets/HandlePage-Bun58ePo.js +0 -1
  170. package/dist/client/assets/NamePage-CXyClUPJ.js +0 -1
  171. package/dist/client/assets/NewDirectMessageMenu-BjqYwnXW.js +0 -1
  172. package/dist/client/assets/PhotoPage-hn5b42qN.js +0 -1
  173. package/dist/client/assets/RuntimeSetupDialog-ufwCvCJB.js +0 -1
  174. package/dist/client/assets/SessionsPage-CBE1KHYg.js +0 -1
  175. package/dist/client/assets/_shell-bcx2y7VT.js +0 -88
  176. package/dist/client/assets/_shell._home.index-B-OFwU9u.js +0 -3
  177. package/dist/client/assets/_shell._home.tasks-jAQczH7j.js +0 -1
  178. package/dist/client/assets/_shell.channels-CGzsxvXD.js +0 -10
  179. package/dist/client/assets/_shell.marketplace-3YAsNaRk.js +0 -1
  180. package/dist/client/assets/_shell.marketplace_.sources-cI3nNBXr.js +0 -1
  181. package/dist/client/assets/_shell.team-BE_60YS4.js +0 -28
  182. package/dist/client/assets/_shell.x._extensionId-jiyP599c.js +0 -1
  183. package/dist/client/assets/_shell.x._extensionId_._-jiyP599c.js +0 -1
  184. package/dist/client/assets/index-B2JJZXsq.js +0 -1
  185. package/dist/client/assets/index-BAjUSKoJ.js +0 -1
  186. package/dist/client/assets/index-BpDY3eoD.js +0 -1
  187. package/dist/client/assets/index-ExcAk4pE.css +0 -1
  188. package/dist/client/assets/index-F7Lcwnfm.js +0 -1
  189. package/dist/client/assets/kickoff-Btbza7bw.js +0 -3
  190. package/dist/client/assets/use-full-activity-feed-2o7GNAMe.js +0 -1
  191. package/dist/client/assets/use-is-below-desktop-DBet5zg_.js +0 -1
  192. package/dist/client/assets/use-pending-read-DmrlNHS0.js +0 -1
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-Dm53S0up.js","assets/index-Dr-0P6rd.js","assets/index-ExcAk4pE.css"])))=>i.map(i=>d[i]);
2
- var ui=Object.defineProperty;var di=(e,t,n)=>t in e?ui(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Ze=(e,t,n)=>di(e,typeof t!="symbol"?t+"":t,n);import{oy as fi,oz as Qr,ns as Yr,oA as mi,oB as Xr,nH as pi,r as c,oC as Jr,oD as hi,oE as gi,oF as un,a4 as Qe,j as r,a3 as G,bl as ie,h0 as Zn,ae as xe,kL as Zr,w as at,iK as xi,oG as bi,oH as ea,oI as yi,oJ as vi,fQ as ki,B as ne,cQ as Ee,dc as Te,oK as ta,oL as lt,oM as Ve,Z as H,$ as ot,X as Le,oN as mt,iR as Ci,oO as Si,I as ji,oP as _i,oQ as dn,e5 as wi,oR as Ni,oS as Ei,fn as Di,b2 as gt,oT as na,gZ as Ai,oU as Ti,gi as Fi,dK as sa,h2 as Ri,aN as oe,oV as Mi,oW as $n,an as Ii,oX as Fs,dR as Rs,dQ as it,oY as Oi,oZ as $i,o_ as vt,o$ as Gt,aj as Ye,p0 as es,ag as kt,gB as jt,dP as ts,bW as _t,cV as Pi,cW as Li,cX as zi,cY as Bi,cZ as Ui,da as qi,e as Ms,hS as Hi,c_ as Wi,F as ze,hT as Vi,p1 as ns,dD as Gi,p2 as Ki,p3 as Qi,hL as ss,p4 as ra,p5 as aa,p6 as Yi,p7 as Xi,hD as rs,af as as,cf as wt,dN as os,d8 as is,dL as Ji,p8 as Zi,p9 as oa,pa as el,pb as tl,gV as nl,e1 as sl,gh as Ge,iB as Nt,dk as ls,pc as rl,b5 as al,df as Et,pd as Be,pe as Ue,iC as ia,pf as Xt,db as Dt,iD as ol,bV as ct,x as At,pg as il,kU as Is,lw as la,kV as ll,C as cs,bp as cl,bq as ul,ph as dl,l as fl,mm as ca,aK as ml,pi as pl,pj as hl,pk as gl,pl as xl,o3 as bl,nV as Jt,aL as yl,gK as vl,c0 as kl,bv as Cl,i3 as Sl,at as us,dd as Os,f as ua,pm as jl,eS as _l,aQ as wl,h9 as da,h5 as fa,lx as Ct,pn as ma,po as Nl,pp as El,pq as pa,pr as Dl,di as Al,ps as Tl,pt as Fl,pu as Rl,pv as Ml,v as ha,G as Zt,aJ as ga,pw as xa,px as Il,lN as fn,iq as Ol,jQ as $l,b7 as ba,hw as Pl,hx as $s,py as Pn,pz as ya,pA as Ll,pB as zl,pC as va,eW as Bl,kT as Ul,fR as ql,fS as Hl,fT as Wl,fU as Vl,fV as Gl,fW as Kl,fX as Ql,fY as Yl,pD as ds,pE as Xl,pF as Jl,pG as Zl,ik as ec,il as tc,im as nc,io as mn,pH as sc,ip as Ps,iA as rc,bA as ac,iE as oc,bC as ic,pI as Ls,c3 as lc,fG as ka,c8 as Ca,b_ as cc,c7 as uc,ce as Sa,cc as dc,ly as fs,pJ as fc,aq as mc,pK as pc,l2 as te,pL as hc,pM as gc,aa as xc,fA as zs,hy as We,pN as pn,ks as xt,nU as Ne,pO as Bs,pP as Us,pQ as qs,pR as hn,pS as st,eN as bt,pT as bc,pU as ja,pV as _a,pW as yc,pX as vc,pY as wa,lA as kc,pZ as Na,p_ as et,kG as Ea,p$ as Cc,bz as Sc,lz as jc,q0 as _c,q1 as wc,fo as Da,q2 as Nc,bH as Hs,mU as Aa,g7 as en,q3 as Ec,q4 as Dc,gf as Ta,gg as ms,j7 as Ac,q5 as Tc,q6 as Fc,q7 as Rc,q8 as Mc,q9 as Ic,cg as Oc,hz as $c,lE as Pc,fe as Lc,kO as zc,dv as Bc}from"./index-Dr-0P6rd.js";import{P as Uc}from"./PromptSuggestionChips-BZOaY5Tx.js";import{u as qc,a as Hc,L as Wc,f as Vc,b as Gc,c as Kc,B as Qc,d as Yc}from"./kickoff-Btbza7bw.js";import{E as Xc,F as Jc,e as Zc,h as eu,f as tu,P as nu,g as su,d as ru,q as au,j as ou,b as iu,G as lu,B as cu,H as Fa,z as uu,u as du,D as fu,v as mu,t as pu,p as hu,w as gu,y as xu,o as bu,n as yu,k as vu,s as ku,M as Cu,i as Su,S as ju,U as _u,A as wu,I as Nu,J as Eu,K as Ws,x as Du,R as Au}from"./use-session-diagnostics-7xxJ6zQQ.js";import{C as Tu}from"./card-BTgwskmX.js";import{B as Fu}from"./banner-CU2Nh3Kv.js";import{j as Ru,k as Mu,t as Mt,b as Ln,n as Iu,N as Ra,o as Ou,g as $u,C as St,M as tt,f as Pu,D as Lu,U as zu,F as Bu}from"./index-kHXlTLUx.js";import{a as Uu}from"./markdown-content-aNzh-54y.js";import{u as qu,b as Hu,F as Wu}from"./WidgetErrorCard-BQwrR6PJ.js";import{P as Vu,W as Gu,a as Ku,C as Qu,b as Yu}from"./find-latest-widget-fence-BGiexm6r.js";import{a as Xu,c as Ju}from"./composer-insert-BpyATrmR.js";import{A as zn,M as Zu}from"./McpAppFrame-DmHduNgp.js";import{F as Ma}from"./file-DlQX-hKl.js";import{S as ed}from"./shield-x-DioB6qH_.js";import{u as td,M as nd}from"./McpSigninBody-DoY09n4J.js";import{f as sd}from"./format-duration-BCr6uzby.js";import{l as rd}from"./use-connector-management-pgVHbXoO.js";import{A as ad}from"./AgentRequestCard-CAaBGC0L.js";import{F as od,h as id}from"./use-session-canvas-BaXuEhw8.js";import"./use-is-below-desktop-DBet5zg_.js";import"./git-branch-Dq_w3Iyx.js";import"./RuntimeSetupDialog-ufwCvCJB.js";import"./layers-B0oCOfxz.js";import"./file-drag-GDx2qhdk.js";import"./paperclip-Cj1P85mz.js";import"./index-CcV9S7cO.js";import"./table-P4N5xQn2.js";import"./package-CoTlAnXZ.js";import"./heart-Bp14wOx6.js";import"./rotate-cw-DrGRGSwy.js";function ld(...e){const t=!Array.isArray(e[0]),n=t?0:-1,s=e[0+n],a=e[1+n],o=e[2+n],i=e[3+n],l=fi(a,o,i);return t?l(s):l}function cd(e,t,n={}){const s=e.get();let a=null,o=s,i;const l=typeof s=="string"?s.replace(/[\d.-]/g,""):void 0,u=()=>{a&&(a.stop(),a=null),e.animation=void 0},d=()=>{const h=Vs(e.get()),m=Vs(o);if(h===m){u();return}const x=a?a.getGeneratorVelocity():e.getVelocity();u(),a=new mi({keyframes:[h,m],velocity:x,type:"spring",restDelta:.001,restSpeed:.01,...n,onUpdate:i})},f=()=>{var h;d(),e.animation=a??void 0,(h=e.events.animationStart)==null||h.notify(),a==null||a.then(()=>{var m;e.animation=void 0,(m=e.events.animationComplete)==null||m.notify()})};if(e.attach((h,m)=>{o=h,i=x=>m(gn(x,l)),Qr.postRender(f)},u),Yr(t)){let h=n.skipInitialAnimation===!0;const m=t.on("change",g=>{h?(h=!1,e.jump(gn(g,l),!1)):e.set(gn(g,l))}),x=e.on("destroy",m);return()=>{m(),x()}}return u}function gn(e,t){return t?e+t:e}function Vs(e){return typeof e=="number"?e:parseFloat(e)}function Ia(e){const t=Xr(()=>pi(e)),{isStatic:n}=c.useContext(Jr);if(n){const[,s]=c.useState(e);c.useEffect(()=>t.on("change",s),[])}return t}function Oa(e,t){const n=Ia(t()),s=()=>n.set(t());return s(),hi(()=>{const a=()=>Qr.preRender(s,!1,!0),o=e.map(i=>i.on("change",a));return()=>{o.forEach(i=>i()),gi(s)}}),n}function ud(e){un.current=[],e();const t=Oa(un.current,e);return un.current=void 0,t}function $a(e,t,n,s){if(typeof e=="function")return ud(e);const o=typeof t=="function"?t:ld(t,n,s),i=Array.isArray(e)?Gs(e,o):Gs([e],([u])=>o(u)),l=Array.isArray(e)?void 0:e.accelerate;return l&&!l.isTransformed&&typeof t!="function"&&Array.isArray(n)&&(s==null?void 0:s.clamp)!==!1&&(i.accelerate={...l,times:t,keyframes:n,isTransformed:!0}),i}function Gs(e,t){const n=Xr(()=>[]);return Oa(e,()=>{n.length=0;const s=e.length;for(let a=0;a<s;a++)n[a]=e[a].get();return t(n)})}function dd(e,t={}){const{isStatic:n}=c.useContext(Jr),s=()=>Yr(e)?e.get():e;if(n)return $a(s);const a=Ia(s());return c.useInsertionEffect(()=>cd(a,e,t),[a,JSON.stringify(t)]),a}function fd(e,t={}){return dd(e,{type:"spring",...t})}function md(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),s=Math.floor(t%3600/60);return`${n}h ${String(s).padStart(2,"0")}m`}function Pa(e){const[t,n]=c.useState(()=>Date.now()),s=c.useRef(null);if(c.useEffect(()=>{if(e===null){s.current&&(clearInterval(s.current),s.current=null);return}return n(Date.now()),s.current=setInterval(()=>n(Date.now()),1e3),()=>{s.current&&(clearInterval(s.current),s.current=null)}},[e]),e===null)return{formatted:"0m 00s",ms:0};const a=Math.max(0,t-e);return{formatted:md(a),ms:a}}function pd(e={}){const{timeoutMs:t=3e4,onIdle:n,onReturn:s}=e,a=c.useRef(!1),o=c.useRef(null),i=c.useCallback(()=>{a.current||(a.current=!0,n==null||n())},[n]),l=c.useCallback(()=>{a.current&&(a.current=!1,s==null||s())},[s]),u=c.useCallback(()=>{o.current&&clearTimeout(o.current),o.current=setTimeout(i,t),l()},[t,i,l]);return c.useEffect(()=>{o.current=setTimeout(i,t);const d=["mousemove","keydown","scroll","touchstart"];d.forEach(h=>document.addEventListener(h,u,{passive:!0}));const f=()=>{document.hidden?i():u()};return document.addEventListener("visibilitychange",f),()=>{o.current&&clearTimeout(o.current),d.forEach(h=>document.removeEventListener(h,u)),document.removeEventListener("visibilitychange",f)}},[t,i,u]),{isIdle:a.current}}function hd({activeInteraction:e,onApprove:t,onAlwaysAllow:n,onDeny:s,onToggleOption:a,onNavigateOption:o,onNavigateQuestion:i,onSubmit:l,optionCount:u=0,focusedIndex:d=0}){const f=c.useRef(!1);c.useEffect(()=>{f.current=!1},[e==null?void 0:e.toolCallId]),c.useEffect(()=>{if(!e)return;function h(m){const x=m.target,g=(x.tagName==="TEXTAREA"||x.tagName==="INPUT")&&!x.disabled;if(!f.current&&!(m.metaKey||m.ctrlKey||m.altKey)){if(e.type==="approval"){if(m.key==="Enter"&&g&&x.closest("[data-approval-field]")!==null)return;m.key==="Enter"&&m.shiftKey?(m.preventDefault(),f.current=!0,n==null||n()):m.key==="Enter"?(m.preventDefault(),f.current=!0,t==null||t()):m.key==="Escape"&&(m.preventDefault(),f.current=!0,s==null||s());return}if(e.type==="question"){if(g){if(m.key==="Enter"&&!m.shiftKey){m.preventDefault(),l==null||l();return}if(m.key==="ArrowUp"){m.preventDefault(),o==null||o("up");return}if(m.key==="ArrowDown"){m.preventDefault(),o==null||o("down");return}return}const S=parseInt(m.key,10);if(S>=1&&S<=9){m.preventDefault(),S-1<u&&(a==null||a(S-1));return}switch(m.key){case"ArrowUp":m.preventDefault(),o==null||o("up");break;case"ArrowDown":m.preventDefault(),o==null||o("down");break;case" ":m.preventDefault(),a==null||a(d);break;case"ArrowLeft":case"[":m.preventDefault(),i==null||i("prev");break;case"ArrowRight":case"]":m.preventDefault(),i==null||i("next");break;case"Enter":m.preventDefault(),l==null||l();break}}}}return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[e,t,n,s,a,o,i,l,u,d])}function La(){const[e,t]=c.useState(()=>!document.hidden);return c.useEffect(()=>{const n=()=>t(!document.hidden);return document.addEventListener("visibilitychange",n),()=>document.removeEventListener("visibilitychange",n)},[]),e}/**
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BRGOMmOM.js","assets/index-C63bLSO4.js","assets/index-DFEF2MFy.css"])))=>i.map(i=>d[i]);
2
+ var ui=Object.defineProperty;var di=(e,t,n)=>t in e?ui(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Ze=(e,t,n)=>di(e,typeof t!="symbol"?t+"":t,n);import{oH as fi,oI as Qr,nB as Yr,oJ as mi,oK as Xr,nQ as pi,r as c,oL as Jr,oM as hi,oN as gi,oO as un,a4 as Qe,j as r,a3 as G,bo as ie,hi as Zn,ae as xe,kU as Zr,w as at,jr as xi,oP as bi,oQ as ea,oR as yi,oS as vi,ga as ki,B as ne,cT as Ee,df as Te,oT as ta,oU as lt,oV as Ve,Z as H,$ as ot,X as Le,oW as mt,jy as Ci,oX as Si,I as ji,oY as _i,oZ as dn,e7 as wi,o_ as Ni,o$ as Ei,fL as Di,b5 as gt,p0 as na,hf as Ai,p1 as Ti,gA as Fi,ap as sa,hk as Ri,aQ as oe,p2 as Mi,p3 as $n,an as Ii,p4 as Fs,dT as Rs,dS as it,p5 as Oi,p6 as $i,p7 as vt,p8 as Gt,aj as Ye,p9 as es,ag as kt,gT as jt,dR as ts,bZ as _t,cY as Pi,cZ as Li,c_ as zi,c$ as Bi,d0 as qi,dd as Ui,e as Ms,i3 as Hi,d1 as Wi,F as ze,i4 as Vi,pa as ns,dG as Gi,pb as Ki,pc as Qi,hY as ss,pd as ra,pe as aa,pf as Yi,pg as Xi,hR as rs,af as as,ci as wt,dP as os,db as is,dN as Ji,ph as Zi,pi as oa,pj as el,pk as tl,hb as nl,e3 as sl,gz as Ge,ja as Nt,dn as ls,pl as rl,b8 as al,di as Et,pm as Be,pn as qe,iT as ia,po as Xt,de as Dt,jl as ol,bY as ct,x as At,pp as il,l1 as Is,lF as la,l2 as ll,C as cs,bs as cl,bt as ul,pq as dl,l as fl,mv as ca,aN as ml,pr as pl,ps as hl,pt as gl,pu as xl,oc as bl,o2 as Jt,aO as yl,h0 as vl,c3 as kl,by as Cl,ih as Sl,aw as us,dg as Os,f as ua,pv as jl,et as _l,aT as wl,fk as da,hn as fa,lG as Ct,pw as ma,px as Nl,py as El,pz as pa,pA as Dl,dl as Al,pB as Tl,pC as Fl,pD as Rl,pE as Ml,v as ha,G as Zt,aM as ga,pF as xa,pG as Il,lW as fn,iD as Ol,k3 as $l,ba,eR as Pl,eS as $s,pH as Pn,pI as ya,pJ as Ll,pK as zl,pL as va,ex as Bl,l0 as ql,gb as Ul,gc as Hl,gd as Wl,ge as Vl,gf as Gl,gg as Kl,gh as Ql,gi as Yl,pM as ds,pN as Xl,pO as Jl,pP as Zl,iy as ec,iz as tc,iA as nc,iB as mn,pQ as sc,iC as Ps,jk as rc,bD as ac,jh as oc,bF as ic,pR as Ls,c6 as lc,g0 as ka,cb as Ca,c1 as cc,ca as uc,ch as Sa,cf as dc,lH as fs,pS as fc,at as mc,pT as pc,lb as te,pU as hc,pV as gc,aa as xc,fX as zs,hN as We,pW as pn,kC as xt,o1 as Ne,pX as Bs,pY as qs,pZ as Us,jL as hn,p_ as st,eo as bt,p$ as bc,q0 as ja,q1 as _a,q2 as yc,q3 as vc,q4 as wa,lJ as kc,q5 as Na,q6 as et,kP as Ea,q7 as Cc,bC as Sc,lI as jc,q8 as _c,q9 as wc,fM as Da,qa as Nc,bK as Hs,n1 as Aa,eU as en,qb as Ec,qc as Dc,gx as Ta,gy as ms,iS as Ac,qd as Tc,qe as Fc,qf as Rc,qg as Mc,qh as Ic,cj as Oc,eN as $c,lN as Pc,fC as Lc,kX as zc,dy as Bc}from"./index-C63bLSO4.js";import{P as qc}from"./PromptSuggestionChips-EO_0zbzq.js";import{u as Uc,a as Hc,L as Wc,f as Vc,b as Gc,c as Kc,B as Qc,d as Yc}from"./kickoff-xkt4LpIP.js";import{E as Xc,F as Jc,e as Zc,h as eu,f as tu,P as nu,g as su,d as ru,q as au,j as ou,b as iu,G as lu,B as cu,H as Fa,z as uu,u as du,D as fu,v as mu,t as pu,p as hu,w as gu,y as xu,o as bu,n as yu,k as vu,s as ku,M as Cu,i as Su,S as ju,U as _u,A as wu,I as Nu,J as Eu,K as Ws,x as Du,R as Au}from"./use-session-diagnostics-C41hV7rK.js";import{C as Tu}from"./card-CKZCX8ol.js";import{B as Fu}from"./banner-Dh5mO27l.js";import{j as Ru,k as Mu,t as Mt,b as Ln,n as Iu,N as Ra,o as Ou,g as $u,C as St,M as tt,f as Pu,D as Lu,U as zu,F as Bu}from"./index-BUVKya1M.js";import{a as qu}from"./markdown-content-CoK3F0c0.js";import{u as Uu,b as Hu}from"./WidgetErrorCard-D--KcgW1.js";import{P as Wu,W as Vu,a as Gu,C as Ku,b as Qu}from"./find-latest-widget-fence--3kWMT1F.js";import{a as Yu,c as Xu}from"./composer-insert-BpyATrmR.js";import{A as zn,M as Ju}from"./McpAppFrame-6zxszx9A.js";import{F as Ma}from"./file-CMPbZedq.js";import{S as Zu}from"./shield-x-Bh5xap8N.js";import{u as ed,M as td}from"./McpSigninBody-DBWSc6bm.js";import{f as nd}from"./format-duration-BCr6uzby.js";import{l as sd}from"./use-connector-management-Cohvs7jD.js";import{A as rd}from"./AgentRequestCard-CcMh6JyE.js";import{F as ad,h as od}from"./use-session-canvas-CZIsr9qL.js";import{F as id}from"./file-text-9a0DChCq.js";import"./use-is-below-desktop-5LlietdR.js";import"./git-branch-hfu8isLA.js";import"./RuntimeSetupDialog-Cqn_Grel.js";import"./layers-Cy8Tme6i.js";import"./file-drag-GDx2qhdk.js";import"./paperclip-IgDeVFea.js";import"./index-BDfoFNcA.js";import"./table-BEtvgYmW.js";import"./package-DE8sQpId.js";import"./heart-SRafwnSd.js";import"./rotate-cw-DaduzRfP.js";function ld(...e){const t=!Array.isArray(e[0]),n=t?0:-1,s=e[0+n],a=e[1+n],o=e[2+n],i=e[3+n],l=fi(a,o,i);return t?l(s):l}function cd(e,t,n={}){const s=e.get();let a=null,o=s,i;const l=typeof s=="string"?s.replace(/[\d.-]/g,""):void 0,u=()=>{a&&(a.stop(),a=null),e.animation=void 0},d=()=>{const h=Vs(e.get()),m=Vs(o);if(h===m){u();return}const x=a?a.getGeneratorVelocity():e.getVelocity();u(),a=new mi({keyframes:[h,m],velocity:x,type:"spring",restDelta:.001,restSpeed:.01,...n,onUpdate:i})},f=()=>{var h;d(),e.animation=a??void 0,(h=e.events.animationStart)==null||h.notify(),a==null||a.then(()=>{var m;e.animation=void 0,(m=e.events.animationComplete)==null||m.notify()})};if(e.attach((h,m)=>{o=h,i=x=>m(gn(x,l)),Qr.postRender(f)},u),Yr(t)){let h=n.skipInitialAnimation===!0;const m=t.on("change",g=>{h?(h=!1,e.jump(gn(g,l),!1)):e.set(gn(g,l))}),x=e.on("destroy",m);return()=>{m(),x()}}return u}function gn(e,t){return t?e+t:e}function Vs(e){return typeof e=="number"?e:parseFloat(e)}function Ia(e){const t=Xr(()=>pi(e)),{isStatic:n}=c.useContext(Jr);if(n){const[,s]=c.useState(e);c.useEffect(()=>t.on("change",s),[])}return t}function Oa(e,t){const n=Ia(t()),s=()=>n.set(t());return s(),hi(()=>{const a=()=>Qr.preRender(s,!1,!0),o=e.map(i=>i.on("change",a));return()=>{o.forEach(i=>i()),gi(s)}}),n}function ud(e){un.current=[],e();const t=Oa(un.current,e);return un.current=void 0,t}function $a(e,t,n,s){if(typeof e=="function")return ud(e);const o=typeof t=="function"?t:ld(t,n,s),i=Array.isArray(e)?Gs(e,o):Gs([e],([u])=>o(u)),l=Array.isArray(e)?void 0:e.accelerate;return l&&!l.isTransformed&&typeof t!="function"&&Array.isArray(n)&&(s==null?void 0:s.clamp)!==!1&&(i.accelerate={...l,times:t,keyframes:n,isTransformed:!0}),i}function Gs(e,t){const n=Xr(()=>[]);return Oa(e,()=>{n.length=0;const s=e.length;for(let a=0;a<s;a++)n[a]=e[a].get();return t(n)})}function dd(e,t={}){const{isStatic:n}=c.useContext(Jr),s=()=>Yr(e)?e.get():e;if(n)return $a(s);const a=Ia(s());return c.useInsertionEffect(()=>cd(a,e,t),[a,JSON.stringify(t)]),a}function fd(e,t={}){return dd(e,{type:"spring",...t})}function md(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),s=Math.floor(t%3600/60);return`${n}h ${String(s).padStart(2,"0")}m`}function Pa(e){const[t,n]=c.useState(()=>Date.now()),s=c.useRef(null);if(c.useEffect(()=>{if(e===null){s.current&&(clearInterval(s.current),s.current=null);return}return n(Date.now()),s.current=setInterval(()=>n(Date.now()),1e3),()=>{s.current&&(clearInterval(s.current),s.current=null)}},[e]),e===null)return{formatted:"0m 00s",ms:0};const a=Math.max(0,t-e);return{formatted:md(a),ms:a}}function pd(e={}){const{timeoutMs:t=3e4,onIdle:n,onReturn:s}=e,a=c.useRef(!1),o=c.useRef(null),i=c.useCallback(()=>{a.current||(a.current=!0,n==null||n())},[n]),l=c.useCallback(()=>{a.current&&(a.current=!1,s==null||s())},[s]),u=c.useCallback(()=>{o.current&&clearTimeout(o.current),o.current=setTimeout(i,t),l()},[t,i,l]);return c.useEffect(()=>{o.current=setTimeout(i,t);const d=["mousemove","keydown","scroll","touchstart"];d.forEach(h=>document.addEventListener(h,u,{passive:!0}));const f=()=>{document.hidden?i():u()};return document.addEventListener("visibilitychange",f),()=>{o.current&&clearTimeout(o.current),d.forEach(h=>document.removeEventListener(h,u)),document.removeEventListener("visibilitychange",f)}},[t,i,u]),{isIdle:a.current}}function hd({activeInteraction:e,onApprove:t,onAlwaysAllow:n,onDeny:s,onToggleOption:a,onNavigateOption:o,onNavigateQuestion:i,onSubmit:l,optionCount:u=0,focusedIndex:d=0}){const f=c.useRef(!1);c.useEffect(()=>{f.current=!1},[e==null?void 0:e.toolCallId]),c.useEffect(()=>{if(!e)return;function h(m){const x=m.target,g=(x.tagName==="TEXTAREA"||x.tagName==="INPUT")&&!x.disabled;if(!f.current&&!(m.metaKey||m.ctrlKey||m.altKey)){if(e.type==="approval"){if(m.key==="Enter"&&g&&x.closest("[data-approval-field]")!==null)return;m.key==="Enter"&&m.shiftKey?(m.preventDefault(),f.current=!0,n==null||n()):m.key==="Enter"?(m.preventDefault(),f.current=!0,t==null||t()):m.key==="Escape"&&(m.preventDefault(),f.current=!0,s==null||s());return}if(e.type==="question"){if(g){if(m.key==="Enter"&&!m.shiftKey){m.preventDefault(),l==null||l();return}if(m.key==="ArrowUp"){m.preventDefault(),o==null||o("up");return}if(m.key==="ArrowDown"){m.preventDefault(),o==null||o("down");return}return}const S=parseInt(m.key,10);if(S>=1&&S<=9){m.preventDefault(),S-1<u&&(a==null||a(S-1));return}switch(m.key){case"ArrowUp":m.preventDefault(),o==null||o("up");break;case"ArrowDown":m.preventDefault(),o==null||o("down");break;case" ":m.preventDefault(),a==null||a(d);break;case"ArrowLeft":case"[":m.preventDefault(),i==null||i("prev");break;case"ArrowRight":case"]":m.preventDefault(),i==null||i("next");break;case"Enter":m.preventDefault(),l==null||l();break}}}}return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[e,t,n,s,a,o,i,l,u,d])}function La(){const[e,t]=c.useState(()=>!document.hidden);return c.useEffect(()=>{const n=()=>t(!document.hidden);return document.addEventListener("visibilitychange",n),()=>document.removeEventListener("visibilitychange",n)},[]),e}/**
3
3
  * @license lucide-react v1.48.0 - ISC
4
4
  *
5
5
  * This source code is licensed under the ISC license.
@@ -14,12 +14,12 @@ var ui=Object.defineProperty;var di=(e,t,n)=>t in e?ui(e,t,{enumerable:!0,config
14
14
  *
15
15
  * This source code is licensed under the ISC license.
16
16
  * See the LICENSE file in the root directory of this source tree.
17
- */const Ua={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"}]]};Ua.node;const bd=Qe(Ua);/**
17
+ */const qa={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"}]]};qa.node;const bd=Qe(qa);/**
18
18
  * @license lucide-react v1.48.0 - ISC
19
19
  *
20
20
  * This source code is licensed under the ISC license.
21
21
  * See the LICENSE file in the root directory of this source tree.
22
- */const qa={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"}]]};qa.node;const yd=Qe(qa);/**
22
+ */const Ua={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"}]]};Ua.node;const yd=Qe(Ua);/**
23
23
  * @license lucide-react v1.48.0 - ISC
24
24
  *
25
25
  * This source code is licensed under the ISC license.
@@ -34,33 +34,33 @@ var ui=Object.defineProperty;var di=(e,t,n)=>t in e?ui(e,t,{enumerable:!0,config
34
34
  *
35
35
  * This source code is licensed under the ISC license.
36
36
  * See the LICENSE file in the root directory of this source tree.
37
- */const Va={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"}]]};Va.node;const Cd=Qe(Va);function Sd({color:e,isTextStreaming:t,fadeEdges:n=!0,edge:s="bottom"}){const a=t?1.8:2.5,o=n?"linear-gradient(to right, transparent, black 15%, black 85%, transparent)":void 0,i=s==="top"?"pointer-events-none absolute right-0 top-0 left-0":"pointer-events-none absolute right-0 bottom-0 left-0",l=s==="top"?"top":"bottom";return r.jsxs(G.div,{"aria-hidden":!0,initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.4},className:i,style:{height:n?10:0,overflow:n?"hidden":"visible",maskImage:o,WebkitMaskImage:o},children:[r.jsx("div",{className:"absolute right-0 left-0",style:{[l]:0,height:6,backgroundColor:e,opacity:.6,filter:"blur(3px)"}}),r.jsx(G.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"}}),r.jsx(ie,{children:t&&r.jsx(G.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 xn={"word-boundary":3,substring:2,subsequence:1},jd=new Set(["/",":","-","_","."," "]);function _d(e,t){if(t===0)return!0;const n=e[t-1];if(jd.has(n))return!0;const s=e[t];return n===n.toLowerCase()&&s!==s.toLowerCase()&&s===s.toUpperCase()}function It(e,t){return Array.from({length:t},(n,s)=>e+s)}function Ot(e,t,n){const s=1/(1+t),a=n/e.length;return(s*.6+a*.4)*.999}function wd(e,t){let n=0,s=0,a=0;const o=[];for(let i=0;i<t.length&&n<e.length;i++)t[i]===e[n]?(n++,s++,s>a&&(a=s),o.push(i)):s=0;return n===e.length?{indices:o,maxRun:a}:null}function Nd(e,t){const n=t.indices[t.indices.length-1]-t.indices[0]+1,s=t.maxRun/t.indices.length,a=t.indices.length/n,o=t.indices.length/e.length;return(s*.4+a*.3+o*.3)*.999}function Ht(e,t){if(!e)return{match:!0,tier:null,score:0,indices:[]};const n=e.toLowerCase(),s=t.toLowerCase();if(s===n)return{match:!0,tier:"exact",score:5+Ot(t,0,n.length),indices:It(0,n.length)};if(s.startsWith(n))return{match:!0,tier:"prefix",score:4+Ot(t,0,n.length),indices:It(0,n.length)};for(let i=1;i<=s.length-n.length;i++)if(_d(t,i)&&s.startsWith(n,i))return{match:!0,tier:"word-boundary",score:xn["word-boundary"]+Ot(t,i,n.length),indices:It(i,n.length)};const a=s.indexOf(n);if(a>=0)return{match:!0,tier:"substring",score:xn.substring+Ot(t,a,n.length),indices:It(a,n.length)};const o=wd(n,s);return o?{match:!0,tier:"subsequence",score:xn.subsequence+Nd(t,o),indices:o.indices}:{match:!1,tier:null,score:0,indices:[]}}function Ga(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/^./,t=>t.toUpperCase())}function Ed(e,t){return e.length<=t?e:e.slice(0,t)+"…"}function Dd(e){return/^[/~.]/.test(e)||/\.(ts|tsx|js|jsx|json|md|py|rs|go|sh|yml|yaml|toml)$/.test(e)}function Bn(e,t){if(e===null)return r.jsx("span",{className:"text-muted-foreground italic",children:"null"});if(typeof e=="boolean")return r.jsx("span",{className:"text-amber-600 dark:text-amber-400",children:String(e)});if(typeof e=="number")return r.jsx("span",{className:"text-blue-600 dark:text-blue-400",children:e});if(typeof e=="string"){const n=Ed(e,t);return Dd(e)?r.jsx("code",{className:"bg-muted rounded px-1 py-0.5 text-xs break-all",children:n}):r.jsx("span",{className:"break-words",children:n})}if(Array.isArray(e)){const n=e.slice(0,5),s=e.length-5;return r.jsxs("div",{className:"space-y-0.5",children:[n.map((a,o)=>r.jsx("div",{className:"border-border/40 border-l pl-2",children:Bn(a,80)},o)),s>0&&r.jsxs("span",{className:"text-muted-foreground text-xs italic",children:["… and ",s," more"]})]})}if(typeof e=="object"){const n=Object.entries(e);return r.jsx("div",{className:"space-y-0.5",children:n.map(([s,a])=>r.jsxs("div",{className:"border-border/40 border-l pl-2",children:[r.jsxs("span",{className:"text-muted-foreground text-xs",children:[Ga(s),": "]}),typeof a=="object"&&a!==null?r.jsx("span",{className:"text-muted-foreground italic",children:"{…}"}):Bn(a,80)]},s))})}return r.jsx("span",{children:String(e)})}function Ka({toolName:e,input:t,isStreaming:n=!1}){if(!t)return null;if(n){const o=t.length>5120?t.slice(0,5120)+"…":t;return r.jsxs("pre",{className:"text-muted-foreground overflow-x-auto text-xs whitespace-pre-wrap",children:[o,r.jsx("span",{className:"animate-breath ml-0.5 inline-block size-1.5 rounded-full bg-current"})]})}let s;try{s=JSON.parse(t)}catch{const o=t.length>5120?t.slice(0,5120)+"…":t;return r.jsx("pre",{className:"overflow-x-auto text-xs whitespace-pre-wrap",children:o})}if(typeof s!="object"||s===null||Array.isArray(s)){const o=t.length>5120?t.slice(0,5120)+"…":t;return r.jsx("pre",{className:"overflow-x-auto text-xs whitespace-pre-wrap",children:o})}const a=Object.entries(s);return a.length===0?null:r.jsx("dl",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs",children:a.map(([o,i])=>r.jsxs("div",{className:"contents",children:[r.jsx("dt",{className:"text-muted-foreground py-0.5 font-medium whitespace-nowrap",children:Ga(o)}),r.jsx("dd",{className:"min-w-0 py-0.5",children:Bn(i,120)})]},o))})}class Ad{constructor(t){Ze(this,"config");Ze(this,"recentCompletions",[]);Ze(this,"queue",[]);Ze(this,"isIdle",!1);Ze(this,"debounceTimer",null);this.config=t}onTaskCompleted(t,n){if(!this.config.enabled)return;const s=Date.now();this.recentCompletions.push(s),this.recentCompletions=this.recentCompletions.filter(l=>s-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:s};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:s};this.emitOrQueue(l)}}setIdle(t){this.isIdle=t}onUserReturn(){if(this.queue.length>0){const n=this.queue.some(s=>s.level==="major")?this.queue.find(s=>s.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 Td={background:"radial-gradient(circle, rgba(255,215,0,0.15) 0%, transparent 70%)"},Fd={mode:"blur-in",duration:150,easing:"ease-out",sep:"word"},Rd={none:void 0,fade:"fadeIn","blur-in":"blurIn","slide-up":"slideUp"};function Md(e){const t=Rd[e.mode];return t?{animation:t,duration:e.duration??150,easing:e.easing??"ease-out",sep:e.sep??"word"}:!1}function Id(e,t=40){if(e.length<=t)return e;const n=e.split("/").pop()??e,s=n.length+2,a=Math.max(6,t-s);return`${e.slice(0,a)}…/${n}`}function Od({onlyFirst:e=!1}={}){const a="(?:\\u001B\\][^\\u0007\\u001B\\u009C]*(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";return new RegExp(a,e?void 0:"g")}const $d=Od({onlyFirst:!0});function Pd(e){if($d.test(e))return"ansi";const t=e.trimStart();if(t.startsWith("{")||t.startsWith("["))try{return JSON.parse(e),"json"}catch{}return"plain"}function tn(e){var n;const{sessions:t}=Zn();if(e)return(n=t.find(s=>s.id===e))==null?void 0:n.runtime}const Ld=typeof window<"u"&&window.location.pathname===bi;let bn=null,Ks=!Ld;function zd(e){return Ks?bn===e?!0:(bn=null,!1):(Ks=!0,bn=e,!0)}function Bd(e){var s;const t=xe(),n=((s=Zr(e))==null?void 0:s.draft)===!0;c.useEffect(()=>{if(!e||n)return;let a=!1;const o=()=>{a||document.visibilityState!=="visible"||(a=!0,document.removeEventListener("visibilitychange",o),zd(e)||at.getState().recordOpened("session",e),t.markSessionOpened(e).catch(i=>{xi(t,i)}))};if(o(),!a)return document.addEventListener("visibilitychange",o),()=>document.removeEventListener("visibilitychange",o)},[e,n,t])}function Qa(){const e=ea(),t=Zr(e.session);return{cwd:(t==null?void 0:t.cwd)??e.dir??null}}function Ya({agentId:e,agentName:t,onResumed:n}){const s=yi(),{data:a,dataUpdatedAt:o,refetch:i}=vi(),[l]=c.useState(()=>Date.now());c.useEffect(()=>{i()},[e,i]);const u=t??"This agent";return a!=null&&o>=l&&!a.pauses.some(f=>f.agentId===e)?null:r.jsxs("div",{"data-testid":"agent-paused-notice",role:"status",className:"border-border bg-muted/50 my-2 flex items-center gap-3 rounded-lg border px-4 py-3",children:[r.jsx(ki,{className:"text-muted-foreground size-4 shrink-0","aria-hidden":!0}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsxs("p",{className:"text-sm font-medium",children:[u," is paused"]}),r.jsx("p",{className:"text-muted-foreground text-xs",children:"Resume it, then send your message again."})]}),r.jsx(ne,{size:"sm",variant:"outline",disabled:s.isPending,onClick:()=>s.mutate(e,{onSuccess:()=>{Ee(`${u} resumed`),n==null||n()}}),children:"Resume"})]})}const Ud={session:"this chat",project:"this project",user:"all your Claude chats"};function qd(e){return e===void 0?void 0:Ud[e]}const Hd={duration:.12,ease:"easeOut"},Wd={duration:0},Qs=new Set(["Bash","Write","Edit","NotebookEdit"]),Ys=new Set(["WebFetch","WebSearch"]);function Vd(e){const t=e.includes("__")?e.split("__").pop():e;return Qs.has(t)||Qs.has(e)?"high":Ys.has(t)||Ys.has(e)||e.startsWith("mcp__")?"medium":"low"}function Gd(e){const t=Math.floor(e/60),n=e%60;return t>0?`${t}:${String(n).padStart(2,"0")}`:`${n}s`}function Xa({sessionId:e,toolCallId:t,toolName:n,input:s,isActive:a=!1,onDecided:o,ref:i,timeoutMs:l,approvalStartedAt:u,approvalRemainingMs:d,approvalParked:f,approvalTitle:h,approvalDisplayName:m,approvalDescription:x,approvalBlockedPath:g,approvalDecisionReason:S,approvalHasSuggestions:b,approvalAlwaysAllowScope:y,allowsDenyReason:C=!0}){const v=xe(),p=Te(),j=c.useMemo(()=>Vd(n),[n]),_=ta(n),D=lt(n,s),T=m||D,N=qd(y),[A,k]=c.useState(!1),[E,w]=c.useState(null),[R,O]=c.useState(null),[F,$]=c.useState(!1),[B,q]=c.useState(""),Y=c.useRef(""),[se,V]=c.useState(!1),L=a&&!se,[I,P]=c.useState(()=>Date.now()),Q=c.useRef(!1);c.useLayoutEffect(()=>{if(!Q.current){Q.current=!0;return}P(Date.now())},[l,u,d]);const[ae,M]=c.useState(null),W=c.useMemo(()=>{if(!l||f===!0)return null;const z=d!==void 0?I+d:u?u+l:I+l,he=Math.min(l,Math.max(0,l-(z-I)));return{expiresAt:z,elapsedMs:he}},[I,l,u,d,f]),X=E||!l||!W?null:ae!==null&&ae.expiresAt===W.expiresAt?ae.seconds:Math.max(0,Math.ceil((W.expiresAt-I)/1e3));c.useEffect(()=>{if(E||!l||!W)return;const{expiresAt:z}=W,he=setInterval(()=>{const ce=Math.max(0,Math.ceil((z-Date.now())/1e3));M({expiresAt:z,seconds:ce}),ce<=0&&clearInterval(he)},1e3);return()=>clearInterval(he)},[l,W,E]);const J=f===!0||X===0,Z=E||X===null?"":X<=0?"Nobody answered. The agent is waiting for you.":X<=Ni?"One minute left to answer.":X<=Ei?"Two minutes left to answer.":"",K=c.useCallback(async()=>{if(!(A||E)){k(!0),O(null);try{await v.approveTool(e,t),w("approved"),o==null||o()}catch(z){z.code==="INTERACTION_ALREADY_RESOLVED"?(w("approved"),o==null||o()):(console.error("Approval failed:",z),O("Couldn’t send your answer. Try again."))}finally{k(!1)}}},[A,E,v,e,t,o]),le=c.useCallback(async()=>{if(!(A||E)){k(!0),O(null);try{await v.approveTool(e,t,!0),w("approved"),o==null||o()}catch(z){z.code==="INTERACTION_ALREADY_RESOLVED"?(w("approved"),o==null||o()):(console.error("Always Allow failed:",z),O("Couldn’t send your answer. Try again."))}finally{k(!1)}}},[A,E,v,e,t,o]),fe=c.useCallback(async()=>{if(!(A||E)){k(!0),O(null);try{await v.denyTool(e,t,Y.current.trim()||void 0),w("denied"),o==null||o()}catch(z){z.code==="INTERACTION_ALREADY_RESOLVED"?(w("denied"),o==null||o()):(console.error("Deny failed:",z),O("Couldn’t send your answer. Try again."))}finally{k(!1)}}},[A,E,v,e,t,o]);c.useImperativeHandle(i,()=>({approve(){K()},alwaysAllow(){le()},deny(){fe()}}),[K,le,fe]);const me=r.jsx("span",{role:"status","aria-live":"assertive","aria-atomic":"true",className:"sr-only",children:Z});if(E){const z=E==="approved";return r.jsxs(r.Fragment,{children:[r.jsx(G.div,{initial:p?!1:{opacity:0,scaleY:.9},animate:{opacity:1,scaleY:1},transition:p?Wd:Hd,style:{originY:0},children:r.jsx(Ve,{"data-testid":"tool-approval-decided","data-decision":E,icon:z?r.jsx(ot,{className:"text-status-success size-(--size-icon-sm) shrink-0"}):r.jsx(Le,{className:"text-status-error size-(--size-icon-sm) shrink-0"}),label:r.jsx("span",{className:"text-3xs font-mono",children:T}),trailing:r.jsx("span",{className:H("text-2xs rounded-full px-1.5 py-0.5 font-medium",z?"bg-status-success-bg text-status-success-fg":"bg-status-error-bg text-status-error-fg"),children:z?"Allowed":"Not allowed"})})}),me]})}return r.jsxs(r.Fragment,{children:[r.jsxs(mt.Root,{isActive:a,isResolved:!!E,onAllow:K,onDeny:fe,className:"my-1","data-testid":"tool-approval",children:[r.jsxs("div",{className:"mb-1 flex items-center gap-2",children:[r.jsx(Ci,{className:H("size-(--size-icon-md)",j==="high"&&"text-status-error",j==="medium"&&"text-status-warning",j==="low"&&"text-muted-foreground")}),r.jsx(mt.Headline,{className:"font-semibold",children:h||"Your agent wants to use a tool"})]}),(x||S||g)&&r.jsxs(mt.Detail,{className:"mb-2",children:[x&&r.jsx("p",{children:x}),S&&!x&&r.jsx("p",{children:S}),g&&r.jsxs("p",{className:"font-mono",children:["Path: ",g]})]}),(l||J)&&!E&&r.jsx("div",{className:"mb-2",children:r.jsx(mt.Countdown,{secondsLeft:J?null:X,...J?{}:{timeoutMs:l},elapsedMs:(W==null?void 0:W.elapsedMs)??0,label:J?Si:X===null?"":`${Gd(X)} remaining`})}),r.jsxs("div",{className:"mb-2 flex items-center gap-1.5",children:[_&&r.jsx("span",{className:"bg-muted text-muted-foreground text-3xs rounded px-1 py-0.5 font-medium",children:_}),r.jsx("span",{className:"font-mono text-xs",children:T})]}),s&&r.jsx("div",{className:"bg-muted mb-3 rounded p-2",children:r.jsx(Ka,{toolName:n,input:s})}),R&&r.jsx("p",{className:"text-status-error text-2xs mb-2",children:R}),C&&F&&r.jsx("div",{className:"mb-2",children:r.jsx(ji,{autoFocus:!0,"data-approval-field":"",value:B,maxLength:_i,disabled:A,onFocus:()=>V(!0),onBlur:()=>V(!1),onChange:z=>{q(z.target.value),Y.current=z.target.value},onKeyDown:z=>{z.key==="Enter"&&(z.preventDefault(),fe())},placeholder:"Why not? The agent sees this.","aria-label":"Reason for not allowing",className:"text-xs"})}),r.jsxs(mt.Actions,{children:[r.jsxs(ne,{size:"sm",onClick:K,disabled:A,className:"transition-opacity duration-150",children:[r.jsx(ot,{className:"size-(--size-icon-xs)"})," Allow",L&&r.jsx(dn,{className:"ml-1.5",children:"Enter"})]}),b&&r.jsxs(ne,{size:"sm",variant:"outline",onClick:le,disabled:A,"aria-label":N===void 0?"Always allow":`Always allow, ${N}`,className:"transition-opacity duration-150",children:[r.jsx(wi,{className:"size-(--size-icon-xs)"})," Always allow",N!==void 0&&r.jsx("span",{className:"text-2xs opacity-70",children:`· ${N}`}),L&&r.jsx(dn,{className:"ml-1.5",children:"Shift+Enter"})]}),r.jsxs(ne,{size:"sm",variant:"outline",onClick:fe,disabled:A,className:"transition-opacity duration-150",children:[r.jsx(Le,{className:"size-(--size-icon-xs)"})," Don’t allow",a&&r.jsx(dn,{className:"ml-1.5",children:"Esc"})]}),C&&!F&&r.jsx("button",{type:"button",onClick:()=>$(!0),disabled:A,className:H("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 Kd(e){if(!e)return[];const t=e.properties??{};return Object.entries(t).map(([n,s])=>({key:n,label:s.description??n,type:s.type??"string",options:s.enum,defaultValue:s.default}))}function Qd({sessionId:e,interactionId:t,serverName:n,message:s,mode:a="form",url:o,requestedSchema:i,status:l,action:u}){const d=xe(),[f,h]=c.useState(!1),[m,x]=c.useState(null),[g,S]=c.useState(null),[b,y]=c.useState({}),[C,v]=c.useState(!1),p=c.useMemo(()=>Kd(i),[i]),j=l!=="pending",_=c.useCallback(async(E,w)=>{if(!(f||j)){h(!0),x(null),S(null);try{await d.submitElicitation(e,t,E,w)}catch(R){if(R.code!=="INTERACTION_ALREADY_RESOLVED"){x("Couldn’t send your answer. Try again."),S(R instanceof Error?R.message:null),h(!1);return}}h(!1)}},[d,e,t,f,j]),D=c.useCallback(()=>{const E={};for(const w of p)E[w.key]=b[w.key]??w.defaultValue??"";_("accept",E)},[p,b,_]),T=c.useCallback(()=>{_("accept")},[_]),N=c.useCallback(()=>{_("decline")},[_]),A=c.useCallback((E,w)=>{y(R=>({...R,[E]:w}))},[]),k=c.useCallback(()=>{if(o){if(!Di(o)){x(`Couldn’t open ${o}. Nothing has been authorized.`),S(null);return}x(null),S(null),v(!0)}},[o]);return j?r.jsxs("div",{className:"text-muted-foreground flex items-center gap-2 py-1 text-xs",children:[r.jsx("span",{className:"font-mono",children:n}),r.jsx("span",{children:"·"}),r.jsx("span",{children:u==="accept"?"Authorized":u==="decline"?"Declined":"Cancelled"})]}):r.jsxs(G.div,{initial:{opacity:0,y:4},animate:{opacity:1,y:0},transition:{duration:.15},className:H("border-border bg-card my-2 rounded-xl border p-4","shadow-soft"),children:[r.jsxs("div",{className:"text-muted-foreground mb-2 flex items-center gap-2 text-xs",children:[r.jsx("span",{className:"bg-muted text-3xs inline-flex items-center rounded-md px-2 py-0.5 font-mono",children:n}),r.jsx("span",{children:"needs something from you"})]}),r.jsx("p",{className:"mb-3 text-sm",children:s}),m&&r.jsxs("div",{className:"mb-2",children:[r.jsx("p",{className:"text-destructive text-xs break-words",children:m}),g&&r.jsx("p",{className:"text-muted-foreground/70 mt-1 text-xs break-words",children:g})]}),a==="url"&&o&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(ne,{size:"sm",variant:"outline",onClick:k,disabled:f,children:"Open authorization page"}),C&&r.jsx(ne,{size:"sm",onClick:T,disabled:f,children:f?"Sending…":"Done"}),r.jsx(ne,{size:"sm",variant:"ghost",onClick:N,disabled:f,children:"Decline"})]}),a==="form"&&r.jsxs(r.Fragment,{children:[p.length>0?r.jsx("div",{className:"mb-3 space-y-2",children:p.map(E=>r.jsxs("div",{children:[r.jsx("label",{htmlFor:`elicitation-${t}-${E.key}`,className:"text-muted-foreground mb-1 block text-xs font-medium",children:E.label}),E.options?r.jsxs("select",{id:`elicitation-${t}-${E.key}`,className:"border-input bg-background w-full rounded-md border px-3 py-1.5 text-sm",value:b[E.key]??String(E.defaultValue??""),onChange:w=>A(E.key,w.target.value),disabled:f,children:[r.jsx("option",{value:"",children:"Select…"}),E.options.map(w=>r.jsx("option",{value:w,children:w},w))]}):r.jsx("input",{id:`elicitation-${t}-${E.key}`,type:E.type==="number"?"number":"text",className:"border-input bg-background w-full rounded-md border px-3 py-1.5 text-sm",placeholder:String(E.defaultValue??""),value:b[E.key]??"",onChange:w=>A(E.key,w.target.value),disabled:f})]},E.key))}):r.jsx("p",{className:"text-muted-foreground mb-3 text-xs",children:"No additional input required."}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(ne,{size:"sm",onClick:D,disabled:f,children:f?"Sending…":"Accept"}),r.jsx(ne,{size:"sm",variant:"ghost",onClick:N,disabled:f,children:"Decline"})]})]})]})}const Yd=8,Xd={duration:.3,ease:[.16,1,.3,1]},Jd={duration:0};function Zd(e){const t=Math.round(e/1e3),n=Math.floor(t/60),s=t%60;return n>0?`${n}:${String(s).padStart(2,"0")}`:`${s}s`}function ef(e){return new Date(e).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"})}function tf(e){return`${e} action${e===1?"":"s"}`}function nf({outcome:e,items:t,resolvedAt:n,startedAt:s,reasonGiven:a,className:o}){var S;const i=Te(),[l,u]=c.useState(!1),d=t.length,f=d>1,h=f?tf(d):(S=t[0])==null?void 0:S.label,m=n!==void 0&&s!==void 0?Math.max(0,n-s):null,x=e==="allowed"?ot:e==="denied"?Le:gt,g=e==="allowed"?"text-status-success":e==="denied"?"text-status-error":"text-muted-foreground";return r.jsxs(G.div,{"data-testid":"approval-receipt","data-outcome":e,"data-count":d,initial:i?!1:{opacity:0,y:Yd},animate:{opacity:1,y:0},transition:i?Jd:Xd,className:H("text-muted-foreground my-1 text-xs",o),children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(x,{className:H("size-(--size-icon-xs) shrink-0",g),"aria-hidden":"true"}),r.jsx("span",{className:"min-w-0 truncate",children:e==="expired"?r.jsxs(r.Fragment,{children:["Expired · ",f?`${h} `:"","denied",m!==null&&` after ${Zd(m)}`]}):r.jsxs(r.Fragment,{children:["You ",e==="allowed"?"allowed":"denied"," ",f?h:r.jsx("span",{className:"font-mono",children:h}),e==="denied"&&a===!0&&r.jsx(r.Fragment,{children:" · agent was told why"})]})}),n!==void 0&&r.jsx("time",{dateTime:new Date(n).toISOString(),className:"ml-auto shrink-0 tabular-nums opacity-70",children:ef(n)}),f&&r.jsx("button",{type:"button",onClick:()=>u(b=>!b),"aria-expanded":l,className:H("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"})]}),f&&l&&r.jsx("ul",{"data-testid":"approval-receipt-items",className:"mt-1 ml-6 space-y-0.5",children:t.map(b=>r.jsx("li",{className:"truncate font-mono",children:b.label},b.toolCallId))})]})}function sf({outcome:e,reasonGiven:t,members:n,lead:s,children:a}){return r.jsxs("div",{className:"flex flex-col",children:[r.jsx(nf,{outcome:e,items:n.map(o=>({toolCallId:o.toolCallId,label:o.approvalDisplayName||lt(o.toolName,o.input??"")})),resolvedAt:s.approvalResolvedAt,startedAt:s.approvalStartedAt,reasonGiven:t}),e!=="allowed"&&s.result&&r.jsx(na,{"data-testid":"approval-receipt-result",content:s.result,className:"text-muted-foreground mt-0.5 ml-6"}),e==="allowed"&&a]})}function Ja(e){return e.endsWith("connectors.request_connection")||e.endsWith("connectors_request_connection")}function Za(e){if(e)try{return JSON.parse(e)}catch{return}}function Wt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function rf(e){const t=Za(e);if(!Wt(t))return;const{serviceSlug:n,reason:s}=t;if(!(typeof n!="string"||typeof s!="string"))return{serviceSlug:n,reason:s}}function eo(e){const t=Za(e);if(Wt(t)&&typeof t.requestId=="string")return t.requestId;if(Wt(t)&&Array.isArray(t.content)){const n=t.content.map(s=>Wt(s)&&typeof s.text=="string"?s.text:"").join("");return eo(n)}}function af(e,t){const n=eo(t.result);if(n)return e.find(a=>a.requestId===n);const s=rf(t.input);if(s)return e.filter(a=>a.serviceSlug===s.serviceSlug).sort((a,o)=>o.createdAt.localeCompare(a.createdAt))[0]}function of({sessionId:e,input:t,result:n,fallback:s}){const a=rd(e),o=a.data?af(a.data,{input:t,result:n}):void 0;return o?r.jsx("div",{className:"my-3","data-testid":"chat-agent-request",children:r.jsx(ad,{request:o})}):r.jsx(r.Fragment,{children:s})}const yn={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}},lf={match:!1,bucket:Number.POSITIVE_INFINITY,score:0};function Xs(e){return e.startsWith("/")?e.slice(1):e}function Js(e,t){return e.bucket<t.bucket||e.bucket===t.bucket&&e.score>t.score}function cf(e,t){let n=lf;const s=Ht(e,Xs(t.fullCommand));s.match&&s.tier&&(n={match:!0,bucket:yn.name[s.tier],score:s.score});for(const a of t.aliases??[]){const o=Ht(e,Xs(a));if(!o.match||!o.tier)continue;const i={bucket:yn.alias[o.tier],score:o.score};Js(i,n)&&(n={match:!0,...i,matchedAlias:a})}if(t.description){const a=Ht(e,t.description);if(a.match&&a.tier){const o={bucket:yn.description[a.tier],score:a.score};Js(o,n)&&(n={match:!0,...o})}}return n}function uf({onAllow:e,onNotNow:t}){return r.jsxs(Tu,{"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:[r.jsx(Ai,{className:"text-muted-foreground size-4 shrink-0","aria-hidden":!0}),r.jsx("p",{className:"text-muted-foreground min-w-0 flex-1 text-xs",children:"Get notified when this needs you, even in another tab."}),r.jsxs("div",{className:"flex w-full shrink-0 flex-wrap items-center justify-end gap-1.5 sm:w-auto",children:[r.jsx(ne,{variant:"ghost",size:"sm",responsive:!1,className:"h-7 px-2 text-xs",onClick:t,children:"Not now"}),r.jsx(ne,{variant:"outline",size:"sm",responsive:!1,className:"h-7 px-2 text-xs",onClick:e,children:"Turn on notifications"})]})]})}function df(e){const t=qc(),{permission:n,request:s}=Ti(),{prefs:a,setPrefs:o}=Fi(),{data:i}=sa(),l=i!==void 0,[u,d]=c.useState(!1),f=Ri()||n==="unsupported";c.useEffect(()=>{if(f||!e)return;const g=setTimeout(Hc,Wc);return()=>clearTimeout(g)},[f,e]);const h=c.useCallback(()=>{d(!0),s().then(()=>{o({browserPermissionPrimerDismissed:!0})})},[s,o]),m=c.useCallback(()=>{d(!0),o({browserPermissionPrimerDismissed:!0})},[o]);return{eligible:!f&&l&&t&&!u&&n==="default"&&!a.browserPermissionPrimerDismissed,allow:h,notNow:m}}const to="dorkos:mcp-app-consent:";function no(e){return`${to}${e}`}function ff(e){try{return localStorage.getItem(no(e))==="granted"}catch{return!1}}function mf(e){try{localStorage.setItem(no(e),"granted")}catch{}pf()}const Un=new Set;function pf(){for(const e of Un)e()}function hf(e){Un.add(e);const t=n=>{var s;(s=n.key)!=null&&s.startsWith(to)&&e()};return window.addEventListener("storage",t),()=>{Un.delete(e),window.removeEventListener("storage",t)}}function gf(e){const t=c.useSyncExternalStore(hf,()=>ff(e),()=>!1),n=c.useCallback(()=>mf(e),[e]);return{consented:t,grant:n}}const xf="h-80";function bf({sessionId:e,serverName:t,uri:n,title:s}){const{consented:a,grant:o}=gf(t),i=oe(d=>d.openPip),l=()=>{const d=oe.getState(),f={type:"mcp_app",serverName:t,uri:n,title:s};d.openCanvasDocument(f),$n(d,"user",f)},u=()=>{i({kind:"mcp_app",sessionId:e,serverName:t,uri:n,title:s??`App · ${t}`})};return a?r.jsxs("div",{className:"overflow-hidden rounded-lg border",children:[r.jsxs("div",{className:"bg-muted/40 flex items-center justify-between border-b px-3 py-1.5",children:[r.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[r.jsx(zn,{className:"text-muted-foreground size-3.5 shrink-0"}),r.jsx("span",{className:"truncate",children:s??`App · ${t}`})]}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.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:r.jsx(Vu,{className:"size-3.5"})}),r.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:r.jsx(Mi,{className:"size-3.5"})})]})]}),r.jsx(Zu,{sessionId:e,serverName:t,uri:n,title:s,onRequestFullscreen:l,onRequestPip:u,className:xf})]}):r.jsxs("div",{className:"bg-muted/40 flex flex-col gap-3 rounded-lg border p-4",children:[r.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[r.jsx(zn,{className:"text-muted-foreground size-4 shrink-0"}),r.jsxs("span",{children:["Interactive app from ",t]})]}),r.jsxs("div",{className:"text-muted-foreground space-y-1 text-xs",children:[r.jsxs("p",{children:["It runs code from ",t," in a sealed-off frame."]}),r.jsx("p",{children:"It can’t see your chat, files or credentials."})]}),r.jsx("div",{children:r.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"})})]})}function yf(e){return e.replace(/[-_]+/g," ").trim()}function vf({action:e}){const t=qu(),n=yf(e.actionId),s=`Widget interaction${e.title?`, ${e.title}`:""}: ${n}`;return r.jsxs(G.span,{"data-testid":"ui-action-chip",title:e.payload?JSON.stringify(e.payload):void 0,className:H("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?Hu:void 0,children:[r.jsx("span",{className:"sr-only",children:s}),r.jsx("span",{"aria-hidden":!0,className:"bg-primary/10 text-primary flex size-5 shrink-0 items-center justify-center rounded-full",children:r.jsx(Cd,{className:"size-3"})}),r.jsxs("span",{"aria-hidden":!0,className:"text-muted-foreground truncate",children:[e.title&&r.jsx("span",{className:"text-foreground font-medium",children:e.title}),e.title&&r.jsx("span",{className:"px-1 opacity-50",children:"·"}),r.jsx("span",{className:"text-foreground font-medium",children:n})]})]})}const kf=/<ui_action>([\s\S]*?)<\/ui_action>/;function Zs(e){try{const t=JSON.parse(e);return t!==null&&typeof t=="object"?t:null}catch{return null}}function Cf(e){const t=e.match(kf);if(!t)return null;const n=t[1].split(`
37
+ */const Va={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"}]]};Va.node;const Cd=Qe(Va);function Sd({color:e,isTextStreaming:t,fadeEdges:n=!0,edge:s="bottom"}){const a=t?1.8:2.5,o=n?"linear-gradient(to right, transparent, black 15%, black 85%, transparent)":void 0,i=s==="top"?"pointer-events-none absolute right-0 top-0 left-0":"pointer-events-none absolute right-0 bottom-0 left-0",l=s==="top"?"top":"bottom";return r.jsxs(G.div,{"aria-hidden":!0,initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.4},className:i,style:{height:n?10:0,overflow:n?"hidden":"visible",maskImage:o,WebkitMaskImage:o},children:[r.jsx("div",{className:"absolute right-0 left-0",style:{[l]:0,height:6,backgroundColor:e,opacity:.6,filter:"blur(3px)"}}),r.jsx(G.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"}}),r.jsx(ie,{children:t&&r.jsx(G.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 xn={"word-boundary":3,substring:2,subsequence:1},jd=new Set(["/",":","-","_","."," "]);function _d(e,t){if(t===0)return!0;const n=e[t-1];if(jd.has(n))return!0;const s=e[t];return n===n.toLowerCase()&&s!==s.toLowerCase()&&s===s.toUpperCase()}function It(e,t){return Array.from({length:t},(n,s)=>e+s)}function Ot(e,t,n){const s=1/(1+t),a=n/e.length;return(s*.6+a*.4)*.999}function wd(e,t){let n=0,s=0,a=0;const o=[];for(let i=0;i<t.length&&n<e.length;i++)t[i]===e[n]?(n++,s++,s>a&&(a=s),o.push(i)):s=0;return n===e.length?{indices:o,maxRun:a}:null}function Nd(e,t){const n=t.indices[t.indices.length-1]-t.indices[0]+1,s=t.maxRun/t.indices.length,a=t.indices.length/n,o=t.indices.length/e.length;return(s*.4+a*.3+o*.3)*.999}function Ht(e,t){if(!e)return{match:!0,tier:null,score:0,indices:[]};const n=e.toLowerCase(),s=t.toLowerCase();if(s===n)return{match:!0,tier:"exact",score:5+Ot(t,0,n.length),indices:It(0,n.length)};if(s.startsWith(n))return{match:!0,tier:"prefix",score:4+Ot(t,0,n.length),indices:It(0,n.length)};for(let i=1;i<=s.length-n.length;i++)if(_d(t,i)&&s.startsWith(n,i))return{match:!0,tier:"word-boundary",score:xn["word-boundary"]+Ot(t,i,n.length),indices:It(i,n.length)};const a=s.indexOf(n);if(a>=0)return{match:!0,tier:"substring",score:xn.substring+Ot(t,a,n.length),indices:It(a,n.length)};const o=wd(n,s);return o?{match:!0,tier:"subsequence",score:xn.subsequence+Nd(t,o),indices:o.indices}:{match:!1,tier:null,score:0,indices:[]}}function Ga(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/^./,t=>t.toUpperCase())}function Ed(e,t){return e.length<=t?e:e.slice(0,t)+"…"}function Dd(e){return/^[/~.]/.test(e)||/\.(ts|tsx|js|jsx|json|md|py|rs|go|sh|yml|yaml|toml)$/.test(e)}function Bn(e,t){if(e===null)return r.jsx("span",{className:"text-muted-foreground italic",children:"null"});if(typeof e=="boolean")return r.jsx("span",{className:"text-amber-600 dark:text-amber-400",children:String(e)});if(typeof e=="number")return r.jsx("span",{className:"text-blue-600 dark:text-blue-400",children:e});if(typeof e=="string"){const n=Ed(e,t);return Dd(e)?r.jsx("code",{className:"bg-muted rounded px-1 py-0.5 text-xs break-all",children:n}):r.jsx("span",{className:"break-words",children:n})}if(Array.isArray(e)){const n=e.slice(0,5),s=e.length-5;return r.jsxs("div",{className:"space-y-0.5",children:[n.map((a,o)=>r.jsx("div",{className:"border-border/40 border-l pl-2",children:Bn(a,80)},o)),s>0&&r.jsxs("span",{className:"text-muted-foreground text-xs italic",children:["… and ",s," more"]})]})}if(typeof e=="object"){const n=Object.entries(e);return r.jsx("div",{className:"space-y-0.5",children:n.map(([s,a])=>r.jsxs("div",{className:"border-border/40 border-l pl-2",children:[r.jsxs("span",{className:"text-muted-foreground text-xs",children:[Ga(s),": "]}),typeof a=="object"&&a!==null?r.jsx("span",{className:"text-muted-foreground italic",children:"{…}"}):Bn(a,80)]},s))})}return r.jsx("span",{children:String(e)})}function Ka({toolName:e,input:t,isStreaming:n=!1}){if(!t)return null;if(n){const o=t.length>5120?t.slice(0,5120)+"…":t;return r.jsxs("pre",{className:"text-muted-foreground overflow-x-auto text-xs whitespace-pre-wrap",children:[o,r.jsx("span",{className:"animate-breath ml-0.5 inline-block size-1.5 rounded-full bg-current"})]})}let s;try{s=JSON.parse(t)}catch{const o=t.length>5120?t.slice(0,5120)+"…":t;return r.jsx("pre",{className:"overflow-x-auto text-xs whitespace-pre-wrap",children:o})}if(typeof s!="object"||s===null||Array.isArray(s)){const o=t.length>5120?t.slice(0,5120)+"…":t;return r.jsx("pre",{className:"overflow-x-auto text-xs whitespace-pre-wrap",children:o})}const a=Object.entries(s);return a.length===0?null:r.jsx("dl",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs",children:a.map(([o,i])=>r.jsxs("div",{className:"contents",children:[r.jsx("dt",{className:"text-muted-foreground py-0.5 font-medium whitespace-nowrap",children:Ga(o)}),r.jsx("dd",{className:"min-w-0 py-0.5",children:Bn(i,120)})]},o))})}class Ad{constructor(t){Ze(this,"config");Ze(this,"recentCompletions",[]);Ze(this,"queue",[]);Ze(this,"isIdle",!1);Ze(this,"debounceTimer",null);this.config=t}onTaskCompleted(t,n){if(!this.config.enabled)return;const s=Date.now();this.recentCompletions.push(s),this.recentCompletions=this.recentCompletions.filter(l=>s-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:s};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:s};this.emitOrQueue(l)}}setIdle(t){this.isIdle=t}onUserReturn(){if(this.queue.length>0){const n=this.queue.some(s=>s.level==="major")?this.queue.find(s=>s.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 Td={background:"radial-gradient(circle, rgba(255,215,0,0.15) 0%, transparent 70%)"},Fd={mode:"blur-in",duration:150,easing:"ease-out",sep:"word"},Rd={none:void 0,fade:"fadeIn","blur-in":"blurIn","slide-up":"slideUp"};function Md(e){const t=Rd[e.mode];return t?{animation:t,duration:e.duration??150,easing:e.easing??"ease-out",sep:e.sep??"word"}:!1}function Id(e,t=40){if(e.length<=t)return e;const n=e.split("/").pop()??e,s=n.length+2,a=Math.max(6,t-s);return`${e.slice(0,a)}…/${n}`}function Od({onlyFirst:e=!1}={}){const a="(?:\\u001B\\][^\\u0007\\u001B\\u009C]*(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";return new RegExp(a,e?void 0:"g")}const $d=Od({onlyFirst:!0});function Pd(e){if($d.test(e))return"ansi";const t=e.trimStart();if(t.startsWith("{")||t.startsWith("["))try{return JSON.parse(e),"json"}catch{}return"plain"}function tn(e){var n;const{sessions:t}=Zn();if(e)return(n=t.find(s=>s.id===e))==null?void 0:n.runtime}const Ld=typeof window<"u"&&window.location.pathname===bi;let bn=null,Ks=!Ld;function zd(e){return Ks?bn===e?!0:(bn=null,!1):(Ks=!0,bn=e,!0)}function Bd(e){var s;const t=xe(),n=((s=Zr(e))==null?void 0:s.draft)===!0;c.useEffect(()=>{if(!e||n)return;let a=!1;const o=()=>{a||document.visibilityState!=="visible"||(a=!0,document.removeEventListener("visibilitychange",o),zd(e)||at.getState().recordOpened("session",e),t.markSessionOpened(e).catch(i=>{xi(t,i)}))};if(o(),!a)return document.addEventListener("visibilitychange",o),()=>document.removeEventListener("visibilitychange",o)},[e,n,t])}function Qa(){const e=ea(),t=Zr(e.session);return{cwd:(t==null?void 0:t.cwd)??e.dir??null}}function Ya({agentId:e,agentName:t,onResumed:n}){const s=yi(),{data:a,dataUpdatedAt:o,refetch:i}=vi(),[l]=c.useState(()=>Date.now());c.useEffect(()=>{i()},[e,i]);const u=t??"This agent";return a!=null&&o>=l&&!a.pauses.some(f=>f.agentId===e)?null:r.jsxs("div",{"data-testid":"agent-paused-notice",role:"status",className:"border-border bg-muted/50 my-2 flex items-center gap-3 rounded-lg border px-4 py-3",children:[r.jsx(ki,{className:"text-muted-foreground size-4 shrink-0","aria-hidden":!0}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsxs("p",{className:"text-sm font-medium",children:[u," is paused"]}),r.jsx("p",{className:"text-muted-foreground text-xs",children:"Resume it, then send your message again."})]}),r.jsx(ne,{size:"sm",variant:"outline",disabled:s.isPending,onClick:()=>s.mutate(e,{onSuccess:()=>{Ee(`${u} resumed`),n==null||n()}}),children:"Resume"})]})}const qd={session:"this chat",project:"this project",user:"all your Claude chats"};function Ud(e){return e===void 0?void 0:qd[e]}const Hd={duration:.12,ease:"easeOut"},Wd={duration:0},Qs=new Set(["Bash","Write","Edit","NotebookEdit"]),Ys=new Set(["WebFetch","WebSearch"]);function Vd(e){const t=e.includes("__")?e.split("__").pop():e;return Qs.has(t)||Qs.has(e)?"high":Ys.has(t)||Ys.has(e)||e.startsWith("mcp__")?"medium":"low"}function Gd(e){const t=Math.floor(e/60),n=e%60;return t>0?`${t}:${String(n).padStart(2,"0")}`:`${n}s`}function Xa({sessionId:e,toolCallId:t,toolName:n,input:s,isActive:a=!1,onDecided:o,ref:i,timeoutMs:l,approvalStartedAt:u,approvalRemainingMs:d,approvalParked:f,approvalTitle:h,approvalDisplayName:m,approvalDescription:x,approvalBlockedPath:g,approvalDecisionReason:S,approvalHasSuggestions:b,approvalAlwaysAllowScope:y,allowsDenyReason:C=!0}){const v=xe(),p=Te(),j=c.useMemo(()=>Vd(n),[n]),_=ta(n),D=lt(n,s),T=m||D,N=Ud(y),[A,k]=c.useState(!1),[E,w]=c.useState(null),[R,O]=c.useState(null),[F,$]=c.useState(!1),[B,U]=c.useState(""),Y=c.useRef(""),[se,V]=c.useState(!1),L=a&&!se,[I,P]=c.useState(()=>Date.now()),Q=c.useRef(!1);c.useLayoutEffect(()=>{if(!Q.current){Q.current=!0;return}P(Date.now())},[l,u,d]);const[ae,M]=c.useState(null),W=c.useMemo(()=>{if(!l||f===!0)return null;const z=d!==void 0?I+d:u?u+l:I+l,he=Math.min(l,Math.max(0,l-(z-I)));return{expiresAt:z,elapsedMs:he}},[I,l,u,d,f]),X=E||!l||!W?null:ae!==null&&ae.expiresAt===W.expiresAt?ae.seconds:Math.max(0,Math.ceil((W.expiresAt-I)/1e3));c.useEffect(()=>{if(E||!l||!W)return;const{expiresAt:z}=W,he=setInterval(()=>{const ce=Math.max(0,Math.ceil((z-Date.now())/1e3));M({expiresAt:z,seconds:ce}),ce<=0&&clearInterval(he)},1e3);return()=>clearInterval(he)},[l,W,E]);const J=f===!0||X===0,Z=E||X===null?"":X<=0?"Nobody answered. The agent is waiting for you.":X<=Ni?"One minute left to answer.":X<=Ei?"Two minutes left to answer.":"",K=c.useCallback(async()=>{if(!(A||E)){k(!0),O(null);try{await v.approveTool(e,t),w("approved"),o==null||o()}catch(z){z.code==="INTERACTION_ALREADY_RESOLVED"?(w("approved"),o==null||o()):(console.error("Approval failed:",z),O("Couldn’t send your answer. Try again."))}finally{k(!1)}}},[A,E,v,e,t,o]),le=c.useCallback(async()=>{if(!(A||E)){k(!0),O(null);try{await v.approveTool(e,t,!0),w("approved"),o==null||o()}catch(z){z.code==="INTERACTION_ALREADY_RESOLVED"?(w("approved"),o==null||o()):(console.error("Always Allow failed:",z),O("Couldn’t send your answer. Try again."))}finally{k(!1)}}},[A,E,v,e,t,o]),fe=c.useCallback(async()=>{if(!(A||E)){k(!0),O(null);try{await v.denyTool(e,t,Y.current.trim()||void 0),w("denied"),o==null||o()}catch(z){z.code==="INTERACTION_ALREADY_RESOLVED"?(w("denied"),o==null||o()):(console.error("Deny failed:",z),O("Couldn’t send your answer. Try again."))}finally{k(!1)}}},[A,E,v,e,t,o]);c.useImperativeHandle(i,()=>({approve(){K()},alwaysAllow(){le()},deny(){fe()}}),[K,le,fe]);const me=r.jsx("span",{role:"status","aria-live":"assertive","aria-atomic":"true",className:"sr-only",children:Z});if(E){const z=E==="approved";return r.jsxs(r.Fragment,{children:[r.jsx(G.div,{initial:p?!1:{opacity:0,scaleY:.9},animate:{opacity:1,scaleY:1},transition:p?Wd:Hd,style:{originY:0},children:r.jsx(Ve,{"data-testid":"tool-approval-decided","data-decision":E,icon:z?r.jsx(ot,{className:"text-status-success size-(--size-icon-sm) shrink-0"}):r.jsx(Le,{className:"text-status-error size-(--size-icon-sm) shrink-0"}),label:r.jsx("span",{className:"text-3xs font-mono",children:T}),trailing:r.jsx("span",{className:H("text-2xs rounded-full px-1.5 py-0.5 font-medium",z?"bg-status-success-bg text-status-success-fg":"bg-status-error-bg text-status-error-fg"),children:z?"Allowed":"Not allowed"})})}),me]})}return r.jsxs(r.Fragment,{children:[r.jsxs(mt.Root,{isActive:a,isResolved:!!E,onAllow:K,onDeny:fe,className:"my-1","data-testid":"tool-approval",children:[r.jsxs("div",{className:"mb-1 flex items-center gap-2",children:[r.jsx(Ci,{className:H("size-(--size-icon-md)",j==="high"&&"text-status-error",j==="medium"&&"text-status-warning",j==="low"&&"text-muted-foreground")}),r.jsx(mt.Headline,{className:"font-semibold",children:h||"Your agent wants to use a tool"})]}),(x||S||g)&&r.jsxs(mt.Detail,{className:"mb-2",children:[x&&r.jsx("p",{children:x}),S&&!x&&r.jsx("p",{children:S}),g&&r.jsxs("p",{className:"font-mono",children:["Path: ",g]})]}),(l||J)&&!E&&r.jsx("div",{className:"mb-2",children:r.jsx(mt.Countdown,{secondsLeft:J?null:X,...J?{}:{timeoutMs:l},elapsedMs:(W==null?void 0:W.elapsedMs)??0,label:J?Si:X===null?"":`${Gd(X)} remaining`})}),r.jsxs("div",{className:"mb-2 flex items-center gap-1.5",children:[_&&r.jsx("span",{className:"bg-muted text-muted-foreground text-3xs rounded px-1 py-0.5 font-medium",children:_}),r.jsx("span",{className:"font-mono text-xs",children:T})]}),s&&r.jsx("div",{className:"bg-muted mb-3 rounded p-2",children:r.jsx(Ka,{toolName:n,input:s})}),R&&r.jsx("p",{className:"text-status-error text-2xs mb-2",children:R}),C&&F&&r.jsx("div",{className:"mb-2",children:r.jsx(ji,{autoFocus:!0,"data-approval-field":"",value:B,maxLength:_i,disabled:A,onFocus:()=>V(!0),onBlur:()=>V(!1),onChange:z=>{U(z.target.value),Y.current=z.target.value},onKeyDown:z=>{z.key==="Enter"&&(z.preventDefault(),fe())},placeholder:"Why not? The agent sees this.","aria-label":"Reason for not allowing",className:"text-xs"})}),r.jsxs(mt.Actions,{children:[r.jsxs(ne,{size:"sm",onClick:K,disabled:A,className:"transition-opacity duration-150",children:[r.jsx(ot,{className:"size-(--size-icon-xs)"})," Allow",L&&r.jsx(dn,{className:"ml-1.5",children:"Enter"})]}),b&&r.jsxs(ne,{size:"sm",variant:"outline",onClick:le,disabled:A,"aria-label":N===void 0?"Always allow":`Always allow, ${N}`,className:"transition-opacity duration-150",children:[r.jsx(wi,{className:"size-(--size-icon-xs)"})," Always allow",N!==void 0&&r.jsx("span",{className:"text-2xs opacity-70",children:`· ${N}`}),L&&r.jsx(dn,{className:"ml-1.5",children:"Shift+Enter"})]}),r.jsxs(ne,{size:"sm",variant:"outline",onClick:fe,disabled:A,className:"transition-opacity duration-150",children:[r.jsx(Le,{className:"size-(--size-icon-xs)"})," Don’t allow",a&&r.jsx(dn,{className:"ml-1.5",children:"Esc"})]}),C&&!F&&r.jsx("button",{type:"button",onClick:()=>$(!0),disabled:A,className:H("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 Kd(e){if(!e)return[];const t=e.properties??{};return Object.entries(t).map(([n,s])=>({key:n,label:s.description??n,type:s.type??"string",options:s.enum,defaultValue:s.default}))}function Qd({sessionId:e,interactionId:t,serverName:n,message:s,mode:a="form",url:o,requestedSchema:i,status:l,action:u}){const d=xe(),[f,h]=c.useState(!1),[m,x]=c.useState(null),[g,S]=c.useState(null),[b,y]=c.useState({}),[C,v]=c.useState(!1),p=c.useMemo(()=>Kd(i),[i]),j=l!=="pending",_=c.useCallback(async(E,w)=>{if(!(f||j)){h(!0),x(null),S(null);try{await d.submitElicitation(e,t,E,w)}catch(R){if(R.code!=="INTERACTION_ALREADY_RESOLVED"){x("Couldn’t send your answer. Try again."),S(R instanceof Error?R.message:null),h(!1);return}}h(!1)}},[d,e,t,f,j]),D=c.useCallback(()=>{const E={};for(const w of p)E[w.key]=b[w.key]??w.defaultValue??"";_("accept",E)},[p,b,_]),T=c.useCallback(()=>{_("accept")},[_]),N=c.useCallback(()=>{_("decline")},[_]),A=c.useCallback((E,w)=>{y(R=>({...R,[E]:w}))},[]),k=c.useCallback(()=>{if(o){if(!Di(o)){x(`Couldn’t open ${o}. Nothing has been authorized.`),S(null);return}x(null),S(null),v(!0)}},[o]);return j?r.jsxs("div",{className:"text-muted-foreground flex items-center gap-2 py-1 text-xs",children:[r.jsx("span",{className:"font-mono",children:n}),r.jsx("span",{children:"·"}),r.jsx("span",{children:u==="accept"?"Authorized":u==="decline"?"Declined":"Cancelled"})]}):r.jsxs(G.div,{initial:{opacity:0,y:4},animate:{opacity:1,y:0},transition:{duration:.15},className:H("border-border bg-card my-2 rounded-xl border p-4","shadow-soft"),children:[r.jsxs("div",{className:"text-muted-foreground mb-2 flex items-center gap-2 text-xs",children:[r.jsx("span",{className:"bg-muted text-3xs inline-flex items-center rounded-md px-2 py-0.5 font-mono",children:n}),r.jsx("span",{children:"needs something from you"})]}),r.jsx("p",{className:"mb-3 text-sm",children:s}),m&&r.jsxs("div",{className:"mb-2",children:[r.jsx("p",{className:"text-destructive text-xs break-words",children:m}),g&&r.jsx("p",{className:"text-muted-foreground/70 mt-1 text-xs break-words",children:g})]}),a==="url"&&o&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(ne,{size:"sm",variant:"outline",onClick:k,disabled:f,children:"Open authorization page"}),C&&r.jsx(ne,{size:"sm",onClick:T,disabled:f,children:f?"Sending…":"Done"}),r.jsx(ne,{size:"sm",variant:"ghost",onClick:N,disabled:f,children:"Decline"})]}),a==="form"&&r.jsxs(r.Fragment,{children:[p.length>0?r.jsx("div",{className:"mb-3 space-y-2",children:p.map(E=>r.jsxs("div",{children:[r.jsx("label",{htmlFor:`elicitation-${t}-${E.key}`,className:"text-muted-foreground mb-1 block text-xs font-medium",children:E.label}),E.options?r.jsxs("select",{id:`elicitation-${t}-${E.key}`,className:"border-input bg-background w-full rounded-md border px-3 py-1.5 text-sm",value:b[E.key]??String(E.defaultValue??""),onChange:w=>A(E.key,w.target.value),disabled:f,children:[r.jsx("option",{value:"",children:"Select…"}),E.options.map(w=>r.jsx("option",{value:w,children:w},w))]}):r.jsx("input",{id:`elicitation-${t}-${E.key}`,type:E.type==="number"?"number":"text",className:"border-input bg-background w-full rounded-md border px-3 py-1.5 text-sm",placeholder:String(E.defaultValue??""),value:b[E.key]??"",onChange:w=>A(E.key,w.target.value),disabled:f})]},E.key))}):r.jsx("p",{className:"text-muted-foreground mb-3 text-xs",children:"No additional input required."}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(ne,{size:"sm",onClick:D,disabled:f,children:f?"Sending…":"Accept"}),r.jsx(ne,{size:"sm",variant:"ghost",onClick:N,disabled:f,children:"Decline"})]})]})]})}const Yd=8,Xd={duration:.3,ease:[.16,1,.3,1]},Jd={duration:0};function Zd(e){const t=Math.round(e/1e3),n=Math.floor(t/60),s=t%60;return n>0?`${n}:${String(s).padStart(2,"0")}`:`${s}s`}function ef(e){return new Date(e).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"})}function tf(e){return`${e} action${e===1?"":"s"}`}function nf({outcome:e,items:t,resolvedAt:n,startedAt:s,reasonGiven:a,className:o}){var S;const i=Te(),[l,u]=c.useState(!1),d=t.length,f=d>1,h=f?tf(d):(S=t[0])==null?void 0:S.label,m=n!==void 0&&s!==void 0?Math.max(0,n-s):null,x=e==="allowed"?ot:e==="denied"?Le:gt,g=e==="allowed"?"text-status-success":e==="denied"?"text-status-error":"text-muted-foreground";return r.jsxs(G.div,{"data-testid":"approval-receipt","data-outcome":e,"data-count":d,initial:i?!1:{opacity:0,y:Yd},animate:{opacity:1,y:0},transition:i?Jd:Xd,className:H("text-muted-foreground my-1 text-xs",o),children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(x,{className:H("size-(--size-icon-xs) shrink-0",g),"aria-hidden":"true"}),r.jsx("span",{className:"min-w-0 truncate",children:e==="expired"?r.jsxs(r.Fragment,{children:["Expired · ",f?`${h} `:"","denied",m!==null&&` after ${Zd(m)}`]}):r.jsxs(r.Fragment,{children:["You ",e==="allowed"?"allowed":"denied"," ",f?h:r.jsx("span",{className:"font-mono",children:h}),e==="denied"&&a===!0&&r.jsx(r.Fragment,{children:" · agent was told why"})]})}),n!==void 0&&r.jsx("time",{dateTime:new Date(n).toISOString(),className:"ml-auto shrink-0 tabular-nums opacity-70",children:ef(n)}),f&&r.jsx("button",{type:"button",onClick:()=>u(b=>!b),"aria-expanded":l,className:H("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"})]}),f&&l&&r.jsx("ul",{"data-testid":"approval-receipt-items",className:"mt-1 ml-6 space-y-0.5",children:t.map(b=>r.jsx("li",{className:"truncate font-mono",children:b.label},b.toolCallId))})]})}function sf({outcome:e,reasonGiven:t,members:n,lead:s,children:a}){return r.jsxs("div",{className:"flex flex-col",children:[r.jsx(nf,{outcome:e,items:n.map(o=>({toolCallId:o.toolCallId,label:o.approvalDisplayName||lt(o.toolName,o.input??"")})),resolvedAt:s.approvalResolvedAt,startedAt:s.approvalStartedAt,reasonGiven:t}),e!=="allowed"&&s.result&&r.jsx(na,{"data-testid":"approval-receipt-result",content:s.result,className:"text-muted-foreground mt-0.5 ml-6"}),e==="allowed"&&a]})}function Ja(e){return e.endsWith("connectors.request_connection")||e.endsWith("connectors_request_connection")}function Za(e){if(e)try{return JSON.parse(e)}catch{return}}function Wt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function rf(e){const t=Za(e);if(!Wt(t))return;const{serviceSlug:n,reason:s}=t;if(!(typeof n!="string"||typeof s!="string"))return{serviceSlug:n,reason:s}}function eo(e){const t=Za(e);if(Wt(t)&&typeof t.requestId=="string")return t.requestId;if(Wt(t)&&Array.isArray(t.content)){const n=t.content.map(s=>Wt(s)&&typeof s.text=="string"?s.text:"").join("");return eo(n)}}function af(e,t){const n=eo(t.result);if(n)return e.find(a=>a.requestId===n);const s=rf(t.input);if(s)return e.filter(a=>a.serviceSlug===s.serviceSlug).sort((a,o)=>o.createdAt.localeCompare(a.createdAt))[0]}function of({sessionId:e,input:t,result:n,fallback:s}){const a=sd(e),o=a.data?af(a.data,{input:t,result:n}):void 0;return o?r.jsx("div",{className:"my-3","data-testid":"chat-agent-request",children:r.jsx(rd,{request:o})}):r.jsx(r.Fragment,{children:s})}const yn={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}},lf={match:!1,bucket:Number.POSITIVE_INFINITY,score:0};function Xs(e){return e.startsWith("/")?e.slice(1):e}function Js(e,t){return e.bucket<t.bucket||e.bucket===t.bucket&&e.score>t.score}function cf(e,t){let n=lf;const s=Ht(e,Xs(t.fullCommand));s.match&&s.tier&&(n={match:!0,bucket:yn.name[s.tier],score:s.score});for(const a of t.aliases??[]){const o=Ht(e,Xs(a));if(!o.match||!o.tier)continue;const i={bucket:yn.alias[o.tier],score:o.score};Js(i,n)&&(n={match:!0,...i,matchedAlias:a})}if(t.description){const a=Ht(e,t.description);if(a.match&&a.tier){const o={bucket:yn.description[a.tier],score:a.score};Js(o,n)&&(n={match:!0,...o})}}return n}function uf({onAllow:e,onNotNow:t}){return r.jsxs(Tu,{"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:[r.jsx(Ai,{className:"text-muted-foreground size-4 shrink-0","aria-hidden":!0}),r.jsx("p",{className:"text-muted-foreground min-w-0 flex-1 text-xs",children:"Get notified when this needs you, even in another tab."}),r.jsxs("div",{className:"flex w-full shrink-0 flex-wrap items-center justify-end gap-1.5 sm:w-auto",children:[r.jsx(ne,{variant:"ghost",size:"sm",responsive:!1,className:"h-7 px-2 text-xs",onClick:t,children:"Not now"}),r.jsx(ne,{variant:"outline",size:"sm",responsive:!1,className:"h-7 px-2 text-xs",onClick:e,children:"Turn on notifications"})]})]})}function df(e){const t=Uc(),{permission:n,request:s}=Ti(),{prefs:a,setPrefs:o}=Fi(),{data:i}=sa(),l=i!==void 0,[u,d]=c.useState(!1),f=Ri()||n==="unsupported";c.useEffect(()=>{if(f||!e)return;const g=setTimeout(Hc,Wc);return()=>clearTimeout(g)},[f,e]);const h=c.useCallback(()=>{d(!0),s().then(()=>{o({browserPermissionPrimerDismissed:!0})})},[s,o]),m=c.useCallback(()=>{d(!0),o({browserPermissionPrimerDismissed:!0})},[o]);return{eligible:!f&&l&&t&&!u&&n==="default"&&!a.browserPermissionPrimerDismissed,allow:h,notNow:m}}const to="dorkos:mcp-app-consent:";function no(e){return`${to}${e}`}function ff(e){try{return localStorage.getItem(no(e))==="granted"}catch{return!1}}function mf(e){try{localStorage.setItem(no(e),"granted")}catch{}pf()}const qn=new Set;function pf(){for(const e of qn)e()}function hf(e){qn.add(e);const t=n=>{var s;(s=n.key)!=null&&s.startsWith(to)&&e()};return window.addEventListener("storage",t),()=>{qn.delete(e),window.removeEventListener("storage",t)}}function gf(e){const t=c.useSyncExternalStore(hf,()=>ff(e),()=>!1),n=c.useCallback(()=>mf(e),[e]);return{consented:t,grant:n}}const xf="h-80";function bf({sessionId:e,serverName:t,uri:n,title:s}){const{consented:a,grant:o}=gf(t),i=oe(d=>d.openPip),l=()=>{const d=oe.getState(),f={type:"mcp_app",serverName:t,uri:n,title:s};d.openCanvasDocument(f),$n(d,"user",f)},u=()=>{i({kind:"mcp_app",sessionId:e,serverName:t,uri:n,title:s??`App · ${t}`})};return a?r.jsxs("div",{className:"overflow-hidden rounded-lg border",children:[r.jsxs("div",{className:"bg-muted/40 flex items-center justify-between border-b px-3 py-1.5",children:[r.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[r.jsx(zn,{className:"text-muted-foreground size-3.5 shrink-0"}),r.jsx("span",{className:"truncate",children:s??`App · ${t}`})]}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.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:r.jsx(Wu,{className:"size-3.5"})}),r.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:r.jsx(Mi,{className:"size-3.5"})})]})]}),r.jsx(Ju,{sessionId:e,serverName:t,uri:n,title:s,onRequestFullscreen:l,onRequestPip:u,className:xf})]}):r.jsxs("div",{className:"bg-muted/40 flex flex-col gap-3 rounded-lg border p-4",children:[r.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[r.jsx(zn,{className:"text-muted-foreground size-4 shrink-0"}),r.jsxs("span",{children:["Interactive app from ",t]})]}),r.jsxs("div",{className:"text-muted-foreground space-y-1 text-xs",children:[r.jsxs("p",{children:["It runs code from ",t," in a sealed-off frame."]}),r.jsx("p",{children:"It can’t see your chat, files or credentials."})]}),r.jsx("div",{children:r.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"})})]})}function yf(e){return e.replace(/[-_]+/g," ").trim()}function vf({action:e}){const t=Uu(),n=yf(e.actionId),s=`Widget interaction${e.title?`, ${e.title}`:""}: ${n}`;return r.jsxs(G.span,{"data-testid":"ui-action-chip",title:e.payload?JSON.stringify(e.payload):void 0,className:H("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?Hu:void 0,children:[r.jsx("span",{className:"sr-only",children:s}),r.jsx("span",{"aria-hidden":!0,className:"bg-primary/10 text-primary flex size-5 shrink-0 items-center justify-center rounded-full",children:r.jsx(Cd,{className:"size-3"})}),r.jsxs("span",{"aria-hidden":!0,className:"text-muted-foreground truncate",children:[e.title&&r.jsx("span",{className:"text-foreground font-medium",children:e.title}),e.title&&r.jsx("span",{className:"px-1 opacity-50",children:"·"}),r.jsx("span",{className:"text-foreground font-medium",children:n})]})]})}const kf=/<ui_action>([\s\S]*?)<\/ui_action>/;function Zs(e){try{const t=JSON.parse(e);return t!==null&&typeof t=="object"?t:null}catch{return null}}function Cf(e){const t=e.match(kf);if(!t)return null;const n=t[1].split(`
38
38
  `);let s=null,a=null,o=null,i=null;for(let l=0;l<n.length;l++){const u=n[l],d=u.match(/^\s*Widget:\s*(.*)$/);if(d){const x=d[1].trim();s=x&&x!=="(untitled)"?x:null;continue}const f=u.match(/^\s*Action:\s*(.*)$/);if(f){a=f[1].trim();continue}const h=u.match(/^\s*Widget ID:\s*(.*)$/);if(h){o=h[1].trim()||null;continue}const m=u.match(/^\s*Payload:\s*(.*)$/);if(m){const x=m[1].trim();if(x&&x!=="(none)")i=Zs(x);else if(!x){let g="";for(let S=l+1;S<n.length;S++){g+=(g?`
39
- `:"")+n[S];const b=Zs(g.trim());if(b){i=b;break}}}break}}return a?{title:s,actionId:a,widgetId:o,payload:i}:null}const Sf="dorkos:chat:last-seen:";function jf(){try{const e=[];for(let t=0;t<window.localStorage.length;t++){const n=window.localStorage.key(t);n!=null&&n.startsWith(Sf)&&e.push(n)}for(const t of e)window.localStorage.removeItem(t)}catch{}}function _f(e){let t=0;for(const n of e)n._streaming!==!0&&t++;return t}function wf(e){if(typeof e!="object"||e===null)return!1;const{userId:t,threadKind:n,threadId:s,lastReadSeq:a}=e;return typeof t=="string"&&typeof n=="string"&&typeof s=="string"&&typeof a=="number"&&Number.isInteger(a)}function Nf(e,t){const n=xe(),[s,a]=c.useState(()=>({sessionId:e,lastReadSeq:null,hydrated:!1}));s.sessionId!==e&&a({sessionId:e,lastReadSeq:null,hydrated:!1});const o=c.useRef(0),i=c.useRef(null),l=c.useRef(!1),u=c.useRef(!1),d=c.useRef(e),f=c.useRef(null),h=_f(t);c.useEffect(()=>{jf();let y=!1;return d.current=e,o.current=0,i.current=null,l.current=!1,u.current=!1,(async()=>{let C=null;try{C=await n.getReadCursor("session",e)}catch{}y||(C&&(o.current=C.lastReadSeq,f.current=C.userId),a({sessionId:e,lastReadSeq:(C==null?void 0:C.lastReadSeq)??null,hydrated:!0}))})(),()=>{y=!0}},[n,e]);const m=c.useCallback(async()=>{if(!l.current){l.current=!0;try{for(;;){const y=i.current;if(y===null)break;if(i.current=null,y.sessionId!==d.current)continue;if(u.current)break;const C=o.current;o.current=Math.max(C,y.seq);try{const v=await n.setReadCursor("session",y.sessionId,y.seq);f.current=v.userId??f.current}catch{o.current=C,y.sessionId===d.current&&(u.current=!0);break}}}finally{l.current=!1}}},[n]),x=c.useCallback(()=>{!s.hydrated||u.current||h<=o.current||(i.current={sessionId:e,seq:h},m())},[s.hydrated,e,h,m]);Ii("read_cursor",y=>{if(!wf(y)||y.threadKind!=="session"||y.threadId!==e)return;const C=f.current;C!==null&&y.userId!==C||y.lastReadSeq<=o.current||(o.current=y.lastReadSeq,a({sessionId:e,lastReadSeq:y.lastReadSeq,hydrated:!0}))});const g=c.useMemo(()=>t.filter(y=>y._streaming!==!0).map((y,C)=>({id:y.id,seq:C+1})),[t]),S=s.lastReadSeq,b=Ru(g,S===null?null:Math.min(S,h));return{lastSeenMessageId:b.lastSeenId,unreadFromStart:b.fromStart,markSeen:x,isHydrated:s.hydrated}}function Ke(e){return e.notAllowed!==!0&&e.usage.state!=="limited"}function Ef(e,t){if(e.id===it||!e.eligible)return e.reason;const n=Oi(e.usage,"seven_day");if(!n||n.usedPct===null)return"usage unknown";const s=Math.min(100,Math.max(0,Math.round(100-n.usedPct))),a=$i(n.resetsAt,t);return a?`${s}% left · resets ${a}`:`${s}% left`}function nn(e,t){return e.runtime!==void 0&&e.runtime!==t}function Df(e,t){const n=[],s=[];for(const a of e)(nn(a,t)?s:n).push(a);return{same:n,other:s}}function Kt(e,t){return`${e.runtime??t}:${e.id}`}function Af(e,t,n){if(nn(e,t)){const s=e.runtime;return!e.label&&e.id===vt?`${Gt({runtime:s,accountLabel:null,identityGate:!1})} (this computer's sign-in)`:Gt({runtime:s,accountLabel:e.label,identityGate:!0})}return e.label?e.label:e.id===vt&&e.usage.label?e.usage.label:e.usage.path?n(e.usage.path):e.id}function Tf(e,t){const n=e.accounts.find(a=>a.id===e.recommendedId);if(n&&Ke(n))return Kt(n,t);const s=e.accounts.find(Ke);return s?Kt(s,t):null}function Ff(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 Rf(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 Mf(e){return e.carryOver===!1}function If(e,t,n){return e?!0:(t==null?void 0:t.accounts.some(s=>nn(s,n)))??!1}function Of(e){return{id:it,runtime:e,label:Rs,color:Fs,eligible:!0,reason:"paid from your DorkOS account",usage:{runtime:"claude-code",accountId:it,path:"",label:Rs,color:Fs,subscriptionType:null,plan:null,credits:null,spend:null,windows:[],state:"unknown",limit:null,updatedAt:null}}}function so(e,t){const n=xe();return Ye({queryKey:es.continueOptions(e),queryFn:()=>n.getContinueOptions(e),enabled:t,staleTime:0,retry:!1})}function $f(e){const t=xe();return kt({mutationFn:n=>t.continueSession(e,n),retry:!1})}function Pf(e){const t=xe();return kt({mutationFn:()=>t.cancelAutoContinue(e),retry:!1})}const er="claude-code",Lf="No other account can take this work right now.";function zf(e){return e instanceof Error&&e.message?e.message:"Couldn’t continue on that account. Try again."}function Bf({row:e,value:t,name:n,status:s,selected:a}){const o=Ke(e);return r.jsxs("label",{"data-slot":"continue-account-row","data-eligible":e.eligible,className:H("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:[r.jsx(Vi,{value:t,disabled:!o,className:"sr-only"}),r.jsx("span",{"aria-hidden":!0,className:"inline-flex",children:r.jsx(ns,{color:e.color,name:n})}),r.jsx("span",{className:"max-w-[55%] shrink-0 truncate font-medium",children:n}),e.badge==="recommended"&&r.jsx("span",{className:H(Gi.success,"border-status-success-border text-2xs shrink-0 rounded-full border px-1.5"),children:"recommended"}),r.jsx("span",{className:"text-muted-foreground ml-auto min-w-0 pl-1 text-right text-xs",children:s})]})}function ro({open:e,onOpenChange:t,sessionId:n,account:s,cancelAutoFirst:a=!1,now:o,onCloseAutoFocus:i}){var ae;const l=jt(),u=o??new Date(l),d=c.useId(),f=s.runtime??er,{accounts:h,nameFor:m}=ts(),[,x]=_t(),g=Pf(n),S=c.useRef(!1),{mutate:b,reset:y}=g;c.useEffect(()=>{if(!e){S.current=!1,y();return}!a||S.current||(S.current=!0,b())},[e,a,b,y]);const C=e&&(!a||g.isSuccess),v=so(n,C),p=$f(n),[j,_]=c.useState(null),D=()=>{p.isPending||(_(null),p.reset(),t(!1))},T=M=>M?t(!0):D(),N=C?v.data:void 0,A=N==null?void 0:N.ranking,k=N&&!Mf(N.plan)?[...N.ranking.accounts,...N.credits?[Of(f)]:[]]:[],E=k.some(Ke),w=j??(A?Tf(A,f):null),R=k.find(M=>Kt(M,f)===w)??null,O=R!==null&&Ke(R),F=M=>Af(M,f,m),{same:$,other:B}=Df(k,f),q=Rf((N==null?void 0:N.advised)===!0,s.trackerItems.some(M=>M.via==="this-chat")),Y=s.accountId??((ae=s.limit)==null?void 0:ae.accountId)??null,se=(N==null?void 0:N.advised)===!0&&f===er&&Y!==null?Ff(h.filter(M=>M.id&&M.id!==Y&&!$.some(W=>W.id===M.id)).map(M=>m(M.path))):null,V=()=>{!R||!Ke(R)||p.mutate(nn(R,f)?{account:R.id,runtime:R.runtime}:{account:R.id},{onSuccess:M=>{D(),M.sessionId&&x(M.sessionId)}})},L=M=>{const W=Kt(M,f);return r.jsx(Bf,{row:M,value:W,name:F(M),status:Ef(M,u),selected:W===w},W)},I=g.isError?g.error:v.isError&&C?v.error:p.isError?p.error:null,P=e&&!I&&(!C||v.isPending),Q=!P&&N!==void 0;return r.jsx(Pi,{open:e,onOpenChange:T,children:r.jsxs(Li,{className:"max-h-[85vh] !min-h-0",desktopProps:{className:"sm:max-w-[380px]"},onCloseAutoFocus:i,"aria-labelledby":d,children:[r.jsxs(zi,{className:"shrink-0 text-left",children:[r.jsx(Bi,{id:d,className:"text-left",children:"Continue on another account"}),r.jsx(Ui,{className:"text-left",children:q.subtitle})]}),r.jsxs(qi,{className:"flex flex-col gap-3",children:[P&&r.jsxs("div",{className:"flex flex-col gap-1.5",children:[r.jsx(Ms,{className:"h-11 rounded-lg"}),r.jsx(Ms,{className:"h-11 rounded-lg"})]}),Q&&(E?r.jsxs(Hi,{"aria-labelledby":d,value:w??"",onValueChange:_,className:"min-w-0 grid-cols-1 gap-1.5",children:[$.map(L),B.length>0&&r.jsx("div",{className:"text-muted-foreground mt-2 text-xs font-semibold tracking-wide uppercase",children:"Other runtimes"}),B.map(L)]}):r.jsx("p",{className:"text-muted-foreground text-sm",children:Lf})),Q&&se&&r.jsx("p",{className:"text-muted-foreground text-xs",children:se}),Q&&r.jsxs("ul",{className:"text-muted-foreground list-disc pl-4 text-xs",children:[r.jsx("li",{children:q.carries}),r.jsx("li",{children:q.doesnt})]}),I!==null&&r.jsx("p",{role:"alert",className:"text-destructive text-sm",children:zf(I)})]}),r.jsxs(Wi,{className:"shrink-0",children:[r.jsx(ne,{variant:"outline",onClick:D,disabled:p.isPending,children:"Cancel"}),r.jsxs(ne,{onClick:V,disabled:!Q||!E||!O||p.isPending,"aria-busy":p.isPending||void 0,children:[p.isPending&&r.jsx(ze,{}),R&&Q&&E?`Continue on ${F(R)}`:"Continue"]})]})]})})}const Uf=1440*60*1e3,qf="Paused until you continue or the account resets",Hf="Paused until the task moves or the account resets",Wf=new Set(["limited","handing-off","wait-only","all-accounts-out","model-limited"]);function Vf(e){return Wf.has(e)?"critical":"neutral"}function ao(e){return e.carryOver===!1}function rt(e,t){return e!==null&&Date.parse(e)<=t.getTime()}function ps(e){return`${e} should have reset by now.`}function Gf(e,t,n,s){if(rt(n,s))return ps(e);const a=Ki(t,n,s);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 oo(e){return e.plan.mode==="waiting"&&e.plan.resumeAt?e.plan.resumeAt:e.resetsAt}function tr(e,t,n){if(t===null)return`Waiting for ${e}`;if(rt(t,n))return ps(e);const s=Date.parse(t)-n.getTime();return s<Uf?`Waiting for ${e} · back in ${Qi(s)}`:`Waiting for ${e} · back ${ss(t,n)}`}function Kf(e,t){return Math.max(0,Math.ceil((Date.parse(e)-t.getTime())/1e3))}const Qf=new Set(["continue-on","move-now","keep-going","resume","open-moved"]);function Yf(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(s=>s!==!1)}const Xf=new Set(["limited","handing-off","wait-only","all-accounts-out","model-limited","waiting-reset"]),vn={canSubmit:!0,placeholder:null};function Jf(e,t,n){if(!e)return vn;const s=ra(e);if(s==="moved")return{canSubmit:t,placeholder:null};if(!Xf.has(s))return vn;const a=i=>i!==null&&!rt(i,n);return a(oo(e))||e.plan.mode==="auto"&&a(e.plan.fireAt)?{canSubmit:!1,placeholder:s==="handing-off"?Hf:qf}:vn}const Zf=300*1e3;function io(e,t){const n=Date.parse(e)-Date.parse(t);return Number.isFinite(n)&&n>=0&&n<=Zf}function em(e,t){let n=null;for(const s of e)io(s.since,t)&&(n===null||Date.parse(s.since)<Date.parse(n.since))&&(n=s);return n}function qn(e,t){var n;return e?((n=t.find(s=>s.value===e))==null?void 0:n.displayName)??e:null}function tm(e,t){return{from:qn(e.modelFrom,t)??(e.scope==="model"?aa(e.window,t):null),to:qn(e.modelTo,t)}}function lo(){const{accounts:e,nameFor:t,colorFor:n}=ts(),s=Yi("claude-code",{accountId:vt,path:null});return a=>{const o=Xi({accountId:a,path:null,accounts:e,usage:a===vt?s:null,nameFor:t,colorFor:n});return{name:o.name??a,color:o.color}}}const nr=rs(e=>({episodes:new Set,choose:t=>e(n=>n.episodes.has(t)?n:{episodes:new Set([...n.episodes,t])})}));function nm(e,t){return`${e}\0${t}`}function co(e,t){const n=t===null?null:nm(e,t),s=nr(o=>n!==null&&o.episodes.has(n)),a=nr(o=>o.choose);return{continuedHere:s,continueHere:()=>{n!==null&&a(n)}}}const sr="claude-code",sm=new Set(["limited","handing-off","model-limited"]),rm=new Set(["limited","model-limited","all-accounts-out"]);function am(e){return(e==null?void 0:e.runsOn)==="own-sign-in"&&e.chosenBy==="user"}function om(e){return e instanceof Error&&e.message?e.message:"Couldn’t do that. Try again."}function im(e,t){var Y,se,V;const n=xe(),s=as(),[,a]=_t(),o=wt(e,{fetchUsage:!1}),i=t??o,l=i.limit,u=l?ra(l):null,d=i.runtime??sr,f=i.visible,h=lo(),m=d===sr&&(l!=null&&l.accountId)?h(l.accountId).name:i.name,x=Gt({runtime:d,accountLabel:m,identityGate:f}),g=os({sessionId:e||void 0,runtime:d}).data??[],S=l?ao(l.plan):!0,b=u!==null&&sm.has(u)&&!S,{isLoaded:y}=ts(),{data:C}=is(),v=y&&C!==void 0,p=u==="model-limited",j=so(e,b&&v&&(p?f:!f)),_=b&&(p?f&&(((Y=j.data)==null?void 0:Y.ranking.accounts.some(Ke))??!1):If(f,(se=j.data)==null?void 0:se.ranking,d)),{continuedHere:D,continueHere:T}=co(e,(l==null?void 0:l.since)??null),{data:N}=Ji(),A=u!==null&&rm.has(u)&&!S&&(l==null?void 0:l.accountId)!==it&&Zi(N,d)&&!am((V=N==null?void 0:N.defaults)==null?void 0:V[d]),k=(l==null?void 0:l.since)??null,E=`${k}:${u}`,[w,R]=c.useState(null),O=L=>R(L===null?null:{key:E,message:L}),F=L=>O(om(L)),$=kt({mutationFn:L=>n.waitForReset(e,L),retry:!1,onError:F}),B=kt({mutationFn:L=>n.continueSession(e,L),retry:!1,onError:F,onSuccess:L=>{L.sessionId&&L.sessionId!==e&&a(L.sessionId)}}),q=c.useRef(k);return c.useEffect(()=>{q.current!==null&&k===null&&s.invalidateQueries({queryKey:es.limitHistory(e)}),q.current=k},[k,e,s]),{account:i,limit:l,state:u,runtime:d,subject:x,identityGate:f,canPick:_,creditsOffered:A,nameOf:h,models:g,continuedHere:D,continueHere:T,wait:L=>{O(null),$.mutate(L===void 0?{}:{autoResume:L})},continueOn:L=>{O(null),B.mutate(L)},openSession:L=>a(L),pending:$.isPending||B.isPending,failure:(w==null?void 0:w.key)===E?w.message:null}}function kn({visible:e,spoken:t,spokenKey:n}){const[s,a]=c.useState({key:n,text:t});return s.key!==n&&a({key:n,text:t}),r.jsxs(r.Fragment,{children:[r.jsx("span",{"aria-hidden":!0,children:e}),r.jsx("span",{className:"sr-only",children:s.key===n?s.text:t})]})}function Cn({account:e,showDot:t}){return r.jsxs(r.Fragment,{children:[t&&e.color&&r.jsx("span",{"aria-hidden":!0,className:"mr-1 inline-flex align-middle",children:r.jsx(ns,{color:e.color,name:e.name,tooltip:!1})}),e.name]})}function lm(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 cm({sessionId:e,onSend:t,account:n,now:s}){const a=im(e,n),o=oa(),{limit:i,state:l,subject:u,identityGate:d}=a,f=jt(l==="handing-off"?1e3:6e4),h=s??new Date(f),m=i?i.since:null,[x,g]=c.useState(null),S=a.canPick&&m!==null&&x===m,b=E=>g(E?m:null),y=c.useId();if(!i||!l)return null;const C=a.creditsOffered&&o!==null,v=i.plan,p=qn(i.modelFallback,a.models),j=Yf(l,{canPick:a.canPick,hasFallback:p!==null,continuedHere:a.continuedHere}),_=`${l}:${i.since}:${u}`;let D,T=null,N=!1;switch(l){case"all-accounts-out":{D="All accounts are out.";const E=i.allOut;if(E!=null&&E.resetsAt){const w=a.nameOf(E.accountId);T=rt(E.resetsAt,h)?ps(w.name):r.jsxs(r.Fragment,{children:["Soonest back: ",r.jsx(Cn,{account:w,showDot:d}),","," ",ss(E.resetsAt,h)]})}break}case"model-limited":D=`${aa(i.window,a.models)} is out on ${u} for this week.`;break;case"waiting-reset":{const E=oo(i);D=r.jsx(kn,{visible:tr(u,E,h),spoken:tr(u,E,h),spokenKey:`${_}:${rt(E,h)}`});break}case"reset-ready":D=v.mode==="waiting"&&v.unconfirmed?`${u} should have reset by now.`:`${u} has reset.`;break;case"moved":{if(v.mode!=="continued")return null;const E=a.nameOf(v.accountId);D=r.jsxs(r.Fragment,{children:["This task continued on ",r.jsx(Cn,{account:E,showDot:d}),"."]});break}default:{const E=Gf(u,i.window,i.resetsAt,h);if(D=r.jsx(kn,{visible:E,spoken:E,spokenKey:`${_}:${rt(i.resetsAt,h)}`}),l==="handing-off"&&v.mode==="auto"){const w=a.nameOf(v.target),R=Kf(v.fireAt,h);N=R===0,T=r.jsx(kn,{visible:r.jsxs(r.Fragment,{children:["Moving this task to ",r.jsx(Cn,{account:w,showDot:d}),N?"…":` in ${R}s…`]}),spoken:N?`Moving this task to ${w.name}.`:`Moving this task to ${w.name} in ${R} seconds.`,spokenKey:`${_}:${v.fireAt}:${w.name}:${N}`})}}}const A=E=>{switch(E){case"continue-on":case"choose":b(!0);return;case"move-now":v.mode==="auto"&&a.continueOn({account:v.target});return;case"keep-going":i.modelFallback&&a.continueOn({model:i.modelFallback});return;case"resume":t(el);return;case"open-moved":v.mode==="continued"&&a.openSession(v.sessionId);return;case"continue-here":a.continueHere();return;case"wait":a.wait();return}},k=l==="waiting-reset"&&v.mode==="waiting"&&!ao(v);return r.jsxs(r.Fragment,{children:[r.jsxs(Fu,{variant:Vf(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:[r.jsxs("p",{children:[r.jsx("strong",{className:"font-semibold",children:D}),T&&r.jsxs(r.Fragment,{children:[" ",T]})]}),k&&r.jsxs("div",{className:"mt-1.5 flex items-center gap-2",children:[r.jsx("input",{id:y,type:"checkbox",className:"size-3.5",checked:v.autoResume,disabled:a.pending,onChange:E=>a.wait(E.target.checked)}),r.jsx("label",{htmlFor:y,children:"Continue automatically when it resets"})]}),C&&o&&r.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:it})})}),j.length>0&&r.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1.5",children:j.map(E=>r.jsx(ne,{size:"sm",variant:Qf.has(E)&&!C?"default":E==="continue-here"?"ghost":"outline",className:"h-auto min-h-11 max-w-full py-1 whitespace-normal md:min-h-8",disabled:a.pending||E==="move-now"&&N,onClick:()=>A(E),children:lm(E,p)},E))}),a.failure&&r.jsx("p",{role:"alert",className:"text-destructive mt-1.5",children:a.failure})]}),a.canPick&&r.jsx(ro,{open:S,onOpenChange:b,sessionId:e,account:{runtime:a.runtime,accountId:a.account.accountId,limit:i,trackerItems:a.account.trackerItems},cancelAutoFirst:l==="handing-off",now:s})]})}function um(e){const t=xe();return Ye({queryKey:es.limitHistory(e),queryFn:()=>t.getLimitHistory(e),enabled:e!=="",retry:!1})}const dm={moved:nl,"resumed-reset":gt,"resumed-model":gt,"resumed-early":gt};function fm({entry:e,now:t}){const n=jt(),s=t??new Date(n),a=lo(),o=tl(e.runtime),i=os({runtime:e.runtime}).data??[],[,l]=_t(),u=e.runtime==="claude-code"&&e.accountId?a(e.accountId).name:null,d=Gt({runtime:e.runtime,accountLabel:u,identityGate:o}),f=`at ${ss(e.resolvedAt,s)}`,h=dm[e.resolution];let m;switch(e.resolution){case"moved":{const x=e.toAccountId?a(e.toAccountId):null,g=x?r.jsxs(r.Fragment,{children:[o&&x.color&&r.jsx("span",{"aria-hidden":!0,className:"mr-0.5 inline-flex align-middle",children:r.jsx(ns,{color:x.color,name:x.name,tooltip:!1})}),x.name]}):null;m=r.jsxs(r.Fragment,{children:[d," ran out · moved",g&&r.jsxs(r.Fragment,{children:[" to ",e.toSessionId?r.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]})," ",f]});break}case"resumed-reset":m=`Resumed after reset ${f}`;break;case"resumed-model":{const{from:x,to:g}=tm(e,i);m=g?`${x??d} ran out · continued on ${g} ${f}`:`${d} ran out · continued here ${f}`;break}case"resumed-early":m=`${d} ran out · continued here ${f}`;break}return r.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:[r.jsx(h,{"aria-hidden":!0,className:"size-3 shrink-0"}),r.jsx("span",{className:"min-w-0",children:m})]})}function mm({sessionId:e,at:t,fallback:n,now:s}){const{limit:a}=wt(e,{fetchUsage:!1}),o=um(e),[i,l]=c.useState(null),u=a!==null&&(t===""||io(a.since,t));if(u&&((i==null?void 0:i.data)!==o.dataUpdatedAt||i.error!==o.errorUpdatedAt)&&l({data:o.dataUpdatedAt,error:o.errorUpdatedAt}),u||o.isPending)return null;const d=o.data&&t?em(o.data.entries,t):null;return d?r.jsx(fm,{entry:d,now:s}):a===null&&i!==null&&o.dataUpdatedAt===i.data&&o.errorUpdatedAt===i.error?null:r.jsx(r.Fragment,{children:n})}function pm(e){const{limit:t}=wt(e,{fetchUsage:!1}),{continuedHere:n}=co(e,(t==null?void 0:t.since)??null),s=jt();return Jf(t,n,new Date(s))}function hm(e){return wt(e,{fetchUsage:!1}).limit!==null}function gm({text:e,indices:t,startOffset:n=0}){const s=new Set(t.map(a=>a-n));return r.jsx(r.Fragment,{children:e.split("").map((a,o)=>s.has(o)?r.jsx("span",{className:"text-foreground font-semibold",children:a},o):r.jsx("span",{children:a},o))})}function xm({filteredFiles:e,selectedIndex:t,onSelect:n}){return c.useEffect(()=>{const s=document.getElementById(`file-item-${t}`);s&&s.scrollIntoView({block:"nearest"})},[t]),r.jsx(G.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:s=>s.preventDefault(),children:r.jsx("div",{id:"file-palette-listbox",role:"listbox",className:"max-h-72 overflow-y-auto p-1.5",children:e.length===0?r.jsx("div",{className:"text-muted-foreground px-2 py-4 text-center text-sm",children:"No files found."}):e.map((s,a)=>{const o=a===t,i=s.isDirectory?sl:Ma;return r.jsxs("div",{id:`file-item-${a}`,role:"option","aria-selected":o,"data-selected":o,tabIndex:o?0:-1,onClick:()=>n(s),onKeyDown:l=>{l.key==="Enter"&&n(s)},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:[r.jsx(i,{className:"text-muted-foreground mt-0.5 size-4 shrink-0"}),r.jsxs("div",{className:"min-w-0",children:[r.jsx("span",{className:"text-foreground truncate text-sm font-medium",children:r.jsx(gm,{text:s.filename,indices:s.indices,startOffset:s.directory.length})}),s.directory&&r.jsx("p",{className:"text-muted-foreground/70 truncate text-xs leading-normal",children:s.directory})]})]},s.path)})})})}function bm(e){const t=xe();return Ye({queryKey:["files",{cwd:e??null}],queryFn:()=>t.listFiles(e),enabled:!!e,staleTime:Ge.FILES_STALE_TIME_MS,gcTime:Ge.FILES_GC_TIME_MS})}const ym="You",vm="human",km="system",Cm="System",Sm="agent",jm="Agent",_m="chat-sender:",rr="room-author:",wm="Room member",Nm="runtime:";function Em(e){return e.messageType==="local_command_output"||e.messageType==="compaction"}function Dm(e,t){var o,i,l,u,d,f;if(Em(e)||e._chatStop)return{kind:"system",id:km,displayName:Cm};const n=e.role==="user"?(i=(o=e.chatMessages)==null?void 0:o[0])==null?void 0:i.from:void 0;if(n){const h=n.agentId??n.chatId,m=((l=t.senderAgent)==null?void 0:l.call(t,n))??Nt({id:h});return{kind:"agent",id:`${_m}${h}`,displayName:n.agentName,emoji:m.emoji,color:m.color}}const s=e.role==="user"?e.roomMessage:void 0;if(s&&!((u=s.author)!=null&&u.you))return Am(s,t);if(e.role==="user")return{kind:"human",id:vm,displayName:((d=t.humanName)==null?void 0:d.trim())||ym};if(t.agent){const{id:h,displayName:m,emoji:x,color:g,imageUrl:S}=t.agent;return{kind:"agent",id:h,displayName:m,emoji:x,color:g,imageUrl:S}}const a=(f=t.runtime)==null?void 0:f.trim();return a?{kind:"agent",id:`${Nm}${a}`,displayName:ls(a),runtime:a}:{kind:"agent",id:Sm,displayName:jm}}function Am(e,t){var a;const{author:n}=e;if(!n)return{kind:"human",id:`${rr}entry:${e.entryId}`,displayName:wm};const s=`${rr}${n.id}`;if(n.kind==="agent"){const o=n.agentId??n.id,i=((a=t.senderAgent)==null?void 0:a.call(t,{agentId:o,chatId:o}))??Nt({id:o,...n.emoji?{icon:n.emoji}:{},...n.color?{color:n.color}:{}});return{kind:"agent",id:s,displayName:n.displayName,...i}}return{kind:n.kind,id:s,displayName:n.displayName}}function uo(e){return`msg-${e}`}function Tm(e,t){const{resolveAuthor:n,now:s,lastSeenMessageId:a,unreadFromStart:o}=t,i=e.map((l,u)=>n(l,u));return Mu(e.map((l,u)=>({id:l.id,authorId:i[u].id,timestamp:l.timestamp})),{now:s,lastSeenId:a,unreadFromStart:o}).map(l=>l.kind!=="item"?l:{kind:"message",key:uo(e[l.index].id),messageIndex:l.index,message:e[l.index],grouping:l.grouping,author:i[l.index]})}function Fm(e){const t=[],n=new Set;for(const s of e){const a=s.lastIndexOf("/"),o=a>=0?s.slice(0,a+1):"",i=a>=0?s.slice(a+1):s;t.push({path:s,filename:i,directory:o,isDirectory:!1});const l=s.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 Rm(e,t){const n=[...e].reverse().find(s=>s.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 fo=Symbol("no-error-part");function Mm(e){for(let t=e.length-1;t>=0;t--){const n=e[t].parts;for(let s=n.length-1;s>=0;s--){const a=n[s];if(a.type==="error")return a.category}}return fo}function Im(e){const{messages:t,status:n,lastErrorCategory:s,queuedCount:a,draft:o}=e;if(o.trim().length>0||n==="streaming"||a>0)return null;let i=-1;for(let d=t.length-1;d>=0;d--)if(t[d].role==="user"){i=d;break}const l=i===-1?"":t[i].content.trim();if(!l)return null;const u=Mm(t.slice(i+1));return u!==fo?u==="auth_error"?l:null:n==="error"&&s==="auth_error"?l:null}const Om="dorkos:signin-resume",$m=1e4;function Pm(){const e=c.useRef(new Map),t=c.useRef(null);return c.useEffect(()=>{const n=rl(Om);t.current=n;const s=e.current,a=n.onMessage(o=>{s.set(o.sessionId,Date.now())});return()=>{a(),n.close(),t.current=null}},[]),c.useMemo(()=>({claimedElsewhere:n=>{const s=e.current.get(n);return s!==void 0&&Date.now()-s<$m},claim:n=>{var s;return(s=t.current)==null?void 0:s.postMessage({sessionId:n})}}),[])}function mo(e){switch(e){case"pending":case"running":return r.jsx(ze,{size:"xs",className:Mt({status:e})});case"complete":return r.jsx(ot,{className:H("size-(--size-icon-xs)",Mt({status:e}))});case"error":return r.jsx(Le,{className:H("size-(--size-icon-xs)",Mt({status:e}))});case"neutral":return r.jsx(al,{className:H("size-(--size-icon-xs)",Mt({status:e}))})}}function ar({type:e,toolName:t,toolInput:n,...s}){const a=e==="approval"?"Waiting for approval":"Answering questions",o=t?lt(t,n??""):null,i=o?`${a} · ${o}`:`${a}…`;return r.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",...s,children:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(ze,{className:"shrink-0"}),r.jsx("span",{className:"truncate text-xs",children:i})]})})}function Tt({expanded:e,onToggle:t,header:n,children:s,variant:a="default",dimmed:o=!1,disabled:i=!1,hideChevron:l=!1,extraContent:u,ariaLabel:d,className:f,...h}){const m=l?void 0:e;return r.jsxs("div",{className:H("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",f),...h,children:[r.jsxs("button",{onClick:()=>!i&&t(),disabled:i,className:H("focus-ring flex w-full items-center gap-2 rounded-md px-3 py-1",i&&"cursor-default"),"aria-expanded":m,"aria-label":d,children:[n,!l&&!i&&r.jsx(G.div,{animate:{rotate:e?180:0},transition:{type:"spring",stiffness:400,damping:30},className:"ml-auto",children:r.jsx(Et,{className:"text-muted-foreground size-(--size-icon-xs)"})})]}),u,r.jsx(ie,{initial:!1,children:e&&r.jsx(G.div,{variants:Ue,initial:"initial",animate:"animate",exit:"exit",transition:Be,className:"overflow-hidden",children:r.jsx("div",{className:"border-border/50 border-t px-3 pt-1 pb-3",children:s})})})]})}const Lm=[0,.2,.4];function po({className:e}){return r.jsx("div",{className:H("flex gap-1",e),"data-testid":"typing-dots","aria-hidden":"true",children:Lm.map(t=>r.jsx("span",{className:"bg-muted-foreground h-2 w-2 rounded-full",style:{animation:"typing-dot 1.4s ease-in-out infinite",animationDelay:`${t}s`}},t))})}function zm({record:e}){const t=Te(),{color:n,emoji:s}=Nt({id:e.agentId,icon:e.icon,color:e.color}),a=e.displayName.trim()||"Your agent";return r.jsxs("div",{className:"flex flex-col items-center gap-5 text-center","data-testid":"first-light",children:[r.jsx(G.div,{animate:t?void 0:{scale:[1,1.05,1],opacity:[.9,1,.9]},transition:t?void 0:{duration:3,repeat:1/0,ease:"easeInOut"},children:r.jsx(ia,{color:n,emoji:s,size:"lg"})}),r.jsxs("div",{className:"flex flex-col items-center gap-3",children:[r.jsxs("p",{className:"text-muted-foreground text-base","aria-live":"polite",children:[a," is waking up…"]}),r.jsx(po,{})]})]})}function Bm({birthRecord:e,firstLightRecord:t}){return(e==null?void 0:e.greetingFailed)===!0?r.jsxs("div",{className:"text-center","data-testid":"greeting-failed-empty",children:[r.jsxs("p",{className:"text-muted-foreground text-base",children:[e.displayName," couldn’t say hello just now"]}),r.jsx("p",{className:"text-muted-foreground/60 mt-2 text-sm",children:"Send a message to get started."})]}):t?r.jsx(zm,{record:t}):r.jsxs("div",{className:"text-center",children:[r.jsx("p",{className:"text-muted-foreground text-base",children:"Start a chat"}),r.jsx("p",{className:"text-muted-foreground/60 mt-2 text-sm",children:"Type a message below to begin."})]})}function Um(e){const t=new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}function qm({sessionId:e}){const t=Xt(e),n=Te();if(!t||t.kind==="first-message")return null;const s=Um(t.bornAt),a=Dt(t.runtime).label;return r.jsxs(G.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:[r.jsx(ol,{className:"text-primary size-3.5 shrink-0 fill-current","aria-hidden":"true"}),r.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[r.jsx("span",{className:"text-foreground font-medium",children:t.displayName}),s&&r.jsxs(r.Fragment,{children:[r.jsx(Sn,{}),r.jsxs("span",{children:["born ",s]})]}),r.jsx(Sn,{}),r.jsxs("span",{className:"min-w-0 truncate",children:["lives in ",r.jsx("code",{className:"text-2xs",children:t.path})]}),r.jsx(Sn,{}),r.jsxs("span",{className:"shrink-0",children:["runs on ",a]})]})]})}function Sn(){return r.jsx("span",{"aria-hidden":"true",className:"text-muted-foreground/50 shrink-0",children:"·"})}const Hm="another chat";function Wm(e,t){const n=t==null?void 0:t.find(s=>s.id===e);return n?il(n)?Is("autonomy"):n.label:la(e)?Is("autonomy"):ll(e)}function Vm({startedBy:e,modes:t}){var o;const n=ct();if(!e)return null;const s=((o=e.reason)==null?void 0:o.trim())||null,a=e.kind==="chat"?e.permission:null;return r.jsxs(r.Fragment,{children:[r.jsx(Gm,{startedBy:e,reason:s,navigate:n}),a&&r.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 ",Wm(a.mode,t),","," ",a.sameAsStarter?"same as":"lower than"," the chat that started it."]})]})}function Gm({startedBy:e,reason:t,navigate:n}){return r.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"?r.jsxs(r.Fragment,{children:["Started by the"," ",r.jsx("span",{className:"text-foreground font-medium",children:e.extensionName})," extension"]}):r.jsxs(r.Fragment,{children:["Started from"," ",r.jsx("button",{type:"button",onClick:()=>void n(At({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??Hm})]}),t&&r.jsxs(r.Fragment,{children:[": ",t]})]})}function Km({content:e}){const[t,n]=c.useState(!1);return r.jsxs("div",{"data-testid":"started-prompt",className:"px-4 py-1",children:[r.jsxs("button",{type:"button","aria-expanded":t,onClick:()=>n(s=>!s),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",r.jsx(cs,{"aria-hidden":"true",className:H("size-3 transition-transform duration-200",t&&"rotate-90")})]}),t&&r.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})]})}const Qm={a:ul},ho=c.createContext({isStreaming:!1});function Ym(e){const t=c.useContext(ho);return r.jsx(Ku,{...e,...t})}const Xm={renderers:[{language:Gu,component:Ym}]};function hs({content:e,isStreaming:t=!1,textEffect:n=Fd,sessionId:s,isLatestWidgetMessage:a}){const o=Md(n),i=c.useMemo(()=>({sessionId:s,isLatestMessage:a,isStreaming:t}),[s,a,t]);return r.jsx(ho.Provider,{value:i,children:r.jsx("div",{className:H("relative",t&&"streaming-cursor"),children:r.jsx(Uu,{resetKey:e,fallback:r.jsx("div",{className:"text-sm break-words whitespace-pre-wrap",children:e}),children:r.jsx(cl,{shikiTheme:["github-light","github-dark"],components:Qm,animated:o,isAnimating:t,plugins:Xm,children:e})})})})}function Hn(e){if(e)try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}}function ue(e,t){const n=e==null?void 0:e[t];return typeof n=="string"&&n.length>0?n:void 0}function Jm(e){const t=Hn(e);if(t){if(Array.isArray(t.content))for(const n of t.content){const s=typeof(n==null?void 0:n.text)=="string"?Hn(n.text):void 0;if(s)return s}return t}}function go(e){const t=dl(e.toolName);if(t!=="chat_send"&&t!=="session_start"&&t!=="chat_stop")return null;const n=Hn(e.input),s=Jm(e.result),a=Zm(e,s),o=a===void 0&&(s==null?void 0:s.status)==="approval_required",i=ue(n,"delivery");return{tool:t,...ue(n,t==="chat_stop"?"chat":"to")!==void 0?{to:ue(n,t==="chat_stop"?"chat":"to")}:{},...ue(n,t==="session_start"?"prompt":"message")!==void 0?{message:ue(n,t==="session_start"?"prompt":"message")}:{},...ue(n,"summary")!==void 0?{summary:ue(n,"summary")}:{},...i==="queue"||i==="steer"||i==="interrupt"?{delivery:i}:{},...ue(n,"reason")!==void 0?{reason:ue(n,"reason")}:{},...ue(s,"messageId")!==void 0?{messageId:ue(s,"messageId")}:{},...(ue(s,"chatId")??ue(s,"sessionId"))!==void 0?{chatId:ue(s,"chatId")??ue(s,"sessionId")}:{},...a!==void 0?{error:a}:{},...o?{waiting:o}:{},...t==="chat_stop"&&a===void 0&&(s==null?void 0:s.stopped)===!1?{notRunning:!0}:{},...ue(s,"note")!==void 0?{note:ue(s,"note")}:{}}}const $t="It could not be sent.";function Zm(e,t){var n;if((t==null?void 0:t.status)==="denied")return ue(t,"message")??$t;if((t==null?void 0:t.ok)===!1||typeof(t==null?void 0:t.error)=="string")return ue(t,"error")??ue(t,"message")??$t;if(e.status==="error")return t?ue(t,"error")??ue(t,"message")??$t:((n=e.result)==null?void 0:n.trim())||$t}function ep(e,t=60){const n=e.trim().split(new RegExp("(?<=[.!?])\\s"))[0]??"";if(n.length<=t)return n;const s=n.slice(0,t),a=s.lastIndexOf(" ");return`${(a>t/2?s.slice(0,a):s).replace(/[\s,;:.]+$/,"")}…`}function tp(e,t){if(e){for(let n=t.length-1;n>=0;n--)if(t[n].to.chatId===e)return t[n].to}}function np(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 sp(e,t){if(e&&e.trim())return e.trim();const s=((t??"").split(`
40
- `).find(a=>a.trim()!=="")??"").replace(/^#+\s*/,"").trim();return s.length>72?`${s.slice(0,71)}…`:s}function rp(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 ap(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 op(e,t){var n,s;for(const a of e){if((n=a.chatMessages)!=null&&n.some(i=>i.id===t))return a.id;const o=[...a.toolCalls??[],...(a.parts??[]).filter(i=>i.type==="tool_call")];for(const i of o)if(((s=go(i))==null?void 0:s.messageId)===t)return a.id}}function ip(e,t){if(t.length===0)return e;const n=[];let s=0;const a=o=>({id:`chat-stop-${o.id}`,role:"user",content:"",parts:[],timestamp:o.at,_chatStop:o});for(const o of e){const i=o.timestamp==="",l=i?Number.NaN:Date.parse(o.timestamp),u=d=>i||!Number.isNaN(l)&&Date.parse(d.at)<l;for(;s<t.length&&u(t[s]);)n.push(a(t[s])),s+=1;n.push(o)}for(;s<t.length;)n.push(a(t[s])),s+=1;return n}function lp({stamp:e}){const t=ap(e);return t.length===0?null:r.jsx(r.Fragment,{children:t.map(n=>r.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 xo({stamp:e}){const t=ct(),n=e.from.chatTitle??"another chat";return r.jsxs("span",{"data-testid":"chat-from-mark",className:"inline-flex min-w-0 flex-wrap items-center gap-1.5 text-xs",children:[r.jsxs("span",{className:"text-muted-foreground inline-flex min-w-0 items-center gap-1",children:[r.jsx("span",{"aria-hidden":!0,children:"·"}),r.jsx("span",{children:"from"}),r.jsx("button",{type:"button",onClick:()=>void t(At({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})]}),r.jsx(lp,{stamp:e})]})}function cp({sessionId:e,messageId:t}){const n=ct();return r.jsxs("button",{type:"button","data-testid":"chat-reply-to",onClick:()=>void n(At({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:[r.jsx(xd,{"aria-hidden":!0,className:"size-3"}),"Reply to your message"]})}function up({stamps:e,sessionId:t}){return r.jsx("div",{className:"space-y-2","data-testid":"received-chat-messages",children:e.map((n,s)=>r.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&&r.jsx(cp,{sessionId:t,messageId:n.replyToId}),s>0&&r.jsxs("div",{className:"text-muted-foreground mb-1 flex flex-wrap items-center gap-1.5 text-xs",children:[r.jsx("span",{className:"text-foreground/80 font-medium",children:n.from.agentName}),r.jsx(xo,{stamp:n})]}),r.jsx("div",{className:"msg-prose",children:r.jsx(hs,{content:n.text,isStreaming:!1,...t?{sessionId:t}:{}})})]},n.id))})}function dp({stamp:e}){const t=ct(),n=e.roomLabel??"a room";return r.jsxs("span",{"data-testid":"room-post-mark",className:"text-muted-foreground inline-flex min-w-0 items-center gap-1 text-xs",children:[r.jsx("span",{"aria-hidden":!0,children:"·"}),r.jsx("span",{children:"in"}),r.jsx("button",{type:"button","aria-label":`Open ${n}`,onClick:()=>void t({...fl.channels(),search:{id:e.roomId}}),className:"focus-ring text-foreground/80 hover:text-foreground max-w-48 truncate underline-offset-4 hover:underline",children:n})]})}const fp={muted:"text-muted-foreground",active:"text-foreground",done:"text-muted-foreground",error:"text-destructive"};function mp(e){return e.charAt(0).toUpperCase()+e.slice(1)}function pp(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 s=mp(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. ${s} is on this now.`:`${s} is working on it.`;case"delivered":return`${s} read it and finished its turn.`;case"replied":return`${s} replied.`;case"failed":return t.failureReason??"It was not delivered.";default:return"Sent."}}function hp(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 gp({part:e,sent:t,at:n,sessionId:s}){const[a,o]=c.useState(!1),i=c.useId(),l=ct(),u=go(e);if(!u)return null;const d=e.status==="pending"||e.status==="running",f=np(u,t),h=(f==null?void 0:f.to.chatId)??u.chatId??(u.tool==="chat_stop"?u.to:void 0),m=(f==null?void 0:f.to)??tp(h,t),x=(m==null?void 0:m.agentName)??"the agent",g=m==null?void 0:m.chatTitle,S=Nt({id:(m==null?void 0:m.agentId)??u.to??h??"chat"}),b=u.tool==="chat_stop"?hp(u,d):rp(f,{...u,pending:d}),y=sp((f==null?void 0:f.summary)??u.summary,(f==null?void 0:f.text)??u.message),C=n?Ln(n):f?Ln(f.sentAt):"",v=u.error??((f==null?void 0:f.status)==="failed"?f.failureReason:void 0),p=v?ep(v):u.tool==="chat_stop"?u.reason:y!==g?y:"",j=u.tool==="session_start"?vd:u.tool==="chat_stop"?ca:ml,_=u.tool==="session_start"?"Started spin-off chat":u.tool==="chat_stop"?u.error||u.notRunning?"Tried to stop":"Stopped":"To",D=u.tool==="session_start"?g??(y||"a new chat"):u.tool==="chat_stop"?g??"a chat":(m==null?void 0:m.agentName)??g??"a chat",T=()=>{h&&l(At({session:h,...f?{message:f.id}:{}}))};return r.jsxs("div",{"data-testid":"sent-chat-card","data-tool":u.tool,"data-state":b.label,className:"border-border/70 bg-background my-1.5 rounded-lg border text-sm",children:[r.jsxs("button",{type:"button",onClick:()=>o(N=>!N),"aria-expanded":a,...a?{"aria-controls":i}:{},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:[r.jsx(ia,{size:"xs",emoji:S.emoji,color:S.color}),r.jsx(j,{"aria-hidden":!0,className:"text-muted-foreground hidden size-3.5 shrink-0 sm:block"}),r.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[r.jsxs("span",{className:"text-muted-foreground",children:[_," "]}),r.jsx("span",{className:"font-medium",children:D}),u.tool==="chat_send"&&g&&(m==null?void 0:m.agentName)&&r.jsxs("span",{className:"text-muted-foreground",children:[" · ",g]}),p&&(u.tool!=="session_start"||v)&&r.jsxs("span",{"data-testid":"sent-chat-aside",className:H("text-muted-foreground",!v&&"hidden sm:inline"),children:[" ","· ",p]})]}),r.jsxs("span",{className:"flex shrink-0 items-center gap-2",children:[r.jsx("span",{className:H("text-xs",fp[b.tone]),"data-testid":"sent-chat-state",children:b.label}),C&&r.jsx("time",{className:"text-muted-foreground hidden text-xs tabular-nums sm:inline",children:C}),r.jsx(Et,{"aria-hidden":!0,className:H("text-muted-foreground size-3.5 transition-transform duration-200",a&&"rotate-180")})]})]}),a&&r.jsxs("div",{id:i,className:"border-border/60 space-y-2 border-t px-3 py-2",children:[((f==null?void 0:f.text)??u.message??u.reason)&&r.jsx("div",{className:"msg-prose",children:r.jsx(hs,{content:(f==null?void 0:f.text)??u.message??u.reason??"",isStreaming:!1,...s?{sessionId:s}:{}})}),r.jsxs("p",{className:"text-muted-foreground text-xs",children:[pp(u,f,x),u.note&&u.tool!=="chat_stop"&&f?` ${u.note}`:""]}),h&&!u.error&&!u.waiting&&r.jsx("button",{type:"button",onClick:T,className:"focus-ring text-foreground text-xs font-medium underline-offset-4 hover:underline",children:"Open chat →"})]})]})}function xp({notice:e}){const t=ct();return r.jsxs("div",{"data-testid":"chat-stop-line",className:"text-muted-foreground flex flex-wrap items-center gap-1.5 text-xs",children:[r.jsx(ca,{"aria-hidden":!0,className:"size-3.5 shrink-0"}),r.jsxs("span",{children:["Stopped by ",r.jsx("span",{className:"text-foreground/80 font-medium",children:e.by.agentName})," · ",r.jsx("button",{type:"button",onClick:()=>void t(At({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}`:""]})]})}const bp={sent:[],stops:[]},yp=new xl;function bo(e){const t=pl(),n=c.useContext(hl),s=gl(e??""),{data:a}=Ye({queryKey:["chat-activity",e,s],queryFn:()=>t.getChatActivity(e),enabled:!!e&&t!==null&&n!==void 0,placeholderData:(o,i)=>(i==null?void 0:i.queryKey[1])===e?o:void 0,staleTime:3e4},n??yp);return a??bp}function vp({celebration:e,onComplete:t}){const n=c.useRef(null),s=(e==null?void 0:e.level)==="major",a=c.useCallback(()=>{t()},[t]);return c.useEffect(()=>{if(!s)return;let o=!1;bl({kind:"burst"}).then(l=>{if(o){l();return}n.current=l});const i=setTimeout(()=>{a()},Jt.CELEBRATION_DISPLAY_MS);return()=>{var l;o=!0,(l=n.current)==null||l.call(n),n.current=null,clearTimeout(i)}},[s,a]),r.jsx(ie,{children:s&&r.jsx(G.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:Td})})}const gs=c.createContext(null);function kp({children:e,value:t}){const n=c.useMemo(()=>t,[t.sessionId,t.isStreaming,t.isLatestWidgetMessage,t.isFinalMessage,t.activeToolCallId,t.onToolRef,t.focusedOptionIndex,t.onToolDecided,t.onRetry,t.onSigninComplete,t.onChooseModel,t.inputZoneToolCallId,t.textEffect,t.runtimeLabel,t.allowsDenyReason]);return r.jsx(gs,{value:n,children:e})}function Cp(){const e=c.useContext(gs);if(!e)throw new Error("useMessageContext must be used within MessageProvider");return e}function Sp(){return c.useContext(gs)}function jp(e){if(e<1e3)return"<1s";const t=Math.floor(e/1e3);if(t<60)return`${t}s`;const n=Math.floor(t/60),s=t%60;return`${n}m ${s}s`}function _p({text:e,isStreaming:t,elapsedMs:n}){const[s,a]=c.useState(t),o=c.useRef(t),i=c.useRef(null);c.useEffect(()=>{o.current&&!t&&a(!1),o.current=t},[t]),c.useEffect(()=>{t&&s&&i.current&&(i.current.scrollTop=i.current.scrollHeight)},[e,t,s]);const l=n?`Thought for ${jp(n)}`:"Thinking…";return r.jsx(Tt,{expanded:s,onToggle:()=>a(!s),variant:"thinking",dimmed:!t,disabled:t,ariaLabel:l,"data-testid":"thinking-block","data-streaming":t?"true":void 0,header:r.jsxs(r.Fragment,{children:[r.jsx(gd,{className:H("text-muted-foreground size-(--size-icon-xs)",t&&"animate-breath")}),r.jsx("span",{className:H("text-3xs text-muted-foreground font-mono",t&&"animate-breath"),children:l})]}),children:r.jsx("div",{ref:i,className:"max-h-32 overflow-y-auto",children:r.jsx("pre",{className:"text-muted-foreground text-xs break-words whitespace-pre-wrap",children:e})})})}function wp({mode:e,memories:t,isStreaming:n}){const[s,a]=c.useState(n),o=c.useRef(n);if(c.useEffect(()=>{o.current&&!n&&a(!1),o.current=n},[n]),t.length===0)return null;const i=t.length,l=n?i<=1?"Consulting memory…":`Consulting ${i} memories…`:i===1?"Recalled 1 memory":`Recalled ${i} memories`,u=e==="synthesize"?yl:vl,d=e==="synthesize"?"sparkles":"bookopen";return r.jsx(Tt,{expanded:s,onToggle:()=>a(!s),variant:"memory",dimmed:!n,disabled:n,ariaLabel:l,"data-testid":"memory-recall-block","data-streaming":n?"true":void 0,header:r.jsxs(r.Fragment,{children:[r.jsx(u,{"aria-hidden":"true","data-testid":"memory-recall-header-icon","data-icon":d,className:H("text-muted-foreground size-(--size-icon-xs)",n&&"animate-breath")}),r.jsx("span",{className:H("text-3xs text-muted-foreground font-mono",n&&"animate-breath"),children:l})]}),children:r.jsx(Np,{memories:t})})}function Np({memories:e}){return r.jsx("ul",{className:"flex flex-col gap-1 px-3 py-2",children:e.map(t=>r.jsx(Ep,{memory:t},t.path))})}function Ep({memory:e}){const t=e.path.startsWith("<synthesis:"),n=e.scope==="team"?kl:Cl,s=e.scope==="team"?"team":"personal",{copy:a}=Sl({toastOnSettle:!0}),o=()=>{const i=t&&e.content?e.content:e.path;a(i)};if(t&&e.content){const i=e.path.replace(/^<synthesis:/,"synthesis:").replace(/>$/,"");return r.jsx("li",{children:r.jsxs("button",{type:"button",onClick:o,"aria-label":`Copy synthesized ${s} 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:[r.jsx("span",{className:"text-sm",children:e.content}),r.jsxs("span",{className:"text-3xs text-muted-foreground flex items-center gap-1 font-mono",children:[r.jsx(n,{"aria-hidden":"true",className:"size-(--size-icon-xs)"}),i]})]})})}return r.jsx("li",{children:r.jsxs("button",{type:"button",onClick:o,"aria-label":`Copy ${s} 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:[r.jsx("span",{className:"flex-1 truncate font-mono text-sm",children:Id(e.path,40)}),r.jsx(n,{"aria-hidden":"true",className:"text-muted-foreground size-(--size-icon-xs)"})]})})}function Vt(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}function yo(e){return e===void 0?"Summarized (asked by the agent)":`Summarized at ${e}% (asked by the agent)`}function Dp(e){if((e==null?void 0:e.requestedBy)==="agent")return yo(e.contextPercent);const t=["Context compacted"];return(e==null?void 0:e.preTokens)!==void 0&&t.push(`${Vt(e.preTokens)} tokens`),e!=null&&e.trigger&&t.push(e.trigger),t.join(" · ")}function Ap(e,t){return e===void 0?"Compacted context":t===void 0?`Compacted context · ${Vt(e)} tokens summarized`:`Compacted context · ${Vt(e)} → ${Vt(t)} tokens`}function Tp({trigger:e,preTokens:t,postTokens:n,failed:s,error:a,requestedBy:o,contextPercent:i}){return s?r.jsx(Ve,{"data-testid":"compact-boundary-row","data-failed":"true",icon:r.jsx(us,{"aria-hidden":"true",className:"text-status-warning-dot size-3 shrink-0"}),label:r.jsx("span",{className:"text-status-warning-fg",children:o==="agent"?"Couldn’t compact (asked by the agent)":"Couldn’t compact"}),children:a?r.jsx("p",{className:"text-muted-foreground mt-1 text-xs",children:a}):null}):o==="agent"?r.jsx(Ve,{"data-testid":"compact-boundary-row","data-requested-by":"agent",icon:r.jsx(Os,{"aria-hidden":"true",className:"text-muted-foreground size-3 shrink-0"}),label:r.jsx("span",{className:"text-muted-foreground",children:yo(i)})}):r.jsx(Ve,{"data-testid":"compact-boundary-row",icon:r.jsx(Os,{"aria-hidden":"true",className:"text-muted-foreground size-3 shrink-0"}),label:r.jsx("span",{className:"text-muted-foreground",children:Ap(t,n)}),trailing:e?r.jsx("span",{"data-testid":"compact-boundary-trigger",className:"text-3xs text-muted-foreground/70 ml-auto font-mono uppercase",children:e}):void 0})}function Fp({part:e}){const[t,n]=c.useState(!1);return t?r.jsxs("div",{"data-testid":"message-image-missing",className:H("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:[r.jsx(kd,{"aria-hidden":"true",className:"size-4 shrink-0"}),r.jsx("span",{children:e.alt?`${e.alt}, not available`:"This image is not available."})]}):r.jsx("figure",{className:"my-3","data-testid":"message-image",children:r.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:r.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 Rp({content:e}){return r.jsx(Ve,{"data-testid":"staged-context-note",icon:r.jsx(ua,{"aria-hidden":"true",className:"text-muted-foreground size-3 shrink-0"}),label:r.jsx("span",{className:"text-muted-foreground",children:"Added context for the next reply"}),children:r.jsx("p",{className:"text-muted-foreground/80 mt-1 text-xs whitespace-pre-wrap",children:e})})}function Mp(e){if(e<1e3)return"<1s";const t=Math.floor(e/1e3);if(t<60)return`${t}s`;const n=Math.floor(t/60),s=t%60;return`${n}m ${s}s`}function Ip(e){return e==="untracked"?"neutral":e==="stopped"?"complete":e}function Op(e){const t=[];return e.toolUses&&t.push(`${e.toolUses} tool ${e.toolUses===1?"call":"calls"}`),e.durationMs&&t.push(Mp(e.durationMs)),t.length>0?t.join(" · "):null}function $p({part:e}){const[t,n]=c.useState(!1),s=c.useRef(null),a=Op(e),o=e.subagentText,i=e.status==="untracked",l=!!(a||e.summary||e.lastToolName||o||i);return c.useEffect(()=>{const u=s.current;u&&(u.scrollTop=u.scrollHeight)},[o]),r.jsx(Tt,{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:r.jsxs(r.Fragment,{children:[mo(Ip(e.status)),r.jsx("span",{className:"text-3xs truncate font-mono",children:e.description}),a&&r.jsx("span",{className:"text-3xs text-muted-foreground ml-1 shrink-0",children:a})]}),children:r.jsxs("div",{className:"space-y-1.5",children:[o&&r.jsxs("div",{className:"space-y-1",children:[r.jsx("p",{className:"text-3xs text-muted-foreground/70 tracking-wide uppercase",children:"Helper output"}),r.jsx("pre",{ref:s,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"&&r.jsxs("p",{className:"text-3xs text-muted-foreground",children:["Last tool: ",r.jsx("span",{className:"font-mono",children:e.lastToolName})]}),e.summary&&r.jsx("pre",{className:"overflow-x-auto text-xs whitespace-pre-wrap",children:e.summary}),i&&r.jsx("p",{className:"text-3xs text-muted-foreground","data-testid":"subagent-untracked",children:"No longer tracked. It may still be running."})]})})}const Pp=e=>typeof e=="boolean"||e instanceof Boolean,Lp=e=>typeof e=="number"||e instanceof Number,zp=e=>typeof e=="bigint"||e instanceof BigInt,vo=e=>!!e&&e instanceof Date,Bp=e=>typeof e=="string"||e instanceof String,Up=e=>Array.isArray(e),ko=e=>typeof e=="object"&&e!==null,Co=e=>!!e&&e instanceof Object&&typeof e=="function";function Qt(e,t){return t===void 0&&(t=!1),!e||t?`"${e}"`:e}function qp(e,t,n){return n?JSON.stringify(e):t?`"${e}"`:e}function So(e){let{field:t,value:n,data:s,lastElement:a,openBracket:o,closeBracket:i,level:l,style:u,shouldExpandNode:d,clickToExpandNode:f,outerRef:h,beforeExpandChange:m}=e;const x=c.useRef(!1),[g,S]=c.useState(()=>d(l,n,t)),b=c.useRef(null);c.useEffect(()=>{x.current?S(d(l,n,t)):x.current=!0},[d]);const y=c.useId();if(s.length===0)return Hp({field:t,openBracket:o,closeBracket:i,lastElement:a,style:u});const C=g?u.collapseIcon:u.expandIcon,v=g?u.ariaLables.collapseJson:u.ariaLables.expandJson,p=l+1,j=s.length-1,_=N=>{g!==N&&(!m||m({level:l,value:n,field:t,newExpandValue:N}))&&S(N)},D=N=>{if(N.key==="ArrowRight"||N.key==="ArrowLeft")N.preventDefault(),_(N.key==="ArrowRight");else if(N.key==="ArrowUp"||N.key==="ArrowDown"){N.preventDefault();const A=N.key==="ArrowUp"?-1:1;if(!h.current)return;const k=h.current.querySelectorAll("[role=button]");let E=-1;for(let R=0;R<k.length;R++)if(k[R].tabIndex===0){E=R;break}if(E<0)return;const w=(E+A+k.length)%k.length;k[E].tabIndex=-1,k[w].tabIndex=0,k[w].focus()}},T=()=>{var N;_(!g);const A=b.current;if(!A)return;const k=(N=h.current)===null||N===void 0?void 0:N.querySelector('[role=button][tabindex="0"]');k&&(k.tabIndex=-1),A.tabIndex=0,A.focus()};return c.createElement("div",{className:u.basicChildStyle,role:"treeitem","aria-expanded":g,"aria-selected":void 0},c.createElement("span",{className:C,onClick:T,onKeyDown:D,role:"button","aria-label":v,"aria-expanded":g,"aria-controls":g?y:void 0,ref:b,tabIndex:l===0?0:-1}),(t||t==="")&&(f?c.createElement("span",{className:u.clickableLabel,onClick:T,onKeyDown:D},Qt(t,u.quotesForFieldNames),":"):c.createElement("span",{className:u.label},Qt(t,u.quotesForFieldNames),":")),c.createElement("span",{className:u.punctuation},o),g?c.createElement("ul",{id:y,role:"group",className:u.childFieldsContainer},s.map((N,A)=>c.createElement(Wn,{key:N[0]||A,field:N[0],value:N[1],style:u,lastElement:A===j,level:p,shouldExpandNode:d,clickToExpandNode:f,beforeExpandChange:m,outerRef:h}))):c.createElement("span",{className:u.collapsedContent,onClick:T,onKeyDown:D}),c.createElement("span",{className:u.punctuation},i),!a&&c.createElement("span",{className:u.punctuation},","))}function Hp(e){let{field:t,openBracket:n,closeBracket:s,lastElement:a,style:o}=e;return c.createElement("div",{className:o.basicChildStyle,role:"treeitem","aria-selected":void 0},(t||t==="")&&c.createElement("span",{className:o.label},Qt(t,o.quotesForFieldNames),":"),c.createElement("span",{className:o.punctuation},n),c.createElement("span",{className:o.punctuation},s),!a&&c.createElement("span",{className:o.punctuation},","))}function Wp(e){let{field:t,value:n,style:s,lastElement:a,shouldExpandNode:o,clickToExpandNode:i,level:l,outerRef:u,beforeExpandChange:d}=e;return So({field:t,value:n,lastElement:a||!1,level:l,openBracket:"{",closeBracket:"}",style:s,shouldExpandNode:o,clickToExpandNode:i,data:Object.keys(n).map(f=>[f,n[f]]),outerRef:u,beforeExpandChange:d})}function Vp(e){let{field:t,value:n,style:s,lastElement:a,level:o,shouldExpandNode:i,clickToExpandNode:l,outerRef:u,beforeExpandChange:d}=e;return So({field:t,value:n,lastElement:a||!1,level:o,openBracket:"[",closeBracket:"]",style:s,shouldExpandNode:i,clickToExpandNode:l,data:n.map(f=>[void 0,f]),outerRef:u,beforeExpandChange:d})}function Gp(e){let{field:t,value:n,style:s,lastElement:a}=e,o,i=s.otherValue;return n===null?(o="null",i=s.nullValue):n===void 0?(o="undefined",i=s.undefinedValue):Bp(n)?(o=qp(n,!s.noQuotesForStringValues,s.stringifyStringValues),i=s.stringValue):Pp(n)?(o=n?"true":"false",i=s.booleanValue):Lp(n)?(o=n.toString(),i=s.numberValue):zp(n)?(o=`${n.toString()}n`,i=s.numberValue):vo(n)?o=n.toISOString():Co(n)?o="function() { }":o=n.toString(),c.createElement("div",{className:s.basicChildStyle,role:"treeitem","aria-selected":void 0},(t||t==="")&&c.createElement("span",{className:s.label},Qt(t,s.quotesForFieldNames),":"),c.createElement("span",{className:i},o),!a&&c.createElement("span",{className:s.punctuation},","))}function Wn(e){const t=e.value;return Up(t)?c.createElement(Vp,Object.assign({},e)):ko(t)&&!vo(t)&&!Co(t)?c.createElement(Wp,Object.assign({},e)):c.createElement(Gp,Object.assign({},e))}var ee={"container-light":"_2IvMF _GzYRV","basic-element-style":"_2bkNM","child-fields-container":"_1BXBN","label-light":"_1MGIk","clickable-label-light":"_2YKJg _1MGIk _1MFti","punctuation-light":"_3uHL6 _3eOF8","value-null-light":"_2T6PJ","value-undefined-light":"_1Gho6","value-string-light":"_vGjyY","value-number-light":"_1bQdo","value-boolean-light":"_3zQKs","value-other-light":"_1xvuR","collapse-icon-light":"_oLqym _f10Tu _1MFti _1LId0","expand-icon-light":"_2AXVT _f10Tu _1MFti _1UmXx","collapsed-content-light":"_2KJWg _1pNG9 _1MFti","container-dark":"_11RoI _GzYRV","expand-icon-dark":"_17H2C _f10Tu _1MFti _1UmXx","collapse-icon-dark":"_3QHg2 _f10Tu _1MFti _1LId0","collapsed-content-dark":"_3fDAz _1pNG9 _1MFti","label-dark":"_2bSDX","clickable-label-dark":"_1RQEj _2bSDX _1MFti","punctuation-dark":"_gsbQL _3eOF8","value-null-dark":"_LaAZe","value-undefined-dark":"_GTKgm","value-string-dark":"_Chy1W","value-number-dark":"_2bveF","value-boolean-dark":"_2vRm-","value-other-dark":"_1prJR"};const jo={collapseJson:"collapse JSON",expandJson:"expand JSON"},jn={container:ee["container-light"],basicChildStyle:ee["basic-element-style"],childFieldsContainer:ee["child-fields-container"],label:ee["label-light"],clickableLabel:ee["clickable-label-light"],nullValue:ee["value-null-light"],undefinedValue:ee["value-undefined-light"],stringValue:ee["value-string-light"],booleanValue:ee["value-boolean-light"],numberValue:ee["value-number-light"],otherValue:ee["value-other-light"],punctuation:ee["punctuation-light"],collapseIcon:ee["collapse-icon-light"],expandIcon:ee["expand-icon-light"],collapsedContent:ee["collapsed-content-light"],noQuotesForStringValues:!1,quotesForFieldNames:!1,ariaLables:jo,stringifyStringValues:!1},Kp={container:ee["container-dark"],basicChildStyle:ee["basic-element-style"],childFieldsContainer:ee["child-fields-container"],label:ee["label-dark"],clickableLabel:ee["clickable-label-dark"],nullValue:ee["value-null-dark"],undefinedValue:ee["value-undefined-dark"],stringValue:ee["value-string-dark"],booleanValue:ee["value-boolean-dark"],numberValue:ee["value-number-dark"],otherValue:ee["value-other-dark"],punctuation:ee["punctuation-dark"],collapseIcon:ee["collapse-icon-dark"],expandIcon:ee["expand-icon-dark"],collapsedContent:ee["collapsed-content-dark"],noQuotesForStringValues:!1,quotesForFieldNames:!1,ariaLables:jo,stringifyStringValues:!1},Qp=()=>!0,Yp=e=>e<1,Xp=e=>{let{data:t,style:n=jn,shouldExpandNode:s=Qp,clickToExpandNode:a=!1,beforeExpandChange:o,compactTopLevel:i,...l}=e;const u=c.useRef(null);return c.createElement("div",Object.assign({"aria-label":"JSON view"},l,{className:n.container,ref:u,role:"tree"}),i&&ko(t)?Object.entries(t).map(d=>{let[f,h]=d;return c.createElement(Wn,{key:f,field:f,value:h,style:{...jn,...n},lastElement:!0,level:1,shouldExpandNode:s,clickToExpandNode:a,beforeExpandChange:o,outerRef:u})}):c.createElement(Wn,{value:t,style:{...jn,...n},lastElement:!0,level:0,shouldExpandNode:s,clickToExpandNode:a,outerRef:u,beforeExpandChange:o}))};var we={},_n,or;function Jp(){if(or)return _n;or=1;const e=[[{color:"0, 0, 0",class:"ansi-black"},{color:"187, 0, 0",class:"ansi-red"},{color:"0, 187, 0",class:"ansi-green"},{color:"187, 187, 0",class:"ansi-yellow"},{color:"0, 0, 187",class:"ansi-blue"},{color:"187, 0, 187",class:"ansi-magenta"},{color:"0, 187, 187",class:"ansi-cyan"},{color:"255,255,255",class:"ansi-white"}],[{color:"85, 85, 85",class:"ansi-bright-black"},{color:"255, 85, 85",class:"ansi-bright-red"},{color:"0, 255, 0",class:"ansi-bright-green"},{color:"255, 255, 85",class:"ansi-bright-yellow"},{color:"85, 85, 255",class:"ansi-bright-blue"},{color:"255, 85, 255",class:"ansi-bright-magenta"},{color:"85, 255, 255",class:"ansi-bright-cyan"},{color:"255, 255, 255",class:"ansi-bright-white"}]],t=/(https?:\/\/(?:[A-Za-z0-9#;/?:@=+$',_.!~*()[\]-]|&amp;|%[A-Fa-f0-9]{2})+)/gm;class n{static escapeForHtml(a){return new n().escapeForHtml(a)}static linkify(a){return new n().linkify(a)}static ansiToHtml(a,o){return new n().ansiToHtml(a,o)}static ansiToJson(a,o){return new n().ansiToJson(a,o)}static ansiToText(a){return new n().ansiToText(a)}constructor(){this.fg=this.bg=this.fg_truecolor=this.bg_truecolor=null,this.bright=0,this.decorations=[]}setupPalette(){this.PALETTE_COLORS=[];for(let l=0;l<2;++l)for(let u=0;u<8;++u)this.PALETTE_COLORS.push(e[l][u].color);let a=[0,95,135,175,215,255],o=(l,u,d)=>a[l]+", "+a[u]+", "+a[d];for(let l=0;l<6;++l)for(let u=0;u<6;++u)for(let d=0;d<6;++d)this.PALETTE_COLORS.push(o(l,u,d));let i=8;for(let l=0;l<24;++l,i+=10)this.PALETTE_COLORS.push(i+", "+i+", "+i)}escapeForHtml(a){return a.replace(/[&<>\"]/gm,o=>o=="&"?"&amp;":o=='"'?"&quot;":o=="<"?"&lt;":o==">"?"&gt;":"")}linkify(a){return a.replace(t,o=>`<a href="${o}">${o}</a>`)}ansiToHtml(a,o){return this.process(a,o,!0)}ansiToJson(a,o){return o=o||{},o.json=!0,o.clearLine=!1,this.process(a,o,!0)}ansiToText(a){return this.process(a,{},!1)}process(a,o,i){let l=this,u=a.split(/\033\[/),d=u.shift();o==null&&(o={}),o.clearLine=/\r/.test(a);let f=u.map(h=>this.processChunk(h,o,i));if(o&&o.json){let h=l.processChunkJson("");return h.content=d,h.clearLine=o.clearLine,f.unshift(h),o.remove_empty&&(f=f.filter(m=>!m.isEmpty())),f}else f.unshift(d);return f.join("")}processChunkJson(a,o,i){o=typeof o>"u"?{}:o;let l=o.use_classes=typeof o.use_classes<"u"&&o.use_classes,u=o.key=l?"class":"color",d={content:a,fg:null,bg:null,fg_truecolor:null,bg_truecolor:null,isInverted:!1,clearLine:o.clearLine,decoration:null,decorations:[],was_processed:!1,isEmpty:()=>!d.content},f=a.match(/^([!\x3c-\x3f]*)([\d;]*)([\x20-\x2c]*[\x40-\x7e])([\s\S]*)/m);if(!f)return d;d.content=f[4];let h=f[2].split(";");if(f[1]!==""||f[3]!=="m"||!i)return d;let m=this;for(;h.length>0;){let x=h.shift(),g=parseInt(x);if(isNaN(g)||g===0)m.fg=m.bg=null,m.decorations=[];else if(g===1)m.decorations.push("bold");else if(g===2)m.decorations.push("dim");else if(g===3)m.decorations.push("italic");else if(g===4)m.decorations.push("underline");else if(g===5)m.decorations.push("blink");else if(g===7)m.decorations.push("reverse");else if(g===8)m.decorations.push("hidden");else if(g===9)m.decorations.push("strikethrough");else if(g===21)m.removeDecoration("bold");else if(g===22)m.removeDecoration("bold"),m.removeDecoration("dim");else if(g===23)m.removeDecoration("italic");else if(g===24)m.removeDecoration("underline");else if(g===25)m.removeDecoration("blink");else if(g===27)m.removeDecoration("reverse");else if(g===28)m.removeDecoration("hidden");else if(g===29)m.removeDecoration("strikethrough");else if(g===39)m.fg=null;else if(g===49)m.bg=null;else if(g>=30&&g<38)m.fg=e[0][g%10][u];else if(g>=90&&g<98)m.fg=e[1][g%10][u];else if(g>=40&&g<48)m.bg=e[0][g%10][u];else if(g>=100&&g<108)m.bg=e[1][g%10][u];else if(g===38||g===48){let S=g===38;if(h.length>=1){let b=h.shift();if(b==="5"&&h.length>=1){let y=parseInt(h.shift());if(y>=0&&y<=255)if(!l)this.PALETTE_COLORS||m.setupPalette(),S?m.fg=this.PALETTE_COLORS[y]:m.bg=this.PALETTE_COLORS[y];else{let C=y>=16?"ansi-palette-"+y:e[y>7?1:0][y%8].class;S?m.fg=C:m.bg=C}}else if(b==="2"&&h.length>=3){let y=parseInt(h.shift()),C=parseInt(h.shift()),v=parseInt(h.shift());if(y>=0&&y<=255&&C>=0&&C<=255&&v>=0&&v<=255){let p=y+", "+C+", "+v;l?S?(m.fg="ansi-truecolor",m.fg_truecolor=p):(m.bg="ansi-truecolor",m.bg_truecolor=p):S?m.fg=p:m.bg=p}}}}}return m.fg===null&&m.bg===null&&m.decorations.length===0||(d.fg=m.fg,d.bg=m.bg,d.fg_truecolor=m.fg_truecolor,d.bg_truecolor=m.bg_truecolor,d.decorations=m.decorations,d.decoration=m.decorations.slice(-1).pop()||null,d.was_processed=!0),d}processChunk(a,o,i){o=o||{};let l=this.processChunkJson(a,o,i),u=o.use_classes;if(l.decorations=l.decorations.filter(g=>{if(g==="reverse"){l.fg||(l.fg=e[0][7][u?"class":"color"]),l.bg||(l.bg=e[0][0][u?"class":"color"]);let S=l.fg;l.fg=l.bg,l.bg=S;let b=l.fg_truecolor;return l.fg_truecolor=l.bg_truecolor,l.bg_truecolor=b,l.isInverted=!0,!1}return!0}),o.json)return l;if(l.isEmpty())return"";if(!l.was_processed)return l.content;let d=[],f=[],h=[],m={},x=g=>{let S=[],b;for(b in g)g.hasOwnProperty(b)&&S.push("data-"+b+'="'+this.escapeForHtml(g[b])+'"');return S.length>0?" "+S.join(" "):""};return l.isInverted&&(m["ansi-is-inverted"]="true"),l.fg&&(u?(d.push(l.fg+"-fg"),l.fg_truecolor!==null&&(m["ansi-truecolor-fg"]=l.fg_truecolor,l.fg_truecolor=null)):d.push("color:rgb("+l.fg+")")),l.bg&&(u?(d.push(l.bg+"-bg"),l.bg_truecolor!==null&&(m["ansi-truecolor-bg"]=l.bg_truecolor,l.bg_truecolor=null)):d.push("background-color:rgb("+l.bg+")")),l.decorations.forEach(g=>{if(u){f.push("ansi-"+g);return}g==="bold"?f.push("font-weight:bold"):g==="dim"?f.push("opacity:0.5"):g==="italic"?f.push("font-style:italic"):g==="hidden"?f.push("visibility:hidden"):g==="strikethrough"?h.push("line-through"):h.push(g)}),h.length&&f.push("text-decoration:"+h.join(" ")),u?'<span class="'+d.concat(f).join(" ")+'"'+x(m)+">"+l.content+"</span>":'<span style="'+d.concat(f).join(";")+'"'+x(m)+">"+l.content+"</span>"}removeDecoration(a){const o=this.decorations.indexOf(a);o>=0&&this.decorations.splice(o,1)}}return _n=n,_n}var pt={exports:{}},ir;function Zp(){if(ir)return pt.exports;ir=1;function e(a){if(!a)return"";if(!/\r/.test(a))return a;for(a=a.replace(/\r+\n/gm,`
39
+ `:"")+n[S];const b=Zs(g.trim());if(b){i=b;break}}}break}}return a?{title:s,actionId:a,widgetId:o,payload:i}:null}const Sf="dorkos:chat:last-seen:";function jf(){try{const e=[];for(let t=0;t<window.localStorage.length;t++){const n=window.localStorage.key(t);n!=null&&n.startsWith(Sf)&&e.push(n)}for(const t of e)window.localStorage.removeItem(t)}catch{}}function _f(e){let t=0;for(const n of e)n._streaming!==!0&&t++;return t}function wf(e){if(typeof e!="object"||e===null)return!1;const{userId:t,threadKind:n,threadId:s,lastReadSeq:a}=e;return typeof t=="string"&&typeof n=="string"&&typeof s=="string"&&typeof a=="number"&&Number.isInteger(a)}function Nf(e,t){const n=xe(),[s,a]=c.useState(()=>({sessionId:e,lastReadSeq:null,hydrated:!1}));s.sessionId!==e&&a({sessionId:e,lastReadSeq:null,hydrated:!1});const o=c.useRef(0),i=c.useRef(null),l=c.useRef(!1),u=c.useRef(!1),d=c.useRef(e),f=c.useRef(null),h=_f(t);c.useEffect(()=>{jf();let y=!1;return d.current=e,o.current=0,i.current=null,l.current=!1,u.current=!1,(async()=>{let C=null;try{C=await n.getReadCursor("session",e)}catch{}y||(C&&(o.current=C.lastReadSeq,f.current=C.userId),a({sessionId:e,lastReadSeq:(C==null?void 0:C.lastReadSeq)??null,hydrated:!0}))})(),()=>{y=!0}},[n,e]);const m=c.useCallback(async()=>{if(!l.current){l.current=!0;try{for(;;){const y=i.current;if(y===null)break;if(i.current=null,y.sessionId!==d.current)continue;if(u.current)break;const C=o.current;o.current=Math.max(C,y.seq);try{const v=await n.setReadCursor("session",y.sessionId,y.seq);f.current=v.userId??f.current}catch{o.current=C,y.sessionId===d.current&&(u.current=!0);break}}}finally{l.current=!1}}},[n]),x=c.useCallback(()=>{!s.hydrated||u.current||h<=o.current||(i.current={sessionId:e,seq:h},m())},[s.hydrated,e,h,m]);Ii("read_cursor",y=>{if(!wf(y)||y.threadKind!=="session"||y.threadId!==e)return;const C=f.current;C!==null&&y.userId!==C||y.lastReadSeq<=o.current||(o.current=y.lastReadSeq,a({sessionId:e,lastReadSeq:y.lastReadSeq,hydrated:!0}))});const g=c.useMemo(()=>t.filter(y=>y._streaming!==!0).map((y,C)=>({id:y.id,seq:C+1})),[t]),S=s.lastReadSeq,b=Ru(g,S===null?null:Math.min(S,h));return{lastSeenMessageId:b.lastSeenId,unreadFromStart:b.fromStart,markSeen:x,isHydrated:s.hydrated}}function Ke(e){return e.notAllowed!==!0&&e.usage.state!=="limited"}function Ef(e,t){if(e.id===it||!e.eligible)return e.reason;const n=Oi(e.usage,"seven_day");if(!n||n.usedPct===null)return"usage unknown";const s=Math.min(100,Math.max(0,Math.round(100-n.usedPct))),a=$i(n.resetsAt,t);return a?`${s}% left · resets ${a}`:`${s}% left`}function nn(e,t){return e.runtime!==void 0&&e.runtime!==t}function Df(e,t){const n=[],s=[];for(const a of e)(nn(a,t)?s:n).push(a);return{same:n,other:s}}function Kt(e,t){return`${e.runtime??t}:${e.id}`}function Af(e,t,n){if(nn(e,t)){const s=e.runtime;return!e.label&&e.id===vt?`${Gt({runtime:s,accountLabel:null,identityGate:!1})} (this computer's sign-in)`:Gt({runtime:s,accountLabel:e.label,identityGate:!0})}return e.label?e.label:e.id===vt&&e.usage.label?e.usage.label:e.usage.path?n(e.usage.path):e.id}function Tf(e,t){const n=e.accounts.find(a=>a.id===e.recommendedId);if(n&&Ke(n))return Kt(n,t);const s=e.accounts.find(Ke);return s?Kt(s,t):null}function Ff(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 Rf(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 Mf(e){return e.carryOver===!1}function If(e,t,n){return e?!0:(t==null?void 0:t.accounts.some(s=>nn(s,n)))??!1}function Of(e){return{id:it,runtime:e,label:Rs,color:Fs,eligible:!0,reason:"paid from your DorkOS account",usage:{runtime:"claude-code",accountId:it,path:"",label:Rs,color:Fs,subscriptionType:null,plan:null,credits:null,spend:null,windows:[],state:"unknown",limit:null,updatedAt:null}}}function so(e,t){const n=xe();return Ye({queryKey:es.continueOptions(e),queryFn:()=>n.getContinueOptions(e),enabled:t,staleTime:0,retry:!1})}function $f(e){const t=xe();return kt({mutationFn:n=>t.continueSession(e,n),retry:!1})}function Pf(e){const t=xe();return kt({mutationFn:()=>t.cancelAutoContinue(e),retry:!1})}const er="claude-code",Lf="No other account can take this work right now.";function zf(e){return e instanceof Error&&e.message?e.message:"Couldn’t continue on that account. Try again."}function Bf({row:e,value:t,name:n,status:s,selected:a}){const o=Ke(e);return r.jsxs("label",{"data-slot":"continue-account-row","data-eligible":e.eligible,className:H("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:[r.jsx(Vi,{value:t,disabled:!o,className:"sr-only"}),r.jsx("span",{"aria-hidden":!0,className:"inline-flex",children:r.jsx(ns,{color:e.color,name:n})}),r.jsx("span",{className:"max-w-[55%] shrink-0 truncate font-medium",children:n}),e.badge==="recommended"&&r.jsx("span",{className:H(Gi.success,"border-status-success-border text-2xs shrink-0 rounded-full border px-1.5"),children:"recommended"}),r.jsx("span",{className:"text-muted-foreground ml-auto min-w-0 pl-1 text-right text-xs",children:s})]})}function ro({open:e,onOpenChange:t,sessionId:n,account:s,cancelAutoFirst:a=!1,now:o,onCloseAutoFocus:i}){var ae;const l=jt(),u=o??new Date(l),d=c.useId(),f=s.runtime??er,{accounts:h,nameFor:m}=ts(),[,x]=_t(),g=Pf(n),S=c.useRef(!1),{mutate:b,reset:y}=g;c.useEffect(()=>{if(!e){S.current=!1,y();return}!a||S.current||(S.current=!0,b())},[e,a,b,y]);const C=e&&(!a||g.isSuccess),v=so(n,C),p=$f(n),[j,_]=c.useState(null),D=()=>{p.isPending||(_(null),p.reset(),t(!1))},T=M=>M?t(!0):D(),N=C?v.data:void 0,A=N==null?void 0:N.ranking,k=N&&!Mf(N.plan)?[...N.ranking.accounts,...N.credits?[Of(f)]:[]]:[],E=k.some(Ke),w=j??(A?Tf(A,f):null),R=k.find(M=>Kt(M,f)===w)??null,O=R!==null&&Ke(R),F=M=>Af(M,f,m),{same:$,other:B}=Df(k,f),U=Rf((N==null?void 0:N.advised)===!0,s.trackerItems.some(M=>M.via==="this-chat")),Y=s.accountId??((ae=s.limit)==null?void 0:ae.accountId)??null,se=(N==null?void 0:N.advised)===!0&&f===er&&Y!==null?Ff(h.filter(M=>M.id&&M.id!==Y&&!$.some(W=>W.id===M.id)).map(M=>m(M.path))):null,V=()=>{!R||!Ke(R)||p.mutate(nn(R,f)?{account:R.id,runtime:R.runtime}:{account:R.id},{onSuccess:M=>{D(),M.sessionId&&x(M.sessionId)}})},L=M=>{const W=Kt(M,f);return r.jsx(Bf,{row:M,value:W,name:F(M),status:Ef(M,u),selected:W===w},W)},I=g.isError?g.error:v.isError&&C?v.error:p.isError?p.error:null,P=e&&!I&&(!C||v.isPending),Q=!P&&N!==void 0;return r.jsx(Pi,{open:e,onOpenChange:T,children:r.jsxs(Li,{className:"max-h-[85vh] !min-h-0",desktopProps:{className:"sm:max-w-[380px]"},onCloseAutoFocus:i,"aria-labelledby":d,children:[r.jsxs(zi,{className:"shrink-0 text-left",children:[r.jsx(Bi,{id:d,className:"text-left",children:"Continue on another account"}),r.jsx(qi,{className:"text-left",children:U.subtitle})]}),r.jsxs(Ui,{className:"flex flex-col gap-3",children:[P&&r.jsxs("div",{className:"flex flex-col gap-1.5",children:[r.jsx(Ms,{className:"h-11 rounded-lg"}),r.jsx(Ms,{className:"h-11 rounded-lg"})]}),Q&&(E?r.jsxs(Hi,{"aria-labelledby":d,value:w??"",onValueChange:_,className:"min-w-0 grid-cols-1 gap-1.5",children:[$.map(L),B.length>0&&r.jsx("div",{className:"text-muted-foreground mt-2 text-xs font-semibold tracking-wide uppercase",children:"Other runtimes"}),B.map(L)]}):r.jsx("p",{className:"text-muted-foreground text-sm",children:Lf})),Q&&se&&r.jsx("p",{className:"text-muted-foreground text-xs",children:se}),Q&&r.jsxs("ul",{className:"text-muted-foreground list-disc pl-4 text-xs",children:[r.jsx("li",{children:U.carries}),r.jsx("li",{children:U.doesnt})]}),I!==null&&r.jsx("p",{role:"alert",className:"text-destructive text-sm",children:zf(I)})]}),r.jsxs(Wi,{className:"shrink-0",children:[r.jsx(ne,{variant:"outline",onClick:D,disabled:p.isPending,children:"Cancel"}),r.jsxs(ne,{onClick:V,disabled:!Q||!E||!O||p.isPending,"aria-busy":p.isPending||void 0,children:[p.isPending&&r.jsx(ze,{}),R&&Q&&E?`Continue on ${F(R)}`:"Continue"]})]})]})})}const qf=1440*60*1e3,Uf="Paused until you continue or the account resets",Hf="Paused until the task moves or the account resets",Wf=new Set(["limited","handing-off","wait-only","all-accounts-out","model-limited"]);function Vf(e){return Wf.has(e)?"critical":"neutral"}function ao(e){return e.carryOver===!1}function rt(e,t){return e!==null&&Date.parse(e)<=t.getTime()}function ps(e){return`${e} should have reset by now.`}function Gf(e,t,n,s){if(rt(n,s))return ps(e);const a=Ki(t,n,s);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 oo(e){return e.plan.mode==="waiting"&&e.plan.resumeAt?e.plan.resumeAt:e.resetsAt}function tr(e,t,n){if(t===null)return`Waiting for ${e}`;if(rt(t,n))return ps(e);const s=Date.parse(t)-n.getTime();return s<qf?`Waiting for ${e} · back in ${Qi(s)}`:`Waiting for ${e} · back ${ss(t,n)}`}function Kf(e,t){return Math.max(0,Math.ceil((Date.parse(e)-t.getTime())/1e3))}const Qf=new Set(["continue-on","move-now","keep-going","resume","open-moved"]);function Yf(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(s=>s!==!1)}const Xf=new Set(["limited","handing-off","wait-only","all-accounts-out","model-limited","waiting-reset"]),vn={canSubmit:!0,placeholder:null};function Jf(e,t,n){if(!e)return vn;const s=ra(e);if(s==="moved")return{canSubmit:t,placeholder:null};if(!Xf.has(s))return vn;const a=i=>i!==null&&!rt(i,n);return a(oo(e))||e.plan.mode==="auto"&&a(e.plan.fireAt)?{canSubmit:!1,placeholder:s==="handing-off"?Hf:Uf}:vn}const Zf=300*1e3;function io(e,t){const n=Date.parse(e)-Date.parse(t);return Number.isFinite(n)&&n>=0&&n<=Zf}function em(e,t){let n=null;for(const s of e)io(s.since,t)&&(n===null||Date.parse(s.since)<Date.parse(n.since))&&(n=s);return n}function Un(e,t){var n;return e?((n=t.find(s=>s.value===e))==null?void 0:n.displayName)??e:null}function tm(e,t){return{from:Un(e.modelFrom,t)??(e.scope==="model"?aa(e.window,t):null),to:Un(e.modelTo,t)}}function lo(){const{accounts:e,nameFor:t,colorFor:n}=ts(),s=Yi("claude-code",{accountId:vt,path:null});return a=>{const o=Xi({accountId:a,path:null,accounts:e,usage:a===vt?s:null,nameFor:t,colorFor:n});return{name:o.name??a,color:o.color}}}const nr=rs(e=>({episodes:new Set,choose:t=>e(n=>n.episodes.has(t)?n:{episodes:new Set([...n.episodes,t])})}));function nm(e,t){return`${e}\0${t}`}function co(e,t){const n=t===null?null:nm(e,t),s=nr(o=>n!==null&&o.episodes.has(n)),a=nr(o=>o.choose);return{continuedHere:s,continueHere:()=>{n!==null&&a(n)}}}const sr="claude-code",sm=new Set(["limited","handing-off","model-limited"]),rm=new Set(["limited","model-limited","all-accounts-out"]);function am(e){return(e==null?void 0:e.runsOn)==="own-sign-in"&&e.chosenBy==="user"}function om(e){return e instanceof Error&&e.message?e.message:"Couldn’t do that. Try again."}function im(e,t){var Y,se,V;const n=xe(),s=as(),[,a]=_t(),o=wt(e,{fetchUsage:!1}),i=t??o,l=i.limit,u=l?ra(l):null,d=i.runtime??sr,f=i.visible,h=lo(),m=d===sr&&(l!=null&&l.accountId)?h(l.accountId).name:i.name,x=Gt({runtime:d,accountLabel:m,identityGate:f}),g=os({sessionId:e||void 0,runtime:d}).data??[],S=l?ao(l.plan):!0,b=u!==null&&sm.has(u)&&!S,{isLoaded:y}=ts(),{data:C}=is(),v=y&&C!==void 0,p=u==="model-limited",j=so(e,b&&v&&(p?f:!f)),_=b&&(p?f&&(((Y=j.data)==null?void 0:Y.ranking.accounts.some(Ke))??!1):If(f,(se=j.data)==null?void 0:se.ranking,d)),{continuedHere:D,continueHere:T}=co(e,(l==null?void 0:l.since)??null),{data:N}=Ji(),A=u!==null&&rm.has(u)&&!S&&(l==null?void 0:l.accountId)!==it&&Zi(N,d)&&!am((V=N==null?void 0:N.defaults)==null?void 0:V[d]),k=(l==null?void 0:l.since)??null,E=`${k}:${u}`,[w,R]=c.useState(null),O=L=>R(L===null?null:{key:E,message:L}),F=L=>O(om(L)),$=kt({mutationFn:L=>n.waitForReset(e,L),retry:!1,onError:F}),B=kt({mutationFn:L=>n.continueSession(e,L),retry:!1,onError:F,onSuccess:L=>{L.sessionId&&L.sessionId!==e&&a(L.sessionId)}}),U=c.useRef(k);return c.useEffect(()=>{U.current!==null&&k===null&&s.invalidateQueries({queryKey:es.limitHistory(e)}),U.current=k},[k,e,s]),{account:i,limit:l,state:u,runtime:d,subject:x,identityGate:f,canPick:_,creditsOffered:A,nameOf:h,models:g,continuedHere:D,continueHere:T,wait:L=>{O(null),$.mutate(L===void 0?{}:{autoResume:L})},continueOn:L=>{O(null),B.mutate(L)},openSession:L=>a(L),pending:$.isPending||B.isPending,failure:(w==null?void 0:w.key)===E?w.message:null}}function kn({visible:e,spoken:t,spokenKey:n}){const[s,a]=c.useState({key:n,text:t});return s.key!==n&&a({key:n,text:t}),r.jsxs(r.Fragment,{children:[r.jsx("span",{"aria-hidden":!0,children:e}),r.jsx("span",{className:"sr-only",children:s.key===n?s.text:t})]})}function Cn({account:e,showDot:t}){return r.jsxs(r.Fragment,{children:[t&&e.color&&r.jsx("span",{"aria-hidden":!0,className:"mr-1 inline-flex align-middle",children:r.jsx(ns,{color:e.color,name:e.name,tooltip:!1})}),e.name]})}function lm(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 cm({sessionId:e,onSend:t,account:n,now:s}){const a=im(e,n),o=oa(),{limit:i,state:l,subject:u,identityGate:d}=a,f=jt(l==="handing-off"?1e3:6e4),h=s??new Date(f),m=i?i.since:null,[x,g]=c.useState(null),S=a.canPick&&m!==null&&x===m,b=E=>g(E?m:null),y=c.useId();if(!i||!l)return null;const C=a.creditsOffered&&o!==null,v=i.plan,p=Un(i.modelFallback,a.models),j=Yf(l,{canPick:a.canPick,hasFallback:p!==null,continuedHere:a.continuedHere}),_=`${l}:${i.since}:${u}`;let D,T=null,N=!1;switch(l){case"all-accounts-out":{D="All accounts are out.";const E=i.allOut;if(E!=null&&E.resetsAt){const w=a.nameOf(E.accountId);T=rt(E.resetsAt,h)?ps(w.name):r.jsxs(r.Fragment,{children:["Soonest back: ",r.jsx(Cn,{account:w,showDot:d}),","," ",ss(E.resetsAt,h)]})}break}case"model-limited":D=`${aa(i.window,a.models)} is out on ${u} for this week.`;break;case"waiting-reset":{const E=oo(i);D=r.jsx(kn,{visible:tr(u,E,h),spoken:tr(u,E,h),spokenKey:`${_}:${rt(E,h)}`});break}case"reset-ready":D=v.mode==="waiting"&&v.unconfirmed?`${u} should have reset by now.`:`${u} has reset.`;break;case"moved":{if(v.mode!=="continued")return null;const E=a.nameOf(v.accountId);D=r.jsxs(r.Fragment,{children:["This task continued on ",r.jsx(Cn,{account:E,showDot:d}),"."]});break}default:{const E=Gf(u,i.window,i.resetsAt,h);if(D=r.jsx(kn,{visible:E,spoken:E,spokenKey:`${_}:${rt(i.resetsAt,h)}`}),l==="handing-off"&&v.mode==="auto"){const w=a.nameOf(v.target),R=Kf(v.fireAt,h);N=R===0,T=r.jsx(kn,{visible:r.jsxs(r.Fragment,{children:["Moving this task to ",r.jsx(Cn,{account:w,showDot:d}),N?"…":` in ${R}s…`]}),spoken:N?`Moving this task to ${w.name}.`:`Moving this task to ${w.name} in ${R} seconds.`,spokenKey:`${_}:${v.fireAt}:${w.name}:${N}`})}}}const A=E=>{switch(E){case"continue-on":case"choose":b(!0);return;case"move-now":v.mode==="auto"&&a.continueOn({account:v.target});return;case"keep-going":i.modelFallback&&a.continueOn({model:i.modelFallback});return;case"resume":t(el);return;case"open-moved":v.mode==="continued"&&a.openSession(v.sessionId);return;case"continue-here":a.continueHere();return;case"wait":a.wait();return}},k=l==="waiting-reset"&&v.mode==="waiting"&&!ao(v);return r.jsxs(r.Fragment,{children:[r.jsxs(Fu,{variant:Vf(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:[r.jsxs("p",{children:[r.jsx("strong",{className:"font-semibold",children:D}),T&&r.jsxs(r.Fragment,{children:[" ",T]})]}),k&&r.jsxs("div",{className:"mt-1.5 flex items-center gap-2",children:[r.jsx("input",{id:y,type:"checkbox",className:"size-3.5",checked:v.autoResume,disabled:a.pending,onChange:E=>a.wait(E.target.checked)}),r.jsx("label",{htmlFor:y,children:"Continue automatically when it resets"})]}),C&&o&&r.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:it})})}),j.length>0&&r.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1.5",children:j.map(E=>r.jsx(ne,{size:"sm",variant:Qf.has(E)&&!C?"default":E==="continue-here"?"ghost":"outline",className:"h-auto min-h-11 max-w-full py-1 whitespace-normal md:min-h-8",disabled:a.pending||E==="move-now"&&N,onClick:()=>A(E),children:lm(E,p)},E))}),a.failure&&r.jsx("p",{role:"alert",className:"text-destructive mt-1.5",children:a.failure})]}),a.canPick&&r.jsx(ro,{open:S,onOpenChange:b,sessionId:e,account:{runtime:a.runtime,accountId:a.account.accountId,limit:i,trackerItems:a.account.trackerItems},cancelAutoFirst:l==="handing-off",now:s})]})}function um(e){const t=xe();return Ye({queryKey:es.limitHistory(e),queryFn:()=>t.getLimitHistory(e),enabled:e!=="",retry:!1})}const dm={moved:nl,"resumed-reset":gt,"resumed-model":gt,"resumed-early":gt};function fm({entry:e,now:t}){const n=jt(),s=t??new Date(n),a=lo(),o=tl(e.runtime),i=os({runtime:e.runtime}).data??[],[,l]=_t(),u=e.runtime==="claude-code"&&e.accountId?a(e.accountId).name:null,d=Gt({runtime:e.runtime,accountLabel:u,identityGate:o}),f=`at ${ss(e.resolvedAt,s)}`,h=dm[e.resolution];let m;switch(e.resolution){case"moved":{const x=e.toAccountId?a(e.toAccountId):null,g=x?r.jsxs(r.Fragment,{children:[o&&x.color&&r.jsx("span",{"aria-hidden":!0,className:"mr-0.5 inline-flex align-middle",children:r.jsx(ns,{color:x.color,name:x.name,tooltip:!1})}),x.name]}):null;m=r.jsxs(r.Fragment,{children:[d," ran out · moved",g&&r.jsxs(r.Fragment,{children:[" to ",e.toSessionId?r.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]})," ",f]});break}case"resumed-reset":m=`Resumed after reset ${f}`;break;case"resumed-model":{const{from:x,to:g}=tm(e,i);m=g?`${x??d} ran out · continued on ${g} ${f}`:`${d} ran out · continued here ${f}`;break}case"resumed-early":m=`${d} ran out · continued here ${f}`;break}return r.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:[r.jsx(h,{"aria-hidden":!0,className:"size-3 shrink-0"}),r.jsx("span",{className:"min-w-0",children:m})]})}function mm({sessionId:e,at:t,fallback:n,now:s}){const{limit:a}=wt(e,{fetchUsage:!1}),o=um(e),[i,l]=c.useState(null),u=a!==null&&(t===""||io(a.since,t));if(u&&((i==null?void 0:i.data)!==o.dataUpdatedAt||i.error!==o.errorUpdatedAt)&&l({data:o.dataUpdatedAt,error:o.errorUpdatedAt}),u||o.isPending)return null;const d=o.data&&t?em(o.data.entries,t):null;return d?r.jsx(fm,{entry:d,now:s}):a===null&&i!==null&&o.dataUpdatedAt===i.data&&o.errorUpdatedAt===i.error?null:r.jsx(r.Fragment,{children:n})}function pm(e){const{limit:t}=wt(e,{fetchUsage:!1}),{continuedHere:n}=co(e,(t==null?void 0:t.since)??null),s=jt();return Jf(t,n,new Date(s))}function hm(e){return wt(e,{fetchUsage:!1}).limit!==null}function gm({text:e,indices:t,startOffset:n=0}){const s=new Set(t.map(a=>a-n));return r.jsx(r.Fragment,{children:e.split("").map((a,o)=>s.has(o)?r.jsx("span",{className:"text-foreground font-semibold",children:a},o):r.jsx("span",{children:a},o))})}function xm({filteredFiles:e,selectedIndex:t,onSelect:n}){return c.useEffect(()=>{const s=document.getElementById(`file-item-${t}`);s&&s.scrollIntoView({block:"nearest"})},[t]),r.jsx(G.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:s=>s.preventDefault(),children:r.jsx("div",{id:"file-palette-listbox",role:"listbox",className:"max-h-72 overflow-y-auto p-1.5",children:e.length===0?r.jsx("div",{className:"text-muted-foreground px-2 py-4 text-center text-sm",children:"No files found."}):e.map((s,a)=>{const o=a===t,i=s.isDirectory?sl:Ma;return r.jsxs("div",{id:`file-item-${a}`,role:"option","aria-selected":o,"data-selected":o,tabIndex:o?0:-1,onClick:()=>n(s),onKeyDown:l=>{l.key==="Enter"&&n(s)},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:[r.jsx(i,{className:"text-muted-foreground mt-0.5 size-4 shrink-0"}),r.jsxs("div",{className:"min-w-0",children:[r.jsx("span",{className:"text-foreground truncate text-sm font-medium",children:r.jsx(gm,{text:s.filename,indices:s.indices,startOffset:s.directory.length})}),s.directory&&r.jsx("p",{className:"text-muted-foreground/70 truncate text-xs leading-normal",children:s.directory})]})]},s.path)})})})}function bm(e){const t=xe();return Ye({queryKey:["files",{cwd:e??null}],queryFn:()=>t.listFiles(e),enabled:!!e,staleTime:Ge.FILES_STALE_TIME_MS,gcTime:Ge.FILES_GC_TIME_MS})}const ym="You",vm="human",km="system",Cm="System",Sm="agent",jm="Agent",_m="chat-sender:",rr="room-author:",wm="Room member",Nm="runtime:";function Em(e){return e.messageType==="local_command_output"||e.messageType==="compaction"}function Dm(e,t){var o,i,l,u,d,f;if(Em(e)||e._chatStop)return{kind:"system",id:km,displayName:Cm};const n=e.role==="user"?(i=(o=e.chatMessages)==null?void 0:o[0])==null?void 0:i.from:void 0;if(n){const h=n.agentId??n.chatId,m=((l=t.senderAgent)==null?void 0:l.call(t,n))??Nt({id:h});return{kind:"agent",id:`${_m}${h}`,displayName:n.agentName,emoji:m.emoji,color:m.color}}const s=e.role==="user"?e.roomMessage:void 0;if(s&&!((u=s.author)!=null&&u.you))return Am(s,t);if(e.role==="user")return{kind:"human",id:vm,displayName:((d=t.humanName)==null?void 0:d.trim())||ym};if(t.agent){const{id:h,displayName:m,emoji:x,color:g,imageUrl:S}=t.agent;return{kind:"agent",id:h,displayName:m,emoji:x,color:g,imageUrl:S}}const a=(f=t.runtime)==null?void 0:f.trim();return a?{kind:"agent",id:`${Nm}${a}`,displayName:ls(a),runtime:a}:{kind:"agent",id:Sm,displayName:jm}}function Am(e,t){var a;const{author:n}=e;if(!n)return{kind:"human",id:`${rr}entry:${e.entryId}`,displayName:wm};const s=`${rr}${n.id}`;if(n.kind==="agent"){const o=n.agentId??n.id,i=((a=t.senderAgent)==null?void 0:a.call(t,{agentId:o,chatId:o}))??Nt({id:o,...n.emoji?{icon:n.emoji}:{},...n.color?{color:n.color}:{}});return{kind:"agent",id:s,displayName:n.displayName,...i}}return{kind:n.kind,id:s,displayName:n.displayName}}function uo(e){return`msg-${e}`}function Tm(e,t){const{resolveAuthor:n,now:s,lastSeenMessageId:a,unreadFromStart:o}=t,i=e.map((l,u)=>n(l,u));return Mu(e.map((l,u)=>({id:l.id,authorId:i[u].id,timestamp:l.timestamp})),{now:s,lastSeenId:a,unreadFromStart:o}).map(l=>l.kind!=="item"?l:{kind:"message",key:uo(e[l.index].id),messageIndex:l.index,message:e[l.index],grouping:l.grouping,author:i[l.index]})}function Fm(e){const t=[],n=new Set;for(const s of e){const a=s.lastIndexOf("/"),o=a>=0?s.slice(0,a+1):"",i=a>=0?s.slice(a+1):s;t.push({path:s,filename:i,directory:o,isDirectory:!1});const l=s.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 Rm(e,t){const n=[...e].reverse().find(s=>s.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 fo=Symbol("no-error-part");function Mm(e){for(let t=e.length-1;t>=0;t--){const n=e[t].parts;for(let s=n.length-1;s>=0;s--){const a=n[s];if(a.type==="error")return a.category}}return fo}function Im(e){const{messages:t,status:n,lastErrorCategory:s,queuedCount:a,draft:o}=e;if(o.trim().length>0||n==="streaming"||a>0)return null;let i=-1;for(let d=t.length-1;d>=0;d--)if(t[d].role==="user"){i=d;break}const l=i===-1?"":t[i].content.trim();if(!l)return null;const u=Mm(t.slice(i+1));return u!==fo?u==="auth_error"?l:null:n==="error"&&s==="auth_error"?l:null}const Om="dorkos:signin-resume",$m=1e4;function Pm(){const e=c.useRef(new Map),t=c.useRef(null);return c.useEffect(()=>{const n=rl(Om);t.current=n;const s=e.current,a=n.onMessage(o=>{s.set(o.sessionId,Date.now())});return()=>{a(),n.close(),t.current=null}},[]),c.useMemo(()=>({claimedElsewhere:n=>{const s=e.current.get(n);return s!==void 0&&Date.now()-s<$m},claim:n=>{var s;return(s=t.current)==null?void 0:s.postMessage({sessionId:n})}}),[])}function mo(e){switch(e){case"pending":case"running":return r.jsx(ze,{size:"xs",className:Mt({status:e})});case"complete":return r.jsx(ot,{className:H("size-(--size-icon-xs)",Mt({status:e}))});case"error":return r.jsx(Le,{className:H("size-(--size-icon-xs)",Mt({status:e}))});case"neutral":return r.jsx(al,{className:H("size-(--size-icon-xs)",Mt({status:e}))})}}function ar({type:e,toolName:t,toolInput:n,...s}){const a=e==="approval"?"Waiting for approval":"Answering questions",o=t?lt(t,n??""):null,i=o?`${a} · ${o}`:`${a}…`;return r.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",...s,children:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(ze,{className:"shrink-0"}),r.jsx("span",{className:"truncate text-xs",children:i})]})})}function Tt({expanded:e,onToggle:t,header:n,children:s,variant:a="default",dimmed:o=!1,disabled:i=!1,hideChevron:l=!1,extraContent:u,ariaLabel:d,className:f,...h}){const m=l?void 0:e;return r.jsxs("div",{className:H("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",f),...h,children:[r.jsxs("button",{onClick:()=>!i&&t(),disabled:i,className:H("focus-ring flex w-full items-center gap-2 rounded-md px-3 py-1",i&&"cursor-default"),"aria-expanded":m,"aria-label":d,children:[n,!l&&!i&&r.jsx(G.div,{animate:{rotate:e?180:0},transition:{type:"spring",stiffness:400,damping:30},className:"ml-auto",children:r.jsx(Et,{className:"text-muted-foreground size-(--size-icon-xs)"})})]}),u,r.jsx(ie,{initial:!1,children:e&&r.jsx(G.div,{variants:qe,initial:"initial",animate:"animate",exit:"exit",transition:Be,className:"overflow-hidden",children:r.jsx("div",{className:"border-border/50 border-t px-3 pt-1 pb-3",children:s})})})]})}const Lm=[0,.2,.4];function po({className:e}){return r.jsx("div",{className:H("flex gap-1",e),"data-testid":"typing-dots","aria-hidden":"true",children:Lm.map(t=>r.jsx("span",{className:"bg-muted-foreground h-2 w-2 rounded-full",style:{animation:"typing-dot 1.4s ease-in-out infinite",animationDelay:`${t}s`}},t))})}function zm({record:e}){const t=Te(),{color:n,emoji:s}=Nt({id:e.agentId,icon:e.icon,color:e.color}),a=e.displayName.trim()||"Your agent";return r.jsxs("div",{className:"flex flex-col items-center gap-5 text-center","data-testid":"first-light",children:[r.jsx(G.div,{animate:t?void 0:{scale:[1,1.05,1],opacity:[.9,1,.9]},transition:t?void 0:{duration:3,repeat:1/0,ease:"easeInOut"},children:r.jsx(ia,{color:n,emoji:s,size:"lg"})}),r.jsxs("div",{className:"flex flex-col items-center gap-3",children:[r.jsxs("p",{className:"text-muted-foreground text-base","aria-live":"polite",children:[a," is waking up…"]}),r.jsx(po,{})]})]})}function Bm({birthRecord:e,firstLightRecord:t}){return(e==null?void 0:e.greetingFailed)===!0?r.jsxs("div",{className:"text-center","data-testid":"greeting-failed-empty",children:[r.jsxs("p",{className:"text-muted-foreground text-base",children:[e.displayName," couldn’t say hello just now"]}),r.jsx("p",{className:"text-muted-foreground/60 mt-2 text-sm",children:"Send a message to get started."})]}):t?r.jsx(zm,{record:t}):r.jsxs("div",{className:"text-center",children:[r.jsx("p",{className:"text-muted-foreground text-base",children:"Start a chat"}),r.jsx("p",{className:"text-muted-foreground/60 mt-2 text-sm",children:"Type a message below to begin."})]})}function qm(e){const t=new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Um({sessionId:e}){const t=Xt(e),n=Te();if(!t||t.kind==="first-message")return null;const s=qm(t.bornAt),a=Dt(t.runtime).label;return r.jsxs(G.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:[r.jsx(ol,{className:"text-primary size-3.5 shrink-0 fill-current","aria-hidden":"true"}),r.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[r.jsx("span",{className:"text-foreground font-medium",children:t.displayName}),s&&r.jsxs(r.Fragment,{children:[r.jsx(Sn,{}),r.jsxs("span",{children:["born ",s]})]}),r.jsx(Sn,{}),r.jsxs("span",{className:"min-w-0 truncate",children:["lives in ",r.jsx("code",{className:"text-2xs",children:t.path})]}),r.jsx(Sn,{}),r.jsxs("span",{className:"shrink-0",children:["runs on ",a]})]})]})}function Sn(){return r.jsx("span",{"aria-hidden":"true",className:"text-muted-foreground/50 shrink-0",children:"·"})}const Hm="another chat";function Wm(e,t){const n=t==null?void 0:t.find(s=>s.id===e);return n?il(n)?Is("autonomy"):n.label:la(e)?Is("autonomy"):ll(e)}function Vm({startedBy:e,modes:t}){var o;const n=ct();if(!e)return null;const s=((o=e.reason)==null?void 0:o.trim())||null,a=e.kind==="chat"?e.permission:null;return r.jsxs(r.Fragment,{children:[r.jsx(Gm,{startedBy:e,reason:s,navigate:n}),a&&r.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 ",Wm(a.mode,t),","," ",a.sameAsStarter?"same as":"lower than"," the chat that started it."]})]})}function Gm({startedBy:e,reason:t,navigate:n}){return r.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"?r.jsxs(r.Fragment,{children:["Started by the"," ",r.jsx("span",{className:"text-foreground font-medium",children:e.extensionName})," extension"]}):r.jsxs(r.Fragment,{children:["Started from"," ",r.jsx("button",{type:"button",onClick:()=>void n(At({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??Hm})]}),t&&r.jsxs(r.Fragment,{children:[": ",t]})]})}function Km({content:e}){const[t,n]=c.useState(!1);return r.jsxs("div",{"data-testid":"started-prompt",className:"px-4 py-1",children:[r.jsxs("button",{type:"button","aria-expanded":t,onClick:()=>n(s=>!s),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",r.jsx(cs,{"aria-hidden":"true",className:H("size-3 transition-transform duration-200",t&&"rotate-90")})]}),t&&r.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})]})}const Qm={a:ul},ho=c.createContext({isStreaming:!1});function Ym(e){const t=c.useContext(ho);return r.jsx(Gu,{...e,...t})}const Xm={renderers:[{language:Vu,component:Ym}]};function hs({content:e,isStreaming:t=!1,textEffect:n=Fd,sessionId:s,isLatestWidgetMessage:a}){const o=Md(n),i=c.useMemo(()=>({sessionId:s,isLatestMessage:a,isStreaming:t}),[s,a,t]);return r.jsx(ho.Provider,{value:i,children:r.jsx("div",{className:H("relative",t&&"streaming-cursor"),children:r.jsx(qu,{resetKey:e,fallback:r.jsx("div",{className:"text-sm break-words whitespace-pre-wrap",children:e}),children:r.jsx(cl,{shikiTheme:["github-light","github-dark"],components:Qm,animated:o,isAnimating:t,plugins:Xm,children:e})})})})}function Hn(e){if(e)try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}}function ue(e,t){const n=e==null?void 0:e[t];return typeof n=="string"&&n.length>0?n:void 0}function Jm(e){const t=Hn(e);if(t){if(Array.isArray(t.content))for(const n of t.content){const s=typeof(n==null?void 0:n.text)=="string"?Hn(n.text):void 0;if(s)return s}return t}}function go(e){const t=dl(e.toolName);if(t!=="chat_send"&&t!=="session_start"&&t!=="chat_stop")return null;const n=Hn(e.input),s=Jm(e.result),a=Zm(e,s),o=a===void 0&&(s==null?void 0:s.status)==="approval_required",i=ue(n,"delivery");return{tool:t,...ue(n,t==="chat_stop"?"chat":"to")!==void 0?{to:ue(n,t==="chat_stop"?"chat":"to")}:{},...ue(n,t==="session_start"?"prompt":"message")!==void 0?{message:ue(n,t==="session_start"?"prompt":"message")}:{},...ue(n,"summary")!==void 0?{summary:ue(n,"summary")}:{},...i==="queue"||i==="steer"||i==="interrupt"?{delivery:i}:{},...ue(n,"reason")!==void 0?{reason:ue(n,"reason")}:{},...ue(s,"messageId")!==void 0?{messageId:ue(s,"messageId")}:{},...(ue(s,"chatId")??ue(s,"sessionId"))!==void 0?{chatId:ue(s,"chatId")??ue(s,"sessionId")}:{},...a!==void 0?{error:a}:{},...o?{waiting:o}:{},...t==="chat_stop"&&a===void 0&&(s==null?void 0:s.stopped)===!1?{notRunning:!0}:{},...ue(s,"note")!==void 0?{note:ue(s,"note")}:{}}}const $t="It could not be sent.";function Zm(e,t){var n;if((t==null?void 0:t.status)==="denied")return ue(t,"message")??$t;if((t==null?void 0:t.ok)===!1||typeof(t==null?void 0:t.error)=="string")return ue(t,"error")??ue(t,"message")??$t;if(e.status==="error")return t?ue(t,"error")??ue(t,"message")??$t:((n=e.result)==null?void 0:n.trim())||$t}function ep(e,t=60){const n=e.trim().split(new RegExp("(?<=[.!?])\\s"))[0]??"";if(n.length<=t)return n;const s=n.slice(0,t),a=s.lastIndexOf(" ");return`${(a>t/2?s.slice(0,a):s).replace(/[\s,;:.]+$/,"")}…`}function tp(e,t){if(e){for(let n=t.length-1;n>=0;n--)if(t[n].to.chatId===e)return t[n].to}}function np(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 sp(e,t){if(e&&e.trim())return e.trim();const s=((t??"").split(`
40
+ `).find(a=>a.trim()!=="")??"").replace(/^#+\s*/,"").trim();return s.length>72?`${s.slice(0,71)}…`:s}function rp(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 ap(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 op(e,t){var n,s;for(const a of e){if((n=a.chatMessages)!=null&&n.some(i=>i.id===t))return a.id;const o=[...a.toolCalls??[],...(a.parts??[]).filter(i=>i.type==="tool_call")];for(const i of o)if(((s=go(i))==null?void 0:s.messageId)===t)return a.id}}function ip(e,t){if(t.length===0)return e;const n=[];let s=0;const a=o=>({id:`chat-stop-${o.id}`,role:"user",content:"",parts:[],timestamp:o.at,_chatStop:o});for(const o of e){const i=o.timestamp==="",l=i?Number.NaN:Date.parse(o.timestamp),u=d=>i||!Number.isNaN(l)&&Date.parse(d.at)<l;for(;s<t.length&&u(t[s]);)n.push(a(t[s])),s+=1;n.push(o)}for(;s<t.length;)n.push(a(t[s])),s+=1;return n}function lp({stamp:e}){const t=ap(e);return t.length===0?null:r.jsx(r.Fragment,{children:t.map(n=>r.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 xo({stamp:e}){const t=ct(),n=e.from.chatTitle??"another chat";return r.jsxs("span",{"data-testid":"chat-from-mark",className:"inline-flex min-w-0 flex-wrap items-center gap-1.5 text-xs",children:[r.jsxs("span",{className:"text-muted-foreground inline-flex min-w-0 items-center gap-1",children:[r.jsx("span",{"aria-hidden":!0,children:"·"}),r.jsx("span",{children:"from"}),r.jsx("button",{type:"button",onClick:()=>void t(At({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})]}),r.jsx(lp,{stamp:e})]})}function cp({sessionId:e,messageId:t}){const n=ct();return r.jsxs("button",{type:"button","data-testid":"chat-reply-to",onClick:()=>void n(At({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:[r.jsx(xd,{"aria-hidden":!0,className:"size-3"}),"Reply to your message"]})}function up({stamps:e,sessionId:t}){return r.jsx("div",{className:"space-y-2","data-testid":"received-chat-messages",children:e.map((n,s)=>r.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&&r.jsx(cp,{sessionId:t,messageId:n.replyToId}),s>0&&r.jsxs("div",{className:"text-muted-foreground mb-1 flex flex-wrap items-center gap-1.5 text-xs",children:[r.jsx("span",{className:"text-foreground/80 font-medium",children:n.from.agentName}),r.jsx(xo,{stamp:n})]}),r.jsx("div",{className:"msg-prose",children:r.jsx(hs,{content:n.text,isStreaming:!1,...t?{sessionId:t}:{}})})]},n.id))})}function dp({stamp:e}){const t=ct(),n=e.roomLabel??"a room";return r.jsxs("span",{"data-testid":"room-post-mark",className:"text-muted-foreground inline-flex min-w-0 items-center gap-1 text-xs",children:[r.jsx("span",{"aria-hidden":!0,children:"·"}),r.jsx("span",{children:"in"}),r.jsx("button",{type:"button","aria-label":`Open ${n}`,onClick:()=>void t({...fl.channels(),search:{id:e.roomId}}),className:"focus-ring text-foreground/80 hover:text-foreground max-w-48 truncate underline-offset-4 hover:underline",children:n})]})}const fp={muted:"text-muted-foreground",active:"text-foreground",done:"text-muted-foreground",error:"text-destructive"};function mp(e){return e.charAt(0).toUpperCase()+e.slice(1)}function pp(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 s=mp(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. ${s} is on this now.`:`${s} is working on it.`;case"delivered":return`${s} read it and finished its turn.`;case"replied":return`${s} replied.`;case"failed":return t.failureReason??"It was not delivered.";default:return"Sent."}}function hp(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 gp({part:e,sent:t,at:n,sessionId:s}){const[a,o]=c.useState(!1),i=c.useId(),l=ct(),u=go(e);if(!u)return null;const d=e.status==="pending"||e.status==="running",f=np(u,t),h=(f==null?void 0:f.to.chatId)??u.chatId??(u.tool==="chat_stop"?u.to:void 0),m=(f==null?void 0:f.to)??tp(h,t),x=(m==null?void 0:m.agentName)??"the agent",g=m==null?void 0:m.chatTitle,S=Nt({id:(m==null?void 0:m.agentId)??u.to??h??"chat"}),b=u.tool==="chat_stop"?hp(u,d):rp(f,{...u,pending:d}),y=sp((f==null?void 0:f.summary)??u.summary,(f==null?void 0:f.text)??u.message),C=n?Ln(n):f?Ln(f.sentAt):"",v=u.error??((f==null?void 0:f.status)==="failed"?f.failureReason:void 0),p=v?ep(v):u.tool==="chat_stop"?u.reason:y!==g?y:"",j=u.tool==="session_start"?vd:u.tool==="chat_stop"?ca:ml,_=u.tool==="session_start"?"Started spin-off chat":u.tool==="chat_stop"?u.error||u.notRunning?"Tried to stop":"Stopped":"To",D=u.tool==="session_start"?g??(y||"a new chat"):u.tool==="chat_stop"?g??"a chat":(m==null?void 0:m.agentName)??g??"a chat",T=()=>{h&&l(At({session:h,...f?{message:f.id}:{}}))};return r.jsxs("div",{"data-testid":"sent-chat-card","data-tool":u.tool,"data-state":b.label,className:"border-border/70 bg-background my-1.5 rounded-lg border text-sm",children:[r.jsxs("button",{type:"button",onClick:()=>o(N=>!N),"aria-expanded":a,...a?{"aria-controls":i}:{},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:[r.jsx(ia,{size:"xs",emoji:S.emoji,color:S.color}),r.jsx(j,{"aria-hidden":!0,className:"text-muted-foreground hidden size-3.5 shrink-0 sm:block"}),r.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[r.jsxs("span",{className:"text-muted-foreground",children:[_," "]}),r.jsx("span",{className:"font-medium",children:D}),u.tool==="chat_send"&&g&&(m==null?void 0:m.agentName)&&r.jsxs("span",{className:"text-muted-foreground",children:[" · ",g]}),p&&(u.tool!=="session_start"||v)&&r.jsxs("span",{"data-testid":"sent-chat-aside",className:H("text-muted-foreground",!v&&"hidden sm:inline"),children:[" ","· ",p]})]}),r.jsxs("span",{className:"flex shrink-0 items-center gap-2",children:[r.jsx("span",{className:H("text-xs",fp[b.tone]),"data-testid":"sent-chat-state",children:b.label}),C&&r.jsx("time",{className:"text-muted-foreground hidden text-xs tabular-nums sm:inline",children:C}),r.jsx(Et,{"aria-hidden":!0,className:H("text-muted-foreground size-3.5 transition-transform duration-200",a&&"rotate-180")})]})]}),a&&r.jsxs("div",{id:i,className:"border-border/60 space-y-2 border-t px-3 py-2",children:[((f==null?void 0:f.text)??u.message??u.reason)&&r.jsx("div",{className:"msg-prose",children:r.jsx(hs,{content:(f==null?void 0:f.text)??u.message??u.reason??"",isStreaming:!1,...s?{sessionId:s}:{}})}),r.jsxs("p",{className:"text-muted-foreground text-xs",children:[pp(u,f,x),u.note&&u.tool!=="chat_stop"&&f?` ${u.note}`:""]}),h&&!u.error&&!u.waiting&&r.jsx("button",{type:"button",onClick:T,className:"focus-ring text-foreground text-xs font-medium underline-offset-4 hover:underline",children:"Open chat →"})]})]})}function xp({notice:e}){const t=ct();return r.jsxs("div",{"data-testid":"chat-stop-line",className:"text-muted-foreground flex flex-wrap items-center gap-1.5 text-xs",children:[r.jsx(ca,{"aria-hidden":!0,className:"size-3.5 shrink-0"}),r.jsxs("span",{children:["Stopped by ",r.jsx("span",{className:"text-foreground/80 font-medium",children:e.by.agentName})," · ",r.jsx("button",{type:"button",onClick:()=>void t(At({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}`:""]})]})}const bp={sent:[],stops:[]},yp=new xl;function bo(e){const t=pl(),n=c.useContext(hl),s=gl(e??""),{data:a}=Ye({queryKey:["chat-activity",e,s],queryFn:()=>t.getChatActivity(e),enabled:!!e&&t!==null&&n!==void 0,placeholderData:(o,i)=>(i==null?void 0:i.queryKey[1])===e?o:void 0,staleTime:3e4},n??yp);return a??bp}function vp({celebration:e,onComplete:t}){const n=c.useRef(null),s=(e==null?void 0:e.level)==="major",a=c.useCallback(()=>{t()},[t]);return c.useEffect(()=>{if(!s)return;let o=!1;bl({kind:"burst"}).then(l=>{if(o){l();return}n.current=l});const i=setTimeout(()=>{a()},Jt.CELEBRATION_DISPLAY_MS);return()=>{var l;o=!0,(l=n.current)==null||l.call(n),n.current=null,clearTimeout(i)}},[s,a]),r.jsx(ie,{children:s&&r.jsx(G.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:Td})})}const gs=c.createContext(null);function kp({children:e,value:t}){const n=c.useMemo(()=>t,[t.sessionId,t.isStreaming,t.isLatestWidgetMessage,t.isFinalMessage,t.activeToolCallId,t.onToolRef,t.focusedOptionIndex,t.onToolDecided,t.onRetry,t.onSigninComplete,t.onChooseModel,t.inputZoneToolCallId,t.textEffect,t.runtimeLabel,t.allowsDenyReason]);return r.jsx(gs,{value:n,children:e})}function Cp(){const e=c.useContext(gs);if(!e)throw new Error("useMessageContext must be used within MessageProvider");return e}function Sp(){return c.useContext(gs)}function jp(e){if(e<1e3)return"<1s";const t=Math.floor(e/1e3);if(t<60)return`${t}s`;const n=Math.floor(t/60),s=t%60;return`${n}m ${s}s`}function _p({text:e,isStreaming:t,elapsedMs:n}){const[s,a]=c.useState(t),o=c.useRef(t),i=c.useRef(null);c.useEffect(()=>{o.current&&!t&&a(!1),o.current=t},[t]),c.useEffect(()=>{t&&s&&i.current&&(i.current.scrollTop=i.current.scrollHeight)},[e,t,s]);const l=n?`Thought for ${jp(n)}`:"Thinking…";return r.jsx(Tt,{expanded:s,onToggle:()=>a(!s),variant:"thinking",dimmed:!t,disabled:t,ariaLabel:l,"data-testid":"thinking-block","data-streaming":t?"true":void 0,header:r.jsxs(r.Fragment,{children:[r.jsx(gd,{className:H("text-muted-foreground size-(--size-icon-xs)",t&&"animate-breath")}),r.jsx("span",{className:H("text-3xs text-muted-foreground font-mono",t&&"animate-breath"),children:l})]}),children:r.jsx("div",{ref:i,className:"max-h-32 overflow-y-auto",children:r.jsx("pre",{className:"text-muted-foreground text-xs break-words whitespace-pre-wrap",children:e})})})}function wp({mode:e,memories:t,isStreaming:n}){const[s,a]=c.useState(n),o=c.useRef(n);if(c.useEffect(()=>{o.current&&!n&&a(!1),o.current=n},[n]),t.length===0)return null;const i=t.length,l=n?i<=1?"Consulting memory…":`Consulting ${i} memories…`:i===1?"Recalled 1 memory":`Recalled ${i} memories`,u=e==="synthesize"?yl:vl,d=e==="synthesize"?"sparkles":"bookopen";return r.jsx(Tt,{expanded:s,onToggle:()=>a(!s),variant:"memory",dimmed:!n,disabled:n,ariaLabel:l,"data-testid":"memory-recall-block","data-streaming":n?"true":void 0,header:r.jsxs(r.Fragment,{children:[r.jsx(u,{"aria-hidden":"true","data-testid":"memory-recall-header-icon","data-icon":d,className:H("text-muted-foreground size-(--size-icon-xs)",n&&"animate-breath")}),r.jsx("span",{className:H("text-3xs text-muted-foreground font-mono",n&&"animate-breath"),children:l})]}),children:r.jsx(Np,{memories:t})})}function Np({memories:e}){return r.jsx("ul",{className:"flex flex-col gap-1 px-3 py-2",children:e.map(t=>r.jsx(Ep,{memory:t},t.path))})}function Ep({memory:e}){const t=e.path.startsWith("<synthesis:"),n=e.scope==="team"?kl:Cl,s=e.scope==="team"?"team":"personal",{copy:a}=Sl({toastOnSettle:!0}),o=()=>{const i=t&&e.content?e.content:e.path;a(i)};if(t&&e.content){const i=e.path.replace(/^<synthesis:/,"synthesis:").replace(/>$/,"");return r.jsx("li",{children:r.jsxs("button",{type:"button",onClick:o,"aria-label":`Copy synthesized ${s} 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:[r.jsx("span",{className:"text-sm",children:e.content}),r.jsxs("span",{className:"text-3xs text-muted-foreground flex items-center gap-1 font-mono",children:[r.jsx(n,{"aria-hidden":"true",className:"size-(--size-icon-xs)"}),i]})]})})}return r.jsx("li",{children:r.jsxs("button",{type:"button",onClick:o,"aria-label":`Copy ${s} 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:[r.jsx("span",{className:"flex-1 truncate font-mono text-sm",children:Id(e.path,40)}),r.jsx(n,{"aria-hidden":"true",className:"text-muted-foreground size-(--size-icon-xs)"})]})})}function Vt(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}function yo(e){return e===void 0?"Summarized (asked by the agent)":`Summarized at ${e}% (asked by the agent)`}function Dp(e){if((e==null?void 0:e.requestedBy)==="agent")return yo(e.contextPercent);const t=["Context compacted"];return(e==null?void 0:e.preTokens)!==void 0&&t.push(`${Vt(e.preTokens)} tokens`),e!=null&&e.trigger&&t.push(e.trigger),t.join(" · ")}function Ap(e,t){return e===void 0?"Compacted context":t===void 0?`Compacted context · ${Vt(e)} tokens summarized`:`Compacted context · ${Vt(e)} → ${Vt(t)} tokens`}function Tp({trigger:e,preTokens:t,postTokens:n,failed:s,error:a,requestedBy:o,contextPercent:i}){return s?r.jsx(Ve,{"data-testid":"compact-boundary-row","data-failed":"true",icon:r.jsx(us,{"aria-hidden":"true",className:"text-status-warning-dot size-3 shrink-0"}),label:r.jsx("span",{className:"text-status-warning-fg",children:o==="agent"?"Couldn’t compact (asked by the agent)":"Couldn’t compact"}),children:a?r.jsx("p",{className:"text-muted-foreground mt-1 text-xs",children:a}):null}):o==="agent"?r.jsx(Ve,{"data-testid":"compact-boundary-row","data-requested-by":"agent",icon:r.jsx(Os,{"aria-hidden":"true",className:"text-muted-foreground size-3 shrink-0"}),label:r.jsx("span",{className:"text-muted-foreground",children:yo(i)})}):r.jsx(Ve,{"data-testid":"compact-boundary-row",icon:r.jsx(Os,{"aria-hidden":"true",className:"text-muted-foreground size-3 shrink-0"}),label:r.jsx("span",{className:"text-muted-foreground",children:Ap(t,n)}),trailing:e?r.jsx("span",{"data-testid":"compact-boundary-trigger",className:"text-3xs text-muted-foreground/70 ml-auto font-mono uppercase",children:e}):void 0})}function Fp({part:e}){const[t,n]=c.useState(!1);return t?r.jsxs("div",{"data-testid":"message-image-missing",className:H("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:[r.jsx(kd,{"aria-hidden":"true",className:"size-4 shrink-0"}),r.jsx("span",{children:e.alt?`${e.alt}, not available`:"This image is not available."})]}):r.jsx("figure",{className:"my-3","data-testid":"message-image",children:r.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:r.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 Rp({content:e}){return r.jsx(Ve,{"data-testid":"staged-context-note",icon:r.jsx(ua,{"aria-hidden":"true",className:"text-muted-foreground size-3 shrink-0"}),label:r.jsx("span",{className:"text-muted-foreground",children:"Added context for the next reply"}),children:r.jsx("p",{className:"text-muted-foreground/80 mt-1 text-xs whitespace-pre-wrap",children:e})})}function Mp(e){if(e<1e3)return"<1s";const t=Math.floor(e/1e3);if(t<60)return`${t}s`;const n=Math.floor(t/60),s=t%60;return`${n}m ${s}s`}function Ip(e){return e==="untracked"?"neutral":e==="stopped"?"complete":e}function Op(e){const t=[];return e.toolUses&&t.push(`${e.toolUses} tool ${e.toolUses===1?"call":"calls"}`),e.durationMs&&t.push(Mp(e.durationMs)),t.length>0?t.join(" · "):null}function $p({part:e}){const[t,n]=c.useState(!1),s=c.useRef(null),a=Op(e),o=e.subagentText,i=e.status==="untracked",l=!!(a||e.summary||e.lastToolName||o||i);return c.useEffect(()=>{const u=s.current;u&&(u.scrollTop=u.scrollHeight)},[o]),r.jsx(Tt,{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:r.jsxs(r.Fragment,{children:[mo(Ip(e.status)),r.jsx("span",{className:"text-3xs truncate font-mono",children:e.description}),a&&r.jsx("span",{className:"text-3xs text-muted-foreground ml-1 shrink-0",children:a})]}),children:r.jsxs("div",{className:"space-y-1.5",children:[o&&r.jsxs("div",{className:"space-y-1",children:[r.jsx("p",{className:"text-3xs text-muted-foreground/70 tracking-wide uppercase",children:"Helper output"}),r.jsx("pre",{ref:s,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"&&r.jsxs("p",{className:"text-3xs text-muted-foreground",children:["Last tool: ",r.jsx("span",{className:"font-mono",children:e.lastToolName})]}),e.summary&&r.jsx("pre",{className:"overflow-x-auto text-xs whitespace-pre-wrap",children:e.summary}),i&&r.jsx("p",{className:"text-3xs text-muted-foreground","data-testid":"subagent-untracked",children:"No longer tracked. It may still be running."})]})})}const Pp=e=>typeof e=="boolean"||e instanceof Boolean,Lp=e=>typeof e=="number"||e instanceof Number,zp=e=>typeof e=="bigint"||e instanceof BigInt,vo=e=>!!e&&e instanceof Date,Bp=e=>typeof e=="string"||e instanceof String,qp=e=>Array.isArray(e),ko=e=>typeof e=="object"&&e!==null,Co=e=>!!e&&e instanceof Object&&typeof e=="function";function Qt(e,t){return t===void 0&&(t=!1),!e||t?`"${e}"`:e}function Up(e,t,n){return n?JSON.stringify(e):t?`"${e}"`:e}function So(e){let{field:t,value:n,data:s,lastElement:a,openBracket:o,closeBracket:i,level:l,style:u,shouldExpandNode:d,clickToExpandNode:f,outerRef:h,beforeExpandChange:m}=e;const x=c.useRef(!1),[g,S]=c.useState(()=>d(l,n,t)),b=c.useRef(null);c.useEffect(()=>{x.current?S(d(l,n,t)):x.current=!0},[d]);const y=c.useId();if(s.length===0)return Hp({field:t,openBracket:o,closeBracket:i,lastElement:a,style:u});const C=g?u.collapseIcon:u.expandIcon,v=g?u.ariaLables.collapseJson:u.ariaLables.expandJson,p=l+1,j=s.length-1,_=N=>{g!==N&&(!m||m({level:l,value:n,field:t,newExpandValue:N}))&&S(N)},D=N=>{if(N.key==="ArrowRight"||N.key==="ArrowLeft")N.preventDefault(),_(N.key==="ArrowRight");else if(N.key==="ArrowUp"||N.key==="ArrowDown"){N.preventDefault();const A=N.key==="ArrowUp"?-1:1;if(!h.current)return;const k=h.current.querySelectorAll("[role=button]");let E=-1;for(let R=0;R<k.length;R++)if(k[R].tabIndex===0){E=R;break}if(E<0)return;const w=(E+A+k.length)%k.length;k[E].tabIndex=-1,k[w].tabIndex=0,k[w].focus()}},T=()=>{var N;_(!g);const A=b.current;if(!A)return;const k=(N=h.current)===null||N===void 0?void 0:N.querySelector('[role=button][tabindex="0"]');k&&(k.tabIndex=-1),A.tabIndex=0,A.focus()};return c.createElement("div",{className:u.basicChildStyle,role:"treeitem","aria-expanded":g,"aria-selected":void 0},c.createElement("span",{className:C,onClick:T,onKeyDown:D,role:"button","aria-label":v,"aria-expanded":g,"aria-controls":g?y:void 0,ref:b,tabIndex:l===0?0:-1}),(t||t==="")&&(f?c.createElement("span",{className:u.clickableLabel,onClick:T,onKeyDown:D},Qt(t,u.quotesForFieldNames),":"):c.createElement("span",{className:u.label},Qt(t,u.quotesForFieldNames),":")),c.createElement("span",{className:u.punctuation},o),g?c.createElement("ul",{id:y,role:"group",className:u.childFieldsContainer},s.map((N,A)=>c.createElement(Wn,{key:N[0]||A,field:N[0],value:N[1],style:u,lastElement:A===j,level:p,shouldExpandNode:d,clickToExpandNode:f,beforeExpandChange:m,outerRef:h}))):c.createElement("span",{className:u.collapsedContent,onClick:T,onKeyDown:D}),c.createElement("span",{className:u.punctuation},i),!a&&c.createElement("span",{className:u.punctuation},","))}function Hp(e){let{field:t,openBracket:n,closeBracket:s,lastElement:a,style:o}=e;return c.createElement("div",{className:o.basicChildStyle,role:"treeitem","aria-selected":void 0},(t||t==="")&&c.createElement("span",{className:o.label},Qt(t,o.quotesForFieldNames),":"),c.createElement("span",{className:o.punctuation},n),c.createElement("span",{className:o.punctuation},s),!a&&c.createElement("span",{className:o.punctuation},","))}function Wp(e){let{field:t,value:n,style:s,lastElement:a,shouldExpandNode:o,clickToExpandNode:i,level:l,outerRef:u,beforeExpandChange:d}=e;return So({field:t,value:n,lastElement:a||!1,level:l,openBracket:"{",closeBracket:"}",style:s,shouldExpandNode:o,clickToExpandNode:i,data:Object.keys(n).map(f=>[f,n[f]]),outerRef:u,beforeExpandChange:d})}function Vp(e){let{field:t,value:n,style:s,lastElement:a,level:o,shouldExpandNode:i,clickToExpandNode:l,outerRef:u,beforeExpandChange:d}=e;return So({field:t,value:n,lastElement:a||!1,level:o,openBracket:"[",closeBracket:"]",style:s,shouldExpandNode:i,clickToExpandNode:l,data:n.map(f=>[void 0,f]),outerRef:u,beforeExpandChange:d})}function Gp(e){let{field:t,value:n,style:s,lastElement:a}=e,o,i=s.otherValue;return n===null?(o="null",i=s.nullValue):n===void 0?(o="undefined",i=s.undefinedValue):Bp(n)?(o=Up(n,!s.noQuotesForStringValues,s.stringifyStringValues),i=s.stringValue):Pp(n)?(o=n?"true":"false",i=s.booleanValue):Lp(n)?(o=n.toString(),i=s.numberValue):zp(n)?(o=`${n.toString()}n`,i=s.numberValue):vo(n)?o=n.toISOString():Co(n)?o="function() { }":o=n.toString(),c.createElement("div",{className:s.basicChildStyle,role:"treeitem","aria-selected":void 0},(t||t==="")&&c.createElement("span",{className:s.label},Qt(t,s.quotesForFieldNames),":"),c.createElement("span",{className:i},o),!a&&c.createElement("span",{className:s.punctuation},","))}function Wn(e){const t=e.value;return qp(t)?c.createElement(Vp,Object.assign({},e)):ko(t)&&!vo(t)&&!Co(t)?c.createElement(Wp,Object.assign({},e)):c.createElement(Gp,Object.assign({},e))}var ee={"container-light":"_2IvMF _GzYRV","basic-element-style":"_2bkNM","child-fields-container":"_1BXBN","label-light":"_1MGIk","clickable-label-light":"_2YKJg _1MGIk _1MFti","punctuation-light":"_3uHL6 _3eOF8","value-null-light":"_2T6PJ","value-undefined-light":"_1Gho6","value-string-light":"_vGjyY","value-number-light":"_1bQdo","value-boolean-light":"_3zQKs","value-other-light":"_1xvuR","collapse-icon-light":"_oLqym _f10Tu _1MFti _1LId0","expand-icon-light":"_2AXVT _f10Tu _1MFti _1UmXx","collapsed-content-light":"_2KJWg _1pNG9 _1MFti","container-dark":"_11RoI _GzYRV","expand-icon-dark":"_17H2C _f10Tu _1MFti _1UmXx","collapse-icon-dark":"_3QHg2 _f10Tu _1MFti _1LId0","collapsed-content-dark":"_3fDAz _1pNG9 _1MFti","label-dark":"_2bSDX","clickable-label-dark":"_1RQEj _2bSDX _1MFti","punctuation-dark":"_gsbQL _3eOF8","value-null-dark":"_LaAZe","value-undefined-dark":"_GTKgm","value-string-dark":"_Chy1W","value-number-dark":"_2bveF","value-boolean-dark":"_2vRm-","value-other-dark":"_1prJR"};const jo={collapseJson:"collapse JSON",expandJson:"expand JSON"},jn={container:ee["container-light"],basicChildStyle:ee["basic-element-style"],childFieldsContainer:ee["child-fields-container"],label:ee["label-light"],clickableLabel:ee["clickable-label-light"],nullValue:ee["value-null-light"],undefinedValue:ee["value-undefined-light"],stringValue:ee["value-string-light"],booleanValue:ee["value-boolean-light"],numberValue:ee["value-number-light"],otherValue:ee["value-other-light"],punctuation:ee["punctuation-light"],collapseIcon:ee["collapse-icon-light"],expandIcon:ee["expand-icon-light"],collapsedContent:ee["collapsed-content-light"],noQuotesForStringValues:!1,quotesForFieldNames:!1,ariaLables:jo,stringifyStringValues:!1},Kp={container:ee["container-dark"],basicChildStyle:ee["basic-element-style"],childFieldsContainer:ee["child-fields-container"],label:ee["label-dark"],clickableLabel:ee["clickable-label-dark"],nullValue:ee["value-null-dark"],undefinedValue:ee["value-undefined-dark"],stringValue:ee["value-string-dark"],booleanValue:ee["value-boolean-dark"],numberValue:ee["value-number-dark"],otherValue:ee["value-other-dark"],punctuation:ee["punctuation-dark"],collapseIcon:ee["collapse-icon-dark"],expandIcon:ee["expand-icon-dark"],collapsedContent:ee["collapsed-content-dark"],noQuotesForStringValues:!1,quotesForFieldNames:!1,ariaLables:jo,stringifyStringValues:!1},Qp=()=>!0,Yp=e=>e<1,Xp=e=>{let{data:t,style:n=jn,shouldExpandNode:s=Qp,clickToExpandNode:a=!1,beforeExpandChange:o,compactTopLevel:i,...l}=e;const u=c.useRef(null);return c.createElement("div",Object.assign({"aria-label":"JSON view"},l,{className:n.container,ref:u,role:"tree"}),i&&ko(t)?Object.entries(t).map(d=>{let[f,h]=d;return c.createElement(Wn,{key:f,field:f,value:h,style:{...jn,...n},lastElement:!0,level:1,shouldExpandNode:s,clickToExpandNode:a,beforeExpandChange:o,outerRef:u})}):c.createElement(Wn,{value:t,style:{...jn,...n},lastElement:!0,level:0,shouldExpandNode:s,clickToExpandNode:a,outerRef:u,beforeExpandChange:o}))};var we={},_n,or;function Jp(){if(or)return _n;or=1;const e=[[{color:"0, 0, 0",class:"ansi-black"},{color:"187, 0, 0",class:"ansi-red"},{color:"0, 187, 0",class:"ansi-green"},{color:"187, 187, 0",class:"ansi-yellow"},{color:"0, 0, 187",class:"ansi-blue"},{color:"187, 0, 187",class:"ansi-magenta"},{color:"0, 187, 187",class:"ansi-cyan"},{color:"255,255,255",class:"ansi-white"}],[{color:"85, 85, 85",class:"ansi-bright-black"},{color:"255, 85, 85",class:"ansi-bright-red"},{color:"0, 255, 0",class:"ansi-bright-green"},{color:"255, 255, 85",class:"ansi-bright-yellow"},{color:"85, 85, 255",class:"ansi-bright-blue"},{color:"255, 85, 255",class:"ansi-bright-magenta"},{color:"85, 255, 255",class:"ansi-bright-cyan"},{color:"255, 255, 255",class:"ansi-bright-white"}]],t=/(https?:\/\/(?:[A-Za-z0-9#;/?:@=+$',_.!~*()[\]-]|&amp;|%[A-Fa-f0-9]{2})+)/gm;class n{static escapeForHtml(a){return new n().escapeForHtml(a)}static linkify(a){return new n().linkify(a)}static ansiToHtml(a,o){return new n().ansiToHtml(a,o)}static ansiToJson(a,o){return new n().ansiToJson(a,o)}static ansiToText(a){return new n().ansiToText(a)}constructor(){this.fg=this.bg=this.fg_truecolor=this.bg_truecolor=null,this.bright=0,this.decorations=[]}setupPalette(){this.PALETTE_COLORS=[];for(let l=0;l<2;++l)for(let u=0;u<8;++u)this.PALETTE_COLORS.push(e[l][u].color);let a=[0,95,135,175,215,255],o=(l,u,d)=>a[l]+", "+a[u]+", "+a[d];for(let l=0;l<6;++l)for(let u=0;u<6;++u)for(let d=0;d<6;++d)this.PALETTE_COLORS.push(o(l,u,d));let i=8;for(let l=0;l<24;++l,i+=10)this.PALETTE_COLORS.push(i+", "+i+", "+i)}escapeForHtml(a){return a.replace(/[&<>\"]/gm,o=>o=="&"?"&amp;":o=='"'?"&quot;":o=="<"?"&lt;":o==">"?"&gt;":"")}linkify(a){return a.replace(t,o=>`<a href="${o}">${o}</a>`)}ansiToHtml(a,o){return this.process(a,o,!0)}ansiToJson(a,o){return o=o||{},o.json=!0,o.clearLine=!1,this.process(a,o,!0)}ansiToText(a){return this.process(a,{},!1)}process(a,o,i){let l=this,u=a.split(/\033\[/),d=u.shift();o==null&&(o={}),o.clearLine=/\r/.test(a);let f=u.map(h=>this.processChunk(h,o,i));if(o&&o.json){let h=l.processChunkJson("");return h.content=d,h.clearLine=o.clearLine,f.unshift(h),o.remove_empty&&(f=f.filter(m=>!m.isEmpty())),f}else f.unshift(d);return f.join("")}processChunkJson(a,o,i){o=typeof o>"u"?{}:o;let l=o.use_classes=typeof o.use_classes<"u"&&o.use_classes,u=o.key=l?"class":"color",d={content:a,fg:null,bg:null,fg_truecolor:null,bg_truecolor:null,isInverted:!1,clearLine:o.clearLine,decoration:null,decorations:[],was_processed:!1,isEmpty:()=>!d.content},f=a.match(/^([!\x3c-\x3f]*)([\d;]*)([\x20-\x2c]*[\x40-\x7e])([\s\S]*)/m);if(!f)return d;d.content=f[4];let h=f[2].split(";");if(f[1]!==""||f[3]!=="m"||!i)return d;let m=this;for(;h.length>0;){let x=h.shift(),g=parseInt(x);if(isNaN(g)||g===0)m.fg=m.bg=null,m.decorations=[];else if(g===1)m.decorations.push("bold");else if(g===2)m.decorations.push("dim");else if(g===3)m.decorations.push("italic");else if(g===4)m.decorations.push("underline");else if(g===5)m.decorations.push("blink");else if(g===7)m.decorations.push("reverse");else if(g===8)m.decorations.push("hidden");else if(g===9)m.decorations.push("strikethrough");else if(g===21)m.removeDecoration("bold");else if(g===22)m.removeDecoration("bold"),m.removeDecoration("dim");else if(g===23)m.removeDecoration("italic");else if(g===24)m.removeDecoration("underline");else if(g===25)m.removeDecoration("blink");else if(g===27)m.removeDecoration("reverse");else if(g===28)m.removeDecoration("hidden");else if(g===29)m.removeDecoration("strikethrough");else if(g===39)m.fg=null;else if(g===49)m.bg=null;else if(g>=30&&g<38)m.fg=e[0][g%10][u];else if(g>=90&&g<98)m.fg=e[1][g%10][u];else if(g>=40&&g<48)m.bg=e[0][g%10][u];else if(g>=100&&g<108)m.bg=e[1][g%10][u];else if(g===38||g===48){let S=g===38;if(h.length>=1){let b=h.shift();if(b==="5"&&h.length>=1){let y=parseInt(h.shift());if(y>=0&&y<=255)if(!l)this.PALETTE_COLORS||m.setupPalette(),S?m.fg=this.PALETTE_COLORS[y]:m.bg=this.PALETTE_COLORS[y];else{let C=y>=16?"ansi-palette-"+y:e[y>7?1:0][y%8].class;S?m.fg=C:m.bg=C}}else if(b==="2"&&h.length>=3){let y=parseInt(h.shift()),C=parseInt(h.shift()),v=parseInt(h.shift());if(y>=0&&y<=255&&C>=0&&C<=255&&v>=0&&v<=255){let p=y+", "+C+", "+v;l?S?(m.fg="ansi-truecolor",m.fg_truecolor=p):(m.bg="ansi-truecolor",m.bg_truecolor=p):S?m.fg=p:m.bg=p}}}}}return m.fg===null&&m.bg===null&&m.decorations.length===0||(d.fg=m.fg,d.bg=m.bg,d.fg_truecolor=m.fg_truecolor,d.bg_truecolor=m.bg_truecolor,d.decorations=m.decorations,d.decoration=m.decorations.slice(-1).pop()||null,d.was_processed=!0),d}processChunk(a,o,i){o=o||{};let l=this.processChunkJson(a,o,i),u=o.use_classes;if(l.decorations=l.decorations.filter(g=>{if(g==="reverse"){l.fg||(l.fg=e[0][7][u?"class":"color"]),l.bg||(l.bg=e[0][0][u?"class":"color"]);let S=l.fg;l.fg=l.bg,l.bg=S;let b=l.fg_truecolor;return l.fg_truecolor=l.bg_truecolor,l.bg_truecolor=b,l.isInverted=!0,!1}return!0}),o.json)return l;if(l.isEmpty())return"";if(!l.was_processed)return l.content;let d=[],f=[],h=[],m={},x=g=>{let S=[],b;for(b in g)g.hasOwnProperty(b)&&S.push("data-"+b+'="'+this.escapeForHtml(g[b])+'"');return S.length>0?" "+S.join(" "):""};return l.isInverted&&(m["ansi-is-inverted"]="true"),l.fg&&(u?(d.push(l.fg+"-fg"),l.fg_truecolor!==null&&(m["ansi-truecolor-fg"]=l.fg_truecolor,l.fg_truecolor=null)):d.push("color:rgb("+l.fg+")")),l.bg&&(u?(d.push(l.bg+"-bg"),l.bg_truecolor!==null&&(m["ansi-truecolor-bg"]=l.bg_truecolor,l.bg_truecolor=null)):d.push("background-color:rgb("+l.bg+")")),l.decorations.forEach(g=>{if(u){f.push("ansi-"+g);return}g==="bold"?f.push("font-weight:bold"):g==="dim"?f.push("opacity:0.5"):g==="italic"?f.push("font-style:italic"):g==="hidden"?f.push("visibility:hidden"):g==="strikethrough"?h.push("line-through"):h.push(g)}),h.length&&f.push("text-decoration:"+h.join(" ")),u?'<span class="'+d.concat(f).join(" ")+'"'+x(m)+">"+l.content+"</span>":'<span style="'+d.concat(f).join(";")+'"'+x(m)+">"+l.content+"</span>"}removeDecoration(a){const o=this.decorations.indexOf(a);o>=0&&this.decorations.splice(o,1)}}return _n=n,_n}var pt={exports:{}},ir;function Zp(){if(ir)return pt.exports;ir=1;function e(a){if(!a)return"";if(!/\r/.test(a))return a;for(a=a.replace(/\r+\n/gm,`
41
41
  `);/\r./.test(a);)a=a.replace(/^([^\r\n]*)\r+([^\r\n]+)/gm,function(o,i,l){return l+i.slice(l.length)});return a}function t(a){for(var o=0,i=0;i<a.length;i++)a[o].length<=a[i].length&&(o=i);return o}function n(a){if(!/\r/.test(a))return a;for(var o=a.split("\r"),i=[];o.length>0;){var l=t(o);i.push(o[l]),o=o.slice(l+1)}return i.join("\r")}function s(a){if(!a)return"";if(!/\r/.test(a))return a;if(!/\n/.test(a))return n(a);a=a.replace(/\r+\n/gm,`
42
42
  `);var o=a.lastIndexOf(`
43
43
  `);return e(a.slice(0,o))+`
44
- `+n(a.slice(o+1))}return pt.exports=e,pt.exports.escapeCarriageReturn=e,pt.exports.escapeCarriageReturnSafe=s,pt.exports}var Pe={},lr;function eh(){if(lr)return Pe;lr=1;var e=/[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,t=/[\0-\x1F\x7F-\x9F]/,n=/[\xAD\u0600-\u0605\u061C\u06DD\u070F\u0890\u0891\u08E2\u180E\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF\uFFF9-\uFFFB]|\uD804[\uDCBD\uDCCD]|\uD80D[\uDC30-\uDC3F]|\uD82F[\uDCA0-\uDCA3]|\uD834[\uDD73-\uDD7A]|\uDB40[\uDC01\uDC20-\uDC7F]/,s=/[!-#%-\*,-\/:;\?@\[-\]_\{\}\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061D-\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1B7D\u1B7E\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u2E52-\u2E5D\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD803[\uDEAD\uDF55-\uDF59\uDF86-\uDF89]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5A\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDEB9\uDF3C-\uDF3E]|\uD806[\uDC3B\uDD44-\uDD46\uDDE2\uDE3F-\uDE46\uDE9A-\uDE9C\uDE9E-\uDEA2\uDF00-\uDF09]|\uD807[\uDC41-\uDC45\uDC70\uDC71\uDEF7\uDEF8\uDF43-\uDF4F\uDFFF]|\uD809[\uDC70-\uDC74]|\uD80B[\uDFF1\uDFF2]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD81B[\uDE97-\uDE9A\uDFE2]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]/,a=/[\$\+<->\^`\|~\xA2-\xA6\xA8\xA9\xAC\xAE-\xB1\xB4\xB8\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0384\u0385\u03F6\u0482\u058D-\u058F\u0606-\u0608\u060B\u060E\u060F\u06DE\u06E9\u06FD\u06FE\u07F6\u07FE\u07FF\u0888\u09F2\u09F3\u09FA\u09FB\u0AF1\u0B70\u0BF3-\u0BFA\u0C7F\u0D4F\u0D79\u0E3F\u0F01-\u0F03\u0F13\u0F15-\u0F17\u0F1A-\u0F1F\u0F34\u0F36\u0F38\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE\u0FCF\u0FD5-\u0FD8\u109E\u109F\u1390-\u1399\u166D\u17DB\u1940\u19DE-\u19FF\u1B61-\u1B6A\u1B74-\u1B7C\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u2044\u2052\u207A-\u207C\u208A-\u208C\u20A0-\u20C0\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F\u218A\u218B\u2190-\u2307\u230C-\u2328\u232B-\u2426\u2440-\u244A\u249C-\u24E9\u2500-\u2767\u2794-\u27C4\u27C7-\u27E5\u27F0-\u2982\u2999-\u29D7\u29DC-\u29FB\u29FE-\u2B73\u2B76-\u2B95\u2B97-\u2BFF\u2CE5-\u2CEA\u2E50\u2E51\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFF\u3004\u3012\u3013\u3020\u3036\u3037\u303E\u303F\u309B\u309C\u3190\u3191\u3196-\u319F\u31C0-\u31E3\u31EF\u3200-\u321E\u322A-\u3247\u3250\u3260-\u327F\u328A-\u32B0\u32C0-\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA700-\uA716\uA720\uA721\uA789\uA78A\uA828-\uA82B\uA836-\uA839\uAA77-\uAA79\uAB5B\uAB6A\uAB6B\uFB29\uFBB2-\uFBC2\uFD40-\uFD4F\uFDCF\uFDFC-\uFDFF\uFE62\uFE64-\uFE66\uFE69\uFF04\uFF0B\uFF1C-\uFF1E\uFF3E\uFF40\uFF5C\uFF5E\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFFC\uFFFD]|\uD800[\uDD37-\uDD3F\uDD79-\uDD89\uDD8C-\uDD8E\uDD90-\uDD9C\uDDA0\uDDD0-\uDDFC]|\uD802[\uDC77\uDC78\uDEC8]|\uD805\uDF3F|\uD807[\uDFD5-\uDFF1]|\uD81A[\uDF3C-\uDF3F\uDF45]|\uD82F\uDC9C|\uD833[\uDF50-\uDFC3]|\uD834[\uDC00-\uDCF5\uDD00-\uDD26\uDD29-\uDD64\uDD6A-\uDD6C\uDD83\uDD84\uDD8C-\uDDA9\uDDAE-\uDDEA\uDE00-\uDE41\uDE45\uDF00-\uDF56]|\uD835[\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3]|\uD836[\uDC00-\uDDFF\uDE37-\uDE3A\uDE6D-\uDE74\uDE76-\uDE83\uDE85\uDE86]|\uD838[\uDD4F\uDEFF]|\uD83B[\uDCAC\uDCB0\uDD2E\uDEF0\uDEF1]|\uD83C[\uDC00-\uDC2B\uDC30-\uDC93\uDCA0-\uDCAE\uDCB1-\uDCBF\uDCC1-\uDCCF\uDCD1-\uDCF5\uDD0D-\uDDAD\uDDE6-\uDE02\uDE10-\uDE3B\uDE40-\uDE48\uDE50\uDE51\uDE60-\uDE65\uDF00-\uDFFF]|\uD83D[\uDC00-\uDED7\uDEDC-\uDEEC\uDEF0-\uDEFC\uDF00-\uDF76\uDF7B-\uDFD9\uDFE0-\uDFEB\uDFF0]|\uD83E[\uDC00-\uDC0B\uDC10-\uDC47\uDC50-\uDC59\uDC60-\uDC87\uDC90-\uDCAD\uDCB0\uDCB1\uDD00-\uDE53\uDE60-\uDE6D\uDE70-\uDE7C\uDE80-\uDE88\uDE90-\uDEBD\uDEBF-\uDEC5\uDECE-\uDEDB\uDEE0-\uDEE8\uDEF0-\uDEF8\uDF00-\uDF92\uDF94-\uDFCA]/,o=/[ \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/;return Pe.Any=e,Pe.Cc=t,Pe.Cf=n,Pe.P=s,Pe.S=a,Pe.Z=o,Pe}var wn,cr;function th(){if(cr)return wn;cr=1;var e=eh();function t(v){const p={};v=v||{},p.src_Any=e.Any.source,p.src_Cc=e.Cc.source,p.src_Z=e.Z.source,p.src_P=e.P.source,p.src_ZPCc=[p.src_Z,p.src_P,p.src_Cc].join("|"),p.src_ZCc=[p.src_Z,p.src_Cc].join("|");const j="[><|]";return p.src_pseudo_letter=`(?:(?!${j}|${p.src_ZPCc})${p.src_Any})`,p.src_ip4="(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)",p.src_auth=`(?:(?:(?!${p.src_ZCc}|[@/\\[\\]()]).){1,50}@)?`,p.src_port="(?::(?:6(?:[0-4]\\d{3}|5(?:[0-4]\\d{2}|5(?:[0-2]\\d|3[0-5])))|[1-5]?\\d{1,4}))?",p.src_host_terminator=`(?=$|${j}|${p.src_ZPCc})(?!${v["---"]?"-(?!--)|":"-|"}_|:\\d|\\.-|\\.(?!$|${p.src_ZPCc}))`,p.src_path=`(?:[/?#](?:(?!${p.src_ZCc}|${j}|[()[\\]{}.,"'?!\\-;]).|\\[(?:(?!${p.src_ZCc}|\\]).)*\\]|\\((?:(?!${p.src_ZCc}|[)]).)*\\)|\\{(?:(?!${p.src_ZCc}|[}]).)*\\}|\\"(?:(?!${p.src_ZCc}|["]).)+\\"|\\'(?:(?!${p.src_ZCc}|[']).)+\\'|\\'(?=${p.src_pseudo_letter}|[-])|\\.{2,}[a-zA-Z0-9%/&]|\\.(?!${p.src_ZCc}|[.]|$)|`+(v["---"]?"\\-(?!--(?:[^-]|$))(?:-*)|":"\\-+|")+`,(?!${p.src_ZCc}|$)|;(?!${p.src_ZCc}|$)|\\!+(?!${p.src_ZCc}|[!]|$)|\\?(?!${p.src_ZCc}|[?]|$))+|\\/)?`,p.src_email_name='[\\-;:&=\\+\\$,\\.a-zA-Z0-9_][\\-;:&=\\+\\$,\\"\\.a-zA-Z0-9_]{0,63}',p.src_xn="xn--[a-z0-9\\-]{1,59}",p.src_domain_root="(?:"+p.src_xn+`|${p.src_pseudo_letter}{1,63})`,p.src_domain="(?:"+p.src_xn+`|(?:${p.src_pseudo_letter})|(?:${p.src_pseudo_letter}(?:-|${p.src_pseudo_letter}){0,61}${p.src_pseudo_letter}))`,p.src_host=`(?:(?:(?:(?:${p.src_domain})\\.)*${p.src_domain}))`,p.tpl_host_fuzzy="(?:"+p.src_ip4+`|(?:(?:(?:${p.src_domain})\\.)+(?:%TLDS%)))`,p.tpl_host_no_ip_fuzzy=`(?:(?:(?:${p.src_domain})\\.)+(?:%TLDS%))`,p.src_host_strict=p.src_host+p.src_host_terminator,p.tpl_host_fuzzy_strict=p.tpl_host_fuzzy+p.src_host_terminator,p.src_host_port_strict=p.src_host+p.src_port+p.src_host_terminator,p.tpl_host_port_fuzzy_strict=p.tpl_host_fuzzy+p.src_port+p.src_host_terminator,p.tpl_host_port_no_ip_fuzzy_strict=p.tpl_host_no_ip_fuzzy+p.src_port+p.src_host_terminator,p.tpl_host_fuzzy_test=`localhost|www\\.|\\.\\d{1,3}\\.|(?:\\.(?:%TLDS%)(?:${p.src_ZPCc}|>|$))`,p.tpl_email_fuzzy=`(^|${j}|"|\\(|${p.src_ZCc})(${p.src_email_name}@${p.tpl_host_fuzzy_strict})`,p.tpl_link_fuzzy=`(^|(?![.:/\\-_@])(?:[$+<=>^\`||]|${p.src_ZPCc}))((?![$+<=>^\`||])${p.tpl_host_port_fuzzy_strict}${p.src_path})`,p.tpl_link_no_ip_fuzzy=`(^|(?![.:/\\-_@])(?:[$+<=>^\`||]|${p.src_ZPCc}))((?![$+<=>^\`||])${p.tpl_host_port_no_ip_fuzzy_strict}${p.src_path})`,p}function n(v){return Array.prototype.slice.call(arguments,1).forEach(function(j){j&&Object.keys(j).forEach(function(_){v[_]=j[_]})}),v}function s(v){return Object.prototype.toString.call(v)}function a(v){return s(v)==="[object String]"}function o(v){return s(v)==="[object Object]"}function i(v){return s(v)==="[object RegExp]"}function l(v){return s(v)==="[object Function]"}function u(v){return v.replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")}const d={fuzzyLink:!0,fuzzyEmail:!0,fuzzyIP:!1};function f(v){return Object.keys(v||{}).reduce(function(p,j){return p||d.hasOwnProperty(j)},!1)}const h={"http:":{validate:function(v,p,j){const _=v.slice(p);return j.re.http||(j.re.http=new RegExp(`^\\/\\/${j.re.src_auth}${j.re.src_host_port_strict}${j.re.src_path}`,"i")),j.re.http.test(_)?_.match(j.re.http)[0].length:0}},"https:":"http:","ftp:":"http:","//":{validate:function(v,p,j){const _=v.slice(p);return j.re.no_http||(j.re.no_http=new RegExp("^"+j.re.src_auth+`(?:localhost|(?:(?:${j.re.src_domain})\\.)+${j.re.src_domain_root})`+j.re.src_port+j.re.src_host_terminator+j.re.src_path,"i")),j.re.no_http.test(_)?p>=3&&v[p-3]===":"||p>=3&&v[p-3]==="/"?0:_.match(j.re.no_http)[0].length:0}},"mailto:":{validate:function(v,p,j){const _=v.slice(p);return j.re.mailto||(j.re.mailto=new RegExp(`^${j.re.src_email_name}@${j.re.src_host_strict}`,"i")),j.re.mailto.test(_)?_.match(j.re.mailto)[0].length:0}}},m="a[cdefgilmnoqrstuwxz]|b[abdefghijmnorstvwyz]|c[acdfghiklmnoruvwxyz]|d[ejkmoz]|e[cegrstu]|f[ijkmor]|g[abdefghilmnpqrstuwy]|h[kmnrtu]|i[delmnoqrst]|j[emop]|k[eghimnprwyz]|l[abcikrstuvy]|m[acdeghklmnopqrstuvwxyz]|n[acefgilopruz]|om|p[aefghklmnrstwy]|qa|r[eosuw]|s[abcdeghijklmnortuvxyz]|t[cdfghjklmnortvwz]|u[agksyz]|v[aceginu]|w[fs]|y[et]|z[amw]",x="biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф".split("|");function g(v){return function(p,j){const _=p.slice(j);return v.test(_)?_.match(v)[0].length:0}}function S(){return function(v,p){p.normalize(v)}}function b(v){const p=v.re=t(v.__opts__),j=v.__tlds__.slice();v.onCompile(),v.__tlds_replaced__||j.push(m),j.push(p.src_xn),p.src_tlds=j.join("|");function _(A){return A.replace("%TLDS%",p.src_tlds)}p.email_fuzzy=RegExp(_(p.tpl_email_fuzzy),"i"),p.email_fuzzy_global=RegExp(_(p.tpl_email_fuzzy),"ig"),p.link_fuzzy=RegExp(_(p.tpl_link_fuzzy),"i"),p.link_fuzzy_global=RegExp(_(p.tpl_link_fuzzy),"ig"),p.link_no_ip_fuzzy=RegExp(_(p.tpl_link_no_ip_fuzzy),"i"),p.link_no_ip_fuzzy_global=RegExp(_(p.tpl_link_no_ip_fuzzy),"ig"),p.host_fuzzy_test=RegExp(_(p.tpl_host_fuzzy_test),"i");const D=[];v.__compiled__={};function T(A,k){throw new Error(`(LinkifyIt) Invalid schema "${A}": ${k}`)}Object.keys(v.__schemas__).forEach(function(A){const k=v.__schemas__[A];if(k===null)return;const E={validate:null,link:null};if(v.__compiled__[A]=E,o(k)){i(k.validate)?E.validate=g(k.validate):l(k.validate)?E.validate=k.validate:T(A,k),l(k.normalize)?E.normalize=k.normalize:k.normalize?T(A,k):E.normalize=S();return}if(a(k)){D.push(A);return}T(A,k)}),D.forEach(function(A){v.__compiled__[v.__schemas__[A]]&&(v.__compiled__[A].validate=v.__compiled__[v.__schemas__[A]].validate,v.__compiled__[A].normalize=v.__compiled__[v.__schemas__[A]].normalize)}),v.__compiled__[""]={validate:null,normalize:S()};const N=Object.keys(v.__compiled__).filter(function(A){return A.length>0&&v.__compiled__[A]}).map(u).join("|");v.re.schema_test=RegExp(`(^|(?!_)(?:[><|]|${p.src_ZPCc}))(${N})`,"i"),v.re.schema_search=RegExp(`(^|(?!_)(?:[><|]|${p.src_ZPCc}))(${N})`,"ig"),v.re.schema_at_start=RegExp(`^${v.re.schema_search.source}`,"i"),v.re.pretest=RegExp(`(${v.re.schema_test.source})|(${v.re.host_fuzzy_test.source})|@`,"i")}function y(v,p,j,_){const D=v.slice(j,_);this.schema=p.toLowerCase(),this.index=j,this.lastIndex=_,this.raw=D,this.text=D,this.url=D}function C(v,p){if(!(this instanceof C))return new C(v,p);p||f(v)&&(p=v,v={}),this.__opts__=n({},d,p),this.__schemas__=n({},h,v),this.__compiled__={},this.__tlds__=x,this.__tlds_replaced__=!1,this.re={},b(this)}return C.prototype.add=function(p,j){return this.__schemas__[p]=j,b(this),this},C.prototype.set=function(p){return this.__opts__=n(this.__opts__,p),this},C.prototype.test=function(p){if(!p.length)return!1;let j,_;if(this.re.schema_test.test(p)){for(_=this.re.schema_search,_.lastIndex=0;(j=_.exec(p))!==null;)if(this.testSchemaAt(p,j[2],_.lastIndex))return!0}return!!(this.__opts__.fuzzyLink&&this.__compiled__["http:"]&&p.search(this.re.host_fuzzy_test)>=0&&p.match(this.__opts__.fuzzyIP?this.re.link_fuzzy:this.re.link_no_ip_fuzzy)!==null||this.__opts__.fuzzyEmail&&this.__compiled__["mailto:"]&&p.indexOf("@")>=0&&p.match(this.re.email_fuzzy)!==null)},C.prototype.pretest=function(p){return this.re.pretest.test(p)},C.prototype.testSchemaAt=function(p,j,_){return this.__compiled__[j.toLowerCase()]?this.__compiled__[j.toLowerCase()].validate(p,_,this):0},C.prototype.match=function(p){const j=[],_=[],D=[],T=[];let N,A,k;function E(O,F){return O?F?O.index!==F.index?O.index<F.index?O:F:O.lastIndex>=F.lastIndex?O:F:O:F}if(!p.length)return null;if(this.re.schema_test.test(p))for(k=this.re.schema_search,k.lastIndex=0;(N=k.exec(p))!==null;)A=this.testSchemaAt(p,N[2],k.lastIndex),A&&_.push({schema:N[2],index:N.index+N[1].length,lastIndex:N.index+N[0].length+A});if(this.__opts__.fuzzyLink&&this.__compiled__["http:"])for(k=this.__opts__.fuzzyIP?this.re.link_fuzzy_global:this.re.link_no_ip_fuzzy_global,k.lastIndex=0;(N=k.exec(p))!==null;)D.push({schema:"",index:N.index+N[1].length,lastIndex:N.index+N[0].length});if(this.__opts__.fuzzyEmail&&this.__compiled__["mailto:"])for(k=this.re.email_fuzzy_global,k.lastIndex=0;(N=k.exec(p))!==null;)T.push({schema:"mailto:",index:N.index+N[1].length,lastIndex:N.index+N[0].length});const w=[0,0,0];let R=0;for(;;){const O=[_[w[0]],T[w[1]],D[w[2]]],F=E(E(O[0],O[1]),O[2]);if(!F)break;if(F===O[0]?w[0]++:F===O[1]?w[1]++:w[2]++,F.index<R)continue;const $=new y(p,F.schema,F.index,F.lastIndex);this.__compiled__[$.schema].normalize($,this),j.push($),R=F.lastIndex}return j.length?j:null},C.prototype.matchAtStart=function(p){if(!p.length)return null;const j=this.re.schema_at_start.exec(p);if(!j)return null;const _=this.testSchemaAt(p,j[2],j[0].length);if(!_)return null;const D=new y(p,j[2],j.index+j[1].length,j.index+j[0].length+_);return this.__compiled__[D.schema].normalize(D,this),D},C.prototype.tlds=function(p,j){return p=Array.isArray(p)?p:[p],j?(this.__tlds__=this.__tlds__.concat(p).sort().filter(function(_,D,T){return _!==T[D-1]}).reverse(),b(this),this):(this.__tlds__=p.slice(),this.__tlds_replaced__=!0,b(this),this)},C.prototype.normalize=function(p){p.schema||(p.url=`http://${p.url}`),p.schema==="mailto:"&&!/^mailto:/i.test(p.url)&&(p.url=`mailto:${p.url}`)},C.prototype.onCompile=function(){},wn=C,wn}var ur;function nh(){if(ur)return we;ur=1;var e=we&&we.__createBinding||(Object.create?(function(b,y,C,v){v===void 0&&(v=C);var p=Object.getOwnPropertyDescriptor(y,C);(!p||("get"in p?!y.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return y[C]}}),Object.defineProperty(b,v,p)}):(function(b,y,C,v){v===void 0&&(v=C),b[v]=y[C]})),t=we&&we.__setModuleDefault||(Object.create?(function(b,y){Object.defineProperty(b,"default",{enumerable:!0,value:y})}):function(b,y){b.default=y}),n=we&&we.__importStar||(function(){var b=function(y){return b=Object.getOwnPropertyNames||function(C){var v=[];for(var p in C)Object.prototype.hasOwnProperty.call(C,p)&&(v[v.length]=p);return v},b(y)};return function(y){if(y&&y.__esModule)return y;var C={};if(y!=null)for(var v=b(y),p=0;p<v.length;p++)v[p]!=="default"&&e(C,y,v[p]);return t(C,y),C}})(),s=we&&we.__importDefault||function(b){return b&&b.__esModule?b:{default:b}};Object.defineProperty(we,"__esModule",{value:!0}),we.default=g;const a=s(Jp()),o=Zp(),i=s(th()),l=n(jl());function u(b,y=!1){return b=(0,o.escapeCarriageReturn)(S(b)),a.default.ansiToJson(b,{json:!0,remove_empty:!0,use_classes:y})}function d(b){let y="";return b.bg&&(y+=`${b.bg}-bg `),b.fg&&(y+=`${b.fg}-fg `),b.decoration&&(y+=`ansi-${b.decoration} `),y===""?null:(y=y.substring(0,y.length-1),y)}function f(b){const y={};switch(b.bg&&(y.backgroundColor=`rgb(${b.bg})`),b.fg&&(y.color=`rgb(${b.fg})`),b.decoration){case"bold":y.fontWeight="bold";break;case"dim":y.opacity="0.5";break;case"italic":y.fontStyle="italic";break;case"hidden":y.visibility="hidden";break;case"strikethrough":y.textDecoration="line-through";break;case"underline":y.textDecoration="underline";break;case"blink":y.textDecoration="blink";break}return y}function h(b,y,C,v){const p=y?null:f(C),j=y?d(C):null;return b?b==="fuzzy"?x(C,v,p,j):m(C,v,p,j):l.createElement("span",{style:p,key:v,className:j},C.content)}function m(b,y,C,v){const p=[],j=/(\s|^)(https?:\/\/(?:www\.|(?!www))[^\s.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})/g;let _=0,D;for(;(D=j.exec(b.content))!==null;){const[,T,N]=D,A=D.index+T.length;A>_&&p.push(b.content.substring(_,A));const k=N.startsWith("www.")?`http://${N}`:N;p.push(l.createElement("a",{key:_,href:k,target:"_blank"},`${N}`)),_=j.lastIndex}return _<b.content.length&&p.push(b.content.substring(_)),l.createElement("span",{style:C,key:y,className:v},p)}function x(b,y,C,v){var p;const j=(0,i.default)({fuzzyEmail:!1}).tlds(["io"],!0);if(!j.pretest(b.content))return l.createElement("span",{style:C,key:y,className:v},b.content);const _=j.match(b.content);if(!_)return l.createElement("span",{style:C,key:y,className:v},b.content);const D=[b.content.substring(0,(p=_[0])===null||p===void 0?void 0:p.index)];return _.forEach((T,N)=>{var A;D.push(l.createElement("a",{href:T.url,target:"_blank",key:N},b.content.substring(T.index,T.lastIndex))),_[N+1]&&D.push(b.content.substring(_[N].lastIndex,(A=_[N+1])===null||A===void 0?void 0:A.index))}),_[_.length-1].lastIndex!==b.content.length&&D.push(b.content.substring(_[_.length-1].lastIndex,b.content.length)),l.createElement("span",{style:C,key:y,className:v},D)}function g(b){const{className:y,useClasses:C,children:v,linkify:p}=b;return l.createElement("code",{className:y},u(v??"",C??!1).map(h.bind(null,p??!1,C??!1)))}function S(b){let y=b;do b=y,y=b.replace(/[^\n]\x08/gm,"");while(y.length<b.length);return b}return we}var sh=nh();const rh=_l(sh),ah=c.lazy(()=>wl(()=>import("./index-Dm53S0up.js"),__vite__mapDeps([0,1,2]))),oh={...Kp,container:"bg-transparent text-xs font-mono leading-relaxed",label:"text-muted-foreground font-medium mr-1",clickableLabel:"text-muted-foreground font-medium mr-1 cursor-pointer",nullValue:"text-muted-foreground italic",undefinedValue:"text-muted-foreground italic",stringValue:"text-foreground",booleanValue:"text-amber-400",numberValue:"text-blue-400",otherValue:"text-muted-foreground",punctuation:"text-muted-foreground",collapseIcon:'text-muted-foreground mr-1 cursor-pointer text-[1.2em] select-none after:content-["▾"]',expandIcon:'text-muted-foreground mr-1 cursor-pointer text-[1.2em] select-none after:content-["▸"]',collapsedContent:'text-muted-foreground mr-1 cursor-pointer after:text-[0.8em] after:content-["…"]'},dr=5120;function ih(e){try{const t=JSON.parse(e);return typeof t=="object"&&t!==null&&("old_string"in t||"new_string"in t)?t:null}catch{return null}}function Nn({children:e,rawContent:t,supportsRawToggle:n,isRaw:s,onToggleRaw:a}){const[o,i]=c.useState(!1),l=t.length>dr,u=l&&!o?t.slice(0,dr):t;return r.jsxs("div",{className:"space-y-1",children:[n&&r.jsx("div",{className:"flex justify-end",children:r.jsx("button",{onClick:a,className:"text-muted-foreground hover:text-foreground text-xs underline",children:s?"Formatted":"Raw"})}),s?r.jsxs(r.Fragment,{children:[r.jsx("pre",{className:"max-h-64 overflow-y-auto text-xs whitespace-pre-wrap",children:u}),l&&!o&&r.jsxs("button",{onClick:()=>i(!0),className:"text-muted-foreground hover:text-foreground text-xs underline",children:["Show full output (",(t.length/1024).toFixed(1),"KB)"]})]}):e]})}function lh({oldValue:e,newValue:t,rawContent:n}){return r.jsx(c.Suspense,{fallback:r.jsx("pre",{className:"max-h-64 overflow-y-auto text-xs whitespace-pre-wrap",children:n}),children:r.jsx(ah,{oldValue:e,newValue:t,splitView:!1,useDarkTheme:!0,hideLineNumbers:!0,showDiffOnly:!0,extraLinesSurroundingDiff:2,styles:{variables:{dark:{diffViewerBackground:"transparent",addedBackground:"rgba(34, 197, 94, 0.1)",addedColor:"rgb(134, 239, 172)",addedGutterBackground:"rgba(34, 197, 94, 0.08)",wordAddedBackground:"rgba(34, 197, 94, 0.2)",removedBackground:"rgba(239, 68, 68, 0.1)",removedColor:"rgb(252, 165, 165)",removedGutterBackground:"rgba(239, 68, 68, 0.08)",wordRemovedBackground:"rgba(239, 68, 68, 0.2)",gutterBackground:"hsl(0 0% 9%)",gutterBackgroundDark:"hsl(0 0% 7%)",gutterColor:"hsl(0 0% 40%)"}}}})})}function _o({content:e,toolName:t,input:n}){const[s,a]=c.useState(!1);if(t==="Edit"&&n){const i=ih(n);if(i)return r.jsx(lh,{oldValue:i.old_string??"",newValue:i.new_string??"",rawContent:e})}const o=Pd(e);if(o==="json"){let i;try{i=JSON.parse(e)}catch{i={}}return r.jsx(Nn,{rawContent:e,supportsRawToggle:!0,isRaw:s,onToggleRaw:()=>a(l=>!l),children:r.jsx(Xp,{data:i,style:oh,shouldExpandNode:Yp})})}return o==="ansi"?r.jsx(Nn,{rawContent:e,supportsRawToggle:!0,isRaw:s,onToggleRaw:()=>a(i=>!i),children:r.jsx("pre",{className:"max-h-64 overflow-y-auto text-xs whitespace-pre-wrap",children:r.jsx(rh,{children:e})})}):r.jsx(Nn,{rawContent:e,supportsRawToggle:!1,isRaw:!0,onToggleRaw:()=>{},children:null})}function ch(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 s=n.error;if(typeof s.message=="string")return s.message}return typeof n.message=="string"?n.message:e}catch{return e}}function uh(e){const t=ch(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 s=t.match(/The ['"`]([^'"`]+)['"`] model is not supported when using Codex with a ChatGPT account\b/i);return s?{message:`${s[1]} isn’t available with a ChatGPT account. Choose another model from the model menu.`,category:"model_unavailable",details:e}:null}const wo="runtimes";function dh({label:e}){const{open:t}=da();return r.jsx("button",{type:"button",onClick:()=>t(wo),className:"text-muted-foreground hover:text-foreground mt-2 block text-xs underline decoration-dotted underline-offset-2 transition-colors",children:e})}function fh({runtime:e,sessionId:t,onRetry:n,onSigninComplete:s}){const[a,o]=c.useState(!1),i=Fl(e,{sessionId:t,onCompleted:()=>o((s==null?void 0:s())??!1)}),l=Rl(e);return i.isSuccess?r.jsxs("div",{className:"mt-3","data-testid":"auth-error-signin-success",children:[r.jsxs("p",{className:"text-status-success-fg flex items-center gap-2 text-sm",role:"status",children:[r.jsx(ot,{"aria-hidden":"true",className:"size-3.5 shrink-0"}),a?"Signed in. Sending your message again…":"Signed in."]}),!a&&n&&r.jsxs(ne,{size:"sm",onClick:n,className:"mt-2 gap-1.5",children:[r.jsx(Ct,{className:"size-3"}),"Retry"]})]}):r.jsxs("div",{className:"mt-3","data-testid":"auth-error-signin",children:[r.jsx("p",{className:"text-muted-foreground mb-2 flex items-center gap-2 text-sm",role:"status",children:i.isPending&&r.jsxs(r.Fragment,{children:[r.jsx(ze,{size:"xs",className:"shrink-0"}),l.signInPending]})}),i.isError&&r.jsx("p",{className:"text-destructive mb-2 text-sm",role:"alert",children:i.errorMessage}),r.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[r.jsxs(ne,{size:"sm",onClick:i.login,disabled:i.isPending,className:"gap-1.5","data-testid":"auth-error-signin-button",children:[r.jsx(fa,{className:"size-3"}),i.isError?"Try again":l.signInLabel]}),n&&r.jsxs(ne,{variant:"outline",size:"sm",onClick:n,className:"gap-1.5",children:[r.jsx(Ct,{className:"size-3"}),"Retry"]})]}),r.jsx(dh,{label:"Use an API key instead"})]})}function fr({onRetry:e}){return r.jsx("div",{className:"mt-3","data-testid":"auth-error-remote-guidance",children:r.jsx(El,{...e?{onRetry:e}:{}})})}function No({onRetry:e}){const{open:t}=da();return r.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[r.jsxs(ne,{size:"sm",onClick:()=>t(wo),className:"gap-1.5",children:[r.jsx(fa,{className:"size-3"}),"Fix sign-in"]}),e&&r.jsxs(ne,{variant:"outline",size:"sm",onClick:e,className:"gap-1.5",children:[r.jsx(Ct,{className:"size-3"}),"Retry"]})]})}function mh({runtime:e,sessionId:t,onRetry:n,renderOffer:s,lead:a,children:o}){const i=!ma(),l=pa(),u=oe(m=>m.setRetryAccount),d=Dt(e).label,f=s({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:it,sessionId:t}),n())}}),h=m=>r.jsxs("section",{"aria-label":"Other ways",children:[r.jsx("p",{className:"text-muted-foreground text-2xs font-medium tracking-wide uppercase",children:"Other ways"}),m]});return a?r.jsxs("div",{className:"mt-3 space-y-3","data-testid":"auth-error-credits-first",children:[f,h(o),r.jsx(Dl,{ollama:Al(e)==="provider-picker",remote:i})]}):r.jsxs("div",{"data-testid":"auth-error-credits-other-way",children:[o,r.jsx("div",{className:"mt-3",children:h(f)})]})}function ph({sessionId:e,onRetry:t,onSigninComplete:n}){var h;const{sessions:s,isLoading:a}=Zn(),o=ma(),i=(h=s.find(m=>m.id===e))==null?void 0:h.runtime,l=Nl(i),u=oa(),d=i!==void 0&&u!==null&&(l==="lead"||l==="other-way");if(!o&&!d)return r.jsx(fr,{onRetry:t});if(a)return null;const f=o?!i||!Tl(i)?r.jsx(No,{onRetry:t}):r.jsx(fh,{runtime:i,sessionId:e,onRetry:t,onSigninComplete:n}):r.jsx(fr,{onRetry:t});return d&&i&&u?r.jsx(mh,{runtime:i,sessionId:e,onRetry:t,renderOffer:u,lead:l==="lead",children:f}):f}function hh({sessionId:e,onRetry:t,onSigninComplete:n}){return e?r.jsx(ph,{sessionId:e,onRetry:t,onSigninComplete:n}):r.jsx(No,{onRetry:t})}const gh="credits_unavailable",xh="folder-sign-in";function bh({onRetry:e,sessionId:t,runtimeLabel:n,reason:s}){const a=oe(g=>g.setRetryAccount),o=Ml(),i=pa(),l=ha(),u=tn(t),d=Zt(u??null);if(!e)return null;const f=yh(d),h=n?`your ${n}`:"your own",m=()=>{if(d!==void 0){if(f==="pick-for-send"){t&&a({id:vt,sessionId:t}),e();return}i.mutate({runtime:d.type,useCredits:!1},{onSuccess:()=>f==="new-conversation"?l(void 0,{runtime:d.type}):e()})}},x=()=>{t&&o.mutate(t,{onSuccess:({launch:g})=>{g!=null&&g.ok&&a({id:g.accountId,sessionId:t}),e()}})};return r.jsxs("div",{className:"mt-2 flex flex-col gap-2","data-testid":"credits-error-actions",children:[r.jsxs("div",{className:"flex flex-wrap gap-2",children:[r.jsxs(ne,{size:"sm",variant:"outline",onClick:e,className:"gap-1.5",children:[r.jsx(Ct,{className:"size-3"}),"Retry"]}),t&&r.jsx(ne,{size:"sm",variant:"outline",onClick:m,disabled:d===void 0||i.isPending,children:f==="new-conversation"?`Start a new chat on ${h} sign-in`:`Use ${h} sign-in`}),t&&s===xh&&r.jsx(ne,{size:"sm",variant:"outline",onClick:x,disabled:o.isPending,children:"Don’t use credits in this project"})]}),t&&f==="whole-runtime"&&r.jsxs("p",{className:"text-muted-foreground text-xs","data-testid":"credits-own-sign-in-reach",children:["This moves all ",n??"its"," chats to ",h," sign-in, not just this one."]}),o.error&&r.jsx("p",{className:"text-muted-foreground text-xs",role:"status",children:o.error.message}),i.isError&&r.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 yh(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 vh({category:e,onChooseModel:t}){return t?r.jsxs(ne,{size:"sm",onClick:t,className:"mt-3 gap-1.5",children:[r.jsx(ga,{className:"size-3"}),e==="runtime_update_required"?"Choose another model":"Choose model"]}):null}const kh="your agent",Ch="agent",mr={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}},Sh=new Set(["max_turns","budget_exceeded","output_format_error","auth_error"]);function jh(e){return`Sign in to ${e??kh} again`}function _h(e){return`Your ${e??Ch} login stopped working. Sign in again to continue.`}const wh="rate_limit";function sn(e){const{code:t,at:n,sessionId:s,reason:a}=e;return t===xa&&a?r.jsx(Ya,{agentId:a}):t===wh&&s?r.jsx(mm,{sessionId:s,at:n??"",fallback:r.jsx(pr,{...e})}):r.jsx(pr,{...e})}function pr({message:e,category:t,details:n,onRetry:s,heading:a,subtext:o,runtimeLabel:i,sessionId:l,onSigninComplete:u,onChooseModel:d,code:f,reason:h}){const[m,x]=c.useState(!1),g=f===gh,S=c.useMemo(()=>uh(e),[e]),b=(S==null?void 0:S.category)??t,y=(S==null?void 0:S.message)??e,C=S?n!=null&&n.includes(S.details??"")?n:[n,S.details].filter(Boolean).join(`
44
+ `+n(a.slice(o+1))}return pt.exports=e,pt.exports.escapeCarriageReturn=e,pt.exports.escapeCarriageReturnSafe=s,pt.exports}var Pe={},lr;function eh(){if(lr)return Pe;lr=1;var e=/[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,t=/[\0-\x1F\x7F-\x9F]/,n=/[\xAD\u0600-\u0605\u061C\u06DD\u070F\u0890\u0891\u08E2\u180E\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF\uFFF9-\uFFFB]|\uD804[\uDCBD\uDCCD]|\uD80D[\uDC30-\uDC3F]|\uD82F[\uDCA0-\uDCA3]|\uD834[\uDD73-\uDD7A]|\uDB40[\uDC01\uDC20-\uDC7F]/,s=/[!-#%-\*,-\/:;\?@\[-\]_\{\}\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061D-\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1B7D\u1B7E\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u2E52-\u2E5D\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD803[\uDEAD\uDF55-\uDF59\uDF86-\uDF89]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5A\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDEB9\uDF3C-\uDF3E]|\uD806[\uDC3B\uDD44-\uDD46\uDDE2\uDE3F-\uDE46\uDE9A-\uDE9C\uDE9E-\uDEA2\uDF00-\uDF09]|\uD807[\uDC41-\uDC45\uDC70\uDC71\uDEF7\uDEF8\uDF43-\uDF4F\uDFFF]|\uD809[\uDC70-\uDC74]|\uD80B[\uDFF1\uDFF2]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD81B[\uDE97-\uDE9A\uDFE2]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]/,a=/[\$\+<->\^`\|~\xA2-\xA6\xA8\xA9\xAC\xAE-\xB1\xB4\xB8\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0384\u0385\u03F6\u0482\u058D-\u058F\u0606-\u0608\u060B\u060E\u060F\u06DE\u06E9\u06FD\u06FE\u07F6\u07FE\u07FF\u0888\u09F2\u09F3\u09FA\u09FB\u0AF1\u0B70\u0BF3-\u0BFA\u0C7F\u0D4F\u0D79\u0E3F\u0F01-\u0F03\u0F13\u0F15-\u0F17\u0F1A-\u0F1F\u0F34\u0F36\u0F38\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE\u0FCF\u0FD5-\u0FD8\u109E\u109F\u1390-\u1399\u166D\u17DB\u1940\u19DE-\u19FF\u1B61-\u1B6A\u1B74-\u1B7C\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u2044\u2052\u207A-\u207C\u208A-\u208C\u20A0-\u20C0\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F\u218A\u218B\u2190-\u2307\u230C-\u2328\u232B-\u2426\u2440-\u244A\u249C-\u24E9\u2500-\u2767\u2794-\u27C4\u27C7-\u27E5\u27F0-\u2982\u2999-\u29D7\u29DC-\u29FB\u29FE-\u2B73\u2B76-\u2B95\u2B97-\u2BFF\u2CE5-\u2CEA\u2E50\u2E51\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFF\u3004\u3012\u3013\u3020\u3036\u3037\u303E\u303F\u309B\u309C\u3190\u3191\u3196-\u319F\u31C0-\u31E3\u31EF\u3200-\u321E\u322A-\u3247\u3250\u3260-\u327F\u328A-\u32B0\u32C0-\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA700-\uA716\uA720\uA721\uA789\uA78A\uA828-\uA82B\uA836-\uA839\uAA77-\uAA79\uAB5B\uAB6A\uAB6B\uFB29\uFBB2-\uFBC2\uFD40-\uFD4F\uFDCF\uFDFC-\uFDFF\uFE62\uFE64-\uFE66\uFE69\uFF04\uFF0B\uFF1C-\uFF1E\uFF3E\uFF40\uFF5C\uFF5E\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFFC\uFFFD]|\uD800[\uDD37-\uDD3F\uDD79-\uDD89\uDD8C-\uDD8E\uDD90-\uDD9C\uDDA0\uDDD0-\uDDFC]|\uD802[\uDC77\uDC78\uDEC8]|\uD805\uDF3F|\uD807[\uDFD5-\uDFF1]|\uD81A[\uDF3C-\uDF3F\uDF45]|\uD82F\uDC9C|\uD833[\uDF50-\uDFC3]|\uD834[\uDC00-\uDCF5\uDD00-\uDD26\uDD29-\uDD64\uDD6A-\uDD6C\uDD83\uDD84\uDD8C-\uDDA9\uDDAE-\uDDEA\uDE00-\uDE41\uDE45\uDF00-\uDF56]|\uD835[\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3]|\uD836[\uDC00-\uDDFF\uDE37-\uDE3A\uDE6D-\uDE74\uDE76-\uDE83\uDE85\uDE86]|\uD838[\uDD4F\uDEFF]|\uD83B[\uDCAC\uDCB0\uDD2E\uDEF0\uDEF1]|\uD83C[\uDC00-\uDC2B\uDC30-\uDC93\uDCA0-\uDCAE\uDCB1-\uDCBF\uDCC1-\uDCCF\uDCD1-\uDCF5\uDD0D-\uDDAD\uDDE6-\uDE02\uDE10-\uDE3B\uDE40-\uDE48\uDE50\uDE51\uDE60-\uDE65\uDF00-\uDFFF]|\uD83D[\uDC00-\uDED7\uDEDC-\uDEEC\uDEF0-\uDEFC\uDF00-\uDF76\uDF7B-\uDFD9\uDFE0-\uDFEB\uDFF0]|\uD83E[\uDC00-\uDC0B\uDC10-\uDC47\uDC50-\uDC59\uDC60-\uDC87\uDC90-\uDCAD\uDCB0\uDCB1\uDD00-\uDE53\uDE60-\uDE6D\uDE70-\uDE7C\uDE80-\uDE88\uDE90-\uDEBD\uDEBF-\uDEC5\uDECE-\uDEDB\uDEE0-\uDEE8\uDEF0-\uDEF8\uDF00-\uDF92\uDF94-\uDFCA]/,o=/[ \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/;return Pe.Any=e,Pe.Cc=t,Pe.Cf=n,Pe.P=s,Pe.S=a,Pe.Z=o,Pe}var wn,cr;function th(){if(cr)return wn;cr=1;var e=eh();function t(v){const p={};v=v||{},p.src_Any=e.Any.source,p.src_Cc=e.Cc.source,p.src_Z=e.Z.source,p.src_P=e.P.source,p.src_ZPCc=[p.src_Z,p.src_P,p.src_Cc].join("|"),p.src_ZCc=[p.src_Z,p.src_Cc].join("|");const j="[><|]";return p.src_pseudo_letter=`(?:(?!${j}|${p.src_ZPCc})${p.src_Any})`,p.src_ip4="(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)",p.src_auth=`(?:(?:(?!${p.src_ZCc}|[@/\\[\\]()]).){1,50}@)?`,p.src_port="(?::(?:6(?:[0-4]\\d{3}|5(?:[0-4]\\d{2}|5(?:[0-2]\\d|3[0-5])))|[1-5]?\\d{1,4}))?",p.src_host_terminator=`(?=$|${j}|${p.src_ZPCc})(?!${v["---"]?"-(?!--)|":"-|"}_|:\\d|\\.-|\\.(?!$|${p.src_ZPCc}))`,p.src_path=`(?:[/?#](?:(?!${p.src_ZCc}|${j}|[()[\\]{}.,"'?!\\-;]).|\\[(?:(?!${p.src_ZCc}|\\]).)*\\]|\\((?:(?!${p.src_ZCc}|[)]).)*\\)|\\{(?:(?!${p.src_ZCc}|[}]).)*\\}|\\"(?:(?!${p.src_ZCc}|["]).)+\\"|\\'(?:(?!${p.src_ZCc}|[']).)+\\'|\\'(?=${p.src_pseudo_letter}|[-])|\\.{2,}[a-zA-Z0-9%/&]|\\.(?!${p.src_ZCc}|[.]|$)|`+(v["---"]?"\\-(?!--(?:[^-]|$))(?:-*)|":"\\-+|")+`,(?!${p.src_ZCc}|$)|;(?!${p.src_ZCc}|$)|\\!+(?!${p.src_ZCc}|[!]|$)|\\?(?!${p.src_ZCc}|[?]|$))+|\\/)?`,p.src_email_name='[\\-;:&=\\+\\$,\\.a-zA-Z0-9_][\\-;:&=\\+\\$,\\"\\.a-zA-Z0-9_]{0,63}',p.src_xn="xn--[a-z0-9\\-]{1,59}",p.src_domain_root="(?:"+p.src_xn+`|${p.src_pseudo_letter}{1,63})`,p.src_domain="(?:"+p.src_xn+`|(?:${p.src_pseudo_letter})|(?:${p.src_pseudo_letter}(?:-|${p.src_pseudo_letter}){0,61}${p.src_pseudo_letter}))`,p.src_host=`(?:(?:(?:(?:${p.src_domain})\\.)*${p.src_domain}))`,p.tpl_host_fuzzy="(?:"+p.src_ip4+`|(?:(?:(?:${p.src_domain})\\.)+(?:%TLDS%)))`,p.tpl_host_no_ip_fuzzy=`(?:(?:(?:${p.src_domain})\\.)+(?:%TLDS%))`,p.src_host_strict=p.src_host+p.src_host_terminator,p.tpl_host_fuzzy_strict=p.tpl_host_fuzzy+p.src_host_terminator,p.src_host_port_strict=p.src_host+p.src_port+p.src_host_terminator,p.tpl_host_port_fuzzy_strict=p.tpl_host_fuzzy+p.src_port+p.src_host_terminator,p.tpl_host_port_no_ip_fuzzy_strict=p.tpl_host_no_ip_fuzzy+p.src_port+p.src_host_terminator,p.tpl_host_fuzzy_test=`localhost|www\\.|\\.\\d{1,3}\\.|(?:\\.(?:%TLDS%)(?:${p.src_ZPCc}|>|$))`,p.tpl_email_fuzzy=`(^|${j}|"|\\(|${p.src_ZCc})(${p.src_email_name}@${p.tpl_host_fuzzy_strict})`,p.tpl_link_fuzzy=`(^|(?![.:/\\-_@])(?:[$+<=>^\`||]|${p.src_ZPCc}))((?![$+<=>^\`||])${p.tpl_host_port_fuzzy_strict}${p.src_path})`,p.tpl_link_no_ip_fuzzy=`(^|(?![.:/\\-_@])(?:[$+<=>^\`||]|${p.src_ZPCc}))((?![$+<=>^\`||])${p.tpl_host_port_no_ip_fuzzy_strict}${p.src_path})`,p}function n(v){return Array.prototype.slice.call(arguments,1).forEach(function(j){j&&Object.keys(j).forEach(function(_){v[_]=j[_]})}),v}function s(v){return Object.prototype.toString.call(v)}function a(v){return s(v)==="[object String]"}function o(v){return s(v)==="[object Object]"}function i(v){return s(v)==="[object RegExp]"}function l(v){return s(v)==="[object Function]"}function u(v){return v.replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")}const d={fuzzyLink:!0,fuzzyEmail:!0,fuzzyIP:!1};function f(v){return Object.keys(v||{}).reduce(function(p,j){return p||d.hasOwnProperty(j)},!1)}const h={"http:":{validate:function(v,p,j){const _=v.slice(p);return j.re.http||(j.re.http=new RegExp(`^\\/\\/${j.re.src_auth}${j.re.src_host_port_strict}${j.re.src_path}`,"i")),j.re.http.test(_)?_.match(j.re.http)[0].length:0}},"https:":"http:","ftp:":"http:","//":{validate:function(v,p,j){const _=v.slice(p);return j.re.no_http||(j.re.no_http=new RegExp("^"+j.re.src_auth+`(?:localhost|(?:(?:${j.re.src_domain})\\.)+${j.re.src_domain_root})`+j.re.src_port+j.re.src_host_terminator+j.re.src_path,"i")),j.re.no_http.test(_)?p>=3&&v[p-3]===":"||p>=3&&v[p-3]==="/"?0:_.match(j.re.no_http)[0].length:0}},"mailto:":{validate:function(v,p,j){const _=v.slice(p);return j.re.mailto||(j.re.mailto=new RegExp(`^${j.re.src_email_name}@${j.re.src_host_strict}`,"i")),j.re.mailto.test(_)?_.match(j.re.mailto)[0].length:0}}},m="a[cdefgilmnoqrstuwxz]|b[abdefghijmnorstvwyz]|c[acdfghiklmnoruvwxyz]|d[ejkmoz]|e[cegrstu]|f[ijkmor]|g[abdefghilmnpqrstuwy]|h[kmnrtu]|i[delmnoqrst]|j[emop]|k[eghimnprwyz]|l[abcikrstuvy]|m[acdeghklmnopqrstuvwxyz]|n[acefgilopruz]|om|p[aefghklmnrstwy]|qa|r[eosuw]|s[abcdeghijklmnortuvxyz]|t[cdfghjklmnortvwz]|u[agksyz]|v[aceginu]|w[fs]|y[et]|z[amw]",x="biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф".split("|");function g(v){return function(p,j){const _=p.slice(j);return v.test(_)?_.match(v)[0].length:0}}function S(){return function(v,p){p.normalize(v)}}function b(v){const p=v.re=t(v.__opts__),j=v.__tlds__.slice();v.onCompile(),v.__tlds_replaced__||j.push(m),j.push(p.src_xn),p.src_tlds=j.join("|");function _(A){return A.replace("%TLDS%",p.src_tlds)}p.email_fuzzy=RegExp(_(p.tpl_email_fuzzy),"i"),p.email_fuzzy_global=RegExp(_(p.tpl_email_fuzzy),"ig"),p.link_fuzzy=RegExp(_(p.tpl_link_fuzzy),"i"),p.link_fuzzy_global=RegExp(_(p.tpl_link_fuzzy),"ig"),p.link_no_ip_fuzzy=RegExp(_(p.tpl_link_no_ip_fuzzy),"i"),p.link_no_ip_fuzzy_global=RegExp(_(p.tpl_link_no_ip_fuzzy),"ig"),p.host_fuzzy_test=RegExp(_(p.tpl_host_fuzzy_test),"i");const D=[];v.__compiled__={};function T(A,k){throw new Error(`(LinkifyIt) Invalid schema "${A}": ${k}`)}Object.keys(v.__schemas__).forEach(function(A){const k=v.__schemas__[A];if(k===null)return;const E={validate:null,link:null};if(v.__compiled__[A]=E,o(k)){i(k.validate)?E.validate=g(k.validate):l(k.validate)?E.validate=k.validate:T(A,k),l(k.normalize)?E.normalize=k.normalize:k.normalize?T(A,k):E.normalize=S();return}if(a(k)){D.push(A);return}T(A,k)}),D.forEach(function(A){v.__compiled__[v.__schemas__[A]]&&(v.__compiled__[A].validate=v.__compiled__[v.__schemas__[A]].validate,v.__compiled__[A].normalize=v.__compiled__[v.__schemas__[A]].normalize)}),v.__compiled__[""]={validate:null,normalize:S()};const N=Object.keys(v.__compiled__).filter(function(A){return A.length>0&&v.__compiled__[A]}).map(u).join("|");v.re.schema_test=RegExp(`(^|(?!_)(?:[><|]|${p.src_ZPCc}))(${N})`,"i"),v.re.schema_search=RegExp(`(^|(?!_)(?:[><|]|${p.src_ZPCc}))(${N})`,"ig"),v.re.schema_at_start=RegExp(`^${v.re.schema_search.source}`,"i"),v.re.pretest=RegExp(`(${v.re.schema_test.source})|(${v.re.host_fuzzy_test.source})|@`,"i")}function y(v,p,j,_){const D=v.slice(j,_);this.schema=p.toLowerCase(),this.index=j,this.lastIndex=_,this.raw=D,this.text=D,this.url=D}function C(v,p){if(!(this instanceof C))return new C(v,p);p||f(v)&&(p=v,v={}),this.__opts__=n({},d,p),this.__schemas__=n({},h,v),this.__compiled__={},this.__tlds__=x,this.__tlds_replaced__=!1,this.re={},b(this)}return C.prototype.add=function(p,j){return this.__schemas__[p]=j,b(this),this},C.prototype.set=function(p){return this.__opts__=n(this.__opts__,p),this},C.prototype.test=function(p){if(!p.length)return!1;let j,_;if(this.re.schema_test.test(p)){for(_=this.re.schema_search,_.lastIndex=0;(j=_.exec(p))!==null;)if(this.testSchemaAt(p,j[2],_.lastIndex))return!0}return!!(this.__opts__.fuzzyLink&&this.__compiled__["http:"]&&p.search(this.re.host_fuzzy_test)>=0&&p.match(this.__opts__.fuzzyIP?this.re.link_fuzzy:this.re.link_no_ip_fuzzy)!==null||this.__opts__.fuzzyEmail&&this.__compiled__["mailto:"]&&p.indexOf("@")>=0&&p.match(this.re.email_fuzzy)!==null)},C.prototype.pretest=function(p){return this.re.pretest.test(p)},C.prototype.testSchemaAt=function(p,j,_){return this.__compiled__[j.toLowerCase()]?this.__compiled__[j.toLowerCase()].validate(p,_,this):0},C.prototype.match=function(p){const j=[],_=[],D=[],T=[];let N,A,k;function E(O,F){return O?F?O.index!==F.index?O.index<F.index?O:F:O.lastIndex>=F.lastIndex?O:F:O:F}if(!p.length)return null;if(this.re.schema_test.test(p))for(k=this.re.schema_search,k.lastIndex=0;(N=k.exec(p))!==null;)A=this.testSchemaAt(p,N[2],k.lastIndex),A&&_.push({schema:N[2],index:N.index+N[1].length,lastIndex:N.index+N[0].length+A});if(this.__opts__.fuzzyLink&&this.__compiled__["http:"])for(k=this.__opts__.fuzzyIP?this.re.link_fuzzy_global:this.re.link_no_ip_fuzzy_global,k.lastIndex=0;(N=k.exec(p))!==null;)D.push({schema:"",index:N.index+N[1].length,lastIndex:N.index+N[0].length});if(this.__opts__.fuzzyEmail&&this.__compiled__["mailto:"])for(k=this.re.email_fuzzy_global,k.lastIndex=0;(N=k.exec(p))!==null;)T.push({schema:"mailto:",index:N.index+N[1].length,lastIndex:N.index+N[0].length});const w=[0,0,0];let R=0;for(;;){const O=[_[w[0]],T[w[1]],D[w[2]]],F=E(E(O[0],O[1]),O[2]);if(!F)break;if(F===O[0]?w[0]++:F===O[1]?w[1]++:w[2]++,F.index<R)continue;const $=new y(p,F.schema,F.index,F.lastIndex);this.__compiled__[$.schema].normalize($,this),j.push($),R=F.lastIndex}return j.length?j:null},C.prototype.matchAtStart=function(p){if(!p.length)return null;const j=this.re.schema_at_start.exec(p);if(!j)return null;const _=this.testSchemaAt(p,j[2],j[0].length);if(!_)return null;const D=new y(p,j[2],j.index+j[1].length,j.index+j[0].length+_);return this.__compiled__[D.schema].normalize(D,this),D},C.prototype.tlds=function(p,j){return p=Array.isArray(p)?p:[p],j?(this.__tlds__=this.__tlds__.concat(p).sort().filter(function(_,D,T){return _!==T[D-1]}).reverse(),b(this),this):(this.__tlds__=p.slice(),this.__tlds_replaced__=!0,b(this),this)},C.prototype.normalize=function(p){p.schema||(p.url=`http://${p.url}`),p.schema==="mailto:"&&!/^mailto:/i.test(p.url)&&(p.url=`mailto:${p.url}`)},C.prototype.onCompile=function(){},wn=C,wn}var ur;function nh(){if(ur)return we;ur=1;var e=we&&we.__createBinding||(Object.create?(function(b,y,C,v){v===void 0&&(v=C);var p=Object.getOwnPropertyDescriptor(y,C);(!p||("get"in p?!y.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return y[C]}}),Object.defineProperty(b,v,p)}):(function(b,y,C,v){v===void 0&&(v=C),b[v]=y[C]})),t=we&&we.__setModuleDefault||(Object.create?(function(b,y){Object.defineProperty(b,"default",{enumerable:!0,value:y})}):function(b,y){b.default=y}),n=we&&we.__importStar||(function(){var b=function(y){return b=Object.getOwnPropertyNames||function(C){var v=[];for(var p in C)Object.prototype.hasOwnProperty.call(C,p)&&(v[v.length]=p);return v},b(y)};return function(y){if(y&&y.__esModule)return y;var C={};if(y!=null)for(var v=b(y),p=0;p<v.length;p++)v[p]!=="default"&&e(C,y,v[p]);return t(C,y),C}})(),s=we&&we.__importDefault||function(b){return b&&b.__esModule?b:{default:b}};Object.defineProperty(we,"__esModule",{value:!0}),we.default=g;const a=s(Jp()),o=Zp(),i=s(th()),l=n(jl());function u(b,y=!1){return b=(0,o.escapeCarriageReturn)(S(b)),a.default.ansiToJson(b,{json:!0,remove_empty:!0,use_classes:y})}function d(b){let y="";return b.bg&&(y+=`${b.bg}-bg `),b.fg&&(y+=`${b.fg}-fg `),b.decoration&&(y+=`ansi-${b.decoration} `),y===""?null:(y=y.substring(0,y.length-1),y)}function f(b){const y={};switch(b.bg&&(y.backgroundColor=`rgb(${b.bg})`),b.fg&&(y.color=`rgb(${b.fg})`),b.decoration){case"bold":y.fontWeight="bold";break;case"dim":y.opacity="0.5";break;case"italic":y.fontStyle="italic";break;case"hidden":y.visibility="hidden";break;case"strikethrough":y.textDecoration="line-through";break;case"underline":y.textDecoration="underline";break;case"blink":y.textDecoration="blink";break}return y}function h(b,y,C,v){const p=y?null:f(C),j=y?d(C):null;return b?b==="fuzzy"?x(C,v,p,j):m(C,v,p,j):l.createElement("span",{style:p,key:v,className:j},C.content)}function m(b,y,C,v){const p=[],j=/(\s|^)(https?:\/\/(?:www\.|(?!www))[^\s.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})/g;let _=0,D;for(;(D=j.exec(b.content))!==null;){const[,T,N]=D,A=D.index+T.length;A>_&&p.push(b.content.substring(_,A));const k=N.startsWith("www.")?`http://${N}`:N;p.push(l.createElement("a",{key:_,href:k,target:"_blank"},`${N}`)),_=j.lastIndex}return _<b.content.length&&p.push(b.content.substring(_)),l.createElement("span",{style:C,key:y,className:v},p)}function x(b,y,C,v){var p;const j=(0,i.default)({fuzzyEmail:!1}).tlds(["io"],!0);if(!j.pretest(b.content))return l.createElement("span",{style:C,key:y,className:v},b.content);const _=j.match(b.content);if(!_)return l.createElement("span",{style:C,key:y,className:v},b.content);const D=[b.content.substring(0,(p=_[0])===null||p===void 0?void 0:p.index)];return _.forEach((T,N)=>{var A;D.push(l.createElement("a",{href:T.url,target:"_blank",key:N},b.content.substring(T.index,T.lastIndex))),_[N+1]&&D.push(b.content.substring(_[N].lastIndex,(A=_[N+1])===null||A===void 0?void 0:A.index))}),_[_.length-1].lastIndex!==b.content.length&&D.push(b.content.substring(_[_.length-1].lastIndex,b.content.length)),l.createElement("span",{style:C,key:y,className:v},D)}function g(b){const{className:y,useClasses:C,children:v,linkify:p}=b;return l.createElement("code",{className:y},u(v??"",C??!1).map(h.bind(null,p??!1,C??!1)))}function S(b){let y=b;do b=y,y=b.replace(/[^\n]\x08/gm,"");while(y.length<b.length);return b}return we}var sh=nh();const rh=_l(sh),ah=c.lazy(()=>wl(()=>import("./index-BRGOMmOM.js"),__vite__mapDeps([0,1,2]))),oh={...Kp,container:"bg-transparent text-xs font-mono leading-relaxed",label:"text-muted-foreground font-medium mr-1",clickableLabel:"text-muted-foreground font-medium mr-1 cursor-pointer",nullValue:"text-muted-foreground italic",undefinedValue:"text-muted-foreground italic",stringValue:"text-foreground",booleanValue:"text-amber-400",numberValue:"text-blue-400",otherValue:"text-muted-foreground",punctuation:"text-muted-foreground",collapseIcon:'text-muted-foreground mr-1 cursor-pointer text-[1.2em] select-none after:content-["▾"]',expandIcon:'text-muted-foreground mr-1 cursor-pointer text-[1.2em] select-none after:content-["▸"]',collapsedContent:'text-muted-foreground mr-1 cursor-pointer after:text-[0.8em] after:content-["…"]'},dr=5120;function ih(e){try{const t=JSON.parse(e);return typeof t=="object"&&t!==null&&("old_string"in t||"new_string"in t)?t:null}catch{return null}}function Nn({children:e,rawContent:t,supportsRawToggle:n,isRaw:s,onToggleRaw:a}){const[o,i]=c.useState(!1),l=t.length>dr,u=l&&!o?t.slice(0,dr):t;return r.jsxs("div",{className:"space-y-1",children:[n&&r.jsx("div",{className:"flex justify-end",children:r.jsx("button",{onClick:a,className:"text-muted-foreground hover:text-foreground text-xs underline",children:s?"Formatted":"Raw"})}),s?r.jsxs(r.Fragment,{children:[r.jsx("pre",{className:"max-h-64 overflow-y-auto text-xs whitespace-pre-wrap",children:u}),l&&!o&&r.jsxs("button",{onClick:()=>i(!0),className:"text-muted-foreground hover:text-foreground text-xs underline",children:["Show full output (",(t.length/1024).toFixed(1),"KB)"]})]}):e]})}function lh({oldValue:e,newValue:t,rawContent:n}){return r.jsx(c.Suspense,{fallback:r.jsx("pre",{className:"max-h-64 overflow-y-auto text-xs whitespace-pre-wrap",children:n}),children:r.jsx(ah,{oldValue:e,newValue:t,splitView:!1,useDarkTheme:!0,hideLineNumbers:!0,showDiffOnly:!0,extraLinesSurroundingDiff:2,styles:{variables:{dark:{diffViewerBackground:"transparent",addedBackground:"rgba(34, 197, 94, 0.1)",addedColor:"rgb(134, 239, 172)",addedGutterBackground:"rgba(34, 197, 94, 0.08)",wordAddedBackground:"rgba(34, 197, 94, 0.2)",removedBackground:"rgba(239, 68, 68, 0.1)",removedColor:"rgb(252, 165, 165)",removedGutterBackground:"rgba(239, 68, 68, 0.08)",wordRemovedBackground:"rgba(239, 68, 68, 0.2)",gutterBackground:"hsl(0 0% 9%)",gutterBackgroundDark:"hsl(0 0% 7%)",gutterColor:"hsl(0 0% 40%)"}}}})})}function _o({content:e,toolName:t,input:n}){const[s,a]=c.useState(!1);if(t==="Edit"&&n){const i=ih(n);if(i)return r.jsx(lh,{oldValue:i.old_string??"",newValue:i.new_string??"",rawContent:e})}const o=Pd(e);if(o==="json"){let i;try{i=JSON.parse(e)}catch{i={}}return r.jsx(Nn,{rawContent:e,supportsRawToggle:!0,isRaw:s,onToggleRaw:()=>a(l=>!l),children:r.jsx(Xp,{data:i,style:oh,shouldExpandNode:Yp})})}return o==="ansi"?r.jsx(Nn,{rawContent:e,supportsRawToggle:!0,isRaw:s,onToggleRaw:()=>a(i=>!i),children:r.jsx("pre",{className:"max-h-64 overflow-y-auto text-xs whitespace-pre-wrap",children:r.jsx(rh,{children:e})})}):r.jsx(Nn,{rawContent:e,supportsRawToggle:!1,isRaw:!0,onToggleRaw:()=>{},children:null})}function ch(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 s=n.error;if(typeof s.message=="string")return s.message}return typeof n.message=="string"?n.message:e}catch{return e}}function uh(e){const t=ch(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 s=t.match(/The ['"`]([^'"`]+)['"`] model is not supported when using Codex with a ChatGPT account\b/i);return s?{message:`${s[1]} isn’t available with a ChatGPT account. Choose another model from the model menu.`,category:"model_unavailable",details:e}:null}const wo="runtimes";function dh({label:e}){const{open:t}=da();return r.jsx("button",{type:"button",onClick:()=>t(wo),className:"text-muted-foreground hover:text-foreground mt-2 block text-xs underline decoration-dotted underline-offset-2 transition-colors",children:e})}function fh({runtime:e,sessionId:t,onRetry:n,onSigninComplete:s}){const[a,o]=c.useState(!1),i=Fl(e,{sessionId:t,onCompleted:()=>o((s==null?void 0:s())??!1)}),l=Rl(e);return i.isSuccess?r.jsxs("div",{className:"mt-3","data-testid":"auth-error-signin-success",children:[r.jsxs("p",{className:"text-status-success-fg flex items-center gap-2 text-sm",role:"status",children:[r.jsx(ot,{"aria-hidden":"true",className:"size-3.5 shrink-0"}),a?"Signed in. Sending your message again…":"Signed in."]}),!a&&n&&r.jsxs(ne,{size:"sm",onClick:n,className:"mt-2 gap-1.5",children:[r.jsx(Ct,{className:"size-3"}),"Retry"]})]}):r.jsxs("div",{className:"mt-3","data-testid":"auth-error-signin",children:[r.jsx("p",{className:"text-muted-foreground mb-2 flex items-center gap-2 text-sm",role:"status",children:i.isPending&&r.jsxs(r.Fragment,{children:[r.jsx(ze,{size:"xs",className:"shrink-0"}),l.signInPending]})}),i.isError&&r.jsx("p",{className:"text-destructive mb-2 text-sm",role:"alert",children:i.errorMessage}),r.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[r.jsxs(ne,{size:"sm",onClick:i.login,disabled:i.isPending,className:"gap-1.5","data-testid":"auth-error-signin-button",children:[r.jsx(fa,{className:"size-3"}),i.isError?"Try again":l.signInLabel]}),n&&r.jsxs(ne,{variant:"outline",size:"sm",onClick:n,className:"gap-1.5",children:[r.jsx(Ct,{className:"size-3"}),"Retry"]})]}),r.jsx(dh,{label:"Use an API key instead"})]})}function fr({onRetry:e}){return r.jsx("div",{className:"mt-3","data-testid":"auth-error-remote-guidance",children:r.jsx(El,{...e?{onRetry:e}:{}})})}function No({onRetry:e}){const{open:t}=da();return r.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[r.jsxs(ne,{size:"sm",onClick:()=>t(wo),className:"gap-1.5",children:[r.jsx(fa,{className:"size-3"}),"Fix sign-in"]}),e&&r.jsxs(ne,{variant:"outline",size:"sm",onClick:e,className:"gap-1.5",children:[r.jsx(Ct,{className:"size-3"}),"Retry"]})]})}function mh({runtime:e,sessionId:t,onRetry:n,renderOffer:s,lead:a,children:o}){const i=!ma(),l=pa(),u=oe(m=>m.setRetryAccount),d=Dt(e).label,f=s({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:it,sessionId:t}),n())}}),h=m=>r.jsxs("section",{"aria-label":"Other ways",children:[r.jsx("p",{className:"text-muted-foreground text-2xs font-medium tracking-wide uppercase",children:"Other ways"}),m]});return a?r.jsxs("div",{className:"mt-3 space-y-3","data-testid":"auth-error-credits-first",children:[f,h(o),r.jsx(Dl,{ollama:Al(e)==="provider-picker",remote:i})]}):r.jsxs("div",{"data-testid":"auth-error-credits-other-way",children:[o,r.jsx("div",{className:"mt-3",children:h(f)})]})}function ph({sessionId:e,onRetry:t,onSigninComplete:n}){var h;const{sessions:s,isLoading:a}=Zn(),o=ma(),i=(h=s.find(m=>m.id===e))==null?void 0:h.runtime,l=Nl(i),u=oa(),d=i!==void 0&&u!==null&&(l==="lead"||l==="other-way");if(!o&&!d)return r.jsx(fr,{onRetry:t});if(a)return null;const f=o?!i||!Tl(i)?r.jsx(No,{onRetry:t}):r.jsx(fh,{runtime:i,sessionId:e,onRetry:t,onSigninComplete:n}):r.jsx(fr,{onRetry:t});return d&&i&&u?r.jsx(mh,{runtime:i,sessionId:e,onRetry:t,renderOffer:u,lead:l==="lead",children:f}):f}function hh({sessionId:e,onRetry:t,onSigninComplete:n}){return e?r.jsx(ph,{sessionId:e,onRetry:t,onSigninComplete:n}):r.jsx(No,{onRetry:t})}const gh="credits_unavailable",xh="folder-sign-in";function bh({onRetry:e,sessionId:t,runtimeLabel:n,reason:s}){const a=oe(g=>g.setRetryAccount),o=Ml(),i=pa(),l=ha(),u=tn(t),d=Zt(u??null);if(!e)return null;const f=yh(d),h=n?`your ${n}`:"your own",m=()=>{if(d!==void 0){if(f==="pick-for-send"){t&&a({id:vt,sessionId:t}),e();return}i.mutate({runtime:d.type,useCredits:!1},{onSuccess:()=>f==="new-conversation"?l(void 0,{runtime:d.type}):e()})}},x=()=>{t&&o.mutate(t,{onSuccess:({launch:g})=>{g!=null&&g.ok&&a({id:g.accountId,sessionId:t}),e()}})};return r.jsxs("div",{className:"mt-2 flex flex-col gap-2","data-testid":"credits-error-actions",children:[r.jsxs("div",{className:"flex flex-wrap gap-2",children:[r.jsxs(ne,{size:"sm",variant:"outline",onClick:e,className:"gap-1.5",children:[r.jsx(Ct,{className:"size-3"}),"Retry"]}),t&&r.jsx(ne,{size:"sm",variant:"outline",onClick:m,disabled:d===void 0||i.isPending,children:f==="new-conversation"?`Start a new chat on ${h} sign-in`:`Use ${h} sign-in`}),t&&s===xh&&r.jsx(ne,{size:"sm",variant:"outline",onClick:x,disabled:o.isPending,children:"Don’t use credits in this project"})]}),t&&f==="whole-runtime"&&r.jsxs("p",{className:"text-muted-foreground text-xs","data-testid":"credits-own-sign-in-reach",children:["This moves all ",n??"its"," chats to ",h," sign-in, not just this one."]}),o.error&&r.jsx("p",{className:"text-muted-foreground text-xs",role:"status",children:o.error.message}),i.isError&&r.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 yh(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 vh({category:e,onChooseModel:t}){return t?r.jsxs(ne,{size:"sm",onClick:t,className:"mt-3 gap-1.5",children:[r.jsx(ga,{className:"size-3"}),e==="runtime_update_required"?"Choose another model":"Choose model"]}):null}const kh="your agent",Ch="agent",mr={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}},Sh=new Set(["max_turns","budget_exceeded","output_format_error","auth_error"]);function jh(e){return`Sign in to ${e??kh} again`}function _h(e){return`Your ${e??Ch} login stopped working. Sign in again to continue.`}const wh="rate_limit";function sn(e){const{code:t,at:n,sessionId:s,reason:a}=e;return t===xa&&a?r.jsx(Ya,{agentId:a}):t===wh&&s?r.jsx(mm,{sessionId:s,at:n??"",fallback:r.jsx(pr,{...e})}):r.jsx(pr,{...e})}function pr({message:e,category:t,details:n,onRetry:s,heading:a,subtext:o,runtimeLabel:i,sessionId:l,onSigninComplete:u,onChooseModel:d,code:f,reason:h}){const[m,x]=c.useState(!1),g=f===gh,S=c.useMemo(()=>uh(e),[e]),b=(S==null?void 0:S.category)??t,y=(S==null?void 0:S.message)??e,C=S?n!=null&&n.includes(S.details??"")?n:[n,S.details].filter(Boolean).join(`
45
45
  `):n,v=b==="auth_error",p=b?mr[b]??mr.execution_error:null,j=v?jh(i):b==="runtime_update_required"&&i?`${i} update required`:p==null?void 0:p.heading,_=v?_h(i):p==null?void 0:p.subtext,D=g?"Couldn’t reach DorkOS credits":S?j??"Error":a??j??"Error",T=y.trim(),N=b!==void 0&&Sh.has(b),A=g?T:(S&&(o==null?void 0:o.trim())===e.trim()?void 0:o)??(N?_:T||_)??T,k=A.trim(),E=c.useMemo(()=>Il(T),[T]),w=!T||T===k||T===D,R=!w&&(!N||E)?T:null,O=w||R!==null||C!=null&&C.includes(T)?C:[C,T].filter(Boolean).join(`
46
- `),F=(p==null?void 0:p.retryable)??!!s;return r.jsx("div",{"data-testid":"error-message-block",className:H("my-2 rounded-lg border px-4 py-3","border-destructive/30 bg-destructive/5 text-foreground"),children:r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx(us,{className:"text-destructive mt-0.5 size-4 shrink-0"}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"text-sm font-medium",children:D}),r.jsx("p",{className:"text-muted-foreground mt-0.5 text-sm wrap-anywhere whitespace-pre-wrap",children:r.jsx(fn,{text:A})}),R&&r.jsx("p",{className:"text-muted-foreground mt-1 text-sm wrap-anywhere whitespace-pre-wrap",children:r.jsx(fn,{text:R})}),O&&r.jsxs("button",{type:"button",onClick:()=>x(!m),className:"text-muted-foreground hover:text-foreground mt-2 flex items-center gap-1 text-xs","aria-expanded":m,children:[r.jsx(G.div,{animate:{rotate:m?0:-90},transition:{type:"spring",stiffness:400,damping:30},children:r.jsx(Et,{className:"size-3"})}),"Details"]}),r.jsx(ie,{initial:!1,children:m&&O&&r.jsx(G.div,{variants:Ue,initial:"initial",animate:"animate",exit:"exit",transition:Be,className:"overflow-hidden",children:r.jsx("pre",{className:"bg-muted/50 mt-1 max-h-40 overflow-auto rounded p-2 text-xs whitespace-pre-wrap",children:r.jsx(fn,{text:O})})})}),g&&r.jsx(bh,{onRetry:s,sessionId:l,runtimeLabel:i,reason:h}),v&&r.jsx(hh,{sessionId:l,onRetry:s,onSigninComplete:u}),(b==="model_unavailable"||b==="runtime_update_required")&&r.jsx(vh,{category:b,onChooseModel:d})]}),!v&&!g&&F&&s&&r.jsxs(ne,{variant:"outline",size:"sm",onClick:s,className:"shrink-0 gap-1.5",children:[r.jsx(Ct,{className:"size-3"}),"Retry"]})]})})}const Nh=8;function Eh({toolName:e,reasonType:t,reason:n,message:s,agentId:a}){const o=n||s,i=t==="classifier",l=t==="asyncAgent",u=a!==void 0?`Helper ${a.slice(0,Nh)}`:l?"A background helper":null,f=u!==null?`${u} was blocked from using ${e}${i?" by auto mode":""}: ${o}`:i?`Blocked by auto mode: ${o}`:`Blocked: ${o}`;return r.jsxs("div",{"data-testid":"permission-denied-chip","data-reason-type":t,"data-agent-id":a,className:H("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:[r.jsx(ed,{"aria-hidden":"true",className:"mt-0.5 size-4 shrink-0 text-amber-600 dark:text-amber-500"}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"text-sm",children:f}),l?r.jsxs(r.Fragment,{children:[r.jsx("p",{className:"text-muted-foreground mt-0.5 text-xs",children:"Background helpers can’t ask for approval, so this was blocked."}),r.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,r.jsx("p",{className:"text-muted-foreground mt-0.5 font-mono text-xs",children:e})]})]})}const Dh=50;function Ah(e){return e.type==="tool_call"&&e.interactiveType==="approval"&&e.approvalOutcome!==void 0}function Th(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)<=Dh}function Fh(e){const t=new Map;let n=null;for(let s=0;s<e.length;s++){const a=e[s];if(!Ah(a)){n=null;continue}if(n&&Th(n.part,a)){n.group.indices.push(s),t.set(s,n.group);continue}const o={leadIndex:s,indices:[s],outcome:a.approvalOutcome,reasonGiven:a.approvalReasonGiven??!1};t.set(s,o),n={group:o,part:a}}return t}function Rh(e){return e.questionOutcome!==void 0?e.questionOutcome==="answered":e.status!=="pending"}function Mh(e){return e.status==="pending"?void 0:e.questionOutcome}function Ih({message:e}){return r.jsx(Ve,{"data-testid":"unreadable-entry-note",icon:r.jsx(Ol,{"aria-hidden":"true",className:"text-muted-foreground size-3 shrink-0"}),label:r.jsx("span",{className:"text-muted-foreground",children:e})})}function Oh({title:e}){return r.jsxs("div",{"data-testid":"capability-approval-timed-out",className:H("my-2 flex items-start gap-2 rounded-md border px-3 py-2","text-foreground border-border bg-muted/40"),children:[r.jsx(gt,{"aria-hidden":"true",className:"text-muted-foreground mt-0.5 size-4 shrink-0"}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"text-sm",children:"The agent stopped waiting for your answer."}),r.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 Vn({testId:e,icon:t,children:n}){return r.jsxs("div",{"data-testid":e,className:H("my-2 flex items-start gap-2 rounded-md border px-3 py-2","text-foreground border-border bg-muted/40"),children:[t,r.jsx("div",{className:"min-w-0 flex-1",children:n})]})}function $h({part:e}){return e.outcome==="failed"?r.jsx(Vn,{testId:"mcp-signin-failed",icon:r.jsx(us,{"aria-hidden":"true",className:"text-status-warning-dot mt-0.5 size-4 shrink-0"}),children:r.jsxs("p",{className:"text-sm",children:["Sign-in to “",e.serverName,"” didn’t finish. Ask your agent to retry."]})}):r.jsx(Vn,{testId:"mcp-signin-receipt",icon:r.jsx(ba,{"aria-hidden":"true",className:"text-status-success mt-0.5 size-4 shrink-0"}),children:r.jsxs("p",{className:"text-sm",children:["Connected to ",e.serverName,e.toolCount===void 0?"":` · ${e.toolCount} tool${e.toolCount===1?"":"s"}`,"."]})})}function Ph({part:e}){const t=td(e.agentId,e.serverName),{adopt:n}=t,s=e.outcome!==void 0;return c.useEffect(()=>{s||n({flowId:e.flowId,authorizeUrl:e.authorizeUrl,disclosure:e.disclosure})},[s,n,e.flowId,e.authorizeUrl,e.disclosure]),e.outcome!==void 0?r.jsx($h,{part:e}):r.jsxs(Vn,{testId:"mcp-signin-card",icon:r.jsx($l,{"aria-hidden":"true",className:"text-muted-foreground mt-0.5 size-4 shrink-0"}),children:[r.jsxs("p",{className:"text-sm",children:["Sign in to ",e.serverName]}),r.jsx(nd,{flow:t,serverName:e.serverName,failedActions:r.jsx(ne,{variant:"secondary",size:"sm",onClick:()=>t.start(),className:"focus-visible:ring-2",children:"Try again"})})]})}function Lh({fromName:e,toName:t}){return r.jsx(Ve,{"data-testid":"model-substituted-row",icon:r.jsx(ga,{"aria-hidden":"true",className:"text-muted-foreground size-3 shrink-0"}),label:r.jsxs("span",{className:"text-muted-foreground",children:["DorkOS credits don’t cover ",e,", so this ran on ",t,". Switch in the model menu."]})})}const zh={running:r.jsx(ze,{size:"xs",className:"text-muted-foreground"}),success:r.jsx(ot,{className:"text-muted-foreground size-(--size-icon-xs)"}),error:r.jsx(Le,{className:"text-destructive size-(--size-icon-xs)"}),cancelled:r.jsx(Le,{className:"text-muted-foreground size-(--size-icon-xs)"})};function Bh({hook:e}){const t=!!(e.stdout||e.stderr),[n,s]=c.useState(e.status==="error"),a=e.stderr||e.stdout;return r.jsxs("div",{children:[r.jsxs("button",{onClick:()=>t&&s(o=>!o),className:H("flex w-full items-center gap-1.5 py-0.5",!t&&"cursor-default"),"aria-expanded":t?n:void 0,disabled:!t,children:[zh[e.status],r.jsx("span",{className:H("text-3xs font-mono",e.status==="error"?"text-destructive":"text-muted-foreground"),children:e.hookName}),e.status==="error"&&r.jsx("span",{className:"text-3xs text-destructive",children:"Error"}),e.exitCode!==void 0&&r.jsxs("span",{className:"text-3xs text-muted-foreground ml-auto",children:["exit ",e.exitCode]})]}),r.jsx(ie,{initial:!1,children:n&&t&&a&&r.jsx(G.div,{variants:Ue,initial:"initial",animate:"animate",exit:"exit",transition:Be,className:"overflow-hidden",children:r.jsx("pre",{className:"text-muted-foreground max-h-32 overflow-y-auto py-1 text-xs whitespace-pre-wrap",children:a})})})]})}function Uh({toolCall:e,defaultExpanded:t=!1}){const[n,s]=c.useState(t),a=!!e.progressOutput;c.useEffect(()=>{a&&!n&&s(!0)},[a]);const o=e.hooks&&e.hooks.length>0?r.jsx("div",{className:"border-border/50 space-y-0.5 border-t px-3 py-1",children:e.hooks.map(u=>r.jsx(Bh,{hook:u},u.hookId))}):void 0,i=e.startedAt&&e.completedAt?e.completedAt-e.startedAt:void 0,l=ta(e.toolName);return r.jsxs(Tt,{expanded:n,onToggle:()=>s(!n),dimmed:e.status==="complete",extraContent:o,"data-testid":"tool-call-card","data-tool-name":e.toolName,"data-status":e.status,header:r.jsxs(r.Fragment,{children:[mo(e.status),l&&r.jsx("span",{className:"bg-muted text-muted-foreground text-3xs rounded px-1 py-0.5 font-medium",children:l}),r.jsx("span",{className:"text-3xs flex-1 text-left font-mono",children:lt(e.toolName,e.input)}),i!==void 0&&r.jsx("span",{className:"text-muted-foreground text-3xs tabular-nums",children:sd(i)})]}),children:[e.status==="running"&&!e.input?r.jsxs("div",{className:"text-muted-foreground flex items-center gap-1.5 py-1 text-xs",children:[r.jsx(ze,{size:"xs"}),r.jsx("span",{children:"Preparing…"})]}):e.input!==void 0&&e.input!==""?r.jsx(Ka,{toolName:e.toolName,input:e.input,isStreaming:e.status==="running"}):null,e.progressOutput&&!e.result&&r.jsx(na,{content:e.progressOutput,className:"mt-2 border-t pt-2"}),e.result&&r.jsx("div",{className:"mt-2 border-t pt-2",children:r.jsx(_o,{content:e.result,toolName:e.toolName,input:e.input})})]})}function qh(e){if(e.startsWith("mcp__"))return e.split("__")[1]||void 0}function Eo(e,t,n){const s=c.useRef(e),[a,o]=c.useState(!(t&&s.current==="complete"));return c.useEffect(()=>{if(t&&e==="complete"&&s.current!=="complete"&&!n){const i=setTimeout(()=>o(!1),Jt.TOOL_CALL_AUTO_HIDE_MS);return()=>clearTimeout(i)}},[e,t,n]),!t||n?!0:a}function Hh({part:e,autoHide:t,expandToolCalls:n}){var o;const s=((o=e.hooks)==null?void 0:o.some(i=>i.status==="error"))??!1,a=Eo(e.status,t,s);return r.jsx(ie,{children:a&&r.jsx(G.div,{exit:{height:0,opacity:0},transition:{duration:.3,ease:[.4,0,.2,1]},className:"overflow-hidden",children:r.jsx(Uh,{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 En({part:e,sessionId:t,autoHide:n,expandToolCalls:s}){const a=e.ui?qh(e.toolName):void 0,o=r.jsx(Hh,{part:e,autoHide:n,expandToolCalls:s});return!e.ui||e.status!=="complete"||!a?o:r.jsxs("div",{className:"flex flex-col gap-2",children:[o,r.jsx(bf,{sessionId:t,serverName:a,uri:e.ui.resourceUri})]})}function Wh({part:e,autoHide:t,index:n}){const s=e.isStreaming?"running":"complete",a=Eo(s,t,!1);return r.jsx(ie,{children:a&&r.jsx(G.div,{exit:{height:0,opacity:0},transition:{duration:.3,ease:[.4,0,.2,1]},className:"overflow-hidden",children:r.jsx(_p,{text:e.text,isStreaming:e.isStreaming??!1,elapsedMs:e.elapsedMs})},`thinking-${n}`)})}const Vh=4,hr=2;function Gh({children:e}){const[t,n]=c.useState(!1);if(e.length<=Vh||t)return r.jsx(r.Fragment,{children:e});const s=e.length-hr;return r.jsxs(r.Fragment,{children:[e.slice(0,hr),r.jsx(Tt,{expanded:!1,onToggle:()=>n(!0),ariaLabel:`Show ${s} more steps`,className:"border-l-muted-foreground/15",header:r.jsxs("span",{className:"text-3xs text-muted-foreground font-mono",children:["and ",s," more steps…"]}),children:r.jsx(r.Fragment,{})})]})}const Kh=/\|\||&&|;|\|/,Qh=/<<|>/,gr=60;function Yh(e){if(!e)return null;try{const t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function Fe(e,t){const n=e[t];return typeof n=="string"&&n.length>0?n:void 0}function Xh(e,t){const n=e.split(`
46
+ `),F=(p==null?void 0:p.retryable)??!!s;return r.jsx("div",{"data-testid":"error-message-block",className:H("my-2 rounded-lg border px-4 py-3","border-destructive/30 bg-destructive/5 text-foreground"),children:r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx(us,{className:"text-destructive mt-0.5 size-4 shrink-0"}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"text-sm font-medium",children:D}),r.jsx("p",{className:"text-muted-foreground mt-0.5 text-sm wrap-anywhere whitespace-pre-wrap",children:r.jsx(fn,{text:A})}),R&&r.jsx("p",{className:"text-muted-foreground mt-1 text-sm wrap-anywhere whitespace-pre-wrap",children:r.jsx(fn,{text:R})}),O&&r.jsxs("button",{type:"button",onClick:()=>x(!m),className:"text-muted-foreground hover:text-foreground mt-2 flex items-center gap-1 text-xs","aria-expanded":m,children:[r.jsx(G.div,{animate:{rotate:m?0:-90},transition:{type:"spring",stiffness:400,damping:30},children:r.jsx(Et,{className:"size-3"})}),"Details"]}),r.jsx(ie,{initial:!1,children:m&&O&&r.jsx(G.div,{variants:qe,initial:"initial",animate:"animate",exit:"exit",transition:Be,className:"overflow-hidden",children:r.jsx("pre",{className:"bg-muted/50 mt-1 max-h-40 overflow-auto rounded p-2 text-xs whitespace-pre-wrap",children:r.jsx(fn,{text:O})})})}),g&&r.jsx(bh,{onRetry:s,sessionId:l,runtimeLabel:i,reason:h}),v&&r.jsx(hh,{sessionId:l,onRetry:s,onSigninComplete:u}),(b==="model_unavailable"||b==="runtime_update_required")&&r.jsx(vh,{category:b,onChooseModel:d})]}),!v&&!g&&F&&s&&r.jsxs(ne,{variant:"outline",size:"sm",onClick:s,className:"shrink-0 gap-1.5",children:[r.jsx(Ct,{className:"size-3"}),"Retry"]})]})})}const Nh=8;function Eh({toolName:e,reasonType:t,reason:n,message:s,agentId:a}){const o=n||s,i=t==="classifier",l=t==="asyncAgent",u=a!==void 0?`Helper ${a.slice(0,Nh)}`:l?"A background helper":null,f=u!==null?`${u} was blocked from using ${e}${i?" by auto mode":""}: ${o}`:i?`Blocked by auto mode: ${o}`:`Blocked: ${o}`;return r.jsxs("div",{"data-testid":"permission-denied-chip","data-reason-type":t,"data-agent-id":a,className:H("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:[r.jsx(Zu,{"aria-hidden":"true",className:"mt-0.5 size-4 shrink-0 text-amber-600 dark:text-amber-500"}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"text-sm",children:f}),l?r.jsxs(r.Fragment,{children:[r.jsx("p",{className:"text-muted-foreground mt-0.5 text-xs",children:"Background helpers can’t ask for approval, so this was blocked."}),r.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,r.jsx("p",{className:"text-muted-foreground mt-0.5 font-mono text-xs",children:e})]})]})}const Dh=50;function Ah(e){return e.type==="tool_call"&&e.interactiveType==="approval"&&e.approvalOutcome!==void 0}function Th(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)<=Dh}function Fh(e){const t=new Map;let n=null;for(let s=0;s<e.length;s++){const a=e[s];if(!Ah(a)){n=null;continue}if(n&&Th(n.part,a)){n.group.indices.push(s),t.set(s,n.group);continue}const o={leadIndex:s,indices:[s],outcome:a.approvalOutcome,reasonGiven:a.approvalReasonGiven??!1};t.set(s,o),n={group:o,part:a}}return t}function Rh(e){return e.questionOutcome!==void 0?e.questionOutcome==="answered":e.status!=="pending"}function Mh(e){return e.status==="pending"?void 0:e.questionOutcome}function Ih({message:e}){return r.jsx(Ve,{"data-testid":"unreadable-entry-note",icon:r.jsx(Ol,{"aria-hidden":"true",className:"text-muted-foreground size-3 shrink-0"}),label:r.jsx("span",{className:"text-muted-foreground",children:e})})}function Oh({title:e}){return r.jsxs("div",{"data-testid":"capability-approval-timed-out",className:H("my-2 flex items-start gap-2 rounded-md border px-3 py-2","text-foreground border-border bg-muted/40"),children:[r.jsx(gt,{"aria-hidden":"true",className:"text-muted-foreground mt-0.5 size-4 shrink-0"}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"text-sm",children:"The agent stopped waiting for your answer."}),r.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 Vn({testId:e,icon:t,children:n}){return r.jsxs("div",{"data-testid":e,className:H("my-2 flex items-start gap-2 rounded-md border px-3 py-2","text-foreground border-border bg-muted/40"),children:[t,r.jsx("div",{className:"min-w-0 flex-1",children:n})]})}function $h({part:e}){return e.outcome==="failed"?r.jsx(Vn,{testId:"mcp-signin-failed",icon:r.jsx(us,{"aria-hidden":"true",className:"text-status-warning-dot mt-0.5 size-4 shrink-0"}),children:r.jsxs("p",{className:"text-sm",children:["Sign-in to “",e.serverName,"” didn’t finish. Ask your agent to retry."]})}):r.jsx(Vn,{testId:"mcp-signin-receipt",icon:r.jsx(ba,{"aria-hidden":"true",className:"text-status-success mt-0.5 size-4 shrink-0"}),children:r.jsxs("p",{className:"text-sm",children:["Connected to ",e.serverName,e.toolCount===void 0?"":` · ${e.toolCount} tool${e.toolCount===1?"":"s"}`,"."]})})}function Ph({part:e}){const t=ed(e.agentId,e.serverName),{adopt:n}=t,s=e.outcome!==void 0;return c.useEffect(()=>{s||n({flowId:e.flowId,authorizeUrl:e.authorizeUrl,disclosure:e.disclosure})},[s,n,e.flowId,e.authorizeUrl,e.disclosure]),e.outcome!==void 0?r.jsx($h,{part:e}):r.jsxs(Vn,{testId:"mcp-signin-card",icon:r.jsx($l,{"aria-hidden":"true",className:"text-muted-foreground mt-0.5 size-4 shrink-0"}),children:[r.jsxs("p",{className:"text-sm",children:["Sign in to ",e.serverName]}),r.jsx(td,{flow:t,serverName:e.serverName,failedActions:r.jsx(ne,{variant:"secondary",size:"sm",onClick:()=>t.start(),className:"focus-visible:ring-2",children:"Try again"})})]})}function Lh({fromName:e,toName:t}){return r.jsx(Ve,{"data-testid":"model-substituted-row",icon:r.jsx(ga,{"aria-hidden":"true",className:"text-muted-foreground size-3 shrink-0"}),label:r.jsxs("span",{className:"text-muted-foreground",children:["DorkOS credits don’t cover ",e,", so this ran on ",t,". Switch in the model menu."]})})}const zh={running:r.jsx(ze,{size:"xs",className:"text-muted-foreground"}),success:r.jsx(ot,{className:"text-muted-foreground size-(--size-icon-xs)"}),error:r.jsx(Le,{className:"text-destructive size-(--size-icon-xs)"}),cancelled:r.jsx(Le,{className:"text-muted-foreground size-(--size-icon-xs)"})};function Bh({hook:e}){const t=!!(e.stdout||e.stderr),[n,s]=c.useState(e.status==="error"),a=e.stderr||e.stdout;return r.jsxs("div",{children:[r.jsxs("button",{onClick:()=>t&&s(o=>!o),className:H("flex w-full items-center gap-1.5 py-0.5",!t&&"cursor-default"),"aria-expanded":t?n:void 0,disabled:!t,children:[zh[e.status],r.jsx("span",{className:H("text-3xs font-mono",e.status==="error"?"text-destructive":"text-muted-foreground"),children:e.hookName}),e.status==="error"&&r.jsx("span",{className:"text-3xs text-destructive",children:"Error"}),e.exitCode!==void 0&&r.jsxs("span",{className:"text-3xs text-muted-foreground ml-auto",children:["exit ",e.exitCode]})]}),r.jsx(ie,{initial:!1,children:n&&t&&a&&r.jsx(G.div,{variants:qe,initial:"initial",animate:"animate",exit:"exit",transition:Be,className:"overflow-hidden",children:r.jsx("pre",{className:"text-muted-foreground max-h-32 overflow-y-auto py-1 text-xs whitespace-pre-wrap",children:a})})})]})}function qh({toolCall:e,defaultExpanded:t=!1}){const[n,s]=c.useState(t),a=!!e.progressOutput;c.useEffect(()=>{a&&!n&&s(!0)},[a]);const o=e.hooks&&e.hooks.length>0?r.jsx("div",{className:"border-border/50 space-y-0.5 border-t px-3 py-1",children:e.hooks.map(u=>r.jsx(Bh,{hook:u},u.hookId))}):void 0,i=e.startedAt&&e.completedAt?e.completedAt-e.startedAt:void 0,l=ta(e.toolName);return r.jsxs(Tt,{expanded:n,onToggle:()=>s(!n),dimmed:e.status==="complete",extraContent:o,"data-testid":"tool-call-card","data-tool-name":e.toolName,"data-status":e.status,header:r.jsxs(r.Fragment,{children:[mo(e.status),l&&r.jsx("span",{className:"bg-muted text-muted-foreground text-3xs rounded px-1 py-0.5 font-medium",children:l}),r.jsx("span",{className:"text-3xs flex-1 text-left font-mono",children:lt(e.toolName,e.input)}),i!==void 0&&r.jsx("span",{className:"text-muted-foreground text-3xs tabular-nums",children:nd(i)})]}),children:[e.status==="running"&&!e.input?r.jsxs("div",{className:"text-muted-foreground flex items-center gap-1.5 py-1 text-xs",children:[r.jsx(ze,{size:"xs"}),r.jsx("span",{children:"Preparing…"})]}):e.input!==void 0&&e.input!==""?r.jsx(Ka,{toolName:e.toolName,input:e.input,isStreaming:e.status==="running"}):null,e.progressOutput&&!e.result&&r.jsx(na,{content:e.progressOutput,className:"mt-2 border-t pt-2"}),e.result&&r.jsx("div",{className:"mt-2 border-t pt-2",children:r.jsx(_o,{content:e.result,toolName:e.toolName,input:e.input})})]})}function Uh(e){if(e.startsWith("mcp__"))return e.split("__")[1]||void 0}function Eo(e,t,n){const s=c.useRef(e),[a,o]=c.useState(!(t&&s.current==="complete"));return c.useEffect(()=>{if(t&&e==="complete"&&s.current!=="complete"&&!n){const i=setTimeout(()=>o(!1),Jt.TOOL_CALL_AUTO_HIDE_MS);return()=>clearTimeout(i)}},[e,t,n]),!t||n?!0:a}function Hh({part:e,autoHide:t,expandToolCalls:n}){var o;const s=((o=e.hooks)==null?void 0:o.some(i=>i.status==="error"))??!1,a=Eo(e.status,t,s);return r.jsx(ie,{children:a&&r.jsx(G.div,{exit:{height:0,opacity:0},transition:{duration:.3,ease:[.4,0,.2,1]},className:"overflow-hidden",children:r.jsx(qh,{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 En({part:e,sessionId:t,autoHide:n,expandToolCalls:s}){const a=e.ui?Uh(e.toolName):void 0,o=r.jsx(Hh,{part:e,autoHide:n,expandToolCalls:s});return!e.ui||e.status!=="complete"||!a?o:r.jsxs("div",{className:"flex flex-col gap-2",children:[o,r.jsx(bf,{sessionId:t,serverName:a,uri:e.ui.resourceUri})]})}function Wh({part:e,autoHide:t,index:n}){const s=e.isStreaming?"running":"complete",a=Eo(s,t,!1);return r.jsx(ie,{children:a&&r.jsx(G.div,{exit:{height:0,opacity:0},transition:{duration:.3,ease:[.4,0,.2,1]},className:"overflow-hidden",children:r.jsx(_p,{text:e.text,isStreaming:e.isStreaming??!1,elapsedMs:e.elapsedMs})},`thinking-${n}`)})}const Vh=4,hr=2;function Gh({children:e}){const[t,n]=c.useState(!1);if(e.length<=Vh||t)return r.jsx(r.Fragment,{children:e});const s=e.length-hr;return r.jsxs(r.Fragment,{children:[e.slice(0,hr),r.jsx(Tt,{expanded:!1,onToggle:()=>n(!0),ariaLabel:`Show ${s} more steps`,className:"border-l-muted-foreground/15",header:r.jsxs("span",{className:"text-3xs text-muted-foreground font-mono",children:["and ",s," more steps…"]}),children:r.jsx(r.Fragment,{})})]})}const Kh=/\|\||&&|;|\|/,Qh=/<<|>/,gr=60;function Yh(e){if(!e)return null;try{const t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function Fe(e,t){const n=e[t];return typeof n=="string"&&n.length>0?n:void 0}function Xh(e,t){const n=e.split(`
47
47
  `),s=t.split(`
48
48
  `);let a=0;for(;a<n.length&&a<s.length&&n[a]===s[a];)a++;let o=0;for(;o<n.length-a&&o<s.length-a&&n[n.length-1-o]===s[s.length-1-o];)o++;const i=a+o;return{additions:Math.max(0,s.length-i),deletions:Math.max(0,n.length-i)}}function Gn(e){const t=e.old_string,n=e.new_string;if(!(typeof t!="string"&&typeof n!="string"))return Xh(typeof t=="string"?t:"",typeof n=="string"?n:"")}function Jh(e){const t=e.edits;if(!Array.isArray(t))return Gn(e);let n=0,s=0,a=!1;for(const o of t){if(typeof o!="object"||o===null)continue;const i=Gn(o);i&&(n+=i.additions,s+=i.deletions,a=!0)}return a?{additions:n,deletions:s}:void 0}function Zh(e){return e?` +${e.additions} −${e.deletions}`:""}function eg(e){return e.length===0?0:e.replace(/\n$/,"").split(`
49
49
  `).length}function Do(e){const t=e.replace(/\/+$/,"");if(t.length===0)return e;const n=t.startsWith("/"),s=[];for(const o of t.split("/"))if(!(o===""||o===".")){if(o===".."){const i=s[s.length-1];i!==void 0&&i!==".."?s.pop():n||s.push("..");continue}s.push(o)}const a=s.join("/");return a.length===0?n?"/":e:n?`/${a}`:a}function tg(e,t){if(e===t)return!0;const n=e.startsWith("/")?e:t,s=e.startsWith("/")?t:e;return!n.startsWith("/")||s.startsWith("/")?!1:n.endsWith(`/${s}`)}function Ao(e){const t=Do(e).split("/");return t[t.length-1]||e}function ng(e){try{const t=new URL(e);return t.hash="",t.toString()}catch{return e}}function sg(e){try{return new URL(e).hostname.replace(/^www\./,"")}catch{return e}}function rg(e){if(!e)return;const t=e.trim();if(t.length===0)return;if(/^no (matches|files)/i.test(t))return 0;const n=/^(\d+)$/.exec(t);if(n)return Number(n[1]);const s=/(\d+)\s+(?:matches?|lines?)/i.exec(t);if(s)return Number(s[1]);if(!/\d+\s+files?/i.test(t))return t.split(`
50
50
  `).filter(a=>a.trim().length>0).length}function ag(e){var s;const n=((s=e.split(`
51
51
  `).find(a=>a.trim().length>0))==null?void 0:s.trim())??e.trim();return n.length<=gr?n:`${n.slice(0,gr-1).trimEnd()}…`}function og(e){const t=[];let n="",s=null,a=!1;for(const o of e){if(s){o===s?s=null:n+=o;continue}if(o==='"'||o==="'"){s=o,a=!0;continue}if(/\s/.test(o)){a&&t.push(n),n="",a=!1;continue}n+=o,a=!0}return a&&t.push(n),t}function ig(e){const t=[];for(const n of e.split(`
52
52
  `)){for(const s of n.split(Kh)){const a=og(s.trim());if(a.length===0)continue;let o;if(a[0]==="git"&&a[1]==="rm")o=2;else if(a[0]==="rm")o=1;else continue;for(const i of a.slice(o)){if(i.includes(">")||i.includes("<"))break;i==="--"||i.startsWith("-")||i.length===0||t.push(i)}}if(Qh.test(n))break}return t}const xr={delete:3,create:2,edit:1,read:0,search:0,fetch:0,run:0},lg=new Set(["Task","Agent","TodoWrite"]);function xs(e){return e===1?"1 hit":`${e} hits`}const cg=/[*?[\]~$]/;function ht(e,t,n,s,a){const o=Do(e);return{key:`file:${o}`,kind:"file",label:a===!0?o:Ao(o),fullTarget:o,verb:t,entry:n,additions:s==null?void 0:s.additions,deletions:s==null?void 0:s.deletions,pattern:a===!0?!0:void 0}}function ug(e){const{toolName:t}=e;if(lg.has(t)||t.startsWith("mcp__"))return[];const n=Yh(e.input);if(!n)return[];switch(t){case"Read":{const s=Fe(n,"file_path");return s?[ht(s,"read","read")]:[]}case"Glob":{const s=Fe(n,"pattern");return s?[{key:`file:${s}`,kind:"file",label:s,fullTarget:s,verb:"read",entry:"globbed",pattern:!0}]:[]}case"Grep":{const s=Fe(n,"pattern");if(!s)return[];const a=e.status==="error"?void 0:rg(e.result);return[{key:`grep:${s}`,kind:"command",label:`"${s}"`,fullTarget:s,verb:"search",entry:a===void 0?"searched":`searched (${xs(a)})`,hits:a}]}case"Edit":case"MultiEdit":case"NotebookEdit":{const s=Fe(n,"file_path")??Fe(n,"notebook_path");if(!s)return[];const a=t==="MultiEdit"?Jh(n):Gn(n);return[ht(s,"edit",`edited${Zh(a)}`,a)]}case"Write":{const s=Fe(n,"file_path");if(!s)return[];if(!/created/i.test(e.result??""))return[ht(s,"edit","wrote")];const o=Fe(n,"content"),i=o===void 0?void 0:{additions:eg(o)};return[ht(s,"create",`created${i?` +${i.additions}`:""}`,i)]}case"Bash":{const s=Fe(n,"command");if(!s)return[];const a=[{key:`run:${s}`,kind:"command",label:ag(s),fullTarget:s,verb:"run",entry:"ran"}];for(const o of ig(s))a.push(ht(o,"delete","deleted",void 0,cg.test(o)));return a}case"WebFetch":{const s=Fe(n,"url");return s?[{key:`url:${ng(s)}`,kind:"url",label:sg(s),fullTarget:s,verb:"fetch",entry:"fetched"}]:[]}case"WebSearch":{const s=Fe(n,"query");return s?[{key:`websearch:${s}`,kind:"command",label:s,fullTarget:s,verb:"search",entry:"searched the web"}]:[]}default:return[]}}function dg(e,t){if(t.kind!=="file"||t.pattern===!0||e.has(t.key))return t.key;for(const n of e.values())if(!(n.kind!=="file"||n.pattern===!0)&&tg(n.fullTarget,t.fullTarget))return n.key;return t.key}function fg(e,t,n,s,a){const o=dg(e,t),i=e.get(o);if(!i){e.set(o,{key:o,kind:t.kind,label:t.label,fullTarget:t.fullTarget,verb:t.verb,live:s,error:a,touches:1,additions:t.additions,deletions:t.deletions,hits:t.hits,pattern:t.pattern,firstSeq:n,lastSeq:n,history:[t.entry]});return}i.touches+=1,i.lastSeq=n,i.live=i.live||s,i.error=i.error||a,i.history.push(t.entry),t.additions!==void 0&&(i.additions=(i.additions??0)+t.additions),t.deletions!==void 0&&(i.deletions=(i.deletions??0)+t.deletions),t.hits!==void 0&&(i.hits=(i.hits??0)+t.hits),t.pattern||(i.pattern=void 0),i.kind==="file"&&i.pattern!==!0&&t.fullTarget.startsWith("/")&&!i.fullTarget.startsWith("/")&&(i.fullTarget=t.fullTarget,i.label=Ao(t.fullTarget)),i.verb==="read"&&t.verb==="edit"&&(i.upgraded=!0),xr[t.verb]>xr[i.verb]&&(i.verb=t.verb)}const br=new WeakMap;function mg(e){const t=br.get(e);if(t&&t.input===e.input&&t.result===e.result&&t.status===e.status)return t.touches;const n=ug(e);return br.set(e,{input:e.input,result:e.result,status:e.status,touches:n}),n}function pg(e){const t=new Map;return e.forEach((n,s)=>{if(n.type!=="tool_call")return;const a=n.status==="pending"||n.status==="running",o=n.status==="error";for(const i of mg(n))fg(t,i,s,a,o)}),[...t.values()]}const To={expanded:!1,verbFilter:null,order:"grouped"},Dn=rs(e=>({views:{},update:(t,n)=>e(s=>({views:{...s.views,[t]:{...s.views[t]??To,...n}}}))}));function hg(e,t){const n=t.find(s=>s.type==="tool_call");return`${e}:${(n==null?void 0:n.toolCallId)??""}`}function gg(e){const t=Dn(l=>l.views[e]),n=Dn(l=>l.update),s=t??To,a=c.useCallback(()=>{var l;return n(e,{expanded:!((l=Dn.getState().views[e])!=null&&l.expanded)})},[e,n]),o=c.useCallback(l=>n(e,{verbFilter:l}),[e,n]),i=c.useCallback(l=>n(e,{order:l}),[e,n]);return c.useMemo(()=>({...s,toggleExpanded:a,setVerbFilter:o,setOrder:i}),[s,a,o,i])}const yr=4,ut=[.4,0,.2,1],xg={type:"spring",stiffness:320,damping:28},bg={duration:.25,ease:ut},yg={x:-16,scale:.45,opacity:0},Yt={duration:.15,ease:ut},vr={duration:.3,ease:ut},kr={duration:.15,ease:ut},vg={duration:.3,ease:ut},kg={stiffness:220,damping:30},Cg={rotate:[0,-4,3,0],scale:[1,1.08,1,1]},Sg={duration:.3,ease:ut};function jg(e,t){return e?t?{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0,transition:Yt},transition:Yt}:{initial:{opacity:0,y:7},animate:{opacity:1,y:0},exit:{...yg,transition:bg},transition:xg}:{}}const rn={read:"📖",search:"🔍",edit:"✏️",create:"✚",delete:"🗑",fetch:"🌐",run:"▮"},an={read:"Read",search:"Searched",edit:"Edited",create:"Created",delete:"Deleted",fetch:"Fetched",run:"Ran"},Fo=["read","search","edit","create","delete","fetch","run"];function Ro(e){return Fo.map(t=>{const n=e.filter(a=>a.verb===t),s={verb:t,chips:n};for(const a of n)a.additions!==void 0&&(s.additions=(s.additions??0)+a.additions),a.deletions!==void 0&&(s.deletions=(s.deletions??0)+a.deletions);return s}).filter(t=>t.chips.length>0)}const _g=["z-30","-ml-2 z-20 opacity-70","-ml-2 z-10 opacity-45"];function wg({chips:e,expanded:t,controls:n,onExpand:s}){const a=Te()??!1,o=e.slice(-3).reverse();return r.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:s,className:H("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:[r.jsx(G.span,{animate:a?{rotate:0,scale:1}:Cg,transition:Sg,className:"flex origin-bottom items-center",children:o.map((i,l)=>r.jsx("span",{"aria-hidden":"true",className:H("bg-card border-border text-3xs flex size-5 items-center justify-center rounded-full border leading-none",_g[l]),children:rn[i.verb]},i.key))},e.length),r.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})]})}function Cr({value:e,live:t}){const n=Te()??!1,s=fd(e,kg),a=$a(s,o=>Math.round(o));return c.useEffect(()=>{s.set(e)},[s,e]),!t||n?r.jsx(r.Fragment,{children:e}):r.jsx(G.span,{children:a})}function Ng(e){return e.kind!=="command"&&e.pattern!==!0}function Eg(e){return[e.fullTarget,e.history.join(", "),e.pattern===!0?"A pattern, not one file. There is nothing to open.":""].filter(Boolean).join(`
53
- `)}function Dg(e){const t=e.pattern===!0&&e.verb==="read"?"Globbed":an[e.verb],n=e.verb==="run"?e.label:e.fullTarget,s=[`${t} ${n}`];return e.touches>1&&s.push(`${e.touches} times`),e.hits!==void 0&&s.push(xs(e.hits)),e.additions!==void 0&&s.push(`${e.additions} added`),e.deletions!==void 0&&s.push(`${e.deletions} removed`),e.error&&s.push("didn’t work"),s.join(", ")}const Sr="bg-muted text-muted-foreground shrink-0 rounded-full px-1.5 text-3xs leading-[1.4] tabular-nums";function Mo({chip:e,onOpen:t,animated:n=!1,pulseUpgrade:s=!1,onUpgradeSeen:a}){const o=Te()??!1,i=s&&!o,l=Ng(e),u=e.verb==="delete",d=e.additions!==void 0||e.deletions!==void 0,f=n&&(e.verb==="create"||e.verb==="delete");return r.jsxs(G.button,{...jg(n,o),type:"button","data-testid":"touch-chip","data-verb":e.verb,"data-live":e.live,"data-arriving":f?"true":void 0,title:Eg(e),"aria-label":Dg(e),onClick:()=>t(e),className:H("touch-chip relative inline-flex max-w-56 items-center gap-1.5 rounded-full border","px-2 py-0.5 text-xs","bg-card text-foreground border-border","focus-visible:ring-ring outline-none focus-visible:ring-2",l?"hover:bg-accent hover:text-accent-foreground":"cursor-default",u&&"text-muted-foreground line-through opacity-60",e.error&&"border-destructive/40 bg-destructive/10 text-destructive"),children:[r.jsx("span",{"aria-hidden":"true",className:"chip-sweep"}),r.jsxs("span",{className:"chip-icon relative inline-flex w-4 shrink-0 items-center justify-center leading-none",children:[r.jsx("span",{className:"chip-glyph inline-flex items-center justify-center [perspective:400px]",children:r.jsx(ie,{initial:!1,mode:"wait",children:r.jsx(G.span,{"aria-hidden":"true",initial:o?{opacity:0}:{opacity:0,rotateX:-90},animate:o?{opacity:1}:{opacity:1,rotateX:0},exit:o?{opacity:0}:{opacity:0,rotateX:90},transition:kr,children:rn[e.verb]},e.verb)})}),i&&r.jsx(G.span,{"aria-hidden":"true","data-testid":"chip-upgrade-pulse",className:"border-primary pointer-events-none absolute -inset-1 rounded-full border",initial:{scale:.6,opacity:.8},animate:{scale:1.8,opacity:0},transition:vg,onAnimationComplete:()=>a==null?void 0:a(e.key)})]}),r.jsx("span",{className:"chip-label truncate",children:e.label}),e.verb==="edit"&&e.live&&r.jsx("span",{"aria-hidden":"true","data-testid":"chip-caret",className:"chip-caret"}),e.verb==="run"&&e.live&&r.jsx("span",{"aria-hidden":"true","data-testid":"chip-cursor",className:"chip-cursor"}),e.verb==="fetch"&&e.live&&r.jsxs("span",{"aria-hidden":"true","data-testid":"chip-dots",className:"chip-dots",children:[r.jsx("span",{}),r.jsx("span",{}),r.jsx("span",{})]}),e.verb==="create"&&f&&r.jsxs(r.Fragment,{children:[r.jsx("svg",{"aria-hidden":"true","data-testid":"chip-pen",className:"chip-pen",children:r.jsx("rect",{x:"0",y:"0",width:"100%",height:"100%",rx:"11",ry:"11",pathLength:"100"})}),r.jsx("span",{"aria-hidden":"true",className:"chip-spark"})]}),e.verb==="delete"&&f&&r.jsx("span",{"aria-hidden":"true","data-testid":"chip-puff",className:"chip-puff"}),e.touches>1&&r.jsxs("span",{className:Sr,children:["×",e.touches]}),e.hits!==void 0&&r.jsx("span",{className:Sr,children:xs(e.hits)}),d&&r.jsxs(G.span,{className:"shrink-0 tabular-nums",initial:i?{opacity:0,x:-4}:!1,animate:{opacity:1,x:0},transition:kr,children:[e.additions!==void 0&&r.jsxs("span",{className:"text-status-success-fg",children:["+",r.jsx(Cr,{value:e.additions,live:e.live})]}),e.additions!==void 0&&e.deletions!==void 0&&" ",e.deletions!==void 0&&r.jsxs("span",{className:"text-destructive",children:["−",r.jsx(Cr,{value:e.deletions,live:e.live})]})]})]})}const jr=new Map(Fo.map((e,t)=>[e,t]));function Ag(e,t){const n=[...e];return t==="chronological"?n.sort((s,a)=>s.lastSeq-a.lastSeq):n.sort((s,a)=>(jr.get(s.verb)??0)-(jr.get(a.verb)??0)||s.firstSeq-a.firstSeq)}function Tg({id:e,chips:t,onOpen:n,verbFilter:s,onVerbFilterChange:a,order:o,onOrderChange:i}){const l=c.useMemo(()=>Ro(t),[t]),u=c.useMemo(()=>{const d=s?t.filter(f=>f.verb===s):t;return Ag(d,o)},[t,s,o]);return r.jsxs("div",{id:e,role:"region","aria-label":"Touched files and links","data-testid":"chip-tray",className:"border-border bg-card/50 flex flex-col gap-2 rounded-md border p-2",children:[r.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[r.jsx("div",{role:"group","aria-label":"Filter by what happened",className:"flex flex-wrap gap-1",children:l.map(d=>{const f=s===d.verb;return r.jsxs(ne,{variant:"outline",size:"xs","aria-pressed":f,"data-testid":`chip-filter-${d.verb}`,onClick:()=>a(f?null:d.verb),className:H("rounded-full",f?"border-primary dark:border-primary text-foreground":"text-muted-foreground"),children:[r.jsx("span",{"aria-hidden":"true",children:rn[d.verb]}),r.jsx("span",{className:"sr-only",children:an[d.verb]}),r.jsx("span",{className:"tabular-nums",children:d.chips.length})]},d.verb)})}),r.jsxs(Pl,{value:o,onValueChange:d=>i(d),"aria-label":"Order the roster",className:"w-auto",children:[r.jsx($s,{value:"grouped",children:"Grouped"}),r.jsx($s,{value:"chronological",children:"Chronological"})]})]}),r.jsx("div",{"data-testid":"chip-tray-roster",className:"flex max-h-60 flex-wrap items-start gap-1.5 overflow-y-auto overscroll-contain",children:u.map(d=>r.jsx(Mo,{chip:d,onOpen:n},d.key))})]})}const Fg=new Set;function Rg(){const[e,t]=c.useState(Fg),n=c.useCallback((a,o)=>o===!0&&!e.has(a),[e]),s=c.useCallback(a=>{t(o=>o.has(a)?o:new Set(o).add(a))},[]);return{shouldPulse:n,acknowledge:s}}function Mg(e){const t=[...e].sort((n,s)=>n.lastSeq-s.lastSeq);return{visible:t.slice(-yr),absorbed:t.slice(0,Math.max(0,t.length-yr))}}function Ig(e){return e.map(t=>{const n=[`${t.chips.length} ${an[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 Og({verb:e,count:t,additions:n,deletions:s}){return r.jsxs("span",{"data-testid":`chip-summary-${e}`,className:"inline-flex items-center gap-1",children:[r.jsx("span",{"aria-hidden":"true",children:rn[e]}),r.jsx("span",{className:"sr-only",children:an[e]}),r.jsx("span",{className:"tabular-nums",children:t}),(n!==void 0||s!==void 0)&&r.jsxs("span",{className:"tabular-nums",children:[n!==void 0&&r.jsxs("span",{className:"text-status-success-fg",children:["+",n]}),n!==void 0&&s!==void 0&&" ",s!==void 0&&r.jsxs("span",{className:"text-destructive",children:["−",s]})]})]})}function $g({parts:e,sessionId:t,turnActive:n=!1}){const s=Te()??!1,a=c.useMemo(()=>pg(e),[e]),o=Rg(),i=c.useId(),l=gg(c.useMemo(()=>hg(t,e),[t,e])),u=c.useCallback(x=>{if(x.pattern===!0)return;const g=oe.getState();if(x.kind==="url"){const S={type:"url",url:x.fullTarget};g.openCanvasDocument(S),$n(g,"user",S);return}if(x.kind==="file"){const S={type:"file",sourcePath:x.fullTarget};g.openCanvasDocument(S),$n(g,"user",S)}},[]),d=c.useMemo(()=>Ro(a),[a]),f=n||a.some(x=>x.live),{visible:h,absorbed:m}=c.useMemo(()=>Mg(a),[a]);return a.length===0?null:r.jsxs("div",{"data-testid":"touch-chip-strip",className:"mt-2 flex flex-col gap-2",children:[r.jsx(ie,{initial:!1,mode:"wait",children:f?r.jsxs(G.div,{"data-testid":"chip-live-row",role:"group","aria-label":"Latest activity",exit:s?{opacity:0}:{opacity:0,height:0},transition:s?Yt:vr,className:"flex min-w-0 items-center gap-1.5 overflow-hidden",children:[m.length>0&&r.jsx(wg,{chips:m,expanded:l.expanded,controls:i,onExpand:l.toggleExpanded}),r.jsx(ie,{initial:!1,children:h.map(x=>r.jsx(Mo,{chip:x,onOpen:u,animated:!0,pulseUpgrade:o.shouldPulse(x.key,x.upgraded),onUpgradeSeen:o.acknowledge},x.key))})]},"live"):r.jsxs(G.div,{"data-testid":"chip-summary-line",role:"group","aria-label":Ig(d),initial:{opacity:0},animate:{opacity:1},transition:s?Yt:vr,className:"text-muted-foreground flex flex-wrap items-center gap-x-1.5 gap-y-1 text-xs",children:[d.map((x,g)=>r.jsxs(c.Fragment,{children:[g>0&&r.jsx("span",{"aria-hidden":"true",children:"·"}),r.jsx(Og,{verb:x.verb,count:x.chips.length,additions:x.additions,deletions:x.deletions})]},x.verb)),r.jsx("span",{"aria-hidden":"true",children:"·"}),r.jsx("button",{type:"button","aria-expanded":l.expanded,"aria-controls":i,onClick:l.toggleExpanded,className:H("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&&r.jsx(Tg,{id:i,chips:a,onOpen:u,verbFilter:l.verbFilter,onVerbFilterChange:l.setVerbFilter,order:l.order,onOrderChange:l.setOrder})]})}function _r(e){return e.type==="thinking"?!0:e.type==="tool_call"&&!e.interactiveType&&!Ja(e.toolName)&&!Pn(e.toolName)}function Pg({message:e}){const{sessionId:t,isStreaming:n,isLatestWidgetMessage:s,isFinalMessage:a,activeToolCallId:o,onToolRef:i,focusedOptionIndex:l,onToolDecided:u,onRetry:d,onSigninComplete:f,onChooseModel:h,inputZoneToolCallId:m,textEffect:x,runtimeLabel:g,allowsDenyReason:S}=Cp(),{expandToolCalls:b,autoHideToolCalls:y}=oe(),C=e.parts??[],{sent:v}=bo(t),p=c.useCallback(k=>{i==null||i(k)},[i]),j=c.useCallback(k=>{i==null||i(k)},[i]),_=Fh(C.map(k=>k.type==="tool_call"&&Pn(k.toolName)?{...k,interactiveType:void 0}:k));let D=-1;for(let k=C.length-1;k>=0;k--)if(C[k].type==="text"){D=k;break}function T(k,E){if(k.type==="text")return r.jsx("div",{className:"msg-prose",children:r.jsx(hs,{content:k.text,isStreaming:n&&E===D,textEffect:x,sessionId:t,isLatestWidgetMessage:s})},`text-${E}`);if(k.type==="background_task")return r.jsx($p,{part:k},k.taskId);if(k.type==="error"&&k.code===ya)return r.jsx(Ih,{message:k.message},`unreadable-${E}`);if(k.type==="error")return r.jsx(sn,{message:k.message,category:k.category,details:k.details,code:k.code,reason:k.reason,at:e.timestamp,onRetry:a&&k.category!==void 0?d:void 0,onSigninComplete:f,onChooseModel:h,runtimeLabel:g,sessionId:t},`error-${E}`);if(k.type==="thinking")return r.jsx(Wh,{part:k,autoHide:y,index:E},`thinking-${E}`);if(k.type==="elicitation")return r.jsx(Qd,{sessionId:t,interactionId:k.interactionId,serverName:k.serverName,message:k.message,mode:k.mode,url:k.url,requestedSchema:k.requestedSchema,status:k.status,action:k.action},`elicitation-${k.interactionId}`);if(k.type==="memory_recall")return r.jsx(wp,{mode:k.mode,memories:k.memories,isStreaming:k.isStreaming??!1},`memory-recall-${E}`);if(k.type==="permission_denied")return r.jsx(Eh,{toolName:k.toolName,reasonType:k.reasonType,reason:k.reason,message:k.message,agentId:k.agentId},`permission-denied-${k.toolCallId}-${E}`);if(k.type==="model_substituted")return r.jsx(Lh,{fromName:k.fromName,toName:k.toName},`model-substituted-${E}`);if(k.type==="compact_boundary")return r.jsx(Tp,{trigger:k.trigger,preTokens:k.preTokens,postTokens:k.postTokens,failed:k.failed,error:k.error,requestedBy:k.requestedBy,contextPercent:k.contextPercent},`compact-boundary-${E}`);if(k.type==="capability_approval")return k.outcome==="timeout"?r.jsx(Oh,{title:Ll(k.approval)},`capability-approval-${k.approval.approvalId}`):r.jsx(zl,{approval:k.approval},`capability-approval-${k.approval.approvalId}`);if(k.type==="mcp_signin")return r.jsx(Ph,{part:k},`mcp-signin-${k.agentId}-${k.flowId}`);if(k.type==="image")return r.jsx(Fp,{part:k},`image-${k.attachmentId}-${E}`);if(k.type!=="tool_call")return null;const w=k;if(w.interactiveType==="approval"&&w.status==="pending"){if(w.toolCallId===m)return r.jsx(ar,{type:"approval",toolName:w.toolName,toolInput:w.input},w.toolCallId);const O=w.toolCallId===o;return r.jsx(Xa,{ref:O?p:void 0,sessionId:t,toolCallId:w.toolCallId,toolName:w.toolName,input:w.input||"",timeoutMs:w.timeoutMs,approvalStartedAt:w.approvalStartedAt,approvalRemainingMs:w.approvalRemainingMs,approvalParked:w.approvalParked,approvalTitle:w.approvalTitle,approvalDisplayName:w.approvalDisplayName,approvalDescription:w.approvalDescription,approvalBlockedPath:w.approvalBlockedPath,approvalDecisionReason:w.approvalDecisionReason,approvalHasSuggestions:w.approvalHasSuggestions,approvalAlwaysAllowScope:w.approvalAlwaysAllowScope,isActive:O,onDecided:u?()=>u(w.toolCallId):void 0,allowsDenyReason:S},w.toolCallId)}const R=_.get(E);if(R){if(R.leadIndex!==E)return null;const O=R.indices.map(F=>C[F]).filter(F=>F.type==="tool_call");return r.jsx(sf,{outcome:R.outcome,reasonGiven:R.reasonGiven,members:O,lead:w,children:O.map(F=>r.jsx(En,{part:F,sessionId:t,autoHide:y,expandToolCalls:b},F.toolCallId))},`approval-receipt-${w.toolCallId}`)}if(w.interactiveType==="question"){if(w.toolCallId===m)return r.jsx(ar,{type:"question",toolName:w.toolName,toolInput:w.input},w.toolCallId);const O=w.toolCallId===o;return r.jsx(va,{ref:O?j:void 0,sessionId:t,toolCallId:w.toolCallId,questions:w.questions??[],answers:w.answers??(Rh(w)?{}:void 0),outcome:Mh(w),result:w.result,isActive:O,focusedOptionIndex:O?l:-1,onDecided:u?F=>u(w.toolCallId,F):void 0},w.toolCallId)}return Pn(w.toolName)?r.jsx(gp,{part:w,sent:v,...e.timestamp?{at:e.timestamp}:{},...t?{sessionId:t}:{}},w.toolCallId):Ja(w.toolName)?r.jsx(of,{sessionId:t,input:w.input,result:w.result,fallback:r.jsx(En,{part:w,sessionId:t,autoHide:y,expandToolCalls:b})},w.toolCallId):r.jsx(En,{part:w,sessionId:t,autoHide:y,expandToolCalls:b},w.toolCallId)}const N=[];let A=[];for(let k=0;k<C.length;k++){const E=C[k];_r(E)?A.push(k):(A.length>0&&(N.push(A.length===1?{type:"single",index:A[0]}:{type:"run",indices:[...A]}),A=[]),N.push({type:"single",index:k}))}return A.length>0&&N.push(A.length===1?{type:"single",index:A[0]}:{type:"run",indices:[...A]}),r.jsxs(r.Fragment,{children:[N.map(k=>{if(k.type==="single"){const w=C[k.index];return _r(w)?r.jsx("div",{className:"my-3",children:T(w,k.index)},`spacer-${k.index}`):T(w,k.index)}const E=k.indices.map(w=>T(C[w],w));return r.jsx("div",{className:"my-3",children:r.jsx(Gh,{children:E})},`run-${k.indices[0]}`)}),r.jsx($g,{parts:C,sessionId:t,turnActive:e._streaming===!0})]})}const Lg=/^Please read the following uploaded file\(s\):\n((?:- .+\n)+)\n?/,zg=/^[a-f0-9]{8}-/,Bg=new Set(["png","jpg","jpeg","gif","webp","svg"]);function Ug(e){const t=e.match(Lg);if(!t)return{files:[],textContent:e};const s=t[1].split(`
54
- `).filter(o=>o.startsWith("- ")).map(o=>{var f;const i=o.slice(2).trim(),u=(i.split("/").pop()??i).replace(zg,""),d=((f=u.split(".").pop())==null?void 0:f.toLowerCase())??"";return{path:i,displayName:u,isImage:Bg.has(d)}}),a=e.slice(t[0].length).trim();return{files:s,textContent:a}}function qg(e){var n;switch(((n=e.split(".").pop())==null?void 0:n.toLowerCase())??""){case"txt":case"md":case"log":return Wu;case"ts":case"tsx":case"js":case"jsx":case"json":case"py":case"rs":case"go":return od;case"csv":case"xls":case"xlsx":return yd;case"png":case"jpg":case"jpeg":case"gif":case"webp":case"svg":return bd;default:return Ma}}function Hg({files:e}){const t=oe(n=>n.selectedCwd);return e.length===0?null:r.jsx("div",{className:"flex flex-wrap gap-1.5 pb-1.5",children:e.map(n=>{const s=n.path.split("/").pop()??n.path;if(n.isImage){const o=`/api/uploads/${encodeURIComponent(s)}?cwd=${encodeURIComponent(t??"")}`;return r.jsx(G.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{duration:.15},children:r.jsx("a",{href:o,target:"_blank",rel:"noopener noreferrer",children:r.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=qg(n.displayName);return r.jsxs(G.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:[r.jsx(a,{className:"text-muted-foreground size-3 shrink-0"}),r.jsx("span",{className:"max-w-40 truncate",children:n.displayName})]},n.path)})})}function Wg({message:e}){var i;const t=(i=Sp())==null?void 0:i.sessionId,[n,s]=c.useState(!1),a=c.useMemo(()=>Ug(e.content),[e.content]),o=c.useMemo(()=>Cf(e.content),[e.content]);if(o)return r.jsx(vf,{action:o});if(e.chatMessages&&e.chatMessages.length>0)return r.jsx(up,{stamps:e.chatMessages,...t?{sessionId:t}:{}});if(e.messageType==="command")return r.jsx("div",{className:"text-msg-command-fg font-mono text-sm break-words",children:e.content});if(e.messageType==="local_command_output")return r.jsx(_o,{content:e.content,toolName:""});if(e.messageType==="compaction"){const l=Dp(e.compactMetadata),u=e.content.trim(),d=r.jsx("div",{className:"bg-border/40 h-px flex-1"});return u.length===0?r.jsxs("div",{"data-testid":"compaction-row",className:"text-msg-compaction-fg flex w-full items-center gap-2 text-xs",children:[d,r.jsx("span",{children:l}),d]}):r.jsxs("div",{className:"w-full","data-testid":"compaction-row",children:[r.jsxs("button",{onClick:()=>s(!n),className:"text-msg-compaction-fg flex w-full items-center gap-2 text-xs",children:[d,r.jsx(cs,{className:H("size-3 transition-transform duration-200",n&&"rotate-90")}),r.jsx("span",{children:l}),d]}),n&&r.jsx("div",{className:"text-msg-compaction-fg mt-2 text-xs whitespace-pre-wrap",children:e.content})]})}return r.jsxs("div",{children:[a.files.length>0&&r.jsx(Hg,{files:a.files}),a.textContent&&r.jsx("div",{className:"break-words whitespace-pre-wrap",children:a.textContent})]})}function Vg({tasks:e,isCollapsed:t,onToggleCollapse:n}){const s=e.length,a=e.filter(l=>l.status==="completed").length,o=a===s&&s>0,i=s>0?a/s*100:0;return r.jsxs("button",{onClick:n,className:"text-muted-foreground hover:text-foreground flex w-full items-center gap-2 text-xs",children:[t?r.jsx(cs,{className:"size-(--size-icon-xs) shrink-0"}):r.jsx(Et,{className:"size-(--size-icon-xs) shrink-0"}),r.jsx("div",{className:"bg-muted h-0.5 flex-1 overflow-hidden rounded-full",children:r.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:`${i}%`}})}),r.jsxs("span",{className:"shrink-0 tabular-nums",children:[a,"/",s," ",s===1?"task":"tasks"]})]})}function Gg({activeForm:e,isCollapsed:t}){return r.jsx(ie,{children:e&&!t&&r.jsxs(G.div,{variants:Ue,initial:"initial",animate:"animate",exit:"exit",transition:Be,className:"mb-1 flex items-center gap-2 text-xs text-blue-400",children:[r.jsx(ze,{size:"xs",className:"shrink-0"}),r.jsx("span",{className:"truncate",children:e})]})})}const Kg={in_progress:"",pending:"waiting ",completed:"done "};function wr({tasks:e,onScrollToTask:t}){return r.jsx(r.Fragment,{children:e.map((n,s)=>r.jsxs("span",{children:[r.jsx("button",{onClick:a=>{a.stopPropagation(),t(n.id)},className:"hover:text-foreground underline decoration-dotted",children:n.subject}),s<e.length-1&&", "]},n.id))})}function Qg({task:e,taskMap:t,statusSince:n,onScrollToTask:s}){var d,f;const a=Pa(n),o=Kg[e.status]??"",i=((d=e.blockedBy)==null?void 0:d.map(h=>t.get(h)).filter(h=>h!=null))??[],l=((f=e.blocks)==null?void 0:f.map(h=>t.get(h)).filter(h=>h!=null))??[],u=[];return n!==null&&u.push(r.jsxs("span",{children:[o,a.formatted]},"time")),e.owner&&u.push(r.jsx("span",{children:e.owner},"owner")),i.length>0&&u.push(r.jsxs("span",{className:"inline-flex items-center gap-1",children:["← ",r.jsx(wr,{tasks:i,onScrollToTask:s})]},"blocked-by")),l.length>0&&u.push(r.jsxs("span",{className:"inline-flex items-center gap-1",children:["→ ",r.jsx(wr,{tasks:l,onScrollToTask:s})]},"blocks")),r.jsxs(G.div,{variants:Ue,initial:"initial",animate:"animate",exit:"exit",transition:Be,className:"mt-0.5 ml-6 space-y-1",children:[e.description&&r.jsx("p",{className:"text-muted-foreground text-xs whitespace-pre-wrap",children:e.description}),u.length>0&&r.jsx("div",{className:"text-muted-foreground text-2xs flex flex-wrap items-center gap-1",children:u.map((h,m)=>r.jsxs("span",{className:"flex items-center gap-1",children:[m>0&&r.jsx("span",{className:"text-muted-foreground/50",children:"·"}),h]},m))})]})}const Nr={in_progress:r.jsx(ze,{size:"xs",className:"text-status-info shrink-0"}),pending:r.jsx(Bl,{className:"text-muted-foreground size-(--size-icon-xs) shrink-0"}),completed:r.jsx(ba,{className:"text-status-success size-(--size-icon-xs) shrink-0"})};function Yg({task:e,isBlocked:t,isExpanded:n,onToggleExpand:s,onHover:a,isHighlightedAsDep:o,isHighlightedAsDependent:i,taskMap:l,statusSince:u,isCelebrating:d,onCelebrationComplete:f,onScrollToTask:h}){const m=x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),s())};return r.jsxs(G.li,{"data-task-id":e.id,children:[r.jsxs("div",{role:"button",tabIndex:0,"aria-expanded":n,"data-task-id":e.id,onClick:s,onKeyDown:m,onMouseEnter:()=>a(e.id),onMouseLeave:()=>a(null),className:H("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",i&&"border-l-2 border-amber-400 pl-1.5",!o&&!i&&"border-l-2 border-transparent pl-1.5"),children:[d&&r.jsx(G.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?r.jsx(G.span,{initial:{scale:1},animate:{scale:[1,1.4,1]},transition:{type:"spring",stiffness:400,damping:10},onAnimationComplete:()=>f==null?void 0:f(),children:Nr[e.status]}):Nr[e.status],r.jsx("span",{className:"truncate",children:e.subject})]}),r.jsx(ie,{children:n&&r.jsx(Qg,{task:e,taskMap:l,statusSince:u,onScrollToTask:h})})]})}function Xg(e,t){var n;return(n=e.blockedBy)!=null&&n.length?e.blockedBy.some(s=>{const a=t.get(s);return a&&a.status!=="completed"}):!1}const Jg=10,Zg="max-h-[30svh] sm:max-h-[40svh]";function ex({tasks:e,taskMap:t,activeForm:n,isCollapsed:s,onToggleCollapse:a,celebratingTaskId:o,onCelebrationComplete:i,statusTimestamps:l}){const[u,d]=c.useState(null),[f,h]=c.useState(null),m=c.useCallback(b=>{d(y=>y===b?null:b)},[]),x=c.useCallback(b=>{const y=document.querySelector(`[data-task-id="${b}"]`);y&&(y.scrollIntoView({behavior:"smooth",block:"nearest"}),y.classList.add("bg-blue-500/10"),setTimeout(()=>y.classList.remove("bg-blue-500/10"),1e3))},[]);if(e.length===0)return null;const g=e.slice(0,Jg),S=f?t.get(f):null;return r.jsxs("div",{className:"border-t px-4 py-2",children:[r.jsx(Gg,{activeForm:n,isCollapsed:s}),r.jsx(Vg,{tasks:e,isCollapsed:s,onToggleCollapse:a}),r.jsx(ie,{children:!s&&r.jsx(G.ul,{variants:Ue,initial:"initial",animate:"animate",exit:"exit",transition:Be,className:H("mt-1 space-y-0.5 overflow-y-auto",Zg),children:g.map(b=>{var _,D;const y=b.id===o&&b.status==="completed",C=Xg(b,t),v=l.get(b.id),p=((_=S==null?void 0:S.blockedBy)==null?void 0:_.includes(b.id))??!1,j=((D=S==null?void 0:S.blocks)==null?void 0:D.includes(b.id))??!1;return r.jsx(Yg,{task:b,isBlocked:C,isExpanded:u===b.id,onToggleExpand:()=>m(b.id),onHover:h,isHighlightedAsDep:p,isHighlightedAsDependent:j,taskMap:t,statusSince:(v==null?void 0:v.since)??null,isCelebrating:y,onCelebrationComplete:i,onScrollToTask:x},b.id)})})})]})}function tx({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 r.jsx("div",{className:"pointer-events-none absolute inset-0",children:t.map((n,s)=>r.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`}},s))})}const nx=350;function sx({status:e,color:t}){return r.jsxs("svg",{className:"check-appear h-6 w-[22px]",viewBox:"0 0 22 24","data-status":e,children:[r.jsx("circle",{cx:"11",cy:"12",r:"7",fill:"none",stroke:t,strokeWidth:"1.5",opacity:"0.3"}),e==="error"&&r.jsxs(r.Fragment,{children:[r.jsx("line",{x1:"8",y1:"9",x2:"14",y2:"15",stroke:t,strokeWidth:"2",strokeLinecap:"round"}),r.jsx("line",{x1:"14",y1:"9",x2:"8",y2:"15",stroke:t,strokeWidth:"2",strokeLinecap:"round"})]}),e==="untracked"&&r.jsx("line",{x1:"8",y1:"12",x2:"14",y2:"12",stroke:t,strokeWidth:"2",strokeLinecap:"round",opacity:"0.5"}),e!=="error"&&e!=="untracked"&&r.jsx("polyline",{points:"7,12 10,15 15,9",fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]})}function rx({agent:e,index:t}){const n=c.useMemo(()=>({animationDelay:`${t*.09}s`}),[t]),[s,a]=c.useState(e.status==="running"?"running":"done"),o=c.useRef(e.status),i=c.useRef(null);return c.useEffect(()=>{const l=o.current;if(o.current=e.status,l==="running"&&e.status!=="running"){a("celebrating"),i.current=setTimeout(()=>a("done"),nx);return}l!=="running"&&e.status==="running"&&(i.current&&clearTimeout(i.current),i.current=null,a("running"))},[e.status]),c.useEffect(()=>()=>{i.current&&clearTimeout(i.current)},[]),s==="done"?r.jsx("div",{className:"relative inline-flex",children:r.jsx(sx,{status:e.status,color:e.color})}):r.jsxs("div",{className:"group relative inline-flex",children:[r.jsx("svg",{className:"h-6 w-[22px] shrink-0",style:{"--c":e.color},viewBox:"0 0 22 24","aria-label":e.description,children:r.jsxs("g",{className:"r-all",style:n,children:[r.jsx("circle",{cx:"11",cy:"4.5",r:"2.8",fill:"var(--c)"}),r.jsx("circle",{cx:"12.3",cy:"3.7",r:"0.6",fill:"hsl(0 0% 100% / 0.7)"}),r.jsx("ellipse",{cx:"11",cy:"10.5",rx:"2.5",ry:"3.5",fill:"var(--c)"}),r.jsxs("g",{className:"r-rua",style:n,children:[r.jsx("line",{x1:"12",y1:"9",x2:"14",y2:"11",stroke:"var(--c)",strokeWidth:"1.8",strokeLinecap:"round"}),r.jsx("g",{className:"r-rfa",style:n,children:r.jsx("line",{x1:"14",y1:"11",x2:"14.5",y2:"13",stroke:"var(--c)",strokeWidth:"1.8",strokeLinecap:"round"})})]}),r.jsxs("g",{className:"r-lua",style:n,children:[r.jsx("line",{x1:"10",y1:"9",x2:"8",y2:"11",stroke:"var(--c)",strokeWidth:"1.8",strokeLinecap:"round"}),r.jsx("g",{className:"r-lfa",style:n,children:r.jsx("line",{x1:"8",y1:"11",x2:"7.5",y2:"13",stroke:"var(--c)",strokeWidth:"1.8",strokeLinecap:"round"})})]}),r.jsxs("g",{className:"r-rt",style:n,children:[r.jsx("line",{x1:"11",y1:"14",x2:"13",y2:"17",stroke:"var(--c)",strokeWidth:"1.8",strokeLinecap:"round"}),r.jsx("g",{className:"r-rs",style:n,children:r.jsx("line",{x1:"13",y1:"17",x2:"13.5",y2:"21",stroke:"var(--c)",strokeWidth:"1.8",strokeLinecap:"round"})})]}),r.jsxs("g",{className:"r-lt",style:n,children:[r.jsx("line",{x1:"11",y1:"14",x2:"9",y2:"17",stroke:"var(--c)",strokeWidth:"1.8",strokeLinecap:"round"}),r.jsx("g",{className:"r-ls",style:n,children:r.jsx("line",{x1:"9",y1:"17",x2:"8.5",y2:"21",stroke:"var(--c)",strokeWidth:"1.8",strokeLinecap:"round"})})]})]})}),s==="celebrating"&&r.jsx(tx,{color:e.color}),s==="running"&&r.jsxs("div",{"data-testid":"agent-runner-tooltip",className:H("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:[r.jsxs("div",{className:"mb-0.5 flex items-center gap-1.5 font-semibold",children:[r.jsx("div",{className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:e.color}}),e.description]}),r.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&&r.jsxs("div",{className:"text-muted-foreground/60 text-3xs mt-0.5 font-mono",children:["Last: ",e.lastToolName]}),r.jsx("div",{className:"border-t-border absolute top-full left-1/2 -translate-x-1/2 border-5 border-transparent"})]})]})}function ax({bashTasks:e}){const t=Te(),n=e.filter(a=>a.taskType==="bash"),s=n.length;return s===0?null:r.jsxs("div",{role:"status","aria-live":"polite","aria-label":`${s} bash task${s!==1?"s":""} running`,className:"flex items-center gap-1.5",children:[r.jsx(ie,{mode:"popLayout",children:n.map(a=>r.jsxs(G.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&&r.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"}}),r.jsx("span",{className:"relative size-1.5 rounded-full",style:{backgroundColor:a.color}})]},a.taskId))}),r.jsxs("span",{className:"text-muted-foreground text-xs whitespace-nowrap",children:[s," task",s!==1?"s":""]})]})}const ox=3e3;function ix({taskType:e,onConfirm:t}){const[n,s]=c.useState(!1),a=c.useRef(null);c.useEffect(()=>()=>{a.current&&clearTimeout(a.current)},[]),c.useEffect(()=>{if(n)return a.current=setTimeout(()=>{s(!1)},ox),()=>{a.current&&clearTimeout(a.current)}},[n]);const o=c.useCallback(()=>{if(e==="bash"){t();return}n?(a.current&&clearTimeout(a.current),s(!1),t()):s(!0)},[e,n,t]),i=c.useCallback(l=>{(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),o())},[o]);return r.jsx("button",{onClick:o,onKeyDown:i,className:H("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?":r.jsx(Le,{className:"size-3"})})}function Er({task:e,onStop:t}){const n=e.taskType==="agent"?e.description??"Background agent":e.command??"Background task",s=e.durationMs?Math.round(e.durationMs/1e3):0,a=e.status==="running";return r.jsxs("div",{className:H("flex items-center gap-2 rounded-md px-2 py-1 text-xs",a?"bg-muted":"bg-muted/50 opacity-60"),children:[r.jsx("span",{className:"size-2 shrink-0 rounded-full",style:{backgroundColor:e.color}}),r.jsx("span",{className:"text-muted-foreground/60 text-3xs shrink-0 tracking-wider uppercase",children:e.taskType}),r.jsx("span",{className:"text-foreground min-w-0 flex-1 truncate",children:n}),e.taskType==="agent"&&e.toolUses!==void 0&&e.toolUses>0&&r.jsxs("span",{className:"text-muted-foreground/60 text-3xs shrink-0 font-mono",children:[e.toolUses," tools"]}),e.taskType==="agent"&&e.lastToolName&&r.jsxs("span",{className:"text-muted-foreground/60 text-3xs hidden max-w-24 shrink-0 truncate font-mono md:inline",children:["Last: ",e.lastToolName]}),s>0&&r.jsxs("span",{className:"text-muted-foreground/60 text-3xs shrink-0 font-mono",children:[s,"s"]}),a&&r.jsx(ix,{taskType:e.taskType,onConfirm:t})]})}function lx({tasks:e,ambientTasks:t=[],onStopTask:n}){return r.jsx(G.div,{variants:Ue,initial:"initial",animate:"animate",exit:"exit",transition:Be,className:"border-border overflow-hidden border-t px-2 py-1.5",children:r.jsxs("div",{className:"flex flex-col gap-1",children:[e.map(s=>r.jsx(Er,{task:s,onStop:()=>n(s.taskId)},s.taskId)),t.length>0&&r.jsxs(r.Fragment,{children:[r.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(s=>r.jsx(Er,{task:s,onStop:()=>n(s.taskId)},s.taskId))]})]})})}const Kn=4;function cx(e){return e==="stopped"?"complete":e}const ux="relative after:absolute after:-inset-x-1 after:-inset-y-2.5 md:after:hidden",Io=[.16,1,.3,1],dx={width:{duration:.4,ease:Io},opacity:{duration:.25}};function fx({tasks:e,onStopTask:t}){const[n,s]=c.useState(!1),a=Te(),{shown:o,ambient:i}=Xc(e),l=o.filter(b=>b.taskType==="agent"),u=o.filter(b=>b.taskType==="bash"),d=o.length,f=l.slice(0,Kn),h=l.length-Kn,m=l.reduce((b,y)=>b+(y.toolUses??0),0),x=Math.max(0,...o.map(b=>Math.round((b.durationMs??0)/1e3))),g=a?{duration:0}:{duration:.35,ease:Io},S=d>0;return r.jsx(ie,{children:(d>0||i.length>0)&&r.jsxs(G.div,{...S?{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:[r.jsxs("div",{className:"flex min-h-9 items-center gap-2 px-2 py-1.5",children:[l.length>0&&r.jsx(mx,{visibleAgents:f,overflowAgentCount:h,allAgentTasks:l}),l.length>0&&u.length>0&&r.jsx("div",{className:"bg-border h-4 w-px shrink-0"}),u.length>0&&r.jsx(ax,{bashTasks:u}),d>0&&r.jsxs(r.Fragment,{children:[r.jsxs("span",{className:"text-muted-foreground text-xs whitespace-nowrap",children:[r.jsx("strong",{className:"text-foreground font-semibold",children:d})," task",d!==1?"s":""," running"]}),r.jsxs("span",{className:"text-muted-foreground/60 text-2xs ml-auto font-mono whitespace-nowrap",children:[m>0&&r.jsxs(r.Fragment,{children:[m," tools · "]}),x,"s"]})]}),r.jsxs("button",{type:"button",onClick:()=>s(b=>!b),className:H("text-muted-foreground hover:text-foreground flex shrink-0 items-center gap-1 transition-colors duration-150",d>0?"ml-1":"ml-auto",ux),"aria-label":n?"Collapse task details":"Expand task details","aria-expanded":n,children:[d>0&&r.jsx("span",{className:"text-3xs tabular-nums",children:d}),r.jsx(Et,{className:H("size-3.5 transition-transform duration-200",n&&"rotate-180")})]})]}),r.jsx(ie,{children:n&&r.jsx(lx,{tasks:o,ambientTasks:i,onStopTask:t})})]},"background-task-bar")})}function mx({visibleAgents:e,overflowAgentCount:t,allAgentTasks:n}){return r.jsxs("div",{className:"flex items-center gap-0",children:[r.jsx(ie,{mode:"popLayout",children:e.map((s,a)=>r.jsx(G.div,{initial:{width:0,opacity:0},animate:{width:22,opacity:1},exit:{width:0,opacity:0},transition:dx,className:"shrink-0",children:r.jsx(rx,{agent:{taskId:s.taskId,description:s.description??"",status:cx(s.status),color:s.color,toolUses:s.toolUses,lastToolName:s.lastToolName,durationMs:s.durationMs,summary:s.summary},index:a})},s.taskId))}),t>0&&r.jsx(px,{count:t,overflowTasks:n.slice(Kn)})]})}function px({count:e,overflowTasks:t}){return r.jsxs("div",{className:"group relative",children:[r.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]}),r.jsxs("div",{"data-testid":"overflow-badge-tooltip",className:H("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=>r.jsxs("div",{className:"flex items-center gap-1.5 py-0.5",children:[r.jsx("div",{className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:n.color}}),r.jsx("span",{className:"text-3xs",children:n.description})]},n.taskId)),r.jsx("div",{className:"border-t-border absolute top-full left-1/2 -translate-x-1/2 border-5 border-transparent"})]})]})}const An="after:absolute after:-inset-1 md:after:hidden";function hx({queue:e,editingId:t,onEdit:n,onRemove:s,onSend:a,onMoveUp:o,statusNote:i,onSwitchNow:l}){return e.length===0?null:r.jsxs(G.div,{variants:Ue,initial:"initial",animate:"animate",exit:"exit",transition:Be,className:"mb-1.5 overflow-hidden",children:[r.jsxs("div",{className:"text-muted-foreground mb-1 flex items-baseline gap-1 text-xs",children:[r.jsxs("span",{className:"font-medium",children:["Queued (",e.length,")"]}),r.jsxs("span",{className:"truncate",children:["· ",i]})]}),r.jsx("div",{className:"space-y-0.5",children:r.jsx(ie,{mode:"popLayout",children:e.map((u,d)=>r.jsx(G.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:r.jsxs("div",{className:H("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:[r.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:[r.jsxs("span",{className:"text-muted-foreground shrink-0 text-xs font-medium",children:[d+1,"."]}),r.jsxs("span",{className:"min-w-0 flex-1",children:[r.jsx("span",{className:"text-muted-foreground line-clamp-1 text-sm",children:u.content}),u.notice!==null&&r.jsx("span",{className:"text-muted-foreground/70 line-clamp-1 text-xs",children:u.notice}),u.waiting!==void 0&&r.jsx("span",{className:"text-muted-foreground/70 line-clamp-1 text-xs",children:u.waiting.line})]}),!u.mine&&r.jsxs("span",{className:"text-muted-foreground/60 flex shrink-0 items-center",title:"Queued from another window",children:[r.jsx(zn,{className:"size-3","aria-hidden":"true"}),r.jsx("span",{className:"sr-only",children:"Queued from another window"})]})]}),u.waiting!==void 0&&l!==void 0&&r.jsxs(r.Fragment,{children:[r.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"}),r.jsx("span",{id:`switch-now-${u.id}`,className:"sr-only",children:u.waiting.switchHint})]}),d>0&&r.jsx("button",{type:"button",onClick:()=>o(u.id),className:H("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",An),"aria-label":`Move queued message ${d+1} earlier`,children:r.jsx(Ul,{className:"size-3"})}),d>0&&r.jsx("button",{type:"button",onClick:()=>a(u.id),"aria-label":`Send queued message ${d+1} next`,className:H("focus-ring text-muted-foreground hover:text-foreground relative flex size-6 shrink-0 items-center justify-center rounded-sm transition-colors",An),children:r.jsx(Qu,{className:"size-3"})}),r.jsx("button",{type:"button",onClick:()=>s(u.id),className:H("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",An),"aria-label":`Remove queued message ${d+1}`,children:r.jsx(Le,{className:"size-3"})})]})},u.id))})})]})}function gx({open:e,onOpenChange:t,queuedCount:n,onConfirm:s}){const a=n===1?"message":"messages";return r.jsx(ql,{open:e,onOpenChange:t,children:r.jsxs(Hl,{children:[r.jsxs(Wl,{children:[r.jsxs(Vl,{children:["Stop, and put ",n," queued ",a," back?"]}),r.jsxs(Gl,{children:["The agent stops. Your ",a," ",n===1?"goes":"go"," back to the composer."]})]}),r.jsxs(Kl,{children:[r.jsx(Ql,{children:"Keep going"}),r.jsx(Yl,{onClick:s,children:"Stop"})]})]})})}const xx={initial:{opacity:0,y:4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4}},bx={duration:.3,ease:"easeInOut"};function yx({text:e,animationKey:t}){return r.jsx("div",{className:"pointer-events-none absolute inset-0 flex items-start overflow-hidden py-0.5",children:r.jsx(ie,{mode:"wait",children:r.jsx(G.span,{variants:xx,initial:"initial",animate:"animate",exit:"exit",transition:bx,className:"text-muted-foreground truncate text-sm",children:e},t)})})}function vx(e){const t=xe();return Ye({queryKey:["workspace-for-session",e??null],queryFn:()=>t.resolveWorkspace(e),enabled:!!e}).data??null}async function Oo(e,t,n){try{return await e.runCommandIntent(t,"compact",n),!0}catch(s){const a=s.code==="SESSION_LOCKED";return Ee.error(a?"Your agent is busy. Try again in a moment.":"Couldn’t compact the chat."),!1}}const Qn=rs(e=>({open:!1,setOpen:t=>e({open:t}),reveal:()=>e({open:!0})})),kx=200,Yn=[{name:"rename",description:"Rename the current chat",argHint:"<new title>",run:(e,t)=>{const n=e.replace(/\s+/g," ").trim().slice(0,kx).trim();return n?t.sessionId?(t.renameSession(n),!0):(t.notify("No open chat to rename","error"),!1):(t.notify("Usage: /rename <new title>","error"),!1)}},{name:"clear",description:"Start a new chat here",run:(e,t)=>(t.startFreshSession(t.sessionId),!0)},{name:"context",description:"Show context usage and cost",run:(e,t)=>(t.focusUsageSurface(),!0)}],Cx=/^\/(\S+)(?:\s+([\s\S]*))?$/;function $o(e){const t=Cx.exec(e);if(!t)return null;const n=t[1],s=(t[2]??"").trim(),a=ds(n);if(a&&a.fulfillment==="client-native"){const i=Yn.find(l=>l.name===a.id);if(i)return{command:i,args:s}}const o=Yn.find(i=>i.name===n.toLowerCase());return o?{command:o,args:s}:null}const Dr=Yn.map(e=>({command:e.name,fullCommand:`/${e.name}`,description:e.description,argumentHint:e.argHint}));function Po(e){const t=/^\/(\S+)([\s\S]*)$/.exec(e.trim());return t?{token:t[1],rest:t[2].trim()}:null}function Sx(e){const t=Po(e);return t?ds(t.token)?!0:$o(e.trim())!==null:!1}function jx(e,t,n={}){const{mutateAsync:s}=Xl(e),a=xe(),{startFreshSession:o,compact:i}=n,[l,u]=c.useState(0),d=c.useCallback(h=>{u(x=>x+1);const m=()=>u(x=>Math.max(0,x-1));h.then(m,m)},[]);return{tryRun:c.useCallback(h=>{const m=Po(h),x=m?ds(m.token):null;if(m&&(x==null?void 0:x.fulfillment)==="runtime"&&i){if(!i.supported)return Ee.error(`Compact isn’t available on ${i.runtimeLabel||"this agent"}`),{handled:!0,ran:!1};if(!t)return Ee.error("No open chat to compact"),{handled:!0,ran:!1};const y=Oo(a,t,m.rest||void 0);return d(y),{handled:!0,ran:!0,confirmed:y}}const g=$o(h);if(!g)return{handled:!1};let S;return{handled:!0,ran:g.command.run(g.args,{sessionId:t,renameSession:y=>{t&&(S=s({sessionId:t,title:y}).then(()=>(Ee.success(`Renamed chat to “${y}”`),!0),()=>!1),d(S))},notify:(y,C)=>C==="error"?Ee.error(y):Ee.success(y),startFreshSession:y=>o==null?void 0:o(y),focusUsageSurface:()=>Qn.getState().reveal()}),...S?{confirmed:S}:{}}},[s,a,t,o,i,d]),commandPending:l>0}}function Lo(e,t){return{supported:(e==null?void 0:e.compact.supported)!==!1,runtimeLabel:t}}function Ar(e){const t=e.trim().toLowerCase();return t.startsWith("/")?t:`/${t}`}function _x(e){return Zl.map(t=>{var s,a;const n=t.fulfillment==="runtime"&&((a=(s=e==null?void 0:e.commandIntents)==null?void 0:s[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 wx(e,t){const n=Jl(),s=_x(t),a=Dr.filter(l=>!(l.command!==void 0&&n.has(`/${l.command}`))),o=new Set(Dr.map(l=>l.command)),i=e.filter(l=>{if(l.command!==void 0&&o.has(l.command))return!1;const u=[l.fullCommand,...l.aliases??[]].map(Ar);return l.command!==void 0&&u.push(Ar(l.command)),!u.some(d=>n.has(d))});return[...s,...a,...i]}const Nx=3e4;function Ex({percent:e,compactSupported:t,isStreaming:n}){return!(e===null||e<Jc||!t||n)}function Dx({sessionId:e,percent:t,compactSupported:n,isStreaming:s}){const a=xe(),[o,i]=c.useState(!1),l=c.useRef(!1),u=c.useRef(null),d=c.useCallback(()=>{l.current=!1,i(!1),u.current!==null&&(clearTimeout(u.current),u.current=null)},[]);c.useEffect(()=>{s&&l.current&&d()},[s,d]),c.useEffect(()=>()=>{u.current!==null&&clearTimeout(u.current)},[]);const f=c.useCallback(()=>{l.current||!e||(l.current=!0,i(!0),u.current=setTimeout(()=>{u.current=null,l.current=!1,i(!1)},Nx),Oo(a,e).then(h=>{h||d()}))},[e,a,d]);return{visible:Ex({percent:t,compactSupported:n,isStreaming:s}),percent:t??0,pending:o,onCompact:f}}function Ax({children:e,onSwitchAgent:t,onViewProfile:n,onNewSession:s}){return r.jsxs(ec,{children:[r.jsx(tc,{className:"min-w-0",children:e}),r.jsxs(nc,{className:"w-48",children:[r.jsxs(mn,{onClick:t,children:[r.jsx(sc,{className:"mr-2 size-4"}),"Switch agent"]}),r.jsx(Ps,{}),r.jsxs(mn,{onClick:n,children:[r.jsx(rc,{className:"mr-2 size-4"}),"View profile"]}),r.jsx(Ps,{}),r.jsxs(mn,{onClick:s,children:[r.jsx(ua,{className:"mr-2 size-4"}),"New chat"]})]})]})}function Tx({agentName:e,agentColor:t,agentEmoji:n,agentPath:s,nameHidden:a}){const o=ac(s),{open:i}=oc(),l=c.useCallback(()=>{s&&ic.getState().openProfileDocked(s)},[s]),u=c.useCallback(()=>{if(o===void 0)return l();i(o)},[o,i,l]),d=c.useCallback(()=>{oe.getState().openGlobalPaletteWithSearch("@")},[]),f=ha(),h=c.useCallback(()=>{f(s??void 0)},[f,s]);return!e||!t||!n?null:r.jsx("span",{className:"inline-flex min-w-0 items-center",children:s?r.jsx(Ax,{onSwitchAgent:d,onViewProfile:u,onNewSession:h,children:r.jsx(Ls,{size:"xs",name:e,color:t,emoji:n,nameHidden:a,onClick:u,className:"max-w-full"})}):r.jsx(Ls,{size:"xs",name:e,color:t,emoji:n,nameHidden:a,className:"max-w-full"})})}function Fx({sessionId:e,account:t}){const[n,s]=c.useState(!1),[a,o]=c.useState(!1),i=c.useRef(null);return r.jsxs(r.Fragment,{children:[r.jsx("span",{ref:i,className:"contents",children:r.jsx(lc,{sessionId:e,account:t,open:n,onOpenChange:s,onContinue:()=>{s(!1),o(!0)}})}),r.jsx(ro,{open:a,onOpenChange:o,sessionId:e,account:t,onCloseAutoFocus:l=>{var d;const u=(d=i.current)==null?void 0:d.querySelector("button");u&&(l.preventDefault(),u.focus())}})]})}function Rx({ctx:e,items:t}){return r.jsx("span",{className:"inline-flex min-w-0 items-center gap-2",children:t.map((n,s)=>{const a=n.component;return r.jsxs(c.Fragment,{children:[s>0&&r.jsx("span",{className:"text-muted-foreground/30 shrink-0","aria-hidden":"true",children:"·"}),r.jsx("span",{role:"group","aria-label":n.label,"data-testid":`extension-status-item-${n.id}`,className:"inline-flex min-w-0 items-center",children:r.jsx(ka,{fallback:null,onError:o=>zo(n,o),children:r.jsx(a,{...e})})})]},n.id)})})}function zo(e,t){console.warn(`[extensions] ${e.extensionId}'s status-bar item "${e.id}" failed to draw and is hidden.`,t)}function Mx({ctx:e,items:t}){return r.jsx(r.Fragment,{children:t.map(n=>{const s=n.component;return r.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:[r.jsx("span",{className:"shrink-0",children:n.label}),r.jsx("span",{className:"min-w-0 flex-1"}),r.jsx("span",{className:"text-muted-foreground inline-flex min-w-0 items-center text-xs",children:r.jsx(ka,{fallback:null,onError:a=>zo(n,a),children:r.jsx(s,{...e})})})]},n.id)})})}function Ix(e){const{costUsd:t,costBasis:n,...s}=e;return s}function Ox(e){var f;const{sessionId:t,agent:n,status:s,runtimeChip:a,onUpdateSession:o}=e,i={},l=e.density!=="full";n.name&&n.color&&n.emoji&&(i.agent=r.jsx(Tx,{agentName:n.name,agentColor:n.color,agentEmoji:n.emoji,agentPath:n.path,nameHidden:e.density==="avatar"})),s.cwd&&(i.cwd=r.jsx(Zc,{cwd:s.cwd})),e.gitStatus&&(i.git=r.jsx(lu,{data:e.gitStatus,workspace:e.workspace,compact:l})),a.runtime!==null&&(i.runtime=r.jsx(eu,{runtime:a.runtime,model:a.model,onChangeRuntime:a.onChangeRuntime,canSelect:a.canSelect,account:a.account,compact:!0}));const u=Ca(e.account);u!==null&&(i.account=r.jsx(Fx,{sessionId:t,account:e.account})),e.extensions.items.length>0&&(i.extensions=r.jsx(Rx,{ctx:e.extensions.ctx,items:e.extensions.items})),i.model=r.jsx(tu,{model:s.model,onChangeModel:h=>o({model:h}),effort:s.effort,onChangeEffort:h=>o({effort:h??void 0}),fastMode:s.fastMode,onChangeFastMode:h=>o({fastMode:h}),disabled:!t,sessionId:t||void 0,runtime:a.runtime,onCredits:e.account.onCredits,compact:l}),(f=e.plan)!=null&&f.active||(i.permission=r.jsx(nu,{mode:s.permissionMode,onChangeMode:e.onChangeMode,disabled:!t,pending:!s.permissionModeKnown,runtime:a.runtime,modelSupportsAutoMode:e.modelSupportsAutoMode,compact:l,makeDefault:e.makeDefault,onOpenChange:e.onPermissionPickerOpenChange})),e.plan&&(i.plan=r.jsx(su,{descriptor:e.plan.descriptor,active:e.plan.active,onToggle:e.plan.onToggle,disabled:!t})),e.contextPercent!==null&&(i.context=r.jsx(ru,{percent:e.contextPercent,contextUsage:e.contextUsage,compact:e.compact,reading:e.contextReading}));const d=e.usage&&e.usageSource==="account"&&!e.supportsCostTracking?Ix(e.usage):e.usage;return d&&cc(d)&&(e.supportsCostTracking||e.usageSource==="account")&&!au({account:u})&&(i.usage=r.jsx(uc,{usage:d,observedAt:e.usageObservedAt,now:e.now})),e.liveSubagentCount>0&&(i.subagents=r.jsx(ou,{count:e.liveSubagentCount,running:e.runningSubagents,waiting:e.waitingOnSubagents})),i.connection=r.jsx(iu,{connectionState:e.connectionState,compact:l}),i}const $x=[],Px="(max-width: 639px)";function Lx({sessionId:e,sessionStatus:t,isStreaming:n,syncConnectionState:s,agentName:a,agentColor:o,agentEmoji:i,agentPath:l}){var Ie,qe;const{ref:u,budget:d}=cu(),f=Sa(e),h=Fa(e,t,n,f.runtime),m=wt(e||null),{pins:x}=uu(),g=du(e),S=fu(e,m,g.usage),b=S.usage,y=jt(),C=new Date(y),v=dc(b,S.observedAt,C),p=g.contextUsage,j=((Ie=fs(e))==null?void 0:Ie.contextUsage)??null,_=Qn(re=>re.open),D=Qn(re=>re.setOpen),{data:T}=mu(h.cwd),N=vx(h.cwd),{project:A}=fc(h.cwd),k=mc(Px),E=c.useMemo(()=>({sessionId:e,cwd:h.cwd,project:A,trackerItems:m.trackerItems,compact:k}),[e,h.cwd,A,m.trackerItems,k]),w=pu(E),{data:R}=is(),O=hu(g.activeSubagents).running,F=g.runningSubagentCount??O.length,{data:$}=os({sessionId:e||void 0,runtime:f.runtime??void 0}),B=((qe=$==null?void 0:$.find(re=>re.value===h.model))==null?void 0:qe.supportsAutoMode)??!1,q=Zt(f.runtime),Y=(q==null?void 0:q.permissionModes.values)??$x,se=q==null?void 0:q.permissionModes.default,V=pc(e),L=te(re=>re.recordAutoConfirmed),[I,P]=c.useState(!1),Q=gu({sessionId:e,runtime:f.runtime,declaredModes:Y,runtimeDefaultMode:se}),[ae,M]=c.useState(!1),W=c.useCallback(re=>h.updateSession({permissionMode:re}),[h]),X=c.useCallback(re=>{if(re==="auto"&&!V){P(!0);return}W(re).then(Ce=>{Ce&&Q.offerFor(re)})},[V,W,Q,P]),J=c.useCallback(()=>{L(e),W("auto"),P(!1)},[L,e,W,P]),Z=hc(Y),K=Z!==void 0&&h.permissionMode===Z.id,le=gc(e),fe=te(re=>re.recordModeBeforePlan),me=c.useCallback(re=>{if(!Z)return;if(re){fe(e,h.permissionMode),W(Z.id);return}const Ce=le,$e=Ce!==void 0&&Y.some(Xe=>Xe.id===Ce)&&(Ce!=="auto"||B)?Ce:se;$e&&W($e)},[Z,fe,e,h,W,le,Y,B,se]),z=f.runtime?Dt(f.runtime).label:"",he=Lo(q==null?void 0:q.commandIntents,z),ce=g.contextPercent,je=Dx({sessionId:e,percent:ce,compactSupported:he.supported,isStreaming:n}),[ke,De]=c.useState(!1);xu(()=>De(re=>!re));const Me={cwd:h.cwd,git:bu(T)?yu(T.branch,T.clean,T.detached):null,contextPercent:ce,connectionState:s,permissionMode:h.permissionMode,permissionDescriptor:(q==null?void 0:q.permissionModes.values.find(re=>re.id===h.permissionMode))??null,permissionPickerOpen:ae,plan:Z?{active:K}:null,runtime:f.runtime===null||R===void 0?null:{type:f.runtime,isDefault:f.runtime===R.defaultRuntime,canSelect:f.canSelect},account:Ca(m),usage:b,usageStale:v,subagentsInFlight:F,extensionItems:w.promotion},de=je.visible&&d.density==="full",Oe=je.visible&&!de,ye=Ox({sessionId:e,agent:{name:a,color:o,emoji:i,path:l},status:h,onUpdateSession:h.updateSession,onChangeMode:X,makeDefault:ae?Q.line:null,onPermissionPickerOpenChange:M,modelSupportsAutoMode:B,plan:Z?{descriptor:Z,active:K,onToggle:me}:null,gitStatus:T,workspace:N,runtimeChip:f,account:m,contextPercent:ce,contextUsage:p,contextReading:j,compact:de?{pending:je.pending,onCompact:je.onCompact}:null,usage:b,usageSource:S.source,usageObservedAt:S.observedAt,now:C,supportsCostTracking:(q==null?void 0:q.supportsCostTracking)??!0,runningSubagents:O,liveSubagentCount:F,waitingOnSubagents:g.lifecycle==="idle",connectionState:s,density:d.density,extensions:{ctx:E,items:w.visible}}),{items:_e,overflow:be}=vu(ku({ctx:Me,pins:x,nodes:ye}),d);return r.jsxs("div",{ref:u,className:"relative pt-2",children:[!ae&&Q.line&&r.jsx(Cu,{...Q.line,placement:"overlay"}),r.jsx(Su,{items:_e,trailing:r.jsx(ju,{open:ke,onOpenChange:De,diagnostics:g,controls:{plan:Z?{active:K,onToggle:me}:null},promotionContext:Me,overflowCount:be,addOns:w.visible.length>0?r.jsx(Mx,{ctx:E,items:w.visible}):void 0,urgentAction:Oe?{label:`Compact chat · ${je.percent}% full`,onAction:je.onCompact,pending:je.pending}:null})}),r.jsx(_u,{usage:b??null,accountUsage:S.accountUsage,observedAt:S.observedAt,open:_,onOpenChange:D}),r.jsx(wu,{open:I,onOpenChange:P,onConfirm:J})]})}const zx=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 Bx(e){return e!==void 0&&e!=="completed"}function Ux(e){const t=zx[e];return t!==void 0?t:qx(e)}function qx(e){if(e.length===0)return"Ended";const t=e.replace(/[_-]+/g," ").trim().split(/\s+/);if(t.length===0)return"Ended";const[n,...s]=t;return[n.charAt(0).toUpperCase()+n.slice(1).toLowerCase(),...s.map(o=>o.toLowerCase())].join(" ")}function Hx({terminalReason:e}){const t=Bx(e),n=t?Ux(e):"";return r.jsx(ie,{children:t&&r.jsx(G.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:r.jsx(xc,{variant:"secondary","aria-label":`Chat ended: ${n}`,children:n})},e)})}const Wx="The turn ended before completing.";function Vx({sessionId:e,onRetry:t,onSigninComplete:n,onChooseModel:s}){var m;const a=tn(e),o=((m=fs(e))==null?void 0:m.lastError)??null,i=(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=!i&&a?`${Dt(a).label} stopped unexpectedly`:void 0,u=(o==null?void 0:o.message)??Wx,d=i?void 0:u,f=a?ls(a):void 0,h=o?[o.code,o.details].filter(Boolean).join(`
53
+ `)}function Dg(e){const t=e.pattern===!0&&e.verb==="read"?"Globbed":an[e.verb],n=e.verb==="run"?e.label:e.fullTarget,s=[`${t} ${n}`];return e.touches>1&&s.push(`${e.touches} times`),e.hits!==void 0&&s.push(xs(e.hits)),e.additions!==void 0&&s.push(`${e.additions} added`),e.deletions!==void 0&&s.push(`${e.deletions} removed`),e.error&&s.push("didn’t work"),s.join(", ")}const Sr="bg-muted text-muted-foreground shrink-0 rounded-full px-1.5 text-3xs leading-[1.4] tabular-nums";function Mo({chip:e,onOpen:t,animated:n=!1,pulseUpgrade:s=!1,onUpgradeSeen:a}){const o=Te()??!1,i=s&&!o,l=Ng(e),u=e.verb==="delete",d=e.additions!==void 0||e.deletions!==void 0,f=n&&(e.verb==="create"||e.verb==="delete");return r.jsxs(G.button,{...jg(n,o),type:"button","data-testid":"touch-chip","data-verb":e.verb,"data-live":e.live,"data-arriving":f?"true":void 0,title:Eg(e),"aria-label":Dg(e),onClick:()=>t(e),className:H("touch-chip relative inline-flex max-w-56 items-center gap-1.5 rounded-full border","px-2 py-0.5 text-xs","bg-card text-foreground border-border","focus-visible:ring-ring outline-none focus-visible:ring-2",l?"hover:bg-accent hover:text-accent-foreground":"cursor-default",u&&"text-muted-foreground line-through opacity-60",e.error&&"border-destructive/40 bg-destructive/10 text-destructive"),children:[r.jsx("span",{"aria-hidden":"true",className:"chip-sweep"}),r.jsxs("span",{className:"chip-icon relative inline-flex w-4 shrink-0 items-center justify-center leading-none",children:[r.jsx("span",{className:"chip-glyph inline-flex items-center justify-center [perspective:400px]",children:r.jsx(ie,{initial:!1,mode:"wait",children:r.jsx(G.span,{"aria-hidden":"true",initial:o?{opacity:0}:{opacity:0,rotateX:-90},animate:o?{opacity:1}:{opacity:1,rotateX:0},exit:o?{opacity:0}:{opacity:0,rotateX:90},transition:kr,children:rn[e.verb]},e.verb)})}),i&&r.jsx(G.span,{"aria-hidden":"true","data-testid":"chip-upgrade-pulse",className:"border-primary pointer-events-none absolute -inset-1 rounded-full border",initial:{scale:.6,opacity:.8},animate:{scale:1.8,opacity:0},transition:vg,onAnimationComplete:()=>a==null?void 0:a(e.key)})]}),r.jsx("span",{className:"chip-label truncate",children:e.label}),e.verb==="edit"&&e.live&&r.jsx("span",{"aria-hidden":"true","data-testid":"chip-caret",className:"chip-caret"}),e.verb==="run"&&e.live&&r.jsx("span",{"aria-hidden":"true","data-testid":"chip-cursor",className:"chip-cursor"}),e.verb==="fetch"&&e.live&&r.jsxs("span",{"aria-hidden":"true","data-testid":"chip-dots",className:"chip-dots",children:[r.jsx("span",{}),r.jsx("span",{}),r.jsx("span",{})]}),e.verb==="create"&&f&&r.jsxs(r.Fragment,{children:[r.jsx("svg",{"aria-hidden":"true","data-testid":"chip-pen",className:"chip-pen",children:r.jsx("rect",{x:"0",y:"0",width:"100%",height:"100%",rx:"11",ry:"11",pathLength:"100"})}),r.jsx("span",{"aria-hidden":"true",className:"chip-spark"})]}),e.verb==="delete"&&f&&r.jsx("span",{"aria-hidden":"true","data-testid":"chip-puff",className:"chip-puff"}),e.touches>1&&r.jsxs("span",{className:Sr,children:["×",e.touches]}),e.hits!==void 0&&r.jsx("span",{className:Sr,children:xs(e.hits)}),d&&r.jsxs(G.span,{className:"shrink-0 tabular-nums",initial:i?{opacity:0,x:-4}:!1,animate:{opacity:1,x:0},transition:kr,children:[e.additions!==void 0&&r.jsxs("span",{className:"text-status-success-fg",children:["+",r.jsx(Cr,{value:e.additions,live:e.live})]}),e.additions!==void 0&&e.deletions!==void 0&&" ",e.deletions!==void 0&&r.jsxs("span",{className:"text-destructive",children:["−",r.jsx(Cr,{value:e.deletions,live:e.live})]})]})]})}const jr=new Map(Fo.map((e,t)=>[e,t]));function Ag(e,t){const n=[...e];return t==="chronological"?n.sort((s,a)=>s.lastSeq-a.lastSeq):n.sort((s,a)=>(jr.get(s.verb)??0)-(jr.get(a.verb)??0)||s.firstSeq-a.firstSeq)}function Tg({id:e,chips:t,onOpen:n,verbFilter:s,onVerbFilterChange:a,order:o,onOrderChange:i}){const l=c.useMemo(()=>Ro(t),[t]),u=c.useMemo(()=>{const d=s?t.filter(f=>f.verb===s):t;return Ag(d,o)},[t,s,o]);return r.jsxs("div",{id:e,role:"region","aria-label":"Touched files and links","data-testid":"chip-tray",className:"border-border bg-card/50 flex flex-col gap-2 rounded-md border p-2",children:[r.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[r.jsx("div",{role:"group","aria-label":"Filter by what happened",className:"flex flex-wrap gap-1",children:l.map(d=>{const f=s===d.verb;return r.jsxs(ne,{variant:"outline",size:"xs","aria-pressed":f,"data-testid":`chip-filter-${d.verb}`,onClick:()=>a(f?null:d.verb),className:H("rounded-full",f?"border-primary dark:border-primary text-foreground":"text-muted-foreground"),children:[r.jsx("span",{"aria-hidden":"true",children:rn[d.verb]}),r.jsx("span",{className:"sr-only",children:an[d.verb]}),r.jsx("span",{className:"tabular-nums",children:d.chips.length})]},d.verb)})}),r.jsxs(Pl,{value:o,onValueChange:d=>i(d),"aria-label":"Order the roster",className:"w-auto",children:[r.jsx($s,{value:"grouped",children:"Grouped"}),r.jsx($s,{value:"chronological",children:"Chronological"})]})]}),r.jsx("div",{"data-testid":"chip-tray-roster",className:"flex max-h-60 flex-wrap items-start gap-1.5 overflow-y-auto overscroll-contain",children:u.map(d=>r.jsx(Mo,{chip:d,onOpen:n},d.key))})]})}const Fg=new Set;function Rg(){const[e,t]=c.useState(Fg),n=c.useCallback((a,o)=>o===!0&&!e.has(a),[e]),s=c.useCallback(a=>{t(o=>o.has(a)?o:new Set(o).add(a))},[]);return{shouldPulse:n,acknowledge:s}}function Mg(e){const t=[...e].sort((n,s)=>n.lastSeq-s.lastSeq);return{visible:t.slice(-yr),absorbed:t.slice(0,Math.max(0,t.length-yr))}}function Ig(e){return e.map(t=>{const n=[`${t.chips.length} ${an[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 Og({verb:e,count:t,additions:n,deletions:s}){return r.jsxs("span",{"data-testid":`chip-summary-${e}`,className:"inline-flex items-center gap-1",children:[r.jsx("span",{"aria-hidden":"true",children:rn[e]}),r.jsx("span",{className:"sr-only",children:an[e]}),r.jsx("span",{className:"tabular-nums",children:t}),(n!==void 0||s!==void 0)&&r.jsxs("span",{className:"tabular-nums",children:[n!==void 0&&r.jsxs("span",{className:"text-status-success-fg",children:["+",n]}),n!==void 0&&s!==void 0&&" ",s!==void 0&&r.jsxs("span",{className:"text-destructive",children:["−",s]})]})]})}function $g({parts:e,sessionId:t,turnActive:n=!1}){const s=Te()??!1,a=c.useMemo(()=>pg(e),[e]),o=Rg(),i=c.useId(),l=gg(c.useMemo(()=>hg(t,e),[t,e])),u=c.useCallback(x=>{if(x.pattern===!0)return;const g=oe.getState();if(x.kind==="url"){const S={type:"url",url:x.fullTarget};g.openCanvasDocument(S),$n(g,"user",S);return}if(x.kind==="file"){const S={type:"file",sourcePath:x.fullTarget};g.openCanvasDocument(S),$n(g,"user",S)}},[]),d=c.useMemo(()=>Ro(a),[a]),f=n||a.some(x=>x.live),{visible:h,absorbed:m}=c.useMemo(()=>Mg(a),[a]);return a.length===0?null:r.jsxs("div",{"data-testid":"touch-chip-strip",className:"mt-2 flex flex-col gap-2",children:[r.jsx(ie,{initial:!1,mode:"wait",children:f?r.jsxs(G.div,{"data-testid":"chip-live-row",role:"group","aria-label":"Latest activity",exit:s?{opacity:0}:{opacity:0,height:0},transition:s?Yt:vr,className:"flex min-w-0 items-center gap-1.5 overflow-hidden",children:[m.length>0&&r.jsx(wg,{chips:m,expanded:l.expanded,controls:i,onExpand:l.toggleExpanded}),r.jsx(ie,{initial:!1,children:h.map(x=>r.jsx(Mo,{chip:x,onOpen:u,animated:!0,pulseUpgrade:o.shouldPulse(x.key,x.upgraded),onUpgradeSeen:o.acknowledge},x.key))})]},"live"):r.jsxs(G.div,{"data-testid":"chip-summary-line",role:"group","aria-label":Ig(d),initial:{opacity:0},animate:{opacity:1},transition:s?Yt:vr,className:"text-muted-foreground flex flex-wrap items-center gap-x-1.5 gap-y-1 text-xs",children:[d.map((x,g)=>r.jsxs(c.Fragment,{children:[g>0&&r.jsx("span",{"aria-hidden":"true",children:"·"}),r.jsx(Og,{verb:x.verb,count:x.chips.length,additions:x.additions,deletions:x.deletions})]},x.verb)),r.jsx("span",{"aria-hidden":"true",children:"·"}),r.jsx("button",{type:"button","aria-expanded":l.expanded,"aria-controls":i,onClick:l.toggleExpanded,className:H("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&&r.jsx(Tg,{id:i,chips:a,onOpen:u,verbFilter:l.verbFilter,onVerbFilterChange:l.setVerbFilter,order:l.order,onOrderChange:l.setOrder})]})}function _r(e){return e.type==="thinking"?!0:e.type==="tool_call"&&!e.interactiveType&&!Ja(e.toolName)&&!Pn(e.toolName)}function Pg({message:e}){const{sessionId:t,isStreaming:n,isLatestWidgetMessage:s,isFinalMessage:a,activeToolCallId:o,onToolRef:i,focusedOptionIndex:l,onToolDecided:u,onRetry:d,onSigninComplete:f,onChooseModel:h,inputZoneToolCallId:m,textEffect:x,runtimeLabel:g,allowsDenyReason:S}=Cp(),{expandToolCalls:b,autoHideToolCalls:y}=oe(),C=e.parts??[],{sent:v}=bo(t),p=c.useCallback(k=>{i==null||i(k)},[i]),j=c.useCallback(k=>{i==null||i(k)},[i]),_=Fh(C.map(k=>k.type==="tool_call"&&Pn(k.toolName)?{...k,interactiveType:void 0}:k));let D=-1;for(let k=C.length-1;k>=0;k--)if(C[k].type==="text"){D=k;break}function T(k,E){if(k.type==="text")return r.jsx("div",{className:"msg-prose",children:r.jsx(hs,{content:k.text,isStreaming:n&&E===D,textEffect:x,sessionId:t,isLatestWidgetMessage:s})},`text-${E}`);if(k.type==="background_task")return r.jsx($p,{part:k},k.taskId);if(k.type==="error"&&k.code===ya)return r.jsx(Ih,{message:k.message},`unreadable-${E}`);if(k.type==="error")return r.jsx(sn,{message:k.message,category:k.category,details:k.details,code:k.code,reason:k.reason,at:e.timestamp,onRetry:a&&k.category!==void 0?d:void 0,onSigninComplete:f,onChooseModel:h,runtimeLabel:g,sessionId:t},`error-${E}`);if(k.type==="thinking")return r.jsx(Wh,{part:k,autoHide:y,index:E},`thinking-${E}`);if(k.type==="elicitation")return r.jsx(Qd,{sessionId:t,interactionId:k.interactionId,serverName:k.serverName,message:k.message,mode:k.mode,url:k.url,requestedSchema:k.requestedSchema,status:k.status,action:k.action},`elicitation-${k.interactionId}`);if(k.type==="memory_recall")return r.jsx(wp,{mode:k.mode,memories:k.memories,isStreaming:k.isStreaming??!1},`memory-recall-${E}`);if(k.type==="permission_denied")return r.jsx(Eh,{toolName:k.toolName,reasonType:k.reasonType,reason:k.reason,message:k.message,agentId:k.agentId},`permission-denied-${k.toolCallId}-${E}`);if(k.type==="model_substituted")return r.jsx(Lh,{fromName:k.fromName,toName:k.toName},`model-substituted-${E}`);if(k.type==="compact_boundary")return r.jsx(Tp,{trigger:k.trigger,preTokens:k.preTokens,postTokens:k.postTokens,failed:k.failed,error:k.error,requestedBy:k.requestedBy,contextPercent:k.contextPercent},`compact-boundary-${E}`);if(k.type==="capability_approval")return k.outcome==="timeout"?r.jsx(Oh,{title:Ll(k.approval)},`capability-approval-${k.approval.approvalId}`):r.jsx(zl,{approval:k.approval},`capability-approval-${k.approval.approvalId}`);if(k.type==="mcp_signin")return r.jsx(Ph,{part:k},`mcp-signin-${k.agentId}-${k.flowId}`);if(k.type==="image")return r.jsx(Fp,{part:k},`image-${k.attachmentId}-${E}`);if(k.type!=="tool_call")return null;const w=k;if(w.interactiveType==="approval"&&w.status==="pending"){if(w.toolCallId===m)return r.jsx(ar,{type:"approval",toolName:w.toolName,toolInput:w.input},w.toolCallId);const O=w.toolCallId===o;return r.jsx(Xa,{ref:O?p:void 0,sessionId:t,toolCallId:w.toolCallId,toolName:w.toolName,input:w.input||"",timeoutMs:w.timeoutMs,approvalStartedAt:w.approvalStartedAt,approvalRemainingMs:w.approvalRemainingMs,approvalParked:w.approvalParked,approvalTitle:w.approvalTitle,approvalDisplayName:w.approvalDisplayName,approvalDescription:w.approvalDescription,approvalBlockedPath:w.approvalBlockedPath,approvalDecisionReason:w.approvalDecisionReason,approvalHasSuggestions:w.approvalHasSuggestions,approvalAlwaysAllowScope:w.approvalAlwaysAllowScope,isActive:O,onDecided:u?()=>u(w.toolCallId):void 0,allowsDenyReason:S},w.toolCallId)}const R=_.get(E);if(R){if(R.leadIndex!==E)return null;const O=R.indices.map(F=>C[F]).filter(F=>F.type==="tool_call");return r.jsx(sf,{outcome:R.outcome,reasonGiven:R.reasonGiven,members:O,lead:w,children:O.map(F=>r.jsx(En,{part:F,sessionId:t,autoHide:y,expandToolCalls:b},F.toolCallId))},`approval-receipt-${w.toolCallId}`)}if(w.interactiveType==="question"){if(w.toolCallId===m)return r.jsx(ar,{type:"question",toolName:w.toolName,toolInput:w.input},w.toolCallId);const O=w.toolCallId===o;return r.jsx(va,{ref:O?j:void 0,sessionId:t,toolCallId:w.toolCallId,questions:w.questions??[],answers:w.answers??(Rh(w)?{}:void 0),outcome:Mh(w),result:w.result,isActive:O,focusedOptionIndex:O?l:-1,onDecided:u?F=>u(w.toolCallId,F):void 0},w.toolCallId)}return Pn(w.toolName)?r.jsx(gp,{part:w,sent:v,...e.timestamp?{at:e.timestamp}:{},...t?{sessionId:t}:{}},w.toolCallId):Ja(w.toolName)?r.jsx(of,{sessionId:t,input:w.input,result:w.result,fallback:r.jsx(En,{part:w,sessionId:t,autoHide:y,expandToolCalls:b})},w.toolCallId):r.jsx(En,{part:w,sessionId:t,autoHide:y,expandToolCalls:b},w.toolCallId)}const N=[];let A=[];for(let k=0;k<C.length;k++){const E=C[k];_r(E)?A.push(k):(A.length>0&&(N.push(A.length===1?{type:"single",index:A[0]}:{type:"run",indices:[...A]}),A=[]),N.push({type:"single",index:k}))}return A.length>0&&N.push(A.length===1?{type:"single",index:A[0]}:{type:"run",indices:[...A]}),r.jsxs(r.Fragment,{children:[N.map(k=>{if(k.type==="single"){const w=C[k.index];return _r(w)?r.jsx("div",{className:"my-3",children:T(w,k.index)},`spacer-${k.index}`):T(w,k.index)}const E=k.indices.map(w=>T(C[w],w));return r.jsx("div",{className:"my-3",children:r.jsx(Gh,{children:E})},`run-${k.indices[0]}`)}),r.jsx($g,{parts:C,sessionId:t,turnActive:e._streaming===!0})]})}const Lg=/^Please read the following uploaded file\(s\):\n((?:- .+\n)+)\n?/,zg=/^[a-f0-9]{8}-/,Bg=new Set(["png","jpg","jpeg","gif","webp","svg"]);function qg(e){const t=e.match(Lg);if(!t)return{files:[],textContent:e};const s=t[1].split(`
54
+ `).filter(o=>o.startsWith("- ")).map(o=>{var f;const i=o.slice(2).trim(),u=(i.split("/").pop()??i).replace(zg,""),d=((f=u.split(".").pop())==null?void 0:f.toLowerCase())??"";return{path:i,displayName:u,isImage:Bg.has(d)}}),a=e.slice(t[0].length).trim();return{files:s,textContent:a}}function Ug(e){var n;switch(((n=e.split(".").pop())==null?void 0:n.toLowerCase())??""){case"txt":case"md":case"log":return id;case"ts":case"tsx":case"js":case"jsx":case"json":case"py":case"rs":case"go":return ad;case"csv":case"xls":case"xlsx":return yd;case"png":case"jpg":case"jpeg":case"gif":case"webp":case"svg":return bd;default:return Ma}}function Hg({files:e}){const t=oe(n=>n.selectedCwd);return e.length===0?null:r.jsx("div",{className:"flex flex-wrap gap-1.5 pb-1.5",children:e.map(n=>{const s=n.path.split("/").pop()??n.path;if(n.isImage){const o=`/api/uploads/${encodeURIComponent(s)}?cwd=${encodeURIComponent(t??"")}`;return r.jsx(G.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{duration:.15},children:r.jsx("a",{href:o,target:"_blank",rel:"noopener noreferrer",children:r.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=Ug(n.displayName);return r.jsxs(G.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:[r.jsx(a,{className:"text-muted-foreground size-3 shrink-0"}),r.jsx("span",{className:"max-w-40 truncate",children:n.displayName})]},n.path)})})}function Wg({message:e}){var i;const t=(i=Sp())==null?void 0:i.sessionId,[n,s]=c.useState(!1),a=c.useMemo(()=>qg(e.content),[e.content]),o=c.useMemo(()=>Cf(e.content),[e.content]);if(o)return r.jsx(vf,{action:o});if(e.chatMessages&&e.chatMessages.length>0)return r.jsx(up,{stamps:e.chatMessages,...t?{sessionId:t}:{}});if(e.messageType==="command")return r.jsx("div",{className:"text-msg-command-fg font-mono text-sm break-words",children:e.content});if(e.messageType==="local_command_output")return r.jsx(_o,{content:e.content,toolName:""});if(e.messageType==="compaction"){const l=Dp(e.compactMetadata),u=e.content.trim(),d=r.jsx("div",{className:"bg-border/40 h-px flex-1"});return u.length===0?r.jsxs("div",{"data-testid":"compaction-row",className:"text-msg-compaction-fg flex w-full items-center gap-2 text-xs",children:[d,r.jsx("span",{children:l}),d]}):r.jsxs("div",{className:"w-full","data-testid":"compaction-row",children:[r.jsxs("button",{onClick:()=>s(!n),className:"text-msg-compaction-fg flex w-full items-center gap-2 text-xs",children:[d,r.jsx(cs,{className:H("size-3 transition-transform duration-200",n&&"rotate-90")}),r.jsx("span",{children:l}),d]}),n&&r.jsx("div",{className:"text-msg-compaction-fg mt-2 text-xs whitespace-pre-wrap",children:e.content})]})}return r.jsxs("div",{children:[a.files.length>0&&r.jsx(Hg,{files:a.files}),a.textContent&&r.jsx("div",{className:"break-words whitespace-pre-wrap",children:a.textContent})]})}function Vg({tasks:e,isCollapsed:t,onToggleCollapse:n}){const s=e.length,a=e.filter(l=>l.status==="completed").length,o=a===s&&s>0,i=s>0?a/s*100:0;return r.jsxs("button",{onClick:n,className:"text-muted-foreground hover:text-foreground flex w-full items-center gap-2 text-xs",children:[t?r.jsx(cs,{className:"size-(--size-icon-xs) shrink-0"}):r.jsx(Et,{className:"size-(--size-icon-xs) shrink-0"}),r.jsx("div",{className:"bg-muted h-0.5 flex-1 overflow-hidden rounded-full",children:r.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:`${i}%`}})}),r.jsxs("span",{className:"shrink-0 tabular-nums",children:[a,"/",s," ",s===1?"task":"tasks"]})]})}function Gg({activeForm:e,isCollapsed:t}){return r.jsx(ie,{children:e&&!t&&r.jsxs(G.div,{variants:qe,initial:"initial",animate:"animate",exit:"exit",transition:Be,className:"mb-1 flex items-center gap-2 text-xs text-blue-400",children:[r.jsx(ze,{size:"xs",className:"shrink-0"}),r.jsx("span",{className:"truncate",children:e})]})})}const Kg={in_progress:"",pending:"waiting ",completed:"done "};function wr({tasks:e,onScrollToTask:t}){return r.jsx(r.Fragment,{children:e.map((n,s)=>r.jsxs("span",{children:[r.jsx("button",{onClick:a=>{a.stopPropagation(),t(n.id)},className:"hover:text-foreground underline decoration-dotted",children:n.subject}),s<e.length-1&&", "]},n.id))})}function Qg({task:e,taskMap:t,statusSince:n,onScrollToTask:s}){var d,f;const a=Pa(n),o=Kg[e.status]??"",i=((d=e.blockedBy)==null?void 0:d.map(h=>t.get(h)).filter(h=>h!=null))??[],l=((f=e.blocks)==null?void 0:f.map(h=>t.get(h)).filter(h=>h!=null))??[],u=[];return n!==null&&u.push(r.jsxs("span",{children:[o,a.formatted]},"time")),e.owner&&u.push(r.jsx("span",{children:e.owner},"owner")),i.length>0&&u.push(r.jsxs("span",{className:"inline-flex items-center gap-1",children:["← ",r.jsx(wr,{tasks:i,onScrollToTask:s})]},"blocked-by")),l.length>0&&u.push(r.jsxs("span",{className:"inline-flex items-center gap-1",children:["→ ",r.jsx(wr,{tasks:l,onScrollToTask:s})]},"blocks")),r.jsxs(G.div,{variants:qe,initial:"initial",animate:"animate",exit:"exit",transition:Be,className:"mt-0.5 ml-6 space-y-1",children:[e.description&&r.jsx("p",{className:"text-muted-foreground text-xs whitespace-pre-wrap",children:e.description}),u.length>0&&r.jsx("div",{className:"text-muted-foreground text-2xs flex flex-wrap items-center gap-1",children:u.map((h,m)=>r.jsxs("span",{className:"flex items-center gap-1",children:[m>0&&r.jsx("span",{className:"text-muted-foreground/50",children:"·"}),h]},m))})]})}const Nr={in_progress:r.jsx(ze,{size:"xs",className:"text-status-info shrink-0"}),pending:r.jsx(Bl,{className:"text-muted-foreground size-(--size-icon-xs) shrink-0"}),completed:r.jsx(ba,{className:"text-status-success size-(--size-icon-xs) shrink-0"})};function Yg({task:e,isBlocked:t,isExpanded:n,onToggleExpand:s,onHover:a,isHighlightedAsDep:o,isHighlightedAsDependent:i,taskMap:l,statusSince:u,isCelebrating:d,onCelebrationComplete:f,onScrollToTask:h}){const m=x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),s())};return r.jsxs(G.li,{"data-task-id":e.id,children:[r.jsxs("div",{role:"button",tabIndex:0,"aria-expanded":n,"data-task-id":e.id,onClick:s,onKeyDown:m,onMouseEnter:()=>a(e.id),onMouseLeave:()=>a(null),className:H("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",i&&"border-l-2 border-amber-400 pl-1.5",!o&&!i&&"border-l-2 border-transparent pl-1.5"),children:[d&&r.jsx(G.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?r.jsx(G.span,{initial:{scale:1},animate:{scale:[1,1.4,1]},transition:{type:"spring",stiffness:400,damping:10},onAnimationComplete:()=>f==null?void 0:f(),children:Nr[e.status]}):Nr[e.status],r.jsx("span",{className:"truncate",children:e.subject})]}),r.jsx(ie,{children:n&&r.jsx(Qg,{task:e,taskMap:l,statusSince:u,onScrollToTask:h})})]})}function Xg(e,t){var n;return(n=e.blockedBy)!=null&&n.length?e.blockedBy.some(s=>{const a=t.get(s);return a&&a.status!=="completed"}):!1}const Jg=10,Zg="max-h-[30svh] sm:max-h-[40svh]";function ex({tasks:e,taskMap:t,activeForm:n,isCollapsed:s,onToggleCollapse:a,celebratingTaskId:o,onCelebrationComplete:i,statusTimestamps:l}){const[u,d]=c.useState(null),[f,h]=c.useState(null),m=c.useCallback(b=>{d(y=>y===b?null:b)},[]),x=c.useCallback(b=>{const y=document.querySelector(`[data-task-id="${b}"]`);y&&(y.scrollIntoView({behavior:"smooth",block:"nearest"}),y.classList.add("bg-blue-500/10"),setTimeout(()=>y.classList.remove("bg-blue-500/10"),1e3))},[]);if(e.length===0)return null;const g=e.slice(0,Jg),S=f?t.get(f):null;return r.jsxs("div",{className:"border-t px-4 py-2",children:[r.jsx(Gg,{activeForm:n,isCollapsed:s}),r.jsx(Vg,{tasks:e,isCollapsed:s,onToggleCollapse:a}),r.jsx(ie,{children:!s&&r.jsx(G.ul,{variants:qe,initial:"initial",animate:"animate",exit:"exit",transition:Be,className:H("mt-1 space-y-0.5 overflow-y-auto",Zg),children:g.map(b=>{var _,D;const y=b.id===o&&b.status==="completed",C=Xg(b,t),v=l.get(b.id),p=((_=S==null?void 0:S.blockedBy)==null?void 0:_.includes(b.id))??!1,j=((D=S==null?void 0:S.blocks)==null?void 0:D.includes(b.id))??!1;return r.jsx(Yg,{task:b,isBlocked:C,isExpanded:u===b.id,onToggleExpand:()=>m(b.id),onHover:h,isHighlightedAsDep:p,isHighlightedAsDependent:j,taskMap:t,statusSince:(v==null?void 0:v.since)??null,isCelebrating:y,onCelebrationComplete:i,onScrollToTask:x},b.id)})})})]})}function tx({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 r.jsx("div",{className:"pointer-events-none absolute inset-0",children:t.map((n,s)=>r.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`}},s))})}const nx=350;function sx({status:e,color:t}){return r.jsxs("svg",{className:"check-appear h-6 w-[22px]",viewBox:"0 0 22 24","data-status":e,children:[r.jsx("circle",{cx:"11",cy:"12",r:"7",fill:"none",stroke:t,strokeWidth:"1.5",opacity:"0.3"}),e==="error"&&r.jsxs(r.Fragment,{children:[r.jsx("line",{x1:"8",y1:"9",x2:"14",y2:"15",stroke:t,strokeWidth:"2",strokeLinecap:"round"}),r.jsx("line",{x1:"14",y1:"9",x2:"8",y2:"15",stroke:t,strokeWidth:"2",strokeLinecap:"round"})]}),e==="untracked"&&r.jsx("line",{x1:"8",y1:"12",x2:"14",y2:"12",stroke:t,strokeWidth:"2",strokeLinecap:"round",opacity:"0.5"}),e!=="error"&&e!=="untracked"&&r.jsx("polyline",{points:"7,12 10,15 15,9",fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]})}function rx({agent:e,index:t}){const n=c.useMemo(()=>({animationDelay:`${t*.09}s`}),[t]),[s,a]=c.useState(e.status==="running"?"running":"done"),o=c.useRef(e.status),i=c.useRef(null);return c.useEffect(()=>{const l=o.current;if(o.current=e.status,l==="running"&&e.status!=="running"){a("celebrating"),i.current=setTimeout(()=>a("done"),nx);return}l!=="running"&&e.status==="running"&&(i.current&&clearTimeout(i.current),i.current=null,a("running"))},[e.status]),c.useEffect(()=>()=>{i.current&&clearTimeout(i.current)},[]),s==="done"?r.jsx("div",{className:"relative inline-flex",children:r.jsx(sx,{status:e.status,color:e.color})}):r.jsxs("div",{className:"group relative inline-flex",children:[r.jsx("svg",{className:"h-6 w-[22px] shrink-0",style:{"--c":e.color},viewBox:"0 0 22 24","aria-label":e.description,children:r.jsxs("g",{className:"r-all",style:n,children:[r.jsx("circle",{cx:"11",cy:"4.5",r:"2.8",fill:"var(--c)"}),r.jsx("circle",{cx:"12.3",cy:"3.7",r:"0.6",fill:"hsl(0 0% 100% / 0.7)"}),r.jsx("ellipse",{cx:"11",cy:"10.5",rx:"2.5",ry:"3.5",fill:"var(--c)"}),r.jsxs("g",{className:"r-rua",style:n,children:[r.jsx("line",{x1:"12",y1:"9",x2:"14",y2:"11",stroke:"var(--c)",strokeWidth:"1.8",strokeLinecap:"round"}),r.jsx("g",{className:"r-rfa",style:n,children:r.jsx("line",{x1:"14",y1:"11",x2:"14.5",y2:"13",stroke:"var(--c)",strokeWidth:"1.8",strokeLinecap:"round"})})]}),r.jsxs("g",{className:"r-lua",style:n,children:[r.jsx("line",{x1:"10",y1:"9",x2:"8",y2:"11",stroke:"var(--c)",strokeWidth:"1.8",strokeLinecap:"round"}),r.jsx("g",{className:"r-lfa",style:n,children:r.jsx("line",{x1:"8",y1:"11",x2:"7.5",y2:"13",stroke:"var(--c)",strokeWidth:"1.8",strokeLinecap:"round"})})]}),r.jsxs("g",{className:"r-rt",style:n,children:[r.jsx("line",{x1:"11",y1:"14",x2:"13",y2:"17",stroke:"var(--c)",strokeWidth:"1.8",strokeLinecap:"round"}),r.jsx("g",{className:"r-rs",style:n,children:r.jsx("line",{x1:"13",y1:"17",x2:"13.5",y2:"21",stroke:"var(--c)",strokeWidth:"1.8",strokeLinecap:"round"})})]}),r.jsxs("g",{className:"r-lt",style:n,children:[r.jsx("line",{x1:"11",y1:"14",x2:"9",y2:"17",stroke:"var(--c)",strokeWidth:"1.8",strokeLinecap:"round"}),r.jsx("g",{className:"r-ls",style:n,children:r.jsx("line",{x1:"9",y1:"17",x2:"8.5",y2:"21",stroke:"var(--c)",strokeWidth:"1.8",strokeLinecap:"round"})})]})]})}),s==="celebrating"&&r.jsx(tx,{color:e.color}),s==="running"&&r.jsxs("div",{"data-testid":"agent-runner-tooltip",className:H("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:[r.jsxs("div",{className:"mb-0.5 flex items-center gap-1.5 font-semibold",children:[r.jsx("div",{className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:e.color}}),e.description]}),r.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&&r.jsxs("div",{className:"text-muted-foreground/60 text-3xs mt-0.5 font-mono",children:["Last: ",e.lastToolName]}),r.jsx("div",{className:"border-t-border absolute top-full left-1/2 -translate-x-1/2 border-5 border-transparent"})]})]})}function ax({bashTasks:e}){const t=Te(),n=e.filter(a=>a.taskType==="bash"),s=n.length;return s===0?null:r.jsxs("div",{role:"status","aria-live":"polite","aria-label":`${s} bash task${s!==1?"s":""} running`,className:"flex items-center gap-1.5",children:[r.jsx(ie,{mode:"popLayout",children:n.map(a=>r.jsxs(G.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&&r.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"}}),r.jsx("span",{className:"relative size-1.5 rounded-full",style:{backgroundColor:a.color}})]},a.taskId))}),r.jsxs("span",{className:"text-muted-foreground text-xs whitespace-nowrap",children:[s," task",s!==1?"s":""]})]})}const ox=3e3;function ix({taskType:e,onConfirm:t}){const[n,s]=c.useState(!1),a=c.useRef(null);c.useEffect(()=>()=>{a.current&&clearTimeout(a.current)},[]),c.useEffect(()=>{if(n)return a.current=setTimeout(()=>{s(!1)},ox),()=>{a.current&&clearTimeout(a.current)}},[n]);const o=c.useCallback(()=>{if(e==="bash"){t();return}n?(a.current&&clearTimeout(a.current),s(!1),t()):s(!0)},[e,n,t]),i=c.useCallback(l=>{(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),o())},[o]);return r.jsx("button",{onClick:o,onKeyDown:i,className:H("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?":r.jsx(Le,{className:"size-3"})})}function Er({task:e,onStop:t}){const n=e.taskType==="agent"?e.description??"Background agent":e.command??"Background task",s=e.durationMs?Math.round(e.durationMs/1e3):0,a=e.status==="running";return r.jsxs("div",{className:H("flex items-center gap-2 rounded-md px-2 py-1 text-xs",a?"bg-muted":"bg-muted/50 opacity-60"),children:[r.jsx("span",{className:"size-2 shrink-0 rounded-full",style:{backgroundColor:e.color}}),r.jsx("span",{className:"text-muted-foreground/60 text-3xs shrink-0 tracking-wider uppercase",children:e.taskType}),r.jsx("span",{className:"text-foreground min-w-0 flex-1 truncate",children:n}),e.taskType==="agent"&&e.toolUses!==void 0&&e.toolUses>0&&r.jsxs("span",{className:"text-muted-foreground/60 text-3xs shrink-0 font-mono",children:[e.toolUses," tools"]}),e.taskType==="agent"&&e.lastToolName&&r.jsxs("span",{className:"text-muted-foreground/60 text-3xs hidden max-w-24 shrink-0 truncate font-mono md:inline",children:["Last: ",e.lastToolName]}),s>0&&r.jsxs("span",{className:"text-muted-foreground/60 text-3xs shrink-0 font-mono",children:[s,"s"]}),a&&r.jsx(ix,{taskType:e.taskType,onConfirm:t})]})}function lx({tasks:e,ambientTasks:t=[],onStopTask:n}){return r.jsx(G.div,{variants:qe,initial:"initial",animate:"animate",exit:"exit",transition:Be,className:"border-border overflow-hidden border-t px-2 py-1.5",children:r.jsxs("div",{className:"flex flex-col gap-1",children:[e.map(s=>r.jsx(Er,{task:s,onStop:()=>n(s.taskId)},s.taskId)),t.length>0&&r.jsxs(r.Fragment,{children:[r.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(s=>r.jsx(Er,{task:s,onStop:()=>n(s.taskId)},s.taskId))]})]})})}const Kn=4;function cx(e){return e==="stopped"?"complete":e}const ux="relative after:absolute after:-inset-x-1 after:-inset-y-2.5 md:after:hidden",Io=[.16,1,.3,1],dx={width:{duration:.4,ease:Io},opacity:{duration:.25}};function fx({tasks:e,onStopTask:t}){const[n,s]=c.useState(!1),a=Te(),{shown:o,ambient:i}=Xc(e),l=o.filter(b=>b.taskType==="agent"),u=o.filter(b=>b.taskType==="bash"),d=o.length,f=l.slice(0,Kn),h=l.length-Kn,m=l.reduce((b,y)=>b+(y.toolUses??0),0),x=Math.max(0,...o.map(b=>Math.round((b.durationMs??0)/1e3))),g=a?{duration:0}:{duration:.35,ease:Io},S=d>0;return r.jsx(ie,{children:(d>0||i.length>0)&&r.jsxs(G.div,{...S?{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:[r.jsxs("div",{className:"flex min-h-9 items-center gap-2 px-2 py-1.5",children:[l.length>0&&r.jsx(mx,{visibleAgents:f,overflowAgentCount:h,allAgentTasks:l}),l.length>0&&u.length>0&&r.jsx("div",{className:"bg-border h-4 w-px shrink-0"}),u.length>0&&r.jsx(ax,{bashTasks:u}),d>0&&r.jsxs(r.Fragment,{children:[r.jsxs("span",{className:"text-muted-foreground text-xs whitespace-nowrap",children:[r.jsx("strong",{className:"text-foreground font-semibold",children:d})," task",d!==1?"s":""," running"]}),r.jsxs("span",{className:"text-muted-foreground/60 text-2xs ml-auto font-mono whitespace-nowrap",children:[m>0&&r.jsxs(r.Fragment,{children:[m," tools · "]}),x,"s"]})]}),r.jsxs("button",{type:"button",onClick:()=>s(b=>!b),className:H("text-muted-foreground hover:text-foreground flex shrink-0 items-center gap-1 transition-colors duration-150",d>0?"ml-1":"ml-auto",ux),"aria-label":n?"Collapse task details":"Expand task details","aria-expanded":n,children:[d>0&&r.jsx("span",{className:"text-3xs tabular-nums",children:d}),r.jsx(Et,{className:H("size-3.5 transition-transform duration-200",n&&"rotate-180")})]})]}),r.jsx(ie,{children:n&&r.jsx(lx,{tasks:o,ambientTasks:i,onStopTask:t})})]},"background-task-bar")})}function mx({visibleAgents:e,overflowAgentCount:t,allAgentTasks:n}){return r.jsxs("div",{className:"flex items-center gap-0",children:[r.jsx(ie,{mode:"popLayout",children:e.map((s,a)=>r.jsx(G.div,{initial:{width:0,opacity:0},animate:{width:22,opacity:1},exit:{width:0,opacity:0},transition:dx,className:"shrink-0",children:r.jsx(rx,{agent:{taskId:s.taskId,description:s.description??"",status:cx(s.status),color:s.color,toolUses:s.toolUses,lastToolName:s.lastToolName,durationMs:s.durationMs,summary:s.summary},index:a})},s.taskId))}),t>0&&r.jsx(px,{count:t,overflowTasks:n.slice(Kn)})]})}function px({count:e,overflowTasks:t}){return r.jsxs("div",{className:"group relative",children:[r.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]}),r.jsxs("div",{"data-testid":"overflow-badge-tooltip",className:H("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=>r.jsxs("div",{className:"flex items-center gap-1.5 py-0.5",children:[r.jsx("div",{className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:n.color}}),r.jsx("span",{className:"text-3xs",children:n.description})]},n.taskId)),r.jsx("div",{className:"border-t-border absolute top-full left-1/2 -translate-x-1/2 border-5 border-transparent"})]})]})}const An="after:absolute after:-inset-1 md:after:hidden";function hx({queue:e,editingId:t,onEdit:n,onRemove:s,onSend:a,onMoveUp:o,statusNote:i,onSwitchNow:l}){return e.length===0?null:r.jsxs(G.div,{variants:qe,initial:"initial",animate:"animate",exit:"exit",transition:Be,className:"mb-1.5 overflow-hidden",children:[r.jsxs("div",{className:"text-muted-foreground mb-1 flex items-baseline gap-1 text-xs",children:[r.jsxs("span",{className:"font-medium",children:["Queued (",e.length,")"]}),r.jsxs("span",{className:"truncate",children:["· ",i]})]}),r.jsx("div",{className:"space-y-0.5",children:r.jsx(ie,{mode:"popLayout",children:e.map((u,d)=>r.jsx(G.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:r.jsxs("div",{className:H("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:[r.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:[r.jsxs("span",{className:"text-muted-foreground shrink-0 text-xs font-medium",children:[d+1,"."]}),r.jsxs("span",{className:"min-w-0 flex-1",children:[r.jsx("span",{className:"text-muted-foreground line-clamp-1 text-sm",children:u.content}),u.notice!==null&&r.jsx("span",{className:"text-muted-foreground/70 line-clamp-1 text-xs",children:u.notice}),u.waiting!==void 0&&r.jsx("span",{className:"text-muted-foreground/70 line-clamp-1 text-xs",children:u.waiting.line})]}),!u.mine&&r.jsxs("span",{className:"text-muted-foreground/60 flex shrink-0 items-center",title:"Queued from another window",children:[r.jsx(zn,{className:"size-3","aria-hidden":"true"}),r.jsx("span",{className:"sr-only",children:"Queued from another window"})]})]}),u.waiting!==void 0&&l!==void 0&&r.jsxs(r.Fragment,{children:[r.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"}),r.jsx("span",{id:`switch-now-${u.id}`,className:"sr-only",children:u.waiting.switchHint})]}),d>0&&r.jsx("button",{type:"button",onClick:()=>o(u.id),className:H("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",An),"aria-label":`Move queued message ${d+1} earlier`,children:r.jsx(ql,{className:"size-3"})}),d>0&&r.jsx("button",{type:"button",onClick:()=>a(u.id),"aria-label":`Send queued message ${d+1} next`,className:H("focus-ring text-muted-foreground hover:text-foreground relative flex size-6 shrink-0 items-center justify-center rounded-sm transition-colors",An),children:r.jsx(Ku,{className:"size-3"})}),r.jsx("button",{type:"button",onClick:()=>s(u.id),className:H("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",An),"aria-label":`Remove queued message ${d+1}`,children:r.jsx(Le,{className:"size-3"})})]})},u.id))})})]})}function gx({open:e,onOpenChange:t,queuedCount:n,onConfirm:s}){const a=n===1?"message":"messages";return r.jsx(Ul,{open:e,onOpenChange:t,children:r.jsxs(Hl,{children:[r.jsxs(Wl,{children:[r.jsxs(Vl,{children:["Stop, and put ",n," queued ",a," back?"]}),r.jsxs(Gl,{children:["The agent stops. Your ",a," ",n===1?"goes":"go"," back to the composer."]})]}),r.jsxs(Kl,{children:[r.jsx(Ql,{children:"Keep going"}),r.jsx(Yl,{onClick:s,children:"Stop"})]})]})})}const xx={initial:{opacity:0,y:4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4}},bx={duration:.3,ease:"easeInOut"};function yx({text:e,animationKey:t}){return r.jsx("div",{className:"pointer-events-none absolute inset-0 flex items-start overflow-hidden py-0.5",children:r.jsx(ie,{mode:"wait",children:r.jsx(G.span,{variants:xx,initial:"initial",animate:"animate",exit:"exit",transition:bx,className:"text-muted-foreground truncate text-sm",children:e},t)})})}function vx(e){const t=xe();return Ye({queryKey:["workspace-for-session",e??null],queryFn:()=>t.resolveWorkspace(e),enabled:!!e}).data??null}async function Oo(e,t,n){try{return await e.runCommandIntent(t,"compact",n),!0}catch(s){const a=s.code==="SESSION_LOCKED";return Ee.error(a?"Your agent is busy. Try again in a moment.":"Couldn’t compact the chat."),!1}}const Qn=rs(e=>({open:!1,setOpen:t=>e({open:t}),reveal:()=>e({open:!0})})),kx=200,Yn=[{name:"rename",description:"Rename the current chat",argHint:"<new title>",run:(e,t)=>{const n=e.replace(/\s+/g," ").trim().slice(0,kx).trim();return n?t.sessionId?(t.renameSession(n),!0):(t.notify("No open chat to rename","error"),!1):(t.notify("Usage: /rename <new title>","error"),!1)}},{name:"clear",description:"Start a new chat here",run:(e,t)=>(t.startFreshSession(t.sessionId),!0)},{name:"context",description:"Show context usage and cost",run:(e,t)=>(t.focusUsageSurface(),!0)}],Cx=/^\/(\S+)(?:\s+([\s\S]*))?$/;function $o(e){const t=Cx.exec(e);if(!t)return null;const n=t[1],s=(t[2]??"").trim(),a=ds(n);if(a&&a.fulfillment==="client-native"){const i=Yn.find(l=>l.name===a.id);if(i)return{command:i,args:s}}const o=Yn.find(i=>i.name===n.toLowerCase());return o?{command:o,args:s}:null}const Dr=Yn.map(e=>({command:e.name,fullCommand:`/${e.name}`,description:e.description,argumentHint:e.argHint}));function Po(e){const t=/^\/(\S+)([\s\S]*)$/.exec(e.trim());return t?{token:t[1],rest:t[2].trim()}:null}function Sx(e){const t=Po(e);return t?ds(t.token)?!0:$o(e.trim())!==null:!1}function jx(e,t,n={}){const{mutateAsync:s}=Xl(e),a=xe(),{startFreshSession:o,compact:i}=n,[l,u]=c.useState(0),d=c.useCallback(h=>{u(x=>x+1);const m=()=>u(x=>Math.max(0,x-1));h.then(m,m)},[]);return{tryRun:c.useCallback(h=>{const m=Po(h),x=m?ds(m.token):null;if(m&&(x==null?void 0:x.fulfillment)==="runtime"&&i){if(!i.supported)return Ee.error(`Compact isn’t available on ${i.runtimeLabel||"this agent"}`),{handled:!0,ran:!1};if(!t)return Ee.error("No open chat to compact"),{handled:!0,ran:!1};const y=Oo(a,t,m.rest||void 0);return d(y),{handled:!0,ran:!0,confirmed:y}}const g=$o(h);if(!g)return{handled:!1};let S;return{handled:!0,ran:g.command.run(g.args,{sessionId:t,renameSession:y=>{t&&(S=s({sessionId:t,title:y}).then(()=>(Ee.success(`Renamed chat to “${y}”`),!0),()=>!1),d(S))},notify:(y,C)=>C==="error"?Ee.error(y):Ee.success(y),startFreshSession:y=>o==null?void 0:o(y),focusUsageSurface:()=>Qn.getState().reveal()}),...S?{confirmed:S}:{}}},[s,a,t,o,i,d]),commandPending:l>0}}function Lo(e,t){return{supported:(e==null?void 0:e.compact.supported)!==!1,runtimeLabel:t}}function Ar(e){const t=e.trim().toLowerCase();return t.startsWith("/")?t:`/${t}`}function _x(e){return Zl.map(t=>{var s,a;const n=t.fulfillment==="runtime"&&((a=(s=e==null?void 0:e.commandIntents)==null?void 0:s[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 wx(e,t){const n=Jl(),s=_x(t),a=Dr.filter(l=>!(l.command!==void 0&&n.has(`/${l.command}`))),o=new Set(Dr.map(l=>l.command)),i=e.filter(l=>{if(l.command!==void 0&&o.has(l.command))return!1;const u=[l.fullCommand,...l.aliases??[]].map(Ar);return l.command!==void 0&&u.push(Ar(l.command)),!u.some(d=>n.has(d))});return[...s,...a,...i]}const Nx=3e4;function Ex({percent:e,compactSupported:t,isStreaming:n}){return!(e===null||e<Jc||!t||n)}function Dx({sessionId:e,percent:t,compactSupported:n,isStreaming:s}){const a=xe(),[o,i]=c.useState(!1),l=c.useRef(!1),u=c.useRef(null),d=c.useCallback(()=>{l.current=!1,i(!1),u.current!==null&&(clearTimeout(u.current),u.current=null)},[]);c.useEffect(()=>{s&&l.current&&d()},[s,d]),c.useEffect(()=>()=>{u.current!==null&&clearTimeout(u.current)},[]);const f=c.useCallback(()=>{l.current||!e||(l.current=!0,i(!0),u.current=setTimeout(()=>{u.current=null,l.current=!1,i(!1)},Nx),Oo(a,e).then(h=>{h||d()}))},[e,a,d]);return{visible:Ex({percent:t,compactSupported:n,isStreaming:s}),percent:t??0,pending:o,onCompact:f}}function Ax({children:e,onSwitchAgent:t,onViewProfile:n,onNewSession:s}){return r.jsxs(ec,{children:[r.jsx(tc,{className:"min-w-0",children:e}),r.jsxs(nc,{className:"w-48",children:[r.jsxs(mn,{onClick:t,children:[r.jsx(sc,{className:"mr-2 size-4"}),"Switch agent"]}),r.jsx(Ps,{}),r.jsxs(mn,{onClick:n,children:[r.jsx(rc,{className:"mr-2 size-4"}),"View profile"]}),r.jsx(Ps,{}),r.jsxs(mn,{onClick:s,children:[r.jsx(ua,{className:"mr-2 size-4"}),"New chat"]})]})]})}function Tx({agentName:e,agentColor:t,agentEmoji:n,agentPath:s,nameHidden:a}){const o=ac(s),{open:i}=oc(),l=c.useCallback(()=>{s&&ic.getState().openProfileDocked(s)},[s]),u=c.useCallback(()=>{if(o===void 0)return l();i(o)},[o,i,l]),d=c.useCallback(()=>{oe.getState().openGlobalPaletteWithSearch("@")},[]),f=ha(),h=c.useCallback(()=>{f(s??void 0)},[f,s]);return!e||!t||!n?null:r.jsx("span",{className:"inline-flex min-w-0 items-center",children:s?r.jsx(Ax,{onSwitchAgent:d,onViewProfile:u,onNewSession:h,children:r.jsx(Ls,{size:"xs",name:e,color:t,emoji:n,nameHidden:a,onClick:u,className:"max-w-full"})}):r.jsx(Ls,{size:"xs",name:e,color:t,emoji:n,nameHidden:a,className:"max-w-full"})})}function Fx({sessionId:e,account:t}){const[n,s]=c.useState(!1),[a,o]=c.useState(!1),i=c.useRef(null);return r.jsxs(r.Fragment,{children:[r.jsx("span",{ref:i,className:"contents",children:r.jsx(lc,{sessionId:e,account:t,open:n,onOpenChange:s,onContinue:()=>{s(!1),o(!0)}})}),r.jsx(ro,{open:a,onOpenChange:o,sessionId:e,account:t,onCloseAutoFocus:l=>{var d;const u=(d=i.current)==null?void 0:d.querySelector("button");u&&(l.preventDefault(),u.focus())}})]})}function Rx({ctx:e,items:t}){return r.jsx("span",{className:"inline-flex min-w-0 items-center gap-2",children:t.map((n,s)=>{const a=n.component;return r.jsxs(c.Fragment,{children:[s>0&&r.jsx("span",{className:"text-muted-foreground/30 shrink-0","aria-hidden":"true",children:"·"}),r.jsx("span",{role:"group","aria-label":n.label,"data-testid":`extension-status-item-${n.id}`,className:"inline-flex min-w-0 items-center",children:r.jsx(ka,{fallback:null,onError:o=>zo(n,o),children:r.jsx(a,{...e})})})]},n.id)})})}function zo(e,t){console.warn(`[extensions] ${e.extensionId}'s status-bar item "${e.id}" failed to draw and is hidden.`,t)}function Mx({ctx:e,items:t}){return r.jsx(r.Fragment,{children:t.map(n=>{const s=n.component;return r.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:[r.jsx("span",{className:"shrink-0",children:n.label}),r.jsx("span",{className:"min-w-0 flex-1"}),r.jsx("span",{className:"text-muted-foreground inline-flex min-w-0 items-center text-xs",children:r.jsx(ka,{fallback:null,onError:a=>zo(n,a),children:r.jsx(s,{...e})})})]},n.id)})})}function Ix(e){const{costUsd:t,costBasis:n,...s}=e;return s}function Ox(e){var f;const{sessionId:t,agent:n,status:s,runtimeChip:a,onUpdateSession:o}=e,i={},l=e.density!=="full";n.name&&n.color&&n.emoji&&(i.agent=r.jsx(Tx,{agentName:n.name,agentColor:n.color,agentEmoji:n.emoji,agentPath:n.path,nameHidden:e.density==="avatar"})),s.cwd&&(i.cwd=r.jsx(Zc,{cwd:s.cwd})),e.gitStatus&&(i.git=r.jsx(lu,{data:e.gitStatus,workspace:e.workspace,compact:l})),a.runtime!==null&&(i.runtime=r.jsx(eu,{runtime:a.runtime,model:a.model,onChangeRuntime:a.onChangeRuntime,canSelect:a.canSelect,account:a.account,compact:!0}));const u=Ca(e.account);u!==null&&(i.account=r.jsx(Fx,{sessionId:t,account:e.account})),e.extensions.items.length>0&&(i.extensions=r.jsx(Rx,{ctx:e.extensions.ctx,items:e.extensions.items})),i.model=r.jsx(tu,{model:s.model,onChangeModel:h=>o({model:h}),effort:s.effort,onChangeEffort:h=>o({effort:h??void 0}),fastMode:s.fastMode,onChangeFastMode:h=>o({fastMode:h}),disabled:!t,sessionId:t||void 0,runtime:a.runtime,onCredits:e.account.onCredits,compact:l}),(f=e.plan)!=null&&f.active||(i.permission=r.jsx(nu,{mode:s.permissionMode,onChangeMode:e.onChangeMode,disabled:!t,pending:!s.permissionModeKnown,runtime:a.runtime,modelSupportsAutoMode:e.modelSupportsAutoMode,compact:l,makeDefault:e.makeDefault,onOpenChange:e.onPermissionPickerOpenChange})),e.plan&&(i.plan=r.jsx(su,{descriptor:e.plan.descriptor,active:e.plan.active,onToggle:e.plan.onToggle,disabled:!t})),e.contextPercent!==null&&(i.context=r.jsx(ru,{percent:e.contextPercent,contextUsage:e.contextUsage,compact:e.compact,reading:e.contextReading}));const d=e.usage&&e.usageSource==="account"&&!e.supportsCostTracking?Ix(e.usage):e.usage;return d&&cc(d)&&(e.supportsCostTracking||e.usageSource==="account")&&!au({account:u})&&(i.usage=r.jsx(uc,{usage:d,observedAt:e.usageObservedAt,now:e.now})),e.liveSubagentCount>0&&(i.subagents=r.jsx(ou,{count:e.liveSubagentCount,running:e.runningSubagents,waiting:e.waitingOnSubagents})),i.connection=r.jsx(iu,{connectionState:e.connectionState,compact:l}),i}const $x=[],Px="(max-width: 639px)";function Lx({sessionId:e,sessionStatus:t,isStreaming:n,syncConnectionState:s,agentName:a,agentColor:o,agentEmoji:i,agentPath:l}){var Ie,Ue;const{ref:u,budget:d}=cu(),f=Sa(e),h=Fa(e,t,n,f.runtime),m=wt(e||null),{pins:x}=uu(),g=du(e),S=fu(e,m,g.usage),b=S.usage,y=jt(),C=new Date(y),v=dc(b,S.observedAt,C),p=g.contextUsage,j=((Ie=fs(e))==null?void 0:Ie.contextUsage)??null,_=Qn(re=>re.open),D=Qn(re=>re.setOpen),{data:T}=mu(h.cwd),N=vx(h.cwd),{project:A}=fc(h.cwd),k=mc(Px),E=c.useMemo(()=>({sessionId:e,cwd:h.cwd,project:A,trackerItems:m.trackerItems,compact:k}),[e,h.cwd,A,m.trackerItems,k]),w=pu(E),{data:R}=is(),O=hu(g.activeSubagents).running,F=g.runningSubagentCount??O.length,{data:$}=os({sessionId:e||void 0,runtime:f.runtime??void 0}),B=((Ue=$==null?void 0:$.find(re=>re.value===h.model))==null?void 0:Ue.supportsAutoMode)??!1,U=Zt(f.runtime),Y=(U==null?void 0:U.permissionModes.values)??$x,se=U==null?void 0:U.permissionModes.default,V=pc(e),L=te(re=>re.recordAutoConfirmed),[I,P]=c.useState(!1),Q=gu({sessionId:e,runtime:f.runtime,declaredModes:Y,runtimeDefaultMode:se}),[ae,M]=c.useState(!1),W=c.useCallback(re=>h.updateSession({permissionMode:re}),[h]),X=c.useCallback(re=>{if(re==="auto"&&!V){P(!0);return}W(re).then(Ce=>{Ce&&Q.offerFor(re)})},[V,W,Q,P]),J=c.useCallback(()=>{L(e),W("auto"),P(!1)},[L,e,W,P]),Z=hc(Y),K=Z!==void 0&&h.permissionMode===Z.id,le=gc(e),fe=te(re=>re.recordModeBeforePlan),me=c.useCallback(re=>{if(!Z)return;if(re){fe(e,h.permissionMode),W(Z.id);return}const Ce=le,$e=Ce!==void 0&&Y.some(Xe=>Xe.id===Ce)&&(Ce!=="auto"||B)?Ce:se;$e&&W($e)},[Z,fe,e,h,W,le,Y,B,se]),z=f.runtime?Dt(f.runtime).label:"",he=Lo(U==null?void 0:U.commandIntents,z),ce=g.contextPercent,je=Dx({sessionId:e,percent:ce,compactSupported:he.supported,isStreaming:n}),[ke,De]=c.useState(!1);xu(()=>De(re=>!re));const Me={cwd:h.cwd,git:bu(T)?yu(T.branch,T.clean,T.detached):null,contextPercent:ce,connectionState:s,permissionMode:h.permissionMode,permissionDescriptor:(U==null?void 0:U.permissionModes.values.find(re=>re.id===h.permissionMode))??null,permissionPickerOpen:ae,plan:Z?{active:K}:null,runtime:f.runtime===null||R===void 0?null:{type:f.runtime,isDefault:f.runtime===R.defaultRuntime,canSelect:f.canSelect},account:Ca(m),usage:b,usageStale:v,subagentsInFlight:F,extensionItems:w.promotion},de=je.visible&&d.density==="full",Oe=je.visible&&!de,ye=Ox({sessionId:e,agent:{name:a,color:o,emoji:i,path:l},status:h,onUpdateSession:h.updateSession,onChangeMode:X,makeDefault:ae?Q.line:null,onPermissionPickerOpenChange:M,modelSupportsAutoMode:B,plan:Z?{descriptor:Z,active:K,onToggle:me}:null,gitStatus:T,workspace:N,runtimeChip:f,account:m,contextPercent:ce,contextUsage:p,contextReading:j,compact:de?{pending:je.pending,onCompact:je.onCompact}:null,usage:b,usageSource:S.source,usageObservedAt:S.observedAt,now:C,supportsCostTracking:(U==null?void 0:U.supportsCostTracking)??!0,runningSubagents:O,liveSubagentCount:F,waitingOnSubagents:g.lifecycle==="idle",connectionState:s,density:d.density,extensions:{ctx:E,items:w.visible}}),{items:_e,overflow:be}=vu(ku({ctx:Me,pins:x,nodes:ye}),d);return r.jsxs("div",{ref:u,className:"relative pt-2",children:[!ae&&Q.line&&r.jsx(Cu,{...Q.line,placement:"overlay"}),r.jsx(Su,{items:_e,trailing:r.jsx(ju,{open:ke,onOpenChange:De,diagnostics:g,controls:{plan:Z?{active:K,onToggle:me}:null},promotionContext:Me,overflowCount:be,addOns:w.visible.length>0?r.jsx(Mx,{ctx:E,items:w.visible}):void 0,urgentAction:Oe?{label:`Compact chat · ${je.percent}% full`,onAction:je.onCompact,pending:je.pending}:null})}),r.jsx(_u,{usage:b??null,accountUsage:S.accountUsage,observedAt:S.observedAt,open:_,onOpenChange:D}),r.jsx(wu,{open:I,onOpenChange:P,onConfirm:J})]})}const zx=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 Bx(e){return e!==void 0&&e!=="completed"}function qx(e){const t=zx[e];return t!==void 0?t:Ux(e)}function Ux(e){if(e.length===0)return"Ended";const t=e.replace(/[_-]+/g," ").trim().split(/\s+/);if(t.length===0)return"Ended";const[n,...s]=t;return[n.charAt(0).toUpperCase()+n.slice(1).toLowerCase(),...s.map(o=>o.toLowerCase())].join(" ")}function Hx({terminalReason:e}){const t=Bx(e),n=t?qx(e):"";return r.jsx(ie,{children:t&&r.jsx(G.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:r.jsx(xc,{variant:"secondary","aria-label":`Chat ended: ${n}`,children:n})},e)})}const Wx="The turn ended before completing.";function Vx({sessionId:e,onRetry:t,onSigninComplete:n,onChooseModel:s}){var m;const a=tn(e),o=((m=fs(e))==null?void 0:m.lastError)??null,i=(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=!i&&a?`${Dt(a).label} stopped unexpectedly`:void 0,u=(o==null?void 0:o.message)??Wx,d=i?void 0:u,f=a?ls(a):void 0,h=o?[o.code,o.details].filter(Boolean).join(`
55
55
  `):void 0;return r.jsx(G.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:r.jsx(sn,{category:(o==null?void 0:o.category)??"execution_error",heading:l,message:u,subtext:d,details:h||void 0,onRetry:t,onSigninComplete:n,onChooseModel:s,runtimeLabel:f,sessionId:e,...o!=null&&o.code?{code:o.code}:{},...o!=null&&o.reason?{reason:o.reason}:{}})})}const Gx=["Type @ to mention a file","Type / to browse commands","End a line with \\ to keep typing","Drop or paste files to attach"];function Kx(e,t,n){const s=c.useCallback(g=>{var C;if(!e||!t.current)return;const S=te.getState(),b=(C=n.current)==null?void 0:C.get(e);if(b!==void 0&&S.getSession(e).mountGeneration!==b)return;const y=typeof g=="function"?g(S.getSession(e).messages):g;S.updateSession(e,{messages:y})},[e,t,n]),a=c.useCallback(g=>{e&&te.getState().updateSession(e,{input:g})},[e]),o=c.useCallback(g=>{e&&te.getState().updateSession(e,{status:g})},[e]),i=c.useCallback(g=>{e&&te.getState().updateSession(e,{error:g})},[e]),l=c.useCallback(g=>{e&&te.getState().updateSession(e,{sessionStatus:g})},[e]),u=c.useCallback(g=>{e&&te.getState().updateSession(e,{estimatedTokens:g})},[e]),d=c.useCallback(g=>{e&&te.getState().updateSession(e,{streamStartTime:g})},[e]),f=c.useCallback(g=>{e&&te.getState().updateSession(e,{isTextStreaming:g})},[e]),h=c.useCallback(g=>{e&&te.getState().updateSession(e,{systemStatus:g})},[e]),m=c.useCallback(g=>{e&&te.getState().updateSession(e,{operationProgress:g})},[e]),x=c.useCallback(g=>{e&&te.getState().updateSession(e,{promptSuggestions:g})},[e]);return{setMessages:s,setInput:a,setStatus:o,setError:i,setSessionStatus:l,setEstimatedTokens:u,setStreamStartTime:d,setIsTextStreaming:f,setSystemStatus:h,setOperationProgress:m,setPromptSuggestions:x}}function bs(e){const t=[],n=[];for(const s of e)s.type==="text"?t.push(s.text):s.type==="tool_call"&&n.push({toolCallId:s.toolCallId,toolName:s.toolName,input:s.input||"",result:s.result,progressOutput:s.progressOutput,status:s.status,interactiveType:s.interactiveType,questions:s.questions,answers:s.answers,timeoutMs:s.timeoutMs,hooks:s.hooks,startedAt:s.startedAt,completedAt:s.completedAt,approvalStartedAt:s.approvalStartedAt,approvalRemainingMs:s.approvalRemainingMs,approvalParked:s.approvalParked,approvalTitle:s.approvalTitle,approvalDisplayName:s.approvalDisplayName,approvalDescription:s.approvalDescription,approvalBlockedPath:s.approvalBlockedPath,approvalDecisionReason:s.approvalDecisionReason,approvalHasSuggestions:s.approvalHasSuggestions,approvalAlwaysAllowScope:s.approvalAlwaysAllowScope});return{content:t.join(`
56
- `),toolCalls:n}}function yt(e){const t=e.parts?[...e.parts]:[];if(t.length===0&&(e.content&&t.push({type:"text",text:e.content}),e.toolCalls))for(const s of e.toolCalls)t.push({type:"tool_call",toolCallId:s.toolCallId,toolName:s.toolName,input:s.input,result:s.result,status:s.status,...s.questions||s.questionOutcome?{interactiveType:"question",questions:s.questions,answers:s.answers,questionOutcome:s.questionOutcome}:{},...s.approvalOutcome?{interactiveType:"approval",approvalOutcome:s.approvalOutcome,approvalResolvedAt:s.approvalResolvedAt,approvalStartedAt:s.approvalStartedAt,approvalReasonGiven:s.approvalReasonGiven}:{}});const n=bs(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}:{},...e.roomMessage?{roomMessage:e.roomMessage}:{}}}function Qx(e,t,n){const s=new Set(e.map(d=>d.id)),a=e.filter(d=>d._streaming),o=a.find(d=>d.role==="user"),i=a.find(d=>d.role==="assistant"),l=[];let u=-1;for(let d=0;d<t.length;d++){const f=t[d];if(!s.has(f.id)){if(o&&f.role==="user"&&f.content===o.content){u=d,n(h=>h.map(m=>m.id===o.id?{...yt(f),_streaming:!1}:m));continue}if(i&&u>=0&&d===u+1&&f.role==="assistant"){const h=yt(f),m=new Set(h.parts.filter(S=>S.type==="background_task").map(S=>S.taskId)),x=i.parts.filter(S=>S.type==="background_task"&&!m.has(S.taskId)),g=x.length>0?[...h.parts,...x]:h.parts;n(S=>S.map(b=>b.id===i.id?{...h,parts:g,_streaming:!1}:b));continue}l.push(f)}}l.length>0&&n(d=>[...d,...l.map(yt)])}function Yx({sessionId:e,sid:t,transport:n,sessionCwd:s,enableMessagePolling:a,isStreaming:o,setMessages:i}){const l=La(),u=s.cwd,d=c.useRef(u);c.useEffect(()=>{d.current=u},[u]);const f=Ye({queryKey:["messages",e,u],queryFn:()=>n.getMessages(e,u??void 0),staleTime:Ge.MESSAGE_STALE_TIME_MS,refetchOnWindowFocus:!1,enabled:e!==null,refetchInterval:()=>o||!a?!1:l?Ge.ACTIVE_TAB_REFETCH_MS:Ge.BACKGROUND_TAB_REFETCH_MS});return c.useEffect(()=>{const h=te.getState();t&&h.updateSession(t,{historySeeded:!1}),h.getSession(e??"").status!=="streaming"&&i([])},[e,u,t,i]),c.useEffect(()=>{if(!f.data)return;const h=f.data.messages,m=te.getState().getSession(t).historySeeded;if(!m&&h.length>0){if(o)return;t&&te.getState().updateSession(t,{historySeeded:!0}),i(h.map(yt));return}m&&!o&&Qx(te.getState().getSession(t).messages,h,i)},[f.data,o,t,i]),{historyQuery:f}}function Bo(e,t){if(e===t)return;const{opened:n,counts:s,mergeUsage:a}=at.getState(),o=zs("session",e),i=Date.parse(n[o]??"");Number.isNaN(i)||a([{key:zs("session",t),lastUsedAt:i,useCount:s[o]??1}])}function Xn(e,t,n){e&&n.then(s=>{if(!s)return;const a=te.getState();a.getSession(e).input.trim()===t.trim()&&a.updateSession(e,{input:""})},()=>{})}const Pt=new Map;function Xx(e,t){const s=(Pt.get(e)??Promise.resolve()).then(t),a=s.then(()=>{},()=>{});return Pt.set(e,a),a.then(()=>{Pt.get(e)===a&&Pt.delete(e)}),s}const nt=new Set;function Tr(e){var a;const t=e,n=typeof(t==null?void 0:t.code)=="string"?t.code:void 0,s=(a=t==null?void 0:t.body)==null?void 0:a.agentId;return{...n?{code:n}:{},...typeof s=="string"?{agentId:s}:{}}}function Jx({sessionId:e,input:t,status:n,transport:s,queryClient:a,selectedCwd:o,onSessionIdChangeReplace:i,transformContent:l,launchRuntime:u,agentPath:d,agentLookupPending:f,agentLookupFailed:h,launchAccount:m,takeSeedContext:x,setInput:g,setError:S,tryNativeCommand:b}){const y=c.useRef(o);c.useEffect(()=>{y.current=o},[o]);const C=c.useRef(u);c.useEffect(()=>{C.current=u},[u]);const v=c.useRef(m);c.useEffect(()=>{v.current=m},[m]);const{data:p}=is(),j=c.useRef(p==null?void 0:p.defaultRuntime);c.useEffect(()=>{j.current=p==null?void 0:p.defaultRuntime},[p==null?void 0:p.defaultRuntime]);const _=Nu(e,u),D=c.useRef(_.mode);c.useEffect(()=>{D.current=_.mode},[_.mode]);const T=c.useRef(l);c.useEffect(()=>{T.current=l});const N=c.useRef(x);c.useEffect(()=>{N.current=x});const A=c.useRef(i);c.useEffect(()=>{A.current=i});const k=c.useCallback(async(V,L,I={})=>{var le,fe,me;if(!I.kickoff){const z=b(V);if(z.handled){L&&z.ran&&(z.confirmed?Xn(e,V,z.confirmed):g(""));return}}const P=e,Q=I.cwd??y.current;S(null);const ae=a.getQueryData(We.list(Q))??[],M=pn(P),W=(M==null?void 0:M.draft)??!ae.some(z=>z.id===P),X=(M==null?void 0:M.draft)===!1?!1:W||nt.has(P);if(X&&(f||h))return;X&&nt.add(P),I.kickoff||(at.getState().recordOpened("session",P),Q&&at.getState().recordOpened("agent",Q)),xt.attachSession(P,Q);let J;try{J=!I.kickoff&&T.current?await T.current(V):V}catch(z){if(I.kickoff)throw z;S({heading:"Couldn’t send message",message:z.message||"The attachment didn’t upload. Try again.",retryable:!1});return}const Z=Ne.getState();if(W){const z=new Date().toISOString();Bs(a,Q,{id:P,title:`Chat ${P.slice(0,8)}`,createdAt:z,updatedAt:z,permissionMode:((le=a.getQueryData(We.detail(P,Q)))==null?void 0:le.permissionMode)??D.current??"default",runtime:C.current??j.current??"claude-code"})}const K=crypto.randomUUID();I.kickoff||Z.setOptimisticUserMessage(P,{id:K,content:V}),Z.setTriggerPending(P,!0),L&&g("");try{const z=Us(oe.getState(),Q??null),{uiState:he,commit:ce}=qs(P,z),ke={clientMessageId:K,context:he?{uiState:he}:void 0};X&&(ke.create=!0),X&&C.current&&(ke.runtime=C.current),X&&d&&(ke.agentPath=d),X&&v.current&&(ke.account=v.current);const De=oe.getState().retryAccount;(De==null?void 0:De.sessionId)===P&&(ke.account=De.id,oe.getState().setRetryAccount(null));const Me=(fe=N.current)==null?void 0:fe.call(N);Me&&(ke.seedContext=Me);const{sessionId:de}=await s.postMessage(P,J,Q??void 0,ke);if(nt.delete(P),M){const ye={...M,draft:!1};hn(P,ye),hn(de,ye)}if(ce(de),de!==P){Ne.getState().migrateSessionContinuity(P,de),oe.getState().carryCanvasWritesAcross(P,de),xt.attachSession(de,Q),Bo(P,de),st.getState().migrate(P,de);const ye=a.getQueryData(We.list(Q))??[],_e=ye.find(be=>be.id===P);_e&&!ye.some(be=>be.id===de)&&Bs(a,Q,{..._e,id:de}),a.setQueryData(We.list(Q),be=>be==null?void 0:be.filter(Ie=>Ie.id!==P))}(me=A.current)==null||me.call(A,de);const Oe=de;setTimeout(()=>{var be;const ye=bt.getState().rekeys[Oe]??Oe,_e=Ne.getState().getSession(ye);_e.triggerPending&&((be=_e.status)==null?void 0:be.lifecycle)!=="streaming"&&Ne.getState().setTriggerPending(ye,!1)},Jt.TRIGGER_PENDING_TIMEOUT_MS)}catch(z){if(Ne.getState().setOptimisticUserMessage(P,null),Ne.getState().setTriggerPending(P,!1),I.kickoff)throw z;S({heading:"Couldn’t send message",message:z.message||"Couldn’t reach DorkOS. Try again.",retryable:!0,...Tr(z)})}},[e,s,a,g,S,b,d,f,h]),E=c.useCallback(async(V,L)=>{!V.trim()||n==="streaming"||await k(V.trim(),(L==null?void 0:L.clearInput)===!0,{...L!=null&&L.cwd?{cwd:L.cwd}:{}})},[n,k]),w=c.useCallback(()=>E(t,{clearInput:!0}),[t,E]),R=c.useCallback(async(V,L,I)=>{if(!e)return!1;const P=e,Q=y.current;S(null);const ae=(a.getQueryData(We.list(Q))??[]).some(W=>W.id===P),M=pn(P);return((M==null?void 0:M.draft)??!ae)&&nt.add(P),Xx(P,async()=>{var X;let W;try{W=T.current?await T.current(V):V}catch(J){return S({heading:I,message:J.message||"The attachment didn’t upload. Try again.",retryable:!1}),!1}try{const J=Us(oe.getState(),Q??null),{uiState:Z,commit:K}=qs(P,J),le={...Z?{uiState:Z}:{},...L==="queue"?{queued:!0}:{}},fe=Object.keys(le).length>0?le:void 0,me=((X=pn(P))==null?void 0:X.draft)===!1?!1:nt.has(P);if(me&&(f||h))return!1;const{sessionId:z}=await s.postMessage(P,W,Q??void 0,{context:fe,disposition:L,...me?{create:!0,...C.current&&{runtime:C.current},...v.current&&{account:v.current},...d&&{agentPath:d}}:{}});return me&&nt.delete(P),M&&hn(z,{...M,draft:!1}),K(z),!0}catch(J){return S({heading:I,message:J.message||"Couldn’t reach DorkOS. Try again.",retryable:!1,...Tr(J)}),!1}})},[e,s,a,S,d,f,h]),O=c.useCallback(V=>R(V,"queue","Couldn’t queue message"),[R]),F=c.useCallback(V=>R(V,"steer","Couldn’t steer the agent"),[R]),$=c.useCallback(V=>R(V,"stage","Couldn’t add context"),[R]),B=c.useCallback(async()=>{if(!e)return{receipt:{outcome:"not-running",reason:"no-open-turn",runtime:"unknown"},cancelled:[]};try{const{receipt:V,cancelledQueued:L}=await s.interruptSession(e);return{receipt:V,cancelled:L??[]}}catch{return{receipt:{outcome:"failed",reason:"delivery-failed",runtime:"unknown"},cancelled:[]}}},[e,s]),q=c.useCallback(async V=>{S(null),await k(V,!1)},[k,S]),Y=c.useCallback(async(V,L)=>{await k(V,!1,{kickoff:!0,...L?{cwd:L}:{}})},[k]),se=c.useCallback((V,L)=>{},[]);return{handleSubmit:w,submitContent:E,enqueueContent:O,steerContent:F,addContextContent:$,stop:B,retryMessage:q,submitKickoff:Y,markToolCallResponded:se}}const Lt=new Set,Fr=new Set,zt=new Set;function Zx(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 e0({sessionId:e,cwd:t,status:n,messages:s,hydrated:a,canStart:o=!0,submitKickoff:i,submitContent:l}){const u=Xt(e),d=s.length,f=s.some(Zx);c.useEffect(()=>{if(!e)return;if(!u){t&&d===0&&n==="idle"&&st.getState().claimByPath(t,e);return}if(u.fired||Lt.has(e)||!o||d>0||n!=="idle")return;Lt.add(e),st.getState().markFired(e);const h=u.kind==="first-message";(h?l:i)(u.kickoffMessage,u.path||void 0).catch(x=>{console.warn("[chat] first-turn trigger failed for newborn session",e,x),Fr.has(e)?h||st.getState().markGreetingFailed(e):(Fr.add(e),Lt.delete(e),st.getState().resetFired(e))})},[e,t,u,n,d,o,i,l]),c.useEffect(()=>{if(!(!e||!u)&&u.kind!=="first-message"&&!(!u.fired&&!Lt.has(e))&&!u.greetingFailed){if(f){zt.delete(e);return}if(n==="streaming"){zt.add(e);return}a&&zt.has(e)&&(zt.delete(e),st.getState().markGreetingFailed(e))}},[e,u,n,f,a])}function t0(e,t){return c.useEffect(()=>{bc(),xt.connectList(),e&&xt.attachSession(e,t)},[e,t]),c.useEffect(()=>()=>xt.releaseSession(),[]),ja(e??"")}function n0(e,t){const n=_a(e),s=c.useRef(t);c.useEffect(()=>{s.current=t}),c.useEffect(()=>{var a;!n||!e||(Bo(e,n),(a=s.current)==null||a.call(s,n))},[n,e])}const s0=500;function r0(e,t,n){const s=c.useRef(new Map),[a,o]=c.useState(null),i=t.length>0?t[0].seq:-1;c.useEffect(()=>{const h=s.current;if(!e||!n){e&&h.delete(e),o(null);return}let m=h.get(e);(!m||m.turnSeq!==i)&&(m={turnSeq:i,anchor:Date.now()},h.set(e,m)),o(m.anchor)},[e,n,i]);const l=c.useMemo(()=>{let h=0;for(const m of t)m.type==="text_delta"&&(h+=m.text.length);return h/4},[t]),[u,d]=c.useState(!1),f=c.useRef({sid:null,tokens:0});return c.useEffect(()=>{const h=f.current,m=e===h.sid&&l>h.tokens;if(f.current={sid:e,tokens:l},m&&!u&&d(!0),!m&&!u)return;const x=setTimeout(()=>d(!1),s0);return()=>clearTimeout(x)},[e,l,u]),{streamStartTime:a,estimatedTokens:l,isTextStreaming:u}}function a0(e,t,n,s){const a=c.useRef(new Map),o=c.useRef(s);c.useEffect(()=>{o.current=s}),c.useEffect(()=>{var d;if(!e)return;const i=a.current,l=n??0;let u=i.get(e);(!u||u.floor!==l)&&(u={floor:l,seen:l},i.set(e,u));for(const f of t)f.seq<=u.seen||(f.type==="todo_update"&&((d=o.current)==null||d.call(o,{action:f.action,task:f.task,tasks:f.tasks,previousId:f.previousId})),u.seen=f.seq)},[e,t,n])}function o0(e){let t=null,n=null;for(const s of e){if(s.type==="operation_progress"){t=s.state==="started"?{operation:s.operation,determinate:s.determinate,...s.percent!==void 0?{percent:s.percent}:{},...s.message!==void 0?{message:s.message}:{}}:null;continue}if(s.type==="system_status"){s.status||(n={message:s.message});continue}n=null}return{operationProgress:t,systemStatus:n}}function i0(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 l0(e,t){return((e==null?void 0:e.message)??null)===((t==null?void 0:t.message)??null)}function c0(e,t,n,s){const a=c.useRef(new Map),o=c.useRef(new Map),i=c.useRef(n),l=c.useRef(s);c.useEffect(()=>{i.current=n,l.current=s}),c.useEffect(()=>{if(!e)return;const{operationProgress:u,systemStatus:d}=o0(t),f=a.current.get(e)??null;i0(f,u)||(i.current(u),a.current.set(e,u));const h=o.current.get(e)??null;l0(h,d)||(l.current(d),o.current.set(e,d))},[e,t])}function u0(e,t){for(let n=e.length-1;n>=0;n--){const s=e[n];if(s.type==="capability_approval"&&s.approval.approvalId===t)return s}}function d0(e,t){const n=u0(e,t.approval.approvalId);n?n.approval=t.approval:e.push({type:"capability_approval",approval:t.approval})}function f0(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 s=e[n];s.outcome="timeout"}function m0(e,t,n){return e.findIndex(s=>s.type==="mcp_signin"&&s.agentId===t&&s.serverName===n&&s.outcome===void 0)}function p0(e,t){const n={type:"mcp_signin",serverName:t.serverName,agentId:t.agentId,flowId:t.flowId,authorizeUrl:t.authorizeUrl,disclosure:t.disclosure},s=m0(e,t.agentId,t.serverName);s===-1?e.push(n):e[s]=n}function h0(e,t){const n=e.findIndex(a=>a.type==="mcp_signin"&&a.flowId===t.flowId);if(n===-1)return;const s=e[n];s.outcome=t.outcome,t.toolCount!==void 0&&(s.toolCount=t.toolCount)}const Rr="__in_progress_turn__",g0="__optimistic_user__";function x0(e){return{id:g0,role:"user",content:e,parts:[{type:"text",text:e}],timestamp:"",_streaming:!0}}function b0(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 y0(e){return{id:`staged-${e.messageId}`,role:"user",content:e.content,parts:[{type:"text",text:e.content}],timestamp:"",_streaming:!0,_stagedContext:!0}}function Re(e,t){for(let n=e.length-1;n>=0;n--){const s=e[n];if(s.type==="tool_call"&&s.toolCallId===t)return s}}function on(e,t){for(let n=e.length-1;n>=0;n--){const s=e[n];if(s.type==="elicitation"&&s.interactionId===t)return s}}function v0(e,t){for(let n=e.length-1;n>=0;n--){const s=e[n];if(s.type==="background_task"&&s.taskId===t)return s}}function k0(e,t){Uo(e);const n=e[e.length-1];n&&n.type==="text"?n.text+=t.text:e.push({type:"text",text:t.text})}function C0(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 Uo(e){for(const t of e)t.type==="thinking"&&t.isStreaming&&(t.isStreaming=!1)}function S0(e,t,n){const s=Re(e,t.toolCallId);if(s){t.input!==void 0&&(s.input=(s.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 j0(e,t){const n=Re(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 _0(e,t){const n=Re(e,t.toolCallId);n&&(n.progressOutput=(n.progressOutput??"")+t.content)}function qo(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},s=Re(e,t.id);s?Object.assign(s,n):e.push({type:"tool_call",toolCallId:t.id,toolName:t.toolName,...n})}function Ho(e,t){const n=Re(e,t.id),s={timeoutMs:t.timeoutMs,approvalStartedAt:t.startedAt,approvalRemainingMs:t.remainingMs};n?(n.interactiveType="question",n.questions=t.questions,n.status="pending",Object.assign(n,s)):e.push({type:"tool_call",toolCallId:t.id,toolName:"AskUserQuestion",input:"",status:"pending",interactiveType:"question",questions:t.questions,...s})}function Wo(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},s=on(e,t.id);s?Object.assign(s,n):e.push({type:"elicitation",interactionId:t.id,...n})}function w0(e){return e==="denied"||e==="expired"||e==="cancelled"?"error":e==="answered"?"complete":"running"}function N0(e,t){const n=Re(e,t.id);if(n){n.status==="pending"&&(n.status=w0(t.resolution),n.approvalRemainingMs=void 0);const a=yc(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=vc(t);o&&(n.questionOutcome=o)}const s=on(e,t.id);s&&s.status==="pending"&&(s.status="submitted",s.remainingMs=void 0)}function E0(e,t){for(let n=e.length-1;n>=0;n--){const s=e[n];if(s.type==="tool_call"&&s.hooks){const a=s.hooks.find(o=>o.hookId===t);if(a)return a}}}function D0(e,t){for(const n of e.values()){const s=n.find(a=>a.hookId===t);if(s)return s}}function A0(e,t,n){const s=E0(e,t.hookId)??D0(n,t.hookId);if(s){s.status=t.status,t.hookName!==void 0&&(s.hookName=t.hookName),t.stdout!==void 0&&(s.stdout=t.stdout),t.stderr!==void 0&&(s.stderr=t.stderr),t.exitCode!==void 0&&(s.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=Re(e,t.toolCallId);o?o.hooks=[...o.hooks??[],a]:n.set(t.toolCallId,[...n.get(t.toolCallId)??[],a])}function T0(e,t){const n=e[0];if(n&&n.type==="memory_recall"){const o=new Set(n.memories.map(l=>l.path)),i=t.memories.filter(l=>!o.has(l.path));i.length>0&&(n.memories=[...n.memories,...i]);return}const s=new Set,a=t.memories.filter(o=>s.has(o.path)?!1:(s.add(o.path),!0));e.unshift({type:"memory_recall",mode:t.mode,memories:a,isStreaming:!0})}function F0(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 R0(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 M0(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 I0(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 O0(e,t){Uo(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 $0(e,t){const n=v0(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 P0={approval:"approval_required",question:"question_prompt",elicitation:"elicitation_prompt"};function L0(e){const{type:t,...n}=e;return{...n,seq:0,type:P0[t]}}function z0(e,t){const n=Re(e,t);return(n==null?void 0:n.interactiveType)!==void 0?!0:on(e,t)!==void 0}function B0(e,t){switch(t.type){case"approval_required":qo(e,t);break;case"question_prompt":Ho(e,t);break;case"elicitation_prompt":Wo(e,t);break}}function U0(e,t,n){const s=Re(e,t.id);if(s){!n&&s.result===void 0&&(s.status="pending"),s.approvalStartedAt=t.startedAt,s.approvalRemainingMs=t.remainingMs,t.timeoutMs!==void 0&&(s.timeoutMs=t.timeoutMs),s.approvalParked=t.parked===!0?!0:void 0;return}const a=on(e,t.id);a&&(a.startedAt=t.startedAt,a.remainingMs=t.remainingMs,t.timeoutMs!==void 0&&(a.timeoutMs=t.timeoutMs))}function q0(e,t,n){for(const s of t){if(z0(e,s.id)){U0(e,s,n.has(s.id));continue}B0(e,L0(s)),H0(e,s)}}function H0(e,t){if(t.parked!==!0)return;const n=Re(e,t.id);n&&(n.approvalParked=!0)}function W0(e){const t=new Set;for(const n of e)n.type==="interaction_resolved"&&t.add(n.id);return t}function Jn(e){const t=[],n=new Map;for(const s of e)switch(s.type){case"text_delta":k0(t,s);break;case"thinking_delta":C0(t,s);break;case"tool_call":S0(t,s,n);break;case"tool_result":j0(t,s);break;case"tool_progress":_0(t,s);break;case"approval_required":qo(t,s);break;case"question_prompt":Ho(t,s);break;case"elicitation_prompt":Wo(t,s);break;case"capability_approval_required":d0(t,s);break;case"capability_approval_resolved":f0(t,s);break;case"mcp_signin_required":p0(t,s);break;case"mcp_signin_resolved":h0(t,s);break;case"interaction_resolved":N0(t,s);break;case"subagent_update":$0(t,s);break;case"hook_update":A0(t,s,n);break;case"memory_recall":T0(t,s);break;case"image_attachment":F0(t,s);break;case"compact_boundary":R0(t,s);break;case"permission_denied":M0(t,s);break;case"model_substituted":t.push({type:"model_substituted",from:s.from,fromName:s.fromName,to:s.to,toName:s.toName,reason:s.reason});break;case"operation_progress":I0(t,s);break;case"error":O0(t,s);break}return t}function Mr(e,t){if(e.length===0)return null;const n=bs(e);return{id:t,role:"assistant",content:n.content,toolCalls:n.toolCalls.length>0?n.toolCalls:[],parts:e,timestamp:"",_streaming:!0}}function V0(e,t){const n=[];let s=[],a=0;for(const l of e){if(l.type!=="turn_input"&&l.type!=="context_staged"){s.push(l);continue}const u=Jn(s),d=Mr(u,`${Rr}-${a}`);d&&n.push(d),a+=1,n.push(l.type==="turn_input"?b0(l):y0(l)),s=[]}const o=Jn(s);q0(o,t,W0(e));const i=Mr(o,Rr);return i&&n.push(i),n}function G0(e){const t=new Set;for(const n of e)for(const s of n.parts)s.type==="tool_call"&&t.add(s.toolCallId);return t}function K0(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 Q0(e,t){const n=e.parts.filter(a=>a.type!=="tool_call"||!t.has(a.toolCallId)||!K0(a));if(n.length===e.parts.length)return e;if(n.length===0)return null;const s=bs(n);return{...e,parts:n,content:s.content,toolCalls:s.toolCalls.length>0?s.toolCalls:void 0}}function Y0(e){let t=e.length;for(;t>0&&e[t-1].role==="assistant";)t-=1;return t}function X0(e,t,n=[],s=null){const a=V0(t,n),o=G0(a),i=e.map(yt),l=o.size===0?i.length:Y0(i),u=[];for(const[d,f]of i.entries()){const h=d<l?f:Q0(f,o);h&&u.push(h)}return s&&u.push(x0(s.content)),u.push(...a),u}function Ir(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 J0(e,t){return e.interactiveType==="approval"&&e.approvalOutcome===t.outcome&&e.approvalResolvedAt===t.resolvedAt&&e.approvalStartedAt===t.startedAt&&e.approvalReasonGiven===t.reasonGiven}function Z0(e,t){return t.size===0?e:e.map(n=>{if(!n.parts)return n;let s=!1;const a=n.parts.map(o=>{if(o.type!=="tool_call")return o;const i=t.get(o.toolCallId);return!i||J0(o,i)?o:(s=!0,{...o,interactiveType:"approval",approvalOutcome:i.outcome,approvalResolvedAt:i.resolvedAt,approvalStartedAt:i.startedAt,approvalReasonGiven:i.reasonGiven,...i.displayName!==void 0?{approvalDisplayName:i.displayName}:{}})});return s?{...n,parts:a}:n})}function eb({sessionId:e,transport:t,sessionCwd:n,streamState:s,queryClient:a,onStreamingDone:o}){var C;const i=n.cwd,l=c.useRef(e),u=c.useRef(i),d=c.useRef(o);c.useEffect(()=>{l.current=e,u.current=i,d.current=o});const f=c.useRef(new Map),h=c.useRef(new Map),m=c.useRef(new Map),x=c.useRef(new Map),g=c.useRef(new Map),S=((C=s.status)==null?void 0:C.lifecycle)??null,b=s.hydrationGeneration,y=s.userTurnCount;c.useEffect(()=>{var A,k,E;if(!e)return;const v=g.current.get(e);g.current.set(e,y),v!==void 0&&y!==v&&x.current.set(e,!1);const p=h.current.get(e);if(h.current.set(e,b),p!==b){f.current.set(e,S),S==="streaming"&&m.current.set(e,((A=Ne.getState().getSession(e).optimisticUserMessage)==null?void 0:A.id)??null);return}const j=f.current.get(e)??null;if(f.current.set(e,S),S==="streaming"&&j!=="streaming"&&m.current.set(e,((k=Ne.getState().getSession(e).optimisticUserMessage)==null?void 0:k.id)??null),!(j==="streaming"&&S!=="streaming"&&S!==null))return;const D=e,T=m.current.get(D)??null,N=Ir(Jn(Ne.getState().getSession(D).inProgressTurn));t.getMessages(D,u.current??void 0).then(w=>{var q;const R=Ne.getState(),O=R.getSession(D),F=((q=O.status)==null?void 0:q.lifecycle)==="streaming",$=new Map([...Ir(O.messages.flatMap(Y=>Y.parts??[])),...N]);R.setHistoryMessages(D,Z0(w.messages,$),{preserveInProgressTurn:F});const B=O.optimisticUserMessage;(B===null||B.id===T)&&R.setOptimisticUserMessage(D,null)}).catch(w=>{console.warn("[turn-end-reconcile] history reload failed",{sessionId:D,error:w instanceof Error?w.message:String(w)})}),a.invalidateQueries({queryKey:["tasks",D]}),x.current.get(D)!==!0&&(x.current.set(D,!0),(E=d.current)==null||E.call(d))},[e,S,b,y,t,a])}function tb(e){return e.streamReadyCursor!==null||e.messages.length>0||e.inProgressTurn.length>0||e.optimisticUserMessage!==null}function Vo(e,t){const n=tb(e)?X0(e.messages,e.inProgressTurn,e.pendingInteractions,e.optimisticUserMessage):t;return Vc(n)}function nb(e,t={}){const n=xe(),s=as(),a=oe(K=>K.selectedCwd),o=oe(K=>K.enableMessagePolling),i=oe(K=>K.pendingAccount),l=Qa(),u=e??"",{messages:d,input:f,status:h,error:m,sessionStatus:x,systemStatus:g,operationProgress:S,promptSuggestions:b}=wa(u),y=t0(e,l.cwd);n0(e,t.onSessionIdChangeReplace);const C=kc(u),v=c.useMemo(()=>Vo(y,d),[y,d]),p=Eu(y,h),{streamStartTime:j,estimatedTokens:_,isTextStreaming:D}=r0(e,y.inProgressTurn,p==="streaming");a0(e,y.inProgressTurn,y.streamReadyCursor,t.onTaskEvent);const T=c.useRef(!0);c.useEffect(()=>(T.current=!0,()=>{T.current=!1}),[]);const N=c.useRef(new Map);c.useLayoutEffect(()=>{u&&(N.current.has(u)||N.current.set(u,te.getState().getSession(u).mountGeneration))},[u]);const{setMessages:A,setInput:k,setError:E,setSystemStatus:w,setOperationProgress:R}=Kx(u,T,N);c0(e,y.inProgressTurn,R,w),u&&te.getState().initSession(u),c.useEffect(()=>{e&&(te.getState().initSession(e),te.getState().touchSession(e),N.current.set(e,te.getState().getSession(e).mountGeneration))},[e]),c.useEffect(()=>{if(e)return bt.getState().clearUnseen(e),bt.subscribe(K=>{K.unseen[e]!==void 0&&bt.getState().clearUnseen(e)})},[e]);const{historyQuery:O}=Yx({sessionId:e,sid:u,transport:n,sessionCwd:l,enableMessagePolling:o,isStreaming:p==="streaming",setMessages:A}),F=jx(a,e,{startFreshSession:t.startFreshSession,compact:t.compactIntent}),{handleSubmit:$,submitContent:B,enqueueContent:q,steerContent:Y,addContextContent:se,stop:V,retryMessage:L,submitKickoff:I,markToolCallResponded:P}=Jx({sessionId:e,input:f,status:p,transport:n,queryClient:s,selectedCwd:a,onSessionIdChangeReplace:t.onSessionIdChangeReplace,transformContent:t.transformContent,launchRuntime:t.launchRuntime,agentPath:t.agentPath,agentLookupPending:t.agentLookupPending,agentLookupFailed:t.agentLookupFailed,launchAccount:(i==null?void 0:i.sessionId)===u?i.id:null,takeSeedContext:t.takeSeedContext,setInput:k,setError:E,tryNativeCommand:F.tryRun}),Q=y.streamReadyCursor!==null,ae=c.useCallback((K,le)=>B(K,le?{cwd:le}:void 0),[B]);e0({sessionId:e,cwd:a,status:p,messages:v,hydrated:Q,canStart:!t.agentLookupPending&&!t.agentLookupFailed,submitKickoff:I,submitContent:ae}),eb({sessionId:e,transport:n,sessionCwd:l,streamState:y,queryClient:s,onStreamingDone:t.onStreamingDone});const M=O.isLoading&&v.length===0,W=c.useMemo(()=>v.flatMap(K=>K.toolCalls||[]).filter(K=>K.interactiveType&&K.status==="pending"),[v]),X=W[0]||null,J=X!==null,Z=(X==null?void 0:X.interactiveType)||null;return{messages:v,input:f,setInput:k,handleSubmit:$,submitContent:B,enqueueContent:q,steerContent:Y,addContextContent:se,status:p,error:m,stop:V,retryMessage:L,isLoadingHistory:M,hydrated:Q,sessionStatus:x,streamStartTime:j,estimatedTokens:_,isTextStreaming:D,isWaitingForUser:J,waitingType:Z,activeInteraction:X,pendingInteractions:W,markToolCallResponded:P,systemStatus:g,operationProgress:S,promptSuggestions:b,syncConnectionState:C,tryNativeCommand:F.tryRun,commandPending:F.commandPending}}function sb(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. ${ab(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 rb(e,t){return!Na(e)||e.outcome==="not-running"&&t}function ab(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 ob(){const e=oe(d=>d.showTaskCelebrations),[t,n]=c.useState(null),[s,a]=c.useState(null),o=c.useRef(null),i=c.useRef(!1);c.useEffect(()=>{const d=window.matchMedia("(prefers-reduced-motion: reduce)");i.current=d.matches;const f=h=>{i.current=h.matches};return d.addEventListener("change",f),()=>d.removeEventListener("change",f)},[]),pd({timeoutMs:et.IDLE_TIMEOUT_MS,onIdle:c.useCallback(()=>{var d;(d=o.current)==null||d.setIdle(!0)},[]),onReturn:c.useCallback(()=>{var d,f;(d=o.current)==null||d.setIdle(!1),(f=o.current)==null||f.onUserReturn()},[])}),c.useEffect(()=>{const d=new Ad({enabled:e,miniProbability:et.MINI_PROBABILITY,debounceWindowMs:et.DEBOUNCE_WINDOW_MS,debounceThreshold:et.DEBOUNCE_THRESHOLD,minTasksForMajor:et.MIN_TASKS_FOR_MAJOR,idleTimeoutMs:et.IDLE_TIMEOUT_MS,onCelebrate:f=>{i.current&&f.level==="major"?n({...f,level:"mini"}):n(f),f.level==="mini"&&a(f.taskId)}});return o.current=d,()=>d.destroy()},[e]);const l=c.useCallback((d,f)=>{var h;d.action==="update"&&d.task.status==="completed"&&d.task.id&&((h=o.current)==null||h.onTaskCompleted(d.task.id,f))},[]),u=c.useCallback(()=>{n(null),a(null)},[]);return{handleTaskEvent:l,activeCelebration:t,celebratingTaskId:s,clearCelebration:u}}function Tn(){return{tasks:new Map,statusTimestamps:new Map,legacyCreateCount:0}}function ib(e){const t={};for(const[n,s]of Object.entries(e))s!==void 0&&s!==""&&(t[n]=s);return t}function Fn(e,t,n){switch(t.action){case"snapshot":{e.tasks.clear(),e.statusTimestamps.clear();const s=t.tasks??[t.task];for(const a of s)e.tasks.set(a.id,a),e.statusTimestamps.set(a.id,{status:a.status,since:n});return}case"create":{const s=t.task.id||`legacy:${e.legacyCreateCount++}`,a=s===t.task.id?t.task:{...t.task,id:s};e.tasks.set(s,a),e.statusTimestamps.set(s,{status:a.status,since:n});return}case"id_assigned":{const s=t.previousId;if(!s)return;const a=e.tasks.get(s);if(!a)return;const o=t.task.id;e.tasks.delete(s),e.tasks.set(o,{...a,id:o});const i=e.statusTimestamps.get(s);e.statusTimestamps.delete(s),e.statusTimestamps.set(o,i??{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 s=e.tasks.get(t.task.id);if(!s)return;e.tasks.set(t.task.id,{...s,...ib(t.task)}),t.task.status&&t.task.status!==s.status&&e.statusTimestamps.set(t.task.id,{status:t.task.status,since:n});return}}}function Or(e,t){var n;return(n=e.blockedBy)!=null&&n.length?e.blockedBy.some(s=>{const a=t.get(s);return a&&a.status!=="completed"}):!1}function lb(e,t){return[...e].sort((n,s)=>{const a=n.status==="in_progress"?0:n.status==="pending"&&!Or(n,t)?1:n.status==="pending"?2:3,o=s.status==="in_progress"?0:s.status==="pending"&&!Or(s,t)?1:s.status==="pending"?2:3;return a-o})}const cb=10;let $r=0;function Bt(e){return e==="streaming"||e==="blocked"}function ub(e,t=!1){const n=xe(),a=Qa().cwd,o=oe(N=>N.enableMessagePolling),i=La(),[l,u]=c.useState(Tn()),d=Ea(e??""),[f,h]=c.useState(()=>!Bt(d)),m=c.useRef([]),x=c.useRef(0),{data:g}=Ye({queryKey:["tasks",e,a],queryFn:async()=>{const N=++$r;return{...await n.getTasks(e,a??void 0),fetchOrder:N}},staleTime:3e4,refetchOnWindowFocus:!1,enabled:e!==null,refetchInterval:()=>!o||t?!1:i?Ge.ACTIVE_TAB_REFETCH_MS:Ge.BACKGROUND_TAB_REFETCH_MS}),S=c.useRef(null);c.useEffect(()=>{const N=`${e??""}::${a??""}`,A=S.current!==N;if(S.current=N,A&&(m.current=[],x.current=0,u(Tn())),!g||g.fetchOrder<=x.current)return;x.current=g.fetchOrder;const k=Tn();g.tasks.length>0&&Fn(k,{action:"snapshot",task:g.tasks[0],tasks:g.tasks},Date.now()),m.current=m.current.filter(({order:E})=>E>g.fetchOrder);for(const{event:E,receivedAt:w}of m.current)Fn(k,E,w);u(k)},[g,e,a]);const b=c.useCallback(N=>{const A=Date.now();N.action==="snapshot"&&(m.current=[]),m.current.push({order:++$r,event:N,receivedAt:A}),u(k=>{const E={tasks:new Map(k.tasks),statusTimestamps:new Map(k.statusTimestamps),legacyCreateCount:k.legacyCreateCount};return Fn(E,N,A),E})},[]),y=c.useRef(!1),C=c.useCallback(()=>{h(N=>(y.current=!N,!N))},[]),v=c.useRef(Bt(d));c.useEffect(()=>{const N=Bt(d);N!==v.current&&(v.current=N,N?y.current||h(!1):h(!0))},[d]);const p=c.useRef(null);c.useEffect(()=>{const N=`${e??""}::${a??""}`;if(p.current===N)return;p.current=N;const A=Bt(d);v.current=A,y.current=!1,h(!A)},[e,a,d]);const j=Array.from(l.tasks.values()),_=lb(j,l.tasks),D=j.find(N=>N.status==="in_progress"),T=(D==null?void 0:D.activeForm)??null;return{tasks:_.slice(0,cb),taskMap:l.tasks,activeForm:T,isCollapsed:f,toggleCollapse:C,handleTaskEvent:b,statusTimestamps:l.statusTimestamps}}function db(e){const t=c.useRef(null),[n,s]=c.useState(0),[a,o]=c.useState(!1),[i,l]=c.useState(0),u=c.useCallback(y=>{t.current=y,l(y&&"getOptionCount"in y?y.getOptionCount():0)},[]);c.useEffect(()=>{s(0),l(0),o(!1)},[e==null?void 0:e.toolCallId]);const d=c.useMemo(()=>e!=null&&e.interactiveType?{type:e.interactiveType,toolCallId:e.toolCallId}:null,[e]),f=c.useCallback(()=>{const y=t.current;y&&"approve"in y&&y.approve()},[]),h=c.useCallback(()=>{const y=t.current;y&&"alwaysAllow"in y&&y.alwaysAllow()},[]),m=c.useCallback(()=>{const y=t.current;y&&"deny"in y&&y.deny()},[]),x=c.useCallback(y=>{const C=t.current;C&&"toggleOption"in C&&(C.toggleOption(y),s(y),o(!0))},[]),g=c.useCallback(y=>{if(!a){o(!0);return}s(C=>{const v=t.current,p=v&&"getOptionCount"in v?v.getOptionCount():0;return p===0?C:y==="up"?C<=0?p-1:C-1:C>=p-1?0:C+1})},[a]),S=c.useCallback(y=>{const C=t.current;C&&"navigateQuestion"in C&&(C.navigateQuestion(y),s(0),o(!0),l(C.getOptionCount()))},[]),b=c.useCallback(()=>{const y=t.current;y&&"submit"in y&&y.submit()},[]);return hd({activeInteraction:d,onApprove:f,onAlwaysAllow:h,onDeny:m,onToggleOption:x,onNavigateOption:g,onNavigateQuestion:S,onSubmit:b,optionCount:i,focusedIndex:n}),{handleToolRef:u,focusedOptionIndex:a?n:-1}}function Ut(e,t,n){var o;const s=e.length;if(s===0)return 0;let a=(t%s+s)%s;for(let i=0;i<s;i++){if(!((o=e[a])!=null&&o.disabled))return a;a=(a+n+s)%s}return t}function fb({commands:e,input:t,cursorPos:n}){const[s,a]=c.useState(!1),[o,i]=c.useState(""),[l,u]=c.useState(-1),d=c.useMemo(()=>o?e.map(j=>({cmd:j,rank:cf(o,j)})).filter(j=>j.rank.match).sort((j,_)=>j.rank.bucket-_.rank.bucket||_.rank.score-j.rank.score).map(({cmd:j,rank:_})=>({...j,matchedAlias:_.matchedAlias})):e,[e,o]),[f,h]=c.useState(null),m=f!==null&&f.query===o&&f.open===s?f.index:Ut(d,0,1),x=d[m],g=d.length===0||x!==void 0&&!x.disabled?m:Ut(d,0,1),S=c.useCallback((j,_)=>{const T=j.slice(0,_).match(/(^|\s)\/([\w:-]*)$/);return T?(a(!0),i(T[2]),u((T.index??0)+T[1].length),!0):(a(!1),!1)},[]),b=c.useCallback(j=>{const _=t.slice(0,l),D=t.slice(l+1+o.length);return a(!1),_+j.fullCommand+(D.startsWith(" ")?"":" ")+D},[t,o,l]),y=c.useCallback(()=>{h({query:o,open:s,index:Ut(d,g+1,1)})},[d,g,o,s]),C=c.useCallback(()=>{h({query:o,open:s,index:Ut(d,g-1,-1)})},[d,g,o,s]),v=c.useCallback(()=>{const j=d[g];return j&&!j.disabled?b(j):(j||a(!1),null)},[d,g,b]),p=c.useCallback(()=>{a(!1),i("")},[]);return{showCommands:s,setShowCommands:a,commandQuery:o,selectedIndex:g,filteredCommands:d,slashTriggerPos:l,detectCommandTrigger:S,handleCommandSelect:b,handleArrowUp:C,handleArrowDown:y,handleKeyboardSelect:v,resetCommand:p}}function mb({fileEntries:e,input:t,cursorPos:n}){const[s,a]=c.useState(!1),[o,i]=c.useState(""),[l,u]=c.useState(0),[d,f]=c.useState(-1),h=c.useMemo(()=>s?o?e.map(C=>({...C,...Ht(o,C.path)})).filter(C=>C.match).sort((C,v)=>v.score-C.score).slice(0,50):e.slice(0,50).map(C=>({...C,indices:[]})):[],[e,o,s]);c.useEffect(()=>{u(0)},[o,s]),c.useEffect(()=>{h.length>0&&l>=h.length&&u(h.length-1)},[h.length,l]);const m=c.useCallback((C,v)=>{const j=C.slice(0,v).match(/(^|\s)@([\w./:-]*)$/);return j?(a(!0),i(j[2]),f((j.index??0)+j[1].length),!0):(a(!1),!1)},[]),x=c.useCallback(C=>{const v=t.slice(0,d),p=t.slice(d+1+o.length);if(C.isDirectory){const _=v+"@"+C.path+p,D=v.length+1+C.path.length;return i(C.path),u(0),{newValue:_,newCursorPos:D,keepOpen:!0}}const j=v+"@"+C.path+" "+p;return a(!1),{newValue:j,keepOpen:!1}},[t,d,o]),g=c.useCallback(()=>{u(C=>h.length===0?0:(C+1)%h.length)},[h.length]),S=c.useCallback(()=>{u(C=>h.length===0?0:(C-1+h.length)%h.length)},[h.length]),b=c.useCallback(()=>h.length>0&&l<h.length?x(h[l]):(a(!1),null),[h,l,x]),y=c.useCallback(()=>{a(!1),i("")},[]);return{showFiles:s,setShowFiles:a,fileQuery:o,fileSelectedIndex:l,filteredFiles:h,fileTriggerPos:d,detectFileTrigger:m,handleFileSelect:x,handleArrowUp:S,handleArrowDown:g,handleKeyboardSelect:b,resetFiles:y}}function pb({input:e,setInput:t,commands:n,fileEntries:s}){const[a,o]=c.useState(0),i=fb({commands:n,input:e,cursorPos:a}),l=mb({fileEntries:s,input:e,cursorPos:a}),u=c.useCallback((_,D)=>{if(l.detectFileTrigger(_,D)){i.setShowCommands(!1);return}if(i.detectCommandTrigger(_,D)){l.setShowFiles(!1);return}l.setShowFiles(!1),i.setShowCommands(!1)},[l,i]),d=c.useRef({value:e,cursor:0});c.useEffect(()=>{d.current.value=e},[e]);const f=c.useCallback(_=>{t(_),d.current={value:_,cursor:d.current.cursor||_.length},u(_,d.current.cursor)},[t,u]),h=c.useCallback(_=>{o(_),d.current={value:d.current.value,cursor:_},u(d.current.value,_)},[u]),m=c.useCallback(_=>{const D=i.handleCommandSelect(_);t(D)},[i,t]),x=c.useCallback(_=>{const D=l.handleFileSelect(_);t(D.newValue),D.newCursorPos!==void 0&&o(D.newCursorPos)},[l,t]),g=c.useCallback(()=>{l.showFiles?l.handleArrowDown():i.handleArrowDown()},[l,i]),S=c.useCallback(()=>{l.showFiles?l.handleArrowUp():i.handleArrowUp()},[l,i]),b=c.useCallback(()=>{if(l.showFiles){const _=l.handleKeyboardSelect();_&&(t(_.newValue),_.newCursorPos!==void 0&&o(_.newCursorPos))}else if(i.showCommands){const _=i.handleKeyboardSelect();_&&t(_)}},[l,i,t]),y=c.useCallback(()=>{i.setShowCommands(!1),l.setShowFiles(!1)},[i,l]),C=i.showCommands||l.showFiles,v=l.showFiles&&l.filteredFiles.length>0||i.showCommands&&i.filteredCommands.length>0,p=l.showFiles?"file-palette-listbox":i.showCommands?"command-palette-listbox":void 0,j=l.showFiles&&l.filteredFiles.length>0?`file-item-${l.fileSelectedIndex}`:i.showCommands&&i.filteredCommands.length>0?`command-item-${i.selectedIndex}`:void 0;return{commands:{show:i.showCommands,filtered:i.filteredCommands,selectedIndex:i.selectedIndex},files:{show:l.showFiles,filtered:l.filteredFiles,selectedIndex:l.fileSelectedIndex},isPaletteOpen:C,paletteHasResults:v,activeDescendantId:j,paletteListboxId:p,handleInputChange:f,handleCursorChange:h,handleArrowUp:S,handleArrowDown:g,handleKeyboardSelect:b,handleCommandSelect:m,handleFileSelect:x,dismissPalettes:y}}function hb(e,t,n){const s=oe(i=>i.setIsStreaming),a=oe(i=>i.setIsWaitingForUser),o=oe(i=>i.setIsTextStreaming);c.useEffect(()=>(s(e==="streaming"),()=>s(!1)),[e,s]),c.useEffect(()=>(a(t),()=>a(!1)),[t,a]),c.useEffect(()=>(o(n),()=>o(!1)),[n,o])}function gb(){const e=xe(),t=oe(m=>m.selectedCwd),[n,s]=c.useState([]),a=c.useCallback(m=>{const x=m.map(g=>({id:crypto.randomUUID(),file:g,status:"pending",progress:0}));s(g=>[...g,...x])},[]),o=c.useCallback(m=>{s(x=>x.filter(g=>g.id!==m))},[]),i=c.useCallback(()=>{s([])},[]),l=c.useCallback(m=>{s(x=>x.map(g=>g.id===m&&g.status==="error"?{...g,status:"pending",progress:0,error:void 0}:g))},[]),u=c.useRef(null),d=kt({meta:{suppressErrorToast:!0},mutationFn:async m=>{if(!t)throw new Error("No working directory selected");s(b=>b.map(y=>m.some(C=>C.id===y.id)?{...y,status:"uploading"}:y));const x=b=>{s(y=>y.map(C=>C.status==="uploading"?{...C,progress:b.percentage}:C))},g=new AbortController;u.current=g;const S=m.map(b=>b.file);return e.uploadFiles(S,t,x,g.signal)},onSettled:()=>{u.current=null},onSuccess:(m,x)=>{s(g=>g.map(S=>{const b=x.findIndex(y=>y.id===S.id);return b===-1?S:{...S,status:"uploaded",progress:100,result:m[b]}}))},onError:m=>{s(x=>x.map(g=>g.status==="uploading"?{...g,status:"error",error:m.message}:g))}}),f=c.useCallback(()=>{var m;(m=u.current)==null||m.abort()},[]),h=c.useCallback(async()=>{const m=n.filter(b=>b.status==="error");if(m.length>0)throw new Error(m.length===1?`${m[0].file.name} did not upload. Retry it or remove it, then send again.`:`${m.length} attachments did not upload. Retry them or remove them, then send again.`);const x=n.filter(b=>b.status==="uploaded"&&b.result).map(b=>b.result.savedPath),g=n.filter(b=>b.status==="pending");if(g.length===0)return x;const S=await d.mutateAsync(g);return[...x,...S.map(b=>b.savedPath)]},[n,d]);return{pendingFiles:n,addFiles:a,removeFile:o,retryFile:l,clearFiles:i,cancelUpload:f,uploadAndGetPaths:h,hasPendingFiles:n.length>0,hasFailedUpload:n.some(m=>m.status==="error"),isUploading:d.isPending}}const Rn=new Set,Mn=new Set;function xb(e,t){return`${e}\0${t}`}function bb({sessionId:e,prompt:t,autoSend:n,input:s,setInput:a,messageCount:o,hydrated:i,status:l,submitBlocked:u=!1,submit:d,onSeeded:f,onConsumed:h}){const m=t!=null&&t.trim()?t:void 0,x=e&&m?xb(e,m):null;c.useEffect(()=>{if(!(!x||!m)&&!Rn.has(x)&&i){if(Rn.add(x),s.length>0||o>0){Mn.add(x),h==null||h();return}a(m),f==null||f(),n||h==null||h()}},[x,m,n,s,i,o,a,f,h]),c.useEffect(()=>{!x||!m||!n||Mn.has(x)||Rn.has(x)&&s===m&&(!i||o>0||l==="streaming"||u||(Mn.add(x),h==null||h(),d()))},[x,m,n,s,i,o,l,u,d,h])}const Pr=Cc-256,Lr=`
56
+ `),toolCalls:n}}function yt(e){const t=e.parts?[...e.parts]:[];if(t.length===0&&(e.content&&t.push({type:"text",text:e.content}),e.toolCalls))for(const s of e.toolCalls)t.push({type:"tool_call",toolCallId:s.toolCallId,toolName:s.toolName,input:s.input,result:s.result,status:s.status,...s.questions||s.questionOutcome?{interactiveType:"question",questions:s.questions,answers:s.answers,questionOutcome:s.questionOutcome}:{},...s.approvalOutcome?{interactiveType:"approval",approvalOutcome:s.approvalOutcome,approvalResolvedAt:s.approvalResolvedAt,approvalStartedAt:s.approvalStartedAt,approvalReasonGiven:s.approvalReasonGiven}:{}});const n=bs(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}:{},...e.roomMessage?{roomMessage:e.roomMessage}:{}}}function Qx(e,t,n){const s=new Set(e.map(d=>d.id)),a=e.filter(d=>d._streaming),o=a.find(d=>d.role==="user"),i=a.find(d=>d.role==="assistant"),l=[];let u=-1;for(let d=0;d<t.length;d++){const f=t[d];if(!s.has(f.id)){if(o&&f.role==="user"&&f.content===o.content){u=d,n(h=>h.map(m=>m.id===o.id?{...yt(f),_streaming:!1}:m));continue}if(i&&u>=0&&d===u+1&&f.role==="assistant"){const h=yt(f),m=new Set(h.parts.filter(S=>S.type==="background_task").map(S=>S.taskId)),x=i.parts.filter(S=>S.type==="background_task"&&!m.has(S.taskId)),g=x.length>0?[...h.parts,...x]:h.parts;n(S=>S.map(b=>b.id===i.id?{...h,parts:g,_streaming:!1}:b));continue}l.push(f)}}l.length>0&&n(d=>[...d,...l.map(yt)])}function Yx({sessionId:e,sid:t,transport:n,sessionCwd:s,enableMessagePolling:a,isStreaming:o,setMessages:i}){const l=La(),u=s.cwd,d=c.useRef(u);c.useEffect(()=>{d.current=u},[u]);const f=Ye({queryKey:["messages",e,u],queryFn:()=>n.getMessages(e,u??void 0),staleTime:Ge.MESSAGE_STALE_TIME_MS,refetchOnWindowFocus:!1,enabled:e!==null,refetchInterval:()=>o||!a?!1:l?Ge.ACTIVE_TAB_REFETCH_MS:Ge.BACKGROUND_TAB_REFETCH_MS});return c.useEffect(()=>{const h=te.getState();t&&h.updateSession(t,{historySeeded:!1}),h.getSession(e??"").status!=="streaming"&&i([])},[e,u,t,i]),c.useEffect(()=>{if(!f.data)return;const h=f.data.messages,m=te.getState().getSession(t).historySeeded;if(!m&&h.length>0){if(o)return;t&&te.getState().updateSession(t,{historySeeded:!0}),i(h.map(yt));return}m&&!o&&Qx(te.getState().getSession(t).messages,h,i)},[f.data,o,t,i]),{historyQuery:f}}function Bo(e,t){if(e===t)return;const{opened:n,counts:s,mergeUsage:a}=at.getState(),o=zs("session",e),i=Date.parse(n[o]??"");Number.isNaN(i)||a([{key:zs("session",t),lastUsedAt:i,useCount:s[o]??1}])}function Xn(e,t,n){e&&n.then(s=>{if(!s)return;const a=te.getState();a.getSession(e).input.trim()===t.trim()&&a.updateSession(e,{input:""})},()=>{})}const Pt=new Map;function Xx(e,t){const s=(Pt.get(e)??Promise.resolve()).then(t),a=s.then(()=>{},()=>{});return Pt.set(e,a),a.then(()=>{Pt.get(e)===a&&Pt.delete(e)}),s}const nt=new Set;function Tr(e){var a;const t=e,n=typeof(t==null?void 0:t.code)=="string"?t.code:void 0,s=(a=t==null?void 0:t.body)==null?void 0:a.agentId;return{...n?{code:n}:{},...typeof s=="string"?{agentId:s}:{}}}function Jx({sessionId:e,input:t,status:n,transport:s,queryClient:a,selectedCwd:o,onSessionIdChangeReplace:i,transformContent:l,launchRuntime:u,agentPath:d,agentLookupPending:f,agentLookupFailed:h,launchAccount:m,takeSeedContext:x,setInput:g,setError:S,tryNativeCommand:b}){const y=c.useRef(o);c.useEffect(()=>{y.current=o},[o]);const C=c.useRef(u);c.useEffect(()=>{C.current=u},[u]);const v=c.useRef(m);c.useEffect(()=>{v.current=m},[m]);const{data:p}=is(),j=c.useRef(p==null?void 0:p.defaultRuntime);c.useEffect(()=>{j.current=p==null?void 0:p.defaultRuntime},[p==null?void 0:p.defaultRuntime]);const _=Nu(e,u),D=c.useRef(_.mode);c.useEffect(()=>{D.current=_.mode},[_.mode]);const T=c.useRef(l);c.useEffect(()=>{T.current=l});const N=c.useRef(x);c.useEffect(()=>{N.current=x});const A=c.useRef(i);c.useEffect(()=>{A.current=i});const k=c.useCallback(async(V,L,I={})=>{var le,fe,me;if(!I.kickoff){const z=b(V);if(z.handled){L&&z.ran&&(z.confirmed?Xn(e,V,z.confirmed):g(""));return}}const P=e,Q=I.cwd??y.current;S(null);const ae=a.getQueryData(We.list(Q))??[],M=pn(P),W=(M==null?void 0:M.draft)??!ae.some(z=>z.id===P),X=(M==null?void 0:M.draft)===!1?!1:W||nt.has(P);if(X&&(f||h))return;X&&nt.add(P),I.kickoff||(at.getState().recordOpened("session",P),Q&&at.getState().recordOpened("agent",Q)),xt.attachSession(P,Q);let J;try{J=!I.kickoff&&T.current?await T.current(V):V}catch(z){if(I.kickoff)throw z;S({heading:"Couldn’t send message",message:z.message||"The attachment didn’t upload. Try again.",retryable:!1});return}const Z=Ne.getState();if(W){const z=new Date().toISOString();Bs(a,Q,{id:P,title:`Chat ${P.slice(0,8)}`,createdAt:z,updatedAt:z,permissionMode:((le=a.getQueryData(We.detail(P,Q)))==null?void 0:le.permissionMode)??D.current??"default",runtime:C.current??j.current??"claude-code"})}const K=crypto.randomUUID();I.kickoff||Z.setOptimisticUserMessage(P,{id:K,content:V}),Z.setTriggerPending(P,!0),L&&g("");try{const z=qs(oe.getState(),Q??null),{uiState:he,commit:ce}=Us(P,z),ke={clientMessageId:K,context:he?{uiState:he}:void 0};X&&(ke.create=!0),X&&C.current&&(ke.runtime=C.current),X&&d&&(ke.agentPath=d),X&&v.current&&(ke.account=v.current);const De=oe.getState().retryAccount;(De==null?void 0:De.sessionId)===P&&(ke.account=De.id,oe.getState().setRetryAccount(null));const Me=(fe=N.current)==null?void 0:fe.call(N);Me&&(ke.seedContext=Me);const{sessionId:de}=await s.postMessage(P,J,Q??void 0,ke);if(nt.delete(P),M){const ye={...M,draft:!1};hn(P,ye),hn(de,ye)}if(ce(de),de!==P){Ne.getState().migrateSessionContinuity(P,de),oe.getState().carryCanvasWritesAcross(P,de),xt.attachSession(de,Q),Bo(P,de),st.getState().migrate(P,de);const ye=a.getQueryData(We.list(Q))??[],_e=ye.find(be=>be.id===P);_e&&!ye.some(be=>be.id===de)&&Bs(a,Q,{..._e,id:de}),a.setQueryData(We.list(Q),be=>be==null?void 0:be.filter(Ie=>Ie.id!==P))}(me=A.current)==null||me.call(A,de);const Oe=de;setTimeout(()=>{var be;const ye=bt.getState().rekeys[Oe]??Oe,_e=Ne.getState().getSession(ye);_e.triggerPending&&((be=_e.status)==null?void 0:be.lifecycle)!=="streaming"&&Ne.getState().setTriggerPending(ye,!1)},Jt.TRIGGER_PENDING_TIMEOUT_MS)}catch(z){if(Ne.getState().setOptimisticUserMessage(P,null),Ne.getState().setTriggerPending(P,!1),I.kickoff)throw z;S({heading:"Couldn’t send message",message:z.message||"Couldn’t reach DorkOS. Try again.",retryable:!0,...Tr(z)})}},[e,s,a,g,S,b,d,f,h]),E=c.useCallback(async(V,L)=>{!V.trim()||n==="streaming"||await k(V.trim(),(L==null?void 0:L.clearInput)===!0,{...L!=null&&L.cwd?{cwd:L.cwd}:{}})},[n,k]),w=c.useCallback(()=>E(t,{clearInput:!0}),[t,E]),R=c.useCallback(async(V,L,I)=>{if(!e)return!1;const P=e,Q=y.current;S(null);const ae=(a.getQueryData(We.list(Q))??[]).some(W=>W.id===P),M=pn(P);return((M==null?void 0:M.draft)??!ae)&&nt.add(P),Xx(P,async()=>{var X;let W;try{W=T.current?await T.current(V):V}catch(J){return S({heading:I,message:J.message||"The attachment didn’t upload. Try again.",retryable:!1}),!1}try{const J=qs(oe.getState(),Q??null),{uiState:Z,commit:K}=Us(P,J),le={...Z?{uiState:Z}:{},...L==="queue"?{queued:!0}:{}},fe=Object.keys(le).length>0?le:void 0,me=((X=pn(P))==null?void 0:X.draft)===!1?!1:nt.has(P);if(me&&(f||h))return!1;const{sessionId:z}=await s.postMessage(P,W,Q??void 0,{context:fe,disposition:L,...me?{create:!0,...C.current&&{runtime:C.current},...v.current&&{account:v.current},...d&&{agentPath:d}}:{}});return me&&nt.delete(P),M&&hn(z,{...M,draft:!1}),K(z),!0}catch(J){return S({heading:I,message:J.message||"Couldn’t reach DorkOS. Try again.",retryable:!1,...Tr(J)}),!1}})},[e,s,a,S,d,f,h]),O=c.useCallback(V=>R(V,"queue","Couldn’t queue message"),[R]),F=c.useCallback(V=>R(V,"steer","Couldn’t steer the agent"),[R]),$=c.useCallback(V=>R(V,"stage","Couldn’t add context"),[R]),B=c.useCallback(async()=>{if(!e)return{receipt:{outcome:"not-running",reason:"no-open-turn",runtime:"unknown"},cancelled:[]};try{const{receipt:V,cancelledQueued:L}=await s.interruptSession(e);return{receipt:V,cancelled:L??[]}}catch{return{receipt:{outcome:"failed",reason:"delivery-failed",runtime:"unknown"},cancelled:[]}}},[e,s]),U=c.useCallback(async V=>{S(null),await k(V,!1)},[k,S]),Y=c.useCallback(async(V,L)=>{await k(V,!1,{kickoff:!0,...L?{cwd:L}:{}})},[k]),se=c.useCallback((V,L)=>{},[]);return{handleSubmit:w,submitContent:E,enqueueContent:O,steerContent:F,addContextContent:$,stop:B,retryMessage:U,submitKickoff:Y,markToolCallResponded:se}}const Lt=new Set,Fr=new Set,zt=new Set;function Zx(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 e0({sessionId:e,cwd:t,status:n,messages:s,hydrated:a,canStart:o=!0,submitKickoff:i,submitContent:l}){const u=Xt(e),d=s.length,f=s.some(Zx);c.useEffect(()=>{if(!e)return;if(!u){t&&d===0&&n==="idle"&&st.getState().claimByPath(t,e);return}if(u.fired||Lt.has(e)||!o||d>0||n!=="idle")return;Lt.add(e),st.getState().markFired(e);const h=u.kind==="first-message";(h?l:i)(u.kickoffMessage,u.path||void 0).catch(x=>{console.warn("[chat] first-turn trigger failed for newborn session",e,x),Fr.has(e)?h||st.getState().markGreetingFailed(e):(Fr.add(e),Lt.delete(e),st.getState().resetFired(e))})},[e,t,u,n,d,o,i,l]),c.useEffect(()=>{if(!(!e||!u)&&u.kind!=="first-message"&&!(!u.fired&&!Lt.has(e))&&!u.greetingFailed){if(f){zt.delete(e);return}if(n==="streaming"){zt.add(e);return}a&&zt.has(e)&&(zt.delete(e),st.getState().markGreetingFailed(e))}},[e,u,n,f,a])}function t0(e,t){return c.useEffect(()=>{bc(),xt.connectList(),e&&xt.attachSession(e,t)},[e,t]),c.useEffect(()=>()=>xt.releaseSession(),[]),ja(e??"")}function n0(e,t){const n=_a(e),s=c.useRef(t);c.useEffect(()=>{s.current=t}),c.useEffect(()=>{var a;!n||!e||(Bo(e,n),(a=s.current)==null||a.call(s,n))},[n,e])}const s0=500;function r0(e,t,n){const s=c.useRef(new Map),[a,o]=c.useState(null),i=t.length>0?t[0].seq:-1;c.useEffect(()=>{const h=s.current;if(!e||!n){e&&h.delete(e),o(null);return}let m=h.get(e);(!m||m.turnSeq!==i)&&(m={turnSeq:i,anchor:Date.now()},h.set(e,m)),o(m.anchor)},[e,n,i]);const l=c.useMemo(()=>{let h=0;for(const m of t)m.type==="text_delta"&&(h+=m.text.length);return h/4},[t]),[u,d]=c.useState(!1),f=c.useRef({sid:null,tokens:0});return c.useEffect(()=>{const h=f.current,m=e===h.sid&&l>h.tokens;if(f.current={sid:e,tokens:l},m&&!u&&d(!0),!m&&!u)return;const x=setTimeout(()=>d(!1),s0);return()=>clearTimeout(x)},[e,l,u]),{streamStartTime:a,estimatedTokens:l,isTextStreaming:u}}function a0(e,t,n,s){const a=c.useRef(new Map),o=c.useRef(s);c.useEffect(()=>{o.current=s}),c.useEffect(()=>{var d;if(!e)return;const i=a.current,l=n??0;let u=i.get(e);(!u||u.floor!==l)&&(u={floor:l,seen:l},i.set(e,u));for(const f of t)f.seq<=u.seen||(f.type==="todo_update"&&((d=o.current)==null||d.call(o,{action:f.action,task:f.task,tasks:f.tasks,previousId:f.previousId})),u.seen=f.seq)},[e,t,n])}function o0(e){let t=null,n=null;for(const s of e){if(s.type==="operation_progress"){t=s.state==="started"?{operation:s.operation,determinate:s.determinate,...s.percent!==void 0?{percent:s.percent}:{},...s.message!==void 0?{message:s.message}:{}}:null;continue}if(s.type==="system_status"){s.status||(n={message:s.message});continue}n=null}return{operationProgress:t,systemStatus:n}}function i0(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 l0(e,t){return((e==null?void 0:e.message)??null)===((t==null?void 0:t.message)??null)}function c0(e,t,n,s){const a=c.useRef(new Map),o=c.useRef(new Map),i=c.useRef(n),l=c.useRef(s);c.useEffect(()=>{i.current=n,l.current=s}),c.useEffect(()=>{if(!e)return;const{operationProgress:u,systemStatus:d}=o0(t),f=a.current.get(e)??null;i0(f,u)||(i.current(u),a.current.set(e,u));const h=o.current.get(e)??null;l0(h,d)||(l.current(d),o.current.set(e,d))},[e,t])}function u0(e,t){for(let n=e.length-1;n>=0;n--){const s=e[n];if(s.type==="capability_approval"&&s.approval.approvalId===t)return s}}function d0(e,t){const n=u0(e,t.approval.approvalId);n?n.approval=t.approval:e.push({type:"capability_approval",approval:t.approval})}function f0(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 s=e[n];s.outcome="timeout"}function m0(e,t,n){return e.findIndex(s=>s.type==="mcp_signin"&&s.agentId===t&&s.serverName===n&&s.outcome===void 0)}function p0(e,t){const n={type:"mcp_signin",serverName:t.serverName,agentId:t.agentId,flowId:t.flowId,authorizeUrl:t.authorizeUrl,disclosure:t.disclosure},s=m0(e,t.agentId,t.serverName);s===-1?e.push(n):e[s]=n}function h0(e,t){const n=e.findIndex(a=>a.type==="mcp_signin"&&a.flowId===t.flowId);if(n===-1)return;const s=e[n];s.outcome=t.outcome,t.toolCount!==void 0&&(s.toolCount=t.toolCount)}const Rr="__in_progress_turn__",g0="__optimistic_user__";function x0(e){return{id:g0,role:"user",content:e,parts:[{type:"text",text:e}],timestamp:"",_streaming:!0}}function b0(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 y0(e){return{id:`staged-${e.messageId}`,role:"user",content:e.content,parts:[{type:"text",text:e.content}],timestamp:"",_streaming:!0,_stagedContext:!0}}function Re(e,t){for(let n=e.length-1;n>=0;n--){const s=e[n];if(s.type==="tool_call"&&s.toolCallId===t)return s}}function on(e,t){for(let n=e.length-1;n>=0;n--){const s=e[n];if(s.type==="elicitation"&&s.interactionId===t)return s}}function v0(e,t){for(let n=e.length-1;n>=0;n--){const s=e[n];if(s.type==="background_task"&&s.taskId===t)return s}}function k0(e,t){qo(e);const n=e[e.length-1];n&&n.type==="text"?n.text+=t.text:e.push({type:"text",text:t.text})}function C0(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 qo(e){for(const t of e)t.type==="thinking"&&t.isStreaming&&(t.isStreaming=!1)}function S0(e,t,n){const s=Re(e,t.toolCallId);if(s){t.input!==void 0&&(s.input=(s.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 j0(e,t){const n=Re(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 _0(e,t){const n=Re(e,t.toolCallId);n&&(n.progressOutput=(n.progressOutput??"")+t.content)}function Uo(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},s=Re(e,t.id);s?Object.assign(s,n):e.push({type:"tool_call",toolCallId:t.id,toolName:t.toolName,...n})}function Ho(e,t){const n=Re(e,t.id),s={timeoutMs:t.timeoutMs,approvalStartedAt:t.startedAt,approvalRemainingMs:t.remainingMs};n?(n.interactiveType="question",n.questions=t.questions,n.status="pending",Object.assign(n,s)):e.push({type:"tool_call",toolCallId:t.id,toolName:"AskUserQuestion",input:"",status:"pending",interactiveType:"question",questions:t.questions,...s})}function Wo(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},s=on(e,t.id);s?Object.assign(s,n):e.push({type:"elicitation",interactionId:t.id,...n})}function w0(e){return e==="denied"||e==="expired"||e==="cancelled"?"error":e==="answered"?"complete":"running"}function N0(e,t){const n=Re(e,t.id);if(n){n.status==="pending"&&(n.status=w0(t.resolution),n.approvalRemainingMs=void 0);const a=yc(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=vc(t);o&&(n.questionOutcome=o)}const s=on(e,t.id);s&&s.status==="pending"&&(s.status="submitted",s.remainingMs=void 0)}function E0(e,t){for(let n=e.length-1;n>=0;n--){const s=e[n];if(s.type==="tool_call"&&s.hooks){const a=s.hooks.find(o=>o.hookId===t);if(a)return a}}}function D0(e,t){for(const n of e.values()){const s=n.find(a=>a.hookId===t);if(s)return s}}function A0(e,t,n){const s=E0(e,t.hookId)??D0(n,t.hookId);if(s){s.status=t.status,t.hookName!==void 0&&(s.hookName=t.hookName),t.stdout!==void 0&&(s.stdout=t.stdout),t.stderr!==void 0&&(s.stderr=t.stderr),t.exitCode!==void 0&&(s.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=Re(e,t.toolCallId);o?o.hooks=[...o.hooks??[],a]:n.set(t.toolCallId,[...n.get(t.toolCallId)??[],a])}function T0(e,t){const n=e[0];if(n&&n.type==="memory_recall"){const o=new Set(n.memories.map(l=>l.path)),i=t.memories.filter(l=>!o.has(l.path));i.length>0&&(n.memories=[...n.memories,...i]);return}const s=new Set,a=t.memories.filter(o=>s.has(o.path)?!1:(s.add(o.path),!0));e.unshift({type:"memory_recall",mode:t.mode,memories:a,isStreaming:!0})}function F0(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 R0(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 M0(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 I0(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 O0(e,t){qo(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 $0(e,t){const n=v0(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 P0={approval:"approval_required",question:"question_prompt",elicitation:"elicitation_prompt"};function L0(e){const{type:t,...n}=e;return{...n,seq:0,type:P0[t]}}function z0(e,t){const n=Re(e,t);return(n==null?void 0:n.interactiveType)!==void 0?!0:on(e,t)!==void 0}function B0(e,t){switch(t.type){case"approval_required":Uo(e,t);break;case"question_prompt":Ho(e,t);break;case"elicitation_prompt":Wo(e,t);break}}function q0(e,t,n){const s=Re(e,t.id);if(s){!n&&s.result===void 0&&(s.status="pending"),s.approvalStartedAt=t.startedAt,s.approvalRemainingMs=t.remainingMs,t.timeoutMs!==void 0&&(s.timeoutMs=t.timeoutMs),s.approvalParked=t.parked===!0?!0:void 0;return}const a=on(e,t.id);a&&(a.startedAt=t.startedAt,a.remainingMs=t.remainingMs,t.timeoutMs!==void 0&&(a.timeoutMs=t.timeoutMs))}function U0(e,t,n){for(const s of t){if(z0(e,s.id)){q0(e,s,n.has(s.id));continue}B0(e,L0(s)),H0(e,s)}}function H0(e,t){if(t.parked!==!0)return;const n=Re(e,t.id);n&&(n.approvalParked=!0)}function W0(e){const t=new Set;for(const n of e)n.type==="interaction_resolved"&&t.add(n.id);return t}function Jn(e){const t=[],n=new Map;for(const s of e)switch(s.type){case"text_delta":k0(t,s);break;case"thinking_delta":C0(t,s);break;case"tool_call":S0(t,s,n);break;case"tool_result":j0(t,s);break;case"tool_progress":_0(t,s);break;case"approval_required":Uo(t,s);break;case"question_prompt":Ho(t,s);break;case"elicitation_prompt":Wo(t,s);break;case"capability_approval_required":d0(t,s);break;case"capability_approval_resolved":f0(t,s);break;case"mcp_signin_required":p0(t,s);break;case"mcp_signin_resolved":h0(t,s);break;case"interaction_resolved":N0(t,s);break;case"subagent_update":$0(t,s);break;case"hook_update":A0(t,s,n);break;case"memory_recall":T0(t,s);break;case"image_attachment":F0(t,s);break;case"compact_boundary":R0(t,s);break;case"permission_denied":M0(t,s);break;case"model_substituted":t.push({type:"model_substituted",from:s.from,fromName:s.fromName,to:s.to,toName:s.toName,reason:s.reason});break;case"operation_progress":I0(t,s);break;case"error":O0(t,s);break}return t}function Mr(e,t){if(e.length===0)return null;const n=bs(e);return{id:t,role:"assistant",content:n.content,toolCalls:n.toolCalls.length>0?n.toolCalls:[],parts:e,timestamp:"",_streaming:!0}}function V0(e,t){const n=[];let s=[],a=0;for(const l of e){if(l.type!=="turn_input"&&l.type!=="context_staged"){s.push(l);continue}const u=Jn(s),d=Mr(u,`${Rr}-${a}`);d&&n.push(d),a+=1,n.push(l.type==="turn_input"?b0(l):y0(l)),s=[]}const o=Jn(s);U0(o,t,W0(e));const i=Mr(o,Rr);return i&&n.push(i),n}function G0(e){const t=new Set;for(const n of e)for(const s of n.parts)s.type==="tool_call"&&t.add(s.toolCallId);return t}function K0(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 Q0(e,t){const n=e.parts.filter(a=>a.type!=="tool_call"||!t.has(a.toolCallId)||!K0(a));if(n.length===e.parts.length)return e;if(n.length===0)return null;const s=bs(n);return{...e,parts:n,content:s.content,toolCalls:s.toolCalls.length>0?s.toolCalls:void 0}}function Y0(e){let t=e.length;for(;t>0&&e[t-1].role==="assistant";)t-=1;return t}function X0(e,t,n=[],s=null){const a=V0(t,n),o=G0(a),i=e.map(yt),l=o.size===0?i.length:Y0(i),u=[];for(const[d,f]of i.entries()){const h=d<l?f:Q0(f,o);h&&u.push(h)}return s&&u.push(x0(s.content)),u.push(...a),u}function Ir(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 J0(e,t){return e.interactiveType==="approval"&&e.approvalOutcome===t.outcome&&e.approvalResolvedAt===t.resolvedAt&&e.approvalStartedAt===t.startedAt&&e.approvalReasonGiven===t.reasonGiven}function Z0(e,t){return t.size===0?e:e.map(n=>{if(!n.parts)return n;let s=!1;const a=n.parts.map(o=>{if(o.type!=="tool_call")return o;const i=t.get(o.toolCallId);return!i||J0(o,i)?o:(s=!0,{...o,interactiveType:"approval",approvalOutcome:i.outcome,approvalResolvedAt:i.resolvedAt,approvalStartedAt:i.startedAt,approvalReasonGiven:i.reasonGiven,...i.displayName!==void 0?{approvalDisplayName:i.displayName}:{}})});return s?{...n,parts:a}:n})}function eb({sessionId:e,transport:t,sessionCwd:n,streamState:s,queryClient:a,onStreamingDone:o}){var C;const i=n.cwd,l=c.useRef(e),u=c.useRef(i),d=c.useRef(o);c.useEffect(()=>{l.current=e,u.current=i,d.current=o});const f=c.useRef(new Map),h=c.useRef(new Map),m=c.useRef(new Map),x=c.useRef(new Map),g=c.useRef(new Map),S=((C=s.status)==null?void 0:C.lifecycle)??null,b=s.hydrationGeneration,y=s.userTurnCount;c.useEffect(()=>{var A,k,E;if(!e)return;const v=g.current.get(e);g.current.set(e,y),v!==void 0&&y!==v&&x.current.set(e,!1);const p=h.current.get(e);if(h.current.set(e,b),p!==b){f.current.set(e,S),S==="streaming"&&m.current.set(e,((A=Ne.getState().getSession(e).optimisticUserMessage)==null?void 0:A.id)??null);return}const j=f.current.get(e)??null;if(f.current.set(e,S),S==="streaming"&&j!=="streaming"&&m.current.set(e,((k=Ne.getState().getSession(e).optimisticUserMessage)==null?void 0:k.id)??null),!(j==="streaming"&&S!=="streaming"&&S!==null))return;const D=e,T=m.current.get(D)??null,N=Ir(Jn(Ne.getState().getSession(D).inProgressTurn));t.getMessages(D,u.current??void 0).then(w=>{var U;const R=Ne.getState(),O=R.getSession(D),F=((U=O.status)==null?void 0:U.lifecycle)==="streaming",$=new Map([...Ir(O.messages.flatMap(Y=>Y.parts??[])),...N]);R.setHistoryMessages(D,Z0(w.messages,$),{preserveInProgressTurn:F});const B=O.optimisticUserMessage;(B===null||B.id===T)&&R.setOptimisticUserMessage(D,null)}).catch(w=>{console.warn("[turn-end-reconcile] history reload failed",{sessionId:D,error:w instanceof Error?w.message:String(w)})}),a.invalidateQueries({queryKey:["tasks",D]}),x.current.get(D)!==!0&&(x.current.set(D,!0),(E=d.current)==null||E.call(d))},[e,S,b,y,t,a])}function tb(e){return e.streamReadyCursor!==null||e.messages.length>0||e.inProgressTurn.length>0||e.optimisticUserMessage!==null}function Vo(e,t){const n=tb(e)?X0(e.messages,e.inProgressTurn,e.pendingInteractions,e.optimisticUserMessage):t;return Vc(n)}function nb(e,t={}){const n=xe(),s=as(),a=oe(K=>K.selectedCwd),o=oe(K=>K.enableMessagePolling),i=oe(K=>K.pendingAccount),l=Qa(),u=e??"",{messages:d,input:f,status:h,error:m,sessionStatus:x,systemStatus:g,operationProgress:S,promptSuggestions:b}=wa(u),y=t0(e,l.cwd);n0(e,t.onSessionIdChangeReplace);const C=kc(u),v=c.useMemo(()=>Vo(y,d),[y,d]),p=Eu(y,h),{streamStartTime:j,estimatedTokens:_,isTextStreaming:D}=r0(e,y.inProgressTurn,p==="streaming");a0(e,y.inProgressTurn,y.streamReadyCursor,t.onTaskEvent);const T=c.useRef(!0);c.useEffect(()=>(T.current=!0,()=>{T.current=!1}),[]);const N=c.useRef(new Map);c.useLayoutEffect(()=>{u&&(N.current.has(u)||N.current.set(u,te.getState().getSession(u).mountGeneration))},[u]);const{setMessages:A,setInput:k,setError:E,setSystemStatus:w,setOperationProgress:R}=Kx(u,T,N);c0(e,y.inProgressTurn,R,w),u&&te.getState().initSession(u),c.useEffect(()=>{e&&(te.getState().initSession(e),te.getState().touchSession(e),N.current.set(e,te.getState().getSession(e).mountGeneration))},[e]),c.useEffect(()=>{if(e)return bt.getState().clearUnseen(e),bt.subscribe(K=>{K.unseen[e]!==void 0&&bt.getState().clearUnseen(e)})},[e]);const{historyQuery:O}=Yx({sessionId:e,sid:u,transport:n,sessionCwd:l,enableMessagePolling:o,isStreaming:p==="streaming",setMessages:A}),F=jx(a,e,{startFreshSession:t.startFreshSession,compact:t.compactIntent}),{handleSubmit:$,submitContent:B,enqueueContent:U,steerContent:Y,addContextContent:se,stop:V,retryMessage:L,submitKickoff:I,markToolCallResponded:P}=Jx({sessionId:e,input:f,status:p,transport:n,queryClient:s,selectedCwd:a,onSessionIdChangeReplace:t.onSessionIdChangeReplace,transformContent:t.transformContent,launchRuntime:t.launchRuntime,agentPath:t.agentPath,agentLookupPending:t.agentLookupPending,agentLookupFailed:t.agentLookupFailed,launchAccount:(i==null?void 0:i.sessionId)===u?i.id:null,takeSeedContext:t.takeSeedContext,setInput:k,setError:E,tryNativeCommand:F.tryRun}),Q=y.streamReadyCursor!==null,ae=c.useCallback((K,le)=>B(K,le?{cwd:le}:void 0),[B]);e0({sessionId:e,cwd:a,status:p,messages:v,hydrated:Q,canStart:!t.agentLookupPending&&!t.agentLookupFailed,submitKickoff:I,submitContent:ae}),eb({sessionId:e,transport:n,sessionCwd:l,streamState:y,queryClient:s,onStreamingDone:t.onStreamingDone});const M=O.isLoading&&v.length===0,W=c.useMemo(()=>v.flatMap(K=>K.toolCalls||[]).filter(K=>K.interactiveType&&K.status==="pending"),[v]),X=W[0]||null,J=X!==null,Z=(X==null?void 0:X.interactiveType)||null;return{messages:v,input:f,setInput:k,handleSubmit:$,submitContent:B,enqueueContent:U,steerContent:Y,addContextContent:se,status:p,error:m,stop:V,retryMessage:L,isLoadingHistory:M,hydrated:Q,sessionStatus:x,streamStartTime:j,estimatedTokens:_,isTextStreaming:D,isWaitingForUser:J,waitingType:Z,activeInteraction:X,pendingInteractions:W,markToolCallResponded:P,systemStatus:g,operationProgress:S,promptSuggestions:b,syncConnectionState:C,tryNativeCommand:F.tryRun,commandPending:F.commandPending}}function sb(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. ${ab(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 rb(e,t){return!Na(e)||e.outcome==="not-running"&&t}function ab(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 ob(){const e=oe(d=>d.showTaskCelebrations),[t,n]=c.useState(null),[s,a]=c.useState(null),o=c.useRef(null),i=c.useRef(!1);c.useEffect(()=>{const d=window.matchMedia("(prefers-reduced-motion: reduce)");i.current=d.matches;const f=h=>{i.current=h.matches};return d.addEventListener("change",f),()=>d.removeEventListener("change",f)},[]),pd({timeoutMs:et.IDLE_TIMEOUT_MS,onIdle:c.useCallback(()=>{var d;(d=o.current)==null||d.setIdle(!0)},[]),onReturn:c.useCallback(()=>{var d,f;(d=o.current)==null||d.setIdle(!1),(f=o.current)==null||f.onUserReturn()},[])}),c.useEffect(()=>{const d=new Ad({enabled:e,miniProbability:et.MINI_PROBABILITY,debounceWindowMs:et.DEBOUNCE_WINDOW_MS,debounceThreshold:et.DEBOUNCE_THRESHOLD,minTasksForMajor:et.MIN_TASKS_FOR_MAJOR,idleTimeoutMs:et.IDLE_TIMEOUT_MS,onCelebrate:f=>{i.current&&f.level==="major"?n({...f,level:"mini"}):n(f),f.level==="mini"&&a(f.taskId)}});return o.current=d,()=>d.destroy()},[e]);const l=c.useCallback((d,f)=>{var h;d.action==="update"&&d.task.status==="completed"&&d.task.id&&((h=o.current)==null||h.onTaskCompleted(d.task.id,f))},[]),u=c.useCallback(()=>{n(null),a(null)},[]);return{handleTaskEvent:l,activeCelebration:t,celebratingTaskId:s,clearCelebration:u}}function Tn(){return{tasks:new Map,statusTimestamps:new Map,legacyCreateCount:0}}function ib(e){const t={};for(const[n,s]of Object.entries(e))s!==void 0&&s!==""&&(t[n]=s);return t}function Fn(e,t,n){switch(t.action){case"snapshot":{e.tasks.clear(),e.statusTimestamps.clear();const s=t.tasks??[t.task];for(const a of s)e.tasks.set(a.id,a),e.statusTimestamps.set(a.id,{status:a.status,since:n});return}case"create":{const s=t.task.id||`legacy:${e.legacyCreateCount++}`,a=s===t.task.id?t.task:{...t.task,id:s};e.tasks.set(s,a),e.statusTimestamps.set(s,{status:a.status,since:n});return}case"id_assigned":{const s=t.previousId;if(!s)return;const a=e.tasks.get(s);if(!a)return;const o=t.task.id;e.tasks.delete(s),e.tasks.set(o,{...a,id:o});const i=e.statusTimestamps.get(s);e.statusTimestamps.delete(s),e.statusTimestamps.set(o,i??{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 s=e.tasks.get(t.task.id);if(!s)return;e.tasks.set(t.task.id,{...s,...ib(t.task)}),t.task.status&&t.task.status!==s.status&&e.statusTimestamps.set(t.task.id,{status:t.task.status,since:n});return}}}function Or(e,t){var n;return(n=e.blockedBy)!=null&&n.length?e.blockedBy.some(s=>{const a=t.get(s);return a&&a.status!=="completed"}):!1}function lb(e,t){return[...e].sort((n,s)=>{const a=n.status==="in_progress"?0:n.status==="pending"&&!Or(n,t)?1:n.status==="pending"?2:3,o=s.status==="in_progress"?0:s.status==="pending"&&!Or(s,t)?1:s.status==="pending"?2:3;return a-o})}const cb=10;let $r=0;function Bt(e){return e==="streaming"||e==="blocked"}function ub(e,t=!1){const n=xe(),a=Qa().cwd,o=oe(N=>N.enableMessagePolling),i=La(),[l,u]=c.useState(Tn()),d=Ea(e??""),[f,h]=c.useState(()=>!Bt(d)),m=c.useRef([]),x=c.useRef(0),{data:g}=Ye({queryKey:["tasks",e,a],queryFn:async()=>{const N=++$r;return{...await n.getTasks(e,a??void 0),fetchOrder:N}},staleTime:3e4,refetchOnWindowFocus:!1,enabled:e!==null,refetchInterval:()=>!o||t?!1:i?Ge.ACTIVE_TAB_REFETCH_MS:Ge.BACKGROUND_TAB_REFETCH_MS}),S=c.useRef(null);c.useEffect(()=>{const N=`${e??""}::${a??""}`,A=S.current!==N;if(S.current=N,A&&(m.current=[],x.current=0,u(Tn())),!g||g.fetchOrder<=x.current)return;x.current=g.fetchOrder;const k=Tn();g.tasks.length>0&&Fn(k,{action:"snapshot",task:g.tasks[0],tasks:g.tasks},Date.now()),m.current=m.current.filter(({order:E})=>E>g.fetchOrder);for(const{event:E,receivedAt:w}of m.current)Fn(k,E,w);u(k)},[g,e,a]);const b=c.useCallback(N=>{const A=Date.now();N.action==="snapshot"&&(m.current=[]),m.current.push({order:++$r,event:N,receivedAt:A}),u(k=>{const E={tasks:new Map(k.tasks),statusTimestamps:new Map(k.statusTimestamps),legacyCreateCount:k.legacyCreateCount};return Fn(E,N,A),E})},[]),y=c.useRef(!1),C=c.useCallback(()=>{h(N=>(y.current=!N,!N))},[]),v=c.useRef(Bt(d));c.useEffect(()=>{const N=Bt(d);N!==v.current&&(v.current=N,N?y.current||h(!1):h(!0))},[d]);const p=c.useRef(null);c.useEffect(()=>{const N=`${e??""}::${a??""}`;if(p.current===N)return;p.current=N;const A=Bt(d);v.current=A,y.current=!1,h(!A)},[e,a,d]);const j=Array.from(l.tasks.values()),_=lb(j,l.tasks),D=j.find(N=>N.status==="in_progress"),T=(D==null?void 0:D.activeForm)??null;return{tasks:_.slice(0,cb),taskMap:l.tasks,activeForm:T,isCollapsed:f,toggleCollapse:C,handleTaskEvent:b,statusTimestamps:l.statusTimestamps}}function db(e){const t=c.useRef(null),[n,s]=c.useState(0),[a,o]=c.useState(!1),[i,l]=c.useState(0),u=c.useCallback(y=>{t.current=y,l(y&&"getOptionCount"in y?y.getOptionCount():0)},[]);c.useEffect(()=>{s(0),l(0),o(!1)},[e==null?void 0:e.toolCallId]);const d=c.useMemo(()=>e!=null&&e.interactiveType?{type:e.interactiveType,toolCallId:e.toolCallId}:null,[e]),f=c.useCallback(()=>{const y=t.current;y&&"approve"in y&&y.approve()},[]),h=c.useCallback(()=>{const y=t.current;y&&"alwaysAllow"in y&&y.alwaysAllow()},[]),m=c.useCallback(()=>{const y=t.current;y&&"deny"in y&&y.deny()},[]),x=c.useCallback(y=>{const C=t.current;C&&"toggleOption"in C&&(C.toggleOption(y),s(y),o(!0))},[]),g=c.useCallback(y=>{if(!a){o(!0);return}s(C=>{const v=t.current,p=v&&"getOptionCount"in v?v.getOptionCount():0;return p===0?C:y==="up"?C<=0?p-1:C-1:C>=p-1?0:C+1})},[a]),S=c.useCallback(y=>{const C=t.current;C&&"navigateQuestion"in C&&(C.navigateQuestion(y),s(0),o(!0),l(C.getOptionCount()))},[]),b=c.useCallback(()=>{const y=t.current;y&&"submit"in y&&y.submit()},[]);return hd({activeInteraction:d,onApprove:f,onAlwaysAllow:h,onDeny:m,onToggleOption:x,onNavigateOption:g,onNavigateQuestion:S,onSubmit:b,optionCount:i,focusedIndex:n}),{handleToolRef:u,focusedOptionIndex:a?n:-1}}function qt(e,t,n){var o;const s=e.length;if(s===0)return 0;let a=(t%s+s)%s;for(let i=0;i<s;i++){if(!((o=e[a])!=null&&o.disabled))return a;a=(a+n+s)%s}return t}function fb({commands:e,input:t,cursorPos:n}){const[s,a]=c.useState(!1),[o,i]=c.useState(""),[l,u]=c.useState(-1),d=c.useMemo(()=>o?e.map(j=>({cmd:j,rank:cf(o,j)})).filter(j=>j.rank.match).sort((j,_)=>j.rank.bucket-_.rank.bucket||_.rank.score-j.rank.score).map(({cmd:j,rank:_})=>({...j,matchedAlias:_.matchedAlias})):e,[e,o]),[f,h]=c.useState(null),m=f!==null&&f.query===o&&f.open===s?f.index:qt(d,0,1),x=d[m],g=d.length===0||x!==void 0&&!x.disabled?m:qt(d,0,1),S=c.useCallback((j,_)=>{const T=j.slice(0,_).match(/(^|\s)\/([\w:-]*)$/);return T?(a(!0),i(T[2]),u((T.index??0)+T[1].length),!0):(a(!1),!1)},[]),b=c.useCallback(j=>{const _=t.slice(0,l),D=t.slice(l+1+o.length);return a(!1),_+j.fullCommand+(D.startsWith(" ")?"":" ")+D},[t,o,l]),y=c.useCallback(()=>{h({query:o,open:s,index:qt(d,g+1,1)})},[d,g,o,s]),C=c.useCallback(()=>{h({query:o,open:s,index:qt(d,g-1,-1)})},[d,g,o,s]),v=c.useCallback(()=>{const j=d[g];return j&&!j.disabled?b(j):(j||a(!1),null)},[d,g,b]),p=c.useCallback(()=>{a(!1),i("")},[]);return{showCommands:s,setShowCommands:a,commandQuery:o,selectedIndex:g,filteredCommands:d,slashTriggerPos:l,detectCommandTrigger:S,handleCommandSelect:b,handleArrowUp:C,handleArrowDown:y,handleKeyboardSelect:v,resetCommand:p}}function mb({fileEntries:e,input:t,cursorPos:n}){const[s,a]=c.useState(!1),[o,i]=c.useState(""),[l,u]=c.useState(0),[d,f]=c.useState(-1),h=c.useMemo(()=>s?o?e.map(C=>({...C,...Ht(o,C.path)})).filter(C=>C.match).sort((C,v)=>v.score-C.score).slice(0,50):e.slice(0,50).map(C=>({...C,indices:[]})):[],[e,o,s]);c.useEffect(()=>{u(0)},[o,s]),c.useEffect(()=>{h.length>0&&l>=h.length&&u(h.length-1)},[h.length,l]);const m=c.useCallback((C,v)=>{const j=C.slice(0,v).match(/(^|\s)@([\w./:-]*)$/);return j?(a(!0),i(j[2]),f((j.index??0)+j[1].length),!0):(a(!1),!1)},[]),x=c.useCallback(C=>{const v=t.slice(0,d),p=t.slice(d+1+o.length);if(C.isDirectory){const _=v+"@"+C.path+p,D=v.length+1+C.path.length;return i(C.path),u(0),{newValue:_,newCursorPos:D,keepOpen:!0}}const j=v+"@"+C.path+" "+p;return a(!1),{newValue:j,keepOpen:!1}},[t,d,o]),g=c.useCallback(()=>{u(C=>h.length===0?0:(C+1)%h.length)},[h.length]),S=c.useCallback(()=>{u(C=>h.length===0?0:(C-1+h.length)%h.length)},[h.length]),b=c.useCallback(()=>h.length>0&&l<h.length?x(h[l]):(a(!1),null),[h,l,x]),y=c.useCallback(()=>{a(!1),i("")},[]);return{showFiles:s,setShowFiles:a,fileQuery:o,fileSelectedIndex:l,filteredFiles:h,fileTriggerPos:d,detectFileTrigger:m,handleFileSelect:x,handleArrowUp:S,handleArrowDown:g,handleKeyboardSelect:b,resetFiles:y}}function pb({input:e,setInput:t,commands:n,fileEntries:s}){const[a,o]=c.useState(0),i=fb({commands:n,input:e,cursorPos:a}),l=mb({fileEntries:s,input:e,cursorPos:a}),u=c.useCallback((_,D)=>{if(l.detectFileTrigger(_,D)){i.setShowCommands(!1);return}if(i.detectCommandTrigger(_,D)){l.setShowFiles(!1);return}l.setShowFiles(!1),i.setShowCommands(!1)},[l,i]),d=c.useRef({value:e,cursor:0});c.useEffect(()=>{d.current.value=e},[e]);const f=c.useCallback(_=>{t(_),d.current={value:_,cursor:d.current.cursor||_.length},u(_,d.current.cursor)},[t,u]),h=c.useCallback(_=>{o(_),d.current={value:d.current.value,cursor:_},u(d.current.value,_)},[u]),m=c.useCallback(_=>{const D=i.handleCommandSelect(_);t(D)},[i,t]),x=c.useCallback(_=>{const D=l.handleFileSelect(_);t(D.newValue),D.newCursorPos!==void 0&&o(D.newCursorPos)},[l,t]),g=c.useCallback(()=>{l.showFiles?l.handleArrowDown():i.handleArrowDown()},[l,i]),S=c.useCallback(()=>{l.showFiles?l.handleArrowUp():i.handleArrowUp()},[l,i]),b=c.useCallback(()=>{if(l.showFiles){const _=l.handleKeyboardSelect();_&&(t(_.newValue),_.newCursorPos!==void 0&&o(_.newCursorPos))}else if(i.showCommands){const _=i.handleKeyboardSelect();_&&t(_)}},[l,i,t]),y=c.useCallback(()=>{i.setShowCommands(!1),l.setShowFiles(!1)},[i,l]),C=i.showCommands||l.showFiles,v=l.showFiles&&l.filteredFiles.length>0||i.showCommands&&i.filteredCommands.length>0,p=l.showFiles?"file-palette-listbox":i.showCommands?"command-palette-listbox":void 0,j=l.showFiles&&l.filteredFiles.length>0?`file-item-${l.fileSelectedIndex}`:i.showCommands&&i.filteredCommands.length>0?`command-item-${i.selectedIndex}`:void 0;return{commands:{show:i.showCommands,filtered:i.filteredCommands,selectedIndex:i.selectedIndex},files:{show:l.showFiles,filtered:l.filteredFiles,selectedIndex:l.fileSelectedIndex},isPaletteOpen:C,paletteHasResults:v,activeDescendantId:j,paletteListboxId:p,handleInputChange:f,handleCursorChange:h,handleArrowUp:S,handleArrowDown:g,handleKeyboardSelect:b,handleCommandSelect:m,handleFileSelect:x,dismissPalettes:y}}function hb(e,t,n){const s=oe(i=>i.setIsStreaming),a=oe(i=>i.setIsWaitingForUser),o=oe(i=>i.setIsTextStreaming);c.useEffect(()=>(s(e==="streaming"),()=>s(!1)),[e,s]),c.useEffect(()=>(a(t),()=>a(!1)),[t,a]),c.useEffect(()=>(o(n),()=>o(!1)),[n,o])}function gb(){const e=xe(),t=oe(m=>m.selectedCwd),[n,s]=c.useState([]),a=c.useCallback(m=>{const x=m.map(g=>({id:crypto.randomUUID(),file:g,status:"pending",progress:0}));s(g=>[...g,...x])},[]),o=c.useCallback(m=>{s(x=>x.filter(g=>g.id!==m))},[]),i=c.useCallback(()=>{s([])},[]),l=c.useCallback(m=>{s(x=>x.map(g=>g.id===m&&g.status==="error"?{...g,status:"pending",progress:0,error:void 0}:g))},[]),u=c.useRef(null),d=kt({meta:{suppressErrorToast:!0},mutationFn:async m=>{if(!t)throw new Error("No working directory selected");s(b=>b.map(y=>m.some(C=>C.id===y.id)?{...y,status:"uploading"}:y));const x=b=>{s(y=>y.map(C=>C.status==="uploading"?{...C,progress:b.percentage}:C))},g=new AbortController;u.current=g;const S=m.map(b=>b.file);return e.uploadFiles(S,t,x,g.signal)},onSettled:()=>{u.current=null},onSuccess:(m,x)=>{s(g=>g.map(S=>{const b=x.findIndex(y=>y.id===S.id);return b===-1?S:{...S,status:"uploaded",progress:100,result:m[b]}}))},onError:m=>{s(x=>x.map(g=>g.status==="uploading"?{...g,status:"error",error:m.message}:g))}}),f=c.useCallback(()=>{var m;(m=u.current)==null||m.abort()},[]),h=c.useCallback(async()=>{const m=n.filter(b=>b.status==="error");if(m.length>0)throw new Error(m.length===1?`${m[0].file.name} did not upload. Retry it or remove it, then send again.`:`${m.length} attachments did not upload. Retry them or remove them, then send again.`);const x=n.filter(b=>b.status==="uploaded"&&b.result).map(b=>b.result.savedPath),g=n.filter(b=>b.status==="pending");if(g.length===0)return x;const S=await d.mutateAsync(g);return[...x,...S.map(b=>b.savedPath)]},[n,d]);return{pendingFiles:n,addFiles:a,removeFile:o,retryFile:l,clearFiles:i,cancelUpload:f,uploadAndGetPaths:h,hasPendingFiles:n.length>0,hasFailedUpload:n.some(m=>m.status==="error"),isUploading:d.isPending}}const Rn=new Set,Mn=new Set;function xb(e,t){return`${e}\0${t}`}function bb({sessionId:e,prompt:t,autoSend:n,input:s,setInput:a,messageCount:o,hydrated:i,status:l,submitBlocked:u=!1,submit:d,onSeeded:f,onConsumed:h}){const m=t!=null&&t.trim()?t:void 0,x=e&&m?xb(e,m):null;c.useEffect(()=>{if(!(!x||!m)&&!Rn.has(x)&&i){if(Rn.add(x),s.length>0||o>0){Mn.add(x),h==null||h();return}a(m),f==null||f(),n||h==null||h()}},[x,m,n,s,i,o,a,f,h]),c.useEffect(()=>{!x||!m||!n||Mn.has(x)||Rn.has(x)&&s===m&&(!i||o>0||l==="streaming"||u||(Mn.add(x),h==null||h(),d()))},[x,m,n,s,i,o,l,u,d,h])}const Pr=Cc-256,Lr=`
57
57
  …(context truncated)`,zr={"/":"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 yb(e){const t=`/${e.split("/").filter(Boolean)[0]??""}`;return zr[e]??zr[t]??`the ${e} page`}function vb(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 ${yb(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(`
58
- `);return n.length<=Pr?n:n.slice(0,Pr-Lr.length)+Lr}const kb="dorkbot-help",qt=new Set;function Cb({sessionId:e,seed:t,messageCount:n,hydrated:s,onConsumed:a}){const o=t===kb&&e!==null,{data:i}=Sc({enabled:o}),{data:l}=sa(),u=bt(jc(m=>Object.entries(m.statuses).filter(([,x])=>x.lifecycle==="error").map(([x])=>x))),d=c.useRef({agentNames:[],version:null,updateReady:!1,erroredSessionIds:[]}),f=c.useRef({armed:o,sessionId:e,messageCount:n}),h=c.useRef(a);return c.useEffect(()=>{const m=(l==null?void 0:l.latestVersion)??null,x=(l==null?void 0:l.version)??null;d.current={agentNames:((i==null?void 0:i.agents)??[]).map(g=>g.displayName??g.name),version:x,updateReady:m!==null&&x!==null&&_c(m,x),erroredSessionIds:u}},[i,l,u]),c.useEffect(()=>{f.current={armed:o,sessionId:e,messageCount:n},h.current=a},[o,e,n,a]),c.useEffect(()=>{!o||e===null||!s||n===0||qt.has(e)||(qt.add(e),a==null||a())},[o,e,s,n,a]),c.useCallback(()=>{var x;const m=f.current;if(!(!m.armed||m.sessionId===null)&&!(m.messageCount>0)&&!qt.has(m.sessionId))return qt.add(m.sessionId),(x=h.current)==null||x.call(h),vb({...d.current,originPath:wc()})},[])}function Sb(e,t,n,s=!1){if(e!=="error"||t||s)return!1;let a=-1;for(let i=n.length-1;i>=0;i--)if(n[i].role==="user"){a=i;break}return!n.slice(a+1).some(i=>i.parts.some(l=>l.type==="error"&&l.code!==ya))}const jb=4e3;function _b(e){const t=e.approvalDisplayName||lt(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 wb(e,t){const n=c.useRef(null),s=c.useRef(null),[a,o]=c.useState({text:"",nonce:0});return c.useEffect(()=>{s.current!==t&&(s.current=t,n.current=null);const i=e.filter(d=>d.type==="tool_call"&&d.approvalOutcome!==void 0);if(n.current===null){n.current=new Set(i.map(d=>d.toolCallId));return}const l=i.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?_b(l[0]):`Answered ${l.length} permission requests. Recorded in the chat.`;o(d=>({text:u,nonce:d.nonce+1}))},[e,t]),c.useEffect(()=>{if(a.text==="")return;const i=setTimeout(()=>o(l=>({text:"",nonce:l.nonce})),jb);return()=>clearTimeout(i)},[a]),a.text===""?"":a.nonce%2===0?a.text:`${a.text}​`}const Br=["hsl(var(--chart-1))","hsl(var(--chart-2))","hsl(var(--chart-3))","hsl(var(--chart-4))","hsl(var(--chart-5))"],Ur=5e3,Nb=1e3,Eb=1500,Db=new Set;function Ab(e){const t=c.useRef(new Map),n=Da({byTask:new Map,assigned:0}),[s,a]=c.useState(Db),[,o]=c.useState(0),i=c.useMemo(()=>{const u=new Map;for(const d of e)for(const f of d.parts)f.type==="background_task"&&u.set(f.taskId,f);return u},[e]);c.useEffect(()=>{if(!Array.from(i.values()).some(f=>f.taskType==="bash"&&f.status==="running"&&Date.now()-f.startedAt<Ur))return;const d=setInterval(()=>{o(f=>f+1)},Nb);return()=>clearInterval(d)},[i]);const l=c.useRef(new Set);return c.useLayoutEffect(()=>{for(const[u,d]of i)t.current.get(u)==="running"&&d.status!=="running"&&!Ws(d)&&a(h=>h.has(u)?h:new Set(h).add(u)),t.current.set(u,d.status)},[i]),c.useEffect(()=>{for(const u of s)l.current.has(u)||(l.current.add(u),setTimeout(()=>{l.current.delete(u),a(d=>{if(!d.has(u))return d;const f=new Set(d);return f.delete(u),f})},Eb))},[s]),c.useMemo(()=>{const u=Date.now(),d=[],f=n.read();let h=f.assigned;for(const[m,x]of i){const g=x.status==="running",S=s.has(m);if(!g&&!S||x.taskType==="bash"&&g&&u-x.startedAt<Ur)continue;let b=f.byTask.get(m);b===void 0&&(b=Br[h%Br.length],h+=1,f.byTask.set(m,b),n.write({byTask:f.byTask,assigned:h})),d.push({taskId:x.taskId,taskType:x.taskType,status:x.status,color:b,startedAt:x.startedAt,description:x.description,toolUses:x.toolUses,lastToolName:x.lastToolName,durationMs:x.durationMs,summary:x.summary,command:x.command,ambient:Ws(x)})}return d},[i,s,n])}const Tb=new Set(["streaming","blocked"]);function Fb(e,t){return e.length===0||e[0].waitingOn!==void 0||t&&Tb.has(t)?e:e.slice(1)}function In(e,t,n){return`${e} ${e===1?t:n}`}const qr={"delivery-owed":"a helper’s report","waiting-on-person":"your answer","timer-pending":"a reminder the agent set"},Rb={"timer-pending":"Switching now cancels the reminder."};function Mb(e){const{agents:t,shells:n,other:s}=e.holding,a=[t>0?In(t,"helper","helpers"):void 0,n>0?In(n,"command","commands"):void 0,s>0?In(s,"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)}`,i=e.pins,l=i.includes("cwd")&&e.targetFolderName?`moves to ${e.targetFolderName}`:i.includes("agentIdentity")?"switches agents":i.includes("systemPromptAppend")?"loads new instructions":"applies new settings";return{line:`${o!==void 0?`Held for ${o}.`:e.because!==void 0&&qr[e.because]!==void 0?`Held for ${qr[e.because]}.`:"Held until the agent is free."} Sending it ${l}.`,switchHint:o!==void 0?`Switching now stops ${o}.`:(e.because!==void 0?Rb[e.because]:void 0)??"Switching now stops what the agent is doing."}}const Ib={"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 Ob(e){return e!=null&&e.degradedBecause?Ib[e.degradedBecause]:null}function Hr(e){return(e==null?void 0:e.code)==="QUEUED_MESSAGE_NOT_FOUND"}function $b({sessionId:e,waiting:t,onEnqueue:n}){const s=xe(),a=Nc(e??""),[o,i]=c.useState(null),l=c.useMemo(()=>t.map(p=>({id:p.id,content:p.content,mine:s.clientId===void 0||p.enqueuedBy===s.clientId,notice:Ob(a[p.id]),...p.waitingOn?{waiting:Mb(p.waitingOn)}:{}})),[t,a,s.clientId]),u=c.useMemo(()=>{if(o===null)return null;const p=l.findIndex(j=>j.id===o);return p===-1?null:p},[o,l]),d=c.useCallback(()=>{var p;if(e)return(p=Ne.getState().getSession(e).queuedMessages[0])==null?void 0:p.id},[e]),f=c.useCallback((p,j)=>{p().catch(_=>{Hr(_)||Ee.error(j)})},[]),h=c.useCallback(async p=>{const j=p.trim();return!j||!e?!1:n(j)},[e,n]),m=c.useCallback((p,j)=>{e&&f(()=>s.updateQueuedMessage(e,p,{content:j}),"Couldn’t save that change")},[e,s,f]),x=c.useCallback(p=>{i(j=>j===p?null:j),e&&f(()=>s.removeQueuedMessage(e,p),"Couldn’t take that message off the queue")},[e,s,f]),g=c.useCallback((p,j)=>{if(!e)return;const _=D=>s.updateQueuedMessage(e,p,{move:{before:D}});f(async()=>{try{await _(j)}catch(D){if(!Hr(D))throw D;const T=d();if(T===void 0||T===p)return;await _(T)}},"Couldn’t move that message")},[e,s,f,d]),S=c.useCallback(p=>l.findIndex(_=>_.id===p)<=0?!1:(i(_=>_===p?null:_),g(p,l[0].id),!0),[l,g]),b=c.useCallback(p=>{const j=l.findIndex(_=>_.id===p);j<=0||g(p,l[j-1].id)},[l,g]),y=c.useCallback(p=>{const j=l.find(_=>_.id===p);return j?(i(p),j.content):null},[l]),C=c.useCallback(()=>{i(null)},[]),v=c.useCallback(p=>{o!==null&&(m(o,p),i(null))},[o,m]);return{queue:l,editingId:o,editingIndex:u,addToQueue:h,removeFromQueue:x,sendNow:S,moveUp:b,startEditing:y,cancelEditing:C,saveEditing:v,updateQueued:m}}function Go(e,t){return e===null?null:`${e} ${t??""}`}function Pb({input:e,setInput:t,sessionId:n,selectedCwd:s,waiting:a,onEnqueue:o,onSteer:i,onStage:l,tryNativeCommand:u,chatInputRef:d}){const f=c.useRef(""),h=c.useRef(null),m=Go(n,s);c.useEffect(()=>{f.current="",h.current=null},[m]);const x=$b({sessionId:n,waiting:a,onEnqueue:o}),g=x.cancelEditing;c.useEffect(()=>{g()},[m,g]);const S=c.useCallback(()=>{const F=x.editingId;if(F===null)return;const $=e.trim();$&&(x.updateQueued(F,$),Sx($)&&Ee.warning("Saved as a command. It runs instead of sending."))},[e,x]),b=Hs(x.editingId),y=Hs(x.updateQueued);c.useEffect(()=>{const F=n;return()=>{const $=b.read();if($===null||!F)return;const B=te.getState(),q=B.getSession(F).input.trim();q&&y.read()($,q),B.updateSession(F,{input:f.current})}},[m]);const C=c.useCallback(F=>{const $=e.trim();if(!$)return;const B=u($);if(B.handled){if(!B.ran)return;B.confirmed?Xn(n,$,B.confirmed):t("");return}if(h.current===$)return;h.current=$,at.getState().recordOpened("session",n),s&&at.getState().recordOpened("agent",s);const q=F($);q.finally(()=>{h.current===$&&(h.current=null)}),Xn(n,$,q)},[e,s,n,t,u]),v=c.useCallback(()=>C(F=>x.addToQueue(F)),[C,x]),p=c.useCallback(()=>{i&&C(i)},[C,i]),j=c.useCallback(()=>{l&&C(l)},[C,l]),_=c.useCallback(F=>{var q,Y;if(x.editingId===F){(q=d.current)==null||q.focus();return}const $=x.editingId!==null;$&&S();const B=x.startEditing(F);B!==null&&($||(f.current=e),t(B),(Y=d.current)==null||Y.focus())},[e,x,S,t,d]),D=c.useCallback(()=>{if(x.editingId===null)return;const F=e.trim();if(!F)return;const $=u(F);if($.handled){$.ran&&(x.cancelEditing(),t(f.current));return}x.saveEditing(F),t(f.current)},[e,x,t,u]),T=c.useCallback(()=>{x.cancelEditing(),t(f.current)},[x,t]),N=c.useCallback(F=>{x.editingId===F&&t(f.current),x.removeFromQueue(F)},[x,t]),A=c.useCallback(F=>{const $=x.editingId===F;$&&S(),x.sendNow(F)&&$&&t(f.current)},[x,S,t]),k=c.useCallback(F=>{x.moveUp(F)},[x]),E=c.useCallback(F=>{var q;const $=(q=x.queue[F])==null?void 0:q.id;if($!==void 0&&$===x.editingId)return;S();const B=$===void 0?null:x.startEditing($);if(B===null){x.cancelEditing(),t(f.current);return}t(B)},[x,S,t]),w=c.useCallback(()=>{S(),x.cancelEditing(),t(f.current)},[S,x,t]),R=c.useCallback(()=>{const{editingIndex:F,queue:$}=x;if(F===null){if($.length===0)return;f.current=e,E($.length-1)}else F>0?E(F-1):w()},[E,e,w,x]),O=c.useCallback(()=>{const{editingIndex:F,queue:$}=x;F!==null&&(F<$.length-1?E(F+1):w())},[E,w,x]);return{queue:x.queue,editingId:x.editingId,editingIndex:x.editingIndex,handleQueue:v,handleSteer:p,handleStage:j,handleQueueEdit:_,handleQueueSaveEdit:D,handleQueueCancelEdit:T,handleQueueRemove:N,handleQueueSend:A,handleQueueMoveUp:k,handleQueueNavigateUp:R,handleQueueNavigateDown:O,leaveQueueForStop:w}}const Lb=5e3,Wr=3;function Ko(){try{const e=Number(localStorage.getItem(Aa.PLACEHOLDER_HINT_CYCLES));return Number.isFinite(e)&&e>0?e:0}catch{return 0}}function zb(){const e=Ko()+1;try{localStorage.setItem(Aa.PLACEHOLDER_HINT_CYCLES,String(e))}catch{}return e}function Bb(e){const t=[...e];for(let n=t.length-1;n>0;n--){const s=Math.floor(Math.random()*(n+1));[t[n],t[s]]=[t[s],t[n]]}return t}function Ub({defaultText:e,hints:t,enabled:n,intervalMs:s=Lb}){const[a]=c.useState(()=>t.length>0?Bb(t):[]),[o,i]=c.useState(()=>Ko()>=Wr),[l,u]=c.useState({key:0,hintIndex:-1}),d=c.useRef(0),f=c.useRef(0),h=c.useRef(!1);return c.useEffect(()=>{if(o||!n||t.length===0){h.current&&(h.current=!1,d.current+=1,u({key:d.current,hintIndex:-1}));return}const x=setInterval(()=>{if(d.current+=1,h.current=!h.current,!h.current){u({key:d.current,hintIndex:-1});return}const g=f.current%t.length;f.current+=1,f.current%t.length===0&&zb()>=Wr&&i(!0),u({key:d.current,hintIndex:g})},s);return()=>clearInterval(x)},[n,t.length,s,o]),{text:l.hintIndex>=0?a[l.hintIndex]??e:e,key:l.key}}const On=/[.!?…:](?=\s|$)|\n/g;function Vr(e,t,n){const s=e.startsWith(t)?t.length:0,a=e.slice(0,s),o=e.slice(s);if(o.trim()==="")return{chunk:"",announced:a};if(n)return{chunk:o.trim(),announced:e};On.lastIndex=0;let i=-1;for(let l=On.exec(o);l!==null;l=On.exec(o))i=l.index+l[0].length;return i===-1?{chunk:"",announced:a}:{chunk:o.slice(0,i).trim(),announced:e.slice(0,s+i)}}const qb=1500,Hb=4e3,Wb=400;function Vb({messageId:e,text:t,isStreaming:n}){const s=c.useRef(new Map),[a,o]=c.useState({text:"",nonce:0});return c.useEffect(()=>{if(e===void 0)return;if(s.current.get(e)===void 0){if(!n)return;s.current.clear(),s.current.set(e,{announced:t.length<=Wb?"":t})}const l=s.current.get(e),{chunk:u,announced:d}=Vr(t,l.announced,!1);l.announced=d,u!==""&&o(h=>({text:u,nonce:h.nonce+1}));const f=setTimeout(()=>{const h=Vr(t,l.announced,!0);l.announced=h.announced,h.chunk!==""&&o(m=>({text:h.chunk,nonce:m.nonce+1}))},qb);return()=>clearTimeout(f)},[e,t,n]),c.useEffect(()=>{if(a.text==="")return;const i=setTimeout(()=>o(l=>({text:"",nonce:l.nonce})),Hb);return()=>clearTimeout(i)},[a]),a.text===""?"":a.nonce%2===0?a.text:`${a.text}​`}const Qo={reactions:!1,threads:!1,runWith:!0,attachments:!0,mentions:!1,streamHealth:!1,presence:!1,turnStatus:!0,asks:!0};function Gr(e){return e>=1e3?`~${(e/1e3).toFixed(1)}k tokens`:`~${Math.round(e)} tokens`}function Gb(e){const{formatted:t}=Pa(e.status==="streaming"?e.streamStartTime:null),n=la(e.permissionMode),s=c.useRef(e.status),a=c.useRef(t),o=c.useRef(e.estimatedTokens),[i,l]=c.useState(!1);return c.useEffect(()=>{e.status==="streaming"&&(a.current=t,o.current=e.estimatedTokens,s.current!=="streaming"&&l(!1))},[e.status,t,e.estimatedTokens]),c.useEffect(()=>{s.current==="streaming"&&e.status==="idle"&&o.current>0&&l(!0),s.current=e.status},[e.status]),c.useEffect(()=>{if(!i)return;const u=setTimeout(()=>l(!1),Jt.TURN_COMPLETE_DISMISS_MS);return()=>clearTimeout(u)},[i]),Iu({capabilities:Qo,asks:e.asks??Ra,stalled:!1,presence:Ou,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:Gr(e.estimatedTokens),isBypass:n,showComplete:i,lastElapsed:a.current,lastTokens:Gr(o.current)}})}function Kb(e){const{sessionId:t,placeholder:n,files:s}=e,a=c.useRef(e);c.useEffect(()=>{a.current=e});const o=c.useCallback(S=>a.current.files.addFiles(S),[]),i=c.useCallback(S=>a.current.files.removeFile(S),[]),l=c.useCallback(S=>a.current.files.retryFile(S),[]),u=c.useCallback(()=>a.current.files.cancelUpload(),[]),{pendingFiles:d,hasFailedUpload:f,isUploading:h}=s,m=c.useMemo(()=>({staged:d,add:o,remove:i,retry:l,cancel:u,hasFailed:f,isUploading:h,holdsSendWhileUploading:!0}),[d,f,h,o,i,l,u]),x=c.useCallback(async S=>{await a.current.submit(S.text)},[]),g=c.useCallback(async S=>{if(!await a.current.enqueue(S.text))throw new Error("Couldn’t queue that message. Try again.")},[]);return c.useMemo(()=>({kind:"session",id:t,placeholder:n,canSend:t!=="",...t===""?{canSendReason:"Pick a chat, or start a new one."}:{},send:x,queue:g,attachments:m}),[t,n,m,x,g])}function Qb({error:e,composerAgent:t,onRetry:n}){return e.code===xa&&e.agentId?r.jsx("div",{className:"mx-4 mb-2",children:r.jsx(Ya,{agentId:e.agentId,...(t==null?void 0:t.id)===e.agentId?{agentName:en(t,"This agent")}:{}})}):r.jsx("div",{className:"mx-4 mb-2",children:r.jsx(sn,{message:e.message,heading:e.heading,subtext:e.message,onRetry:e.retryable?n:void 0})})}const Yb={duration:.16,delay:.08,ease:[.16,1,.3,1]},Xb={duration:0};function Jb({sessionId:e,activeInteraction:t,pendingApprovals:n,focusedOptionIndex:s,onToolRef:a,onToolDecided:o,queueDepth:i=0,allowsDenyReason:l=!0}){const u=g=>o(t.toolCallId,g),d=Te(),{answerAll:f,isAnswering:h,error:m}=Ec(),x=c.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 r.jsxs(r.Fragment,{children:[n.length>=2&&r.jsx(Dc,{className:"mb-1.5",headline:`${n.length} tools are waiting on you`,items:n.map(g=>({id:g.toolCallId,line:lt(g.toolName,g.input??"")})),onAllowAll:()=>void f(x,"allow"),onDenyAll:()=>void f(x,"deny"),isAnswering:h,error:m}),r.jsx(ie,{mode:"wait",initial:!1,children:r.jsx(G.div,{initial:d?!1:{opacity:0,y:6},animate:{opacity:1,y:0},transition:d?Xb:Yb,children:t.interactiveType==="approval"?r.jsx(Xa,{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?r.jsx(va,{ref:a,sessionId:e,toolCallId:t.toolCallId,questions:t.questions,answers:t.answers,isActive:!0,focusedOptionIndex:s,onDecided:u}):null},t.toolCallId)}),i>0&&r.jsx("p",{className:"text-muted-foreground px-1 pt-2 text-xs",children:i===1?"1 message sends once you answer.":`${i} messages send once you answer.`})]})}function Zb({filteredCommands:e,selectedIndex:t,onSelect:n}){const s=c.useMemo(()=>{const a=[],o=new Map;let i=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:i++})}for(const[l,u]of o)a.push({namespace:l,items:u});return a},[e]);return c.useEffect(()=>{const a=document.getElementById(`command-item-${t}`);a&&a.scrollIntoView({block:"nearest"})},[t]),r.jsx(G.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:r.jsx("div",{id:"command-palette-listbox",role:"listbox",className:"max-h-72 overflow-y-auto p-1.5",children:e.length===0?r.jsx("div",{className:"text-muted-foreground px-2 py-4 text-center text-sm",children:"No commands found."}):s.map(({namespace:a,items:o},i)=>r.jsxs("div",{children:[i>0&&r.jsx("div",{className:"bg-border mx-2 my-1.5 h-px"}),r.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,f=l.disabled===!0;return r.jsxs("div",{id:`command-item-${u}`,role:"option","aria-selected":d,"aria-disabled":f,"data-selected":d,"data-disabled":f,tabIndex:d?0:-1,onClick:()=>{f||n(l)},onKeyDown:h=>{h.key==="Enter"&&!f&&n(l)},className:f?"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:[r.jsxs("div",{className:"flex min-w-0 items-baseline gap-2",children:[r.jsx("span",{className:"text-foreground shrink-0 font-mono text-[13px] font-medium",children:l.fullCommand}),l.argumentHint&&r.jsx("span",{className:"text-muted-foreground/50 shrink-0 font-mono text-xs",children:l.argumentHint}),f&&l.disabledReason?r.jsx("span",{className:"text-muted-foreground/70 text-2xs ml-auto shrink-0",children:l.disabledReason}):l.matchedAlias&&r.jsxs("span",{className:"text-muted-foreground/60 text-2xs ml-auto shrink-0 font-mono italic",children:["matched /",l.matchedAlias.replace(/^\//,"")]})]}),l.description&&r.jsx("p",{className:"text-muted-foreground mt-0.5 truncate text-xs leading-normal",children:l.description})]},l.fullCommand)})]},a))})})}function ey(e,t,n,s){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":s}function ty({chatInputRef:e,input:t,autocomplete:n,steerContent:s,addContextContent:a,tryNativeCommand:o,commandPending:i,agentLookupPending:l=!1,agentLookupError:u=!1,status:d,stop:f,setInput:h,sessionId:m,sessionStatus:x,waiting:g,interaction:S,sync:b}){var $e,Xe;const{active:y,pendingApprovals:C,focusedOptionIndex:v,onToolRef:p,onToolDecided:j}=S,_=d==="streaming",D=oe(pe=>pe.isTextStreaming),[T]=Ta(),N=xe(),{data:A}=ms(T),k=Ac(A??null,T??""),E=A?en(A):void 0,{target:w}=$u(),R=(w==null?void 0:w.placeholder)??"Send a message…",O=Tc(m),F=pm(m),$=tn(m),B=Zt($),q=Fc(m),Y=((B==null?void 0:B.supportsSteer)??!1)&&(q??!0),se=(B==null?void 0:B.supportsContextStaging)??!1,V=(($e=B==null?void 0:B.permissionModes)==null?void 0:$e.denyReason)??!0,L=c.useCallback(async pe=>{if((w==null?void 0:w.queue)===void 0)return!1;try{return await w.queue({text:pe}),!0}catch{return!1}},[w]),I=Pb({input:t,setInput:h,sessionId:m,selectedCwd:T,waiting:g,onEnqueue:L,onSteer:s,onStage:a,tryNativeCommand:o,chatInputRef:e}),[P,Q]=c.useState(null),ae=c.useRef(null),M=c.useCallback(pe=>{const ge=ae.current;if(ae.current=null,pe.length===0)return;const Se=pe.map(Ae=>ge&&Ae.id===ge.id?ge.content:Ae.content).join(`
58
+ `);return n.length<=Pr?n:n.slice(0,Pr-Lr.length)+Lr}const kb="dorkbot-help",Ut=new Set;function Cb({sessionId:e,seed:t,messageCount:n,hydrated:s,onConsumed:a}){const o=t===kb&&e!==null,{data:i}=Sc({enabled:o}),{data:l}=sa(),u=bt(jc(m=>Object.entries(m.statuses).filter(([,x])=>x.lifecycle==="error").map(([x])=>x))),d=c.useRef({agentNames:[],version:null,updateReady:!1,erroredSessionIds:[]}),f=c.useRef({armed:o,sessionId:e,messageCount:n}),h=c.useRef(a);return c.useEffect(()=>{const m=(l==null?void 0:l.latestVersion)??null,x=(l==null?void 0:l.version)??null;d.current={agentNames:((i==null?void 0:i.agents)??[]).map(g=>g.displayName??g.name),version:x,updateReady:m!==null&&x!==null&&_c(m,x),erroredSessionIds:u}},[i,l,u]),c.useEffect(()=>{f.current={armed:o,sessionId:e,messageCount:n},h.current=a},[o,e,n,a]),c.useEffect(()=>{!o||e===null||!s||n===0||Ut.has(e)||(Ut.add(e),a==null||a())},[o,e,s,n,a]),c.useCallback(()=>{var x;const m=f.current;if(!(!m.armed||m.sessionId===null)&&!(m.messageCount>0)&&!Ut.has(m.sessionId))return Ut.add(m.sessionId),(x=h.current)==null||x.call(h),vb({...d.current,originPath:wc()})},[])}function Sb(e,t,n,s=!1){if(e!=="error"||t||s)return!1;let a=-1;for(let i=n.length-1;i>=0;i--)if(n[i].role==="user"){a=i;break}return!n.slice(a+1).some(i=>i.parts.some(l=>l.type==="error"&&l.code!==ya))}const jb=4e3;function _b(e){const t=e.approvalDisplayName||lt(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 wb(e,t){const n=c.useRef(null),s=c.useRef(null),[a,o]=c.useState({text:"",nonce:0});return c.useEffect(()=>{s.current!==t&&(s.current=t,n.current=null);const i=e.filter(d=>d.type==="tool_call"&&d.approvalOutcome!==void 0);if(n.current===null){n.current=new Set(i.map(d=>d.toolCallId));return}const l=i.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?_b(l[0]):`Answered ${l.length} permission requests. Recorded in the chat.`;o(d=>({text:u,nonce:d.nonce+1}))},[e,t]),c.useEffect(()=>{if(a.text==="")return;const i=setTimeout(()=>o(l=>({text:"",nonce:l.nonce})),jb);return()=>clearTimeout(i)},[a]),a.text===""?"":a.nonce%2===0?a.text:`${a.text}​`}const Br=["hsl(var(--chart-1))","hsl(var(--chart-2))","hsl(var(--chart-3))","hsl(var(--chart-4))","hsl(var(--chart-5))"],qr=5e3,Nb=1e3,Eb=1500,Db=new Set;function Ab(e){const t=c.useRef(new Map),n=Da({byTask:new Map,assigned:0}),[s,a]=c.useState(Db),[,o]=c.useState(0),i=c.useMemo(()=>{const u=new Map;for(const d of e)for(const f of d.parts)f.type==="background_task"&&u.set(f.taskId,f);return u},[e]);c.useEffect(()=>{if(!Array.from(i.values()).some(f=>f.taskType==="bash"&&f.status==="running"&&Date.now()-f.startedAt<qr))return;const d=setInterval(()=>{o(f=>f+1)},Nb);return()=>clearInterval(d)},[i]);const l=c.useRef(new Set);return c.useLayoutEffect(()=>{for(const[u,d]of i)t.current.get(u)==="running"&&d.status!=="running"&&!Ws(d)&&a(h=>h.has(u)?h:new Set(h).add(u)),t.current.set(u,d.status)},[i]),c.useEffect(()=>{for(const u of s)l.current.has(u)||(l.current.add(u),setTimeout(()=>{l.current.delete(u),a(d=>{if(!d.has(u))return d;const f=new Set(d);return f.delete(u),f})},Eb))},[s]),c.useMemo(()=>{const u=Date.now(),d=[],f=n.read();let h=f.assigned;for(const[m,x]of i){const g=x.status==="running",S=s.has(m);if(!g&&!S||x.taskType==="bash"&&g&&u-x.startedAt<qr)continue;let b=f.byTask.get(m);b===void 0&&(b=Br[h%Br.length],h+=1,f.byTask.set(m,b),n.write({byTask:f.byTask,assigned:h})),d.push({taskId:x.taskId,taskType:x.taskType,status:x.status,color:b,startedAt:x.startedAt,description:x.description,toolUses:x.toolUses,lastToolName:x.lastToolName,durationMs:x.durationMs,summary:x.summary,command:x.command,ambient:Ws(x)})}return d},[i,s,n])}const Tb=new Set(["streaming","blocked"]);function Fb(e,t){return e.length===0||e[0].waitingOn!==void 0||t&&Tb.has(t)?e:e.slice(1)}function In(e,t,n){return`${e} ${e===1?t:n}`}const Ur={"delivery-owed":"a helper’s report","waiting-on-person":"your answer","timer-pending":"a reminder the agent set"},Rb={"timer-pending":"Switching now cancels the reminder."};function Mb(e){const{agents:t,shells:n,other:s}=e.holding,a=[t>0?In(t,"helper","helpers"):void 0,n>0?In(n,"command","commands"):void 0,s>0?In(s,"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)}`,i=e.pins,l=i.includes("cwd")&&e.targetFolderName?`moves to ${e.targetFolderName}`:i.includes("agentIdentity")?"switches agents":i.includes("systemPromptAppend")?"loads new instructions":"applies new settings";return{line:`${o!==void 0?`Held for ${o}.`:e.because!==void 0&&Ur[e.because]!==void 0?`Held for ${Ur[e.because]}.`:"Held until the agent is free."} Sending it ${l}.`,switchHint:o!==void 0?`Switching now stops ${o}.`:(e.because!==void 0?Rb[e.because]:void 0)??"Switching now stops what the agent is doing."}}const Ib={"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 Ob(e){return e!=null&&e.degradedBecause?Ib[e.degradedBecause]:null}function Hr(e){return(e==null?void 0:e.code)==="QUEUED_MESSAGE_NOT_FOUND"}function $b({sessionId:e,waiting:t,onEnqueue:n}){const s=xe(),a=Nc(e??""),[o,i]=c.useState(null),l=c.useMemo(()=>t.map(p=>({id:p.id,content:p.content,mine:s.clientId===void 0||p.enqueuedBy===s.clientId,notice:Ob(a[p.id]),...p.waitingOn?{waiting:Mb(p.waitingOn)}:{}})),[t,a,s.clientId]),u=c.useMemo(()=>{if(o===null)return null;const p=l.findIndex(j=>j.id===o);return p===-1?null:p},[o,l]),d=c.useCallback(()=>{var p;if(e)return(p=Ne.getState().getSession(e).queuedMessages[0])==null?void 0:p.id},[e]),f=c.useCallback((p,j)=>{p().catch(_=>{Hr(_)||Ee.error(j)})},[]),h=c.useCallback(async p=>{const j=p.trim();return!j||!e?!1:n(j)},[e,n]),m=c.useCallback((p,j)=>{e&&f(()=>s.updateQueuedMessage(e,p,{content:j}),"Couldn’t save that change")},[e,s,f]),x=c.useCallback(p=>{i(j=>j===p?null:j),e&&f(()=>s.removeQueuedMessage(e,p),"Couldn’t take that message off the queue")},[e,s,f]),g=c.useCallback((p,j)=>{if(!e)return;const _=D=>s.updateQueuedMessage(e,p,{move:{before:D}});f(async()=>{try{await _(j)}catch(D){if(!Hr(D))throw D;const T=d();if(T===void 0||T===p)return;await _(T)}},"Couldn’t move that message")},[e,s,f,d]),S=c.useCallback(p=>l.findIndex(_=>_.id===p)<=0?!1:(i(_=>_===p?null:_),g(p,l[0].id),!0),[l,g]),b=c.useCallback(p=>{const j=l.findIndex(_=>_.id===p);j<=0||g(p,l[j-1].id)},[l,g]),y=c.useCallback(p=>{const j=l.find(_=>_.id===p);return j?(i(p),j.content):null},[l]),C=c.useCallback(()=>{i(null)},[]),v=c.useCallback(p=>{o!==null&&(m(o,p),i(null))},[o,m]);return{queue:l,editingId:o,editingIndex:u,addToQueue:h,removeFromQueue:x,sendNow:S,moveUp:b,startEditing:y,cancelEditing:C,saveEditing:v,updateQueued:m}}function Go(e,t){return e===null?null:`${e} ${t??""}`}function Pb({input:e,setInput:t,sessionId:n,selectedCwd:s,waiting:a,onEnqueue:o,onSteer:i,onStage:l,tryNativeCommand:u,chatInputRef:d}){const f=c.useRef(""),h=c.useRef(null),m=Go(n,s);c.useEffect(()=>{f.current="",h.current=null},[m]);const x=$b({sessionId:n,waiting:a,onEnqueue:o}),g=x.cancelEditing;c.useEffect(()=>{g()},[m,g]);const S=c.useCallback(()=>{const F=x.editingId;if(F===null)return;const $=e.trim();$&&(x.updateQueued(F,$),Sx($)&&Ee.warning("Saved as a command. It runs instead of sending."))},[e,x]),b=Hs(x.editingId),y=Hs(x.updateQueued);c.useEffect(()=>{const F=n;return()=>{const $=b.read();if($===null||!F)return;const B=te.getState(),U=B.getSession(F).input.trim();U&&y.read()($,U),B.updateSession(F,{input:f.current})}},[m]);const C=c.useCallback(F=>{const $=e.trim();if(!$)return;const B=u($);if(B.handled){if(!B.ran)return;B.confirmed?Xn(n,$,B.confirmed):t("");return}if(h.current===$)return;h.current=$,at.getState().recordOpened("session",n),s&&at.getState().recordOpened("agent",s);const U=F($);U.finally(()=>{h.current===$&&(h.current=null)}),Xn(n,$,U)},[e,s,n,t,u]),v=c.useCallback(()=>C(F=>x.addToQueue(F)),[C,x]),p=c.useCallback(()=>{i&&C(i)},[C,i]),j=c.useCallback(()=>{l&&C(l)},[C,l]),_=c.useCallback(F=>{var U,Y;if(x.editingId===F){(U=d.current)==null||U.focus();return}const $=x.editingId!==null;$&&S();const B=x.startEditing(F);B!==null&&($||(f.current=e),t(B),(Y=d.current)==null||Y.focus())},[e,x,S,t,d]),D=c.useCallback(()=>{if(x.editingId===null)return;const F=e.trim();if(!F)return;const $=u(F);if($.handled){$.ran&&(x.cancelEditing(),t(f.current));return}x.saveEditing(F),t(f.current)},[e,x,t,u]),T=c.useCallback(()=>{x.cancelEditing(),t(f.current)},[x,t]),N=c.useCallback(F=>{x.editingId===F&&t(f.current),x.removeFromQueue(F)},[x,t]),A=c.useCallback(F=>{const $=x.editingId===F;$&&S(),x.sendNow(F)&&$&&t(f.current)},[x,S,t]),k=c.useCallback(F=>{x.moveUp(F)},[x]),E=c.useCallback(F=>{var U;const $=(U=x.queue[F])==null?void 0:U.id;if($!==void 0&&$===x.editingId)return;S();const B=$===void 0?null:x.startEditing($);if(B===null){x.cancelEditing(),t(f.current);return}t(B)},[x,S,t]),w=c.useCallback(()=>{S(),x.cancelEditing(),t(f.current)},[S,x,t]),R=c.useCallback(()=>{const{editingIndex:F,queue:$}=x;if(F===null){if($.length===0)return;f.current=e,E($.length-1)}else F>0?E(F-1):w()},[E,e,w,x]),O=c.useCallback(()=>{const{editingIndex:F,queue:$}=x;F!==null&&(F<$.length-1?E(F+1):w())},[E,w,x]);return{queue:x.queue,editingId:x.editingId,editingIndex:x.editingIndex,handleQueue:v,handleSteer:p,handleStage:j,handleQueueEdit:_,handleQueueSaveEdit:D,handleQueueCancelEdit:T,handleQueueRemove:N,handleQueueSend:A,handleQueueMoveUp:k,handleQueueNavigateUp:R,handleQueueNavigateDown:O,leaveQueueForStop:w}}const Lb=5e3,Wr=3;function Ko(){try{const e=Number(localStorage.getItem(Aa.PLACEHOLDER_HINT_CYCLES));return Number.isFinite(e)&&e>0?e:0}catch{return 0}}function zb(){const e=Ko()+1;try{localStorage.setItem(Aa.PLACEHOLDER_HINT_CYCLES,String(e))}catch{}return e}function Bb(e){const t=[...e];for(let n=t.length-1;n>0;n--){const s=Math.floor(Math.random()*(n+1));[t[n],t[s]]=[t[s],t[n]]}return t}function qb({defaultText:e,hints:t,enabled:n,intervalMs:s=Lb}){const[a]=c.useState(()=>t.length>0?Bb(t):[]),[o,i]=c.useState(()=>Ko()>=Wr),[l,u]=c.useState({key:0,hintIndex:-1}),d=c.useRef(0),f=c.useRef(0),h=c.useRef(!1);return c.useEffect(()=>{if(o||!n||t.length===0){h.current&&(h.current=!1,d.current+=1,u({key:d.current,hintIndex:-1}));return}const x=setInterval(()=>{if(d.current+=1,h.current=!h.current,!h.current){u({key:d.current,hintIndex:-1});return}const g=f.current%t.length;f.current+=1,f.current%t.length===0&&zb()>=Wr&&i(!0),u({key:d.current,hintIndex:g})},s);return()=>clearInterval(x)},[n,t.length,s,o]),{text:l.hintIndex>=0?a[l.hintIndex]??e:e,key:l.key}}const On=/[.!?…:](?=\s|$)|\n/g;function Vr(e,t,n){const s=e.startsWith(t)?t.length:0,a=e.slice(0,s),o=e.slice(s);if(o.trim()==="")return{chunk:"",announced:a};if(n)return{chunk:o.trim(),announced:e};On.lastIndex=0;let i=-1;for(let l=On.exec(o);l!==null;l=On.exec(o))i=l.index+l[0].length;return i===-1?{chunk:"",announced:a}:{chunk:o.slice(0,i).trim(),announced:e.slice(0,s+i)}}const Ub=1500,Hb=4e3,Wb=400;function Vb({messageId:e,text:t,isStreaming:n}){const s=c.useRef(new Map),[a,o]=c.useState({text:"",nonce:0});return c.useEffect(()=>{if(e===void 0)return;if(s.current.get(e)===void 0){if(!n)return;s.current.clear(),s.current.set(e,{announced:t.length<=Wb?"":t})}const l=s.current.get(e),{chunk:u,announced:d}=Vr(t,l.announced,!1);l.announced=d,u!==""&&o(h=>({text:u,nonce:h.nonce+1}));const f=setTimeout(()=>{const h=Vr(t,l.announced,!0);l.announced=h.announced,h.chunk!==""&&o(m=>({text:h.chunk,nonce:m.nonce+1}))},Ub);return()=>clearTimeout(f)},[e,t,n]),c.useEffect(()=>{if(a.text==="")return;const i=setTimeout(()=>o(l=>({text:"",nonce:l.nonce})),Hb);return()=>clearTimeout(i)},[a]),a.text===""?"":a.nonce%2===0?a.text:`${a.text}​`}const Qo={reactions:!1,threads:!1,runWith:!0,attachments:!0,mentions:!1,streamHealth:!1,presence:!1,turnStatus:!0,asks:!0};function Gr(e){return e>=1e3?`~${(e/1e3).toFixed(1)}k tokens`:`~${Math.round(e)} tokens`}function Gb(e){const{formatted:t}=Pa(e.status==="streaming"?e.streamStartTime:null),n=la(e.permissionMode),s=c.useRef(e.status),a=c.useRef(t),o=c.useRef(e.estimatedTokens),[i,l]=c.useState(!1);return c.useEffect(()=>{e.status==="streaming"&&(a.current=t,o.current=e.estimatedTokens,s.current!=="streaming"&&l(!1))},[e.status,t,e.estimatedTokens]),c.useEffect(()=>{s.current==="streaming"&&e.status==="idle"&&o.current>0&&l(!0),s.current=e.status},[e.status]),c.useEffect(()=>{if(!i)return;const u=setTimeout(()=>l(!1),Jt.TURN_COMPLETE_DISMISS_MS);return()=>clearTimeout(u)},[i]),Iu({capabilities:Qo,asks:e.asks??Ra,stalled:!1,presence:Ou,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:Gr(e.estimatedTokens),isBypass:n,showComplete:i,lastElapsed:a.current,lastTokens:Gr(o.current)}})}function Kb(e){const{sessionId:t,placeholder:n,files:s}=e,a=c.useRef(e);c.useEffect(()=>{a.current=e});const o=c.useCallback(S=>a.current.files.addFiles(S),[]),i=c.useCallback(S=>a.current.files.removeFile(S),[]),l=c.useCallback(S=>a.current.files.retryFile(S),[]),u=c.useCallback(()=>a.current.files.cancelUpload(),[]),{pendingFiles:d,hasFailedUpload:f,isUploading:h}=s,m=c.useMemo(()=>({staged:d,add:o,remove:i,retry:l,cancel:u,hasFailed:f,isUploading:h,holdsSendWhileUploading:!0}),[d,f,h,o,i,l,u]),x=c.useCallback(async S=>{await a.current.submit(S.text)},[]),g=c.useCallback(async S=>{if(!await a.current.enqueue(S.text))throw new Error("Couldn’t queue that message. Try again.")},[]);return c.useMemo(()=>({kind:"session",id:t,placeholder:n,canSend:t!=="",...t===""?{canSendReason:"Pick a chat, or start a new one."}:{},send:x,queue:g,attachments:m}),[t,n,m,x,g])}function Qb({error:e,composerAgent:t,onRetry:n}){return e.code===xa&&e.agentId?r.jsx("div",{className:"mx-4 mb-2",children:r.jsx(Ya,{agentId:e.agentId,...(t==null?void 0:t.id)===e.agentId?{agentName:en(t,"This agent")}:{}})}):r.jsx("div",{className:"mx-4 mb-2",children:r.jsx(sn,{message:e.message,heading:e.heading,subtext:e.message,onRetry:e.retryable?n:void 0})})}const Yb={duration:.16,delay:.08,ease:[.16,1,.3,1]},Xb={duration:0};function Jb({sessionId:e,activeInteraction:t,pendingApprovals:n,focusedOptionIndex:s,onToolRef:a,onToolDecided:o,queueDepth:i=0,allowsDenyReason:l=!0}){const u=g=>o(t.toolCallId,g),d=Te(),{answerAll:f,isAnswering:h,error:m}=Ec(),x=c.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 r.jsxs(r.Fragment,{children:[n.length>=2&&r.jsx(Dc,{className:"mb-1.5",headline:`${n.length} tools are waiting on you`,items:n.map(g=>({id:g.toolCallId,line:lt(g.toolName,g.input??"")})),onAllowAll:()=>void f(x,"allow"),onDenyAll:()=>void f(x,"deny"),isAnswering:h,error:m}),r.jsx(ie,{mode:"wait",initial:!1,children:r.jsx(G.div,{initial:d?!1:{opacity:0,y:6},animate:{opacity:1,y:0},transition:d?Xb:Yb,children:t.interactiveType==="approval"?r.jsx(Xa,{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?r.jsx(va,{ref:a,sessionId:e,toolCallId:t.toolCallId,questions:t.questions,answers:t.answers,isActive:!0,focusedOptionIndex:s,onDecided:u}):null},t.toolCallId)}),i>0&&r.jsx("p",{className:"text-muted-foreground px-1 pt-2 text-xs",children:i===1?"1 message sends once you answer.":`${i} messages send once you answer.`})]})}function Zb({filteredCommands:e,selectedIndex:t,onSelect:n}){const s=c.useMemo(()=>{const a=[],o=new Map;let i=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:i++})}for(const[l,u]of o)a.push({namespace:l,items:u});return a},[e]);return c.useEffect(()=>{const a=document.getElementById(`command-item-${t}`);a&&a.scrollIntoView({block:"nearest"})},[t]),r.jsx(G.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:r.jsx("div",{id:"command-palette-listbox",role:"listbox",className:"max-h-72 overflow-y-auto p-1.5",children:e.length===0?r.jsx("div",{className:"text-muted-foreground px-2 py-4 text-center text-sm",children:"No commands found."}):s.map(({namespace:a,items:o},i)=>r.jsxs("div",{children:[i>0&&r.jsx("div",{className:"bg-border mx-2 my-1.5 h-px"}),r.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,f=l.disabled===!0;return r.jsxs("div",{id:`command-item-${u}`,role:"option","aria-selected":d,"aria-disabled":f,"data-selected":d,"data-disabled":f,tabIndex:d?0:-1,onClick:()=>{f||n(l)},onKeyDown:h=>{h.key==="Enter"&&!f&&n(l)},className:f?"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:[r.jsxs("div",{className:"flex min-w-0 items-baseline gap-2",children:[r.jsx("span",{className:"text-foreground shrink-0 font-mono text-[13px] font-medium",children:l.fullCommand}),l.argumentHint&&r.jsx("span",{className:"text-muted-foreground/50 shrink-0 font-mono text-xs",children:l.argumentHint}),f&&l.disabledReason?r.jsx("span",{className:"text-muted-foreground/70 text-2xs ml-auto shrink-0",children:l.disabledReason}):l.matchedAlias&&r.jsxs("span",{className:"text-muted-foreground/60 text-2xs ml-auto shrink-0 font-mono italic",children:["matched /",l.matchedAlias.replace(/^\//,"")]})]}),l.description&&r.jsx("p",{className:"text-muted-foreground mt-0.5 truncate text-xs leading-normal",children:l.description})]},l.fullCommand)})]},a))})})}function ey(e,t,n,s){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":s}function ty({chatInputRef:e,input:t,autocomplete:n,steerContent:s,addContextContent:a,tryNativeCommand:o,commandPending:i,agentLookupPending:l=!1,agentLookupError:u=!1,status:d,stop:f,setInput:h,sessionId:m,sessionStatus:x,waiting:g,interaction:S,sync:b}){var $e,Xe;const{active:y,pendingApprovals:C,focusedOptionIndex:v,onToolRef:p,onToolDecided:j}=S,_=d==="streaming",D=oe(pe=>pe.isTextStreaming),[T]=Ta(),N=xe(),{data:A}=ms(T),k=Ac(A??null,T??""),E=A?en(A):void 0,{target:w}=$u(),R=(w==null?void 0:w.placeholder)??"Send a message…",O=Tc(m),F=pm(m),$=tn(m),B=Zt($),U=Fc(m),Y=((B==null?void 0:B.supportsSteer)??!1)&&(U??!0),se=(B==null?void 0:B.supportsContextStaging)??!1,V=(($e=B==null?void 0:B.permissionModes)==null?void 0:$e.denyReason)??!0,L=c.useCallback(async pe=>{if((w==null?void 0:w.queue)===void 0)return!1;try{return await w.queue({text:pe}),!0}catch{return!1}},[w]),I=Pb({input:t,setInput:h,sessionId:m,selectedCwd:T,waiting:g,onEnqueue:L,onSteer:s,onStage:a,tryNativeCommand:o,chatInputRef:e}),[P,Q]=c.useState(null),ae=c.useRef(null),M=c.useCallback(pe=>{const ge=ae.current;if(ae.current=null,pe.length===0)return;const Se=pe.map(Ae=>ge&&Ae.id===ge.id?ge.content:Ae.content).join(`
59
59
 
60
60
  `),He=te.getState().getSession(m).input.trim();h(He?`${He}
61
61
 
62
- ${Se}`:Se)},[m,h]),[W,X]=c.useState(null),J=W===m&&_,Z=c.useRef(null),K=c.useCallback(()=>{Z.current=null,X(null)},[]);c.useEffect(()=>{_||K()},[_,m,K]);const le=c.useRef(_);c.useEffect(()=>{le.current=_},[_]);const fe=I.leaveQueueForStop,me=c.useRef(I.editingId);c.useEffect(()=>{me.current=I.editingId},[I.editingId]);const z=c.useCallback(()=>{const pe=me.current;if(pe!==null){const ge=te.getState().getSession(m).input.trim();ge&&(ae.current={id:pe,content:ge}),fe()}Z.current=m,X(m),f().then(ge=>{M(ge.cancelled),rb(ge.receipt,le.current)&&K();const Se=sb(ge.receipt);Se.message!==null&&!Na(ge.receipt)&&(Se.isFailure?Ee.error(Se.message):Ee.warning(Se.message))}).catch(()=>{K()})},[m,f,M,K,fe]),he=c.useCallback(()=>{if(!(Z.current===m||J)){if(g.length===0){z();return}Q({sessionId:m,queuedCount:g.length})}},[m,J,g.length,z]),ce=c.useCallback(()=>{Z.current===m||J||(Q(null),z())},[m,J,z]);c.useEffect(()=>{(P==null?void 0:P.sessionId)===m&&g.length===0&&Q(null)},[P,m,g.length]);const{messages:je}=wa(m),ke=ja(m),De=c.useMemo(()=>Vo(ke,je),[ke,je]),Me=Ab(De),de=c.useCallback(async pe=>{if(m)try{await N.stopTask(m,pe)}catch(ge){console.error("[chat] Failed to stop task:",ge)}},[m,N]),Oe=c.useCallback(()=>{m&&N.switchSessionProcess(m).catch(()=>{Ee.error("Couldn’t switch. Try again.")})},[m,N]),ye=c.useRef(t);c.useEffect(()=>{ye.current=t});const _e=c.useCallback(pe=>{var Ae;const ge=ye.current,Se=ge.length>0&&!/\s$/.test(ge)?" ":"",He=`${ge}${Se}${pe}`;h(He),(Ae=e.current)==null||Ae.focusAt(He.length)},[h,e]);c.useEffect(()=>Xu(_e),[_e]);const be=!_&&I.editingIndex===null,Ie=Ub({defaultText:R,hints:Gx,enabled:be&&t===""}),qe=Rc(),re=c.useCallback(()=>{n.dismissPalettes(),!(w===null||!w.canSend)&&w.send({text:t})},[n,w,t]),Ce=c.useCallback(()=>{n.dismissPalettes(),I.handleQueue()},[n,I]),dt=c.useCallback(()=>{n.dismissPalettes(),I.handleSteer()},[n,I]),ft=c.useCallback(()=>{n.dismissPalettes(),I.handleStage()},[n,I]);return r.jsx(St.Composer,{className:"chat-input-container",onPathDropped:pe=>_e(Ju(pe)),inputRef:e,value:t,onChange:n.handleInputChange,onSubmit:re,head:r.jsx(ie,{children:_&&r.jsx(Sd,{color:k.color,isTextStreaming:D,edge:"top"})}),asks:y?r.jsx(Jb,{sessionId:m,activeInteraction:y,pendingApprovals:C,focusedOptionIndex:v,onToolRef:p,onToolDecided:j,queueDepth:I.queue.length,allowsDenyReason:V}):null,overlays:r.jsx(r.Fragment,{children:r.jsxs(ie,{children:[n.commands.show&&r.jsx(Zb,{filteredCommands:n.commands.filtered,selectedIndex:n.commands.selectedIndex,onSelect:n.handleCommandSelect}),n.files.show&&r.jsx(xm,{filteredFiles:n.files.filtered,selectedIndex:n.files.selectedIndex,onSelect:n.handleFileSelect})]})}),queue:r.jsx(ie,{children:I.queue.length>0&&r.jsx(hx,{queue:I.queue,editingId:I.editingId,onEdit:I.handleQueueEdit,onRemove:I.handleQueueRemove,onSend:I.handleQueueSend,onMoveUp:I.handleQueueMoveUp,onSwitchNow:Oe,statusNote:O?"Waiting for your answer above":((Xe=I.queue[0])==null?void 0:Xe.waiting)!==void 0?"Sending when the agent is free":"Sending one at a time as the agent finishes"})}),aboveInput:r.jsx(fx,{tasks:Me,onStopTask:de}),footer:r.jsx(St.Footer,{asChild:!0,children:r.jsx(Lx,{sessionId:m,sessionStatus:x,isStreaming:_,syncConnectionState:b.connectionState,agentName:E,agentColor:k.color,agentEmoji:k.emoji,agentPath:T??void 0})}),input:{isStreaming:_,commandPending:i,...l||u?{canSubmit:!1,canSubmitReason:u?"Check this folder again before you start.":"Checking this folder…"}:{},...F.canSubmit?{}:{canSubmit:!1},onStop:he,stopPending:J,onEscape:n.dismissPalettes,onClear:()=>{h(""),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:qe,editingQueueItem:I.editingIndex!==null,...I.editingIndex===null?{}:{editingPosition:I.editingIndex+1},queueDepth:I.queue.length,onQueue:Ce,...Y?{onSteer:dt}:{},...se?{onStage:ft}:{},onSaveEdit:I.handleQueueSaveEdit,onCancelEdit:I.handleQueueCancelEdit,onQueueNavigateUp:I.handleQueueNavigateUp,onQueueNavigateDown:I.handleQueueNavigateDown,queueHasItems:I.queue.length>0,contextKey:Go(m,T)??void 0,placeholder:F.placeholder??ey(I.editingIndex,_,I.queue.length,R),placeholderOverlay:be&&F.canSubmit?r.jsx(yx,{text:Ie.text,animationKey:Ie.key}):null},children:r.jsx(gx,{open:(P==null?void 0:P.sessionId)===m,onOpenChange:pe=>{pe||Q(null)},queuedCount:(P==null?void 0:P.queuedCount)??0,onConfirm:ce})})}const ny=e=>{const t=e;return t.role==="user"?r.jsx(Wg,{message:t}):r.jsx(Pg,{message:t})};function sy({message:e,grouping:t,author:n,sessionId:s,isNew:a=!1,isStreaming:o=!1,isLatestWidgetMessage:i=!0,isFinalMessage:l=!0,activeToolCallId:u=null,onToolRef:d,focusedOptionIndex:f=-1,onToolDecided:h,onRetry:m,onSigninComplete:x,onChooseModel:g,inputZoneToolCallId:S=null,textEffect:b,runtimeLabel:y,allowsDenyReason:C,feedPosition:v}){var B,q;const p=c.useId(),j=`${p}-author`,_=`${p}-content`,D=c.useRef(null),T=t.position==="first"||t.position==="only",N=e.role==="user",A=N&&e.messageType!=="local_command_output",k=N?(B=e.chatMessages)==null?void 0:B[0]:void 0,E=N&&k===void 0?e.roomMessage:void 0,w=A&&k===void 0&&(E===void 0||((q=E.author)==null?void 0:q.you)===!0)&&e.messageType!=="command"&&e.messageType!=="compaction"&&e.content.trim().length>0,R=e.timestamp?Ln(e.timestamp):"",O=R.length>0,F=O?e.timestamp:void 0,$=c.useCallback(()=>{var Y;return(Y=D.current)==null?void 0:Y.focus()},[]);return r.jsx(kp,{value:{sessionId:s,isStreaming:o,isLatestWidgetMessage:i,isFinalMessage:l,activeToolCallId:u,onToolRef:d,focusedOptionIndex:f,onToolDecided:h,onRetry:m,onSigninComplete:x,onChooseModel:g,inputZoneToolCallId:S,textEffect:b,runtimeLabel:y,allowsDenyReason:C},children:r.jsxs(tt.Root,{ref:D,role:A?"user":"assistant",position:t.position,isNew:a,"data-testid":"message-item","data-role":e.role,...T?{"aria-labelledby":j}:{"aria-label":O?`${n.displayName}, ${R}`:n.displayName},"aria-describedby":_,...Pu(v),children:[r.jsx(tt.Gutter,{author:n,at:F}),r.jsxs(tt.Body,{children:[r.jsx(tt.Author,{id:j,author:n,at:F,...k?{mark:r.jsx(xo,{stamp:k}),className:"flex-wrap gap-y-0.5"}:E?{mark:r.jsx(dp,{stamp:E}),className:"flex-wrap gap-y-0.5"}:{}}),r.jsx(tt.Content,{id:_,children:ny(e,{rowId:e.id})}),w&&r.jsx(tt.Actions,{runWith:{prompt:e.content,sessionId:s},onExit:$})]})]})})}const Kr="Conversation",ry=[];function ay(e){for(let t=e.length-1;t>=0;t--)if(e[t].content.includes(Yu))return t;return-1}function oy({messages:e,sessionId:t,isLoadingHistory:n=!1,hydrated:s=!1,isTextStreaming:a=!1,activeToolCallId:o=null,onToolRef:i,focusedOptionIndex:l=-1,onToolDecided:u,onRetry:d,onSigninComplete:f,onChooseModel:h,inputZoneToolCallId:m=null,textEffect:x,runtimeLabel:g,allowsDenyReason:S,landOnRow:b,foldFirstPrompt:y=!1}){const{stops:C}=bo(t),v=c.useMemo(()=>ip(e,C),[e,C]),p=c.useMemo(()=>{let M=0;return v.map(W=>W._chatStop?-1:M++)},[v]),j=Da(null);j.read()===null&&e.length>0&&j.write(e.length);const _=c.useMemo(()=>ay(v),[v]),D=c.useMemo(()=>y?v.findIndex(M=>M.role==="user"&&M.messageType===void 0&&!M._stagedContext&&!M._chatStop):-1,[y,v]),T=Xt(t),N=oe(M=>M.selectedCwd),A=tn(t),{data:k}=ms(N),E=c.useMemo(()=>({agent:k?{id:k.id,displayName:en(k),...Nt(k)}:null,runtime:A}),[k,A]),w=e[e.length-1],R=(w==null?void 0:w.role)==="assistant"?w:void 0,O=Vb({messageId:R==null?void 0:R.id,text:(R==null?void 0:R.content)??"",isStreaming:R!==void 0&&a}),F=wb((w==null?void 0:w.parts)??ry,t),{lastSeenMessageId:$,unreadFromStart:B,markSeen:q,isHydrated:Y}=Nf(t,e),[se,V]=c.useState(()=>Date.now()),L=c.useRef(null);c.useLayoutEffect(()=>{const M=Date.now(),W=new Date(M).toDateString();if(L.current===null){L.current=W;return}L.current!==W&&(L.current=W,V(M))},[v]);const I=c.useMemo(()=>Tm(v,{resolveAuthor:M=>Dm(M,E),now:se,lastSeenMessageId:$,unreadFromStart:B}),[v,E,se,$,B]),P=c.useMemo(()=>I.map(M=>M.kind==="day-divider"?{kind:"day-divider",id:M.key,label:M.label}:M.kind==="unread-divider"?{kind:"unread-divider",id:M.key}:{kind:"message",id:M.key,payload:M.message,grouping:M.grouping,author:M.author,at:M.message.timestamp}),[I]),Q=c.useCallback((M,W)=>{var he,ce;const X=I[W.index];if(X.kind==="day-divider")return r.jsx(Lu,{label:X.label});if(X.kind==="unread-divider")return r.jsx(zu,{});const{message:J,messageIndex:Z}=X;if(J._stagedContext)return r.jsx(Rp,{content:J.content});if(J._chatStop)return r.jsx("div",{className:"px-4 py-1",children:r.jsx(xp,{notice:J._chatStop})});if(Z===D)return r.jsx(Km,{content:((ce=(he=J.chatMessages)==null?void 0:he[0])==null?void 0:ce.text)??J.content});const K=p[Z]??Z,le=K===e.length-1,fe=le&&J.role==="assistant",me=_===-1||Z>=_,z=j.read();return r.jsx(sy,{message:J,grouping:X.grouping,author:X.author,sessionId:t,isNew:z!==null&&K>=z,isStreaming:fe&&a,isLatestWidgetMessage:me,isFinalMessage:le,activeToolCallId:o,onToolRef:i,focusedOptionIndex:l,onToolDecided:u,onRetry:d,onSigninComplete:f,onChooseModel:h,inputZoneToolCallId:m,textEffect:x,runtimeLabel:g,allowsDenyReason:S,feedPosition:{index:K+1,total:e.length}})},[I,e.length,p,_,D,t,j,a,o,i,l,u,d,f,h,m,x,g,S]),ae=T&&T.kind!=="first-message"&&T.fired&&!T.greetingFailed&&s?T:null;return r.jsx(St.Timeline,{conversationId:t,label:Kr,rows:P,renderRow:Q,landOn:"unread",landingReady:Y,...b===void 0?{}:{landOnRow:b},onReachedBottom:q,transcriptAnnouncement:O,approvalAnnouncement:F,className:"pt-12 [--conversation-thumb-top:3rem]",loading:n?r.jsx(Bu,{label:Kr,busy:!0,className:"flex h-full items-center justify-center","data-testid":"transcript-feed-loading",children:r.jsxs("div",{className:"text-muted-foreground flex items-center gap-2 text-sm",children:[r.jsx(po,{}),"Loading chat…"]})}):void 0,empty:r.jsx("div",{className:"flex h-full items-center justify-center",children:r.jsx(Bm,{birthRecord:T,firstLightRecord:ae})}),"data-testid":"message-list",feedTestId:"transcript-feed"})}function iy({sessionId:e,launchRuntime:t,launchPrompt:n,launchSend:s=!1,launchSeed:a,onLaunchConsumed:o,landOnRow:i}){var Es,Ds,As;const[,l]=_t(),u=as(),d=c.useRef(null),f=c.useRef(null),h=c.useCallback(()=>{var U,ve;(ve=(U=f.current)==null?void 0:U.querySelector('[data-testid="model-config-trigger"]'))==null||ve.click()},[]),m=ub(e),x=Mc(e??""),g=ob(),{play:S}=Gc(),[b]=Ta(),{data:y,isPending:C,isError:v,refetch:p}=ms(b),{sessions:j}=Zn(),_=e!==null&&!j.some(U=>U.id===e),D=Ic(e),T=gb(),N=c.useCallback(async U=>{let ve=U;if(T.hasPendingFiles){const Je=await T.uploadAndGetPaths(),Ts=b?Je.map(Rt=>Rt.startsWith(b)?Rt.slice(b.length).replace(/^\//,""):Rt):Je;Ts.length>0&&(ve=`Please read the following uploaded file(s):
62
+ ${Se}`:Se)},[m,h]),[W,X]=c.useState(null),J=W===m&&_,Z=c.useRef(null),K=c.useCallback(()=>{Z.current=null,X(null)},[]);c.useEffect(()=>{_||K()},[_,m,K]);const le=c.useRef(_);c.useEffect(()=>{le.current=_},[_]);const fe=I.leaveQueueForStop,me=c.useRef(I.editingId);c.useEffect(()=>{me.current=I.editingId},[I.editingId]);const z=c.useCallback(()=>{const pe=me.current;if(pe!==null){const ge=te.getState().getSession(m).input.trim();ge&&(ae.current={id:pe,content:ge}),fe()}Z.current=m,X(m),f().then(ge=>{M(ge.cancelled),rb(ge.receipt,le.current)&&K();const Se=sb(ge.receipt);Se.message!==null&&!Na(ge.receipt)&&(Se.isFailure?Ee.error(Se.message):Ee.warning(Se.message))}).catch(()=>{K()})},[m,f,M,K,fe]),he=c.useCallback(()=>{if(!(Z.current===m||J)){if(g.length===0){z();return}Q({sessionId:m,queuedCount:g.length})}},[m,J,g.length,z]),ce=c.useCallback(()=>{Z.current===m||J||(Q(null),z())},[m,J,z]);c.useEffect(()=>{(P==null?void 0:P.sessionId)===m&&g.length===0&&Q(null)},[P,m,g.length]);const{messages:je}=wa(m),ke=ja(m),De=c.useMemo(()=>Vo(ke,je),[ke,je]),Me=Ab(De),de=c.useCallback(async pe=>{if(m)try{await N.stopTask(m,pe)}catch(ge){console.error("[chat] Failed to stop task:",ge)}},[m,N]),Oe=c.useCallback(()=>{m&&N.switchSessionProcess(m).catch(()=>{Ee.error("Couldn’t switch. Try again.")})},[m,N]),ye=c.useRef(t);c.useEffect(()=>{ye.current=t});const _e=c.useCallback(pe=>{var Ae;const ge=ye.current,Se=ge.length>0&&!/\s$/.test(ge)?" ":"",He=`${ge}${Se}${pe}`;h(He),(Ae=e.current)==null||Ae.focusAt(He.length)},[h,e]);c.useEffect(()=>Yu(_e),[_e]);const be=!_&&I.editingIndex===null,Ie=qb({defaultText:R,hints:Gx,enabled:be&&t===""}),Ue=Rc(),re=c.useCallback(()=>{n.dismissPalettes(),!(w===null||!w.canSend)&&w.send({text:t})},[n,w,t]),Ce=c.useCallback(()=>{n.dismissPalettes(),I.handleQueue()},[n,I]),dt=c.useCallback(()=>{n.dismissPalettes(),I.handleSteer()},[n,I]),ft=c.useCallback(()=>{n.dismissPalettes(),I.handleStage()},[n,I]);return r.jsx(St.Composer,{className:"chat-input-container",onPathDropped:pe=>_e(Xu(pe)),inputRef:e,value:t,onChange:n.handleInputChange,onSubmit:re,head:r.jsx(ie,{children:_&&r.jsx(Sd,{color:k.color,isTextStreaming:D,edge:"top"})}),asks:y?r.jsx(Jb,{sessionId:m,activeInteraction:y,pendingApprovals:C,focusedOptionIndex:v,onToolRef:p,onToolDecided:j,queueDepth:I.queue.length,allowsDenyReason:V}):null,overlays:r.jsx(r.Fragment,{children:r.jsxs(ie,{children:[n.commands.show&&r.jsx(Zb,{filteredCommands:n.commands.filtered,selectedIndex:n.commands.selectedIndex,onSelect:n.handleCommandSelect}),n.files.show&&r.jsx(xm,{filteredFiles:n.files.filtered,selectedIndex:n.files.selectedIndex,onSelect:n.handleFileSelect})]})}),queue:r.jsx(ie,{children:I.queue.length>0&&r.jsx(hx,{queue:I.queue,editingId:I.editingId,onEdit:I.handleQueueEdit,onRemove:I.handleQueueRemove,onSend:I.handleQueueSend,onMoveUp:I.handleQueueMoveUp,onSwitchNow:Oe,statusNote:O?"Waiting for your answer above":((Xe=I.queue[0])==null?void 0:Xe.waiting)!==void 0?"Sending when the agent is free":"Sending one at a time as the agent finishes"})}),aboveInput:r.jsx(fx,{tasks:Me,onStopTask:de}),footer:r.jsx(St.Footer,{asChild:!0,children:r.jsx(Lx,{sessionId:m,sessionStatus:x,isStreaming:_,syncConnectionState:b.connectionState,agentName:E,agentColor:k.color,agentEmoji:k.emoji,agentPath:T??void 0})}),input:{isStreaming:_,commandPending:i,...l||u?{canSubmit:!1,canSubmitReason:u?"Check this folder again before you start.":"Checking this folder…"}:{},...F.canSubmit?{}:{canSubmit:!1},onStop:he,stopPending:J,onEscape:n.dismissPalettes,onClear:()=>{h(""),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:Ue,editingQueueItem:I.editingIndex!==null,...I.editingIndex===null?{}:{editingPosition:I.editingIndex+1},queueDepth:I.queue.length,onQueue:Ce,...Y?{onSteer:dt}:{},...se?{onStage:ft}:{},onSaveEdit:I.handleQueueSaveEdit,onCancelEdit:I.handleQueueCancelEdit,onQueueNavigateUp:I.handleQueueNavigateUp,onQueueNavigateDown:I.handleQueueNavigateDown,queueHasItems:I.queue.length>0,contextKey:Go(m,T)??void 0,placeholder:F.placeholder??ey(I.editingIndex,_,I.queue.length,R),placeholderOverlay:be&&F.canSubmit?r.jsx(yx,{text:Ie.text,animationKey:Ie.key}):null},children:r.jsx(gx,{open:(P==null?void 0:P.sessionId)===m,onOpenChange:pe=>{pe||Q(null)},queuedCount:(P==null?void 0:P.queuedCount)??0,onConfirm:ce})})}const ny=e=>{const t=e;return t.role==="user"?r.jsx(Wg,{message:t}):r.jsx(Pg,{message:t})};function sy({message:e,grouping:t,author:n,sessionId:s,isNew:a=!1,isStreaming:o=!1,isLatestWidgetMessage:i=!0,isFinalMessage:l=!0,activeToolCallId:u=null,onToolRef:d,focusedOptionIndex:f=-1,onToolDecided:h,onRetry:m,onSigninComplete:x,onChooseModel:g,inputZoneToolCallId:S=null,textEffect:b,runtimeLabel:y,allowsDenyReason:C,feedPosition:v}){var B,U;const p=c.useId(),j=`${p}-author`,_=`${p}-content`,D=c.useRef(null),T=t.position==="first"||t.position==="only",N=e.role==="user",A=N&&e.messageType!=="local_command_output",k=N?(B=e.chatMessages)==null?void 0:B[0]:void 0,E=N&&k===void 0?e.roomMessage:void 0,w=A&&k===void 0&&(E===void 0||((U=E.author)==null?void 0:U.you)===!0)&&e.messageType!=="command"&&e.messageType!=="compaction"&&e.content.trim().length>0,R=e.timestamp?Ln(e.timestamp):"",O=R.length>0,F=O?e.timestamp:void 0,$=c.useCallback(()=>{var Y;return(Y=D.current)==null?void 0:Y.focus()},[]);return r.jsx(kp,{value:{sessionId:s,isStreaming:o,isLatestWidgetMessage:i,isFinalMessage:l,activeToolCallId:u,onToolRef:d,focusedOptionIndex:f,onToolDecided:h,onRetry:m,onSigninComplete:x,onChooseModel:g,inputZoneToolCallId:S,textEffect:b,runtimeLabel:y,allowsDenyReason:C},children:r.jsxs(tt.Root,{ref:D,role:A?"user":"assistant",position:t.position,isNew:a,"data-testid":"message-item","data-role":e.role,...T?{"aria-labelledby":j}:{"aria-label":O?`${n.displayName}, ${R}`:n.displayName},"aria-describedby":_,...Pu(v),children:[r.jsx(tt.Gutter,{author:n,at:F}),r.jsxs(tt.Body,{children:[r.jsx(tt.Author,{id:j,author:n,at:F,...k?{mark:r.jsx(xo,{stamp:k}),className:"flex-wrap gap-y-0.5"}:E?{mark:r.jsx(dp,{stamp:E}),className:"flex-wrap gap-y-0.5"}:{}}),r.jsx(tt.Content,{id:_,children:ny(e,{rowId:e.id})}),w&&r.jsx(tt.Actions,{runWith:{prompt:e.content,sessionId:s},onExit:$})]})]})})}const Kr="Conversation",ry=[];function ay(e){for(let t=e.length-1;t>=0;t--)if(e[t].content.includes(Qu))return t;return-1}function oy({messages:e,sessionId:t,isLoadingHistory:n=!1,hydrated:s=!1,isTextStreaming:a=!1,activeToolCallId:o=null,onToolRef:i,focusedOptionIndex:l=-1,onToolDecided:u,onRetry:d,onSigninComplete:f,onChooseModel:h,inputZoneToolCallId:m=null,textEffect:x,runtimeLabel:g,allowsDenyReason:S,landOnRow:b,foldFirstPrompt:y=!1}){const{stops:C}=bo(t),v=c.useMemo(()=>ip(e,C),[e,C]),p=c.useMemo(()=>{let M=0;return v.map(W=>W._chatStop?-1:M++)},[v]),j=Da(null);j.read()===null&&e.length>0&&j.write(e.length);const _=c.useMemo(()=>ay(v),[v]),D=c.useMemo(()=>y?v.findIndex(M=>M.role==="user"&&M.messageType===void 0&&!M._stagedContext&&!M._chatStop):-1,[y,v]),T=Xt(t),N=oe(M=>M.selectedCwd),A=tn(t),{data:k}=ms(N),E=c.useMemo(()=>({agent:k?{id:k.id,displayName:en(k),...Nt(k)}:null,runtime:A}),[k,A]),w=e[e.length-1],R=(w==null?void 0:w.role)==="assistant"?w:void 0,O=Vb({messageId:R==null?void 0:R.id,text:(R==null?void 0:R.content)??"",isStreaming:R!==void 0&&a}),F=wb((w==null?void 0:w.parts)??ry,t),{lastSeenMessageId:$,unreadFromStart:B,markSeen:U,isHydrated:Y}=Nf(t,e),[se,V]=c.useState(()=>Date.now()),L=c.useRef(null);c.useLayoutEffect(()=>{const M=Date.now(),W=new Date(M).toDateString();if(L.current===null){L.current=W;return}L.current!==W&&(L.current=W,V(M))},[v]);const I=c.useMemo(()=>Tm(v,{resolveAuthor:M=>Dm(M,E),now:se,lastSeenMessageId:$,unreadFromStart:B}),[v,E,se,$,B]),P=c.useMemo(()=>I.map(M=>M.kind==="day-divider"?{kind:"day-divider",id:M.key,label:M.label}:M.kind==="unread-divider"?{kind:"unread-divider",id:M.key}:{kind:"message",id:M.key,payload:M.message,grouping:M.grouping,author:M.author,at:M.message.timestamp}),[I]),Q=c.useCallback((M,W)=>{var he,ce;const X=I[W.index];if(X.kind==="day-divider")return r.jsx(Lu,{label:X.label});if(X.kind==="unread-divider")return r.jsx(zu,{});const{message:J,messageIndex:Z}=X;if(J._stagedContext)return r.jsx(Rp,{content:J.content});if(J._chatStop)return r.jsx("div",{className:"px-4 py-1",children:r.jsx(xp,{notice:J._chatStop})});if(Z===D)return r.jsx(Km,{content:((ce=(he=J.chatMessages)==null?void 0:he[0])==null?void 0:ce.text)??J.content});const K=p[Z]??Z,le=K===e.length-1,fe=le&&J.role==="assistant",me=_===-1||Z>=_,z=j.read();return r.jsx(sy,{message:J,grouping:X.grouping,author:X.author,sessionId:t,isNew:z!==null&&K>=z,isStreaming:fe&&a,isLatestWidgetMessage:me,isFinalMessage:le,activeToolCallId:o,onToolRef:i,focusedOptionIndex:l,onToolDecided:u,onRetry:d,onSigninComplete:f,onChooseModel:h,inputZoneToolCallId:m,textEffect:x,runtimeLabel:g,allowsDenyReason:S,feedPosition:{index:K+1,total:e.length}})},[I,e.length,p,_,D,t,j,a,o,i,l,u,d,f,h,m,x,g,S]),ae=T&&T.kind!=="first-message"&&T.fired&&!T.greetingFailed&&s?T:null;return r.jsx(St.Timeline,{conversationId:t,label:Kr,rows:P,renderRow:Q,landOn:"unread",landingReady:Y,...b===void 0?{}:{landOnRow:b},onReachedBottom:U,transcriptAnnouncement:O,approvalAnnouncement:F,className:"pt-12 [--conversation-thumb-top:3rem]",loading:n?r.jsx(Bu,{label:Kr,busy:!0,className:"flex h-full items-center justify-center","data-testid":"transcript-feed-loading",children:r.jsxs("div",{className:"text-muted-foreground flex items-center gap-2 text-sm",children:[r.jsx(po,{}),"Loading chat…"]})}):void 0,empty:r.jsx("div",{className:"flex h-full items-center justify-center",children:r.jsx(Bm,{birthRecord:T,firstLightRecord:ae})}),"data-testid":"message-list",feedTestId:"transcript-feed"})}function iy({sessionId:e,launchRuntime:t,launchPrompt:n,launchSend:s=!1,launchSeed:a,onLaunchConsumed:o,landOnRow:i}){var Es,Ds,As;const[,l]=_t(),u=as(),d=c.useRef(null),f=c.useRef(null),h=c.useCallback(()=>{var q,ve;(ve=(q=f.current)==null?void 0:q.querySelector('[data-testid="model-config-trigger"]'))==null||ve.click()},[]),m=ub(e),x=Mc(e??""),g=ob(),{play:S}=Gc(),[b]=Ta(),{data:y,isPending:C,isError:v,refetch:p}=ms(b),{sessions:j}=Zn(),_=e!==null&&!j.some(q=>q.id===e),D=Ic(e),T=gb(),N=c.useCallback(async q=>{let ve=q;if(T.hasPendingFiles){const Je=await T.uploadAndGetPaths(),Ts=b?Je.map(Rt=>Rt.startsWith(b)?Rt.slice(b.length).replace(/^\//,""):Rt):Je;Ts.length>0&&(ve=`Please read the following uploaded file(s):
63
63
  ${Ts.map(ci=>`- ${ci}`).join(`
64
64
  `)}
65
65
 
66
- ${ve}`),T.clearFiles()}return ve},[T,b]),A=c.useCallback(U=>{m.handleTaskEvent(U);const ve=m.tasks.map(Je=>Je.id===U.task.id?{...Je,...U.task}:Je);g.handleTaskEvent(U,ve)},[m,g]);c.useCallback(U=>{l(U),u.invalidateQueries({queryKey:We.bySession(U)})},[l,u]);const k=c.useCallback(U=>{l(U,{replace:!0}),u.invalidateQueries({queryKey:We.bySession(U)})},[l,u]),E=c.useCallback(U=>{l(crypto.randomUUID(),{continuedFrom:U??void 0,draft:!0})},[l]),w=Sa(e??""),R=Zt(w.runtime),O=w.runtime?Dt(w.runtime).label:"",F=((Es=R==null?void 0:R.permissionModes)==null?void 0:Es.denyReason)??!0,$=c.useMemo(()=>Lo(R==null?void 0:R.commandIntents,O),[R,O]),B=c.useRef(null),q=c.useCallback(()=>{var U;return(U=B.current)==null?void 0:U.call(B)},[]),{messages:Y,input:se,setInput:V,handleSubmit:L,submitContent:I,enqueueContent:P,steerContent:Q,addContextContent:ae,status:M,error:W,stop:X,isLoadingHistory:J,hydrated:Z,sessionStatus:K,streamStartTime:le,estimatedTokens:fe,isTextStreaming:me,isWaitingForUser:z,waitingType:he,activeInteraction:ce,pendingInteractions:je,markToolCallResponded:ke,systemStatus:De,operationProgress:Me,promptSuggestions:de,syncConnectionState:Oe,retryMessage:ye,tryNativeCommand:_e,commandPending:be}=nb(e,{transformContent:N,onTaskEvent:A,onSessionIdChangeReplace:k,startFreshSession:E,compactIntent:$,launchRuntime:t,...y&&b?{agentPath:b}:{},agentLookupPending:b!==null&&C,agentLookupFailed:b!==null&&v,takeSeedContext:q,onStreamingDone:c.useCallback(()=>{S("turn-end"),u.invalidateQueries({queryKey:["commands"]})},[S,u])}),Ie=c.useCallback(U=>I(U,{clearInput:!0}),[I]),{permissionMode:qe,permissionModeKnown:re}=Fa(e,K,M==="streaming"),Ce=Du(e,w.runtime,re?qe:void 0),dt=Oc(U=>U.setOpen);c.useEffect(()=>{dt(!1)},[e,dt]);const{handleToolRef:ft,focusedOptionIndex:$e}=db(ce);hb(M,z,me),c.useEffect(()=>{var U;(U=d.current)==null||U.focusUnlessTouch()},[e]);const Xe=c.useCallback(()=>{var U;(U=d.current)==null||U.focusUnlessTouch()},[]);bb({sessionId:e,prompt:n,autoSend:s,input:se,setInput:V,messageCount:Y.length,hydrated:Z,status:M,submitBlocked:_&&b!==null&&(C||v),submit:L,onSeeded:Xe,onConsumed:o});const pe=Cb({sessionId:e,seed:a,messageCount:Y.length,hydrated:Z,onConsumed:o});c.useEffect(()=>{B.current=pe},[pe]);const ge=w.runtime?ls(w.runtime):void 0,{data:Se}=Kc(b,e??void 0,w.runtime??void 0),He=c.useMemo(()=>wx((Se==null?void 0:Se.commands)??[],{commandIntents:R==null?void 0:R.commandIntents,runtimeLabel:O}),[Se,R,O]),{data:Ae}=bm(b),Yo=c.useMemo(()=>Ae!=null&&Ae.files?Fm(Ae.files):[],[Ae]),Xo=pb({input:se,setInput:V,commands:He,fileEntries:Yo}),ys=c.useCallback(()=>{const U=[...Y].reverse().find(ve=>ve.role==="user");U!=null&&U.content&&I(U.content)},[Y,I]),vs=Xt(e??""),Jo=c.useCallback(()=>{const U=Rm(Y,vs);U&&ye(U)},[Y,vs,ye]),ks=M==="idle"&&de.length>0&&se.length===0,Zo=$c("chat.suggestion-chips"),ei=hm(e??""),ti=Sb(M,W,Y,ei),ni=c.useMemo(()=>Y.some(U=>U.role==="user"),[Y]),Cs=c.useCallback(U=>{var ve;V(U),(ve=d.current)==null||ve.focus()},[V]),si=Ra,Ft=Pc(e??""),ln=Ea(e??""),ri=c.useMemo(()=>Fb(Ft,ln),[Ft,ln]),Ss=(As=(Ds=fs(e??""))==null?void 0:Ds.lastError)==null?void 0:As.category,cn=Pm(),js=c.useCallback(()=>{const U=e??"";if(cn.claimedElsewhere(U))return!1;const ve=Im({messages:Y,status:M,lastErrorCategory:Ss,queuedCount:Ft.length,draft:te.getState().getSession(U).input});return ve===null?!1:(cn.claim(U),I(ve),!0)},[Y,M,Ss,Ft.length,e,I,cn]),ai=y?`Message ${en(y)}…`:"Send a message…",oi=Kb({sessionId:e??"",placeholder:ai,submit:Ie,enqueue:P,files:T}),{eligible:_s,allow:ws,notNow:Ns}=df(M==="streaming"),ii=c.useMemo(()=>[{id:"prompt-suggestions",show:ks,render:()=>r.jsx(Uc,{suggestions:de,onChipClick:Cs})},{id:"permission-primer",show:_s,render:()=>r.jsx(uf,{onAllow:ws,onNotNow:Ns})},{id:"read-only-mode",show:Ce.eligible,render:()=>r.jsx(Au,{runtimeLabel:Ce.runtimeLabel,onShown:Ce.markShown,onDismiss:Ce.dismiss})}],[ks,de,Cs,_s,ws,Ns,Ce]),li=Gb({asks:si,status:M,streamStartTime:le,estimatedTokens:fe,permissionMode:qe,isWaitingForUser:z??!1,waitingType:he??"approval",operationProgress:Me,systemStatus:De,activity:x});return r.jsx(St.Root,{surface:"session",capabilities:Qo,target:oi,children:r.jsxs("div",{ref:f,"data-testid":"chat-panel","data-turn-status":M,"data-turn-lifecycle":ln??void 0,className:"flex h-full w-full flex-col",children:[r.jsx(qm,{sessionId:e}),r.jsx(Vm,{startedBy:D,modes:R==null?void 0:R.permissionModes.values}),r.jsx(oy,{messages:Y,sessionId:e,isLoadingHistory:J,hydrated:Z,isTextStreaming:me,activeToolCallId:(ce==null?void 0:ce.toolCallId)??null,onToolRef:ft,focusedOptionIndex:$e,onToolDecided:ke,onRetry:ys,onSigninComplete:js,onChooseModel:h,inputZoneToolCallId:(ce==null?void 0:ce.toolCallId)??null,runtimeLabel:ge,allowsDenyReason:F,...i===void 0?{}:{landOnRow:i},foldFirstPrompt:D!==null}),r.jsx(Hx,{terminalReason:K==null?void 0:K.terminalReason}),r.jsx(St.LiveLane,{state:li,scope:"session"}),r.jsx(Qc,{candidates:ii,ready:Z,name:"session-bottom-slot",className:"px-4 pb-2"}),M==="idle"&&Zo.map(U=>r.jsx(U.component,{},U.id)),r.jsx(vp,{celebration:g.activeCelebration,onComplete:g.clearCelebration}),r.jsx(ex,{tasks:m.tasks,taskMap:m.taskMap,activeForm:m.activeForm,isCollapsed:m.isCollapsed,onToggleCollapse:m.toggleCollapse,celebratingTaskId:g.celebratingTaskId,onCelebrationComplete:g.clearCelebration,statusTimestamps:m.statusTimestamps}),ti&&r.jsx(Vx,{sessionId:e,onRetry:ni?ys:void 0,onSigninComplete:js,onChooseModel:h}),W&&r.jsx(Qb,{error:W,composerAgent:y,onRetry:Jo}),_&&v&&r.jsx("div",{className:"mx-4 mb-2",children:r.jsx(sn,{heading:"Couldn’t check this folder",message:"DorkOS couldn’t tell if an agent owns this folder. Try again.",onRetry:()=>void p()})}),e&&r.jsx(cm,{sessionId:e,onSend:U=>void I(U)}),r.jsx(ty,{chatInputRef:d,input:se,autocomplete:Xo,steerContent:Q,addContextContent:ae,tryNativeCommand:_e,commandPending:be,agentLookupPending:_&&b!==null&&C,agentLookupError:_&&b!==null&&v,status:M,stop:X,setInput:V,sessionId:e??"",sessionStatus:K,waiting:ri,interaction:{active:ce,pendingApprovals:je.filter(U=>U.interactiveType==="approval"),focusedOptionIndex:$e,onToolRef:ft,onToolDecided:ke},sync:{connectionState:Oe}})]})})}function ly(e,t){const n=e===null||t===void 0?null:`${e}:${t}`,s=c.useRef(null),a=c.useCallback(()=>{if(n===null||s.current===n||(s.current=n,t===void 0||e===null))return;const o=Ne.getState().getSession(e).messages;return uo(op(o,t)??t)},[n,t,e]);return n===null?void 0:a}function cy(){const[e]=_t();Bd(e);const{runtime:t,prompt:n,send:s,seed:a,message:o}=ea(),i=Lc(),l=ly(e,o),{data:u}=zc(e,{enabled:!1,select:h=>h.title}),d=_a(e);id(e,{canonical:d===null}),Yc();const f=c.useCallback(()=>{i==null||i({search:h=>({...h,prompt:void 0,send:void 0,seed:void 0}),replace:!0})},[i]);return r.jsxs(r.Fragment,{children:[r.jsx(Bc,{children:u!=null&&u.trim()?u:"Chat"}),r.jsx(iy,{sessionId:e,launchRuntime:t,launchPrompt:n,launchSend:s==="1",launchSeed:a,onLaunchConsumed:f,...l===void 0?{}:{landOnRow:l}})]})}const By=cy;export{By as component};
66
+ ${ve}`),T.clearFiles()}return ve},[T,b]),A=c.useCallback(q=>{m.handleTaskEvent(q);const ve=m.tasks.map(Je=>Je.id===q.task.id?{...Je,...q.task}:Je);g.handleTaskEvent(q,ve)},[m,g]);c.useCallback(q=>{l(q),u.invalidateQueries({queryKey:We.bySession(q)})},[l,u]);const k=c.useCallback(q=>{l(q,{replace:!0}),u.invalidateQueries({queryKey:We.bySession(q)})},[l,u]),E=c.useCallback(q=>{l(crypto.randomUUID(),{continuedFrom:q??void 0,draft:!0})},[l]),w=Sa(e??""),R=Zt(w.runtime),O=w.runtime?Dt(w.runtime).label:"",F=((Es=R==null?void 0:R.permissionModes)==null?void 0:Es.denyReason)??!0,$=c.useMemo(()=>Lo(R==null?void 0:R.commandIntents,O),[R,O]),B=c.useRef(null),U=c.useCallback(()=>{var q;return(q=B.current)==null?void 0:q.call(B)},[]),{messages:Y,input:se,setInput:V,handleSubmit:L,submitContent:I,enqueueContent:P,steerContent:Q,addContextContent:ae,status:M,error:W,stop:X,isLoadingHistory:J,hydrated:Z,sessionStatus:K,streamStartTime:le,estimatedTokens:fe,isTextStreaming:me,isWaitingForUser:z,waitingType:he,activeInteraction:ce,pendingInteractions:je,markToolCallResponded:ke,systemStatus:De,operationProgress:Me,promptSuggestions:de,syncConnectionState:Oe,retryMessage:ye,tryNativeCommand:_e,commandPending:be}=nb(e,{transformContent:N,onTaskEvent:A,onSessionIdChangeReplace:k,startFreshSession:E,compactIntent:$,launchRuntime:t,...y&&b?{agentPath:b}:{},agentLookupPending:b!==null&&C,agentLookupFailed:b!==null&&v,takeSeedContext:U,onStreamingDone:c.useCallback(()=>{S("turn-end"),u.invalidateQueries({queryKey:["commands"]})},[S,u])}),Ie=c.useCallback(q=>I(q,{clearInput:!0}),[I]),{permissionMode:Ue,permissionModeKnown:re}=Fa(e,K,M==="streaming"),Ce=Du(e,w.runtime,re?Ue:void 0),dt=Oc(q=>q.setOpen);c.useEffect(()=>{dt(!1)},[e,dt]);const{handleToolRef:ft,focusedOptionIndex:$e}=db(ce);hb(M,z,me),c.useEffect(()=>{var q;(q=d.current)==null||q.focusUnlessTouch()},[e]);const Xe=c.useCallback(()=>{var q;(q=d.current)==null||q.focusUnlessTouch()},[]);bb({sessionId:e,prompt:n,autoSend:s,input:se,setInput:V,messageCount:Y.length,hydrated:Z,status:M,submitBlocked:_&&b!==null&&(C||v),submit:L,onSeeded:Xe,onConsumed:o});const pe=Cb({sessionId:e,seed:a,messageCount:Y.length,hydrated:Z,onConsumed:o});c.useEffect(()=>{B.current=pe},[pe]);const ge=w.runtime?ls(w.runtime):void 0,{data:Se}=Kc(b,e??void 0,w.runtime??void 0),He=c.useMemo(()=>wx((Se==null?void 0:Se.commands)??[],{commandIntents:R==null?void 0:R.commandIntents,runtimeLabel:O}),[Se,R,O]),{data:Ae}=bm(b),Yo=c.useMemo(()=>Ae!=null&&Ae.files?Fm(Ae.files):[],[Ae]),Xo=pb({input:se,setInput:V,commands:He,fileEntries:Yo}),ys=c.useCallback(()=>{const q=[...Y].reverse().find(ve=>ve.role==="user");q!=null&&q.content&&I(q.content)},[Y,I]),vs=Xt(e??""),Jo=c.useCallback(()=>{const q=Rm(Y,vs);q&&ye(q)},[Y,vs,ye]),ks=M==="idle"&&de.length>0&&se.length===0,Zo=$c("chat.suggestion-chips"),ei=hm(e??""),ti=Sb(M,W,Y,ei),ni=c.useMemo(()=>Y.some(q=>q.role==="user"),[Y]),Cs=c.useCallback(q=>{var ve;V(q),(ve=d.current)==null||ve.focus()},[V]),si=Ra,Ft=Pc(e??""),ln=Ea(e??""),ri=c.useMemo(()=>Fb(Ft,ln),[Ft,ln]),Ss=(As=(Ds=fs(e??""))==null?void 0:Ds.lastError)==null?void 0:As.category,cn=Pm(),js=c.useCallback(()=>{const q=e??"";if(cn.claimedElsewhere(q))return!1;const ve=Im({messages:Y,status:M,lastErrorCategory:Ss,queuedCount:Ft.length,draft:te.getState().getSession(q).input});return ve===null?!1:(cn.claim(q),I(ve),!0)},[Y,M,Ss,Ft.length,e,I,cn]),ai=y?`Message ${en(y)}…`:"Send a message…",oi=Kb({sessionId:e??"",placeholder:ai,submit:Ie,enqueue:P,files:T}),{eligible:_s,allow:ws,notNow:Ns}=df(M==="streaming"),ii=c.useMemo(()=>[{id:"prompt-suggestions",show:ks,render:()=>r.jsx(qc,{suggestions:de,onChipClick:Cs})},{id:"permission-primer",show:_s,render:()=>r.jsx(uf,{onAllow:ws,onNotNow:Ns})},{id:"read-only-mode",show:Ce.eligible,render:()=>r.jsx(Au,{runtimeLabel:Ce.runtimeLabel,onShown:Ce.markShown,onDismiss:Ce.dismiss})}],[ks,de,Cs,_s,ws,Ns,Ce]),li=Gb({asks:si,status:M,streamStartTime:le,estimatedTokens:fe,permissionMode:Ue,isWaitingForUser:z??!1,waitingType:he??"approval",operationProgress:Me,systemStatus:De,activity:x});return r.jsx(St.Root,{surface:"session",capabilities:Qo,target:oi,children:r.jsxs("div",{ref:f,"data-testid":"chat-panel","data-turn-status":M,"data-turn-lifecycle":ln??void 0,className:"flex h-full w-full flex-col",children:[r.jsx(Um,{sessionId:e}),r.jsx(Vm,{startedBy:D,modes:R==null?void 0:R.permissionModes.values}),r.jsx(oy,{messages:Y,sessionId:e,isLoadingHistory:J,hydrated:Z,isTextStreaming:me,activeToolCallId:(ce==null?void 0:ce.toolCallId)??null,onToolRef:ft,focusedOptionIndex:$e,onToolDecided:ke,onRetry:ys,onSigninComplete:js,onChooseModel:h,inputZoneToolCallId:(ce==null?void 0:ce.toolCallId)??null,runtimeLabel:ge,allowsDenyReason:F,...i===void 0?{}:{landOnRow:i},foldFirstPrompt:D!==null}),r.jsx(Hx,{terminalReason:K==null?void 0:K.terminalReason}),r.jsx(St.LiveLane,{state:li,scope:"session"}),r.jsx(Qc,{candidates:ii,ready:Z,name:"session-bottom-slot",className:"px-4 pb-2"}),M==="idle"&&Zo.map(q=>r.jsx(q.component,{},q.id)),r.jsx(vp,{celebration:g.activeCelebration,onComplete:g.clearCelebration}),r.jsx(ex,{tasks:m.tasks,taskMap:m.taskMap,activeForm:m.activeForm,isCollapsed:m.isCollapsed,onToggleCollapse:m.toggleCollapse,celebratingTaskId:g.celebratingTaskId,onCelebrationComplete:g.clearCelebration,statusTimestamps:m.statusTimestamps}),ti&&r.jsx(Vx,{sessionId:e,onRetry:ni?ys:void 0,onSigninComplete:js,onChooseModel:h}),W&&r.jsx(Qb,{error:W,composerAgent:y,onRetry:Jo}),_&&v&&r.jsx("div",{className:"mx-4 mb-2",children:r.jsx(sn,{heading:"Couldn’t check this folder",message:"DorkOS couldn’t tell if an agent owns this folder. Try again.",onRetry:()=>void p()})}),e&&r.jsx(cm,{sessionId:e,onSend:q=>void I(q)}),r.jsx(ty,{chatInputRef:d,input:se,autocomplete:Xo,steerContent:Q,addContextContent:ae,tryNativeCommand:_e,commandPending:be,agentLookupPending:_&&b!==null&&C,agentLookupError:_&&b!==null&&v,status:M,stop:X,setInput:V,sessionId:e??"",sessionStatus:K,waiting:ri,interaction:{active:ce,pendingApprovals:je.filter(q=>q.interactiveType==="approval"),focusedOptionIndex:$e,onToolRef:ft,onToolDecided:ke},sync:{connectionState:Oe}})]})})}function ly(e,t){const n=e===null||t===void 0?null:`${e}:${t}`,s=c.useRef(null),a=c.useCallback(()=>{if(n===null||s.current===n||(s.current=n,t===void 0||e===null))return;const o=Ne.getState().getSession(e).messages;return uo(op(o,t)??t)},[n,t,e]);return n===null?void 0:a}function cy(){const[e]=_t();Bd(e);const{runtime:t,prompt:n,send:s,seed:a,message:o}=ea(),i=Lc(),l=ly(e,o),{data:u}=zc(e,{enabled:!1,select:h=>h.title}),d=_a(e);od(e,{canonical:d===null}),Yc();const f=c.useCallback(()=>{i==null||i({search:h=>({...h,prompt:void 0,send:void 0,seed:void 0}),replace:!0})},[i]);return r.jsxs(r.Fragment,{children:[r.jsx(Bc,{children:u!=null&&u.trim()?u:"Chat"}),r.jsx(iy,{sessionId:e,launchRuntime:t,launchPrompt:n,launchSend:s==="1",launchSeed:a,onLaunchConsumed:f,...l===void 0?{}:{landOnRow:l}})]})}const qy=cy;export{qy as component};