@forsion/unit 2.12.2 → 2.13.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 (204) hide show
  1. package/README.md +61 -0
  2. package/backendWorker.mjs +6 -2
  3. package/main.mjs +987 -495
  4. package/package.json +1 -1
  5. package/release.json +5 -5
  6. package/web/assets/ArtificialView-BSv3Mx5C.js +1 -0
  7. package/web/assets/{AutomationBuilder-sxWdUa0L.js → AutomationBuilder-BuiHtVB-.js} +1 -1
  8. package/web/assets/CalendarConfigView-BJtG6cqN.js +1 -0
  9. package/web/assets/CalendarView-C-FX1RED.js +1 -0
  10. package/web/assets/CapabilityMenu-kx1TIJYN.js +1 -0
  11. package/web/assets/{CheckboxInput-BsaoUHZ0.js → CheckboxInput-eW7xdiRS.js} +1 -1
  12. package/web/assets/Chrome-B77-lQyh.js +1 -0
  13. package/web/assets/{CodeView-j065KtVh.js → CodeView-Df3AiSIi.js} +3 -3
  14. package/web/assets/DashboardGridView-MlO1dpuo.js +17 -0
  15. package/web/assets/{EventCard-BmDQkEj9.js → EventCard-CDmeCbI8.js} +1 -1
  16. package/web/assets/ExcalidrawCanvas-D9vkBh_5.js +1 -0
  17. package/web/assets/{FloatingToc-CENybkAA.js → FloatingToc-tART_jC4.js} +1 -1
  18. package/web/assets/HomepageView-Trqmd3RV.js +1 -0
  19. package/web/assets/ImageStudioPanels-BfCVTnKC.js +3 -0
  20. package/web/assets/ImageStudioView-KJhx0wJk.js +1 -0
  21. package/web/assets/InlineFiles-BHwivGbQ.js +1 -0
  22. package/web/assets/MarkdownBlock--__nPQGh.css +1 -0
  23. package/web/assets/MarkdownBlock-D8LgHFYY.js +58 -0
  24. package/web/assets/ModelPill-DrW2cG0l.js +2 -0
  25. package/web/assets/MuseLibraryView-CW78Uivf.js +2 -0
  26. package/web/assets/{MuseView-d-iBk3sc.js → MuseView-Cb6R_l4i.js} +2 -2
  27. package/web/assets/{PageHistoryPanel-CR-k1AM7.js → PageHistoryPanel-BQs9IWTP.js} +2 -2
  28. package/web/assets/PdfAnnotator-BFTBkxvO.js +505 -0
  29. package/web/assets/PdfAnnotator-C_kglLCA.css +1 -0
  30. package/web/assets/{ProductView-u2aezVsl.js → ProductView-mB-S0j81.js} +1 -1
  31. package/web/assets/RightPanel-BVZeVO3c.js +4 -0
  32. package/web/assets/RunLocationPicker-BE5mxnab.css +1 -0
  33. package/web/assets/RunLocationPicker-CyVa0RJa.js +38 -0
  34. package/web/assets/{SidebarRow-BuSkKH5q.js → SidebarRow-D77yrSLf.js} +1 -1
  35. package/web/assets/{SketchCard-D87GADyG.js → SketchCard-CAAr_cqF.js} +5 -5
  36. package/web/assets/{StudioGuestSurface-BijU_EEb.js → StudioGuestSurface-DthpuVGg.js} +1 -1
  37. package/web/assets/{TodoListView-DPPVpPUn.js → TodoListView-C3ZkMIIf.js} +1 -1
  38. package/web/assets/{Tooltip-DY4ISA-e.js → Tooltip-D9Dt9ZTr.js} +1 -1
  39. package/web/assets/UnifiedPage-C75y-MKT.js +68 -0
  40. package/web/assets/UnifiedPage-CWXc_mo1.css +1 -0
  41. package/web/assets/{amadeus-manual.en-DWaN2fPs.js → amadeus-manual.en-D5wZKuag.js} +3 -3
  42. package/web/assets/{amadeus-manual.zh--7D5TS8X.js → amadeus-manual.zh-Br5fidrj.js} +3 -3
  43. package/web/assets/{appStore-Dg9WALEA.js → appStore-B1ynyt42.js} +186 -120
  44. package/web/assets/appStore-BC_CQv-L.css +1 -0
  45. package/web/assets/{arrow-up-right-CpQs92mu.js → arrow-up-right-R10mR2I6.js} +1 -1
  46. package/web/assets/{astryxBridge-BZhaZPs4.js → astryxBridge-CU_kQTEl.js} +3 -3
  47. package/web/assets/automationListSource-B8EIRmDW.js +1 -0
  48. package/web/assets/book-open-DBJ3dDpw.js +1 -0
  49. package/web/assets/{calendarNavStore-C7fGRpoH.js → calendarNavStore-DGvUlU5N.js} +1 -1
  50. package/web/assets/{canvasPrefs-BeG4oEgP.js → canvasPrefs-DwL_OAAo.js} +1 -1
  51. package/web/assets/chatBoxSurface-Lq-2qfd3.js +1 -0
  52. package/web/assets/{circle-question-mark-WL3vbp-Z.js → circle-question-mark-HPZpZQxd.js} +1 -1
  53. package/web/assets/{circle-x-D7s-M5sB.js → circle-x-BZfe7d6S.js} +1 -1
  54. package/web/assets/{client-BSKpsyAw.js → client-DxGbwZLy.js} +1 -1
  55. package/web/assets/{code-xml-BALV9u_c.js → code-xml-joKQ-qGS.js} +1 -1
  56. package/web/assets/{codeStudioStore-C2mWfm32.js → codeStudioStore-C7rGKlOC.js} +1 -1
  57. package/web/assets/codingNavigation-CZB4v1ZW.css +1 -0
  58. package/web/assets/codingNavigation-CjeWG4xm.js +47 -0
  59. package/web/assets/{create-4xUyKtAF.js → create-BjBRKATq.js} +4 -4
  60. package/web/assets/dashboardSurface-Cojgf_-U.js +1 -0
  61. package/web/assets/{deskCapture-Df701U8L.js → deskCapture-DnGWk1iq.js} +1 -1
  62. package/web/assets/{diff2html-BV-zCH4d.js → diff2html-Cd1rVi_Z.js} +1 -1
  63. package/web/assets/{docx-preview-DW4IyU_Q.js → docx-preview-CK0k1mUD.js} +1 -1
  64. package/web/assets/{emoji-DGaxpCIu.js → emoji-Cjm3bKiF.js} +1 -1
  65. package/web/assets/floatingTocSurface-Dd1pT5j5.js +1 -0
  66. package/web/assets/foldActions-Dm-uAt3L.js +1 -0
  67. package/web/assets/folder-CvZyHIgb.js +1 -0
  68. package/web/assets/{folder-plus-D1TDb7k9.js → folder-plus-BRScGQ9m.js} +1 -1
  69. package/web/assets/gestures-CZQVefU0.js +1 -0
  70. package/web/assets/{hand-Crrw-nSn.js → hand-D3QspKYq.js} +1 -1
  71. package/web/assets/{hard-drive-BbyVSbfP.js → hard-drive-BQsHSala.js} +1 -1
  72. package/web/assets/i18n-ecQQxiMQ.css +1 -0
  73. package/web/assets/i18n.generated-BZRHO2Nc.js +15 -0
  74. package/web/assets/imageStudio--KF9gwHA.css +1 -0
  75. package/web/assets/imageStudio-Cy3_437s.js +2 -0
  76. package/web/assets/{index-CflzrdSt.js → index-0AYHATDX.js} +1 -1
  77. package/web/assets/{index-Dg9oixs4.js → index-1FhRiJ_X.js} +1 -1
  78. package/web/assets/{index-CqyM6tQ0.js → index-4E9nrhwf.js} +1 -1
  79. package/web/assets/{index-Cmr7gVZQ.js → index-8ag1K7AZ.js} +1 -1
  80. package/web/assets/{index-SZ5waGAq.js → index-9BmmlTjY.js} +1 -1
  81. package/web/assets/{index-CzM-C2Sd.js → index-B5GxvbNm.js} +1 -1
  82. package/web/assets/{index-DKhyDkGB.js → index-BPhwi4-v.js} +1 -1
  83. package/web/assets/index-BaRySZ-M.js +1 -0
  84. package/web/assets/{index-Brik2pf9.js → index-BcVGjCAJ.js} +1 -1
  85. package/web/assets/{index-OHi69jDq.js → index-BdZaheMZ.js} +1 -1
  86. package/web/assets/{index-D1f_JwPH.js → index-BgDZGDqt.js} +1 -1
  87. package/web/assets/{index-C6GJulug.js → index-BgtO11q8.js} +1 -1
  88. package/web/assets/{index-CF4RV4mh.js → index-Bh_nLVTc.js} +90 -90
  89. package/web/assets/{index-DjzSBM0U.js → index-BnWj6ggb.js} +1 -1
  90. package/web/assets/{index-BRW82CsP.js → index-Bpc3R3DS.js} +1 -1
  91. package/web/assets/{index-BCZZVJ_w.js → index-C9yo04Ck.js} +1 -1
  92. package/web/assets/{index--drOLtq7.js → index-CcOag8eb.js} +1 -1
  93. package/web/assets/{index-Czu_bbDM.js → index-D0FLFLfh.js} +1 -1
  94. package/web/assets/{index-KL5Rj9kP.js → index-D6mpAJ9S.js} +1 -1
  95. package/web/assets/{index-tAXBa_fN.js → index-DElrDw66.js} +1 -1
  96. package/web/assets/{index-DUWR2nZi.js → index-DJLWTPtq.js} +1 -1
  97. package/web/assets/{index-gPSbFSUn.js → index-DNE_PBJt.js} +1 -1
  98. package/web/assets/index-Dj-PygjB.js +1 -0
  99. package/web/assets/{index-BYsdKR_1.js → index-Dkd-nl1u.js} +1 -1
  100. package/web/assets/{index-C7U6T-k8.js → index-GjLSlygt.js} +1 -1
  101. package/web/assets/{invitePage-lLQ-e0pj.js → invitePage-B4gMvEKi.js} +1 -1
  102. package/web/assets/{ipc-DQOD2UKk.js → ipc-CPhL3bPp.js} +1 -1
  103. package/web/assets/{jszip.min-DZxV9uZ_.js → jszip.min-DAJT9RUA.js} +1 -1
  104. package/web/assets/launchpad-C2c1MSVX.css +1 -0
  105. package/web/assets/{layout-grid-B_pjJwz4.js → layout-grid-DfUfnvDS.js} +1 -1
  106. package/web/assets/{linkFollow-C0_3k_PC.js → linkFollow-C6PHGUxk.js} +5 -5
  107. package/web/assets/{list-tree-DkAJYEXd.js → list-tree-DaGpnIYu.js} +1 -1
  108. package/web/assets/{listFold-BsOVn9UZ.js → listFold-Q_8mh5ZG.js} +1 -1
  109. package/web/assets/{lock-BnGHxjeE.js → lock-DQ_yL4nF.js} +1 -1
  110. package/web/assets/{log-out-DBuMeqik.js → log-out-DFwTeh2X.js} +1 -1
  111. package/web/assets/main-CwqZ_ymb.js +19 -0
  112. package/web/assets/markdownEditorSurface-e_oMhqx-.js +3 -0
  113. package/web/assets/mdMarkStore-DjN4bf1T.js +2 -0
  114. package/web/assets/{mdMarks-Bq7Hl-4C.js → mdMarks-cmL6vzR-.js} +1 -1
  115. package/web/assets/{message-square-plus-BiAZAvcw.js → message-square-plus-CEHkduIL.js} +1 -1
  116. package/web/assets/{messages-BH5MfQdZ.js → messages-CBtmbpur.js} +1 -1
  117. package/web/assets/minus-BUT48dAC.js +1 -0
  118. package/web/assets/mobileEntry-qR7BAROr.js +13 -0
  119. package/web/assets/nativeDownload-CziEyW_p.js +1 -0
  120. package/web/assets/{pageChrome-xLNdFaSg.css → pageChrome-CovzZPdb.css} +1 -1
  121. package/web/assets/pageChrome-DFz_AAzZ.js +1 -0
  122. package/web/assets/{pageTree-CZH2J6cc.js → pageTree-yVO1_fSy.js} +2 -2
  123. package/web/assets/{pen-tool-lkmBqliH.js → pen-tool-uxsFELYC.js} +1 -1
  124. package/web/assets/{pencil-Cvk91P_Z.js → pencil-BSbra1Ra.js} +1 -1
  125. package/web/assets/pluginChat-BMFnf_j2.js +2 -0
  126. package/web/assets/{redo-2-DSi54z4e.js → redo-2-BK5LMNa5.js} +1 -1
  127. package/web/assets/{rotate-ccw-CUlnplr0.js → rotate-ccw-HedfU4na.js} +1 -1
  128. package/web/assets/{sharePage-MM6UpPJ9.js → sharePage-CpzDpuU1.js} +2 -2
  129. package/web/assets/{shareViewer-CDZ8lTdy.js → shareViewer-BwzH2bIs.js} +1 -1
  130. package/web/assets/{star-CwDiGyUW.js → star-CgYon3z4.js} +1 -1
  131. package/web/assets/tableSurface-CmDwnKnd.js +1 -0
  132. package/web/assets/{terminal-DIXogYJY.js → terminal-krsPf1mc.js} +1 -1
  133. package/web/assets/{terminalView-B3aZSsrQ.js → terminalView-4e2_u5_I.js} +1 -1
  134. package/web/assets/theme-C6D3tMGV.css +1 -0
  135. package/web/assets/type-GJYLEhY-.js +1 -0
  136. package/web/assets/{undo-2-tUKCv5Gs.js → undo-2-DCTs4Ro4.js} +1 -1
  137. package/web/assets/{unitAccount-D8lVwaaT.js → unitAccount-D3xjX3cu.js} +1 -1
  138. package/web/assets/{unitBridge-D547ublk.js → unitBridge-D5JcIkAP.js} +1 -1
  139. package/web/assets/{unitCloudTransport-BVF6lVp4.js → unitCloudTransport-B44L3x6M.js} +1 -1
  140. package/web/assets/{unitOwnerAccess-BfnEjsZb.js → unitOwnerAccess-CRUHWGpf.js} +1 -1
  141. package/web/assets/{unitShim-DxetRgmP.js → unitShim-_VzxvdEG.js} +3 -3
  142. package/web/assets/{upload-BbeAsMuD.js → upload-MVVRQtkj.js} +1 -1
  143. package/web/assets/userSpaces-CI4eqEgh.js +1 -0
  144. package/web/assets/viewportLock-BH26xHQO.js +611 -0
  145. package/web/assets/viewportLock-IP1zaVkz.css +1 -0
  146. package/web/assets/{workflow-DuoVRSSX.js → workflow-DzeW9OXR.js} +1 -1
  147. package/web/assets/{zoom-in-hr5bRpDL.js → zoom-in-CovPsw4g.js} +1 -1
  148. package/web/index.html +212 -13
  149. package/web/assets/ArtificialView-B4ESD4iK.js +0 -1
  150. package/web/assets/CalendarConfigView-cCfo_EvZ.js +0 -1
  151. package/web/assets/CalendarView-wgLapctk.js +0 -1
  152. package/web/assets/CapabilityMenu-BQBsM638.js +0 -1
  153. package/web/assets/ChatView-BIUk0OJd.css +0 -1
  154. package/web/assets/ChatView-C-jCJnyS.js +0 -47
  155. package/web/assets/Chrome-CwFiDmre.js +0 -1
  156. package/web/assets/DashboardGridView-DXqe0vPd.js +0 -17
  157. package/web/assets/ExcalidrawCanvas-C3egkikA.js +0 -1
  158. package/web/assets/HomepageView-CRdhjLXu.js +0 -1
  159. package/web/assets/ImageStudioPanels-Dke7xf8E.js +0 -3
  160. package/web/assets/ImageStudioView-g38V8gaj.js +0 -1
  161. package/web/assets/InlineFiles-C_hjvn3u.js +0 -1
  162. package/web/assets/MarkdownBlock-DIjYEhTK.js +0 -56
  163. package/web/assets/ModelPill-BPlgovPo.js +0 -1
  164. package/web/assets/MuseLibraryView-CenyTTim.js +0 -2
  165. package/web/assets/PdfAnnotator-CGzC_o1Q.css +0 -1
  166. package/web/assets/PdfAnnotator-D79ip27w.js +0 -560
  167. package/web/assets/RightPanel-C3OJTIqT.js +0 -4
  168. package/web/assets/RunLocationPicker-BNcZ7KKF.css +0 -1
  169. package/web/assets/RunLocationPicker-CTYXUH2z.js +0 -34
  170. package/web/assets/UnifiedPage-CKNtVD_n.js +0 -57
  171. package/web/assets/UnifiedPage-DX_sTpyZ.css +0 -1
  172. package/web/assets/appStore-Di8LXuJ9.css +0 -1
  173. package/web/assets/automationListSource-DP5xZBxo.js +0 -1
  174. package/web/assets/chatBoxSurface-zvcyfrxE.js +0 -1
  175. package/web/assets/dashboardSurface-CFTH5z4c.js +0 -1
  176. package/web/assets/ellipsis-r1EcXsFq.js +0 -1
  177. package/web/assets/floatingTocSurface-C6RJ6i41.js +0 -1
  178. package/web/assets/foldActions-B7KByFdN.js +0 -1
  179. package/web/assets/folder-DlxnPmWY.js +0 -1
  180. package/web/assets/frame-_xBVYe3P.js +0 -1
  181. package/web/assets/gestures-CkW1Kfs9.js +0 -1
  182. package/web/assets/i18n-D-eU58uw.css +0 -1
  183. package/web/assets/i18n.generated-Bbsz16cl.js +0 -15
  184. package/web/assets/imageStudio-BqbNOvpu.css +0 -1
  185. package/web/assets/imageStudio-C_Rs630L.js +0 -2
  186. package/web/assets/index-BCubCwdT.js +0 -1
  187. package/web/assets/index-DZfZTksa.js +0 -1
  188. package/web/assets/main-Dki8NlsT.js +0 -21
  189. package/web/assets/markdownEditorSurface-B4PeUzed.js +0 -3
  190. package/web/assets/mdMarkStore-CsKl7C8O.js +0 -2
  191. package/web/assets/minus-Cyv1YzOU.js +0 -1
  192. package/web/assets/mobileEntry-Bd_nKr0D.js +0 -13
  193. package/web/assets/nativeDownload-D-f1_L2S.js +0 -1
  194. package/web/assets/pageChrome-C9_azUYW.js +0 -1
  195. package/web/assets/panel-left-rOc8As0s.js +0 -1
  196. package/web/assets/pen-line-m6_HvWZ9.js +0 -1
  197. package/web/assets/sticky-note-BIuPUSOU.js +0 -1
  198. package/web/assets/tableSurface-Y_JBQsuz.js +0 -1
  199. package/web/assets/theme-DfEi_DND.css +0 -1
  200. package/web/assets/type-Cqoabh7H.js +0 -1
  201. package/web/assets/userSpaces-DyyAn7vj.js +0 -1
  202. package/web/assets/viewportLock-C4SX-9PO.js +0 -103
  203. package/web/assets/viewportLock-DYSe7Jsn.css +0 -1
  204. package/web/assets/waves-horizontal-B8ZpHQ5H.js +0 -1
@@ -1,34 +0,0 @@
1
- import{j as e,d as l,t as Te,r as me,u as we,T as jn,R as zn,K as Xo,M as Jo,N as Zo,v as Fa}from"./index-CF4RV4mh.js";import{z as Be,u as P,kN as Qo,k as nt,kO as er,kP as tr,kQ as nr,S as ji,kR as sr,aO as Ot,eN as bi,bQ as ar,bp as Ds,eF as Si,U as ks,au as tt,aI as Xe,aQ as xs,af as An,jY as ir,kS as or,kT as rr,kU as cr,jZ as lr,k4 as ur,k5 as dr,kV as hr,kW as mr,kX as pr,eU as Ft,i as bn,da as nn,dN as En,aa as Wa,ar as es,br as fr,ag as rn,ht as gr,b5 as Mn,cp as xt,A as Ni,a7 as Ci,kY as zi,N as _s,B as Ua,kZ as vr,b3 as Dn,k_ as yr,cH as kr,hh as xr,he as Ba,ck as wr,k$ as jr,g as br,bO as Sr,aK as Nr,dG as Cr,dU as zr,jS as qa,aT as Ar,Z as Er,l0 as Mr,l1 as Rr,l2 as Tr,jx as $r,dJ as Lr,l3 as ts,l4 as Ai,l5 as Ir,l6 as Pr,cd as Ha,cc as Dr,l7 as _r,b8 as Or,l8 as Fr,gG as Wr,l9 as Ur,C as Ei,gL as Va,cm as Dt,cl as Br,H as qr,la as Hr,gJ as wt,lb as Vr,lc as Kr,ld as Wt,kC as cn,bK as Yr,h5 as Gr,le as Ka,n as ns,lf as ln,kA as sn,lg as Mi,lh as Os,jE as Xr,an as Rn,a2 as Ri,bL as Ti,km as Jr,li as Zr,lj as Qr,ge as Fs,lk as ec,o as tc,f as nc,ll as $i,c as sc,e as ac,kg as Li,lm as ic,hp as oc,d4 as Ya,gf as ss,a8 as ws,aG as rc,dA as cc,ln as lc,lo as uc,Y as dc,ab as hc,hG as Ii,dH as Pi,kv as Ga,kw as mc}from"./appStore-Dg9WALEA.js";import{u as Xa,n as Ja}from"./codeStudioStore-C2mWfm32.js";import{a as pc,u as Za,C as fc,h as gc}from"./RightPanel-C3OJTIqT.js";import{t as js,c as vc,g as yc,a as kc}from"./ModelPill-BPlgovPo.js";import{P as Tn}from"./pencil-Cvk91P_Z.js";import{c as xc,D as wc}from"./create-4xUyKtAF.js";import{S as jc,W as bc}from"./approvalText-Cy2UAUAQ.js";import{c as Sc,C as Nc,g as Cc,t as Di,u as zc,A as Ac,m as Ec,d as Mc,S as Rc,P as as,a as Tc,f as _i,b as Oi}from"./SidebarRow-BuSkKH5q.js";import{M as $c}from"./message-square-plus-BiAZAvcw.js";import"./client-BSKpsyAw.js";import{F as $n}from"./folder-DlxnPmWY.js";import{H as Lc}from"./hand-Crrw-nSn.js";import{W as Ic}from"./waves-horizontal-B8ZpHQ5H.js";import{E as Ln}from"./ellipsis-r1EcXsFq.js";import{F as Fi}from"./folder-plus-D1TDb7k9.js";import{i as Pc}from"./ipc-DQOD2UKk.js";import{c as Ws,n as kn}from"./nativeDownload-D-f1_L2S.js";import{a as Dc,S as Wi,I as _c}from"./pageChrome-C9_azUYW.js";const Oc=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h2",key:"tvwodi"}],["path",{d:"M20 8v11a2 2 0 0 1-2 2h-2",key:"1gkqxj"}],["path",{d:"m9 15 3-3 3 3",key:"1pd0qc"}],["path",{d:"M12 12v9",key:"192myk"}]],Fc=Be("archive-restore",Oc);const Wc=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]],bs=Be("archive",Wc);const Uc=[["path",{d:"M2 10v3",key:"1fnikh"}],["path",{d:"M6 6v11",key:"11sgs0"}],["path",{d:"M10 3v18",key:"yhl04a"}],["path",{d:"M14 8v7",key:"3a1oy3"}],["path",{d:"M18 5v13",key:"123xd1"}],["path",{d:"M22 10v3",key:"154ddg"}]],Bc=Be("audio-lines",Uc);const qc=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"m9.5 10.5 5 5",key:"ra9qjz"}],["path",{d:"m14.5 10.5-5 5",key:"l2rkpq"}]],Qa=Be("folder-x",qc);const Hc=[["path",{d:"M13.4 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-7.4",key:"re6nr2"}],["path",{d:"M2 6h4",key:"aawbzj"}],["path",{d:"M2 10h4",key:"l0bgd4"}],["path",{d:"M2 14h4",key:"1gsvsf"}],["path",{d:"M2 18h4",key:"1bu2t1"}],["path",{d:"M21.378 5.626a1 1 0 1 0-3.004-3.004l-5.01 5.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"pqwjuv"}]],Vc=Be("notebook-pen",Hc);const Kc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M9 21V9",key:"1oto5p"}]],Ss=Be("panels-top-left",Kc);const Yc=[["circle",{cx:"11",cy:"4",r:"2",key:"vol9p0"}],["circle",{cx:"18",cy:"8",r:"2",key:"17gozi"}],["circle",{cx:"20",cy:"16",r:"2",key:"1v9bxh"}],["path",{d:"M9 10a5 5 0 0 1 5 5v3.5a3.5 3.5 0 0 1-6.84 1.045Q6.52 17.48 4.46 16.84A3.5 3.5 0 0 1 5.5 10Z",key:"1ydw1z"}]],Gc=Be("paw-print",Yc);const Xc=[["line",{x1:"9",x2:"9",y1:"4",y2:"20",key:"ovs5a5"}],["path",{d:"M4 7c0-1.7 1.3-3 3-3h13",key:"10pag4"}],["path",{d:"M18 20c-1.7 0-3-1.3-3-3V4",key:"1gaosr"}]],Jc=Be("pi",Xc);const Zc=[["path",{d:"M12 17v5",key:"bb1du9"}],["path",{d:"M15 9.34V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H7.89",key:"znwnzq"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M9 9v1.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h11",key:"c9qhm2"}]],Qc=Be("pin-off",Zc);const el=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}],["path",{d:"M12 17h.01",key:"p32p05"}]],tl=Be("shield-question-mark",el);const nl=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"19",x2:"19",y1:"8",y2:"14",key:"1bvyxn"}],["line",{x1:"22",x2:"16",y1:"11",y2:"11",key:"1shjgl"}]],Ui=Be("user-plus",nl);let en=null,is=null;function sl(t){const n=P.getState().tr;return n(`channel.name.${t}`)}function al(t){const n=t.filter(i=>i.enabled&&i.workspace).map(i=>({key:i.workspace,name:sl(i.kind),kind:"channel",channel:i.kind,path:i.workspace,system:!0})),a=P.getState().channelWorkspaces;a.length===n.length&&a.every((i,c)=>i.key===n[c].key&&i.name===n[c].name&&i.channel===n[c].channel)||P.setState({channelWorkspaces:n})}const il=Ws((t,n)=>({channels:[],available:!1,loaded:!1,refresh:async()=>{if(window.tangu?.backendStatus)try{const a=await nr(nt()),o=Array.isArray(a.channels)?a.channels:[];t({channels:o,available:!!a.available,loaded:!0}),al(o)}catch{}},save:async(a,o)=>{await tr(nt(),a,o),await n().refresh()},connect:async a=>{const o=await er(nt(),a);return await n().refresh(),P.getState().refreshSessions(P.getState().cfg),o},disconnect:async(a,o)=>{await Qo(nt(),a,o),await n().refresh()},startPolling:()=>{if(en!=null)return;const a=()=>{P.getState().connState==="ok"&&n().refresh()};en=window.setInterval(a,15e3);let o=P.getState().connState;is=P.subscribe(i=>{i.connState==="ok"&&o!=="ok"&&n().refresh(),o=i.connState}),a()},stopPolling:()=>{en!=null&&(window.clearInterval(en),en=null),is?.(),is=null}})),ol=({size:t})=>e.jsx("svg",{width:t,height:t,viewBox:"0 0 14 14",fill:"currentColor","aria-hidden":"true",children:e.jsx("path",{d:"M10.931 3.34a.112.112 0 0 0-.069-.104l-.038-.007c-1.537.05-2.45.318-3.714 1.002v6.683c.48-.248.936-.44 1.414-.58.695-.203 1.417-.292 2.303-.305l.038-.008a.113.113 0 0 0 .066-.104V3.341ZM2.363 9.919c0 .064.051.11.105.111l.33.008c1.162.046 2.042.243 2.975.662-.403-.585-1.008-1.075-1.654-1.292a.991.991 0 0 1-.674-.941v-5.14a6.36 6.36 0 0 0-.59-.076l-.37-.02a.115.115 0 0 0-.122.111v6.577Zm9.455-.001a.998.998 0 0 1-.877.992l-.101.007c-.832.012-1.47.095-2.066.27-.599.174-1.176.448-1.883.863a.444.444 0 0 1-.449 0c-1.299-.763-2.229-1.07-3.689-1.125l-.299-.008a.997.997 0 0 1-.977-.998V3.342c0-.573.478-1.017 1.038-.999l.417.023c.188.015.35.037.513.062v-.754c0-.708.749-1.244 1.429-.903.984.492 1.836 1.449 2.15 2.505 1.216-.617 2.222-.884 3.771-.934l.105.003a.998.998 0 0 1 .918.996v6.576ZM4.332 8.466c0 .049.03.087.07.1l.24.091a4.319 4.319 0 0 1 1.581 1.176V3.721c-.164-.803-.799-1.617-1.584-2.07l-.162-.088c-.025-.012-.054-.013-.088.009a.12.12 0 0 0-.057.102v6.792Z"})}),rl=({size:t})=>e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:e.jsx("path",{d:"m4.7144 15.9555 4.7174-2.6471.079-.2307-.079-.1275h-.2307l-.7893-.0486-2.6956-.0729-2.3375-.0971-2.2646-.1214-.5707-.1215-.5343-.7042.0546-.3522.4797-.3218.686.0608 1.5179.1032 2.2767.1578 1.6514.0972 2.4468.255h.3886l.0546-.1579-.1336-.0971-.1032-.0972L6.973 9.8356l-2.55-1.6879-1.3356-.9714-.7225-.4918-.3643-.4614-.1578-1.0078.6557-.7225.8803.0607.2246.0607.8925.686 1.9064 1.4754 2.4893 1.8336.3643.3035.1457-.1032.0182-.0728-.164-.2733-1.3539-2.4467-1.445-2.4893-.6435-1.032-.17-.6194c-.0607-.255-.1032-.4674-.1032-.7285L6.287.1335 6.6997 0l.9957.1336.419.3642.6192 1.4147 1.0018 2.2282 1.5543 3.0296.4553.8985.2429.8318.091.255h.1579v-.1457l.1275-1.706.2368-2.0947.2307-2.6957.0789-.7589.3764-.9107.7468-.4918.5828.2793.4797.686-.0668.4433-.2853 1.8517-.5586 2.9021-.3643 1.9429h.2125l.2429-.2429.9835-1.3053 1.6514-2.0643.7286-.8196.85-.9046.5464-.4311h1.0321l.759 1.1293-.34 1.1657-1.0625 1.3478-.8804 1.1414-1.2628 1.7-.7893 1.36.0729.1093.1882-.0183 2.8535-.607 1.5421-.2794 1.8396-.3157.8318.3886.091.3946-.3278.8075-1.967.4857-2.3072.4614-3.4364.8136-.0425.0304.0486.0607 1.5482.1457.6618.0364h1.621l3.0175.2247.7892.522.4736.6376-.079.4857-1.2142.6193-1.6393-.3886-3.825-.9107-1.3113-.3279h-.1822v.1093l1.0929 1.0686 2.0035 1.8092 2.5075 2.3314.1275.5768-.3218.4554-.34-.0486-2.2039-1.6575-.85-.7468-1.9246-1.621h-.1275v.17l.4432.6496 2.3436 3.5214.1214 1.0807-.17.3521-.6071.2125-.6679-.1214-1.3721-1.9246L14.38 17.959l-1.1414-1.9428-.1397.079-.674 7.2552-.3156.3703-.7286.2793-.6071-.4614-.3218-.7468.3218-1.4753.3886-1.9246.3157-1.53.2853-1.9004.17-.6314-.0121-.0425-.1397.0182-1.4328 1.9672-2.1796 2.9446-1.7243 1.8456-.4128.164-.7164-.3704.0667-.6618.4008-.5889 2.386-3.0357 1.4389-1.882.929-1.0868-.0062-.1579h-.0546l-6.3385 4.1164-1.1293.1457-.4857-.4554.0608-.7467.2307-.2429 1.9064-1.3114Z"})}),ei=({engineId:t,size:n=16})=>{const a=t.toLowerCase();return a.includes("claude")?e.jsx(rl,{size:n}):a.includes("codex")||a.includes("openai")?e.jsx(ol,{size:n}):a.includes("claw")?e.jsx(Gc,{size:n}):a==="pi"||a.startsWith("pi-")?e.jsx(Jc,{size:n}):a.includes("dsh")||a.includes("deepseek")?e.jsx(Ic,{size:n}):e.jsx(ji,{size:n})},cl="forsion_realtime_cfg_rev";let Sn={model:"",voice:""},ti=!1;const Ns=new Set;function os(){window.tangu?.getConfig?.().then(t=>{const n={model:t.realtimeModelId?.trim()||"",voice:t.realtimeVoice?.trim()||""};n.model===Sn.model&&n.voice===Sn.voice||(Sn=n,Ns.forEach(a=>a()))}).catch(()=>{})}function ll(){return l.useSyncExternalStore(t=>(ti||(ti=!0,os(),window.addEventListener("storage",n=>{n.key===cl&&os()}),window.addEventListener("focus",os)),Ns.add(t),()=>{Ns.delete(t)}),()=>Sn)}const Bi="forsion_voice_call_evt";function ul(t){try{localStorage.setItem(Bi,JSON.stringify({...t,n:`${Date.now()}-${Math.random()}`}))}catch{}}const In="forsion_voice_call_active",Nn=new Set;let ni=!1;function dl(t){try{t?localStorage.setItem(In,t):localStorage.removeItem(In)}catch{}Nn.forEach(n=>n())}function qi(){try{return localStorage.getItem(In)}catch{return null}}function hl(t){return ni||(ni=!0,window.addEventListener("storage",n=>{(n.key===In||n.key===null)&&Nn.forEach(a=>a())})),Nn.add(t),()=>{Nn.delete(t)}}const ml=4e3,jd=1500;function pl(t,n,a=2e3){const o=`${Date.now()}-${Math.random()}`;return new Promise(i=>{const c=Hi(u=>{u.kind==="text-ack"&&u.id===o&&(c(),clearTimeout(r),i(!0))}),r=setTimeout(()=>{c(),qi()===t&&dl(null),i(!1)},a);ul({kind:"text",sessionId:t,text:n,id:o,at:Date.now()})})}function Hi(t){const n=a=>{if(!(a.key!==Bi||!a.newValue))try{t(JSON.parse(a.newValue))}catch{}};return window.addEventListener("storage",n),()=>window.removeEventListener("storage",n)}const fl=.04,si=24e3;let Ne=null,Cs=null;const zs=new Set;let Cn=null,Ut=null;const As=()=>zs.forEach(t=>t()),Vi=t=>{Ne&&(Ne={...Ne,...t},As())};function bd(t){return zs.add(t),()=>{zs.delete(t)}}const Sd=()=>Ne,Nd=()=>Cs;function gl(t){Cn?.(t)}function Cd(){Ne&&Vi({muted:!Ne.muted})}const zd=t=>Ut?.mic(t)??Promise.resolve(),Ad=t=>Ut?.speaker(t)??Promise.resolve(),Ed=t=>Ut?.run(t),Md=t=>Ut?.text(t)??!1;async function Rd(t){Ne&&gl(),Cs=null,Ne={sessionId:t.sessionId,phase:"connecting",muted:!1,working:null,analyser:null,connectedAt:null},As();let n=null,a=null;const o=new AudioContext({sampleRate:16e3}),i=new AudioContext({sampleRate:si}),c=o.createAnalyser(),r=i.createAnalyser();r.connect(i.destination);const u=new Set;let d=0,h=!1,f=null,k=null;const x=z=>({echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1,...z?{deviceId:z}:{}}),T=()=>{f=o.createMediaStreamSource(n),f.connect(c),k&&f.connect(k)},M=z=>(i.setSinkId?.(z)??Promise.resolve()).catch(S=>console.warn("[realtime] setSinkId failed:",S)),A=z=>{h||Vi(z)},I=(z=500)=>{t.onActivity&&window.setTimeout(t.onActivity,z)},U=()=>{u.forEach(z=>{try{z.stop()}catch{}}),u.clear(),d=0},_=z=>{const S=new Int16Array(z,0,z.byteLength>>1);if(!S.length)return;const g=i.createBuffer(1,S.length,si),F=g.getChannelData(0);for(let O=0;O<S.length;O++)F[O]=S[O]/32768;const H=i.createBufferSource();H.buffer=g,H.connect(r);const W=Math.max(i.currentTime+.05,d);H.start(W),d=W+g.duration,u.add(H),H.onended=()=>{u.delete(H),!u.size&&Ne?.phase==="speaking"&&A({phase:"listening",analyser:c})},Ne?.phase!=="speaking"&&A({phase:"speaking",analyser:r})},D=z=>{if(h)return;h=!0;const S=Cn===D;S&&(Cn=null),U();try{a?.close()}catch{}n?.getTracks().forEach(g=>g.stop()),o.close().catch(()=>{}),i.close().catch(()=>{}),S&&(Ut=null,Cs=z||null,Ne=null,As()),I(300)};Cn=D,Ut={mic:async z=>{const S=await navigator.mediaDevices.getUserMedia({audio:x(z)});if(h){S.getTracks().forEach(g=>g.stop());return}f?.disconnect(),n?.getTracks().forEach(g=>g.stop()),n=S,f&&T()},speaker:M,run:z=>{t.run=z,a?.readyState===WebSocket.OPEN&&a.send(JSON.stringify({type:"run",run:z}))},text:z=>h||!Ne?.connectedAt||Ne.phase==="reconnecting"||a?.readyState!==WebSocket.OPEN?!1:(U(),A({phase:"thinking",analyser:c}),a.send(JSON.stringify({type:"text",text:z})),I(),!0)};try{if(n=await navigator.mediaDevices.getUserMedia({audio:x(t.micId)}),h){n.getTracks().forEach(S=>S.stop());return}t.speakerId&&await M(t.speakerId);const z=await sr(t.target);if(h)return;a=new WebSocket(z),a.binaryType="arraybuffer"}catch(z){D(z?.message||String(z));return}const w=a;w.onopen=()=>w.send(JSON.stringify({type:"start",session_id:t.sessionId,model:t.model,voice:t.voice||void 0,title:t.title,run:t.run})),w.onclose=z=>D(z.reason||(z.code===1e3?void 0:`connection closed (${z.code})`)),w.onmessage=z=>{if(h)return;if(z.data instanceof ArrayBuffer){_(z.data);return}let S;try{S=JSON.parse(String(z.data))}catch{return}switch(S.type){case"ready":{if(k){A(u.size?{phase:"speaking",analyser:r}:{phase:"listening",analyser:c});break}k=o.createScriptProcessor(1024,1,1),k.connect(o.destination),k.onaudioprocess=g=>{if(h||!Ne||Ne.muted||w.readyState!==WebSocket.OPEN)return;const F=g.inputBuffer.getChannelData(0);let H=0;for(let E=0;E<F.length;E++)H+=F[E]*F[E];const W=u.size>0&&Math.sqrt(H/F.length)<fl,O=new Int16Array(F.length);if(!W)for(let E=0;E<F.length;E++)O[E]=Math.max(-32768,Math.min(32767,Math.round(F[E]*32767)));w.send(O.buffer)},T(),A({phase:"listening",analyser:c,connectedAt:Date.now()});break}case"input_audio_buffer.speech_started":U(),A({phase:"hearing",analyser:c});break;case"input_audio_buffer.speech_stopped":A({phase:"thinking"});break;case"conversation.item.input_audio_transcription.completed":case"response.audio_transcript.done":I();break;case"response.done":!u.size&&Ne?.phase==="thinking"&&S.response?.status!=="completed"&&A({phase:"listening",analyser:c});break;case"transcript.corrected":typeof S.message_id=="string"&&typeof S.text=="string"&&t.onTranscriptFix?.(S.message_id,S.text);break;case"tangu.run":A({working:S.status==="started"?String(S.task||""):null}),I(S.status==="started"?300:800);break;case"error":console.warn("[realtime] upstream error:",S.error?.message||S.error);break;case"reconnecting":S.replay&&U(),A({phase:"reconnecting"});break;case"end":D(S.reason&&S.reason!=="client closed"?String(S.reason):void 0);break}}}me({"voiceinput.silent":{zh:"没采集到声音(输入电平≈0):检查系统输入设备是否选对、麦克风没被静音",en:"No audio captured (input level ≈ 0): check that the right input device is selected and that the microphone is not muted"},"voiceinput.unsupported":{zh:"此环境不支持语音输入",en:"Voice input is not supported in this environment"},"voiceinput.denied":{zh:"麦克风权限被拒绝(打开 系统设置 › 隐私与安全 › 麦克风,允许本 App)",en:"Microphone access was denied (open System Settings › Privacy & Security › Microphone and allow this app)"},"voiceinput.noDevice":{zh:"没检测到麦克风设备",en:"No microphone found"},"voiceinput.openFailed":{zh:"麦克风打不开:{e}",en:"Could not open the microphone: {e}"},"voiceinput.unclear":{zh:"没听清,再试一次",en:"Didn't catch that — try again"}});async function vl(t){const n=await t.arrayBuffer(),a=new AudioContext,o=await a.decodeAudioData(n);await a.close();const i=Math.max(1,Math.round(o.duration*16e3)),c=new OfflineAudioContext(1,i,16e3),r=c.createBufferSource();r.buffer=o,r.connect(c.destination),r.start();const u=(await c.startRendering()).getChannelData(0);let d=0,h=0;for(let f=0;f<u.length;f++){const k=Math.abs(u[f]);k>d&&(d=k),h+=u[f]*u[f]}if(console.warn(`[voice] captured ${u.length} samples @16k, ${(u.length/16e3).toFixed(2)}s, peak=${d.toFixed(4)} rms=${Math.sqrt(h/(u.length||1)).toFixed(4)}`),d<.005)throw new Error(Te("voiceinput.silent"));return yl(u,16e3)}function yl(t,n){const a=t.length,o=new ArrayBuffer(44+a*2),i=new DataView(o),c=(h,f)=>{for(let k=0;k<f.length;k++)i.setUint8(h+k,f.charCodeAt(k))};c(0,"RIFF"),i.setUint32(4,36+a*2,!0),c(8,"WAVE"),c(12,"fmt "),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,1,!0),i.setUint32(24,n,!0),i.setUint32(28,n*2,!0),i.setUint16(32,2,!0),i.setUint16(34,16,!0),c(36,"data"),i.setUint32(40,a*2,!0);for(let h=0;h<a;h++){const f=Math.max(-1,Math.min(1,t[h]));i.setInt16(44+h*2,f<0?f*32768:f*32767,!0)}const r=new Uint8Array(o);let u="";const d=32768;for(let h=0;h<r.length;h+=d)u+=String.fromCharCode(...r.subarray(h,h+d));return btoa(u)}function kl(t,n){const[a,o]=l.useState(!1),[i,c]=l.useState(!1),[r,u]=l.useState(null),d=l.useRef(null),h=l.useRef([]),f=l.useRef(!1),[k,x]=l.useState(null),T=l.useRef(null),M=l.useCallback(()=>{x(null),T.current?.close().catch(()=>{}),T.current=null},[]);l.useEffect(()=>M,[M]);const A=typeof navigator<"u"&&!!navigator.mediaDevices?.getUserMedia&&typeof MediaRecorder<"u"&&!!window.tangu?.transcribeAudio,I=l.useCallback(w=>{f.current=w,d.current?.stop()},[]),U=l.useCallback(async()=>{if(u(null),!A){u(Te("voiceinput.unsupported"));return}let w;try{w=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(S){console.warn("[voice] getUserMedia failed:",S?.name,S?.message||S),u(S?.name==="NotAllowedError"?Te("voiceinput.denied"):S?.name==="NotFoundError"?Te("voiceinput.noDevice"):Te("voiceinput.openFailed",{e:S?.name||S?.message||S}));return}try{const S=new AudioContext,g=S.createAnalyser();g.fftSize=128,g.smoothingTimeConstant=.7,S.createMediaStreamSource(w).connect(g),T.current=S,x(g)}catch{}const z=new MediaRecorder(w);d.current=z,h.current=[],f.current=!1,z.ondataavailable=S=>{S.data.size&&h.current.push(S.data)},z.onstop=async()=>{if(w.getTracks().forEach(g=>g.stop()),M(),o(!1),d.current=null,f.current||!h.current.length)return;const S=new Blob(h.current,{type:z.mimeType||"audio/webm"});c(!0);try{const g=await window.tangu.transcribeAudio({audioBase64:await vl(S),mime:"audio/wav",modelId:n});g?t(g):u(Te("voiceinput.unclear"))}catch(g){console.warn("[voice] transcribe failed:",g?.message||g),u(g?.message||String(g))}finally{c(!1)}},z.start(),o(!0)},[A,n,t,M]),_=l.useCallback(()=>{i||(a?I(!1):U())},[i,a,U,I]),D=l.useCallback(()=>{a&&I(!0)},[a,I]);return{recording:a,busy:i,error:r,toggle:_,cancel:D,supported:A,analyser:k}}const ai=40,ii=.1,xl=3.2;function wl({analyser:t,recording:n,busy:a,onStop:o,onSend:i,status:c,stopTitle:r,t:u}){const d=l.useRef(null),[h,f]=l.useState(0),k=l.useRef(0);l.useEffect(()=>{if(!n)return;k.current=Date.now(),f(0);const T=window.setInterval(()=>f(Math.floor((Date.now()-k.current)/1e3)),250);return()=>window.clearInterval(T)},[n]),l.useEffect(()=>{const T=d.current;if(!t||!n||!T)return;const M=T.getContext("2d");if(!M)return;const A=window.devicePixelRatio||1;T.width=Math.max(1,T.clientWidth)*A,T.height=Math.max(1,T.clientHeight)*A,M.setTransform(A,0,0,A,0,0);const I=getComputedStyle(document.documentElement),U=(I.getPropertyValue("--accent-ink")||I.getPropertyValue("--accent")||"#7c3aed").trim(),_=(I.getPropertyValue("--border")||"rgba(127,127,127,0.4)").trim(),D=new Uint8Array(t.fftSize),w=[];let z=Date.now(),S=0;const g=()=>{S=requestAnimationFrame(g);const F=Date.now();t.getByteTimeDomainData(D);let H=0;for(let X=0;X<D.length;X++){const J=(D[X]-128)/128;H+=J*J}const W=Math.min(1,Math.sqrt(H/D.length)*xl);for(;F-z>=ai;)w.push({t:z,level:W}),z+=ai;const O=T.clientWidth,E=T.clientHeight,G=E/2;for(M.clearRect(0,0,O,E),M.strokeStyle=_,M.lineWidth=1,M.setLineDash([2,3]),M.beginPath(),M.moveTo(0,G),M.lineTo(O,G),M.stroke(),M.setLineDash([]);w.length&&O-(F-w[0].t)*ii<-4;)w.shift();M.fillStyle=U;for(const X of w){const J=O-(F-X.t)*ii;if(J<-4||J>O)continue;const ee=Math.max(2,X.level*(E-4));M.globalAlpha=J<O*.15?Math.max(0,J/(O*.15)):1,M.beginPath(),M.roundRect(J-1.1,G-ee/2,2.2,ee,1.1),M.fill()}M.globalAlpha=1};return g(),()=>cancelAnimationFrame(S)},[t,n]);const x=`${Math.floor(h/60)}:${String(h%60).padStart(2,"0")}`;return a?e.jsxs("div",{className:"t2c-voicebar",children:[e.jsx(Ot,{size:14,className:"spin"}),e.jsx("span",{className:"t2c-voicelabel",children:u("input.micBusy")}),e.jsx("span",{className:"t2c-grow"})]}):e.jsxs("div",{className:"t2c-voicebar",children:[e.jsx("canvas",{ref:d,className:"t2c-voicewave"}),e.jsx("span",{className:"t2c-voicetime",children:c??x}),e.jsx("button",{className:"t2c-voicestop",title:r??u("input.micStop"),onClick:o,children:e.jsx(bi,{size:12})}),i&&e.jsx("button",{className:"t2c-send",title:u("input.send"),onClick:i,children:e.jsx(ar,{size:16})})]})}me({"ultraConfirm.title":{zh:"开启 Ultra?",en:"Turn on Ultra?"},"ultraConfirm.msg":{zh:"Ultra 会把思考拉满、上下文用到模型支持的上限,并主动把能并行的活拆给多个子代理同时做。一次任务的 token 消耗可能是平时的数倍,适合大任务。",en:"Ultra maxes out thinking, uses the model's full context window, and proactively splits parallelizable work across several subagents. One task can use several times the usual tokens, so it suits big jobs."},"ultraConfirm.recommend":{zh:"推荐配合「完全放行」使用:多个子代理并行时,每个需要确认的操作都会停下来等你批准。",en:"Full access is recommended: with several subagents running in parallel, every action that needs approval stops and waits for you."},"ultraConfirm.fullAccess":{zh:"同时把本会话切到「完全放行」",en:"Also switch this session to Full access"},"ultraConfirm.skip":{zh:"以后不再显示",en:"Don't show this again"},"ultraConfirm.confirm":{zh:"开启 Ultra",en:"Turn on Ultra"}});const Ki="forsion_ultra_confirm_off";function jl(){try{return localStorage.getItem(Ki)==="1"}catch{return!1}}function bl({offerFullAccess:t,onConfirm:n,onClose:a}){const{t:o}=we(),[i,c]=l.useState(!1),[r,u]=l.useState(!1),d=l.useRef(typeof document<"u"?document.activeElement:null);l.useEffect(()=>()=>{const f=d.current;f?.isConnected&&typeof f.focus=="function"&&f.focus({preventScroll:!0})},[]);const h=f=>{if(f.key!=="Tab")return;const k=f.currentTarget.querySelector(".dialog"),x=k?[...k.querySelectorAll('button, input, [tabindex]:not([tabindex="-1"])')].filter(A=>!A.disabled):[];if(!x.length)return;const T=x[0],M=x[x.length-1];f.shiftKey&&document.activeElement===T?(f.preventDefault(),M.focus()):!f.shiftKey&&document.activeElement===M&&(f.preventDefault(),T.focus())};return Ds.createPortal(e.jsx("div",{className:"am-app tangu-lovable",style:{display:"contents"},"data-ultra-confirm":!0,"data-keep-menus":!0,onKeyDown:h,children:e.jsxs(Si,{title:o("ultraConfirm.title"),message:o("ultraConfirm.msg"),confirmLabel:o("ultraConfirm.confirm"),danger:!1,onConfirm:()=>{if(r)try{localStorage.setItem(Ki,"1")}catch{}n({fullAccess:t&&i})},onClose:a,children:[t&&e.jsx("div",{className:"dialog-msg",children:o("ultraConfirm.recommend")}),t&&e.jsxs("label",{className:"dialog-check","data-ultra-full-access":!0,children:[e.jsx("input",{type:"checkbox",checked:i,onChange:f=>c(f.target.checked)}),e.jsx("span",{children:o("ultraConfirm.fullAccess")})]}),e.jsxs("label",{className:"dialog-check","data-ultra-skip":!0,children:[e.jsx("input",{type:"checkbox",checked:r,onChange:f=>u(f.target.checked)}),e.jsx("span",{children:o("ultraConfirm.skip")})]})]})}),document.body)}me({"session.untitled":{zh:"新会话",en:"New session"},"session.rootlessGroup":{zh:"无项目会话",en:"No project"}});const Sl="New Chat";function _t(t,n){const a=(t||"").trim();return!a||a===Sl?n("session.untitled"):t}function rs(t,n){return t.kind==="rootless"?n("session.rootlessGroup"):t.name}me({"group.setup.selfPacedHint":{zh:"发消息后成员同时开工,可相互 @ 交接;每位成员自己决定何时收尾,全员完成即结束,没有轮数上限。",en:"After you send, members work in parallel and can @-mention each other; each decides when they are done, and the team stops once everyone is — no round limit."}});const Nl=()=>({name:"",description:"",model:"",systemPrompt:"",thinkingLevel:"",maxIterations:"",approvalMode:""}),Cl=()=>`temp-${Date.now().toString(36)}-${Math.floor(Math.random()*46656).toString(36)}`,zl=({agents:t,models:n,initialAgents:a,initialTempAgents:o,active:i,hideDisable:c,onConfirm:r,onDisable:u,onClose:d})=>{const{t:h}=we(),f=l.useMemo(()=>new Set(t.map(g=>g.slug)),[t]),[k,x]=l.useState(()=>a.filter(g=>f.has(g))),[T,M]=l.useState(o||[]),[A,I]=l.useState(null),U=l.useMemo(()=>(n||[]).map(g=>({id:g.id,label:g.name||g.id})),[n]),D=k.length+T.length>=2,w=g=>x(F=>F.includes(g)?F.filter(H=>H!==g):[...F,g]),z=()=>{if(!A||!A.name.trim()||!A.systemPrompt.trim())return;const g=A.slug||Cl(),F={slug:g,name:A.name.trim(),description:A.description.trim(),model:A.model,tools:[],thinkingLevel:A.thinkingLevel,maxIterations:A.maxIterations?Number(A.maxIterations):null,approvalMode:A.approvalMode,createdBy:"user",createdAt:"",systemPrompt:A.systemPrompt.trim()};M(H=>{const W=H.findIndex(O=>O.slug===g);if(W>=0){const O=H.slice();return O[W]=F,O}return[...H,F]}),I(null)},S=()=>{D&&r({groupAgents:[...k,...T.map(g=>g.slug)],groupTempAgents:T})};return e.jsx("div",{onClick:d,style:{position:"fixed",inset:0,background:"var(--overlay-scrim)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:e.jsxs("div",{"data-team-setup":!0,onClick:g=>g.stopPropagation(),style:{width:480,maxWidth:"92vw",maxHeight:"86vh",overflow:"auto",borderRadius:"var(--radius-md, 12px)",background:"var(--bg)",color:"var(--text)",border:"1px solid var(--border)",boxShadow:"var(--card-shadow)",padding:18},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:6},children:[e.jsx(ks,{size:18}),e.jsx("strong",{style:{fontSize:"var(--ui-font-heading, 14px)",flex:1},children:h("group.setup.title")}),e.jsx("button",{className:"icon-btn",onClick:d,title:h("group.setup.close"),children:e.jsx(tt,{size:16})})]}),A?e.jsxs("div",{className:"field",children:[e.jsx("div",{className:"hint",style:{marginBottom:8},children:h("group.setup.tempFormHint")}),e.jsxs("div",{className:"field",children:[e.jsx("label",{children:h("settings.agents.name")}),e.jsx("input",{type:"text",value:A.name,placeholder:h("settings.agents.namePlaceholder"),onChange:g=>I({...A,name:g.target.value})})]}),e.jsxs("div",{className:"field",children:[e.jsx("label",{children:h("settings.agents.desc")}),e.jsx("input",{type:"text",value:A.description,onChange:g=>I({...A,description:g.target.value})})]}),e.jsxs("div",{className:"field",children:[e.jsx("label",{children:h("settings.agents.model")}),e.jsxs("select",{value:A.model,onChange:g=>I({...A,model:g.target.value}),children:[e.jsx("option",{value:"",children:h("settings.agents.modelDefault")}),U.map(g=>e.jsx("option",{value:g.id,children:g.label},g.id))]})]}),e.jsxs("div",{className:"field",children:[e.jsx("label",{children:h("settings.agents.systemPrompt")}),e.jsx("textarea",{rows:6,value:A.systemPrompt,placeholder:h("settings.agents.systemPromptPlaceholder"),onChange:g=>I({...A,systemPrompt:g.target.value})})]}),e.jsxs("div",{className:"field-row",children:[e.jsxs("div",{className:"field",children:[e.jsx("label",{children:h("settings.agents.thinking")}),e.jsxs("select",{value:A.thinkingLevel,onChange:g=>I({...A,thinkingLevel:g.target.value}),children:[e.jsx("option",{value:"",children:h("settings.agents.inherit")}),jn.map(g=>e.jsx("option",{value:g,children:js(g,h)},g))]})]}),e.jsxs("div",{className:"field",children:[e.jsx("label",{children:h("settings.agents.maxIter")}),e.jsx("input",{type:"number",min:10,max:200,value:A.maxIterations,onChange:g=>I({...A,maxIterations:g.target.value})})]}),e.jsxs("div",{className:"field",children:[e.jsx("label",{children:h("settings.agents.approval")}),e.jsxs("select",{value:A.approvalMode,onChange:g=>I({...A,approvalMode:g.target.value}),children:[e.jsx("option",{value:"",children:h("settings.agents.inherit")}),e.jsx("option",{value:"readonly",children:"readonly"}),e.jsx("option",{value:"auto-edit",children:"auto-edit"}),e.jsx("option",{value:"full-auto",children:"full-auto"}),e.jsx("option",{value:"custom",children:"custom"})]})]})]}),e.jsxs("div",{style:{display:"flex",gap:8},children:[e.jsxs("button",{className:"btn primary sm",disabled:!A.name.trim()||!A.systemPrompt.trim(),onClick:z,children:[e.jsx(Xe,{size:13})," ",h("group.setup.tempSave")]}),e.jsx("button",{className:"btn ghost sm",onClick:()=>I(null),children:h("group.setup.close")})]})]}):e.jsxs(e.Fragment,{children:[t.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{fontSize:"var(--ui-font-meta, 12px)",fontWeight:600,margin:"8px 0 6px",color:"var(--text-dim)"},children:h("group.setup.savedAgents")}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4,marginBottom:12},children:t.map(g=>{const F=k.includes(g.slug);return e.jsxs("button",{onClick:()=>w(g.slug),style:{display:"flex",alignItems:"center",gap:10,textAlign:"left",padding:"8px 10px",borderRadius:"var(--radius-sm, 6px)",border:`1px solid ${F?"var(--accent-ink)":"var(--border)"}`,background:F?"var(--accent-soft)":"transparent",color:"inherit",cursor:"pointer"},children:[e.jsx("span",{style:{width:16,height:16,borderRadius:4,flexShrink:0,display:"inline-flex",alignItems:"center",justifyContent:"center",border:`1px solid ${F?"var(--accent-ink)":"var(--border)"}`,background:F?"var(--accent-ink)":"transparent"},children:F&&e.jsx(Xe,{size:12,color:"var(--on-accent-ink, var(--on-accent))"})}),e.jsxs("span",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontSize:"var(--ui-font-body, 13px)",fontWeight:600},children:g.name}),g.description&&e.jsx("div",{style:{fontSize:"var(--ui-font-caption, 11px)",color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:g.description})]})]},g.slug)})})]}),e.jsx("div",{style:{fontSize:"var(--ui-font-meta, 12px)",fontWeight:600,margin:"8px 0 6px",color:"var(--text-dim)"},children:h("group.setup.tempAgents")}),T.length>0&&e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4,marginBottom:8},children:T.map(g=>e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"8px 10px",borderRadius:"var(--radius-sm, 6px)",border:"1px solid var(--accent-ink)",background:"var(--accent-soft)"},children:[e.jsx(Ui,{size:14,style:{flexShrink:0,opacity:.8}}),e.jsxs("span",{style:{flex:1,minWidth:0},children:[e.jsx("span",{style:{fontSize:"var(--ui-font-body, 13px)",fontWeight:600},children:g.name}),e.jsx("span",{style:{fontSize:"var(--ui-font-caption, 11px)",color:"var(--text-dim)",marginLeft:6},children:h("group.setup.tempBadge")})]}),e.jsx("button",{className:"icon-btn",title:h("common.edit"),onClick:()=>I({slug:g.slug,name:g.name,description:g.description,model:g.model,systemPrompt:g.systemPrompt,thinkingLevel:g.thinkingLevel,maxIterations:g.maxIterations!=null?String(g.maxIterations):"",approvalMode:g.approvalMode}),children:e.jsx(Tn,{size:13})}),e.jsx("button",{className:"icon-btn",title:h("common.delete"),onClick:()=>M(F=>F.filter(H=>H.slug!==g.slug)),children:e.jsx(xs,{size:13})})]},g.slug))}),e.jsxs("button",{className:"btn ghost sm",style:{marginBottom:14},onClick:()=>I(Nl()),children:[e.jsx(An,{size:13})," ",h("group.setup.addTemp")]}),e.jsx("div",{style:{fontSize:"var(--ui-font-meta, 12px)",color:"var(--text-dim)",margin:"6px 0 14px"},children:h("group.setup.selfPacedHint")}),e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[i&&!c&&e.jsx("button",{className:"btn sm",onClick:()=>{u(),d()},children:h("group.setup.disable")}),e.jsx("button",{className:"btn primary sm",onClick:S,disabled:!D,children:h(i?"group.setup.update":"group.setup.start")})]}),!D&&e.jsx("div",{style:{fontSize:"var(--ui-font-caption, 11px)",color:"var(--danger)",textAlign:"right",marginTop:6},children:h("group.setup.needTwo")})]})]})})},xn=2e5,cs=(t,n,a)=>xc(t,t,n,a,void 0,void 0,{context:3});function Al(t){if(!/^\*\*\* (Begin Patch|(Add|Update|Delete) File:)/m.test(t))return null;const n=t.replace(/\r\n/g,`
2
- `).split(`
3
- `),a=/^\*\*\* (Add|Update|Delete) File: (.+)$/,o=r=>a.test(r)||/^\*\*\* (Begin|End) Patch$/.test(r.trim()),i=[];let c=0;for(;c<n.length;){const r=a.exec(n[c]);if(!r){c++;continue}const u=r[1],d=r[2].trim();c++;let h="";const f=u==="Update"?/^\*\*\* Move to: (.+)$/.exec(n[c]??""):null;f&&(h=f[1].trim(),c++);const k=[];for(;c<n.length&&!o(n[c]);)k.push(n[c]),c++;if(u==="Delete"){i.push(`--- ${d}`,"+++ /dev/null","@@ -1,1 +0,0 @@","-(deleted)");continue}if(u==="Add"){const I=k.filter(U=>U.startsWith("+")).map(U=>U.slice(1));if(!I.length)continue;i.push("--- /dev/null",`+++ ${d}`,`@@ -0,0 +1,${I.length} @@`,...I.map(U=>"+"+U));continue}const x=[`--- ${d}`,`+++ ${h||d}`];let T=[],M="";const A=()=>{if(!T.length)return;const I=T.filter(_=>_[0]!=="+").length,U=T.filter(_=>_[0]!=="-").length;x.push(`@@ -1,${I} +1,${U} @@${M?" "+M:""}`,...T),T=[]};for(const I of k){const U=/^@@ ?(.*)$/.exec(I);if(U){A(),M=U[1]||"";continue}I.startsWith("+")||I.startsWith("-")||I.startsWith(" ")?T.push(I):T.push(" "+I)}A(),x.length>2&&i.push(...x)}return i.length?i.join(`
4
- `)+`
5
- `:null}function El(t,n){if(!n)return null;let a;try{a=JSON.parse(n)}catch{return null}if(!a||typeof a!="object")return null;const o=typeof a.path=="string"&&a.path?a.path:"file";try{switch(t){case"edit_file":{const i=String(a.old_string??""),c=String(a.new_string??"");return!i&&!c||i.length+c.length>xn?null:cs(o,i,c)}case"multi_edit":{if(!Array.isArray(a.edits)||!a.edits.length)return null;let i=0;const c=[];for(let r=0;r<a.edits.length;r++){const u=a.edits[r],d=String(u?.old_string??""),h=String(u?.new_string??"");if(i+=d.length+h.length,i>xn)return null;c.push(cs(a.edits.length>1?`${o} · #${r+1}`:o,d,h))}return c.join(`
6
- `)}case"write_file":{const i=String(a.content??"");return!i||i.length>xn?null:cs(o,"",i)}case"apply_patch":{const i=String(a.patch??a.input??a.diff??"");return i.length>xn?null:/^@@[ -]/m.test(i)&&/^(--- |\+\+\+ )/m.test(i)?i:Al(i)}default:return null}}catch{return null}}me({"approval.remoteReadOnly":{zh:"远程连接下只能原样批准或拒绝,要改命令请在那台设备本机上操作",en:"Over a remote connection you can only approve or reject as is. To change the command, use that device itself"},"approval.remote.caller":{zh:"来自远程会话 · {name}",en:"From a remote session · {name}"},"approval.remote.device":{zh:"来自远程会话 · 已登记设备",en:"From a remote session · a registered device"},"approval.remote.account":{zh:"来自远程会话 · 账号下未识别的客户端",en:"From a remote session · an unidentified client on your account"},"approval.remote.lan":{zh:"来自远程会话 · 局域网配对设备",en:"From a remote session · a LAN-paired device"},"approval.remote.p2p":{zh:"来自远程会话 · 点对点直连",en:"From a remote session · a peer-to-peer connection"},"approval.remote.unknown":{zh:"来自远程会话",en:"From a remote session"},"approval.localOnly":{zh:"这项操作涉及受保护的配置,只能在执行它的电脑上批准",en:"This touches protected configuration and can only be approved on the computer running it"},"approval.byHost":{zh:"在执行的电脑上",en:"on the host computer"},"approval.byHostNamed":{zh:"在执行的电脑上({device})",en:"on the host computer ({device})"},"approval.byDevice":{zh:"在 {device} 上",en:"on {device}"},"approval.byRegisteredDevice":{zh:"在已登记设备上",en:"on a registered device"},"approval.byOther":{zh:"在另一台设备上",en:"on another device"},"approval.byChannel":{zh:"经消息通道",en:"via a messaging channel"}});const Es=new Set,Td=t=>Es.has(t),Ml=t=>ur(dr(t)).remoteApprover,oi=480,$d=({req:t,onDecide:n,sessionId:a})=>{const{t:o}=we(),i=Ml(a),c=ir(a),r=t.name==="run_bash",u=(()=>{if(!r||!t.arguments)return"";try{return String(JSON.parse(t.arguments).command??"")}catch{return""}})(),[d,h]=l.useState(u),f=l.useRef(null),[k,x]=l.useState(!1);l.useLayoutEffect(()=>{const g=f.current;if(!g)return;g.style.height="auto";const F=g.scrollHeight;g.style.height=`${Math.min(F,oi)}px`,x(F>oi)},[d]);const T=jc.test(d),M=bc.test(d),A=t.status!=="pending",I=l.useMemo(()=>r?null:El(t.name,t.arguments),[r,t.name,t.arguments]),U=or(t.reason)&&!i,_=rr(t.reason,o),D=cr(t.remote,o),w=!(t.localOnly&&i),z=A?lr(t.answeredBy,{remotePage:i,answeredHere:Es.has(t.approvalId),hostName:c},o):"",S=g=>{if(A||g!=="reject"&&!w)return;Es.add(t.approvalId);const F=r&&!i&&d.trim()&&d!==u?{command:d}:void 0;n(g,g==="reject"?void 0:F)};return e.jsxs("div",{className:`approval-card${A?" resolved":""}`,children:[e.jsxs("div",{className:"approval-title",children:[e.jsx(tl,{size:15,style:{color:"var(--accent-ink)"}}),o("approval.requestExec",{name:t.name}),A&&e.jsxs("span",{style:{fontWeight:400,fontSize:"var(--ui-font-meta, 12px)",color:"var(--text-faint)"},children:[t.status==="approved"?o("approval.statusApproved"):t.status==="rejected"?o("approval.statusRejected"):o("approval.statusExpired"),z&&e.jsxs("span",{"data-answered-by":!0,children:[" · ",z]})]})]}),D&&e.jsx("div",{className:"approval-why","data-approval-remote":!0,children:D}),_&&e.jsx("div",{className:"approval-why",children:_}),r&&!A&&!i?e.jsx("textarea",{className:"approval-edit",value:d,onChange:g=>h(g.target.value),ref:f,rows:1,spellCheck:!1}):null,r&&!A&&(k||T||M)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"approval-why",children:[k&&e.jsx("div",{children:o("approval.cmdOverflow")}),T&&e.jsx("div",{children:o("approval.cmdHiddenChars")}),M&&e.jsx("div",{children:o("approval.cmdWideBlank")})]}),(T||M)&&e.jsx("div",{className:"approval-preview",children:t.preview})]}),r&&!A&&!i?null:e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"approval-preview",children:t.preview}),I&&e.jsx("div",{className:"approval-diff",children:e.jsx(wc,{text:I,side:!1})}),i&&!A&&w&&e.jsx("div",{className:"approval-why","data-remote-readonly":!0,children:o("approval.remoteReadOnly")}),!A&&!w&&e.jsx("div",{className:"approval-why","data-local-only":!0,children:o("approval.localOnly")})]}),!A&&e.jsxs("div",{className:"approval-actions",children:[w&&e.jsxs("button",{className:"btn primary sm",onClick:()=>S("approve"),children:[e.jsx(Xe,{size:13})," ",o("approval.approve")]}),U&&w&&e.jsxs("button",{className:"btn ghost sm",onClick:()=>S("approve_always"),children:[e.jsx(pc,{size:13})," ",o("approval.approveAlways")]}),e.jsxs("button",{className:"btn danger sm",onClick:()=>S("reject"),children:[e.jsx(tt,{size:13})," ",o("approval.reject")]})]})]})},Rl=["readonly","auto-edit","full-auto"],Tl={base:"auto-edit"},ls=t=>t.join(`
7
- `),us=t=>t.split(`
8
- `).map(n=>n.trim()).filter(Boolean),$l=({cfg:t,onClose:n})=>{const{t:a}=we(),[o,i]=l.useState(Tl.base),[c,r]=l.useState({deny:"",ask:"",allow:""}),[u,d]=l.useState(!0),[h,f]=l.useState(!1),[k,x]=l.useState(!1),[T,M]=l.useState(""),A=zn.useRef(t);A.current=t;const I=zn.useCallback(()=>{d(!0),M(""),hr(nt()).then(D=>{i(D.base),r({deny:ls(D.deny),ask:ls(D.ask),allow:ls(D.allow)}),f(!0),d(!1)}).catch(D=>{M(String(D?.message||D)),f(!1),d(!1)})},[]);l.useEffect(()=>{I()},[I]);const U=async()=>{if(h){x(!0),M("");try{await pr(nt(),{base:o,deny:us(c.deny),ask:us(c.ask),allow:us(c.allow)}),n()}catch(D){M(String(D?.message||D)),x(!1)}}},_=D=>e.jsxs("div",{className:"field",children:[e.jsx("label",{children:e.jsx("b",{children:a(`approvalRules.${D}`)})}),e.jsx("div",{className:"hint",children:a(`approvalRules.${D}Hint`)}),e.jsx("textarea",{value:c[D],onChange:w=>r(z=>({...z,[D]:w.target.value})),rows:3,spellCheck:!1,placeholder:a(`approvalRules.${D}Ph`),style:{width:"100%",fontFamily:"var(--font-mono)",fontSize:"var(--ui-font-meta, 12px)"}})]},D);return e.jsx("div",{className:"apvr-modal",onClick:n,style:{position:"fixed",inset:0,background:"var(--overlay-scrim)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:e.jsxs("div",{onClick:D=>D.stopPropagation(),style:{background:"var(--bg-card)",border:"var(--border-width) solid var(--border)",borderRadius:"var(--radius-lg, 12px)",padding:18,width:"min(620px, 92vw)",maxHeight:"86vh",overflow:"auto",boxShadow:"var(--card-shadow)"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:10},children:[e.jsx("b",{children:a("approvalRules.title")}),e.jsx("button",{className:"icon-btn",onClick:n,children:e.jsx(tt,{size:15})})]}),u?e.jsx("div",{className:"field",children:e.jsxs("div",{className:"hint",children:[e.jsx(Ot,{size:14,className:"spin"})," ",a("common.loading")]})}):h?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"field",children:[e.jsx("div",{className:"hint",children:a("approvalRules.scopeNote")}),e.jsx("div",{className:"hint",style:{marginTop:4},children:a("approvalRules.syntax")})]}),e.jsxs("div",{className:"field",children:[e.jsx("label",{children:e.jsx("b",{children:a("approvalRules.base")})}),e.jsx("div",{className:"hint",children:a("approvalRules.baseHint")}),e.jsx("div",{style:{display:"flex",gap:6,marginTop:6},children:Rl.map(D=>e.jsx("button",{className:`btn sm${o===D?" primary":" ghost"}`,onClick:()=>i(D),children:a(mr[D])},D))})]}),["deny","ask","allow"].map(_),T&&e.jsx("div",{className:"field",children:e.jsx("div",{className:"hint",style:{color:"var(--danger)"},children:T})})]}):e.jsxs("div",{className:"field",children:[e.jsx("div",{className:"hint",style:{color:"var(--danger)"},children:a("approvalRules.loadFailed")}),e.jsx("div",{className:"hint",children:T}),e.jsx("div",{style:{marginTop:8},children:e.jsx("button",{className:"btn sm ghost",onClick:I,children:a("common.retry")})})]}),e.jsxs("div",{style:{display:"flex",gap:6,justifyContent:"flex-end",marginTop:14},children:[e.jsx("button",{className:"btn ghost sm",onClick:n,children:a("common.cancel")}),e.jsxs("button",{className:"btn primary sm",disabled:!h||k,onClick:()=>{U()},children:[k?e.jsx(Ot,{size:13,className:"spin"}):null," ",a("common.save")]})]})]})})},Ll=[{name:"/help",key:"help",zh:"显示帮助与命令列表",en:"Show help and the command list",surfaces:["tui","desktop","channel"]},{name:"/feedback",key:"feedback",zh:"提交问题或建议,可在命令后填写反馈内容",en:"Report an issue or suggestion; optionally add your feedback after the command",surfaces:["desktop"]},{name:"/new",key:"new",zh:"开始新会话",en:"Start a new session",surfaces:["tui","desktop","channel"]},{name:"/clear",key:"clear",zh:"清屏(保留会话历史)",en:"Clear the screen (history is kept)",surfaces:["tui"]},{name:"/sessions",key:"sessions",aliases:["/list"],zh:"列出最近会话",en:"List recent sessions",surfaces:["tui","desktop","channel"]},{name:"/resume",key:"resume",aliases:["/switch"],zh:"恢复会话并续聊",en:"Resume a session and continue",arg:"<id|序号>",surfaces:["tui","channel"]},{name:"/rename",key:"rename",arg:"<标题>",zh:"重命名本会话",en:"Rename this session",surfaces:["tui"]},{name:"/branch",key:"branch",arg:"[序号]",aliases:["/fork"],zh:"从某条回复后分支新会话(继承历史),缺省最近",en:"Branch a new session from a reply (inherits history); defaults to the latest",surfaces:["tui","desktop"]},{name:"/btw",key:"btw",arg:"[问题]",aliases:["/side"],zh:"顺便问一句:带着本会话上下文旁聊,不进主对话、不打断正在跑的任务",en:"Ask a side question with this session as context; not added to the conversation and never interrupts a running task",surfaces:["desktop"]},{name:"/compact",key:"compact",arg:"[关注点]",zh:"压缩上下文:总结后精简续接(同会话;可附本次摘要的关注点)",en:"Compact context: summarize, then continue compactly (optional focus for this summary)",surfaces:["tui","desktop","channel"]},{name:"/status",key:"status",zh:"本会话概况:模型 / 思考档 / 审批档 / 工作目录 / 用量",en:"Session overview: model, thinking level, approval mode, cwd, usage",surfaces:["tui","desktop","channel"]},{name:"/export",key:"export",zh:"导出本会话为 Markdown",en:"Export this session as Markdown",surfaces:["tui","desktop"]},{name:"/cost",key:"cost",zh:"本会话 token 用量与费用",en:"Token usage and cost for this session",surfaces:["tui","desktop","channel"]},{name:"/diff",key:"diff",zh:"查看工作目录的 git 改动(含未跟踪文件)",en:"Show git changes in the working directory (including untracked files)",surfaces:["tui"]},{name:"/copy",key:"copy",zh:"复制上一条回复到剪贴板",en:"Copy the last reply to the clipboard",surfaces:["tui","desktop"]},{name:"/retry",key:"retry",zh:"重跑上一条用户消息",en:"Re-run the last user message",surfaces:["tui","desktop"]},{name:"/edit",key:"edit",zh:"编辑最近一条消息并重跑($EDITOR)",en:"Edit the last message and re-run ($EDITOR)",surfaces:["tui"]},{name:"/delete",key:"delete",zh:"删除最近一轮对话",en:"Delete the last turn",surfaces:["tui"]},{name:"/queue",key:"queue",arg:"[clear]",zh:"查看排队项:运行中发的消息与 /compact 等命令排到本轮结束后依次执行(/queue clear 清空)",en:"Show queued items: messages and commands like /compact sent while running run in order after this turn (/queue clear to empty)",surfaces:["tui"]},{name:"/stop",key:"stop",zh:"停止当前运行",en:"Stop the current run",surfaces:["desktop","channel"]},{name:"/model",key:"model",arg:"[名称|序号]",zh:"切换模型(不带参数列出可选模型)",en:"Switch model (no argument lists the available models)",surfaces:["tui","desktop","channel"]},{name:"/think",key:"think",arg:"<档位>",aliases:["/effort"],zh:"思考强度:off|minimal|low|medium|high|xhigh|max(模型不支持的档自动降档)",en:"Thinking level: off|minimal|low|medium|high|xhigh|max (auto-clamped to what the model supports)",surfaces:["tui","desktop","channel"]},{name:"/approval",key:"approval",arg:"<档位>",aliases:["/permissions"],zh:"查看或切换审批档:readonly|auto-edit|full-auto|custom",en:"Show or switch the approval mode: readonly|auto-edit|full-auto|custom",surfaces:["tui","desktop","channel"]},{name:"/loop",key:"loop",arg:"<1-200>",zh:"最大循环轮数(默认 90;耗尽会提示)",en:"Max loop iterations (default 90; you get a prompt when exhausted)",surfaces:["tui","desktop","channel"]},{name:"/verify",key:"verify",arg:"<命令|off>",zh:"本会话验证命令:收尾前自动跑,不绿不许收(off 关闭)",en:"Session verify command — runs before the turn may end; must pass (off to clear)",surfaces:["desktop"]},{name:"/plan",key:"plan",zh:"切换计划模式:只读调研 → 提交计划求批准",en:"Toggle plan mode: read-only research, then submit a plan for approval",surfaces:["tui","desktop"]},{name:"/chat",key:"chat",zh:"切到 Chat 模式(轻量:答完即停、临时工作区、不写笔记;侧栏只列聊天会话,新会话按此模式创建,已创建的会话不可切换)",en:"Switch to Chat mode (light: answers and stops, temporary workspace, never writes your notes; the sidebar lists chat sessions only, new sessions use it, existing sessions are fixed)",surfaces:["desktop"]},{name:"/work",key:"work",zh:"切到 Work 模式(完整工具面:文件、命令、技能、子代理;侧栏列出全部项目)",en:"Switch to Work mode (full toolset: files, commands, skills, subagents; the sidebar lists all projects)",surfaces:["desktop"]},{name:"/voice",key:"voice",zh:"切到语音消息(该 Agent 回复变语音)",en:"Switch to voice messages (this agent replies as voice)",surfaces:["desktop","channel"]},{name:"/text",key:"text",zh:"切回文字消息",en:"Switch back to text messages",surfaces:["channel"]},{name:"/cwd",key:"cwd",arg:"[path]",zh:"查看或切换工作目录",en:"Show or change the working directory",surfaces:["tui"]},{name:"/config",key:"config",zh:"查看当前设置",en:"Show current settings",surfaces:["tui","desktop"]},{name:"/login",key:"login",zh:"重新登录 Forsion",en:"Sign in to Forsion again",surfaces:["tui","desktop"]},{name:"/hotkeys",key:"hotkeys",zh:"查看快捷键",en:"Show keyboard shortcuts",surfaces:["tui"]},{name:"/exit",key:"exit",zh:"退出 Tangu",en:"Quit Tangu",surfaces:["tui"]},{name:"/tools",key:"tools",zh:"列出当前模式可用工具",en:"List tools available in the current mode",surfaces:["tui","desktop"]},{name:"/skills",key:"skills",zh:"列出可用技能(✓=本会话启用)",en:"List available skills (✓ = enabled for this session)",surfaces:["tui","desktop"]},{name:"/skill",key:"skill",arg:"<id>",zh:"启用/停用技能",en:"Enable or disable a skill",surfaces:["tui"]},{name:"/agents",key:"agents",zh:"列出本地 Normal Agent(自定义人格)",en:"List local normal agents (custom personas)",surfaces:["tui","desktop","channel"]},{name:"/agent",key:"agent",arg:"<slug>",zh:"启用 Agent;管理:/agent new|edit|rm <slug>",en:"Activate an agent; manage with /agent new|edit|rm <slug>",surfaces:["tui","desktop","channel"]},{name:"/groupchat",key:"groupchat",arg:"<slug…>",zh:"团队模式(/groupchat off 退出)",en:"Team mode (/groupchat off to leave)",surfaces:["tui","desktop"]},{name:"/historian",key:"historian",zh:"Historian 状态/活动;/historian on|off 开关",en:"Historian status/activity; /historian on|off to toggle",surfaces:["tui","desktop"]},{name:"/muse",key:"muse",zh:"Muse 状态/TODO;/muse on|off 开关",en:"Muse status/TODOs; /muse on|off to toggle",surfaces:["tui","desktop"]},{name:"/memory",key:"memory",arg:"[edit]",zh:"查看/编辑长期记忆",en:"View or edit long-term memory",surfaces:["tui","desktop"]},{name:"/refine",key:"refine",arg:"[focus]",zh:"复盘本会话,沉淀 Agent 的工作笔记(可回滚)",en:"Reflect on this conversation and refine the agent's working notes (reversible)",surfaces:["tui","desktop"]},{name:"/log",key:"log",arg:"[YYYY-MM-DD]",zh:"查看每日日志",en:"View the daily log",surfaces:["tui"]},{name:"/mcp",key:"mcp",zh:"列出 MCP server 状态",en:"List MCP server status",surfaces:["tui","desktop"]},{name:"/plugins",key:"plugins",zh:"列出已发现插件",en:"List discovered plugins",surfaces:["tui","desktop"]}];function ri(t){return Ll.filter(n=>n.surfaces.includes(t))}me({"addMenu.label":{zh:"添加",en:"Add"},"addMenu.newChat":{zh:"新会话",en:"New session"},"addMenu.agent":{zh:"添加 Agent",en:"Add agent"},"addMenu.files":{zh:"添加文件或文件夹",en:"Add files or folders"},"addMenu.conversation":{zh:"添加会话",en:"Add session"},"addMenu.view":{zh:"添加正在使用的 View",en:"Add an active View"},"addMenu.searchChats":{zh:"搜索全部会话",en:"Search all sessions"},"addMenu.searchViews":{zh:"搜索全部 View",en:"Search all Views"},"addMenu.recent":{zh:"最近使用",en:"Recent"},"addMenu.allChats":{zh:"全部会话",en:"All sessions"},"addMenu.inUse":{zh:"正在使用",en:"In use"},"addMenu.allViews":{zh:"全部 View",en:"All Views"},"addMenu.noMatches":{zh:"没有匹配项",en:"No matches"}});const ds=new Set(["chat","chat-panel","home","launcher","sidebar-empty"]);function hs(t){const n=new Set;return t.filter(a=>n.has(a.key)?!1:(n.add(a.key),!0))}const Il=({open:t,disabled:n,activeSessionId:a,canUsePathPicker:o,onOpenChange:i,onNewSession:c,onAddAgent:r,onPickPaths:u,onPickFiles:d,onAddReference:h})=>{const{t:f}=we(),[k,x]=l.useState(null),[T,M]=l.useState(""),[A,I]=l.useState("right"),[U,_]=l.useState(0),D=l.useRef(null),w=l.useRef(null),z=l.useRef(null),S=l.useRef(null),g=Ft(t,{boundary:".t2-chat-view"}),F=Ft(k?`${k}:${A}`:"",{boundary:".t2-chat-view"}),H=P(C=>C.sessions),W=P(C=>C.archivedSessions),O=Sc(C=>C.items),E=bn(C=>C.mainTabs),G=bn(C=>C.leftTabs),X=bn(C=>C.rightTabs),J=nn(C=>C.vaultRoot);l.useEffect(()=>{t||(x(null),M(""))},[t]),l.useEffect(()=>{M(""),k&&requestAnimationFrame(()=>z.current?.focus())},[k]),l.useLayoutEffect(()=>{const C=D.current,K=w.current;if(!k||!C||!K)return;const q=()=>{const Je=C.getBoundingClientRect(),Me=(C.closest(".t2c-card")||C.closest(".t2-chat-view"))?.getBoundingClientRect(),at=Ci(K),jt=Me?zi(Je.left,Je.right,K.offsetWidth,Me.left,Me.right,at):"right";I(Le=>Le===jt?Le:jt),_(Le=>Le===C.offsetHeight+6?Le:C.offsetHeight+6)};q(),window.addEventListener("resize",q),window.addEventListener(En,q);const Ae=new ResizeObserver(q);Ae.observe(C),Ae.observe(K);const $e=C.closest(".t2c-card")||C.closest(".t2-chat-view");return $e&&Ae.observe($e),()=>{window.removeEventListener("resize",q),window.removeEventListener(En,q),Ae.disconnect()}},[k]);const ee=l.useMemo(()=>{const C=new Set;return[...H,...W].filter(K=>K.id===a||C.has(K.id)?!1:(C.add(K.id),!0))},[H,W,a]),De=l.useMemo(()=>{const C=new Map(ee.map(q=>[q.id,q])),K=O.filter(q=>q.kind==="chat").map(q=>C.get(q.id)).filter(Boolean);return(K.length?K:ee).slice(0,6)},[ee,O]),ze=l.useMemo(()=>{const C=T.trim().toLocaleLowerCase();return C?ee.filter(K=>`${K.title||""}
9
- ${K.summary||""}`.toLocaleLowerCase().includes(C)).slice(0,12):De},[T,De,ee]),j=l.useMemo(()=>{const C=E.flatMap(q=>{if(ds.has(q.type))return[];const Ae=q.title||Wa(es(q.type)?.displayName||q.type);if(q.filePath){const $e=q.type==="amadeus-editor"&&!!J;return[{key:`${$e?"note":"file"}:${q.filePath}`,type:q.type,title:Ae,ref:$e?{kind:"note",path:q.filePath}:{kind:"file",path:q.filePath},meta:q.filePath}]}return[{key:`view:${q.type}`,type:q.type,title:Ae,ref:{kind:"view",type:q.type,title:Ae}}]}),K=[...G,...X].flatMap(q=>ds.has(q.type)?[]:[{key:`view:${q.type}`,type:q.type,title:q.title,ref:{kind:"view",type:q.type,title:q.title}}]);return hs([...C,...K]).slice(0,8)},[E,G,X,J]),B=l.useMemo(()=>hs(O.flatMap(C=>C.kind==="chat"?[]:C.kind==="note"?[{key:C.key,type:"amadeus-editor",title:C.title,ref:{kind:"note",path:C.id},meta:C.id}]:C.kind==="file"&&C.viewType?[{key:C.key,type:C.viewType,title:C.title,ref:{kind:"file",path:C.id},meta:C.id}]:C.kind==="view"&&C.viewType&&es(C.viewType)?[{key:C.key,type:C.viewType,title:C.title,ref:{kind:"view",type:C.viewType,title:C.title}}]:[])).slice(0,6),[O]),te=fr().filter(C=>!ds.has(C.type)).map(C=>{const K=Wa(C.displayName);return{key:`view:${C.type}`,type:C.type,title:K,ref:{kind:"view",type:C.type,title:K}}}),ge=(()=>{const C=T.trim().toLocaleLowerCase();return C?hs([...j,...B,...te]).filter(K=>`${K.title}
10
- ${K.type}
11
- ${K.meta||""}`.toLocaleLowerCase().includes(C)).slice(0,12):[]})(),ve=C=>{h(C),i(!1)},ye=async()=>{if(o&&window.tangu?.pickPaths){i(!1);const C=await window.tangu.pickPaths();C.length&&await u(C);return}S.current?.click()},_e=C=>es(C)?.icon||Ss,je=C=>C.map(K=>{const q=K.ref.kind==="file"||K.ref.kind==="note"?_s:_e(K.type);return e.jsxs("button",{className:"menu-item add-menu-result",title:K.meta||K.title,onClick:()=>ve(K.ref),children:[e.jsx(q,{size:14}),e.jsxs("span",{className:"grow add-menu-result-main",children:[e.jsx("span",{className:"add-menu-result-title",children:K.title}),K.meta&&e.jsx("span",{className:"add-menu-result-meta",children:K.meta})]})]},K.key)});return e.jsxs("span",{className:`add-pill-wrap t2c-capsule-peer${t?" is-open":""}`,"data-cmenu":!0,children:[e.jsxs("button",{className:`t2c-pill add-pill-btn${t?" is-open":""}`,title:f("input.addContent"),"aria-expanded":t,disabled:n,onClick:()=>i(!t),children:[e.jsx(An,{size:16,className:"add-pill-plus"}),e.jsx("span",{className:"add-pill-label",children:f("addMenu.label")}),e.jsx(rn,{size:10,className:"add-pill-chevron"})]}),t&&e.jsxs("div",{ref:C=>{D.current=C,g.ref.current=C},className:"composer-menu composer-menu--add",style:g.style,children:[e.jsxs("button",{className:"menu-item",onClick:()=>{c?.(),i(!1)},children:[e.jsx($c,{size:14}),e.jsx("span",{className:"grow",children:f("addMenu.newChat")})]}),r&&e.jsxs("button",{className:"menu-item","data-add-agent":!0,onClick:()=>{r(),i(!1)},children:[e.jsx(Ui,{size:14}),e.jsx("span",{className:"grow",children:f("addMenu.agent")})]}),e.jsxs("button",{className:"menu-item",onClick:()=>{ye()},children:[e.jsx(gr,{size:14}),e.jsx("span",{className:"grow",children:f("addMenu.files")})]}),e.jsxs("button",{className:`menu-item add-menu-parent${k==="conversation"?" active":""}`,"aria-expanded":k==="conversation",onPointerEnter:()=>x("conversation"),onFocus:()=>x("conversation"),onClick:()=>x("conversation"),children:[e.jsx(Mn,{size:14}),e.jsx("span",{className:"grow",children:f("addMenu.conversation")}),e.jsx(xt,{size:13})]}),e.jsxs("button",{className:`menu-item add-menu-parent${k==="view"?" active":""}`,"aria-expanded":k==="view",onPointerEnter:()=>x("view"),onFocus:()=>x("view"),onClick:()=>x("view"),children:[e.jsx(Ss,{size:14}),e.jsx("span",{className:"grow",children:f("addMenu.view")}),e.jsx(xt,{size:13})]})]}),t&&k&&e.jsxs("div",{ref:C=>{w.current=C,F.ref.current=C},className:`composer-menu add-menu-sub ${A}`,"data-pane":k,style:{...F.style,bottom:A==="stacked"?`calc(100% + ${U}px)`:void 0},children:[e.jsxs("label",{className:"add-menu-search",children:[e.jsx(Ni,{size:13}),e.jsx("input",{ref:z,value:T,onChange:C=>M(C.currentTarget.value),placeholder:f(k==="conversation"?"addMenu.searchChats":"addMenu.searchViews")})]}),e.jsx("div",{className:"add-menu-sub-scroll",children:k==="conversation"?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"menu-section",children:f(T.trim()?"addMenu.allChats":"addMenu.recent")}),ze.map(C=>e.jsxs("button",{className:"menu-item add-menu-result",title:C.summary||C.title||"",onClick:()=>ve({kind:"session",id:C.id,title:C.title||"Chat"}),children:[e.jsx(Mn,{size:14}),e.jsxs("span",{className:"grow add-menu-result-main",children:[e.jsx("span",{className:"add-menu-result-title",children:C.title||"Chat"}),C.summary&&e.jsx("span",{className:"add-menu-result-meta",children:C.summary})]})]},C.id)),!ze.length&&e.jsx("div",{className:"add-menu-empty",children:f("addMenu.noMatches")})]}):T.trim()?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"menu-section",children:f("addMenu.allViews")}),je(ge),!ge.length&&e.jsx("div",{className:"add-menu-empty",children:f("addMenu.noMatches")})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"menu-section",children:f("addMenu.inUse")}),je(j),!j.length&&e.jsx("div",{className:"add-menu-empty",children:f("addMenu.noMatches")}),!!B.length&&e.jsx("div",{className:"menu-section add-menu-section-gap",children:f("addMenu.recent")}),je(B)]})})]}),e.jsx("input",{ref:S,type:"file",multiple:!0,hidden:!0,onChange:C=>{d(C.currentTarget.files),C.currentTarget.value="",i(!1)}})]})};function Pl({active:t,disabled:n,agents:a,currentAgentSlug:o,onNormalWork:i,onAgentSwitch:c,onClose:r}){const{t:u}=we(),[d,h]=l.useState(!1),[f,k]=l.useState("right"),[x,T]=l.useState(0),M=l.useRef(null),A=l.useRef(null),I=Ft(d?f:"",{boundary:".t2-chat-view"}),U=a.filter(w=>w.createdBy!=="system"),_=c&&U.length?()=>h(!0):void 0,D=a.find(w=>w.slug===o);return l.useLayoutEffect(()=>{const w=M.current,z=A.current,S=w?.closest(".composer-menu");if(!d||!w||!z||!S)return;const g=()=>{const W=S.getBoundingClientRect(),O=(S.closest(".t2c-card")||S.closest(".t2-chat-view"))?.getBoundingClientRect(),E=S.closest(".t2-chat-view")?.getBoundingClientRect(),G=Ci(z),X=O?zi(W.left,W.right,z.offsetWidth,O.left,O.right,G):"right";k(ee=>ee===X?ee:X);const J=vr(w.getBoundingClientRect().top,z.offsetHeight,W.top,W.bottom,E?.top??0,E?.bottom??window.innerHeight,G);T(ee=>Math.abs(ee-J)<.5?ee:J)};g(),window.addEventListener("resize",g),window.addEventListener(En,g);const F=new ResizeObserver(g);F.observe(S),F.observe(z);const H=S.closest(".t2c-card")||S.closest(".t2-chat-view");return H&&F.observe(H),()=>{window.removeEventListener("resize",g),window.removeEventListener(En,g),F.disconnect()}},[d]),l.useEffect(()=>{const w=M.current?.closest(".composer-menu");if(!d||!w)return;const z=S=>{const g=S.target?.closest?.(".menu-item");g&&!M.current?.contains(g)&&h(!1)};return w.addEventListener("pointerover",z),w.addEventListener("focusin",z),()=>{w.removeEventListener("pointerover",z),w.removeEventListener("focusin",z)}},[d]),e.jsxs("div",{ref:M,className:"mode-normal-row",onPointerEnter:_,children:[e.jsxs("button",{className:`menu-item${t?" active":""}`,"data-normal-work":!0,disabled:n,onClick:()=>{i(),r()},children:[e.jsx(Ua,{size:14}),e.jsx("span",{className:"grow",children:u("input.normalWork")}),t&&e.jsx(Xe,{size:13})]}),_&&e.jsxs("button",{className:"menu-item mode-agent-trigger","data-agent-switch":!0,"aria-haspopup":"menu","aria-expanded":d,title:u("input.agentSwitch.section"),onFocus:_,onClick:_,children:[D&&e.jsx("span",{className:"mode-agent-name",children:D.name}),e.jsx(xt,{size:13})]}),d&&_&&e.jsxs("div",{ref:w=>{A.current=w,I.ref.current=w},className:`cm-sub ${f}`,"data-pane":"agents",role:"menu",style:{...I.style,"--cm-sub-top":`${x}px`},children:[e.jsx("div",{className:"menu-section",children:u("input.agentSwitch.section")}),U.map(w=>e.jsxs("button",{role:"menuitemradio","aria-checked":o===w.slug,className:`menu-item${o===w.slug?" active":""}`,onClick:()=>{c(w.slug),r()},children:[e.jsx(Ua,{size:14}),e.jsx("span",{className:"grow",children:w.name}),o===w.slug&&e.jsx(Xe,{size:13})]},w.slug))]})]})}function Dl(t){const n=t.find(o=>o.active),a=(n?.filePath?n:void 0)??t.find(o=>o.front&&o.filePath)??t.find(o=>o.type==="amadeus-editor"&&o.filePath)??t.find(o=>o.filePath);return a?a.type==="amadeus-editor"?a.filePath?`note:${a.filePath}`:"note":a.filePath?`file:${a.filePath}`:"":""}const wn={color:"var(--accent-ink)",flexShrink:0};function _l({chip:t,onRemove:n,removeTitle:a,children:o}){return e.jsxs("span",{className:"attach-chip",title:t.token,"data-ref-kind":t.kind,children:[t.kind==="session"?e.jsx(Dn,{size:13,style:wn}):t.kind==="folder"?e.jsx($n,{size:13,style:wn}):t.kind==="view"?e.jsx(Ss,{size:13,style:wn}):e.jsx(_s,{size:13,style:wn}),e.jsx("span",{children:o??t.name}),n&&e.jsx("button",{type:"button",title:a,"aria-label":a,onClick:n,children:e.jsx(tt,{size:12})})]})}const ms=t=>t.replace(/[\\/]+$/,"").split(/[\\/]/).pop()||t,Ol=t=>t.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&");function Fl(t){if(/[\s"<>[\]]/.test(t)||t.includes("://"))return!1;const n=/^(~?\/|[A-Za-z]:[\\/])/.test(t),a=t.split(/[\\/]/).filter(Boolean);return n?a.length>=(/^[A-Za-z]:/.test(t)?3:2):a.length>=2&&/\.[A-Za-z0-9]{1,10}$/.test(a[a.length-1])}const Wl=/^\[\[([^[\]\n]+)\]\]/,Ul=/^"([^"\n]+)"/,Bl=/^<forsion-view type="([^"\n]*)" title="([^"\n]*)" \/>/,ql=/^[^\s]+/;function Hl(t,n){const a=t.slice(n);let o=Wl.exec(a);if(o){const i=o[1],c=i.indexOf("|"),r=(c===-1?i:i.slice(0,c)).trim(),u=(c===-1?"":i.slice(c+1)).trim();return r?{ref:yr(r)?{token:o[0],name:u||"Chat",kind:"session",wiki:i}:{token:o[0],name:u||ms(r).replace(/\.md$/i,""),kind:"note",wiki:i},end:n+o[0].length,strong:!0}:null}if(o=Bl.exec(a),o)return{ref:{token:o[0],name:Ol(o[2]),kind:"view"},end:n+o[0].length,strong:!0};if(o=Ul.exec(a),o){const i=o[1];return!/\s/.test(i)||!/[\\/]/.test(i)?null:{ref:{token:o[0],name:ms(i),kind:"file"},end:n+o[0].length,strong:!0}}return o=ql.exec(a),o&&Fl(o[0])?{ref:{token:o[0],name:ms(o[0]),kind:"file"},end:n+o[0].length,strong:!1}:null}function Ld(t){if(!t)return null;const n=t.indexOf(`
12
- `),a=n===-1?t:t.slice(0,n),o=[];let i=!0,c=0;for(;c<a.length;){const r=Hl(a,c);if(!r)return null;if(o.push(r.ref),i=i&&r.strong,c=r.end,c===a.length)break;if(a[c]!==" "||(c+=1,c===a.length))return null}return!o.length||n===-1&&!i?null:{refs:o,body:n===-1?"":t.slice(n+1)}}const Vl=({tier:t})=>{const n=(t||"free").toLowerCase();if(n==="free"||!n)return null;const a=n==="pro"?{background:"linear-gradient(135deg, #8B5CF6, #A855F7)",color:"#fff",border:"none"}:{background:"linear-gradient(135deg, #F59E0B, #F97316)",color:"#fff",border:"none"};return e.jsx("span",{className:"tier-badge",style:a,children:n})};me({"ctx.pop.title":{zh:"上下文窗口",en:"Context window"},"ctx.pop.compact":{zh:"立即压缩",en:"Compact now"},"ctx.grp.tools":{zh:"工具与本轮",en:"Tools & this run"},"ctx.grp.system":{zh:"系统提示",en:"System prompt"},"ctx.sec.human":{zh:"协作说明",en:"Collaboration handbook"},"ctx.grp.memory":{zh:"记忆",en:"Memory"},"ctx.grp.project":{zh:"项目与资料",en:"Project & files"},"ctx.grp.skills":{zh:"技能",en:"Skills"},"ctx.grp.used":{zh:"已用",en:"Used"},"ctx.grp.buffer":{zh:"自动压缩预留",en:"Auto-compact buffer"},"ctx.grp.free":{zh:"剩余可用",en:"Free space"},"ctx.untilCompact":{zh:"还剩 {left} 触发自动压缩({n},{pct}%)",en:"{left} until auto-compact ({n}, {pct}%)"},"ctx.limit.title":{zh:"Forsion 额度",en:"Forsion usage limits"},"ctx.limit.resetsIn":{zh:"{h} 小时 {m} 分钟后重置",en:"Resets in {h} hr {m} min"},"ctx.limit.resetsAt":{zh:"{when} 重置",en:"Resets {when}"},"ctx.limit.used":{zh:"已用 {pct}%",en:"{pct}% used"}});const We=t=>t>=1e6?`${Math.floor(t/1e5)/10}M`:t>=1e3?`${Math.floor(t/100)/10}k`:String(t),ci=new Set(["persona","harness","human","guidance","profile","project","agentFolder","memory","skills","environment","hooks","plan"]),li="var(--model-tag-blue)",Kl=[{id:"system",keys:["persona","guidance","environment","hooks","plan"],color:"var(--warning)"},{id:"memory",keys:["memory","profile","harness","human"],color:"var(--green)"},{id:"project",keys:["project","agentFolder"],color:"color-mix(in srgb, var(--accent-ink) 55%, transparent)"},{id:"skills",keys:["skills"],color:"color-mix(in srgb, var(--model-tag-blue) 45%, var(--green))"}];function Yl(t,n,a){if(!n)return t>0?[{id:"used",label:a("ctx.grp.used"),tokens:t,color:li}]:[];let o=Math.max(0,t);const i=d=>{const h=Math.min(o,Math.max(0,d));return o-=h,h},c=Kl.map(d=>{const h=n.sections.filter(x=>d.keys.includes(x.k)||d.id==="system"&&!ci.has(x.k)),f=h.reduce((x,T)=>x+T.tokens,0),k=i(f);return{id:d.id,label:a(`ctx.grp.${d.id}`),color:d.color,tokens:k,parts:k===f?h.map(x=>({label:ci.has(x.k)?a(`ctx.sec.${x.k}`):x.k,tokens:x.tokens})):void 0}}),r={id:"messages",label:a("ctx.sec.history",{n:n.historyCount}),tokens:i(n.historyTokens),color:li},u={id:"tools",label:a("ctx.grp.tools"),tokens:o,color:"var(--model-tag-purple)"};return[r,u,...c].filter(d=>d.tokens>0)}const Yi=8*36e5,Gl=t=>864e5-(t+Yi)%864e5;function Xl(t){const n=/^(\d{4})-(\d{2})-(\d{2})/.exec(t||"");return n?new Date(Date.UTC(Number(n[1]),Number(n[2])-1,Number(n[3]))-Yi):null}function Jl({open:t,contextWindow:n,ctxTokens:a,sessionTokens:o,runCost:i,costLimit:c,ctxInfo:r,onCompact:u}){const{t:d}=we(),[h,f]=l.useState(!1),k=a||0,x=_=>_/n*100,T=_=>`${Math.round(x(_)*10)/10}%`,M=Yl(Math.min(k,n),r??null,d),A=r?.compactAt&&r.compactAt<n?r.compactAt:0,I=A?Math.max(0,n-Math.max(A,k)):0,U=Math.max(0,n-k-I);return e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",className:"t2c-cu-head","aria-expanded":h,onClick:()=>f(_=>!_),children:[e.jsx("span",{className:"t2c-cu-title",children:d("ctx.pop.title")}),e.jsxs("span",{className:"t2c-cu-num",children:[We(k)," / ",We(n)," tokens (",Math.min(100,Math.round(x(k))),"%)"]}),e.jsx(xt,{size:13,className:"t2c-cu-chev","aria-hidden":"true"})]}),e.jsxs("span",{className:"t2c-cu-bar","aria-hidden":"true",children:[M.map(_=>e.jsx("span",{style:{width:`${x(_.tokens)}%`,background:_.color}},_.id)),I>0&&e.jsx("span",{className:"t2c-cu-buffer",style:{width:`${x(I)}%`}})]}),r&&r.ctxWindowSource!=="override"&&(r.ctxWindowMax??0)>r.ctxWindow&&e.jsx("span",{className:"t2c-ctxinfo-src",children:d("ctx.windowCapped",{max:We(r.ctxWindowMax),n:We(r.ctxWindow)})}),h&&e.jsxs("span",{className:"t2c-cu-detail",children:[e.jsxs("span",{className:"t2c-cu-legend",children:[M.map(_=>e.jsxs(l.Fragment,{children:[e.jsxs("span",{className:"t2c-cu-row",children:[e.jsx("i",{style:{background:_.color}}),e.jsx("span",{children:_.label}),e.jsx("span",{children:We(_.tokens)}),e.jsx("span",{children:T(_.tokens)})]}),_.parts&&_.parts.length>1&&_.parts.map(D=>e.jsxs("span",{className:"t2c-cu-row is-sub",children:[e.jsx("i",{}),e.jsx("span",{children:D.label}),e.jsxs("span",{children:["~",We(D.tokens)]}),e.jsx("span",{})]},D.label))]},_.id)),I>0&&e.jsxs("span",{className:"t2c-cu-row",children:[e.jsx("i",{className:"t2c-cu-buffer"}),e.jsx("span",{children:d("ctx.grp.buffer")}),e.jsx("span",{children:We(I)}),e.jsx("span",{children:T(I)})]}),e.jsxs("span",{className:"t2c-cu-row",children:[e.jsx("i",{className:"is-free"}),e.jsx("span",{children:d("ctx.grp.free")}),e.jsx("span",{children:We(U)}),e.jsx("span",{children:T(U)})]})]}),r&&e.jsx("span",{className:"t2c-ctxinfo-src",children:d(`ctx.windowSource.${["override","model","learned","family","default"].includes(r.ctxWindowSource)?r.ctxWindowSource:"default"}`)}),!!o&&o>0&&e.jsx("span",{className:"t2c-ctxinfo-src",children:d("input.sessionTokens",{n:We(o)})}),r&&e.jsxs("span",{className:"t2c-ctxinfo-files",children:[e.jsxs("span",{className:"t2c-ctxinfo-label",children:[d("ctx.files.label"),r.filesTruncated?` ${d("ctx.files.truncated")}`:""]}),r.files.length>0?r.files.map(_=>e.jsx("span",{className:"t2c-ctxinfo-file",title:_,children:_.split(/[/\\]/).slice(-2).join("/")},_)):e.jsx("span",{className:"t2c-ctxinfo-file dim",children:d("ctx.files.none")})]})]}),e.jsxs("span",{className:"t2c-cu-foot",children:[A>0&&e.jsx("span",{children:d("ctx.untilCompact",{left:We(Math.max(0,A-k)),n:We(A),pct:Math.round(x(A))})}),u&&e.jsx("button",{type:"button",className:"t2c-ctxring-compact",onClick:u,title:d("input.slash.compact"),children:d("ctx.pop.compact")})]}),i!=null&&c!=null&&c>0&&e.jsx("span",{className:"t2c-ctxinfo-src","data-warn":i>=c*.8||void 0,children:d("input.runCost",{used:Math.round(i).toLocaleString(),limit:c.toLocaleString()})}),e.jsx(Zl,{open:t})]})}function Zl({open:t}){const{t:n,locale:a}=we(),o=P(x=>x.authInfo?.loggedIn&&x.authInfo.tokenValid!==!1?`${x.authInfo.accountId??""}:${x.authInfo.username??""}`:null),i=o!==null&&!!window.tangu?.accountQuota,c=P(x=>x.authInfo?.membershipTier),[r,u]=l.useState(null),d=l.useRef(0);if(l.useEffect(()=>kr(x=>{d.current++,u(x)}),[]),l.useEffect(()=>{u(null)},[o]),l.useEffect(()=>{if(!i||!t)return;let x=!0;const T=++d.current;return window.tangu.accountQuota().then(M=>{!x||T!==d.current||M?.status!==200||!M.json||(u(M.json),xr(M.json))}).catch(()=>{}),()=>{x=!1}},[t,o,i]),!i||!r)return null;const h=Gl(Date.now()),f=Xl(r.weeklyResetAt),k=[{key:"daily",label:n("sidebar.account.menu.daily"),limit:Number(r.dailyLimit),rem:Ba(r.dailyLimit,r.dailyRemaining,r.dailyPercent),reset:n("ctx.limit.resetsIn",{h:Math.floor(h/36e5),m:Math.floor(h%36e5/6e4)})},{key:"weekly",label:n("sidebar.account.menu.weekly"),limit:Number(r.weeklyLimit),rem:Ba(r.weeklyLimit,r.weeklyRemaining,r.weeklyPercent),reset:f?n("ctx.limit.resetsAt",{when:wr(f,{locale:a})}):""}].filter(x=>x.limit<0||x.rem!==null);return k.length?e.jsxs("span",{className:"t2c-cu-limits",children:[e.jsxs("span",{className:"t2c-cu-limits-title",children:[n("ctx.limit.title"),e.jsx(Vl,{tier:c})]}),k.map(x=>e.jsxs("span",{className:"t2c-cu-limit","data-limit":x.key,children:[e.jsxs("span",{className:"t2c-cu-limit-line",children:[e.jsx("span",{className:"t2c-cu-limit-name",children:x.label}),x.rem!==null&&e.jsx("span",{className:"t2c-cu-limit-reset",children:x.reset}),e.jsx("span",{children:x.rem===null?n("sidebar.account.menu.unlimited"):n("ctx.limit.used",{pct:Math.round(100-x.rem)})})]}),x.rem!==null&&e.jsx("span",{className:"t2c-cu-bar","data-warn":x.rem<=15||void 0,"aria-hidden":"true",children:e.jsx("span",{style:{width:`${100-x.rem}%`}})})]},x.key))]}):null}me({"livecall.start":{zh:"语音通话",en:"Voice call"},"livecall.return":{zh:"回到通话",en:"Back to the call"},"livecall.localOnly":{zh:"语音通话只能在本机的会话里用",en:"Voice calls only work in sessions on this computer"},"livecall.typeHint":{zh:"通话中:打的字会直接送进电话",en:"In a call: typed messages go straight into the call"},"livecall.textFallback":{zh:"通话没接上,这条改发给 Tangu 了",en:"The call did not pick this up, so it was sent to Tangu instead"}});me({"input.agentSwitch.section":{zh:"切换 Agent",en:"Switch agent"},"input.mention.projectNote":{zh:"派往项目 · 在该项目新建会话开工",en:"Dispatch to project · starts a new session there"},"input.normalWork":{zh:"普通模式",en:"Normal mode"},"input.presetChat":{zh:"Chat",en:"Chat"},"input.presetWork":{zh:"Work",en:"Work"},"input.presetLocked":{zh:"模式在创建会话时确定;换模式请新建会话",en:"Mode is fixed when the session is created; start a new session to change it"},"input.approvalSection.team":{zh:"团队审批档 · 改动对全队生效",en:"Approval mode for the whole team"},"composer2.exportRoleUser":{zh:"我",en:"Me"},"composer2.listSep":{zh:"、",en:", "}});const Ql=8e3,Us="input.tip.steer",ui=[Us,"input.tip.switchChat","input.tip.quote","input.tip.dropFiles","input.tip.wikiRef","input.tip.dragSession","input.tip.branch","input.tip.newTab","input.tip.palette","input.tip.quickFind","input.tip.findInChat","input.tip.toc"],eu=[Us,"input.tip.wikiRef"];me({"input.tip":{zh:"小贴士:{tip}",en:"Tip: {tip}"},"input.runningPlaceholder":{zh:"运行中,可继续输入…",en:"Working… You can keep typing"},"input.steer.queuedHint":{zh:"排队项在本轮结束后依次执行 · ↑ 取回编辑",en:"Queued items run in order after this turn · ↑ to recall"},"input.tip.steer":{zh:"运行中也能继续发消息,会在下一步交给 Agent",en:"You can send while it runs: the agent reads it at the next step"},"input.tip.switchChat":{zh:"可以先切去别的会话,运行不会中断,侧栏圆点标出运行中",en:"Switch chats meanwhile; this run keeps going, marked by a sidebar dot"},"input.tip.quote":{zh:"划选回复里的文字,点「引用」即可带进下一条消息",en:"Select text in a reply and click Quote to cite it in your next message"},"input.tip.dropFiles":{zh:"文件可拖到聊天区任意位置,截图可直接粘贴进输入框",en:"Drop files anywhere in the chat, or paste a screenshot into the box"},"input.tip.wikiRef":{zh:"输入 [[ 可引用历史会话,本机项目里还能引用笔记和文件",en:"Type [[ to reference past chats, or notes and files in local projects"},"input.tip.dragSession":{zh:"把侧栏的会话拖进对话区,即可挂为引用随消息发送",en:"Drag a chat from the sidebar into the conversation to cite it"},"input.tip.branch":{zh:"悬停已完成的回复,点分支图标即可从此处开出新会话",en:"Hover a finished reply and click the branch icon to fork a new chat"},"input.tip.newTab":{zh:"⌘/Ctrl 点击侧栏里的会话,会在新标签页打开",en:"⌘/Ctrl-click a session in the sidebar to open it in a new tab"},"input.tip.palette":{zh:"按 ⌘/Ctrl+K 打开命令面板,搜索并执行命令",en:"Press ⌘/Ctrl+K to open the command palette and run commands"},"input.tip.quickFind":{zh:"⌘/Ctrl+P 快速查找,按名称跳到会话",en:"⌘/Ctrl+P opens quick find: jump to a session by name"},"input.tip.findInChat":{zh:"⌘/Ctrl+F 在当前对话里查找文字",en:"Press ⌘/Ctrl+F to find text in the current conversation"},"input.tip.toc":{zh:"悬停对话左侧的短横线展开目录,点击即可跳回任意一轮提问",en:"Hover the bars on the chat's left edge, then click to jump to a turn"}});const ps=5*1024*1024,di=15e4,fs=25*1024*1024,gs=[{id:"readonly",Icon:Lc,key:"input.approval.readonly",desc:"input.approval.readonlyDesc"},{id:"auto-edit",Icon:Nr,key:"input.approval.autoEdit",desc:"input.approval.autoEditDesc"},{id:"full-auto",Icon:Cr,key:"input.approval.fullAuto",desc:"input.approval.fullAutoDesc",danger:!0},{id:"custom",Icon:zr,key:"input.approval.custom",desc:"input.approval.customDesc"}],an=t=>t.split(/[\\/]/).pop()||t,tu=".t2-chat-view";function nu(t,n,a){const o=t.closest(tu)??t,i=h=>Array.from(h.dataTransfer?.types??[]).includes("Files"),c=h=>{o===t?a(h):o.toggleAttribute("data-filedrop",h)},r=h=>{i(h)&&(h.preventDefault(),h.dataTransfer&&(h.dataTransfer.dropEffect="copy"),c(!0))},u=h=>{o.contains(h.relatedTarget)||c(!1)},d=h=>{i(h)&&(h.preventDefault(),c(!1),h.dataTransfer?.files?.length&&n(h.dataTransfer.files))};return o.addEventListener("dragover",r),o.addEventListener("dragleave",u),o.addEventListener("drop",d),()=>{o.removeEventListener("dragover",r),o.removeEventListener("dragleave",u),o.removeEventListener("drop",d),c(!1)}}const kt=t=>({token:/\s/.test(t)?`"${t}"`:t,name:an(t),kind:"file"}),su=t=>({token:/\s/.test(t)?`"${t}"`:t,name:an(t),kind:"folder"}),au=(t,n)=>{const a=o=>String(o).replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;");return{token:`<forsion-view type="${a(t)}" title="${a(n)}" />`,name:n,kind:"view"}};function vs(t,n){const a=Ai(t,n).trim();return t.kind==="session"?{token:a,name:t.title||"Chat",kind:"session"}:t.kind==="note"?{token:a,name:an(t.path),kind:"note"}:kt(t.path)}function iu(t,n,a,o){if(a){if(n>=t.length)return null;const c=n+1;return{pos:c,val:t[t.length-c]}}if(n===0)return null;const i=n-1;return{pos:i,val:i===0?o:t[t.length-i]}}function ou(t,n,a){return/^\/refine(\s|$)/i.test(a)&&(a="/refine"+a.slice(7)),/^\/refine(\s|$)/.test(a)&&(t||n)?`${a}
13
-
14
- ${t}${n}`.trimEnd():t+n+a}function ru(t,n=200){return t>0?`${Math.min(t,n)}px`:"auto"}function cu(t,n){const a=/(?:^|\s)(\/\S*)$/.exec(t.slice(0,n));return a?{start:n-a[1].length,token:a[1]}:null}const Id=({sessionId:t,advisory:n,approvalTray:a,autoFocus:o,disabled:i,disabledPlaceholder:c,running:r,execConfig:u,teamApproval:d,models:h,modelsResponse:f,modelId:k,onModelChange:x,engines:T,engineId:M,engineModels:A,engineModelId:I,onEngineModelChange:U,engineCommands:_,thinkingLevel:D,onThinkingChange:w,ultra:z,defaultModelIds:S,onDefaultModelChange:g,onContextWindowChange:F,maxIterations:H,onMaxIterationsChange:W,verifyCommand:O,onVerifyCommandChange:E,preset:G,onPresetChange:X,planMode:J,onPlanModeChange:ee,voiceMode:De,onVoiceModeChange:ze,liveOwner:j,liveSessionKey:B,prepareLiveSession:te,skills:ge,groupChat:ve,groupAgents:ye,groupTempAgents:_e,onGroupChange:je,onAddAgent:C,onNormalWork:K,agents:q,onAgentSwitch:Ae,currentAgentSlug:$e,mentionProjects:Je,onNewSession:Me,onBranch:at,onOpenSettings:jt,onExecConfigChange:Le,onSend:bt,onStop:p,quotedText:R,onClearQuote:$,onBtw:Y,contextWindow:de,ctxTokens:he,sessionTokens:Ze,runCost:Oe,costLimit:Fe,ctxInfo:pe,onCompact:Q,seedText:Qe,onSeedConsumed:ho,appendRefs:_n,onAppendRefsConsumed:mo,autoRefFromMain:Hs,sentHistory:Vs,pendingSteer:dt,onCancelSteer:po,onWithdrawSteer:Ks,onSteerNow:Ys})=>{const{t:N,locale:On}=we(),[re,ce]=l.useState(""),[Gs,Xs]=l.useState(0),[fo]=l.useState(()=>!!window.tangu?.mobile||!!window.matchMedia?.("(hover: none)").matches),Js=(fo?eu:ui).filter(s=>!M||s!==Us),[go,Fn]=l.useState(!1),[ht,vo]=l.useState(!1),[Wn,Zs]=l.useState(!1);l.useEffect(()=>{if(!r||ht)return;Xs(Math.floor(Math.random()*ui.length));let s=0;const m=window.setInterval(()=>{Fn(!0),s=window.setTimeout(()=>{Xs(v=>v+1),Fn(!1)},300)},Ql);return()=>{window.clearInterval(m),window.clearTimeout(s),Fn(!1),Zs(!1)}},[r,ht]);const[Un,yo]=l.useState([]),[St,Bt]=l.useState([]),[Nt,un]=l.useState([]),[dn,Bn]=l.useState([]),[Qs,ko]=l.useState(null),Ct=s=>Bn(m=>{const v=new Set(m.map(b=>b.token)),y=[];for(const b of s)v.has(b.token)||(v.add(b.token),y.push(b));return y.length?[...m,...y]:m}),[zt,qn]=l.useState([]),[ea,be]=l.useState(null),[ta,Ie]=l.useState(0),[qt,hn]=l.useState(null),[na,sa]=l.useState(!1),aa=l.useRef(null),[Ee,Re]=l.useState(null),[xo,Ht]=l.useState(!1),[Pe,mt]=l.useState(0),[ia,mn]=l.useState(0),[oa,ra]=l.useState(!1),[wo,Hn]=l.useState(""),[ca,Vn]=l.useState([]),[la,pn]=l.useState(0),[ua,da]=l.useState(!1),[ha,ma]=l.useState(null),Kn=l.useRef(""),[jo,bo]=l.useState(!1),[Vt,Kt]=l.useState(0),pa=l.useRef(""),ke=l.useRef(null),At=l.useRef(null);l.useLayoutEffect(()=>{const s=At.current;if(!s)return;const m=new ResizeObserver(([v])=>vo(v.contentRect.width<=360));return m.observe(s),()=>m.disconnect()},[]);const Yt=l.useMemo(()=>{const s=new Map(ri("desktop").map(m=>[m.name,m]));return m=>{const v=s.get(m);return v?On==="en"?v.en:v.zh:m}},[On]);l.useEffect(()=>{let s=!0;return jr(nt()).then(m=>{s&&yo(m)}),()=>{s=!1}},[]);const So=async()=>{const s=P.getState(),m=Ce,b=([...m?s.messagesBySession[m]||[]:[]].reverse().find(L=>L.role==="assistant")?.content||"").trim();if(!b){s.toast(N("input.slash.nothingToCopy"),!0);return}try{await navigator.clipboard.writeText(b),s.toast(N("input.slash.copied"))}catch{s.toast(N("input.slash.nothingToCopy"),!0)}},No=async()=>{const s=P.getState(),m=Ce;if(![...m?s.messagesBySession[m]||[]:[]].reverse().find(b=>b.role==="user")){s.toast(N("input.slash.nothingToRetry"),!0);return}await s.retry(m)},Co=async()=>{const s=P.getState(),m=Ce;if(!m){s.toast(N("input.slash.nothingToExport"),!0);return}const v=s.sessions.find(oe=>oe.id===m);let y=[];try{let oe=0;for(let ue=0;ue<20;ue++){const Ye=await Dr(Ha(m),m,500,oe||void 0);if(!Ye.length||(y=[...Ye,...y],Ye.length<500)||(oe=Number(Ye[0]?.timestamp)||0,!oe))break}}catch{}if(y.length||(y=s.messagesBySession[m]||[]),!y.length){s.toast(N("input.slash.nothingToExport"),!0);return}const b=v?.title||"Tangu Session",L=["---",`id: ${m}`,`title: ${JSON.stringify(b)}`,...v?.summary?[`summary: ${JSON.stringify(v.summary)}`]:[],...v?.model_id?[`model: ${v.model_id}`]:[],`exported_at: ${new Date().toISOString()}`,"---","",`# ${b}`,""];for(const oe of y){const ue=oe.role==="model"?"assistant":oe.role;if(ue!=="user"&&ue!=="assistant")continue;const Ye=(oe.content||"").trim(),Qt=Array.isArray(oe.tool_calls)?oe.tool_calls:[];if(!Ye&&!Qt.length)continue;L.push(ue==="user"?`## ${N("composer2.exportRoleUser")}`:"## Tangu",""),Ye&&L.push(Ye,"");for(const yt of Qt){const Z=yt?.function?.name||yt?.name||"tool";let Se="";try{Se=String(typeof yt?.function?.arguments=="string"?yt.function.arguments:JSON.stringify(yt?.function?.arguments??""))}catch{Se=""}Se=Se.replace(/\s+/g," ").trim(),L.push(`> 🔧 \`${Z}\`${Se&&Se!=="{}"?` ${Se.length>200?Se.slice(0,200)+"…":Se}`:""}`)}Qt.length&&L.push("");const vt=Array.isArray(oe.attachments)?oe.attachments:[];vt.length&&L.push(`> 📎 ${vt.length} attachment(s)`,"")}const V=new Blob([L.join(`
15
- `)],{type:"text/markdown"}),ne=document.createElement("a");ne.href=URL.createObjectURL(V),ne.download=`tangu-${String(m).slice(0,8)}.md`,ne.click(),setTimeout(()=>URL.revokeObjectURL(ne.href),1e3)},ie=kl(s=>{ce(m=>m?m.replace(/\s+$/,"")+" "+s:s),Kt(0),requestAnimationFrame(se)}),zo=ie.recording||ie.busy,Yn=l.useRef(!1),Ao=()=>{Yn.current=!0,ie.toggle()};l.useEffect(()=>{!Yn.current||ie.recording||ie.busy||(Yn.current=!1,re.trim()&&yn())},[ie.recording,ie.busy]);const Eo=P(s=>s.activeId),Ce=t===void 0?Eo:t,fn=j??t===null,{model:fa,voice:Mo}=ll(),[Gn,ga]=l.useState(!1),[va,ya]=l.useState(""),Ro=l.useSyncExternalStore(hl,qi),gn=!!Ce&&Ro===Ce;l.useEffect(()=>{if(fn)return Hi(s=>{if(s.kind==="activity"){P.getState().pollSession(s.sessionId);return}if(s.kind==="transcript"){const m=()=>{const b=P.getState().messagesBySession[s.sessionId]?.find(L=>L.id===s.messageId);return b?(b.content!==s.text&&P.setState(L=>({messagesBySession:{...L.messagesBySession,[s.sessionId]:(L.messagesBySession[s.sessionId]||[]).map(V=>V.id===s.messageId?{...V,content:s.text}:V)}})),!0):!1};if(m())return;const v=P.subscribe(()=>{m()&&(v(),clearTimeout(y))}),y=setTimeout(v,3e4);return}s.kind==="effort"&&P.setState(m=>m.configBySession[s.sessionId]?{configBySession:{...m.configBySession,[s.sessionId]:{...m.configBySession[s.sessionId],thinkingLevel:s.level,...s.level!=="max"?{ultra:void 0}:{}}}}:{})})},[fn]);const To=async()=>{if(!Gn){ga(!0),ya("");try{let s=B!==void 0?B:Ce;if(!s){const L=P.getState().activeId;s=te?await te():await P.getState().newSession().then(()=>P.getState().activeId),s===L&&(s=null)}if(!s)return;if(Ha(s).key!=="home"){ya(N("livecall.localOnly"));return}const{modelId:v,agentConfig:y}=P.getState().voiceRunParams(s),b={type:"voice-call",params:{sessionId:s,model:fa,voice:Mo,title:N("livecall.title"),agentSlug:y.agentSlug,run:{model_id:v,agent_config:y}}};window.tangu?.openMini?.({view:b,mainView:{type:"chat",params:{sessionId:s}},title:N("livecall.title")})}finally{ga(!1)}}},le=u.execMode==="host",fe=G==="chat",Gt=M?void 0:q?.find(s=>s.slug===$e),Et=u.approvalMode||Gt?.approvalMode||"auto-edit",pt=D||(ve?void 0:Gt?.thinkingLevel)||void 0,it=le&&!fe&&!M&&!ve,Mt=it&&!!z&&pt==="max",{window:ft,stale:$o}=vc({ctxInfo:pe,contextWindow:de,running:r,ultra:Mt,model:f?.models.find(s=>s.id===k),engineUncapped:f?.ultraUncapped}),Xn=$o&&pe?{...pe,ctxWindow:ft||pe.ctxWindow,compactAt:void 0}:pe,[Lo,ka]=l.useState(!1),Xt=(s,m)=>w?m===!0&&!Mt&&!jl()?(ka(!0),!1):(w(s,m),!0):!1,xa=Ft(Ee==="mode",{boundary:".t2-chat-view"}),wa=Ft(Ee==="ctx",{boundary:".t2-chat-view"});l.useEffect(()=>{if(!Ee)return;const s=v=>{v.target?.closest?.("[data-cmenu], [data-keep-menus]")||Re(null)},m=v=>{v.key==="Escape"&&!document.querySelector("[data-keep-menus]")&&Re(null)};return document.addEventListener("mousedown",s),document.addEventListener("keydown",m),()=>{document.removeEventListener("mousedown",s),document.removeEventListener("keydown",m)}},[Ee]);const se=()=>{const s=ke.current;if(s){if(!s.value){s.style.height="";return}s.style.height="auto",s.style.height=ru(s.scrollHeight)}};l.useEffect(()=>{const s=ke.current;if(!s||typeof ResizeObserver>"u")return;let m=s.clientWidth;const v=new ResizeObserver(()=>{s.clientWidth!==m&&(m=s.clientWidth,se())});return v.observe(s),()=>v.disconnect()},[]),l.useLayoutEffect(se,[re]),l.useLayoutEffect(()=>{const s=ke.current;r&&!ht&&!Wn&&s&&!s.value&&s.scrollHeight>s.clientHeight+2&&Zs(!0)},[r,Gs,On,Wn,re,ht]);const ja=s=>{s&&Vt===0&&(pa.current=re);const m=iu(Vs||[],Vt,s,pa.current);m&&(Kt(m.pos),ce(m.val),requestAnimationFrame(()=>{const v=ke.current;v&&(v.focus(),v.selectionStart=v.selectionEnd=m.val.length,mt(m.val.length)),se()}))};l.useEffect(()=>{Qe&&(ce(Qe),ho?.(),requestAnimationFrame(()=>{ke.current?.focus(),se()}))},[Qe]),l.useEffect(()=>{R&&requestAnimationFrame(()=>ke.current?.focus())},[R]),l.useEffect(()=>{_n?.refs.length&&(Ct(_n.refs.map(s=>vs(s,lt||""))),mo?.(),requestAnimationFrame(()=>{ke.current?.focus(),se()}))},[_n?.seq]);const qe=s=>{const m=aa.current,v=m?.start??0,y=m?.end??1/0;ce(L=>L.slice(0,v)+s+L.slice(y));const b=v+s.length;return requestAnimationFrame(()=>{const L=ke.current;L&&(!P.getState().feedbackOpen&&!document.querySelector("[data-keep-menus]")&&L.focus(),L.selectionStart=L.selectionEnd=b,mt(b)),se()}),v},ba=l.useMemo(()=>{const s=()=>{qe(""),hn(null)},m=P.getState,v={"/stop":r?()=>{p(),s()}:void 0,"/new":Me?()=>{Me(),s()}:void 0,"/branch":at?()=>{at(),s()}:void 0,"/compact":Q?()=>{Q(),s()}:void 0,"/plan":ee&&!fe?()=>{ee(!J),s()}:void 0,"/chat":X?()=>{X("chat"),s()}:()=>{m().toast(N("input.presetLocked")),s()},"/work":X?()=>{X("work"),s()}:()=>{m().toast(N("input.presetLocked")),s()},"/voice":ze?()=>{ze(!De),s()}:void 0,"/model":x&&h?.length?()=>{hn({start:qe("/model ")}),Ie(0)}:void 0,"/loop":W?()=>{qe("/loop "),Ie(0)}:void 0,"/verify":le&&E?()=>{qe("/verify "),Ie(0)}:void 0,"/think":w?()=>{qe("/think"),Ie(0)}:void 0,"/refine":le?()=>{qe("/refine "),Ie(0)}:void 0,"/approval":()=>{Re("mode"),s()},"/help":()=>{m().openSettings("about"),s()},"/feedback":window.tangu?.submitFeedback?()=>{m().openFeedback()&&s()}:void 0,"/btw":Y?()=>{qe("/btw "),Ie(0)}:void 0,"/skills":()=>{m().openSettings("skills"),s()},"/tools":()=>{m().openSettings("agents"),s()},"/agents":()=>{m().openSettings("agents"),s()},"/agent":()=>{m().openSettings("agents"),s()},"/mcp":()=>{m().openSettings("mcp"),s()},"/plugins":()=>{m().openSettings("plugins"),s()},"/memory":()=>{m().openSettings("forsion/f-sync"),s()},"/config":()=>{m().openSettings("general"),s()},"/login":window.tangu?.forsionLogin?()=>{m().openSettings("forsion"),s()}:void 0,"/historian":()=>{m().setActiveSpecial("agents"),s()},"/muse":()=>{m().setActiveSpecial("agents"),s()},"/groupchat":je&&!fe?()=>{Ht(!0),s()}:void 0,"/sessions":()=>{m().setActiveId(null),s()},"/cost":()=>{m().pushNotice(`${(Ze??0).toLocaleString()} tokens · ${N("input.ctxLabel")} ${(he??0).toLocaleString()}/${(ft??0).toLocaleString()}`+(Oe!=null&&Fe!=null&&Fe>0?` · ${N("input.runCost",{used:Math.round(Oe).toLocaleString(),limit:Fe.toLocaleString()})}`:"")),s()},"/status":()=>{m().pushNotice([`${N("input.slash.status")}`,`model=${k||"-"}`,`think=${pt||"medium"}${pe?.thinkingRequested===(pt||"medium")&&pe.thinkingEffective&&pe.thinkingEffective!==pe.thinkingRequested?`→${pe.thinkingEffective}`:""}`,`approval=${u.approvalMode||Gt?.approvalMode||(u.execMode==="host"?"auto-edit":"full-auto")} (${u.approvalMode?"session":Gt?.approvalMode?"agent":"default"})`,`cwd=${u.cwd||"-"}`,`loop=${H||pe?.maxIterations||90} (${H?"session":pe?.maxIterationsSource||"default"})`,`verify=${O||"-"}`,`tokens=${(Ze??0).toLocaleString()}`,`cost=${Oe!=null?Math.round(Oe).toLocaleString():"-"}${Fe!=null&&Fe>0?`/${Fe.toLocaleString()}`:""}`].join(`
16
- `)),s()},"/copy":()=>{So(),s()},"/retry":()=>{No(),s()},"/export":()=>{Co(),s()}},y=[];if(r){const b=v["/stop"];b&&y.push({cmd:"/stop",desc:Yt("/stop"),run:b})}if(M){Me&&y.push({cmd:"/new",desc:Yt("/new"),run:()=>{Me(),s()}}),v["/feedback"]&&y.push({cmd:"/feedback",desc:Yt("/feedback"),run:v["/feedback"]});for(const b of _||[])b.name.replace(/^\//,"").toLowerCase()==="feedback"&&v["/feedback"]||y.push({cmd:`/${b.name}`,desc:b.hint?`${b.description} · ${b.hint}`:b.description,run:()=>{qe(`/${b.name} `),Ie(0)}});return y}if(w){const b=M?void 0:h?.find(L=>L.id===k)?.thinkingLevels;for(const L of jn){const V=!!b&&!b.includes(L);y.push({cmd:`/think ${L}`,desc:`${N("input.slash.thinkDesc",{level:js(L,N)})}${V?` ${N("pill.thinkUnsupported")}`:""}${!Mt&&pt===L?N("input.slash.current"):""}`,run:()=>{Xt(L,it?!1:void 0),s()}})}it&&y.push({cmd:"/think ultra",desc:`${N("pill.ultraTitle")}${Mt?N("input.slash.current"):""}`,run:()=>{Xt("max",!0),s()}})}for(const b of ri("desktop")){if(b.name==="/stop")continue;const L=v[b.name];L&&y.push({cmd:b.arg?`${b.name} ${b.arg}`:b.name,desc:Yt(b.name),run:L})}for(const b of Un)y.push({cmd:b.argHint?`/${b.name} ${b.argHint}`:`/${b.name}`,desc:b.description,run:()=>{qe(`/${b.name} `),Ie(0)}});if(ge?.length)for(const b of ge)y.push({cmd:`/skill:${b.id}`,desc:N("input.slash.skillUse",{name:b.name}),run:()=>{qn(L=>L.some(V=>V.id===b.id)?L:[...L,b]),s()}});return y},[r,p,J,De,ze,pt,H,W,O,E,h,k,ge,ee,w,x,Me,at,Q,je,fe,X,M,_,Un,Yt,u,Gt,Ze,he,ft,Oe,Fe,pe,!!Y,it,Mt]),He=l.useMemo(()=>{if(i||na)return null;const s=re.slice(0,Pe);if(qt&&s.startsWith("/model ",qt.start))return{start:qt.start,token:s.slice(qt.start),sub:"model"};const m=cu(re,Pe);return m?{...m,sub:null}:null},[re,Pe,i,na,qt]);aa.current=He?{start:He.start,end:Pe}:null;const ot=l.useMemo(()=>{if(!He)return[];if(He.sub==="model"){const v=He.token.slice(7).toLowerCase();return(h||[]).filter(y=>!v||y.id.toLowerCase().includes(v)||y.name.toLowerCase().includes(v)).slice(0,12).map(y=>({cmd:y.id===k?`● ${y.name}`:y.name,desc:`${y.source==="direct"?N("input.directPrefix"):""}${y.provider} · ${y.id}`,run:()=>{x?.(y.id),qe(""),hn(null)}}))}const s=He.token.toLowerCase(),m=s.startsWith("/th");return ba.filter(v=>(m||!v.cmd.startsWith("/think "))&&(v.cmd.toLowerCase().startsWith(s)||s.length>1&&v.desc.toLowerCase().includes(s.slice(1)))).slice(0,10)},[He,ba,h,k]),Rt=!!He&&ot.length>0;l.useEffect(()=>{Ie(0)},[He?.start,He?.token]);const Jt=!!ve&&(ye?.length||0)>=2,[Io,Sa]=l.useState([]),Zt=!!Je?.length,Na=l.useMemo(()=>{if(Zt)return(Je||[]).map(v=>({slug:v.path,name:v.name,description:v.path}));if(!Jt)return q||[];const s=(q||[]).filter(v=>ye.includes(v.slug)),m=new Set(s.map(v=>v.slug));return[...s,...(_e||[]).filter(v=>!m.has(v.slug))]},[Jt,q,ye,_e,Zt,Je]),rt=l.useMemo(()=>{if(i||Rt||oa)return null;const s=/(?:^|\s)@([^\s@]*)$/.exec(re.slice(0,Pe));return s?{query:s[1],start:Pe-s[1].length-1}:null},[re,Pe,i,Rt,oa]),ct=l.useMemo(()=>{if(!rt)return[];const s=rt.query.toLowerCase();return Na.filter(m=>!s||m.name.toLowerCase().includes(s)||m.slug.toLowerCase().includes(s)).slice(0,10)},[rt,Na]),Ca=!!rt&&ct.length>0;l.useEffect(()=>{mn(0)},[rt?.start,rt?.query]);const za=s=>{if(!rt)return;const m=re.slice(0,rt.start),v=`@${s.name} `,y=m+v+re.slice(Pe);ce(y),Zt?Sa(L=>L.some(V=>V.path===s.slug)?L:[...L,{name:s.name,path:s.slug}]):Jt?Hn(s.slug):Vn(L=>L.includes(s.slug)?L:[...L,s.slug]);const b=m.length+v.length;requestAnimationFrame(()=>{const L=ke.current;L&&(L.focus(),L.selectionStart=L.selectionEnd=b,mt(b)),se()})},Ve=l.useMemo(()=>{if(i||Rt||ua)return null;const s=/\[\[([^\]\n]*)$/.exec(re.slice(0,Pe));return s?{query:s[1],start:Pe-s[1].length-2}:null},[re,Pe,i,Rt,ua]);l.useEffect(()=>{if(!Ve||!le)return;window.amadeus&&br();const s=u.cwd;if(!s||Kn.current===s)return;Kn.current=s,ma(null);const m=new Set(["node_modules","dist","build","out","target",".git",".venv","venv","__pycache__"]);(async()=>{const y=[],b=[{dir:s,rel:"",depth:0}];for(;b.length&&y.length<2e3;){const{dir:L,rel:V,depth:ne}=b.shift();let oe=[];try{oe=await window.tangu?.listDir?.(L)||[]}catch{continue}for(const ue of oe)if(!ue.name.startsWith(".")){if(ue.isDir)ne<8&&!m.has(ue.name)&&b.push({dir:ue.path,rel:V?`${V}/${ue.name}`:ue.name,depth:ne+1});else if(y.push(V?`${V}/${ue.name}`:ue.name),y.length>=2e3)break}}return y})().then(y=>{Kn.current===s&&ma(y)}).catch(()=>{})},[Ve,u.cwd,le]);const Aa=nn(s=>s.pages),lt=nn(s=>s.vaultRoot),Ea=nn(s=>s.icons),Ma=P(s=>s.sessions),Tt=Xa(s=>s.pendingPrompt),gt=Za(s=>s.pending);l.useEffect(()=>{!gt||gt.sessionId!==Ce||!At.current?.closest("[data-image-studio-chat]")||!At.current.getClientRects().length||Za.getState().consume(gt.seq)&&(ce(s=>s.trim()?`${s}
17
-
18
- ${gt.text}`:gt.text),Bt(s=>[...s,...gt.attachments]),requestAnimationFrame(()=>{ke.current?.focus(),se()}))},[gt,Ce]),l.useEffect(()=>{if(!Tt||!At.current?.getClientRects().length)return;const s=P.getState(),m=Ce?s.sessions.find(v=>v.id===Ce)?.project_path:s.newChatWs?.path;Ja(m||"")!==Ja(Tt.project)||!Xa.getState().consumePrompt(Tt.seq)||(ce(v=>v.trim()?`${v}
19
-
20
- ${Tt.text}`:Tt.text),requestAnimationFrame(()=>{ke.current?.focus(),se()}))},[Tt,Ce]);const ut=l.useMemo(()=>{if(!Ve)return[];const s=Ve.query.toLowerCase(),m=[...le?Aa.map(b=>({p:b,note:!0})):[],...le?(ha??[]).map(b=>({p:b})):[],...Ma.filter(b=>b.id!==Ce).slice(0,300).map(b=>({p:_t(b.title,N),session:{id:b.id,title:_t(b.title,N),summary:b.summary}}))],v=s?m.filter(b=>b.p.toLowerCase().includes(s)):m,y=b=>{const L=(b.note?b.p.replace(/\.md$/i,""):b.p).split("/").pop().toLowerCase();return(L.startsWith(s)?0:L.includes(s)?1:2)*1e4+b.p.length};return[...v].sort((b,L)=>y(b)-y(L)).slice(0,10)},[Ve,ha,Aa,Ma,Ce,le,N]),Jn=!!Ve&&ut.length>0;l.useEffect(()=>{pn(0)},[Ve?.start,Ve?.query]);const Ra=s=>{if(!Ve)return;const m=(s.session?Ai({kind:"session",id:s.session.id,title:s.session.title},lt||""):s.note&&lt?Pr(lt,s.p):/\s/.test(s.p)?`"${s.p}"`:s.p).trim();Ct([{token:m,name:s.session?s.session.title:an(s.p),kind:s.session?"session":s.note?"note":"file"}]);const v=re.slice(0,Ve.start);ce(v+re.slice(Pe)),requestAnimationFrame(()=>{const y=ke.current;y&&(y.focus(),y.selectionStart=y.selectionEnd=v.length,mt(v.length)),se()})},Ta=nn(s=>s.activePage??s.activeNotePath),$t=bn(s=>Dl(s.mainTabs)),vn=l.useMemo(()=>{if(!le||!Hs||!$t)return null;const s=$t==="note"?Ta:$t.startsWith("note:")?$t.slice(5):"",m=s?lt?vs({kind:"note",path:s},lt):null:kt($t.slice(5));return!m||Qs===m.token||dn.some(v=>v.token===m.token)?null:m},[le,Hs,$t,Ta,lt,Qs,dn]),et=vn?[vn,...dn]:dn,$a=s=>{const m=(s??re).trim(),v=s==null?m:"",y=/^\/feedback(?:\s+([\s\S]*))?$/i.exec(v);if(y&&window.tangu?.submitFeedback){P.getState().openFeedback(y[1]?.trim())&&(ce(""),requestAnimationFrame(se));return}const b=/^\/(?:btw|side)(?:\s+([\s\S]*))?$/i.exec(v);if(b&&Y){Y(b[1]?.trim()||void 0,R||void 0),R&&$?.(),ce(""),requestAnimationFrame(se);return}if(!m&&!et.length)return;const L=/^\/compact(?:\s+([\s\S]+))?$/i.exec(v);if(L&&Q){Q((L[1]||"").trim()||void 0),ce(""),requestAnimationFrame(se);return}const V=/^\/loop(?:\s+(\d+))?$/i.exec(v);if(V&&W){if(V[1]){const Z=Math.min(Math.max(1,parseInt(V[1],10)),200);W(Z),be(N("input.slash.loopSet",{n:Z}))}else be(N("input.slash.loop",{current:H||pe?.maxIterations||90}));ce(""),requestAnimationFrame(se);return}const ne=/^\/verify(?:\s+([\s\S]+))?$/i.exec(v);if(ne&&le&&E){const Z=(ne[1]||"").trim();Z?/^(off|clear|关闭)$/i.test(Z)?(E(""),be(N("input.slash.verifyCleared"))):(E(Z),be(N("input.slash.verifySet",{cmd:Z}))):be(N("input.slash.verifyUsage",{current:O||N("input.slash.verifyNone")})),ce(""),requestAnimationFrame(se);return}if(ze&&/^\/(voice|text)$/i.test(v)){const Z=/^\/voice$/i.test(m);ze(Z),be(N(Z?"input.slash.voiceOnHint":"input.slash.voiceOffHint")),ce(""),requestAnimationFrame(se);return}const oe=/^\/(?:think|effort)(?:\s+(\S+))?$/i.exec(v);if(oe&&w){const Z=(oe[1]||"").toLowerCase();it&&Z==="ultra"?Xt("max",!0)&&be(N("input.slash.thinkSet",{level:N("pill.ultra")})):jn.includes(Z)?(Xt(Z,it?!1:void 0),be(N("input.slash.thinkSet",{level:js(Z,N)}))):be(N("input.slash.thinkUsage",{levels:[...jn,...it?["ultra"]:[]].join("|")})),ce(""),requestAnimationFrame(se);return}const ue=/^\/([a-z0-9][a-z0-9-]*)(?:\s+([\s\S]*))?$/i.exec(v);if(ue&&Un.some(Z=>Z.name===ue[1].toLowerCase())){const Z=ue[1].toLowerCase(),Se=ue[2]||"";ce(""),requestAnimationFrame(se),Ir(nt(),Z,Se).then(Lt=>bt(Lt,[],[],void 0,void 0)).catch(Lt=>be(String(Lt?.message||Lt)));return}if(i)return;if(gn&&!s&&m&&m.length<=ml&&!St.length&&!Nt.length&&!et.length&&!R&&!zt.length)return ce(""),Kt(0),be(null),requestAnimationFrame(se),pl(Ce,m).then(async Z=>{if(Z)return!0;const Se=await Promise.resolve($a(m)).catch(()=>!1)??!1;return Se?be(N("livecall.textFallback")):ce(Lt=>Lt||m),Se});const Ye=R?`${R.split(`
21
- `).map(Z=>`> ${Z}`).join(`
22
- `)}
23
-
24
- `:"",Qt=et.length?et.map(Z=>Z.token).join(" ")+`
25
- `:"",vt=ou(Qt,Ye,m);if(vt.length>di){be(N("input.tooLong",{len:vt.length.toLocaleString(),max:di.toLocaleString()}));return}be(null);const yt=Zt?{mentionProjects:(()=>{const Z=Io.filter(Se=>vt.includes(`@${Se.name}`));return Z.length?Z:void 0})()}:Jt?{priorityAgent:wo||void 0}:{mentionAgents:ca.length?ca:void 0};return bt(vt,St,Nt,zt.map(Z=>Z.id),yt).then(Z=>Z?(s||(ce(""),Kt(0)),Bt([]),un([]),Bn([]),qn([]),Hn(""),Vn([]),Sa([]),$?.(),requestAnimationFrame(se),!0):!1)},yn=()=>{$a()},La=async s=>{if(!s)return;const m=[],v=[];for(const y of Array.from(s)){if(!y.type.startsWith("image/")){v.push(N("input.skip.notImage",{name:y.name}));continue}if(y.size>ps){v.push(N("input.skip.tooBig",{name:y.name,mb:String(Math.round(ps/1024/1024))}));continue}const b=await y.arrayBuffer();let L="";const V=new Uint8Array(b);for(let ne=0;ne<V.length;ne+=32768)L+=String.fromCharCode(...V.subarray(ne,ne+32768));m.push({name:y.name,mimeType:y.type,data:btoa(L),size:y.size})}be(v.length?N("input.skip.imageHint",{items:v.join(N("composer2.listSep"))}):null),Bt(y=>[...y,...m])},Zn=async s=>{if(!s)return;const m=[],v=[];for(const y of Array.from(s)){if(y.size>fs){v.push(N("input.skip.tooBig",{name:y.name,mb:String(Math.round(fs/1024/1024))}));continue}const b=await y.arrayBuffer();let L="";const V=new Uint8Array(b);for(let ne=0;ne<V.length;ne+=32768)L+=String.fromCharCode(...V.subarray(ne,ne+32768));m.push({name:y.name,mimeType:y.type||"application/octet-stream",data:btoa(L),size:y.size})}be(v.length?N("input.skip.simple",{items:v.join(N("composer2.listSep"))}):null),un(y=>[...y,...m])},Ia=s=>{if(s.length){if(le&&window.tangu?.getPathForFile){const m=Array.from(s).map(v=>{try{return window.tangu.getPathForFile(v)}catch{return""}}).filter(Boolean);if(m.length){Ct(m.map(kt)),requestAnimationFrame(()=>{ke.current?.focus(),se()});return}}Zn(s)}},Pa=l.useRef(Ia);Pa.current=Ia,l.useEffect(()=>{const s=At.current;return s?nu(s,m=>Pa.current(m),bo):void 0},[]);const Po=async s=>{if(!s?.length)return;const m=Array.from(s).filter(y=>y.type.startsWith("image/")),v=Array.from(s).filter(y=>!y.type.startsWith("image/"));if(m.length){const y=new DataTransfer;m.forEach(b=>y.items.add(b)),await La(y.files)}if(v.length){const y=new DataTransfer;v.forEach(b=>y.items.add(b)),await Zn(y.files)}},Do=async s=>{const m=[],v=[],y=[];for(const b of s){if(b.isDirectory){y.push(su(b.path));continue}try{const L=await window.tangu?.readHostFile?.(b.path);if(!L||L.tooLarge){y.push(kt(b.path));continue}const V={name:an(b.path),mimeType:L.mimeType,data:L.content,size:L.size};L.mimeType.startsWith("image/")&&L.size<=ps?m.push(V):L.size<=fs?v.push(V):y.push(kt(b.path))}catch{y.push(kt(b.path))}}m.length&&Bt(b=>[...b,...m]),v.length&&un(b=>[...b,...v]),y.length&&Ct(y)},_o=s=>{Ct([s.kind==="view"?au(s.type,s.title):vs(s,lt||"")]),requestAnimationFrame(()=>ke.current?.focus())},[Oo,Da]=l.useState(!1),Fo=P(s=>s.cfg),Wo=s=>{Le({execMode:"host",approvalMode:s,cwd:u.cwd}),Re(null)},_a=Sr(),Uo=l.useMemo(()=>yc(h||[],_a),[h,_a]),Ke=!!ve&&(ye?.length||0)>=2,Bo=!!fa&&fn&&!!window.tangu?.openMini&&!(J&&!fe)&&!Ke&&!fe&&!M,Qn=gs.find(s=>s.id===Et)||gs[1],qo=Ke?N("group.modeLabel",{n:ye.length}):N(J&&!fe?"input.planMode":fe?"input.presetChat":le?Qn.key:"input.normal"),Ho=Ke?ks:J&&!fe?qa:le?Qn.Icon:Dn,Oa=!Ke&&!(J&&!fe)&&!fe&&le&&Qn.id==="full-auto",Vo=!fe&&(!!ee||le||!!je||!!Ae),Ko=(T||[]).find(s=>s.id===M)?.name||N("input.engineDefault"),xe=!!M,Yo=xe?[{label:Ko,options:A||[]}]:Uo.map(s=>({key:s.key,label:s.provider,source:s.source,options:s.models.map(m=>({...m,description:`${m.provider} · ${m.id}`}))})),Go=xe||!!x||!!w;return e.jsxs("div",{className:"t2c",children:[xo&&e.jsx(zl,{agents:q||[],models:h,initialAgents:ye||[],initialTempAgents:_e,active:Ke,hideDisable:!0,onConfirm:s=>{je?.({groupChat:!0,...s}),Ht(!1),Ar("chat.group")},onDisable:()=>je?.({groupChat:!1}),onClose:()=>Ht(!1)}),e.jsxs("div",{className:"t2c-inner",children:[!!dt?.length&&e.jsxs("div",{className:"t2c-steer",role:"status","aria-label":N("input.steer.waiting"),children:[dt.map(s=>e.jsxs("div",{className:"t2c-steer-item",children:[e.jsx(Nc,{size:12,className:"t2c-steer-ic"}),e.jsx("span",{className:"t2c-steer-text",title:s.text,children:s.text}),e.jsx("button",{className:"t2c-steer-x",title:N("input.steer.remove"),onClick:()=>po?.(s.id),children:e.jsx(tt,{size:12})})]},s.id)),e.jsxs("div",{className:"t2c-steer-foot",children:[e.jsx("span",{className:"t2c-steer-hint",children:N(dt.some(s=>s.localOnly)?"input.steer.queuedHint":"input.steer.hint")}),Ys&&dt.some(s=>!s.localOnly)&&e.jsxs("button",{className:"t2c-steer-now",onClick:Ys,children:[e.jsx(Er,{size:11})," ",N("input.steer.now")]})]})]}),a,e.jsxs(Mr,{ref:At,className:jo?"dragover":void 0,children:[n,ea&&e.jsx("div",{className:"t2c-hint",children:ea}),R&&e.jsxs("div",{className:"t2c-quote",children:[e.jsx("span",{className:"t2c-quote-text",children:R.length>280?`${R.slice(0,280)}…`:R}),e.jsx("button",{title:N("input.remove"),onClick:()=>$?.(),className:"t2c-quote-x",children:e.jsx(tt,{size:12})})]}),et.length>0&&e.jsxs("div",{className:"t2c-chiprow t2c-refrow",role:"group","aria-label":N("input.ref.selected"),children:[e.jsx("span",{className:"t2c-reflabel",children:N("input.ref.selected")}),et.map(s=>e.jsx(_l,{chip:s,removeTitle:N("input.remove"),onRemove:()=>{vn&&s.token===vn.token?ko(s.token):Bn(m=>m.filter(v=>v.token!==s.token))}},s.token))]}),St.length>0&&e.jsx("div",{className:"t2c-chiprow",children:St.map((s,m)=>e.jsxs("span",{className:"attach-chip",children:[s.mimeType.startsWith("image/")&&e.jsx("img",{src:`data:${s.mimeType};base64,${s.data}`,alt:s.name}),e.jsx("span",{children:s.name}),e.jsx("button",{title:N("input.remove"),onClick:()=>Bt(St.filter((v,y)=>y!==m)),children:e.jsx(tt,{size:12})})]},`${s.name}-${m}`))}),Nt.length>0&&e.jsx("div",{className:"t2c-chiprow",children:Nt.map((s,m)=>e.jsxs("span",{className:"attach-chip",title:N("input.wsUploadTitle",{name:s.name}),children:[s.mimeType.startsWith("image/")?e.jsx("img",{src:`data:${s.mimeType};base64,${s.data}`,alt:s.name}):e.jsx(_s,{size:14,style:{color:"var(--accent-ink)",flexShrink:0}}),e.jsx("span",{children:s.name}),e.jsx("span",{style:{fontSize:"var(--ui-font-caption, 11px)",color:"var(--text-faint)",flexShrink:0},children:N("input.toWorkspace")}),e.jsx("button",{title:N("input.remove"),onClick:()=>un(Nt.filter((v,y)=>y!==m)),children:e.jsx(tt,{size:12})})]},`ws-${s.name}-${m}`))}),zt.length>0&&e.jsx("div",{className:"t2c-chiprow",children:zt.map(s=>e.jsxs("span",{className:"attach-chip",title:N("input.skillChipTitle"),children:[e.jsx(ji,{size:13,style:{color:"var(--accent-ink)",flexShrink:0}}),e.jsx("span",{children:s.name}),e.jsx("button",{title:N("input.remove"),onClick:()=>qn(zt.filter(m=>m.id!==s.id)),children:e.jsx(tt,{size:12})})]},`skill-${s.id}`))}),e.jsx(Rr,{autoSize:!1,ref:ke,className:"t2c-ta",rows:1,autoFocus:o,value:re,placeholder:i?c||N("input.placeholderDisabled"):gn?N("livecall.typeHint"):r?ht?N("input.runningPlaceholder"):N("input.tip",{tip:N(Js[Gs%Js.length])}):N("input.placeholder"),"data-tip-fade":r&&!ht&&go||void 0,"data-tip-tall":r&&!ht&&Wn||void 0,disabled:i,onChange:s=>{ce(s.target.value),mt(s.target.selectionStart||0),sa(!1),ra(!1),da(!1),Vt&&Kt(0),s.target.value.includes("@")||(Hn(""),Vn([])),se()},onSelect:s=>mt(s.target.selectionStart||0),onPaste:s=>{const m=s.clipboardData?.files;if(!m?.length)return;s.preventDefault();const v=Array.from(m),y=v.filter(V=>V.type.startsWith("image/")),b=v.filter(V=>!V.type.startsWith("image/")),L=[];if(b.length){const V=[];for(const ne of b){let oe="";if(le)try{oe=window.tangu?.getPathForFile?.(ne)||""}catch{oe=""}oe?V.push(oe):L.push(ne)}V.length&&(Ct(V.map(kt)),requestAnimationFrame(()=>{ke.current?.focus(),se()}))}if(y.length){const V=new DataTransfer;y.forEach(ne=>V.items.add(ne)),La(V.files)}if(L.length){const V=new DataTransfer;L.forEach(ne=>V.items.add(ne)),Zn(V.files)}},onKeyDown:s=>{if(Jn){if(s.key==="ArrowDown"){s.preventDefault(),pn(m=>(m+1)%ut.length);return}if(s.key==="ArrowUp"){s.preventDefault(),pn(m=>(m-1+ut.length)%ut.length);return}if((s.key==="Enter"||s.key==="Tab")&&!s.nativeEvent.isComposing){s.preventDefault(),Ra(ut[Math.min(la,ut.length-1)]);return}if(s.key==="Escape"){s.preventDefault(),da(!0);return}}if(Ca){if(s.key==="ArrowDown"){s.preventDefault(),mn(m=>(m+1)%ct.length);return}if(s.key==="ArrowUp"){s.preventDefault(),mn(m=>(m-1+ct.length)%ct.length);return}if((s.key==="Enter"||s.key==="Tab")&&!s.nativeEvent.isComposing){s.preventDefault(),za(ct[Math.min(ia,ct.length-1)]);return}if(s.key==="Escape"){s.preventDefault(),ra(!0);return}}if(Rt){if(s.key==="ArrowDown"){s.preventDefault(),Ie(m=>(m+1)%ot.length);return}if(s.key==="ArrowUp"){s.preventDefault(),Ie(m=>(m-1+ot.length)%ot.length);return}if((s.key==="Enter"||s.key==="Tab")&&!s.nativeEvent.isComposing){s.preventDefault(),ot[Math.min(ta,ot.length-1)]?.run();return}if(s.key==="Escape"){s.preventDefault(),sa(!0),hn(null);return}}if(s.key==="ArrowUp"&&dt?.length&&Ks&&Vt===0&&s.currentTarget.selectionStart===s.currentTarget.selectionEnd&&re.slice(0,s.currentTarget.selectionStart).indexOf(`
26
- `)===-1){s.preventDefault();const m=dt[dt.length-1];Ks(m.id).then(v=>{v&&(ce(y=>y.trim()?`${v}
27
-
28
- ${y}`:v),requestAnimationFrame(()=>{const y=ke.current;y&&(y.focus(),y.selectionStart=y.selectionEnd=v.length,mt(v.length)),se()}))});return}if(s.key==="ArrowUp"&&s.currentTarget.selectionStart===s.currentTarget.selectionEnd&&re.slice(0,s.currentTarget.selectionStart).indexOf(`
29
- `)===-1&&Vs?.length){s.preventDefault(),ja(!0);return}if(s.key==="ArrowDown"&&Vt>0&&s.currentTarget.selectionStart===s.currentTarget.selectionEnd&&re.slice(s.currentTarget.selectionStart).indexOf(`
30
- `)===-1){s.preventDefault(),ja(!1);return}s.key==="Enter"&&!s.shiftKey&&!s.nativeEvent.isComposing&&(s.preventDefault(),yn())}}),Rt&&e.jsx("div",{className:"t2c-menu",children:ot.map((s,m)=>e.jsxs("button",{className:"t2c-menu-item","data-active":m===Math.min(ta,ot.length-1)||void 0,onMouseEnter:()=>Ie(m),onClick:()=>s.run(),children:[e.jsx("span",{className:"t2c-menu-cmd",children:s.cmd}),e.jsx("span",{className:"t2c-menu-desc",children:s.desc})]},`${s.cmd}-${m}`))}),Ca&&!Jn&&e.jsxs("div",{className:"t2c-menu",children:[e.jsx("div",{className:"t2c-menu-sec",children:N(Zt?"input.mention.projectNote":Jt?"input.mention.groupNote":"input.mention.delegateNote")}),ct.map((s,m)=>e.jsxs("button",{className:"t2c-menu-item","data-active":m===Math.min(ia,ct.length-1)||void 0,onMouseEnter:()=>mn(m),onClick:()=>za(s),children:[e.jsxs("span",{className:"t2c-menu-cmd",children:["@",s.name]}),e.jsx("span",{className:"t2c-menu-desc",children:s.description||s.slug})]},s.slug))]}),Jn&&e.jsxs("div",{className:"t2c-menu",children:[e.jsx("div",{className:"t2c-menu-sec",children:N("input.fileref.note")}),ut.map((s,m)=>e.jsxs("button",{className:"t2c-menu-item","data-active":m===Math.min(la,ut.length-1)||void 0,onMouseEnter:()=>pn(m),onClick:()=>Ra(s),children:[e.jsx("span",{className:"t2c-menu-cmd",children:s.session?`💬 ${s.session.title}`:s.note?`${Ea[s.p]?`${Ea[s.p]} `:""}${s.p.split("/").pop().replace(/\.md$/i,"")}`:s.p.split("/").pop()}),e.jsx("span",{className:"t2c-menu-desc",children:s.session?s.session.summary||N("input.fileref.session"):s.p})]},s.session?`s:${s.session.id}`:(s.note?"n:":"f:")+s.p))]}),e.jsxs(Tr,{children:[e.jsx(Il,{open:Ee==="add",disabled:i,activeSessionId:Ce,canUsePathPicker:le,onOpenChange:s=>Re(s?"add":null),onNewSession:Me,onAddAgent:!r&&!fe&&!xe?C||(je?()=>Ht(!0):void 0):void 0,onPickPaths:Do,onPickFiles:Po,onAddReference:_o}),zo?e.jsx(wl,{analyser:ie.analyser,recording:ie.recording,busy:ie.busy,onStop:ie.toggle,onSend:Ao,t:N}):e.jsxs(e.Fragment,{children:[Vo&&e.jsxs("span",{className:`mode-pill-wrap t2c-capsule-peer${Ee==="mode"?" is-open":""}`,"data-cmenu":!0,children:[e.jsxs("button",{className:`t2c-pill mode-pill-btn${Ee==="mode"?" is-open":""}${J&&!fe?" active":""}`,"data-danger":Oa||void 0,title:N(Oa?"input.approval.fullAutoDesc":"input.modeChipTitle"),"aria-expanded":Ee==="mode",onClick:()=>Re(s=>s==="mode"?null:"mode"),children:[e.jsx(Ho,{size:13}),e.jsx("span",{className:"t2c-pill-label",children:qo}),e.jsx(rn,{size:10})]}),Ee==="mode"&&e.jsxs("div",{ref:xa.ref,className:"composer-menu composer-menu--mode",style:xa.style,children:[K&&!fe&&e.jsx(Pl,{active:!J&&!Ke&&Et==="auto-edit",disabled:r,agents:q||[],currentAgentSlug:$e,onNormalWork:K,onAgentSwitch:!xe&&!Ke?Ae:void 0,onClose:()=>Re(null)}),ee&&!fe&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"menu-section",children:N("input.planMode")}),e.jsxs("button",{className:`menu-item${J?" active":""}`,onClick:()=>{ee(!J),Re(null)},children:[e.jsx(qa,{size:14}),e.jsx("span",{className:"grow",children:N(J?"input.planModeOn":"input.planModeEnable")}),J&&e.jsx(Xe,{size:13})]})]}),je&&!xe&&!fe&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"menu-section",children:N("group.menu.section")}),e.jsxs("button",{className:`menu-item${Ke?" active":""}`,onClick:()=>{Ht(!0),Re(null)},children:[e.jsx(ks,{size:14}),e.jsx("span",{className:"grow",children:Ke?N("group.menu.configured",{n:ye.length}):N("group.menu.enable")}),Ke&&e.jsx(Xe,{size:13})]})]}),le&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"menu-section",children:N(d?"input.approvalSection.team":"input.approvalSection")}),gs.map(({id:s,Icon:m,key:v,desc:y,...b})=>e.jsxs("button",{className:`menu-item approval-item${Et===s?" active":""}${"danger"in b?" danger":""}`,"aria-describedby":`approval-mode-desc-${s}`,onClick:()=>Wo(s),children:[e.jsx(m,{size:15,className:"approval-ic"}),e.jsx("span",{className:"grow approval-title",children:N(v)}),Et===s&&e.jsx(Xe,{size:13,className:"approval-ck"}),e.jsx("span",{id:`approval-mode-desc-${s}`,role:"tooltip",className:"approval-hover-desc",children:N(y)})]},s)),Et==="custom"&&e.jsxs("button",{className:"menu-item approval-item","aria-describedby":"approval-edit-rules-desc",onClick:()=>{Da(!0),Re(null)},children:[e.jsx($r,{size:15,className:"approval-ic"}),e.jsx("span",{className:"grow approval-title",children:N("input.approval.editRules")}),e.jsx("span",{id:"approval-edit-rules-desc",role:"tooltip",className:"approval-hover-desc",children:N("input.approval.editRulesDesc")})]})]})]})]}),e.jsx("span",{className:"t2c-grow"}),!fe&&!!ft&&ft>0&&(()=>{const s=Math.min(100,Math.round((he||0)/ft*100)),m=Xn?.compactAt?(he||0)>=Xn.compactAt*.8:s>=80,v=9,y=2*Math.PI*v;return e.jsxs("span",{className:`t2c-ctxring t2c-collapse-on-capsule-open${Ee==="ctx"?" is-open":""}`,"data-warn":m||void 0,"data-cmenu":!0,children:[e.jsx("button",{type:"button",className:"t2c-ctxring-btn","aria-expanded":Ee==="ctx","aria-label":`${N("input.ctxLabel")} ${s}%`,...Di(()=>Ee==="ctx"?null:[`${N("input.ctxLabel")} ${s}%`]),onClick:()=>{Cc(),Re(b=>b==="ctx"?null:"ctx")},children:e.jsxs("svg",{viewBox:"0 0 24 24",width:"20",height:"20","aria-hidden":"true",children:[e.jsx("circle",{className:"t2c-ctxring-track",cx:"12",cy:"12",r:v}),e.jsx("circle",{className:"t2c-ctxring-fill",cx:"12",cy:"12",r:v,style:{strokeDasharray:y,strokeDashoffset:y*(1-s/100)}})]})}),e.jsx("span",{ref:wa.ref,className:"t2c-ctxring-pop",style:wa.style,children:e.jsx(Jl,{open:Ee==="ctx",contextWindow:ft,ctxTokens:he,sessionTokens:Ze,runCost:Oe,costLimit:Fe,ctxInfo:Xn,onCompact:Q?()=>{Q(),Re(null)}:void 0})})]})})(),Go&&e.jsx(kc,{className:"t2c-capsule-peer",open:Ee==="model",onOpenChange:s=>Re(s?"model":null),disabled:i,modelId:xe?I:k,groups:Yo,onSelect:xe?s=>U?.(s):s=>x?.(s),thinkingLevel:xe?void 0:pt,onThinkingChange:xe||!w?void 0:(s,m)=>{Xt(s,m)},allowUltra:it,ultra:Mt,running:r,supportedThinking:xe?void 0:h?.find(s=>s.id===k)?.thinkingLevels,effectiveThinking:xe?void 0:pe?.thinkingRequested===(pt||"medium")?pe?.thinkingEffective:void 0,modelsResponse:xe?void 0:f,defaultModelIds:xe?void 0:S,onDefaultModelChange:xe?void 0:g,onContextWindowChange:xe?void 0:F,emptyLabel:xe?N("input.engineModelDefault"):void 0,footnote:!xe&&!le&&!h?.some(s=>s.source==="direct")?N("input.cloudModelHint"):void 0}),e.jsx("button",{className:`t2c-iconbtn t2c-mic-control t2c-collapse-on-capsule-open${ie.recording?" recording":""}`,title:ie.busy?N("input.micBusy"):ie.recording?N("input.micStop"):ie.error||N("input.micStart"),disabled:i||ie.busy||!ie.supported,onClick:ie.toggle,children:ie.busy?e.jsx(Ot,{size:14,className:"spin"}):e.jsx(Lr,{size:14})}),r?e.jsxs(e.Fragment,{children:[(!!re.trim()||et.length>0)&&e.jsx(ts,{onClick:yn,disabled:i,title:N("input.send"),"aria-label":N("input.send")}),e.jsxs("button",{className:"t2c-stop",onClick:p,title:N("input.stop"),"aria-label":N("input.stop"),children:[e.jsx(bi,{size:10}),e.jsx("span",{className:"t2c-stop-label",children:N("input.stop")})]})]}):Bo&&!re.trim()&&!et.length&&!St.length&&!Nt.length&&!R&&!zt.length?e.jsx(ts,{className:"t2c-live-control",onClick:()=>{To()},disabled:!!i||Gn,title:N(gn?"livecall.return":"livecall.start"),"aria-label":N(gn?"livecall.return":"livecall.start"),children:Gn?e.jsx(Ot,{size:16,className:"spin"}):e.jsx(Bc,{size:16})}):e.jsx(ts,{onClick:yn,disabled:i||!re.trim()&&!et.length,title:N("input.send"),"aria-label":N("input.send")})]})]}),ie.error&&!ie.recording&&!ie.busy&&e.jsx("div",{className:"t2c-hint",style:{marginTop:6,marginBottom:0},children:ie.error}),va&&fn&&!ie.error&&e.jsx("div",{className:"t2c-hint",style:{marginTop:6,marginBottom:0},children:va})]})]}),Oo&&e.jsx($l,{cfg:Fo,onClose:()=>Da(!1)}),Lo&&e.jsx(bl,{offerFullAccess:le&&!d&&Et!=="full-auto",onConfirm:({fullAccess:s})=>{s&&Le({execMode:"host",approvalMode:"full-auto",cwd:u.cwd}),w?.("max",!0)},onClose:()=>ka(!1)})]})};function lu(t,n){const a=Math.max(0,t.content-t.width);if(t.left>=a-1)return 0;const o=t.left+t.width,i=n.find(r=>r.end>o+1),c=i?Math.min(i.start,a):a;return c>t.left+1?c:Math.min(o,a)}function uu(t,n){return t-n>1}me({"chatPicker.engine":{zh:"引擎",en:"Engine"},"chatPicker.agent":{zh:"Agent",en:"Agent"}});function du({label:t,value:n,icon:a,options:o,onChange:i,busy:c=!1}){const r=o.find(u=>u.value===n);return e.jsxs("label",{className:"compact-chat-picker","aria-busy":c||void 0,title:r?.name,children:[e.jsx("span",{className:"compact-chat-picker-kind",children:t}),e.jsx("span",{className:"compact-chat-picker-icon",children:a}),e.jsx("span",{className:"compact-chat-picker-name",children:r?.name||t}),e.jsx(rn,{size:13}),e.jsxs("select",{"aria-label":t,value:r?n:"",onChange:u=>i(u.target.value),children:[!r&&e.jsx("option",{value:"",disabled:!0,children:t}),o.map(u=>e.jsx("option",{value:u.value,disabled:u.disabled,children:u.description?`${u.name} — ${u.description}`:u.name},u.value))]})]})}const hu=({label:t,children:n,role:a="radiogroup"})=>{const{t:o}=we(),i=l.useRef(null),[c,r]=l.useState(!1);l.useLayoutEffect(()=>{const d=i.current;if(!d)return;const h=()=>{const k=d.parentElement,x=k&&getComputedStyle(k),T=k&&x?k.clientWidth-parseFloat(x.paddingLeft)-parseFloat(x.paddingRight):d.clientWidth;r(uu(d.scrollWidth,T))};h();const f=new ResizeObserver(h);f.observe(d);for(const k of Array.from(d.children))f.observe(k);return()=>f.disconnect()},[n]),l.useEffect(()=>{const d=i.current,h=d?.querySelector('[aria-checked="true"],[aria-pressed="true"]');if(!d||!h)return;const f=d.getBoundingClientRect(),k=h.getBoundingClientRect();k.right>f.right?d.scrollLeft+=k.right-f.right+6:k.left<f.left&&(d.scrollLeft-=f.left-k.left+6)},[]);const u=l.useCallback(()=>{const d=i.current;if(!d)return;const h=d.getBoundingClientRect(),f=Array.from(d.children).map(k=>{const x=k.getBoundingClientRect();return{start:x.left-h.left+d.scrollLeft,end:x.right-h.left+d.scrollLeft}});d.scrollTo({left:lu({left:d.scrollLeft,width:d.clientWidth,content:d.scrollWidth},f),behavior:"smooth"})},[]);return e.jsxs("div",{className:"engine-picker-bar","data-more":c||void 0,children:[e.jsx("div",{className:"engine-picker-scroll",ref:i,role:a,"aria-label":t,children:n}),c&&e.jsx("button",{type:"button",className:"engine-picker-more",onClick:u,title:o("pill.more"),"aria-label":o("pill.more"),children:e.jsx(Ln,{size:16})})]})};function mu(t,n,a){const o=_r(t,n),i=o.groupAgents??[];return o.groupChat&&i.length>=2?{kind:"team",count:i.length}:{kind:"agent",slug:o.agentSlug||a||null}}const Ms=t=>Array.from((t||"").trim());function pu(t,n){const a=t.map(r=>r.toLowerCase()),o=a.join("");let i=0;for(const r of n){if(!r.length||r.join("")===o||r[0]!==a[0])continue;let u=0;for(;u<a.length&&u<r.length&&a[u]===r[u];)u++;i=Math.max(i,u)}const c=[];for(let r=i;i&&r<t.length;r++)t[r].trim()&&c.push(t[r]);return{first:t[0],picks:c,collides:i>0}}function fu(t){const n=t.map(u=>Ms(u)),a=n.map(u=>u.map(d=>d.toLowerCase())),o=n.map(()=>"?"),i=new Set,c=[];n.forEach((u,d)=>{if(!u.length)return;const{first:h,picks:f,collides:k}=pu(u,a);if(!k||!f.length){o[d]=h.toUpperCase(),i.add(h.toLowerCase());return}c.push({index:d,key:a[d].join(""),picks:f,first:h})}),c.sort((u,d)=>u.key<d.key?-1:u.key>d.key?1:u.index-d.index);const r=new Map;for(const u of c){const d=r.get(u.key);if(d){o[u.index]=d;continue}const f=(u.picks.find(k=>!i.has(k.toLowerCase()))??u.first).toUpperCase();i.add(f.toLowerCase()),r.set(u.key,f),o[u.index]=f}return o}function gu(t,n=[]){const a=Ms(t);if(!a.length)return"?";const o=a.join("").toLowerCase();let i=n.findIndex(r=>Ms(r).join("").toLowerCase()===o);const c=i>=0?n:[t,...n];return i<0&&(i=0),fu(c)[i]}const hi=(...t)=>t.filter(Boolean).join(" ")||void 0;function vu({name:t,url:n,siblings:a,className:o,imgClassName:i,initialClassName:c,size:r,fill:u,title:d,style:h,...f}){return n?e.jsx("img",{...f,className:hi(o,i),src:n,alt:"",title:d,draggable:!1,width:r,height:r,style:h}):e.jsx("span",{...f,className:hi("agent-avatar-initial",u&&"agent-avatar-fill",o,c),title:d,"aria-hidden":"true",style:h,children:e.jsx("span",{className:"agent-avatar-glyph",children:gu(t,a)})})}me({"agentSelect.title":{zh:"选择 Agent",en:"Pick agents"},"agentSelect.hintDefault":{zh:"由默认 Agent {name} 处理",en:"Handled by the default agent, {name}"},"agentSelect.hintDefaultAnon":{zh:"由默认 Agent 处理",en:"Handled by the default agent"},"agentSelect.hintOne":{zh:"{name} 将处理这条消息",en:"{name} will handle this message"},"agentSelect.removeHint":{zh:"再次点击移除",en:"Click again to remove"},"agentSelect.team":{zh:"团队模式 · {n} 人",en:"Team mode · {n} people"},"agentSelect.picked":{zh:"已选",en:"Picked"},"agentSelect.default":{zh:"默认 Agent",en:"Default agent"},"agentSelect.defaultTag":{zh:"默认",en:"Default"},"agentSelect.direct":{zh:"私聊",en:"Direct chat"}});const It=2,Pt=t=>`agent:${t}`,tn=t=>`engine:${t}`,yu=(t,n)=>t.length===n.length&&t.every((a,o)=>a===n[o]);function ku(t){if(t.engineId)return[];const n=t.groupAgents??[];return t.groupChat&&n.length>=2?[...n]:t.agentSlug?[t.agentSlug]:[]}function Pd({sessionId:t,cfg:n}){const{t:a}=we(),[o,i]=l.useState(null),c=P(Or(j=>({agentDefs:j.agentDefs,agentAvatars:j.agentAvatars,defaultAgentSlug:j.defaultAgentSlug,engines:j.engines,engineCaps:j.engineCaps,teams:j.teams}))),r=P(j=>t?null:Fr(j,Wr())),u=P(j=>r?j.projectSettingsByPath[r]??null:null),d=P(j=>!r||r in j.projectSettingsByPath);l.useEffect(()=>{r&&!d&&P.getState().ensureProjectSettings(r).catch(()=>null)},[r,d]);const h=n.engineId||"",f=ku(n),k=h?[tn(h)]:f.map(Pt),x=h&&!c.engineCaps[h]?h:"",T=l.useMemo(()=>{const j=c.agentDefs.map(B=>({id:Pt(B.slug),kind:"agent",slug:B.slug,name:B.name,description:B.description,system:B.createdBy==="system"}));for(const B of n.groupAgents??[]){if(j.some(ge=>ge.id===Pt(B)))continue;const te=n.groupTempAgents?.find(ge=>ge.slug===B);j.push({id:Pt(B),kind:"agent",slug:B,name:te?.name||B,description:te?.description})}if(n.agentSlug&&!j.some(B=>B.id===Pt(n.agentSlug))&&j.push({id:Pt(n.agentSlug),kind:"agent",slug:n.agentSlug,name:n.agentSlug}),n.execMode==="host")for(const B of c.engines)B.available&&j.push({id:tn(B.id),kind:"engine",engineId:B.id,name:B.name});return h&&!j.some(B=>B.id===tn(h))&&j.push({id:tn(h),kind:"engine",engineId:h,name:c.engines.find(B=>B.id===h)?.name||h}),j},[c.agentDefs,c.engines,h,n.execMode,n.groupAgents,n.groupTempAgents,n.agentSlug]),M=l.useMemo(()=>new Map(T.map(j=>[j.id,j])),[T]),A=l.useMemo(()=>T.filter(j=>j.kind==="agent").map(j=>j.name),[T]),I=k.map(j=>M.get(j)).filter(j=>!!j),U=T.filter(j=>!k.includes(j.id)),_=n.groupChat?f.length:0,D=j=>{const B=!!n.groupChat&&f.length<It;if(!h&&!B&&yu(f,j))return;const te=P.getState(),ge=!!h,ve=(n.groupTempAgents||[]).filter(C=>j.includes(C.slug)),ye=ge?{engineId:void 0,engineModelId:void 0}:{};if(j.length>=It){const C={groupChat:!0,groupAgents:j,groupTempAgents:ve.length?ve:void 0,...ye};t?te.patchSessionConfig(C,t):te.setNewChatCfg(K=>({...K,...C}));return}const _e=j[0]||"",je={groupChat:!1,groupAgents:void 0,groupTempAgents:void 0,...ye};t?te.selectSessionAgent(_e,t,je):(te.setNewChatCfg(C=>({...C,...je})),te.selectNewChatAgent(_e))},w=j=>{const B=P.getState();t?B.setSessionEngine(j,t):B.setNewChatCfg(te=>({...te,engineId:j||void 0,engineModelId:void 0,...j?{groupChat:!1,groupAgents:void 0,agentSlug:void 0}:{}}))},z=l.useRef(null),S=l.useRef(null);l.useEffect(()=>{const j=z.current;if(!j)return;z.current=null,S.current?.querySelector(`[data-pill-id="${CSS.escape(j)}"]`)?.focus()});const g=j=>{if(z.current=j.id,j.kind==="engine"){w(j.engineId===h?"":j.engineId);return}const B=f.includes(j.slug)?f.filter(te=>te!==j.slug):[...f,j.slug];D(B)},F=()=>{h?w(""):D([])},H=j=>{j.kind==="agent"?Va("agent",j.slug):Va("engine",j.engineId)},W=j=>j.kind==="engine"?x===j.engineId?e.jsx(Ot,{size:16,className:"spin"}):e.jsx(ei,{engineId:j.engineId,size:16}):e.jsx(vu,{name:j.name,url:c.agentAvatars[j.slug],siblings:A,imgClassName:"agent-pill-avatar",initialClassName:"agent-pill-initial"}),O=(j,B)=>{const te=j.kind==="agent"&&j.description?`${j.name} — ${j.description}`:j.name;return B?`${te} · ${a("agentSelect.removeHint")}`:j.kind==="agent"&&j.slug===c.defaultAgentSlug?`${te} · ${a("agentSelect.defaultTag")}`:te},E=(j,B)=>{const te=B!==null,ge=j.kind==="engine"&&x===j.engineId;return e.jsxs("button",{type:"button","aria-pressed":te,"data-pill-id":j.id,className:`engine-pill agent-pill${te?" selected":""}`,"data-agent-slug":j.kind==="agent"?j.slug:void 0,"data-engine-id":j.kind==="engine"?j.engineId:void 0,title:O(j,te),disabled:!!x&&!ge,onClick:()=>{(!x||ge)&&g(j)},onContextMenu:ve=>{ve.preventDefault(),i({...gc(ve),items:[{label:a("agentSelect.direct"),icon:e.jsx(Ei,{size:13}),run:()=>H(j)}]})},children:[te&&I.length>=It&&e.jsx("span",{className:"agent-pill-index",children:B+1}),e.jsx("span",{className:"engine-pill-icon",children:W(j)}),e.jsx("span",{className:"engine-pill-label",children:j.name}),j.kind==="agent"&&j.system&&e.jsx("span",{className:"agent-badge-system",children:a("agent.badge.system")})]},j.id)};if(n.preset==="chat"||!T.length)return null;const G=mu(n,t?{}:Ur(u,Array.isArray(c.teams)?c.teams:[]).config,c.defaultAgentSlug),X=G.kind==="agent"&&G.slug?c.agentDefs.find(j=>j.slug===G.slug)?.name:void 0,J=_>=It?a("agentSelect.team",{n:_}):I.length===1?a("agentSelect.hintOne",{name:I[0].name}):G.kind==="team"?a("agentSelect.team",{n:G.count}):X?a("agentSelect.hintDefault",{name:X}):a("agentSelect.hintDefaultAnon"),ee=_<It&&I.length!==1&&G.kind!=="team",De=k[0]||"",ze=I[0]?W(I[0]):e.jsx(ei,{engineId:"",size:16});return e.jsxs("div",{ref:S,className:"engine-picker agent-picker agent-select-strip",role:"group","aria-label":a("agentSelect.title"),children:[e.jsx(du,{label:a("chatPicker.agent"),value:De,icon:ze,options:[{value:"",name:a("agentSelect.default")},...T.map(j=>({value:j.id,name:j.name,description:k.includes(j.id)?a("agentSelect.picked"):j.kind==="agent"?j.description:void 0,disabled:!!x&&j.id!==tn(x)}))],onChange:j=>{if(!j){F();return}const B=M.get(j);B&&g(B)},busy:!!x}),e.jsx(hu,{label:a("agentSelect.title"),role:"group",children:[...I.map((j,B)=>E(j,B)),...I.length>0?[e.jsx("span",{className:"agent-select-sep","aria-hidden":"true"},"sep")]:[],...U.map(j=>E(j,null))]}),e.jsx("div",{className:`engine-picker-hint${_>=It?" agent-select-team":""}${ee?" is-default":""}`,children:J}),o&&e.jsx(fc,{menu:o,onClose:()=>i(null)})]})}const Dd=({workspaces:t,value:n,onChange:a,onAddProject:o,onAddCloudProject:i})=>{const{t:c}=we(),[r,u]=l.useState(!1),[d,h]=l.useState(""),[f,k]=l.useState(!1),[x,T]=l.useState(""),M=l.useRef(null),A=l.useRef(null),I=Ft(r);l.useEffect(()=>{if(!r)return;const E=X=>{M.current&&!M.current.contains(X.target)&&(u(!1),h(""),k(!1),T(""))},G=X=>{X.key==="Escape"&&(u(!1),h(""),k(!1),T(""),M.current?.querySelector(".project-pill")?.focus())};return window.addEventListener("mousedown",E),window.addEventListener("keydown",G),()=>{window.removeEventListener("mousedown",E),window.removeEventListener("keydown",G)}},[r]);const U=t.filter(E=>E.kind!=="channel"),_=U.find(E=>E.key===n||!!n&&E.sessionKeys?.includes(n))||U.find(E=>E.kind==="local"&&E.system)||U[0]||null,D=U.find(E=>E.kind==="rootless")||null,w=U.filter(E=>E.kind!=="rootless"),z=d.trim().toLowerCase(),S=w.filter(E=>!z||`${E.name} ${E.path||""} ${E.project||""}`.toLowerCase().includes(z)),g=w.length>=6,F=_?.kind==="cloud"?Dt:_?.kind==="rootless"?Qa:$n,H=()=>{u(!1),h(""),k(!1),T("")},W=E=>{a(E),H()};l.useEffect(()=>{if(!r||Br())return;const E=requestAnimationFrame(()=>{(g?A.current?.querySelector(".project-menu-search input"):A.current?.querySelector(".project-menu-item.active"))?.focus()});return()=>cancelAnimationFrame(E)},[r,g]);const O=E=>{if(!["ArrowDown","ArrowUp","Home","End"].includes(E.key))return;const G=[...A.current?.querySelectorAll(".project-menu-item:not(:disabled)")||[]];if(!G.length)return;E.preventDefault();const X=G.indexOf(document.activeElement),J=E.key==="Home"?0:E.key==="End"?G.length-1:X<0?E.key==="ArrowDown"?0:G.length-1:E.key==="ArrowDown"?(X+1)%G.length:(X-1+G.length)%G.length;G[J]?.focus()};return e.jsxs("div",{className:`project-selector${r?" is-open":""}`,ref:M,children:[e.jsxs("button",{className:`composer-chip project-pill${r?" is-open":""}`,onClick:()=>r?H():u(!0),title:c("input.project.label"),"aria-haspopup":"menu","aria-expanded":r,children:[e.jsx(F,{size:13}),e.jsx("span",{className:"project-pill-name",children:_?.name||c("input.project.none")}),e.jsx(rn,{size:12})]}),r&&e.jsxs("div",{ref:E=>{A.current=E,I.ref.current=E},className:"composer-menu project-menu",style:I.style,role:"menu","aria-label":c("input.project.label"),onKeyDown:O,children:[g&&e.jsxs("label",{className:"project-menu-search",children:[e.jsx(Ni,{size:13}),e.jsx("input",{value:d,onChange:E=>h(E.target.value),placeholder:c("input.project.search")})]}),e.jsxs("div",{className:"project-menu-list",children:[S.map(E=>e.jsxs("button",{className:`menu-item project-menu-item${E.key===_?.key?" active":""}`,role:"menuitemradio","aria-checked":E.key===_?.key,onClick:()=>W(E),children:[E.kind==="cloud"?e.jsx(Dt,{size:14}):e.jsx($n,{size:14}),e.jsx("span",{className:"grow project-menu-name",children:E.name}),e.jsx("span",{className:"project-menu-check",children:E.key===_?.key?e.jsx(Xe,{size:13}):null})]},E.key)),!S.length&&e.jsx("div",{className:"project-menu-empty",children:c("input.project.noMatches")})]}),D&&e.jsx("div",{className:"project-menu-section project-menu-projectless-section",role:"group",children:e.jsxs("button",{className:`menu-item project-menu-item project-menu-projectless${D.key===_?.key?" active":""}`,role:"menuitemradio","aria-checked":D.key===_?.key,onClick:()=>W(D),children:[e.jsx(Qa,{size:14}),e.jsx("span",{className:"grow project-menu-name",children:c("input.project.dontWork")}),e.jsx("span",{className:"project-menu-check",children:D.key===_?.key?e.jsx(Xe,{size:13}):null})]})}),(i||o)&&e.jsxs("div",{className:"project-menu-section project-menu-actions",role:"group",children:[i&&(f?e.jsxs("label",{className:"project-menu-search project-menu-naming",children:[e.jsx(Dt,{size:13}),e.jsx("input",{autoFocus:!0,value:x,onChange:E=>T(E.target.value),placeholder:c("input.project.cloudName"),onKeyDown:E=>{E.key==="Enter"&&x.trim()&&(i(x.trim()),H()),E.key==="Escape"&&(E.stopPropagation(),T(""),k(!1))}})]}):e.jsxs("button",{className:"menu-item project-menu-item project-menu-add",role:"menuitem",onClick:()=>k(!0),children:[e.jsx(Dt,{size:14}),e.jsx("span",{className:"grow",children:c("input.project.addCloud")})]})),o&&e.jsxs("button",{className:"menu-item project-menu-item project-menu-add",role:"menuitem",onClick:()=>{o(),H()},children:[e.jsx(Fi,{size:14}),e.jsx("span",{className:"grow",children:c("input.project.add")})]})]})]})]})},Rs=qr,mi=/^[0-9a-zA-Z-]{8,64}$/;function Gi(t){return t.kind==="unit"?`unit:${t.unitId.toLowerCase()}`:""}function xu(t){if(typeof t=="string"){const a=/^unit:(.+)$/.exec(t);return a&&mi.test(a[1])?Object.freeze({kind:"unit",unitId:a[1].toLowerCase()}):Rs}const n=t;return n&&typeof n=="object"&&n.kind==="unit"&&typeof n.unitId=="string"&&mi.test(n.unitId)?Object.freeze({kind:"unit",unitId:n.unitId.toLowerCase()}):Rs}const wu=5*6e4,pi=new Set(["remoteOff","awaitingConfirm","denied","callerBlocked"]);function Ts(t){if(t==null)return null;const n=typeof t=="object"?t:{},a=typeof n.code=="string"?n.code:"",o=typeof n.status=="number"?n.status:NaN;switch(a){case"ENGINE_NOT_READY":return"starting";case"UNIT_OFFLINE":case"UNIT_DISCONNECTED":return"offline";case"UNIT_TIMEOUT":return"unreachable";case"REMOTE_SESSIONS_OFF":return"remoteOff";case"REMOTE_CALLER_UNCONFIRMED":return Pc(n.reason)?"callerBlocked":n.state==="denied"?"denied":"awaitingConfirm";case"CALLER_UNAVAILABLE":case"CALLER_UNSUPPORTED":case"UNIT_CALLER_INVALID":case"UNIT_CALLER_EXPIRED":return"unreachable"}return a?o>=500?"unreachable":null:n.name==="TypeError"||n.name==="AbortError"||o===0||o>=500?"unreachable":null}const fi=t=>t.state||t.reason?{...t.state?{state:t.state}:{},...t.reason?{reason:t.reason}:{}}:void 0;function ju(t,n,a,o=Date.now()){if(!t.online)return{status:"offline"};if(t.capsLive&&t.caps){const i=t.caps.engine;if(i==="external")return{status:"noEngine"};if(i==="stopped")return{status:"engineStopped"};if(i==="starting")return{status:"starting"}}if(n&&!n.ok){const i=Ts(n)??"unreachable",c=pi.has(i)?fi(n):void 0;return c?{status:i,refusal:c}:{status:i}}if(a&&o-a.at>=0&&o-a.at<wu){const i=Ts({status:403,code:a.code,state:a.state,reason:a.reason});if(i&&pi.has(i)){const c=fi(a);return c?{status:i,refusal:c}:{status:i}}}return n?.ok?{status:"ready"}:{status:"checking"}}function bu(t){return!!(t.online&&t.capsLive&&t.caps?.engine==="ready")}const Su=1e4,Nu=8e3,Cu=50,zu={sessions:[],fetchedAt:null,loading:!1};async function Au(){if(typeof window.tangu?.unitSelf=="function")try{const t=await window.tangu.unitSelf();return{id:t?.unitId?t.unitId.toLowerCase():null,registered:!!t?.registered}}catch{}try{const t=await window.tangu?.unitHostStatus?.();if(t?.unitId)return{id:t.unitId.toLowerCase(),registered:null}}catch{}return{id:null,registered:null}}function Eu(t,n){return t.filter(a=>!!a&&typeof a.id=="string"&&Os(a.id)&&(a.kind??"desktop")==="desktop"&&a.id.toLowerCase()!==n)}function Mu(t){const n=t?.sessions;if(!Array.isArray(n))return[];const a=[];for(const o of n){if(!o||typeof o!="object")continue;const i=o;if(typeof i.id!="string"||!i.id||i.id.length>200||i.archived)continue;const{location:c,...r}=i;a.push({...r,title:typeof r.title=="string"?r.title:""})}return a}function st(t){return{kind:"unit",unitId:t.toLowerCase()}}const ae=Ws((t,n)=>({gen:0,units:null,byUnit:{},refreshedAt:0,selfRegistered:null,refreshRoster:async()=>{if(!Vr()||!window.tangu?.unitsList)return null;const a=n().gen;let o=null;try{const r=await window.tangu.unitsList();r?.status===200&&Array.isArray(r.json?.units)&&(o=r.json.units)}catch{}if(a!==n().gen)return null;if(!o)return n().units;const i=await Au(),c=Eu(o,i.id);if(a!==n().gen)return null;for(const r of c)Kr(st(r.id),r.name);return t({units:c,selfRegistered:i.registered}),c},refresh:async(a={})=>{if(!wt())return;const o=n().gen,i=await n().refreshRoster();if(!i||o!==n().gen||(await Promise.all(i.map(u=>Ru(u,o,!!a.force,!!a.periodic))),o!==n().gen))return;const c=new Set(i.map(u=>u.id.toLowerCase())),r=Object.fromEntries(Object.entries(n().byUnit).filter(([u])=>c.has(u)));t({byUnit:r,refreshedAt:Date.now()}),$u()},reset:()=>{t(a=>({gen:a.gen+1,units:null,byUnit:{},refreshedAt:0,selfRegistered:null})),Hr()}}));function Ge(t,n){const a=t.toLowerCase();ae.setState(o=>({byUnit:{...o.byUnit,[a]:{...o.byUnit[a]??zu,...n}}}))}async function Ru(t,n,a,o=!1){const i=t.id.toLowerCase(),c=ae.getState().byUnit[i];if(o&&Tu(Wt.getState().probes[i]))return;if(!t.online){Ge(i,{sessions:[],loading:!1});return}if(ae.getState().selfRegistered===!1){Ge(i,{sessions:[],loading:!1});return}if(t.capsLive&&t.caps?.engine&&t.caps.engine!=="ready"){Ge(i,{sessions:[],loading:!1});return}if(!a&&c?.fetchedAt&&Date.now()-c.fetchedAt<Su)return;const r=cn(st(i));if(r){Ge(i,{loading:!0});try{const u=await Yr(r,`/agent/sessions?archived=false&limit=${Cu}&app_id=${encodeURIComponent(Gr)}`,{},{timeoutMs:Nu});let d=null;try{d=await u.json()}catch{}if(n!==ae.getState().gen)return;if(!u.ok){const k=d??{},x=Ka({status:u.status,code:k.code,state:k.state,reason:k.reason});ns(i,x),Ge(i,{sessions:gi(i,x),fetchedAt:Date.now(),loading:!1});return}const h=st(i),f=Mu(d).filter(k=>ln(k.id,h)?(console.warn(`[device-sessions] dropped session ${k.id} listed by ${i}: that id already belongs to another location`),!1):!0);ns(i,{ok:!0}),Ge(i,{sessions:f,fetchedAt:Date.now(),loading:!1})}catch(u){if(n!==ae.getState().gen)return;const d=Ka(u);ns(i,d),Ge(i,{sessions:gi(i,d),fetchedAt:Date.now(),loading:!1})}}}function Tu(t){if(!t||t.ok)return!1;const n=Xr(t.status,{code:t.code});return n==="caller-unavailable"||n==="gone"||n==="account-auth?"}function gi(t,n){return Ts(n)==="unreachable"?ae.getState().byUnit[t]?.sessions??[]:[]}function $u(){const t=ae.getState().byUnit,n=new Map;for(const[c,r]of Object.entries(t))for(const u of r.sessions)sn(Mi(u.id),st(c))&&n.set(u.id,u);if(!n.size)return;const a=P.getState();let o=!1;const i=a.sessions.map(c=>{const r=c.location?.kind==="unit"?n.get(c.id):void 0;return!r||r.title===c.title&&r.updated_at===c.updated_at&&r.summary===c.summary?c:(o=!0,{...c,title:r.title,updated_at:r.updated_at,summary:r.summary})});o&&P.setState({sessions:i})}function Bs(t,n=Date.now()){const a=Wt.getState(),o=t.id.toLowerCase(),i=ju(t,a.probes[o]??null,a.sticky[o]??null,n);return i.status==="checking"&&ae.getState().selfRegistered===!1&&bu(t)?{status:"ready"}:i}function Xi(t){const n=t.toLowerCase();return ae.getState().units?.find(a=>a.id.toLowerCase()===n)??null}function $s(t,n){if(!t?.id||!Os(n.unitId))return!1;const a=st(n.unitId);if(Zr(t.id,a)==="conflict")return console.warn(`[device-sessions] refused to open ${t.id} on ${a.unitId}: that id already belongs to another location`),!1;const{location:o,...i}=t,c=Qr(i);return P.setState(r=>({sessions:[c,...r.sessions.filter(u=>u.id!==t.id)],configBySession:r.configBySession[t.id]||!t.agent_config?r.configBySession:{...r.configBySession,[t.id]:t.agent_config}})),(Rn.getState().activeSpaceId==="home"||Rn.getState().activeSpaceId==="inbox")&&Ri("tangu"),Ti(t.id),!0}async function _d(t,n){if(!wt()||!Os(t)||!n)return!1;const a=st(t);if(ln(n,a))return!1;const o=P.getState();if((o.sessions.find(u=>u.id===n)??o.archivedSessions.find(u=>u.id===n))&&sn(Mi(n),a))return(Rn.getState().activeSpaceId==="home"||Rn.getState().activeSpaceId==="inbox")&&Ri("tangu"),Ti(n),!0;const c=ae.getState().byUnit[a.unitId]?.sessions.find(u=>u.id===n);if(c)return $s(c,a);const r=cn(a);if(!r)return!1;try{const u=await Jr(r,n);return!u||u.id!==n?!1:$s(u,a)}catch{return!1}}async function Lu(t,n,a){const o=st(t),i=cn(o);if(!i||ln(n,o))return;const c=u=>u.id===n?{...u,title:a}:u,r=ae.getState().byUnit[o.unitId];r&&Ge(o.unitId,{sessions:r.sessions.map(c)}),P.setState(u=>({sessions:u.sessions.map(d=>d.location?.kind==="unit"?c(d):d)}));try{await Fs(i,n,{title:a})}catch(u){P.getState().toast(P.getState().tr("app.renameFail",{e:u?.message||u}),!0)}}async function Iu(t,n,a){const o=st(t),i=cn(o);if(!i||ln(n,o))return!1;const c=ec(a);if(a!==null&&!c)return P.getState().toast(P.getState().tr("session.icon.invalid"),!0),!1;try{const r=await Fs(i,n,{emoji:c}),u=h=>h.id===n?{...h,emoji:r.emoji}:h,d=ae.getState().byUnit[o.unitId];return d&&Ge(o.unitId,{sessions:d.sessions.map(u)}),P.setState(h=>({sessions:h.sessions.map(f=>f.location&&sn(f.location,o)?u(f):f),archivedSessions:h.archivedSessions.map(f=>f.location&&sn(f.location,o)?u(f):f)})),!0}catch(r){return P.getState().toast(P.getState().tr("session.icon.saveFail",{e:r?.message||r}),!0),!1}}async function Pu(t,n){const a=st(t),o=cn(a);if(!o||ln(n,a))return;try{await Fs(o,n,{archived:!0})}catch(c){P.getState().toast(c?.message||String(c),!0);return}const i=ae.getState().byUnit[a.unitId];i&&Ge(a.unitId,{sessions:i.sessions.filter(c=>c.id!==n)}),P.setState(c=>({sessions:c.sessions.filter(r=>!(r.id===n&&r.location?.kind==="unit"))})),P.getState().activeId===n&&P.getState().setActiveId(null)}let vi=P.getState().cfg?.token??"";P.subscribe(t=>{const n=t.cfg?.token??"";n!==vi&&(vi=n,ae.getState().reset())});const Ue=Ws(()=>({draftSeq:0,explicitSeq:null,reconciledSeq:null,explicitPending:!1,chooser:null}));function Od(t){return Ue.setState({chooser:t}),()=>{Ue.getState().chooser===t&&Ue.setState({chooser:null})}}const Du="forsion_run_location:";function Ji(){const t=Xo(sc(),P.getState().cfg?.token||"");return t?`${Du}${t}`:null}function _u(){const t=Ji();if(!t)return null;try{const n=localStorage.getItem(t);return n===null?null:xu(n)}catch{return null}}function Zi(t){const n=Ji();if(n)try{localStorage.setItem(n,Gi(t))}catch{}}async function Fd(t,n){Zi(t),Ue.setState({explicitPending:!0});try{await $i(t,{name:n.name??null})}finally{Ue.setState(a=>({explicitSeq:a.draftSeq,explicitPending:!1}))}}let yi=!1,Ls=!1;function Qi(){if(!wt())return!1;const t=Ue.getState();if(P.getState().activeId||t.explicitPending||t.explicitSeq===t.draftSeq||t.reconciledSeq===t.draftSeq)return!1;const n=nc();let a=_u();yi||(yi=!0,a===null&&n.kind==="unit"&&(a=n,Zi(n)));let o=Rs,i=null;if(a?.kind==="unit"){if(ae.getState().units===null)return!1;const c=Xi(a.unitId);if(c){const r=Bs(c).status;if(r==="checking")return!1;r==="ready"&&(o=a,i=c.name)}}if(Ue.setState({reconciledSeq:t.draftSeq}),!sn(o,n)){Ls=!0;let c;try{c=$i(o,{name:i})}finally{Ls=!1}c.catch(()=>{})}return!0}tc(()=>{if(Ls)return;const t=Ue.getState();Ue.setState({explicitSeq:P.getState().activeId?t.draftSeq+1:t.draftSeq})});const Ou=1e4;let ys=P.getState().activeId;P.subscribe(t=>{if(t.activeId===ys)return;const n=ys;if(ys=t.activeId,n&&!t.activeId){Ue.setState(o=>({draftSeq:o.draftSeq+1}));const a=ae.getState();Date.now()-a.refreshedAt<Ou?Qi():a.refresh().catch(()=>{})}});ae.subscribe((t,n)=>{t.refreshedAt!==n.refreshedAt&&Qi()});me({"session.icon.set":{zh:"设置图标",en:"Set icon"},"session.icon.invalid":{zh:"请选择一个 Emoji 作为会话图标",en:"Choose one emoji for the session icon"},"session.icon.saveFail":{zh:"图标未能保存:{e}",en:"Could not save the icon: {e}"}});function qs({emoji:t,fallback:n,size:a=17}){return t?e.jsx("span",{"data-session-emoji":t,"aria-hidden":"true",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:a,height:a,flexShrink:0,fontSize:a,lineHeight:1},children:t}):e.jsx(e.Fragment,{children:n??e.jsx(Ei,{size:a})})}function Wd({params:t,size:n}){const a=P(o=>{const i=t.followActive!==!1?o.activeId:t.sessionId;return o.sessions.find(c=>c.id===i)?.emoji??o.archivedSessions.find(c=>c.id===i)?.emoji});return e.jsx(qs,{emoji:a,size:n})}function eo({sessionId:t,current:n,x:a,y:o,onClose:i,onSave:c}){const r=l.useRef(!1),u=async d=>{if(!r.current){r.current=!0;try{await(c?c(d):P.getState().setSessionEmoji(t,d))&&i()}finally{r.current=!1}}};return Ds.createPortal(e.jsx(Dc,{x:a,y:o,current:n,onPick:d=>{u(d)},onClose:i}),document.body)}const to=({open:t,children:n})=>{const a=zc();return e.jsx(Ac,{initial:!1,children:t&&e.jsx(Ec.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:a?0:.24,ease:[.2,.8,.3,1]},style:{overflow:"hidden"},children:n})})};function Fu({path:t,fallback:n,className:a}){const o=P(u=>u.projectSettingsByPath[t]?.icon),i=P(u=>u.projectIconUrls[t]),c=P(u=>u.connState==="ok"),r=Jo(o);return l.useEffect(()=>{c&&P.getState().ensureProjectSettings(t)},[t,c]),l.useEffect(()=>{c&&r&&P.getState().loadProjectIcon(t)},[t,c,r]),r?i?e.jsx("img",{className:a,src:i,alt:"",draggable:!1}):e.jsx(e.Fragment,{children:n}):o?e.jsx("span",{className:a,"aria-hidden":"true",children:o}):e.jsx(e.Fragment,{children:n})}me({"agentRemove.title":{zh:"删除 Agent「{name}」?",en:'Delete agent "{name}"?'},"agentRemove.msg":{zh:"会从 Agent 名册和侧栏移除,历史私聊保留(只读)。它的记忆与 Library 默认保留在 Tangu 数据目录的 agents/.removed/ 里。",en:"It is removed from the agent roster and the sidebar; past direct chats are kept (read-only). By default its memory and Library are kept in agents/.removed/ in the Tangu data folder."},"agentRemove.msgCloud":{zh:"会从 Agent 名册移除,历史会话保留(只读)。",en:"It is removed from the agent roster; past sessions are kept (read-only)."},"agentRemove.files":{zh:"同时删除相关文件:它的记忆、Library 等,移到废纸篓",en:"Also delete related files: its memory, Library and the rest, moved to the Trash"},"agentRemove.confirm":{zh:"删除",en:"Delete"},"agentRemove.done":{zh:"已删除 Agent「{name}」",en:'Agent "{name}" deleted'}});function no({title:t,message:n,confirmLabel:a,filesLabel:o,onConfirm:i,onClose:c}){const[r,u]=l.useState(!1);return Ds.createPortal(e.jsx("div",{className:"am-app tangu-lovable",style:{display:"contents"},"data-remove-dialog":!0,children:e.jsx(Si,{title:t,message:n,confirmLabel:a,onConfirm:()=>i(!!o&&r),onClose:c,children:o&&e.jsxs("label",{className:"dialog-check",children:[e.jsx("input",{type:"checkbox",checked:r,onChange:d=>u(d.target.checked)}),e.jsx("span",{children:o})]})})}),document.body)}function Ud({agent:t,onDone:n,onClose:a}){const{t:o}=we(),i=!!t.libraryDir,c=t.name||t.slug;return e.jsx(no,{title:o("agentRemove.title",{name:c}),message:o(i?"agentRemove.msg":"agentRemove.msgCloud"),confirmLabel:o("agentRemove.confirm"),filesLabel:i&&window.tangu?.trashHostPath?o("agentRemove.files"):void 0,onConfirm:r=>{const u=P.getState();u.removeAgent(t,r).then(()=>{u.toast(o("agentRemove.done",{name:c})),n?.()}).catch(d=>u.toast(String(d?.message||d),!0))},onClose:a})}const so="forsion_orbits_pinned_entries_v1",on=(t,n)=>Object.prototype.hasOwnProperty.call(t,n);function ki(t,n){return on(t,n)}function ao(t,n){let a=0;for(const o of Object.values(t))Number.isFinite(o)&&(a=Math.max(a,o));return Math.max(n,a+1)}function Bd(t,n,a=Date.now()){if(on(t,n)){const o={...t};return delete o[n],o}return{...t,[n]:ao(t,a)}}function qd(t,n,a=Date.now()){return on(t,n)?{...t,[n]:ao(t,a)}:t}function Hd(t=typeof localStorage>"u"?null:localStorage){if(!t)return{};try{const n=JSON.parse(t.getItem(so)||"{}");if(!n||typeof n!="object"||Array.isArray(n))return{};const a={};for(const[o,i]of Object.entries(n))o&&Number.isFinite(i)&&Number(i)>0&&(a[o]=Number(i));return a}catch{return{}}}function Vd(t,n=typeof localStorage>"u"?null:localStorage){try{n?.setItem(so,JSON.stringify(t))}catch{}}function Wu(t,n){return t.map((a,o)=>({entry:a,index:o})).sort((a,o)=>{const i=on(n,a.entry.key),c=on(n,o.entry.key);return i!==c?i?-1:1:i&&c?n[o.entry.key]-n[a.entry.key]||a.index-o.index:o.entry.at-a.entry.at||a.index-o.index}).map(({entry:a})=>a)}me({"sidebar.attention":{zh:"{n} 项等你处理",en:"{n} waiting for you"},"sidebar.attentionLocalOnly":{zh:"{n} 项等你处理 · 含只能在那台电脑上批准的操作",en:"{n} waiting for you · includes actions that can only be approved on that computer"}});const io=({n:t,localOnly:n})=>{const{t:a}=we();return e.jsx("span",{className:"t2s-dot attention","data-attention":t,title:a(n?"sidebar.attentionLocalOnly":"sidebar.attention",{n:t})})};me({"chat.toNote.action":{zh:"整理成笔记",en:"Turn into note"},"chat.toNote.working":{zh:"正在把对话整理成笔记…",en:"Turning the chat into a note…"},"chat.toNote.empty":{zh:"这段对话还没有可整理的内容",en:"This chat has nothing to turn into a note yet"},"chat.toNote.done":{zh:"已整理成笔记「{name}」",en:"Saved as the note “{name}”"},"chat.toNote.failed":{zh:"没能整理成笔记:{reason}",en:"Couldn’t turn the chat into a note: {reason}"},"chat.toNote.workingTail":{zh:"对话较长,只整理最近的部分…",en:"This chat is long; only the most recent part will be turned into a note…"},"chat.toNote.emptyAnswer":{zh:"模型没有返回内容",en:"the model returned nothing"},"chat.toNote.nameTaken":{zh:"同名笔记太多(已试到 -20)",en:"too many notes with that name (tried up to -20)"}});const Uu=["The text in <selection> is a chat transcript between a user and an AI assistant.","Turn it into a standalone, well-organized note that someone can reread later without the chat.",'Start with exactly one "# " heading that names the topic.',"Keep the conclusions, decisions, facts, numbers, code and step-by-step instructions; drop greetings, filler, retries and back-and-forth.","Use headings, lists and tables where they help. Do not mention that it came from a chat.","Write in the language the user wrote in."].join(" "),Is=2e4;function oo(t){const n=[];for(const a of t){if(a.role!=="user"&&a.role!=="assistant")continue;const o=(a.role==="assistant"?oc(a.content).text:a.content).trim();o&&n.push(`${a.role==="user"?"User":"Assistant"}:
31
- ${o}`)}return n.join(`
32
-
33
- `)}function Bu(t){const n=oo(t);return n.length>Is?n.slice(-Is):n}function qu(t,n){const a=/^\s*#[ \t]+(.+?)[ \t]*#*[ \t]*(?:\r?\n|$)/.exec(t);return{title:(a?a[1]:n).replace(/[\\/:*?"<>|#^[\]]/g," ").replace(/\s+/g," ").trim().slice(0,80)||n,body:(a?t.slice(a[0].length):t).replace(/^\s*\n/,"")}}function Hu(){return ac()&&!!Li()?.complete}async function Vu(t,n){for(let a=1;a<=20;a++){const o=`${a===1?t:`${t}-${a}`}.md`;if(await Ya.readTextFile?.(o)?.catch(()=>null)!=null)continue;const i=await Ya.writeTextFile(o,n,{create:!0,base:Zo("")});if(!(i&&i.ok===!1))return o}return null}async function Ku(t){const n=Li()?.complete;if(!n)return!1;const a=P.getState(),o=[...a.sessions,...a.archivedSessions].find(i=>i.id===t);try{a.messagesBySession[t]?.length||await a.loadSessionHistory(t);const i=P.getState().messagesBySession[t]||[],c=Bu(i);if(!c)return kn({text:Te("chat.toNote.empty"),level:"info",inAppOnly:!0}),!1;kn({text:Te(oo(i).length>Is?"chat.toNote.workingTail":"chat.toNote.working"),level:"info",inAppOnly:!0});const r=await n({action:"custom",instruction:Uu,selection:c,title:o?.title||void 0});if(!r.text.trim())throw new Error(Te("chat.toNote.emptyAnswer"));const{title:u,body:d}=qu(r.text,o?.title?.trim()||Te("amadeus.default.note")),h=await Vu(u,d.trimEnd()+`
34
- `);if(!h)throw new Error(Te("chat.toNote.nameTaken"));return kn({text:Te("chat.toNote.done",{name:u}),level:"success",receipt:!0}),ic(h),!0}catch(i){return kn({text:Te("chat.toNote.failed",{reason:i instanceof Error?i.message:String(i)}),level:"error",inAppOnly:!0}),!1}}const xi={wechat:cc,telegram:rc,qq:Mn};me({"sidebar.openInNewTab":{zh:"在新标签页打开",en:"Open in new tab"},"sidebar.archiveN":{zh:"归档 {n} 项",en:"Archive {n}"},"sidebar.unarchiveN":{zh:"取消归档 {n} 项",en:"Unarchive {n}"},"sidebar.deleteN":{zh:"删除 {n} 项",en:"Delete {n}"},"sidebar.deleteConfirmN":{zh:"删除选中的 {n} 个会话?不可撤销。",en:"Delete {n} selected chats? This cannot be undone."},"sidebar.mode.chat":{zh:"Chat",en:"Chat"},"sidebar.mode.work":{zh:"Work",en:"Work"},"sidebar.mode.tip":{zh:"Chat:轻聊天,只列聊天会话;Work:完整工具面,列出全部项目",en:"Chat: light conversations, chat sessions only. Work: full toolset, all projects"},"sidebar.pin":{zh:"置顶",en:"Pin to top"},"sidebar.unpin":{zh:"取消置顶",en:"Unpin"},"sidebar.ws.details":{zh:"查看详情",en:"View details"},"sidebar.ws.removeTitle":{zh:"移除项目「{name}」?",en:'Remove project "{name}"?'},"sidebar.ws.removeMsg":{zh:"会从侧栏移除它,并删除其中的 {count} 个会话,不可撤销。磁盘上的项目文件夹不会删除。",en:"It is removed from the sidebar and its {count} session(s) are deleted. This cannot be undone. The project folder on disk is not deleted."},"sidebar.ws.removeFiles":{zh:"同时删除相关文件:项目里的 .tangu 文件夹(Tangu 的指令、技能、计划),移到废纸篓",en:"Also delete related files: the project's .tangu folder (Tangu instructions, skills and plans), moved to the Trash"},"sidebar.ws.removeAction":{zh:"移除",en:"Remove"}});const ro="forsion_tangu_collapsed_projects",co="forsion_tangu_workspace_order";function Yu(){try{return new Set(JSON.parse(localStorage.getItem(ro)||"[]"))}catch{return new Set}}function wi(t){try{localStorage.setItem(ro,JSON.stringify([...t]))}catch{}}function Gu(){try{const t=JSON.parse(localStorage.getItem(co)||"[]");return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}}function Xu(t){try{localStorage.setItem(co,JSON.stringify(t))}catch{}}function Ps(t){const n=String(t||"").trim();if(!n)return 0;const a=Date.parse(n.includes("T")?n:n.replace(" ","T"));return Number.isFinite(a)?a:0}const Ju=({icon:t,title:n,active:a,onClick:o,onExpand:i,act:c})=>e.jsxs("button",{className:`t2s-special${a?" active":""}`,"data-act":c,onClick:o,children:[e.jsx("span",{className:"t2s-special-ic",children:t}),e.jsx("span",{className:"t2s-special-title",children:n}),i&&e.jsx("span",{className:"t2s-special-go",onClick:r=>{r.stopPropagation(),i()},children:e.jsx(xt,{size:14})})]}),Kd=t=>{const{t:n}=we(),a=l.useRef(null),o=t.allSessions??t.sessions,i=t.allArchived??t.archivedSessions,c=Mc(a),[r,u]=l.useState(null),[d,h]=l.useState(null),[f,k]=l.useState(null),[x,T]=l.useState(""),[M,A]=l.useState(()=>{try{return Math.max(1,Number(localStorage.getItem("tangu_ws_session_limit"))||5)}catch{return 5}});l.useEffect(()=>{const p=()=>{try{A(Math.max(1,Number(localStorage.getItem("tangu_ws_session_limit"))||5))}catch{}};return window.addEventListener("tangu:wslimit",p),()=>window.removeEventListener("tangu:wslimit",p)},[]);const[I,U]=l.useState(!1),[_,D]=l.useState(Yu),[w,z]=l.useState(Gu),[S,g]=l.useState(null),[F,H]=l.useState(null),W=l.useRef(null),O=l.useRef(!1),[E,G]=l.useState(null),[X,J]=l.useState(null),[ee,De]=l.useState(null),[ze,j]=l.useState(""),B=l.useRef(null),te=il(p=>p.channels),ge=l.useMemo(()=>{const p=new Map;for(const R of te)p.set(R.kind,R.runtime.some($=>$.running));return p},[te]),ve=l.useMemo(()=>{const p=new Map;for(const R of t.workspaces)p.set(R.key,[]);for(const R of t.sessions){const $=Fa(R,t.workspaces);p.has($)||p.set($,[]),p.get($).push(R)}return p},[t.workspaces,t.sessions]),ye=l.useMemo(()=>{const p=new Map(t.workspaces.map(Y=>[Y.key,Y])),R=[];for(const Y of w){const de=p.get(Y);de&&(R.push(de),p.delete(Y))}const $=[...p.values()].sort((Y,de)=>(Y.kind==="channel"?-1:0)-(de.kind==="channel"?-1:0));return[...R,...$]},[t.workspaces,w]),_e=S?ye.findIndex(p=>p.key===S):-1,je=l.useMemo(()=>{const p=ye.map($=>({key:`ws:${$.key}`,ws:$,at:(ve.get($.key)||[]).reduce((Y,de)=>Math.max(Y,Ps(de.updated_at)),0)}));if(t.orderBy!=="activity")return p;const R=(t.extraRows||[]).map($=>({key:`row:${$.key}`,at:$.at,node:$.node}));return Wu([...R,...p],t.pinnedEntries||{})},[ye,ve,t.orderBy,t.extraRows,t.pinnedEntries]),C=t.orderBy!=="activity",K=p=>{const R=S;if(g(null),H(null),!R||R===p)return;const $=ye.map(he=>he.key),Y=$.indexOf(p);if(Y<0||!$.includes(R))return;const de=hc($,R,Y);z(de),Xu(de)},q=p=>{D(R=>{const $=new Set(R);return $.has(p)?$.delete(p):$.add(p),wi($),$})},Ae=p=>{D(R=>{if(!R.has(p))return R;const $=new Set(R);return $.delete(p),wi($),$})},$e=p=>{t.onEnterWorkspace?.(p),Ae(p)};l.useEffect(()=>{if(!O.current){O.current=!0;return}t.activeWorkspaceKey!=null&&Ae(t.activeWorkspaceKey)},[t.activeWorkspaceKey]),l.useEffect(()=>{f&&W.current?.select()},[f]),l.useEffect(()=>{ee&&B.current?.select()},[ee]),l.useEffect(()=>{if(!r&&!E)return;const p=()=>{u(null),G(null)};return window.addEventListener("click",p),window.addEventListener("contextmenu",p),()=>{window.removeEventListener("click",p),window.removeEventListener("contextmenu",p)}},[r,E]);const Je=(p,R)=>{p.preventDefault(),p.stopPropagation(),G(null);const $=c.batch(R.id);$.length===1&&c.only(R.id),u({id:R.id,ids:$,x:p.clientX,y:p.clientY,archived:!!R.archived})},Me=(p,R)=>{p.preventDefault(),p.stopPropagation(),u(null),G({ws:R,x:p.clientX,y:p.clientY})},at=()=>{f&&x.trim()&&t.onRename(f,x.trim()),k(null)},jt=()=>{if(ee&&ze.trim()){const p=t.workspaces.find(R=>R.key===ee);p&&t.onRenameWorkspace(p,ze.trim())}De(null)},Le=(p,R)=>{const $=p.kind==="channel"?xi[p.channel||"wechat"]:p.kind==="cloud"?Dt:p.kind==="rootless"?Mn:R?$n:dc;return e.jsxs("span",{className:"t2s-lead",children:[ss(p)?e.jsx(Fu,{path:p.path,className:"amx-page-emoji t2s-project-icon",fallback:e.jsx($,{className:"t2s-lead-icon"})}):e.jsx($,{className:"t2s-lead-icon"}),e.jsx("span",{className:`t2s-chev t2s-lead-chev${R?"":" open"}`,onClick:Y=>{Y.stopPropagation(),q(p.key)},children:e.jsx(xt,{size:12})})]})},bt=p=>e.jsx(Oi,{as:"button",className:`${p.id===t.activeId?"active":""}${c.has(p.id)?" sel":""}`.trim()||void 0,selId:p.id,title:p.summary||p.title||void 0,depth:t.flat?0:1,lead:e.jsxs(e.Fragment,{children:[e.jsx(qs,{emoji:p.emoji,fallback:t.rowIcon?.(p)??e.jsx(Dn,{className:"t2s-lead-icon t2s-dim"})}),t.attentionIds?.get(p.id)?e.jsx(io,{n:t.attentionIds.get(p.id).n,localOnly:t.attentionIds.get(p.id).localOnly}):t.runningIds.has(p.id)?e.jsx("span",{className:"t2s-dot running",title:n("sidebar.running")}):t.unreadIds.has(p.id)?e.jsx("span",{className:"t2s-dot unread",title:n("sidebar.unread")}):null]}),trailing:e.jsx("span",{className:"t2s-srow-menu",onClick:R=>Je(R,p),children:e.jsx(Ln,{size:14})}),onClick:R=>{const $=c.click(p.id,R);if($.open==="none")return;t.onSelect(p.id,$.open==="new"?{newTab:!0}:void 0);const Y=t.sessionWorkspaceKeyOf?t.sessionWorkspaceKeyOf(p):Fa(p,t.workspaces);Y&&(t.onActivateEntry?.(`ws:${Y}`),$e(Y))},onContextMenu:R=>Je(R,p),draggable:f!==p.id,onDragStart:R=>{const $=R.currentTarget.getBoundingClientRect();R.dataTransfer.setDragImage(R.currentTarget,R.clientX-$.left,R.clientY-$.top),R.dataTransfer.effectAllowed="copy";const Y=[...o,...i],de=c.batch(p.id).map(he=>{const Ze=Y.find(Oe=>Oe.id===he);return{kind:"session",id:he,title:_t(Ze?.title,n)}});uc(R.dataTransfer,de)},children:f===p.id?e.jsx("input",{ref:W,className:"t2s-rename",value:x,onChange:R=>T(R.target.value),onBlur:at,onKeyDown:R=>{R.key==="Enter"&&at(),R.key==="Escape"&&k(null)},onClick:R=>R.stopPropagation()}):e.jsx("span",{className:"t2s-srow-title",children:_t(p.title,n)})},p.id);return e.jsxs("aside",{className:"t2s-side",ref:a,children:[e.jsxs("div",{className:"t2s-scroll",onDragOver:p=>{S&&(p.preventDefault(),p.dataTransfer.dropEffect="move")},onDrop:p=>{S&&F&&(p.preventDefault(),K(F))},children:[t.showSpecial&&e.jsx("div",{className:"t2s-special-group",children:e.jsxs("div",{className:"t2s-special-row",children:[e.jsx(Ju,{icon:e.jsx(Rc,{}),title:n("sidebar.newChat"),active:!1,onClick:t.onNewChat,act:"new-chat"}),t.mode&&t.onModeChange&&e.jsxs("div",{className:"t2s-vaultseg t2s-mode",role:"tablist","aria-label":n("sidebar.mode.tip"),title:n("sidebar.mode.tip"),children:[e.jsx("div",{className:"t2s-vaultseg-thumb","data-side":t.mode}),["chat","work"].map(p=>e.jsx("button",{type:"button",role:"tab","aria-selected":t.mode===p,"data-mode":p,className:t.mode===p?"on":void 0,onClick:()=>t.onModeChange(p),children:n(p==="chat"?"sidebar.mode.chat":"sidebar.mode.work")},p))]})]})}),je.map((p,R)=>{if(p.node)return e.jsx(zn.Fragment,{children:p.node},p.key);const $=p.ws,Y=ki(t.pinnedEntries||{},p.key),de=ve.get($.key)||[];if(t.flat)return e.jsx("div",{className:"t2s-group-sessions t2s-flat",children:de.map(bt)},$.key);const he=_.has($.key),Ze={onDragOver:Q=>{if(!S)return;Q.preventDefault(),Q.dataTransfer.dropEffect="move";const Qe=S===$.key?null:$.key;F!==Qe&&H(Qe)},onDrop:Q=>{S&&(Q.preventDefault(),Q.stopPropagation(),K($.key))}},Oe=!!S&&F===$.key&&S!==$.key,Fe=Oe&&_e>=0&&_e<R,pe=Fe?he?" drag-over below":"":Oe?" drag-over":"";return e.jsxs(zn.Fragment,{children:[e.jsxs("div",{className:`t2s-group${pe}${S===$.key?" dragging":""}`,"data-workspace-key":$.key,"data-pinned":Y?"true":void 0,"data-active":t.activeWorkspaceKey===$.key?"true":void 0,style:{paddingLeft:_i(0)},...Di(()=>[$.path||"",Tc("tip.sessions",{count:de.length})].filter(Boolean)),draggable:C&&ee!==$.key,onContextMenu:Q=>Me(Q,$),onDragStart:Q=>{const Qe=Q.currentTarget.getBoundingClientRect();Q.dataTransfer.setDragImage(Q.currentTarget,Q.clientX-Qe.left,Q.clientY-Qe.top),Q.dataTransfer.effectAllowed="move",g($.key)},...Ze,onDragEnd:()=>{g(null),H(null)},children:[ee===$.key?e.jsxs("div",{className:"t2s-group-toggle t2s-folder-row",style:{cursor:"default"},children:[Le($,he),e.jsx("input",{ref:B,className:"t2s-rename",value:ze,onChange:Q=>j(Q.target.value),onBlur:jt,onKeyDown:Q=>{Q.key==="Enter"&&jt(),Q.key==="Escape"&&De(null)},onClick:Q=>Q.stopPropagation()})]}):$.kind==="channel"?e.jsxs("button",{className:"t2s-group-toggle t2s-folder-row",onClick:()=>{t.onActivateEntry?.(p.key),he?$e($.key):q($.key)},children:[Le($,he),e.jsx("span",{className:"t2s-group-label",children:rs($,n)}),Y&&e.jsx(as,{className:"t2o-pin-mark","aria-hidden":"true"}),e.jsx("span",{className:`t2s-mini-dot${ge.get($.channel||"wechat")?" ok":""}`})]}):e.jsxs("button",{className:"t2s-group-toggle t2s-folder-row",onClick:()=>{t.onActivateEntry?.(p.key),he?$e($.key):q($.key)},children:[Le($,he),e.jsx("span",{className:"t2s-group-label",children:rs($,n)}),Y&&e.jsx(as,{className:"t2o-pin-mark","aria-hidden":"true"})]}),(!$.system||t.onTogglePinned||t.onShowWorkspaceDetails&&ss($))&&e.jsx("button",{type:"button",className:"t2s-group-add",title:n("sidebar.ws.menu"),onClick:Q=>Me(Q,$),children:e.jsx(Ln,{size:14})}),e.jsx("button",{type:"button",className:"t2s-group-add",title:n("sidebar.newChatIn",{name:rs($,n)}),onClick:()=>t.onNewInWorkspace($),children:e.jsx(An,{size:14})})]}),e.jsx(to,{open:!he,children:e.jsxs("div",{className:`t2s-group-sessions${Fe&&!he?" drag-over-end":""}`,...Ze,children:[de.slice(0,M).map(bt),de.length>M&&e.jsxs("button",{className:"t2s-viewmore",onClick:()=>t.onOpenWorkspace($.key),children:[n("sidebar.viewMore")," · ",de.length-M]})]})})]},$.key)}),t.deviceSections]}),(window.tangu?.pickDirectory&&!t.flat||t.archivedSessions.length>0)&&e.jsxs("div",{className:"t2s-foot",children:[window.tangu?.pickDirectory&&!t.flat&&e.jsxs("button",{className:"t2s-add-ws",onClick:t.onAddWorkspace,children:[e.jsx(Fi,{size:14})," ",n("sidebar.addLocalWorkspace")]}),t.archivedSessions.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"t2s-srow t2s-archived-toggle",onClick:()=>U(!I),children:[e.jsx("span",{className:"t2s-chev",children:e.jsx(bs,{size:13})}),e.jsx("span",{className:"t2s-srow-title t2s-faint",children:n("sidebar.archived")}),e.jsx("span",{className:"t2s-count",children:t.archivedSessions.length})]}),I&&t.archivedSessions.map(bt)]})]}),r&&e.jsxs(ws,{className:"ctx-menu",x:r.x,y:r.y,onClick:p=>p.stopPropagation(),children:[r.ids.length===1&&e.jsxs("button",{onClick:()=>{t.onSelect(r.id,{newTab:!0}),u(null)},children:[e.jsx(An,{size:13})," ",n("sidebar.openInNewTab")]}),r.ids.length===1&&e.jsxs("button",{onClick:()=>{const p=[...o,...i].find(R=>R.id===r.id);h({id:r.id,current:p?.emoji??null,x:r.x,y:r.y}),u(null)},children:[e.jsx(Wi,{size:13})," ",n("session.icon.set")]}),r.ids.length===1&&e.jsxs("button",{onClick:()=>{const p=[...o,...i].find(R=>R.id===r.id);T(p?.title||""),k(r.id),u(null)},children:[e.jsx(Tn,{size:13})," ",n("sidebar.rename")]}),r.ids.length===1&&Hu()&&e.jsxs("button",{onClick:()=>{Ku(r.id),u(null)},children:[e.jsx(Vc,{size:13})," ",n("chat.toNote.action")]}),e.jsxs("button",{onClick:()=>{for(const p of r.ids)t.onArchive(p,!r.archived);c.clear(),u(null)},children:[r.archived?e.jsx(Fc,{size:13}):e.jsx(bs,{size:13}),r.ids.length>1?n(r.archived?"sidebar.unarchiveN":"sidebar.archiveN",{n:String(r.ids.length)}):r.archived?n("sidebar.unarchive"):n("sidebar.archive")]}),r.ids.length===1&&(()=>{const p=[...o,...i].find(Y=>Y.id===r.id),R=p?.project_path?t.workspaces.find(Y=>Y.kind==="channel"&&Y.key===p.project_path):null;if(!p||!R?.channel)return null;const $=xi[R.channel];return e.jsxs("button",{onClick:()=>{u(null),lc(nt(),R.channel,r.id).then(()=>t.onToast?.(n("sidebar.wechat.setConnectedOk"))).catch(Y=>t.onToast?.(n("sidebar.wechat.setConnectedFail",{e:Y?.message||Y}),!0))},children:[e.jsx($,{size:13})," ",n("sidebar.channel.setAsConnected")]})})(),r.ids.every(p=>t.archivedSessions.some(R=>R.id===p))&&e.jsxs("button",{className:"danger",onClick:()=>{const p=r.ids,R=[...o,...i].find(Y=>Y.id===r.id);if(u(null),!!(p.length>1?window.confirm(n("sidebar.deleteConfirmN",{n:String(p.length)})):window.confirm(n("sidebar.deleteConfirm",{name:_t(R?.title,n)})))){for(const Y of p)t.onDelete(Y);c.clear()}},children:[e.jsx(xs,{size:13})," ",r.ids.length>1?n("sidebar.deleteN",{n:String(r.ids.length)}):n("sidebar.delete")]})]}),d&&e.jsx(eo,{sessionId:d.id,current:d.current,x:d.x,y:d.y,onClose:()=>h(null)}),E&&e.jsxs(ws,{className:"ctx-menu",x:E.x,y:E.y,onClick:p=>p.stopPropagation(),children:[t.onTogglePinned&&(()=>{const p=`ws:${E.ws.key}`,R=ki(t.pinnedEntries||{},p);return e.jsxs("button",{onClick:()=>{G(null),t.onTogglePinned?.(p)},children:[R?e.jsx(Qc,{size:13}):e.jsx(as,{size:13})," ",n(R?"sidebar.unpin":"sidebar.pin")]})})(),t.onShowWorkspaceDetails&&ss(E.ws)&&[...o,...i].some(p=>p.project_path===E.ws.path&&!p.projectless)&&e.jsxs("button",{"data-act":"ws-details",onClick:()=>{const p=E.ws;G(null),t.onShowWorkspaceDetails?.(p)},children:[e.jsx(_c,{size:13})," ",n("sidebar.ws.details")]}),!E.ws.system&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>{j(E.ws.name),De(E.ws.key),G(null)},children:[e.jsx(Tn,{size:13})," ",n("sidebar.ws.rename")]}),e.jsxs("button",{className:"danger","data-act":"ws-remove",onClick:()=>{J(E.ws),G(null)},children:[e.jsx(xs,{size:13})," ",n("sidebar.ws.remove")]})]})]}),X&&e.jsx(no,{title:n("sidebar.ws.removeTitle",{name:X.name}),message:n("sidebar.ws.removeMsg",{count:[...o,...i].filter(p=>p.project_path===X.key).length}),confirmLabel:n("sidebar.ws.removeAction"),filesLabel:X.kind==="local"&&window.tangu?.trashHostPath?n("sidebar.ws.removeFiles"):void 0,onConfirm:p=>t.onRemoveWorkspace(X,{deleteFiles:p}),onClose:()=>J(null)})]})};me({"devstatus.checking":{zh:"正在连接…",en:"Connecting…"},"devstatus.ready":{zh:"在线",en:"Online"},"devstatus.starting":{zh:"引擎正在启动",en:"Engine is starting"},"devstatus.engineStopped":{zh:"引擎没有运行",en:"Engine isn't running"},"devstatus.noEngine":{zh:"没有 Agent 引擎",en:"No agent engine"},"devstatus.offline":{zh:"离线",en:"Offline"},"devstatus.unreachable":{zh:"暂时连不上",en:"Can't reach it"},"devstatus.remoteOff":{zh:"未开启远程会话",en:"Remote sessions off"},"devstatus.awaitingConfirm":{zh:"等待那台电脑允许",en:"Waiting for approval there"},"devstatus.denied":{zh:"拒绝了这台手机",en:"Declined this phone"},"devstatus.callerBlocked":{zh:"不允许这台手机运行",en:"Doesn't allow this phone"},"devstatus.long.checking":{zh:"正在连接这台电脑…",en:"Connecting to this computer…"},"devstatus.long.ready":{zh:"在线,可以在上面运行会话",en:"Online. Sessions can run here"},"devstatus.long.starting":{zh:"这台电脑在线,Agent 引擎正在启动",en:"This computer is online and its agent engine is starting"},"devstatus.long.engineStopped":{zh:"Forsion 已打开,但 Agent 引擎没有运行",en:"Forsion is open, but its agent engine isn't running"},"devstatus.long.noEngine":{zh:"这台设备上的 Forsion 没有 Agent 引擎",en:"Forsion on this device has no agent engine"},"devstatus.long.offline":{zh:"离线,重新上线后这里会显示它的会话",en:"Offline. Its sessions show up here when it's back"},"devstatus.long.unreachable":{zh:"暂时连不上,稍后重试",en:"Can't reach it right now. Try again shortly"},"devstatus.long.remoteOff":{zh:"这台电脑没有开启「允许远程会话」",en:"Remote sessions are turned off on this computer"},"devstatus.long.awaitingConfirm":{zh:"请在那台电脑上允许这台手机",en:"Allow this phone on that computer to continue"},"devstatus.long.denied":{zh:"那台电脑拒绝了这台手机",en:"That computer declined this phone"},"devstatus.long.callerBlocked":{zh:"那台电脑不允许这台手机运行会话,请在它的「设置 › 远程会话」中调整",en:"That computer doesn't let this phone run sessions. Change it in Settings › Remote sessions there"},"sidebar.device.label":{zh:"{name} 上的会话",en:"Sessions on {name}"},"sidebar.device.empty":{zh:"还没有会话",en:"No sessions yet"},"sidebar.device.pickFirst":{zh:"在「在哪运行」里选过这台电脑后,这里会显示它的会话",en:"Pick this computer under Run on to see its sessions here"},"sidebar.device.menu":{zh:"更多操作",en:"More actions"}});function Pn(t,n){const a=typeof t=="string"?t.trim():"";return a.length>n?`${a.slice(0,n-1)}…`:a}const lo="forsion_device_sections_collapsed";function Zu(){try{const t=JSON.parse(localStorage.getItem(lo)||"[]");return new Set(Array.isArray(t)?t.filter(n=>typeof n=="string").slice(0,200):[])}catch{return new Set}}function Qu(t){try{localStorage.setItem(lo,JSON.stringify([...t]))}catch{}}function ed({u:t}){return t.icon?e.jsx("span",{className:"t2d-emoji","aria-hidden":!0,children:Pn(t.icon,4)}):t.platform==="win32"||t.platform==="linux"?e.jsx(Ii,{className:"t2s-lead-icon"}):e.jsx(Pi,{className:"t2s-lead-icon"})}function Yd(t,n){const a=t?.get(n);return a?e.jsx(io,{n:a.n,localOnly:a.localOnly}):null}function uo(){const t=P(n=>n.connState);l.useEffect(()=>{if(!wt())return;const n=()=>{ae.getState().refresh()},a=()=>{ae.getState().refresh({periodic:!0})};n();let o=null;const i=()=>{o&&(clearInterval(o),o=null),(typeof document>"u"||document.visibilityState==="visible")&&(o=setInterval(a,3e4))},c=()=>{document.visibilityState==="visible"&&n(),i()};return i(),document.addEventListener("visibilitychange",c),()=>{document.removeEventListener("visibilitychange",c),o&&clearInterval(o)}},[]),l.useEffect(()=>{t==="ok"&&wt()&&ae.getState().refresh()},[t])}function Gd(t){const{t:n}=we();uo();const a=ae(w=>w.units),o=ae(w=>w.byUnit);Wt(w=>w.probes),Wt(w=>w.sticky);const i=P(w=>w.sessions),c=ae(w=>w.selfRegistered),[r,u]=l.useState(Zu),[d,h]=l.useState(null),[f,k]=l.useState(null),[x,T]=l.useState(null),[M,A]=l.useState(""),I=l.useRef(null);l.useEffect(()=>{x&&I.current?.select()},[x]),l.useEffect(()=>{if(!d)return;const w=()=>h(null),z=S=>{S.key==="Escape"&&h(null)};return window.addEventListener("click",w),window.addEventListener("contextmenu",w),window.addEventListener("keydown",z),()=>{window.removeEventListener("click",w),window.removeEventListener("contextmenu",w),window.removeEventListener("keydown",z)}},[d]);const U=l.useMemo(()=>{const w={};for(const z of a||[]){const S=z.id.toLowerCase();if(!z.online){w[S]=[];continue}const g=o[S]?.sessions??[],F=new Set(g.map(O=>O.id)),W=[...i.filter(O=>O.location?.kind==="unit"&&O.location.unitId===S&&!F.has(O.id)&&!O.archived),...g].sort((O,E)=>Ps(E.updated_at)-Ps(O.updated_at));w[S]=t.filter?t.filter(W):W}return w},[a,o,i,t.filter]);if(!wt()||!a?.length)return null;const _=w=>{u(z=>{const S=new Set(z);return S.has(w)?S.delete(w):S.add(w),Qu(S),S})},D=()=>{x&&M.trim()&&Lu(x.unitId,x.id,M.trim()),T(null)};return e.jsxs("div",{className:"t2d-sections","data-device-sections":!0,children:[a.map(w=>{const z=w.id.toLowerCase(),S=Bs(w).status,g=U[z]??[],F=r.has(z),H=Pn(w.name,60)||n("engine.target.defaultName");return e.jsxs("div",{className:"t2d-section","data-device-section":z,"data-device-status":S,children:[e.jsx("div",{className:"t2s-group t2d-head",style:{paddingLeft:_i(0)},title:n(`devstatus.long.${S}`),children:e.jsxs("button",{type:"button",className:"t2s-group-toggle t2s-folder-row t2d-toggle","aria-expanded":!F,"aria-label":n("sidebar.device.label",{name:H}),onClick:()=>_(z),children:[e.jsxs("span",{className:"t2s-lead",children:[e.jsx(ed,{u:w}),e.jsx("span",{className:`t2s-chev t2s-lead-chev${F?"":" open"}`,children:e.jsx(xt,{size:12})})]}),e.jsx("span",{className:"t2s-group-label t2d-name",children:H}),e.jsx("span",{className:"t2d-status","data-tone":S==="ready"?"ok":S==="checking"?"wait":"warn",role:"status",children:n(`devstatus.${S}`)})]})}),e.jsx(to,{open:!F,children:e.jsxs("div",{className:"t2s-group-sessions",children:[g.map(W=>e.jsx(Oi,{as:x?.id===W.id?"div":"button",className:W.id===t.activeId?"active":void 0,depth:1,title:W.summary||W.title||void 0,lead:e.jsxs(e.Fragment,{children:[e.jsx(qs,{emoji:W.emoji,fallback:e.jsx(Dn,{className:"t2s-lead-icon t2s-dim"})}),t.rowBadge?.(W)??(t.runningIds.has(W.id)?e.jsx("span",{className:"t2s-dot running"}):t.unreadIds.has(W.id)?e.jsx("span",{className:"t2s-dot unread"}):null)]}),trailing:x?.id===W.id?void 0:e.jsx("span",{className:"t2s-srow-menu",role:"button","aria-label":n("sidebar.device.menu"),onClick:O=>{O.stopPropagation(),h({unitId:z,id:W.id,x:O.clientX,y:O.clientY})},children:e.jsx(Ln,{size:14})}),onClick:()=>{x?.id!==W.id&&$s(W,{unitId:z})},onContextMenu:O=>{O.preventDefault(),O.stopPropagation(),h({unitId:z,id:W.id,x:O.clientX,y:O.clientY})},children:x?.id===W.id?e.jsx("input",{ref:I,className:"t2s-rename",value:M,onChange:O=>A(O.target.value),onBlur:D,onKeyDown:O=>{O.key==="Enter"&&D(),O.key==="Escape"&&T(null)},onClick:O=>O.stopPropagation()}):e.jsx("span",{className:"t2s-srow-title","data-remote-session":W.id,children:_t(Pn(W.title,200),n)})},W.id)),S==="ready"&&!g.length&&e.jsx("div",{className:"t2d-empty",children:n(c===!1?"sidebar.device.pickFirst":"sidebar.device.empty")})]})})]},z)}),d&&e.jsxs(ws,{className:"ctx-menu",x:d.x,y:d.y,onClick:w=>w.stopPropagation(),children:[e.jsxs("button",{onClick:()=>{const w=U[d.unitId]?.find(z=>z.id===d.id);k({...d,current:w?.emoji??null}),h(null)},children:[e.jsx(Wi,{size:13})," ",n("session.icon.set")]}),e.jsxs("button",{onClick:()=>{const w=U[d.unitId]?.find(z=>z.id===d.id);A(w?.title||""),T({unitId:d.unitId,id:d.id}),h(null)},children:[e.jsx(Tn,{size:13})," ",n("sidebar.rename")]}),e.jsxs("button",{onClick:()=>{const w=d;h(null),Pu(w.unitId,w.id)},children:[e.jsx(bs,{size:13})," ",n("sidebar.archive")]})]}),f&&e.jsx(eo,{sessionId:f.id,current:f.current,x:f.x,y:f.y,onSave:w=>Iu(f.unitId,f.id,w),onClose:()=>k(null)})]})}me({"runloc.label":{zh:"运行位置",en:"Run on"},"runloc.cloud":{zh:"云端",en:"Cloud"},"runloc.thisDevice":{zh:"这台电脑",en:"This computer"},"runloc.pillTitle":{zh:"新会话在哪运行:{where}",en:"New sessions run on: {where}"}});function td(){const t=ae(n=>n.units);return wt()&&!!t?.length}function Xd(){const{t}=we();uo();const n=td(),a=Ga(d=>d.ref);Ga(d=>d.name),ae(d=>d.units),Wt(d=>d.probes),Wt(d=>d.sticky);const o=Ue(d=>d.chooser);if(!n)return null;const i=a.kind==="unit"?Xi(a.unitId):null,c=i?Bs(i).status:null,r=a.kind==="unit"?Pn(mc(a)||i?.name,60)||t("engine.target.defaultName"):t("runloc.cloud"),u=a.kind==="home"?Dt:i?.platform==="win32"||i?.platform==="linux"?Ii:Pi;return e.jsx("div",{className:"project-selector runloc","data-run-location-picker":!0,"data-run-location":Gi(a)||"home","data-device-status":c??void 0,children:e.jsxs("button",{type:"button",className:"composer-chip project-pill runloc-pill",title:t("runloc.pillTitle",{where:r}),"aria-label":t("runloc.pillTitle",{where:r}),"aria-haspopup":"dialog",disabled:!o,onClick:()=>o?.(),children:[e.jsx(u,{size:13}),e.jsx("span",{className:"project-pill-name",children:r}),c&&c!=="ready"&&e.jsx("span",{className:"runloc-status","data-tone":c==="checking"?"wait":"warn",children:t(`devstatus.${c}`)}),o&&e.jsx(rn,{size:12})]})})}export{_l as $,bs as A,dl as B,Id as C,Gd as D,ei as E,Hi as F,jd as G,Md as H,ul as I,Cd as J,qi as K,zd as L,Ad as M,Vc as N,Ed as O,Fu as P,_d as Q,cl as R,Kd as S,Vl as T,Ui as U,Pd as V,Xd as W,Dd as X,to as Y,El as Z,Ld as _,Fc as a,tl as a0,Td as a1,Ml as a2,$d as a3,We as a4,td as a5,_t as b,eo as c,ju as d,qs as e,gu as f,vu as g,Ud as h,Od as i,Wd as j,Yd as k,Ps as l,ki as m,Qc as n,Vd as o,qd as p,bd as q,Hd as r,Fd as s,Bd as t,il as u,Sd as v,rs as w,Nd as x,Rd as y,gl as z};