@forsion/unit 2.13.2 → 2.13.4

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 (207) hide show
  1. package/main.mjs +25 -3
  2. package/package.json +1 -1
  3. package/release.json +5 -5
  4. package/web/assets/ArtificialView-DLh75dAI.js +1 -0
  5. package/web/assets/AutomationBuilder-DNWWGnFr.js +1 -0
  6. package/web/assets/CalendarConfigView-G7je7k9-.js +1 -0
  7. package/web/assets/{CalendarView-D7ZUE_dr.js → CalendarView-B2MtaOJk.js} +1 -1
  8. package/web/assets/{CapabilityMenu-CrsaTtDe.js → CapabilityMenu-DJaZ_Cyt.js} +1 -1
  9. package/web/assets/{CheckboxInput-DVO2-1J7.js → CheckboxInput-FYXLaZke.js} +1 -1
  10. package/web/assets/{Chrome-BvpbCvo1.js → Chrome-CFonajM4.js} +1 -1
  11. package/web/assets/{CodeView-CB4kG7Y6.js → CodeView-GZ0BAgoW.js} +3 -3
  12. package/web/assets/DashboardGridView-D9s9pez_.css +1 -0
  13. package/web/assets/DashboardGridView-Xgw4wa0_.js +17 -0
  14. package/web/assets/{EventCard-c6s4uGBu.js → EventCard-_39F_I5M.js} +1 -1
  15. package/web/assets/ExcalidrawCanvas-rXujil36.js +1 -0
  16. package/web/assets/{FloatingToc-ldOYWe2C.js → FloatingToc-DNqAkkI0.js} +1 -1
  17. package/web/assets/GitCloneDialog-Bj9G3o-n.css +1 -0
  18. package/web/assets/GitCloneDialog-CQx-O4j1.js +1 -0
  19. package/web/assets/HomepageView-DcWmTPQO.css +1 -0
  20. package/web/assets/HomepageView-MYEk3RCs.js +3 -0
  21. package/web/assets/{ImageStudioPanels-DgMYAsHj.js → ImageStudioPanels-4wnb2XF4.js} +2 -2
  22. package/web/assets/ImageStudioView-qrmW8pfx.js +1 -0
  23. package/web/assets/InlineAiPanel-B3kd1ob2.js +1 -0
  24. package/web/assets/InlineAiPanel-DZZijfif.css +1 -0
  25. package/web/assets/InlineFiles-Clnqh9jD.js +1 -0
  26. package/web/assets/MarkdownBlock-DQTuoen3.css +1 -0
  27. package/web/assets/MarkdownBlock-DT_wsaja.js +58 -0
  28. package/web/assets/ModelPill-JaIH3ffZ.js +2 -0
  29. package/web/assets/MuseLibraryView-16p1zsxz.css +1 -0
  30. package/web/assets/MuseLibraryView-DOJVVeU6.js +2 -0
  31. package/web/assets/{MuseView-3GL4Ltoj.js → MuseView-uxTmjVQa.js} +2 -2
  32. package/web/assets/{PageHistoryPanel-BMQC-V_l.js → PageHistoryPanel-Bn4-XmdK.js} +2 -2
  33. package/web/assets/{PdfAnnotator-CyAw8sgq.js → PdfAnnotator-Cq8cklTz.js} +1 -1
  34. package/web/assets/PenRow-COOYAaxx.js +1 -0
  35. package/web/assets/ProductView-DPTveulg.js +1 -0
  36. package/web/assets/RightPanel-BJUacrsf.js +4 -0
  37. package/web/assets/RightPanel-D0zk1g3I.css +1 -0
  38. package/web/assets/{SketchCard-DAD0jR0i.js → SketchCard-B_UU5sxV.js} +3 -3
  39. package/web/assets/{StudioGuestSurface-DlUKXBXv.js → StudioGuestSurface-yBa4QKfX.js} +1 -1
  40. package/web/assets/TargetHealthNotice-BLzDB-Xl.css +1 -0
  41. package/web/assets/TargetHealthNotice-CgkdTdhB.js +47 -0
  42. package/web/assets/{TodoListView-_yFkPUrw.js → TodoListView-CricdCfW.js} +1 -1
  43. package/web/assets/{Tooltip-DXuy9-1_.js → Tooltip-o8ZqIb3L.js} +1 -1
  44. package/web/assets/UnifiedPage-BWAyqj65.js +69 -0
  45. package/web/assets/ViewSelectionBar-35x8TiLA.js +2 -0
  46. package/web/assets/{amadeus-manual.en-DzRWr4BL.js → amadeus-manual.en-B8J-svqq.js} +1 -1
  47. package/web/assets/{amadeus-manual.zh-DW32DkL7.js → amadeus-manual.zh-CkCOFnrg.js} +1 -1
  48. package/web/assets/appStore-CI1_L5OS.js +3357 -0
  49. package/web/assets/appStore-DQc2marq.css +1 -0
  50. package/web/assets/{arrow-up-right-KPFbRA41.js → arrow-up-right-BDsMFoNQ.js} +1 -1
  51. package/web/assets/{astryxBridge-Bupzouso.js → astryxBridge-CH_c5xjo.js} +3 -3
  52. package/web/assets/automationListSource-CB6AWkL_.js +1 -0
  53. package/web/assets/{boardSurface-BHuMoQN-.js → boardSurface-CLvEUjbF.js} +1 -1
  54. package/web/assets/{book-open-CBeNsIpo.js → book-open-BLzEdGfu.js} +1 -1
  55. package/web/assets/{calendarNavStore-Duyhbmm_.js → calendarNavStore-BHUNxDx8.js} +1 -1
  56. package/web/assets/{canvasPrefs-CxfyDTMT.js → canvasPrefs-CvE7mgyq.js} +1 -1
  57. package/web/assets/{chatBoxSurface-OBzO1Z5E.js → chatBoxSurface-CuuHLzs5.js} +1 -1
  58. package/web/assets/{circle-question-mark-M8QUJJYk.js → circle-question-mark-BM4ZRxQS.js} +1 -1
  59. package/web/assets/{circle-x-Szwop5L_.js → circle-x-DTcNGZDT.js} +1 -1
  60. package/web/assets/{client-CPUljePZ.js → client-CaivGZFR.js} +5 -5
  61. package/web/assets/{code-xml-n9mgGgkv.js → code-xml-AE3mT4T5.js} +1 -1
  62. package/web/assets/{codeStudioStore-DXMQwRzG.js → codeStudioStore-DhyMazGT.js} +1 -1
  63. package/web/assets/codingNavigation-B0kVsy4x.js +53 -0
  64. package/web/assets/codingNavigation-DHCidM4N.css +1 -0
  65. package/web/assets/{create-C19zqt5N.js → create-1JI2I47p.js} +2 -2
  66. package/web/assets/dashboardSurface-CIE5HybN.js +1 -0
  67. package/web/assets/{deskCapture-B_LKZSPt.js → deskCapture-COW7aG5Y.js} +1 -1
  68. package/web/assets/{diff2html-DrCCWvpR.js → diff2html-Daje9Kkm.js} +1 -1
  69. package/web/assets/{docx-preview-Bi7wekSM.js → docx-preview-CABR7n30.js} +1 -1
  70. package/web/assets/emoji-DZ9CA_3l.css +1 -0
  71. package/web/assets/emoji-DphwSxPx.js +1 -0
  72. package/web/assets/{floatingTocSurface-rc1ZC7-I.js → floatingTocSurface-BOm2QYBK.js} +1 -1
  73. package/web/assets/{foldActions-BGocXE-o.js → foldActions-DNbJPlPl.js} +1 -1
  74. package/web/assets/{folder-CoOsfQ64.js → folder-DotgUhYD.js} +1 -1
  75. package/web/assets/{folder-plus-d5MwIMlf.js → folder-plus-aJgL9NeP.js} +1 -1
  76. package/web/assets/gestures-dqncPOwo.js +1 -0
  77. package/web/assets/git-branch-CwR2qic6.js +1 -0
  78. package/web/assets/{hand-fuehbnkI.js → hand-XNkzNiW2.js} +1 -1
  79. package/web/assets/{hard-drive-Bh1DmZg0.js → hard-drive-CfWKRoAE.js} +1 -1
  80. package/web/assets/i18n-CykmULlm.css +1 -0
  81. package/web/assets/i18n.generated-BwynSSMk.js +15 -0
  82. package/web/assets/{imageStudio-Dgl1wZNB.js → imageStudio-CWgLpC_d.js} +2 -2
  83. package/web/assets/imageStudio-DZ0qGU2s.css +1 -0
  84. package/web/assets/{index-2tD0kijW.js → index-B65ULikK.js} +1 -1
  85. package/web/assets/{index-BPqoEOV_.js → index-BGfvNj7R.js} +1 -1
  86. package/web/assets/{index-38xsQSS9.js → index-BIIeiIap.js} +1 -1
  87. package/web/assets/{index-B5UW6SaE.js → index-BOzsniE1.js} +89 -89
  88. package/web/assets/{index-YRWOePBS.js → index-BfrjVzia.js} +1 -1
  89. package/web/assets/{index-CnDAYLti.js → index-Bi9UtjVz.js} +1 -1
  90. package/web/assets/{index-fViJsYjM.js → index-C1uilc9i.js} +1 -1
  91. package/web/assets/{index-CPLtf9Vc.js → index-C3Dc3Ivz.js} +1 -1
  92. package/web/assets/{index-B8Co6KG3.js → index-CJF_Ld1Y.js} +1 -1
  93. package/web/assets/{index-lfow5R3O.js → index-CMARP4oV.js} +1 -1
  94. package/web/assets/{index-Dx9aIoyo.js → index-C_RsQVNm.js} +1 -1
  95. package/web/assets/{index-D4CSH-v1.js → index-ChyxZMm8.js} +1 -1
  96. package/web/assets/{index-7kdR1oL8.js → index-CoKcOaZg.js} +1 -1
  97. package/web/assets/{index-Ce1sNSS8.js → index-CuviSCbk.js} +1 -1
  98. package/web/assets/{index-Ch0FIsJX.js → index-Cw43kua8.js} +1 -1
  99. package/web/assets/{index-DvOrTnw2.js → index-D1fu6XQN.js} +1 -1
  100. package/web/assets/{index-QjVOA7QM.js → index-DG-hXb63.js} +1 -1
  101. package/web/assets/index-DjnTfJpN.js +1 -0
  102. package/web/assets/{index-DcRyQ3eU.js → index-Dtw0abst.js} +1 -1
  103. package/web/assets/{index-Dy07SBfH.js → index-O05r2Ty6.js} +1 -1
  104. package/web/assets/{index-BCG8Wnc4.js → index-W3ErfZiX.js} +1 -1
  105. package/web/assets/{index-e-MxdHFO.js → index-Yc56b3XX.js} +1 -1
  106. package/web/assets/{index-Dff-DL1v.js → index-d4jCdYJH.js} +1 -1
  107. package/web/assets/{index-Dc8iMctf.js → index-gt5JBIFf.js} +1 -1
  108. package/web/assets/{index-Df9jregv.js → index-siHtlYTM.js} +1 -1
  109. package/web/assets/{invitePage-Dgl3-c_m.js → invitePage-Bgveo6Hj.js} +1 -1
  110. package/web/assets/{ipc-CNlIRMtU.js → ipc-B6hkgxQL.js} +1 -1
  111. package/web/assets/{jszip.min-tyV0GaJg.js → jszip.min-eU-k-vEy.js} +1 -1
  112. package/web/assets/{layout-grid-DFmwM9NU.js → layout-grid-CraV7nhh.js} +1 -1
  113. package/web/assets/linkFollow-BpvDWzUx.js +8 -0
  114. package/web/assets/{list-tree-i07HsP3D.js → list-tree-cLJw-jYQ.js} +1 -1
  115. package/web/assets/{listFold-Aea6I0Sa.js → listFold-M8s5JYEC.js} +1 -1
  116. package/web/assets/{lock-TSDKuCod.js → lock-DBkXXwaI.js} +1 -1
  117. package/web/assets/lock-open-C-9-AWct.js +1 -0
  118. package/web/assets/{log-out-DK84lW5n.js → log-out-C8bDXj9P.js} +1 -1
  119. package/web/assets/main-CMk6twzA.js +20 -0
  120. package/web/assets/markdownEditorSurface-DgQ0TUWH.js +3 -0
  121. package/web/assets/{message-square-plus-3wFslIMY.js → message-square-plus-8pfimvem.js} +1 -1
  122. package/web/assets/{messages-DEAGRsC3.js → messages-CKtabOqy.js} +1 -1
  123. package/web/assets/minus-CfA9fAN3.js +1 -0
  124. package/web/assets/mobileEntry-NcMcK0LV.js +13 -0
  125. package/web/assets/{nativeDownload-B3JGkABw.js → nativeDownload-CNtwSCy0.js} +1 -1
  126. package/web/assets/pageChrome-BR4cfIaA.js +1 -0
  127. package/web/assets/pageChrome-BbUhILy0.css +1 -0
  128. package/web/assets/{pageTree-DZ7Eiro-.js → pageTree-BYYPgZm_.js} +4 -4
  129. package/web/assets/{pen-tool-ChGmX6g_.js → pen-tool-C5ftHCnm.js} +1 -1
  130. package/web/assets/{pencil-CJsJD7M_.js → pencil-ehhM9_9k.js} +1 -1
  131. package/web/assets/phoneList-B6gwUJZF.js +9 -0
  132. package/web/assets/phoneList-iRdfiKA8.css +1 -0
  133. package/web/assets/pluginChat-DTTWWiUS.js +2 -0
  134. package/web/assets/{redo-2-CI57sDFr.js → redo-2-DCEAgQlN.js} +1 -1
  135. package/web/assets/{rotate-ccw-xgT_0UN9.js → rotate-ccw-DdkrbRAB.js} +1 -1
  136. package/web/assets/selectionActions-BQD2kox1.js +2 -0
  137. package/web/assets/selectionBarSurface-CzUZmJDJ.js +1 -0
  138. package/web/assets/server-Ddu9f1k3.js +1 -0
  139. package/web/assets/sharePage-CNrm2xTC.js +2 -0
  140. package/web/assets/{shareViewer-DKPWhTJv.js → shareViewer-BiMqIBxP.js} +2 -2
  141. package/web/assets/{star-C9KTji9N.js → star-Dxv7XANS.js} +1 -1
  142. package/web/assets/tableSurface-Bly1iCXc.js +1 -0
  143. package/web/assets/{terminal-DPZazOQ2.js → terminal-CAmmC9cV.js} +1 -1
  144. package/web/assets/{terminalView-CsJmxE_m.js → terminalView-lbcBgG0c.js} +1 -1
  145. package/web/assets/theme-CUWFlazV.css +1 -0
  146. package/web/assets/{type-C5J875vb.js → type-Dz6rnTvG.js} +1 -1
  147. package/web/assets/{undo-2-BOUt5qks.js → undo-2-B7izWNb_.js} +1 -1
  148. package/web/assets/{unitAccount-BIAIxKNp.js → unitAccount-DGwGsmC3.js} +1 -1
  149. package/web/assets/{unitBridge-b2C6zb3a.js → unitBridge-CE2yAvm0.js} +1 -1
  150. package/web/assets/{unitCloudTransport-NGtDDKWo.js → unitCloudTransport-BGFwkaDM.js} +1 -1
  151. package/web/assets/{unitOwnerAccess-CwH9ApZT.js → unitOwnerAccess-D4nKS6Gg.js} +1 -1
  152. package/web/assets/{unitShim-CY8EVkKD.js → unitShim-2_2hhGxS.js} +3 -3
  153. package/web/assets/{upload-CrbEAW8C.js → upload-DqpRRAhG.js} +1 -1
  154. package/web/assets/userSpaces-VFu4s05v.js +1 -0
  155. package/web/assets/viewportLock-3AOdDmwi.js +631 -0
  156. package/web/assets/viewportLock-djvL8fUQ.css +1 -0
  157. package/web/assets/{zoom-in-BcuPvIYd.js → zoom-in-Bf-eKTnH.js} +1 -1
  158. package/web/index.html +2 -2
  159. package/web/assets/ArtificialView-Bs_6B211.js +0 -1
  160. package/web/assets/AutomationBuilder-C-IFaaBp.js +0 -1
  161. package/web/assets/CalendarConfigView-DEsNvVkD.js +0 -1
  162. package/web/assets/DashboardGridView-hpRmBr9B.css +0 -1
  163. package/web/assets/DashboardGridView-tgaj9-SM.js +0 -17
  164. package/web/assets/ExcalidrawCanvas-NdV86AR3.js +0 -1
  165. package/web/assets/HomepageView-4joJWYlg.js +0 -1
  166. package/web/assets/HomepageView-Cxf3AWBu.css +0 -1
  167. package/web/assets/ImageStudioView-_CYHoOoG.js +0 -1
  168. package/web/assets/InlineFiles-BIfsx3R-.js +0 -1
  169. package/web/assets/MarkdownBlock--__nPQGh.css +0 -1
  170. package/web/assets/MarkdownBlock-wYEaBBOr.js +0 -58
  171. package/web/assets/ModelPill-DveHcLqq.js +0 -2
  172. package/web/assets/MuseLibraryView-Do9RnKiq.js +0 -2
  173. package/web/assets/PenRow-BSB-h5Pb.js +0 -1
  174. package/web/assets/ProductView-B96OeHOP.js +0 -1
  175. package/web/assets/RightPanel-BgSeCLnw.js +0 -4
  176. package/web/assets/RunLocationPicker-CEmFio4n.css +0 -1
  177. package/web/assets/RunLocationPicker-M1UoJyjf.js +0 -38
  178. package/web/assets/UnifiedPage-EJNWKzxN.js +0 -68
  179. package/web/assets/appStore-CidPWYa0.js +0 -3254
  180. package/web/assets/appStore-DeaC1U32.css +0 -1
  181. package/web/assets/automationListSource-1aOVKBLw.js +0 -1
  182. package/web/assets/codingNavigation-CCjs1kon.js +0 -53
  183. package/web/assets/codingNavigation-yp19w6uu.css +0 -1
  184. package/web/assets/dashboardSurface-BwcH16Qc.js +0 -1
  185. package/web/assets/emoji-DczIG8SO.js +0 -1
  186. package/web/assets/gestures-CXFaEydn.js +0 -1
  187. package/web/assets/i18n-DjziAw8r.css +0 -1
  188. package/web/assets/i18n.generated-BiQFRL2U.js +0 -15
  189. package/web/assets/imageStudio--KF9gwHA.css +0 -1
  190. package/web/assets/index-BqGpbntz.js +0 -1
  191. package/web/assets/linkFollow-iP2zfbA3.js +0 -8
  192. package/web/assets/main-D7CEGndC.js +0 -20
  193. package/web/assets/markdownEditorSurface-DISu_twy.js +0 -3
  194. package/web/assets/minus-BBdfT_sc.js +0 -1
  195. package/web/assets/mobileEntry-5UaAITwY.js +0 -13
  196. package/web/assets/pageChrome-BDHHmRnt.css +0 -1
  197. package/web/assets/pageChrome-DFi9zs6F.js +0 -1
  198. package/web/assets/phoneList-DrxIwJxQ.js +0 -9
  199. package/web/assets/phoneList-DvpzD3zT.css +0 -1
  200. package/web/assets/pluginChat-0QI9a8Q1.js +0 -2
  201. package/web/assets/sharePage-C2Yqx0NQ.js +0 -2
  202. package/web/assets/tableSurface-cYs6dX6B.js +0 -1
  203. package/web/assets/theme-Dgqst5S9.css +0 -1
  204. package/web/assets/userSpaces-B_Njvel_.js +0 -1
  205. package/web/assets/viewportLock-Bi3orrUs.css +0 -1
  206. package/web/assets/viewportLock-DZ927PNz.js +0 -629
  207. package/web/assets/workflow-DY2Cnaei.js +0 -1
@@ -0,0 +1,47 @@
1
+ import{d,t as Be,r as je,j as t,u as Ee,T as ks,R as gn,U as cl,W as ll,B as sa,X as ul}from"./index-BOzsniE1.js";import{J as qe,u as I,mE as dl,q as kt,mF as pl,mG as ml,mH as fl,T as br,mI as hl,iD as jr,ai as gl,mJ as vl,mK as bo,ab as yl,mL as Sr,aD as kl,aa as wl,aU as Yt,cE as Nr,bu as xl,an as Qa,fI as Cr,W as ja,aM as pt,aR as at,bw as ws,aA as Cs,lY as bl,mM as jl,mN as Sl,mO as Nl,lZ as Cl,m5 as zl,lV as El,mP as Ml,mQ as Al,mR as Rl,fX as Xt,t as xs,b as qn,af as zs,ax as jo,ae as aa,g5 as Tl,$ as Il,a0 as Ll,aC as yn,aX as fn,bX as It,b9 as zr,V as Er,mS as kn,am as Mr,mT as Ar,j9 as $l,a1 as Is,K as ia,mU as Dl,aQ as Xn,mV as _l,mW as Pl,mX as Ol,mY as Fl,mZ as Ul,m_ as So,m$ as Wl,cB as Bl,iY as ql,iU as No,cf as Hl,n0 as Vl,m3 as Ls,n1 as Kl,h as Yl,bs as Xl,e1 as Gl,ei as Sa,ez as Rr,lR as Co,ew as Jl,n2 as oa,cD as Ql,a7 as Zl,n3 as eu,n4 as tu,n5 as nu,n6 as Za,cF as su,n7 as Tr,n8 as au,n9 as iu,c8 as zo,na as ou,lm as ru,c7 as cu,aB as Es,nb as lu,a_ as uu,nc as du,hW as Gn,nd as pu,X as Ir,i4 as Eo,ch as hn,cg as mu,H as fu,ne as hu,hZ as Lt,nf as Lr,ng as gu,nh as wn,ni as Jt,bo as $r,nj as Mo,n as ra,nk as Jn,nl as xn,nm as Dr,nn as ei,lt as vu,hU as $s,x as Ms,y as _r,bp as Pr,iK as yu,iI as ku,no as wu,np as xu,hk as ti,nq as Na,nr as bu,o as ju,f as Su,b4 as Nu,g as Cu,mh as Or,ns as zu,j5 as Eu,dd as Ao,m4 as Mu,l as Au,gP as bs,hl as ca,aq as Ca,gQ as Ro,c3 as Ru,ec as Tu,nt as Iu,eC as Lu,nu as $u,i1 as Du,a9 as _u,au as Pu,fh as Fr,ej as za,nv as Gt,nw as Ou,nx as ni,ey as Fu,ny as Uu,nz as Wu,nA as us,nB as Bu,nC as qu,la as Hu,lb as Vu,nD as Ur,nE as Ku,eH as Yu,nF as Xu,nG as Gu}from"./appStore-CI1_L5OS.js";import{u as To,n as Io,b as la}from"./codeStudioStore-DhyMazGT.js";import{a as Ju,u as Lo,C as Qu,j as Zu}from"./RightPanel-BJUacrsf.js";import{c as Qn,n as ds}from"./nativeDownload-CNtwSCy0.js";import"./client-CaivGZFR.js";import{m as ed,p as si,C as td,q as nd,t as Wr,u as sd,A as ad,h as id,b as Ea,i as od,S as rd,j as cd,w as ld,v as ud,x as dd,P as ps,g as pd,k as Br,e as Ma,f as qr,s as md,l as fd}from"./phoneList-B6gwUJZF.js";import{t as Aa,c as hd,g as gd,a as vd}from"./ModelPill-JaIH3ffZ.js";import{P as Vn}from"./pencil-ehhM9_9k.js";import{c as yd,D as kd}from"./create-1JI2I47p.js";import{S as wd,W as xd}from"./approvalText-Cy2UAUAQ.js";import{M as bd}from"./message-square-plus-8pfimvem.js";import{F as bn}from"./folder-DotgUhYD.js";import{u as jd}from"./emoji-DphwSxPx.js";import{H as Sd}from"./hand-XNkzNiW2.js";import{F as ai}from"./folder-plus-aJgL9NeP.js";import{i as ii,b as Nd,d as Cd,e as zd}from"./ipc-B6hkgxQL.js";import{I as Ed,S as Hr}from"./pageChrome-BR4cfIaA.js";import{S as Md}from"./server-Ddu9f1k3.js";import{R as Ad}from"./rotate-ccw-DdkrbRAB.js";const Rd=[["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"}]],Td=qe("audio-lines",Rd);const Id=[["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M8.35 2.69A10 10 0 0 1 21.3 15.65",key:"1pfsoa"}],["path",{d:"M19.08 19.08A10 10 0 1 1 4.92 4.92",key:"1ablyi"}]],Ld=qe("circle-off",Id);const $d=[["path",{d:"M18 19a5 5 0 0 1-5-5v8",key:"sz5oeg"}],["path",{d:"M9 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v5",key:"1w6njk"}],["circle",{cx:"13",cy:"12",r:"2",key:"1j92g6"}],["circle",{cx:"20",cy:"19",r:"2",key:"1obnsp"}]],Dd=qe("folder-git-2",$d);const _d=[["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"}]],$o=qe("folder-x",_d);const Pd=[["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"}]],Od=qe("notebook-pen",Pd);const Fd=[["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"}]],js=qe("panels-top-left",Fd);const Ud=[["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"}]],Wd=qe("paw-print",Ud);const Bd=[["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"}]],qd=qe("pi",Bd);const Hd=[["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"}]],Do=qe("pin-off",Hd);const Vd=[["path",{d:"M18.36 6.64A9 9 0 0 1 20.77 15",key:"dxknvb"}],["path",{d:"M6.16 6.16a9 9 0 1 0 12.68 12.68",key:"1x7qb5"}],["path",{d:"M12 2v4",key:"3427ic"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],Kd=qe("power-off",Vd);const Yd=[["path",{d:"M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z",key:"rib7q0"}],["path",{d:"M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z",key:"1ymkrd"}]],Xd=qe("quote",Yd);const Gd=[["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"}]],Jd=qe("shield-question-mark",Gd);const Qd=[["line",{x1:"10",x2:"14",y1:"2",y2:"2",key:"14vaq8"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11",key:"17fdiu"}],["circle",{cx:"12",cy:"14",r:"8",key:"1e1u0o"}]],Zd=qe("timer",Qd);const ep=[["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"}]],Vr=qe("user-plus",ep);const tp=[["path",{d:"M2 12q2.5 2 5 0t5 0 5 0 5 0",key:"8ddzzs"}],["path",{d:"M2 19q2.5 2 5 0t5 0 5 0 5 0",key:"1wj4st"}],["path",{d:"M2 5q2.5 2 5 0t5 0 5 0 5 0",key:"69x50u"}]],np=qe("waves-horizontal",tp);const sp=[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}],["path",{d:"M5 12.859a10 10 0 0 1 5.17-2.69",key:"1dl1wf"}],["path",{d:"M19 12.859a10 10 0 0 0-2.007-1.523",key:"4k23kn"}],["path",{d:"M2 8.82a15 15 0 0 1 4.177-2.643",key:"1grhjp"}],["path",{d:"M22 8.82a15 15 0 0 0-11.288-3.764",key:"z3jwby"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],Ra=qe("wifi-off",sp);let On=null,ua=null;function ap(e){const n=I.getState().tr;return n(`channel.name.${e}`)}function ip(e){const n=e.filter(o=>o.enabled&&o.workspace).map(o=>({key:o.workspace,name:ap(o.kind),kind:"channel",channel:o.kind,path:o.workspace,system:!0})),s=I.getState().channelWorkspaces;s.length===n.length&&s.every((o,r)=>o.key===n[r].key&&o.name===n[r].name&&o.channel===n[r].channel)||I.setState({channelWorkspaces:n})}const op=Qn((e,n)=>({channels:[],available:!1,loaded:!1,refresh:async()=>{if(window.tangu?.backendStatus)try{const s=await fl(kt()),i=Array.isArray(s.channels)?s.channels:[];e({channels:i,available:!!s.available,loaded:!0}),ip(i)}catch{}},save:async(s,i)=>{await ml(kt(),s,i),await n().refresh()},connect:async s=>{const i=await pl(kt(),s);return await n().refresh(),I.getState().refreshSessions(I.getState().cfg),i},disconnect:async(s,i)=>{await dl(kt(),s,i),await n().refresh()},startPolling:()=>{if(On!=null)return;const s=()=>{I.getState().connState==="ok"&&n().refresh()};On=window.setInterval(s,15e3);let i=I.getState().connState;ua=I.subscribe(o=>{o.connState==="ok"&&i!=="ok"&&n().refresh(),i=o.connState}),s()},stopPolling:()=>{On!=null&&(window.clearInterval(On),On=null),ua?.(),ua=null}}));je({"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.silentPhone":{zh:"没录到声音,再试一次",en:"No sound was recorded — try again"},"voiceinput.deniedPhone":{zh:"麦克风权限被拒绝(到系统设置 › 应用 › 权限里允许麦克风)",en:"Microphone access was denied (allow it in system Settings › Apps › Permissions)"},"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 rp(e){const n=await e.arrayBuffer(),s=new AudioContext,i=await s.decodeAudioData(n);await s.close();const o=Math.max(1,Math.round(i.duration*16e3)),r=new OfflineAudioContext(1,o,16e3),c=r.createBufferSource();c.buffer=i,c.connect(r.destination),c.start();const u=(await r.startRendering()).getChannelData(0);let l=0,p=0;for(let f=0;f<u.length;f++){const v=Math.abs(u[f]);v>l&&(l=v),p+=u[f]*u[f]}if(console.warn(`[voice] captured ${u.length} samples @16k, ${(u.length/16e3).toFixed(2)}s, peak=${l.toFixed(4)} rms=${Math.sqrt(p/(u.length||1)).toFixed(4)}`),l<.005)throw new Error(window.tangu?.mobile?Be("voiceinput.silentPhone"):Be("voiceinput.silent"));return cp(u,16e3)}function cp(e,n){const s=e.length,i=new ArrayBuffer(44+s*2),o=new DataView(i),r=(p,f)=>{for(let v=0;v<f.length;v++)o.setUint8(p+v,f.charCodeAt(v))};r(0,"RIFF"),o.setUint32(4,36+s*2,!0),r(8,"WAVE"),r(12,"fmt "),o.setUint32(16,16,!0),o.setUint16(20,1,!0),o.setUint16(22,1,!0),o.setUint32(24,n,!0),o.setUint32(28,n*2,!0),o.setUint16(32,2,!0),o.setUint16(34,16,!0),r(36,"data"),o.setUint32(40,s*2,!0);for(let p=0;p<s;p++){const f=Math.max(-1,Math.min(1,e[p]));o.setInt16(44+p*2,f<0?f*32768:f*32767,!0)}const c=new Uint8Array(i);let u="";const l=32768;for(let p=0;p<c.length;p+=l)u+=String.fromCharCode(...c.subarray(p,p+l));return btoa(u)}function lp(e,n){const[s,i]=d.useState(!1),[o,r]=d.useState(!1),[c,u]=d.useState(null),l=d.useRef(null),p=d.useRef([]),f=d.useRef(!1),[v,w]=d.useState(null),E=d.useRef(null),A=d.useCallback(()=>{w(null),E.current?.close().catch(()=>{}),E.current=null},[]);d.useEffect(()=>A,[A]);const z=typeof navigator<"u"&&!!navigator.mediaDevices?.getUserMedia&&typeof MediaRecorder<"u"&&!!window.tangu?.transcribeAudio,b=d.useCallback(U=>{f.current=U,l.current?.stop()},[]),$=d.useCallback(async()=>{if(u(null),!z){u(Be("voiceinput.unsupported"));return}let U;try{U=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(R){console.warn("[voice] getUserMedia failed:",R?.name,R?.message||R),u(R?.name==="NotAllowedError"?window.tangu?.mobile?Be("voiceinput.deniedPhone"):Be("voiceinput.denied"):R?.name==="NotFoundError"?Be("voiceinput.noDevice"):Be("voiceinput.openFailed",{e:R?.name||R?.message||R}));return}try{const R=new AudioContext,x=R.createAnalyser();x.fftSize=128,x.smoothingTimeConstant=.7,R.createMediaStreamSource(U).connect(x),E.current=R,w(x)}catch{}const K=new MediaRecorder(U);l.current=K,p.current=[],f.current=!1,K.ondataavailable=R=>{R.data.size&&p.current.push(R.data)},K.onstop=async()=>{if(U.getTracks().forEach(x=>x.stop()),A(),i(!1),l.current=null,f.current||!p.current.length)return;const R=new Blob(p.current,{type:K.mimeType||"audio/webm"});r(!0);try{const x=await window.tangu.transcribeAudio({audioBase64:await rp(R),mime:"audio/wav",modelId:n});x?e(x):u(Be("voiceinput.unclear"))}catch(x){console.warn("[voice] transcribe failed:",x?.message||x),u(x?.message||String(x))}finally{r(!1)}},K.start(),i(!0)},[z,n,e,A]),D=d.useCallback(()=>{o||(s?b(!1):$())},[o,s,$,b]),L=d.useCallback(()=>{s&&b(!0)},[s,b]);return{recording:s,busy:o,error:c,toggle:D,cancel:L,supported:z,analyser:v}}const up=({size:e})=>t.jsx("svg",{width:e,height:e,viewBox:"0 0 14 14",fill:"currentColor","aria-hidden":"true",children:t.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"})}),dp=({size:e})=>t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:t.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"})}),_o=({engineId:e,size:n=16})=>{const s=e.toLowerCase();return s.includes("claude")?t.jsx(dp,{size:n}):s.includes("codex")||s.includes("openai")?t.jsx(up,{size:n}):s.includes("claw")?t.jsx(Wd,{size:n}):s==="pi"||s.startsWith("pi-")?t.jsx(qd,{size:n}):s.includes("dsh")||s.includes("deepseek")?t.jsx(np,{size:n}):t.jsx(br,{size:n})},pp=e=>/(^|\/)qwen-audio-/i.test(e);function mp(e,n){return n&&e===n.id?n.apiModelId||n.id:e}const fp=(e,n)=>pp(mp(e,n)),hp=(e,n)=>fp(e,n)?"longanqian":"Tina";function gp(e,n){const s=e.realtimeModelId?.trim()||"";return s||!e.realtimeModelUnset?s:n.signedIn&&n.model?.id?n.model.id:""}function vp(e,n){const s=gp(e,n),i=e.realtimeVoice?.trim()||"";return{model:s,voice:i||(s&&n.model&&s===n.model.id?hp(s,n.model):"")}}const Ta="forsion_voice_call_voice",yp=50,kp=1e3,wp=300,xp=2500;function Po(e){try{e?localStorage.setItem(Ta,JSON.stringify({...e,t:Date.now()})):localStorage.removeItem(Ta)}catch{}}let mt=null,Kr=0,Oo,Fo=!1;const Ia=new Set;function Yr(e){clearTimeout(Oo);let n=null;try{n=e?JSON.parse(e):null}catch{n=null}const s=mt;if(n&&typeof n.sessionId=="string"&&typeof n.phase=="string"){const i=s?.sessionId===n.sessionId&&s.phase===n.phase;mt={sessionId:n.sessionId,phase:n.phase,level:Math.min(1,Math.max(0,Number(n.level)||0)),since:i?s.since:Date.now()},Kr=Date.now(),Oo=setTimeout(()=>Yr(null),xp)}else mt=null;(s?.sessionId!==mt?.sessionId||s?.phase!==mt?.phase)&&Ia.forEach(i=>i())}function Xr(){Fo||typeof window>"u"||typeof window.addEventListener!="function"||(Fo=!0,window.addEventListener("storage",e=>{(e.key===Ta||e.key===null)&&Yr(e.key?e.newValue:null)}))}function zh(){return Xr(),mt&&mt.level>0&&Date.now()-Kr>wp&&(mt={...mt,level:0}),mt}function Eh(e){return Xr(),Ia.add(e),()=>{Ia.delete(e)}}const bp="forsion_realtime_cfg_rev";let Hn={realtimeModelId:"",realtimeModelUnset:!1,realtimeVoice:""},Uo=!1;const La=new Set;function da(){window.tangu?.getConfig?.().then(e=>{const n={realtimeModelId:e.realtimeModelId?.trim()||"",realtimeModelUnset:!!e.realtimeModelUnset,realtimeVoice:e.realtimeVoice?.trim()||""};n.realtimeModelId===Hn.realtimeModelId&&n.realtimeModelUnset===Hn.realtimeModelUnset&&n.realtimeVoice===Hn.realtimeVoice||(Hn=n,La.forEach(s=>s()))}).catch(()=>{})}function jp(){return d.useSyncExternalStore(e=>(Uo||(Uo=!0,da(),window.addEventListener("storage",n=>{n.key===bp&&da()}),window.addEventListener("focus",da)),La.add(e),()=>{La.delete(e)}),()=>Hn)}const Gr="forsion_voice_call_evt",$a=new Set;function Sp(e){try{localStorage.setItem(Gr,JSON.stringify({...e,n:`${Date.now()}-${Math.random()}`}))}catch{}$a.forEach(n=>{try{n(e)}catch{}})}let Jr=null,Wo=0;const Da=new Set;function Np(e){e&&!Te&&Wo++,Jr=e?{...e,dial:Wo}:null,Da.forEach(n=>n())}const Mh=()=>Jr;function Ah(e){return Da.add(e),()=>{Da.delete(e)}}const As="forsion_voice_call_active",Ss=new Set;let Bo=!1;function Cp(e){try{e?localStorage.setItem(As,e):localStorage.removeItem(As)}catch{}Ss.forEach(n=>n())}function Qr(){try{return localStorage.getItem(As)}catch{return null}}function zp(e){return Bo||(Bo=!0,window.addEventListener("storage",n=>{(n.key===As||n.key===null)&&Ss.forEach(s=>s())})),Ss.add(e),()=>{Ss.delete(e)}}const Ep=4e3,Rh=1500;function Mp(e,n,s=2e3){const i=`${Date.now()}-${Math.random()}`;return new Promise(o=>{const r=Zr(u=>{u.kind==="text-ack"&&u.id===i&&(r(),clearTimeout(c),o(!0))}),c=setTimeout(()=>{r(),Qr()===e&&Cp(null),o(!1)},s);Sp({kind:"text",sessionId:e,text:n,id:i,at:Date.now()})})}function Zr(e){const n=s=>{if(!(s.key!==Gr||!s.newValue))try{e(JSON.parse(s.newValue))}catch{}};return window.addEventListener("storage",n),$a.add(e),()=>{window.removeEventListener("storage",n),$a.delete(e)}}const Ap=.04,Rp="backgrounded",qo=24e3;let Te=null,_a=null;const Pa=new Set;let Ns=null,jn=null;const Oa=()=>Pa.forEach(e=>e()),ec=e=>{Te&&(Te={...Te,...e},Oa())};function Th(e){return Pa.add(e),()=>{Pa.delete(e)}}const Ih=()=>Te,Lh=()=>_a;function Tp(e){Ns?.(e)}function $h(){Te&&ec({muted:!Te.muted})}const Dh=e=>jn?.mic(e)??Promise.resolve(),_h=e=>jn?.speaker(e)??Promise.resolve(),Ph=e=>jn?.run(e),Oh=e=>jn?.text(e)??!1;async function Fh(e){Te&&Tp(),_a=null,Te={sessionId:e.sessionId,phase:"connecting",muted:!1,working:null,analyser:null,connectedAt:null},Oa();let n=null,s=null;const i=new AudioContext({sampleRate:16e3}),o=new AudioContext({sampleRate:qo}),r=i.createAnalyser(),c=o.createAnalyser();c.connect(o.destination);const u=new Set;let l=0,p=!1,f=null,v=null;const w=C=>({echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1,...C?{deviceId:C}:{}}),E=()=>{f=i.createMediaStreamSource(n),f.connect(r),v&&f.connect(v)},A=C=>(o.setSinkId?.(C)??Promise.resolve()).catch(_=>console.warn("[realtime] setSinkId failed:",_)),z=C=>{p||ec(C)},b=(C=500)=>{e.onActivity&&window.setTimeout(e.onActivity,C)},$=()=>{u.forEach(C=>{try{C.stop()}catch{}}),u.clear(),l=0},D=C=>{const _=new Int16Array(C,0,C.byteLength>>1);if(!_.length)return;const q=o.createBuffer(1,_.length,qo),Z=q.getChannelData(0);for(let g=0;g<_.length;g++)Z[g]=_[g]/32768;const oe=o.createBufferSource();oe.buffer=q,oe.connect(c);const re=Math.max(o.currentTime+.05,l);oe.start(re),l=re+q.duration,u.add(oe),oe.onended=()=>{u.delete(oe),!u.size&&Te?.phase==="speaking"&&z({phase:"listening",analyser:r})},Te?.phase!=="speaking"&&z({phase:"speaking",analyser:c})},L=new Uint8Array(c.fftSize);let U="",K=0;const R=window.setInterval(()=>{if(p||!Te)return;const C=u.size>0,_=C?"speaking":Te.phase,q=Date.now();if(!C&&_===U&&q-K<kp)return;let Z=0;if(C){c.getByteTimeDomainData(L);const oe=L.length>>1;let re=0;for(let g=oe;g<L.length;g++){const P=(L[g]-128)/128;re+=P*P}Z=Math.min(1,Math.sqrt(re/(L.length-oe))*4)}U=_,K=q,Po({sessionId:e.sessionId,phase:_,level:Z})},yp),x=()=>Po(null);window.addEventListener("pagehide",x);const O=!!window.tangu?.mobile,J=()=>{document.hidden&&Q(Rp)};let ee=null;O&&(document.addEventListener("visibilitychange",J),navigator.wakeLock?.request("screen").then(C=>{p?C.release().catch(()=>{}):ee=C}).catch(()=>{}));const Q=C=>{if(p)return;p=!0;const _=Ns===Q;_&&(Ns=null),window.clearInterval(R),window.removeEventListener("pagehide",x),document.removeEventListener("visibilitychange",J),ee?.release().catch(()=>{}),_&&x(),$();try{s?.close()}catch{}n?.getTracks().forEach(q=>q.stop()),i.close().catch(()=>{}),o.close().catch(()=>{}),_&&(jn=null,_a=C||null,Te=null,Oa()),b(300)};Ns=Q,jn={mic:async C=>{const _=await navigator.mediaDevices.getUserMedia({audio:w(C)});if(p){_.getTracks().forEach(q=>q.stop());return}f?.disconnect(),n?.getTracks().forEach(q=>q.stop()),n=_,f&&E()},speaker:A,run:C=>{e.run=C,s?.readyState===WebSocket.OPEN&&s.send(JSON.stringify({type:"run",run:C}))},text:C=>p||!Te?.connectedAt||Te.phase==="reconnecting"||s?.readyState!==WebSocket.OPEN?!1:($(),z({phase:"thinking",analyser:r}),s.send(JSON.stringify({type:"text",text:C})),b(),!0)};try{if(n=await navigator.mediaDevices.getUserMedia({audio:w(e.micId)}),p){n.getTracks().forEach(_=>_.stop());return}e.speakerId&&await A(e.speakerId);const C=await hl(e.target);if(p)return;s=C.protocols?new WebSocket(C.url,C.protocols):new WebSocket(C.url),s.binaryType="arraybuffer"}catch(C){Q(C?.message||String(C));return}const H=s;H.onopen=()=>H.send(JSON.stringify({type:"start",session_id:e.sessionId,model:e.model,voice:e.voice||void 0,title:e.title,run:{...e.run,app_id:jr}})),H.onclose=C=>Q(C.reason||(C.code===1e3?void 0:`connection closed (${C.code})`)),H.onmessage=C=>{if(p)return;if(C.data instanceof ArrayBuffer){D(C.data);return}let _;try{_=JSON.parse(String(C.data))}catch{return}switch(_.type){case"ready":{if(v){z(u.size?{phase:"speaking",analyser:c}:{phase:"listening",analyser:r});break}v=i.createScriptProcessor(1024,1,1),v.connect(i.destination),v.onaudioprocess=q=>{if(p||!Te||Te.muted||H.readyState!==WebSocket.OPEN)return;const Z=q.inputBuffer.getChannelData(0);let oe=0;for(let P=0;P<Z.length;P++)oe+=Z[P]*Z[P];const re=u.size>0&&Math.sqrt(oe/Z.length)<Ap,g=new Int16Array(Z.length);if(!re)for(let P=0;P<Z.length;P++)g[P]=Math.max(-32768,Math.min(32767,Math.round(Z[P]*32767)));H.send(g.buffer)},E(),z({phase:"listening",analyser:r,connectedAt:Date.now()});break}case"input_audio_buffer.speech_started":$(),z({phase:"hearing",analyser:r});break;case"input_audio_buffer.speech_stopped":z({phase:"thinking"});break;case"conversation.item.input_audio_transcription.completed":case"response.audio_transcript.done":b();break;case"response.done":!u.size&&Te?.phase==="thinking"&&_.response?.status!=="completed"&&z({phase:"listening",analyser:r});break;case"transcript.corrected":typeof _.message_id=="string"&&typeof _.text=="string"&&e.onTranscriptFix?.(_.message_id,_.text);break;case"tangu.run":z({working:_.status==="started"?String(_.task||""):null}),b(_.status==="started"?300:800);break;case"error":console.warn("[realtime] upstream error:",_.error?.message||_.error);break;case"reconnecting":_.replay&&$(),z({phase:"reconnecting"});break;case"end":Q(_.reason&&_.reason!=="client closed"?String(_.reason):void 0);break}}}const Fa=e=>Array.from((e||"").trim());function Ip(e,n){const s=e.map(c=>c.toLowerCase()),i=s.join("");let o=0;for(const c of n){if(!c.length||c.join("")===i||c[0]!==s[0])continue;let u=0;for(;u<s.length&&u<c.length&&s[u]===c[u];)u++;o=Math.max(o,u)}const r=[];for(let c=o;o&&c<e.length;c++)e[c].trim()&&r.push(e[c]);return{first:e[0],picks:r,collides:o>0}}function Lp(e){const n=e.map(u=>Fa(u)),s=n.map(u=>u.map(l=>l.toLowerCase())),i=n.map(()=>"?"),o=new Set,r=[];n.forEach((u,l)=>{if(!u.length)return;const{first:p,picks:f,collides:v}=Ip(u,s);if(!v||!f.length){i[l]=p.toUpperCase(),o.add(p.toLowerCase());return}r.push({index:l,key:s[l].join(""),picks:f,first:p})}),r.sort((u,l)=>u.key<l.key?-1:u.key>l.key?1:u.index-l.index);const c=new Map;for(const u of r){const l=c.get(u.key);if(l){i[u.index]=l;continue}const f=(u.picks.find(v=>!o.has(v.toLowerCase()))??u.first).toUpperCase();o.add(f.toLowerCase()),c.set(u.key,f),i[u.index]=f}return i}function $p(e,n=[]){const s=Fa(e);if(!s.length)return"?";const i=s.join("").toLowerCase();let o=n.findIndex(c=>Fa(c).join("").toLowerCase()===i);const r=o>=0?n:[e,...n];return o<0&&(o=0),Lp(r)[o]}const Ho=(...e)=>e.filter(Boolean).join(" ")||void 0;function Dp({name:e,url:n,siblings:s,className:i,imgClassName:o,initialClassName:r,size:c,fill:u,title:l,style:p,...f}){return n?t.jsx("img",{...f,className:Ho(i,o),src:n,alt:"",title:l,draggable:!1,width:c,height:c,style:p}):t.jsx("span",{...f,className:Ho("agent-avatar-initial",u&&"agent-avatar-fill",i,r),title:l,"aria-hidden":"true",style:p,children:t.jsx("span",{className:"agent-avatar-glyph",children:$p(e,s)})})}je({"cmd.refFrontWindow":{zh:"引用刚才在用的窗口",en:"Reference the window you were just using"}});const Ua="forsion:appref-add",Wa="data-appref-target";async function pa(e,n=!1){const s=document.activeElement,i=e??await window.tangu?.appRefs?.frontmost().catch(()=>null);if(!i)return;if(s?.isContentEditable&&s.closest(".am-app")){s.focus(),document.execCommand("insertText",!1,Sr(i)+" ");return}const o=i.kind==="window"?window.tangu?.appRefs?.snapshot?.(i).catch(()=>null):void 0;(tc().find(c=>c.contains(s))??await Pp(n))?.dispatchEvent(new CustomEvent(Ua,{detail:{ref:i,image:o}}))}const tc=()=>[...document.querySelectorAll(`[${Wa}]`)],_p=()=>tc().find(e=>e.getClientRects().length>0);let Vo=null;const Pp=e=>Vo??=Op(e).finally(()=>{Vo=null});async function Op(e){const n=wl.getState().run;let s=!1;for(let i=0;i<40;i++){const o=_p();if(o)return o;const r=i%10===(e?9:0);r&&n("new-chat"),r&&!s&&i>=(e?19:10)&&(s=!0,n("show-chat-panel")),await new Promise(c=>setTimeout(c,100))}}let Ko=!1;function Fp(){if(Ko||!window.tangu?.appRefs)return;Ko=!0;const e={id:"chat.reference-front-window",title:()=>Be("cmd.refFrontWindow"),hotkey:vl,run:()=>{pa()}};gl(e);const n=window.tangu.appRefs;n.onHotkey?.(o=>{const r=bo(o);r&&pa(r)}),n.takePendingHotkey?.().then(o=>{const r=bo(o);r&&pa(r,!0)},()=>{});let s=null;const i=()=>{const o=kl(e);o!==s&&(s=o,n.setGlobalHotkey?.(o))};i(),yl.subscribe(i)}const Yo=Qn((e,n)=>({pending:[],queue:(s,i)=>e(o=>({pending:[...o.pending,{sessionId:s,text:i}]})),take:s=>{const i=n().pending.filter(o=>o.sessionId===s);return i.length&&e(o=>({pending:o.pending.filter(r=>r.sessionId!==s)})),i.map(o=>o.text)}})),Xo=40,Go=.1,Up=3.2;function Wp({analyser:e,recording:n,busy:s,onStop:i,onSend:o,status:r,stopTitle:c,t:u}){const l=d.useRef(null),[p,f]=d.useState(0),v=d.useRef(0);d.useEffect(()=>{if(!n)return;v.current=Date.now(),f(0);const E=window.setInterval(()=>f(Math.floor((Date.now()-v.current)/1e3)),250);return()=>window.clearInterval(E)},[n]),d.useEffect(()=>{const E=l.current;if(!e||!n||!E)return;const A=E.getContext("2d");if(!A)return;const z=window.devicePixelRatio||1;E.width=Math.max(1,E.clientWidth)*z,E.height=Math.max(1,E.clientHeight)*z,A.setTransform(z,0,0,z,0,0);const b=getComputedStyle(document.documentElement),$=(b.getPropertyValue("--accent-ink")||b.getPropertyValue("--accent")||"#7c3aed").trim(),D=(b.getPropertyValue("--border")||"rgba(127,127,127,0.4)").trim(),L=new Uint8Array(e.fftSize),U=[];let K=Date.now(),R=0;const x=()=>{R=requestAnimationFrame(x);const O=Date.now();e.getByteTimeDomainData(L);let J=0;for(let _=0;_<L.length;_++){const q=(L[_]-128)/128;J+=q*q}const ee=Math.min(1,Math.sqrt(J/L.length)*Up);for(;O-K>=Xo;)U.push({t:K,level:ee}),K+=Xo;const Q=E.clientWidth,H=E.clientHeight,C=H/2;for(A.clearRect(0,0,Q,H),A.strokeStyle=D,A.lineWidth=1,A.setLineDash([2,3]),A.beginPath(),A.moveTo(0,C),A.lineTo(Q,C),A.stroke(),A.setLineDash([]);U.length&&Q-(O-U[0].t)*Go<-4;)U.shift();A.fillStyle=$;for(const _ of U){const q=Q-(O-_.t)*Go;if(q<-4||q>Q)continue;const Z=Math.max(2,_.level*(H-4));A.globalAlpha=q<Q*.15?Math.max(0,q/(Q*.15)):1,A.beginPath(),A.roundRect(q-1.1,C-Z/2,2.2,Z,1.1),A.fill()}A.globalAlpha=1};return x(),()=>cancelAnimationFrame(R)},[e,n]);const w=`${Math.floor(p/60)}:${String(p%60).padStart(2,"0")}`;return s?t.jsxs("div",{className:"t2c-voicebar",children:[t.jsx(Yt,{size:14,className:"spin"}),t.jsx("span",{className:"t2c-voicelabel",children:u("input.micBusy")}),t.jsx("span",{className:"t2c-grow"})]}):t.jsxs("div",{className:"t2c-voicebar",children:[t.jsx("canvas",{ref:l,className:"t2c-voicewave"}),t.jsx("span",{className:"t2c-voicetime",children:r??w}),t.jsx("button",{className:"t2c-voicestop",title:c??u("input.micStop"),onClick:i,children:t.jsx(Nr,{size:12})}),o&&t.jsx("button",{className:"t2c-send",title:u("input.send"),onClick:o,children:t.jsx(xl,{size:16})})]})}je({"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 nc="forsion_ultra_confirm_off";function Bp(){try{return localStorage.getItem(nc)==="1"}catch{return!1}}function qp({offerFullAccess:e,onConfirm:n,onClose:s}){const{t:i}=Ee(),[o,r]=d.useState(!1),[c,u]=d.useState(!1),l=d.useRef(typeof document<"u"?document.activeElement:null);d.useEffect(()=>()=>{const f=l.current;f?.isConnected&&typeof f.focus=="function"&&f.focus({preventScroll:!0})},[]);const p=f=>{if(f.key!=="Tab")return;const v=f.currentTarget.querySelector(".dialog"),w=v?[...v.querySelectorAll('button, input, [tabindex]:not([tabindex="-1"])')].filter(z=>!z.disabled):[];if(!w.length)return;const E=w[0],A=w[w.length-1];f.shiftKey&&document.activeElement===E?(f.preventDefault(),A.focus()):!f.shiftKey&&document.activeElement===A&&(f.preventDefault(),E.focus())};return Qa.createPortal(t.jsx("div",{className:"am-app tangu-lovable",style:{display:"contents"},"data-ultra-confirm":!0,"data-keep-menus":!0,onKeyDown:p,children:t.jsxs(Cr,{title:i("ultraConfirm.title"),message:i("ultraConfirm.msg"),confirmLabel:i("ultraConfirm.confirm"),danger:!1,onConfirm:()=>{if(c)try{localStorage.setItem(nc,"1")}catch{}n({fullAccess:e&&o})},onClose:s,children:[e&&t.jsx("div",{className:"dialog-msg",children:i("ultraConfirm.recommend")}),e&&t.jsxs("label",{className:"dialog-check","data-ultra-full-access":!0,children:[t.jsx("input",{type:"checkbox",checked:o,onChange:f=>r(f.target.checked)}),t.jsx("span",{children:i("ultraConfirm.fullAccess")})]}),t.jsxs("label",{className:"dialog-check","data-ultra-skip":!0,children:[t.jsx("input",{type:"checkbox",checked:c,onChange:f=>u(f.target.checked)}),t.jsx("span",{children:i("ultraConfirm.skip")})]})]})}),document.body)}je({"session.untitled":{zh:"新会话",en:"New session"},"session.rootlessGroup":{zh:"无项目会话",en:"No project"}});const Hp="New Chat";function yt(e,n){const s=(e||"").trim();return!s||s===Hp?n("session.untitled"):e}function Fn(e,n){return e.kind==="rootless"?n("session.rootlessGroup"):e.name}je({"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 Vp=()=>({name:"",description:"",model:"",systemPrompt:"",thinkingLevel:"",maxIterations:"",approvalMode:""}),Kp=()=>`temp-${Date.now().toString(36)}-${Math.floor(Math.random()*46656).toString(36)}`,Yp=({agents:e,models:n,initialAgents:s,initialTempAgents:i,active:o,hideDisable:r,onConfirm:c,onDisable:u,onClose:l})=>{const{t:p}=Ee(),f=d.useMemo(()=>new Set(e.map(x=>x.slug)),[e]),[v,w]=d.useState(()=>s.filter(x=>f.has(x))),[E,A]=d.useState(i||[]),[z,b]=d.useState(null),$=d.useMemo(()=>(n||[]).map(x=>({id:x.id,label:x.name||x.id})),[n]),L=v.length+E.length>=2,U=x=>w(O=>O.includes(x)?O.filter(J=>J!==x):[...O,x]),K=()=>{if(!z||!z.name.trim()||!z.systemPrompt.trim())return;const x=z.slug||Kp(),O={slug:x,name:z.name.trim(),description:z.description.trim(),model:z.model,tools:[],thinkingLevel:z.thinkingLevel,maxIterations:z.maxIterations?Number(z.maxIterations):null,approvalMode:z.approvalMode,createdBy:"user",createdAt:"",systemPrompt:z.systemPrompt.trim()};A(J=>{const ee=J.findIndex(Q=>Q.slug===x);if(ee>=0){const Q=J.slice();return Q[ee]=O,Q}return[...J,O]}),b(null)},R=()=>{L&&c({groupAgents:[...v,...E.map(x=>x.slug)],groupTempAgents:E})};return t.jsx("div",{onClick:l,style:{position:"fixed",inset:0,background:"var(--overlay-scrim)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:t.jsxs("div",{"data-team-setup":!0,onClick:x=>x.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:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:6},children:[t.jsx(ja,{size:18}),t.jsx("strong",{style:{fontSize:"var(--ui-font-heading, 14px)",flex:1},children:p("group.setup.title")}),t.jsx("button",{className:"icon-btn",onClick:l,title:p("group.setup.close"),children:t.jsx(pt,{size:16})})]}),z?t.jsxs("div",{className:"field",children:[t.jsx("div",{className:"hint",style:{marginBottom:8},children:p("group.setup.tempFormHint")}),t.jsxs("div",{className:"field",children:[t.jsx("label",{children:p("settings.agents.name")}),t.jsx("input",{type:"text",value:z.name,placeholder:p("settings.agents.namePlaceholder"),onChange:x=>b({...z,name:x.target.value})})]}),t.jsxs("div",{className:"field",children:[t.jsx("label",{children:p("settings.agents.desc")}),t.jsx("input",{type:"text",value:z.description,onChange:x=>b({...z,description:x.target.value})})]}),t.jsxs("div",{className:"field",children:[t.jsx("label",{children:p("settings.agents.model")}),t.jsxs("select",{value:z.model,onChange:x=>b({...z,model:x.target.value}),children:[t.jsx("option",{value:"",children:p("settings.agents.modelDefault")}),$.map(x=>t.jsx("option",{value:x.id,children:x.label},x.id))]})]}),t.jsxs("div",{className:"field",children:[t.jsx("label",{children:p("settings.agents.systemPrompt")}),t.jsx("textarea",{rows:6,value:z.systemPrompt,placeholder:p("settings.agents.systemPromptPlaceholder"),onChange:x=>b({...z,systemPrompt:x.target.value})})]}),t.jsxs("div",{className:"field-row",children:[t.jsxs("div",{className:"field",children:[t.jsx("label",{children:p("settings.agents.thinking")}),t.jsxs("select",{value:z.thinkingLevel,onChange:x=>b({...z,thinkingLevel:x.target.value}),children:[t.jsx("option",{value:"",children:p("settings.agents.inherit")}),ks.map(x=>t.jsx("option",{value:x,children:Aa(x,p)},x))]})]}),t.jsxs("div",{className:"field",children:[t.jsx("label",{children:p("settings.agents.maxIter")}),t.jsx("input",{type:"number",min:10,max:200,value:z.maxIterations,onChange:x=>b({...z,maxIterations:x.target.value})})]}),t.jsxs("div",{className:"field",children:[t.jsx("label",{children:p("settings.agents.approval")}),t.jsxs("select",{value:z.approvalMode,onChange:x=>b({...z,approvalMode:x.target.value}),children:[t.jsx("option",{value:"",children:p("settings.agents.inherit")}),t.jsx("option",{value:"readonly",children:"readonly"}),t.jsx("option",{value:"auto-edit",children:"auto-edit"}),t.jsx("option",{value:"full-auto",children:"full-auto"}),t.jsx("option",{value:"custom",children:"custom"})]})]})]}),t.jsxs("div",{style:{display:"flex",gap:8},children:[t.jsxs("button",{className:"btn primary sm",disabled:!z.name.trim()||!z.systemPrompt.trim(),onClick:K,children:[t.jsx(at,{size:13})," ",p("group.setup.tempSave")]}),t.jsx("button",{className:"btn ghost sm",onClick:()=>b(null),children:p("group.setup.close")})]})]}):t.jsxs(t.Fragment,{children:[e.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{fontSize:"var(--ui-font-meta, 12px)",fontWeight:600,margin:"8px 0 6px",color:"var(--text-dim)"},children:p("group.setup.savedAgents")}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4,marginBottom:12},children:e.map(x=>{const O=v.includes(x.slug);return t.jsxs("button",{onClick:()=>U(x.slug),style:{display:"flex",alignItems:"center",gap:10,textAlign:"left",padding:"8px 10px",borderRadius:"var(--radius-sm, 6px)",border:`1px solid ${O?"var(--accent-ink)":"var(--border)"}`,background:O?"var(--accent-soft)":"transparent",color:"inherit",cursor:"pointer"},children:[t.jsx("span",{style:{width:16,height:16,borderRadius:4,flexShrink:0,display:"inline-flex",alignItems:"center",justifyContent:"center",border:`1px solid ${O?"var(--accent-ink)":"var(--border)"}`,background:O?"var(--accent-ink)":"transparent"},children:O&&t.jsx(at,{size:12,color:"var(--on-accent-ink, var(--on-accent))"})}),t.jsxs("span",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{fontSize:"var(--ui-font-body, 13px)",fontWeight:600},children:x.name}),x.description&&t.jsx("div",{style:{fontSize:"var(--ui-font-caption, 11px)",color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:x.description})]})]},x.slug)})})]}),t.jsx("div",{style:{fontSize:"var(--ui-font-meta, 12px)",fontWeight:600,margin:"8px 0 6px",color:"var(--text-dim)"},children:p("group.setup.tempAgents")}),E.length>0&&t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4,marginBottom:8},children:E.map(x=>t.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:[t.jsx(Vr,{size:14,style:{flexShrink:0,opacity:.8}}),t.jsxs("span",{style:{flex:1,minWidth:0},children:[t.jsx("span",{style:{fontSize:"var(--ui-font-body, 13px)",fontWeight:600},children:x.name}),t.jsx("span",{style:{fontSize:"var(--ui-font-caption, 11px)",color:"var(--text-dim)",marginLeft:6},children:p("group.setup.tempBadge")})]}),t.jsx("button",{className:"icon-btn",title:p("common.edit"),onClick:()=>b({slug:x.slug,name:x.name,description:x.description,model:x.model,systemPrompt:x.systemPrompt,thinkingLevel:x.thinkingLevel,maxIterations:x.maxIterations!=null?String(x.maxIterations):"",approvalMode:x.approvalMode}),children:t.jsx(Vn,{size:13})}),t.jsx("button",{className:"icon-btn",title:p("common.delete"),onClick:()=>A(O=>O.filter(J=>J.slug!==x.slug)),children:t.jsx(ws,{size:13})})]},x.slug))}),t.jsxs("button",{className:"btn ghost sm",style:{marginBottom:14},onClick:()=>b(Vp()),children:[t.jsx(Cs,{size:13})," ",p("group.setup.addTemp")]}),t.jsx("div",{style:{fontSize:"var(--ui-font-meta, 12px)",color:"var(--text-dim)",margin:"6px 0 14px"},children:p("group.setup.selfPacedHint")}),t.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[o&&!r&&t.jsx("button",{className:"btn sm",onClick:()=>{u(),l()},children:p("group.setup.disable")}),t.jsx("button",{className:"btn primary sm",onClick:R,disabled:!L,children:p(o?"group.setup.update":"group.setup.start")})]}),!L&&t.jsx("div",{style:{fontSize:"var(--ui-font-caption, 11px)",color:"var(--danger)",textAlign:"right",marginTop:6},children:p("group.setup.needTwo")})]})]})})},ms=2e5,ma=(e,n,s)=>yd(e,e,n,s,void 0,void 0,{context:3});function Xp(e){if(!/^\*\*\* (Begin Patch|(Add|Update|Delete) File:)/m.test(e))return null;const n=e.replace(/\r\n/g,`
2
+ `).split(`
3
+ `),s=/^\*\*\* (Add|Update|Delete) File: (.+)$/,i=c=>s.test(c)||/^\*\*\* (Begin|End) Patch$/.test(c.trim()),o=[];let r=0;for(;r<n.length;){const c=s.exec(n[r]);if(!c){r++;continue}const u=c[1],l=c[2].trim();r++;let p="";const f=u==="Update"?/^\*\*\* Move to: (.+)$/.exec(n[r]??""):null;f&&(p=f[1].trim(),r++);const v=[];for(;r<n.length&&!i(n[r]);)v.push(n[r]),r++;if(u==="Delete"){o.push(`--- ${l}`,"+++ /dev/null","@@ -1,1 +0,0 @@","-(deleted)");continue}if(u==="Add"){const b=v.filter($=>$.startsWith("+")).map($=>$.slice(1));if(!b.length)continue;o.push("--- /dev/null",`+++ ${l}`,`@@ -0,0 +1,${b.length} @@`,...b.map($=>"+"+$));continue}const w=[`--- ${l}`,`+++ ${p||l}`];let E=[],A="";const z=()=>{if(!E.length)return;const b=E.filter(D=>D[0]!=="+").length,$=E.filter(D=>D[0]!=="-").length;w.push(`@@ -1,${b} +1,${$} @@${A?" "+A:""}`,...E),E=[]};for(const b of v){const $=/^@@ ?(.*)$/.exec(b);if($){z(),A=$[1]||"";continue}b.startsWith("+")||b.startsWith("-")||b.startsWith(" ")?E.push(b):E.push(" "+b)}z(),w.length>2&&o.push(...w)}return o.length?o.join(`
4
+ `)+`
5
+ `:null}function Gp(e,n){if(!n)return null;let s;try{s=JSON.parse(n)}catch{return null}if(!s||typeof s!="object")return null;const i=typeof s.path=="string"&&s.path?s.path:"file";try{switch(e){case"edit_file":{const o=String(s.old_string??""),r=String(s.new_string??"");return!o&&!r||o.length+r.length>ms?null:ma(i,o,r)}case"multi_edit":{if(!Array.isArray(s.edits)||!s.edits.length)return null;let o=0;const r=[];for(let c=0;c<s.edits.length;c++){const u=s.edits[c],l=String(u?.old_string??""),p=String(u?.new_string??"");if(o+=l.length+p.length,o>ms)return null;r.push(ma(s.edits.length>1?`${i} · #${c+1}`:i,l,p))}return r.join(`
6
+ `)}case"write_file":{const o=String(s.content??"");return!o||o.length>ms?null:ma(i,"",o)}case"apply_patch":{const o=String(s.patch??s.input??s.diff??"");return o.length>ms?null:/^@@[ -]/m.test(o)&&/^(--- |\+\+\+ )/m.test(o)?o:Xp(o)}default:return null}}catch{return null}}je({"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 Ba=new Set,Uh=e=>Ba.has(e),Jp=e=>zl(El(e)).remoteApprover,Jo=480,Wh=({req:e,onDecide:n,sessionId:s})=>{const{t:i}=Ee(),o=Jp(s),r=bl(s),c=e.name==="run_bash",u=(()=>{if(!c||!e.arguments)return"";try{return String(JSON.parse(e.arguments).command??"")}catch{return""}})(),[l,p]=d.useState(u),f=d.useRef(null),[v,w]=d.useState(!1);d.useLayoutEffect(()=>{const x=f.current;if(!x)return;x.style.height="auto";const O=x.scrollHeight;x.style.height=`${Math.min(O,Jo)}px`,w(O>Jo)},[l]);const E=wd.test(l),A=xd.test(l),z=e.status!=="pending",b=d.useMemo(()=>c?null:Gp(e.name,e.arguments),[c,e.name,e.arguments]),$=jl(e.reason)&&!o,D=Sl(e.reason,i),L=Nl(e.remote,i),U=!(e.localOnly&&o),K=z?Cl(e.answeredBy,{remotePage:o,answeredHere:Ba.has(e.approvalId),hostName:r},i):"",R=x=>{if(z||x!=="reject"&&!U)return;Ba.add(e.approvalId);const O=c&&!o&&l.trim()&&l!==u?{command:l}:void 0;n(x,x==="reject"?void 0:O)};return t.jsxs("div",{className:`approval-card${z?" resolved":""}`,children:[t.jsxs("div",{className:"approval-title",children:[t.jsx(Jd,{size:15,style:{color:"var(--accent-ink)"}}),i("approval.requestExec",{name:e.name}),z&&t.jsxs("span",{style:{fontWeight:400,fontSize:"var(--ui-font-meta, 12px)",color:"var(--text-faint)"},children:[e.status==="approved"?i("approval.statusApproved"):e.status==="rejected"?i("approval.statusRejected"):i("approval.statusExpired"),K&&t.jsxs("span",{"data-answered-by":!0,children:[" · ",K]})]})]}),L&&t.jsx("div",{className:"approval-why","data-approval-remote":!0,children:L}),D&&t.jsx("div",{className:"approval-why",children:D}),c&&!z&&!o?t.jsx("textarea",{className:"approval-edit",value:l,onChange:x=>p(x.target.value),ref:f,rows:1,spellCheck:!1}):null,c&&!z&&(v||E||A)&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"approval-why",children:[v&&t.jsx("div",{children:i("approval.cmdOverflow")}),E&&t.jsx("div",{children:i("approval.cmdHiddenChars")}),A&&t.jsx("div",{children:i("approval.cmdWideBlank")})]}),(E||A)&&t.jsx("div",{className:"approval-preview",children:e.preview})]}),c&&!z&&!o?null:t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"approval-preview",children:e.preview}),b&&t.jsx("div",{className:"approval-diff",children:t.jsx(kd,{text:b,side:!1})}),o&&!z&&U&&t.jsx("div",{className:"approval-why","data-remote-readonly":!0,children:i("approval.remoteReadOnly")}),!z&&!U&&t.jsx("div",{className:"approval-why","data-local-only":!0,children:i("approval.localOnly")})]}),!z&&t.jsxs("div",{className:"approval-actions",children:[U&&t.jsxs("button",{className:"btn primary sm",onClick:()=>R("approve"),children:[t.jsx(at,{size:13})," ",i("approval.approve")]}),$&&U&&t.jsxs("button",{className:"btn ghost sm",onClick:()=>R("approve_always"),children:[t.jsx(Ju,{size:13})," ",i("approval.approveAlways")]}),t.jsxs("button",{className:"btn danger sm",onClick:()=>R("reject"),children:[t.jsx(pt,{size:13})," ",i("approval.reject")]})]})]})},Qp=["readonly","auto-edit","full-auto"],Zp={base:"auto-edit"},fa=e=>e.join(`
7
+ `),ha=e=>e.split(`
8
+ `).map(n=>n.trim()).filter(Boolean),em=({cfg:e,onClose:n})=>{const{t:s}=Ee(),[i,o]=d.useState(Zp.base),[r,c]=d.useState({deny:"",ask:"",allow:""}),[u,l]=d.useState(!0),[p,f]=d.useState(!1),[v,w]=d.useState(!1),[E,A]=d.useState(""),z=gn.useRef(e);z.current=e;const b=gn.useCallback(()=>{l(!0),A(""),Ml(kt()).then(L=>{o(L.base),c({deny:fa(L.deny),ask:fa(L.ask),allow:fa(L.allow)}),f(!0),l(!1)}).catch(L=>{A(String(L?.message||L)),f(!1),l(!1)})},[]);d.useEffect(()=>{b()},[b]);const $=async()=>{if(p){w(!0),A("");try{await Rl(kt(),{base:i,deny:ha(r.deny),ask:ha(r.ask),allow:ha(r.allow)}),n()}catch(L){A(String(L?.message||L)),w(!1)}}},D=L=>t.jsxs("div",{className:"field",children:[t.jsx("label",{children:t.jsx("b",{children:s(`approvalRules.${L}`)})}),t.jsx("div",{className:"hint",children:s(`approvalRules.${L}Hint`)}),t.jsx("textarea",{value:r[L],onChange:U=>c(K=>({...K,[L]:U.target.value})),rows:3,spellCheck:!1,placeholder:s(`approvalRules.${L}Ph`),style:{width:"100%",fontFamily:"var(--font-mono)",fontSize:"var(--ui-font-meta, 12px)"}})]},L);return t.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:t.jsxs("div",{onClick:L=>L.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:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:10},children:[t.jsx("b",{children:s("approvalRules.title")}),t.jsx("button",{className:"icon-btn",onClick:n,children:t.jsx(pt,{size:15})})]}),u?t.jsx("div",{className:"field",children:t.jsxs("div",{className:"hint",children:[t.jsx(Yt,{size:14,className:"spin"})," ",s("common.loading")]})}):p?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"field",children:[t.jsx("div",{className:"hint",children:s("approvalRules.scopeNote")}),t.jsx("div",{className:"hint",style:{marginTop:4},children:s("approvalRules.syntax")})]}),t.jsxs("div",{className:"field",children:[t.jsx("label",{children:t.jsx("b",{children:s("approvalRules.base")})}),t.jsx("div",{className:"hint",children:s("approvalRules.baseHint")}),t.jsx("div",{style:{display:"flex",gap:6,marginTop:6},children:Qp.map(L=>t.jsx("button",{className:`btn sm${i===L?" primary":" ghost"}`,onClick:()=>o(L),children:s(Al[L])},L))})]}),["deny","ask","allow"].map(D),E&&t.jsx("div",{className:"field",children:t.jsx("div",{className:"hint",style:{color:"var(--danger)"},children:E})})]}):t.jsxs("div",{className:"field",children:[t.jsx("div",{className:"hint",style:{color:"var(--danger)"},children:s("approvalRules.loadFailed")}),t.jsx("div",{className:"hint",children:E}),t.jsx("div",{style:{marginTop:8},children:t.jsx("button",{className:"btn sm ghost",onClick:b,children:s("common.retry")})})]}),t.jsxs("div",{style:{display:"flex",gap:6,justifyContent:"flex-end",marginTop:14},children:[t.jsx("button",{className:"btn ghost sm",onClick:n,children:s("common.cancel")}),t.jsxs("button",{className:"btn primary sm",disabled:!p||v,onClick:()=>{$()},children:[v?t.jsx(Yt,{size:13,className:"spin"}):null," ",s("common.save")]})]})]})})},tm=[{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 evolution record (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 Qo(e){return tm.filter(n=>n.surfaces.includes(e))}function nm(e){const n=e.find(i=>i.active),s=(n&&Un(n)?n:void 0)??e.find(i=>i.front&&Un(i))??e.find(i=>i.type==="amadeus-editor"&&Un(i))??e.find(i=>Un(i));return s?Un(s):""}function Un(e){return e.filePath?qa(e.type,e.filePath)?`note:${e.filePath}`:sc(e.filePath)?`file:${e.filePath}`:"":""}const sc=e=>/^(\/|[A-Za-z]:[\\/]|\\\\)/.test(e),qa=(e,n)=>(e.startsWith("amadeus-")||e==="dashboard")&&!sc(n);je({"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.camera":{zh:"拍照",en:"Take photo"},"addMenu.photos":{zh:"相册",en:"Photos"},"addMenu.file":{zh:"文件",en:"Files"},"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"},"addMenu.app":{zh:"添加应用或窗口",en:"Add an app or window"},"addMenu.searchApps":{zh:"搜索窗口和应用",en:"Search windows and apps"},"addMenu.openWindows":{zh:"打开的窗口",en:"Open windows"},"addMenu.apps":{zh:"应用",en:"Apps"},"addMenu.appRunning":{zh:"正在运行",en:"Running"},"addMenu.appIdle":{zh:"没在运行",en:"Not running"},"addMenu.windowsUnavailable":{zh:"窗口列不出来:电脑操作的本机助手没装或没有「辅助功能」权限",en:"Windows can't be listed: the Computer Use helper isn't installed or lacks Accessibility permission"},"addMenu.windowsUnavailableWin":{zh:"窗口列不出来:系统自带的 PowerShell 没能运行",en:"Windows can't be listed: the built-in PowerShell couldn't run"}});const ga=new Set(["chat","chat-panel","home","launcher","sidebar-empty"]),sm=300;function am(e,n,s=sm){const i=new Set(e.map(r=>r.id)),o=n.filter(r=>!i.has(r.id));return o.length>s?null:{recent:[...e],rest:o}}function fs(e){const n=new Set;return e.filter(s=>n.has(s.key)?!1:(n.add(s.key),!0))}const im=({open:e,disabled:n,activeSessionId:s,canUsePathPicker:i,onOpenChange:o,onNewSession:r,onAddAgent:c,onPickPaths:u,onPickFiles:l,onAddReference:p})=>{const{t:f}=Ee(),[v,w]=d.useState(null),[E,A]=d.useState(null),[z,b]=d.useState(""),[$,D]=d.useState("right"),[L,U]=d.useState(0),K=d.useRef(null),R=d.useRef(null),x=d.useRef(null),O=d.useRef(null),J=Xt(e,{boundary:".t2-chat-view"}),ee=Xt(v?`${v}:${$}`:"",{boundary:".t2-chat-view"}),Q=I(k=>k.sessions),H=I(k=>k.archivedSessions),C=ed(k=>k.items),_=xs(k=>k.mainTabs),q=xs(k=>k.leftTabs),Z=xs(k=>k.rightTabs),oe=qn(k=>k.vaultRoot);d.useEffect(()=>{e||(w(null),b(""))},[e]),d.useEffect(()=>{b(""),v&&requestAnimationFrame(()=>x.current?.focus())},[v]),d.useEffect(()=>{if(v!=="app")return;let k=!0;return window.tangu?.appRefs?.list().then(V=>{k&&A(V)},()=>{}),()=>{k=!1}},[v]),d.useLayoutEffect(()=>{const k=K.current,V=R.current;if(!v||!k||!V)return;const W=()=>{const De=k.getBoundingClientRect(),it=(k.closest(".t2c-card")||k.closest(".t2-chat-view"))?.getBoundingClientRect(),Ke=Mr(V),Pe=it?Ar(De.left,De.right,V.offsetWidth,it.left,it.right,Ke):"right";D(fe=>fe===Pe?fe:Pe),U(fe=>fe===k.offsetHeight+6?fe:k.offsetHeight+6)};W(),window.addEventListener("resize",W),window.addEventListener(zs,W);const ze=new ResizeObserver(W);ze.observe(k),ze.observe(V);const _e=k.closest(".t2c-card")||k.closest(".t2-chat-view");return _e&&ze.observe(_e),()=>{window.removeEventListener("resize",W),window.removeEventListener(zs,W),ze.disconnect()}},[v]);const re=d.useMemo(()=>{const k=new Set;return[...Q,...H].filter(V=>V.id===s||k.has(V.id)?!1:(k.add(V.id),!0))},[Q,H,s]),g=d.useMemo(()=>{const k=new Map(re.map(W=>[W.id,W])),V=C.filter(W=>W.kind==="chat").map(W=>k.get(W.id)).filter(Boolean);return(V.length?V:re).slice(0,6)},[re,C]),P=d.useMemo(()=>{const k=z.trim().toLocaleLowerCase();return k?re.filter(V=>`${V.title||""}
9
+ ${V.summary||""}`.toLocaleLowerCase().includes(k)).slice(0,12):g},[z,g,re]),G=d.useMemo(()=>{const k=_.flatMap(W=>{if(ga.has(W.type))return[];const ze=W.title||jo(aa(W.type)?.displayName||W.type),_e=!!W.filePath&&qa(W.type,W.filePath);if(W.filePath&&(!_e||oe)){const De=_e;return[{key:`${De?"note":"file"}:${W.filePath}`,type:W.type,title:ze,ref:De?{kind:"note",path:W.filePath}:{kind:"file",path:W.filePath},meta:W.filePath}]}return[{key:`view:${W.type}`,type:W.type,title:ze,ref:{kind:"view",type:W.type,title:ze}}]}),V=[...q,...Z].flatMap(W=>ga.has(W.type)?[]:[{key:`view:${W.type}`,type:W.type,title:W.title,ref:{kind:"view",type:W.type,title:W.title}}]);return fs([...k,...V]).slice(0,8)},[_,q,Z,oe]),he=d.useMemo(()=>fs(C.flatMap(k=>k.kind==="chat"?[]:k.kind==="note"?[{key:k.key,type:"amadeus-editor",title:k.title,ref:{kind:"note",path:k.id},meta:k.id}]:k.kind==="file"&&k.viewType?qa(k.viewType,k.id)?oe?[{key:k.key,type:k.viewType,title:k.title,ref:{kind:"note",path:k.id},meta:k.id}]:[]:[{key:k.key,type:k.viewType,title:k.title,ref:{kind:"file",path:k.id},meta:k.id}]:k.kind==="view"&&k.viewType&&aa(k.viewType)?[{key:k.key,type:k.viewType,title:k.title,ref:{kind:"view",type:k.viewType,title:k.title}}]:[])).slice(0,6),[C,oe]),we=Tl().filter(k=>!ga.has(k.type)).map(k=>{const V=jo(k.displayName);return{key:`view:${k.type}`,type:k.type,title:V,ref:{kind:"view",type:k.type,title:V}}}),Ce=(()=>{const k=z.trim().toLocaleLowerCase();return k?fs([...G,...he,...we]).filter(V=>`${V.title}
10
+ ${V.type}
11
+ ${V.meta||""}`.toLocaleLowerCase().includes(k)).slice(0,12):[]})(),de=(()=>{const k=z.trim().toLocaleLowerCase(),V=W=>!k||W.toLocaleLowerCase().includes(k);return{windows:(E?.windows??[]).filter(W=>V(`${W.title}
12
+ ${W.app}`)).slice(0,12),apps:(E?.apps??[]).filter(W=>V(W.name)).slice(0,k?12:8)}})(),xe=k=>{p(k),o(!1)},Ie=async k=>{o(!1);const V=await k();if(!V.length)return;const W=new DataTransfer;V.forEach(ze=>W.items.add(ze)),await l(W.files)},B=async()=>{if(i&&window.tangu?.pickPaths){o(!1);const k=await window.tangu.pickPaths();k.length&&await u(k);return}if(window.tangu?.pickFiles)return Ie(()=>window.tangu.pickFiles());O.current?.click()},ne=k=>aa(k)?.icon||js,se=k=>{const V=k.ref.kind==="file"||k.ref.kind==="note"?Is:ne(k.type);return{id:`ref:${k.key}`,label:k.title,detail:k.meta,icon:t.jsx(V,{size:14}),run:()=>xe(k.ref)}},ye=k=>({id:`session:${k.id}`,label:k.title||"Chat",detail:k.summary||void 0,icon:t.jsx(fn,{size:14}),run:()=>xe({kind:"session",id:k.id,title:k.title||"Chat"})}),Le={id:"new-chat",label:f("addMenu.newChat"),icon:t.jsx(bd,{size:14}),run:()=>{r?.(),o(!1)}},te=c?{id:"add-agent",act:"add-agent",label:f("addMenu.agent"),icon:t.jsx(Vr,{size:14}),run:()=>{c(),o(!1)}}:null,Me={id:"files",label:f("addMenu.files"),icon:t.jsx($l,{size:14}),run:()=>{B()}},He=window.tangu,Je=He?.takePhoto&&He.pickPhotos&&He.pickFiles?[{id:"camera",label:f("addMenu.camera"),icon:t.jsx(Il,{size:14}),run:()=>{Ie(()=>He.takePhoto())}},{id:"photos",label:f("addMenu.photos"),icon:t.jsx(Ll,{size:14}),run:()=>{Ie(()=>He.pickPhotos())}},{...Me,label:f("addMenu.file")}]:[Me],Qt=()=>{const k=am(g,re),V=fs([...G,...he]),W=new Set(V.map(_e=>_e.key)),ze=f("addMenu.noMatches");return{title:f("addMenu.label"),back:f("common.back"),sections:[{items:[Le,...te?[te]:[],...Je,k?{id:"conversation",label:f("addMenu.conversation"),icon:t.jsx(fn,{size:14}),search:{placeholder:f("addMenu.searchChats"),empty:ze},children:[{title:f("addMenu.recent"),items:k.recent.map(ye)},{title:f("addMenu.allChats"),items:k.rest.map(ye)}]}:{id:"conversation",label:f("addMenu.conversation"),icon:t.jsx(fn,{size:14}),run:()=>{o(!0),w("conversation")}},{id:"view",label:f("addMenu.view"),icon:t.jsx(js,{size:14}),search:{placeholder:f("addMenu.searchViews"),empty:ze},children:[{title:f("addMenu.inUse"),items:G.map(se)},{title:f("addMenu.recent"),items:he.filter(_e=>!G.some(De=>De.key===_e.key)).map(se)},{title:f("addMenu.allViews"),items:we.filter(_e=>!W.has(_e.key)).map(se)}]}]}]}},Ze=k=>k.map(V=>{const W=se(V);return t.jsxs("button",{className:"menu-item add-menu-result",title:V.meta||V.title,onClick:W.run,children:[W.icon,t.jsxs("span",{className:"grow add-menu-result-main",children:[t.jsx("span",{className:"add-menu-result-title",children:W.label}),W.detail&&t.jsx("span",{className:"add-menu-result-meta",children:W.detail})]})]},V.key)});return t.jsxs("span",{className:`add-pill-wrap t2c-capsule-peer${e?" is-open":""}`,"data-cmenu":!0,children:[t.jsxs("button",{className:`t2c-pill add-pill-btn${e?" is-open":""}`,title:f("input.addContent"),"aria-expanded":e,disabled:n,onClick:()=>{!e&&si(Qt,{})||o(!e)},children:[t.jsx(Cs,{size:16,className:"add-pill-plus"}),t.jsx("span",{className:"add-pill-label",children:f("addMenu.label")}),t.jsx(yn,{size:10,className:"add-pill-chevron"})]}),e&&t.jsxs("div",{ref:k=>{K.current=k,J.ref.current=k},className:"composer-menu composer-menu--add",style:J.style,children:[t.jsxs("button",{className:"menu-item",onClick:Le.run,children:[Le.icon,t.jsx("span",{className:"grow",children:Le.label})]}),te&&t.jsxs("button",{className:"menu-item","data-add-agent":!0,onClick:te.run,children:[te.icon,t.jsx("span",{className:"grow",children:te.label})]}),t.jsxs("button",{className:"menu-item",onClick:Me.run,children:[Me.icon,t.jsx("span",{className:"grow",children:Me.label})]}),t.jsxs("button",{className:`menu-item add-menu-parent${v==="conversation"?" active":""}`,"aria-expanded":v==="conversation",onPointerEnter:()=>w("conversation"),onFocus:()=>w("conversation"),onClick:()=>w("conversation"),children:[t.jsx(fn,{size:14}),t.jsx("span",{className:"grow",children:f("addMenu.conversation")}),t.jsx(It,{size:13})]}),t.jsxs("button",{className:`menu-item add-menu-parent${v==="view"?" active":""}`,"aria-expanded":v==="view",onPointerEnter:()=>w("view"),onFocus:()=>w("view"),onClick:()=>w("view"),children:[t.jsx(js,{size:14}),t.jsx("span",{className:"grow",children:f("addMenu.view")}),t.jsx(It,{size:13})]}),window.tangu?.appRefs&&t.jsxs("button",{className:`menu-item add-menu-parent${v==="app"?" active":""}`,"aria-expanded":v==="app","data-add-app":!0,onPointerEnter:()=>w("app"),onFocus:()=>w("app"),onClick:()=>w("app"),children:[t.jsx(zr,{size:14}),t.jsx("span",{className:"grow",children:f("addMenu.app")}),t.jsx(It,{size:13})]})]}),e&&v&&t.jsxs("div",{ref:k=>{R.current=k,ee.ref.current=k},className:`composer-menu add-menu-sub ${$}`,"data-pane":v,style:{...ee.style,bottom:$==="stacked"?`calc(100% + ${L}px)`:void 0},children:[t.jsxs("label",{className:"add-menu-search",children:[t.jsx(Er,{size:13}),t.jsx("input",{ref:x,value:z,onChange:k=>b(k.currentTarget.value),placeholder:f(v==="conversation"?"addMenu.searchChats":v==="app"?"addMenu.searchApps":"addMenu.searchViews")})]}),t.jsx("div",{className:"add-menu-sub-scroll",children:v==="conversation"?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"menu-section",children:f(z.trim()?"addMenu.allChats":"addMenu.recent")}),P.map(k=>{const V=ye(k);return t.jsxs("button",{className:"menu-item add-menu-result",title:k.summary||k.title||"",onClick:V.run,children:[V.icon,t.jsxs("span",{className:"grow add-menu-result-main",children:[t.jsx("span",{className:"add-menu-result-title",children:V.label}),V.detail&&t.jsx("span",{className:"add-menu-result-meta",children:V.detail})]})]},k.id)}),!P.length&&t.jsx("div",{className:"add-menu-empty",children:f("addMenu.noMatches")})]}):v==="app"?t.jsxs(t.Fragment,{children:[E?.error&&t.jsx("div",{className:"add-menu-empty",children:f(/Win/i.test(navigator.platform)?"addMenu.windowsUnavailableWin":"addMenu.windowsUnavailable")}),!!de.windows.length&&t.jsx("div",{className:"menu-section",children:f("addMenu.openWindows")}),de.windows.map(k=>t.jsxs("button",{className:"menu-item add-menu-result","data-app-kind":"window",title:k.title,onClick:()=>xe({kind:"window",id:k.id,name:k.title}),children:[t.jsx(kn,{id:k.id,className:"add-menu-appico"}),t.jsxs("span",{className:"grow add-menu-result-main",children:[t.jsx("span",{className:"add-menu-result-title",children:k.title}),t.jsx("span",{className:"add-menu-result-meta",children:k.app})]})]},`w:${k.id}:${k.title}`)),!!de.apps.length&&t.jsx("div",{className:`menu-section${de.windows.length?" add-menu-section-gap":""}`,children:f("addMenu.apps")}),de.apps.map(k=>t.jsxs("button",{className:"menu-item add-menu-result","data-app-kind":"app",title:k.name,onClick:()=>xe({kind:"app",id:k.id,name:k.name}),children:[t.jsx(kn,{id:k.id,className:"add-menu-appico"}),t.jsxs("span",{className:"grow add-menu-result-main",children:[t.jsx("span",{className:"add-menu-result-title",children:k.name}),t.jsx("span",{className:"add-menu-result-meta",children:f(k.running?"addMenu.appRunning":"addMenu.appIdle")})]})]},`a:${k.id}`)),E&&!de.windows.length&&!de.apps.length&&t.jsx("div",{className:"add-menu-empty",children:f("addMenu.noMatches")})]}):z.trim()?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"menu-section",children:f("addMenu.allViews")}),Ze(Ce),!Ce.length&&t.jsx("div",{className:"add-menu-empty",children:f("addMenu.noMatches")})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"menu-section",children:f("addMenu.inUse")}),Ze(G),!G.length&&t.jsx("div",{className:"add-menu-empty",children:f("addMenu.noMatches")}),!!he.length&&t.jsx("div",{className:"menu-section add-menu-section-gap",children:f("addMenu.recent")}),Ze(he)]})})]}),t.jsx("input",{ref:O,type:"file",multiple:!0,hidden:!0,onChange:k=>{l(k.currentTarget.files),k.currentTarget.value="",o(!1)}})]})};function ac(e,n){const s=e.agents.filter(u=>u.createdBy!=="system"),i=e.agents.find(u=>u.slug===e.currentAgentSlug),o={id:"normal-work",label:n("input.normalWork"),icon:t.jsx(ia,{size:14}),checked:e.active,disabled:e.disabled,run:()=>{e.onNormalWork(),e.onClose()}},r=e.onAgentSwitch?s.map(u=>({id:`agent:${u.slug}`,label:u.name,icon:t.jsx(ia,{size:14}),checked:e.currentAgentSlug===u.slug,run:()=>{e.onAgentSwitch(u.slug),e.onClose()}})):[],c=r.length?{id:"agent-switch",label:n("input.agentSwitch.section"),detail:i?.name,icon:t.jsx(ia,{size:14}),children:[{items:r}]}:null;return{normal:o,agentSwitch:c,agents:r}}function om(e){const{currentAgentSlug:n,agents:s}=e,{t:i}=Ee(),[o,r]=d.useState(!1),[c,u]=d.useState("right"),[l,p]=d.useState(0),f=d.useRef(null),v=d.useRef(null),w=Xt(o?c:"",{boundary:".t2-chat-view"}),E=ac(e,i),A=E.agentSwitch?()=>r(!0):void 0,z=s.find(b=>b.slug===n);return d.useLayoutEffect(()=>{const b=f.current,$=v.current,D=b?.closest(".composer-menu");if(!o||!b||!$||!D)return;const L=()=>{const R=D.getBoundingClientRect(),x=(D.closest(".t2c-card")||D.closest(".t2-chat-view"))?.getBoundingClientRect(),O=D.closest(".t2-chat-view")?.getBoundingClientRect(),J=Mr($),ee=x?Ar(R.left,R.right,$.offsetWidth,x.left,x.right,J):"right";u(H=>H===ee?H:ee);const Q=Dl(b.getBoundingClientRect().top,$.offsetHeight,R.top,R.bottom,O?.top??0,O?.bottom??window.innerHeight,J);p(H=>Math.abs(H-Q)<.5?H:Q)};L(),window.addEventListener("resize",L),window.addEventListener(zs,L);const U=new ResizeObserver(L);U.observe(D),U.observe($);const K=D.closest(".t2c-card")||D.closest(".t2-chat-view");return K&&U.observe(K),()=>{window.removeEventListener("resize",L),window.removeEventListener(zs,L),U.disconnect()}},[o]),d.useEffect(()=>{const b=f.current?.closest(".composer-menu");if(!o||!b)return;const $=D=>{const L=D.target?.closest?.(".menu-item");L&&!f.current?.contains(L)&&r(!1)};return b.addEventListener("pointerover",$),b.addEventListener("focusin",$),()=>{b.removeEventListener("pointerover",$),b.removeEventListener("focusin",$)}},[o]),t.jsxs("div",{ref:f,className:"mode-normal-row",onPointerEnter:A,children:[t.jsxs("button",{className:`menu-item${E.normal.checked?" active":""}`,"data-normal-work":!0,disabled:E.normal.disabled,onClick:E.normal.run,children:[E.normal.icon,t.jsx("span",{className:"grow",children:E.normal.label}),E.normal.checked&&t.jsx(at,{size:13})]}),A&&t.jsxs("button",{className:"menu-item mode-agent-trigger","data-agent-switch":!0,"aria-haspopup":"menu","aria-expanded":o,title:i("input.agentSwitch.section"),onFocus:A,onClick:A,children:[z&&t.jsx("span",{className:"mode-agent-name",children:z.name}),t.jsx(It,{size:13})]}),o&&A&&t.jsxs("div",{ref:b=>{v.current=b,w.ref.current=b},className:`cm-sub ${c}`,"data-pane":"agents",role:"menu",style:{...w.style,"--cm-sub-top":`${l}px`},children:[t.jsx("div",{className:"menu-section",children:i("input.agentSwitch.section")}),E.agents.map(b=>t.jsxs("button",{role:"menuitemradio","aria-checked":!!b.checked,className:`menu-item${b.checked?" active":""}`,onClick:b.run,children:[b.icon,t.jsx("span",{className:"grow",children:b.label}),b.checked&&t.jsx(at,{size:13})]},b.id))]})]})}const Wn={color:"var(--accent-ink)",flexShrink:0};function rm({chip:e,appRef:n}){const s=Ol(n),i=Fl()?s?.state:"missing",{sub:o,hint:r}=Ul(n,s);return t.jsxs("span",{className:"attach-chip attach-chip--appref","data-ref-kind":e.kind,"data-off":i==="closed"||i==="missing"||void 0,title:[o,r].filter(Boolean).join(`
13
+ `)||e.name,role:i==="missing"?void 0:"link",tabIndex:i==="missing"?void 0:0,onClick:()=>{i!=="missing"&&So(n)},onKeyDown:c=>{c.key==="Enter"&&i!=="missing"&&So(n)},children:[t.jsx(kn,{id:n.id,className:"attach-chip-appico"}),t.jsx("span",{children:e.name})]})}function cm({chip:e,onRemove:n,onInline:s,removeTitle:i,inlineTitle:o,children:r}){return e.appRef&&!n?t.jsx(rm,{chip:e,appRef:e.appRef}):t.jsxs("span",{className:"attach-chip",title:s&&o?`${e.token}
14
+ ${o}`:e.token,"data-ref-kind":e.kind,onMouseDown:s?c=>{c.shiftKey&&c.preventDefault()}:void 0,onClick:s?c=>{c.shiftKey&&(c.preventDefault(),s())}:void 0,children:[e.appRef?t.jsx(kn,{id:e.appRef.id,className:"attach-chip-appico"}):e.kind==="session"?t.jsx(Xn,{size:13,style:Wn}):e.kind==="folder"?t.jsx(bn,{size:13,style:Wn}):e.kind==="view"?t.jsx(js,{size:13,style:Wn}):e.kind==="app"||e.kind==="window"?t.jsx(zr,{size:13,style:Wn}):t.jsx(Is,{size:13,style:Wn}),t.jsx("span",{children:r??e.name}),n&&t.jsx("button",{type:"button",title:i,"aria-label":i,onClick:c=>{c.stopPropagation(),n()},children:t.jsx(pt,{size:12})})]})}const va=e=>e.replace(/[\\/]+$/,"").split(/[\\/]/).pop()||e,Zo=e=>e.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&");function lm(e){if(/[\s"<>[\]]/.test(e)||e.includes("://"))return!1;const n=/^(~?\/|[A-Za-z]:[\\/])/.test(e),s=e.split(/[\\/]/).filter(Boolean);return n?s.length>=(/^[A-Za-z]:/.test(e)?3:2):s.length>=2&&/\.[A-Za-z0-9]{1,10}$/.test(s[s.length-1])}const um=/^\[\[([^[\]\n]+)\]\]/,dm=/^"([^"\n]+)"/,pm=/^<forsion-view type="([^"\n]*)" title="([^"\n]*)" \/>/,mm=/^<forsion-app app="([^"\n]*)"[^>\n]* \/>/,fm=/^[^\s]+/;function hm(e,n){const s=e.slice(n);let i=um.exec(s);if(i){const o=i[1],r=o.indexOf("|"),c=(r===-1?o:o.slice(0,r)).trim(),u=(r===-1?"":o.slice(r+1)).trim();if(!c)return null;const l=_l(o);return l?{ref:{token:i[0],name:l.name,kind:l.kind,appRef:l},end:n+i[0].length,strong:!0}:{ref:Pl(c)?{token:i[0],name:u||"Chat",kind:"session",wiki:o}:{token:i[0],name:u||va(c).replace(/\.md$/i,""),kind:"note",wiki:o},end:n+i[0].length,strong:!0}}if(i=pm.exec(s),i)return{ref:{token:i[0],name:Zo(i[2]),kind:"view"},end:n+i[0].length,strong:!0};if(i=mm.exec(s),i)return{ref:{token:i[0],name:Zo(i[1]),kind:"app"},end:n+i[0].length,strong:!0};if(i=dm.exec(s),i){const o=i[1];return!/\s/.test(o)||!/[\\/]/.test(o)?null:{ref:{token:i[0],name:va(o),kind:"file"},end:n+i[0].length,strong:!0}}return i=fm.exec(s),i&&lm(i[0])?{ref:{token:i[0],name:va(i[0]),kind:"file"},end:n+i[0].length,strong:!1}:null}function Bh(e){if(!e)return null;const n=e.indexOf(`
15
+ `),s=n===-1?e:e.slice(0,n),i=[];let o=!0,r=0;for(;r<s.length;){const c=hm(s,r);if(!c)return null;if(i.push(c.ref),o=o&&c.strong,r=c.end,r===s.length)break;if(s[r]!==" "||(r+=1,r===s.length))return null}return!i.length||n===-1&&!o?null:{refs:i,body:n===-1?"":e.slice(n+1)}}const er=e=>(e.note?e.p.replace(/\.md$/i,""):e.p).split("/").pop();function ya(e,n,s=10){const i=n.toLowerCase(),o=i?e.filter(p=>p.p.toLowerCase().includes(i)):e,r=p=>{const f=er(p).toLowerCase();return(f.startsWith(i)?0:f.includes(i)?1:2)*1e4+p.p.length},c=[...o].sort((p,f)=>r(p)-r(f)).slice(0,s);if(!i.replace(/[\s\-_/.]+/g,"")||c.length>=s)return c;const u=new Set(c),l=[];for(const p of e){if(u.has(p))continue;const f=Wl(i,er(p));f!==null&&l.push({c:p,s:f})}return l.sort((p,f)=>f.s-p.s),[...c,...l.slice(0,s-c.length).map(p=>p.c)]}const gm=["all","window","app","note","file","session"],oi=e=>e.app?e.app.kind:e.session?"session":e.note?"note":"file";function vm(e){const n=new Set(e.map(oi)),s=gm.filter(i=>i!=="all"&&n.has(i));return s.length>1?["all",...s]:[]}function ym(e,n,s){if(!e.length||s!=="ArrowLeft"&&s!=="ArrowRight")return null;const i=Math.max(0,e.indexOf(n));return s==="ArrowLeft"?i>0?e[i-1]:null:e[Math.min(i+1,e.length-1)]}function tr(e,n,s){if(s!=="all"){const r=e.filter(c=>oi(c)===s);return!n&&(s==="window"||s==="app")?r.slice(0,10):ya(r,n,10)}if(n)return ya(e,n,10);const i=e.filter(r=>r.app?.kind==="window").slice(0,4),o=e.filter(r=>r.app?.kind==="app").slice(0,3);return[...i,...o,...ya(e.filter(r=>!r.app),"",10-Math.min(5,i.length+o.length))]}const Zn="  ",ic=" ",ri="  ([^  \\n]{1,96}) ",km=e=>[...String(e||"").replace(/\u2060/g,"").replace(/[\u2007\u202F\r\n]+/g," ").trim()].slice(0,80).join("").trimEnd();function wm(e,n){let s=km(e);for(let i=0;s&&n(s);i++){if(i>=16)return"";s+="⁠"}return s}const xm=e=>`${Zn}${e}${ic}`;function bm(e,n){if(!e.includes(Zn))return[];const s=[],i=new RegExp(ri,"gu");let o;for(;o=i.exec(e);)n(o[1])&&s.push({start:o.index,end:o.index+o[0].length,name:o[1]});return s}function jm(e,n,s){return e.find(i=>s==="back"?i.start<n&&n<=i.end:i.start<=n&&n<i.end)}function Sm(e,n){const s=new Set;return e.includes(Zn)?{text:e.replace(new RegExp(ri,"gu"),(o,r)=>{const c=n(r);return c===void 0?o:(s.add(r),c)}),used:s}:{text:e,used:s}}function Nm(e,n){return!n||!e.includes(Zn)?e:e.replace(new RegExp(ri,"gu"),(s,i)=>i===n?i.replace(/\u2060+$/,""):s)}const nr=e=>e.replace(/[^\S\u2007\u202F]+$/,""),Cm=["fontFamily","fontSize","fontWeight","fontStyle","lineHeight","letterSpacing","wordSpacing","textIndent","textAlign","tabSize","paddingTop","paddingRight","paddingBottom","paddingLeft","direction","fontFeatureSettings","fontVariantNumeric","wordBreak"];function zm({text:e,runs:n,chipOf:s}){const i=d.useRef(null),o=d.useRef(null),r=n.length>0;if(d.useLayoutEffect(()=>{const l=i.current,p=o.current,f=l?.previousElementSibling;if(!r||!l||!p||!(f instanceof HTMLTextAreaElement))return;const v=()=>{const E=getComputedStyle(f);for(const b of Cm)l.style[b]=E[b];let A=f.clientLeft,z=f.clientTop;for(let b=f;b&&b!==l.offsetParent;b=b.offsetParent)A+=b.offsetLeft,z+=b.offsetTop;l.style.left=`${A}px`,l.style.top=`${z}px`,l.style.width=`${f.clientWidth}px`,l.style.height=`${f.clientHeight}px`,p.style.transform=`translateY(${-f.scrollTop}px)`};v();const w=new ResizeObserver(v);return w.observe(f),f.addEventListener("scroll",v,{passive:!0}),()=>{w.disconnect(),f.removeEventListener("scroll",v)}},[r,e]),!r)return null;const c=[];let u=0;return n.forEach((l,p)=>{l.start>u&&c.push(e.slice(u,l.start));const f=s(l.name);c.push(t.jsxs("span",{className:"t2c-inref",children:[t.jsxs("span",{className:"t2c-inref-slot",children:[Zn,f?.appRef?t.jsx(kn,{id:f.appRef.id,className:"t2c-inref-ico"}):f?.kind==="session"?t.jsx(Xn,{className:"t2c-inref-ico"}):f?.kind==="folder"?t.jsx(bn,{className:"t2c-inref-ico"}):t.jsx(Is,{className:"t2c-inref-ico"})]}),l.name,ic]},p)),u=l.end}),c.push(e.slice(u)+(e.endsWith(`
16
+ `)?"​":"")),t.jsx("div",{ref:i,className:"t2c-mirror","aria-hidden":!0,children:t.jsx("div",{ref:o,children:c})})}function Em(e,n){const s=n.trim();return!s||e.includes(s)?[...e]:[...e,s]}const qh={sid:null,list:[]},Mm=[],Am=(e,n)=>e.sid===n?e.list:Mm,Hh=(e,n,s)=>({sid:n,list:Em(Am(e,n),s)});function Rm(e){return e.map(n=>`${n.split(`
17
+ `).map(s=>`> ${s}`).join(`
18
+ `)}
19
+
20
+ `).join("")}function Vh(e){const n=e.split(`
21
+ `),s=[];let i=0;const o=r=>r!==void 0&&/^>(?: |$)/.test(r);for(;o(n[i]);){const r=[];for(;o(n[i]);i++)r.push(n[i].replace(/^> ?/,""));for(s.push(r.join(`
22
+ `));n[i]==="";)i++}return s.length?{quotes:s,body:n.slice(i).join(`
23
+ `)}:null}const ci={text:"",attachments:[],wsFiles:[],refChips:[],pinnedSkills:[],mentionedSlug:"",mentionAgents:[],mentionedProjects:[]},sr="new",es=Qn(()=>({}));function Ha(e,n,s){es.setState(i=>{const o=i[e]??ci,r=typeof s=="function"?s(o[n]):s;return r===o[n]?i:{...i,[e]:{...o,[n]:r}}},!0)}function Tm(e,n=!1){es.setState(s=>{const i=s[e];if(!i)return s;const{[e]:o,...r}=s;return n&&i.text?{...r,[e]:{...ci,text:i.text}}:r},!0)}const ar=e=>!e||!e.text&&!e.attachments.length&&!e.wsFiles.length&&!e.refChips.length&&!e.pinnedSkills.length;function Im(e,n){es.setState(s=>{const i=s[e];if(e===n||ar(i)||!ar(s[n]))return s;const{[e]:o,...r}=s;return{...r,[n]:i}},!0)}function Rt(e,n){const s=es(r=>(r[e]??ci)[n]),i=d.useRef(e);i.current=e;const o=d.useRef(r=>Ha(i.current,n,r)).current;return[s,o]}const Lm=({tier:e})=>{const n=(e||"free").toLowerCase();if(n==="free"||!n)return null;const s=n==="pro"?{background:"linear-gradient(135deg, #8B5CF6, #A855F7)",color:"#fff",border:"none"}:{background:"linear-gradient(135deg, #F59E0B, #F97316)",color:"#fff",border:"none"};return t.jsx("span",{className:"tier-badge",style:s,children:n})};je({"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 nt=e=>e>=1e6?`${Math.floor(e/1e5)/10}M`:e>=1e3?`${Math.floor(e/100)/10}k`:String(e),ir=new Set(["persona","harness","human","guidance","profile","project","agentFolder","memory","skills","environment","hooks","plan"]),or="var(--model-tag-blue)",$m=[{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 Dm(e,n,s){if(!n)return e>0?[{id:"used",label:s("ctx.grp.used"),tokens:e,color:or}]:[];let i=Math.max(0,e);const o=l=>{const p=Math.min(i,Math.max(0,l));return i-=p,p},r=$m.map(l=>{const p=n.sections.filter(w=>l.keys.includes(w.k)||l.id==="system"&&!ir.has(w.k)),f=p.reduce((w,E)=>w+E.tokens,0),v=o(f);return{id:l.id,label:s(`ctx.grp.${l.id}`),color:l.color,tokens:v,parts:v===f?p.map(w=>({label:ir.has(w.k)?s(`ctx.sec.${w.k}`):w.k,tokens:w.tokens})):void 0}}),c={id:"messages",label:s("ctx.sec.history",{n:n.historyCount}),tokens:o(n.historyTokens),color:or},u={id:"tools",label:s("ctx.grp.tools"),tokens:i,color:"var(--model-tag-purple)"};return[c,u,...r].filter(l=>l.tokens>0)}const oc=8*36e5,_m=e=>864e5-(e+oc)%864e5;function Pm(e){const n=/^(\d{4})-(\d{2})-(\d{2})/.exec(e||"");return n?new Date(Date.UTC(Number(n[1]),Number(n[2])-1,Number(n[3]))-oc):null}function Om({open:e,contextWindow:n,ctxTokens:s,sessionTokens:i,runCost:o,costLimit:r,ctxInfo:c,onCompact:u}){const{t:l}=Ee(),[p,f]=d.useState(!1),v=s||0,w=D=>D/n*100,E=D=>`${Math.round(w(D)*10)/10}%`,A=Dm(Math.min(v,n),c??null,l),z=c?.compactAt&&c.compactAt<n?c.compactAt:0,b=z?Math.max(0,n-Math.max(z,v)):0,$=Math.max(0,n-v-b);return t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",className:"t2c-cu-head","aria-expanded":p,onClick:()=>f(D=>!D),children:[t.jsx("span",{className:"t2c-cu-title",children:l("ctx.pop.title")}),t.jsxs("span",{className:"t2c-cu-num",children:[nt(v)," / ",nt(n)," tokens (",Math.min(100,Math.round(w(v))),"%)"]}),t.jsx(It,{size:13,className:"t2c-cu-chev","aria-hidden":"true"})]}),t.jsxs("span",{className:"t2c-cu-bar","aria-hidden":"true",children:[A.map(D=>t.jsx("span",{style:{width:`${w(D.tokens)}%`,background:D.color}},D.id)),b>0&&t.jsx("span",{className:"t2c-cu-buffer",style:{width:`${w(b)}%`}})]}),c&&c.ctxWindowSource!=="override"&&(c.ctxWindowMax??0)>c.ctxWindow&&t.jsx("span",{className:"t2c-ctxinfo-src",children:l("ctx.windowCapped",{max:nt(c.ctxWindowMax),n:nt(c.ctxWindow)})}),p&&t.jsxs("span",{className:"t2c-cu-detail",children:[t.jsxs("span",{className:"t2c-cu-legend",children:[A.map(D=>t.jsxs(d.Fragment,{children:[t.jsxs("span",{className:"t2c-cu-row",children:[t.jsx("i",{style:{background:D.color}}),t.jsx("span",{children:D.label}),t.jsx("span",{children:nt(D.tokens)}),t.jsx("span",{children:E(D.tokens)})]}),D.parts&&D.parts.length>1&&D.parts.map(L=>t.jsxs("span",{className:"t2c-cu-row is-sub",children:[t.jsx("i",{}),t.jsx("span",{children:L.label}),t.jsxs("span",{children:["~",nt(L.tokens)]}),t.jsx("span",{})]},L.label))]},D.id)),b>0&&t.jsxs("span",{className:"t2c-cu-row",children:[t.jsx("i",{className:"t2c-cu-buffer"}),t.jsx("span",{children:l("ctx.grp.buffer")}),t.jsx("span",{children:nt(b)}),t.jsx("span",{children:E(b)})]}),t.jsxs("span",{className:"t2c-cu-row",children:[t.jsx("i",{className:"is-free"}),t.jsx("span",{children:l("ctx.grp.free")}),t.jsx("span",{children:nt($)}),t.jsx("span",{children:E($)})]})]}),c&&t.jsx("span",{className:"t2c-ctxinfo-src",children:l(`ctx.windowSource.${["override","model","learned","family","default"].includes(c.ctxWindowSource)?c.ctxWindowSource:"default"}`)}),!!i&&i>0&&t.jsx("span",{className:"t2c-ctxinfo-src",children:l("input.sessionTokens",{n:nt(i)})}),c&&t.jsxs("span",{className:"t2c-ctxinfo-files",children:[t.jsxs("span",{className:"t2c-ctxinfo-label",children:[l("ctx.files.label"),c.filesTruncated?` ${l("ctx.files.truncated")}`:""]}),c.files.length>0?c.files.map(D=>t.jsx("span",{className:"t2c-ctxinfo-file",title:D,children:D.split(/[/\\]/).slice(-2).join("/")},D)):t.jsx("span",{className:"t2c-ctxinfo-file dim",children:l("ctx.files.none")})]})]}),t.jsxs("span",{className:"t2c-cu-foot",children:[z>0&&t.jsx("span",{children:l("ctx.untilCompact",{left:nt(Math.max(0,z-v)),n:nt(z),pct:Math.round(w(z))})}),u&&t.jsx("button",{type:"button",className:"t2c-ctxring-compact",onClick:u,title:l("input.slash.compact"),children:l("ctx.pop.compact")})]}),o!=null&&r!=null&&r>0&&t.jsx("span",{className:"t2c-ctxinfo-src","data-warn":o>=r*.8||void 0,children:l("input.runCost",{used:Math.round(o).toLocaleString(),limit:r.toLocaleString()})}),t.jsx(Fm,{open:e})]})}function Fm({open:e}){const{t:n,locale:s}=Ee(),i=I(w=>w.authInfo?.loggedIn&&w.authInfo.tokenValid!==!1?`${w.authInfo.accountId??""}:${w.authInfo.username??""}`:null),o=i!==null&&!!window.tangu?.accountQuota,r=I(w=>w.authInfo?.membershipTier),[c,u]=d.useState(null),l=d.useRef(0);if(d.useEffect(()=>Bl(w=>{l.current++,u(w)}),[]),d.useEffect(()=>{u(null)},[i]),d.useEffect(()=>{if(!o||!e)return;let w=!0;const E=++l.current;return window.tangu.accountQuota().then(A=>{!w||E!==l.current||A?.status!==200||!A.json||(u(A.json),ql(A.json))}).catch(()=>{}),()=>{w=!1}},[e,i,o]),!o||!c)return null;const p=_m(Date.now()),f=Pm(c.weeklyResetAt),v=[{key:"daily",label:n("sidebar.account.menu.daily"),limit:Number(c.dailyLimit),rem:No(c.dailyLimit,c.dailyRemaining,c.dailyPercent),reset:n("ctx.limit.resetsIn",{h:Math.floor(p/36e5),m:Math.floor(p%36e5/6e4)})},{key:"weekly",label:n("sidebar.account.menu.weekly"),limit:Number(c.weeklyLimit),rem:No(c.weeklyLimit,c.weeklyRemaining,c.weeklyPercent),reset:f?n("ctx.limit.resetsAt",{when:Hl(f,{locale:s})}):""}].filter(w=>w.limit<0||w.rem!==null);return v.length?t.jsxs("span",{className:"t2c-cu-limits",children:[t.jsxs("span",{className:"t2c-cu-limits-title",children:[n("ctx.limit.title"),t.jsx(Lm,{tier:r})]}),v.map(w=>t.jsxs("span",{className:"t2c-cu-limit","data-limit":w.key,children:[t.jsxs("span",{className:"t2c-cu-limit-line",children:[t.jsx("span",{className:"t2c-cu-limit-name",children:w.label}),w.rem!==null&&t.jsx("span",{className:"t2c-cu-limit-reset",children:w.reset}),t.jsx("span",{children:w.rem===null?n("sidebar.account.menu.unlimited"):n("ctx.limit.used",{pct:Math.round(100-w.rem)})})]}),w.rem!==null&&t.jsx("span",{className:"t2c-cu-bar","data-warn":w.rem<=15||void 0,"aria-hidden":"true",children:t.jsx("span",{style:{width:`${100-w.rem}%`}})})]},w.key))]}):null}je({"input.fileref.noteApps":{zh:"引用窗口 / 应用 / 笔记 / 文件 / 会话",en:"Reference a window / app / note / file / session"},"input.refcat.label":{zh:"引用分类",en:"Reference categories"},"input.refcat.all":{zh:"全部",en:"All"},"input.refcat.window":{zh:"窗口",en:"Windows"},"input.refcat.app":{zh:"应用",en:"Apps"},"input.refcat.note":{zh:"笔记",en:"Notes"},"input.refcat.file":{zh:"文件",en:"Files"},"input.refcat.session":{zh:"会话",en:"Sessions"},"input.ref.windowOf":{zh:"{app} 的窗口",en:"{app} window"},"input.ref.appRunning":{zh:"应用 · 正在运行",en:"App · Running"},"input.ref.appIdle":{zh:"应用 · 没在运行",en:"App · Not running"},"input.ref.shiftInline":{zh:"按住 Shift 点击:插到光标处",en:"Shift-click to insert at the cursor"},"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.cloudOnly":{zh:"这个会话在你的电脑上,语音通话暂时只能在云端的会话里用",en:"This session lives on your computer. For now, voice calls only work in cloud sessions"},"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"}});je({"input.modeSheetTitle":{zh:"模式",en:"Mode"},"input.hubSheetTitle":{zh:"模型与模式",en:"Model and mode"},"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"},"input.planModeTeamOff":{zh:"团队模式下不可用",en:"Not available in team mode"},"composer2.exportRoleUser":{zh:"我",en:"Me"},"composer2.listSep":{zh:"、",en:", "}});const Um=8e3,Wm=[],li="input.tip.steer",rr=[li,"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"],Bm=[li,"input.tip.wikiRef"];je({"input.quote.group":{zh:"引用",en:"Quotes"},"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. You can quote several passages"},"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 hs=5*1024*1024,cr=15e4,ka=25*1024*1024,wa=[{id:"readonly",Icon:Sd,key:"input.approval.readonly",desc:"input.approval.readonlyDesc"},{id:"auto-edit",Icon:Gl,key:"input.approval.autoEdit",desc:"input.approval.autoEditDesc"},{id:"full-auto",Icon:Sa,key:"input.approval.fullAuto",desc:"input.approval.fullAutoDesc",danger:!0},{id:"custom",Icon:Rr,key:"input.approval.custom",desc:"input.approval.customDesc"}],Kn=e=>e.split(/[\\/]/).pop()||e,qm=".t2-chat-view";function Hm(e,n,s){const i=e.closest(qm)??e,o=v=>Array.from(v.dataTransfer?.types??[]).includes("Files"),r=v=>{i===e?s(v):i.toggleAttribute("data-filedrop",v)},c=v=>{o(v)&&(v.preventDefault(),v.dataTransfer&&(v.dataTransfer.dropEffect="copy"),r(!0))},u=v=>{i.contains(v.relatedTarget)||r(!1)},l=v=>{o(v)&&(v.preventDefault(),r(!1),v.dataTransfer?.files?.length&&n(v.dataTransfer.files))},p=i.ownerDocument?.defaultView,f=()=>r(!1);return i.addEventListener("dragover",c),i.addEventListener("dragleave",u),i.addEventListener("drop",l),p?.addEventListener("dragend",f),p?.addEventListener("drop",f,!0),p?.addEventListener("blur",f),()=>{i.removeEventListener("dragover",c),i.removeEventListener("dragleave",u),i.removeEventListener("drop",l),p?.removeEventListener("dragend",f),p?.removeEventListener("drop",f,!0),p?.removeEventListener("blur",f),r(!1)}}const Vt=e=>({token:/\s/.test(e)?`"${e}"`:e,name:Kn(e),kind:"file"}),Vm=e=>({token:/\s/.test(e)?`"${e}"`:e,name:Kn(e),kind:"folder"}),Km=(e,n)=>{const s=i=>String(i).replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;");return{token:`<forsion-view type="${s(e)}" title="${s(n)}" />`,name:n,kind:"view"}},Ym=e=>{const n=s=>String(s).replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\n/g," ");return{token:`<forsion-app app="${n(e.app)}" bundleId="${n(e.bundleId||"")}" pid="${e.pid}" windowId="${e.windowId}" title="${n(e.title)}" />`,name:e.app,kind:"app"}},Va=e=>({token:Sr(e),name:e.name,kind:e.kind,appRef:e}),Xm=e=>e.kind!=="view"&&(e.kind!=="app"||!!e.appRef);function Gm(e){const n=new Map;for(const s of e)s.run&&!n.has(s.run)&&n.set(s.run,s);return n}function Jm(e,n){if(e.kind!=="file")return e.token;const s=e.token.replace(/^"(.*)"$/,"$1"),i=/^(~?\/|[A-Za-z]:[\\/])/.test(s)?s:n?`${n.replace(/[\\/]+$/,"")}/${s}`:"";return i&&!/[[\]|#\n]/.test(i)?`[[${i}|${e.name.replace(/[[\]|]+/g," ")}]]`:e.token}function xa(e,n){if(e.kind==="app"||e.kind==="window")return Va(e);const s=Tr(e,n).trim();return e.kind==="session"?{token:s,name:e.title||"Chat",kind:"session"}:e.kind==="note"?{token:s,name:Kn(e.path),kind:"note"}:Vt(e.path)}function Qm(e,n,s,i){if(s){if(n>=e.length)return null;const r=n+1;return{pos:r,val:e[e.length-r]}}if(n===0)return null;const o=n-1;return{pos:o,val:o===0?i:e[e.length-o]}}function Zm(e,n,s){return/^\/refine(\s|$)/i.test(s)&&(s="/refine"+s.slice(7)),/^\/refine(\s|$)/.test(s)&&(e||n)?`${s}
24
+
25
+ ${e}${n}`.trimEnd():e+n+s}function ef(e,n=200){return e>0?`${Math.min(e,n)}px`:"auto"}function tf(e,n){const s=/(?:^|\s)(\/\S*)$/.exec(e.slice(0,n));return s?{start:n-s[1].length,token:s[1]}:null}const Kh=({sessionId:e,advisory:n,approvalTray:s,autoFocus:i,disabled:o,disabledPlaceholder:r,running:c,execConfig:u,teamApproval:l,models:p,modelsResponse:f,modelId:v,onModelChange:w,engines:E,engineId:A,engineModels:z,engineModelId:b,onEngineModelChange:$,engineCommands:D,thinkingLevel:L,onThinkingChange:U,ultra:K,defaultModelIds:R,onDefaultModelChange:x,onContextWindowChange:O,maxIterations:J,onMaxIterationsChange:ee,verifyCommand:Q,onVerifyCommandChange:H,preset:C,onPresetChange:_,planMode:q,onPlanModeChange:Z,voiceMode:oe,onVoiceModeChange:re,liveOwner:g,liveSessionKey:P,prepareLiveSession:G,skills:he,groupChat:we,groupAgents:Ce,groupTempAgents:de,onGroupChange:xe,onAddAgent:Ie,onNormalWork:B,agents:ne,onAgentSwitch:se,currentAgentSlug:ye,mentionProjects:Le,onNewSession:te,onBranch:Me,onOpenSettings:He,onExecConfigChange:Je,onSend:Qt,onStop:Ze,quotes:k=Wm,onRemoveQuote:V,onClearQuote:W,onBtw:ze,contextWindow:_e,ctxTokens:De,sessionTokens:it,runCost:Ke,costLimit:Pe,ctxInfo:fe,onCompact:ot,seedText:h,onSeedConsumed:F,seedShare:j,takeSeedShare:X,appendRefs:ce,onAppendRefsConsumed:le,autoRefFromMain:Ve,appRef:rt,sentHistory:$t,pendingSteer:ft,onCancelSteer:ge,onWithdrawSteer:xt,onSteerNow:di})=>{const{t:N,locale:Ds}=Ee(),Sc=I(a=>a.activeId),Se=e===void 0?Sc:e,Nc=d.useId(),Ye=e===void 0?`preview:${Nc}`:e??sr,_s=d.useRef(Ye);_s.current=Ye;const[ue,ve]=Rt(Ye,"text"),[pi,mi]=d.useState(0),[Ps]=d.useState(()=>!!window.tangu?.mobile||!!window.matchMedia?.("(hover: none)").matches),fi=(Ps?Bm:rr).filter(a=>!A||a!==li),[Cc,Os]=d.useState(!1),[Dt,zc]=d.useState(!1),[Fs,hi]=d.useState(!1);d.useEffect(()=>{if(!c||Dt)return;mi(Math.floor(Math.random()*rr.length));let a=0;const m=window.setInterval(()=>{Os(!0),a=window.setTimeout(()=>{mi(y=>y+1),Os(!1)},300)},Um);return()=>{window.clearInterval(m),window.clearTimeout(a),Os(!1),hi(!1)}},[c,Dt]);const[Us,Ec]=d.useState([]),[Zt,ts]=Rt(Ye,"attachments"),[en,Ws]=Rt(Ye,"wsFiles"),[ht,gi]=Rt(Ye,"refChips"),[Bs,Mc]=d.useState(null),_t=a=>gi(m=>{const y=[...m];let S=!1;for(const M of a){const T=y.findIndex(Y=>Y.token===M.token);T===-1?(y.push(M),S=!0):M.run&&!y[T].run&&(y[T]={...y[T],run:M.run},S=!0)}return S?y:m}),[tn,vi]=Rt(Ye,"pinnedSkills"),[yi,Oe]=d.useState(null),[ki,Qe]=d.useState(0),[Sn,Nn]=d.useState(null),[wi,xi]=d.useState(!1),bi=d.useRef(null),[Fe,et]=d.useState(null),[Ac,Cn]=d.useState(!1),[Xe,gt]=d.useState(0),[ji,ns]=d.useState(0),[Si,Ni]=d.useState(!1),[Rc,Ci]=Rt(Ye,"mentionedSlug"),[zi,Ei]=Rt(Ye,"mentionAgents"),[Mi,ss]=d.useState(0),[Ai,Ri]=d.useState(!1),[Ti,Ii]=d.useState(null),[Li,qs]=d.useState("all"),[as,Tc]=d.useState(null),Hs=d.useRef(""),[Ic,Lc]=d.useState(!1),[Pt,nn]=d.useState(0),Vs=d.useRef(""),$i=d.useRef(Pt);$i.current=Pt,d.useLayoutEffect(()=>(nn(0),gt(0),Nn(null),()=>{$i.current>0&&Ha(Ye,"text",Vs.current)}),[Ye]);const Ne=d.useRef(null),bt=d.useRef(null);d.useLayoutEffect(()=>{const a=bt.current;if(!a)return;const m=new ResizeObserver(([y])=>zc(y.contentRect.width<=360));return m.observe(a),()=>m.disconnect()},[]);const zn=d.useMemo(()=>{const a=new Map(Qo("desktop").map(m=>[m.name,m]));return m=>{const y=a.get(m);return y?Ds==="en"?y.en:y.zh:m}},[Ds]);d.useEffect(()=>{let a=!0;return Vl(kt()).then(m=>{a&&Ec(m)}),()=>{a=!1}},[]);const $c=async()=>{const a=I.getState(),m=Se,M=([...m?a.messagesBySession[m]||[]:[]].reverse().find(T=>T.role==="assistant")?.content||"").trim();if(!M){a.toast(N("input.slash.nothingToCopy"),!0);return}try{await navigator.clipboard.writeText(M),a.toast(N("input.slash.copied"))}catch{a.toast(N("input.slash.nothingToCopy"),!0)}},Dc=async()=>{const a=I.getState(),m=Se;if(![...m?a.messagesBySession[m]||[]:[]].reverse().find(M=>M.role==="user")){a.toast(N("input.slash.nothingToRetry"),!0);return}await a.retry(m)},_c=async()=>{const a=I.getState(),m=Se;if(!m){a.toast(N("input.slash.nothingToExport"),!0);return}const y=a.sessions.find(be=>be.id===m);let S=[];try{S=(await cu(zo(m),m)).messages}catch{}if(S.length||(S=a.messagesBySession[m]||[]),!S.length){a.toast(N("input.slash.nothingToExport"),!0);return}const M=y?.title||"Tangu Session",T=["---",`id: ${m}`,`title: ${JSON.stringify(M)}`,...y?.summary?[`summary: ${JSON.stringify(y.summary)}`]:[],...y?.model_id?[`model: ${y.model_id}`]:[],`exported_at: ${new Date().toISOString()}`,"---","",`# ${M}`,""];for(const be of S){const Re=be.role==="model"?"assistant":be.role;if(Re!=="user"&&Re!=="assistant")continue;const At=(be.content||"").trim(),_n=Array.isArray(be.tool_calls)?be.tool_calls:[];if(!At&&!_n.length)continue;T.push(Re==="user"?`## ${N("composer2.exportRoleUser")}`:"## Tangu",""),At&&T.push(At,"");for(const Ht of _n){const un=Ht?.function?.name||Ht?.name||"tool";let tt="";try{tt=String(typeof Ht?.function?.arguments=="string"?Ht.function.arguments:JSON.stringify(Ht?.function?.arguments??""))}catch{tt=""}tt=tt.replace(/\s+/g," ").trim(),T.push(`> 🔧 \`${un}\`${tt&&tt!=="{}"?` ${tt.length>200?tt.slice(0,200)+"…":tt}`:""}`)}_n.length&&T.push("");const Pn=Array.isArray(be.attachments)?be.attachments:[];Pn.length&&T.push(`> 📎 ${Pn.length} attachment(s)`,"")}const Y=new Blob([T.join(`
26
+ `)],{type:"text/markdown"}),ie=document.createElement("a");ie.href=URL.createObjectURL(Y),ie.download=`tangu-${String(m).slice(0,8)}.md`,ie.click(),setTimeout(()=>URL.revokeObjectURL(ie.href),1e3)},ke=lp(a=>{ve(m=>m?nr(m)+" "+a:a),nn(0),requestAnimationFrame(pe)}),Di=ke.recording||ke.busy,Ks=d.useRef(!1),Pc=()=>{Ks.current=!0,ke.toggle()};d.useEffect(()=>{!Ks.current||ke.recording||ke.busy||(Ks.current=!1,ue.trim()&&os())},[ke.recording,ke.busy]);const _i=Ls(Se),is=g??e===null,Pi=jp(),Oi=I(a=>a.modelsResp?.realtimeModel??null),Fi=I(a=>!!a.authInfo?.loggedIn&&a.authInfo.tokenValid!==!1)&&!!window.tangu?.forsionLogin,{model:Ui,voice:Oc}=d.useMemo(()=>vp(Pi,{model:Oi,signedIn:Fi}),[Pi,Oi,Fi]),[Ys,Wi]=d.useState(!1),[Bi,qi]=d.useState(""),Hi=!!window.tangu?.mobile,Fc=d.useSyncExternalStore(zp,Qr),En=!!Se&&Fc===Se,Xs=Kl(a=>(e?a.bySession[e]:void 0)||""),Gs=!!Xs&&!ue&&!c&&!o&&!En&&!Ps;d.useEffect(()=>{if(is)return Zr(a=>{if(a.kind==="activity"){I.getState().pollSession(a.sessionId);return}if(a.kind==="transcript"){const m=()=>{const M=I.getState().messagesBySession[a.sessionId]?.find(T=>T.id===a.messageId);return M?(M.content!==a.text&&I.setState(T=>({messagesBySession:{...T.messagesBySession,[a.sessionId]:(T.messagesBySession[a.sessionId]||[]).map(Y=>Y.id===a.messageId?{...Y,content:a.text}:Y)}})),!0):!1};if(m())return;const y=I.subscribe(()=>{m()&&(y(),clearTimeout(S))}),S=setTimeout(y,3e4);return}a.kind==="effort"&&I.setState(m=>m.configBySession[a.sessionId]?{configBySession:{...m.configBySession,[a.sessionId]:{...m.configBySession[a.sessionId],thinkingLevel:a.level,...a.level!=="max"?{ultra:void 0}:{}}}}:{})})},[is]);const Uc=async()=>{if(!Ys){Wi(!0),qi("");try{let a=P!==void 0?P:Se;if(!a){const T=I.getState().activeId;a=G?await G():await I.getState().newSession().then(()=>I.getState().activeId),a===T&&(a=null)}if(!a)return;if(zo(a).key!=="home"){qi(N(Hi?"livecall.cloudOnly":"livecall.localOnly"));return}const{modelId:y,agentConfig:S}=I.getState().voiceRunParams(a),M={type:"voice-call",params:{sessionId:a,model:Ui,voice:Oc,title:N("livecall.title"),agentSlug:S.agentSlug,run:{model_id:y,agent_config:S}}};window.tangu?.openMini?window.tangu.openMini({view:M,mainView:{type:"chat",params:{sessionId:a}},title:N("livecall.title")}):Np(M.params)}finally{Wi(!1)}}},Ue=u.execMode==="host",ct=Ue&&_i.kind==="home",Ae=C==="chat",Mn=A?void 0:ne?.find(a=>a.slug===ye),An=u.approvalMode||Mn?.approvalMode||"auto-edit",Ot=L||(we?void 0:Mn?.thinkingLevel)||void 0,jt=Ue&&!Ae&&!A&&!we,sn=jt&&!!K&&Ot==="max",{window:Ft,stale:Wc}=hd({ctxInfo:fe,contextWindow:_e,running:c,ultra:sn,model:f?.models.find(a=>a.id===v),engineUncapped:f?.ultraUncapped}),Js=Wc&&fe?{...fe,ctxWindow:Ft||fe.ctxWindow,compactAt:void 0}:fe,[Bc,Vi]=d.useState(!1),Rn=(a,m)=>U?m===!0&&!sn&&!Bp()?(Vi(!0),!1):(U(a,m),!0):!1,Ki=Xt(Fe==="mode",{boundary:".t2-chat-view"}),Yi=Xt(Fe==="ctx",{boundary:".t2-chat-view"});d.useEffect(()=>{if(!Fe)return;const a=y=>{y.target?.closest?.("[data-cmenu], [data-keep-menus]")||et(null)},m=y=>{y.key==="Escape"&&!document.querySelector("[data-keep-menus]")&&et(null)};return document.addEventListener("mousedown",a),document.addEventListener("keydown",m),()=>{document.removeEventListener("mousedown",a),document.removeEventListener("keydown",m)}},[Fe]);const pe=()=>{const a=Ne.current;if(a){if(!a.value){a.style.height="";return}a.style.height="auto",a.style.height=ef(a.scrollHeight)}};d.useEffect(()=>{const a=Ne.current;if(!a||typeof ResizeObserver>"u")return;let m=a.clientWidth;const y=new ResizeObserver(()=>{a.clientWidth!==m&&(m=a.clientWidth,pe())});return y.observe(a),()=>y.disconnect()},[]),d.useLayoutEffect(pe,[ue]),d.useLayoutEffect(()=>{const a=Ne.current;c&&!Dt&&!Fs&&a&&!a.value&&a.scrollHeight>a.clientHeight+2&&hi(!0)},[c,pi,Ds,Fs,ue,Dt]);const Xi=a=>{a&&Pt===0&&(Vs.current=ue);const m=Qm($t||[],Pt,a,Vs.current);m&&(nn(m.pos),ve(m.val),requestAnimationFrame(()=>{const y=Ne.current;y&&(y.focus(),y.selectionStart=y.selectionEnd=m.val.length,gt(m.val.length)),pe()}))};d.useEffect(()=>{h&&(ve(h),F?.(),requestAnimationFrame(()=>{Ne.current?.focus(),pe()}))},[h]),d.useEffect(()=>{k.length&&requestAnimationFrame(()=>Ne.current?.focus())},[k.length]),d.useEffect(()=>{ce?.refs.length&&(_t(ce.refs.map(a=>xa(a,zt||""))),le?.(),requestAnimationFrame(()=>{Ne.current?.focus(),pe()}))},[ce?.seq]);const lt=a=>{const m=bi.current,y=m?.start??0,S=m?.end??1/0;ve(T=>T.slice(0,y)+a+T.slice(S));const M=y+a.length;return requestAnimationFrame(()=>{const T=Ne.current;T&&(!I.getState().feedbackOpen&&!document.querySelector("[data-keep-menus]")&&T.focus(),T.selectionStart=T.selectionEnd=M,gt(M)),pe()}),y},Gi=d.useMemo(()=>{const a=()=>{lt(""),Nn(null)},m=I.getState,y={"/stop":c?()=>{Ze(),a()}:void 0,"/new":te?()=>{te(),a()}:void 0,"/branch":Me?()=>{Me(),a()}:void 0,"/compact":ot?()=>{ot(),a()}:void 0,"/plan":Z&&!Ae?()=>{Z(!q),a()}:void 0,"/chat":_?()=>{_("chat"),a()}:()=>{m().toast(N("input.presetLocked")),a()},"/work":_?()=>{_("work"),a()}:()=>{m().toast(N("input.presetLocked")),a()},"/voice":re?()=>{re(!oe),a()}:void 0,"/model":w&&p?.length?()=>{Nn({start:lt("/model ")}),Qe(0)}:void 0,"/loop":ee?()=>{lt("/loop "),Qe(0)}:void 0,"/verify":Ue&&H?()=>{lt("/verify "),Qe(0)}:void 0,"/think":U?()=>{lt("/think"),Qe(0)}:void 0,"/refine":Ue?()=>{lt("/refine "),Qe(0)}:void 0,"/approval":()=>{et("mode"),a()},"/help":()=>{m().openSettings("about"),a()},"/feedback":window.tangu?.submitFeedback?()=>{m().openFeedback()&&a()}:void 0,"/btw":ze?()=>{lt("/btw "),Qe(0)}:void 0,"/skills":()=>{m().openSettings("skills"),a()},"/tools":()=>{m().openSettings("agents"),a()},"/agents":()=>{m().openSettings("agents"),a()},"/agent":()=>{m().openSettings("agents"),a()},"/mcp":()=>{m().openSettings("mcp"),a()},"/plugins":()=>{m().openSettings("plugins"),a()},"/memory":()=>{m().openSettings("forsion/f-sync"),a()},"/config":()=>{m().openSettings("general"),a()},"/login":window.tangu?.forsionLogin?()=>{m().openSettings("forsion"),a()}:void 0,"/historian":()=>{m().setActiveSpecial("agents"),a()},"/muse":()=>{m().setActiveSpecial("agents"),a()},"/groupchat":xe&&!Ae?()=>{Cn(!0),a()}:void 0,"/sessions":()=>{m().setActiveId(null),a()},"/cost":()=>{m().pushNotice(`${(it??0).toLocaleString()} tokens · ${N("input.ctxLabel")} ${(De??0).toLocaleString()}/${(Ft??0).toLocaleString()}`+(Ke!=null&&Pe!=null&&Pe>0?` · ${N("input.runCost",{used:Math.round(Ke).toLocaleString(),limit:Pe.toLocaleString()})}`:"")),a()},"/status":()=>{m().pushNotice([`${N("input.slash.status")}`,`model=${v||"-"}`,`think=${Ot||"medium"}${fe?.thinkingRequested===(Ot||"medium")&&fe.thinkingEffective&&fe.thinkingEffective!==fe.thinkingRequested?`→${fe.thinkingEffective}`:""}`,`approval=${u.approvalMode||Mn?.approvalMode||(u.execMode==="host"?"auto-edit":"full-auto")} (${u.approvalMode?"session":Mn?.approvalMode?"agent":"default"})`,`cwd=${u.cwd||"-"}`,`loop=${J||fe?.maxIterations||90} (${J?"session":fe?.maxIterationsSource||"default"})`,`verify=${Q||"-"}`,`tokens=${(it??0).toLocaleString()}`,`cost=${Ke!=null?Math.round(Ke).toLocaleString():"-"}${Pe!=null&&Pe>0?`/${Pe.toLocaleString()}`:""}`].join(`
27
+ `)),a()},"/copy":()=>{$c(),a()},"/retry":()=>{Dc(),a()},"/export":()=>{_c(),a()}},S=[];if(c){const M=y["/stop"];M&&S.push({cmd:"/stop",desc:zn("/stop"),run:M})}if(A){te&&S.push({cmd:"/new",desc:zn("/new"),run:()=>{te(),a()}}),y["/feedback"]&&S.push({cmd:"/feedback",desc:zn("/feedback"),run:y["/feedback"]});for(const M of D||[])M.name.replace(/^\//,"").toLowerCase()==="feedback"&&y["/feedback"]||S.push({cmd:`/${M.name}`,desc:M.hint?`${M.description} · ${M.hint}`:M.description,run:()=>{lt(`/${M.name} `),Qe(0)}});return S}if(U){const M=A?void 0:p?.find(T=>T.id===v)?.thinkingLevels;for(const T of ks){const Y=!!M&&!M.includes(T);S.push({cmd:`/think ${T}`,desc:`${N("input.slash.thinkDesc",{level:Aa(T,N)})}${Y?` ${N("pill.thinkUnsupported")}`:""}${!sn&&Ot===T?N("input.slash.current"):""}`,run:()=>{Rn(T,jt?!1:void 0),a()}})}jt&&S.push({cmd:"/think ultra",desc:`${N("pill.ultraTitle")}${sn?N("input.slash.current"):""}`,run:()=>{Rn("max",!0),a()}})}for(const M of Qo("desktop")){if(M.name==="/stop")continue;const T=y[M.name];T&&S.push({cmd:M.arg?`${M.name} ${M.arg}`:M.name,desc:zn(M.name),run:T})}for(const M of Us)S.push({cmd:M.argHint?`/${M.name} ${M.argHint}`:`/${M.name}`,desc:M.description,run:()=>{lt(`/${M.name} `),Qe(0)}});if(he?.length)for(const M of he)S.push({cmd:`/skill:${M.id}`,desc:N("input.slash.skillUse",{name:M.name}),run:()=>{vi(T=>T.some(Y=>Y.id===M.id)?T:[...T,M]),a()}});return S},[c,Ze,q,oe,re,Ot,J,ee,Q,H,p,v,he,Z,U,w,te,Me,ot,xe,Ae,_,A,D,Us,zn,u,Mn,it,De,Ft,Ke,Pe,fe,!!ze,jt,sn]),ut=d.useMemo(()=>{if(o||wi)return null;const a=ue.slice(0,Xe);if(Sn&&a.startsWith("/model ",Sn.start))return{start:Sn.start,token:a.slice(Sn.start),sub:"model"};const m=tf(ue,Xe);return m?{...m,sub:null}:null},[ue,Xe,o,wi,Sn]);bi.current=ut?{start:ut.start,end:Xe}:null;const St=d.useMemo(()=>{if(!ut)return[];if(ut.sub==="model"){const y=ut.token.slice(7).toLowerCase();return(p||[]).filter(S=>!y||S.id.toLowerCase().includes(y)||S.name.toLowerCase().includes(y)).slice(0,12).map(S=>({cmd:S.id===v?`● ${S.name}`:S.name,desc:`${S.source==="direct"?N("input.directPrefix"):""}${S.provider} · ${S.id}`,run:()=>{w?.(S.id),lt(""),Nn(null)}}))}const a=ut.token.toLowerCase(),m=a.startsWith("/th");return Gi.filter(y=>(m||!y.cmd.startsWith("/think "))&&(y.cmd.toLowerCase().startsWith(a)||a.length>1&&y.desc.toLowerCase().includes(a.slice(1)))).slice(0,10)},[ut,Gi,p,v]),an=!!ut&&St.length>0;d.useEffect(()=>{Qe(0)},[ut?.start,ut?.token]);const Tn=!!we&&(Ce?.length||0)>=2,[qc,Hc]=Rt(Ye,"mentionedProjects"),In=!!Le?.length,Ji=d.useMemo(()=>{if(In)return(Le||[]).map(y=>({slug:y.path,name:y.name,description:y.path}));if(!Tn)return ne||[];const a=(ne||[]).filter(y=>Ce.includes(y.slug)),m=new Set(a.map(y=>y.slug));return[...a,...(de||[]).filter(y=>!m.has(y.slug))]},[Tn,ne,Ce,de,In,Le]),Nt=d.useMemo(()=>{if(o||an||Si)return null;const a=/(?:^|\s)@([^\s@]*)$/.exec(ue.slice(0,Xe));return a?{query:a[1],start:Xe-a[1].length-1}:null},[ue,Xe,o,an,Si]),Ct=d.useMemo(()=>{if(!Nt)return[];const a=Nt.query.toLowerCase();return Ji.filter(m=>!a||m.name.toLowerCase().includes(a)||m.slug.toLowerCase().includes(a)).slice(0,10)},[Nt,Ji]),Qi=!!Nt&&Ct.length>0;d.useEffect(()=>{ns(0)},[Nt?.start,Nt?.query]);const Zi=a=>{if(!Nt)return;const m=ue.slice(0,Nt.start),y=`@${a.name} `,S=m+y+ue.slice(Xe);ve(S),In?Hc(T=>T.some(Y=>Y.path===a.slug)?T:[...T,{name:a.name,path:a.slug}]):Tn?Ci(a.slug):Ei(T=>T.includes(a.slug)?T:[...T,a.slug]);const M=m.length+y.length;requestAnimationFrame(()=>{const T=Ne.current;T&&(T.focus(),T.selectionStart=T.selectionEnd=M,gt(M)),pe()})},We=d.useMemo(()=>{if(o||an||Ai)return null;const a=/\[\[([^\]\n]*)$/.exec(ue.slice(0,Xe));return a?{query:a[1],start:Xe-a[1].length-2}:null},[ue,Xe,o,an,Ai]),eo=!!We;d.useEffect(()=>{if(!eo){qs("all");return}let a=!0;return window.tangu?.appRefs?.list().then(m=>{a&&Tc(m)},()=>{}),()=>{a=!1}},[eo]),d.useEffect(()=>{if(!We||!ct)return;window.amadeus&&Yl();const a=u.cwd;if(!a||Hs.current===a)return;Hs.current=a,Ii(null);const m=new Set(["node_modules","dist","build","out","target",".git",".venv","venv","__pycache__"]);(async()=>{const S=[],M=[{dir:a,rel:"",depth:0}];for(;M.length&&S.length<2e3;){const{dir:T,rel:Y,depth:ie}=M.shift();let be=[];try{be=await window.tangu?.listDir?.(T)||[]}catch{continue}for(const Re of be)if(!Re.name.startsWith(".")){if(Re.isDir)ie<8&&!m.has(Re.name)&&M.push({dir:Re.path,rel:Y?`${Y}/${Re.name}`:Re.name,depth:ie+1});else if(S.push(Y?`${Y}/${Re.name}`:Re.name),S.length>=2e3)break}}return S})().then(S=>{Hs.current===a&&Ii(S)}).catch(()=>{})},[We,u.cwd,ct]);const to=qn(a=>a.pages),zt=qn(a=>a.vaultRoot),no=qn(a=>a.icons),so=I(a=>a.sessions),on=To(a=>a.pendingPrompt),Ut=Lo(a=>a.pending);d.useEffect(()=>{!Ut||Ut.sessionId!==Se||!bt.current?.closest("[data-image-studio-chat]")||!bt.current.getClientRects().length||Lo.getState().consume(Ut.seq)&&(ve(a=>a.trim()?`${a}
28
+
29
+ ${Ut.text}`:Ut.text),ts(a=>[...a,...Ut.attachments]),requestAnimationFrame(()=>{Ne.current?.focus(),pe()}))},[Ut,Se]);const ao=Yo(a=>a.pending);d.useEffect(()=>{if(!Se||!ao.some(m=>m.sessionId===Se)||!bt.current?.closest("[data-plugin-chat]"))return;const a=Yo.getState().take(Se);a.length&&(ve(m=>[...m.trim()?[m]:[],...a].join(`
30
+
31
+ `)),requestAnimationFrame(()=>{Ne.current?.focus(),pe()}))},[ao,Se]),d.useEffect(()=>{if(!on||!bt.current?.getClientRects().length)return;const a=I.getState(),m=Se?a.sessions.find(y=>y.id===Se)?.project_path:a.newChatWs?.path;Io(m||"")!==Io(on.project)||!To.getState().consumePrompt(on.seq)||(ve(y=>y.trim()?`${y}
32
+
33
+ ${on.text}`:on.text),requestAnimationFrame(()=>{Ne.current?.focus(),pe()}))},[on,Se]);const rn=d.useMemo(()=>We?[...(as?.windows??[]).map(a=>({p:a.title,app:{kind:"window",id:a.id,name:a.title},desc:N("input.ref.windowOf",{app:a.app})})),...(as?.apps??[]).map(a=>({p:a.name,app:{kind:"app",id:a.id,name:a.name},desc:N(a.running?"input.ref.appRunning":"input.ref.appIdle")})),...ct?to.map(a=>({p:a,note:!0})):[],...ct?(Ti??[]).map(a=>({p:a})):[],...so.filter(a=>a.id!==Se).slice(0,300).map(a=>({p:yt(a.title,N),session:{id:a.id,title:yt(a.title,N),summary:a.summary}}))]:[],[We,as,Ti,to,so,Se,ct,N]),cn=d.useMemo(()=>vm(rn),[rn]),Et=cn.includes(Li)?Li:"all",Wt=d.useMemo(()=>We?tr(rn,We.query,Et):[],[We,rn,Et]),Ln=d.useMemo(()=>!!We&&(Wt.length>0||tr(rn,We.query,"all").length>0),[We,rn,Wt]),Vc=jd(Ln?Et:"",Ln?cn.join():"");d.useEffect(()=>{ss(0)},[We?.start,We?.query,Et]);const io=a=>{if(!We)return;if(a.app){Qs({...Va(a.app),inline:!0},We.start,Xe);return}const m=(a.session?Tr({kind:"session",id:a.session.id,title:a.session.title},zt||""):a.note&&zt?ou(zt,a.p):/\s/.test(a.p)?`"${a.p}"`:a.p).trim();Qs({token:m,name:a.session?a.session.title:Kn(a.p),kind:a.session?"session":a.note?"note":"file",inline:!0},We.start,Xe)},oo=qn(a=>a.activePage??a.activeNotePath),ln=xs(a=>nm(a.mainTabs)),$n=d.useMemo(()=>{if(rt){const y=Ym(rt);return Bs===y.token||ht.some(S=>S.token===y.token)?null:y}if(!ct||!Ve||!ln)return null;const a=ln==="note"?oo:ln.startsWith("note:")?ln.slice(5):"",m=a?zt?xa({kind:"note",path:a},zt):null:Vt(ln.slice(5));return!m||Bs===m.token||ht.some(y=>y.token===m.token)?null:m},[rt,ct,Ve,ln,oo,zt,Bs,ht]),ro=d.useMemo(()=>$n?[$n,...ht]:ht,[$n,ht]),Bt=d.useMemo(()=>Gm(ht),[ht]),Dn=d.useMemo(()=>bm(ue,a=>Bt.has(a)),[ue,Bt]),Mt=d.useMemo(()=>{const a=new Set(Dn.map(m=>Bt.get(m.name).token));return ro.filter(m=>!m.inline||a.has(m.token))},[ro,Dn,Bt]),co=(a,m,y)=>{const S=Ne.current;if(!S){ve(ue.slice(0,a)+y+ue.slice(m));return}S.focus(),S.setRangeText(y,a,m,"end"),ve(S.value),gt(a+y.length),requestAnimationFrame(pe)},Qs=(a,m,y,S=!1)=>{const M=ht.find(T=>T.token===a.token)?.run||wm(a.name,T=>Bt.has(T));_t([M?{...a,run:M}:{token:a.token,name:a.name,kind:a.kind,appRef:a.appRef}]),(M||!S)&&co(m,y,M?xm(M)+" ":"")},Kc=(a,m)=>co(a,m,""),lo=a=>{const m=a==null?Sm(ue,ae=>{const Ge=Bt.get(ae);return Ge&&Jm(Ge,Ue?u.cwd:void 0)}):null,y=(a??m.text).trim(),S=a==null?y:"",M=/^\/feedback(?:\s+([\s\S]*))?$/i.exec(S);if(M&&window.tangu?.submitFeedback){I.getState().openFeedback(M[1]?.trim())&&(ve(""),requestAnimationFrame(pe));return}const T=/^\/(?:btw|side)(?:\s+([\s\S]*))?$/i.exec(S);if(T&&ze){ze(T[1]?.trim()||void 0,k.join(`
34
+
35
+ `)||void 0),k.length&&W?.(),ve(""),requestAnimationFrame(pe);return}if(!y&&!Mt.length)return;const Y=/^\/compact(?:\s+([\s\S]+))?$/i.exec(S);if(Y&&ot){ot((Y[1]||"").trim()||void 0),ve(""),requestAnimationFrame(pe);return}const ie=/^\/loop(?:\s+(\d+))?$/i.exec(S);if(ie&&ee){if(ie[1]){const ae=Math.min(Math.max(1,parseInt(ie[1],10)),200);ee(ae),Oe(N("input.slash.loopSet",{n:ae}))}else Oe(N("input.slash.loop",{current:J||fe?.maxIterations||90}));ve(""),requestAnimationFrame(pe);return}const be=/^\/verify(?:\s+([\s\S]+))?$/i.exec(S);if(be&&Ue&&H){const ae=(be[1]||"").trim();ae?/^(off|clear|关闭)$/i.test(ae)?(H(""),Oe(N("input.slash.verifyCleared"))):(H(ae),Oe(N("input.slash.verifySet",{cmd:ae}))):Oe(N("input.slash.verifyUsage",{current:Q||N("input.slash.verifyNone")})),ve(""),requestAnimationFrame(pe);return}if(re&&/^\/(voice|text)$/i.test(S)){const ae=/^\/voice$/i.test(y);re(ae),Oe(N(ae?"input.slash.voiceOnHint":"input.slash.voiceOffHint")),ve(""),requestAnimationFrame(pe);return}const Re=/^\/(?:think|effort)(?:\s+(\S+))?$/i.exec(S);if(Re&&U){const ae=(Re[1]||"").toLowerCase();jt&&ae==="ultra"?Rn("max",!0)&&Oe(N("input.slash.thinkSet",{level:N("pill.ultra")})):ks.includes(ae)?(Rn(ae,jt?!1:void 0),Oe(N("input.slash.thinkSet",{level:Aa(ae,N)}))):Oe(N("input.slash.thinkUsage",{levels:[...ks,...jt?["ultra"]:[]].join("|")})),ve(""),requestAnimationFrame(pe);return}const At=/^\/([a-z0-9][a-z0-9-]*)(?:\s+([\s\S]*))?$/i.exec(S);if(At&&Us.some(ae=>ae.name===At[1].toLowerCase())){const ae=At[1].toLowerCase(),Ge=At[2]||"";ve(""),requestAnimationFrame(pe),au(kt(),ae,Ge).then(dn=>Qt(dn,[],[],void 0,void 0)).catch(dn=>Oe(String(dn?.message||dn)));return}if(o)return;if(En&&!a&&y&&y.length<=Ep&&!Zt.length&&!en.length&&!Mt.length&&!k.length&&!tn.length)return ve(""),nn(0),Oe(null),requestAnimationFrame(pe),Mp(Se,y).then(async ae=>{if(ae)return!0;const Ge=await Promise.resolve(lo(y)).catch(()=>!1)??!1;return Ge?Oe(N("livecall.textFallback")):ve(dn=>dn||y),Ge});const _n=Rm(k),Pn=Mt.filter(ae=>!(ae.run&&m?.used.has(ae.run))),Ht=Pn.length?Pn.map(ae=>ae.token).join(" ")+`
36
+ `:"",un=Zm(Ht,_n,y);if(un.length>cr){Oe(N("input.tooLong",{len:un.length.toLocaleString(),max:cr.toLocaleString()}));return}Oe(null);const tt=In?{mentionProjects:(()=>{const ae=qc.filter(Ge=>un.includes(`@${Ge.name}`));return ae.length?ae:void 0})()}:Tn?{priorityAgent:Rc||void 0}:{mentionAgents:zi.length?zi:void 0},ls=Ye,xo=ls===sr?new Set(I.getState().sessions.map(ae=>ae.id)):null;return Qt(un,Zt,en,tn.map(ae=>ae.id),tt).then(ae=>{if(!ae){const Ge=_s.current;return xo&&Ge!==ls&&!xo.has(Ge)&&Im(ls,Ge),!1}return Tm(ls,!!a),a||(nn(0),iu("tick")),W?.(),requestAnimationFrame(pe),!0})},os=()=>{lo()},uo=async a=>{if(!a)return;const m=[],y=[];for(const S of Array.from(a)){if(!S.type.startsWith("image/")){y.push(N("input.skip.notImage",{name:S.name}));continue}if(S.size>hs){y.push(N("input.skip.tooBig",{name:S.name,mb:String(Math.round(hs/1024/1024))}));continue}const M=await S.arrayBuffer();let T="";const Y=new Uint8Array(M);for(let ie=0;ie<Y.length;ie+=32768)T+=String.fromCharCode(...Y.subarray(ie,ie+32768));m.push({name:S.name,mimeType:S.type,data:btoa(T),size:S.size})}Oe(y.length?N("input.skip.imageHint",{items:y.join(N("composer2.listSep"))}):null),ts(S=>[...S,...m])},Zs=async a=>{if(!a)return;const m=[],y=[];for(const S of Array.from(a)){if(S.size>ka){y.push(N("input.skip.tooBig",{name:S.name,mb:String(Math.round(ka/1024/1024))}));continue}const M=await S.arrayBuffer();let T="";const Y=new Uint8Array(M);for(let ie=0;ie<Y.length;ie+=32768)T+=String.fromCharCode(...Y.subarray(ie,ie+32768));m.push({name:S.name,mimeType:S.type||"application/octet-stream",data:btoa(T),size:S.size})}Oe(y.length?N("input.skip.simple",{items:y.join(N("composer2.listSep"))}):null),Ws(S=>[...S,...m])},po=a=>{if(a.length){if(ct&&window.tangu?.getPathForFile){const m=Array.from(a).map(y=>{try{return window.tangu.getPathForFile(y)}catch{return""}}).filter(Boolean);if(m.length){_t(m.map(Vt)),requestAnimationFrame(()=>{Ne.current?.focus(),pe()});return}}Zs(a)}},mo=d.useRef(po);mo.current=po,d.useEffect(()=>{const a=bt.current;return a?Hm(a,m=>mo.current(m),Lc):void 0},[]);const fo=async a=>{if(!a?.length)return;const m=Array.from(a).filter(S=>S.type.startsWith("image/")),y=Array.from(a).filter(S=>!S.type.startsWith("image/"));if(m.length){const S=new DataTransfer;m.forEach(M=>S.items.add(M)),await uo(S.files)}if(y.length){const S=new DataTransfer;y.forEach(M=>S.items.add(M)),await Zs(S.files)}};d.useEffect(()=>{if(!j)return;const a=X?.();if(a&&(a.text&&(ve(m=>m.trim()?`${nr(m)}
37
+
38
+ ${a.text}`:a.text),requestAnimationFrame(()=>pe())),a.files.length)){const m=new DataTransfer;a.files.forEach(y=>m.items.add(y)),fo(m.files)}},[j]);const Yc=async a=>{const m=[],y=[],S=[];for(const M of a){if(M.isDirectory){S.push(Vm(M.path));continue}try{const T=await window.tangu?.readHostFile?.(M.path);if(!T||T.tooLarge){S.push(Vt(M.path));continue}const Y={name:Kn(M.path),mimeType:T.mimeType,data:T.content,size:T.size};T.mimeType.startsWith("image/")&&T.size<=hs?m.push(Y):T.size<=ka?y.push(Y):S.push(Vt(M.path))}catch{S.push(Vt(M.path))}}m.length&&ts(M=>[...M,...m]),y.length&&Ws(M=>[...M,...y]),S.length&&_t(S)};d.useEffect(()=>{const a=bt.current;if(!a||!window.tangu?.appRefs)return;Fp(),a.setAttribute(Wa,"");const m=y=>{const{ref:S,image:M}=y.detail,T=Va(S),Y=_s.current;_t([T]),requestAnimationFrame(()=>Ne.current?.focus()),M?.then(ie=>{const be=ie?Math.floor(ie.data.length*3/4):0;!ie||be>hs||!es.getState()[Y]?.refChips.some(Re=>Re.token===T.token)||Ha(Y,"attachments",Re=>[...Re,{name:`${S.name.replace(/[\\/:*?"<>|]+/g," ").trim().slice(0,80)||"window"}.jpg`,mimeType:ie.mimeType,data:ie.data,size:be}])})};return a.addEventListener(Ua,m),()=>{a.removeEventListener(Ua,m),a.removeAttribute(Wa)}},[]);const Xc=a=>{_t([a.kind==="view"?Km(a.type,a.title):xa(a,zt||"")]),requestAnimationFrame(()=>Ne.current?.focus())},[Gc,ho]=d.useState(!1),Jc=I(a=>a.cfg),Qc=a=>{Je({execMode:"host",approvalMode:a,cwd:u.cwd}),et(null)},go=Xl(),Zc=d.useMemo(()=>gd(p||[],go),[p,go]),vt=!!we&&(Ce?.length||0)>=2,el=!!Ui&&is&&(!!window.tangu?.openMini||Hi)&&!(q&&!Ae)&&!vt&&!Ae&&!A,ea=wa.find(a=>a.id===An)||wa[1],tl=vt?N("group.modeLabel",{n:Ce.length}):N(q&&!Ae?"input.planMode":Ae?"input.presetChat":Ue?ea.key:"input.normal"),nl=vt?ja:q&&!Ae?Co:Ue?ea.Icon:Xn,vo=!vt&&!(q&&!Ae)&&!Ae&&Ue&&ea.id==="full-auto",sl=!Ae&&(!!Z||Ue||!!xe||!!se),al=(E||[]).find(a=>a.id===A)?.name||N("input.engineDefault"),$e=!!A,il=$e?[{label:al,options:z||[]}]:Zc.map(a=>({key:a.key,label:a.provider,source:a.source,options:a.models.map(m=>({...m,description:`${m.provider} · ${m.id}`}))})),ol=$e||!!w||!!U,rs=Jl(),[ih,oh]=d.useState(!1),cs=()=>et(null),yo={active:!q&&!vt&&An==="auto-edit",disabled:c,agents:ne||[],currentAgentSlug:ye,onNormalWork:B||(()=>{}),onAgentSwitch:!$e&&!vt?se:void 0,onClose:cs},ta=Z&&!Ae?{title:N("input.planMode"),items:[{id:"plan-mode",icon:t.jsx(Co,{size:14}),label:N(we?"input.planModeTeamOff":q?"input.planModeOn":"input.planModeEnable"),checked:!!q&&!we,disabled:!!we,run:()=>{Z(!q),cs()}}]}:null,na=xe&&!$e&&!Ae?{title:N("group.menu.section"),items:[{id:"group-chat",label:vt?N("group.menu.configured",{n:Ce.length}):N("group.menu.enable"),icon:t.jsx(ja,{size:14}),checked:vt,run:()=>{Cn(!0),cs()}}]}:null,ko=Ue?wa.map(({id:a,Icon:m,key:y,desc:S,...M})=>({id:`approval:${a}`,approvalId:a,label:N(y),detail:N(S),icon:t.jsx(m,{size:15,className:"approval-ic"}),checked:An===a,danger:"danger"in M,run:()=>Qc(a)})):[],qt=Ue&&An==="custom"?{id:"approval-rules",label:N("input.approval.editRules"),detail:N("input.approval.editRulesDesc"),icon:t.jsx(ru,{size:15,className:"approval-ic"}),run:()=>{ho(!0),cs()}}:null,rl=()=>{const a=B&&!Ae?ac(yo,N):null;return{title:N("input.modeSheetTitle"),back:N("common.back"),sections:[{items:a?[a.normal,...a.agentSwitch?[a.agentSwitch]:[]]:[]},...ta?[ta]:[],...na?[na]:[],...Ue?[{title:N(l?"input.approvalSection.team":"input.approvalSection"),items:[...ko,...qt?[qt]:[]]}]:[]]}},wo=c?t.jsxs(t.Fragment,{children:[(!!ue.trim()||Mt.length>0)&&t.jsx(oa,{onClick:os,disabled:o,title:N("input.send"),"aria-label":N("input.send")}),t.jsxs("button",{className:"t2c-stop",onClick:Ze,title:N("input.stop"),"aria-label":N("input.stop"),children:[t.jsx(Nr,{size:10}),t.jsx("span",{className:"t2c-stop-label",children:N("input.stop")})]})]}):el&&!ue.trim()&&!Mt.length&&!Zt.length&&!en.length&&!k.length&&!tn.length?t.jsx(oa,{className:"t2c-live-control",onClick:()=>{Uc()},disabled:!!o||Ys,title:N(En?"livecall.return":"livecall.start"),"aria-label":N(En?"livecall.return":"livecall.start"),children:Ys?t.jsx(Yt,{size:16,className:"spin"}):t.jsx(Td,{size:16})}):t.jsx(oa,{onClick:os,disabled:o||!ue.trim()&&!Mt.length,title:N("input.send"),"aria-label":N("input.send")});return t.jsxs("div",{className:"t2c",children:[Ac&&t.jsx(Yp,{agents:ne||[],models:p,initialAgents:Ce||[],initialTempAgents:de,active:vt,hideDisable:!0,onConfirm:a=>{xe?.({groupChat:!0,...a}),Cn(!1),Ql("chat.group")},onDisable:()=>xe?.({groupChat:!1}),onClose:()=>Cn(!1)}),t.jsxs("div",{className:"t2c-inner",children:[!!ft?.length&&t.jsxs("div",{className:"t2c-steer",role:"status","aria-label":N("input.steer.waiting"),children:[ft.map(a=>t.jsxs("div",{className:"t2c-steer-item",children:[t.jsx(td,{size:12,className:"t2c-steer-ic"}),t.jsx("span",{className:"t2c-steer-text",title:a.text,children:a.text}),t.jsx("button",{className:"t2c-steer-x",title:N("input.steer.remove"),onClick:()=>ge?.(a.id),children:t.jsx(pt,{size:12})})]},a.id)),t.jsxs("div",{className:"t2c-steer-foot",children:[t.jsx("span",{className:"t2c-steer-hint",children:N(ft.some(a=>a.localOnly)?"input.steer.queuedHint":"input.steer.hint")}),di&&ft.some(a=>!a.localOnly)&&t.jsxs("button",{className:"t2c-steer-now",onClick:di,children:[t.jsx(Zl,{size:11})," ",N("input.steer.now")]})]})]}),s,t.jsxs(eu,{ref:bt,className:`${rs?"t2c-card--phone":""}${Ic?" dragover":""}`,children:[n,yi&&t.jsx("div",{className:"t2c-hint",children:yi}),k.length>0&&t.jsx("div",{className:"t2c-quotes",role:"group","aria-label":N("input.quote.group"),children:k.map((a,m)=>t.jsxs("div",{className:"t2c-quote",children:[t.jsx(Xd,{size:13,className:"t2c-quote-mark","aria-hidden":!0}),t.jsx("span",{className:"t2c-quote-text",children:a.length>280?`${a.slice(0,280)}…`:a}),t.jsx("button",{title:N("input.remove"),"aria-label":N("input.remove"),onClick:()=>V?V(m):W?.(),className:"t2c-quote-x",children:t.jsx(pt,{size:12})})]},a))}),Mt.length>0&&t.jsxs("div",{className:"t2c-chiprow t2c-refrow",role:"group","aria-label":N("input.ref.selected"),children:[t.jsx("span",{className:"t2c-reflabel",children:N("input.ref.selected")}),Mt.map(a=>t.jsx(cm,{chip:a,removeTitle:N("input.remove"),inlineTitle:N("input.ref.shiftInline"),onInline:Xm(a)?()=>{const m=Ne.current;Qs(a,m?.selectionStart??ue.length,m?.selectionEnd??ue.length,!0)}:void 0,onRemove:()=>{if(a.run){const m=a.run;ve(y=>Nm(y,m))}$n&&a.token===$n.token?Mc(a.token):gi(m=>m.filter(y=>y.token!==a.token))}},a.token))]}),Zt.length>0&&t.jsx("div",{className:"t2c-chiprow",children:Zt.map((a,m)=>t.jsxs("span",{className:"attach-chip",children:[a.mimeType.startsWith("image/")&&t.jsx("img",{src:`data:${a.mimeType};base64,${a.data}`,alt:a.name}),t.jsx("span",{children:a.name}),t.jsx("button",{title:N("input.remove"),onClick:()=>ts(Zt.filter((y,S)=>S!==m)),children:t.jsx(pt,{size:12})})]},`${a.name}-${m}`))}),en.length>0&&t.jsx("div",{className:"t2c-chiprow",children:en.map((a,m)=>t.jsxs("span",{className:"attach-chip",title:N("input.wsUploadTitle",{name:a.name}),children:[a.mimeType.startsWith("image/")?t.jsx("img",{src:`data:${a.mimeType};base64,${a.data}`,alt:a.name}):t.jsx(Is,{size:14,style:{color:"var(--accent-ink)",flexShrink:0}}),t.jsx("span",{children:a.name}),t.jsx("span",{style:{fontSize:"var(--ui-font-caption, 11px)",color:"var(--text-faint)",flexShrink:0},children:N("input.toWorkspace")}),t.jsx("button",{title:N("input.remove"),onClick:()=>Ws(en.filter((y,S)=>S!==m)),children:t.jsx(pt,{size:12})})]},`ws-${a.name}-${m}`))}),tn.length>0&&t.jsx("div",{className:"t2c-chiprow",children:tn.map(a=>t.jsxs("span",{className:"attach-chip",title:N("input.skillChipTitle"),children:[t.jsx(br,{size:13,style:{color:"var(--accent-ink)",flexShrink:0}}),t.jsx("span",{children:a.name}),t.jsx("button",{title:N("input.remove"),onClick:()=>vi(tn.filter(m=>m.id!==a.id)),children:t.jsx(pt,{size:12})})]},`skill-${a.id}`))}),(a=>rs?t.jsxs("div",{className:"t2c-field",children:[a,!Di&&wo]}):a)(t.jsxs(t.Fragment,{children:[t.jsx(tu,{autoSize:!1,ref:Ne,className:"t2c-ta",rows:1,autoFocus:i,value:ue,placeholder:Gs?Xs:o?r||N("input.placeholderDisabled"):En?N("livecall.typeHint"):c?Dt?N("input.runningPlaceholder"):N("input.tip",{tip:N(fi[pi%fi.length])}):N(Ps?"input.placeholderTouch":"input.placeholder"),"data-suggestion":Gs||void 0,"data-tip-fade":c&&!Dt&&Cc||void 0,"data-tip-tall":c&&!Dt&&Fs||void 0,disabled:o,onChange:a=>{ve(a.target.value),gt(a.target.selectionStart||0),xi(!1),Ni(!1),Ri(!1),Pt&&nn(0),a.target.value.includes("@")||(Ci(""),Ei([])),pe()},onSelect:a=>gt(a.target.selectionStart||0),onPaste:a=>{const m=a.clipboardData?.files;if(!m?.length)return;a.preventDefault();const y=Array.from(m),S=y.filter(Y=>Y.type.startsWith("image/")),M=y.filter(Y=>!Y.type.startsWith("image/")),T=[];if(M.length){const Y=[];for(const ie of M){let be="";if(ct)try{be=window.tangu?.getPathForFile?.(ie)||""}catch{be=""}be?Y.push(be):T.push(ie)}Y.length&&(_t(Y.map(Vt)),requestAnimationFrame(()=>{Ne.current?.focus(),pe()}))}if(S.length){const Y=new DataTransfer;S.forEach(ie=>Y.items.add(ie)),uo(Y.files)}if(T.length){const Y=new DataTransfer;T.forEach(ie=>Y.items.add(ie)),Zs(Y.files)}},onKeyDown:a=>{if((a.key==="Backspace"||a.key==="Delete")&&Dn.length&&!a.nativeEvent.isComposing&&!a.metaKey&&!a.ctrlKey&&!a.altKey){const m=a.currentTarget,y=m.selectionStart===m.selectionEnd?jm(Dn,m.selectionStart,a.key==="Backspace"?"back":"fwd"):void 0;if(y){a.preventDefault(),Kc(y.start,y.end);return}}if(Ln){const m=Wt.length;if(a.key==="ArrowDown"){a.preventDefault(),m&&ss(T=>(T+1)%m);return}if(a.key==="ArrowUp"){a.preventDefault(),m&&ss(T=>(T-1+m)%m);return}const y=a.currentTarget,S=y.selectionStart!==y.selectionEnd||/\S/.test(y.value[y.selectionEnd]??""),M=Et==="all"&&S?null:ym(cn,Et,a.key);if(M&&!a.shiftKey&&!a.metaKey&&!a.ctrlKey&&!a.altKey&&!a.nativeEvent.isComposing&&a.keyCode!==229){a.preventDefault(),qs(M);return}if((a.key==="Enter"||a.key==="Tab")&&!a.nativeEvent.isComposing){a.preventDefault(),m&&io(Wt[Math.min(Mi,m-1)]);return}if(a.key==="Escape"){a.preventDefault(),Ri(!0);return}}if(Qi){if(a.key==="ArrowDown"){a.preventDefault(),ns(m=>(m+1)%Ct.length);return}if(a.key==="ArrowUp"){a.preventDefault(),ns(m=>(m-1+Ct.length)%Ct.length);return}if((a.key==="Enter"||a.key==="Tab")&&!a.nativeEvent.isComposing){a.preventDefault(),Zi(Ct[Math.min(ji,Ct.length-1)]);return}if(a.key==="Escape"){a.preventDefault(),Ni(!0);return}}if(an){if(a.key==="ArrowDown"){a.preventDefault(),Qe(m=>(m+1)%St.length);return}if(a.key==="ArrowUp"){a.preventDefault(),Qe(m=>(m-1+St.length)%St.length);return}if((a.key==="Enter"||a.key==="Tab")&&!a.nativeEvent.isComposing){a.preventDefault(),St[Math.min(ki,St.length-1)]?.run();return}if(a.key==="Escape"){a.preventDefault(),xi(!0),Nn(null);return}}if(a.key==="Tab"&&!a.shiftKey&&Gs&&!Fe&&!a.nativeEvent.isComposing){a.preventDefault();const m=Xs;ve(m),requestAnimationFrame(()=>{const y=Ne.current;y&&(y.selectionStart=y.selectionEnd=m.length,gt(m.length)),pe()});return}if(a.key==="ArrowUp"&&ft?.length&&xt&&Pt===0&&a.currentTarget.selectionStart===a.currentTarget.selectionEnd&&ue.slice(0,a.currentTarget.selectionStart).indexOf(`
39
+ `)===-1){a.preventDefault();const m=ft[ft.length-1];xt(m.id).then(y=>{y&&(ve(S=>S.trim()?`${y}
40
+
41
+ ${S}`:y),requestAnimationFrame(()=>{const S=Ne.current;S&&(S.focus(),S.selectionStart=S.selectionEnd=y.length,gt(y.length)),pe()}))});return}if(a.key==="ArrowUp"&&a.currentTarget.selectionStart===a.currentTarget.selectionEnd&&ue.slice(0,a.currentTarget.selectionStart).indexOf(`
42
+ `)===-1&&$t?.length){a.preventDefault(),Xi(!0);return}if(a.key==="ArrowDown"&&Pt>0&&a.currentTarget.selectionStart===a.currentTarget.selectionEnd&&ue.slice(a.currentTarget.selectionStart).indexOf(`
43
+ `)===-1){a.preventDefault(),Xi(!1);return}a.key==="Enter"&&!a.shiftKey&&!a.nativeEvent.isComposing&&(a.preventDefault(),os())}}),t.jsx(zm,{text:ue,runs:Dn,chipOf:a=>Bt.get(a)})]})),an&&t.jsx("div",{className:"t2c-menu",children:St.map((a,m)=>t.jsxs("button",{className:"t2c-menu-item","data-active":m===Math.min(ki,St.length-1)||void 0,onMouseEnter:()=>Qe(m),onClick:()=>a.run(),children:[t.jsx("span",{className:"t2c-menu-cmd",children:a.cmd}),t.jsx("span",{className:"t2c-menu-desc",children:a.desc})]},`${a.cmd}-${m}`))}),Qi&&!Ln&&t.jsxs("div",{className:"t2c-menu",children:[t.jsx("div",{className:"t2c-menu-sec",children:N(In?"input.mention.projectNote":Tn?"input.mention.groupNote":"input.mention.delegateNote")}),Ct.map((a,m)=>t.jsxs("button",{className:"t2c-menu-item","data-active":m===Math.min(ji,Ct.length-1)||void 0,onMouseEnter:()=>ns(m),onClick:()=>Zi(a),children:[t.jsxs("span",{className:"t2c-menu-cmd",children:["@",a.name]}),t.jsx("span",{className:"t2c-menu-desc",children:a.description||a.slug})]},a.slug))]}),Ln&&t.jsxs("div",{className:"t2c-menu t2c-menu--refs",children:[cn.length>0&&t.jsx("div",{className:"t2c-cats cap-tabs",ref:Vc,role:"tablist","aria-label":N("input.refcat.label"),children:cn.map(a=>t.jsx("button",{type:"button",className:"t2c-cat",role:"tab","aria-selected":Et===a,"data-cat":a,tabIndex:-1,onMouseDown:m=>m.preventDefault(),onClick:()=>qs(a),children:N(`input.refcat.${a}`)},a))}),!cn.length&&t.jsx("div",{className:"t2c-menu-sec",children:N(as?"input.fileref.noteApps":"input.fileref.note")}),t.jsxs("div",{className:"t2c-menu-list",children:[Wt.map((a,m)=>t.jsxs("button",{className:"t2c-menu-item","data-cat":oi(a),"data-active":m===Math.min(Mi,Wt.length-1)||void 0,onMouseEnter:()=>ss(m),onMouseDown:y=>y.preventDefault(),onClick:()=>io(a),children:[t.jsx("span",{className:"t2c-menu-cmd",children:a.app?t.jsxs(t.Fragment,{children:[t.jsx(kn,{id:a.app.id,className:"t2c-menu-ico"}),a.p]}):a.session?`💬 ${a.session.title}`:a.note?`${no[a.p]?`${no[a.p]} `:""}${a.p.split("/").pop().replace(/\.md$/i,"")}`:a.p.split("/").pop()}),t.jsx("span",{className:"t2c-menu-desc",children:a.app?a.desc:a.session?a.session.summary||N("input.fileref.session"):a.p})]},a.app?`a:${a.app.kind}:${a.app.id}:${a.p}`:a.session?`s:${a.session.id}`:(a.note?"n:":"f:")+a.p)),!Wt.length&&t.jsx("div",{className:"t2c-menu-empty",children:N("addMenu.noMatches")})]},Et)]}),t.jsxs(nu,{children:[t.jsx(im,{open:Fe==="add",disabled:o,activeSessionId:Se,canUsePathPicker:ct,onOpenChange:a=>et(a?"add":null),onNewSession:te,onAddAgent:!c&&!Ae&&!$e?Ie||(xe?()=>Cn(!0):void 0):void 0,onPickPaths:Yc,onPickFiles:fo,onAddReference:Xc}),Di?t.jsx(Wp,{analyser:ke.analyser,recording:ke.recording,busy:ke.busy,onStop:ke.toggle,onSend:Pc,t:N}):t.jsxs(t.Fragment,{children:[sl&&!0&&t.jsxs("span",{className:`mode-pill-wrap t2c-capsule-peer${Fe==="mode"?" is-open":""}`,"data-cmenu":!0,children:[t.jsxs("button",{className:`t2c-pill mode-pill-btn${Fe==="mode"?" is-open":""}${q&&!Ae?" active":""}`,"data-danger":vo||void 0,title:N(vo?"input.approval.fullAutoDesc":"input.modeChipTitle"),"aria-expanded":Fe==="mode",onClick:()=>{if(Fe!=="mode"&&si(rl,{})){et(null);return}et(a=>a==="mode"?null:"mode")},children:[t.jsx(nl,{size:13}),t.jsx("span",{className:"t2c-pill-label",children:tl}),t.jsx(yn,{size:10})]}),Fe==="mode"&&t.jsxs("div",{ref:Ki.ref,className:"composer-menu composer-menu--mode",style:Ki.style,children:[B&&!Ae&&t.jsx(om,{...yo}),[ta,na].map(a=>a&&t.jsxs(gn.Fragment,{children:[t.jsx("div",{className:"menu-section",children:a.title}),a.items.map(m=>t.jsxs("button",{className:`menu-item${m.checked?" active":""}`,disabled:m.disabled,onClick:m.run,children:[m.icon,t.jsx("span",{className:"grow",children:m.label}),m.checked&&t.jsx(at,{size:13})]},m.id))]},a.items[0].id)),Ue&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"menu-section",children:N(l?"input.approvalSection.team":"input.approvalSection")}),ko.map(a=>t.jsxs("button",{className:`menu-item approval-item${a.checked?" active":""}${a.danger?" danger":""}`,"aria-describedby":`approval-mode-desc-${a.approvalId}`,onClick:a.run,children:[a.icon,t.jsx("span",{className:"grow approval-title",children:a.label}),a.checked&&t.jsx(at,{size:13,className:"approval-ck"}),t.jsx("span",{id:`approval-mode-desc-${a.approvalId}`,role:"tooltip",className:"approval-hover-desc",children:a.detail})]},a.approvalId)),qt&&t.jsxs("button",{className:"menu-item approval-item","aria-describedby":"approval-edit-rules-desc",onClick:qt.run,children:[qt.icon,t.jsx("span",{className:"grow approval-title",children:qt.label}),t.jsx("span",{id:"approval-edit-rules-desc",role:"tooltip",className:"approval-hover-desc",children:qt.detail})]})]})]})]}),t.jsx("span",{className:"t2c-grow"}),!Ae&&!!Ft&&Ft>0&&(()=>{const a=Math.min(100,Math.round((De||0)/Ft*100)),m=Js?.compactAt?(De||0)>=Js.compactAt*.8:a>=80,y=9,S=2*Math.PI*y;return t.jsxs("span",{className:`t2c-ctxring t2c-collapse-on-capsule-open${Fe==="ctx"?" is-open":""}`,"data-warn":m||void 0,"data-cmenu":!0,children:[t.jsx("button",{type:"button",className:"t2c-ctxring-btn","aria-expanded":Fe==="ctx","aria-label":`${N("input.ctxLabel")} ${a}%`,...Wr(()=>Fe==="ctx"?null:[`${N("input.ctxLabel")} ${a}%`]),onClick:()=>{nd(),et(M=>M==="ctx"?null:"ctx")},children:t.jsxs("svg",{viewBox:"0 0 24 24",width:"20",height:"20","aria-hidden":"true",children:[t.jsx("circle",{className:"t2c-ctxring-track",cx:"12",cy:"12",r:y}),t.jsx("circle",{className:"t2c-ctxring-fill",cx:"12",cy:"12",r:y,style:{strokeDasharray:S,strokeDashoffset:S*(1-a/100)}})]})}),t.jsx("span",{ref:Yi.ref,className:"t2c-ctxring-pop",style:Yi.style,children:t.jsx(Om,{open:Fe==="ctx",contextWindow:Ft,ctxTokens:De,sessionTokens:it,runCost:Ke,costLimit:Pe,ctxInfo:Js,onCompact:ot?()=>{ot(),et(null)}:void 0})})]})})(),ol&&t.jsx(vd,{scopeKey:`${Se??"draft"}:${Za(_i)}:${$e?"engine":"tangu"}`,className:"t2c-capsule-peer",icon:rs?null:void 0,hub:void 0,open:Fe==="model",onOpenChange:a=>et(a?"model":null),disabled:o,modelId:$e?b:v,groups:il,onSelect:$e?a=>$?.(a):a=>w?.(a),thinkingLevel:$e?void 0:Ot,onThinkingChange:$e||!U?void 0:(a,m)=>{Rn(a,m)},allowUltra:jt,ultra:sn,running:c,supportedThinking:$e?void 0:p?.find(a=>a.id===v)?.thinkingLevels,effectiveThinking:$e?void 0:fe?.thinkingRequested===(Ot||"medium")?fe?.thinkingEffective:void 0,modelsResponse:$e?void 0:f,defaultModelIds:$e?void 0:R,onDefaultModelChange:$e?void 0:x,onContextWindowChange:$e?void 0:O,emptyLabel:$e?N("input.engineModelDefault"):void 0,footnote:!$e&&!Ue&&!p?.some(a=>a.source==="direct")?N("input.cloudModelHint"):void 0}),t.jsx("button",{className:`t2c-iconbtn t2c-mic-control t2c-collapse-on-capsule-open${ke.recording?" recording":""}`,title:ke.busy?N("input.micBusy"):ke.recording?N("input.micStop"):ke.error||N("input.micStart"),disabled:o||ke.busy||!ke.supported,onClick:ke.toggle,children:ke.busy?t.jsx(Yt,{size:14,className:"spin"}):t.jsx(su,{size:14})}),!rs&&wo]})]}),ke.error&&!ke.recording&&!ke.busy&&t.jsx("div",{className:"t2c-hint",style:{marginTop:6,marginBottom:0},children:ke.error}),Bi&&is&&!ke.error&&t.jsx("div",{className:"t2c-hint",style:{marginTop:6,marginBottom:0},children:Bi})]})]}),Gc&&t.jsx(em,{cfg:Jc,onClose:()=>ho(!1)}),Bc&&t.jsx(qp,{offerFullAccess:Ue&&!l&&An!=="full-auto",onConfirm:({fullAccess:a})=>{a&&Je({execMode:"host",approvalMode:"full-auto",cwd:u.cwd}),U?.("max",!0)},onClose:()=>Vi(!1)})]})};function nf(e,n){const s=Math.max(0,e.content-e.width);if(e.left>=s-1)return 0;const i=e.left+e.width,o=n.find(c=>c.end>i+1),r=o?Math.min(o.start,s):s;return r>e.left+1?r:Math.min(i,s)}function sf(e,n){return e-n>1}je({"chatPicker.engine":{zh:"引擎",en:"Engine"},"chatPicker.agent":{zh:"Agent",en:"Agent"}});function af({label:e,value:n,icon:s,options:i,onChange:o,busy:r=!1}){const c=i.find(u=>u.value===n);return t.jsxs("label",{className:"compact-chat-picker","aria-busy":r||void 0,title:c?.name,children:[t.jsx("span",{className:"compact-chat-picker-kind",children:e}),t.jsx("span",{className:"compact-chat-picker-icon",children:s}),t.jsx("span",{className:"compact-chat-picker-name",children:c?.name||e}),t.jsx(yn,{size:13}),t.jsxs("select",{"aria-label":e,value:c?n:"",onChange:u=>o(u.target.value),children:[!c&&t.jsx("option",{value:"",disabled:!0,children:e}),i.map(u=>t.jsx("option",{value:u.value,disabled:u.disabled,children:u.description?`${u.name} — ${u.description}`:u.name},u.value))]})]})}const of=({label:e,children:n,role:s="radiogroup"})=>{const{t:i}=Ee(),o=d.useRef(null),[r,c]=d.useState(!1);d.useLayoutEffect(()=>{const l=o.current;if(!l)return;const p=()=>{const v=l.parentElement,w=v&&getComputedStyle(v),E=v&&w?v.clientWidth-parseFloat(w.paddingLeft)-parseFloat(w.paddingRight):l.clientWidth;c(sf(l.scrollWidth,E))};p();const f=new ResizeObserver(p);f.observe(l);for(const v of Array.from(l.children))f.observe(v);return()=>f.disconnect()},[n]),d.useEffect(()=>{const l=o.current,p=l?.querySelector('[aria-checked="true"],[aria-pressed="true"]');if(!l||!p)return;const f=l.getBoundingClientRect(),v=p.getBoundingClientRect();v.right>f.right?l.scrollLeft+=v.right-f.right+6:v.left<f.left&&(l.scrollLeft-=f.left-v.left+6)},[]);const u=d.useCallback(()=>{const l=o.current;if(!l)return;const p=l.getBoundingClientRect(),f=Array.from(l.children).map(v=>{const w=v.getBoundingClientRect();return{start:w.left-p.left+l.scrollLeft,end:w.right-p.left+l.scrollLeft}});l.scrollTo({left:nf({left:l.scrollLeft,width:l.clientWidth,content:l.scrollWidth},f),behavior:"smooth"})},[]);return t.jsxs("div",{className:"engine-picker-bar","data-more":r||void 0,children:[t.jsx("div",{className:"engine-picker-scroll",ref:o,role:s,"aria-label":e,children:n}),r&&t.jsx("button",{type:"button",className:"engine-picker-more",onClick:u,title:i("pill.more"),"aria-label":i("pill.more"),children:t.jsx(Es,{size:16})})]})};function rf(e,n,s){const i=lu(e,n),o=i.groupAgents??[];return i.groupChat&&o.length>=2?{kind:"team",count:o.length}:{kind:"agent",slug:i.agentSlug||s||null}}je({"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 pn=2,mn=e=>`agent:${e}`,Bn=e=>`engine:${e}`,cf=(e,n)=>e.length===n.length&&e.every((s,i)=>s===n[i]);function lf(e){if(e.engineId)return[];const n=e.groupAgents??[];return e.groupChat&&n.length>=2?[...n]:e.agentSlug?[e.agentSlug]:[]}function Yh({sessionId:e,cfg:n}){const{t:s}=Ee(),[i,o]=d.useState(null),r=I(uu(g=>({agentDefs:g.agentDefs,agentAvatars:g.agentAvatars,defaultAgentSlug:g.defaultAgentSlug,engines:g.engines,engineCaps:g.engineCaps,teams:g.teams}))),c=I(g=>e?null:du(g,Gn())),u=I(g=>c?g.projectSettingsByPath[c]??null:null),l=I(g=>!c||c in g.projectSettingsByPath);d.useEffect(()=>{c&&!l&&I.getState().ensureProjectSettings(c).catch(()=>null)},[c,l]);const p=n.engineId||"",f=lf(n),v=p?[Bn(p)]:f.map(mn),w=p&&!r.engineCaps[p]?p:"",E=d.useMemo(()=>{const g=r.agentDefs.map(P=>({id:mn(P.slug),kind:"agent",slug:P.slug,name:P.name,description:P.description,system:P.createdBy==="system"}));for(const P of n.groupAgents??[]){if(g.some(he=>he.id===mn(P)))continue;const G=n.groupTempAgents?.find(he=>he.slug===P);g.push({id:mn(P),kind:"agent",slug:P,name:G?.name||P,description:G?.description})}if(n.agentSlug&&!g.some(P=>P.id===mn(n.agentSlug))&&g.push({id:mn(n.agentSlug),kind:"agent",slug:n.agentSlug,name:n.agentSlug}),n.execMode==="host")for(const P of r.engines)P.available&&g.push({id:Bn(P.id),kind:"engine",engineId:P.id,name:P.name});return p&&!g.some(P=>P.id===Bn(p))&&g.push({id:Bn(p),kind:"engine",engineId:p,name:r.engines.find(P=>P.id===p)?.name||p}),g},[r.agentDefs,r.engines,p,n.execMode,n.groupAgents,n.groupTempAgents,n.agentSlug]),A=d.useMemo(()=>new Map(E.map(g=>[g.id,g])),[E]),z=d.useMemo(()=>E.filter(g=>g.kind==="agent").map(g=>g.name),[E]),b=v.map(g=>A.get(g)).filter(g=>!!g),$=E.filter(g=>!v.includes(g.id)),D=n.groupChat?f.length:0,L=g=>{const P=!!n.groupChat&&f.length<pn;if(!p&&!P&&cf(f,g))return;const G=I.getState(),he=!!p,we=(n.groupTempAgents||[]).filter(Ie=>g.includes(Ie.slug)),Ce=he?{engineId:void 0,engineModelId:void 0}:{};if(g.length>=pn){const Ie={groupChat:!0,groupAgents:g,groupTempAgents:we.length?we:void 0,...Ce};e?G.patchSessionConfig(Ie,e):G.setNewChatCfg(B=>({...B,...Ie}));return}const de=g[0]||"",xe={groupChat:!1,groupAgents:void 0,groupTempAgents:void 0,...Ce};e?G.selectSessionAgent(de,e,xe):(G.setNewChatCfg(Ie=>({...Ie,...xe})),G.selectNewChatAgent(de))},U=g=>{const P=I.getState();e?P.setSessionEngine(g,e):P.setNewChatCfg(G=>({...G,engineId:g||void 0,engineModelId:void 0,...g?{groupChat:!1,groupAgents:void 0,agentSlug:void 0}:{}}))},K=d.useRef(null),R=d.useRef(null);d.useEffect(()=>{const g=K.current;if(!g)return;K.current=null,R.current?.querySelector(`[data-pill-id="${CSS.escape(g)}"]`)?.focus()});const x=g=>{if(K.current=g.id,g.kind==="engine"){U(g.engineId===p?"":g.engineId);return}const P=f.includes(g.slug)?f.filter(G=>G!==g.slug):[...f,g.slug];L(P)},O=()=>{p?U(""):L([])},J=g=>{g.kind==="agent"?Eo("agent",g.slug):Eo("engine",g.engineId)},ee=g=>g.kind==="engine"?w===g.engineId?t.jsx(Yt,{size:16,className:"spin"}):t.jsx(_o,{engineId:g.engineId,size:16}):t.jsx(Dp,{name:g.name,url:r.agentAvatars[g.slug],siblings:z,imgClassName:"agent-pill-avatar",initialClassName:"agent-pill-initial"}),Q=(g,P)=>{const G=g.kind==="agent"&&g.description?`${g.name} — ${g.description}`:g.name;return P?`${G} · ${s("agentSelect.removeHint")}`:g.kind==="agent"&&g.slug===r.defaultAgentSlug?`${G} · ${s("agentSelect.defaultTag")}`:G},H=(g,P)=>{const G=P!==null,he=g.kind==="engine"&&w===g.engineId;return t.jsxs("button",{type:"button","aria-pressed":G,"data-pill-id":g.id,className:`engine-pill agent-pill${G?" selected":""}`,"data-agent-slug":g.kind==="agent"?g.slug:void 0,"data-engine-id":g.kind==="engine"?g.engineId:void 0,title:Q(g,G),disabled:!!w&&!he,onClick:()=>{(!w||he)&&x(g)},onContextMenu:we=>{we.preventDefault(),o({...Zu(we),items:[{label:s("agentSelect.direct"),icon:t.jsx(Ir,{size:13}),run:()=>J(g)}]})},children:[G&&b.length>=pn&&t.jsx("span",{className:"agent-pill-index",children:P+1}),t.jsx("span",{className:"engine-pill-icon",children:ee(g)}),t.jsx("span",{className:"engine-pill-label",children:g.name}),g.kind==="agent"&&g.system&&t.jsx("span",{className:"agent-badge-system",children:s("agent.badge.system")})]},g.id)};if(n.preset==="chat"||!E.length)return null;const C=rf(n,e?{}:pu(u,Array.isArray(r.teams)?r.teams:[]).config,r.defaultAgentSlug),_=C.kind==="agent"&&C.slug?r.agentDefs.find(g=>g.slug===C.slug)?.name:void 0,q=D>=pn?s("agentSelect.team",{n:D}):b.length===1?s("agentSelect.hintOne",{name:b[0].name}):C.kind==="team"?s("agentSelect.team",{n:C.count}):_?s("agentSelect.hintDefault",{name:_}):s("agentSelect.hintDefaultAnon"),Z=D<pn&&b.length!==1&&C.kind!=="team",oe=v[0]||"",re=b[0]?ee(b[0]):t.jsx(_o,{engineId:"",size:16});return t.jsxs("div",{ref:R,className:"engine-picker agent-picker agent-select-strip",role:"group","aria-label":s("agentSelect.title"),children:[t.jsx(af,{label:s("chatPicker.agent"),value:oe,icon:re,options:[{value:"",name:s("agentSelect.default")},...E.map(g=>({value:g.id,name:g.name,description:v.includes(g.id)?s("agentSelect.picked"):g.kind==="agent"?g.description:void 0,disabled:!!w&&g.id!==Bn(w)}))],onChange:g=>{if(!g){O();return}const P=A.get(g);P&&x(P)},busy:!!w}),t.jsx(of,{label:s("agentSelect.title"),role:"group",children:[...b.map((g,P)=>H(g,P)),...b.length>0?[t.jsx("span",{className:"agent-select-sep","aria-hidden":"true"},"sep")]:[],...$.map(g=>H(g,null))]}),t.jsx("div",{className:`engine-picker-hint${D>=pn?" agent-select-team":""}${Z?" is-default":""}`,children:q}),i&&t.jsx(Qu,{menu:i,onClose:()=>o(null)})]})}const uf=e=>`${e.name} ${e.path||""} ${e.project||""}`,df=e=>[e.path,e.project].filter(n=>!!n&&n!==e.name).join(" · ")||void 0,Xh=({workspaces:e,value:n,onChange:s,onAddProject:i,onCloneProject:o,onAddCloudProject:r})=>{const{t:c}=Ee(),[u,l]=d.useState(!1),[p,f]=d.useState(""),[v,w]=d.useState(!1),[E,A]=d.useState(""),z=d.useRef(null),b=d.useRef(null),$=Xt(u);d.useEffect(()=>{if(!u)return;const g=G=>{z.current&&!z.current.contains(G.target)&&(l(!1),f(""),w(!1),A(""))},P=G=>{G.key==="Escape"&&(l(!1),f(""),w(!1),A(""),z.current?.querySelector(".project-pill")?.focus())};return window.addEventListener("mousedown",g),window.addEventListener("keydown",P),()=>{window.removeEventListener("mousedown",g),window.removeEventListener("keydown",P)}},[u]);const D=e.filter(g=>g.kind!=="channel"),L=D.find(g=>g.key===n||!!n&&g.sessionKeys?.includes(n))||D.find(g=>g.kind==="local"&&g.system)||D[0]||null,U=D.find(g=>g.kind==="rootless")||null,K=D.filter(g=>g.kind!=="rootless"),R=p.trim().toLowerCase(),x=K.filter(g=>!R||uf(g).toLowerCase().includes(R)),O=K.length>=6,J=L?.kind==="cloud"?hn:L?.kind==="rootless"?$o:bn,ee=()=>{l(!1),f(""),w(!1),A("")},Q=g=>{s(g),ee()},H=g=>({id:`ws:${g.key}`,label:g.name,detail:df(g),icon:g.kind==="cloud"?t.jsx(hn,{size:14}):t.jsx(bn,{size:14}),checked:g.key===L?.key,run:()=>Q(g)}),C=U?{id:`ws:${U.key}`,label:c("input.project.dontWork"),icon:t.jsx($o,{size:14}),checked:U.key===L?.key,run:()=>Q(U)}:null,_=r?{id:"add-cloud",label:c("input.project.addCloud"),icon:t.jsx(hn,{size:14}),run:()=>{{w(!0);return}}}:null,q=i?{id:"add-local",label:c("input.project.add"),icon:t.jsx(ai,{size:14}),run:()=>{i(),ee()}}:null,Z=o?{id:"clone-git",label:c("input.project.clone"),icon:t.jsx(Dd,{size:14}),run:()=>{o(),ee()}}:null,oe=()=>({title:c("input.project.label"),back:c("common.back"),...O?{search:{placeholder:c("input.project.search"),empty:c("input.project.noMatches")}}:{},sections:[{items:K.map(H)},{items:C?[C]:[]},{items:[_,q,Z].filter(g=>!!g)}]});d.useEffect(()=>{if(!u||mu())return;const g=requestAnimationFrame(()=>{(O?b.current?.querySelector(".project-menu-search input"):b.current?.querySelector(".project-menu-item.active"))?.focus()});return()=>cancelAnimationFrame(g)},[u,O]);const re=g=>{if(!["ArrowDown","ArrowUp","Home","End"].includes(g.key))return;const P=[...b.current?.querySelectorAll(".project-menu-item:not(:disabled)")||[]];if(!P.length)return;g.preventDefault();const G=P.indexOf(document.activeElement),he=g.key==="Home"?0:g.key==="End"?P.length-1:G<0?g.key==="ArrowDown"?0:P.length-1:g.key==="ArrowDown"?(G+1)%P.length:(G-1+P.length)%P.length;P[he]?.focus()};return t.jsxs("div",{className:`project-selector${u?" is-open":""}`,ref:z,children:[t.jsxs("button",{className:`composer-chip project-pill${u?" is-open":""}`,onClick:()=>{if(u){ee();return}si(oe,{})||l(!0)},title:c("input.project.label"),"aria-haspopup":"menu","aria-expanded":u,children:[t.jsx(J,{size:13}),t.jsx("span",{className:"project-pill-name",children:L?.name||c("input.project.none")}),t.jsx(yn,{size:12})]}),u&&t.jsxs("div",{ref:g=>{b.current=g,$.ref.current=g},className:"composer-menu project-menu",style:$.style,role:"menu","aria-label":c("input.project.label"),onKeyDown:re,children:[O&&t.jsxs("label",{className:"project-menu-search",children:[t.jsx(Er,{size:13}),t.jsx("input",{value:p,onChange:g=>f(g.target.value),placeholder:c("input.project.search")})]}),t.jsxs("div",{className:"project-menu-list",children:[x.map(H).map(g=>t.jsxs("button",{className:`menu-item project-menu-item${g.checked?" active":""}`,role:"menuitemradio","aria-checked":!!g.checked,onClick:g.run,children:[g.icon,t.jsx("span",{className:"grow project-menu-name",children:g.label}),t.jsx("span",{className:"project-menu-check",children:g.checked?t.jsx(at,{size:13}):null})]},g.id)),!x.length&&t.jsx("div",{className:"project-menu-empty",children:c("input.project.noMatches")})]}),C&&t.jsx("div",{className:"project-menu-section project-menu-projectless-section",role:"group",children:t.jsxs("button",{className:`menu-item project-menu-item project-menu-projectless${C.checked?" active":""}`,role:"menuitemradio","aria-checked":C.checked,onClick:C.run,children:[C.icon,t.jsx("span",{className:"grow project-menu-name",children:C.label}),t.jsx("span",{className:"project-menu-check",children:C.checked?t.jsx(at,{size:13}):null})]})}),(_||q||Z)&&t.jsxs("div",{className:"project-menu-section project-menu-actions",role:"group",children:[r&&_&&(v?t.jsxs("label",{className:"project-menu-search project-menu-naming",children:[t.jsx(hn,{size:13}),t.jsx("input",{autoFocus:!0,value:E,onChange:g=>A(g.target.value),placeholder:c("input.project.cloudName"),onKeyDown:g=>{g.key==="Enter"&&E.trim()&&(r(E.trim()),ee()),g.key==="Escape"&&(g.stopPropagation(),A(""),w(!1))}})]}):t.jsxs("button",{className:"menu-item project-menu-item project-menu-add",role:"menuitem",onClick:_.run,children:[_.icon,t.jsx("span",{className:"grow",children:_.label})]})),q&&t.jsxs("button",{className:"menu-item project-menu-item project-menu-add",role:"menuitem",onClick:q.run,children:[q.icon,t.jsx("span",{className:"grow",children:q.label})]}),Z&&t.jsxs("button",{className:"menu-item project-menu-item project-menu-add",role:"menuitem","data-project-menu-clone":!0,onClick:Z.run,children:[Z.icon,t.jsx("span",{className:"grow",children:Z.label})]})]})]})]})},Rs=fu,lr=/^[0-9a-zA-Z-]{8,64}$/;function rc(e){return e.kind==="unit"?`unit:${e.unitId.toLowerCase()}`:""}function pf(e){if(typeof e=="string"){const s=/^unit:(.+)$/.exec(e);return s&&lr.test(s[1])?Object.freeze({kind:"unit",unitId:s[1].toLowerCase()}):Rs}const n=e;return n&&typeof n=="object"&&n.kind==="unit"&&typeof n.unitId=="string"&&lr.test(n.unitId)?Object.freeze({kind:"unit",unitId:n.unitId.toLowerCase()}):Rs}const mf=5*6e4,ur=new Set(["remoteOff","awaitingConfirm","denied","callerBlocked"]);function Ka(e){if(e==null)return null;const n=typeof e=="object"?e:{},s=typeof n.code=="string"?n.code:"",i=typeof n.status=="number"?n.status:NaN;switch(s){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 ii(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 s?i>=500?"unreachable":null:n.name==="TypeError"||n.name==="AbortError"||i===0||i>=500?"unreachable":null}const dr=e=>e.state||e.reason?{...e.state?{state:e.state}:{},...e.reason?{reason:e.reason}:{}}:void 0;function ff(e,n,s,i=Date.now()){if(!e.online)return{status:"offline"};if(e.capsLive&&e.caps){const o=e.caps.engine;if(o==="external")return{status:"noEngine"};if(o==="stopped")return{status:"engineStopped"};if(o==="starting")return{status:"starting"}}if(n&&!n.ok){const o=Ka(n)??"unreachable",r=ur.has(o)?dr(n):void 0;return r?{status:o,refusal:r}:{status:o}}if(s&&i-s.at>=0&&i-s.at<mf){const o=Ka({status:403,code:s.code,state:s.state,reason:s.reason});if(o&&ur.has(o)){const r=dr(s);return r?{status:o,refusal:r}:{status:o}}}return n?.ok?{status:"ready"}:{status:"checking"}}function cc(e){return!!(e.online&&e.capsLive&&e.caps?.engine==="ready")}function lc(e){return e==="native_only"?"nativeOnly":e==="caller_unsupported"||e==="CALLER_UNSUPPORTED"?"callerUnsupported":e==="network"||e==="server_429"||typeof e=="string"&&/^server_5\d\d$/.test(e)?"network":e==="auth_expired"||e==="server_401"||e==="not_signed_in"?"signedOut":"callerUnavailable"}const hf=2e3,gf=Nd+Cd+5e3,vf=3e3;function gs(e,n){const s=n&&typeof n=="object"?n:{};return{ok:!1,status:e,...typeof s.code=="string"?{code:s.code}:{},...typeof s.state=="string"?{state:s.state}:{},...typeof s.reason=="string"?{reason:s.reason}:{}}}function yf(e){const n=e?.code;return n==="CALLER_UNAVAILABLE"||n==="CALLER_UNSUPPORTED"?n:null}function vs(e){const n=yf(e.json);return n?lc(n):e.status===401?"signedOut":null}async function kf(e,n,s,i){const o=()=>!!i?.aborted,r=await s.ensureSelf();if(o())return{kind:"cancelled"};if(!r.ok)return{kind:"phone",issue:lc(r.code)};const c=`${e}/units/${n}/proxy`,u=async(w,E)=>{try{return await s.fetchJson(c+w,{...E,signal:i})}catch{return null}};let l=await u("/unit/remote-access");if(o())return{kind:"cancelled"};if(l===null)return{kind:"device",probe:{ok:!1,status:0}};const p=vs(l);if(p)return{kind:"phone",issue:p};if(l.status===200){let w=l.json??{};const E="REMOTE_CALLER_UNCONFIRMED",A=$=>$.remoteSessions===!1?{kind:"device",sticky:{code:"REMOTE_SESSIONS_OFF",at:s.now()}}:$.caller!=="trusted"&&$.caller!=="paired"&&ii($.reason)?{kind:"device",sticky:{code:E,...typeof $.caller=="string"?{state:$.caller}:{},reason:$.reason,at:s.now()}}:$.caller==="denied"?{kind:"device",sticky:{code:E,state:"denied",at:s.now()}}:null,z=()=>({kind:"device",sticky:{code:E,state:"unconfirmed",at:s.now()}}),b=A(w);if(b)return b;if(w.caller==="unconfirmed"){const $=await u("/unit/remote-access/request",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"});if(o())return{kind:"cancelled"};if($===null)return{kind:"device",probe:{ok:!1,status:0}};const D=vs($);if(D)return{kind:"phone",issue:D};if($.status!==200)return{kind:"device",probe:gs($.status,$.json)};w=$.json??{};const L=A(w);if(L)return L;if(w.caller==="unconfirmed")return z()}if(w.caller==="pending"){const $={code:E,state:"pending",at:s.now()};s.progress?.({sticky:$});const D=s.now()+gf;for(let L=!1;;){if(!L&&s.now()>=D&&(L=!0),await s.sleep(L?vf:hf),o())return{kind:"cancelled"};if(l=await u("/unit/remote-access"),o())return{kind:"cancelled"};if(l===null)return{kind:"device",probe:{ok:!1,status:0}};const U=vs(l);if(U)return{kind:"phone",issue:U};if(l.status!==200)return{kind:"device",probe:gs(l.status,l.json)};w=l.json??{};const K=A(w);if(K)return K;if(!(w.caller==="pending"&&!L)){if(w.caller==="unconfirmed"||w.caller==="pending")return z();break}}}}else if(l.status!==404)return{kind:"device",probe:gs(l.status,l.json)};const f=await u("/engine/agent/sessions");if(o())return{kind:"cancelled"};if(f===null)return{kind:"device",probe:{ok:!1,status:0}};const v=vs(f);return v?{kind:"phone",issue:v}:f.status<200||f.status>=300?{kind:"device",probe:gs(f.status,f.json)}:(s.progress?.({probe:{ok:!0}}),await s.select({kind:"unit",unitId:n}),{kind:"selected"})}const wf=1e4,xf=8e3,bf=50,jf={sessions:[],fetchedAt:null,loading:!1};async function Sf(){if(typeof window.tangu?.unitSelf=="function")try{const e=await window.tangu.unitSelf();return{id:e?.unitId?e.unitId.toLowerCase():null,registered:!!e?.registered}}catch{}try{const e=await window.tangu?.unitHostStatus?.();if(e?.unitId)return{id:e.unitId.toLowerCase(),registered:null}}catch{}return{id:null,registered:null}}function Nf(e,n){return e.filter(s=>!!s&&typeof s.id=="string"&&ei(s.id)&&(s.kind??"desktop")==="desktop"&&s.id.toLowerCase()!==n)}function Cf(e){const n=e?.sessions;if(!Array.isArray(n))return[];const s=[];for(const i of n){if(!i||typeof i!="object")continue;const o=i;if(typeof o.id!="string"||!o.id||o.id.length>200||o.archived)continue;const{location:r,...c}=o;s.push({...c,title:typeof c.title=="string"?c.title:""})}return s}function wt(e){return{kind:"unit",unitId:e.toLowerCase()}}const me=Qn((e,n)=>({gen:0,units:null,byUnit:{},refreshedAt:0,selfRegistered:null,refreshRoster:async()=>{if(!Lr()||!window.tangu?.unitsList)return null;const s=n().gen;let i=null;try{const c=await window.tangu.unitsList();c?.status===200&&Array.isArray(c.json?.units)&&(i=c.json.units)}catch{}if(s!==n().gen)return null;if(!i)return n().units;const o=await Sf(),r=Nf(i,o.id);if(s!==n().gen)return null;for(const c of r)gu(wt(c.id),c.name);return e({units:r,selfRegistered:o.registered}),r},refresh:async(s={})=>{if(!Lt())return;const i=n().gen,o=await n().refreshRoster();if(!o||i!==n().gen||(await Promise.all(o.map(u=>zf(u,i,!!s.force,!!s.periodic))),i!==n().gen))return;const r=new Set(o.map(u=>u.id.toLowerCase())),c=Object.fromEntries(Object.entries(n().byUnit).filter(([u])=>r.has(u)));e({byUnit:c,refreshedAt:Date.now()}),Mf()},reset:()=>{e(s=>({gen:s.gen+1,units:null,byUnit:{},refreshedAt:0,selfRegistered:null})),hu()}}));function dt(e,n){const s=e.toLowerCase();me.setState(i=>({byUnit:{...i.byUnit,[s]:{...i.byUnit[s]??jf,...n}}}))}async function zf(e,n,s,i=!1){const o=e.id.toLowerCase(),r=me.getState().byUnit[o];if(i&&Ef(wn.getState().probes[o]))return;if(!e.online){dt(o,{sessions:[],loading:!1});return}if(me.getState().selfRegistered===!1){dt(o,{sessions:[],loading:!1});return}if(e.capsLive&&e.caps?.engine&&e.caps.engine!=="ready"){dt(o,{sessions:[],loading:!1});return}if(!s&&r?.fetchedAt&&Date.now()-r.fetchedAt<wf)return;const c=Jt(wt(o));if(c){dt(o,{loading:!0});try{const u=await $r(c,`/agent/sessions?archived=false&limit=${bf}&app_id=${encodeURIComponent(jr)}`,{},{timeoutMs:xf});let l=null;try{l=await u.json()}catch{}if(n!==me.getState().gen)return;if(!u.ok){const v=l??{},w=Mo({status:u.status,code:v.code,state:v.state,reason:v.reason});ra(o,w),dt(o,{sessions:pr(o,w),fetchedAt:Date.now(),loading:!1});return}const p=wt(o),f=Cf(l).filter(v=>Jn(v.id,p)?(console.warn(`[device-sessions] dropped session ${v.id} listed by ${o}: that id already belongs to another location`),!1):!0);ra(o,{ok:!0}),dt(o,{sessions:f,fetchedAt:Date.now(),loading:!1})}catch(u){if(n!==me.getState().gen)return;const l=Mo(u);ra(o,l),dt(o,{sessions:pr(o,l),fetchedAt:Date.now(),loading:!1})}}}function Ef(e){if(!e||e.ok)return!1;const n=vu(e.status,{code:e.code});return n==="caller-unavailable"||n==="gone"||n==="account-auth?"}function pr(e,n){return Ka(n)==="unreachable"?me.getState().byUnit[e]?.sessions??[]:[]}function Mf(){const e=me.getState().byUnit,n=new Map;for(const[r,c]of Object.entries(e))for(const u of c.sessions)xn(Dr(u.id),wt(r))&&n.set(u.id,u);if(!n.size)return;const s=I.getState();let i=!1;const o=s.sessions.map(r=>{const c=r.location?.kind==="unit"?n.get(r.id):void 0;return!c||c.title===r.title&&c.updated_at===r.updated_at&&c.summary===r.summary?r:(i=!0,{...r,title:c.title,updated_at:c.updated_at,summary:c.summary})});i&&I.setState({sessions:o})}function Tt(e,n=Date.now()){const s=wn.getState(),i=e.id.toLowerCase(),o=ff(e,s.probes[i]??null,s.sticky[i]??null,n);return o.status==="checking"&&me.getState().selfRegistered===!1&&cc(e)?{status:"ready"}:o}function Ya(e){const n=e.toLowerCase();return me.getState().units?.find(s=>s.id.toLowerCase()===n)??null}function Xa(e,n){if(!e?.id||!ei(n.unitId))return!1;const s=wt(n.unitId);if(ku(e.id,s)==="conflict")return console.warn(`[device-sessions] refused to open ${e.id} on ${s.unitId}: that id already belongs to another location`),!1;const{location:i,...o}=e,r=wu(o);return I.setState(c=>({sessions:[r,...c.sessions.filter(u=>u.id!==e.id)],configBySession:c.configBySession[e.id]||!e.agent_config?c.configBySession:{...c.configBySession,[e.id]:e.agent_config}})),(Ms.getState().activeSpaceId==="home"||Ms.getState().activeSpaceId==="inbox")&&_r("tangu"),Pr(e.id),!0}async function Gh(e,n){if(!Lt()||!ei(e)||!n)return!1;const s=wt(e);if(Jn(n,s))return!1;const i=I.getState();if((i.sessions.find(u=>u.id===n)??i.archivedSessions.find(u=>u.id===n))&&xn(Dr(n),s))return(Ms.getState().activeSpaceId==="home"||Ms.getState().activeSpaceId==="inbox")&&_r("tangu"),Pr(n),!0;const r=me.getState().byUnit[s.unitId]?.sessions.find(u=>u.id===n);if(r)return Xa(r,s);const c=Jt(s);if(!c)return!1;try{const u=await yu(c,n);return!u||u.id!==n?!1:Xa(u,s)}catch{return!1}}async function Af(e,n,s){const i=wt(e),o=Jt(i);if(!o||Jn(n,i))return;const r=u=>u.id===n?{...u,title:s}:u,c=me.getState().byUnit[i.unitId];c&&dt(i.unitId,{sessions:c.sessions.map(r)}),I.setState(u=>({sessions:u.sessions.map(l=>l.location?.kind==="unit"?r(l):l)}));try{await ti(o,n,{title:s})}catch(u){I.getState().toast(I.getState().tr("app.renameFail",{e:u?.message||u}),!0)}}async function Rf(e,n,s){const i=wt(e),o=Jt(i);if(!o||Jn(n,i))return!1;const r=xu(s);if(s!==null&&!r)return I.getState().toast(I.getState().tr("session.icon.invalid"),!0),!1;try{const c=await ti(o,n,{emoji:r}),u=p=>p.id===n?{...p,emoji:c.emoji}:p,l=me.getState().byUnit[i.unitId];return l&&dt(i.unitId,{sessions:l.sessions.map(u)}),I.setState(p=>({sessions:p.sessions.map(f=>f.location&&xn(f.location,i)?u(f):f),archivedSessions:p.archivedSessions.map(f=>f.location&&xn(f.location,i)?u(f):f)})),!0}catch(c){return I.getState().toast(I.getState().tr("session.icon.saveFail",{e:c?.message||c}),!0),!1}}async function Tf(e,n){const s=wt(e),i=Jt(s);if(!i||Jn(n,s))return;try{await ti(i,n,{archived:!0})}catch(r){I.getState().toast(r?.message||String(r),!0);return}const o=me.getState().byUnit[s.unitId];o&&dt(s.unitId,{sessions:o.sessions.filter(r=>r.id!==n)}),I.setState(r=>({sessions:r.sessions.filter(c=>!(c.id===n&&c.location?.kind==="unit"))})),I.getState().activeId===n&&I.getState().setActiveId(null)}let mr=I.getState().cfg?.token??"";I.subscribe(e=>{const n=e.cfg?.token??"";n!==mr&&(mr=n,me.getState().reset())});$s.subscribe(()=>me.getState().reset());const st=Qn(()=>({draftSeq:0,explicitSeq:null,reconciledSeq:null,explicitPending:!1,chooser:null}));function Jh(e){return st.setState({chooser:e}),()=>{st.getState().chooser===e&&st.setState({chooser:null})}}const If="forsion_run_location:";function uc(){const e=bu();return e?`${If}${e}`:null}function Lf(){const e=uc();if(!e)return null;try{const n=localStorage.getItem(e);return n===null?null:pf(n)}catch{return null}}function dc(e){const n=uc();if(n)try{localStorage.setItem(n,rc(e))}catch{}}async function fr(e,n){if(!n.explicit){await Na(e,{name:n.name??null});return}dc(e),st.setState({explicitPending:!0});try{await Na(e,{name:n.name??null})}finally{st.setState(s=>({explicitSeq:s.draftSeq,explicitPending:!1}))}}let hr=!1,Ga=!1;function pc(){if(!Lt())return!1;const e=st.getState();if(I.getState().activeId||e.explicitPending||e.explicitSeq===e.draftSeq||e.reconciledSeq===e.draftSeq)return!1;const n=Su();let s=Lf();hr||(hr=!0,s===null&&n.kind==="unit"&&(s=n,dc(n)));let i=Rs,o=null;if(s?.kind==="unit"){if(me.getState().units===null)return!1;const r=Ya(s.unitId);if(r){const c=Tt(r).status;if(c==="checking")return!1;c==="ready"&&(i=s,o=r.name)}}if(st.setState({reconciledSeq:e.draftSeq}),!xn(i,n)){Ga=!0;let r;try{r=Na(i,{name:o})}finally{Ga=!1}r.catch(()=>{})}return!0}ju(()=>{if(Ga)return;const e=st.getState();st.setState({explicitSeq:I.getState().activeId?e.draftSeq+1:e.draftSeq})});const $f=1e4;let ba=I.getState().activeId;I.subscribe(e=>{if(e.activeId===ba)return;const n=ba;if(ba=e.activeId,n&&!e.activeId){st.setState(i=>({draftSeq:i.draftSeq+1}));const s=me.getState();Date.now()-s.refreshedAt<$f?pc():s.refresh().catch(()=>{})}});me.subscribe((e,n)=>{e.refreshedAt!==n.refreshedAt&&pc()});je({"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 ui({emoji:e,fallback:n,size:s=17}){return e?t.jsx("span",{"data-session-emoji":e,"aria-hidden":"true",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:s,height:s,flexShrink:0,fontSize:s,lineHeight:1},children:e}):t.jsx(t.Fragment,{children:n??t.jsx(Ir,{size:s})})}function Qh({params:e,size:n}){const s=I(i=>{const o=e.followActive!==!1?i.activeId:e.sessionId;return i.sessions.find(r=>r.id===o)?.emoji??i.archivedSessions.find(r=>r.id===o)?.emoji});return t.jsx(ui,{emoji:s,size:n})}function mc({sessionId:e,current:n,x:s,y:i,onClose:o,onSave:r}){const c=d.useRef(!1),u=async l=>{if(!c.current){c.current=!0;try{await(r?r(l):I.getState().setSessionEmoji(e,l))&&o()}finally{c.current=!1}}};return Qa.createPortal(t.jsx(Ed,{x:s,y:i,current:n,onPick:l=>{u(l)},onClose:o}),document.body)}const fc=({open:e,children:n})=>{const s=sd();return t.jsx(ad,{initial:!1,children:e&&t.jsx(Nu.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:s?0:.24,ease:[.2,.8,.3,1]},style:{overflow:"hidden"},children:n})})};function Df({path:e,fallback:n,className:s}){const i=I(u=>u.projectSettingsByPath[e]?.icon),o=I(u=>u.projectIconUrls[e]),r=I(u=>u.connState==="ok"),c=cl(i);return d.useEffect(()=>{r&&I.getState().ensureProjectSettings(e)},[e,r]),d.useEffect(()=>{r&&c&&I.getState().loadProjectIcon(e)},[e,r,c]),c?o?t.jsx("img",{className:s,src:o,alt:"",draggable:!1}):t.jsx(t.Fragment,{children:n}):i?t.jsx("span",{className:s,"aria-hidden":"true",children:i}):t.jsx(t.Fragment,{children:n})}je({"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 hc({title:e,message:n,confirmLabel:s,filesLabel:i,onConfirm:o,onClose:r}){const[c,u]=d.useState(!1);return Qa.createPortal(t.jsx("div",{className:"am-app tangu-lovable",style:{display:"contents"},"data-remove-dialog":!0,children:t.jsx(Cr,{title:e,message:n,confirmLabel:s,onConfirm:()=>o(!!i&&c),onClose:r,children:i&&t.jsxs("label",{className:"dialog-check",children:[t.jsx("input",{type:"checkbox",checked:c,onChange:l=>u(l.target.checked)}),t.jsx("span",{children:i})]})})}),document.body)}function Zh({agent:e,onDone:n,onClose:s}){const{t:i}=Ee(),o=!!e.libraryDir,r=e.name||e.slug;return t.jsx(hc,{title:i("agentRemove.title",{name:r}),message:i(o?"agentRemove.msg":"agentRemove.msgCloud"),confirmLabel:i("agentRemove.confirm"),filesLabel:o&&window.tangu?.trashHostPath?i("agentRemove.files"):void 0,onConfirm:c=>{const u=I.getState();u.removeAgent(e,c).then(()=>{u.toast(i("agentRemove.done",{name:r})),n?.()}).catch(l=>u.toast(String(l?.message||l),!0))},onClose:s})}const gc="forsion_orbits_pinned_entries_v1",Yn=(e,n)=>Object.prototype.hasOwnProperty.call(e,n);function ys(e,n){return Yn(e,n)}function vc(e,n){let s=0;for(const i of Object.values(e))Number.isFinite(i)&&(s=Math.max(s,i));return Math.max(n,s+1)}function eg(e,n,s=Date.now()){if(Yn(e,n)){const i={...e};return delete i[n],i}return{...e,[n]:vc(e,s)}}function tg(e,n,s=Date.now()){return Yn(e,n)?{...e,[n]:vc(e,s)}:e}function ng(e=typeof localStorage>"u"?null:localStorage){if(!e)return{};try{const n=JSON.parse(e.getItem(gc)||"{}");if(!n||typeof n!="object"||Array.isArray(n))return{};const s={};for(const[i,o]of Object.entries(n))i&&Number.isFinite(o)&&Number(o)>0&&(s[i]=Number(o));return s}catch{return{}}}function sg(e,n=typeof localStorage>"u"?null:localStorage){try{n?.setItem(gc,JSON.stringify(e))}catch{}}function gr(e,n){return e.map((s,i)=>({entry:s,index:i})).sort((s,i)=>{const o=Yn(n,s.entry.key),r=Yn(n,i.entry.key);return o!==r?o?-1:1:o&&r?n[i.entry.key]-n[s.entry.key]||s.index-i.index:i.entry.at-s.entry.at||s.index-i.index}).map(({entry:s})=>s)}je({"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 yc=({n:e,localOnly:n})=>{const{t:s}=Ee();return t.jsx("span",{className:"t2s-dot attention","data-attention":e,title:s(n?"sidebar.attentionLocalOnly":"sidebar.attention",{n:e})})};je({"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 _f=["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(" "),Ja=2e4;function kc(e){const n=[];for(const s of e){if(s.role!=="user"&&s.role!=="assistant")continue;const i=(s.role==="assistant"?Eu(s.content).text:s.content).trim();i&&n.push(`${s.role==="user"?"User":"Assistant"}:
44
+ ${i}`)}return n.join(`
45
+
46
+ `)}function Pf(e){const n=kc(e);return n.length>Ja?n.slice(-Ja):n}function Of(e,n){const s=/^\s*#[ \t]+(.+?)[ \t]*#*[ \t]*(?:\r?\n|$)/.exec(e);return{title:(s?s[1]:n).replace(/[\\/:*?"<>|#^[\]]/g," ").replace(/\s+/g," ").trim().slice(0,80)||n,body:(s?e.slice(s[0].length):e).replace(/^\s*\n/,"")}}function Ff(){return Cu()&&!!Or()?.complete}async function Uf(e,n){for(let s=1;s<=20;s++){const i=`${s===1?e:`${e}-${s}`}.md`;if(await Ao.readTextFile?.(i)?.catch(()=>null)!=null)continue;const o=await Ao.writeTextFile(i,n,{create:!0,base:ll("")});if(!(o&&o.ok===!1))return i}return null}async function Wf(e){const n=Or()?.complete;if(!n)return!1;const s=I.getState(),i=[...s.sessions,...s.archivedSessions].find(o=>o.id===e);try{s.messagesBySession[e]?.length||await s.loadSessionHistory(e);const o=I.getState().messagesBySession[e]||[],r=Pf(o);if(!r)return ds({text:Be("chat.toNote.empty"),level:"info",inAppOnly:!0}),!1;ds({text:Be(kc(o).length>Ja?"chat.toNote.workingTail":"chat.toNote.working"),level:"info",inAppOnly:!0});const c=await n({action:"custom",instruction:_f,selection:r,title:i?.title||void 0});if(!c.text.trim())throw new Error(Be("chat.toNote.emptyAnswer"));const{title:u,body:l}=Of(c.text,i?.title?.trim()||Be("amadeus.default.note")),p=await Uf(u,l.trimEnd()+`
47
+ `);if(!p)throw new Error(Be("chat.toNote.nameTaken"));return ds({text:Be("chat.toNote.done",{name:u}),level:"success",receipt:!0}),zu(p),!0}catch(o){return ds({text:Be("chat.toNote.failed",{reason:o instanceof Error?o.message:String(o)}),level:"error",inAppOnly:!0}),!1}}const vr={wechat:Tu,telegram:Ru,qq:fn};je({"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 wc="forsion_tangu_collapsed_projects",xc="forsion_tangu_workspace_order";function Bf(){try{return new Set(JSON.parse(localStorage.getItem(wc)||"[]"))}catch{return new Set}}function yr(e){try{localStorage.setItem(wc,JSON.stringify([...e]))}catch{}}function qf(){try{const e=JSON.parse(localStorage.getItem(xc)||"[]");return Array.isArray(e)?e.filter(n=>typeof n=="string"):[]}catch{return[]}}function Hf(e){try{localStorage.setItem(xc,JSON.stringify(e))}catch{}}function Ts(e){const n=String(e||"").trim();if(!n)return 0;const s=Date.parse(n.includes("T")?n:n.replace(" ","T"));return Number.isFinite(s)?s:0}const Vf=({icon:e,title:n,active:s,onClick:i,onExpand:o,act:r})=>t.jsxs("button",{className:`t2s-special${s?" active":""}`,"data-act":r,onClick:i,children:[t.jsx("span",{className:"t2s-special-ic",children:e}),t.jsx("span",{className:"t2s-special-title",children:n}),o&&t.jsx("span",{className:"t2s-special-go",onClick:c=>{c.stopPropagation(),o()},children:t.jsx(It,{size:14})})]}),ag=e=>{const{t:n}=Ee(),s=d.useRef(null),i=d.useRef(null);id(i,e.timeline?e.onSearch:void 0);const o=e.allSessions??e.sessions,r=e.allArchived??e.archivedSessions,c=Mu(s),[u,l]=d.useState(null),[p,f]=d.useState(null),[v,w]=d.useState(null),[E,A]=d.useState(""),[z,b]=d.useState(()=>{try{return Math.max(1,Number(localStorage.getItem("tangu_ws_session_limit"))||5)}catch{return 5}});d.useEffect(()=>{const h=()=>{try{b(Math.max(1,Number(localStorage.getItem("tangu_ws_session_limit"))||5))}catch{}};return window.addEventListener("tangu:wslimit",h),()=>window.removeEventListener("tangu:wslimit",h)},[]);const[$,D]=d.useState(!1),[L,U]=d.useState(Bf),[K,R]=d.useState(qf),[x,O]=d.useState(null),[J,ee]=d.useState(null),Q=d.useRef(null),H=d.useRef(!1),[C,_]=d.useState(null),[q,Z]=d.useState(null),[oe,re]=d.useState(null),[g,P]=d.useState(""),G=d.useRef(null),he=op(h=>h.channels),we=d.useMemo(()=>{const h=new Map;for(const F of he)h.set(F.kind,F.runtime.some(j=>j.running));return h},[he]),Ce=d.useMemo(()=>{const h=new Map;for(const F of e.workspaces)h.set(F.key,[]);for(const F of e.sessions){const j=sa(F,e.workspaces);h.has(j)||h.set(j,[]),h.get(j).push(F)}return h},[e.workspaces,e.sessions]),de=d.useMemo(()=>{const h=new Map(e.workspaces.map(X=>[X.key,X])),F=[];for(const X of K){const ce=h.get(X);ce&&(F.push(ce),h.delete(X))}const j=[...h.values()].sort((X,ce)=>(X.kind==="channel"?-1:0)-(ce.kind==="channel"?-1:0));return[...F,...j]},[e.workspaces,K]),xe=x?de.findIndex(h=>h.key===x):-1,Ie=d.useMemo(()=>{if(e.timeline)return gr([...(e.extraRows||[]).map(j=>({key:`row:${j.key}`,at:j.at,node:j.node})),...e.sessions.map(j=>({key:`ses:${j.id}`,at:Ts(j.updated_at),session:j}))],e.pinnedEntries||{});const h=de.map(j=>({key:`ws:${j.key}`,ws:j,at:(Ce.get(j.key)||[]).reduce((X,ce)=>Math.max(X,Ts(ce.updated_at)),0)}));if(e.orderBy!=="activity")return h;const F=(e.extraRows||[]).map(j=>({key:`row:${j.key}`,at:j.at,node:j.node}));return gr([...F,...h],e.pinnedEntries||{})},[de,Ce,e.orderBy,e.extraRows,e.pinnedEntries,e.timeline,e.sessions]),B=e.orderBy!=="activity",ne=h=>{const F=x;if(O(null),ee(null),!F||F===h)return;const j=de.map(le=>le.key),X=j.indexOf(h);if(X<0||!j.includes(F))return;const ce=Pu(j,F,X);R(ce),Hf(ce)},se=h=>{U(F=>{const j=new Set(F);return j.has(h)?j.delete(h):j.add(h),yr(j),j})},ye=h=>{U(F=>{if(!F.has(h))return F;const j=new Set(F);return j.delete(h),yr(j),j})},Le=h=>{e.onEnterWorkspace?.(h),ye(h)};d.useEffect(()=>{if(!H.current){H.current=!0;return}e.activeWorkspaceKey!=null&&ye(e.activeWorkspaceKey)},[e.activeWorkspaceKey]),d.useEffect(()=>{v&&Q.current?.select()},[v]),d.useEffect(()=>{oe&&G.current?.select()},[oe]),d.useEffect(()=>{if(!u&&!C)return;const h=()=>{l(null),_(null)};return window.addEventListener("click",h),window.addEventListener("contextmenu",h),()=>{window.removeEventListener("click",h),window.removeEventListener("contextmenu",h)}},[u,C]);const te=(h,F)=>{h.preventDefault(),h.stopPropagation(),_(null);const j=c.batch(F.id);j.length===1&&c.only(F.id),l({id:F.id,ids:j,x:h.clientX,y:h.clientY,archived:!!F.archived})},Me=(h,F)=>{h.preventDefault(),h.stopPropagation(),l(null),_({ws:F,x:h.clientX,y:h.clientY})},He=()=>{v&&E.trim()&&e.onRename(v,E.trim()),w(null)},Je=h=>{const F=[...o,...r].find(X=>X.id===h),j=()=>{A(F?.title||""),w(h)};{j();return}},Qt=h=>{const F=()=>{P(h.name),re(h.key)};{F();return}},Ze=h=>{const F=[],j=h.ids.length===1,X=j?[...o,...r].find(le=>le.id===h.id):void 0;j&&F.push({id:"open-new-tab",label:n("sidebar.openInNewTab"),icon:t.jsx(Cs,{size:13}),run:()=>{e.onSelect(h.id,{newTab:!0}),l(null)}}),j&&F.push({id:"set-icon",label:n("session.icon.set"),icon:t.jsx(Hr,{size:13}),run:()=>{f({id:h.id,current:X?.emoji??null,x:h.x,y:h.y}),l(null)}}),j&&F.push({id:"rename",label:n("sidebar.rename"),icon:t.jsx(Vn,{size:13}),run:()=>{l(null),Je(h.id)}}),j&&Ff()&&F.push({id:"to-note",label:n("chat.toNote.action"),icon:t.jsx(Od,{size:13}),run:()=>{Wf(h.id),l(null)}}),F.push({id:h.archived?"unarchive":"archive",label:h.ids.length>1?n(h.archived?"sidebar.unarchiveN":"sidebar.archiveN",{n:String(h.ids.length)}):h.archived?n("sidebar.unarchive"):n("sidebar.archive"),icon:h.archived?t.jsx(Ro,{size:13}):t.jsx(bs,{size:13}),run:()=>{for(const le of h.ids)e.onArchive(le,!h.archived);c.clear(),l(null)}});const ce=X?.project_path?e.workspaces.find(le=>le.kind==="channel"&&le.key===X.project_path):null;if(X&&ce?.channel){const le=vr[ce.channel];F.push({id:"channel-connect",label:n("sidebar.channel.setAsConnected"),icon:t.jsx(le,{size:13}),run:()=>{l(null),Iu(kt(),ce.channel,h.id).then(()=>e.onToast?.(n("sidebar.wechat.setConnectedOk"))).catch(Ve=>e.onToast?.(n("sidebar.wechat.setConnectedFail",{e:Ve?.message||Ve}),!0))}})}return h.ids.every(le=>e.archivedSessions.some(Ve=>Ve.id===le))&&F.push({id:"delete",danger:!0,icon:t.jsx(ws,{size:13}),label:h.ids.length>1?n("sidebar.deleteN",{n:String(h.ids.length)}):n("sidebar.delete"),run:()=>{const le=h.ids;if(l(null),!!(le.length>1?window.confirm(n("sidebar.deleteConfirmN",{n:String(le.length)})):window.confirm(n("sidebar.deleteConfirm",{name:yt(X?.title,n)})))){for(const rt of le)e.onDelete(rt);c.clear()}}}),F},k=h=>{const F=[];if(e.onTogglePinned){const j=`ws:${h.ws.key}`,X=ys(e.pinnedEntries||{},j);F.push({id:X?"unpin":"pin",label:n(X?"sidebar.unpin":"sidebar.pin"),icon:X?t.jsx(Do,{size:13}):t.jsx(ps,{size:13}),run:()=>{_(null),e.onTogglePinned?.(j)}})}return e.onShowWorkspaceDetails&&ca(h.ws)&&[...o,...r].some(j=>j.project_path===h.ws.path&&!j.projectless)&&F.push({id:"ws-details",act:"ws-details",label:n("sidebar.ws.details"),icon:t.jsx(Lu,{size:13}),run:()=>{const j=h.ws;_(null),e.onShowWorkspaceDetails?.(j)}}),h.ws.system||(F.push({id:"ws-rename",label:n("sidebar.ws.rename"),icon:t.jsx(Vn,{size:13}),run:()=>{const j=h.ws;_(null),Qt(j)}}),F.push({id:"ws-remove",act:"ws-remove",danger:!0,label:n("sidebar.ws.remove"),icon:t.jsx(ws,{size:13}),run:()=>{Z(h.ws),_(null)}})),F},V=h=>{if(h.ids.length!==1)return;const F=[...o,...r].find(j=>j.id===h.id);return yt(F?.title,n)},W=Ea(u,()=>u&&{title:V(u),sections:[{items:Ze(u)}]},()=>l(null)),ze=Ea(C,()=>C&&{title:Fn(C.ws,n),sections:[{items:k(C)}]},()=>_(null)),_e=()=>{if(oe&&g.trim()){const h=e.workspaces.find(F=>F.key===oe);h&&e.onRenameWorkspace(h,g.trim())}re(null)},De=(h,F)=>{const j=h.kind==="channel"?vr[h.channel||"wechat"]:h.kind==="cloud"?hn:h.kind==="rootless"?fn:F?bn:_u;return t.jsxs("span",{className:"t2s-lead",children:[ca(h)?t.jsx(Df,{path:h.path,className:"amx-page-emoji t2s-project-icon",fallback:t.jsx(j,{className:"t2s-lead-icon"})}):t.jsx(j,{className:"t2s-lead-icon"}),t.jsx("span",{className:`t2s-chev t2s-lead-chev${F?"":" open"}`,onClick:X=>{X.stopPropagation(),se(h.key)},children:t.jsx(It,{size:12})})]})},it=h=>{const F=[];if(!h.archived&&e.onTogglePinned){const X=ys(e.pinnedEntries||{},`ses:${h.id}`);F.push({id:X?"unpin":"pin",label:n(X?"sidebar.unpin":"sidebar.pin"),icon:X?t.jsx(Do,{}):t.jsx(ps,{}),run:()=>e.onTogglePinned?.(`ses:${h.id}`)})}h.archived||F.push({id:"rename",label:n("sidebar.rename"),icon:t.jsx(Vn,{}),run:()=>Je(h.id)}),F.push({id:h.archived?"unarchive":"archive",label:n(h.archived?"sidebar.unarchive":"sidebar.archive"),icon:h.archived?t.jsx(Ro,{}):t.jsx(bs,{}),tone:"accent",run:()=>e.onArchive(h.id,!h.archived)});const j=h.archived?Ze({id:h.id,ids:[h.id],x:0,y:0,archived:!0}).find(X=>X.id==="delete"):void 0;return j&&F.push({id:"delete",label:n("sidebar.delete"),icon:t.jsx(ws,{}),tone:"danger",run:()=>j.run?.()}),F},Ke=h=>{const F=sa(h,e.workspaces),j=e.workspaces.find(X=>X.key===F);return j&&j.kind!=="rootless"&&!j.system?Fn(j,n):""},Pe=h=>{const F=t.jsx(qr,{as:"button",className:`${h.id===e.activeId?"active":""}${c.has(h.id)?" sel":""}`.trim()||void 0,selId:h.id,title:h.summary||h.title||void 0,depth:e.flat?0:1,style:e.timeline?{paddingLeft:void 0}:void 0,lead:t.jsxs(t.Fragment,{children:[t.jsx(ui,{emoji:h.emoji,fallback:e.rowIcon?.(h)??t.jsx(Xn,{className:"t2s-lead-icon t2s-dim"})}),e.attentionIds?.get(h.id)?t.jsx(yc,{n:e.attentionIds.get(h.id).n,localOnly:e.attentionIds.get(h.id).localOnly}):e.runningIds.has(h.id)?t.jsx("span",{className:"t2s-dot running",title:n("sidebar.running")}):e.unreadIds.has(h.id)?t.jsx("span",{className:"t2s-dot unread",title:n("sidebar.unread")}):null]}),trailing:t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"t2s-srow-time",children:Du(h.updated_at)}),t.jsx("span",{className:"t2s-srow-menu",onClick:j=>te(j,h),children:t.jsx(Es,{size:14})})]}),onClick:j=>{const X=c.click(h.id,j);if(X.open==="none")return;e.onSelect(h.id,X.open==="new"?{newTab:!0}:void 0);const ce=e.sessionWorkspaceKeyOf?e.sessionWorkspaceKeyOf(h):sa(h,e.workspaces);ce&&(e.onActivateEntry?.(`ws:${ce}`),Le(ce))},onContextMenu:j=>te(j,h),draggable:!e.timeline&&v!==h.id,onDragStart:j=>{const X=j.currentTarget.getBoundingClientRect();j.dataTransfer.setDragImage(j.currentTarget,j.clientX-X.left,j.clientY-X.top),j.dataTransfer.effectAllowed="copy";const ce=[...o,...r],le=c.batch(h.id).map(Ve=>{const rt=ce.find($t=>$t.id===Ve);return{kind:"session",id:Ve,title:yt(rt?.title,n)}});$u(j.dataTransfer,le),md(j.dataTransfer,{open:()=>e.onSelect(h.id)})},children:v===h.id?t.jsx("input",{ref:Q,className:"t2s-rename",value:E,onChange:j=>A(j.target.value),onBlur:He,onKeyDown:j=>{j.key==="Enter"&&He(),j.key==="Escape"&&w(null)},onClick:j=>j.stopPropagation()}):e.timeline?t.jsxs("span",{className:"t2s-srow-text",children:[t.jsx("span",{className:"t2s-srow-title",children:yt(h.title,n)}),(Ke(h)||h.summary)&&t.jsxs("span",{className:"t2s-srow-sub",children:[Ke(h)&&t.jsx("span",{className:"t2s-srow-tag",children:Ke(h)}),Ke(h)&&h.summary?" · ":"",h.summary]})]}):t.jsx("span",{className:"t2s-srow-title",children:yt(h.title,n)})},h.id);return e.timeline?t.jsx(fd,{actions:it(h),children:F},h.id):F},fe=Au(),ot=(window.tangu?.pickDirectory&&!e.flat||e.archivedSessions.length>0)&&t.jsxs("div",{className:"t2s-foot",children:[window.tangu?.pickDirectory&&!e.flat&&t.jsxs("button",{className:"t2s-add-ws",onClick:e.onAddWorkspace,children:[t.jsx(ai,{size:14})," ",n("sidebar.addLocalWorkspace")]}),e.archivedSessions.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"t2s-srow t2s-archived-toggle",onClick:()=>D(!$),children:[t.jsx("span",{className:"t2s-chev",children:t.jsx(bs,{size:13})}),t.jsx("span",{className:"t2s-srow-title t2s-faint",children:n("sidebar.archived")}),t.jsx("span",{className:"t2s-count",children:e.archivedSessions.length})]}),$&&e.archivedSessions.map(Pe)]})]});return t.jsxs("aside",{className:"t2s-side",ref:s,"data-timeline":e.timeline?"":void 0,children:[t.jsxs("div",{className:"t2s-scroll",ref:i,"data-under-dock":fe?"":void 0,onTouchStart:e.timeline?od:void 0,onDragOver:h=>{x&&(h.preventDefault(),h.dataTransfer.dropEffect="move")},onDrop:h=>{x&&J&&(h.preventDefault(),ne(J))},children:[e.showSpecial&&t.jsx("div",{className:"t2s-special-group",children:t.jsxs("div",{className:"t2s-special-row",children:[t.jsx(Vf,{icon:t.jsx(rd,{}),title:n("sidebar.newChat"),active:!1,onClick:e.onNewChat,act:"new-chat"}),e.mode&&e.onModeChange&&t.jsxs("div",{className:"t2s-vaultseg t2s-mode",role:"tablist","aria-label":n("sidebar.mode.tip"),title:n("sidebar.mode.tip"),children:[t.jsx("div",{className:"t2s-vaultseg-thumb","data-side":e.mode}),["chat","work"].map(h=>t.jsx("button",{type:"button",role:"tab","aria-selected":e.mode===h,"data-mode":h,className:e.mode===h?"on":void 0,onClick:()=>e.onModeChange(h),children:n(h==="chat"?"sidebar.mode.chat":"sidebar.mode.work")},h))]})]})}),e.timeline&&e.onSearch&&t.jsx(cd,{}),e.timeline&&e.timelineHead,e.timeline&&ld(Ie,h=>ys(e.pinnedEntries||{},h.key)?"pinned":ud(h.at)).map(h=>"section"in h?t.jsx(dd,{bucket:h.section},`sec:${h.section}`):h.item.session?Pe(h.item.session):t.jsx(gn.Fragment,{children:h.item.node},h.item.key)),!e.timeline&&Ie.map((h,F)=>{if(h.node)return t.jsx(gn.Fragment,{children:h.node},h.key);const j=h.ws,X=ys(e.pinnedEntries||{},h.key),ce=Ce.get(j.key)||[];if(e.flat)return t.jsx("div",{className:"t2s-group-sessions t2s-flat",children:ce.map(Pe)},j.key);const le=L.has(j.key),Ve={onDragOver:ge=>{if(!x)return;ge.preventDefault(),ge.dataTransfer.dropEffect="move";const xt=x===j.key?null:j.key;J!==xt&&ee(xt)},onDrop:ge=>{x&&(ge.preventDefault(),ge.stopPropagation(),ne(j.key))}},rt=!!x&&J===j.key&&x!==j.key,$t=rt&&xe>=0&&xe<F,ft=$t?le?" drag-over below":"":rt?" drag-over":"";return t.jsxs(gn.Fragment,{children:[t.jsxs("div",{className:`t2s-group${ft}${x===j.key?" dragging":""}`,"data-workspace-key":j.key,"data-pinned":X?"true":void 0,"data-active":e.activeWorkspaceKey===j.key?"true":void 0,style:{paddingLeft:Br(0)},...Wr(()=>[j.path||"",pd("tip.sessions",{count:ce.length})].filter(Boolean)),draggable:B&&oe!==j.key,onContextMenu:ge=>Me(ge,j),onDragStart:ge=>{const xt=ge.currentTarget.getBoundingClientRect();ge.dataTransfer.setDragImage(ge.currentTarget,ge.clientX-xt.left,ge.clientY-xt.top),ge.dataTransfer.effectAllowed="move",O(j.key)},...Ve,onDragEnd:()=>{O(null),ee(null)},children:[oe===j.key?t.jsxs("div",{className:"t2s-group-toggle t2s-folder-row",style:{cursor:"default"},children:[De(j,le),t.jsx("input",{ref:G,className:"t2s-rename",value:g,onChange:ge=>P(ge.target.value),onBlur:_e,onKeyDown:ge=>{ge.key==="Enter"&&_e(),ge.key==="Escape"&&re(null)},onClick:ge=>ge.stopPropagation()})]}):j.kind==="channel"?t.jsxs("button",{className:"t2s-group-toggle t2s-folder-row",onClick:()=>{e.onActivateEntry?.(h.key),le?Le(j.key):se(j.key)},children:[De(j,le),t.jsx("span",{className:"t2s-group-label",children:Fn(j,n)}),X&&t.jsx(ps,{className:"t2o-pin-mark","aria-hidden":"true"}),t.jsx("span",{className:`t2s-mini-dot${we.get(j.channel||"wechat")?" ok":""}`})]}):t.jsxs("button",{className:"t2s-group-toggle t2s-folder-row",onClick:()=>{e.onActivateEntry?.(h.key),le?Le(j.key):se(j.key)},children:[De(j,le),t.jsx("span",{className:"t2s-group-label",children:Fn(j,n)}),X&&t.jsx(ps,{className:"t2o-pin-mark","aria-hidden":"true"})]}),(!j.system||e.onTogglePinned||e.onShowWorkspaceDetails&&ca(j))&&t.jsx("button",{type:"button",className:"t2s-group-add",title:n("sidebar.ws.menu"),onClick:ge=>Me(ge,j),children:t.jsx(Es,{size:14})}),t.jsx("button",{type:"button",className:"t2s-group-add",title:n("sidebar.newChatIn",{name:Fn(j,n)}),onClick:()=>e.onNewInWorkspace(j),children:t.jsx(Cs,{size:14})})]}),t.jsx(fc,{open:!le,children:t.jsxs("div",{className:`t2s-group-sessions${$t&&!le?" drag-over-end":""}`,...Ve,children:[ce.slice(0,z).map(Pe),ce.length>z&&t.jsxs("button",{className:"t2s-viewmore",onClick:()=>e.onOpenWorkspace(j.key),children:[n("sidebar.viewMore")," · ",ce.length-z]})]})})]},j.key)}),e.deviceSections,fe&&ot]}),!fe&&ot,u&&W&&t.jsx(Ca,{className:"ctx-menu",x:u.x,y:u.y,onClick:h=>h.stopPropagation(),children:t.jsx(Ma,{items:Ze(u)})}),p&&t.jsx(mc,{sessionId:p.id,current:p.current,x:p.x,y:p.y,onClose:()=>f(null)}),C&&ze&&t.jsx(Ca,{className:"ctx-menu",x:C.x,y:C.y,onClick:h=>h.stopPropagation(),children:t.jsx(Ma,{items:k(C)})}),q&&t.jsx(hc,{title:n("sidebar.ws.removeTitle",{name:q.name}),message:n("sidebar.ws.removeMsg",{count:[...o,...r].filter(h=>h.project_path===q.key).length}),confirmLabel:n("sidebar.ws.removeAction"),filesLabel:q.kind==="local"&&window.tangu?.trashHostPath?n("sidebar.ws.removeFiles"):void 0,onConfirm:h=>e.onRemoveWorkspace(q,{deleteFiles:h}),onClose:()=>Z(null)})]})};je({"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.me.phone":{zh:"这台手机",en:"this phone"},"devstatus.me.computer":{zh:"这台电脑",en:"this computer"},"devstatus.denied":{zh:"拒绝了{me}",en:"Declined {me}"},"devstatus.callerBlocked":{zh:"不允许{me}运行",en:"Doesn't allow {me}"},"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:"请在那台电脑上允许{me}",en:"Allow {me} on that computer to continue"},"devstatus.long.denied":{zh:"那台电脑拒绝了{me}",en:"That computer declined {me}"},"devstatus.long.callerBlocked":{zh:"那台电脑不允许{me}运行会话,请在它的「设置 › 远程会话」中调整",en:"That computer doesn't let {me} 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 Kt(e,n,s=!1){return e(`devstatus.${s?"long.":""}${n}`,{me:e(Gn()==="desktop"?"devstatus.me.computer":"devstatus.me.phone")})}function vn(e,n){const s=typeof e=="string"?e.trim():"";return s.length>n?`${s.slice(0,n-1)}…`:s}const bc="forsion_device_sections_collapsed";function Kf(){try{const e=JSON.parse(localStorage.getItem(bc)||"[]");return new Set(Array.isArray(e)?e.filter(n=>typeof n=="string").slice(0,200):[])}catch{return new Set}}function Yf(e){try{localStorage.setItem(bc,JSON.stringify([...e]))}catch{}}function Xf({u:e}){return e.icon?t.jsx("span",{className:"t2d-emoji","aria-hidden":!0,children:vn(e.icon,4)}):e.platform==="win32"||e.platform==="linux"?t.jsx(Fr,{className:"t2s-lead-icon"}):t.jsx(za,{className:"t2s-lead-icon"})}function ig(e,n){const s=e?.get(n);return s?t.jsx(yc,{n:s.n,localOnly:s.localOnly}):null}function jc(){const e=I(s=>s.connState),n=$s(s=>s.epoch);d.useEffect(()=>{if(!Lt())return;const s=()=>{me.getState().refresh()},i=()=>{me.getState().refresh({periodic:!0})};s();let o=null;const r=()=>{o&&(clearInterval(o),o=null),(typeof document>"u"||document.visibilityState==="visible")&&(o=setInterval(i,3e4))},c=()=>{document.visibilityState==="visible"&&s(),r()};return r(),document.addEventListener("visibilitychange",c),()=>{document.removeEventListener("visibilitychange",c),o&&clearInterval(o)}},[n]),d.useEffect(()=>{e==="ok"&&Lt()&&me.getState().refresh()},[e])}function og(e){const{t:n}=Ee();jc();const s=me(R=>R.units),i=me(R=>R.byUnit);wn(R=>R.probes),wn(R=>R.sticky);const o=I(R=>R.sessions),r=me(R=>R.selfRegistered);$s(R=>R.epoch);const[c,u]=d.useState(Kf),[l,p]=d.useState(null),[f,v]=d.useState(null),[w,E]=d.useState(null),[A,z]=d.useState(""),b=d.useRef(null);d.useEffect(()=>{w&&b.current?.select()},[w]),d.useEffect(()=>{if(!l)return;const R=()=>p(null),x=O=>{O.key==="Escape"&&p(null)};return window.addEventListener("click",R),window.addEventListener("contextmenu",R),window.addEventListener("keydown",x),()=>{window.removeEventListener("click",R),window.removeEventListener("contextmenu",R),window.removeEventListener("keydown",x)}},[l]);const $=d.useMemo(()=>{const R={};for(const x of s||[]){const O=x.id.toLowerCase();if(!x.online){R[O]=[];continue}const J=i[O]?.sessions??[],ee=new Set(J.map(C=>C.id)),H=[...o.filter(C=>C.location?.kind==="unit"&&C.location.unitId===O&&!ee.has(C.id)&&!C.archived),...J].sort((C,_)=>Ts(_.updated_at)-Ts(C.updated_at));R[O]=e.filter?e.filter(H):H}return R},[s,i,o,e.filter]),D=R=>{const x=$[R.unitId]?.find(O=>O.id===R.id);return[{id:"set-icon",label:n("session.icon.set"),icon:t.jsx(Hr,{size:13}),run:()=>{v({...R,current:x?.emoji??null}),p(null)}},{id:"rename",label:n("sidebar.rename"),icon:t.jsx(Vn,{size:13}),run:()=>{p(null);const O=()=>{z(x?.title||""),E({unitId:R.unitId,id:R.id})};{O();return}}},{id:"archive",label:n("sidebar.archive"),icon:t.jsx(bs,{size:13}),run:()=>{p(null),Tf(R.unitId,R.id)}}]},L=Ea(l,()=>l&&{title:yt(vn($[l.unitId]?.find(R=>R.id===l.id)?.title,200),n),sections:[{items:D(l)}]},()=>p(null));if(!Lt()||!s?.length)return null;const U=R=>{u(x=>{const O=new Set(x);return O.has(R)?O.delete(R):O.add(R),Yf(O),O})},K=()=>{w&&A.trim()&&Af(w.unitId,w.id,A.trim()),E(null)};return t.jsxs("div",{className:"t2d-sections","data-device-sections":!0,children:[s.map(R=>{const x=R.id.toLowerCase(),O=Tt(R).status,J=$[x]??[],ee=c.has(x),Q=vn(R.name,60)||n("engine.target.defaultName");return t.jsxs("div",{className:"t2d-section","data-device-section":x,"data-device-status":O,children:[t.jsx("div",{className:"t2s-group t2d-head",style:{paddingLeft:Br(0)},title:Kt(n,O,!0),children:t.jsxs("button",{type:"button",className:"t2s-group-toggle t2s-folder-row t2d-toggle","aria-expanded":!ee,"aria-label":n("sidebar.device.label",{name:Q}),onClick:()=>U(x),children:[t.jsxs("span",{className:"t2s-lead",children:[t.jsx(Xf,{u:R}),t.jsx("span",{className:`t2s-chev t2s-lead-chev${ee?"":" open"}`,children:t.jsx(It,{size:12})})]}),t.jsx("span",{className:"t2s-group-label t2d-name",children:Q}),t.jsx("span",{className:"t2d-status","data-tone":O==="ready"?"ok":O==="checking"?"wait":"warn",role:"status",children:Kt(n,O)})]})}),t.jsx(fc,{open:!ee,children:t.jsxs("div",{className:"t2s-group-sessions",children:[J.map(H=>t.jsx(qr,{as:w?.id===H.id?"div":"button",className:H.id===e.activeId?"active":void 0,depth:1,title:H.summary||H.title||void 0,lead:t.jsxs(t.Fragment,{children:[t.jsx(ui,{emoji:H.emoji,fallback:t.jsx(Xn,{className:"t2s-lead-icon t2s-dim"})}),e.rowBadge?.(H)??(e.runningIds.has(H.id)?t.jsx("span",{className:"t2s-dot running"}):e.unreadIds.has(H.id)?t.jsx("span",{className:"t2s-dot unread"}):null)]}),trailing:w?.id===H.id?void 0:t.jsx("span",{className:"t2s-srow-menu",role:"button","aria-label":n("sidebar.device.menu"),onClick:C=>{C.stopPropagation(),p({unitId:x,id:H.id,x:C.clientX,y:C.clientY})},children:t.jsx(Es,{size:14})}),onClick:()=>{w?.id!==H.id&&Xa(H,{unitId:x})},onContextMenu:C=>{C.preventDefault(),C.stopPropagation(),p({unitId:x,id:H.id,x:C.clientX,y:C.clientY})},children:w?.id===H.id?t.jsx("input",{ref:b,className:"t2s-rename",value:A,onChange:C=>z(C.target.value),onBlur:K,onKeyDown:C=>{C.key==="Enter"&&K(),C.key==="Escape"&&E(null)},onClick:C=>C.stopPropagation()}):t.jsx("span",{className:"t2s-srow-title","data-remote-session":H.id,children:yt(vn(H.title,200),n)})},H.id)),O==="ready"&&!J.length&&t.jsx("div",{className:"t2d-empty",children:n(r===!1?"sidebar.device.pickFirst":"sidebar.device.empty")})]})})]},x)}),l&&L&&t.jsx(Ca,{className:"ctx-menu",x:l.x,y:l.y,onClick:R=>R.stopPropagation(),children:t.jsx(Ma,{items:D(l)})}),f&&t.jsx(mc,{sessionId:f.id,current:f.current,x:f.x,y:f.y,onSave:R=>Rf(f.unitId,f.id,R),onClose:()=>v(null)})]})}je({"runloc.label":{zh:"运行位置",en:"Run on"},"runloc.cloud":{zh:"云端",en:"Cloud"},"runloc.thisDevice":{zh:"这台电脑",en:"This computer"},"runloc.external":{zh:"外部引擎",en:"External engine"},"runloc.pillTitle":{zh:"新会话在哪运行:{where}",en:"New sessions run on: {where}"},"runloc.others":{zh:"我的其他电脑",en:"My other computers"},"runloc.none":{zh:"这个账号下还没有其他电脑。在另一台电脑上登录同一个账号后,它会出现在这里",en:"No other computers on this account yet. Sign in on another computer with the same account and it shows up here"},"runloc.signIn":{zh:"登录后可选择其他电脑",en:"Sign in to see them"},"runloc.manage":{zh:"管理设备…",en:"Manage devices…"},"runloc.confirmPending":{zh:"请在「{name}」上点「允许」",en:'Click Allow on "{name}"'},"runloc.confirmNotAsked":{zh:"「{name}」还没有允许这台电脑,再点一次会去询问",en:`"{name}" hasn't allowed this computer yet. Click it again to ask`},"runloc.reason.strict":{zh:"「{name}」只允许这类连接查看,不会再询问;请在那台电脑的「设置 › 远程会话」中允许",en:`"{name}" only lets connections like this one view sessions and won't ask again. Allow it in Settings › Remote sessions there`},"runloc.reason.neverPrompts":{zh:"「{name}」不会为这类连接弹框询问;请在那台电脑的「设置 › 远程会话」中允许",en:`"{name}" doesn't ask for connections like this one. Allow it in Settings › Remote sessions there`},"runloc.reason.notSignedIn":{zh:"「{name}」没有登录 Forsion,请先在那台电脑上登录",en:`"{name}" isn't signed in to Forsion. Sign in there first`},"runloc.reason.rosterMiss":{zh:"「{name}」的账号里找不到这台电脑,请确认两台电脑登录的是同一个账号",en:`"{name}" can't find this computer in its account. Make sure both computers use the same account`},"runloc.reason.rosterUnreachable":{zh:"「{name}」暂时无法核对这台电脑,请稍后再试",en:`"{name}" can't check this computer right now. Try again shortly`},"runloc.reason.noAnswer":{zh:"「{name}」上没有人回应确认,请稍后再试",en:'No one answered on "{name}". Try again in a minute'},"runloc.reason.busy":{zh:"「{name}」上待确认的请求太多,请稍后再试",en:'"{name}" has too many requests waiting. Try again shortly'},"runloc.issue.callerUnavailable":{zh:"这台电脑暂时无法证明自己的身份,请稍后重试",en:"This computer couldn't verify its identity. Try again later"},"runloc.issue.callerUnsupported":{zh:"服务器版本过旧,暂不支持在其他电脑上运行",en:"The server is too old to run on another computer"},"runloc.issue.network":{zh:"暂时连不上 Forsion,请检查网络后重试",en:"Can't reach Forsion right now. Check your connection and try again"},"runloc.issue.signedOut":{zh:"登录已失效,请重新登录后再试",en:"Your sign-in has expired. Sign in again and retry"}});const Gf={strict:"runloc.reason.strict","never-prompts":"runloc.reason.neverPrompts","not-signed-in":"runloc.reason.notSignedIn","roster-miss":"runloc.reason.rosterMiss","roster-unreachable":"runloc.reason.rosterUnreachable","no-answer":"runloc.reason.noAnswer",busy:"runloc.reason.busy"},Jf={nativeOnly:"runloc.issue.callerUnavailable",callerUnavailable:"runloc.issue.callerUnavailable",callerUnsupported:"runloc.issue.callerUnsupported",network:"runloc.issue.network",signedOut:"runloc.issue.signedOut"};function kr(e,n,s){const i=s.refusal?.reason;return ii(i)&&(s.status==="callerBlocked"||s.status==="denied"||s.status==="awaitingConfirm")?e(Gf[i],{name:n}):s.status==="awaitingConfirm"?e(s.refusal?.state==="unconfirmed"?"runloc.confirmNotAsked":"runloc.confirmPending",{name:n}):Kt(e,s.status,!0)}function Qf(){const e=me(n=>n.units);return $s(n=>n.epoch),Lt()&&!!e?.length}const Zf=()=>Gn()==="desktop";function rg(){const{t:e}=Ee();jc();const n=Qf(),s=Gt(B=>B.ref);Gt(B=>B.name);const i=me(B=>B.units);wn(B=>B.probes),wn(B=>B.sticky);const o=st(B=>B.chooser);I(B=>B.desktopMode);const r=Zf(),[c,u]=d.useState(!1),[l,p]=d.useState(null),[f,v]=d.useState(null),[w,E]=d.useState(null),[A,z]=d.useState(!1),b=d.useRef(null),$=d.useRef(null),D=d.useRef(null),L=Xt(c),U=()=>{b.current?.abort(),b.current=null,u(!1),p(null),v(null),E(null),Uu()},K=d.useRef(U);K.current=U,d.useEffect(()=>{if(!c)return;const B=ye=>{$.current&&!$.current.contains(ye.target)&&K.current()},ne=ye=>{ye.key==="Escape"&&(K.current(),$.current?.querySelector(".project-pill")?.focus())};window.addEventListener("mousedown",B),window.addEventListener("keydown",ne);const se=requestAnimationFrame(()=>D.current?.querySelector(".project-menu-item.active")?.focus());return()=>{window.removeEventListener("mousedown",B),window.removeEventListener("keydown",ne),cancelAnimationFrame(se)}},[c]),d.useEffect(()=>()=>{b.current?.abort()},[]);const R=B=>Tt(B).status==="offline"&&!(s.kind==="unit"&&s.unitId===B.id.toLowerCase()),x=(i||[]).filter(B=>!R(B)),O=(i||[]).filter(R);if(d.useEffect(()=>{c&&!O.length&&document.activeElement===document.body&&D.current?.querySelector(".project-menu-item.active")?.focus()},[c,O.length]),r?!Lr():!n)return null;const J=Ou(),ee=e(J==="local"?"runloc.thisDevice":J==="cloud"?"runloc.cloud":"runloc.external"),Q=J==="local"?za:J==="cloud"?hn:Md,H=B=>B?.platform==="win32"||B?.platform==="linux"?Fr:za,C=B=>vn(B.name,60)||e("engine.target.defaultName"),_=s.kind==="unit"?Ya(s.unitId):null,q=_?Tt(_).status:null,Z=s.kind==="unit"?vn(ni(s)||_?.name,60)||e("engine.target.defaultName"):ee,oe=s.kind==="home"?Q:H(_),re=r||!!o,g=B=>{const ne=B.id.toLowerCase();b.current?.abort();const se=new AbortController;b.current=se,p(ne),v(ne),E(null),Wu(ne);const ye=Jt({kind:"unit",unitId:ne});if(!ye){b.current=null,p(null),E("signedOut");return}const Le=async te=>({status:te.status,json:await te.json().catch(()=>null)});kf("",ne,{ensureSelf:async()=>({ok:!0,unitId:"",name:""}),fetchJson:async(te,Me)=>{const He=te.slice(te.indexOf("/proxy")+6),Je=Me?.signal??void 0;return Le(He.startsWith("/engine/")?await $r(ye,He.slice(7),Je?{signal:Je}:{},{timeoutMs:15e3}):await Bu(ye,He.endsWith("/request"),{...Je?{signal:Je}:{},timeoutMs:15e3}))},select:te=>(b.current=null,u(!1),p(null),v(null),fr(te,{explicit:!0,name:B.name})),sleep:te=>new Promise(Me=>setTimeout(Me,te)),now:()=>Date.now(),progress:te=>{se.signal.aborted||us(ne,te)}},se.signal).then(te=>{se.signal.aborted||te.kind==="cancelled"||(te.kind==="selected"?us(ne,{probe:{ok:!0}}):te.kind==="device"?us(ne,te):E(te.issue))}).catch(te=>{se.signal.aborted||(us(ne,{probe:{ok:!1,status:0}}),I.getState().toast(te?.message||String(te),!0))}).finally(()=>{b.current===se&&(b.current=null,p(null))})},P=()=>{U(),fr(Rs,{explicit:!0}).catch(()=>{})},G=B=>{U(),I.getState().openSettings(B)},he=B=>{if(!["ArrowDown","ArrowUp","Home","End"].includes(B.key))return;const ne=[...D.current?.querySelectorAll(".project-menu-item:not(:disabled)")||[]];if(!ne.length)return;B.preventDefault();const se=ne.indexOf(document.activeElement),ye=B.key==="Home"?0:B.key==="End"?ne.length-1:se<0?B.key==="ArrowDown"?0:ne.length-1:B.key==="ArrowDown"?(se+1)%ne.length:(se-1+ne.length)%ne.length;ne[ye]?.focus()},we=Lt(),Ce=B=>{const ne=B.id.toLowerCase(),se=Tt(B),ye=l===ne,Le=s.kind==="unit"&&s.unitId===ne,te=se.status==="offline"||se.status==="noEngine",Me=ye?se.status==="awaitingConfirm"?Kt(e,se.status):e("devstatus.checking"):se.status==="checking"?cc(B)?e("devstatus.ready"):"":Kt(e,se.status),He=H(B);return t.jsxs("button",{type:"button",className:`menu-item project-menu-item runloc-row${Le?" active":""}`,role:"menuitemradio","aria-checked":Le,"aria-busy":ye||void 0,disabled:te,title:Kt(e,se.status,!0),"data-run-row":ne,"data-status":se.status,"data-reason":se.refusal?.reason,onClick:()=>g(B),children:[t.jsx(He,{size:14}),t.jsx("span",{className:"grow project-menu-name",children:C(B)}),Me&&t.jsx("span",{className:"runloc-row-status","data-tone":se.status==="ready"||se.status==="checking"&&!ye?"ok":ye||se.status==="checking"?"wait":"warn",children:Me}),t.jsx("span",{className:"project-menu-check",children:Le?t.jsx(at,{size:13}):null})]},ne)},de=f?Ya(f):null,xe=de&&l!==f?Tt(de):null,Ie=w?e(Jf[w]):de&&xe&&xe.status!=="ready"&&xe.status!=="checking"?kr(e,C(de),xe):de&&l===f&&Tt(de).status==="awaitingConfirm"?kr(e,C(de),Tt(de)):null;return t.jsxs("div",{className:`project-selector runloc${c?" is-open":""}`,ref:$,"data-run-location-picker":!0,"data-run-location":rc(s)||"home","data-device-status":q??void 0,children:[t.jsxs("button",{type:"button",className:`composer-chip project-pill runloc-pill${c?" is-open":""}`,title:e("runloc.pillTitle",{where:Z}),"aria-label":e("runloc.pillTitle",{where:Z}),"aria-haspopup":r?"menu":"dialog","aria-expanded":r?c:void 0,disabled:!re,onClick:()=>{if(!r){o?.();return}if(c){U();return}u(!0),we&&me.getState().refresh().catch(()=>{})},children:[t.jsx(oe,{size:13}),t.jsx("span",{className:"project-pill-name",children:Z}),q&&q!=="ready"&&t.jsx("span",{className:"runloc-status","data-tone":q==="checking"?"wait":"warn",children:Kt(e,q)}),re&&t.jsx(yn,{size:12})]}),c&&t.jsxs("div",{ref:B=>{D.current=B,L.ref.current=B},className:"composer-menu project-menu runloc-menu",style:L.style,role:"menu","aria-label":e("runloc.label"),onKeyDown:he,children:[t.jsx("div",{className:"project-menu-list",children:t.jsxs("button",{type:"button",className:`menu-item project-menu-item${s.kind==="home"?" active":""}`,role:"menuitemradio","aria-checked":s.kind==="home","data-run-row":"home",onClick:P,children:[t.jsx(Q,{size:14}),t.jsx("span",{className:"grow project-menu-name",children:ee}),t.jsx("span",{className:"project-menu-check",children:s.kind==="home"?t.jsx(at,{size:13}):null})]})}),t.jsxs("div",{className:"project-menu-section",role:"group","aria-label":e("runloc.others"),children:[t.jsx("div",{className:"menu-section",children:e("runloc.others")}),we&&[...x.map(Ce),...O.length?[t.jsxs("button",{type:"button",className:"menu-item project-menu-item runloc-fold",role:"menuitem","aria-expanded":A,"data-run-offline-fold":!0,onClick:()=>z(B=>!B),children:[t.jsx("span",{className:"grow project-menu-name",children:e("unit.offlineGroup")}),t.jsx("span",{className:"runloc-row-status",children:O.length}),t.jsx(yn,{size:12,className:"runloc-fold-chev"})]},"offline-fold")]:[],...A?O.map(Ce):[]],we&&i!==null&&!i.length&&t.jsx("div",{className:"project-menu-empty",children:e("runloc.none")}),!we&&t.jsxs("button",{type:"button",className:"menu-item project-menu-item project-menu-add",role:"menuitem","data-run-signin":!0,onClick:()=>G("forsion"),children:[t.jsx(Fu,{size:14}),t.jsx("span",{className:"grow",children:e("runloc.signIn")})]}),Ie&&t.jsx("div",{className:"project-menu-empty runloc-notice",role:"status","data-run-notice":!0,children:Ie})]}),t.jsx("div",{className:"project-menu-section project-menu-actions",role:"group",children:t.jsxs("button",{type:"button",className:"menu-item project-menu-item project-menu-add",role:"menuitem","data-run-manage":!0,onClick:()=>G("remote-sessions"),children:[t.jsx(Rr,{size:14}),t.jsx("span",{className:"grow",children:e("runloc.manage")})]})})]})]})}function cg(){const e=Gt(r=>r.ref),n=Gn()==="desktop"&&e.kind==="unit"?e.unitId:null,s=I(r=>r.focusDirs),i=I(r=>r.tr),o=me(r=>n?r.byUnit[n]?.sessions:void 0);return d.useMemo(()=>{if(!n)return null;const r=s?.defaultWsDir||s?.homeDir||null,c=[{key:r||ul,name:i("app.defaultWorkspace"),kind:"local",path:r,system:!0,isDefault:!0,sessionKeys:r?[r]:[],unitId:n}],u=new Set(r?[r]:[]);for(const l of o||[]){const p=typeof l.project_path=="string"?l.project_path:"";!p||l.projectless||u.has(p)||u.size>=50||(u.add(p),c.push({key:p,name:typeof l.project_name=="string"&&l.project_name||p.split(/[\\/]/).filter(Boolean).pop()||p,kind:"local",path:p,unitId:n}))}return c.push({...qu(i),unitId:n}),c},[n,s,i,o])}je({"input.folders.add":{zh:"添加文件夹",en:"Add folder"},"input.folders.addHint":{zh:"添加文件夹:Agent 在里面的读写权限与项目目录相同",en:"Add a folder: the agent gets the same access as in the project folder"},"input.folders.remove":{zh:"移除 {name}",en:"Remove {name}"}});const wr=7,eh=[];function lg(){const{t:e}=Ee(),n=I(l=>{Gn();const p=Hu(l);return Vu(l.sessionMode,p)!=="chat"&&p.kind==="local"&&p.path?p.path:null}),s=I(l=>l.newChatCfg.extraRoots)||eh,i=Gt(l=>l.ref.kind==="unit"),o=window.tangu?.pickDirectory,r=d.useRef(!0);if(d.useEffect(()=>(r.current=!0,()=>{r.current=!1}),[]),!n||i||!o)return null;const c=l=>I.getState().setExecConfig({extraRoots:l},null),u=()=>{o().then(l=>{const p=I.getState().newChatCfg.extraRoots||[];!r.current||!l||l===n||p.includes(l)||p.length>=wr||c([...p,l])})};return t.jsxs(t.Fragment,{children:[s.map(l=>t.jsxs("span",{className:"composer-chip project-pill extra-folder",title:l,"data-extra-folder":l,children:[t.jsx(bn,{size:13}),t.jsx("span",{className:"project-pill-name",children:la(l)}),t.jsx("button",{type:"button",className:"extra-folder-x",title:e("input.folders.remove",{name:la(l)}),"aria-label":e("input.folders.remove",{name:la(l)}),onClick:()=>c((I.getState().newChatCfg.extraRoots||[]).filter(p=>p!==l)),children:t.jsx(pt,{size:12})})]},l)),s.length<wr&&t.jsx("button",{type:"button",className:"composer-chip project-pill extra-folder-add",title:e("input.folders.addHint"),"aria-label":e("input.folders.add"),"data-extra-folder-add":!0,onClick:u,children:t.jsx(ai,{size:13})})]})}je({"engine.target.retry":{zh:"重试",en:"Retry"}});const th={offline:Ra,"engine-unavailable":Kd,"engine-auth":Yu,"caller-unavailable":Sa,refused:Sa,"rate-limited":Zd,gone:Ld,connecting:Yt,failed:Ra},xr={offline:"engine.target.offline","engine-unavailable":"engine.target.engineUnavailable","engine-auth":"engine.target.engineAuth","caller-unavailable":"engine.target.callerUnavailable",refused:"engine.target.refused","rate-limited":"engine.target.rateLimited",gone:"engine.target.gone"},nh=new Set(["offline","engine-unavailable","rate-limited","failed","caller-unavailable","engine-auth","refused"]);function sh(e){const n=Ls(e),s=I(i=>i.connState);return Ur(i=>n.kind==="unit"?i.byKey[Za(n)]:void 0),Ku({connState:s},e)}function ug(e){const{t:n}=Ee(),s=Ls(e),i=sh(e);if(Gt(o=>o.name),!(s.kind!=="unit"||i))return n("engine.target.composerWaiting",{name:ni(s)||n("engine.target.defaultName")})}function dg({fallback:e,sessionId:n}){const{t:s}=Ee(),i=Ls(n),o=Gt(b=>b.ref);Gt(b=>b.name);const r=xn(i,o),c=ni(i),u=i.kind==="unit"?Za(i):null,l=Ur(b=>u?b.byKey[u]:void 0),p=I(b=>b.connState),f=I(b=>b.connMessage);if(!u)return t.jsx(t.Fragment,{children:e});const v=c||s("engine.target.defaultName");let w=null,E="";if(l&&xr[l.state]){w=l.state;const b="code"in l?l.code:void 0,$="refusal"in l?l.refusal:void 0;E=zd(b,$)||s(xr[l.state],{name:v})}else r&&p==="idle"?(w="connecting",E=s("engine.target.connecting",{name:v})):r&&p==="err"&&(w="failed",E=f||s("engine.target.offline",{name:v}));if(!w)return t.jsx(t.Fragment,{children:e});const A=th[w]??Ra,z=()=>{if(r){Xu().catch(()=>{});return}const b=Jt(i);b&&Gu(b).catch(()=>{})};return t.jsxs("div",{className:"t2-quota-advisory t2-target-health","data-target-health":w,role:"status","aria-live":"polite",children:[t.jsxs("span",{className:"t2-quota-advisory-copy",children:[t.jsx(A,{size:14,"aria-hidden":"true",className:w==="connecting"?"spin":void 0}),t.jsx("span",{children:E})]}),nh.has(w)&&t.jsx("span",{className:"t2-quota-advisory-actions",children:t.jsxs("button",{className:"t2-quota-action reset",onClick:z,children:[t.jsx(Ad,{size:12,"aria-hidden":"true"})," ",s("engine.target.retry")]})})]})}export{tg as $,Dp as A,Dh as B,Kh as C,_h as D,_o as E,Fn as F,yt as G,mc as H,ui as I,$p as J,Dd as K,Zh as L,Qh as M,Od as N,og as O,Df as P,Xd as Q,bp as R,ag as S,ig as T,ng as U,Ts as V,ys as W,Vr as X,Do as Y,sg as Z,eg as _,Ah as a,Yo as a0,Eh as a1,zh as a2,Lm as a3,Gh as a4,Fp as a5,ug as a6,cg as a7,Yh as a8,rg as a9,Xh as aa,lg as ab,fc as ac,Gp as ad,Bh as ae,Vh as af,cm as ag,Jd as ah,Uh as ai,Jp as aj,Wh as ak,nt as al,sh as am,Qf as an,qh as ao,Am as ap,Hh as aq,dg as ar,fp as b,hp as c,ff as d,gp as e,Th as f,Mh as g,Ih as h,Jh as i,Lh as j,Fh as k,Tp as l,Ph as m,Cp as n,Np as o,Zr as p,Rh as q,kf as r,fr as s,Oh as t,op as u,Sp as v,cp as w,$h as x,Qr as y,Rp as z};