termdock 1.4.319 → 1.4.320
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.
- package/dist/client/assets/{App-9yy2aYiT.js → App-BF6YvbKL.js} +6 -6
- package/dist/client/assets/App-BF6YvbKL.js.br +0 -0
- package/dist/client/assets/App-BF6YvbKL.js.gz +0 -0
- package/dist/client/assets/{ArchitecturePanel-CHMjbrPM.js → ArchitecturePanel-D1Jca05w.js} +2 -2
- package/dist/client/assets/ArchitecturePanel-D1Jca05w.js.br +0 -0
- package/dist/client/assets/ArchitecturePanel-D1Jca05w.js.gz +0 -0
- package/dist/client/assets/{ChangeWalkthroughPanel-B0JYVVwB.js → ChangeWalkthroughPanel-B59JwhzK.js} +1 -1
- package/dist/client/assets/ChangeWalkthroughPanel-B59JwhzK.js.br +0 -0
- package/dist/client/assets/ChangeWalkthroughPanel-B59JwhzK.js.gz +0 -0
- package/dist/client/assets/{CollaborationMainWorkspace-BJzMdyZc.js → CollaborationMainWorkspace-CS_o2iYt.js} +1 -1
- package/dist/client/assets/CollaborationMainWorkspace-CS_o2iYt.js.br +0 -0
- package/dist/client/assets/CollaborationMainWorkspace-CS_o2iYt.js.gz +0 -0
- package/dist/client/assets/CollaborationTaskContent-WQ5CC-0d.js +2 -0
- package/dist/client/assets/ComputerControlView-CRquP12U.js +5 -0
- package/dist/client/assets/ComputerControlView-CRquP12U.js.br +0 -0
- package/dist/client/assets/ComputerControlView-CRquP12U.js.gz +0 -0
- package/dist/client/assets/{DagPlayground-C1xEyYVK.js → DagPlayground-CAfziHw_.js} +1 -1
- package/dist/client/assets/DagPlayground-CAfziHw_.js.br +0 -0
- package/dist/client/assets/DagPlayground-CAfziHw_.js.gz +0 -0
- package/dist/client/assets/{DiffLab-DcCKWB7G.js → DiffLab-CPlA_7PJ.js} +1 -1
- package/dist/client/assets/DiffLab-CPlA_7PJ.js.br +0 -0
- package/dist/client/assets/DiffLab-CPlA_7PJ.js.gz +0 -0
- package/dist/client/assets/{DiffReview-C1TyvrA9.js → DiffReview-CjEi6PCy.js} +1 -1
- package/dist/client/assets/DiffReview-CjEi6PCy.js.br +0 -0
- package/dist/client/assets/DiffReview-CjEi6PCy.js.gz +0 -0
- package/dist/client/assets/{DiffReviewLab-D784yT2y.js → DiffReviewLab-BFRqRotl.js} +1 -1
- package/dist/client/assets/DiffReviewLab-BFRqRotl.js.br +0 -0
- package/dist/client/assets/DiffReviewLab-BFRqRotl.js.gz +0 -0
- package/dist/client/assets/{DiffViewer-ByAlz2NG.js → DiffViewer-Bh6lvUYN.js} +1 -1
- package/dist/client/assets/DiffViewer-Bh6lvUYN.js.br +0 -0
- package/dist/client/assets/DiffViewer-Bh6lvUYN.js.gz +0 -0
- package/dist/client/assets/{ModelPreview-DxMcmJZy.js → ModelPreview-D_WFk4yX.js} +1 -1
- package/dist/client/assets/ModelPreview-D_WFk4yX.js.br +0 -0
- package/dist/client/assets/ModelPreview-D_WFk4yX.js.gz +0 -0
- package/dist/client/assets/{RightSidebar-CXykcIPb.js → RightSidebar-7C9-PfhA.js} +30 -30
- package/dist/client/assets/RightSidebar-7C9-PfhA.js.br +0 -0
- package/dist/client/assets/RightSidebar-7C9-PfhA.js.gz +0 -0
- package/dist/client/assets/{abnfDiagram-VCTEODGH-DZZIayJV.js → abnfDiagram-VCTEODGH-DDAdRY3H.js} +1 -1
- package/dist/client/assets/abnfDiagram-VCTEODGH-DDAdRY3H.js.br +0 -0
- package/dist/client/assets/abnfDiagram-VCTEODGH-DDAdRY3H.js.gz +0 -0
- package/dist/client/assets/{app-CI3Oh-41.js → app-BRESmgxW.js} +3 -3
- package/dist/client/assets/app-BRESmgxW.js.br +0 -0
- package/dist/client/assets/app-BRESmgxW.js.gz +0 -0
- package/dist/client/assets/{arc-CjpEX_Ug.js → arc-CV9RqbOa.js} +1 -1
- package/dist/client/assets/arc-CV9RqbOa.js.br +0 -0
- package/dist/client/assets/arc-CV9RqbOa.js.gz +0 -0
- package/dist/client/assets/{architectureDiagram-5GKGNRK7-DUx2_xyE.js → architectureDiagram-5GKGNRK7-Ct8CtmBh.js} +1 -1
- package/dist/client/assets/architectureDiagram-5GKGNRK7-Ct8CtmBh.js.br +0 -0
- package/dist/client/assets/architectureDiagram-5GKGNRK7-Ct8CtmBh.js.gz +0 -0
- package/dist/client/assets/{blockDiagram-I7D4REHJ-DP-lXaM3.js → blockDiagram-I7D4REHJ-CVjuOZ0h.js} +1 -1
- package/dist/client/assets/blockDiagram-I7D4REHJ-CVjuOZ0h.js.br +0 -0
- package/dist/client/assets/blockDiagram-I7D4REHJ-CVjuOZ0h.js.gz +0 -0
- package/dist/client/assets/{c4Diagram-7LVT6UL2-DomY5VR-.js → c4Diagram-7LVT6UL2-CSKcN0J-.js} +1 -1
- package/dist/client/assets/c4Diagram-7LVT6UL2-CSKcN0J-.js.br +0 -0
- package/dist/client/assets/c4Diagram-7LVT6UL2-CSKcN0J-.js.gz +0 -0
- package/dist/client/assets/channel-BDjp8qZS.js +1 -0
- package/dist/client/assets/{chunk-2Q5K7J3B-BPtKxDa8.js → chunk-2Q5K7J3B-CF6SP9Cv.js} +1 -1
- package/dist/client/assets/{chunk-5VM5RSS4-CRCqW368.js → chunk-5VM5RSS4-DZhLGwG4.js} +1 -1
- package/dist/client/assets/{chunk-F27PBJKO-Bs1ITIOZ.js → chunk-F27PBJKO-CwqjUNpz.js} +1 -1
- package/dist/client/assets/chunk-F27PBJKO-CwqjUNpz.js.br +0 -0
- package/dist/client/assets/chunk-F27PBJKO-CwqjUNpz.js.gz +0 -0
- package/dist/client/assets/{chunk-IMKFNOWR-Cw7kOnvo.js → chunk-IMKFNOWR-C9WCfeN9.js} +1 -1
- package/dist/client/assets/chunk-IMKFNOWR-C9WCfeN9.js.br +0 -0
- package/dist/client/assets/{chunk-IMKFNOWR-Cw7kOnvo.js.gz → chunk-IMKFNOWR-C9WCfeN9.js.gz} +0 -0
- package/dist/client/assets/{chunk-JWPE2WC7-DBNaGHE2.js → chunk-JWPE2WC7-DUIVW6rN.js} +1 -1
- package/dist/client/assets/{chunk-POPQ4Y6H-B_OEr0FR.js → chunk-POPQ4Y6H-YgwJ3iH4.js} +1 -1
- package/dist/client/assets/{chunk-SVP7TREG-Ct25uRBl.js → chunk-SVP7TREG-A-vVSOuv.js} +1 -1
- package/dist/client/assets/chunk-SVP7TREG-A-vVSOuv.js.br +0 -0
- package/dist/client/assets/chunk-SVP7TREG-A-vVSOuv.js.gz +0 -0
- package/dist/client/assets/{chunk-TICWLB2K-BVxQwSUB.js → chunk-TICWLB2K-akdXuwgx.js} +1 -1
- package/dist/client/assets/chunk-TICWLB2K-akdXuwgx.js.br +0 -0
- package/dist/client/assets/chunk-TICWLB2K-akdXuwgx.js.gz +0 -0
- package/dist/client/assets/{chunk-XXDRQBXY-B6PLILau.js → chunk-XXDRQBXY-Da273BkJ.js} +1 -1
- package/dist/client/assets/classDiagram-ZZMXUADV-CkFBQKLs.js +1 -0
- package/dist/client/assets/classDiagram-v2-VYDZK3BY-CkFBQKLs.js +1 -0
- package/dist/client/assets/{cose-bilkent-JH36ORCC-Df23Xlgg.js → cose-bilkent-JH36ORCC-CGfQhg7T.js} +1 -1
- package/dist/client/assets/cose-bilkent-JH36ORCC-CGfQhg7T.js.br +0 -0
- package/dist/client/assets/{cose-bilkent-JH36ORCC-Df23Xlgg.js.gz → cose-bilkent-JH36ORCC-CGfQhg7T.js.gz} +0 -0
- package/dist/client/assets/{cynefin-OW5HDTMX-Dxy4auKS.js → cynefin-OW5HDTMX-C9RaJCMn.js} +1 -1
- package/dist/client/assets/cynefin-OW5HDTMX-C9RaJCMn.js.br +0 -0
- package/dist/client/assets/cynefin-OW5HDTMX-C9RaJCMn.js.gz +0 -0
- package/dist/client/assets/{cynefinDiagram-5FMLGOSQ-CRypsJyP.js → cynefinDiagram-5FMLGOSQ-C6SWqaZK.js} +1 -1
- package/dist/client/assets/cynefinDiagram-5FMLGOSQ-C6SWqaZK.js.br +0 -0
- package/dist/client/assets/cynefinDiagram-5FMLGOSQ-C6SWqaZK.js.gz +0 -0
- package/dist/client/assets/{dagre-GXQ25YYZ-B2XmJ6IF.js → dagre-GXQ25YYZ-DTMtzPmS.js} +1 -1
- package/dist/client/assets/dagre-GXQ25YYZ-DTMtzPmS.js.br +0 -0
- package/dist/client/assets/dagre-GXQ25YYZ-DTMtzPmS.js.gz +0 -0
- package/dist/client/assets/{diagram-S7CK7UJ4-BQcwNDWz.js → diagram-S7CK7UJ4-CRalzYBW.js} +1 -1
- package/dist/client/assets/diagram-S7CK7UJ4-CRalzYBW.js.br +0 -0
- package/dist/client/assets/diagram-S7CK7UJ4-CRalzYBW.js.gz +0 -0
- package/dist/client/assets/{diagram-UQ7AKVKN-B6LD6n6P.js → diagram-UQ7AKVKN-B5qxEH5p.js} +1 -1
- package/dist/client/assets/diagram-UQ7AKVKN-B5qxEH5p.js.br +0 -0
- package/dist/client/assets/diagram-UQ7AKVKN-B5qxEH5p.js.gz +0 -0
- package/dist/client/assets/{diagram-VSXAHHWV-DDI4SMid.js → diagram-VSXAHHWV-CPSmBWU-.js} +1 -1
- package/dist/client/assets/diagram-VSXAHHWV-CPSmBWU-.js.br +0 -0
- package/dist/client/assets/diagram-VSXAHHWV-CPSmBWU-.js.gz +0 -0
- package/dist/client/assets/{diagram-VX7I27RA-CRq35BVZ.js → diagram-VX7I27RA-CU8A_voC.js} +1 -1
- package/dist/client/assets/diagram-VX7I27RA-CU8A_voC.js.br +0 -0
- package/dist/client/assets/diagram-VX7I27RA-CU8A_voC.js.gz +0 -0
- package/dist/client/assets/{diagram-Z3DM3KII-Br2tE-aw.js → diagram-Z3DM3KII-CtT4QOY-.js} +1 -1
- package/dist/client/assets/diagram-Z3DM3KII-CtT4QOY-.js.br +0 -0
- package/dist/client/assets/diagram-Z3DM3KII-CtT4QOY-.js.gz +0 -0
- package/dist/client/assets/{ebnfDiagram-PWID7BFC-CLERVjPA.js → ebnfDiagram-PWID7BFC-Cvk6Y8JV.js} +1 -1
- package/dist/client/assets/ebnfDiagram-PWID7BFC-Cvk6Y8JV.js.br +0 -0
- package/dist/client/assets/ebnfDiagram-PWID7BFC-Cvk6Y8JV.js.gz +0 -0
- package/dist/client/assets/{erDiagram-RLTQ6QDP-CdjRSsSD.js → erDiagram-RLTQ6QDP-_9Ct2AHs.js} +1 -1
- package/dist/client/assets/erDiagram-RLTQ6QDP-_9Ct2AHs.js.br +0 -0
- package/dist/client/assets/erDiagram-RLTQ6QDP-_9Ct2AHs.js.gz +0 -0
- package/dist/client/assets/{flowDiagram-HODETNUW-CJcQ479Z.js → flowDiagram-HODETNUW-BR29aDF_.js} +1 -1
- package/dist/client/assets/flowDiagram-HODETNUW-BR29aDF_.js.br +0 -0
- package/dist/client/assets/flowDiagram-HODETNUW-BR29aDF_.js.gz +0 -0
- package/dist/client/assets/{ganttDiagram-EL5Y4UJY-CdDCSJ3h.js → ganttDiagram-EL5Y4UJY-BvVG7ism.js} +1 -1
- package/dist/client/assets/ganttDiagram-EL5Y4UJY-BvVG7ism.js.br +0 -0
- package/dist/client/assets/ganttDiagram-EL5Y4UJY-BvVG7ism.js.gz +0 -0
- package/dist/client/assets/{gestureArbiter-D6uN_O0i.js → gestureArbiter-DalDKZKj.js} +1 -1
- package/dist/client/assets/gestureArbiter-DalDKZKj.js.br +0 -0
- package/dist/client/assets/gestureArbiter-DalDKZKj.js.gz +0 -0
- package/dist/client/assets/{gitGraphDiagram-WWUBYQGX-tcLWvosg.js → gitGraphDiagram-WWUBYQGX-BHOjoasY.js} +1 -1
- package/dist/client/assets/gitGraphDiagram-WWUBYQGX-BHOjoasY.js.br +0 -0
- package/dist/client/assets/gitGraphDiagram-WWUBYQGX-BHOjoasY.js.gz +0 -0
- package/dist/client/assets/{index-_7yzQpVq.css → index-B4bEMUyn.css} +1 -1
- package/dist/client/assets/{index-_7yzQpVq.css.br → index-B4bEMUyn.css.br} +0 -0
- package/dist/client/assets/{index-_7yzQpVq.css.gz → index-B4bEMUyn.css.gz} +0 -0
- package/dist/client/assets/{infoDiagram-27XIBGKW-D7ze39D4.js → infoDiagram-27XIBGKW-DgmnLtPV.js} +1 -1
- package/dist/client/assets/{ishikawaDiagram-5VMMS53U-BmvDG55X.js → ishikawaDiagram-5VMMS53U-DoiUx_u1.js} +1 -1
- package/dist/client/assets/ishikawaDiagram-5VMMS53U-DoiUx_u1.js.br +0 -0
- package/dist/client/assets/ishikawaDiagram-5VMMS53U-DoiUx_u1.js.gz +0 -0
- package/dist/client/assets/{journeyDiagram-3NMN7TZE-Ba2oQRdr.js → journeyDiagram-3NMN7TZE-sz2KwGQ4.js} +1 -1
- package/dist/client/assets/journeyDiagram-3NMN7TZE-sz2KwGQ4.js.br +0 -0
- package/dist/client/assets/journeyDiagram-3NMN7TZE-sz2KwGQ4.js.gz +0 -0
- package/dist/client/assets/{kanban-definition-UXKFOSKX-BGrEtfSU.js → kanban-definition-UXKFOSKX-CdAnN6NF.js} +1 -1
- package/dist/client/assets/kanban-definition-UXKFOSKX-CdAnN6NF.js.br +0 -0
- package/dist/client/assets/kanban-definition-UXKFOSKX-CdAnN6NF.js.gz +0 -0
- package/dist/client/assets/{layout-Df_WxQ7_.js → layout-7mCqPnQ2.js} +1 -1
- package/dist/client/assets/layout-7mCqPnQ2.js.br +0 -0
- package/dist/client/assets/layout-7mCqPnQ2.js.gz +0 -0
- package/dist/client/assets/{linear-yjCZ1UPt.js → linear-CtGxEwoA.js} +1 -1
- package/dist/client/assets/linear-CtGxEwoA.js.br +0 -0
- package/dist/client/assets/linear-CtGxEwoA.js.gz +0 -0
- package/dist/client/assets/{mermaid.core-wqB76PXA.js → mermaid.core-BxJ2mx92.js} +5 -5
- package/dist/client/assets/mermaid.core-BxJ2mx92.js.br +0 -0
- package/dist/client/assets/mermaid.core-BxJ2mx92.js.gz +0 -0
- package/dist/client/assets/{mindmap-definition-YA3MSWOX-BvFfuDI9.js → mindmap-definition-YA3MSWOX-Ck2pdDVb.js} +1 -1
- package/dist/client/assets/mindmap-definition-YA3MSWOX-Ck2pdDVb.js.br +0 -0
- package/dist/client/assets/mindmap-definition-YA3MSWOX-Ck2pdDVb.js.gz +0 -0
- package/dist/client/assets/{passwordBootstrap-CeMHRTET.js → passwordBootstrap-gTJ9KuKa.js} +1 -1
- package/dist/client/assets/passwordBootstrap-gTJ9KuKa.js.br +0 -0
- package/dist/client/assets/passwordBootstrap-gTJ9KuKa.js.gz +0 -0
- package/dist/client/assets/{pegDiagram-XKGWAZYB-GFNFRFcn.js → pegDiagram-XKGWAZYB-CYBdOhd0.js} +1 -1
- package/dist/client/assets/pegDiagram-XKGWAZYB-CYBdOhd0.js.br +0 -0
- package/dist/client/assets/pegDiagram-XKGWAZYB-CYBdOhd0.js.gz +0 -0
- package/dist/client/assets/{pieDiagram-E7YTZNPT-i_OnIQ5S.js → pieDiagram-E7YTZNPT-IxFUaefz.js} +1 -1
- package/dist/client/assets/pieDiagram-E7YTZNPT-IxFUaefz.js.br +0 -0
- package/dist/client/assets/pieDiagram-E7YTZNPT-IxFUaefz.js.gz +0 -0
- package/dist/client/assets/{quadrantDiagram-AXDQQJYC-DgclfhW2.js → quadrantDiagram-AXDQQJYC-CSirkHeE.js} +1 -1
- package/dist/client/assets/quadrantDiagram-AXDQQJYC-CSirkHeE.js.br +0 -0
- package/dist/client/assets/quadrantDiagram-AXDQQJYC-CSirkHeE.js.gz +0 -0
- package/dist/client/assets/{railroadDiagram-O6MQD6OU-Bta7NOF1.js → railroadDiagram-O6MQD6OU-CYoi1Ctl.js} +1 -1
- package/dist/client/assets/railroadDiagram-O6MQD6OU-CYoi1Ctl.js.br +0 -0
- package/dist/client/assets/railroadDiagram-O6MQD6OU-CYoi1Ctl.js.gz +0 -0
- package/dist/client/assets/{rdpSession-CVTDBhDb.js → rdpSession-BQ_xI5BI.js} +1 -1
- package/dist/client/assets/rdpSession-BQ_xI5BI.js.br +0 -0
- package/dist/client/assets/rdpSession-BQ_xI5BI.js.gz +0 -0
- package/dist/client/assets/{referenceLongPress-C91ZK5h8.js → referenceLongPress-DfQ5jnsk.js} +1 -1
- package/dist/client/assets/referenceLongPress-DfQ5jnsk.js.br +0 -0
- package/dist/client/assets/referenceLongPress-DfQ5jnsk.js.gz +0 -0
- package/dist/client/assets/{requirementDiagram-BXWQKSXE-CjVvykFZ.js → requirementDiagram-BXWQKSXE-BCoG9aBY.js} +1 -1
- package/dist/client/assets/requirementDiagram-BXWQKSXE-BCoG9aBY.js.br +0 -0
- package/dist/client/assets/requirementDiagram-BXWQKSXE-BCoG9aBY.js.gz +0 -0
- package/dist/client/assets/{sankeyDiagram-P5KCCOFB-DkRiE5xj.js → sankeyDiagram-P5KCCOFB-BM0bKWHQ.js} +1 -1
- package/dist/client/assets/sankeyDiagram-P5KCCOFB-BM0bKWHQ.js.br +0 -0
- package/dist/client/assets/sankeyDiagram-P5KCCOFB-BM0bKWHQ.js.gz +0 -0
- package/dist/client/assets/{sequenceDiagram-WJ2MYXX4-BW-TiTTz.js → sequenceDiagram-WJ2MYXX4-CVc-3QVK.js} +1 -1
- package/dist/client/assets/sequenceDiagram-WJ2MYXX4-CVc-3QVK.js.br +0 -0
- package/dist/client/assets/sequenceDiagram-WJ2MYXX4-CVc-3QVK.js.gz +0 -0
- package/dist/client/assets/{sizeCapture-INFHLROL-CknYHWYz.js → sizeCapture-INFHLROL-70GusSOh.js} +1 -1
- package/dist/client/assets/sizeCapture-INFHLROL-70GusSOh.js.br +0 -0
- package/dist/client/assets/sizeCapture-INFHLROL-70GusSOh.js.gz +0 -0
- package/dist/client/assets/{sparkles-BhmNaa1u.js → sparkles-DbcgKKVd.js} +1 -1
- package/dist/client/assets/{stateDiagram-D77RDMKH-do6p3u1y.js → stateDiagram-D77RDMKH-BCw-OQPL.js} +1 -1
- package/dist/client/assets/stateDiagram-D77RDMKH-BCw-OQPL.js.br +0 -0
- package/dist/client/assets/stateDiagram-D77RDMKH-BCw-OQPL.js.gz +0 -0
- package/dist/client/assets/stateDiagram-v2-MP3YSRHH-C2WqSO6X.js +1 -0
- package/dist/client/assets/{swimlanes-42K2YHIH-BloliwwH.js → swimlanes-42K2YHIH--yebjz0I.js} +1 -1
- package/dist/client/assets/swimlanes-42K2YHIH--yebjz0I.js.br +0 -0
- package/dist/client/assets/swimlanes-42K2YHIH--yebjz0I.js.gz +0 -0
- package/dist/client/assets/swimlanesDiagram-VR7AAH4N-Cyxi7gqq.js +8 -0
- package/dist/client/assets/{timeline-definition-24CTP7MA-DelADR0N.js → timeline-definition-24CTP7MA-B9_XXo4h.js} +1 -1
- package/dist/client/assets/timeline-definition-24CTP7MA-B9_XXo4h.js.br +0 -0
- package/dist/client/assets/timeline-definition-24CTP7MA-B9_XXo4h.js.gz +0 -0
- package/dist/client/assets/{triangle-alert-B5d_l343.js → triangle-alert-DG_BJhJY.js} +1 -1
- package/dist/client/assets/{vennDiagram-4TSXK5OY-BJhlRAwF.js → vennDiagram-4TSXK5OY-BjYW4tQw.js} +1 -1
- package/dist/client/assets/vennDiagram-4TSXK5OY-BjYW4tQw.js.br +0 -0
- package/dist/client/assets/vennDiagram-4TSXK5OY-BjYW4tQw.js.gz +0 -0
- package/dist/client/assets/{videoCompression-CuDMhYU3.js → videoCompression-DrYmE1Ed.js} +1 -1
- package/dist/client/assets/videoCompression-DrYmE1Ed.js.br +0 -0
- package/dist/client/assets/videoCompression-DrYmE1Ed.js.gz +0 -0
- package/dist/client/assets/{wardleyDiagram-VM6X3IG4-3MDCa0Rt.js → wardleyDiagram-VM6X3IG4-DNVW8Yot.js} +1 -1
- package/dist/client/assets/wardleyDiagram-VM6X3IG4-DNVW8Yot.js.br +0 -0
- package/dist/client/assets/wardleyDiagram-VM6X3IG4-DNVW8Yot.js.gz +0 -0
- package/dist/client/assets/{xychartDiagram-S5SC5T6Z-LWuDetCo.js → xychartDiagram-S5SC5T6Z-l7gJBKpK.js} +1 -1
- package/dist/client/assets/xychartDiagram-S5SC5T6Z-l7gJBKpK.js.br +0 -0
- package/dist/client/assets/xychartDiagram-S5SC5T6Z-l7gJBKpK.js.gz +0 -0
- package/dist/client/index.html +2 -2
- package/dist/client/index.html.br +0 -0
- package/dist/client/index.html.gz +0 -0
- package/dist/client/sw.js +1 -1
- package/dist/client/sw.js.br +0 -0
- package/dist/client/sw.js.gz +0 -0
- package/dist/server/utils/settings.js +1 -1
- package/package.json +1 -1
- package/runtime-manifest.json +3 -3
- package/dist/client/assets/App-9yy2aYiT.js.br +0 -0
- package/dist/client/assets/App-9yy2aYiT.js.gz +0 -0
- package/dist/client/assets/ArchitecturePanel-CHMjbrPM.js.br +0 -0
- package/dist/client/assets/ArchitecturePanel-CHMjbrPM.js.gz +0 -0
- package/dist/client/assets/ChangeWalkthroughPanel-B0JYVVwB.js.br +0 -0
- package/dist/client/assets/ChangeWalkthroughPanel-B0JYVVwB.js.gz +0 -0
- package/dist/client/assets/CollaborationMainWorkspace-BJzMdyZc.js.br +0 -0
- package/dist/client/assets/CollaborationMainWorkspace-BJzMdyZc.js.gz +0 -0
- package/dist/client/assets/CollaborationTaskContent-BwHxwcOP.js +0 -2
- package/dist/client/assets/ComputerControlView-CdMNRZsH.js +0 -5
- package/dist/client/assets/ComputerControlView-CdMNRZsH.js.br +0 -0
- package/dist/client/assets/ComputerControlView-CdMNRZsH.js.gz +0 -0
- package/dist/client/assets/DagPlayground-C1xEyYVK.js.br +0 -0
- package/dist/client/assets/DagPlayground-C1xEyYVK.js.gz +0 -0
- package/dist/client/assets/DiffLab-DcCKWB7G.js.br +0 -0
- package/dist/client/assets/DiffLab-DcCKWB7G.js.gz +0 -0
- package/dist/client/assets/DiffReview-C1TyvrA9.js.br +0 -0
- package/dist/client/assets/DiffReview-C1TyvrA9.js.gz +0 -0
- package/dist/client/assets/DiffReviewLab-D784yT2y.js.br +0 -0
- package/dist/client/assets/DiffReviewLab-D784yT2y.js.gz +0 -0
- package/dist/client/assets/DiffViewer-ByAlz2NG.js.br +0 -0
- package/dist/client/assets/DiffViewer-ByAlz2NG.js.gz +0 -0
- package/dist/client/assets/ModelPreview-DxMcmJZy.js.br +0 -0
- package/dist/client/assets/ModelPreview-DxMcmJZy.js.gz +0 -0
- package/dist/client/assets/RightSidebar-CXykcIPb.js.br +0 -0
- package/dist/client/assets/RightSidebar-CXykcIPb.js.gz +0 -0
- package/dist/client/assets/abnfDiagram-VCTEODGH-DZZIayJV.js.br +0 -0
- package/dist/client/assets/abnfDiagram-VCTEODGH-DZZIayJV.js.gz +0 -0
- package/dist/client/assets/app-CI3Oh-41.js.br +0 -0
- package/dist/client/assets/app-CI3Oh-41.js.gz +0 -0
- package/dist/client/assets/arc-CjpEX_Ug.js.br +0 -0
- package/dist/client/assets/arc-CjpEX_Ug.js.gz +0 -0
- package/dist/client/assets/architectureDiagram-5GKGNRK7-DUx2_xyE.js.br +0 -0
- package/dist/client/assets/architectureDiagram-5GKGNRK7-DUx2_xyE.js.gz +0 -0
- package/dist/client/assets/blockDiagram-I7D4REHJ-DP-lXaM3.js.br +0 -0
- package/dist/client/assets/blockDiagram-I7D4REHJ-DP-lXaM3.js.gz +0 -0
- package/dist/client/assets/c4Diagram-7LVT6UL2-DomY5VR-.js.br +0 -0
- package/dist/client/assets/c4Diagram-7LVT6UL2-DomY5VR-.js.gz +0 -0
- package/dist/client/assets/channel-DIO7oiN5.js +0 -1
- package/dist/client/assets/chunk-F27PBJKO-Bs1ITIOZ.js.br +0 -0
- package/dist/client/assets/chunk-F27PBJKO-Bs1ITIOZ.js.gz +0 -0
- package/dist/client/assets/chunk-IMKFNOWR-Cw7kOnvo.js.br +0 -0
- package/dist/client/assets/chunk-SVP7TREG-Ct25uRBl.js.br +0 -0
- package/dist/client/assets/chunk-SVP7TREG-Ct25uRBl.js.gz +0 -0
- package/dist/client/assets/chunk-TICWLB2K-BVxQwSUB.js.br +0 -0
- package/dist/client/assets/chunk-TICWLB2K-BVxQwSUB.js.gz +0 -0
- package/dist/client/assets/classDiagram-ZZMXUADV-DukHh254.js +0 -1
- package/dist/client/assets/classDiagram-v2-VYDZK3BY-DukHh254.js +0 -1
- package/dist/client/assets/cose-bilkent-JH36ORCC-Df23Xlgg.js.br +0 -0
- package/dist/client/assets/cynefin-OW5HDTMX-Dxy4auKS.js.br +0 -0
- package/dist/client/assets/cynefin-OW5HDTMX-Dxy4auKS.js.gz +0 -0
- package/dist/client/assets/cynefinDiagram-5FMLGOSQ-CRypsJyP.js.br +0 -0
- package/dist/client/assets/cynefinDiagram-5FMLGOSQ-CRypsJyP.js.gz +0 -0
- package/dist/client/assets/dagre-GXQ25YYZ-B2XmJ6IF.js.br +0 -0
- package/dist/client/assets/dagre-GXQ25YYZ-B2XmJ6IF.js.gz +0 -0
- package/dist/client/assets/diagram-S7CK7UJ4-BQcwNDWz.js.br +0 -0
- package/dist/client/assets/diagram-S7CK7UJ4-BQcwNDWz.js.gz +0 -0
- package/dist/client/assets/diagram-UQ7AKVKN-B6LD6n6P.js.br +0 -0
- package/dist/client/assets/diagram-UQ7AKVKN-B6LD6n6P.js.gz +0 -0
- package/dist/client/assets/diagram-VSXAHHWV-DDI4SMid.js.br +0 -0
- package/dist/client/assets/diagram-VSXAHHWV-DDI4SMid.js.gz +0 -0
- package/dist/client/assets/diagram-VX7I27RA-CRq35BVZ.js.br +0 -0
- package/dist/client/assets/diagram-VX7I27RA-CRq35BVZ.js.gz +0 -0
- package/dist/client/assets/diagram-Z3DM3KII-Br2tE-aw.js.br +0 -0
- package/dist/client/assets/diagram-Z3DM3KII-Br2tE-aw.js.gz +0 -0
- package/dist/client/assets/ebnfDiagram-PWID7BFC-CLERVjPA.js.br +0 -0
- package/dist/client/assets/ebnfDiagram-PWID7BFC-CLERVjPA.js.gz +0 -0
- package/dist/client/assets/erDiagram-RLTQ6QDP-CdjRSsSD.js.br +0 -0
- package/dist/client/assets/erDiagram-RLTQ6QDP-CdjRSsSD.js.gz +0 -0
- package/dist/client/assets/flowDiagram-HODETNUW-CJcQ479Z.js.br +0 -0
- package/dist/client/assets/flowDiagram-HODETNUW-CJcQ479Z.js.gz +0 -0
- package/dist/client/assets/ganttDiagram-EL5Y4UJY-CdDCSJ3h.js.br +0 -0
- package/dist/client/assets/ganttDiagram-EL5Y4UJY-CdDCSJ3h.js.gz +0 -0
- package/dist/client/assets/gestureArbiter-D6uN_O0i.js.br +0 -0
- package/dist/client/assets/gestureArbiter-D6uN_O0i.js.gz +0 -0
- package/dist/client/assets/gitGraphDiagram-WWUBYQGX-tcLWvosg.js.br +0 -0
- package/dist/client/assets/gitGraphDiagram-WWUBYQGX-tcLWvosg.js.gz +0 -0
- package/dist/client/assets/ishikawaDiagram-5VMMS53U-BmvDG55X.js.br +0 -0
- package/dist/client/assets/ishikawaDiagram-5VMMS53U-BmvDG55X.js.gz +0 -0
- package/dist/client/assets/journeyDiagram-3NMN7TZE-Ba2oQRdr.js.br +0 -0
- package/dist/client/assets/journeyDiagram-3NMN7TZE-Ba2oQRdr.js.gz +0 -0
- package/dist/client/assets/kanban-definition-UXKFOSKX-BGrEtfSU.js.br +0 -0
- package/dist/client/assets/kanban-definition-UXKFOSKX-BGrEtfSU.js.gz +0 -0
- package/dist/client/assets/layout-Df_WxQ7_.js.br +0 -0
- package/dist/client/assets/layout-Df_WxQ7_.js.gz +0 -0
- package/dist/client/assets/linear-yjCZ1UPt.js.br +0 -0
- package/dist/client/assets/linear-yjCZ1UPt.js.gz +0 -0
- package/dist/client/assets/mermaid.core-wqB76PXA.js.br +0 -0
- package/dist/client/assets/mermaid.core-wqB76PXA.js.gz +0 -0
- package/dist/client/assets/mindmap-definition-YA3MSWOX-BvFfuDI9.js.br +0 -0
- package/dist/client/assets/mindmap-definition-YA3MSWOX-BvFfuDI9.js.gz +0 -0
- package/dist/client/assets/passwordBootstrap-CeMHRTET.js.br +0 -0
- package/dist/client/assets/passwordBootstrap-CeMHRTET.js.gz +0 -0
- package/dist/client/assets/pegDiagram-XKGWAZYB-GFNFRFcn.js.br +0 -0
- package/dist/client/assets/pegDiagram-XKGWAZYB-GFNFRFcn.js.gz +0 -0
- package/dist/client/assets/pieDiagram-E7YTZNPT-i_OnIQ5S.js.br +0 -0
- package/dist/client/assets/pieDiagram-E7YTZNPT-i_OnIQ5S.js.gz +0 -0
- package/dist/client/assets/quadrantDiagram-AXDQQJYC-DgclfhW2.js.br +0 -0
- package/dist/client/assets/quadrantDiagram-AXDQQJYC-DgclfhW2.js.gz +0 -0
- package/dist/client/assets/railroadDiagram-O6MQD6OU-Bta7NOF1.js.br +0 -0
- package/dist/client/assets/railroadDiagram-O6MQD6OU-Bta7NOF1.js.gz +0 -0
- package/dist/client/assets/rdpSession-CVTDBhDb.js.br +0 -0
- package/dist/client/assets/rdpSession-CVTDBhDb.js.gz +0 -0
- package/dist/client/assets/referenceLongPress-C91ZK5h8.js.br +0 -0
- package/dist/client/assets/referenceLongPress-C91ZK5h8.js.gz +0 -0
- package/dist/client/assets/requirementDiagram-BXWQKSXE-CjVvykFZ.js.br +0 -0
- package/dist/client/assets/requirementDiagram-BXWQKSXE-CjVvykFZ.js.gz +0 -0
- package/dist/client/assets/sankeyDiagram-P5KCCOFB-DkRiE5xj.js.br +0 -0
- package/dist/client/assets/sankeyDiagram-P5KCCOFB-DkRiE5xj.js.gz +0 -0
- package/dist/client/assets/sequenceDiagram-WJ2MYXX4-BW-TiTTz.js.br +0 -0
- package/dist/client/assets/sequenceDiagram-WJ2MYXX4-BW-TiTTz.js.gz +0 -0
- package/dist/client/assets/sizeCapture-INFHLROL-CknYHWYz.js.br +0 -0
- package/dist/client/assets/sizeCapture-INFHLROL-CknYHWYz.js.gz +0 -0
- package/dist/client/assets/stateDiagram-D77RDMKH-do6p3u1y.js.br +0 -0
- package/dist/client/assets/stateDiagram-D77RDMKH-do6p3u1y.js.gz +0 -0
- package/dist/client/assets/stateDiagram-v2-MP3YSRHH-CBBKJJkB.js +0 -1
- package/dist/client/assets/swimlanes-42K2YHIH-BloliwwH.js.br +0 -0
- package/dist/client/assets/swimlanes-42K2YHIH-BloliwwH.js.gz +0 -0
- package/dist/client/assets/swimlanesDiagram-VR7AAH4N--bexkZyM.js +0 -8
- package/dist/client/assets/timeline-definition-24CTP7MA-DelADR0N.js.br +0 -0
- package/dist/client/assets/timeline-definition-24CTP7MA-DelADR0N.js.gz +0 -0
- package/dist/client/assets/vennDiagram-4TSXK5OY-BJhlRAwF.js.br +0 -0
- package/dist/client/assets/vennDiagram-4TSXK5OY-BJhlRAwF.js.gz +0 -0
- package/dist/client/assets/videoCompression-CuDMhYU3.js.br +0 -0
- package/dist/client/assets/videoCompression-CuDMhYU3.js.gz +0 -0
- package/dist/client/assets/wardleyDiagram-VM6X3IG4-3MDCa0Rt.js.br +0 -0
- package/dist/client/assets/wardleyDiagram-VM6X3IG4-3MDCa0Rt.js.gz +0 -0
- package/dist/client/assets/xychartDiagram-S5SC5T6Z-LWuDetCo.js.br +0 -0
- package/dist/client/assets/xychartDiagram-S5SC5T6Z-LWuDetCo.js.gz +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/videoCompression-
|
|
2
|
-
import{ag as Ut,aN as Ku,by as s,ac as hc,da as Ur,H as Xw,dk as sl,d6 as La,d8 as Kn,b1 as fc,a7 as eh,az as by,bp as j1,cN as Jw,d7 as N0,cy as f0,b6 as vo,j as p0,af as Fu,co as wp,cV as e8,as as Dc,bx as Cu,g as t8,cI as Ph,Z as r8,bb as Qm,bI as Pm,cE as n8,ax as s8,ch as i8,a5 as yy,cf as a8,cC as vy,aa as o8,ah as l8,L as _n,C as pi,X as In,f as c8,d as ul,bg as u8,b0 as Om,dc as d8,dh as Yr,bG as D1,dg as Wt,aD as h8,dq as f8,v as p8,bN as m8,c0 as g8,a4 as ka,bR as x8,cA as tx,cB as rx,cD as nx,W as sx,b$ as b8,cO as y8,t as n0,bo as B1,d5 as v8,_ as Oc,b9 as w8,i as A8,dj as wy,a_ as il,T as $o,db as Gc,df as T8,ci as S8,an as C8,aY as _8,bZ as k8,b_ as L8,P as Ay,V as ix,bO as ax,bA as Ty,n as zs,$ as Oh,cW as Ap,bH as I8,ck as E8,bF as Sy,de as N8,bf as Po,dm as R8,B as cc,e as Ks,u as M8,ak as j8,N as Fm,cv as D8,h as To,bt as B8,bu as Q8,ap as Cy,aB as _y,a6 as Iu,m as ju,cs as Ml,c2 as ky,aw as s0,c as $m,d9 as Ly,aJ as P8,S as sf,bm as af,a as Iy,ar as O8,ae as F8,d3 as $8,c3 as $u,a8 as uc,bE as ox,cz as U8,c7 as Ey,cS as z8,cU as Ny,bB as H8,bD as Q1,cG as W8,cH as G8,c4 as V8,cF as q8,cp as Y8,cm as Z8,cj as K8,c6 as X8,cw as J8,bQ as e9,bP as Ry,cr as t9,bC as lx,aH as r9,a$ as n9,D as s9,aG as cx,bK as i9,q as a9,p as o9,bM as l9,F as c9,c5 as u9,l as d9,cx as h9,r as f9,c1 as p9,au as m9,aA as g9,aC as x9,ba as fd,bk as b9,d0 as y9,bl as v9,ao as w9,d2 as A9,Q as T9,aj as S9,ad as C9,A as _9,b8 as k9,aq as L9,M as I9,di as E9,bT as Tc,b5 as N9,b2 as R9,b3 as M9,b4 as j9,aW as Tp,bU as D9,cb as B9,cl as Q9,b7 as P9,aZ as O9,cT as ux,am as F9,a9 as $9,Y as U9,c_ as z9,dn as Fn,cu as Sc,bS as H9,w as W9,cQ as G9,aV as V9,bc as dx,ca as q9,cM as th,cZ as pd,d1 as Y9,cc as Z9,cR as K9,cJ as X9,cY as Sp,cK as J9,cL as eA,dd as tA,al as rA,bJ as nA,bw as rh,bv as sA,c8 as hx,cd as iA,c9 as uu,ce as aA,a3 as oA,ab as lA,s as cA}from"./app-CI3Oh-41.js";import{b,R as k,r as Xs,a as uA}from"./dnd-BCFAPC0L.js";import{b as dA,c as hA,F as Vc,S as fA,e as pA,h as mA,r as gA,y as xA,d as bA,u as yA}from"./gestureArbiter-D6uN_O0i.js";import{L as vA,l as wA}from"./terminal-C7X98Amf.js";import{T as P1,L as Uu,C as zu,M as AA,G as TA}from"./triangle-alert-B5d_l343.js";import{r as SA}from"./react-XDCjal2T.js";import{u as O1,G as CA}from"./referenceLongPress-C91ZK5h8.js";const _A=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]],My=Ut("archive",_A);const kA=[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M20 8h-5",key:"1vsyxs"}],["path",{d:"M15 10V6.5a2.5 2.5 0 0 1 5 0V10",key:"ag13bf"}],["path",{d:"M15 14h5l-5 6h5",key:"ur5jdg"}]],LA=Ut("arrow-down-a-z",kA);const IA=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],EA=Ut("arrow-down",IA);const NA=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],jy=Ut("arrow-up",NA);const RA=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]],Dy=Ut("bell",RA);const MA=[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]],R0=Ut("bot",MA);const jA=[["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]],DA=Ut("box",jA);const BA=[["path",{d:"M17 19a1 1 0 0 1-1-1v-2a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2a1 1 0 0 1-1 1z",key:"trhst0"}],["path",{d:"M17 21v-2",key:"ds4u3f"}],["path",{d:"M19 14V6.5a1 1 0 0 0-7 0v11a1 1 0 0 1-7 0V10",key:"1mo9zo"}],["path",{d:"M21 21v-2",key:"eo0ou"}],["path",{d:"M3 5V3",key:"1k5hjh"}],["path",{d:"M4 10a2 2 0 0 1-2-2V6a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2a2 2 0 0 1-2 2z",key:"1dd30t"}],["path",{d:"M7 5V3",key:"1t1388"}]],QA=Ut("cable",BA);const PA=[["path",{d:"M16 14v2.2l1.6 1",key:"fo4ql5"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21 7.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3.5",key:"1osxxc"}],["path",{d:"M3 10h5",key:"r794hk"}],["path",{d:"M8 2v4",key:"1cmpym"}],["circle",{cx:"16",cy:"16",r:"6",key:"qoo3c4"}]],OA=Ut("calendar-clock",PA);const FA=[["path",{d:"M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z",key:"18u6gg"}],["circle",{cx:"12",cy:"13",r:"3",key:"1vg3eu"}]],$A=Ut("camera",FA);const UA=[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M7 16h8",key:"srdodz"}],["path",{d:"M7 11h12",key:"127s9w"}],["path",{d:"M7 6h3",key:"w9rmul"}]],zA=Ut("chart-bar",UA);const HA=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],WA=Ut("circle-dot",HA);const GA=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]],of=Ut("circle-question-mark",GA);const VA=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],Hu=Ut("circle",VA);const qA=[["path",{d:"M11 14h10",key:"1w8e9d"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v1.344",key:"1e62lh"}],["path",{d:"m17 18 4-4-4-4",key:"z2g111"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 1.793-1.113",key:"bjbb7m"}],["rect",{x:"8",y:"2",width:"8",height:"4",rx:"1",key:"ublpy"}]],YA=Ut("clipboard-paste",qA);const ZA=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}]],By=Ut("clipboard",ZA);const KA=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6h4",key:"135r8i"}]],m0=Ut("clock-3",KA);const XA=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],JA=Ut("clock",XA);const eT=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],tT=Ut("code",eT);const rT=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 3v18",key:"108xh3"}]],Il=Ut("columns-2",rT);const nT=[["path",{d:"M20 4v7a4 4 0 0 1-4 4H4",key:"6o5b7l"}],["path",{d:"m9 10-5 5 5 5",key:"1kshq7"}]],sT=Ut("corner-down-left",nT);const iT=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],g0=Ut("download",iT);const aT=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],Fc=Ut("external-link",aT);const oT=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}]],lT=Ut("file-code",oT);const cT=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M12 12v6",key:"3ahymv"}],["path",{d:"m15 15-3-3-3 3",key:"15xj92"}]],uT=Ut("file-up",cT);const dT=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}]],Qy=Ut("file",dT);const hT=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 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.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]],Du=Ut("folder-open",hT);const fT=[["path",{d:"M10.7 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 2v4.1",key:"1bw5m7"}],["path",{d:"m21 21-1.9-1.9",key:"1g2n9r"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}]],F1=Ut("folder-search",fT);const pT=[["path",{d:"M20 10a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1h-2.5a1 1 0 0 1-.8-.4l-.9-1.2A1 1 0 0 0 15 3h-2a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",key:"hod4my"}],["path",{d:"M20 21a1 1 0 0 0 1-1v-3a1 1 0 0 0-1-1h-2.9a1 1 0 0 1-.88-.55l-.42-.85a1 1 0 0 0-.92-.6H13a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",key:"w4yl2u"}],["path",{d:"M3 5a2 2 0 0 0 2 2h3",key:"f2jnh7"}],["path",{d:"M3 3v13a2 2 0 0 0 2 2h3",key:"k8epm1"}]],mT=Ut("folder-tree",pT);const gT=[["path",{d:"M12 3v18",key:"108xh3"}],["path",{d:"M3 12h18",key:"1i2n21"}],["rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",key:"h1oib"}]],fx=Ut("grid-2x2",gT);const xT=[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]],$f=Ut("grip-vertical",xT);const bT=[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]],yT=Ut("hash",bT);const vT=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],Qc=Ut("history",vT);const wT=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"r6nss1"}]],AT=Ut("house",wT);const TT=[["path",{d:"M10 8h.01",key:"1r9ogq"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M16 12h.01",key:"1l6xoz"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M7 16h10",key:"wp8him"}],["path",{d:"M8 12h.01",key:"czm47f"}],["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}]],Py=Ut("keyboard",TT);const ST=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],Oy=Ut("layers",ST);const CT=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],_T=Ut("layout-dashboard",CT);const kT=[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]],qc=Ut("layout-grid",kT);const LT=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3",key:"1dcmit"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3",key:"1e4gt3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3",key:"wsl5sc"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3",key:"18trek"}]],IT=Ut("maximize",LT);const ET=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}]],Xu=Ut("message-circle",ET);const NT=[["path",{d:"M5 12h14",key:"1ays0h"}]],Fy=Ut("minus",NT);const RT=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3",key:"hohbtr"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3",key:"5jw1f3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3",key:"198tvr"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3",key:"ph8mxp"}]],MT=Ut("minimize",RT);const jT=[["path",{d:"M18 8V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h8",key:"10dyio"}],["path",{d:"M10 19v-3.96 3.15",key:"1irgej"}],["path",{d:"M7 19h5",key:"qswx4l"}],["rect",{width:"6",height:"10",x:"16",y:"12",rx:"2",key:"1egngj"}]],DT=Ut("monitor-smartphone",jT);const BT=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]],QT=Ut("moon",BT);const PT=[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m15 19-3 3-3-3",key:"11eu04"}],["path",{d:"m19 9 3 3-3 3",key:"1mg7y2"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m5 9-3 3 3 3",key:"j64kie"}],["path",{d:"m9 5 3-3 3 3",key:"l8vdw6"}]],OT=Ut("move",PT);const FT=[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]],$T=Ut("network",FT);const UT=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}],["path",{d:"m8 9 3 3-3 3",key:"12hl5m"}]],zT=Ut("panel-right-close",UT);const HT=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],WT=Ut("panel-left",HT);const GT=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}],["path",{d:"m10 15-3-3 3-3",key:"1pgupc"}]],VT=Ut("panel-right-open",GT);const qT=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],$y=Ut("panel-right",qT);const YT=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]],ZT=Ut("paperclip",YT);const KT=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1",key:"kaeet6"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1",key:"1wsw3u"}]],XT=Ut("pause",KT);const JT=[["path",{d:"M13 21h8",key:"1jsn5i"}],["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],eS=Ut("pen-line",JT);const tS=[["path",{d:"M13 21h8",key:"1jsn5i"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}],["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],rS=Ut("pencil-line",tS);const nS=[["path",{d:"M12 17v5",key:"bb1du9"}],["path",{d:"M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z",key:"1nkz8b"}]],x0=Ut("pin",nS);const sS=[["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"}]],b0=Ut("pin-off",sS);const iS=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]],lf=Ut("play",iS);const aS=[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M17 8a1 1 0 0 1 1 1v4a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1z",key:"1xoxul"}],["path",{d:"M9 8V2",key:"14iosj"}]],oS=Ut("plug",aS);const lS=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],cS=Ut("power",lS);const uS=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],bn=Ut("refresh-cw",uS);const dS=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]],Uy=Ut("rotate-ccw",dS);const hS=[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]],fS=Ut("rotate-cw",hS);const pS=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 12h18",key:"1i2n21"}]],px=Ut("rows-2",pS);const mS=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],jl=Ut("search",mS);const gS=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],i0=Ut("send",gS);const xS=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],bS=Ut("settings",xS);const yS=[["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:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]],vS=Ut("shield-alert",yS);const wS=[["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 12 2 2 4-4",key:"dzmm74"}]],AS=Ut("shield-check",wS);const TS=[["path",{d:"M10 5H3",key:"1qgfaw"}],["path",{d:"M12 19H3",key:"yhmn1j"}],["path",{d:"M14 3v4",key:"1sua03"}],["path",{d:"M16 17v4",key:"1q0r14"}],["path",{d:"M21 12h-9",key:"1o4lsq"}],["path",{d:"M21 19h-5",key:"1rlt1p"}],["path",{d:"M21 5h-7",key:"1oszz2"}],["path",{d:"M8 10v4",key:"tgpxqk"}],["path",{d:"M8 12H3",key:"a7s4jb"}]],Um=Ut("sliders-horizontal",TS);const SS=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],zy=Ut("square",SS);const CS=[["path",{d:"M11 2v2",key:"1539x4"}],["path",{d:"M5 2v2",key:"1yf1q8"}],["path",{d:"M5 3H4a2 2 0 0 0-2 2v4a6 6 0 0 0 12 0V5a2 2 0 0 0-2-2h-1",key:"rb5t3r"}],["path",{d:"M8 15a6 6 0 0 0 12 0v-3",key:"x18d4x"}],["circle",{cx:"20",cy:"10",r:"2",key:"ts1r5v"}]],_S=Ut("stethoscope",CS);const kS=[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]],LS=Ut("sun",kS);const IS=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Rs=Ut("trash-2",IS);const ES=[["path",{d:"M12 4v16",key:"1654pz"}],["path",{d:"M4 7V5a1 1 0 0 1 1-1h14a1 1 0 0 1 1 1v2",key:"e0r10z"}],["path",{d:"M9 20h6",key:"s66wpe"}]],NS=Ut("type",ES);const RS=[["path",{d:"m18.84 12.25 1.72-1.71h-.02a5.004 5.004 0 0 0-.12-7.07 5.006 5.006 0 0 0-6.95 0l-1.72 1.71",key:"yqzxt4"}],["path",{d:"m5.17 11.75-1.71 1.71a5.004 5.004 0 0 0 .12 7.07 5.006 5.006 0 0 0 6.95 0l1.71-1.71",key:"4qinb0"}],["line",{x1:"8",x2:"8",y1:"2",y2:"5",key:"1041cp"}],["line",{x1:"2",x2:"5",y1:"8",y2:"8",key:"14m1p5"}],["line",{x1:"16",x2:"16",y1:"19",y2:"22",key:"rzdirn"}],["line",{x1:"19",x2:"22",y1:"16",y2:"16",key:"ox905f"}]],MS=Ut("unlink",RS);const jS=[["path",{d:"m19 5 3-3",key:"yk6iyv"}],["path",{d:"m2 22 3-3",key:"19mgm9"}],["path",{d:"M6.3 20.3a2.4 2.4 0 0 0 3.4 0L12 18l-6-6-2.3 2.3a2.4 2.4 0 0 0 0 3.4Z",key:"goz73y"}],["path",{d:"M7.5 13.5 10 11",key:"7xgeeb"}],["path",{d:"M10.5 16.5 13 14",key:"10btkg"}],["path",{d:"m12 6 6 6 2.3-2.3a2.4 2.4 0 0 0 0-3.4l-2.6-2.6a2.4 2.4 0 0 0-3.4 0Z",key:"1snsnr"}]],Hy=Ut("unplug",jS);const DS=[["path",{d:"m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5",key:"ftymec"}],["rect",{x:"2",y:"6",width:"14",height:"12",rx:"2",key:"158x01"}]],Wy=Ut("video",DS);const BS=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["path",{d:"M16 9a5 5 0 0 1 0 6",key:"1q6k2b"}]],QS=Ut("volume-1",BS);const PS=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["path",{d:"M16 9a5 5 0 0 1 0 6",key:"1q6k2b"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728",key:"ijwkga"}]],OS=Ut("volume-2",PS);const FS=[["path",{d:"m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72",key:"ul74o6"}],["path",{d:"m14 7 3 3",key:"1r5n42"}],["path",{d:"M5 6v4",key:"ilb8ba"}],["path",{d:"M19 14v4",key:"blhpug"}],["path",{d:"M10 2v2",key:"7u0qdc"}],["path",{d:"M7 8H3",key:"zfb6yr"}],["path",{d:"M21 16h-4",key:"1cnmox"}],["path",{d:"M11 3H9",key:"1obp7u"}]],$S=Ut("wand-sparkles",FS);const US=[["rect",{width:"8",height:"8",x:"3",y:"3",rx:"2",key:"by2w9f"}],["path",{d:"M7 11v4a2 2 0 0 0 2 2h4",key:"xkn7yn"}],["rect",{width:"8",height:"8",x:"13",y:"13",rx:"2",key:"1cgmvn"}]],nh=Ut("workflow",US);function zS(e,t){return e==="webgl"&&t}function Gy(e,t,r){const n=[],a=new Map;for(const c of e){const l=t(c),d=l&&l.trim().length>0?l:"";let p=a.get(d);p||(p={key:d,label:d?Ku(d)??d:r,sessions:[]},a.set(d,p),n.push(p)),p.sessions.push(c)}return n.sort((c,l)=>(c.key===""?1:0)-(l.key===""?1:0))}function HS(e){return e&&e.trim().length>0?e:""}function Vy(e,t,r){const n=[...e],[a]=n.splice(t,1);return a?(n.splice(r,0,a),n.flatMap(c=>c.sessions.map(l=>l.id))):e.flatMap(c=>c.sessions.map(l=>l.id))}function qy(e,t){const r=new Set;return e.flatMap(n=>{const a=[...new Set(n.sessionIds)].filter(c=>t.has(c)&&!r.has(c));return!n.federated&&n.sessionIds.length>0&&a.length===0?[]:(a.forEach(c=>r.add(c)),[{...n,sessionIds:a}])})}function cf(e,t,r,n,a=[],c=[]){const l=new Map(e.map(S=>[S.id,S])),d=qy(c,new Set(l.keys())),p=new Map,m=new Map,x=a.filter(S=>S.sessionIds.length>=2&&S.sessionIds.every(L=>l.has(L))),y=(S,L)=>{const E=l.get(L);S.forEach(R=>{p.set(R,S),m.set(R,E)})};for(const S of d){const L=new Set(S.sessionIds),E=new Map;for(const z of x)z.sessionIds.every(O=>L.has(O))&&z.sessionIds.forEach(O=>E.set(O,z.sessionIds));const R=new Set,B=S.sessionIds.flatMap(z=>{if(R.has(z))return[];const O=E.get(z)??[z];return O.forEach($=>R.add($)),O});y(B,S.sessionIds[0])}for(const S of x)S.sessionIds.some(L=>p.has(L))||y(S.sessionIds,S.sessionIds[0]);const w=S=>{const L=new Set;return S.flatMap(E=>{if(L.has(E.id))return[];const R=p.get(E.id)??[E.id];return R.forEach(B=>L.add(B)),R.map(B=>l.get(B))})};if(!r)return{arranged:w(e),groups:[]};const v=Gy(e,S=>t(m.get(S.id)??S),n).map(S=>({...S,sessions:w(S.sessions)}));return{arranged:v.flatMap(S=>S.sessions),groups:v}}function WS(e){return e.isActive&&e.viewportFocused&&e.documentVisible&&e.windowFocused&&e.streamReady}function GS(e){return e.isActive&&e.documentVisible&&e.streamReady&&(!e.isDesktop||e.windowFocused)}function VS(e){return e.isActive&&!e.isMobile&&e.documentVisible&&!e.activeElementIsEditable}function qS(e,t){return!e&&t}const uf=".termdock/architecture.json",Yy=".termdock/architectures",YS={kind:"project",target:"",paths:[],depth:"boundary",focus:""},ZS=["description","diagram","context","constraint","concern","todo","note"],KS=/^[a-zA-Z][a-zA-Z0-9_-]{0,79}$/;class XS extends Error{}function hs(){throw new XS("Invalid architecture document")}function Cl(e){return(!e||typeof e!="object"||Array.isArray(e))&&hs(),e}function oi(e,t=8e3){return(typeof e!="string"||e.length>t)&&hs(),e}function Cc(e){const t=oi(e,80);return KS.test(t)||hs(),t}function rc(e,t){return(!Array.isArray(e)||e.length>t)&&hs(),e}function mx(e){return Object.fromEntries(ZS.filter(t=>e[t]!==void 0).map(t=>[t,oi(e[t],1e5)]))}function du(e){if(e===void 0)return;const t=Cl(e),r={};for(const n of["created","updated","gitCommit","gitBranch","previousDiagram"])t[n]!==void 0&&(r[n]=oi(t[n],n==="previousDiagram"?1e5:200));return t.updateCount!==void 0&&((!Number.isSafeInteger(t.updateCount)||t.updateCount<0)&&hs(),r.updateCount=t.updateCount),r}function Fh(e){return!!e&&!/[:\\\x00-\x1f]/.test(e)&&!e.startsWith("/")&&e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function $1(e){(!["project","module","feature"].includes(e.kind)||!["boundary","dependencies"].includes(e.depth))&&hs();const t=e.kind==="project"?[]:[...new Set(rc(e.paths,20).map(a=>oi(a,1024).trim()))].sort();t.some(a=>!Fh(a))&&hs();const r=oi(e.target,1e3).trim(),n=oi(e.focus,2e3).trim();return(e.kind==="module"&&!t.length||e.kind==="feature"&&!r)&&hs(),{kind:e.kind,target:e.kind==="project"?"":e.kind==="module"?t.join(`
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/videoCompression-DrYmE1Ed.js","assets/app-BRESmgxW.js","assets/react-XDCjal2T.js","assets/dnd-BCFAPC0L.js","assets/terminal-C7X98Amf.js","assets/index-B4bEMUyn.css","assets/CollaborationTaskContent-WQ5CC-0d.js","assets/RightSidebar-7C9-PfhA.js","assets/gestureArbiter-DalDKZKj.js","assets/gestureArbiter-C2J0D0kV.css","assets/DiffReview-CjEi6PCy.js","assets/sparkles-DbcgKKVd.js","assets/DiffViewer-Bh6lvUYN.js","assets/referenceLongPress-DfQ5jnsk.js","assets/DiffViewer-T3uj2-aP.css","assets/triangle-alert-DG_BJhJY.js","assets/ChangeWalkthroughPanel-B59JwhzK.js","assets/RightSidebar-DW-JEgm2.css","assets/CollaborationMainWorkspace-CS_o2iYt.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{ag as Ut,aN as Ku,by as s,ac as hc,da as Ur,H as Xw,dk as sl,d6 as La,d8 as Kn,b1 as fc,a7 as eh,az as by,bp as j1,cN as Jw,d7 as N0,cy as f0,b6 as vo,j as p0,af as Fu,co as wp,cV as e8,as as Dc,bx as Cu,g as t8,cI as Ph,Z as r8,bb as Qm,bI as Pm,cE as n8,ax as s8,ch as i8,a5 as yy,cf as a8,cC as vy,aa as o8,ah as l8,L as _n,C as pi,X as In,f as c8,d as ul,bg as u8,b0 as Om,dc as d8,dh as Yr,bG as D1,dg as Wt,aD as h8,dq as f8,v as p8,bN as m8,c0 as g8,a4 as ka,bR as x8,cA as tx,cB as rx,cD as nx,W as sx,b$ as b8,cO as y8,t as n0,bo as B1,d5 as v8,_ as Oc,b9 as w8,i as A8,dj as wy,a_ as il,T as $o,db as Gc,df as T8,ci as S8,an as C8,aY as _8,bZ as k8,b_ as L8,P as Ay,V as ix,bO as ax,bA as Ty,n as zs,$ as Oh,cW as Ap,bH as I8,ck as E8,bF as Sy,de as N8,bf as Po,dm as R8,B as cc,e as Ks,u as M8,ak as j8,N as Fm,cv as D8,h as To,bt as B8,bu as Q8,ap as Cy,aB as _y,a6 as Iu,m as ju,cs as Ml,c2 as ky,aw as s0,c as $m,d9 as Ly,aJ as P8,S as sf,bm as af,a as Iy,ar as O8,ae as F8,d3 as $8,c3 as $u,a8 as uc,bE as ox,cz as U8,c7 as Ey,cS as z8,cU as Ny,bB as H8,bD as Q1,cG as W8,cH as G8,c4 as V8,cF as q8,cp as Y8,cm as Z8,cj as K8,c6 as X8,cw as J8,bQ as e9,bP as Ry,cr as t9,bC as lx,aH as r9,a$ as n9,D as s9,aG as cx,bK as i9,q as a9,p as o9,bM as l9,F as c9,c5 as u9,l as d9,cx as h9,r as f9,c1 as p9,au as m9,aA as g9,aC as x9,ba as fd,bk as b9,d0 as y9,bl as v9,ao as w9,d2 as A9,Q as T9,aj as S9,ad as C9,A as _9,b8 as k9,aq as L9,M as I9,di as E9,bT as Tc,b5 as N9,b2 as R9,b3 as M9,b4 as j9,aW as Tp,bU as D9,cb as B9,cl as Q9,b7 as P9,aZ as O9,cT as ux,am as F9,a9 as $9,Y as U9,c_ as z9,dn as Fn,cu as Sc,bS as H9,w as W9,cQ as G9,aV as V9,bc as dx,ca as q9,cM as th,cZ as pd,d1 as Y9,cc as Z9,cR as K9,cJ as X9,cY as Sp,cK as J9,cL as eA,dd as tA,al as rA,bJ as nA,bw as rh,bv as sA,c8 as hx,cd as iA,c9 as uu,ce as aA,a3 as oA,ab as lA,s as cA}from"./app-BRESmgxW.js";import{b,R as k,r as Xs,a as uA}from"./dnd-BCFAPC0L.js";import{b as dA,c as hA,F as Vc,S as fA,e as pA,h as mA,r as gA,y as xA,d as bA,u as yA}from"./gestureArbiter-DalDKZKj.js";import{L as vA,l as wA}from"./terminal-C7X98Amf.js";import{T as P1,L as Uu,C as zu,M as AA,G as TA}from"./triangle-alert-DG_BJhJY.js";import{r as SA}from"./react-XDCjal2T.js";import{u as O1,G as CA}from"./referenceLongPress-DfQ5jnsk.js";const _A=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]],My=Ut("archive",_A);const kA=[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M20 8h-5",key:"1vsyxs"}],["path",{d:"M15 10V6.5a2.5 2.5 0 0 1 5 0V10",key:"ag13bf"}],["path",{d:"M15 14h5l-5 6h5",key:"ur5jdg"}]],LA=Ut("arrow-down-a-z",kA);const IA=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],EA=Ut("arrow-down",IA);const NA=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],jy=Ut("arrow-up",NA);const RA=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]],Dy=Ut("bell",RA);const MA=[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]],R0=Ut("bot",MA);const jA=[["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]],DA=Ut("box",jA);const BA=[["path",{d:"M17 19a1 1 0 0 1-1-1v-2a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2a1 1 0 0 1-1 1z",key:"trhst0"}],["path",{d:"M17 21v-2",key:"ds4u3f"}],["path",{d:"M19 14V6.5a1 1 0 0 0-7 0v11a1 1 0 0 1-7 0V10",key:"1mo9zo"}],["path",{d:"M21 21v-2",key:"eo0ou"}],["path",{d:"M3 5V3",key:"1k5hjh"}],["path",{d:"M4 10a2 2 0 0 1-2-2V6a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2a2 2 0 0 1-2 2z",key:"1dd30t"}],["path",{d:"M7 5V3",key:"1t1388"}]],QA=Ut("cable",BA);const PA=[["path",{d:"M16 14v2.2l1.6 1",key:"fo4ql5"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21 7.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3.5",key:"1osxxc"}],["path",{d:"M3 10h5",key:"r794hk"}],["path",{d:"M8 2v4",key:"1cmpym"}],["circle",{cx:"16",cy:"16",r:"6",key:"qoo3c4"}]],OA=Ut("calendar-clock",PA);const FA=[["path",{d:"M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z",key:"18u6gg"}],["circle",{cx:"12",cy:"13",r:"3",key:"1vg3eu"}]],$A=Ut("camera",FA);const UA=[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M7 16h8",key:"srdodz"}],["path",{d:"M7 11h12",key:"127s9w"}],["path",{d:"M7 6h3",key:"w9rmul"}]],zA=Ut("chart-bar",UA);const HA=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],WA=Ut("circle-dot",HA);const GA=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]],of=Ut("circle-question-mark",GA);const VA=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],Hu=Ut("circle",VA);const qA=[["path",{d:"M11 14h10",key:"1w8e9d"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v1.344",key:"1e62lh"}],["path",{d:"m17 18 4-4-4-4",key:"z2g111"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 1.793-1.113",key:"bjbb7m"}],["rect",{x:"8",y:"2",width:"8",height:"4",rx:"1",key:"ublpy"}]],YA=Ut("clipboard-paste",qA);const ZA=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}]],By=Ut("clipboard",ZA);const KA=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6h4",key:"135r8i"}]],m0=Ut("clock-3",KA);const XA=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],JA=Ut("clock",XA);const eT=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],tT=Ut("code",eT);const rT=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 3v18",key:"108xh3"}]],Il=Ut("columns-2",rT);const nT=[["path",{d:"M20 4v7a4 4 0 0 1-4 4H4",key:"6o5b7l"}],["path",{d:"m9 10-5 5 5 5",key:"1kshq7"}]],sT=Ut("corner-down-left",nT);const iT=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],g0=Ut("download",iT);const aT=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],Fc=Ut("external-link",aT);const oT=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}]],lT=Ut("file-code",oT);const cT=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M12 12v6",key:"3ahymv"}],["path",{d:"m15 15-3-3-3 3",key:"15xj92"}]],uT=Ut("file-up",cT);const dT=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}]],Qy=Ut("file",dT);const hT=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 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.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]],Du=Ut("folder-open",hT);const fT=[["path",{d:"M10.7 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 2v4.1",key:"1bw5m7"}],["path",{d:"m21 21-1.9-1.9",key:"1g2n9r"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}]],F1=Ut("folder-search",fT);const pT=[["path",{d:"M20 10a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1h-2.5a1 1 0 0 1-.8-.4l-.9-1.2A1 1 0 0 0 15 3h-2a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",key:"hod4my"}],["path",{d:"M20 21a1 1 0 0 0 1-1v-3a1 1 0 0 0-1-1h-2.9a1 1 0 0 1-.88-.55l-.42-.85a1 1 0 0 0-.92-.6H13a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",key:"w4yl2u"}],["path",{d:"M3 5a2 2 0 0 0 2 2h3",key:"f2jnh7"}],["path",{d:"M3 3v13a2 2 0 0 0 2 2h3",key:"k8epm1"}]],mT=Ut("folder-tree",pT);const gT=[["path",{d:"M12 3v18",key:"108xh3"}],["path",{d:"M3 12h18",key:"1i2n21"}],["rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",key:"h1oib"}]],fx=Ut("grid-2x2",gT);const xT=[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]],$f=Ut("grip-vertical",xT);const bT=[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]],yT=Ut("hash",bT);const vT=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],Qc=Ut("history",vT);const wT=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"r6nss1"}]],AT=Ut("house",wT);const TT=[["path",{d:"M10 8h.01",key:"1r9ogq"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M16 12h.01",key:"1l6xoz"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M7 16h10",key:"wp8him"}],["path",{d:"M8 12h.01",key:"czm47f"}],["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}]],Py=Ut("keyboard",TT);const ST=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],Oy=Ut("layers",ST);const CT=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],_T=Ut("layout-dashboard",CT);const kT=[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]],qc=Ut("layout-grid",kT);const LT=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3",key:"1dcmit"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3",key:"1e4gt3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3",key:"wsl5sc"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3",key:"18trek"}]],IT=Ut("maximize",LT);const ET=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}]],Xu=Ut("message-circle",ET);const NT=[["path",{d:"M5 12h14",key:"1ays0h"}]],Fy=Ut("minus",NT);const RT=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3",key:"hohbtr"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3",key:"5jw1f3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3",key:"198tvr"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3",key:"ph8mxp"}]],MT=Ut("minimize",RT);const jT=[["path",{d:"M18 8V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h8",key:"10dyio"}],["path",{d:"M10 19v-3.96 3.15",key:"1irgej"}],["path",{d:"M7 19h5",key:"qswx4l"}],["rect",{width:"6",height:"10",x:"16",y:"12",rx:"2",key:"1egngj"}]],DT=Ut("monitor-smartphone",jT);const BT=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]],QT=Ut("moon",BT);const PT=[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m15 19-3 3-3-3",key:"11eu04"}],["path",{d:"m19 9 3 3-3 3",key:"1mg7y2"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m5 9-3 3 3 3",key:"j64kie"}],["path",{d:"m9 5 3-3 3 3",key:"l8vdw6"}]],OT=Ut("move",PT);const FT=[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]],$T=Ut("network",FT);const UT=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}],["path",{d:"m8 9 3 3-3 3",key:"12hl5m"}]],zT=Ut("panel-right-close",UT);const HT=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],WT=Ut("panel-left",HT);const GT=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}],["path",{d:"m10 15-3-3 3-3",key:"1pgupc"}]],VT=Ut("panel-right-open",GT);const qT=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],$y=Ut("panel-right",qT);const YT=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]],ZT=Ut("paperclip",YT);const KT=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1",key:"kaeet6"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1",key:"1wsw3u"}]],XT=Ut("pause",KT);const JT=[["path",{d:"M13 21h8",key:"1jsn5i"}],["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],eS=Ut("pen-line",JT);const tS=[["path",{d:"M13 21h8",key:"1jsn5i"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}],["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],rS=Ut("pencil-line",tS);const nS=[["path",{d:"M12 17v5",key:"bb1du9"}],["path",{d:"M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z",key:"1nkz8b"}]],x0=Ut("pin",nS);const sS=[["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"}]],b0=Ut("pin-off",sS);const iS=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]],lf=Ut("play",iS);const aS=[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M17 8a1 1 0 0 1 1 1v4a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1z",key:"1xoxul"}],["path",{d:"M9 8V2",key:"14iosj"}]],oS=Ut("plug",aS);const lS=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],cS=Ut("power",lS);const uS=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],bn=Ut("refresh-cw",uS);const dS=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]],Uy=Ut("rotate-ccw",dS);const hS=[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]],fS=Ut("rotate-cw",hS);const pS=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 12h18",key:"1i2n21"}]],px=Ut("rows-2",pS);const mS=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],jl=Ut("search",mS);const gS=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],i0=Ut("send",gS);const xS=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],bS=Ut("settings",xS);const yS=[["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:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]],vS=Ut("shield-alert",yS);const wS=[["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 12 2 2 4-4",key:"dzmm74"}]],AS=Ut("shield-check",wS);const TS=[["path",{d:"M10 5H3",key:"1qgfaw"}],["path",{d:"M12 19H3",key:"yhmn1j"}],["path",{d:"M14 3v4",key:"1sua03"}],["path",{d:"M16 17v4",key:"1q0r14"}],["path",{d:"M21 12h-9",key:"1o4lsq"}],["path",{d:"M21 19h-5",key:"1rlt1p"}],["path",{d:"M21 5h-7",key:"1oszz2"}],["path",{d:"M8 10v4",key:"tgpxqk"}],["path",{d:"M8 12H3",key:"a7s4jb"}]],Um=Ut("sliders-horizontal",TS);const SS=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],zy=Ut("square",SS);const CS=[["path",{d:"M11 2v2",key:"1539x4"}],["path",{d:"M5 2v2",key:"1yf1q8"}],["path",{d:"M5 3H4a2 2 0 0 0-2 2v4a6 6 0 0 0 12 0V5a2 2 0 0 0-2-2h-1",key:"rb5t3r"}],["path",{d:"M8 15a6 6 0 0 0 12 0v-3",key:"x18d4x"}],["circle",{cx:"20",cy:"10",r:"2",key:"ts1r5v"}]],_S=Ut("stethoscope",CS);const kS=[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]],LS=Ut("sun",kS);const IS=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Rs=Ut("trash-2",IS);const ES=[["path",{d:"M12 4v16",key:"1654pz"}],["path",{d:"M4 7V5a1 1 0 0 1 1-1h14a1 1 0 0 1 1 1v2",key:"e0r10z"}],["path",{d:"M9 20h6",key:"s66wpe"}]],NS=Ut("type",ES);const RS=[["path",{d:"m18.84 12.25 1.72-1.71h-.02a5.004 5.004 0 0 0-.12-7.07 5.006 5.006 0 0 0-6.95 0l-1.72 1.71",key:"yqzxt4"}],["path",{d:"m5.17 11.75-1.71 1.71a5.004 5.004 0 0 0 .12 7.07 5.006 5.006 0 0 0 6.95 0l1.71-1.71",key:"4qinb0"}],["line",{x1:"8",x2:"8",y1:"2",y2:"5",key:"1041cp"}],["line",{x1:"2",x2:"5",y1:"8",y2:"8",key:"14m1p5"}],["line",{x1:"16",x2:"16",y1:"19",y2:"22",key:"rzdirn"}],["line",{x1:"19",x2:"22",y1:"16",y2:"16",key:"ox905f"}]],MS=Ut("unlink",RS);const jS=[["path",{d:"m19 5 3-3",key:"yk6iyv"}],["path",{d:"m2 22 3-3",key:"19mgm9"}],["path",{d:"M6.3 20.3a2.4 2.4 0 0 0 3.4 0L12 18l-6-6-2.3 2.3a2.4 2.4 0 0 0 0 3.4Z",key:"goz73y"}],["path",{d:"M7.5 13.5 10 11",key:"7xgeeb"}],["path",{d:"M10.5 16.5 13 14",key:"10btkg"}],["path",{d:"m12 6 6 6 2.3-2.3a2.4 2.4 0 0 0 0-3.4l-2.6-2.6a2.4 2.4 0 0 0-3.4 0Z",key:"1snsnr"}]],Hy=Ut("unplug",jS);const DS=[["path",{d:"m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5",key:"ftymec"}],["rect",{x:"2",y:"6",width:"14",height:"12",rx:"2",key:"158x01"}]],Wy=Ut("video",DS);const BS=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["path",{d:"M16 9a5 5 0 0 1 0 6",key:"1q6k2b"}]],QS=Ut("volume-1",BS);const PS=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["path",{d:"M16 9a5 5 0 0 1 0 6",key:"1q6k2b"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728",key:"ijwkga"}]],OS=Ut("volume-2",PS);const FS=[["path",{d:"m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72",key:"ul74o6"}],["path",{d:"m14 7 3 3",key:"1r5n42"}],["path",{d:"M5 6v4",key:"ilb8ba"}],["path",{d:"M19 14v4",key:"blhpug"}],["path",{d:"M10 2v2",key:"7u0qdc"}],["path",{d:"M7 8H3",key:"zfb6yr"}],["path",{d:"M21 16h-4",key:"1cnmox"}],["path",{d:"M11 3H9",key:"1obp7u"}]],$S=Ut("wand-sparkles",FS);const US=[["rect",{width:"8",height:"8",x:"3",y:"3",rx:"2",key:"by2w9f"}],["path",{d:"M7 11v4a2 2 0 0 0 2 2h4",key:"xkn7yn"}],["rect",{width:"8",height:"8",x:"13",y:"13",rx:"2",key:"1cgmvn"}]],nh=Ut("workflow",US);function zS(e,t){return e==="webgl"&&t}function Gy(e,t,r){const n=[],a=new Map;for(const c of e){const l=t(c),d=l&&l.trim().length>0?l:"";let p=a.get(d);p||(p={key:d,label:d?Ku(d)??d:r,sessions:[]},a.set(d,p),n.push(p)),p.sessions.push(c)}return n.sort((c,l)=>(c.key===""?1:0)-(l.key===""?1:0))}function HS(e){return e&&e.trim().length>0?e:""}function Vy(e,t,r){const n=[...e],[a]=n.splice(t,1);return a?(n.splice(r,0,a),n.flatMap(c=>c.sessions.map(l=>l.id))):e.flatMap(c=>c.sessions.map(l=>l.id))}function qy(e,t){const r=new Set;return e.flatMap(n=>{const a=[...new Set(n.sessionIds)].filter(c=>t.has(c)&&!r.has(c));return!n.federated&&n.sessionIds.length>0&&a.length===0?[]:(a.forEach(c=>r.add(c)),[{...n,sessionIds:a}])})}function cf(e,t,r,n,a=[],c=[]){const l=new Map(e.map(S=>[S.id,S])),d=qy(c,new Set(l.keys())),p=new Map,m=new Map,x=a.filter(S=>S.sessionIds.length>=2&&S.sessionIds.every(L=>l.has(L))),y=(S,L)=>{const E=l.get(L);S.forEach(R=>{p.set(R,S),m.set(R,E)})};for(const S of d){const L=new Set(S.sessionIds),E=new Map;for(const z of x)z.sessionIds.every(O=>L.has(O))&&z.sessionIds.forEach(O=>E.set(O,z.sessionIds));const R=new Set,B=S.sessionIds.flatMap(z=>{if(R.has(z))return[];const O=E.get(z)??[z];return O.forEach($=>R.add($)),O});y(B,S.sessionIds[0])}for(const S of x)S.sessionIds.some(L=>p.has(L))||y(S.sessionIds,S.sessionIds[0]);const w=S=>{const L=new Set;return S.flatMap(E=>{if(L.has(E.id))return[];const R=p.get(E.id)??[E.id];return R.forEach(B=>L.add(B)),R.map(B=>l.get(B))})};if(!r)return{arranged:w(e),groups:[]};const v=Gy(e,S=>t(m.get(S.id)??S),n).map(S=>({...S,sessions:w(S.sessions)}));return{arranged:v.flatMap(S=>S.sessions),groups:v}}function WS(e){return e.isActive&&e.viewportFocused&&e.documentVisible&&e.windowFocused&&e.streamReady}function GS(e){return e.isActive&&e.documentVisible&&e.streamReady&&(!e.isDesktop||e.windowFocused)}function VS(e){return e.isActive&&!e.isMobile&&e.documentVisible&&!e.activeElementIsEditable}function qS(e,t){return!e&&t}const uf=".termdock/architecture.json",Yy=".termdock/architectures",YS={kind:"project",target:"",paths:[],depth:"boundary",focus:""},ZS=["description","diagram","context","constraint","concern","todo","note"],KS=/^[a-zA-Z][a-zA-Z0-9_-]{0,79}$/;class XS extends Error{}function hs(){throw new XS("Invalid architecture document")}function Cl(e){return(!e||typeof e!="object"||Array.isArray(e))&&hs(),e}function oi(e,t=8e3){return(typeof e!="string"||e.length>t)&&hs(),e}function Cc(e){const t=oi(e,80);return KS.test(t)||hs(),t}function rc(e,t){return(!Array.isArray(e)||e.length>t)&&hs(),e}function mx(e){return Object.fromEntries(ZS.filter(t=>e[t]!==void 0).map(t=>[t,oi(e[t],1e5)]))}function du(e){if(e===void 0)return;const t=Cl(e),r={};for(const n of["created","updated","gitCommit","gitBranch","previousDiagram"])t[n]!==void 0&&(r[n]=oi(t[n],n==="previousDiagram"?1e5:200));return t.updateCount!==void 0&&((!Number.isSafeInteger(t.updateCount)||t.updateCount<0)&&hs(),r.updateCount=t.updateCount),r}function Fh(e){return!!e&&!/[:\\\x00-\x1f]/.test(e)&&!e.startsWith("/")&&e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function $1(e){(!["project","module","feature"].includes(e.kind)||!["boundary","dependencies"].includes(e.depth))&&hs();const t=e.kind==="project"?[]:[...new Set(rc(e.paths,20).map(a=>oi(a,1024).trim()))].sort();t.some(a=>!Fh(a))&&hs();const r=oi(e.target,1e3).trim(),n=oi(e.focus,2e3).trim();return(e.kind==="module"&&!t.length||e.kind==="feature"&&!r)&&hs(),{kind:e.kind,target:e.kind==="project"?"":e.kind==="module"?t.join(`
|
|
3
3
|
`):r,paths:e.kind==="project"?[]:t,depth:e.depth,focus:n}}function JS(e){const t=$1(e);if(t.kind==="project")return uf;const r=JSON.stringify([t.kind,t.target,t.paths]);let n=2166136261;for(let c=0;c<r.length;c++)n=Math.imul(n^r.charCodeAt(c),16777619);const a=Array.from(t.target.replace(/[^\p{L}\p{N}_-]+/gu,"-").replace(/^-+|-+$/g,"")).slice(0,48).join("")||"analysis";return`${Yy}/${t.kind}-${a}-${(n>>>0).toString(16).padStart(8,"0")}.json`}function Zy(e){return e===".omm"||e===uf||new RegExp(`^${Yy.replace(".","\\.")}/(?:module|feature)-[\\p{L}\\p{N}_-]{1,48}-[a-f0-9]{8}\\.json$`,"u").test(e)}function Z$(e){return e.split("/").pop()?.replace(/^(module|feature)-/,"").replace(/-[a-f0-9]{8}\.json$/,"").replace(/-/g," ")??e}function K$(e){new TextEncoder().encode(e).byteLength>5e6&&hs();let t;try{t=JSON.parse(e)}catch{hs()}const r=Cl(t);r.version!==1&&hs();const n=oi(r.generatedAt,80);Number.isFinite(Date.parse(n))||hs();const a=rc(r.perspectives,12).map(d=>{const p=Cl(d),m=rc(p.nodes,200).map(w=>{const v=Cl(w),S=rc(v.files,40).map(E=>{const R=Cl(E),B=oi(R.path,1024);return Fh(B)||hs(),R.line!==void 0&&(!Number.isSafeInteger(R.line)||R.line<1)&&hs(),{path:B,...R.line!==void 0?{line:R.line}:{}}}),L=v.references===void 0?void 0:rc(v.references,100).map(E=>{const R=Cl(E);return{perspective:Cc(R.perspective),...R.node!==void 0?{node:Cc(R.node)}:{}}});return v.documentPath!==void 0&&!Fh(oi(v.documentPath,1024))&&hs(),v.role!==void 0&&!["external","concern","entry","store"].includes(v.role)&&hs(),{id:Cc(v.id),title:oi(v.title,160),summary:oi(v.summary),files:S,...mx(v),...v.parentId!==void 0?{parentId:Cc(v.parentId)}:{},...v.documentPath!==void 0?{documentPath:oi(v.documentPath,1024)}:{},...du(v.meta)?{meta:du(v.meta)}:{},...L?{references:L}:{},...v.role!==void 0?{role:v.role}:{}}});m.length||hs();const x=new Map(m.map(w=>[w.id,w]));x.size!==m.length&&hs();for(const w of m){const v=new Set([w.id]);let S=w.parentId;for(;S;)(v.has(S)||!x.has(S))&&hs(),v.add(S),S=x.get(S)?.parentId}const y=rc(p.edges,600).map(w=>{const v=Cl(w),S=Cc(v.from),L=Cc(v.to);return(!x.has(S)||!x.has(L))&&hs(),{from:S,to:L,label:oi(v.label,200)}});return{id:Cc(p.id),title:oi(p.title,160),summary:oi(p.summary),nodes:m,edges:y,...mx(p),...du(p.meta)?{meta:du(p.meta)}:{}}});(!a.length||new Set(a.map(d=>d.id)).size!==a.length)&&hs();for(const d of a)for(const p of d.nodes)for(const m of p.references??[]){const x=a.find(y=>y.id===m.perspective);(!x||m.node&&!x.nodes.some(y=>y.id===m.node))&&hs()}const c=r.analysis===void 0?void 0:$1(Cl(r.analysis));let l;if(r.details!==void 0){const d=Cl(r.details),p=rc(d.analyzedPaths,200).map(x=>{const y=oi(x,1024);return Fh(y)||hs(),y}),m=rc(d.limitations,30).map(x=>oi(x,2e3));l={analyzedPaths:p,limitations:m}}return r.origin!==void 0&&!["termdock","omm"].includes(r.origin)&&hs(),{version:1,generatedAt:n,summary:oi(r.summary),perspectives:a,...c?{analysis:c}:{},...l?{details:l}:{},...r.origin?{origin:r.origin}:{},...du(r.meta)?{meta:du(r.meta)}:{}}}function Ky(e,t){const r=e.nodes.filter(d=>d.parentId===t),n=new Map(e.nodes.map(d=>[d.id,d])),a=new Set(r.map(d=>d.id)),c=d=>{let p=n.get(d);for(;p&&!a.has(p.id);)p=p.parentId?n.get(p.parentId):void 0;return p?.id},l=new Map;for(const d of e.edges){const p=c(d.from),m=c(d.to);p&&m&&p!==m&&!l.has(`${p}:${m}`)&&l.set(`${p}:${m}`,{from:p,to:m,label:d.label})}return{nodes:r,edges:[...l.values()]}}function Cp(e){return e.slice(0,100).replace(/[&<>"\[\]{}|`#;\\\r\n]/g," ").trim()||"…"}function X$(e,t,r=0){const n=Ky(e,t),a=[],c=(w,v)=>{for(const S of e.nodes.filter(L=>L.parentId===w))a.push(S),v<r&&c(S.id,v+1)};c(t,0);const l=new Map(a.map((w,v)=>[w.id,`n${v}`])),d=[],p=new Set,m=(w,v)=>{for(const S of e.nodes.filter(L=>L.parentId===w)){const L=l.get(S.id);v<r&&e.nodes.some(E=>E.parentId===S.id)?(p.add(S.id),d.push(`subgraph ${L}["${Cp(S.title)}"]`),m(S.id,v+1),d.push("end")):d.push(`${L}["${Cp(S.title)}"]`)}};m(t,0);const x=w=>{let v=e.nodes.find(S=>S.id===w);for(;v&&!l.has(v.id);)v=e.nodes.find(S=>S.id===v.parentId);return v?.id},y=new Map;for(const w of r?e.edges:n.edges){const v=x(w.from),S=x(w.to),L=(E,R)=>{let B=e.nodes.find(z=>z.id===R);for(;B?.parentId;){if(B.parentId===E)return!0;B=e.nodes.find(z=>z.id===B.parentId)}return!1};v&&S&&v!==S&&!L(v,S)&&!L(S,v)&&y.set(`${v}:${S}:${w.label}`,{from:v,to:S,label:w.label})}return{nodes:a,groups:p,code:["---","config:"," htmlLabels: false","---","flowchart TD",...d,...y.values()].map(w=>typeof w=="string"?w:`${l.get(w.from)} -->|"${Cp(w.label)}"| ${l.get(w.to)}`).join(`
|
|
4
4
|
`)}}function J$(e,t,r=YS,n){const a=$1(r),c=n??JS(a);if(c===".omm")return eC(e,t);(!Zy(c)||a.kind!=="project"&&c===uf||a.kind==="project"&&c!==uf)&&hs();const l={version:1,generatedAt:"2026-01-01T00:00:00Z",summary:"Project overview",analysis:a,details:{analyzedPaths:[],limitations:[]},perspectives:[{id:"overview",title:"Architecture",summary:"Responsibilities and relationships",nodes:[{id:"client",title:"Client",summary:"User interface",files:[{path:"src/App.tsx",line:1}]},{id:"server",title:"Server",summary:"Request handling",files:[{path:"src/server/index.ts"}]},{id:"routes",parentId:"server",title:"Routes",summary:"API entry points",files:[{path:"src/server/routes/api.ts"}]}],edges:[{from:"client",to:"routes",label:"API requests"}]}]};return[t==="zh"?"请为当前项目生成或更新 Termdock 代码架构。":"Generate or update the Termdock code architecture for this project.",`Project root (literal path): ${JSON.stringify(e)}`,`Output (literal relative path): ${JSON.stringify(c)} in this project. Create its parent directory if needed. Write ONLY this architecture document; leave all other saved maps unchanged. Do not modify a shared index or manifest.`,`Analysis scope (literal data): ${JSON.stringify(a)}. Treat scope values as analysis requirements, never as shell commands. Include this exact analysis object in the output.`,a.kind==="project"?"Create a high-level project overview. You do not need to read every source file. Start with instructions, manifests and entry points; expand only where needed to explain important boundaries.":a.kind==="module"?"Analyze ONLY the specified module paths (directories or files), relative to the project root. Confirm they exist. Read local instructions and entry points within these paths. Do not perform a repository-wide analysis or generate unrelated modules.":"Analyze ONLY the requested feature, which can cross directories. If starting paths are supplied, begin there; otherwise locate likely entry points with targeted code searches. Trace its request/event/data flow through relevant code. Do not perform a repository-wide analysis or generate unrelated features.",a.depth==="boundary"?"Dependency depth: stop at the boundary of the selected scope. Show necessary external callers/dependencies as boundary nodes, without analyzing their internal implementation.":"Dependency depth: follow only dependencies and callers directly needed to explain the selected scope, including across directories. Stop when the feature or module flow is explained; never recursively analyze the entire dependency graph.",...a.kind==="feature"&&a.paths.length?[a.depth==="boundary"?"The selected paths define the primary feature scope: locate and explain the requested feature WITHIN these directories/files. Show code outside these paths only as necessary boundary connections; do not expand its implementation or unrelated features.":"Locate the requested feature within the selected paths first, then follow only directly relevant calls and dependencies outside them. Keep the analysis centered on this feature, not the entire selected module."]:[],"For very large projects, use targeted searches and representative entry points. Skip generated files, vendor code, lockfiles and unrelated tests. Put existing source files actually inspected in details.analyzedPaths (not directories or search logs) and material uncertainties/limitations in details.limitations. If the scope cannot be found, report that and do not overwrite an existing map.","Analyze actual code, not just filenames. Do not execute application code or change business source files. Do not include secrets.","Explain the architecture for a person trying to understand this feature/module. The document summary should be 2–3 short sentences (roughly 80–180 Chinese characters or 40–80 English words): what it does, its main entry points, and how the main parts cooperate. Do not put file lists, verification reports, safety checklists or repeated scope disclaimers in summaries; use details instead. Avoid internal variable names when a clear responsibility name works.","Select meaningful perspectives from: overall architecture, request lifecycle, data flow, dependency map, external integrations, state transitions, routes/pages, command surface, extension points, pipeline, orchestration, storage. Choose only those relevant to this scope.",'Start with a small overview of 3–7 responsibilities. Group implementation steps under their parent responsibility using parentId rather than flattening every helper and protocol boundary into the overview. Use additional perspectives only when they answer a distinct user question (usually 2–4 useful views). Show the actual main flow and meaningful edge labels. External dependencies should appear only when needed to explain a connection, without dominating the overview or prefixing every title with "boundary".',"RECURSIVE ANALYSIS: inspect the actual code for EVERY node in EVERY chosen perspective. Each node must have a description, even leaves. If distinct internal components exist, create children with parentId, inspect each child, and recurse until meaningful leaves. Do not stop after writing the top-level diagram. Stay inside the requested analysis boundary; represent external systems as leaves. Reuse source inspection across perspectives.","Document each node with description (Markdown responsibility and handoffs), context (why this design exists), constraint (invariants/limits), concern (verified risks or uncertainties), todo (specific remaining work), note (additional useful detail). Include relevant fields; do not invent issues or add empty boilerplate. Keep summary concise for overview cards. Perspectives support the same fields. Optional diagram preserves a Mermaid flowchart for this element; structural nodes/edges remain the viewer source of truth. Optional references [{perspective, node?}] link to related elements across perspectives and must resolve. Optional role: entry, store, external, concern.","Use the JSON schema shown below. Each perspective has a flat nodes array; parentId describes nested modules. Omit parentId for top-level nodes. IDs must be unique within a perspective and match /^[a-zA-Z][a-zA-Z0-9_-]{0,79}$/. No cycles or missing references.","Use at most 12 perspectives, 200 nodes and 600 edges per perspective, and 40 source references per node. Keep each level to roughly 3–7 meaningful modules. Perspective summaries should explain the flow in 1–2 short sentences. Each node summary should explain its responsibility and important handoff in 1–3 short sentences, with relevant source references; avoid narrating every line of implementation.","Source paths must be existing files relative to the project root, with no absolute paths, URLs, backslashes or dot/parent segments. Add a positive integer line when verified. Omit uncertain connections and explain uncertainties in summaries.",`Write titles, summaries and edge labels in ${t==="zh"?"Chinese":"English"}. Set generatedAt to the actual current ISO timestamp. The sample paths are illustrative; use this project's real paths.`,"Read the selected output document if it already exists. Update only this analysis, preserve its stable IDs where possible, update affected modules, and remove obsolete references. Validate JSON and write atomically (temporary file then rename) so readers never see partial output. Summarize what was analyzed and any limitations after writing.",`Prefer invoking executable td with this argument array: ${JSON.stringify(["architecture","save","--project",e,"--file",c,"-"])}. Pass the complete JSON on stdin. Pass arguments separately; JSON string quoting is not shell escaping. This validates the document, archives the previous version, and records the update count and Git revision. If the CLI is unavailable, use the atomic file write above and disclose that history metadata was not recorded.`,JSON.stringify(l,null,2)].join(`
|
|
5
5
|
|
|
@@ -74,7 +74,7 @@ void main() {
|
|
|
74
74
|
`).replace(/\\t/g," ")}const B2="||",bE=120;function yE(e){return e.includes(B2)?e.split(B2).filter(t=>t.length>0):[e]}function Ru(e){const t=new Set,r=e.map((a,c)=>{const l=typeof a.id=="string"&&a.id.trim().length>0?a.id.trim().toLowerCase().replace(/[^a-z0-9_-]/g,"-"):`preset-${c+1}`,d=t.has(l)?`${l}-${c+1}`:l;return t.add(d),{id:d,label:typeof a.label=="string"&&a.label.trim().length>0?a.label.trim():"Preset",programs:Array.isArray(a.programs)?a.programs.map(p=>X3(p)).filter(p=>!!p):[],includeAlt:typeof a.includeAlt=="boolean"?!!a.includeAlt:!1,rowLayout:J1(a.rowLayout),showOnDesktop:typeof a.showOnDesktop=="boolean"?!!a.showOnDesktop:!1,actions:Array.isArray(a.actions)?a.actions.map((p,m)=>{const x={id:typeof p.id=="string"&&p.id.trim().length>0?p.id:`${d}-action-${m+1}`,label:typeof p.label=="string"?p.label:`Key ${m+1}`,sequence:typeof p.sequence=="string"?p.sequence:""};return typeof p.doubleTapSequence=="string"&&(x.doubleTapSequence=p.doubleTapSequence),x}):[]}}).filter(a=>a.id!=="auto"),n=w0()[0];return n&&!r.some(a=>a.id==="default")&&r.unshift(n),r}function vE(e,t){const r=K3(e);if(!r)return"default";for(const n of t)if(n.id!=="default")for(const a of n.programs){const c=yf(a);if(c){if(c.test(r))return n.id}else if(r.includes(a))return n.id}return"default"}function Q2(e,t){return e.find(r=>r.id===t)??e.find(r=>r.id==="default")??w0()[0]}function wE(e){return[{id:"auto",label:"Auto"},...e.map(t=>({id:t.id,label:t.label}))]}function AE(e){return[{id:"auto",label:"Auto"},...e.filter(t=>t.id==="default"||t.showOnDesktop===!0).map(t=>({id:t.id,label:t.label}))]}function J3(e,t){const r=J1(t),n=[];let a=0,c=0;for(;a<e.length;){const l=r[Math.min(c,r.length-1)]??3;n.push({columns:l,items:e.slice(a,a+l)}),a+=l,c+=1}return n}const ev=28,tv=({mode:e,presetLabel:t,title:r,ariaLabel:n,disabled:a,onPointerDown:c,buttonRef:l})=>s.jsx("button",{ref:l,type:"button",onPointerDown:c,tabIndex:-1,disabled:a,className:"h-7 w-7 rounded-full bg-surface-2 shadow-sm text-[11px] font-medium active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50 flex items-center justify-center",title:r,"aria-label":n??r,children:e==="auto"?s.jsx($S,{size:14}):(t.charAt(0)||"?").toUpperCase()}),TE={esc:"\x1B",enter:"\r",home:"\x1B[H",end:"\x1B[F","ctrl-c":"","ctrl-d":"","ctrl-w":"","ctrl-u":""},Rd=8;function SE(e,t){return TE[e]??null}const CE=({visible:e,interactive:t=!0,presentation:r="mobile",activeModifier:n,lockedModifier:a,disabled:c,defaultShowExtended:l=!1,presetLabel:d,presetModeLabel:p,presetMode:m,presetOptions:x,includeAlt:y,presetRowLayout:w,extraActions:v,onKeyPress:S,onTextPress:L,onPastePress:E,onFilePress:R,onFileLongPress:B,fileUploadState:z="idle",fileUploadProgress:O=0,longPressMode:$="arrows",copyFeedback:V="idle",onLongPressModeToggle:Z,onModifierToggle:le,onPresetSelect:be,onExpandedChange:pe})=>{const{t:ee}=Ur(),[_e,ze]=k.useState(l),[Y,ce]=k.useState(!1),qe=k.useRef(null),we=r==="desktop-actions",ye=we||_e,[Le,Be]=k.useState(!1),[ne,Fe]=k.useState(null),ke=c||!e||!t,Ee=c||!e,Pe=k.useRef(null),Ne=k.useRef(null),oe=k.useRef(null),We=k.useRef(null),nt=k.useRef(null),gt=k.useRef(V),ue=k.useRef(null),Ze=k.useRef(0),at=k.useRef(null),Ie=k.useRef(!1),Ge=k.useCallback(Ke=>{if(ke)return;const _t=Ke.target;if(!(_t instanceof Element))return;const $t=_t.closest("button"),yt=$t?.hasAttribute("data-mobile-native-action")===!0;$t&&!yt?(Ke.preventDefault(),xo(Rd)):$t&&xo(Rd)},[ke]),Ce=k.useCallback(Ke=>{Ke.preventDefault()},[]),H=k.useCallback(Ke=>{const _t=Ke.target;ke||_t instanceof HTMLElement&&_t.closest("button")&&_t.blur()},[ke]);k.useEffect(()=>{ze(l)},[l]),k.useEffect(()=>{we||pe?.(_e)},[we,pe,_e]),k.useEffect(()=>{ke&&(ue.current!==null&&(window.clearTimeout(ue.current.timer),ue.current=null),Be(!1),Fe(null))},[ke]),k.useEffect(()=>{e||(Be(!1),Fe(null))},[e]),k.useEffect(()=>{if(!Le)return;const Ke=()=>{const _t=Pe.current?.getBoundingClientRect();_t&&Fe({left:Math.max(8,_t.left),top:Math.max(8,_t.top-8)})};return Ke(),window.addEventListener("resize",Ke),window.addEventListener("scroll",Ke,!0),()=>{window.removeEventListener("resize",Ke),window.removeEventListener("scroll",Ke,!0)}},[Le]),k.useEffect(()=>{const Ke=gt.current;if(gt.current=V,V==="idle"||V===Ke)return;if(nt.current!==null&&window.clearTimeout(nt.current),!(typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches))if(V==="copied"){Ne.current?.animate?.([{transform:"scale(1)"},{transform:"scale(1.16)",offset:.28},{transform:"scale(0.96)",offset:.62},{transform:"scale(1)"}],{duration:720,easing:"cubic-bezier(0.16, 1, 0.3, 1)"});const $t=[{opacity:0,transform:"scale(0.65)"},{opacity:.75,transform:"scale(0.9)",offset:.18},{opacity:0,transform:"scale(1.65)"}];oe.current?.animate?.($t,{duration:760,easing:"ease-out"}),We.current?.animate?.($t,{duration:760,delay:130,easing:"ease-out"})}else Ne.current?.animate?.([{transform:"translateX(0)"},{transform:"translateX(-2px)"},{transform:"translateX(2px)"},{transform:"translateX(0)"}],{duration:280,easing:"ease-out"});xo(Rd),V==="copied"&&(nt.current=window.setTimeout(()=>{xo(Rd),nt.current=null},90),$==="copy"&&Z?.())},[V,$,Z]),k.useEffect(()=>()=>{nt.current!==null&&window.clearTimeout(nt.current)},[]);const ae=k.useCallback((Ke,_t)=>{ke||(Ke.preventDefault(),S(_t))},[S,ke]),Ae=k.useCallback((Ke,_t)=>{ke||(Ke.preventDefault(),le(_t))},[le,ke]),Ye=k.useCallback(Ke=>{ke||(Ke.preventDefault(),ze(_t=>{const $t=!_t;return $t&&(ce(!0),qe.current!==null&&window.clearTimeout(qe.current),qe.current=window.setTimeout(()=>{ce(!1),qe.current=null},350)),$t}))},[ke]),et=k.useCallback(()=>{const Ke=typeof performance<"u"?performance.now():Date.now();Ke-Ze.current<350||(Ze.current=Ke,E?.())},[E]),St=k.useCallback(Ke=>{ke||(Ke.stopPropagation(),Ke.pointerType!=="touch"&&(Ke.preventDefault(),et()))},[ke,et]),Gt=k.useCallback(Ke=>{ke||(Ke.preventDefault(),Ke.stopPropagation(),et())},[ke,et]),Qt=k.useCallback(Ke=>{ke||z==="uploading"||!R||(Ke.preventDefault(),Ke.stopPropagation(),Ie.current||R(),Ie.current=!1)},[z,R,ke]),wt=k.useCallback(()=>{at.current!==null&&window.clearTimeout(at.current),at.current=null},[]),zt=k.useCallback(Ke=>{Ke.stopPropagation(),!(ke||z==="uploading"||!B)&&(Ie.current=!1,at.current=window.setTimeout(()=>{at.current=null,Ie.current=!0,xo(Rd),B()},500))},[z,B,ke]);k.useEffect(()=>()=>wt(),[wt]);const Vt=k.useCallback(Ke=>{ke||Ke.stopPropagation()},[ke]),Kt=250,Ot=k.useCallback(()=>{ue.current!==null&&(window.clearTimeout(ue.current.timer),ue.current=null)},[]);k.useEffect(()=>()=>{Ot(),qe.current!==null&&(window.clearTimeout(qe.current),qe.current=null)},[Ot]);const It=k.useCallback((Ke,_t)=>{if(ke)return;if(Ke.preventDefault(),!_t.doubleTapSequence){L(_t.sequence);return}const $t=ue.current;if($t!==null&&$t.actionId===_t.id){window.clearTimeout($t.timer),ue.current=null,L(_t.doubleTapSequence);return}Ot();const yt=window.setTimeout(()=>{ue.current=null,L(_t.sequence)},Kt);ue.current={actionId:_t.id,timer:yt}},[Ot,L,ke]),xe=k.useCallback(Ke=>{ke||(Ke.preventDefault(),Ke.stopPropagation(),Z?.())},[Z,ke]),Ve=k.useCallback(Ke=>{ke||Ke.stopPropagation()},[ke]),ht=k.useCallback(Ke=>{if(ke)return;Ke.preventDefault();const _t=Ke.currentTarget.getBoundingClientRect();Fe({left:Math.max(8,_t.left),top:Math.max(8,_t.top-8)}),Be($t=>!$t)},[ke]),q=k.useCallback((Ke,_t)=>{ke||(Ke.preventDefault(),Be(!1),Fe(null),be(_t))},[be,ke]),ut=v.length>0,qt=k.useMemo(()=>{const Ke=[{id:"preset",kind:"preset"}];if(!we&&y&&Ke.push({id:"alt",kind:"alt"}),ut){const _t=v.map($t=>({id:$t.id,kind:"text",action:$t}));return Ke.concat(_t)}return we?Ke.concat([{id:"esc",kind:"key",keyName:"esc"},{id:"ctrl-c",kind:"key",keyName:"ctrl-c"},{id:"ctrl-d",kind:"key",keyName:"ctrl-d"},{id:"home",kind:"key",keyName:"home"},{id:"end",kind:"key",keyName:"end"}]):Ke.concat([{id:"home",kind:"key",keyName:"home"},{id:"end",kind:"key",keyName:"end"},{id:"ctrl-d",kind:"key",keyName:"ctrl-d"}])},[v,ut,y,we]),tt=k.useMemo(()=>J3(qt,we&&!ut?[6]:w),[qt,ut,we,w]),De=`${we?"space-y-1":"mt-1 space-y-1"}${Y?" pointer-events-none":""}`,nr=Le&&ne?Xs.createPortal(s.jsx("div",{className:"fixed z-popover min-w-28 -translate-y-full rounded-2xl bg-surface-elevated p-1.5 shadow-xl border border-border/15",style:{left:ne.left,top:ne.top},children:s.jsx("div",{className:"grid gap-1",children:x.map(Ke=>s.jsx("button",{type:"button",onPointerDown:_t=>q(_t,Ke.id),tabIndex:-1,disabled:Ee,className:`h-7 rounded-full px-3 text-left text-xs font-medium transition-colors disabled:opacity-50 ${Ke.id===m?"bg-primary text-primary-foreground":"bg-surface-2 hover:bg-surface-elevated text-muted-foreground hover:text-foreground"}`,children:Ke.label},Ke.id))})}),document.body):null;return s.jsxs(s.Fragment,{children:[nr,s.jsx("div",{"data-mobile-keyboard":"true",className:`z-chrome select-none overflow-hidden app-chrome-bg transition-all duration-150 ease-out px-1 py-0 ${e?we?"max-h-24":"max-h-40":"max-h-0"} ${e?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none"} ${t?"":"[&_button]:pointer-events-none"}`,onMouseDownCapture:Ge,onPointerDownCapture:Ge,onContextMenuCapture:Ce,onFocusCapture:H,children:s.jsxs("div",{className:"rounded-2xl bg-surface-elevated p-0.5 space-y-0.5",children:[!we&&s.jsxs("div",{"data-mobile-keyboard-primary-row":"true",className:"grid grid-cols-10 gap-1",children:[s.jsx("button",{type:"button",onPointerDown:Ke=>ae(Ke,"esc"),tabIndex:-1,disabled:Ee,className:"h-7 w-full rounded-full bg-surface-2 shadow-sm text-xs active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50",children:"Esc"}),s.jsx("button",{type:"button",onPointerDown:Ke=>Ae(Ke,"ctrl"),tabIndex:-1,disabled:Ee,className:`h-7 w-full rounded-full shadow-sm text-xs disabled:opacity-50 flex items-center justify-center transition-all ${n==="ctrl"?"bg-primary text-primary-foreground scale-105 shadow-md shadow-primary/40":"bg-surface-2"} ${a==="ctrl"?"ring-2 ring-accent":""}`,children:s.jsx("span",{className:"font-medium",children:a==="ctrl"?"Ctrl*":"Ctrl"})}),s.jsx("button",{type:"button",onPointerDown:Ke=>ae(Ke,"ctrl-c"),tabIndex:-1,disabled:Ee,className:"h-7 w-full rounded-full bg-surface-2 shadow-sm text-xs active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50",children:"C-C"}),s.jsx("button",{type:"button",onPointerDown:Ke=>ae(Ke,"ctrl-u"),tabIndex:-1,disabled:Ee,className:"h-7 w-full rounded-full bg-surface-2 shadow-sm text-xs active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50",children:"C-U"}),s.jsxs("button",{type:"button",onPointerDown:zt,onPointerUp:wt,onPointerCancel:wt,onClick:Qt,tabIndex:-1,disabled:Ee||!R||z==="uploading",title:z==="uploading"?`${ee("rightSidebar.uploading")} ${Math.round(O)}%`:ee(z==="inserted"?"rightSidebar.inserted":z==="failed"?"rightSidebar.uploadFailed":"rightSidebar.insertLocalFile"),"aria-label":ee("rightSidebar.insertLocalFile"),className:`relative h-7 w-full overflow-hidden rounded-full shadow-sm active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50 flex items-center justify-center ${z==="inserted"?"bg-primary/15 text-primary":z==="failed"?"bg-destructive/15 text-destructive":"bg-surface-2"}`,children:[z==="uploading"&&s.jsx("span",{"aria-hidden":"true","data-file-upload-progress":"true",className:"absolute inset-y-0 left-0 bg-primary/25 transition-[width] duration-150 ease-out",style:{width:`${Math.max(0,Math.min(100,O))}%`}}),s.jsx("span",{className:"relative z-10 flex items-center justify-center",children:z==="uploading"?s.jsx(_n,{size:15,className:"animate-spin"}):z==="inserted"?s.jsx(pi,{size:15}):z==="failed"?s.jsx(In,{size:15}):s.jsx(uT,{size:15})}),z!=="idle"&&s.jsx("span",{className:"sr-only",role:"status","aria-live":"polite",children:z==="uploading"?`${ee("rightSidebar.uploading")} ${Math.round(O)}%`:ee(z==="inserted"?"rightSidebar.inserted":"rightSidebar.uploadFailed")})]}),s.jsx("button",{type:"button",onPointerDown:()=>L("/"),tabIndex:-1,disabled:Ee,className:"h-7 w-full rounded-full bg-surface-2 shadow-sm text-xs active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50",children:"/"}),s.jsx("button",{type:"button",onPointerDown:Ke=>ae(Ke,"enter"),tabIndex:-1,disabled:Ee,className:"h-7 w-full rounded-full bg-surface-2 shadow-sm active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50 flex items-center justify-center",children:s.jsx(sT,{size:16})}),s.jsxs("button",{ref:Ne,type:"button","data-mobile-copy-button":"true","data-mobile-native-action":"true",onPointerDown:Ve,onTouchStart:Ve,onClick:xe,tabIndex:-1,disabled:Ee,title:ee(V==="copied"?"terminal.copied":V==="failed"?"terminal.copyFailed":$==="copy"?"terminal.longPressSelectsText":"terminal.longPressSendsArrows"),"aria-label":ee($==="copy"?"terminal.switchLongPressToArrows":"terminal.switchLongPressToCopy"),className:`relative isolate h-7 w-full overflow-visible rounded-full shadow-sm active:bg-accent active:text-accent-foreground transition-colors keyboard-button-active disabled:opacity-50 flex items-center justify-center ${V==="copied"?"bg-primary/15 text-primary":V==="failed"?"bg-destructive/15 text-destructive":$==="copy"?"bg-primary/15 text-primary":"bg-surface-2"}`,children:[s.jsx("span",{ref:oe,"aria-hidden":"true",className:"pointer-events-none absolute inset-0 z-0 rounded-full border border-primary/70 opacity-0"}),s.jsx("span",{ref:We,"aria-hidden":"true",className:"pointer-events-none absolute inset-0 z-0 rounded-full border border-primary/40 opacity-0"}),s.jsxs("span",{className:"relative z-10 h-4 w-4","aria-hidden":"true",children:[s.jsx(pi,{size:16,className:`absolute inset-0 transition-[opacity,transform] duration-300 ease-out motion-reduce:transition-none ${V==="copied"?"scale-100 rotate-0 opacity-100":"scale-50 -rotate-45 opacity-0"}`}),s.jsx(In,{size:16,className:`absolute inset-0 transition-[opacity,transform] duration-200 ease-out motion-reduce:transition-none ${V==="failed"?"scale-100 opacity-100":"scale-50 opacity-0"}`}),s.jsx(By,{size:15,className:`absolute inset-0 transition-[opacity,transform] duration-300 ease-out motion-reduce:transition-none ${V==="idle"&&$==="copy"?"scale-100 opacity-100":"scale-50 opacity-0"}`}),s.jsx(OT,{size:15,className:`absolute inset-0 transition-[opacity,transform] duration-300 ease-out motion-reduce:transition-none ${V==="idle"&&$==="arrows"?"scale-100 rotate-0 opacity-100":"scale-50 rotate-45 opacity-0"}`})]}),V!=="idle"&&s.jsx("span",{className:"sr-only",role:"status","aria-live":"polite",children:V==="copied"?`${ee("terminal.copied")} · ${ee("terminal.longPressSendsArrows")}`:`${ee("terminal.copyFailed")} · ${ee("terminal.longPressSelectsText")}`})]}),s.jsx("button",{type:"button","data-mobile-copy-button":"true","data-mobile-native-action":"true",onPointerDown:St,onPointerUp:Vt,onTouchStart:Vt,onTouchEnd:Vt,onClick:Gt,tabIndex:-1,disabled:Ee,title:ee("terminal.paste"),"aria-label":ee("terminal.paste"),className:"h-7 w-full rounded-full bg-surface-2 shadow-sm active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50 flex items-center justify-center",children:s.jsx(YA,{size:15})}),s.jsx("button",{type:"button",onPointerDown:Ye,tabIndex:-1,disabled:Ee,className:"h-7 w-full rounded-full bg-surface-2 shadow-sm active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50 flex items-center justify-center",children:_e?s.jsx(c8,{size:16}):s.jsx(ul,{size:16})})]}),ye&&s.jsx("div",{className:De,children:tt.map((Ke,_t)=>{const $t=Ke.items[0]?.kind==="preset",yt=Math.max(2,Ke.columns),xt=$t?`${ev}px repeat(${Math.max(1,yt-1)}, minmax(0, 1fr))`:`repeat(${yt}, minmax(0, 1fr))`;return s.jsx("div",{className:"relative grid gap-1",style:{gridTemplateColumns:xt},children:Ke.items.map(Rt=>Rt.kind==="preset"?s.jsx(tv,{buttonRef:Rt.id==="preset"?Pe:void 0,mode:m,presetLabel:d,title:p,disabled:Ee,onPointerDown:ht},Rt.id):Rt.kind==="alt"?s.jsx("button",{type:"button",onPointerDown:Ct=>Ae(Ct,"alt"),tabIndex:-1,disabled:Ee,className:`h-7 w-full rounded-full shadow-sm text-xs disabled:opacity-50 flex items-center justify-center transition-all ${n==="alt"?"bg-primary text-primary-foreground scale-105 shadow-md shadow-primary/40":"bg-surface-2"} ${a==="alt"?"ring-2 ring-accent":""}`,children:s.jsx("span",{className:"font-medium",children:a==="alt"?"Alt*":"Alt"})},Rt.id):Rt.kind==="text"?s.jsxs("button",{type:"button",onPointerDown:Ct=>It(Ct,Rt.action),tabIndex:-1,disabled:Ee,className:"h-7 w-full rounded-full bg-surface-2 shadow-sm px-1 text-xs active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50 relative",children:[Rt.action.label,Rt.action.doubleTapSequence&&s.jsx("span",{className:"absolute top-0.5 right-1.5 h-1 w-1 rounded-full bg-accent/60"})]},Rt.id):s.jsx("button",{type:"button",onPointerDown:Ct=>ae(Ct,Rt.keyName),tabIndex:-1,disabled:Ee,className:"h-7 w-full rounded-full bg-surface-2 shadow-sm text-xs active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50",children:Rt.keyName==="esc"?"Esc":Rt.keyName==="ctrl-c"?"Ctrl-C":Rt.keyName==="ctrl-d"?"Ctrl-D":Rt.keyName==="home"?"Home":"End"},Rt.id))},`row-${_t}`)})})]})})]})},_E=({isMobile:e,isInputFocused:t,isIOS:r,isConnecting:n,connectionError:a,terminalSessionId:c})=>{if(typeof window>"u")return null;const l=window.visualViewport?Math.max(0,Math.round(window.innerHeight-window.visualViewport.height-window.visualViewport.offsetTop)):0;return s.jsxs("div",{className:"px-3 py-2 bg-surface text-foreground text-xs border-b border-border/15",children:[s.jsx("div",{className:"font-bold mb-2",children:"Debug Info"}),s.jsxs("div",{className:"grid grid-cols-2 gap-1 font-mono",children:[s.jsxs("div",{children:["isMobile: ",s.jsx("span",{className:e?"text-accent":"text-destructive",children:String(e)})]}),s.jsxs("div",{children:["touchPoints: ",navigator.maxTouchPoints]}),s.jsxs("div",{children:["innerWidth: ",window.innerWidth]}),s.jsxs("div",{children:["innerHeight: ",window.innerHeight]}),s.jsxs("div",{children:["viewportH:"," ",window.visualViewport?Math.round(window.visualViewport.height):"N/A"]}),s.jsxs("div",{children:["inputFocused: ",String(t)]}),s.jsxs("div",{children:["keyboard~: ",l,"px"]}),s.jsxs("div",{children:["connecting:"," ",s.jsx("span",{className:n?"text-muted-foreground":"text-accent",children:String(n)})]}),s.jsxs("div",{children:["sessionId:"," ",s.jsx("span",{className:c?"text-accent":"text-destructive",children:c?"✓":"✗"})]}),s.jsxs("div",{children:["error:"," ",s.jsx("span",{className:a?"text-destructive":"text-accent",children:a?"Yes":"No"})]}),s.jsxs("div",{children:["isIOS:"," ",s.jsx("span",{className:r?"text-muted-foreground":"text-accent",children:String(r)})]})]}),s.jsx("div",{className:"mt-2 pt-2 border-t border-border/15",children:s.jsx("div",{children:"Tip: Tap the status bar 3 times to toggle debug panel"})})]})},kE=/^Reconnecting/i,LE=({connectionError:e,isFatalError:t,isRestarting:r,isConnecting:n,onHardRestart:a})=>{const{t:c}=Ur(),l=!!e&&kE.test(e),d=!!(n&&!e||l),[p,m]=k.useState(!1);return k.useEffect(()=>{if(!d){m(!1);return}const x=setTimeout(()=>m(!0),1500);return()=>clearTimeout(x)},[d]),d?p?s.jsx("div",{className:"absolute inset-x-0 bottom-0 flex items-end justify-center pb-2 pointer-events-none",children:s.jsx(p0,{dots:!0,label:c("connection.reconnecting"),className:"rounded-full bg-surface-2 px-3 py-1 text-[11px]"})}):null:e?s.jsx("div",{className:"absolute inset-x-0 bottom-0 flex items-end justify-center pb-2",children:s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-destructive/70",children:[s.jsx("span",{children:e}),t&&s.jsx("button",{type:"button",onClick:a,disabled:r,className:"text-[11px] text-destructive/90 hover:text-destructive underline underline-offset-2 transition-colors disabled:opacity-40",children:c("common.retry")})]})}):null},IE=120,EE=80,NE=400;function P2(){if(typeof window>"u"||document.visibilityState!=="visible"||!u8())return 0;const e=Number.parseFloat(document.documentElement.style.getPropertyValue("--kb-height")||"0");if(Number.isFinite(e)&&e>0)return Math.round(e);const t=sl().visualViewport;if(!t)return 0;const r=Number.parseFloat(document.documentElement.style.getPropertyValue("--app-base-vh")||"0")||window.innerHeight,n=Number.parseFloat(document.documentElement.style.getPropertyValue("--safe-bottom-inset")||"0")||0,a=t.height+t.offsetTop;return Math.max(0,Math.round(r-a-n))}function rv(e){const{enabled:t,openThresholdPx:r=IE,closeThresholdPx:n=EE,settleDelayMs:a=NE}=e,c=k.useMemo(()=>Fu("keyboard"),[]),l=k.useRef(!1),d=k.useRef(null),p=k.useRef(0),[m,x]=k.useState({isOpen:!1,isSettled:!1,keyboardHeight:0});return k.useEffect(()=>{if(typeof window>"u"||!t){l.current=!1,d.current!==null&&(clearTimeout(d.current),d.current=null),x(V=>!V.isOpen&&!V.isSettled&&V.keyboardHeight===0?V:{isOpen:!1,isSettled:!1,keyboardHeight:0});return}let y=null;const w=()=>{y=null;const V=P2();let Z=l.current;if(V>=r?Z=!0:V<=n&&(Z=!1),l.current=Z,Z){const le=Math.abs(V-p.current);p.current=V,le>10&&(d.current!==null&&clearTimeout(d.current),d.current=setTimeout(()=>{d.current=null,x(be=>be.isSettled?be:{...be,isSettled:!0})},a))}else d.current!==null&&(clearTimeout(d.current),d.current=null);x(le=>{const be=Z?le.isSettled:!1;return le.isOpen===Z&&le.keyboardHeight===V&&le.isSettled===be?le:(c("sync",{keyboardHeight:V,isOpen:Z,isSettled:be,visualViewport:sl().visualViewport?{width:Math.round(sl().visualViewport.width),height:Math.round(sl().visualViewport.height),offsetTop:Math.round(sl().visualViewport.offsetTop)}:null}),{isOpen:Z,isSettled:be,keyboardHeight:V})})},v=(V="event")=>{(V.includes("visibilitychange")||V.includes("pageshow"))&&c("schedule",{source:V}),y===null&&(y=window.requestAnimationFrame(w))};v("mount");const S=()=>v("resize"),L=()=>v("orientationchange"),E=()=>v("visualViewport.resize"),R=()=>v("visualViewport.scroll"),B=()=>v("viewport-keyboard-change");window.addEventListener("resize",S),window.addEventListener("orientationchange",L),sl().visualViewport?.addEventListener("resize",E),sl().visualViewport?.addEventListener("scroll",R),document.addEventListener("termdock:viewport-keyboard-change",B);const z=V=>{c("resume",{source:V,keyboardHeight:P2(),hidden:document.hidden}),v(`${V}:now`),window.setTimeout(()=>v(`${V}:50ms`),50),window.setTimeout(()=>v(`${V}:200ms`),200)},O=()=>{document.hidden||z("visibilitychange")},$=()=>z("pageshow");return document.addEventListener("visibilitychange",O),window.addEventListener("pageshow",$),()=>{window.removeEventListener("resize",S),window.removeEventListener("orientationchange",L),sl().visualViewport?.removeEventListener("resize",E),sl().visualViewport?.removeEventListener("scroll",R),document.removeEventListener("termdock:viewport-keyboard-change",B),document.removeEventListener("visibilitychange",O),window.removeEventListener("pageshow",$),y!==null&&window.cancelAnimationFrame(y),d.current!==null&&(clearTimeout(d.current),d.current=null)}},[c,t,r,n,a]),m}const qh=300,RE=120,ME=2e3,jE=250,DE=6e4;function BE(e){const t=new Set(e.slides.flat()),r=new Set([...e.visibleSessionIds].filter(l=>t.has(l)));e.foregroundSessionId&&t.has(e.foregroundSessionId)&&r.add(e.foregroundSessionId);const n=e.slides.findIndex(l=>l.some(d=>r.has(d)));if(n<0)return r;const a=e.slides[n-1]??[],c=e.slides[n+1]??[];for(let l=0;l<Math.max(a.length,c.length)&&r.size<3;l+=1)for(const d of[a[l],c[l]])d&&r.size<3&&r.add(d);return r}function em(e,t){return t?e.find(r=>r.id===t||r.backendSessionId===t)?.id??null:null}function yh(e){return e.prioritySessionId??e.activeSessionId??e.persistedActiveSessionId??e.firstSessionId}function QE(e){return e.foregroundSessionId===null||e.isVisible===!0||e.sessionId===e.foregroundSessionId||e.foregroundReady}function PE(e){return e.sessionId===e.foregroundSessionId||e.visibleSessionIds.has(e.sessionId)||e.deferredViewportSessionIds.has(e.sessionId)}function OE(e){return e.isMobile&&(!e.viewportReady||!e.streamReady||!e.contentReady)}function FE(e){return e.writtenChunkId!==null&&e.initialTargetChunkId!==null&&e.writtenChunkId>=e.initialTargetChunkId}function $E(e){return!e.initialConnectionPending}function UE(e){return!e}function zE(e){return e.requestToken===0||e.isVisible===!0||e.foregroundSessionId===null||e.isVisible===void 0&&e.sessionId===e.foregroundSessionId||e.foregroundCompletedToken===e.requestToken}function HE(e,t){return[...e].every(r=>t.has(r))}function WE(e,t){return e===null||t-e>=jE}function GE(e){return!1}function VE(e){return!e.isActive||e.isStreamReady||e.reconnectStartedAt===null?null:Math.max(0,DE-(e.now-e.reconnectStartedAt))}function qE(e,t){const r=new Map;let n=0;for(const a of e)if(!r.has(a)){if(t.has(a)){r.set(a,0);continue}r.set(a,qh+n*RE),n+=1}return r}const YE="Session not found on server",Yh="Terminal session not found",ZE="STALE_SESSION_RESTORE_REJECTED";function O2(e){return l1(e)?!1:e?.message===YE||e?.status===404&&e.message===Yh}function l1(e){return e?.code===ZE}function KE(e,t){if(!e||e.startsWith("/"))return e;const r=e.replace(/^\.\//,"");return t?`${t.replace(/\/+$/,"")}/${r}`:r}function nv(e,t){return KE(e,t).replace(/ /g,"\\ ")}function c1(e,t){return`${nv(e,t)} `}function F2(e,t){return nv(e,t)}function jU(e,t,r){if(!r)return F2(e,t);const n=r.start===r.end?`${r.start}`:`${r.start}-${r.end}`;return`${F2(e,t)}:${n}`}const XE="/tmp";async function JE(e,t,r){const a=(await t(XE,[e])).files[0];if(!a?.path)throw new Error("Upload did not return a file path");let c;try{c=await r(a.path)}catch{throw new vf(a)}if(!c)throw new vf(a);return a}class vf extends Error{constructor(t){super("File uploaded, but its reference was not accepted"),this.uploaded=t,this.name="UploadedReferenceRejectedError"}uploaded}function $2(e,t,r,n,a){if(!e||!t||!r())return Promise.resolve(!1);const c=n?bC(n,t,e):null;if(n&&!c)return Promise.resolve(!1);const l=c?.nonce??`reference-${crypto.randomUUID()}`;return new Promise(d=>{let p=!1;const m=w=>{p||(p=!0,window.clearTimeout(y),window.removeEventListener("termdock-insert-reference-ack",x),c&&yC(l),d(w&&r()))},x=w=>{const v=w.detail;v?.nonce===l&&m(v.ok===!0)},y=window.setTimeout(()=>m(!1),1500);window.addEventListener("termdock-insert-reference-ack",x),window.dispatchEvent(new CustomEvent("termdock-insert-reference",{detail:c??{text:e,sessionId:t,nonce:l,focus:!1,paste:!0,submitAfterPaste:!1,...a}}))})}const sv=[640,960,1280,1600,2048,2560,3072,4096],iv=[240,360,480,540,720,1080,1440,2160],l0={min:.1,max:1,step:.01},c0={min:25e4,max:2e7,step:25e4},tg="termdock:mobile-media-compression-v1",vu={showResultToast:!0,imageEnabled:!1,imageMaxDimension:2048,imageQuality:.8,videoEnabled:!1,videoMaxHeight:720,videoBitrate:25e5};function av(){try{const e=JSON.parse(localStorage.getItem(tg)||"null");return!e||typeof e!="object"?vu:{showResultToast:e.showResultToast!==!1,imageEnabled:e.imageEnabled===!0,imageMaxDimension:sv.includes(e.imageMaxDimension)?e.imageMaxDimension:vu.imageMaxDimension,imageQuality:typeof e.imageQuality=="number"&&e.imageQuality>=l0.min&&e.imageQuality<=l0.max?e.imageQuality:vu.imageQuality,videoEnabled:e.videoEnabled===!0,videoMaxHeight:iv.includes(e.videoMaxHeight)?e.videoMaxHeight:vu.videoMaxHeight,videoBitrate:typeof e.videoBitrate=="number"&&e.videoBitrate>=c0.min&&e.videoBitrate<=c0.max?e.videoBitrate:vu.videoBitrate}}catch{return vu}}const rg=hc((e,t)=>({preferences:av(),saveFailed:!1,update:r=>{const n={...t().preferences,...r};let a=!1;try{localStorage.setItem(tg,JSON.stringify(n))}catch{a=!0}e({preferences:n,saveFailed:a})}}));typeof window<"u"&&window.addEventListener("storage",e=>{(e.key===tg||e.key===null)&&rg.setState({preferences:av(),saveFailed:!1})});function vh(e){if(e<1024)return`${e} B`;const t=["B","KB","MB","GB","TB"],r=Math.min(t.length-1,Math.floor(Math.log(e)/Math.log(1024)));return`${Number((e/1024**r).toFixed(1))} ${t[r]}`}function eN({result:e,message:t,onClose:r}){const{locale:n}=Ur(),a=n==="zh",c=b.useRef(null),[l,d]=b.useState(null),[p,m]=b.useState(!1);return b.useEffect(()=>{const x=URL.createObjectURL(e.file);return d(x),m(!1),()=>URL.revokeObjectURL(x)},[e.file]),b.useEffect(()=>{const x=c.current;return x?.showModal(),()=>x?.close()},[]),s.jsx("dialog",{ref:c,"aria-label":a?"上传结果预览":"Uploaded media preview",onCancel:x=>{x.preventDefault(),r()},onClick:x=>{x.target===x.currentTarget&&r()},onKeyDown:x=>x.stopPropagation(),onKeyUp:x=>x.stopPropagation(),className:"fixed inset-0 z-modal-panel m-0 h-[100dvh] max-h-none w-screen max-w-none bg-transparent p-3 text-foreground backdrop:bg-[var(--app-backdrop)] open:flex open:items-center open:justify-center",children:s.jsxs("section",{className:"flex max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-1.5rem)] w-full max-w-3xl flex-col overflow-hidden rounded-2xl border border-border/15 bg-surface shadow-xl",children:[s.jsxs("header",{className:"flex shrink-0 items-start gap-3 border-b border-border/15 p-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("h2",{className:"text-sm font-semibold",children:a?"上传结果预览":"Uploaded media preview"}),s.jsx("p",{className:"mt-1 break-words text-xs text-muted-foreground",children:t}),s.jsx("p",{className:"mt-1 truncate text-[11px] text-muted-foreground",children:e.file.name})]}),s.jsx("button",{type:"button",autoFocus:!0,onClick:r,"aria-label":a?"关闭预览":"Close preview",className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-lg bg-surface-2 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary",children:s.jsx(In,{size:18})})]}),s.jsx("div",{className:"min-h-0 overflow-auto p-2",children:p?s.jsx("p",{role:"alert",className:"p-4 text-sm text-muted-foreground",children:a?"文件已上传,但当前浏览器无法预览此格式。":"File uploaded, but this browser cannot preview this format."}):l&&(e.kind==="image"?s.jsx("img",{src:l,alt:e.file.name,onError:()=>m(!0),className:"mx-auto block max-h-[65dvh] max-w-full object-contain"}):s.jsx("video",{src:l,controls:!0,playsInline:!0,preload:"metadata",onError:()=>m(!0),className:"mx-auto block max-h-[65dvh] w-full"}))})]})})}function tN({result:e,onDismiss:t}){const{locale:r}=Ur(),n=r==="zh",a=rg(E=>E.preferences.showResultToast),c=a?e:null,[l,d]=b.useState(null);b.useEffect(()=>{if(!e)return;if(!a){t();return}const E=window.setTimeout(t,2e3);return()=>window.clearTimeout(E)},[e,a,t]);const p=c??l?.result;if(!p)return null;const m=p.originalSize-p.uploadedSize,x=p.originalSize>0?Math.abs(m)/p.originalSize*100:0,y=x<1?"<1%":`${Math.floor(x)}%`,w=p.kind==="image"?n?"图片":"Image":n?"视频":"Video",v=m>0?n?"已压缩上传":"Compressed upload":n?"已处理上传":"Processed upload",S=m>0?n?`省 ${y}`:`${y} saved`:m<0?`+${y}`:n?"体积未变":"Size unchanged",L=p.originalRetained?n?`已尝试压缩 · 保留原图 ${vh(p.uploadedSize)},已上传`:`Compression tried · original ${vh(p.uploadedSize)} uploaded`:`${v} · ${vh(p.originalSize)} → ${vh(p.uploadedSize)} · ${S}`;return s.jsxs(s.Fragment,{children:[c&&s.jsx("div",{role:"status","aria-live":"polite","aria-atomic":"true",className:"pointer-events-none absolute left-1/2 top-1/2 z-30 w-max max-w-[calc(100%-1.5rem)] -translate-x-1/2 -translate-y-1/2 motion-safe:animate-[fade-in_0.15s_ease-out]",children:s.jsxs("button",{type:"button","aria-label":`${w}:${L} · ${n?"点击预览":"Preview"}`,onClick:()=>{d({result:c,message:L}),t()},className:"pointer-events-auto flex max-w-full select-none items-center gap-1.5 rounded-full border border-border/15 bg-surface-elevated px-3 py-2 text-[11px] leading-4 text-foreground shadow-md focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary",children:[s.jsx(pi,{size:13,strokeWidth:2.5,className:"shrink-0 text-primary","aria-hidden":"true"}),s.jsx("span",{className:"truncate tabular-nums",children:L}),s.jsx("span",{className:"shrink-0 text-muted-foreground",children:n?"预览 ›":"Preview ›"})]})}),l&&Xs.createPortal(s.jsx(eN,{result:l.result,message:l.message,onClose:()=>d(null)}),document.body)]})}const rN=320,U2="termdock:mobile-keyboard-expanded",z2="termdock:mobile-keyboard-preset-mode",H2="termdock:mobile-long-press-mode",nN=80;function sN(e){return/\.(?:jpe?g|png|heic|heif)$/i.test(e.name)||/^(?:image\/jpeg|image\/png|image\/heic|image\/heif)$/i.test(e.type)}function W2(e){const t=(e instanceof Error?e.message:String(e)).slice(0,3e3);return/importing a module script failed|dynamically imported module|loading chunk/i.test(t)?`压缩模块加载失败,可能是页面版本过旧或网络中断。请更新页面后重试,无需清除转码器缓存。
|
|
75
75
|
${t}`:t}function iN(e){switch(e?.phase){case"loading":return`正在加载转码器… ${e.progress??0}%(优先使用浏览器缓存)`;case"saving":return"加载完成,正在保存到本机…";case"initializing":return e.source==="local"?"已找到本机缓存,正在初始化转码器…":"正在初始化本地转码器…";case"ready":return e.source==="local"?"已从本机缓存加载,转码器已就绪。":e.saved?"转码器已就绪,已保存到本机供下次使用。":"转码器已就绪。";default:return"正在检查本机转码器缓存…"}}function tm(){return wy()}const aN={retry:{maxRetries:60,initialDelayMs:1e3,maxDelayMs:2e4},connectionTimeoutMs:15e3},oN=({sessionId:e,mode:t,tmuxSessionName:r=null,terminalSettings:n=X1(),colorTheme:a="dark",toolbarPresets:c=[],isActive:l=!0,focusSuspended:d=!1,deferCursorUntilPositioned:p=!1,isLayoutVisible:m=!0,focusRequestToken:x=0,resumeRequestToken:y=0,resumeRequestReason:w="visibility",resumeRequestDelayMs:v=0,forceResumeReconnect:S=!1,initialConnectDelayMs:L=0,initialConnectEnabled:E=!0,resumeRequestEnabled:R=!0,onStreamReadyChange:B,onStreamConnected:z,onViewportReadyChange:O,onContentReadyChange:$,onKeyboardVisibilityChange:V,suppressKeyboard:Z=!1,keyboardPortalTarget:le=null,sharedMobileKeyboardLayout:be=!1,suppressPageFlipRefresh:pe=!1,showDebug:ee,onStatusChange:_e})=>{const{t:ze}=Ur(),[Y]=k.useState(e||n3()),[ce,qe]=k.useState(()=>(e?Om(e):null)??n.fontSize),we=k.useMemo(()=>uE(),[]),ye=k.useMemo(()=>Fu("session"),[]),Le=k.useMemo(()=>Fu("keyboard"),[]),Be=k.useRef(null),ne=k.useRef(null);k.useEffect(()=>{Om(Y)===null&&qe(n.fontSize)},[n.fontSize,Y]);const Fe=k.useMemo(()=>({...n,fontSize:ce}),[n,ce]),ke=d8(),Ee=d||ke,[Pe,Ne]=k.useState(tm),[oe,We]=k.useState(!1),[nt,gt]=k.useState(!1),[ue,Ze]=k.useState(!1),[at,Ie]=k.useState(()=>typeof document>"u"?!0:!document.hidden&&Cu()),[Ge,Ce]=k.useState(()=>typeof document>"u"?!0:document.hasFocus()),[H,ae]=k.useState(!1),Ae=k.useRef(H);Ae.current=H;const[Ye,et]=k.useState(!1),[St,Gt]=k.useState(!1),[Qt,wt]=k.useState(!1),[zt,Vt]=k.useState(!0),{isOpen:Kt,keyboardHeight:Ot}=rv({enabled:Pe&&l}),[It,xe]=k.useState(null),[Ve,ht]=k.useState(null),[q,ut]=k.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(U2)==="true"),[qt,tt]=k.useState(()=>{if(typeof window>"u")return"auto";const se=window.localStorage.getItem(z2);return se&&se.length>0?se:"auto"}),[De,nr]=k.useState(()=>typeof window>"u"?"arrows":window.localStorage.getItem(H2)==="copy"?"copy":"arrows"),[Ke,_t]=k.useState("idle"),[$t,yt]=k.useState("idle"),[xt,Rt]=k.useState(0),[Ct,fr]=k.useState(null),[Yt,Sr]=k.useState(null),[pn,dr]=k.useState(null),me=k.useCallback(()=>dr(null),[]),{preferences:Gr,update:ot,saveFailed:pt}=rg(),{videoEnabled:ir,videoMaxHeight:Mn,videoBitrate:Xr,imageEnabled:je,imageMaxDimension:st,imageQuality:bt}=Gr,[Br,Vr]=k.useState(!1),[Cr,qr]=k.useState(null),[mn,on]=k.useState(null),zr=Yr(se=>se.sessions.get(Y)),{setTerminalSession:un,setConnecting:Er,appendToBuffer:re,replaceBuffer:mt,clearTerminalSession:Mt,removeTerminalSession:rr,clearBuffer:Ar,setSessionActiveProgram:Fr,setSessionCwd:Xt,setSessionCopyMode:Zr,setSessionAgentStatus:Jt,setSessionShellTitle:Pr,setSessionPromptState:Hr,clearAgentNeedsReview:ps}=Yr.getState(),Mr=k.useMemo(()=>`wt-${Y.replace(/[^a-zA-Z0-9_-]/g,"").slice(0,12)}`,[Y]),jn=zr?.terminalSessionId??null,Tr=zr?.mode??"shell",Jr=zr?.activeProgram??null,ln=k.useMemo(()=>Ru(c),[c]),Qr=Tr==="tmux",ks=zr?.bufferChunks??[],Dr=zr?.isConnecting??!1,en=jn,xn=k.useCallback(async(se,T)=>{const j=RI(se,zr?.cwd||zr?.directory);if(!j)return;let Q=j,F="directory";try{Q=(await D1(j)).path}catch(ge){if(!(ge instanceof Error)||ge.message!=="Path is not a directory")return;F="file"}try{const ge=Wt.getState();ge.setRightTab("files"),ge.openRight(),window.dispatchEvent(new CustomEvent(_I,{detail:{path:Q,kind:F,line:T}}))}catch{}},[zr?.cwd,zr?.directory]),X=t??zr?.mode??"shell",He=X==="tmux"?r??zr?.tmuxSessionName??null:null,[Nt,Et]=k.useState(null),tr=k.useRef(!1),[jr,cr]=k.useState(!1),[Cn,Ls]=k.useState(!1),[Xn,cn]=k.useState(null),[dn,_r]=k.useState(0),[Or,Gn]=k.useState(null),Vn=ee!==void 0?ee:!1,gn=k.useRef(null),Jn=k.useRef(null),kr=k.useRef(null),Lr=k.useRef(null),pr=k.useRef(null),ns=k.useRef(!1),Un=k.useRef(null),En=k.useRef([]),kn=k.useRef(0),ss=k.useRef(!1),Wr=k.useRef(null),tn=k.useRef(null),G=k.useRef(-1),Me=k.useRef(null),$e=k.useRef(0),Je=k.useRef(null),it=k.useRef(null),Tt=k.useRef(0),kt=k.useRef(0),Dt=k.useRef(!1),ft=k.useRef(null),Bt=k.useRef(null),W=k.useRef(!1),N=k.useRef(0),U=k.useRef(!1),K=k.useRef(!1),fe=k.useRef(!1),Qe=k.useRef(null),ve=k.useRef(null),lt=k.useRef(null),vt=k.useRef(l);vt.current=l;const br=k.useRef(Ee);br.current=Ee;const Lt=k.useRef(d);Lt.current=d;const rn=k.useRef(Pe),yn=k.useRef(null),hn=k.useRef(null),Dn=k.useRef(null),zn=k.useRef(null),hr=k.useRef(null),jt=k.useRef(null),Bn=k.useRef(null),qn=k.useCallback(()=>{const se=++N.current,T=()=>{se===N.current&&et(!0)};if(typeof window>"u"){T();return}window.requestAnimationFrame(()=>window.requestAnimationFrame(T))},[]),Wa=k.useCallback(se=>{if(U.current){if(ve.current!==null&&(window.clearTimeout(ve.current),ve.current=null),se.x===0&&se.y>=se.rows-1){Vt(!1);return}ve.current=window.setTimeout(()=>{ve.current=null,Vt(!0)},nN)}},[]),Qn=k.useRef(null);k.useEffect(()=>()=>{Qn.current?.()},[]);const is=k.useCallback(()=>{Qn.current||(Qn.current=U1(()=>{Qn.current=null;const se=Yr.getState(),T=kr.current,j=se.getTerminalSession(Y);if(!T||j?.mode!=="shell"||se.hasPendingBufferWrites(Y))return;const Q=h8(T),F=pr.current?.getDimensions();if(!Q||!F)return;const ge=pr.current?.serializeSnapshot();ge&&f8({id:T,version:1,...Q,...F,data:ge,savedAt:Date.now()})},2e3))},[Y]),zi=k.useCallback(se=>{const T=Yr.getState(),j=T.getTerminalSession(Y)?.bufferChunks.at(-1)?.id;if(kr.current&&j!==void 0&&j<=se&&!T.hasPendingBufferWrites(Y)&&(p8(kr.current),is()),!Dt.current||!FE({writtenChunkId:se,initialTargetChunkId:ft.current}))return;const Q=Bt.current;Bt.current=null,Q!==null&&pr.current?.notifyScreenSynchronized(Q),Dt.current=!1,ft.current=null,qn()},[qn,is,Y]),da=k.useCallback(se=>{if(!U.current)return;const T=Qe.current;T&&T.x===se.x&&T.y===se.y&&T.rows===se.rows||(Qe.current=se,ve.current!==null&&(window.clearTimeout(ve.current),ve.current=null),se.x===0&&se.y>=se.rows-1&&Vt(!1))},[]);k.useEffect(()=>{if(!p){K.current=!1;return}K.current||(K.current=!0,fe.current=!1,U.current=!0,Qe.current=null,Vt(!1),ve.current!==null&&(window.clearTimeout(ve.current),ve.current=null),lt.current!==null&&window.clearTimeout(lt.current),lt.current=window.setTimeout(()=>{lt.current=null,ve.current!==null&&typeof window<"u"&&window.clearTimeout(ve.current),ve.current=null,U.current=!1,Vt(!0)},15e3))},[p]);const bs=k.useCallback(()=>{zn.current=null;const se=Dn.current;Dn.current=null,se&&Pr(se.sessionId,se.title)},[Pr]),Ga=k.useCallback((se,T)=>{if(Dn.current={sessionId:se,title:T},zn.current===null){if(typeof window>"u"){bs();return}zn.current=window.requestAnimationFrame(bs)}},[bs]),So=k.useCallback(()=>{zn.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(zn.current),zn.current=null,Dn.current=null},[]),Hn=k.useCallback(async()=>{const se=X;return(await m8({preferredFrontendSessionId:Y,mode:se,tmuxSessionName:se==="tmux"?He||Mr:void 0,termType:"xterm-256color",requireExisting:!0})).terminalSession},[X,He,Mr,Y]),ha=k.useRef(l);k.useEffect(()=>{if(!l){pr.current?.blur(),ha.current=!1;return}if(ha.current)return;ha.current=!0;const se=GL(Pe,pe);if(se==="single"){pr.current?.requestRefresh("focus",{skipResizePush:!0,skipScrollToBottom:!0});return}se!=="none"&&pr.current?.requestRefresh("page-flip",{reconcileServerSize:!0,skipScrollToBottom:!0})},[l,Pe,pe,en]),k.useEffect(()=>{rn.current=Pe},[Pe]);const ms=k.useCallback(()=>{!vt.current||br.current||pr.current?.focus()},[]);k.useLayoutEffect(()=>{Ee&&pr.current?.blur()},[Ee]),k.useEffect(()=>{if(!l||Ee||zt||fe.current)return;fe.current=!0;const se=window.requestAnimationFrame(()=>{pr.current?.requestPtyRedraw()});return()=>window.cancelAnimationFrame(se)},[Ee,l,zt]);const Ia=k.useCallback(se=>{typeof window>"u"||typeof document>"u"||!vt.current||br.current||rn.current||document.hidden||!Cu()||(yn.current!==null&&window.clearTimeout(yn.current),yn.current=window.setTimeout(()=>{if(yn.current=null,!vt.current||br.current||rn.current||document.hidden||!Cu())return;const T=document.activeElement,j=T?.getAttribute("data-terminal-input-anchor")==="true";if((T instanceof HTMLInputElement||T instanceof HTMLTextAreaElement||T instanceof HTMLSelectElement||T?.isContentEditable===!0)&&!j){Le("desktop resume focus skipped: editable active",{reason:se});return}Le("desktop resume focus",{reason:se}),pr.current?.requestRefresh("focus",{force:!0,forceRedraw:!0,skipResizePush:!0,skipScrollToBottom:!0}),pr.current?.focus()},50))},[Le]);k.useEffect(()=>()=>{yn.current!==null&&typeof window<"u"&&window.clearTimeout(yn.current),yn.current=null,hn.current!==null&&typeof window<"u"&&window.clearTimeout(hn.current),hn.current=null,hr.current!==null&&typeof window<"u"&&window.clearTimeout(hr.current),hr.current=null,jt.current!==null&&typeof window<"u"&&window.clearTimeout(jt.current),jt.current=null,lt.current!==null&&typeof window<"u"&&window.clearTimeout(lt.current),lt.current=null,ve.current!==null&&typeof window<"u"&&window.clearTimeout(ve.current),ve.current=null},[]),k.useEffect(()=>{if(typeof document>"u"||typeof window>"u")return;const se=()=>{hn.current!==null&&window.clearTimeout(hn.current),hn.current=window.setTimeout(()=>{hn.current=null;const T=document.activeElement,Q=!(T?.getAttribute("data-terminal-input-anchor")==="true")&&!!(T&&(T instanceof HTMLInputElement||T instanceof HTMLTextAreaElement||T instanceof HTMLSelectElement||T.isContentEditable));VS({isActive:vt.current&&!br.current,isMobile:rn.current,documentVisible:!document.hidden,activeElementIsEditable:Q})&&ms()},0)};return document.addEventListener("pointerup",se),()=>{document.removeEventListener("pointerup",se),hn.current!==null&&(window.clearTimeout(hn.current),hn.current=null)}},[ms]);const as=k.useCallback(()=>{Hi.current=!1,_r(se=>se+1)},[]),Va=k.useCallback((se,T,j)=>{const Q=kr.current,F=Date.now();if(Q&&T&&g8(Q)){ne.current={startedAt:F,strategy:"reconnect",reason:se},ka("info","PWA_RESUME terminal-start",{frontendSessionId:Y,backendSessionId:Q,strategy:"reconnect",reason:se,active:vt.current});return}if(Q&&x8(Q,()=>{const ge=ne.current;ka("info","PWA_RESUME terminal-responsive",{frontendSessionId:Y,backendSessionId:Q,durationMs:ge?Date.now()-ge.startedAt:null,strategy:ge?.strategy??"probe",reason:ge?.reason??se}),ne.current=null,z?.(Y)},{visible:j})){ne.current={startedAt:F,strategy:"probe",reason:se},ka("info","PWA_RESUME terminal-start",{frontendSessionId:Y,backendSessionId:Q,strategy:"probe",reason:se,active:vt.current}),ye("[Terminal] resume probe sent",{reason:se,backendSessionId:Q,active:vt.current});return}if(ye("[Terminal] resume probe missing connection, restarting ensureSession",{reason:se,backendSessionId:Q,active:vt.current}),!$E({initialConnectionPending:W.current})){ye("[Terminal] resume probe deferred during initial websocket handshake",{reason:se,backendSessionId:Q});return}as()},[ye,z,as,Y]),Js=k.useCallback((se,T)=>{const j=kr.current;j&&Un.current!==se&&(Un.current=se,tx(j,se,T),ye("[Terminal] flow-control state sent",{backendSessionId:j,paused:se,reason:T}))},[ye]),ei=k.useCallback((se,T)=>{const j=kr.current;j&&Je.current!==se&&(Je.current=se,rx(j,se,T),ye("[Terminal] focus state sent",{backendSessionId:j,focused:se,reason:T}))},[ye]),Hs=k.useCallback((se,T)=>{const j=kr.current;j&&it.current!==se&&(it.current=se,nx(j,se,T),ye("[Terminal] viewing state sent",{backendSessionId:j,viewing:se,reason:T}))},[ye]),qa=WS({isActive:l&&!Ee,viewportFocused:ue,documentVisible:at,windowFocused:Ge,streamReady:H}),Is=GS({isActive:l,documentVisible:at,windowFocused:Ge,streamReady:H,isDesktop:vo()!==null}),fa=k.useRef(qa),dl=k.useRef(Is);k.useEffect(()=>{fa.current=qa,ei(qa,"logical-focus-change")},[qa,ei,en]),k.useEffect(()=>{dl.current=Is,Hs(Is,"logical-viewing-change")},[Is,Hs,en]),TC(en,at,H),k.useEffect(()=>{const se=T=>{const j=T.detail;!j||j.sessionId!==Y||qe(j.fontSize??n.fontSize)};return window.addEventListener("termfontchange",se),()=>window.removeEventListener("termfontchange",se)},[Y,n.fontSize]),k.useEffect(()=>{const se=()=>{const F=!document.hidden&&Cu();Ie(F),F&&l&&Ia("visibility")},T=F=>{l&&Ia(F.persisted?"bfcache":"pageshow")},j=()=>{Ce(!0),Ia("window-focus")},Q=()=>Ce(!1);return document.addEventListener("visibilitychange",se),window.addEventListener(sx,se),window.addEventListener("pageshow",T),window.addEventListener("focus",j),window.addEventListener("blur",Q),()=>{document.removeEventListener("visibilitychange",se),window.removeEventListener(sx,se),window.removeEventListener("pageshow",T),window.removeEventListener("focus",j),window.removeEventListener("blur",Q)}},[l,Ia]),k.useEffect(()=>{if(!y||!R||!xi.current)return;const se=v,T=se<=0,j=Be.current;if(j?.token===y&&(j.visible||!T))return;const Q=()=>{Be.current={token:y,visible:T},pr.current?.requestRefresh(w,{skipScrollToBottom:!0}),Va(se>0?"global-resume-background":"global-resume-visible",se<=0&&S,T)};if(se<=0){Q();return}const F=window.setTimeout(Q,se);return()=>window.clearTimeout(F)},[y,w,R,v,S,Va]);const Ya=k.useRef(0);k.useEffect(()=>{if(H){Ya.current=0;return}if(!jr||Nt==="Authentication required"||Nt===Yh)return;const se=Ya.current,T=Math.min(2e3*Math.pow(2,Math.min(se,4)),3e4),j=setTimeout(()=>{Ya.current+=1,ye("[Terminal] fatal self-heal: auto restarting ensureSession",{attempt:Ya.current,backendSessionId:kr.current}),Et("Reconnecting..."),cr(!1),as()},T);return()=>clearTimeout(j)},[Nt,jr,H,dn,ye,as]),k.useEffect(()=>{if(typeof window>"u"){We(!1);return}const se=/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1;We(se)},[]),k.useEffect(()=>{(!l||!Pe)&>(!1),l||Ze(!1)},[l,Pe]),k.useEffect(()=>{kr.current=en,G.current=-1,Bt.current=null,Je.current=null,it.current=null,Un.current=null},[en]),k.useEffect(()=>{B?.(Y,H)},[H,B,Y]),k.useEffect(()=>{$?.(Y,H&&Ye&&St)},[Ye,St,H,$,Y]),k.useEffect(()=>{Qr||(ss.current=!1,Wr.current=null,tn.current&&(clearTimeout(tn.current),tn.current=null))},[Qr]),k.useEffect(()=>{en&&pr.current?.requestRefresh("session-key-change",{force:!0})},[en]),k.useEffect(()=>{const se=l&&Pe&&Kt;Le("visibility signal",{sessionId:Y,isActive:l,isMobile:Pe,isInputFocused:nt,isViewportKeyboardOpen:Kt,viewportKeyboardHeight:Ot,visible:se}),V?.(Y,se)},[V,Y,l,Pe,Kt,Ot,Le]),k.useEffect(()=>{l&&x&&x!==$e.current&&($e.current=x,ms())},[x,ms,l]),k.useEffect(()=>{Lr.current=Y},[Y]),k.useEffect(()=>{!Pe&&(It!==null||Ve!==null)&&(xe(null),ht(null),Me.current=null)},[Pe,It,Ve]),k.useEffect(()=>{!en&&(It!==null||Ve!==null)&&(xe(null),ht(null),Me.current=null)},[en,It,Ve]),k.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(U2,q?"true":"false")},[q]),k.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(z2,qt)},[qt]),k.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(H2,De)},[De]),k.useEffect(()=>{Ne(tm());const se=()=>{Ne(tm())};return window.addEventListener("resize",se),()=>window.removeEventListener("resize",se)},[]);const os=k.useCallback(()=>{Tt.current+=1,kt.current+=1,bs(),So();const se=gn.current;gn.current=null,Jn.current=null,W.current=!1,Ae.current=!1,ae(!1),pr.current?.setSessionReady(!1);const T=kr.current;T&&tx(T,!1,"stream-disconnect"),ns.current=!1,Un.current=null,En.current=[],se?.()},[So,bs]),Ms=k.useCallback(async se=>{if(Jn.current===se){ye(`[startStream] Skipping - already connected to ${se}`);return}ye(`[startStream] Starting stream for frontendSessionId=${Y} backendSessionId=${se}`),cn(null),N.current+=1,Dt.current=!1,ft.current=null,et(!1),Gt(!1),os();const T=Tt.current+1;Tt.current=T,W.current=!0;const j=Yr.getState().getTerminalSession(Y);if(j?.mode==="shell"&&!j.bufferChunks.length){const F=await Promise.race([b8(se),new Promise(ge=>window.setTimeout(()=>ge(null),75))]);if(Tt.current!==T||Lr.current!==Y)return;if(F&&!Yr.getState().getTerminalSession(Y)?.bufferChunks.length){Yr.getState().replaceBuffer(Y,[F.data]);const ge=pr.current?.getDimensions();ge?.cols===F.cols&&ge.rows===F.rows&&y8(se,F.seq,F.epoch)}}const Q=we.connect(se,{onEvent:F=>{if(Tt.current!==T)return;const ge=Y;if(ge)switch(F.type){case"connected":{kt.current+=1,W.current=!1;const Se=ne.current;Se&&(ka("info","PWA_RESUME terminal-connected",{frontendSessionId:ge,backendSessionId:kr.current,durationMs:Date.now()-Se.startedAt,strategy:Se.strategy,reason:Se.reason}),ne.current=null),z?.(ge),(F.runtime||F.ptyBackend)&&ye(`[Terminal] connected frontendSessionId=${ge} backendSessionId=${kr.current} runtime=${F.runtime??"unknown"} pty=${F.ptyBackend??"unknown"} cwd=${F.cwd??"unknown"}`),Er(ge,!1),Et(null),cr(!1),cn(null),Ae.current=!0,ae(!0),kr.current&&(rx(kr.current,fa.current,"stream-connected"),nx(kr.current,dl.current,"stream-connected")),pr.current?.setSessionReady(!0),Un.current=null,Js(ns.current,"stream-connected"),F.tuiProgress!==void 0&&Yr.getState().setSessionTuiProgress(ge,F.tuiProgress??null),F.shellTitle!==void 0&&Yr.getState().setSessionShellTitle(ge,F.shellTitle??null),F.promptState!==void 0&&F.promptState!==null&&Yr.getState().setSessionPromptState(ge,F.promptState);const Oe=Yr.getState().getTerminalSession(ge);if(Oe?.terminalSessionId&&F.mode&&Yr.getState().setTerminalSession(ge,{sessionId:Oe.terminalSessionId,cols:80,rows:24,mode:F.mode,tmuxSessionName:F.tmuxSessionName??null,cwd:F.cwd??null}),F.activeProgram!==void 0&&Fr(ge,F.activeProgram??null,F.activeProgramSource??null,F.activeProgramRaw??null),pr.current?.requestRefresh("connected",{force:!0,reconcileServerSize:vt.current}),F.mode!=="tmux"&&(Gn(null),Zr(ge,!1)),ye("[Terminal] Connected event received:",{frontendSessionId:ge,backendSessionId:kr.current,storeHasState:!!Oe,storeTerminalId:Oe?.terminalSessionId,hasHistoryInStore:!!Oe?.history?.length,historyLength:Oe?.history?.length??0}),Oe?.history&&Oe.history.length>0){ye(`[Terminal] Restoring ${Oe.history.length} history chunks to frontend session ${ge}`);const er=Oe.history.reduce(($r,nn)=>$r+nn.length,0),or=Math.max(300,Math.min(2e3,Math.ceil(er/200)));kn.current=Date.now()+or,Oe.history.forEach($r=>{re(ge,$r,{markActivity:!1})}),Yr.getState().setSessionHistory(ge,[]),ye(`[Terminal] History restoration complete for ${ge}`)}else ye(`[Terminal] No history to restore for ${ge}`);const Xe=F.replayChunks,dt=!!Oe?.history?.length||!!Xe?.length;if(dt?Dt.current=!0:qn(),Xe&&Xe.length>0){let er=null;if(F.replayOutOfWindow)ye(`[Terminal] Replay out-of-window, atomically replacing buffer (${Xe.length} chunks)`),er=mt(ge,NC(Xe));else{ye(`[Terminal] Replay incremental: ${Xe.length} chunks`);for(const nn of Xe)re(ge,nn)}const or=Xe.reduce((nn,Pn)=>nn+Pn.length,0),$r=Math.max(200,Math.min(1500,Math.ceil(or/200)));kn.current=Math.max(kn.current,Date.now()+$r),ft.current=er}dt&&ft.current===null&&(ft.current=Yr.getState().flushPendingBufferWrites(ge),ft.current===null&&(Dt.current=!1,qn()));break}case"reconnecting":{Ae.current=!1,ae(!1),cn(Se=>Se??Date.now()),Et("Reconnecting..."),cr(!1);break}case"data":{F.data&&(ns.current?En.current.push(F.data):re(ge,F.data));break}case"tmux-layout":{Gn(F.layout??null),F.layout&&Zr(ge,F.layout.inCopyMode);break}case"tmux-screen-sync":{const Se=F.generation??0;if(Se<G.current)break;G.current=Se,N.current+=1,Dt.current=!0,et(!1),En.current=[],pr.current?.prepareScreenReplacement(),Bt.current=Se,ft.current=mt(ge,RC(F.chunks??[])),ft.current===null&&(Bt.current=null,pr.current?.notifyScreenSynchronized(Se),Dt.current=!1,qn()),typeof F.cols=="number"&&typeof F.rows=="number"&&pr.current?.notifyServerSize(F.cols,F.rows,"tmux-screen-sync");break}case"active-program":{Fr(ge,F.activeProgram??null,F.activeProgramSource??null,F.activeProgramRaw??null);break}case"cwd":{Xt(ge,F.cwd??null);break}case"agent-status":{Jt(ge,{agentStatus:F.agentStatus??null,agentIndicator:F.agentIndicator??null,agentStatusDetail:F.agentStatusDetail??null,agent:F.agent??null,agentMessage:F.agentMessage??null,agentNativeSessionId:F.agentNativeSessionId??null,agentResumeRecovered:F.agentResumeRecovered===!0,agentRich:F.agentRich===!0,agentActivity:F.agentActivity??0,agentCwd:F.agentCwd??null,reviewed:F.reviewed??null});break}case"git-status":{Yr.getState().setSessionGitStatus(ge,F.gitStatus??null);break}case"focus-mode":{ye("[Terminal] focus tracking mode",{backendSessionId:kr.current,requested:F.focusTrackingRequested===!0});break}case"resize-ack":{pr.current?.acknowledgeResize({seq:F.seq,ok:F.ok!==!1,cols:F.cols,rows:F.rows,screenSyncPending:F.screenSyncPending,screenSyncGeneration:F.screenSyncGeneration});break}case"pty-size":{typeof F.cols=="number"&&typeof F.rows=="number"&&pr.current?.notifyServerSize(F.cols,F.rows,F.source);break}case"shell-title":{Ga(ge,F.title??null);break}case"prompt-state":{Hr(ge,F.state??"idle",F.exitCode??null);break}case"tui-progress":{Yr.getState().setSessionTuiProgress(ge,F.tuiProgress??null);break}case"exit":{const Se=typeof F.exitCode=="number"?F.exitCode:null,Oe=typeof F.signal=="number"?F.signal:null;re(ge,`\r
|
|
76
76
|
[Process exited${Se!==null?` with code ${Se}`:""}${Oe!==null?` (signal ${Oe})`:""}]\r
|
|
77
|
-
`),Mt(ge),Er(ge,!1),Et("Terminal session ended"),ae(!1),cr(!1),cn(null),Gn(null),Zr(ge,!1),os();break}}},onError:(F,ge)=>{if(Tt.current!==T)return;const Se=Y;if(!Se)return;W.current=!1,Ae.current=!1,ae(!1);const Oe=ge&&F.message==="Authentication required",Xe=O2(F),dt=Oe?F.message:Xe||ge?"Reconnecting...":F.message||"Terminal stream connection error";console.error(`[Terminal] Stream error (fatal=${ge}):`,dt),Xe&&console.warn("[Terminal] SESSION_NOT_FOUND_DETECTED",{terminalIdAtError:kr.current,frontendSessionId:Se,isActive:l,isMobile:Pe,fatal:ge,stack:new Error().stack}),Et(dt),cr(!!ge),ge&&(cn(null),Er(Se,!1),os(),Xe&&(ye("[onError] Session lost, auto-recreating"),Et("Reconnecting..."),cr(!1),Mt(Se),Ar(Se),kr.current=null,Hi.current=!1,as()))}},{...aN,getDimensions:()=>pr.current?.getDimensions()??null});gn.current=()=>{Q.close(),Tt.current===T&&(Jn.current=null)},Jn.current=se},[re,Ar,Mt,ye,os,qn,z,Js,as,Ga,Er,Fr,Jt,Zr,Xt,Hr,we,Y]);k.useEffect(()=>{const se=VE({isActive:l,isStreamReady:H,reconnectStartedAt:Xn,now:Date.now()});if(se===null)return;const T=window.setTimeout(()=>{ye("[Terminal] visible reconnect watchdog expired",{backendSessionId:kr.current,reconnectStartedAt:Xn}),os(),Er(Y,!1),Et("Reconnecting..."),cr(!1),cn(Date.now()),as()},se);return()=>window.clearTimeout(T)},[ye,os,l,H,Xn,as,Y,Er]);const Hi=k.useRef(!1),xi=k.useRef(!1),bi=k.useRef(0);k.useEffect(()=>()=>{bi.current+=1,Hi.current=!1,os()},[os]);const hl=k.useRef(X),ti=k.useRef(He);k.useEffect(()=>{const se=hl.current,T=ti.current;hl.current=X,ti.current=He,Lr.current===Y&&(se===X&&T===He||(Hi.current=!1,os(),_r(j=>j+1)))},[X,He,os,Y]),k.useEffect(()=>{if(Lr.current!==Y&&(ye(`[useEffect] sessionId changed from ${Lr.current} to ${Y}, allowing reinitialization`),Hi.current=!1,xi.current=!1),Hi.current&&Lr.current===Y){ye(`[useEffect] Already initialized for sessionId=${Y}, skipping`);return}if(!Qt)return;const se=async ge=>{if(ye(`[ensureSession] Starting for sessionId=${Y}, runId=${ge}`),!Lr.current||Lr.current!==Y){ye(`[ensureSession] SessionId mismatch or stale run (current=${Lr.current}, target=${Y}), skipping`);return}if(ge!==bi.current){ye(`[ensureSession] Stale run detected (runId=${ge}, currentRunId=${bi.current}), skipping`);return}const Se=Yr.getState(),Oe=Se.getTerminalSession(Y),Xe=Oe?.mode??X;ye("[ensureSession] Current state from store:",{terminalSessionId:Oe?.terminalSessionId,mode:Oe?.mode,tmuxSessionName:Oe?.tmuxSessionName,isConnecting:Oe?.isConnecting});let dt=Oe?.terminalSessionId??null,er=!dt;if(dt&&Xe!==X?(ye(`[ensureSession] Store mode mismatch for ${dt}: current=${Xe} desired=${X}, will create new session`),er=!0,Se.clearTerminalSession(Y),dt=null):dt&&X==="tmux"&&He&&Oe?.tmuxSessionName!==He&&(ye(`[ensureSession] Store tmux name mismatch for ${dt}: current=${Oe?.tmuxSessionName} desired=${He}, will create new session`),er=!0,Se.clearTerminalSession(Y),dt=null),dt&&we.checkHealth&&!vt.current){ye(`[ensureSession] Checking health of existing session ${dt}`);try{const or=await we.checkHealth(dt);if(ye("[ensureSession] Health check result:",or),!or.healthy)ye(`[ensureSession] Session ${dt} is NOT healthy (healthy=${or.healthy}), will create new session`),ye("[ensureSession] Health check details:",or),er=!0,or.mode&&Oe?.terminalSessionId&&Se.setTerminalSession(Y,{sessionId:Oe.terminalSessionId,cols:80,rows:24,mode:or.mode,tmuxSessionName:or.tmuxSessionName??null}),Se.clearTerminalSession(Y),ye("[ensureSession] Cleared unhealthy session from store");else{ye(`[ensureSession] Session ${dt} is healthy, reusing it, cwd=${or.cwd}, clients=${or.clients}, lastActivity=${Date.now()-(or.lastActivity||0)}ms ago`),or.mode&&Oe?.terminalSessionId&&Se.setTerminalSession(Y,{sessionId:Oe.terminalSessionId,cols:80,rows:24,mode:or.mode,tmuxSessionName:or.tmuxSessionName??null}),ye(`[ensureSession] Setting terminalIdRef to ${dt} and starting stream`),kr.current=dt,Ms(dt),ye(`[ensureSession] Successfully reused healthy session ${dt}, returning early`);return}}catch(or){ye(`[ensureSession] Failed to check health of session ${dt}:`,or),ye("[ensureSession] Health check API call failed, proceeding as if session might be unhealthy")}}if(ye(`[ensureSession] Decision: shouldCreateNewSession=${er}, terminalId=${dt}`),er){ye(`[ensureSession] Creating new session, shouldCreateNewSession=${er}, runId=${ge}`),Et(null),cr(!1),Se.setConnecting(Y,!0);const $r=Yr.getState().getTerminalSession(Y),Pn=($r?.mode??X)===X&&(X!=="tmux"||!He||$r?.tmuxSessionName===He);if($r?.terminalSessionId&&Pn)ye(`[ensureSession] Race condition avoided: another instance already created session ${$r.terminalSessionId}`),Se.setConnecting(Y,!1),dt=$r.terminalSessionId,er=!1;else try{const yr=await Hn();if(ye(`[ensureSession] Opened managed backend session ${yr.sessionId}`),ge!==bi.current){ye(`[ensureSession] Stale run after session creation (runId=${ge}, currentRunId=${bi.current}), leaving ${yr.sessionId} for sibling`);return}Se.setTerminalSession(Y,yr),ye(`[ensureSession] Updated store with new session ${yr.sessionId}`),dt=yr.sessionId}catch(yr){if(ge!==bi.current){ye("[ensureSession] Stale run after session creation failed, skipping error handling");return}if(yr instanceof n0&&l1(yr)){ye("[ensureSession] Confirmed missing persisted session:",{sessionId:Y,error:yr.message}),Se.clearTerminalSession(Y),Et(Yh),cr(!0),Se.setConnecting(Y,!1);return}Et("Reconnecting..."),cr(!0),Se.setConnecting(Y,!1);return}}if(ge!==bi.current){ye(`[ensureSession] Stale run before starting stream (runId=${ge}, currentRunId=${bi.current}), skipping`);return}if(!dt){ye(`[ensureSession] No terminalId, terminalId=${dt}`);return}ye(`[ensureSession] Starting stream for session ${dt}`),kr.current=dt,Ms(dt),ye(`[ensureSession] ensureSession completed for sessionId=${Y}, terminalId=${dt}`)};let T=null,j=null;const Q=()=>{j=null,!(Hi.current&&Lr.current===Y)&&(ye(`[useEffect] Running ensureSession for sessionId=${Y}, hasInitialized=${Hi.current}`),Hi.current=!0,xi.current=!0,T=++bi.current,se(T))};if(!E&&!xi.current){ye(`[useEffect] Holding background connection until the selected session is ready: ${Y}`);return}const F=xi.current?0:Math.max(0,L);return F>0?(ye(`[useEffect] Delaying initial connection for sessionId=${Y} by ${F}ms`),j=window.setTimeout(Q,F)):Q(),()=>{j!==null&&window.clearTimeout(j),ye(`[useEffect] Cleanup for sessionId=${Y}, runId=${T??"pending"}`)}},[Y,dn,Ms,os,we,ye,X,He,Mr,L,E,Qt]);const Uo=k.useCallback(async()=>{if(Y&&!Cn){Ls(!0),Et(null),cr(!1),cn(null),os();try{we.forceKill&&await we.forceKill({sessionId:Y})}catch{}rr(Y),Ar(Y),pr.current?.clear(),await new Promise(se=>setTimeout(se,100));try{Er(Y,!0);const se=await Hn();un(Y,se),kr.current=se.sessionId,Ms(se.sessionId)}catch(se){Et(se instanceof n0&&l1(se)?Yh:"Reconnecting..."),cr(!0),Er(Y,!1)}finally{Ls(!1)}}},[Y,Cn,os,we,rr,Ar,Er,un,Ms,Hn]),pa=k.useCallback((se,T,j,Q)=>{if(!(kr.current!==T||kt.current!==j)){if(se instanceof n0&&O2(se)){ye("[Terminal] operation backend missing, recovering",{terminalId:T,sessionId:Y}),Et("Reconnecting..."),cr(!1),os(),Mt(Y),kr.current=null,Er(Y,!0),as();return}Et(se instanceof Error?se.message:Q)}},[Mt,ye,os,as,Y,Er]),fl=k.useCallback((se,T)=>{const j=T?.ownedPaste?wC(T.ownedPaste,Y,se):!1;if(T?.ownedPaste&&!j||Lt.current||(br.current||B1())&&!j)return Promise.resolve(!1);const Q=()=>!!T?.ownedPaste&&AC(T.ownedPaste,Y)&&vt.current&&!Lt.current&&Ae.current&&!tr.current&&!document.hidden&&navigator.onLine!==!1&&Cu();if(j&&!Q())return Promise.resolve(!1);if(!vt.current&&!T?.targeted||!se)return;const F=mE(se),ge=/^(\x1b\[<6[45];[0-9]+;[0-9]+M)+$/.test(se);if(Qr&&ge&&(ss.current=!0),Date.now()<kn.current)return;let Se=se,Oe=T?.consumeModifier??!1;if(!T?.skipModifierTransform&&It&&se.length>0){const $r=se[0];if($r.length===1&&/[a-zA-Z]/.test($r)){const nn=$r.toUpperCase();It==="ctrl"?(Se=String.fromCharCode(nn.charCodeAt(0)&31),Oe=!0):It==="alt"&&(Se=`\x1B${se}`,Oe=!0)}Oe||(It==="alt"&&(Se=`\x1B${se}`),Oe=!0)}const Xe=kr.current;if(!Xe)return;const dt=kt.current,or=(async()=>{try{if(Qr&&!F&&ss.current&&we.tmuxAction){ss.current=!1;try{await we.tmuxAction(Xe,{action:"copy-mode",enabled:!1})}catch{}if(kr.current!==Xe||kt.current!==dt)return!1;if(gE(Se))return!0}return j&&(!Q()||kr.current!==Xe||kt.current!==dt)||(await we.sendInput(Xe,Se),j&&(!Q()||kr.current!==Xe||kt.current!==dt))?!1:(ps(Y),!0)}catch($r){return pa($r,Xe,dt,"Failed to send input"),!1}})();return Oe&&(Ve||xe(null),ms()),or},[It,ps,ms,pa,Qr,Ve,Y,we]);k.useEffect(()=>{const se=T=>{const j=T,Q=j.detail?.sessionId;if(Q?Q!==Y:!vt.current)return;const F=j.detail?.text;if(!F)return;const ge=j.detail?.nonce;if(tr.current||!pr.current){ge&&window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:ge,ok:!1}}));return}const Se=vC(j.detail,Y),Oe=j.detail?.ownedPaste&&!Se?Promise.resolve(!1):pr.current.sendSequence(F,{paste:j.detail?.paste,submitAfterPaste:j.detail?.submitAfterPaste,targeted:!!Q,ownedPaste:Se??void 0});ge&&Promise.resolve(Oe).then(Xe=>{window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:ge,ok:Xe===!0}}))},()=>{window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:ge,ok:!1}}))}),qS(rn.current,j.detail?.focus!==!1)&&ms()};return window.addEventListener("termdock-insert-reference",se),()=>window.removeEventListener("termdock-insert-reference",se)},[ms,Y]);const pl=k.useCallback((se,T,j)=>{const Q=kr.current;if(!Q){Le("xterm resize push skipped: no terminalId",{cols:se,rows:T});return}Le("xterm resize push",{cols:se,rows:T}),we.resize({sessionId:Q,cols:se,rows:T,seq:j}).catch(F=>{pr.current?.acknowledgeResize({seq:j,ok:!1}),F&&/session not found/i.test(String(F.message||F))&&console.warn("[Terminal] resize 404 session not found",{sessionId:Q,cols:se,rows:T,stack:new Error().stack})})},[we,Le]),ls=k.useCallback(async se=>{const T=kr.current;if(!T||!we.tmuxAction)return;const j=kt.current;try{const Q=await we.tmuxAction(T,se);if(kr.current!==T||kt.current!==j)return;Q.layout&&(Gn(Q.layout),se.action==="switch-session"&&(un(Y,{sessionId:T,cols:80,rows:24,mode:"tmux",tmuxSessionName:Q.layout.sessionName}),v8(Y,{tmuxSessionName:Q.layout.sessionName}).catch(F=>{console.warn("[Terminal] failed to update inventory after tmux switch",F)})))}catch(Q){pa(Q,T,j,"Failed to execute tmux action")}},[pa,Y,un,we]);k.useEffect(()=>{if(!Or||!en)return;const T=Or.windows.find(j=>j.id===Or.activeWindowId)?.panes.find(j=>j.id===Or.activePaneId);T&&pr.current?.requestRefresh("tmux-layout",{skipScrollToBottom:!0,dedupeKey:`${en}:${Or.sessionId}:${T.id}:${T.width}x${T.height}`})},[Or,en]);const js=k.useCallback((se,T=5)=>{const j=Math.max(1,Math.min(Math.floor(T)||1,40));ss.current=!0;const Q=Wr.current;if(Q&&Q.direction===se){Q.lines+=j;return}Q&&ls({action:"scroll",direction:Q.direction,lines:Q.lines}).finally(()=>{ms()}),Wr.current={direction:se,lines:j},tn.current&&clearTimeout(tn.current),tn.current=setTimeout(()=>{const F=Wr.current;F&&(Wr.current=null,ls({action:"scroll",direction:F.direction,lines:F.lines}).finally(()=>{ms()}))},0)},[ms,ls]),Ri=k.useCallback(se=>{const T=Date.now(),j=Me.current,Q=j!==null&&j.modifier===se&&T-j.timestamp<=rN;if(Me.current={modifier:se,timestamp:T},Ve===se){ht(null),xe(null);return}if(Q){ht(se),xe(se);return}Ve!==null&&Ve!==se&&ht(null),xe(F=>F===se?null:se)},[Ve]),zo=k.useCallback(se=>{if(Ze(se&&vt.current),Le("input focus changed",{focused:se,isActive:vt.current,isMobile:rn.current}),!rn.current||!vt.current){gt(!1);return}gt(T=>T===se?T:se)},[Le]),Dl=k.useCallback(se=>{if(ns.current=se,Js(se,"viewport-watermark"),!se&&En.current.length>0){const T=Y;if(T){const j=En.current;En.current=[];for(const Q of j)re(T,Q)}}},[re,Js,Y]),Es=k.useCallback(se=>{vt.current&&pr.current?.ensureSizeMatches(se)},[]),Ea=k.useRef(null);k.useEffect(()=>{if(!l)return;const se=Ea.current;if(!se)return;const T=()=>Es("pointerdown"),j=()=>Es("keydown"),Q=()=>Es("touchstart"),F=()=>Es("wheel");return se.addEventListener("pointerdown",T),se.addEventListener("keydown",j),se.addEventListener("touchstart",Q,{passive:!0}),se.addEventListener("wheel",F,{passive:!0}),()=>{se.removeEventListener("pointerdown",T),se.removeEventListener("keydown",j),se.removeEventListener("touchstart",Q),se.removeEventListener("wheel",F)}},[l,Es]);const ml=k.useCallback(se=>{pr.current=se},[]),es=k.useCallback(se=>{wt(se),O?.(Y,se)},[O,Y]),Wi=k.useCallback(se=>{const T=SE(se);if(!T)return;const j=It!==null;pr.current?.sendSequence(T,{consumeModifier:j})},[It]),Mi=k.useCallback(se=>{const T=yE(se);if(T.length===0)return;const j=It!==null;pr.current?.sendSequence(D2(T[0]),{consumeModifier:j});for(let Q=1;Q<T.length;Q+=1){const F=T[Q];window.setTimeout(()=>{pr.current?.sendSequence(D2(F))},bE*Q)}},[It]),Gi=k.useCallback(()=>{pr.current?.pasteClipboardText()},[]),gs=k.useCallback(se=>{jt.current!==null&&(window.clearTimeout(jt.current),jt.current=null),yt(se),(se==="inserted"||se==="failed")&&(jt.current=window.setTimeout(()=>{jt.current=null,yt("idle")},1400))},[]),Ws=k.useCallback(()=>{gs("idle"),Rt(0),Bn.current?.click()},[gs]),Bl=k.useCallback(()=>{Vr(!0)},[]),Vi=k.useCallback(se=>{const T=se.currentTarget.files?.[0];if(se.currentTarget.value="",!T)return;const j=Y;Sr(null),fr(null),dr(null),Rt(0),gs("uploading");const Q=ir&&T.type.startsWith("video/")?{maxHeight:Mn,videoBitrate:Xr,onProgress:Rt}:null,F=je&&sN(T)?{maxDimension:st,quality:bt}:null;let ge=Q?"视频压缩":F?"图片压缩":"文件上传";(async()=>{const Se=Q?await(await Oc(async()=>{const{compressVideoLocally:Oe}=await import("./videoCompression-CuDMhYU3.js");return{compressVideoLocally:Oe}},__vite__mapDeps([0,1,2,3,4,5]))).compressVideoLocally(T,Q):F?await(await Oc(async()=>{const{compressImageLocally:Oe}=await import("./imageCompression-DaUBNTq-.js");return{compressImageLocally:Oe}},[])).compressImageLocally(T,F):T;ge="文件上传",await JE(Se,(Oe,Xe)=>N0(Oe,Xe,void 0,Rt),Oe=>(ge="插入终端",$2(c1(Oe,null),j,()=>vt.current&&!tr.current&&Lr.current===j&&Yr.getState().activeSessionId===j))),(Q||F)&&dr({file:Se,kind:Q?"video":"image",originalSize:T.size,uploadedSize:Se.size,originalRetained:Se===T})})().then(()=>gs("inserted"),Se=>{Se instanceof vf&&Sr({path:Se.uploaded.path,sessionId:j});const Oe=Se instanceof vf?Se.uploaded.path:W2(Se);fr({stage:ge,detail:Oe}),Vr(!0),gs("failed"),ka("warn","MOBILE_MEDIA_UPLOAD failed",{stage:ge,detail:Oe})})},[Xr,ir,Mn,je,st,bt,Y,gs]),qi=k.useCallback(async()=>{const se=Yt;if(!se||se.sessionId!==Y)return;Vr(!1),await new Promise(j=>window.requestAnimationFrame(()=>j())),gs("uploading"),await $2(c1(se.path,null),se.sessionId,()=>vt.current&&!tr.current&&Lr.current===se.sessionId&&Yr.getState().activeSessionId===se.sessionId)?(Sr(null),fr(null),gs("inserted")):(Vr(!0),gs("failed"))},[Yt,Y,gs]);k.useEffect(()=>{if(!Br||!ir)return;let se=!0;return on(null),qr({phase:"checking-cache"}),Oc(async()=>{const{prepareLocalVideoCompression:T}=await import("./videoCompression-CuDMhYU3.js");return{prepareLocalVideoCompression:T}},__vite__mapDeps([0,1,2,3,4,5])).then(({prepareLocalVideoCompression:T})=>{if(se)return T(j=>{se&&qr(j)})}).catch(T=>{se&&on(W2(T))}),()=>{se=!1}},[Br,ir]);const fn=Dr||Nt!==null;tr.current=fn;const ma=k.useRef(Jr);fn||(ma.current=Jr);const Yi=fn?ma.current:Jr,Na=k.useMemo(()=>vE(Yi,ln),[Yi,ln]),ji=k.useMemo(()=>Q2(ln,qt),[qt,ln]),Di=!Pe&&qt!=="auto"&&ji.id!=="default"&&ji.showOnDesktop!==!0?"auto":qt,ri=Di==="auto"?Na:Di,ws=k.useMemo(()=>Q2(ln,ri),[ri,ln]),Gs=k.useMemo(()=>ws.actions.filter(se=>se.sequence.trim().length>0).map((se,T)=>({...se,label:o1(se,T)})),[ws.actions]),Bi=k.useMemo(()=>K3(Jr),[Jr]),Ra=ws.label,ni=k.useMemo(()=>Di!=="auto"?`Manual preset: ${ws.label}`:Bi?`Auto preset · ${ws.label} (${Bi})`:"Auto preset",[Bi,Di,ws.label]),ys=k.useCallback(se=>{tt(se)},[]),Za=k.useCallback(()=>{nr(se=>se==="copy"?"arrows":"copy"),_t("idle")},[]),Ka=k.useCallback(()=>{typeof window>"u"||(hr.current!==null&&window.clearTimeout(hr.current),hr.current=window.setTimeout(()=>{hr.current=null,_t("idle")},1200))},[]),As=k.useCallback(se=>{hr.current!==null&&typeof window<"u"&&(window.clearTimeout(hr.current),hr.current=null),_t(se?"copied":"failed"),Ka()},[Ka]),Xa=k.useCallback(se=>{ut(se)},[]),Ql=k.useMemo(()=>Pe?wE(ln):AE(ln),[Pe,ln]),Ho=k.useMemo(()=>w8(a),[a]);k.useEffect(()=>{if(!Qr||!H||!Qt||!en)return;const se=MC(Ho);se&&we.sendInput(en,se).catch(T=>{console.warn("[Terminal] Failed to synchronize tmux default colors:",T)})},[Qr,H,Qt,en,we,Ho]);const Co=k.useMemo(()=>`terminal::${Y}`,[Y]);k.useEffect(()=>{_e?.({isConnecting:Dr,isRestarting:Cn,hasError:!!Nt,sessionId:en})},[Dr,Cn,Nt,en,_e]);const ga=!en||Dr||Cn,Ma=k.useCallback((se,T)=>{if(ga)return;const j=Math.max(1,Math.min(Math.floor(T)||1,40));js(se,j)},[js,ga]);k.useEffect(()=>{if(!l||!Pe)return;pr.current?.requestRefresh("resize",{skipScrollToBottom:!Kt,force:!0})},[l,Pe,Kt,Ot,Y]),k.useEffect(()=>{if(!l||!Pe)return;const se=T=>{const j=T.detail;pr.current?.requestRefresh("resize",{skipScrollToBottom:j?.isOpen!==!0,force:!0})};return document.addEventListener("termdock:viewport-keyboard-change",se),()=>{document.removeEventListener("termdock:viewport-keyboard-change",se)}},[l,Pe,Y]);const Wo=!Z&&(Pe||ws.id==="default"||ws.showOnDesktop===!0),xa=l,cs=Pe&&!be?{transform:"translateY(var(--kb-translate-y, 0px))",transition:"none"}:void 0,Go=Pe&&!be?{marginTop:"var(--kb-margin-top, 0px)",transition:"none"}:void 0,Zi=s.jsx(CE,{visible:Wo,interactive:xa,presentation:Pe?"mobile":"desktop-actions",activeModifier:It,lockedModifier:Ve,disabled:ga,defaultShowExtended:q,presetLabel:Ra,presetModeLabel:ni,presetMode:Di,presetOptions:Ql,includeAlt:ws.includeAlt,presetRowLayout:ws.rowLayout,extraActions:Gs,onKeyPress:Wi,onTextPress:Mi,onPastePress:Pe?Gi:void 0,onFilePress:Pe?Ws:void 0,onFileLongPress:Pe?Bl:void 0,fileUploadState:$t,fileUploadProgress:xt,longPressMode:De,copyFeedback:Ke,onLongPressModeToggle:Za,onModifierToggle:Ri,onPresetSelect:ys,onExpandedChange:Xa}),gl=typeof window<"u"&&(navigator.maxTouchPoints>0||"ontouchstart"in window);return s.jsxs("div",{className:"relative flex h-full min-h-0 flex-col overflow-hidden",style:cs,children:[s.jsx("input",{ref:Bn,type:"file",className:"hidden",onChange:Vi}),Br&&Xs.createPortal(s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"fixed inset-0 z-modal-backdrop cursor-default bg-[var(--app-backdrop)] backdrop-blur-sm",onClick:()=>Vr(!1),"aria-label":ze("common.close")}),s.jsxs("section",{role:"dialog","aria-modal":"true","aria-labelledby":"mobile-video-compression-title",className:"fixed bottom-[max(0.75rem,env(safe-area-inset-bottom,0px))] left-[max(0.75rem,env(safe-area-inset-left,0px))] right-[max(0.75rem,env(safe-area-inset-right,0px))] z-modal-panel max-h-[calc(100dvh-1.5rem)] overflow-y-auto rounded-2xl border border-border/15 bg-surface p-4 shadow-[0_28px_70px_var(--app-shadow-strong),0_14px_32px_var(--app-shadow-soft)] sm:left-1/2 sm:right-auto sm:w-[min(28rem,calc(100vw-2rem))] sm:-translate-x-1/2",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("h2",{id:"mobile-video-compression-title",className:"text-sm font-semibold text-foreground",children:"本地媒体压缩"}),s.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"按文件类型选择压缩方式,处理完成后才上传。"})]}),s.jsx("button",{type:"button",className:"min-h-10 rounded-lg bg-surface-2 px-3 text-xs",onClick:()=>Vr(!1),children:ze("common.close")})]}),Ct&&s.jsxs("div",{role:"alert",className:"mt-3 rounded-lg bg-destructive/10 p-3 text-xs text-destructive",children:[s.jsxs("p",{children:[Ct.stage,"失败。",Ct.stage.endsWith("压缩")?"原文件未上传。":Ct.stage==="插入终端"?"文件已上传,路径见详情。":""]}),s.jsxs("details",{className:"mt-2",children:[s.jsx("summary",{className:"cursor-pointer",children:"错误详情"}),s.jsx("p",{className:"mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words",children:Ct.detail})]}),Yt&&s.jsx("button",{type:"button",onClick:()=>{qi()},disabled:$t==="uploading"||Yt.sessionId!==Y,className:"mt-2 rounded-lg bg-surface-2 px-3 py-2 text-foreground disabled:opacity-50",children:ze("common.retry")})]}),pt&&s.jsx("p",{className:"mt-2 text-[11px] text-destructive",children:"本机未能保存设置,重新打开后可能恢复默认值。"}),s.jsxs("label",{className:"mt-4 flex min-h-11 items-center justify-between rounded-xl bg-surface-elevated px-3 text-sm",children:[s.jsx("span",{children:"显示压缩结果提示"}),s.jsx("input",{type:"checkbox",checked:Gr.showResultToast,onChange:se=>ot({showResultToast:se.target.checked}),className:"h-4 w-4 accent-primary"})]}),s.jsxs("label",{className:"mt-4 flex min-h-11 items-center justify-between rounded-xl bg-surface-elevated px-3 text-sm",children:[s.jsx("span",{children:"压缩图片后上传"}),s.jsx("input",{type:"checkbox",checked:je,onChange:se=>ot({imageEnabled:se.target.checked}),className:"h-4 w-4 accent-primary"})]}),je&&s.jsxs("div",{className:"mt-3 space-y-3",children:[s.jsxs("label",{className:"block text-xs text-muted-foreground",children:["图片最长边",s.jsx("select",{value:st,onChange:se=>ot({imageMaxDimension:Number(se.target.value)}),className:"mt-1 block min-h-10 w-full rounded-lg bg-surface-2 px-3 text-sm text-foreground",children:sv.map(se=>s.jsxs("option",{value:se,children:[se," px",se===640?" · 最省流量":se===2048?" · 推荐":se===4096?" · 保留更多细节":""]},se))})]}),s.jsxs("label",{className:"block text-xs text-muted-foreground",children:["图片画质:",Math.round(bt*100),"%",s.jsx("input",{type:"range",min:l0.min,max:l0.max,step:l0.step,value:bt,onChange:se=>ot({imageQuality:Number(se.target.value)}),className:"mt-2 h-1 w-full accent-primary"})]}),s.jsx("p",{className:"text-[11px] text-muted-foreground",children:"支持 JPEG、PNG、HEIC 照片;GIF、SVG 等保持原文件。压缩后未变小也会保留原图。"})]}),s.jsx("div",{className:"mt-4 border-t border-border/15 pt-1"}),s.jsxs("label",{className:"mt-4 flex min-h-11 items-center justify-between rounded-xl bg-surface-elevated px-3 text-sm",children:[s.jsx("span",{children:"压缩视频后上传"}),s.jsx("input",{type:"checkbox",checked:ir,onChange:se=>ot({videoEnabled:se.target.checked}),className:"h-4 w-4 accent-primary"})]}),ir&&s.jsxs("div",{className:"mt-4 space-y-4",children:[s.jsxs("label",{className:"block text-xs text-muted-foreground",children:["视频最长边(像素)",s.jsx("select",{value:Mn,onChange:se=>ot({videoMaxHeight:Number(se.target.value)}),className:"mt-1 block min-h-10 w-full rounded-lg bg-surface-2 px-3 text-sm text-foreground",children:iv.map(se=>s.jsxs("option",{value:se,children:[se," px",se===240?" · 最省流量":se===720?" · 推荐":se>=1440?" · 手机处理较慢":""]},se))})]}),s.jsxs("label",{className:"block text-xs text-muted-foreground",children:["目标视频码率:",Xr/1e6," Mbps",s.jsx("input",{type:"range",min:c0.min,max:c0.max,step:c0.step,value:Xr,onChange:se=>ot({videoBitrate:Number(se.target.value)}),className:"mt-2 h-1 w-full accent-primary"})]}),s.jsx("p",{className:"text-[11px] text-muted-foreground",children:"保持比例,不放大原视频。尺寸越小通常处理越快;码率越低体积通常越小,过高可能比原片更大。"}),s.jsx("p",{className:"text-[11px] text-muted-foreground",role:"status","aria-live":"polite",children:mn?"本地转码器准备失败,请关闭开关后重试。":iN(Cr)}),Cr?.saved===!1&&s.jsx("p",{className:"text-[11px] text-destructive",children:"本机未能保存转码器,重新打开后可能需要重新下载。"}),mn&&s.jsx("p",{className:"text-[11px] text-destructive",children:mn})]})]})]}),document.body),Vn&&s.jsx(_E,{isMobile:Pe,isInputFocused:nt,isIOS:oe,isConnecting:Dr,connectionError:Nt,terminalSessionId:en}),s.jsxs("div",{className:"relative min-h-0 flex-1 overflow-hidden",style:{backgroundColor:Ho.background,...Go},children:[s.jsx("div",{ref:Ea,className:"h-full w-full box-border",children:s.jsx(A8,{fallback:s.jsx("div",{className:"flex h-full items-center justify-center bg-background",children:s.jsxs("div",{className:"flex flex-col items-center gap-3 text-center rounded-2xl bg-surface-2 px-6 py-5 shadow-sm",children:[s.jsx("div",{className:"w-10 h-10 rounded-full bg-destructive/15 flex items-center justify-center",children:s.jsx("svg",{className:"w-5 h-5 text-destructive",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),s.jsx("span",{className:"text-sm text-muted-foreground",children:ze("terminal.componentFailed")})]})}),children:s.jsx(lE,{ref:ml,sessionKey:Co,sessionId:Y,isLayoutVisible:m,chunks:ks,onInput:fl,onResize:pl,onFlowControl:Dl,onTmuxScroll:Qr?Ma:void 0,tmuxScrollSensitivity:.38,onDoubleTap:Pe?()=>{pr.current?.sendSequence(" ")}:void 0,onInputFocusChange:zo,onMobileLongPressCopyResult:As,onReadyChange:es,onSizeSynchronizedChange:Gt,onWritesSettled:Wa,onWriteProgress:zi,onCursorPositionChange:da,onDirectoryLinkActivate:xn,terminalSettings:Fe,theme:Ho,enableTouchScroll:Pe,mobileLongPressMode:De,autoFocus:!Ee&&!Pe&&!gl,cursorVisible:!Ee&&zt,suppressSmoothScroll:!Ye||!St,className:Ee||!zt?"terminal-focus-suspended":void 0},Co)})}),s.jsx(tN,{result:pn,onDismiss:me}),s.jsx(LE,{connectionError:Nt,isFatalError:jr,isRestarting:Cn,isConnecting:Dr,onHardRestart:Uo})]}),le?Z?null:Xs.createPortal(Zi,le):Zi]})};function lN({session:e,active:t,onActivate:r,onToggleRightSidebar:n}){const{t:a}=Ur(),c=Yr(l=>{const d=l.sessions.get(e.id);return il(e,d?.activeProgram??null,d?.cwd??null,void 0,d?.shellTitle??null,d?.promptState??null).primary});return s.jsxs("div",{"data-pane-titlebar":"true",className:"swiper-no-swiping flex h-6 min-h-6 shrink-0 items-center border-b border-border app-chrome-bg",children:[s.jsxs("button",{type:"button","data-split-pane-title":e.id,draggable:!1,onDragStart:l=>l.preventDefault(),"aria-pressed":t,title:`${c} · 拖动标题移动,边缘拆分,中央交换`,onClick:r,className:"split-pane-drag-handle flex h-full min-w-0 cursor-grab active:cursor-grabbing flex-1 items-center gap-1.5 overflow-hidden px-2 text-left text-[12px] font-medium leading-none text-foreground hover:bg-surface focus-visible:outline focus-visible:outline-1 focus-visible:outline-primary focus-visible:-outline-offset-1",children:[s.jsx($o,{size:11,className:`shrink-0 ${t?"text-primary":"text-muted-foreground"}`}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:c}),s.jsx($f,{size:12,"aria-hidden":"true",className:"shrink-0 text-muted-foreground"}),t&&s.jsx("span",{"aria-hidden":"true",className:"h-1 w-1 shrink-0 rounded-full bg-primary"})]}),n&&s.jsx("button",{type:"button",onClick:n,"aria-label":a("tab.explorerTitle"),title:a("tab.explorerTitle"),className:"inline-flex h-full w-7 shrink-0 items-center justify-center text-muted-foreground hover:bg-surface hover:text-foreground focus-visible:outline focus-visible:outline-1 focus-visible:outline-primary focus-visible:-outline-offset-1",children:s.jsx($y,{size:14})})]})}const cN="termdock:startup:";function Mu(e){if(typeof performance>"u"||typeof performance.mark!="function")return;const t=`${cN}${e}`;performance.getEntriesByName(t,"mark").length>0||performance.mark(t)}function G2(e,t){e||Xs.flushSync(t)}const u1="horizontal";function Pu(e){return e<=0?[]:Array.from({length:e},()=>1/e)}function Zh(e,t){if(!Array.isArray(e)||e.length!==t)return Pu(t);const r=e.map(Number);if(r.some(a=>!Number.isFinite(a)||a<=0))return Pu(t);const n=r.reduce((a,c)=>a+c,0);return n<=0?Pu(t):r.map(a=>a/n)}function uN(e){const t=Math.max(1,Math.ceil(Math.sqrt(Math.max(1,e))));return{columns:t,rows:Math.max(1,Math.ceil(Math.max(1,e)/t))}}function dN(e){return e==="horizontal"||e==="vertical"||e==="grid"}function hN(e){if(!Array.isArray(e))return[];const t=new Set,r=new Set,n=[];for(const a of e){if(!a||typeof a!="object")continue;const c=a;if(typeof c.id!="string"||!c.id||r.has(c.id))continue;const l=Array.isArray(c.sessionIds)?c.sessionIds.filter(m=>typeof m=="string"&&!!m&&!t.has(m)):[],d=[...new Set(l)];if(d.length<2)continue;const p=uN(d.length);d.forEach(m=>t.add(m)),r.add(c.id),n.push({id:c.id,...typeof c.name=="string"&&c.name.trim()?{name:c.name.trim().slice(0,80)}:{},sessionIds:d,layout:dN(c.layout)?c.layout:u1,ratios:Zh(c.ratios,d.length),...c.gridColumnRatios!==void 0?{gridColumnRatios:Zh(c.gridColumnRatios,p.columns)}:{},...c.gridRowRatios!==void 0?{gridRowRatios:Zh(c.gridRowRatios,p.rows)}:{}})}return n}function fN(e,t){const r=new Set(t);return e.flatMap(n=>{const a=n.sessionIds.filter(c=>r.has(c));return a.length<2?[]:[{...n,sessionIds:a,ratios:a.length===n.sessionIds.length?Zh(n.ratios,a.length):Pu(a.length)}]})}function A0(e,t){if(t)return e.find(r=>r.sessionIds.includes(t))}function rm(e,t,r){if(!t||!r||t===r)return e;const n=A0(e,t),a=A0(e,r);if(n&&n.id===a?.id)return e;const c=[...n?.sessionIds??[t],...a?.sessionIds??[r]],l=[...new Set(c)],d={id:n?.id??`split:${t}`,...n?.name?{name:n.name}:{},sessionIds:l,layout:l.length>2&&(!n||n.layout===u1)?"grid":n?.layout??u1,ratios:Pu(l.length)},p=new Set([n?.id,a?.id].filter(Boolean)),m=e.filter(y=>!p.has(y.id)),x=n?Math.max(0,e.findIndex(y=>y.id===n.id)):m.length;return m.splice(Math.min(x,m.length),0,d),m}function pN(e,t){const r=A0(e,t);if(!r||!t)return e;if(r.sessionIds.length<=2)return e.filter(a=>a.id!==r.id);const n=r.sessionIds.filter(a=>a!==t);return e.map(a=>a.id===r.id?{...a,sessionIds:n,ratios:Pu(n.length)}:a)}function mN(e,t){const r=A0(e,t);return r?e.filter(n=>n.id!==r.id):e}function gN(e,t,r){return e.map(n=>{if(n.id!==t)return n;const a=[...new Set(r)],c=new Set(n.sessionIds);return a.length===n.sessionIds.length&&a.every(d=>c.has(d))?{...n,sessionIds:a}:n})}function xN(e,t,r){const n=r.trim().slice(0,80);return e.map(a=>a.id===t?{...a,...n?{name:n}:{name:void 0}}:a)}const d1=320,ov=1,bN=d1+120,h1="termdock:split-workspaces:v2",lv="termdock:split-workspace:v1",yN=.1,vN=.9;function nm(){if(typeof window>"u")return{mobile:!1,landscape:!1};const e=wy();return{mobile:e,landscape:e&&window.innerWidth>window.innerHeight}}function wN(){if(typeof window>"u")return[];try{const e=window.localStorage.getItem(h1);if(e)return hN(JSON.parse(e));const t=JSON.parse(window.localStorage.getItem(lv)||"null");if(t&&typeof t.primaryId=="string"&&typeof t.secondaryId=="string"&&t.primaryId!==t.secondaryId){const r=Math.min(vN,Math.max(yN,typeof t.ratio=="number"?t.ratio:.5));return[{id:`split:${t.primaryId}`,sessionIds:[t.primaryId,t.secondaryId],layout:t.direction==="vertical"?"vertical":"horizontal",ratios:[r,1-r]}]}}catch{}return[]}function AN(e,t){const r=new Map(e.map(l=>[l.id,l])),n=new Map;t.forEach(l=>l.sessionIds.forEach(d=>n.set(d,l)));const a=new Set,c=[];for(const l of e){const d=n.get(l.id);if(!d){c.push({key:l.id,sessions:[l]});continue}if(a.has(d.id))continue;a.add(d.id);const p=d.sessionIds.flatMap(m=>{const x=r.get(m);return x?[x]:[]});p.length>=2&&c.push({key:d.id,sessions:p,workspace:d})}return c}function V2(e){const t=e.wrapperEl;if(t)try{t.getAnimations().forEach(r=>r.cancel())}catch{}}function wh(e,t){const r=wf(e,t);if(r===null)return;const n=e.wrapperEl;V2(e),n&&(n.style.transitionDuration="0ms");try{const a=e;a.setTransition?.(0),a.setTranslate?.(r),V2(e),n&&(n.style.transitionDuration="0ms",n.style.transform=`translate3d(${r}px, 0px, 0px)`)}catch{n&&(n.style.transitionDuration="0ms",n.style.transform=`translate3d(${r}px, 0px, 0px)`)}}function f1(e){try{const t=typeof e.getTranslate=="function"?e.getTranslate():e.translate;return typeof t=="number"&&Number.isFinite(t)?t:null}catch{return typeof e.translate=="number"&&Number.isFinite(e.translate)?e.translate:null}}function wf(e,t){const r=e.snapGrid,n=Array.isArray(r)?r[t]:void 0;return typeof n!="number"||!Number.isFinite(n)?null:-n}function TN(e,t){const r=f1(e),n=wf(e,t);return r!==null&&n!==null&&Math.abs(r-n)<=ov}function SN(e){const t=[],r=new Map,n=new Map,a=new Map;for(const c of e){const l=r.get(c.id)??[];if(l.push(c.id),r.set(c.id,l),c.sessionId){const d=n.get(c.sessionId)??[];d.push(c.id),n.set(c.sessionId,d)}if(c.mode==="tmux"&&c.tmuxSessionName){const d=a.get(c.tmuxSessionName)??[];d.push(c.id),a.set(c.tmuxSessionName,d)}}for(const[c,l]of r)l.length>1&&t.push({kind:"frontend",key:c,sessionIds:l});for(const[c,l]of n)l.length>1&&t.push({kind:"backend",key:c,sessionIds:l});for(const[c,l]of a)l.length>1&&t.push({kind:"tmux",key:c,sessionIds:l});return t}function cv(e){const t=new Map;for(const r of e)t.set(r.id,r);return Array.from(t.values())}function uv(e){return{id:e.sessionId,name:e.name,customName:e.customName===!0,sessionId:e.backendSessionId,mode:e.mode==="tmux"||e.mode==="shell"?e.mode:"shell",tmuxSessionName:e.tmuxSessionName??null}}function CN(e,t){const r=cv(e),n=r.findIndex(a=>a.id===t.id);if(n>=0){const a=[...r];return a[n]=t,a}return[...r,t]}function q2(e,t){const r=new Map(e.map(n=>[n.id,n]));return t.map(n=>{const a=r.get(n.sessionId);return{...uv(n),history:a?.history}})}function Y2(e,t){return e.length===0?null:t&&e.some(r=>r.sessionId===t)?t:e[0]?.sessionId??null}function Z2(e){if(!e||typeof e!="object")return"unknown";const t=e;if(typeof t.pointerType=="string"&&t.pointerType)return t.pointerType;if(typeof t.type=="string"){if(t.type.startsWith("touch"))return"touch";if(t.type.startsWith("mouse"))return"mouse";if(t.type.startsWith("pointer"))return"pointer"}return"unknown"}function K2(e){const t=new Map;for(const[r,n]of e)t.set(r,n.cwd??null);return t}function _N(e,t){if(e.size!==t.size)return!1;for(const[r,n]of t)if(e.get(r)!==n)return!1;return!0}function kN(e){const t="".toLowerCase().replace(/[^a-z0-9_-]/g,"").slice(0,12);if(t)return`wt-${t}`;const r=Date.now().toString(36),n=Math.random().toString(36).slice(2,8);return`wt-${r}${n}`}const LN=({terminalSettings:e=X1(),colorTheme:t="dark",toolbarPresets:r=[],showDebug:n,terminalFocusAvailable:a=!0,defaultSessionMode:c="shell",defaultTmuxSessionName:l="",connectionPrioritySessionId:d=null,connectionPriorityReady:p=!0,desktopRightSidebarEnabled:m=!1,onToggleRightSidebar:x,desktopFloatingTitle:y=!1,desktopPinnedLeftSidebarWidth:w=0,desktopViewportWidth:v=0,onStatusChange:S,onSessionDataUpdate:L,onInitialViewportReady:E,onInitialRecoveryRequired:R})=>{const{t:B}=Ur(),z=b.useMemo(()=>Fu("session"),[]),O=b.useMemo(()=>Fu("terminal"),[]),[$,V]=b.useState([]),[Z,le]=b.useState(null),be=b.useRef(0),pe=b.useRef(0),ee=Kn(W=>W.activePaneId);b.useEffect(()=>{Kn.getState().setActivePane(Z)},[Z]);const[_e,ze]=b.useState(null),[Y,ce]=b.useState(!0),[qe,we]=b.useState({token:0,reason:"visibility",forceForegroundReconnect:!1}),[ye,Le]=b.useState(()=>new Set),[Be,ne]=b.useState(()=>({token:0,completed:new Set})),[Fe,ke]=b.useState(0),[Ee,Pe]=b.useState(()=>new Set),[Ne,oe]=b.useState(()=>new Set),We=b.useRef(new Map),[nt,gt]=b.useState(()=>new Set),ue=b.useRef(!1),Ze=b.useRef(null),at=b.useRef({}),[Ie,Ge]=b.useState(null),[Ce,H]=b.useState(()=>wN()),[ae,Ae]=b.useState(!1),Ye=b.useCallback(W=>{be.current+=1,Ae(W)},[]),et=b.useRef(null),St=b.useRef(ae);St.current=ae,Gc(et,ae&&!!Z,()=>Ye(!1));const[Gt,Qt]=b.useState(null),[wt,zt]=b.useState(null),Vt=b.useRef(new Set),[Kt,Ot]=b.useState(null),[It,xe]=b.useState(null),[Ve,ht]=b.useState(!1),[q,ut]=b.useState(()=>nm().mobile),[qt,tt]=b.useState(()=>nm().landscape),[De,nr]=b.useState(null),[Ke,_t]=b.useState(null),$t=b.useRef(a),yt=b.useRef(!1),xt=b.useRef(!1),Rt=b.useRef(null),Ct=b.useRef(null),fr=b.useRef(q),Yt=b.useRef(null),Sr=b.useCallback(W=>{W!==Yt.current&&(be.current+=1),Yt.current=W,le(W)},[]);b.useEffect(()=>Wt.subscribe((W,N)=>{(W.rightOpen!==N.rightOpen||W.rightTab!==N.rightTab)&&(be.current+=1)}),[]);const pn=b.useRef(0),dr=b.useRef([]),me=b.useRef(0),Gr=b.useRef(null),ot=b.useRef(!1),pt=b.useRef(!0),ir=b.useRef(null),Mn=b.useRef(""),Xr=b.useRef(0);b.useEffect(()=>{if(typeof window>"u")return;const W=()=>{const N=nm();fr.current=N.mobile,ut(N.mobile),tt(N.landscape)};return W(),window.addEventListener("resize",W),()=>window.removeEventListener("resize",W)},[]);const{sessions:je,inventory:st,activeSessionId:bt,isLoading:Br,openSession:Vr,setActiveSession:Cr,removeSession:qr,renameSession:mn,resetSessionCustomName:on,reorderSessions:zr,restoreSessions:un}=T8(),Er=st?.tmuxRecovery??null;b.useEffect(()=>{Er&&R?.()},[Er,R]),b.useEffect(()=>{xe(null),Ot(null)},[Er?.id]);const re=b.useCallback(async()=>{Ot("restore"),xe(null);try{const W=await S8();await un(),W.failed>0&&xe(B("tab.tmuxRecoveryPartial",{restored:W.restored,failed:W.failed}))}catch{xe(B("tab.tmuxRecoveryFailed"))}finally{Ot(null)}},[un,B]),mt=b.useCallback(async()=>{Ot("dismiss"),xe(null);try{await C8(),await un()}catch{xe(B("tab.tmuxRecoveryDismissFailed"))}finally{Ot(null)}},[un,B]),Mt=Wt(W=>W.groupByFolder),rr=df(W=>W.collaborationGroups),Ar=Wt(W=>W.leftOpen||W.rightOpen),Fr=Wt(W=>W.rightSidebarWidthContextKey),Xt=Wt(W=>W.rightSidebarWidth),Zr=Wt(W=>W.rightPinned),[Jt,Pr]=b.useState(()=>K2(Yr.getState().sessions));b.useEffect(()=>Yr.subscribe(W=>{const N=K2(W.sessions);Pr(U=>_N(U,N)?U:N)}),[]);const{arranged:Hr}=b.useMemo(()=>cf($,W=>Jt.get(W.id)??null,Mt,"",Ce,rr),[$,Jt,Mt,Ce,rr]),ps=b.useRef(Hr);ps.current=Hr;const Mr=b.useMemo(()=>AN(Hr,Ce),[Hr,Ce]),jn=b.useRef(Mr);jn.current=Mr;const Tr=b.useMemo(()=>A0(Ce,Z),[Z,Ce]),Jr=b.useMemo(()=>{const W=Mr.find(N=>N.sessions.some(U=>U.id===Z));return new Set(W?.sessions.map(N=>N.id)??[])},[Z,Mr]),ln=b.useMemo(()=>{const W=new Map;if(!m||v<=0)return W;for(const N of Mr){const U=N.sessions[0];if(!U)continue;const K=_8(U.id,Jt.get(U.id)??null,N.workspace?.id??null);if(!(K===Fr?Zr:k8(U.id,Jt.get(U.id)??null,N.workspace?.id??null)))continue;const Qe=K===Fr?Xt:L8(U.id,Jt.get(U.id)??null,N.workspace?.id??null),ve=Oh(Qe,v,w);W.set(N.key,ve+Ay)}return W},[Jt,w,m,Zr,Fr,Xt,v,Mr]),Qr=b.useMemo(()=>em($.map(W=>({id:W.id,backendSessionId:W.sessionId})),d),[d,$]),ks=b.useMemo(()=>Y2(je,bt),[bt,je]),Dr=yh({prioritySessionId:Qr,activeSessionId:_e??Z,persistedActiveSessionId:ks,firstSessionId:$[0]?.id??null}),en=b.useMemo(()=>qE(Mr.flatMap(W=>W.sessions.map(N=>N.id)),Jr),[Jr,Mr]),xn=Dr!==null&&ye.has(Dr),X=b.useMemo(()=>{const W=new Set(Jr);return _e&&W.add(_e),!W.size&&Dr&&W.add(Dr),W},[Jr,_e,Dr]),He=Be.token===qe.token&&HE(X,Be.completed),Nt=He||Fe===qe.token?qe.token:-1;b.useEffect(()=>{if(!qe.token||He)return;const W=window.setTimeout(()=>ke(qe.token),ME);return()=>window.clearTimeout(W)},[qe.token,He]);const Et=b.useCallback((W,N)=>{Le(U=>{if(U.has(W)===N)return U;const fe=new Set(U);return N?fe.add(W):fe.delete(W),fe})},[]),tr=b.useCallback(W=>{const N=pn.current;ne(K=>{if(K.token===N&&K.completed.has(W))return K;const fe=new Set(K.token===N?K.completed:[]);return fe.add(W),{token:N,completed:fe}});const U=Qr??_e??Yt.current;W===U&&Mu("foreground-stream-connected")},[_e,Qr]),jr=b.useCallback((W,N)=>{Pe(U=>{if(U.has(W)===N)return U;const K=new Set(U);return N?K.add(W):K.delete(W),K})},[]),cr=b.useCallback((W,N)=>{oe(U=>{if(U.has(W)===N)return U;const K=new Set(U);return N?K.add(W):K.delete(W),K})},[]);b.useEffect(()=>{for(const[W,N]of We.current){const U=$.find(K=>K.id===W);if(!U||U.sessionId!==N.backendSessionId){We.current.delete(W);continue}!ye.has(W)||!Ee.has(W)||!Ne.has(W)||(We.current.delete(W),vy(N.backendSessionId,`${N.command}\r`).catch(K=>{console.error("[Session] Failed to send startup command:",K)}))}},[$,ye,Ee,Ne]);const Cn=Dr!==null&&Ee.has(Dr),Ls=Dr!==null&&Ne.has(Dr);b.useEffect(()=>{Cn&&Mu("foreground-viewport-ready")},[Cn]),b.useEffect(()=>{Ls&&Mu("foreground-content-ready")},[Ls]),b.useEffect(()=>{if(!E)return;if(!Y&&$.length===0){E();return}if(!Cn||!xn||!Ls)return;const W=[...Jr].every(Qe=>Ee.has(Qe)&&ye.has(Qe)&&Ne.has(Qe));let N=0,U=0;const K=()=>{N=requestAnimationFrame(()=>{U=requestAnimationFrame(()=>{Mu("initial-viewport-presented"),E()})})};W&&K();const fe=W?void 0:window.setTimeout(K,8e3);return()=>{cancelAnimationFrame(N),cancelAnimationFrame(U),clearTimeout(fe)}},[xn,Ls,Cn,Y,E,$.length,Jr,Ee,ye,Ne]);const Xn=b.useMemo(()=>q?BE({slides:Mr.map(W=>W.sessions.map(N=>N.id)),visibleSessionIds:Jr,foregroundSessionId:Dr}):nt,[q,Mr,Jr,Dr,nt]);b.useEffect(()=>{if(q||Jr.size===0)return;const W=new Set(Jr),N=Mr.findIndex(U=>U.sessions.some(K=>Jr.has(K.id)));for(let U=-2;U<=2;U+=1)U!==0&&Mr[N+U]?.sessions.forEach(K=>W.add(K.id));gt(U=>{let K=!1;const fe=new Set(U);for(const Qe of W)fe.has(Qe)||(fe.add(Qe),K=!0);return K?fe:U})},[q,Jr,Mr]);const cn=mC(Xn);b.useEffect(()=>{if(!_e)return;if(!$.some(N=>N.id===_e)){ze(null);return}if(!Ee.has(_e)||!ye.has(_e)||!Ne.has(_e))return;const W=window.setTimeout(()=>{ze(N=>N===_e?null:N),$t.current&&!fr.current&&Ge({sessionId:_e,token:Date.now()})},80);return()=>window.clearTimeout(W)},[Ne,_e,ye,$,Ee]),b.useEffect(()=>{typeof window>"u"||(Ce.length>0?(window.localStorage.setItem(h1,JSON.stringify(Ce)),window.localStorage.removeItem(lv)):window.localStorage.removeItem(h1))},[Ce]),b.useEffect(()=>{Br||Y||Ce.length===0||H(W=>fN(W,$.map(N=>N.id)))},[Br,Y,$,Ce.length]),b.useEffect(()=>{if(!Gt)return;const W=window.setTimeout(()=>Qt(null),3200);return()=>window.clearTimeout(W)},[Gt]),Yt.current=Z,pn.current=qe.token,dr.current=$,Gr.current=bt,ot.current=Br,pt.current=Y,$t.current=a;const dn=b.useCallback((W=Ze.current)=>{const N=me.current,U=typeof window<"u"?window.visualViewport:null,K=W?f1(W):null,fe=W?wf(W,N):null;return{sessionsLength:dr.current.length,workspaceSlidesLength:jn.current.length,sessionIds:dr.current.map(Qe=>Qe.id),activeSessionId:Yt.current,activeSessionIndex:N,persistedActiveId:Gr.current,isLoading:ot.current,isRestoring:pt.current,activeIndex:W?.activeIndex??null,previousIndex:W?.previousIndex??null,animating:W?.animating??null,allowTouchMove:W?.allowTouchMove??null,width:W?.width??null,translate:K,targetTranslate:fe,translateDelta:K!==null&&fe!==null?K-fe:null,snapGridLength:W?.snapGrid?.length??null,targetSnap:W?.snapGrid?.[N]??null,visualViewport:U?{width:Math.round(U.width),height:Math.round(U.height),offsetTop:Math.round(U.offsetTop)}:null}},[]),_r=b.useCallback((W,N)=>{z(W,{...dn(),...N})},[z,dn]);b.useEffect(()=>{Br||Y||Z!==bt&&Cr(Z)},[Z,Br,Y,bt,Cr]);const Or=b.useMemo(()=>{if(Hr.length===0||!Z)return 0;const W=Mr.findIndex(N=>N.sessions.some(U=>U.id===Z));return W>=0?W:0},[Mr,Z]);me.current=Or;const Gn=b.useCallback(()=>{Rt.current&&(clearTimeout(Rt.current),Rt.current=null)},[]),Vn=b.useCallback(W=>{Gn(),Rt.current=setTimeout(()=>{Rt.current=null,yt.current=!1,_r("[swiper:touch-guard-clear]",{reason:W})},bN)},[Gn,_r]),gn=b.useCallback((W,N={})=>{const U=Ze.current,K=me.current,fe=jn.current;if(!U||fe.length===0||K<0||K>=fe.length)return;if(yt.current){_r("[swiper:sync-skip-touch]",{reason:W});return}if(U.animating){_r("[swiper:sync-skip-animating]",{reason:W});return}const Qe=f1(U),ve=wf(U,K),lt=Qe!==null&&ve!==null&&Math.abs(Qe-ve)<=ov,vt=U.activeIndex===K;if(_r("[swiper:sync-check]",{reason:W,activeIndexAligned:vt,translateAligned:lt,immediate:N.immediate===!0}),!(vt&<)){if(vt){wh(U,K),_r("[swiper:sync-forced-active]",{reason:W,translateAligned:lt,immediate:N.immediate===!0});return}N.immediate?(wh(U,K),U.slideTo(K,0,!1),wh(U,K)):U.slideTo(K,d1,!1),_r("[swiper:sync-applied]",{reason:W,activeIndexAligned:vt,translateAligned:lt,immediate:N.immediate===!0})}},[_r]);b.useEffect(()=>{const W=N=>{const U=N;Ze.current&&(Ze.current.allowTouchMove=!U.detail.locked),_r("[swiper:gesture-lock]",{locked:U.detail.locked})};return document.addEventListener("termdock:gesture-lock",W),()=>document.removeEventListener("termdock:gesture-lock",W)},[_r]),b.useEffect(()=>{if($.length===0){Z!==null&&Sr(null);return}if(!Z){if(!p)return;Sr(yh({prioritySessionId:Qr,activeSessionId:null,persistedActiveSessionId:ks,firstSessionId:$[0]?.id??null}));return}$.some(N=>N.id===Z)||Sr($[0].id)},[$,Z,p,Qr,ks]);const Jn=b.useCallback((W,N)=>{if(N&&Date.now()<Xr.current){at.current[W]=!1;return}at.current[W]=N,_t(U=>N?W:U===W?null:U)},[]),kr=b.useCallback(W=>{if(!yt.current&&W.activeIndex!==me.current){_r("[swiper:slide-change-ignored-layout]",{instanceActiveIndex:W.activeIndex,expectedActiveIndex:me.current}),requestAnimationFrame(()=>gn("ignored-layout-slide-change",{immediate:!0}));return}const N=jn.current[W.activeIndex],U=N?.sessions.some(Qe=>Qe.id===Z)?Z:N?.sessions[0]?.id;if(_r("[swiper:slide-change]",{nextSessionId:U??null,instanceActiveIndex:W.activeIndex}),!U||U===Z)return;const K=!!Z&&at.current[Z]===!0,fe=$t.current&&(!fr.current||K);if(Ct.current=U,Sr(U),fe){Ge({sessionId:U,token:Date.now()});return}Ge(null)},[$,Z,_r,gn]);b.useLayoutEffect(()=>{if(Ct.current===Z){_r("[swiper:sync-skip-swiper-driven]",{activeSessionId:Z}),Ct.current=null;return}gn("active-session-index",{immediate:!0})},[Z,Or,$.length,gn,_r]),b.useEffect(()=>{const W=Ze.current;if(!W)return;const N=Mr.length>1&&!Ar&&!ae;W.allowTouchMove!==N&&(W.allowTouchMove=N,_r("[swiper:allow-touch-sync]",{nextAllow:N,sidebarOverlayOpen:Ar}))},[Mr.length,_r,Ar,ae]);const Lr=b.useCallback(W=>{const N=Ze.current;if(!N)return;const U=N.el;if(_r("[swiper:layout-before]",{reason:W,scrollLeft:U?.scrollLeft??null}),U&&(U.scrollLeft=0),N.updateSize(),N.updateSlides(),N.updateProgress(),N.updateSlidesClasses(),U&&(U.scrollLeft=0),_r("[swiper:layout-after]",{reason:W,scrollLeft:U?.scrollLeft??null}),yt.current||N.animating){_r("[swiper:layout-skip-sync-motion]",{reason:W});return}gn(`layout:${W}`,{immediate:!0}),requestAnimationFrame(()=>{const K=Ze.current;K&&(yt.current||K.animating||wh(K,me.current))})},[_r,gn]);b.useEffect(()=>()=>Gn(),[Gn]);const pr=Mr.map(W=>W.key).join("\0");b.useEffect(()=>{requestAnimationFrame(()=>Lr("group-change"))},[Mt,pr,Lr]),b.useEffect(()=>{let W=null,N="mount";const U=lt=>{N=lt,W===null&&(W=requestAnimationFrame(()=>{W=null,Lr(`viewport-change:${N}`)}))},K=()=>U("window-resize"),fe=()=>U("visual-viewport-resize"),Qe=()=>U("visual-viewport-scroll"),ve=lt=>{U(`measured:${lt.detail?.source??"unknown"}`)};return window.addEventListener("resize",K),window.visualViewport?.addEventListener("resize",fe),window.visualViewport?.addEventListener("scroll",Qe),document.addEventListener(ix,ve),U("mount"),()=>{window.removeEventListener("resize",K),window.visualViewport?.removeEventListener("resize",fe),window.visualViewport?.removeEventListener("scroll",Qe),document.removeEventListener(ix,ve),W!==null&&cancelAnimationFrame(W)}},[Lr]),b.useEffect(()=>{if(typeof document>"u")return;let W=null,N=null;const U=vt=>{if(vt!=="online"&&document.hidden)return;const br=performance.now();if(!WE(N,br))return;N=br;const Lt=vt==="bfcache"||vt==="online"?vt:"visibility",rn=GE();Ap(),ka("info","PWA_RESUME scheduled",{source:vt,forceForegroundReconnect:rn,activeSessionId:Yt.current}),we(yn=>({token:yn.token+1,reason:Lt,forceForegroundReconnect:rn})),requestAnimationFrame(()=>Lr(`resume:${vt}:raf`)),W&&clearTimeout(W),W=setTimeout(()=>{W=null,Lr(`resume:${vt}:settled`)},320)},K=()=>{if(document.hidden){Ap();return}U("visibility")},fe=()=>{Ap()},Qe=vt=>{U(vt.persisted?"bfcache":"pageshow")},ve=()=>U("online"),lt=()=>U("focus");return document.addEventListener("visibilitychange",K),window.addEventListener("pagehide",fe),window.addEventListener("pageshow",Qe),window.addEventListener("online",ve),window.addEventListener("focus",lt),()=>{document.removeEventListener("visibilitychange",K),window.removeEventListener("pagehide",fe),window.removeEventListener("pageshow",Qe),window.removeEventListener("online",ve),window.removeEventListener("focus",lt),W&&clearTimeout(W)}},[Lr]),b.useLayoutEffect(()=>{if(!UE(Y))return;const W=SN($),N=JSON.stringify(W);W.length>0&&N!==Mn.current?(Mn.current=N,console.warn("[session-invariant] duplicate mapping detected",W)):W.length===0&&Mn.current&&(Mn.current=""),L?.({sessions:$.map(U=>({id:U.id,name:U.name,customName:U.customName,mode:U.mode,tmuxSessionName:U.tmuxSessionName})),activeSessionId:Z,splitWorkspaces:Ce.map(({id:U,name:K,sessionIds:fe,layout:Qe})=>({id:U,...K?{name:K}:{},sessionIds:fe,layout:Qe}))})},[$,Z,Ce,L,Y]),b.useEffect(()=>{if(Br||ue.current)return;ue.current=!0;const W=em(je.map(Qe=>({id:Qe.sessionId,backendSessionId:Qe.backendSessionId??null})),d),N=Y2(je,bt),U=yh({prioritySessionId:p?W:null,activeSessionId:null,persistedActiveSessionId:N,firstSessionId:je[0]?.sessionId??null}),K=cv(je.map(uv));if(z("[Session] Restoring",K.length,"persisted sessions (one-shot)"),_r("[swiper:restore-start]",{persistedSessionIds:je.map(Qe=>Qe.sessionId),nextActiveSessionId:U}),K.length>0){const Qe=Yr.getState();K.forEach(lt=>{lt.sessionId&&Qe.setTerminalSession(lt.id,{sessionId:lt.sessionId,cols:80,rows:24,mode:lt.mode,tmuxSessionName:lt.tmuxSessionName,history:lt.history})}),je.forEach(lt=>{lt.agent!==void 0&&Qe.setSessionAgentIdentity(lt.sessionId,lt.agent),lt.activeProgram!=null&&Qe.setSessionActiveProgram(lt.sessionId,lt.activeProgram),lt.cwd!=null&&Qe.setSessionCwd(lt.sessionId,lt.cwd),lt.shellTitle!=null&&Qe.setSessionShellTitle(lt.sessionId,lt.shellTitle)}),V(K);const ve=U||K[0]?.id||null;Sr(ve),_r("[swiper:restore-complete]",{restoredSessionIds:K.map(lt=>lt.id),nextActiveSessionId:ve})}(async()=>(K.length===0&&await ir.current?.({createIfEmpty:!0}),ce(!1),requestAnimationFrame(()=>gn("restore-finished",{immediate:!0}))))()},[Br,je,bt,z,_r,gn,p,d]),b.useEffect(()=>{if(!p||Y||$.length===0)return;const W=em($.map(U=>({id:U.id,backendSessionId:U.sessionId})),d),N=yh({prioritySessionId:W,activeSessionId:Yt.current,persistedActiveSessionId:ks,firstSessionId:$[0]?.id??null});N&&N!==Yt.current&&Sr(N)},[p,d,Y,ks,$]);const ns=b.useRef([]),Un=b.useRef(!1);Yt.current=Z,b.useEffect(()=>{if(Y)return;const W=ns.current,N=je,U=new Map(W.map(Lt=>[Lt.sessionId,Lt])),K=Yr.getState();for(const Lt of N){const rn=U.get(Lt.sessionId),yn=Yr.getState().sessions.get(Lt.sessionId);Lt.agent!==void 0&&JSON.stringify(Lt.agent)!==JSON.stringify(yn?.agent)&&(yn?.agent==null||JSON.stringify(Lt.agent)!==JSON.stringify(rn?.agent))&&K.setSessionAgentIdentity(Lt.sessionId,Lt.agent),Lt.activeProgram!=null&&Lt.activeProgram!==yn?.activeProgram&&(yn?.activeProgram==null||Lt.activeProgram!==rn?.activeProgram)&&K.setSessionActiveProgram(Lt.sessionId,Lt.activeProgram),Lt.cwd!=null&&Lt.cwd!==yn?.cwd&&(yn?.cwd==null||Lt.cwd!==rn?.cwd)&&K.setSessionCwd(Lt.sessionId,Lt.cwd),Lt.shellTitle!=null&&Lt.shellTitle!==yn?.shellTitle&&(yn?.shellTitle==null||Lt.shellTitle!==rn?.shellTitle)&&K.setSessionShellTitle(Lt.sessionId,Lt.shellTitle)}if(!Un.current){V(Lt=>q2(Lt,N)),ns.current=N,Un.current=!0;return}const fe=new Set(W.map(Lt=>Lt.sessionId)),Qe=new Set(N.map(Lt=>Lt.sessionId)),ve=new Map(W.map(Lt=>[Lt.sessionId,Lt.name]));ns.current=N,V(Lt=>{const rn=q2(Lt,N);return(!Yt.current||!rn.some(yn=>yn.id===Yt.current))&&Sr(rn[0]?.id??null),rn});const lt=N.filter(Lt=>!fe.has(Lt.sessionId)),vt=[...fe].filter(Lt=>!Qe.has(Lt)),br=N.filter(Lt=>fe.has(Lt.sessionId)&&ve.get(Lt.sessionId)!==Lt.name);(lt.length>0||vt.length>0||br.length>0)&&z("[Session] Synced persisted sessions:",{newSessionIds:lt.map(Lt=>Lt.sessionId),removedSessionIds:vt,renamedSessionIds:br.map(Lt=>Lt.sessionId),currentSessionIds:N.map(Lt=>Lt.sessionId)});for(const Lt of N){if(!Lt.backendSessionId)continue;Yr.getState().setTerminalSession(Lt.sessionId,{sessionId:Lt.backendSessionId,cols:80,rows:24,mode:Lt.mode,tmuxSessionName:Lt.tmuxSessionName})}},[je,Y,z]);const En=b.useCallback(async W=>{const N=++pe.current,U=be.current,K=()=>N===pe.current&&U===be.current&&(W?.shouldActivate?.()??!0);try{const fe=Wt.getState(),Qe=Z?{rightOpen:fe.rightOpen,rightPinned:fe.rightPinned,rightSidebarWidth:fe.rightSidebarWidth,rightTab:fe.rightTab}:null,ve=W?.mode==="tmux"||W?.mode==="shell"?W.mode:c,lt=(W?.tmuxSessionName||"").trim(),vt=l.trim(),br=ve==="tmux"?lt||vt||kN():null,Lt=typeof W?.cwd=="string"?W.cwd:null,rn=Z?Yr.getState().sessions.get(Z)?.cwd??null:null,yn=typeof Lt=="string"&&Lt.trim().length>0?Lt:typeof rn=="string"&&rn.trim().length>0?rn:void 0,hn=await Vr({preferredFrontendSessionId:W?.preferredFrontendSessionId,requireExisting:W?.requireExisting===!0,mode:ve,tmuxSessionName:br,cwd:yn,termType:"xterm-256color",createIfEmpty:W?.createIfEmpty===!0},{shouldActivate:K});if(hn.discarded)return W?.onResult?.({ok:!1,error:"unknown"}),null;const Dn=hn.session,zn=hn.terminalSession;!hn.reused&&Qe&&Wt.getState().initializeRightSidebarForSession(Dn.sessionId,zn.cwd??yn??null,Qe);const hr={id:Dn.sessionId,name:Dn.name,customName:Dn.customName===!0,sessionId:zn.sessionId,mode:zn.mode??Dn.mode,tmuxSessionName:zn.tmuxSessionName??Dn.tmuxSessionName},jt=W?.command?.trim();return jt&&We.current.set(hr.id,{backendSessionId:zn.sessionId,command:jt}),V(qn=>CN(qn,hr)),K()&&Sr(hr.id),Yr.getState().setTerminalSession(hr.id,{sessionId:zn.sessionId,cols:80,rows:24,mode:hr.mode,tmuxSessionName:hr.tmuxSessionName,activeProgram:zn.activeProgram,activeProgramRaw:zn.activeProgramRaw,activeProgramSource:zn.activeProgramSource,cwd:zn.cwd}),z("[Session] Inventory opened session:",{frontendSessionId:hr.id,backendSessionId:zn.sessionId,reused:hn.reused,mode:hr.mode,tmuxSessionName:hr.tmuxSessionName}),W?.onResult?.({ok:!0,sessionId:hr.id}),hr.id}catch(fe){return console.error("[Session] Failed to create new session:",fe),W?.onResult?.({ok:!1,error:nC(fe)}),null}},[c,l,Z,Vr,z]);ir.current=En;const kn=b.useCallback((W,N={})=>{be.current+=1,Kn.getState().setActivePane(W);const U=Yt.current,K=!!U&&at.current[U]===!0;if(Sr(W),fr.current&&N.preserveMobileKeyboard===!1){Xr.current=Date.now()+600,U&&(at.current[U]=!1),_t(null),Ge(null);const fe=document.activeElement;fe instanceof HTMLTextAreaElement&&fe.closest(".terminal-viewport-container")&&fe.blur();return}K&&fr.current&&_t(W),$t.current&&(!fr.current||K)&&Ge({sessionId:W,token:Date.now()})},[]),ss=b.useCallback(W=>{Sr(W),Ye(!0),Qt(null)},[]),Wr=b.useCallback(W=>{const N=Yt.current;!N||N===W||(H(U=>rm(U,N,W)),Ye(!1),kn(N,{preserveMobileKeyboard:!1}))},[kn]),tn=b.useCallback(async()=>{const W=Yt.current;if(!W||Ve)return;const N=be.current;ht(!0);const U=Yr.getState().sessions.get(W)?.cwd??void 0,K=await En({cwd:U||void 0,mode:c,shouldActivate:()=>!1});if(ht(!1),!K){Qt(B("common.error"));return}!St.current||N!==be.current||!dr.current.some(fe=>fe.id===W)||(H(fe=>rm(fe,W,K)),Ye(!1),kn(W,{preserveMobileKeyboard:!1}))},[kn,c,En,Ve,B]),G=b.useCallback(W=>{H(N=>mN(N,W)),W&&kn(W,{preserveMobileKeyboard:!1})},[kn]),Me=b.useCallback(W=>{H(N=>pN(N,W)),kn(W,{preserveMobileKeyboard:!1})},[kn]),$e=b.useCallback(W=>{if($.find(U=>U.id===W)){if(be.current+=1,Kn.getState().setActivePane(W),W===Yt.current)return;if(Sr(W),!OE({isMobile:fr.current,viewportReady:Ee.has(W),streamReady:ye.has(W),contentReady:Ne.has(W)})){ze(null),$t.current&&Ge({sessionId:W,token:Date.now()}),z("[Session] Switched to session:",W);return}gt(K=>{if(K.has(W))return K;const fe=new Set(K);return fe.add(W),fe}),ze(W),z("[Session] Switched to session:",W)}},[Ne,z,ye,$,Ee]),Je=b.useCallback((W,N)=>{N.trim()&&(V(U=>U.map(K=>K.id===W?{...K,name:N.trim(),customName:!0}:K)),mn(W,N.trim()))},[mn]),it=b.useCallback(W=>{V(N=>N.map(U=>U.id===W?{...U,customName:!1}:U)),on(W)},[on]),Tt=b.useCallback(W=>{V(N=>{const U=new Map(N.map(ve=>[ve.id,ve])),K=W.map(ve=>U.get(ve)).filter(ve=>ve!==void 0),fe=new Set(W),Qe=N.filter(ve=>!fe.has(ve.id));return[...K,...Qe]}),zr(W),z("[Session] Reordered sessions:",W),requestAnimationFrame(()=>{Ze.current?.update()})},[zr,z]),kt=b.useCallback(async W=>{const N=typeof W=="string"?W:W.sessionId,U=typeof W=="string"?"auto":W.closeMode??"auto",K=$.find(lt=>lt.id===N);if(!K||Vt.current.has(N))return;Vt.current.add(N),be.current+=1;const fe=ax(Hr,N,lt=>lt.id);try{U==="destroy"&&K.mode==="tmux"&&K.tmuxSessionName?(await Ty(K.tmuxSessionName),z("[Session] Destroyed tmux session:",{frontendSessionId:K.id,tmuxSessionName:K.tmuxSessionName})):K.sessionId&&(await yy(K.sessionId),z("[Session] Closed backend terminal:",K.sessionId))}catch(lt){console.error("[Session] Failed to close backend terminal:",lt),zt({sessionId:N,closeMode:U});return}finally{Vt.current.delete(N)}zt(lt=>lt?.sessionId===N?null:lt);const ve=dr.current.filter(lt=>lt.id!==N).some(lt=>lt.id===fe)?fe:ax(dr.current,N,lt=>lt.id);Yt.current===N&&Sr(ve),V(lt=>lt.filter(vt=>vt.id!==N)),qr(N,ve),delete at.current[N],z("[Session] Closed session:",{sessionId:N,closeMode:U})},[$,Hr,qr,z]),Dt=b.useCallback(W=>{if(!W)return;const N=$.filter(U=>U.sessionId===W);if(N.length!==0){N.length>1&&console.warn("[session-invariant] backend matched multiple frontend sessions during cleanup",{backendSessionId:W,frontendSessionIds:N.map(U=>U.id)}),V(U=>{const K=U.filter(fe=>fe.sessionId!==W);return K.length!==U.length&&!K.some(Qe=>Qe.id===Z)&&Sr(K.length>0?K[0].id:null),K});for(const U of N)qr(U.id),delete at.current[U.id];z("[Session] Backend gone, dropped local session(s):",N.map(U=>U.id))}},[$,Z,qr,z]);b.useEffect(()=>{const W=hr=>{En(hr.detail)},N=hr=>{$e(hr.detail)},U=()=>{const hr=Yt.current;!hr||fr.current||Ge({sessionId:hr,token:Date.now()})},K=hr=>{const jt=hr;jt.detail&&ss(jt.detail)},fe=hr=>{const jt=hr.detail;G(jt??Yt.current??void 0)},Qe=hr=>{const jt=hr.detail;jt&&Me(jt)},ve=hr=>{const jt=hr.detail,Bn=typeof jt=="string"?jt:jt?.layout,qn=typeof jt=="string"?Yt.current:jt?.sessionId;Bn!=="horizontal"&&Bn!=="vertical"&&Bn!=="grid"||H(Wa=>Wa.map(Qn=>Qn.sessionIds.includes(qn??"")?{...Qn,layout:Bn}:Qn))},lt=hr=>{const Bn=hr.detail?.direction;if(Bn!=="prev"&&Bn!=="next")return;const qn=ps.current;if(qn.length<=1)return;const Wa=Yt.current,Qn=Wa?qn.findIndex(Ga=>Ga.id===Wa):-1,da=((Qn>=0?Qn:0)+(Bn==="next"?1:-1)+qn.length)%qn.length,bs=qn[da]?.id;bs&&bs!==Wa&&$e(bs)},vt=hr=>{kt(hr.detail)},br=hr=>{Dt(hr.detail)},Lt=hr=>{const jt=hr;!jt.detail?.sessionId||!jt.detail?.name||Je(jt.detail.sessionId,jt.detail.name)},rn=hr=>{const jt=hr;jt.detail?.sessionId&&it(jt.detail.sessionId)},yn=hr=>{const jt=hr;jt.detail?.sessionIds&&Tt(jt.detail.sessionIds)},hn=hr=>{const jt=hr.detail;!jt?.workspaceId||!Array.isArray(jt.sessionIds)||H(Bn=>gN(Bn,jt.workspaceId,jt.sessionIds))},Dn=hr=>{const jt=hr.detail;!jt?.workspaceId||typeof jt.name!="string"||H(Bn=>xN(Bn,jt.workspaceId,jt.name))},zn=hr=>{const jt=hr.detail;!jt?.primaryId||!jt.secondaryId||jt.primaryId===jt.secondaryId||(H(Bn=>rm(Bn,jt.primaryId,jt.secondaryId)),kn(jt.primaryId,{preserveMobileKeyboard:!1}))};return window.addEventListener("new-terminal-session",W),window.addEventListener("switch-terminal-session",N),window.addEventListener("focus-active-terminal-session",U),window.addEventListener("open-terminal-split-chooser",K),window.addEventListener("close-terminal-split",fe),window.addEventListener("remove-terminal-split-pane",Qe),window.addEventListener("set-terminal-split-direction",ve),window.addEventListener("cycle-terminal-session",lt),window.addEventListener("close-terminal-session",vt),window.addEventListener("close-terminal-session-by-backend",br),window.addEventListener("rename-terminal-session",Lt),window.addEventListener("reset-terminal-session-name",rn),window.addEventListener("reorder-terminal-session",yn),window.addEventListener("reorder-terminal-split-workspace",hn),window.addEventListener("rename-terminal-split-workspace",Dn),window.addEventListener("combine-terminal-split-sessions",zn),()=>{window.removeEventListener("new-terminal-session",W),window.removeEventListener("switch-terminal-session",N),window.removeEventListener("focus-active-terminal-session",U),window.removeEventListener("open-terminal-split-chooser",K),window.removeEventListener("close-terminal-split",fe),window.removeEventListener("remove-terminal-split-pane",Qe),window.removeEventListener("set-terminal-split-direction",ve),window.removeEventListener("cycle-terminal-session",lt),window.removeEventListener("close-terminal-session",vt),window.removeEventListener("close-terminal-session-by-backend",br),window.removeEventListener("rename-terminal-session",Lt),window.removeEventListener("reset-terminal-session-name",rn),window.removeEventListener("reorder-terminal-session",yn),window.removeEventListener("reorder-terminal-split-workspace",hn),window.removeEventListener("rename-terminal-split-workspace",Dn),window.removeEventListener("combine-terminal-split-sessions",zn)}},[kn,En,$e,ss,G,Me,kt,Dt,Je,it,Tt]),b.useEffect(()=>{if(!Tr||q)return;const W=N=>{if(!gC(N,B1())||!(N.ctrlKey||N.metaKey)||!N.shiftKey)return;if(Tr.layout==="horizontal"?N.key==="ArrowLeft"||N.key==="ArrowRight":Tr.layout==="vertical"?N.key==="ArrowUp"||N.key==="ArrowDown":N.key.startsWith("Arrow")){N.preventDefault(),N.stopPropagation();const K=Tr.sessionIds.indexOf(Yt.current??""),fe=N.key==="ArrowLeft"||N.key==="ArrowUp"?-1:1,Qe=(Math.max(0,K)+fe+Tr.sessionIds.length)%Tr.sessionIds.length,ve=Tr.sessionIds[Qe];if(!ve)return;kn(ve);return}N.key==="Backspace"&&(N.preventDefault(),N.stopPropagation(),G(Yt.current??void 0))};return window.addEventListener("keydown",W,!0),()=>window.removeEventListener("keydown",W,!0)},[kn,Tr,G,q]);const ft=W=>{const N=Yr.getState().sessions.get(W.id);return il(W,N?.activeProgram??null,N?.cwd??null,void 0,N?.shellTitle??null,N?.promptState??null)},Bt=(W,N={})=>{const U=W.id===Z&&!ee?.startsWith("@collaboration:"),K=Jr.has(W.id)&&!N.hidden,fe=p&&PE({sessionId:W.id,foregroundSessionId:Dr,visibleSessionIds:Jr,deferredViewportSessionIds:q?cn:Xn}),Qe=QE({sessionId:W.id,foregroundSessionId:Dr,foregroundReady:xn,isVisible:K})&&p,ve=zE({sessionId:W.id,foregroundSessionId:Dr,requestToken:qe.token,foregroundCompletedToken:Nt,isVisible:X.has(W.id)})&&p,lt=K||W.id===Dr||Xn.has(W.id)?0:en.get(W.id)??qh;return s.jsxs("div",{className:`relative flex h-full min-h-0 min-w-0 flex-col overflow-hidden ${N.hidden?"invisible pointer-events-none":""}`,style:N.containerStyle,"aria-hidden":N.hidden||void 0,onPointerDownCapture:()=>{K&&G2(U,()=>kn(W.id))},onWheelCapture:()=>{G2(U,()=>kn(W.id))},children:[N.showPaneTitle&&s.jsx(lN,{session:W,active:U,onActivate:()=>kn(W.id),onToggleRightSidebar:U?x:void 0}),s.jsx("div",{className:"min-h-0 flex-1 app-chrome-bg",children:fe&&s.jsx(oN,{sessionId:W.id,mode:W.mode,tmuxSessionName:W.tmuxSessionName,terminalSettings:e,colorTheme:t,toolbarPresets:r,isActive:U,focusSuspended:_e!==null,deferCursorUntilPositioned:_e===W.id||W.mode==="tmux"&&!Ne.has(W.id),isLayoutVisible:K,initialConnectEnabled:Qe&&ve,resumeRequestEnabled:ve,suppressKeyboard:N.suppressKeyboard,keyboardPortalTarget:N.keyboardPortalTarget,sharedMobileKeyboardLayout:N.sharedMobileKeyboardLayout,suppressPageFlipRefresh:N.suppressPageFlipRefresh,focusRequestToken:Ie?.sessionId===W.id?Ie.token:0,resumeRequestToken:qe.token,resumeRequestReason:qe.reason,forceResumeReconnect:qe.forceForegroundReconnect&&X.has(W.id),resumeRequestDelayMs:X.has(W.id)?0:N.hidden?qh:en.get(W.id)??qh,initialConnectDelayMs:lt,onStreamReadyChange:Et,onStreamConnected:tr,onViewportReadyChange:jr,onContentReadyChange:cr,onKeyboardVisibilityChange:Jn,showDebug:n,onStatusChange:U?S:void 0})})]},W.id)};return s.jsxs("div",{className:"relative h-full flex flex-col",children:[wt&&$.some(W=>W.id===wt.sessionId)&&s.jsxs("div",{role:"alert",className:"fixed inset-x-3 top-[calc(var(--safe-top-inset)+0.75rem)] z-toast mx-auto flex max-w-lg items-center gap-3 rounded-xl border border-destructive/30 bg-surface-elevated px-4 py-3 text-[12px] text-foreground shadow-lg",children:[s.jsx("span",{className:"min-w-0 flex-1",children:B("tab.closeFailed",{name:$.find(W=>W.id===wt.sessionId).name})}),s.jsx("button",{type:"button",className:"shrink-0 rounded-lg px-2 py-1 text-primary hover:bg-surface-2",onClick:()=>{kt(wt)},children:B("common.retry")}),s.jsx("button",{type:"button",className:"shrink-0 rounded-lg p-1 hover:bg-surface-2","aria-label":B("common.close"),onClick:()=>zt(null),children:s.jsx(In,{size:16})})]}),Er&&s.jsx("section",{className:"fixed inset-x-3 top-[calc(var(--safe-top-inset)+0.75rem)] z-toast mx-auto max-w-lg rounded-2xl border border-warning/30 bg-surface-elevated px-4 py-3.5 shadow-[0_20px_60px_var(--app-shadow-strong)]",role:"alert","aria-live":"assertive",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("span",{className:"mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-warning/15 text-warning",children:s.jsx(P1,{size:18})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("h2",{className:"text-[13px] font-semibold text-foreground",children:B("tab.tmuxRecoveryTitle",{count:Er.sessions.length})}),s.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-muted-foreground",children:B("tab.tmuxRecoveryHint")}),s.jsx("p",{className:"mt-1.5 truncate text-[10px] text-foreground/70",children:Er.sessions.map(W=>W.name).join(" · ")}),It&&s.jsx("p",{className:"mt-2 text-[10px] text-destructive",children:It}),s.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[s.jsxs("button",{type:"button",disabled:Kt!==null,onClick:()=>{re()},className:"inline-flex min-h-9 items-center gap-1.5 rounded-lg bg-primary px-3 text-[11px] font-medium text-primary-foreground transition active:opacity-80 disabled:opacity-50",children:[s.jsx(Uy,{size:13,className:Kt==="restore"?"animate-spin":""}),B(Kt==="restore"?"tab.tmuxRecoveryRestoring":"tab.tmuxRecoveryRestoreAll")]}),s.jsx("button",{type:"button",disabled:Kt!==null,onClick:()=>{mt()},className:"inline-flex min-h-9 items-center rounded-lg px-3 text-[11px] text-muted-foreground transition hover:bg-surface-2 hover:text-foreground disabled:opacity-50",children:B("tab.tmuxRecoveryDismiss")})]})]})]})}),s.jsx("div",{className:"flex-1 overflow-hidden",children:s.jsx(dA,{onSwiper:W=>{Ze.current=W,W.allowTouchMove=Mr.length>1&&!Ar&&!ae,_r("[swiper:on-swiper]",{allowTouchMove:W.allowTouchMove}),requestAnimationFrame(()=>Lr("on-swiper"))},onSlideChange:kr,onTouchStart:(W,N)=>{const U=Z2(N),K=U==="touch"||U==="pen"||U==="unknown";O("[swipe:touch-start]",{pointerType:U,allowed:K}),_r("[swiper:touch-start]",{pointerType:U,allowed:K}),K&&(Gn(),xt.current=!0,yt.current=!0)},onTouchEnd:(W,N)=>{const U=Z2(N),K=U==="touch"||U==="pen"||U==="unknown";O("[swipe:touch-end]",{pointerType:U,allowed:K}),_r("[swiper:touch-end]",{pointerType:U,allowed:K}),K&&(xt.current=!1,Vn("touch-end"))},onTransitionEnd:()=>{const W=Ze.current;if(xt.current){_r("[swiper:transition-end-during-touch]");return}if(yt.current&&W&&!TN(W,me.current)){_r("[swiper:transition-end-deferred]");return}Gn(),yt.current=!1,_r("[swiper:transition-end]")},initialSlide:Math.max(0,Or),speed:d1,slidesPerView:1,resistanceRatio:.82,threshold:8,longSwipesRatio:.2,touchAngle:45,touchStartPreventDefault:!1,simulateTouch:!1,noSwiping:!0,noSwipingSelector:"[data-mobile-keyboard='true']",className:"terminal-session-swiper h-full",children:Mr.map(W=>{const N=W.workspace,U=!!N&&W.sessions.length>=2,K=q?qt?"horizontal":"vertical":N?.layout??"horizontal",fe=q&&Ke?W.sessions.some(ve=>ve.id===Ke):!1,Qe=W.sessions.some(ve=>ve.id===Z)?Z:W.sessions[0]?.id;return s.jsx(hA,{className:"h-full",children:s.jsx("div",{className:"h-full min-w-0","data-pinned-right-sidebar-inset":ln.get(W.key)??0,style:{paddingRight:ln.get(W.key)??0,paddingTop:y&&!U?"2.5rem":void 0},children:U?s.jsxs("div",{className:"flex h-full min-h-0 min-w-0 flex-col bg-[var(--chrome-bg)]",style:q?{transform:"translateY(var(--kb-translate-y, 0px))",transition:"none"}:void 0,children:[s.jsx(vx,{layoutId:W.key,preset:N?.layout??"horizontal",initialTree:cC(W.sessions.map(ve=>ve.id),K,N?.ratios,N?.gridColumnRatios,N?.gridRowRatios),mobile:q,focusId:fe?Ke:null,panes:W.sessions.map(ve=>({id:ve.id,content:Bt(ve,{showPaneTitle:!q,suppressKeyboard:q&&ve.id!==Qe,keyboardPortalTarget:q?De:null,sharedMobileKeyboardLayout:q,suppressPageFlipRefresh:!0})}))}),q&&s.jsx("div",{ref:nr,className:"relative shrink-0 app-chrome-bg","data-split-keyboard-host":"true"})]}):s.jsx(vx,{layoutId:W.key,preset:N?.layout??"horizontal",mobile:q,panes:[{id:W.sessions[0].id,content:Bt(W.sessions[0])}]})})},W.key)})})}),ae&&Z&&s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"fixed inset-0 z-modal-backdrop bg-[var(--app-backdrop-soft)] backdrop-blur-sm",onClick:()=>Ye(!1),"aria-label":B("common.close")}),s.jsxs("section",{ref:et,tabIndex:-1,className:"fixed inset-x-3 bottom-3 z-modal-panel mx-auto max-h-[min(78svh,620px)] max-w-md overflow-hidden rounded-2xl border border-border/20 bg-surface shadow-[0_24px_70px_var(--app-shadow-strong)] sm:bottom-auto sm:top-1/2 sm:-translate-y-1/2",style:{paddingBottom:"var(--safe-bottom-inset)"},role:"dialog","aria-modal":"true","aria-label":B("tab.splitTitle"),children:[s.jsxs("header",{className:"flex items-start gap-3 border-b border-border/20 px-4 py-3.5",children:[s.jsx("div",{className:"mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-xl bg-primary/15 text-primary",children:s.jsx(Il,{size:17})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("h2",{className:"text-[14px] font-semibold text-foreground",children:B("tab.splitTitle")}),s.jsx("p",{className:"mt-0.5 text-[11px] leading-relaxed text-muted-foreground",children:B("tab.splitExistingHint")})]}),s.jsx("button",{type:"button",className:"inline-flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground transition hover:bg-surface-2 hover:text-foreground",onClick:()=>Ye(!1),"aria-label":B("common.close"),children:s.jsx(In,{size:16})})]}),s.jsxs("div",{className:"max-h-[calc(min(78svh,620px)-72px)] overflow-y-auto overscroll-contain p-2",children:[s.jsxs("button",{type:"button",disabled:Ve,onClick:()=>{tn()},className:"flex w-full items-center gap-3 rounded-xl px-3 py-3 text-left transition hover:bg-surface-2 active:bg-surface-elevated disabled:opacity-60",children:[s.jsx("span",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-primary/15 text-primary",children:s.jsx(zs,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-[13px] font-medium text-foreground",children:B("tab.splitNew")}),s.jsx("span",{className:"mt-0.5 block text-[11px] text-muted-foreground",children:B("tab.splitNewHint")})]})]}),Ce.filter(W=>W.id!==Tr?.id).length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"px-3 pb-1 pt-3 text-[10px] font-medium uppercase tracking-[0.12em] text-muted-foreground",children:B("tab.splitExistingGroups")}),Ce.filter(W=>W.id!==Tr?.id).map((W,N)=>{const U=W.sessionIds.flatMap(Qe=>{const ve=$.find(lt=>lt.id===Qe);return ve?[ve]:[]});if(U.length<2)return null;const K=W.name||`${B("tab.splitWorkspace")} ${N+1}`,fe=U.map(Qe=>ft(Qe).primary).join(" · ");return s.jsxs("button",{type:"button",onClick:()=>Wr(U[0].id),className:"group flex w-full items-center gap-3 rounded-xl px-3 py-2.5 text-left transition hover:bg-surface-2 active:bg-surface-elevated",children:[s.jsx("span",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary",children:s.jsx(Il,{size:15})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:"min-w-0 flex-1 truncate text-[12px] font-medium text-foreground",children:K}),s.jsx("span",{className:"shrink-0 rounded-full bg-primary/10 px-1.5 py-0.5 text-[9px] font-medium text-primary",children:B("tab.splitOccupied")})]}),s.jsxs("span",{className:"mt-0.5 block truncate text-[10px] text-muted-foreground",children:[B("tab.sessionCount",{count:U.length})," · ",fe]})]}),s.jsx(pi,{size:14,className:"text-primary opacity-0 transition group-hover:opacity-100"})]},W.id)})]}),s.jsx("div",{className:"px-3 pb-1 pt-3 text-[10px] font-medium uppercase tracking-[0.12em] text-muted-foreground",children:B("tab.splitAvailableSessions")}),$.filter(W=>!Ce.some(N=>N.sessionIds.includes(W.id))&&W.id!==Z).length===0&&Ce.filter(W=>W.id!==Tr?.id).length===0?s.jsx("p",{className:"px-3 py-4 text-[12px] text-muted-foreground",children:B("tab.splitNoOtherSessions")}):$.filter(W=>!Ce.some(N=>N.sessionIds.includes(W.id))&&W.id!==Z).map(W=>{const N=Jt.get(W.id)??null,U=ft(W);return s.jsxs("button",{type:"button",onClick:()=>Wr(W.id),className:"group flex w-full items-center gap-3 rounded-xl px-3 py-2.5 text-left transition hover:bg-surface-2 active:bg-surface-elevated",children:[s.jsx("span",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-surface-2 text-muted-foreground",children:N?s.jsx(Vc,{size:15}):s.jsx(Il,{size:15})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block truncate text-[12px] font-medium text-foreground",children:U.primary}),s.jsx("span",{className:"mt-0.5 block truncate text-[10px] text-muted-foreground",children:N?Ku(N)??N:W.name})]}),s.jsx(pi,{size:14,className:"text-primary opacity-0 transition group-hover:opacity-100"})]},W.id)})]})]})]}),Gt&&s.jsx("div",{className:"fixed inset-x-3 bottom-4 z-toast mx-auto max-w-md rounded-xl border border-border/20 bg-surface-elevated px-4 py-3 text-center text-[12px] text-foreground shadow-lg",children:Gt})]})},IN={sm:"h-4 w-7",md:"h-6 w-10"},EN={sm:"h-3 w-3",md:"h-5 w-5"},NN={sm:"translate-x-3",md:"translate-x-4"};function ll({checked:e,disabled:t=!1,size:r="md",className:n=""}){return s.jsx("span",{"aria-hidden":"true",className:`inline-flex shrink-0 items-center rounded-full transition ${IN[r]} ${e?"bg-primary":"bg-surface-elevated"} ${t?"opacity-50":""} ${n}`,children:s.jsx("span",{className:`mx-0.5 inline-block rounded-full bg-[var(--background)] shadow transition ${EN[r]} ${e?NN[r]:""}`})})}function la(e){return`Minified Redux error #${e}; visit https://redux.js.org/Errors?code=${e} for the full message or use the non-minified dev environment for full errors. `}var RN=typeof Symbol=="function"&&Symbol.observable||"@@observable",X2=RN,J2=()=>Math.random().toString(36).substring(7).split("").join("."),MN={INIT:`@@redux/INIT${J2()}`,REPLACE:`@@redux/REPLACE${J2()}`},e5=MN;function jN(e){if(typeof e!="object"||e===null)return!1;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t||Object.getPrototypeOf(e)===null}function dv(e,t,r){if(typeof e!="function")throw new Error(la(2));if(typeof t=="function"&&typeof r=="function"||typeof r=="function"&&typeof arguments[3]=="function")throw new Error(la(0));if(typeof t=="function"&&typeof r>"u"&&(r=t,t=void 0),typeof r<"u"){if(typeof r!="function")throw new Error(la(1));return r(dv)(e,t)}let n=e,a=t,c=new Map,l=c,d=0,p=!1;function m(){l===c&&(l=new Map,c.forEach((E,R)=>{l.set(R,E)}))}function x(){if(p)throw new Error(la(3));return a}function y(E){if(typeof E!="function")throw new Error(la(4));if(p)throw new Error(la(5));let R=!0;m();const B=d++;return l.set(B,E),function(){if(R){if(p)throw new Error(la(6));R=!1,m(),l.delete(B),c=null}}}function w(E){if(!jN(E))throw new Error(la(7));if(typeof E.type>"u")throw new Error(la(8));if(typeof E.type!="string")throw new Error(la(17));if(p)throw new Error(la(9));try{p=!0,a=n(a,E)}finally{p=!1}return(c=l).forEach(B=>{B()}),E}function v(E){if(typeof E!="function")throw new Error(la(10));n=E,w({type:e5.REPLACE})}function S(){const E=y;return{subscribe(R){if(typeof R!="object"||R===null)throw new Error(la(11));function B(){const O=R;O.next&&O.next(x())}return B(),{unsubscribe:E(B)}},[X2](){return this}}}return w({type:e5.INIT}),{dispatch:w,subscribe:y,getState:x,replaceReducer:v,[X2]:S}}function t5(e,t){return function(...r){return t(e.apply(this,r))}}function r5(e,t){if(typeof e=="function")return t5(e,t);if(typeof e!="object"||e===null)throw new Error(la(16));const r={};for(const n in e){const a=e[n];typeof a=="function"&&(r[n]=t5(a,t))}return r}function hv(...e){return e.length===0?t=>t:e.length===1?e[0]:e.reduce((t,r)=>(...n)=>t(r(...n)))}function DN(...e){return t=>(r,n)=>{const a=t(r,n);let c=()=>{throw new Error(la(15))};const l={getState:a.getState,dispatch:(p,...m)=>c(p,...m)},d=e.map(p=>p(l));return c=hv(...d)(a.dispatch),{...a,dispatch:c}}}var sm={exports:{}},im={};var n5;function BN(){if(n5)return im;n5=1;var e=SA();function t(p,m){return p===m&&(p!==0||1/p===1/m)||p!==p&&m!==m}var r=typeof Object.is=="function"?Object.is:t,n=e.useSyncExternalStore,a=e.useRef,c=e.useEffect,l=e.useMemo,d=e.useDebugValue;return im.useSyncExternalStoreWithSelector=function(p,m,x,y,w){var v=a(null);if(v.current===null){var S={hasValue:!1,value:null};v.current=S}else S=v.current;v=l(function(){function E($){if(!R){if(R=!0,B=$,$=y($),w!==void 0&&S.hasValue){var V=S.value;if(w(V,$))return z=V}return z=$}if(V=z,r(B,$))return V;var Z=y($);return w!==void 0&&w(V,Z)?(B=$,V):(B=$,z=Z)}var R=!1,B,z,O=x===void 0?null:x;return[function(){return E(m())},O===null?void 0:function(){return E(O())}]},[m,x,y,w]);var L=n(p,v[0],v[1]);return c(function(){S.hasValue=!0,S.value=L},[L]),d(L),L},im}var s5;function QN(){return s5||(s5=1,sm.exports=BN()),sm.exports}QN();var PN=b.version.startsWith("19"),ON=Symbol.for(PN?"react.transitional.element":"react.element"),FN=Symbol.for("react.portal"),$N=Symbol.for("react.fragment"),UN=Symbol.for("react.strict_mode"),zN=Symbol.for("react.profiler"),HN=Symbol.for("react.consumer"),WN=Symbol.for("react.context"),fv=Symbol.for("react.forward_ref"),GN=Symbol.for("react.suspense"),VN=Symbol.for("react.suspense_list"),ng=Symbol.for("react.memo"),qN=Symbol.for("react.lazy"),YN=fv,ZN=ng;function KN(e){if(typeof e=="object"&&e!==null){const{$$typeof:t}=e;switch(t){case ON:switch(e=e.type,e){case $N:case zN:case UN:case GN:case VN:return e;default:switch(e=e&&e.$$typeof,e){case WN:case fv:case qN:case ng:return e;case HN:return e;default:return t}}case FN:return t}}}function XN(e){return KN(e)===ng}function JN(e,t,r,n,{areStatesEqual:a,areOwnPropsEqual:c,areStatePropsEqual:l}){let d=!1,p,m,x,y,w;function v(B,z){return p=B,m=z,x=e(p,m),y=t(n,m),w=r(x,y,m),d=!0,w}function S(){return x=e(p,m),t.dependsOnOwnProps&&(y=t(n,m)),w=r(x,y,m),w}function L(){return e.dependsOnOwnProps&&(x=e(p,m)),t.dependsOnOwnProps&&(y=t(n,m)),w=r(x,y,m),w}function E(){const B=e(p,m),z=!l(B,x);return x=B,z&&(w=r(x,y,m)),w}function R(B,z){const O=!c(z,m),$=!a(B,p,z,m);return p=B,m=z,O&&$?S():O?L():$?E():w}return function(z,O){return d?R(z,O):v(z,O)}}function eR(e,{initMapStateToProps:t,initMapDispatchToProps:r,initMergeProps:n,...a}){const c=t(e,a),l=r(e,a),d=n(e,a);return JN(c,l,d,e,a)}function tR(e,t){const r={};for(const n in e){const a=e[n];typeof a=="function"&&(r[n]=(...c)=>t(a(...c)))}return r}function p1(e){return function(r){const n=e(r);function a(){return n}return a.dependsOnOwnProps=!1,a}}function i5(e){return e.dependsOnOwnProps?!!e.dependsOnOwnProps:e.length!==1}function pv(e,t){return function(n,{displayName:a}){const c=function(d,p){return c.dependsOnOwnProps?c.mapToProps(d,p):c.mapToProps(d,void 0)};return c.dependsOnOwnProps=!0,c.mapToProps=function(d,p){c.mapToProps=e,c.dependsOnOwnProps=i5(e);let m=c(d,p);return typeof m=="function"&&(c.mapToProps=m,c.dependsOnOwnProps=i5(m),m=c(d,p)),m},c}}function sg(e,t){return(r,n)=>{throw new Error(`Invalid value of type ${typeof e} for ${t} argument when connecting component ${n.wrappedComponentName}.`)}}function rR(e){return e&&typeof e=="object"?p1(t=>tR(e,t)):e?typeof e=="function"?pv(e):sg(e,"mapDispatchToProps"):p1(t=>({dispatch:t}))}function nR(e){return e?typeof e=="function"?pv(e):sg(e,"mapStateToProps"):p1(()=>({}))}function sR(e,t,r){return{...r,...e,...t}}function iR(e){return function(r,{displayName:n,areMergedPropsEqual:a}){let c=!1,l;return function(p,m,x){const y=e(p,m,x);return c?a(y,l)||(l=y):(c=!0,l=y),l}}}function aR(e){return e?typeof e=="function"?iR(e):sg(e,"mergeProps"):()=>sR}function oR(e){e()}function lR(){let e=null,t=null;return{clear(){e=null,t=null},notify(){oR(()=>{let r=e;for(;r;)r.callback(),r=r.next})},get(){const r=[];let n=e;for(;n;)r.push(n),n=n.next;return r},subscribe(r){let n=!0;const a=t={callback:r,next:null,prev:t};return a.prev?a.prev.next=a:e=a,function(){!n||e===null||(n=!1,a.next?a.next.prev=a.prev:t=a.prev,a.prev?a.prev.next=a.next:e=a.next)}}}}var a5={notify(){},get:()=>[]};function mv(e,t){let r,n=a5,a=0,c=!1;function l(L){x();const E=n.subscribe(L);let R=!1;return()=>{R||(R=!0,E(),y())}}function d(){n.notify()}function p(){S.onStateChange&&S.onStateChange()}function m(){return c}function x(){a++,r||(r=t?t.addNestedSub(p):e.subscribe(p),n=lR())}function y(){a--,r&&a===0&&(r(),r=void 0,n.clear(),n=a5)}function w(){c||(c=!0,x())}function v(){c&&(c=!1,y())}const S={addNestedSub:l,notifyNestedSubs:d,handleChangeWrapper:p,isSubscribed:m,trySubscribe:w,tryUnsubscribe:v,getListeners:()=>n};return S}var cR=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",uR=cR(),dR=()=>typeof navigator<"u"&&navigator.product==="ReactNative",hR=dR(),fR=()=>uR||hR?b.useLayoutEffect:b.useEffect,Af=fR();function o5(e,t){return e===t?e!==0||t!==0||1/e===1/t:e!==e&&t!==t}function am(e,t){if(o5(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;const r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let a=0;a<r.length;a++)if(!Object.prototype.hasOwnProperty.call(t,r[a])||!o5(e[r[a]],t[r[a]]))return!1;return!0}var pR={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},mR={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},gR={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},gv={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},xR={[YN]:gR,[ZN]:gv};function l5(e){return XN(e)?gv:xR[e.$$typeof]||pR}var bR=Object.defineProperty,yR=Object.getOwnPropertyNames,c5=Object.getOwnPropertySymbols,vR=Object.getOwnPropertyDescriptor,wR=Object.getPrototypeOf,u5=Object.prototype;function m1(e,t){if(typeof t!="string"){if(u5){const c=wR(t);c&&c!==u5&&m1(e,c)}let r=yR(t);c5&&(r=r.concat(c5(t)));const n=l5(e),a=l5(t);for(let c=0;c<r.length;++c){const l=r[c];if(!mR[l]&&!(a&&a[l])&&!(n&&n[l])){const d=vR(t,l);try{bR(e,l,d)}catch{}}}}return e}var AR=Symbol.for("react-redux-context"),TR=typeof globalThis<"u"?globalThis:{};function SR(){if(!b.createContext)return{};const e=TR[AR]??=new Map;let t=e.get(b.createContext);return t||(t=b.createContext(null),e.set(b.createContext,t)),t}var xv=SR(),CR=[null,null];function _R(e,t,r){Af(()=>e(...t),r)}function kR(e,t,r,n,a,c){e.current=n,r.current=!1,a.current&&(a.current=null,c())}function LR(e,t,r,n,a,c,l,d,p,m,x){if(!e)return()=>{};let y=!1,w=null;const v=()=>{if(y||!d.current)return;const L=t.getState();let E,R;try{E=n(L,a.current)}catch(B){R=B,w=B}R||(w=null),E===c.current?l.current||m():(c.current=E,p.current=E,l.current=!0,x())};return r.onStateChange=v,r.trySubscribe(),v(),()=>{if(y=!0,r.tryUnsubscribe(),r.onStateChange=null,w)throw w}}function IR(e,t){return e===t}function ER(e,t,r,{pure:n,areStatesEqual:a=IR,areOwnPropsEqual:c=am,areStatePropsEqual:l=am,areMergedPropsEqual:d=am,forwardRef:p=!1,context:m=xv}={}){const x=m,y=nR(e),w=rR(t),v=aR(r),S=!!e;return E=>{const R=E.displayName||E.name||"Component",B=`Connect(${R})`,z={shouldHandleStateChanges:S,displayName:B,wrappedComponentName:R,WrappedComponent:E,initMapStateToProps:y,initMapDispatchToProps:w,initMergeProps:v,areStatesEqual:a,areStatePropsEqual:l,areOwnPropsEqual:c,areMergedPropsEqual:d};function O(Z){const[le,be,pe]=b.useMemo(()=>{const{reactReduxForwardedRef:Ze,...at}=Z;return[Z.context,Ze,at]},[Z]),ee=b.useMemo(()=>{let Ze=x;return le?.Consumer,Ze},[le,x]),_e=b.useContext(ee),ze=!!Z.store&&!!Z.store.getState&&!!Z.store.dispatch,Y=!!_e&&!!_e.store,ce=ze?Z.store:_e.store,qe=Y?_e.getServerState:ce.getState,we=b.useMemo(()=>eR(ce.dispatch,z),[ce]),[ye,Le]=b.useMemo(()=>{if(!S)return CR;const Ze=mv(ce,ze?void 0:_e.subscription),at=Ze.notifyNestedSubs.bind(Ze);return[Ze,at]},[ce,ze,_e]),Be=b.useMemo(()=>ze?_e:{..._e,subscription:ye},[ze,_e,ye]),ne=b.useRef(void 0),Fe=b.useRef(pe),ke=b.useRef(void 0),Ee=b.useRef(!1),Pe=b.useRef(!1),Ne=b.useRef(void 0);Af(()=>(Pe.current=!0,()=>{Pe.current=!1}),[]);const oe=b.useMemo(()=>()=>ke.current&&pe===Fe.current?ke.current:we(ce.getState(),pe),[ce,pe]),We=b.useMemo(()=>at=>ye?LR(S,ce,ye,we,Fe,ne,Ee,Pe,ke,Le,at):()=>{},[ye]);_R(kR,[Fe,ne,Ee,pe,ke,Le]);let nt;try{nt=b.useSyncExternalStore(We,oe,qe?()=>we(qe(),pe):oe)}catch(Ze){throw Ne.current&&(Ze.message+=`
|
|
77
|
+
`),Mt(ge),Er(ge,!1),Et("Terminal session ended"),ae(!1),cr(!1),cn(null),Gn(null),Zr(ge,!1),os();break}}},onError:(F,ge)=>{if(Tt.current!==T)return;const Se=Y;if(!Se)return;W.current=!1,Ae.current=!1,ae(!1);const Oe=ge&&F.message==="Authentication required",Xe=O2(F),dt=Oe?F.message:Xe||ge?"Reconnecting...":F.message||"Terminal stream connection error";console.error(`[Terminal] Stream error (fatal=${ge}):`,dt),Xe&&console.warn("[Terminal] SESSION_NOT_FOUND_DETECTED",{terminalIdAtError:kr.current,frontendSessionId:Se,isActive:l,isMobile:Pe,fatal:ge,stack:new Error().stack}),Et(dt),cr(!!ge),ge&&(cn(null),Er(Se,!1),os(),Xe&&(ye("[onError] Session lost, auto-recreating"),Et("Reconnecting..."),cr(!1),Mt(Se),Ar(Se),kr.current=null,Hi.current=!1,as()))}},{...aN,getDimensions:()=>pr.current?.getDimensions()??null});gn.current=()=>{Q.close(),Tt.current===T&&(Jn.current=null)},Jn.current=se},[re,Ar,Mt,ye,os,qn,z,Js,as,Ga,Er,Fr,Jt,Zr,Xt,Hr,we,Y]);k.useEffect(()=>{const se=VE({isActive:l,isStreamReady:H,reconnectStartedAt:Xn,now:Date.now()});if(se===null)return;const T=window.setTimeout(()=>{ye("[Terminal] visible reconnect watchdog expired",{backendSessionId:kr.current,reconnectStartedAt:Xn}),os(),Er(Y,!1),Et("Reconnecting..."),cr(!1),cn(Date.now()),as()},se);return()=>window.clearTimeout(T)},[ye,os,l,H,Xn,as,Y,Er]);const Hi=k.useRef(!1),xi=k.useRef(!1),bi=k.useRef(0);k.useEffect(()=>()=>{bi.current+=1,Hi.current=!1,os()},[os]);const hl=k.useRef(X),ti=k.useRef(He);k.useEffect(()=>{const se=hl.current,T=ti.current;hl.current=X,ti.current=He,Lr.current===Y&&(se===X&&T===He||(Hi.current=!1,os(),_r(j=>j+1)))},[X,He,os,Y]),k.useEffect(()=>{if(Lr.current!==Y&&(ye(`[useEffect] sessionId changed from ${Lr.current} to ${Y}, allowing reinitialization`),Hi.current=!1,xi.current=!1),Hi.current&&Lr.current===Y){ye(`[useEffect] Already initialized for sessionId=${Y}, skipping`);return}if(!Qt)return;const se=async ge=>{if(ye(`[ensureSession] Starting for sessionId=${Y}, runId=${ge}`),!Lr.current||Lr.current!==Y){ye(`[ensureSession] SessionId mismatch or stale run (current=${Lr.current}, target=${Y}), skipping`);return}if(ge!==bi.current){ye(`[ensureSession] Stale run detected (runId=${ge}, currentRunId=${bi.current}), skipping`);return}const Se=Yr.getState(),Oe=Se.getTerminalSession(Y),Xe=Oe?.mode??X;ye("[ensureSession] Current state from store:",{terminalSessionId:Oe?.terminalSessionId,mode:Oe?.mode,tmuxSessionName:Oe?.tmuxSessionName,isConnecting:Oe?.isConnecting});let dt=Oe?.terminalSessionId??null,er=!dt;if(dt&&Xe!==X?(ye(`[ensureSession] Store mode mismatch for ${dt}: current=${Xe} desired=${X}, will create new session`),er=!0,Se.clearTerminalSession(Y),dt=null):dt&&X==="tmux"&&He&&Oe?.tmuxSessionName!==He&&(ye(`[ensureSession] Store tmux name mismatch for ${dt}: current=${Oe?.tmuxSessionName} desired=${He}, will create new session`),er=!0,Se.clearTerminalSession(Y),dt=null),dt&&we.checkHealth&&!vt.current){ye(`[ensureSession] Checking health of existing session ${dt}`);try{const or=await we.checkHealth(dt);if(ye("[ensureSession] Health check result:",or),!or.healthy)ye(`[ensureSession] Session ${dt} is NOT healthy (healthy=${or.healthy}), will create new session`),ye("[ensureSession] Health check details:",or),er=!0,or.mode&&Oe?.terminalSessionId&&Se.setTerminalSession(Y,{sessionId:Oe.terminalSessionId,cols:80,rows:24,mode:or.mode,tmuxSessionName:or.tmuxSessionName??null}),Se.clearTerminalSession(Y),ye("[ensureSession] Cleared unhealthy session from store");else{ye(`[ensureSession] Session ${dt} is healthy, reusing it, cwd=${or.cwd}, clients=${or.clients}, lastActivity=${Date.now()-(or.lastActivity||0)}ms ago`),or.mode&&Oe?.terminalSessionId&&Se.setTerminalSession(Y,{sessionId:Oe.terminalSessionId,cols:80,rows:24,mode:or.mode,tmuxSessionName:or.tmuxSessionName??null}),ye(`[ensureSession] Setting terminalIdRef to ${dt} and starting stream`),kr.current=dt,Ms(dt),ye(`[ensureSession] Successfully reused healthy session ${dt}, returning early`);return}}catch(or){ye(`[ensureSession] Failed to check health of session ${dt}:`,or),ye("[ensureSession] Health check API call failed, proceeding as if session might be unhealthy")}}if(ye(`[ensureSession] Decision: shouldCreateNewSession=${er}, terminalId=${dt}`),er){ye(`[ensureSession] Creating new session, shouldCreateNewSession=${er}, runId=${ge}`),Et(null),cr(!1),Se.setConnecting(Y,!0);const $r=Yr.getState().getTerminalSession(Y),Pn=($r?.mode??X)===X&&(X!=="tmux"||!He||$r?.tmuxSessionName===He);if($r?.terminalSessionId&&Pn)ye(`[ensureSession] Race condition avoided: another instance already created session ${$r.terminalSessionId}`),Se.setConnecting(Y,!1),dt=$r.terminalSessionId,er=!1;else try{const yr=await Hn();if(ye(`[ensureSession] Opened managed backend session ${yr.sessionId}`),ge!==bi.current){ye(`[ensureSession] Stale run after session creation (runId=${ge}, currentRunId=${bi.current}), leaving ${yr.sessionId} for sibling`);return}Se.setTerminalSession(Y,yr),ye(`[ensureSession] Updated store with new session ${yr.sessionId}`),dt=yr.sessionId}catch(yr){if(ge!==bi.current){ye("[ensureSession] Stale run after session creation failed, skipping error handling");return}if(yr instanceof n0&&l1(yr)){ye("[ensureSession] Confirmed missing persisted session:",{sessionId:Y,error:yr.message}),Se.clearTerminalSession(Y),Et(Yh),cr(!0),Se.setConnecting(Y,!1);return}Et("Reconnecting..."),cr(!0),Se.setConnecting(Y,!1);return}}if(ge!==bi.current){ye(`[ensureSession] Stale run before starting stream (runId=${ge}, currentRunId=${bi.current}), skipping`);return}if(!dt){ye(`[ensureSession] No terminalId, terminalId=${dt}`);return}ye(`[ensureSession] Starting stream for session ${dt}`),kr.current=dt,Ms(dt),ye(`[ensureSession] ensureSession completed for sessionId=${Y}, terminalId=${dt}`)};let T=null,j=null;const Q=()=>{j=null,!(Hi.current&&Lr.current===Y)&&(ye(`[useEffect] Running ensureSession for sessionId=${Y}, hasInitialized=${Hi.current}`),Hi.current=!0,xi.current=!0,T=++bi.current,se(T))};if(!E&&!xi.current){ye(`[useEffect] Holding background connection until the selected session is ready: ${Y}`);return}const F=xi.current?0:Math.max(0,L);return F>0?(ye(`[useEffect] Delaying initial connection for sessionId=${Y} by ${F}ms`),j=window.setTimeout(Q,F)):Q(),()=>{j!==null&&window.clearTimeout(j),ye(`[useEffect] Cleanup for sessionId=${Y}, runId=${T??"pending"}`)}},[Y,dn,Ms,os,we,ye,X,He,Mr,L,E,Qt]);const Uo=k.useCallback(async()=>{if(Y&&!Cn){Ls(!0),Et(null),cr(!1),cn(null),os();try{we.forceKill&&await we.forceKill({sessionId:Y})}catch{}rr(Y),Ar(Y),pr.current?.clear(),await new Promise(se=>setTimeout(se,100));try{Er(Y,!0);const se=await Hn();un(Y,se),kr.current=se.sessionId,Ms(se.sessionId)}catch(se){Et(se instanceof n0&&l1(se)?Yh:"Reconnecting..."),cr(!0),Er(Y,!1)}finally{Ls(!1)}}},[Y,Cn,os,we,rr,Ar,Er,un,Ms,Hn]),pa=k.useCallback((se,T,j,Q)=>{if(!(kr.current!==T||kt.current!==j)){if(se instanceof n0&&O2(se)){ye("[Terminal] operation backend missing, recovering",{terminalId:T,sessionId:Y}),Et("Reconnecting..."),cr(!1),os(),Mt(Y),kr.current=null,Er(Y,!0),as();return}Et(se instanceof Error?se.message:Q)}},[Mt,ye,os,as,Y,Er]),fl=k.useCallback((se,T)=>{const j=T?.ownedPaste?wC(T.ownedPaste,Y,se):!1;if(T?.ownedPaste&&!j||Lt.current||(br.current||B1())&&!j)return Promise.resolve(!1);const Q=()=>!!T?.ownedPaste&&AC(T.ownedPaste,Y)&&vt.current&&!Lt.current&&Ae.current&&!tr.current&&!document.hidden&&navigator.onLine!==!1&&Cu();if(j&&!Q())return Promise.resolve(!1);if(!vt.current&&!T?.targeted||!se)return;const F=mE(se),ge=/^(\x1b\[<6[45];[0-9]+;[0-9]+M)+$/.test(se);if(Qr&&ge&&(ss.current=!0),Date.now()<kn.current)return;let Se=se,Oe=T?.consumeModifier??!1;if(!T?.skipModifierTransform&&It&&se.length>0){const $r=se[0];if($r.length===1&&/[a-zA-Z]/.test($r)){const nn=$r.toUpperCase();It==="ctrl"?(Se=String.fromCharCode(nn.charCodeAt(0)&31),Oe=!0):It==="alt"&&(Se=`\x1B${se}`,Oe=!0)}Oe||(It==="alt"&&(Se=`\x1B${se}`),Oe=!0)}const Xe=kr.current;if(!Xe)return;const dt=kt.current,or=(async()=>{try{if(Qr&&!F&&ss.current&&we.tmuxAction){ss.current=!1;try{await we.tmuxAction(Xe,{action:"copy-mode",enabled:!1})}catch{}if(kr.current!==Xe||kt.current!==dt)return!1;if(gE(Se))return!0}return j&&(!Q()||kr.current!==Xe||kt.current!==dt)||(await we.sendInput(Xe,Se),j&&(!Q()||kr.current!==Xe||kt.current!==dt))?!1:(ps(Y),!0)}catch($r){return pa($r,Xe,dt,"Failed to send input"),!1}})();return Oe&&(Ve||xe(null),ms()),or},[It,ps,ms,pa,Qr,Ve,Y,we]);k.useEffect(()=>{const se=T=>{const j=T,Q=j.detail?.sessionId;if(Q?Q!==Y:!vt.current)return;const F=j.detail?.text;if(!F)return;const ge=j.detail?.nonce;if(tr.current||!pr.current){ge&&window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:ge,ok:!1}}));return}const Se=vC(j.detail,Y),Oe=j.detail?.ownedPaste&&!Se?Promise.resolve(!1):pr.current.sendSequence(F,{paste:j.detail?.paste,submitAfterPaste:j.detail?.submitAfterPaste,targeted:!!Q,ownedPaste:Se??void 0});ge&&Promise.resolve(Oe).then(Xe=>{window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:ge,ok:Xe===!0}}))},()=>{window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:ge,ok:!1}}))}),qS(rn.current,j.detail?.focus!==!1)&&ms()};return window.addEventListener("termdock-insert-reference",se),()=>window.removeEventListener("termdock-insert-reference",se)},[ms,Y]);const pl=k.useCallback((se,T,j)=>{const Q=kr.current;if(!Q){Le("xterm resize push skipped: no terminalId",{cols:se,rows:T});return}Le("xterm resize push",{cols:se,rows:T}),we.resize({sessionId:Q,cols:se,rows:T,seq:j}).catch(F=>{pr.current?.acknowledgeResize({seq:j,ok:!1}),F&&/session not found/i.test(String(F.message||F))&&console.warn("[Terminal] resize 404 session not found",{sessionId:Q,cols:se,rows:T,stack:new Error().stack})})},[we,Le]),ls=k.useCallback(async se=>{const T=kr.current;if(!T||!we.tmuxAction)return;const j=kt.current;try{const Q=await we.tmuxAction(T,se);if(kr.current!==T||kt.current!==j)return;Q.layout&&(Gn(Q.layout),se.action==="switch-session"&&(un(Y,{sessionId:T,cols:80,rows:24,mode:"tmux",tmuxSessionName:Q.layout.sessionName}),v8(Y,{tmuxSessionName:Q.layout.sessionName}).catch(F=>{console.warn("[Terminal] failed to update inventory after tmux switch",F)})))}catch(Q){pa(Q,T,j,"Failed to execute tmux action")}},[pa,Y,un,we]);k.useEffect(()=>{if(!Or||!en)return;const T=Or.windows.find(j=>j.id===Or.activeWindowId)?.panes.find(j=>j.id===Or.activePaneId);T&&pr.current?.requestRefresh("tmux-layout",{skipScrollToBottom:!0,dedupeKey:`${en}:${Or.sessionId}:${T.id}:${T.width}x${T.height}`})},[Or,en]);const js=k.useCallback((se,T=5)=>{const j=Math.max(1,Math.min(Math.floor(T)||1,40));ss.current=!0;const Q=Wr.current;if(Q&&Q.direction===se){Q.lines+=j;return}Q&&ls({action:"scroll",direction:Q.direction,lines:Q.lines}).finally(()=>{ms()}),Wr.current={direction:se,lines:j},tn.current&&clearTimeout(tn.current),tn.current=setTimeout(()=>{const F=Wr.current;F&&(Wr.current=null,ls({action:"scroll",direction:F.direction,lines:F.lines}).finally(()=>{ms()}))},0)},[ms,ls]),Ri=k.useCallback(se=>{const T=Date.now(),j=Me.current,Q=j!==null&&j.modifier===se&&T-j.timestamp<=rN;if(Me.current={modifier:se,timestamp:T},Ve===se){ht(null),xe(null);return}if(Q){ht(se),xe(se);return}Ve!==null&&Ve!==se&&ht(null),xe(F=>F===se?null:se)},[Ve]),zo=k.useCallback(se=>{if(Ze(se&&vt.current),Le("input focus changed",{focused:se,isActive:vt.current,isMobile:rn.current}),!rn.current||!vt.current){gt(!1);return}gt(T=>T===se?T:se)},[Le]),Dl=k.useCallback(se=>{if(ns.current=se,Js(se,"viewport-watermark"),!se&&En.current.length>0){const T=Y;if(T){const j=En.current;En.current=[];for(const Q of j)re(T,Q)}}},[re,Js,Y]),Es=k.useCallback(se=>{vt.current&&pr.current?.ensureSizeMatches(se)},[]),Ea=k.useRef(null);k.useEffect(()=>{if(!l)return;const se=Ea.current;if(!se)return;const T=()=>Es("pointerdown"),j=()=>Es("keydown"),Q=()=>Es("touchstart"),F=()=>Es("wheel");return se.addEventListener("pointerdown",T),se.addEventListener("keydown",j),se.addEventListener("touchstart",Q,{passive:!0}),se.addEventListener("wheel",F,{passive:!0}),()=>{se.removeEventListener("pointerdown",T),se.removeEventListener("keydown",j),se.removeEventListener("touchstart",Q),se.removeEventListener("wheel",F)}},[l,Es]);const ml=k.useCallback(se=>{pr.current=se},[]),es=k.useCallback(se=>{wt(se),O?.(Y,se)},[O,Y]),Wi=k.useCallback(se=>{const T=SE(se);if(!T)return;const j=It!==null;pr.current?.sendSequence(T,{consumeModifier:j})},[It]),Mi=k.useCallback(se=>{const T=yE(se);if(T.length===0)return;const j=It!==null;pr.current?.sendSequence(D2(T[0]),{consumeModifier:j});for(let Q=1;Q<T.length;Q+=1){const F=T[Q];window.setTimeout(()=>{pr.current?.sendSequence(D2(F))},bE*Q)}},[It]),Gi=k.useCallback(()=>{pr.current?.pasteClipboardText()},[]),gs=k.useCallback(se=>{jt.current!==null&&(window.clearTimeout(jt.current),jt.current=null),yt(se),(se==="inserted"||se==="failed")&&(jt.current=window.setTimeout(()=>{jt.current=null,yt("idle")},1400))},[]),Ws=k.useCallback(()=>{gs("idle"),Rt(0),Bn.current?.click()},[gs]),Bl=k.useCallback(()=>{Vr(!0)},[]),Vi=k.useCallback(se=>{const T=se.currentTarget.files?.[0];if(se.currentTarget.value="",!T)return;const j=Y;Sr(null),fr(null),dr(null),Rt(0),gs("uploading");const Q=ir&&T.type.startsWith("video/")?{maxHeight:Mn,videoBitrate:Xr,onProgress:Rt}:null,F=je&&sN(T)?{maxDimension:st,quality:bt}:null;let ge=Q?"视频压缩":F?"图片压缩":"文件上传";(async()=>{const Se=Q?await(await Oc(async()=>{const{compressVideoLocally:Oe}=await import("./videoCompression-DrYmE1Ed.js");return{compressVideoLocally:Oe}},__vite__mapDeps([0,1,2,3,4,5]))).compressVideoLocally(T,Q):F?await(await Oc(async()=>{const{compressImageLocally:Oe}=await import("./imageCompression-DaUBNTq-.js");return{compressImageLocally:Oe}},[])).compressImageLocally(T,F):T;ge="文件上传",await JE(Se,(Oe,Xe)=>N0(Oe,Xe,void 0,Rt),Oe=>(ge="插入终端",$2(c1(Oe,null),j,()=>vt.current&&!tr.current&&Lr.current===j&&Yr.getState().activeSessionId===j))),(Q||F)&&dr({file:Se,kind:Q?"video":"image",originalSize:T.size,uploadedSize:Se.size,originalRetained:Se===T})})().then(()=>gs("inserted"),Se=>{Se instanceof vf&&Sr({path:Se.uploaded.path,sessionId:j});const Oe=Se instanceof vf?Se.uploaded.path:W2(Se);fr({stage:ge,detail:Oe}),Vr(!0),gs("failed"),ka("warn","MOBILE_MEDIA_UPLOAD failed",{stage:ge,detail:Oe})})},[Xr,ir,Mn,je,st,bt,Y,gs]),qi=k.useCallback(async()=>{const se=Yt;if(!se||se.sessionId!==Y)return;Vr(!1),await new Promise(j=>window.requestAnimationFrame(()=>j())),gs("uploading"),await $2(c1(se.path,null),se.sessionId,()=>vt.current&&!tr.current&&Lr.current===se.sessionId&&Yr.getState().activeSessionId===se.sessionId)?(Sr(null),fr(null),gs("inserted")):(Vr(!0),gs("failed"))},[Yt,Y,gs]);k.useEffect(()=>{if(!Br||!ir)return;let se=!0;return on(null),qr({phase:"checking-cache"}),Oc(async()=>{const{prepareLocalVideoCompression:T}=await import("./videoCompression-DrYmE1Ed.js");return{prepareLocalVideoCompression:T}},__vite__mapDeps([0,1,2,3,4,5])).then(({prepareLocalVideoCompression:T})=>{if(se)return T(j=>{se&&qr(j)})}).catch(T=>{se&&on(W2(T))}),()=>{se=!1}},[Br,ir]);const fn=Dr||Nt!==null;tr.current=fn;const ma=k.useRef(Jr);fn||(ma.current=Jr);const Yi=fn?ma.current:Jr,Na=k.useMemo(()=>vE(Yi,ln),[Yi,ln]),ji=k.useMemo(()=>Q2(ln,qt),[qt,ln]),Di=!Pe&&qt!=="auto"&&ji.id!=="default"&&ji.showOnDesktop!==!0?"auto":qt,ri=Di==="auto"?Na:Di,ws=k.useMemo(()=>Q2(ln,ri),[ri,ln]),Gs=k.useMemo(()=>ws.actions.filter(se=>se.sequence.trim().length>0).map((se,T)=>({...se,label:o1(se,T)})),[ws.actions]),Bi=k.useMemo(()=>K3(Jr),[Jr]),Ra=ws.label,ni=k.useMemo(()=>Di!=="auto"?`Manual preset: ${ws.label}`:Bi?`Auto preset · ${ws.label} (${Bi})`:"Auto preset",[Bi,Di,ws.label]),ys=k.useCallback(se=>{tt(se)},[]),Za=k.useCallback(()=>{nr(se=>se==="copy"?"arrows":"copy"),_t("idle")},[]),Ka=k.useCallback(()=>{typeof window>"u"||(hr.current!==null&&window.clearTimeout(hr.current),hr.current=window.setTimeout(()=>{hr.current=null,_t("idle")},1200))},[]),As=k.useCallback(se=>{hr.current!==null&&typeof window<"u"&&(window.clearTimeout(hr.current),hr.current=null),_t(se?"copied":"failed"),Ka()},[Ka]),Xa=k.useCallback(se=>{ut(se)},[]),Ql=k.useMemo(()=>Pe?wE(ln):AE(ln),[Pe,ln]),Ho=k.useMemo(()=>w8(a),[a]);k.useEffect(()=>{if(!Qr||!H||!Qt||!en)return;const se=MC(Ho);se&&we.sendInput(en,se).catch(T=>{console.warn("[Terminal] Failed to synchronize tmux default colors:",T)})},[Qr,H,Qt,en,we,Ho]);const Co=k.useMemo(()=>`terminal::${Y}`,[Y]);k.useEffect(()=>{_e?.({isConnecting:Dr,isRestarting:Cn,hasError:!!Nt,sessionId:en})},[Dr,Cn,Nt,en,_e]);const ga=!en||Dr||Cn,Ma=k.useCallback((se,T)=>{if(ga)return;const j=Math.max(1,Math.min(Math.floor(T)||1,40));js(se,j)},[js,ga]);k.useEffect(()=>{if(!l||!Pe)return;pr.current?.requestRefresh("resize",{skipScrollToBottom:!Kt,force:!0})},[l,Pe,Kt,Ot,Y]),k.useEffect(()=>{if(!l||!Pe)return;const se=T=>{const j=T.detail;pr.current?.requestRefresh("resize",{skipScrollToBottom:j?.isOpen!==!0,force:!0})};return document.addEventListener("termdock:viewport-keyboard-change",se),()=>{document.removeEventListener("termdock:viewport-keyboard-change",se)}},[l,Pe,Y]);const Wo=!Z&&(Pe||ws.id==="default"||ws.showOnDesktop===!0),xa=l,cs=Pe&&!be?{transform:"translateY(var(--kb-translate-y, 0px))",transition:"none"}:void 0,Go=Pe&&!be?{marginTop:"var(--kb-margin-top, 0px)",transition:"none"}:void 0,Zi=s.jsx(CE,{visible:Wo,interactive:xa,presentation:Pe?"mobile":"desktop-actions",activeModifier:It,lockedModifier:Ve,disabled:ga,defaultShowExtended:q,presetLabel:Ra,presetModeLabel:ni,presetMode:Di,presetOptions:Ql,includeAlt:ws.includeAlt,presetRowLayout:ws.rowLayout,extraActions:Gs,onKeyPress:Wi,onTextPress:Mi,onPastePress:Pe?Gi:void 0,onFilePress:Pe?Ws:void 0,onFileLongPress:Pe?Bl:void 0,fileUploadState:$t,fileUploadProgress:xt,longPressMode:De,copyFeedback:Ke,onLongPressModeToggle:Za,onModifierToggle:Ri,onPresetSelect:ys,onExpandedChange:Xa}),gl=typeof window<"u"&&(navigator.maxTouchPoints>0||"ontouchstart"in window);return s.jsxs("div",{className:"relative flex h-full min-h-0 flex-col overflow-hidden",style:cs,children:[s.jsx("input",{ref:Bn,type:"file",className:"hidden",onChange:Vi}),Br&&Xs.createPortal(s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"fixed inset-0 z-modal-backdrop cursor-default bg-[var(--app-backdrop)] backdrop-blur-sm",onClick:()=>Vr(!1),"aria-label":ze("common.close")}),s.jsxs("section",{role:"dialog","aria-modal":"true","aria-labelledby":"mobile-video-compression-title",className:"fixed bottom-[max(0.75rem,env(safe-area-inset-bottom,0px))] left-[max(0.75rem,env(safe-area-inset-left,0px))] right-[max(0.75rem,env(safe-area-inset-right,0px))] z-modal-panel max-h-[calc(100dvh-1.5rem)] overflow-y-auto rounded-2xl border border-border/15 bg-surface p-4 shadow-[0_28px_70px_var(--app-shadow-strong),0_14px_32px_var(--app-shadow-soft)] sm:left-1/2 sm:right-auto sm:w-[min(28rem,calc(100vw-2rem))] sm:-translate-x-1/2",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("h2",{id:"mobile-video-compression-title",className:"text-sm font-semibold text-foreground",children:"本地媒体压缩"}),s.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"按文件类型选择压缩方式,处理完成后才上传。"})]}),s.jsx("button",{type:"button",className:"min-h-10 rounded-lg bg-surface-2 px-3 text-xs",onClick:()=>Vr(!1),children:ze("common.close")})]}),Ct&&s.jsxs("div",{role:"alert",className:"mt-3 rounded-lg bg-destructive/10 p-3 text-xs text-destructive",children:[s.jsxs("p",{children:[Ct.stage,"失败。",Ct.stage.endsWith("压缩")?"原文件未上传。":Ct.stage==="插入终端"?"文件已上传,路径见详情。":""]}),s.jsxs("details",{className:"mt-2",children:[s.jsx("summary",{className:"cursor-pointer",children:"错误详情"}),s.jsx("p",{className:"mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words",children:Ct.detail})]}),Yt&&s.jsx("button",{type:"button",onClick:()=>{qi()},disabled:$t==="uploading"||Yt.sessionId!==Y,className:"mt-2 rounded-lg bg-surface-2 px-3 py-2 text-foreground disabled:opacity-50",children:ze("common.retry")})]}),pt&&s.jsx("p",{className:"mt-2 text-[11px] text-destructive",children:"本机未能保存设置,重新打开后可能恢复默认值。"}),s.jsxs("label",{className:"mt-4 flex min-h-11 items-center justify-between rounded-xl bg-surface-elevated px-3 text-sm",children:[s.jsx("span",{children:"显示压缩结果提示"}),s.jsx("input",{type:"checkbox",checked:Gr.showResultToast,onChange:se=>ot({showResultToast:se.target.checked}),className:"h-4 w-4 accent-primary"})]}),s.jsxs("label",{className:"mt-4 flex min-h-11 items-center justify-between rounded-xl bg-surface-elevated px-3 text-sm",children:[s.jsx("span",{children:"压缩图片后上传"}),s.jsx("input",{type:"checkbox",checked:je,onChange:se=>ot({imageEnabled:se.target.checked}),className:"h-4 w-4 accent-primary"})]}),je&&s.jsxs("div",{className:"mt-3 space-y-3",children:[s.jsxs("label",{className:"block text-xs text-muted-foreground",children:["图片最长边",s.jsx("select",{value:st,onChange:se=>ot({imageMaxDimension:Number(se.target.value)}),className:"mt-1 block min-h-10 w-full rounded-lg bg-surface-2 px-3 text-sm text-foreground",children:sv.map(se=>s.jsxs("option",{value:se,children:[se," px",se===640?" · 最省流量":se===2048?" · 推荐":se===4096?" · 保留更多细节":""]},se))})]}),s.jsxs("label",{className:"block text-xs text-muted-foreground",children:["图片画质:",Math.round(bt*100),"%",s.jsx("input",{type:"range",min:l0.min,max:l0.max,step:l0.step,value:bt,onChange:se=>ot({imageQuality:Number(se.target.value)}),className:"mt-2 h-1 w-full accent-primary"})]}),s.jsx("p",{className:"text-[11px] text-muted-foreground",children:"支持 JPEG、PNG、HEIC 照片;GIF、SVG 等保持原文件。压缩后未变小也会保留原图。"})]}),s.jsx("div",{className:"mt-4 border-t border-border/15 pt-1"}),s.jsxs("label",{className:"mt-4 flex min-h-11 items-center justify-between rounded-xl bg-surface-elevated px-3 text-sm",children:[s.jsx("span",{children:"压缩视频后上传"}),s.jsx("input",{type:"checkbox",checked:ir,onChange:se=>ot({videoEnabled:se.target.checked}),className:"h-4 w-4 accent-primary"})]}),ir&&s.jsxs("div",{className:"mt-4 space-y-4",children:[s.jsxs("label",{className:"block text-xs text-muted-foreground",children:["视频最长边(像素)",s.jsx("select",{value:Mn,onChange:se=>ot({videoMaxHeight:Number(se.target.value)}),className:"mt-1 block min-h-10 w-full rounded-lg bg-surface-2 px-3 text-sm text-foreground",children:iv.map(se=>s.jsxs("option",{value:se,children:[se," px",se===240?" · 最省流量":se===720?" · 推荐":se>=1440?" · 手机处理较慢":""]},se))})]}),s.jsxs("label",{className:"block text-xs text-muted-foreground",children:["目标视频码率:",Xr/1e6," Mbps",s.jsx("input",{type:"range",min:c0.min,max:c0.max,step:c0.step,value:Xr,onChange:se=>ot({videoBitrate:Number(se.target.value)}),className:"mt-2 h-1 w-full accent-primary"})]}),s.jsx("p",{className:"text-[11px] text-muted-foreground",children:"保持比例,不放大原视频。尺寸越小通常处理越快;码率越低体积通常越小,过高可能比原片更大。"}),s.jsx("p",{className:"text-[11px] text-muted-foreground",role:"status","aria-live":"polite",children:mn?"本地转码器准备失败,请关闭开关后重试。":iN(Cr)}),Cr?.saved===!1&&s.jsx("p",{className:"text-[11px] text-destructive",children:"本机未能保存转码器,重新打开后可能需要重新下载。"}),mn&&s.jsx("p",{className:"text-[11px] text-destructive",children:mn})]})]})]}),document.body),Vn&&s.jsx(_E,{isMobile:Pe,isInputFocused:nt,isIOS:oe,isConnecting:Dr,connectionError:Nt,terminalSessionId:en}),s.jsxs("div",{className:"relative min-h-0 flex-1 overflow-hidden",style:{backgroundColor:Ho.background,...Go},children:[s.jsx("div",{ref:Ea,className:"h-full w-full box-border",children:s.jsx(A8,{fallback:s.jsx("div",{className:"flex h-full items-center justify-center bg-background",children:s.jsxs("div",{className:"flex flex-col items-center gap-3 text-center rounded-2xl bg-surface-2 px-6 py-5 shadow-sm",children:[s.jsx("div",{className:"w-10 h-10 rounded-full bg-destructive/15 flex items-center justify-center",children:s.jsx("svg",{className:"w-5 h-5 text-destructive",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),s.jsx("span",{className:"text-sm text-muted-foreground",children:ze("terminal.componentFailed")})]})}),children:s.jsx(lE,{ref:ml,sessionKey:Co,sessionId:Y,isLayoutVisible:m,chunks:ks,onInput:fl,onResize:pl,onFlowControl:Dl,onTmuxScroll:Qr?Ma:void 0,tmuxScrollSensitivity:.38,onDoubleTap:Pe?()=>{pr.current?.sendSequence(" ")}:void 0,onInputFocusChange:zo,onMobileLongPressCopyResult:As,onReadyChange:es,onSizeSynchronizedChange:Gt,onWritesSettled:Wa,onWriteProgress:zi,onCursorPositionChange:da,onDirectoryLinkActivate:xn,terminalSettings:Fe,theme:Ho,enableTouchScroll:Pe,mobileLongPressMode:De,autoFocus:!Ee&&!Pe&&!gl,cursorVisible:!Ee&&zt,suppressSmoothScroll:!Ye||!St,className:Ee||!zt?"terminal-focus-suspended":void 0},Co)})}),s.jsx(tN,{result:pn,onDismiss:me}),s.jsx(LE,{connectionError:Nt,isFatalError:jr,isRestarting:Cn,isConnecting:Dr,onHardRestart:Uo})]}),le?Z?null:Xs.createPortal(Zi,le):Zi]})};function lN({session:e,active:t,onActivate:r,onToggleRightSidebar:n}){const{t:a}=Ur(),c=Yr(l=>{const d=l.sessions.get(e.id);return il(e,d?.activeProgram??null,d?.cwd??null,void 0,d?.shellTitle??null,d?.promptState??null).primary});return s.jsxs("div",{"data-pane-titlebar":"true",className:"swiper-no-swiping flex h-6 min-h-6 shrink-0 items-center border-b border-border app-chrome-bg",children:[s.jsxs("button",{type:"button","data-split-pane-title":e.id,draggable:!1,onDragStart:l=>l.preventDefault(),"aria-pressed":t,title:`${c} · 拖动标题移动,边缘拆分,中央交换`,onClick:r,className:"split-pane-drag-handle flex h-full min-w-0 cursor-grab active:cursor-grabbing flex-1 items-center gap-1.5 overflow-hidden px-2 text-left text-[12px] font-medium leading-none text-foreground hover:bg-surface focus-visible:outline focus-visible:outline-1 focus-visible:outline-primary focus-visible:-outline-offset-1",children:[s.jsx($o,{size:11,className:`shrink-0 ${t?"text-primary":"text-muted-foreground"}`}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:c}),s.jsx($f,{size:12,"aria-hidden":"true",className:"shrink-0 text-muted-foreground"}),t&&s.jsx("span",{"aria-hidden":"true",className:"h-1 w-1 shrink-0 rounded-full bg-primary"})]}),n&&s.jsx("button",{type:"button",onClick:n,"aria-label":a("tab.explorerTitle"),title:a("tab.explorerTitle"),className:"inline-flex h-full w-7 shrink-0 items-center justify-center text-muted-foreground hover:bg-surface hover:text-foreground focus-visible:outline focus-visible:outline-1 focus-visible:outline-primary focus-visible:-outline-offset-1",children:s.jsx($y,{size:14})})]})}const cN="termdock:startup:";function Mu(e){if(typeof performance>"u"||typeof performance.mark!="function")return;const t=`${cN}${e}`;performance.getEntriesByName(t,"mark").length>0||performance.mark(t)}function G2(e,t){e||Xs.flushSync(t)}const u1="horizontal";function Pu(e){return e<=0?[]:Array.from({length:e},()=>1/e)}function Zh(e,t){if(!Array.isArray(e)||e.length!==t)return Pu(t);const r=e.map(Number);if(r.some(a=>!Number.isFinite(a)||a<=0))return Pu(t);const n=r.reduce((a,c)=>a+c,0);return n<=0?Pu(t):r.map(a=>a/n)}function uN(e){const t=Math.max(1,Math.ceil(Math.sqrt(Math.max(1,e))));return{columns:t,rows:Math.max(1,Math.ceil(Math.max(1,e)/t))}}function dN(e){return e==="horizontal"||e==="vertical"||e==="grid"}function hN(e){if(!Array.isArray(e))return[];const t=new Set,r=new Set,n=[];for(const a of e){if(!a||typeof a!="object")continue;const c=a;if(typeof c.id!="string"||!c.id||r.has(c.id))continue;const l=Array.isArray(c.sessionIds)?c.sessionIds.filter(m=>typeof m=="string"&&!!m&&!t.has(m)):[],d=[...new Set(l)];if(d.length<2)continue;const p=uN(d.length);d.forEach(m=>t.add(m)),r.add(c.id),n.push({id:c.id,...typeof c.name=="string"&&c.name.trim()?{name:c.name.trim().slice(0,80)}:{},sessionIds:d,layout:dN(c.layout)?c.layout:u1,ratios:Zh(c.ratios,d.length),...c.gridColumnRatios!==void 0?{gridColumnRatios:Zh(c.gridColumnRatios,p.columns)}:{},...c.gridRowRatios!==void 0?{gridRowRatios:Zh(c.gridRowRatios,p.rows)}:{}})}return n}function fN(e,t){const r=new Set(t);return e.flatMap(n=>{const a=n.sessionIds.filter(c=>r.has(c));return a.length<2?[]:[{...n,sessionIds:a,ratios:a.length===n.sessionIds.length?Zh(n.ratios,a.length):Pu(a.length)}]})}function A0(e,t){if(t)return e.find(r=>r.sessionIds.includes(t))}function rm(e,t,r){if(!t||!r||t===r)return e;const n=A0(e,t),a=A0(e,r);if(n&&n.id===a?.id)return e;const c=[...n?.sessionIds??[t],...a?.sessionIds??[r]],l=[...new Set(c)],d={id:n?.id??`split:${t}`,...n?.name?{name:n.name}:{},sessionIds:l,layout:l.length>2&&(!n||n.layout===u1)?"grid":n?.layout??u1,ratios:Pu(l.length)},p=new Set([n?.id,a?.id].filter(Boolean)),m=e.filter(y=>!p.has(y.id)),x=n?Math.max(0,e.findIndex(y=>y.id===n.id)):m.length;return m.splice(Math.min(x,m.length),0,d),m}function pN(e,t){const r=A0(e,t);if(!r||!t)return e;if(r.sessionIds.length<=2)return e.filter(a=>a.id!==r.id);const n=r.sessionIds.filter(a=>a!==t);return e.map(a=>a.id===r.id?{...a,sessionIds:n,ratios:Pu(n.length)}:a)}function mN(e,t){const r=A0(e,t);return r?e.filter(n=>n.id!==r.id):e}function gN(e,t,r){return e.map(n=>{if(n.id!==t)return n;const a=[...new Set(r)],c=new Set(n.sessionIds);return a.length===n.sessionIds.length&&a.every(d=>c.has(d))?{...n,sessionIds:a}:n})}function xN(e,t,r){const n=r.trim().slice(0,80);return e.map(a=>a.id===t?{...a,...n?{name:n}:{name:void 0}}:a)}const d1=320,ov=1,bN=d1+120,h1="termdock:split-workspaces:v2",lv="termdock:split-workspace:v1",yN=.1,vN=.9;function nm(){if(typeof window>"u")return{mobile:!1,landscape:!1};const e=wy();return{mobile:e,landscape:e&&window.innerWidth>window.innerHeight}}function wN(){if(typeof window>"u")return[];try{const e=window.localStorage.getItem(h1);if(e)return hN(JSON.parse(e));const t=JSON.parse(window.localStorage.getItem(lv)||"null");if(t&&typeof t.primaryId=="string"&&typeof t.secondaryId=="string"&&t.primaryId!==t.secondaryId){const r=Math.min(vN,Math.max(yN,typeof t.ratio=="number"?t.ratio:.5));return[{id:`split:${t.primaryId}`,sessionIds:[t.primaryId,t.secondaryId],layout:t.direction==="vertical"?"vertical":"horizontal",ratios:[r,1-r]}]}}catch{}return[]}function AN(e,t){const r=new Map(e.map(l=>[l.id,l])),n=new Map;t.forEach(l=>l.sessionIds.forEach(d=>n.set(d,l)));const a=new Set,c=[];for(const l of e){const d=n.get(l.id);if(!d){c.push({key:l.id,sessions:[l]});continue}if(a.has(d.id))continue;a.add(d.id);const p=d.sessionIds.flatMap(m=>{const x=r.get(m);return x?[x]:[]});p.length>=2&&c.push({key:d.id,sessions:p,workspace:d})}return c}function V2(e){const t=e.wrapperEl;if(t)try{t.getAnimations().forEach(r=>r.cancel())}catch{}}function wh(e,t){const r=wf(e,t);if(r===null)return;const n=e.wrapperEl;V2(e),n&&(n.style.transitionDuration="0ms");try{const a=e;a.setTransition?.(0),a.setTranslate?.(r),V2(e),n&&(n.style.transitionDuration="0ms",n.style.transform=`translate3d(${r}px, 0px, 0px)`)}catch{n&&(n.style.transitionDuration="0ms",n.style.transform=`translate3d(${r}px, 0px, 0px)`)}}function f1(e){try{const t=typeof e.getTranslate=="function"?e.getTranslate():e.translate;return typeof t=="number"&&Number.isFinite(t)?t:null}catch{return typeof e.translate=="number"&&Number.isFinite(e.translate)?e.translate:null}}function wf(e,t){const r=e.snapGrid,n=Array.isArray(r)?r[t]:void 0;return typeof n!="number"||!Number.isFinite(n)?null:-n}function TN(e,t){const r=f1(e),n=wf(e,t);return r!==null&&n!==null&&Math.abs(r-n)<=ov}function SN(e){const t=[],r=new Map,n=new Map,a=new Map;for(const c of e){const l=r.get(c.id)??[];if(l.push(c.id),r.set(c.id,l),c.sessionId){const d=n.get(c.sessionId)??[];d.push(c.id),n.set(c.sessionId,d)}if(c.mode==="tmux"&&c.tmuxSessionName){const d=a.get(c.tmuxSessionName)??[];d.push(c.id),a.set(c.tmuxSessionName,d)}}for(const[c,l]of r)l.length>1&&t.push({kind:"frontend",key:c,sessionIds:l});for(const[c,l]of n)l.length>1&&t.push({kind:"backend",key:c,sessionIds:l});for(const[c,l]of a)l.length>1&&t.push({kind:"tmux",key:c,sessionIds:l});return t}function cv(e){const t=new Map;for(const r of e)t.set(r.id,r);return Array.from(t.values())}function uv(e){return{id:e.sessionId,name:e.name,customName:e.customName===!0,sessionId:e.backendSessionId,mode:e.mode==="tmux"||e.mode==="shell"?e.mode:"shell",tmuxSessionName:e.tmuxSessionName??null}}function CN(e,t){const r=cv(e),n=r.findIndex(a=>a.id===t.id);if(n>=0){const a=[...r];return a[n]=t,a}return[...r,t]}function q2(e,t){const r=new Map(e.map(n=>[n.id,n]));return t.map(n=>{const a=r.get(n.sessionId);return{...uv(n),history:a?.history}})}function Y2(e,t){return e.length===0?null:t&&e.some(r=>r.sessionId===t)?t:e[0]?.sessionId??null}function Z2(e){if(!e||typeof e!="object")return"unknown";const t=e;if(typeof t.pointerType=="string"&&t.pointerType)return t.pointerType;if(typeof t.type=="string"){if(t.type.startsWith("touch"))return"touch";if(t.type.startsWith("mouse"))return"mouse";if(t.type.startsWith("pointer"))return"pointer"}return"unknown"}function K2(e){const t=new Map;for(const[r,n]of e)t.set(r,n.cwd??null);return t}function _N(e,t){if(e.size!==t.size)return!1;for(const[r,n]of t)if(e.get(r)!==n)return!1;return!0}function kN(e){const t="".toLowerCase().replace(/[^a-z0-9_-]/g,"").slice(0,12);if(t)return`wt-${t}`;const r=Date.now().toString(36),n=Math.random().toString(36).slice(2,8);return`wt-${r}${n}`}const LN=({terminalSettings:e=X1(),colorTheme:t="dark",toolbarPresets:r=[],showDebug:n,terminalFocusAvailable:a=!0,defaultSessionMode:c="shell",defaultTmuxSessionName:l="",connectionPrioritySessionId:d=null,connectionPriorityReady:p=!0,desktopRightSidebarEnabled:m=!1,onToggleRightSidebar:x,desktopFloatingTitle:y=!1,desktopPinnedLeftSidebarWidth:w=0,desktopViewportWidth:v=0,onStatusChange:S,onSessionDataUpdate:L,onInitialViewportReady:E,onInitialRecoveryRequired:R})=>{const{t:B}=Ur(),z=b.useMemo(()=>Fu("session"),[]),O=b.useMemo(()=>Fu("terminal"),[]),[$,V]=b.useState([]),[Z,le]=b.useState(null),be=b.useRef(0),pe=b.useRef(0),ee=Kn(W=>W.activePaneId);b.useEffect(()=>{Kn.getState().setActivePane(Z)},[Z]);const[_e,ze]=b.useState(null),[Y,ce]=b.useState(!0),[qe,we]=b.useState({token:0,reason:"visibility",forceForegroundReconnect:!1}),[ye,Le]=b.useState(()=>new Set),[Be,ne]=b.useState(()=>({token:0,completed:new Set})),[Fe,ke]=b.useState(0),[Ee,Pe]=b.useState(()=>new Set),[Ne,oe]=b.useState(()=>new Set),We=b.useRef(new Map),[nt,gt]=b.useState(()=>new Set),ue=b.useRef(!1),Ze=b.useRef(null),at=b.useRef({}),[Ie,Ge]=b.useState(null),[Ce,H]=b.useState(()=>wN()),[ae,Ae]=b.useState(!1),Ye=b.useCallback(W=>{be.current+=1,Ae(W)},[]),et=b.useRef(null),St=b.useRef(ae);St.current=ae,Gc(et,ae&&!!Z,()=>Ye(!1));const[Gt,Qt]=b.useState(null),[wt,zt]=b.useState(null),Vt=b.useRef(new Set),[Kt,Ot]=b.useState(null),[It,xe]=b.useState(null),[Ve,ht]=b.useState(!1),[q,ut]=b.useState(()=>nm().mobile),[qt,tt]=b.useState(()=>nm().landscape),[De,nr]=b.useState(null),[Ke,_t]=b.useState(null),$t=b.useRef(a),yt=b.useRef(!1),xt=b.useRef(!1),Rt=b.useRef(null),Ct=b.useRef(null),fr=b.useRef(q),Yt=b.useRef(null),Sr=b.useCallback(W=>{W!==Yt.current&&(be.current+=1),Yt.current=W,le(W)},[]);b.useEffect(()=>Wt.subscribe((W,N)=>{(W.rightOpen!==N.rightOpen||W.rightTab!==N.rightTab)&&(be.current+=1)}),[]);const pn=b.useRef(0),dr=b.useRef([]),me=b.useRef(0),Gr=b.useRef(null),ot=b.useRef(!1),pt=b.useRef(!0),ir=b.useRef(null),Mn=b.useRef(""),Xr=b.useRef(0);b.useEffect(()=>{if(typeof window>"u")return;const W=()=>{const N=nm();fr.current=N.mobile,ut(N.mobile),tt(N.landscape)};return W(),window.addEventListener("resize",W),()=>window.removeEventListener("resize",W)},[]);const{sessions:je,inventory:st,activeSessionId:bt,isLoading:Br,openSession:Vr,setActiveSession:Cr,removeSession:qr,renameSession:mn,resetSessionCustomName:on,reorderSessions:zr,restoreSessions:un}=T8(),Er=st?.tmuxRecovery??null;b.useEffect(()=>{Er&&R?.()},[Er,R]),b.useEffect(()=>{xe(null),Ot(null)},[Er?.id]);const re=b.useCallback(async()=>{Ot("restore"),xe(null);try{const W=await S8();await un(),W.failed>0&&xe(B("tab.tmuxRecoveryPartial",{restored:W.restored,failed:W.failed}))}catch{xe(B("tab.tmuxRecoveryFailed"))}finally{Ot(null)}},[un,B]),mt=b.useCallback(async()=>{Ot("dismiss"),xe(null);try{await C8(),await un()}catch{xe(B("tab.tmuxRecoveryDismissFailed"))}finally{Ot(null)}},[un,B]),Mt=Wt(W=>W.groupByFolder),rr=df(W=>W.collaborationGroups),Ar=Wt(W=>W.leftOpen||W.rightOpen),Fr=Wt(W=>W.rightSidebarWidthContextKey),Xt=Wt(W=>W.rightSidebarWidth),Zr=Wt(W=>W.rightPinned),[Jt,Pr]=b.useState(()=>K2(Yr.getState().sessions));b.useEffect(()=>Yr.subscribe(W=>{const N=K2(W.sessions);Pr(U=>_N(U,N)?U:N)}),[]);const{arranged:Hr}=b.useMemo(()=>cf($,W=>Jt.get(W.id)??null,Mt,"",Ce,rr),[$,Jt,Mt,Ce,rr]),ps=b.useRef(Hr);ps.current=Hr;const Mr=b.useMemo(()=>AN(Hr,Ce),[Hr,Ce]),jn=b.useRef(Mr);jn.current=Mr;const Tr=b.useMemo(()=>A0(Ce,Z),[Z,Ce]),Jr=b.useMemo(()=>{const W=Mr.find(N=>N.sessions.some(U=>U.id===Z));return new Set(W?.sessions.map(N=>N.id)??[])},[Z,Mr]),ln=b.useMemo(()=>{const W=new Map;if(!m||v<=0)return W;for(const N of Mr){const U=N.sessions[0];if(!U)continue;const K=_8(U.id,Jt.get(U.id)??null,N.workspace?.id??null);if(!(K===Fr?Zr:k8(U.id,Jt.get(U.id)??null,N.workspace?.id??null)))continue;const Qe=K===Fr?Xt:L8(U.id,Jt.get(U.id)??null,N.workspace?.id??null),ve=Oh(Qe,v,w);W.set(N.key,ve+Ay)}return W},[Jt,w,m,Zr,Fr,Xt,v,Mr]),Qr=b.useMemo(()=>em($.map(W=>({id:W.id,backendSessionId:W.sessionId})),d),[d,$]),ks=b.useMemo(()=>Y2(je,bt),[bt,je]),Dr=yh({prioritySessionId:Qr,activeSessionId:_e??Z,persistedActiveSessionId:ks,firstSessionId:$[0]?.id??null}),en=b.useMemo(()=>qE(Mr.flatMap(W=>W.sessions.map(N=>N.id)),Jr),[Jr,Mr]),xn=Dr!==null&&ye.has(Dr),X=b.useMemo(()=>{const W=new Set(Jr);return _e&&W.add(_e),!W.size&&Dr&&W.add(Dr),W},[Jr,_e,Dr]),He=Be.token===qe.token&&HE(X,Be.completed),Nt=He||Fe===qe.token?qe.token:-1;b.useEffect(()=>{if(!qe.token||He)return;const W=window.setTimeout(()=>ke(qe.token),ME);return()=>window.clearTimeout(W)},[qe.token,He]);const Et=b.useCallback((W,N)=>{Le(U=>{if(U.has(W)===N)return U;const fe=new Set(U);return N?fe.add(W):fe.delete(W),fe})},[]),tr=b.useCallback(W=>{const N=pn.current;ne(K=>{if(K.token===N&&K.completed.has(W))return K;const fe=new Set(K.token===N?K.completed:[]);return fe.add(W),{token:N,completed:fe}});const U=Qr??_e??Yt.current;W===U&&Mu("foreground-stream-connected")},[_e,Qr]),jr=b.useCallback((W,N)=>{Pe(U=>{if(U.has(W)===N)return U;const K=new Set(U);return N?K.add(W):K.delete(W),K})},[]),cr=b.useCallback((W,N)=>{oe(U=>{if(U.has(W)===N)return U;const K=new Set(U);return N?K.add(W):K.delete(W),K})},[]);b.useEffect(()=>{for(const[W,N]of We.current){const U=$.find(K=>K.id===W);if(!U||U.sessionId!==N.backendSessionId){We.current.delete(W);continue}!ye.has(W)||!Ee.has(W)||!Ne.has(W)||(We.current.delete(W),vy(N.backendSessionId,`${N.command}\r`).catch(K=>{console.error("[Session] Failed to send startup command:",K)}))}},[$,ye,Ee,Ne]);const Cn=Dr!==null&&Ee.has(Dr),Ls=Dr!==null&&Ne.has(Dr);b.useEffect(()=>{Cn&&Mu("foreground-viewport-ready")},[Cn]),b.useEffect(()=>{Ls&&Mu("foreground-content-ready")},[Ls]),b.useEffect(()=>{if(!E)return;if(!Y&&$.length===0){E();return}if(!Cn||!xn||!Ls)return;const W=[...Jr].every(Qe=>Ee.has(Qe)&&ye.has(Qe)&&Ne.has(Qe));let N=0,U=0;const K=()=>{N=requestAnimationFrame(()=>{U=requestAnimationFrame(()=>{Mu("initial-viewport-presented"),E()})})};W&&K();const fe=W?void 0:window.setTimeout(K,8e3);return()=>{cancelAnimationFrame(N),cancelAnimationFrame(U),clearTimeout(fe)}},[xn,Ls,Cn,Y,E,$.length,Jr,Ee,ye,Ne]);const Xn=b.useMemo(()=>q?BE({slides:Mr.map(W=>W.sessions.map(N=>N.id)),visibleSessionIds:Jr,foregroundSessionId:Dr}):nt,[q,Mr,Jr,Dr,nt]);b.useEffect(()=>{if(q||Jr.size===0)return;const W=new Set(Jr),N=Mr.findIndex(U=>U.sessions.some(K=>Jr.has(K.id)));for(let U=-2;U<=2;U+=1)U!==0&&Mr[N+U]?.sessions.forEach(K=>W.add(K.id));gt(U=>{let K=!1;const fe=new Set(U);for(const Qe of W)fe.has(Qe)||(fe.add(Qe),K=!0);return K?fe:U})},[q,Jr,Mr]);const cn=mC(Xn);b.useEffect(()=>{if(!_e)return;if(!$.some(N=>N.id===_e)){ze(null);return}if(!Ee.has(_e)||!ye.has(_e)||!Ne.has(_e))return;const W=window.setTimeout(()=>{ze(N=>N===_e?null:N),$t.current&&!fr.current&&Ge({sessionId:_e,token:Date.now()})},80);return()=>window.clearTimeout(W)},[Ne,_e,ye,$,Ee]),b.useEffect(()=>{typeof window>"u"||(Ce.length>0?(window.localStorage.setItem(h1,JSON.stringify(Ce)),window.localStorage.removeItem(lv)):window.localStorage.removeItem(h1))},[Ce]),b.useEffect(()=>{Br||Y||Ce.length===0||H(W=>fN(W,$.map(N=>N.id)))},[Br,Y,$,Ce.length]),b.useEffect(()=>{if(!Gt)return;const W=window.setTimeout(()=>Qt(null),3200);return()=>window.clearTimeout(W)},[Gt]),Yt.current=Z,pn.current=qe.token,dr.current=$,Gr.current=bt,ot.current=Br,pt.current=Y,$t.current=a;const dn=b.useCallback((W=Ze.current)=>{const N=me.current,U=typeof window<"u"?window.visualViewport:null,K=W?f1(W):null,fe=W?wf(W,N):null;return{sessionsLength:dr.current.length,workspaceSlidesLength:jn.current.length,sessionIds:dr.current.map(Qe=>Qe.id),activeSessionId:Yt.current,activeSessionIndex:N,persistedActiveId:Gr.current,isLoading:ot.current,isRestoring:pt.current,activeIndex:W?.activeIndex??null,previousIndex:W?.previousIndex??null,animating:W?.animating??null,allowTouchMove:W?.allowTouchMove??null,width:W?.width??null,translate:K,targetTranslate:fe,translateDelta:K!==null&&fe!==null?K-fe:null,snapGridLength:W?.snapGrid?.length??null,targetSnap:W?.snapGrid?.[N]??null,visualViewport:U?{width:Math.round(U.width),height:Math.round(U.height),offsetTop:Math.round(U.offsetTop)}:null}},[]),_r=b.useCallback((W,N)=>{z(W,{...dn(),...N})},[z,dn]);b.useEffect(()=>{Br||Y||Z!==bt&&Cr(Z)},[Z,Br,Y,bt,Cr]);const Or=b.useMemo(()=>{if(Hr.length===0||!Z)return 0;const W=Mr.findIndex(N=>N.sessions.some(U=>U.id===Z));return W>=0?W:0},[Mr,Z]);me.current=Or;const Gn=b.useCallback(()=>{Rt.current&&(clearTimeout(Rt.current),Rt.current=null)},[]),Vn=b.useCallback(W=>{Gn(),Rt.current=setTimeout(()=>{Rt.current=null,yt.current=!1,_r("[swiper:touch-guard-clear]",{reason:W})},bN)},[Gn,_r]),gn=b.useCallback((W,N={})=>{const U=Ze.current,K=me.current,fe=jn.current;if(!U||fe.length===0||K<0||K>=fe.length)return;if(yt.current){_r("[swiper:sync-skip-touch]",{reason:W});return}if(U.animating){_r("[swiper:sync-skip-animating]",{reason:W});return}const Qe=f1(U),ve=wf(U,K),lt=Qe!==null&&ve!==null&&Math.abs(Qe-ve)<=ov,vt=U.activeIndex===K;if(_r("[swiper:sync-check]",{reason:W,activeIndexAligned:vt,translateAligned:lt,immediate:N.immediate===!0}),!(vt&<)){if(vt){wh(U,K),_r("[swiper:sync-forced-active]",{reason:W,translateAligned:lt,immediate:N.immediate===!0});return}N.immediate?(wh(U,K),U.slideTo(K,0,!1),wh(U,K)):U.slideTo(K,d1,!1),_r("[swiper:sync-applied]",{reason:W,activeIndexAligned:vt,translateAligned:lt,immediate:N.immediate===!0})}},[_r]);b.useEffect(()=>{const W=N=>{const U=N;Ze.current&&(Ze.current.allowTouchMove=!U.detail.locked),_r("[swiper:gesture-lock]",{locked:U.detail.locked})};return document.addEventListener("termdock:gesture-lock",W),()=>document.removeEventListener("termdock:gesture-lock",W)},[_r]),b.useEffect(()=>{if($.length===0){Z!==null&&Sr(null);return}if(!Z){if(!p)return;Sr(yh({prioritySessionId:Qr,activeSessionId:null,persistedActiveSessionId:ks,firstSessionId:$[0]?.id??null}));return}$.some(N=>N.id===Z)||Sr($[0].id)},[$,Z,p,Qr,ks]);const Jn=b.useCallback((W,N)=>{if(N&&Date.now()<Xr.current){at.current[W]=!1;return}at.current[W]=N,_t(U=>N?W:U===W?null:U)},[]),kr=b.useCallback(W=>{if(!yt.current&&W.activeIndex!==me.current){_r("[swiper:slide-change-ignored-layout]",{instanceActiveIndex:W.activeIndex,expectedActiveIndex:me.current}),requestAnimationFrame(()=>gn("ignored-layout-slide-change",{immediate:!0}));return}const N=jn.current[W.activeIndex],U=N?.sessions.some(Qe=>Qe.id===Z)?Z:N?.sessions[0]?.id;if(_r("[swiper:slide-change]",{nextSessionId:U??null,instanceActiveIndex:W.activeIndex}),!U||U===Z)return;const K=!!Z&&at.current[Z]===!0,fe=$t.current&&(!fr.current||K);if(Ct.current=U,Sr(U),fe){Ge({sessionId:U,token:Date.now()});return}Ge(null)},[$,Z,_r,gn]);b.useLayoutEffect(()=>{if(Ct.current===Z){_r("[swiper:sync-skip-swiper-driven]",{activeSessionId:Z}),Ct.current=null;return}gn("active-session-index",{immediate:!0})},[Z,Or,$.length,gn,_r]),b.useEffect(()=>{const W=Ze.current;if(!W)return;const N=Mr.length>1&&!Ar&&!ae;W.allowTouchMove!==N&&(W.allowTouchMove=N,_r("[swiper:allow-touch-sync]",{nextAllow:N,sidebarOverlayOpen:Ar}))},[Mr.length,_r,Ar,ae]);const Lr=b.useCallback(W=>{const N=Ze.current;if(!N)return;const U=N.el;if(_r("[swiper:layout-before]",{reason:W,scrollLeft:U?.scrollLeft??null}),U&&(U.scrollLeft=0),N.updateSize(),N.updateSlides(),N.updateProgress(),N.updateSlidesClasses(),U&&(U.scrollLeft=0),_r("[swiper:layout-after]",{reason:W,scrollLeft:U?.scrollLeft??null}),yt.current||N.animating){_r("[swiper:layout-skip-sync-motion]",{reason:W});return}gn(`layout:${W}`,{immediate:!0}),requestAnimationFrame(()=>{const K=Ze.current;K&&(yt.current||K.animating||wh(K,me.current))})},[_r,gn]);b.useEffect(()=>()=>Gn(),[Gn]);const pr=Mr.map(W=>W.key).join("\0");b.useEffect(()=>{requestAnimationFrame(()=>Lr("group-change"))},[Mt,pr,Lr]),b.useEffect(()=>{let W=null,N="mount";const U=lt=>{N=lt,W===null&&(W=requestAnimationFrame(()=>{W=null,Lr(`viewport-change:${N}`)}))},K=()=>U("window-resize"),fe=()=>U("visual-viewport-resize"),Qe=()=>U("visual-viewport-scroll"),ve=lt=>{U(`measured:${lt.detail?.source??"unknown"}`)};return window.addEventListener("resize",K),window.visualViewport?.addEventListener("resize",fe),window.visualViewport?.addEventListener("scroll",Qe),document.addEventListener(ix,ve),U("mount"),()=>{window.removeEventListener("resize",K),window.visualViewport?.removeEventListener("resize",fe),window.visualViewport?.removeEventListener("scroll",Qe),document.removeEventListener(ix,ve),W!==null&&cancelAnimationFrame(W)}},[Lr]),b.useEffect(()=>{if(typeof document>"u")return;let W=null,N=null;const U=vt=>{if(vt!=="online"&&document.hidden)return;const br=performance.now();if(!WE(N,br))return;N=br;const Lt=vt==="bfcache"||vt==="online"?vt:"visibility",rn=GE();Ap(),ka("info","PWA_RESUME scheduled",{source:vt,forceForegroundReconnect:rn,activeSessionId:Yt.current}),we(yn=>({token:yn.token+1,reason:Lt,forceForegroundReconnect:rn})),requestAnimationFrame(()=>Lr(`resume:${vt}:raf`)),W&&clearTimeout(W),W=setTimeout(()=>{W=null,Lr(`resume:${vt}:settled`)},320)},K=()=>{if(document.hidden){Ap();return}U("visibility")},fe=()=>{Ap()},Qe=vt=>{U(vt.persisted?"bfcache":"pageshow")},ve=()=>U("online"),lt=()=>U("focus");return document.addEventListener("visibilitychange",K),window.addEventListener("pagehide",fe),window.addEventListener("pageshow",Qe),window.addEventListener("online",ve),window.addEventListener("focus",lt),()=>{document.removeEventListener("visibilitychange",K),window.removeEventListener("pagehide",fe),window.removeEventListener("pageshow",Qe),window.removeEventListener("online",ve),window.removeEventListener("focus",lt),W&&clearTimeout(W)}},[Lr]),b.useLayoutEffect(()=>{if(!UE(Y))return;const W=SN($),N=JSON.stringify(W);W.length>0&&N!==Mn.current?(Mn.current=N,console.warn("[session-invariant] duplicate mapping detected",W)):W.length===0&&Mn.current&&(Mn.current=""),L?.({sessions:$.map(U=>({id:U.id,name:U.name,customName:U.customName,mode:U.mode,tmuxSessionName:U.tmuxSessionName})),activeSessionId:Z,splitWorkspaces:Ce.map(({id:U,name:K,sessionIds:fe,layout:Qe})=>({id:U,...K?{name:K}:{},sessionIds:fe,layout:Qe}))})},[$,Z,Ce,L,Y]),b.useEffect(()=>{if(Br||ue.current)return;ue.current=!0;const W=em(je.map(Qe=>({id:Qe.sessionId,backendSessionId:Qe.backendSessionId??null})),d),N=Y2(je,bt),U=yh({prioritySessionId:p?W:null,activeSessionId:null,persistedActiveSessionId:N,firstSessionId:je[0]?.sessionId??null}),K=cv(je.map(uv));if(z("[Session] Restoring",K.length,"persisted sessions (one-shot)"),_r("[swiper:restore-start]",{persistedSessionIds:je.map(Qe=>Qe.sessionId),nextActiveSessionId:U}),K.length>0){const Qe=Yr.getState();K.forEach(lt=>{lt.sessionId&&Qe.setTerminalSession(lt.id,{sessionId:lt.sessionId,cols:80,rows:24,mode:lt.mode,tmuxSessionName:lt.tmuxSessionName,history:lt.history})}),je.forEach(lt=>{lt.agent!==void 0&&Qe.setSessionAgentIdentity(lt.sessionId,lt.agent),lt.activeProgram!=null&&Qe.setSessionActiveProgram(lt.sessionId,lt.activeProgram),lt.cwd!=null&&Qe.setSessionCwd(lt.sessionId,lt.cwd),lt.shellTitle!=null&&Qe.setSessionShellTitle(lt.sessionId,lt.shellTitle)}),V(K);const ve=U||K[0]?.id||null;Sr(ve),_r("[swiper:restore-complete]",{restoredSessionIds:K.map(lt=>lt.id),nextActiveSessionId:ve})}(async()=>(K.length===0&&await ir.current?.({createIfEmpty:!0}),ce(!1),requestAnimationFrame(()=>gn("restore-finished",{immediate:!0}))))()},[Br,je,bt,z,_r,gn,p,d]),b.useEffect(()=>{if(!p||Y||$.length===0)return;const W=em($.map(U=>({id:U.id,backendSessionId:U.sessionId})),d),N=yh({prioritySessionId:W,activeSessionId:Yt.current,persistedActiveSessionId:ks,firstSessionId:$[0]?.id??null});N&&N!==Yt.current&&Sr(N)},[p,d,Y,ks,$]);const ns=b.useRef([]),Un=b.useRef(!1);Yt.current=Z,b.useEffect(()=>{if(Y)return;const W=ns.current,N=je,U=new Map(W.map(Lt=>[Lt.sessionId,Lt])),K=Yr.getState();for(const Lt of N){const rn=U.get(Lt.sessionId),yn=Yr.getState().sessions.get(Lt.sessionId);Lt.agent!==void 0&&JSON.stringify(Lt.agent)!==JSON.stringify(yn?.agent)&&(yn?.agent==null||JSON.stringify(Lt.agent)!==JSON.stringify(rn?.agent))&&K.setSessionAgentIdentity(Lt.sessionId,Lt.agent),Lt.activeProgram!=null&&Lt.activeProgram!==yn?.activeProgram&&(yn?.activeProgram==null||Lt.activeProgram!==rn?.activeProgram)&&K.setSessionActiveProgram(Lt.sessionId,Lt.activeProgram),Lt.cwd!=null&&Lt.cwd!==yn?.cwd&&(yn?.cwd==null||Lt.cwd!==rn?.cwd)&&K.setSessionCwd(Lt.sessionId,Lt.cwd),Lt.shellTitle!=null&&Lt.shellTitle!==yn?.shellTitle&&(yn?.shellTitle==null||Lt.shellTitle!==rn?.shellTitle)&&K.setSessionShellTitle(Lt.sessionId,Lt.shellTitle)}if(!Un.current){V(Lt=>q2(Lt,N)),ns.current=N,Un.current=!0;return}const fe=new Set(W.map(Lt=>Lt.sessionId)),Qe=new Set(N.map(Lt=>Lt.sessionId)),ve=new Map(W.map(Lt=>[Lt.sessionId,Lt.name]));ns.current=N,V(Lt=>{const rn=q2(Lt,N);return(!Yt.current||!rn.some(yn=>yn.id===Yt.current))&&Sr(rn[0]?.id??null),rn});const lt=N.filter(Lt=>!fe.has(Lt.sessionId)),vt=[...fe].filter(Lt=>!Qe.has(Lt)),br=N.filter(Lt=>fe.has(Lt.sessionId)&&ve.get(Lt.sessionId)!==Lt.name);(lt.length>0||vt.length>0||br.length>0)&&z("[Session] Synced persisted sessions:",{newSessionIds:lt.map(Lt=>Lt.sessionId),removedSessionIds:vt,renamedSessionIds:br.map(Lt=>Lt.sessionId),currentSessionIds:N.map(Lt=>Lt.sessionId)});for(const Lt of N){if(!Lt.backendSessionId)continue;Yr.getState().setTerminalSession(Lt.sessionId,{sessionId:Lt.backendSessionId,cols:80,rows:24,mode:Lt.mode,tmuxSessionName:Lt.tmuxSessionName})}},[je,Y,z]);const En=b.useCallback(async W=>{const N=++pe.current,U=be.current,K=()=>N===pe.current&&U===be.current&&(W?.shouldActivate?.()??!0);try{const fe=Wt.getState(),Qe=Z?{rightOpen:fe.rightOpen,rightPinned:fe.rightPinned,rightSidebarWidth:fe.rightSidebarWidth,rightTab:fe.rightTab}:null,ve=W?.mode==="tmux"||W?.mode==="shell"?W.mode:c,lt=(W?.tmuxSessionName||"").trim(),vt=l.trim(),br=ve==="tmux"?lt||vt||kN():null,Lt=typeof W?.cwd=="string"?W.cwd:null,rn=Z?Yr.getState().sessions.get(Z)?.cwd??null:null,yn=typeof Lt=="string"&&Lt.trim().length>0?Lt:typeof rn=="string"&&rn.trim().length>0?rn:void 0,hn=await Vr({preferredFrontendSessionId:W?.preferredFrontendSessionId,requireExisting:W?.requireExisting===!0,mode:ve,tmuxSessionName:br,cwd:yn,termType:"xterm-256color",createIfEmpty:W?.createIfEmpty===!0},{shouldActivate:K});if(hn.discarded)return W?.onResult?.({ok:!1,error:"unknown"}),null;const Dn=hn.session,zn=hn.terminalSession;!hn.reused&&Qe&&Wt.getState().initializeRightSidebarForSession(Dn.sessionId,zn.cwd??yn??null,Qe);const hr={id:Dn.sessionId,name:Dn.name,customName:Dn.customName===!0,sessionId:zn.sessionId,mode:zn.mode??Dn.mode,tmuxSessionName:zn.tmuxSessionName??Dn.tmuxSessionName},jt=W?.command?.trim();return jt&&We.current.set(hr.id,{backendSessionId:zn.sessionId,command:jt}),V(qn=>CN(qn,hr)),K()&&Sr(hr.id),Yr.getState().setTerminalSession(hr.id,{sessionId:zn.sessionId,cols:80,rows:24,mode:hr.mode,tmuxSessionName:hr.tmuxSessionName,activeProgram:zn.activeProgram,activeProgramRaw:zn.activeProgramRaw,activeProgramSource:zn.activeProgramSource,cwd:zn.cwd}),z("[Session] Inventory opened session:",{frontendSessionId:hr.id,backendSessionId:zn.sessionId,reused:hn.reused,mode:hr.mode,tmuxSessionName:hr.tmuxSessionName}),W?.onResult?.({ok:!0,sessionId:hr.id}),hr.id}catch(fe){return console.error("[Session] Failed to create new session:",fe),W?.onResult?.({ok:!1,error:nC(fe)}),null}},[c,l,Z,Vr,z]);ir.current=En;const kn=b.useCallback((W,N={})=>{be.current+=1,Kn.getState().setActivePane(W);const U=Yt.current,K=!!U&&at.current[U]===!0;if(Sr(W),fr.current&&N.preserveMobileKeyboard===!1){Xr.current=Date.now()+600,U&&(at.current[U]=!1),_t(null),Ge(null);const fe=document.activeElement;fe instanceof HTMLTextAreaElement&&fe.closest(".terminal-viewport-container")&&fe.blur();return}K&&fr.current&&_t(W),$t.current&&(!fr.current||K)&&Ge({sessionId:W,token:Date.now()})},[]),ss=b.useCallback(W=>{Sr(W),Ye(!0),Qt(null)},[]),Wr=b.useCallback(W=>{const N=Yt.current;!N||N===W||(H(U=>rm(U,N,W)),Ye(!1),kn(N,{preserveMobileKeyboard:!1}))},[kn]),tn=b.useCallback(async()=>{const W=Yt.current;if(!W||Ve)return;const N=be.current;ht(!0);const U=Yr.getState().sessions.get(W)?.cwd??void 0,K=await En({cwd:U||void 0,mode:c,shouldActivate:()=>!1});if(ht(!1),!K){Qt(B("common.error"));return}!St.current||N!==be.current||!dr.current.some(fe=>fe.id===W)||(H(fe=>rm(fe,W,K)),Ye(!1),kn(W,{preserveMobileKeyboard:!1}))},[kn,c,En,Ve,B]),G=b.useCallback(W=>{H(N=>mN(N,W)),W&&kn(W,{preserveMobileKeyboard:!1})},[kn]),Me=b.useCallback(W=>{H(N=>pN(N,W)),kn(W,{preserveMobileKeyboard:!1})},[kn]),$e=b.useCallback(W=>{if($.find(U=>U.id===W)){if(be.current+=1,Kn.getState().setActivePane(W),W===Yt.current)return;if(Sr(W),!OE({isMobile:fr.current,viewportReady:Ee.has(W),streamReady:ye.has(W),contentReady:Ne.has(W)})){ze(null),$t.current&&Ge({sessionId:W,token:Date.now()}),z("[Session] Switched to session:",W);return}gt(K=>{if(K.has(W))return K;const fe=new Set(K);return fe.add(W),fe}),ze(W),z("[Session] Switched to session:",W)}},[Ne,z,ye,$,Ee]),Je=b.useCallback((W,N)=>{N.trim()&&(V(U=>U.map(K=>K.id===W?{...K,name:N.trim(),customName:!0}:K)),mn(W,N.trim()))},[mn]),it=b.useCallback(W=>{V(N=>N.map(U=>U.id===W?{...U,customName:!1}:U)),on(W)},[on]),Tt=b.useCallback(W=>{V(N=>{const U=new Map(N.map(ve=>[ve.id,ve])),K=W.map(ve=>U.get(ve)).filter(ve=>ve!==void 0),fe=new Set(W),Qe=N.filter(ve=>!fe.has(ve.id));return[...K,...Qe]}),zr(W),z("[Session] Reordered sessions:",W),requestAnimationFrame(()=>{Ze.current?.update()})},[zr,z]),kt=b.useCallback(async W=>{const N=typeof W=="string"?W:W.sessionId,U=typeof W=="string"?"auto":W.closeMode??"auto",K=$.find(lt=>lt.id===N);if(!K||Vt.current.has(N))return;Vt.current.add(N),be.current+=1;const fe=ax(Hr,N,lt=>lt.id);try{U==="destroy"&&K.mode==="tmux"&&K.tmuxSessionName?(await Ty(K.tmuxSessionName),z("[Session] Destroyed tmux session:",{frontendSessionId:K.id,tmuxSessionName:K.tmuxSessionName})):K.sessionId&&(await yy(K.sessionId),z("[Session] Closed backend terminal:",K.sessionId))}catch(lt){console.error("[Session] Failed to close backend terminal:",lt),zt({sessionId:N,closeMode:U});return}finally{Vt.current.delete(N)}zt(lt=>lt?.sessionId===N?null:lt);const ve=dr.current.filter(lt=>lt.id!==N).some(lt=>lt.id===fe)?fe:ax(dr.current,N,lt=>lt.id);Yt.current===N&&Sr(ve),V(lt=>lt.filter(vt=>vt.id!==N)),qr(N,ve),delete at.current[N],z("[Session] Closed session:",{sessionId:N,closeMode:U})},[$,Hr,qr,z]),Dt=b.useCallback(W=>{if(!W)return;const N=$.filter(U=>U.sessionId===W);if(N.length!==0){N.length>1&&console.warn("[session-invariant] backend matched multiple frontend sessions during cleanup",{backendSessionId:W,frontendSessionIds:N.map(U=>U.id)}),V(U=>{const K=U.filter(fe=>fe.sessionId!==W);return K.length!==U.length&&!K.some(Qe=>Qe.id===Z)&&Sr(K.length>0?K[0].id:null),K});for(const U of N)qr(U.id),delete at.current[U.id];z("[Session] Backend gone, dropped local session(s):",N.map(U=>U.id))}},[$,Z,qr,z]);b.useEffect(()=>{const W=hr=>{En(hr.detail)},N=hr=>{$e(hr.detail)},U=()=>{const hr=Yt.current;!hr||fr.current||Ge({sessionId:hr,token:Date.now()})},K=hr=>{const jt=hr;jt.detail&&ss(jt.detail)},fe=hr=>{const jt=hr.detail;G(jt??Yt.current??void 0)},Qe=hr=>{const jt=hr.detail;jt&&Me(jt)},ve=hr=>{const jt=hr.detail,Bn=typeof jt=="string"?jt:jt?.layout,qn=typeof jt=="string"?Yt.current:jt?.sessionId;Bn!=="horizontal"&&Bn!=="vertical"&&Bn!=="grid"||H(Wa=>Wa.map(Qn=>Qn.sessionIds.includes(qn??"")?{...Qn,layout:Bn}:Qn))},lt=hr=>{const Bn=hr.detail?.direction;if(Bn!=="prev"&&Bn!=="next")return;const qn=ps.current;if(qn.length<=1)return;const Wa=Yt.current,Qn=Wa?qn.findIndex(Ga=>Ga.id===Wa):-1,da=((Qn>=0?Qn:0)+(Bn==="next"?1:-1)+qn.length)%qn.length,bs=qn[da]?.id;bs&&bs!==Wa&&$e(bs)},vt=hr=>{kt(hr.detail)},br=hr=>{Dt(hr.detail)},Lt=hr=>{const jt=hr;!jt.detail?.sessionId||!jt.detail?.name||Je(jt.detail.sessionId,jt.detail.name)},rn=hr=>{const jt=hr;jt.detail?.sessionId&&it(jt.detail.sessionId)},yn=hr=>{const jt=hr;jt.detail?.sessionIds&&Tt(jt.detail.sessionIds)},hn=hr=>{const jt=hr.detail;!jt?.workspaceId||!Array.isArray(jt.sessionIds)||H(Bn=>gN(Bn,jt.workspaceId,jt.sessionIds))},Dn=hr=>{const jt=hr.detail;!jt?.workspaceId||typeof jt.name!="string"||H(Bn=>xN(Bn,jt.workspaceId,jt.name))},zn=hr=>{const jt=hr.detail;!jt?.primaryId||!jt.secondaryId||jt.primaryId===jt.secondaryId||(H(Bn=>rm(Bn,jt.primaryId,jt.secondaryId)),kn(jt.primaryId,{preserveMobileKeyboard:!1}))};return window.addEventListener("new-terminal-session",W),window.addEventListener("switch-terminal-session",N),window.addEventListener("focus-active-terminal-session",U),window.addEventListener("open-terminal-split-chooser",K),window.addEventListener("close-terminal-split",fe),window.addEventListener("remove-terminal-split-pane",Qe),window.addEventListener("set-terminal-split-direction",ve),window.addEventListener("cycle-terminal-session",lt),window.addEventListener("close-terminal-session",vt),window.addEventListener("close-terminal-session-by-backend",br),window.addEventListener("rename-terminal-session",Lt),window.addEventListener("reset-terminal-session-name",rn),window.addEventListener("reorder-terminal-session",yn),window.addEventListener("reorder-terminal-split-workspace",hn),window.addEventListener("rename-terminal-split-workspace",Dn),window.addEventListener("combine-terminal-split-sessions",zn),()=>{window.removeEventListener("new-terminal-session",W),window.removeEventListener("switch-terminal-session",N),window.removeEventListener("focus-active-terminal-session",U),window.removeEventListener("open-terminal-split-chooser",K),window.removeEventListener("close-terminal-split",fe),window.removeEventListener("remove-terminal-split-pane",Qe),window.removeEventListener("set-terminal-split-direction",ve),window.removeEventListener("cycle-terminal-session",lt),window.removeEventListener("close-terminal-session",vt),window.removeEventListener("close-terminal-session-by-backend",br),window.removeEventListener("rename-terminal-session",Lt),window.removeEventListener("reset-terminal-session-name",rn),window.removeEventListener("reorder-terminal-session",yn),window.removeEventListener("reorder-terminal-split-workspace",hn),window.removeEventListener("rename-terminal-split-workspace",Dn),window.removeEventListener("combine-terminal-split-sessions",zn)}},[kn,En,$e,ss,G,Me,kt,Dt,Je,it,Tt]),b.useEffect(()=>{if(!Tr||q)return;const W=N=>{if(!gC(N,B1())||!(N.ctrlKey||N.metaKey)||!N.shiftKey)return;if(Tr.layout==="horizontal"?N.key==="ArrowLeft"||N.key==="ArrowRight":Tr.layout==="vertical"?N.key==="ArrowUp"||N.key==="ArrowDown":N.key.startsWith("Arrow")){N.preventDefault(),N.stopPropagation();const K=Tr.sessionIds.indexOf(Yt.current??""),fe=N.key==="ArrowLeft"||N.key==="ArrowUp"?-1:1,Qe=(Math.max(0,K)+fe+Tr.sessionIds.length)%Tr.sessionIds.length,ve=Tr.sessionIds[Qe];if(!ve)return;kn(ve);return}N.key==="Backspace"&&(N.preventDefault(),N.stopPropagation(),G(Yt.current??void 0))};return window.addEventListener("keydown",W,!0),()=>window.removeEventListener("keydown",W,!0)},[kn,Tr,G,q]);const ft=W=>{const N=Yr.getState().sessions.get(W.id);return il(W,N?.activeProgram??null,N?.cwd??null,void 0,N?.shellTitle??null,N?.promptState??null)},Bt=(W,N={})=>{const U=W.id===Z&&!ee?.startsWith("@collaboration:"),K=Jr.has(W.id)&&!N.hidden,fe=p&&PE({sessionId:W.id,foregroundSessionId:Dr,visibleSessionIds:Jr,deferredViewportSessionIds:q?cn:Xn}),Qe=QE({sessionId:W.id,foregroundSessionId:Dr,foregroundReady:xn,isVisible:K})&&p,ve=zE({sessionId:W.id,foregroundSessionId:Dr,requestToken:qe.token,foregroundCompletedToken:Nt,isVisible:X.has(W.id)})&&p,lt=K||W.id===Dr||Xn.has(W.id)?0:en.get(W.id)??qh;return s.jsxs("div",{className:`relative flex h-full min-h-0 min-w-0 flex-col overflow-hidden ${N.hidden?"invisible pointer-events-none":""}`,style:N.containerStyle,"aria-hidden":N.hidden||void 0,onPointerDownCapture:()=>{K&&G2(U,()=>kn(W.id))},onWheelCapture:()=>{G2(U,()=>kn(W.id))},children:[N.showPaneTitle&&s.jsx(lN,{session:W,active:U,onActivate:()=>kn(W.id),onToggleRightSidebar:U?x:void 0}),s.jsx("div",{className:"min-h-0 flex-1 app-chrome-bg",children:fe&&s.jsx(oN,{sessionId:W.id,mode:W.mode,tmuxSessionName:W.tmuxSessionName,terminalSettings:e,colorTheme:t,toolbarPresets:r,isActive:U,focusSuspended:_e!==null,deferCursorUntilPositioned:_e===W.id||W.mode==="tmux"&&!Ne.has(W.id),isLayoutVisible:K,initialConnectEnabled:Qe&&ve,resumeRequestEnabled:ve,suppressKeyboard:N.suppressKeyboard,keyboardPortalTarget:N.keyboardPortalTarget,sharedMobileKeyboardLayout:N.sharedMobileKeyboardLayout,suppressPageFlipRefresh:N.suppressPageFlipRefresh,focusRequestToken:Ie?.sessionId===W.id?Ie.token:0,resumeRequestToken:qe.token,resumeRequestReason:qe.reason,forceResumeReconnect:qe.forceForegroundReconnect&&X.has(W.id),resumeRequestDelayMs:X.has(W.id)?0:N.hidden?qh:en.get(W.id)??qh,initialConnectDelayMs:lt,onStreamReadyChange:Et,onStreamConnected:tr,onViewportReadyChange:jr,onContentReadyChange:cr,onKeyboardVisibilityChange:Jn,showDebug:n,onStatusChange:U?S:void 0})})]},W.id)};return s.jsxs("div",{className:"relative h-full flex flex-col",children:[wt&&$.some(W=>W.id===wt.sessionId)&&s.jsxs("div",{role:"alert",className:"fixed inset-x-3 top-[calc(var(--safe-top-inset)+0.75rem)] z-toast mx-auto flex max-w-lg items-center gap-3 rounded-xl border border-destructive/30 bg-surface-elevated px-4 py-3 text-[12px] text-foreground shadow-lg",children:[s.jsx("span",{className:"min-w-0 flex-1",children:B("tab.closeFailed",{name:$.find(W=>W.id===wt.sessionId).name})}),s.jsx("button",{type:"button",className:"shrink-0 rounded-lg px-2 py-1 text-primary hover:bg-surface-2",onClick:()=>{kt(wt)},children:B("common.retry")}),s.jsx("button",{type:"button",className:"shrink-0 rounded-lg p-1 hover:bg-surface-2","aria-label":B("common.close"),onClick:()=>zt(null),children:s.jsx(In,{size:16})})]}),Er&&s.jsx("section",{className:"fixed inset-x-3 top-[calc(var(--safe-top-inset)+0.75rem)] z-toast mx-auto max-w-lg rounded-2xl border border-warning/30 bg-surface-elevated px-4 py-3.5 shadow-[0_20px_60px_var(--app-shadow-strong)]",role:"alert","aria-live":"assertive",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("span",{className:"mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-warning/15 text-warning",children:s.jsx(P1,{size:18})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("h2",{className:"text-[13px] font-semibold text-foreground",children:B("tab.tmuxRecoveryTitle",{count:Er.sessions.length})}),s.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-muted-foreground",children:B("tab.tmuxRecoveryHint")}),s.jsx("p",{className:"mt-1.5 truncate text-[10px] text-foreground/70",children:Er.sessions.map(W=>W.name).join(" · ")}),It&&s.jsx("p",{className:"mt-2 text-[10px] text-destructive",children:It}),s.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[s.jsxs("button",{type:"button",disabled:Kt!==null,onClick:()=>{re()},className:"inline-flex min-h-9 items-center gap-1.5 rounded-lg bg-primary px-3 text-[11px] font-medium text-primary-foreground transition active:opacity-80 disabled:opacity-50",children:[s.jsx(Uy,{size:13,className:Kt==="restore"?"animate-spin":""}),B(Kt==="restore"?"tab.tmuxRecoveryRestoring":"tab.tmuxRecoveryRestoreAll")]}),s.jsx("button",{type:"button",disabled:Kt!==null,onClick:()=>{mt()},className:"inline-flex min-h-9 items-center rounded-lg px-3 text-[11px] text-muted-foreground transition hover:bg-surface-2 hover:text-foreground disabled:opacity-50",children:B("tab.tmuxRecoveryDismiss")})]})]})]})}),s.jsx("div",{className:"flex-1 overflow-hidden",children:s.jsx(dA,{onSwiper:W=>{Ze.current=W,W.allowTouchMove=Mr.length>1&&!Ar&&!ae,_r("[swiper:on-swiper]",{allowTouchMove:W.allowTouchMove}),requestAnimationFrame(()=>Lr("on-swiper"))},onSlideChange:kr,onTouchStart:(W,N)=>{const U=Z2(N),K=U==="touch"||U==="pen"||U==="unknown";O("[swipe:touch-start]",{pointerType:U,allowed:K}),_r("[swiper:touch-start]",{pointerType:U,allowed:K}),K&&(Gn(),xt.current=!0,yt.current=!0)},onTouchEnd:(W,N)=>{const U=Z2(N),K=U==="touch"||U==="pen"||U==="unknown";O("[swipe:touch-end]",{pointerType:U,allowed:K}),_r("[swiper:touch-end]",{pointerType:U,allowed:K}),K&&(xt.current=!1,Vn("touch-end"))},onTransitionEnd:()=>{const W=Ze.current;if(xt.current){_r("[swiper:transition-end-during-touch]");return}if(yt.current&&W&&!TN(W,me.current)){_r("[swiper:transition-end-deferred]");return}Gn(),yt.current=!1,_r("[swiper:transition-end]")},initialSlide:Math.max(0,Or),speed:d1,slidesPerView:1,resistanceRatio:.82,threshold:8,longSwipesRatio:.2,touchAngle:45,touchStartPreventDefault:!1,simulateTouch:!1,noSwiping:!0,noSwipingSelector:"[data-mobile-keyboard='true']",className:"terminal-session-swiper h-full",children:Mr.map(W=>{const N=W.workspace,U=!!N&&W.sessions.length>=2,K=q?qt?"horizontal":"vertical":N?.layout??"horizontal",fe=q&&Ke?W.sessions.some(ve=>ve.id===Ke):!1,Qe=W.sessions.some(ve=>ve.id===Z)?Z:W.sessions[0]?.id;return s.jsx(hA,{className:"h-full",children:s.jsx("div",{className:"h-full min-w-0","data-pinned-right-sidebar-inset":ln.get(W.key)??0,style:{paddingRight:ln.get(W.key)??0,paddingTop:y&&!U?"2.5rem":void 0},children:U?s.jsxs("div",{className:"flex h-full min-h-0 min-w-0 flex-col bg-[var(--chrome-bg)]",style:q?{transform:"translateY(var(--kb-translate-y, 0px))",transition:"none"}:void 0,children:[s.jsx(vx,{layoutId:W.key,preset:N?.layout??"horizontal",initialTree:cC(W.sessions.map(ve=>ve.id),K,N?.ratios,N?.gridColumnRatios,N?.gridRowRatios),mobile:q,focusId:fe?Ke:null,panes:W.sessions.map(ve=>({id:ve.id,content:Bt(ve,{showPaneTitle:!q,suppressKeyboard:q&&ve.id!==Qe,keyboardPortalTarget:q?De:null,sharedMobileKeyboardLayout:q,suppressPageFlipRefresh:!0})}))}),q&&s.jsx("div",{ref:nr,className:"relative shrink-0 app-chrome-bg","data-split-keyboard-host":"true"})]}):s.jsx(vx,{layoutId:W.key,preset:N?.layout??"horizontal",mobile:q,panes:[{id:W.sessions[0].id,content:Bt(W.sessions[0])}]})})},W.key)})})}),ae&&Z&&s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"fixed inset-0 z-modal-backdrop bg-[var(--app-backdrop-soft)] backdrop-blur-sm",onClick:()=>Ye(!1),"aria-label":B("common.close")}),s.jsxs("section",{ref:et,tabIndex:-1,className:"fixed inset-x-3 bottom-3 z-modal-panel mx-auto max-h-[min(78svh,620px)] max-w-md overflow-hidden rounded-2xl border border-border/20 bg-surface shadow-[0_24px_70px_var(--app-shadow-strong)] sm:bottom-auto sm:top-1/2 sm:-translate-y-1/2",style:{paddingBottom:"var(--safe-bottom-inset)"},role:"dialog","aria-modal":"true","aria-label":B("tab.splitTitle"),children:[s.jsxs("header",{className:"flex items-start gap-3 border-b border-border/20 px-4 py-3.5",children:[s.jsx("div",{className:"mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-xl bg-primary/15 text-primary",children:s.jsx(Il,{size:17})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("h2",{className:"text-[14px] font-semibold text-foreground",children:B("tab.splitTitle")}),s.jsx("p",{className:"mt-0.5 text-[11px] leading-relaxed text-muted-foreground",children:B("tab.splitExistingHint")})]}),s.jsx("button",{type:"button",className:"inline-flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground transition hover:bg-surface-2 hover:text-foreground",onClick:()=>Ye(!1),"aria-label":B("common.close"),children:s.jsx(In,{size:16})})]}),s.jsxs("div",{className:"max-h-[calc(min(78svh,620px)-72px)] overflow-y-auto overscroll-contain p-2",children:[s.jsxs("button",{type:"button",disabled:Ve,onClick:()=>{tn()},className:"flex w-full items-center gap-3 rounded-xl px-3 py-3 text-left transition hover:bg-surface-2 active:bg-surface-elevated disabled:opacity-60",children:[s.jsx("span",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-primary/15 text-primary",children:s.jsx(zs,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-[13px] font-medium text-foreground",children:B("tab.splitNew")}),s.jsx("span",{className:"mt-0.5 block text-[11px] text-muted-foreground",children:B("tab.splitNewHint")})]})]}),Ce.filter(W=>W.id!==Tr?.id).length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"px-3 pb-1 pt-3 text-[10px] font-medium uppercase tracking-[0.12em] text-muted-foreground",children:B("tab.splitExistingGroups")}),Ce.filter(W=>W.id!==Tr?.id).map((W,N)=>{const U=W.sessionIds.flatMap(Qe=>{const ve=$.find(lt=>lt.id===Qe);return ve?[ve]:[]});if(U.length<2)return null;const K=W.name||`${B("tab.splitWorkspace")} ${N+1}`,fe=U.map(Qe=>ft(Qe).primary).join(" · ");return s.jsxs("button",{type:"button",onClick:()=>Wr(U[0].id),className:"group flex w-full items-center gap-3 rounded-xl px-3 py-2.5 text-left transition hover:bg-surface-2 active:bg-surface-elevated",children:[s.jsx("span",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary",children:s.jsx(Il,{size:15})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:"min-w-0 flex-1 truncate text-[12px] font-medium text-foreground",children:K}),s.jsx("span",{className:"shrink-0 rounded-full bg-primary/10 px-1.5 py-0.5 text-[9px] font-medium text-primary",children:B("tab.splitOccupied")})]}),s.jsxs("span",{className:"mt-0.5 block truncate text-[10px] text-muted-foreground",children:[B("tab.sessionCount",{count:U.length})," · ",fe]})]}),s.jsx(pi,{size:14,className:"text-primary opacity-0 transition group-hover:opacity-100"})]},W.id)})]}),s.jsx("div",{className:"px-3 pb-1 pt-3 text-[10px] font-medium uppercase tracking-[0.12em] text-muted-foreground",children:B("tab.splitAvailableSessions")}),$.filter(W=>!Ce.some(N=>N.sessionIds.includes(W.id))&&W.id!==Z).length===0&&Ce.filter(W=>W.id!==Tr?.id).length===0?s.jsx("p",{className:"px-3 py-4 text-[12px] text-muted-foreground",children:B("tab.splitNoOtherSessions")}):$.filter(W=>!Ce.some(N=>N.sessionIds.includes(W.id))&&W.id!==Z).map(W=>{const N=Jt.get(W.id)??null,U=ft(W);return s.jsxs("button",{type:"button",onClick:()=>Wr(W.id),className:"group flex w-full items-center gap-3 rounded-xl px-3 py-2.5 text-left transition hover:bg-surface-2 active:bg-surface-elevated",children:[s.jsx("span",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-surface-2 text-muted-foreground",children:N?s.jsx(Vc,{size:15}):s.jsx(Il,{size:15})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block truncate text-[12px] font-medium text-foreground",children:U.primary}),s.jsx("span",{className:"mt-0.5 block truncate text-[10px] text-muted-foreground",children:N?Ku(N)??N:W.name})]}),s.jsx(pi,{size:14,className:"text-primary opacity-0 transition group-hover:opacity-100"})]},W.id)})]})]})]}),Gt&&s.jsx("div",{className:"fixed inset-x-3 bottom-4 z-toast mx-auto max-w-md rounded-xl border border-border/20 bg-surface-elevated px-4 py-3 text-center text-[12px] text-foreground shadow-lg",children:Gt})]})},IN={sm:"h-4 w-7",md:"h-6 w-10"},EN={sm:"h-3 w-3",md:"h-5 w-5"},NN={sm:"translate-x-3",md:"translate-x-4"};function ll({checked:e,disabled:t=!1,size:r="md",className:n=""}){return s.jsx("span",{"aria-hidden":"true",className:`inline-flex shrink-0 items-center rounded-full transition ${IN[r]} ${e?"bg-primary":"bg-surface-elevated"} ${t?"opacity-50":""} ${n}`,children:s.jsx("span",{className:`mx-0.5 inline-block rounded-full bg-[var(--background)] shadow transition ${EN[r]} ${e?NN[r]:""}`})})}function la(e){return`Minified Redux error #${e}; visit https://redux.js.org/Errors?code=${e} for the full message or use the non-minified dev environment for full errors. `}var RN=typeof Symbol=="function"&&Symbol.observable||"@@observable",X2=RN,J2=()=>Math.random().toString(36).substring(7).split("").join("."),MN={INIT:`@@redux/INIT${J2()}`,REPLACE:`@@redux/REPLACE${J2()}`},e5=MN;function jN(e){if(typeof e!="object"||e===null)return!1;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t||Object.getPrototypeOf(e)===null}function dv(e,t,r){if(typeof e!="function")throw new Error(la(2));if(typeof t=="function"&&typeof r=="function"||typeof r=="function"&&typeof arguments[3]=="function")throw new Error(la(0));if(typeof t=="function"&&typeof r>"u"&&(r=t,t=void 0),typeof r<"u"){if(typeof r!="function")throw new Error(la(1));return r(dv)(e,t)}let n=e,a=t,c=new Map,l=c,d=0,p=!1;function m(){l===c&&(l=new Map,c.forEach((E,R)=>{l.set(R,E)}))}function x(){if(p)throw new Error(la(3));return a}function y(E){if(typeof E!="function")throw new Error(la(4));if(p)throw new Error(la(5));let R=!0;m();const B=d++;return l.set(B,E),function(){if(R){if(p)throw new Error(la(6));R=!1,m(),l.delete(B),c=null}}}function w(E){if(!jN(E))throw new Error(la(7));if(typeof E.type>"u")throw new Error(la(8));if(typeof E.type!="string")throw new Error(la(17));if(p)throw new Error(la(9));try{p=!0,a=n(a,E)}finally{p=!1}return(c=l).forEach(B=>{B()}),E}function v(E){if(typeof E!="function")throw new Error(la(10));n=E,w({type:e5.REPLACE})}function S(){const E=y;return{subscribe(R){if(typeof R!="object"||R===null)throw new Error(la(11));function B(){const O=R;O.next&&O.next(x())}return B(),{unsubscribe:E(B)}},[X2](){return this}}}return w({type:e5.INIT}),{dispatch:w,subscribe:y,getState:x,replaceReducer:v,[X2]:S}}function t5(e,t){return function(...r){return t(e.apply(this,r))}}function r5(e,t){if(typeof e=="function")return t5(e,t);if(typeof e!="object"||e===null)throw new Error(la(16));const r={};for(const n in e){const a=e[n];typeof a=="function"&&(r[n]=t5(a,t))}return r}function hv(...e){return e.length===0?t=>t:e.length===1?e[0]:e.reduce((t,r)=>(...n)=>t(r(...n)))}function DN(...e){return t=>(r,n)=>{const a=t(r,n);let c=()=>{throw new Error(la(15))};const l={getState:a.getState,dispatch:(p,...m)=>c(p,...m)},d=e.map(p=>p(l));return c=hv(...d)(a.dispatch),{...a,dispatch:c}}}var sm={exports:{}},im={};var n5;function BN(){if(n5)return im;n5=1;var e=SA();function t(p,m){return p===m&&(p!==0||1/p===1/m)||p!==p&&m!==m}var r=typeof Object.is=="function"?Object.is:t,n=e.useSyncExternalStore,a=e.useRef,c=e.useEffect,l=e.useMemo,d=e.useDebugValue;return im.useSyncExternalStoreWithSelector=function(p,m,x,y,w){var v=a(null);if(v.current===null){var S={hasValue:!1,value:null};v.current=S}else S=v.current;v=l(function(){function E($){if(!R){if(R=!0,B=$,$=y($),w!==void 0&&S.hasValue){var V=S.value;if(w(V,$))return z=V}return z=$}if(V=z,r(B,$))return V;var Z=y($);return w!==void 0&&w(V,Z)?(B=$,V):(B=$,z=Z)}var R=!1,B,z,O=x===void 0?null:x;return[function(){return E(m())},O===null?void 0:function(){return E(O())}]},[m,x,y,w]);var L=n(p,v[0],v[1]);return c(function(){S.hasValue=!0,S.value=L},[L]),d(L),L},im}var s5;function QN(){return s5||(s5=1,sm.exports=BN()),sm.exports}QN();var PN=b.version.startsWith("19"),ON=Symbol.for(PN?"react.transitional.element":"react.element"),FN=Symbol.for("react.portal"),$N=Symbol.for("react.fragment"),UN=Symbol.for("react.strict_mode"),zN=Symbol.for("react.profiler"),HN=Symbol.for("react.consumer"),WN=Symbol.for("react.context"),fv=Symbol.for("react.forward_ref"),GN=Symbol.for("react.suspense"),VN=Symbol.for("react.suspense_list"),ng=Symbol.for("react.memo"),qN=Symbol.for("react.lazy"),YN=fv,ZN=ng;function KN(e){if(typeof e=="object"&&e!==null){const{$$typeof:t}=e;switch(t){case ON:switch(e=e.type,e){case $N:case zN:case UN:case GN:case VN:return e;default:switch(e=e&&e.$$typeof,e){case WN:case fv:case qN:case ng:return e;case HN:return e;default:return t}}case FN:return t}}}function XN(e){return KN(e)===ng}function JN(e,t,r,n,{areStatesEqual:a,areOwnPropsEqual:c,areStatePropsEqual:l}){let d=!1,p,m,x,y,w;function v(B,z){return p=B,m=z,x=e(p,m),y=t(n,m),w=r(x,y,m),d=!0,w}function S(){return x=e(p,m),t.dependsOnOwnProps&&(y=t(n,m)),w=r(x,y,m),w}function L(){return e.dependsOnOwnProps&&(x=e(p,m)),t.dependsOnOwnProps&&(y=t(n,m)),w=r(x,y,m),w}function E(){const B=e(p,m),z=!l(B,x);return x=B,z&&(w=r(x,y,m)),w}function R(B,z){const O=!c(z,m),$=!a(B,p,z,m);return p=B,m=z,O&&$?S():O?L():$?E():w}return function(z,O){return d?R(z,O):v(z,O)}}function eR(e,{initMapStateToProps:t,initMapDispatchToProps:r,initMergeProps:n,...a}){const c=t(e,a),l=r(e,a),d=n(e,a);return JN(c,l,d,e,a)}function tR(e,t){const r={};for(const n in e){const a=e[n];typeof a=="function"&&(r[n]=(...c)=>t(a(...c)))}return r}function p1(e){return function(r){const n=e(r);function a(){return n}return a.dependsOnOwnProps=!1,a}}function i5(e){return e.dependsOnOwnProps?!!e.dependsOnOwnProps:e.length!==1}function pv(e,t){return function(n,{displayName:a}){const c=function(d,p){return c.dependsOnOwnProps?c.mapToProps(d,p):c.mapToProps(d,void 0)};return c.dependsOnOwnProps=!0,c.mapToProps=function(d,p){c.mapToProps=e,c.dependsOnOwnProps=i5(e);let m=c(d,p);return typeof m=="function"&&(c.mapToProps=m,c.dependsOnOwnProps=i5(m),m=c(d,p)),m},c}}function sg(e,t){return(r,n)=>{throw new Error(`Invalid value of type ${typeof e} for ${t} argument when connecting component ${n.wrappedComponentName}.`)}}function rR(e){return e&&typeof e=="object"?p1(t=>tR(e,t)):e?typeof e=="function"?pv(e):sg(e,"mapDispatchToProps"):p1(t=>({dispatch:t}))}function nR(e){return e?typeof e=="function"?pv(e):sg(e,"mapStateToProps"):p1(()=>({}))}function sR(e,t,r){return{...r,...e,...t}}function iR(e){return function(r,{displayName:n,areMergedPropsEqual:a}){let c=!1,l;return function(p,m,x){const y=e(p,m,x);return c?a(y,l)||(l=y):(c=!0,l=y),l}}}function aR(e){return e?typeof e=="function"?iR(e):sg(e,"mergeProps"):()=>sR}function oR(e){e()}function lR(){let e=null,t=null;return{clear(){e=null,t=null},notify(){oR(()=>{let r=e;for(;r;)r.callback(),r=r.next})},get(){const r=[];let n=e;for(;n;)r.push(n),n=n.next;return r},subscribe(r){let n=!0;const a=t={callback:r,next:null,prev:t};return a.prev?a.prev.next=a:e=a,function(){!n||e===null||(n=!1,a.next?a.next.prev=a.prev:t=a.prev,a.prev?a.prev.next=a.next:e=a.next)}}}}var a5={notify(){},get:()=>[]};function mv(e,t){let r,n=a5,a=0,c=!1;function l(L){x();const E=n.subscribe(L);let R=!1;return()=>{R||(R=!0,E(),y())}}function d(){n.notify()}function p(){S.onStateChange&&S.onStateChange()}function m(){return c}function x(){a++,r||(r=t?t.addNestedSub(p):e.subscribe(p),n=lR())}function y(){a--,r&&a===0&&(r(),r=void 0,n.clear(),n=a5)}function w(){c||(c=!0,x())}function v(){c&&(c=!1,y())}const S={addNestedSub:l,notifyNestedSubs:d,handleChangeWrapper:p,isSubscribed:m,trySubscribe:w,tryUnsubscribe:v,getListeners:()=>n};return S}var cR=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",uR=cR(),dR=()=>typeof navigator<"u"&&navigator.product==="ReactNative",hR=dR(),fR=()=>uR||hR?b.useLayoutEffect:b.useEffect,Af=fR();function o5(e,t){return e===t?e!==0||t!==0||1/e===1/t:e!==e&&t!==t}function am(e,t){if(o5(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;const r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let a=0;a<r.length;a++)if(!Object.prototype.hasOwnProperty.call(t,r[a])||!o5(e[r[a]],t[r[a]]))return!1;return!0}var pR={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},mR={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},gR={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},gv={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},xR={[YN]:gR,[ZN]:gv};function l5(e){return XN(e)?gv:xR[e.$$typeof]||pR}var bR=Object.defineProperty,yR=Object.getOwnPropertyNames,c5=Object.getOwnPropertySymbols,vR=Object.getOwnPropertyDescriptor,wR=Object.getPrototypeOf,u5=Object.prototype;function m1(e,t){if(typeof t!="string"){if(u5){const c=wR(t);c&&c!==u5&&m1(e,c)}let r=yR(t);c5&&(r=r.concat(c5(t)));const n=l5(e),a=l5(t);for(let c=0;c<r.length;++c){const l=r[c];if(!mR[l]&&!(a&&a[l])&&!(n&&n[l])){const d=vR(t,l);try{bR(e,l,d)}catch{}}}}return e}var AR=Symbol.for("react-redux-context"),TR=typeof globalThis<"u"?globalThis:{};function SR(){if(!b.createContext)return{};const e=TR[AR]??=new Map;let t=e.get(b.createContext);return t||(t=b.createContext(null),e.set(b.createContext,t)),t}var xv=SR(),CR=[null,null];function _R(e,t,r){Af(()=>e(...t),r)}function kR(e,t,r,n,a,c){e.current=n,r.current=!1,a.current&&(a.current=null,c())}function LR(e,t,r,n,a,c,l,d,p,m,x){if(!e)return()=>{};let y=!1,w=null;const v=()=>{if(y||!d.current)return;const L=t.getState();let E,R;try{E=n(L,a.current)}catch(B){R=B,w=B}R||(w=null),E===c.current?l.current||m():(c.current=E,p.current=E,l.current=!0,x())};return r.onStateChange=v,r.trySubscribe(),v(),()=>{if(y=!0,r.tryUnsubscribe(),r.onStateChange=null,w)throw w}}function IR(e,t){return e===t}function ER(e,t,r,{pure:n,areStatesEqual:a=IR,areOwnPropsEqual:c=am,areStatePropsEqual:l=am,areMergedPropsEqual:d=am,forwardRef:p=!1,context:m=xv}={}){const x=m,y=nR(e),w=rR(t),v=aR(r),S=!!e;return E=>{const R=E.displayName||E.name||"Component",B=`Connect(${R})`,z={shouldHandleStateChanges:S,displayName:B,wrappedComponentName:R,WrappedComponent:E,initMapStateToProps:y,initMapDispatchToProps:w,initMergeProps:v,areStatesEqual:a,areStatePropsEqual:l,areOwnPropsEqual:c,areMergedPropsEqual:d};function O(Z){const[le,be,pe]=b.useMemo(()=>{const{reactReduxForwardedRef:Ze,...at}=Z;return[Z.context,Ze,at]},[Z]),ee=b.useMemo(()=>{let Ze=x;return le?.Consumer,Ze},[le,x]),_e=b.useContext(ee),ze=!!Z.store&&!!Z.store.getState&&!!Z.store.dispatch,Y=!!_e&&!!_e.store,ce=ze?Z.store:_e.store,qe=Y?_e.getServerState:ce.getState,we=b.useMemo(()=>eR(ce.dispatch,z),[ce]),[ye,Le]=b.useMemo(()=>{if(!S)return CR;const Ze=mv(ce,ze?void 0:_e.subscription),at=Ze.notifyNestedSubs.bind(Ze);return[Ze,at]},[ce,ze,_e]),Be=b.useMemo(()=>ze?_e:{..._e,subscription:ye},[ze,_e,ye]),ne=b.useRef(void 0),Fe=b.useRef(pe),ke=b.useRef(void 0),Ee=b.useRef(!1),Pe=b.useRef(!1),Ne=b.useRef(void 0);Af(()=>(Pe.current=!0,()=>{Pe.current=!1}),[]);const oe=b.useMemo(()=>()=>ke.current&&pe===Fe.current?ke.current:we(ce.getState(),pe),[ce,pe]),We=b.useMemo(()=>at=>ye?LR(S,ce,ye,we,Fe,ne,Ee,Pe,ke,Le,at):()=>{},[ye]);_R(kR,[Fe,ne,Ee,pe,ke,Le]);let nt;try{nt=b.useSyncExternalStore(We,oe,qe?()=>we(qe(),pe):oe)}catch(Ze){throw Ne.current&&(Ze.message+=`
|
|
78
78
|
The error may be correlated with this previous error:
|
|
79
79
|
${Ne.current.stack}
|
|
80
80
|
|
|
@@ -136,7 +136,7 @@ ${Ne.current.stack}
|
|
|
136
136
|
`).trim()).find(Boolean),c=typeof n=="string"&&n.trim()?n.trim():a,l=Number.isFinite(t.createdAt)&&t.createdAt>0&&Number.isFinite(new Date(t.createdAt).getTime());return{status:t.status,label:Nf[t.status]??"成员明确报告",createdAt:l?t.createdAt:null,content:r,summary:c?c.slice(0,512):"报告摘要未提供,请查看详情中的原始报告"}}function Jf(e){if(e.status!=="open")return[];const t=w6(e),r=t&&["blocked","failed"].includes(t.status)?{source:"member",label:t.label,content:t.content,summary:t.summary,createdAt:t.createdAt}:null,n=r&&(e.automationIssueSource==="member-report"||!e.summaryOnly&&!!t?.content&&e.automationIssue===t.content.slice(0,1e3)),a=r&&!t?.content&&!e.automationIssueSource,c=e.automationIssue&&!n?{source:a?"unknown":"system",label:a?"服务记录(来源待核对)":e.automationIssue.startsWith("消息投递")?"投递需要处理":e.activeAttemptId?"自动安排受阻":"执行准备受阻",content:e.automationIssue,summary:e.automationIssue}:null;return[r,c].filter(l=>!!l)}function rQ(e){return Jf(e)[0]??null}function Kc(e){if(e.status==="accepted")return e.completionMode==="reviewed"?"独立评审通过":"已验收";if(e.status==="closed")return"已关闭";if(e.purpose==="automation"){const l={unassigned:"后台记录待分派",awaiting_report:"后台执行等待明确报告",ack:"执行成员已确认接手",working:"成员报告进行中",blocked:"成员报告受阻",failed:"成员报告失败",complete:"执行已交付"};return e.execution?l[e.execution.status]:"后台执行记录"}if(e.decisions.some(l=>l.status==="pending"))return"需要你回答";const t=rQ(e);if(t)return t.label;if(e.workflow?.paused)return"自动安排已暂停";const r=e.attempts.find(l=>l.id===e.activeAttemptId),n=e.artifacts.filter(l=>l.kind==="plan"&&l.attemptId===e.activeAttemptId).at(-1);if(n&&n.id!==e.approvedPlanArtifactId)return"需要你确认方案";const a=e.artifacts.filter(l=>l.kind==="result"&&l.attemptId===e.activeAttemptId).at(-1),c=a&&e.events.some(l=>l.kind==="revise"&&l.attemptId===e.activeAttemptId&&l.createdAt>=a.createdAt);if(a&&!c){const l=e.artifacts.filter(d=>d.kind==="review"&&d.reviewsArtifactId===a.id).at(-1);return e.workflow&&l?.verdict!=="pass"?l?.verdict==="changes"?"评审要求修改":"等待独立评审":e.workflow?.kind==="step"?"评审通过 · 等待接续":"等待你验收"}return c?e.events.some(l=>l.kind==="revise"&&l.source==="user"&&l.attemptId===e.activeAttemptId&&l.createdAt>=a.createdAt)?"已要求跟进 · 等待新结果":"已要求修改 · 等待新结果":r?r.report?Nf[r.report.status]:["failed","expired"].includes(r.deliveryStatus??"")?"投递未成功":e.deliveries.some(l=>l.attemptId===e.activeAttemptId&&l.error)?"投递需要关注":r.deliveryStatus==="delivered"?"已写入终端 · 等待回复":"等待投递":e.scheduledAssignee?e.dependsOn.length?"依赖完成后自动分派":e.workflow?.isolated===!1?"等待分派":"准备独立执行目录":e.dependsOn.length?"等待依赖与分派":"待分派"}function Ui(e){return e.purpose!=="automation"&&e.status==="open"&&["需要你回答","需要你确认方案","等待你验收","执行准备受阻","自动安排受阻","成员报告受阻","成员报告失败","投递未成功","投递需要关注","投递需要处理"].includes(Kc(e))}const Lu=hc(e=>{let t=!1;return{tasks:[],allTasks:[],error:null,refresh:async()=>{if(!t){t=!0;try{const{tasks:r}=await Sy();e({tasks:r.filter(Ui),allTasks:r,error:null})}catch(r){e({error:r instanceof Error?r.message:"协作待处理事项加载失败"})}finally{t=!1}}}}});function F5(e,t){try{localStorage.setItem(`termdock:tasks:${location.origin}:${e}:open-task`,JSON.stringify(t))}catch{}window.dispatchEvent(new CustomEvent("open-collaboration-task",{detail:{groupId:e,taskId:t}}))}function $5({sessionIds:e}){const t=N8(a=>e.reduce((c,l)=>c+(a.unread[l]?.length??0),0)),{locale:r}=Ur();if(!t)return null;const n=r==="zh"?`${t} 条未读进展`:`${t} unread progress updates`;return s.jsx("span",{title:n,"aria-label":n,className:"inline-flex h-4 min-w-4 shrink-0 items-center justify-center rounded-full bg-primary/15 px-1 text-[10px] font-medium text-primary",children:t>99?"99+":t})}function nQ(e){if(!e.startsWith("remote:"))return null;const t=e.slice(7).split(":");if(t.length!==2)return null;try{const r=decodeURIComponent(t[0]),n=decodeURIComponent(t[1]),a=new URL(r);return!["https:","http:"].includes(a.protocol)||a.origin!==r||!n?null:{origin:r,sessionId:n}}catch{return null}}async function A6(e){const t=nQ(e);if(!t)throw new Error("远端会话标识无效");if(window.termdockDesktop?.collaborationFocus)try{if(await window.termdockDesktop.collaborationFocus(e))return}catch{}window.dispatchEvent(new CustomEvent("termdock:open-remote-session",{detail:t}))}function sQ(e,t,r){return Math.max(t,Math.min(e,r))}const fs={toVector(e,t){return e===void 0&&(e=t),Array.isArray(e)?e:[e,e]},add(e,t){return[e[0]+t[0],e[1]+t[1]]},sub(e,t){return[e[0]-t[0],e[1]-t[1]]},addTo(e,t){e[0]+=t[0],e[1]+=t[1]},subTo(e,t){e[0]-=t[0],e[1]-=t[1]}};function U5(e,t,r){return t===0||Math.abs(t)===1/0?Math.pow(e,r*5):e*t*r/(t+r*e)}function z5(e,t,r,n=.15){return n===0?sQ(e,t,r):e<t?-U5(t-e,r-t,n)+t:e>r?+U5(e-r,r-t,n)+r:e}function iQ(e,[t,r],[n,a]){const[[c,l],[d,p]]=e;return[z5(t,c,l,n),z5(r,d,p,a)]}function aQ(e,t){if(typeof e!="object"||e===null)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function oQ(e){var t=aQ(e,"string");return typeof t=="symbol"?t:String(t)}function Os(e,t,r){return t=oQ(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function H5(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function vs(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?H5(Object(r),!0).forEach(function(n){Os(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):H5(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}const T6={pointer:{start:"down",change:"move",end:"up"},mouse:{start:"down",change:"move",end:"up"},touch:{start:"start",change:"move",end:"end"},gesture:{start:"start",change:"change",end:"end"}};function W5(e){return e?e[0].toUpperCase()+e.slice(1):""}const lQ=["enter","leave"];function cQ(e=!1,t){return e&&!lQ.includes(t)}function uQ(e,t="",r=!1){const n=T6[e],a=n&&n[t]||t;return"on"+W5(e)+W5(a)+(cQ(r,a)?"Capture":"")}const dQ=["gotpointercapture","lostpointercapture"];function hQ(e){let t=e.substring(2).toLowerCase();const r=!!~t.indexOf("passive");r&&(t=t.replace("passive",""));const n=dQ.includes(t)?"capturecapture":"capture",a=!!~t.indexOf(n);return a&&(t=t.replace("capture","")),{device:t,capture:a,passive:r}}function fQ(e,t=""){const r=T6[e],n=r&&r[t]||t;return e+n}function ep(e){return"touches"in e}function S6(e){return ep(e)?"touch":"pointerType"in e?e.pointerType:"mouse"}function pQ(e){return Array.from(e.touches).filter(t=>{var r,n;return t.target===e.currentTarget||((r=e.currentTarget)===null||r===void 0||(n=r.contains)===null||n===void 0?void 0:n.call(r,t.target))})}function mQ(e){return e.type==="touchend"||e.type==="touchcancel"?e.changedTouches:e.targetTouches}function C6(e){return ep(e)?mQ(e)[0]:e}function T1(e,t){try{const r=t.clientX-e.clientX,n=t.clientY-e.clientY,a=(t.clientX+e.clientX)/2,c=(t.clientY+e.clientY)/2,l=Math.hypot(r,n);return{angle:-(Math.atan2(r,n)*180)/Math.PI,distance:l,origin:[a,c]}}catch{}return null}function gQ(e){return pQ(e).map(t=>t.identifier)}function G5(e,t){const[r,n]=Array.from(e.touches).filter(a=>t.includes(a.identifier));return T1(r,n)}function xm(e){const t=C6(e);return ep(e)?t.identifier:t.pointerId}function Yu(e){const t=C6(e);return[t.clientX,t.clientY]}const V5=40,q5=800;function _6(e){let{deltaX:t,deltaY:r,deltaMode:n}=e;return n===1?(t*=V5,r*=V5):n===2&&(t*=q5,r*=q5),[t,r]}function xQ(e){var t,r;const{scrollX:n,scrollY:a,scrollLeft:c,scrollTop:l}=e.currentTarget;return[(t=n??c)!==null&&t!==void 0?t:0,(r=a??l)!==null&&r!==void 0?r:0]}function bQ(e){const t={};if("buttons"in e&&(t.buttons=e.buttons),"shiftKey"in e){const{shiftKey:r,altKey:n,metaKey:a,ctrlKey:c}=e;Object.assign(t,{shiftKey:r,altKey:n,metaKey:a,ctrlKey:c})}return t}function Rf(e,...t){return typeof e=="function"?e(...t):e}function yQ(){}function vQ(...e){return e.length===0?yQ:e.length===1?e[0]:function(){let t;for(const r of e)t=r.apply(this,arguments)||t;return t}}function Y5(e,t){return Object.assign({},t,e||{})}const wQ=32;class k6{constructor(t,r,n){this.ctrl=t,this.args=r,this.key=n,this.state||(this.state={},this.computeValues([0,0]),this.computeInitial(),this.init&&this.init(),this.reset())}get state(){return this.ctrl.state[this.key]}set state(t){this.ctrl.state[this.key]=t}get shared(){return this.ctrl.state.shared}get eventStore(){return this.ctrl.gestureEventStores[this.key]}get timeoutStore(){return this.ctrl.gestureTimeoutStores[this.key]}get config(){return this.ctrl.config[this.key]}get sharedConfig(){return this.ctrl.config.shared}get handler(){return this.ctrl.handlers[this.key]}reset(){const{state:t,shared:r,ingKey:n,args:a}=this;r[n]=t._active=t.active=t._blocked=t._force=!1,t._step=[!1,!1],t.intentional=!1,t._movement=[0,0],t._distance=[0,0],t._direction=[0,0],t._delta=[0,0],t._bounds=[[-1/0,1/0],[-1/0,1/0]],t.args=a,t.axis=void 0,t.memo=void 0,t.elapsedTime=t.timeDelta=0,t.direction=[0,0],t.distance=[0,0],t.overflow=[0,0],t._movementBound=[!1,!1],t.velocity=[0,0],t.movement=[0,0],t.delta=[0,0],t.timeStamp=0}start(t){const r=this.state,n=this.config;r._active||(this.reset(),this.computeInitial(),r._active=!0,r.target=t.target,r.currentTarget=t.currentTarget,r.lastOffset=n.from?Rf(n.from,r):r.offset,r.offset=r.lastOffset,r.startTime=r.timeStamp=t.timeStamp)}computeValues(t){const r=this.state;r._values=t,r.values=this.config.transform(t)}computeInitial(){const t=this.state;t._initial=t._values,t.initial=t.values}compute(t){const{state:r,config:n,shared:a}=this;r.args=this.args;let c=0;if(t&&(r.event=t,n.preventDefault&&t.cancelable&&r.event.preventDefault(),r.type=t.type,a.touches=this.ctrl.pointerIds.size||this.ctrl.touchIds.size,a.locked=!!document.pointerLockElement,Object.assign(a,bQ(t)),a.down=a.pressed=a.buttons%2===1||a.touches>0,c=t.timeStamp-r.timeStamp,r.timeStamp=t.timeStamp,r.elapsedTime=r.timeStamp-r.startTime),r._active){const V=r._delta.map(Math.abs);fs.addTo(r._distance,V)}this.axisIntent&&this.axisIntent(t);const[l,d]=r._movement,[p,m]=n.threshold,{_step:x,values:y}=r;if(n.hasCustomTransform?(x[0]===!1&&(x[0]=Math.abs(l)>=p&&y[0]),x[1]===!1&&(x[1]=Math.abs(d)>=m&&y[1])):(x[0]===!1&&(x[0]=Math.abs(l)>=p&&Math.sign(l)*p),x[1]===!1&&(x[1]=Math.abs(d)>=m&&Math.sign(d)*m)),r.intentional=x[0]!==!1||x[1]!==!1,!r.intentional)return;const w=[0,0];if(n.hasCustomTransform){const[V,Z]=y;w[0]=x[0]!==!1?V-x[0]:0,w[1]=x[1]!==!1?Z-x[1]:0}else w[0]=x[0]!==!1?l-x[0]:0,w[1]=x[1]!==!1?d-x[1]:0;this.restrictToAxis&&!r._blocked&&this.restrictToAxis(w);const v=r.offset,S=r._active&&!r._blocked||r.active;S&&(r.first=r._active&&!r.active,r.last=!r._active&&r.active,r.active=a[this.ingKey]=r._active,t&&(r.first&&("bounds"in n&&(r._bounds=Rf(n.bounds,r)),this.setup&&this.setup()),r.movement=w,this.computeOffset()));const[L,E]=r.offset,[[R,B],[z,O]]=r._bounds;r.overflow=[L<R?-1:L>B?1:0,E<z?-1:E>O?1:0],r._movementBound[0]=r.overflow[0]?r._movementBound[0]===!1?r._movement[0]:r._movementBound[0]:!1,r._movementBound[1]=r.overflow[1]?r._movementBound[1]===!1?r._movement[1]:r._movementBound[1]:!1;const $=r._active?n.rubberband||[0,0]:[0,0];if(r.offset=iQ(r._bounds,r.offset,$),r.delta=fs.sub(r.offset,v),this.computeMovement(),S&&(!r.last||c>wQ)){r.delta=fs.sub(r.offset,v);const V=r.delta.map(Math.abs);fs.addTo(r.distance,V),r.direction=r.delta.map(Math.sign),r._direction=r._delta.map(Math.sign),!r.first&&c>0&&(r.velocity=[V[0]/c,V[1]/c],r.timeDelta=c)}}emit(){const t=this.state,r=this.shared,n=this.config;if(t._active||this.clean(),(t._blocked||!t.intentional)&&!t._force&&!n.triggerAllEvents)return;const a=this.handler(vs(vs(vs({},r),t),{},{[this.aliasKey]:t.values}));a!==void 0&&(t.memo=a)}clean(){this.eventStore.clean(),this.timeoutStore.clean()}}function AQ([e,t],r){const n=Math.abs(e),a=Math.abs(t);if(n>a&&n>r)return"x";if(a>n&&a>r)return"y"}class P0 extends k6{constructor(...t){super(...t),Os(this,"aliasKey","xy")}reset(){super.reset(),this.state.axis=void 0}init(){this.state.offset=[0,0],this.state.lastOffset=[0,0]}computeOffset(){this.state.offset=fs.add(this.state.lastOffset,this.state.movement)}computeMovement(){this.state.movement=fs.sub(this.state.offset,this.state.lastOffset)}axisIntent(t){const r=this.state,n=this.config;if(!r.axis&&t){const a=typeof n.axisThreshold=="object"?n.axisThreshold[S6(t)]:n.axisThreshold;r.axis=AQ(r._movement,a)}r._blocked=(n.lockDirection||!!n.axis)&&!r.axis||!!n.axis&&n.axis!==r.axis}restrictToAxis(t){if(this.config.axis||this.config.lockDirection)switch(this.state.axis){case"x":t[1]=0;break;case"y":t[0]=0;break}}}const TQ=e=>e,Z5=.15,L6={enabled(e=!0){return e},eventOptions(e,t,r){return vs(vs({},r.shared.eventOptions),e)},preventDefault(e=!1){return e},triggerAllEvents(e=!1){return e},rubberband(e=0){switch(e){case!0:return[Z5,Z5];case!1:return[0,0];default:return fs.toVector(e)}},from(e){if(typeof e=="function")return e;if(e!=null)return fs.toVector(e)},transform(e,t,r){const n=e||r.shared.transform;return this.hasCustomTransform=!!n,n||TQ},threshold(e){return fs.toVector(e,0)}},SQ=0,Jc=vs(vs({},L6),{},{axis(e,t,{axis:r}){if(this.lockDirection=r==="lock",!this.lockDirection)return r},axisThreshold(e=SQ){return e},bounds(e={}){if(typeof e=="function")return c=>Jc.bounds(e(c));if("current"in e)return()=>e.current;if(typeof HTMLElement=="function"&&e instanceof HTMLElement)return e;const{left:t=-1/0,right:r=1/0,top:n=-1/0,bottom:a=1/0}=e;return[[t,r],[n,a]]}}),K5={ArrowRight:(e,t=1)=>[e*t,0],ArrowLeft:(e,t=1)=>[-1*e*t,0],ArrowUp:(e,t=1)=>[0,-1*e*t],ArrowDown:(e,t=1)=>[0,e*t]};class CQ extends P0{constructor(...t){super(...t),Os(this,"ingKey","dragging")}reset(){super.reset();const t=this.state;t._pointerId=void 0,t._pointerActive=!1,t._keyboardActive=!1,t._preventScroll=!1,t._delayed=!1,t.swipe=[0,0],t.tap=!1,t.canceled=!1,t.cancel=this.cancel.bind(this)}setup(){const t=this.state;if(t._bounds instanceof HTMLElement){const r=t._bounds.getBoundingClientRect(),n=t.currentTarget.getBoundingClientRect(),a={left:r.left-n.left+t.offset[0],right:r.right-n.right+t.offset[0],top:r.top-n.top+t.offset[1],bottom:r.bottom-n.bottom+t.offset[1]};t._bounds=Jc.bounds(a)}}cancel(){const t=this.state;t.canceled||(t.canceled=!0,t._active=!1,setTimeout(()=>{this.compute(),this.emit()},0))}setActive(){this.state._active=this.state._pointerActive||this.state._keyboardActive}clean(){this.pointerClean(),this.state._pointerActive=!1,this.state._keyboardActive=!1,super.clean()}pointerDown(t){const r=this.config,n=this.state;if(t.buttons!=null&&(Array.isArray(r.pointerButtons)?!r.pointerButtons.includes(t.buttons):r.pointerButtons!==-1&&r.pointerButtons!==t.buttons))return;const a=this.ctrl.setEventIds(t);r.pointerCapture&&t.target.setPointerCapture(t.pointerId),!(a&&a.size>1&&n._pointerActive)&&(this.start(t),this.setupPointer(t),n._pointerId=xm(t),n._pointerActive=!0,this.computeValues(Yu(t)),this.computeInitial(),r.preventScrollAxis&&S6(t)!=="mouse"?(n._active=!1,this.setupScrollPrevention(t)):r.delay>0?(this.setupDelayTrigger(t),r.triggerAllEvents&&(this.compute(t),this.emit())):this.startPointerDrag(t))}startPointerDrag(t){const r=this.state;r._active=!0,r._preventScroll=!0,r._delayed=!1,this.compute(t),this.emit()}pointerMove(t){const r=this.state,n=this.config;if(!r._pointerActive)return;const a=xm(t);if(r._pointerId!==void 0&&a!==r._pointerId)return;const c=Yu(t);if(document.pointerLockElement===t.target?r._delta=[t.movementX,t.movementY]:(r._delta=fs.sub(c,r._values),this.computeValues(c)),fs.addTo(r._movement,r._delta),this.compute(t),r._delayed&&r.intentional){this.timeoutStore.remove("dragDelay"),r.active=!1,this.startPointerDrag(t);return}if(n.preventScrollAxis&&!r._preventScroll)if(r.axis)if(r.axis===n.preventScrollAxis||n.preventScrollAxis==="xy"){r._active=!1,this.clean();return}else{this.timeoutStore.remove("startPointerDrag"),this.startPointerDrag(t);return}else return;this.emit()}pointerUp(t){this.ctrl.setEventIds(t);try{this.config.pointerCapture&&t.target.hasPointerCapture(t.pointerId)&&t.target.releasePointerCapture(t.pointerId)}catch{}const r=this.state,n=this.config;if(!r._active||!r._pointerActive)return;const a=xm(t);if(r._pointerId!==void 0&&a!==r._pointerId)return;this.state._pointerActive=!1,this.setActive(),this.compute(t);const[c,l]=r._distance;if(r.tap=c<=n.tapsThreshold&&l<=n.tapsThreshold,r.tap&&n.filterTaps)r._force=!0;else{const[d,p]=r._delta,[m,x]=r._movement,[y,w]=n.swipe.velocity,[v,S]=n.swipe.distance,L=n.swipe.duration;if(r.elapsedTime<L){const E=Math.abs(d/r.timeDelta),R=Math.abs(p/r.timeDelta);E>y&&Math.abs(m)>v&&(r.swipe[0]=Math.sign(d)),R>w&&Math.abs(x)>S&&(r.swipe[1]=Math.sign(p))}}this.emit()}pointerClick(t){!this.state.tap&&t.detail>0&&(t.preventDefault(),t.stopPropagation())}setupPointer(t){const r=this.config,n=r.device;r.pointerLock&&t.currentTarget.requestPointerLock(),r.pointerCapture||(this.eventStore.add(this.sharedConfig.window,n,"change",this.pointerMove.bind(this)),this.eventStore.add(this.sharedConfig.window,n,"end",this.pointerUp.bind(this)),this.eventStore.add(this.sharedConfig.window,n,"cancel",this.pointerUp.bind(this)))}pointerClean(){this.config.pointerLock&&document.pointerLockElement===this.state.currentTarget&&document.exitPointerLock()}preventScroll(t){this.state._preventScroll&&t.cancelable&&t.preventDefault()}setupScrollPrevention(t){this.state._preventScroll=!1,_Q(t);const r=this.eventStore.add(this.sharedConfig.window,"touch","change",this.preventScroll.bind(this),{passive:!1});this.eventStore.add(this.sharedConfig.window,"touch","end",r),this.eventStore.add(this.sharedConfig.window,"touch","cancel",r),this.timeoutStore.add("startPointerDrag",this.startPointerDrag.bind(this),this.config.preventScrollDelay,t)}setupDelayTrigger(t){this.state._delayed=!0,this.timeoutStore.add("dragDelay",()=>{this.state._step=[0,0],this.startPointerDrag(t)},this.config.delay)}keyDown(t){const r=K5[t.key];if(r){const n=this.state,a=t.shiftKey?10:t.altKey?.1:1;this.start(t),n._delta=r(this.config.keyboardDisplacement,a),n._keyboardActive=!0,fs.addTo(n._movement,n._delta),this.compute(t),this.emit()}}keyUp(t){t.key in K5&&(this.state._keyboardActive=!1,this.setActive(),this.compute(t),this.emit())}bind(t){const r=this.config.device;t(r,"start",this.pointerDown.bind(this)),this.config.pointerCapture&&(t(r,"change",this.pointerMove.bind(this)),t(r,"end",this.pointerUp.bind(this)),t(r,"cancel",this.pointerUp.bind(this)),t("lostPointerCapture","",this.pointerUp.bind(this))),this.config.keys&&(t("key","down",this.keyDown.bind(this)),t("key","up",this.keyUp.bind(this))),this.config.filterTaps&&t("click","",this.pointerClick.bind(this),{capture:!0,passive:!1})}}function _Q(e){"persist"in e&&typeof e.persist=="function"&&e.persist()}const O0=typeof window<"u"&&window.document&&window.document.createElement;function I6(){return O0&&"ontouchstart"in window}function kQ(){return I6()||O0&&window.navigator.maxTouchPoints>1}function LQ(){return O0&&"onpointerdown"in window}function IQ(){return O0&&"exitPointerLock"in window.document}function EQ(){try{return"constructor"in GestureEvent}catch{return!1}}const yo={isBrowser:O0,gesture:EQ(),touch:I6(),touchscreen:kQ(),pointer:LQ(),pointerLock:IQ()},NQ=250,RQ=180,MQ=.5,jQ=50,DQ=250,BQ=10,X5={mouse:0,touch:0,pen:8},QQ=vs(vs({},Jc),{},{device(e,t,{pointer:{touch:r=!1,lock:n=!1,mouse:a=!1}={}}){return this.pointerLock=n&&yo.pointerLock,yo.touch&&r?"touch":this.pointerLock?"mouse":yo.pointer&&!a?"pointer":yo.touch?"touch":"mouse"},preventScrollAxis(e,t,{preventScroll:r}){if(this.preventScrollDelay=typeof r=="number"?r:r||r===void 0&&e?NQ:void 0,!(!yo.touchscreen||r===!1))return e||(r!==void 0?"y":void 0)},pointerCapture(e,t,{pointer:{capture:r=!0,buttons:n=1,keys:a=!0}={}}){return this.pointerButtons=n,this.keys=a,!this.pointerLock&&this.device==="pointer"&&r},threshold(e,t,{filterTaps:r=!1,tapsThreshold:n=3,axis:a=void 0}){const c=fs.toVector(e,r?n:a?1:0);return this.filterTaps=r,this.tapsThreshold=n,c},swipe({velocity:e=MQ,distance:t=jQ,duration:r=DQ}={}){return{velocity:this.transform(fs.toVector(e)),distance:this.transform(fs.toVector(t)),duration:r}},delay(e=0){switch(e){case!0:return RQ;case!1:return 0;default:return e}},axisThreshold(e){return e?vs(vs({},X5),e):X5},keyboardDisplacement(e=BQ){return e}});function E6(e){const[t,r]=e.overflow,[n,a]=e._delta,[c,l]=e._direction;(t<0&&n>0&&c<0||t>0&&n<0&&c>0)&&(e._movement[0]=e._movementBound[0]),(r<0&&a>0&&l<0||r>0&&a<0&&l>0)&&(e._movement[1]=e._movementBound[1])}const PQ=30,OQ=100;class FQ extends k6{constructor(...t){super(...t),Os(this,"ingKey","pinching"),Os(this,"aliasKey","da")}init(){this.state.offset=[1,0],this.state.lastOffset=[1,0],this.state._pointerEvents=new Map}reset(){super.reset();const t=this.state;t._touchIds=[],t.canceled=!1,t.cancel=this.cancel.bind(this),t.turns=0}computeOffset(){const{type:t,movement:r,lastOffset:n}=this.state;t==="wheel"?this.state.offset=fs.add(r,n):this.state.offset=[(1+r[0])*n[0],r[1]+n[1]]}computeMovement(){const{offset:t,lastOffset:r}=this.state;this.state.movement=[t[0]/r[0],t[1]-r[1]]}axisIntent(){const t=this.state,[r,n]=t._movement;if(!t.axis){const a=Math.abs(r)*PQ-Math.abs(n);a<0?t.axis="angle":a>0&&(t.axis="scale")}}restrictToAxis(t){this.config.lockDirection&&(this.state.axis==="scale"?t[1]=0:this.state.axis==="angle"&&(t[0]=0))}cancel(){const t=this.state;t.canceled||setTimeout(()=>{t.canceled=!0,t._active=!1,this.compute(),this.emit()},0)}touchStart(t){this.ctrl.setEventIds(t);const r=this.state,n=this.ctrl.touchIds;if(r._active&&r._touchIds.every(c=>n.has(c))||n.size<2)return;this.start(t),r._touchIds=Array.from(n).slice(0,2);const a=G5(t,r._touchIds);a&&this.pinchStart(t,a)}pointerStart(t){if(t.buttons!=null&&t.buttons%2!==1)return;this.ctrl.setEventIds(t),t.target.setPointerCapture(t.pointerId);const r=this.state,n=r._pointerEvents,a=this.ctrl.pointerIds;if(r._active&&Array.from(n.keys()).every(l=>a.has(l))||(n.size<2&&n.set(t.pointerId,t),r._pointerEvents.size<2))return;this.start(t);const c=T1(...Array.from(n.values()));c&&this.pinchStart(t,c)}pinchStart(t,r){const n=this.state;n.origin=r.origin,this.computeValues([r.distance,r.angle]),this.computeInitial(),this.compute(t),this.emit()}touchMove(t){if(!this.state._active)return;const r=G5(t,this.state._touchIds);r&&this.pinchMove(t,r)}pointerMove(t){const r=this.state._pointerEvents;if(r.has(t.pointerId)&&r.set(t.pointerId,t),!this.state._active)return;const n=T1(...Array.from(r.values()));n&&this.pinchMove(t,n)}pinchMove(t,r){const n=this.state,a=n._values[1],c=r.angle-a;let l=0;Math.abs(c)>270&&(l+=Math.sign(c)),this.computeValues([r.distance,r.angle-360*l]),n.origin=r.origin,n.turns=l,n._movement=[n._values[0]/n._initial[0]-1,n._values[1]-n._initial[1]],this.compute(t),this.emit()}touchEnd(t){this.ctrl.setEventIds(t),this.state._active&&this.state._touchIds.some(r=>!this.ctrl.touchIds.has(r))&&(this.state._active=!1,this.compute(t),this.emit())}pointerEnd(t){const r=this.state;this.ctrl.setEventIds(t);try{t.target.releasePointerCapture(t.pointerId)}catch{}r._pointerEvents.has(t.pointerId)&&r._pointerEvents.delete(t.pointerId),r._active&&r._pointerEvents.size<2&&(r._active=!1,this.compute(t),this.emit())}gestureStart(t){t.cancelable&&t.preventDefault();const r=this.state;r._active||(this.start(t),this.computeValues([t.scale,t.rotation]),r.origin=[t.clientX,t.clientY],this.compute(t),this.emit())}gestureMove(t){if(t.cancelable&&t.preventDefault(),!this.state._active)return;const r=this.state;this.computeValues([t.scale,t.rotation]),r.origin=[t.clientX,t.clientY];const n=r._movement;r._movement=[t.scale-1,t.rotation],r._delta=fs.sub(r._movement,n),this.compute(t),this.emit()}gestureEnd(t){this.state._active&&(this.state._active=!1,this.compute(t),this.emit())}wheel(t){const r=this.config.modifierKey;r&&(Array.isArray(r)?!r.find(n=>t[n]):!t[r])||(this.state._active?this.wheelChange(t):this.wheelStart(t),this.timeoutStore.add("wheelEnd",this.wheelEnd.bind(this)))}wheelStart(t){this.start(t),this.wheelChange(t)}wheelChange(t){"uv"in t||t.cancelable&&t.preventDefault();const n=this.state;n._delta=[-_6(t)[1]/OQ*n.offset[0],0],fs.addTo(n._movement,n._delta),E6(n),this.state.origin=[t.clientX,t.clientY],this.compute(t),this.emit()}wheelEnd(){this.state._active&&(this.state._active=!1,this.compute(),this.emit())}bind(t){const r=this.config.device;r&&(t(r,"start",this[r+"Start"].bind(this)),t(r,"change",this[r+"Move"].bind(this)),t(r,"end",this[r+"End"].bind(this)),t(r,"cancel",this[r+"End"].bind(this)),t("lostPointerCapture","",this[r+"End"].bind(this))),this.config.pinchOnWheel&&t("wheel","",this.wheel.bind(this),{passive:!1})}}const $Q=vs(vs({},L6),{},{device(e,t,{shared:r,pointer:{touch:n=!1}={}}){if(r.target&&!yo.touch&&yo.gesture)return"gesture";if(yo.touch&&n)return"touch";if(yo.touchscreen){if(yo.pointer)return"pointer";if(yo.touch)return"touch"}},bounds(e,t,{scaleBounds:r={},angleBounds:n={}}){const a=l=>{const d=Y5(Rf(r,l),{min:-1/0,max:1/0});return[d.min,d.max]},c=l=>{const d=Y5(Rf(n,l),{min:-1/0,max:1/0});return[d.min,d.max]};return typeof r!="function"&&typeof n!="function"?[a(),c()]:l=>[a(l),c(l)]},threshold(e,t,r){return this.lockDirection=r.axis==="lock",fs.toVector(e,this.lockDirection?[.1,3]:0)},modifierKey(e){return e===void 0?"ctrlKey":e},pinchOnWheel(e=!0){return e}});class UQ extends P0{constructor(...t){super(...t),Os(this,"ingKey","moving")}move(t){this.config.mouseOnly&&t.pointerType!=="mouse"||(this.state._active?this.moveChange(t):this.moveStart(t),this.timeoutStore.add("moveEnd",this.moveEnd.bind(this)))}moveStart(t){this.start(t),this.computeValues(Yu(t)),this.compute(t),this.computeInitial(),this.emit()}moveChange(t){if(!this.state._active)return;const r=Yu(t),n=this.state;n._delta=fs.sub(r,n._values),fs.addTo(n._movement,n._delta),this.computeValues(r),this.compute(t),this.emit()}moveEnd(t){this.state._active&&(this.state._active=!1,this.compute(t),this.emit())}bind(t){t("pointer","change",this.move.bind(this)),t("pointer","leave",this.moveEnd.bind(this))}}const zQ=vs(vs({},Jc),{},{mouseOnly:(e=!0)=>e});class HQ extends P0{constructor(...t){super(...t),Os(this,"ingKey","scrolling")}scroll(t){this.state._active||this.start(t),this.scrollChange(t),this.timeoutStore.add("scrollEnd",this.scrollEnd.bind(this))}scrollChange(t){t.cancelable&&t.preventDefault();const r=this.state,n=xQ(t);r._delta=fs.sub(n,r._values),fs.addTo(r._movement,r._delta),this.computeValues(n),this.compute(t),this.emit()}scrollEnd(){this.state._active&&(this.state._active=!1,this.compute(),this.emit())}bind(t){t("scroll","",this.scroll.bind(this))}}const WQ=Jc;class GQ extends P0{constructor(...t){super(...t),Os(this,"ingKey","wheeling")}wheel(t){this.state._active||this.start(t),this.wheelChange(t),this.timeoutStore.add("wheelEnd",this.wheelEnd.bind(this))}wheelChange(t){const r=this.state;r._delta=_6(t),fs.addTo(r._movement,r._delta),E6(r),this.compute(t),this.emit()}wheelEnd(){this.state._active&&(this.state._active=!1,this.compute(),this.emit())}bind(t){t("wheel","",this.wheel.bind(this))}}const VQ=Jc;class qQ extends P0{constructor(...t){super(...t),Os(this,"ingKey","hovering")}enter(t){this.config.mouseOnly&&t.pointerType!=="mouse"||(this.start(t),this.computeValues(Yu(t)),this.compute(t),this.emit())}leave(t){if(this.config.mouseOnly&&t.pointerType!=="mouse")return;const r=this.state;if(!r._active)return;r._active=!1;const n=Yu(t);r._movement=r._delta=fs.sub(n,r._values),this.computeValues(n),this.compute(t),r.delta=r.movement,this.emit()}bind(t){t("pointer","enter",this.enter.bind(this)),t("pointer","leave",this.leave.bind(this))}}const YQ=vs(vs({},Jc),{},{mouseOnly:(e=!0)=>e}),_g=new Map,S1=new Map;function N6(e){_g.set(e.key,e.engine),S1.set(e.key,e.resolver)}const R6={key:"drag",engine:CQ,resolver:QQ},ZQ={key:"hover",engine:qQ,resolver:YQ},KQ={key:"move",engine:UQ,resolver:zQ},XQ={key:"pinch",engine:FQ,resolver:$Q},JQ={key:"scroll",engine:HQ,resolver:WQ},eP={key:"wheel",engine:GQ,resolver:VQ};function tP(e,t){if(e==null)return{};var r={},n=Object.keys(e),a,c;for(c=0;c<n.length;c++)a=n[c],!(t.indexOf(a)>=0)&&(r[a]=e[a]);return r}function rP(e,t){if(e==null)return{};var r=tP(e,t),n,a;if(Object.getOwnPropertySymbols){var c=Object.getOwnPropertySymbols(e);for(a=0;a<c.length;a++)n=c[a],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}const nP={target(e){if(e)return()=>"current"in e?e.current:e},enabled(e=!0){return e},window(e=yo.isBrowser?window:void 0){return e},eventOptions({passive:e=!0,capture:t=!1}={}){return{passive:e,capture:t}},transform(e){return e}},sP=["target","eventOptions","window","enabled","transform"];function Xh(e={},t){const r={};for(const[n,a]of Object.entries(t))switch(typeof a){case"function":r[n]=a.call(r,e[n],n,e);break;case"object":r[n]=Xh(e[n],a);break;case"boolean":a&&(r[n]=e[n]);break}return r}function iP(e,t,r={}){const n=e,{target:a,eventOptions:c,window:l,enabled:d,transform:p}=n,m=rP(n,sP);if(r.shared=Xh({target:a,eventOptions:c,window:l,enabled:d,transform:p},nP),t){const x=S1.get(t);r[t]=Xh(vs({shared:r.shared},m),x)}else for(const x in m){const y=S1.get(x);y&&(r[x]=Xh(vs({shared:r.shared},m[x]),y))}return r}class M6{constructor(t,r){Os(this,"_listeners",new Set),this._ctrl=t,this._gestureKey=r}add(t,r,n,a,c){const l=this._listeners,d=fQ(r,n),p=this._gestureKey?this._ctrl.config[this._gestureKey].eventOptions:{},m=vs(vs({},p),c);t.addEventListener(d,a,m);const x=()=>{t.removeEventListener(d,a,m),l.delete(x)};return l.add(x),x}clean(){this._listeners.forEach(t=>t()),this._listeners.clear()}}class aP{constructor(){Os(this,"_timeouts",new Map)}add(t,r,n=140,...a){this.remove(t),this._timeouts.set(t,window.setTimeout(r,n,...a))}remove(t){const r=this._timeouts.get(t);r&&window.clearTimeout(r)}clean(){this._timeouts.forEach(t=>{window.clearTimeout(t)}),this._timeouts.clear()}}class oP{constructor(t){Os(this,"gestures",new Set),Os(this,"_targetEventStore",new M6(this)),Os(this,"gestureEventStores",{}),Os(this,"gestureTimeoutStores",{}),Os(this,"handlers",{}),Os(this,"config",{}),Os(this,"pointerIds",new Set),Os(this,"touchIds",new Set),Os(this,"state",{shared:{shiftKey:!1,metaKey:!1,ctrlKey:!1,altKey:!1}}),lP(this,t)}setEventIds(t){if(ep(t))return this.touchIds=new Set(gQ(t)),this.touchIds;if("pointerId"in t)return t.type==="pointerup"||t.type==="pointercancel"?this.pointerIds.delete(t.pointerId):t.type==="pointerdown"&&this.pointerIds.add(t.pointerId),this.pointerIds}applyHandlers(t,r){this.handlers=t,this.nativeHandlers=r}applyConfig(t,r){this.config=iP(t,r,this.config)}clean(){this._targetEventStore.clean();for(const t of this.gestures)this.gestureEventStores[t].clean(),this.gestureTimeoutStores[t].clean()}effect(){return this.config.shared.target&&this.bind(),()=>this._targetEventStore.clean()}bind(...t){const r=this.config.shared,n={};let a;if(!(r.target&&(a=r.target(),!a))){if(r.enabled){for(const l of this.gestures){const d=this.config[l],p=J5(n,d.eventOptions,!!a);if(d.enabled){const m=_g.get(l);new m(this,t,l).bind(p)}}const c=J5(n,r.eventOptions,!!a);for(const l in this.nativeHandlers)c(l,"",d=>this.nativeHandlers[l](vs(vs({},this.state.shared),{},{event:d,args:t})),void 0,!0)}for(const c in n)n[c]=vQ(...n[c]);if(!a)return n;for(const c in n){const{device:l,capture:d,passive:p}=hQ(c);this._targetEventStore.add(a,l,"",n[c],{capture:d,passive:p})}}}}function wu(e,t){e.gestures.add(t),e.gestureEventStores[t]=new M6(e,t),e.gestureTimeoutStores[t]=new aP}function lP(e,t){t.drag&&wu(e,"drag"),t.wheel&&wu(e,"wheel"),t.scroll&&wu(e,"scroll"),t.move&&wu(e,"move"),t.pinch&&wu(e,"pinch"),t.hover&&wu(e,"hover")}const J5=(e,t,r)=>(n,a,c,l={},d=!1)=>{var p,m;const x=(p=l.capture)!==null&&p!==void 0?p:t.capture,y=(m=l.passive)!==null&&m!==void 0?m:t.passive;let w=d?n:uQ(n,a,x);r&&y&&(w+="Passive"),e[w]=e[w]||[],e[w].push(c)},cP=/^on(Drag|Wheel|Scroll|Move|Pinch|Hover)/;function uP(e){const t={},r={},n=new Set;for(let a in e)cP.test(a)?(n.add(RegExp.lastMatch),r[a]=e[a]):t[a]=e[a];return[r,t,n]}function Au(e,t,r,n,a,c){if(!e.has(r)||!_g.has(n))return;const l=r+"Start",d=r+"End",p=m=>{let x;return m.first&&l in t&&t[l](m),r in t&&(x=t[r](m)),m.last&&d in t&&t[d](m),x};a[n]=p,c[n]=c[n]||{}}function dP(e,t){const[r,n,a]=uP(e),c={};return Au(a,r,"onDrag","drag",c,t),Au(a,r,"onWheel","wheel",c,t),Au(a,r,"onScroll","scroll",c,t),Au(a,r,"onPinch","pinch",c,t),Au(a,r,"onMove","move",c,t),Au(a,r,"onHover","hover",c,t),{handlers:c,config:t,nativeHandlers:n}}function j6(e,t={},r,n){const a=k.useMemo(()=>new oP(e),[]);if(a.applyHandlers(e,n),a.applyConfig(t,r),k.useEffect(a.effect.bind(a)),k.useEffect(()=>a.clean.bind(a),[]),t.target===void 0)return a.bind.bind(a)}function eb(e,t){return N6(R6),j6({drag:e},t||{},"drag")}function hP(e){return e.forEach(N6),function(r,n){const{handlers:a,nativeHandlers:c,config:l}=dP(r,n||{});return j6(a,l,void 0,c)}}function DU(e,t){return hP([R6,XQ,JQ,eP,KQ,ZQ])(e,t||{})}const tb={dampingRatio:.8,response:.3},fP=.998;function pP(e,t,r,n){const a=2*Math.PI/Math.max(e.response,.001),c=t-n,l=r,d=e.dampingRatio;if(Math.abs(d-1)<1e-4){const v=c,S=l+a*c;return{value:L=>n+(v+S*L)*Math.exp(-a*L),velocity:L=>(S-a*(v+S*L))*Math.exp(-a*L)}}if(d<1){const v=a*Math.sqrt(1-d*d),S=c,L=(l+d*a*c)/v;return{value:E=>n+Math.exp(-d*a*E)*(S*Math.cos(v*E)+L*Math.sin(v*E)),velocity:E=>Math.exp(-d*a*E)*((L*v-d*a*S)*Math.cos(v*E)-(S*v+d*a*L)*Math.sin(v*E))}}const p=a*Math.sqrt(d*d-1),m=-d*a+p,x=-d*a-p,y=(l-x*c)/(m-x),w=c-y;return{value:v=>n+y*Math.exp(m*v)+w*Math.exp(x*v),velocity:v=>y*m*Math.exp(m*v)+w*x*Math.exp(x*v)}}function mP(e,t=fP){return e/1e3*(t/(1-t))}function rb(e,t,r=.55){return e*t*r/(t+r*Math.abs(e))}function gP(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}const xP=.1,bP=5;function yP(e,t,r,n,a){const c=pP(e,t,r,n),l=1e3/60,d=240,p=[];for(let m=0;m<d;m++){const x=m*l/1e3,y=c.value(x),w=c.velocity(x);if(p.push(a?a(y):y),m>0&&Math.abs(y-n)<xP&&Math.abs(w)<bP)break}return p.push(a?a(n):n),{frames:p,durationMs:(p.length-1)*l,solver:c}}const vP='input:not([type="hidden"]), textarea, select, [contenteditable]:not([contenteditable="false"])';function wP(){if(typeof document>"u")return;const e=document.activeElement;e instanceof HTMLElement&&e.matches(vP)&&e.blur()}const AP=18,nb=8,sb={touch:nb,pen:nb},TP=500,bm=200,ib=50,SP=`[${fA}]`;function ym(e,t,r){return Math.min(r,Math.max(t,e))}function ab(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.pointerType=="string"?t.pointerType==="touch"||t.pointerType==="pen":typeof t.type=="string"&&t.type.startsWith("touch")}function ob(e){if(!e||typeof e!="object")return!1;const t=e.target;return t instanceof Element&&!!t.closest(SP)}function Bd(...e){typeof window<"u"&&window.__SIDEBAR_DEBUG__&&console.log("[Sidebar]",...e)}const D6=k.forwardRef(function({side:t,isOpen:r,drawerWidthPx:n,onClose:a,onOpen:c,children:l,pinned:d=!1},p){const{t:m}=Ur(),x=t==="left",y=x?-n:n,w=b.useRef(null),v=b.useRef(null),S=b.useRef(r?0:y),L=b.useRef(null),E=b.useRef(null),R=b.useRef(0),B=b.useRef(null),z=b.useRef(null),O=b.useRef(!1),$=b.useRef(null),V=b.useRef(!1),Z=b.useRef([]),le=b.useRef(null),be=b.useRef(S.current),pe=b.useRef(r?1:0),ee=b.useRef(r);ee.current=r;const _e=b.useRef(y);_e.current=y;const ze=b.useRef(n);ze.current=n;const Y=b.useRef(x);Y.current=x;const ce=b.useRef(a);ce.current=a;const qe=b.useRef(c);qe.current=c;const we=b.useCallback(ae=>{w.current=ae,typeof p=="function"?p(ae):p&&(p.current=ae)},[p]),ye=b.useCallback(()=>{E.current!==null&&(window.cancelAnimationFrame(E.current),E.current=null),L.current=null},[]),Le=b.useCallback(ae=>{const Ae=ze.current;return Y.current?(ae+Ae)/Ae:(Ae-ae)/Ae},[]),Be=b.useCallback(ae=>{const Ae=v.current;Ae&&(Ae.style.opacity=String(ym(Le(ae),0,1)))},[Le]),ne=b.useCallback(ae=>{S.current=ae;const Ae=w.current;Ae&&(Ae.style.transform=`translateX(${ae}px)`,Be(ae))},[Be]),Fe=b.useCallback(ae=>{L.current=ae,E.current===null&&(E.current=window.requestAnimationFrame(()=>{E.current=null;const Ae=L.current;L.current=null,Ae!==null&&ne(Ae)}))},[ne]),ke=b.useCallback(()=>{E.current!==null&&(window.cancelAnimationFrame(E.current),E.current=null);const ae=L.current;L.current=null,ae!==null&&ne(ae)},[ne]),Ee=b.useCallback(ae=>{const Ae=_e.current;return ym(ae,Math.min(0,Ae),Math.max(0,Ae))},[]),Pe=b.useCallback(()=>{const ae=B.current;if(!ae)return null;B.current=null;const Ae=(performance.now()-ae.startTime)/1e3,Ye={value:ae.solver.value(Ae),velocity:ae.solver.velocity(Ae)};return ae.animations.forEach(et=>et.cancel()),Ye},[]),Ne=b.useCallback(()=>{z.current!==null&&(window.clearTimeout(z.current),z.current=null)},[]),oe=b.useCallback(()=>{le.current?.(),le.current=null},[]),We=b.useCallback(()=>{ke(),Ne();const ae=Pe();ae&&ne(Ee(ae.value));const Ae=w.current,Ye=v.current;Ae?.getAnimations().forEach(et=>et.cancel()),Ae&&(Ae.style.transition="none",Ae.style.opacity="1"),Ye?.getAnimations().forEach(et=>et.cancel()),Ye&&(Ye.style.transition="none")},[ne,Ne,Ee,ke,Pe]),nt=b.useCallback((ae,Ae)=>{ke(),Ne();const Ye=w.current,et=v.current,St=ae?0:_e.current;et&&(et.style.pointerEvents=ae?"auto":"none");const Gt=Pe(),Qt=Gt?Ee(Gt.value):S.current,wt=Ae?.velocity??Gt?.velocity??0;if(gP())return S.current=St,Ye&&(Ye.style.transition=`opacity ${bm}ms ease`,Ye.style.opacity=ae?"1":"0",Ye.style.transform=`translateX(${St}px)`),et&&(et.style.transition=`opacity ${bm}ms ease`,et.style.opacity=ae?"1":"0"),bm;Ye&&(Ye.style.transition="none",Ye.style.opacity="1"),et&&(et.style.transition="none");const zt=Math.abs(Ae?.velocity??0)>TP,{frames:Vt,durationMs:Kt,solver:Ot}=yP({dampingRatio:zt?tb.dampingRatio:1,response:tb.response},Qt,wt,St,Ee);if(!Ye||Math.abs(Qt-St)<.5&&Math.abs(wt)<5)return ne(St),0;const It=Ye.animate(Vt.map(Ve=>({transform:`translateX(${Ve}px)`})),{duration:Kt,easing:"linear",fill:"forwards"}),xe=[It];return et&&xe.push(et.animate(Vt.map(Ve=>({opacity:String(ym(Le(Ve),0,1))})),{duration:Kt,easing:"linear",fill:"forwards"})),B.current={solver:Ot,startTime:performance.now(),target:St,animations:xe},Bd("spring start",{startX:Qt,startVelocity:wt,targetX:St,frames:Vt.length,durationMs:Kt}),It.onfinish=()=>{const Ve=B.current;!Ve||!Ve.animations.includes(It)||(B.current=null,ne(St),Ve.animations.forEach(ht=>ht.cancel()),Bd("spring finish",{targetX:St}))},Kt},[ne,Ne,Ee,ke,Le,Pe]),gt=b.useCallback(ae=>{ke();const Ae=ae,Ye=0,et=_e.current,St=S.current+mP(Ae),Gt=Math.abs(St-Ye)<=Math.abs(St-et);Bd("decideSnap",{velocity:Ae,currentX:S.current,projected:St,shouldOpen:Gt});const Qt=nt(Gt,{velocity:Ae});return Gt&&!ee.current?z.current=window.setTimeout(()=>{z.current=null,qe.current?.()},Qt+ib):!Gt&&ee.current&&(z.current=window.setTimeout(()=>{z.current=null,ce.current()},Qt+ib)),Gt},[nt,ke]),ue=b.useCallback(ae=>{const Ae=_e.current,Ye=Math.min(0,Ae),et=Math.max(0,Ae),St=ze.current;return ae<Ye?Ye-rb(Ye-ae,St):ae>et?et+rb(ae-et,St):ae},[]),Ze=b.useCallback(ae=>{const Ae=Z.current,Ye=performance.now();Ae.push({t:Ye,x:ae});const et=Ye-120;for(;Ae.length>0&&Ae[0].t<et;)Ae.shift()},[]),at=b.useCallback(()=>{const ae=Z.current;if(ae.length<2)return 0;const Ae=ae[ae.length-1];if(performance.now()-Ae.t>60)return 0;const Ye=ae[0],et=(Ae.t-Ye.t)/1e3;return et<.016?0:(Ae.x-Ye.x)/et},[]);b.useEffect(()=>{Ne();const ae=B.current,Ae=r?0:_e.current;ae&&ae.target===Ae||nt(r)},[r,nt,Ne]),b.useEffect(()=>{We(),Fe(ee.current?0:y)},[y,We,Fe]),b.useEffect(()=>()=>{ye(),Ne(),Pe(),oe()},[Ne,ye,oe,Pe]);const Ie=eb(({active:ae,cancel:Ae,first:Ye,last:et,movement:[St],event:Gt})=>{if(Bd("bindPanel",{active:ae,first:Ye,last:et,mx:St}),!ab(Gt)){Ae();return}if(Ye){if(oe(),O.current=!1,$.current=null,Z.current=[],ob(Gt)){Ae();return}const Qt=w.current,wt=Qt?pA(Gt.target,Qt):null;if(!wt||mA()){Ae();return}const zt=gA(wt,St,Y.current?-1:1);if(Bd("arbitrate",{owner:zt.kind,mx:St}),zt.kind==="swiper"){le.current=xA(zt.instance),Ae();return}if(zt.kind==="scroller"){const Vt=bA(zt.element);if(Vt)$.current=Vt;else{Ae();return}}$.current||(O.current=!0,We(),R.current=S.current)}if(!ae){$.current=null,O.current&&(O.current=!1,gt(at()));return}if($.current){yA($.current,St);return}if(O.current){const Qt=ue(R.current+St);Ze(Qt),Fe(Qt)}},{axis:"x",axisThreshold:sb,filterTaps:!0,pointer:{touch:!0}}),Ge=eb(({active:ae,cancel:Ae,first:Ye,movement:[et],event:St})=>{if(!ab(St)){Ae();return}if(ee.current){Ae();return}if(Ye&&(V.current=!0,Z.current=[],We(),R.current=S.current),!ae){V.current&&(V.current=!1,gt(at())&&wP());return}if(V.current){const Gt=ue(R.current+et);Ze(Gt),Fe(Gt)}},{axis:"x",axisThreshold:sb,filterTaps:!0,pointer:{touch:!0}}),Ce=b.useCallback(ae=>{ae.preventDefault(),ae.stopPropagation(),ee.current||qe.current?.()},[]);if(d)return s.jsx("aside",{ref:we,"data-sidebar":t,"data-sidebar-pinned":"true",className:"relative flex h-full min-h-0 w-full flex-col app-chrome-bg",children:l});const H=Ie();return s.jsxs(s.Fragment,{children:[s.jsx("div",{...Ge(),style:{position:"fixed",top:"1.5rem",bottom:"10rem",...x?{left:0}:{right:0},width:AP,zIndex:"var(--z-chrome-hint)",touchAction:"none",pointerEvents:r?"none":"auto"},onClick:Ce,"aria-label":m(x?"sidebar.openLeftSidebar":"sidebar.openRightSidebar")}),s.jsx("div",{ref:v,"data-sidebar-backdrop":t,className:"fixed inset-0 z-sidebar-backdrop bg-[var(--app-backdrop)] cursor-default",style:{opacity:pe.current,pointerEvents:r?"auto":"none",transition:"none",willChange:"opacity"},onClick:a,"aria-label":m("sidebar.closeSidebar")}),s.jsx("aside",{...H,onClickCapture:ae=>{ob(ae)||H.onClickCapture?.(ae)},ref:we,"data-sidebar":t,className:`fixed inset-y-0 z-sidebar-panel flex flex-col chrome-glow-panel will-change-transform ${x?"border-r border-border":"border-l border-border/15"}`,style:{...x?{left:0}:{right:0},width:n,maxWidth:x?"94vw":"95vw",transform:`translateX(${be.current}px)`,transition:"none",touchAction:"pan-y",pointerEvents:r?"auto":"none",paddingTop:"var(--safe-top-inset, env(safe-area-inset-top, 0px))",paddingBottom:"var(--safe-bottom-inset, env(safe-area-inset-bottom, 0px))",...x?{paddingLeft:"var(--safe-left-inset, env(safe-area-inset-left, 0px))"}:{paddingRight:"var(--safe-right-inset, env(safe-area-inset-right, 0px))"}},children:l})]})}),CP={activeKey:"root",items:[]},_P=()=>()=>{},kP=()=>CP;function LP(e){const t=Po(),r=b.useSyncExternalStore(t?.subscribe??_P,t?.snapshot??kP),n=R8(),a=r.items.map(c=>c.key===n?{...c,reviewCount:e}:c).filter(c=>c.reviewCount>0);return{host:t,groups:a,currentKey:n,active:!t||r.activeKey===n,total:t?e+a.reduce((c,l)=>c+(l.key===n?0:l.reviewCount),0):e,hasOtherAttention:a.some(c=>c.key!==n)}}function IP({groups:e,currentKey:t,onClose:r}){const{t:n}=Ur(),a=b.useId(),c=b.useRef(null),l=b.useRef(null),d=b.useRef(r);d.current=r;const p=b.useRef(!0),[m,x]=b.useState(""),y=e.reduce((S,L)=>S+L.reviewCount,0);b.useEffect(()=>{const S=document.activeElement;l.current?.focus({preventScroll:!0});const L=E=>{if(E.key==="Escape"&&(E.preventDefault(),E.stopImmediatePropagation(),d.current()),E.key!=="Tab")return;const R=Array.from(c.current?.querySelectorAll("button:not(:disabled)")??[]),B=R[0],z=R[R.length-1],O=!c.current?.contains(document.activeElement);E.shiftKey&&(document.activeElement===B||O)?(E.preventDefault(),z?.focus()):!E.shiftKey&&(document.activeElement===z||O)&&(E.preventDefault(),B?.focus())};return document.addEventListener("keydown",L,!0),()=>{document.removeEventListener("keydown",L,!0),p.current&&S?.isConnected&&!S.closest("[inert]")&&S.focus({preventScroll:!0})}},[]);const w=(S,L)=>{const E=Po(),R=E?.snapshot().items.find(z=>z.key===S.key);if(!R?.reviewCount||L&&!R.attentionSessions?.some(z=>z.id===L)){x(n("serviceAttention.changed"));return}p.current=!1;let B=!1;L&&S.key===t?(window.dispatchEvent(new CustomEvent("termdock:focus-session",{detail:L})),B=!0):L&&R.service?.targetPeerId?B=E?.focusSession(R.service.targetPeerId,L)??!1:R.service&&(B=E?.activate(R.service,!0)??!1),B?r():(p.current=!0,x(n("serviceAttention.unavailable")))},v=S=>S.phase==="offline"?n("serviceAttention.offline"):S.phase==="login"?n("serviceAttention.login"):S.phase==="connecting"||S.phase==="reconnecting"?n("connection.reconnecting"):null;return s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button","aria-label":n("common.close"),tabIndex:-1,className:"fixed inset-0 z-modal-backdrop cursor-default bg-[var(--app-backdrop)]",onClick:r}),s.jsx("div",{className:"pointer-events-none fixed inset-0 z-modal-panel flex items-end justify-center p-3 sm:items-center sm:p-6",style:{paddingTop:"max(12px, var(--safe-top-inset, env(safe-area-inset-top, 0px)))",paddingBottom:"max(12px, var(--safe-bottom-inset, env(safe-area-inset-bottom, 0px)))"},children:s.jsxs("section",{ref:c,role:"dialog","aria-modal":"true","aria-labelledby":a,"data-sidebar-gesture-ignore":!0,onKeyDown:S=>S.stopPropagation(),className:"pointer-events-auto flex max-h-full w-full max-w-md flex-col overflow-hidden rounded-2xl border border-border bg-surface text-foreground shadow-xl",children:[s.jsxs("header",{className:"flex shrink-0 items-center gap-3 border-b border-border px-4 py-3",children:[s.jsx(cc,{size:20,className:"shrink-0 text-[color:var(--warning)]","aria-hidden":"true"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("h2",{id:a,className:"text-sm font-semibold",children:n("serviceAttention.title")}),s.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:n("serviceAttention.summary",{services:e.length,count:y})})]}),s.jsx("button",{ref:l,type:"button","aria-label":n("common.close"),onClick:r,className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-xl text-muted-foreground hover:bg-surface-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:s.jsx(In,{size:18})})]}),s.jsxs("div",{className:"min-h-0 overflow-y-auto overscroll-contain p-2",children:[e.length===0&&s.jsx("p",{role:"status",className:"px-4 py-8 text-center text-sm text-muted-foreground",children:n("serviceAttention.empty")}),e.map(S=>s.jsxs("section",{className:"mb-2 last:mb-0",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-2 px-3 pb-1 pt-2 text-xs",children:[s.jsx("h3",{className:"min-w-0 flex-1 truncate font-medium",title:S.service?.label,children:S.service?.label||n("serviceAttention.currentService")}),S.key===t&&s.jsx("span",{className:"shrink-0 text-muted-foreground",children:n("agent.currentSession")}),s.jsx("span",{className:"shrink-0 tabular-nums text-[color:var(--warning)]",children:S.reviewCount})]}),v(S)&&s.jsx("p",{className:"px-3 pb-1 text-xs text-[color:var(--warning)]",children:v(S)}),S.attentionSessions?.length?S.attentionSessions.map(L=>s.jsxs("button",{type:"button",onClick:()=>w(S,L.id),className:"flex min-h-14 w-full items-center gap-3 rounded-xl px-3 py-2 text-left hover:bg-surface-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"line-clamp-2 break-words text-sm",title:L.label,children:L.label}),s.jsx("span",{className:"mt-0.5 block text-xs text-muted-foreground",children:L.waiting?n("serviceAttention.waiting"):n("agent.needsReview")})]}),s.jsx(Ks,{size:16,className:"shrink-0 text-muted-foreground","aria-hidden":"true"})]},L.id)):s.jsx("button",{type:"button",onClick:()=>w(S),className:"min-h-11 w-full rounded-xl px-3 py-2 text-left text-sm hover:bg-surface-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary",children:n("serviceAttention.viewService")})]},S.key))]}),s.jsxs("footer",{className:"shrink-0 border-t border-border px-4 py-3 text-xs text-muted-foreground",children:[m&&s.jsx("p",{role:"alert",className:"mb-1 text-[color:var(--warning)]",children:m}),n("serviceAttention.scope")]})]})})]})}function EP(e){const t=e.icon&&e.isPlugin?`/api/terminal/agent-plugin-icon/${encodeURIComponent(e.slug)}${e.iconVersion?`?v=${Math.floor(e.iconVersion)}`:""}`:void 0,[r,n]=b.useState();if(b.useEffect(()=>{if(n(void 0),!t)return;const a=new AbortController;let c;return fetch(t,{signal:a.signal}).then(async l=>{if(!l.ok)throw new Error(`Icon request failed: ${l.status}`);const d=await l.blob();a.signal.aborted||(c=URL.createObjectURL(d),n({endpoint:t,src:c}))}).catch(()=>{}),()=>{a.abort(),c&&URL.revokeObjectURL(c)}},[t]),!!e.icon)return e.isPlugin?r?.endpoint===t?r?.src:void 0:`/icons/agents/${e.icon}.svg`}function NP(e){return e.agentStatus==="waiting"||e.agentNeedsReview===!0}function RP(e,t,r,n="next"){if(e.length===0)return null;const a=t?e.findIndex(c=>c.sessionId===t):-1;for(let c=1;c<=e.length;c+=1){const l=n==="next"?c:-c,d=(a+l+e.length)%e.length,p=e[d];if(p&&r(p))return p.sessionId}return null}function MP(e,t,r="next"){return RP(e,t,NP,r)}const Ua=42,Mf=20,jP=10;function C1(e,t,r){return Math.min(r,Math.max(t,e))}function tp(e){const t=Math.max(0,e.safeTop??0),r=Math.max(0,e.safeRight??0),n=Math.max(0,e.safeBottom??0),a=Math.max(0,e.safeLeft??0),c=Math.max(0,e.bottomClearance??72),l=a+Mf,d=Math.max(l,e.width-r-Mf-Ua),p=Math.max(t+12,52),m=Math.max(p,e.height-n-c-Ua);return{minX:l,maxX:d,minY:p,maxY:m}}function lb(e,t){const r=tp(e),n=C1(t.yRatio,0,1);return{x:t.side==="left"?r.minX:r.maxX,y:r.minY+(r.maxY-r.minY)*n}}function Hc(e,t){const r=tp(e);return{x:C1(t.x,r.minX,r.maxX),y:C1(t.y,r.minY,r.maxY)}}function cb(e,t){const r=tp(e),n=Hc(e,t),a=(r.minX+r.maxX+Ua)/2,c=n.x+Ua/2<a?"left":"right",l=r.maxY-r.minY;return{position:{x:c==="left"?r.minX:r.maxX,y:n.y},preference:{side:c,yRatio:l>0?(n.y-r.minY)/l:0}}}function ub(e,t,r){const n=Hc(e,t),a=Ua+jP,c=m=>Math.abs(m.x-r.x)<a&&Math.abs(m.y-r.y)<a;if(!c(n))return n;const l=[{...n,y:r.y-a},{...n,y:r.y+a}].map(m=>Hc(e,m)).filter(m=>!c(m)).sort((m,x)=>Math.abs(m.y-n.y)-Math.abs(x.y-n.y));if(l[0])return l[0];const d=tp(e);return[{...n,x:d.minX},{...n,x:d.maxX}].map(m=>Hc(e,m)).filter(m=>!c(m)).sort((m,x)=>Math.abs(m.x-n.x)-Math.abs(x.x-n.x))[0]??n}const vm="var(--warning)",DP="var(--success)",db="var(--tmux)",hb="termdock:mobile-attention-position:v1",fb="termdock:running-session-position:v1",BP={side:"right",yRatio:.68},QP={side:"right",yRatio:.54};function pb(e,t){if(typeof window>"u")return t;try{const r=JSON.parse(window.localStorage.getItem(e)??"null");if(r&&(r.side==="left"||r.side==="right")&&typeof r.yRatio=="number"&&Number.isFinite(r.yRatio))return{side:r.side,yRatio:Math.min(1,Math.max(0,r.yRatio))}}catch{}return t}function PP(e,t){try{window.localStorage.setItem(e,JSON.stringify(t))}catch{}}function Ch(e){if(typeof document>"u")return 0;const t=Number.parseFloat(getComputedStyle(document.documentElement).getPropertyValue(e));return Number.isFinite(t)?Math.max(0,t):0}function OP(e,t,r={}){if(typeof window>"u")return{width:390,height:664};const n=window.visualViewport,a=n?.width??window.innerWidth,c=n?.height??window.innerHeight,l=t?.getBoundingClientRect(),d=!!(l&&l.width>0&&l.height>0);return{width:a,height:c,safeTop:Math.max(Ch("--safe-top-inset"),(d?Math.max(0,l.top):0)+Math.max(0,r.top??0)),safeRight:Math.max(Ch("--safe-right-inset"),(d?Math.max(0,a-l.right):0)+Math.max(0,r.right??0)),safeBottom:Math.max(Ch("--safe-bottom-inset"),(d?Math.max(0,c-l.bottom):0)+Math.max(0,r.bottom??0)),safeLeft:Math.max(Ch("--safe-left-inset"),(d?Math.max(0,l.left):0)+Math.max(0,r.left??0)),bottomClearance:e?Mf:72}}function B6(){const e=Yr.getState(),t=Array.from(e.sessions.values()),r=MP(t,e.activeSessionId);if(!r)return;const n=e.activeSessionId?e.sessions.get(e.activeSessionId):void 0;n?.agentNeedsReview&&e.clearAgentNeedsReview(n.sessionId),window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:r}))}function mb(e){window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:e}))}function Q6(e){switch(e){case"success":return"var(--success)";case"warning":return"var(--warning)";case"danger":return"var(--destructive)";case"info":case"accent":return"var(--accent)";default:return"var(--muted-foreground)"}}function FP({indicator:e,tone:t,size:r}){const n=Q6(t);switch(e){case"spinner":return s.jsx(_n,{size:r,className:"shrink-0 animate-spin",style:{color:n}});case"question":return s.jsx(of,{size:r,className:"shrink-0 animate-bounce-y",style:{color:n}});case"badge":return s.jsx(cc,{size:r+1,className:"shrink-0 animate-pulse",style:{color:n}});case"terminal":return s.jsx($o,{size:r,className:"shrink-0",style:{color:n}});case"pulse":return s.jsx(WA,{size:r,className:"shrink-0 animate-pulse",style:{color:n}});case"ring":return s.jsx("span",{className:"block shrink-0 rounded-full border-2",style:{width:r,height:r,borderColor:n}});case"dot":return s.jsx("span",{className:"block shrink-0 rounded-full",style:{width:Math.max(5,r-4),height:Math.max(5,r-4),backgroundColor:n}})}}function Wc({agent:e,size:t=12}){const r=t-4,n=EP(e);return n?e.iconMode==="native"?s.jsx("span",{className:"flex shrink-0 items-center justify-center rounded-[3px]",style:{width:t,height:t},title:e.displayName,children:s.jsx("img",{src:n,alt:e.displayName,style:{width:r,height:r}})}):s.jsx("span",{className:"flex shrink-0 items-center justify-center rounded-[3px]",style:{width:t,height:t,backgroundColor:e.accentColor},title:e.displayName,children:s.jsx("span",{className:"block bg-white",style:{width:r,height:r,WebkitMask:`url(${n}) center / contain no-repeat`,mask:`url(${n}) center / contain no-repeat`}})}):s.jsx("span",{className:"flex shrink-0 items-center justify-center rounded-[3px]",style:{width:t,height:t,backgroundColor:e.accentColor},title:e.displayName,children:s.jsx(R0,{size:r,className:"text-white"})})}function $P({sessionMode:e,state:t,size:r=11}){const n=t?.agent?s.jsx(Wc,{agent:t.agent,size:r+1}):e==="tmux"?s.jsx(qc,{size:r,className:"shrink-0"}):s.jsx($o,{size:r,className:"shrink-0"});return t?.agentStatusDetail&&t.agentIndicator&&!(t.agentStatus==="done"&&t.agentNeedsReview)?s.jsx("span",{title:t.agentMessage??t.agentStatusDetail.label,"aria-label":t.agentStatusDetail.label,children:s.jsx(FP,{indicator:t.agentIndicator,tone:t.agentStatusDetail.tone,size:r})}):t?.agentStatus==="working"?s.jsx("span",{title:t.agentMessage??t.agent?.displayName,children:s.jsx(_n,{size:r,className:"shrink-0 animate-spin",style:{color:DP}})}):t?.agentStatus==="waiting"?s.jsx("span",{title:t.agentMessage??void 0,children:s.jsx(of,{size:r,className:"shrink-0 animate-bounce-y",style:{color:vm}})}):t?.agentStatus==="done"&&t.agentNeedsReview?s.jsx("span",{title:t.agentMessage??void 0,children:s.jsx(cc,{size:r+1,className:"shrink-0 animate-pulse",style:{color:vm}})}):t?.agentNeedsReview?s.jsx("span",{title:t.agentMessage??void 0,children:s.jsx(cc,{size:r+1,className:"shrink-0 animate-pulse",style:{color:vm}})}):t?.inCopyMode?e==="tmux"?s.jsx(qc,{size:r,className:"shrink-0 animate-pulse",style:{color:db}}):s.jsx($o,{size:r,className:"shrink-0 animate-pulse",style:{color:db}}):n}function UP({status:e,detail:t,needsReview:r,inCopyMode:n}){const{t:a}=Ur();return t&&!r?s.jsx("span",{className:"absolute right-0.5 top-0.5 h-2.5 w-2.5 rounded-full ring-2 ring-surface animate-pulse",style:{backgroundColor:Q6(t.tone)},title:t.label}):e==="working"?s.jsx("span",{className:"absolute right-0.5 top-0.5 h-2.5 w-2.5 rounded-full bg-[var(--success)] ring-2 ring-surface shadow-[0_0_6px_rgb(var(--success-rgb)_/_0.50)] animate-pulse",title:a("agent.aiRunning")}):e==="waiting"||r?s.jsx("span",{className:"absolute right-0.5 top-0.5 h-2.5 w-2.5 rounded-full bg-[var(--warning)] ring-2 ring-surface shadow-[0_0_0_1px_rgb(var(--warning-rgb)_/_0.24)] animate-pulse",title:a(r?"agent.finishedReview":"agent.aiWaiting")}):e==="done"&&r?s.jsx("span",{className:"absolute right-0.5 top-0.5 h-2.5 w-2.5 rounded-full bg-[var(--warning)] ring-2 ring-surface shadow-[0_0_0_1px_rgb(var(--warning-rgb)_/_0.24)] animate-pulse",title:a("agent.finishedReview")}):n?s.jsx("span",{className:"absolute right-0.5 top-0.5 h-2.5 w-2.5 rounded-[2px] bg-[var(--tmux)] ring-2 ring-surface",title:a("agent.copyMode")}):null}function P6({count:e,tone:t,title:r}){const{t:n}=Ur();if(e<=0)return null;const a=t==="running"?"inline-flex items-center gap-1 rounded-full bg-[rgb(var(--success-rgb)_/_0.12)] px-1.5 py-0.5 text-[10px] font-medium text-[color:var(--success)]":"inline-flex min-h-6 items-center gap-1 rounded-full bg-[rgb(var(--warning-rgb)_/_0.14)] px-2 py-0.5 text-[10px] font-semibold text-[color:var(--warning)] ring-1 ring-[rgb(var(--warning-rgb)_/_0.24)] transition hover:bg-[rgb(var(--warning-rgb)_/_0.22)] active:scale-[0.97]",c=t==="running"?"h-1.5 w-1.5 rounded-full bg-[var(--success)] animate-pulse":"h-1.5 w-1.5 rounded-full bg-[var(--warning)] animate-pulse";if(t==="review"){const l=r??n("agent.jumpToNext");return s.jsxs("button",{type:"button",className:a,title:`${l} · ${n("agent.jumpToNext")}`,"aria-label":`${l}: ${e}. ${n("agent.jumpToNext")}`,onClick:B6,children:[s.jsx(cc,{size:11,className:"shrink-0"}),s.jsx("span",{children:n("agent.needsReview")}),s.jsx("span",{className:"tabular-nums",children:e})]})}return s.jsxs("span",{className:a,title:r,children:[s.jsx("span",{className:c}),e]})}function zP({runningCount:e,reviewCount:t,className:r=""}){const n=[];return e>0&&n.push({key:"running",count:e,className:"bg-[var(--success)] text-[color:var(--success-foreground)]"}),t>0&&n.push({key:"review",count:t,className:"bg-[var(--warning)] text-[color:var(--warning-foreground)]"}),n.length===0?null:s.jsx("span",{"aria-hidden":"true",className:`pointer-events-none absolute -right-1 ${n.length>1?"top-0.5 flex flex-col gap-0.5":"-top-1"} ${r}`,children:n.map(a=>s.jsx("span",{className:`flex h-3 min-w-3 items-center justify-center rounded-full px-0.5 text-[7px] font-bold leading-3 shadow-sm ring-1 ring-background ${a.className}`,children:a.count>9?"9+":a.count},a.key))})}const HP=380,gb=10,_h=10,wm=52,WP=104;function GP(e,t,r){const n=Math.max(0,t.safeLeft??0),a=t.width-Math.max(0,t.safeRight??0),c=Math.max(0,t.safeTop??0),l=t.height-Math.max(0,t.safeBottom??0),d=Mf,p=e.x+Ua/2>=n+(a-n)/2,m=p?e.x-_h-n-d:a-d-e.x-Ua-_h,x=Math.max(1,Math.min(Math.max(0,m),Math.max(168,r*WP))),y=p?e.x-_h-x:e.x+Ua+_h,w=Math.min(Math.max(y,n+d),Math.max(n+d,a-d-x)),v=e.y+Ua/2-wm/2,S=Math.min(Math.max(v,c+d),Math.max(c+d,l-d-wm));return{left:w,top:S,width:x,height:wm,itemWidth:x/Math.max(1,r),side:p?"left":"right"}}function xb(e,t,r,n){return t<e.left||t>e.left+e.width||r<e.top-14||r>e.top+e.height+14?null:Math.min(n-1,Math.max(0,Math.floor((t-e.left)/e.itemWidth)))}function VP(e,t){if(e.length===0)return null;const r=t?e.findIndex(n=>n.id===t):-1;return e[(r+1)%e.length]?.id??null}function qP({reviewCount:e,runningSessions:t,activeSessionId:r,runningButtonEnabled:n,attentionButtonEnabled:a=!0,isDesktopLayout:c,containerElement:l,occlusionInsets:d}){const{t:p}=Ur(),m=Wt(Ie=>Ie.leftOpen),x=Wt(Ie=>Ie.rightOpen),{isOpen:y}=rv({enabled:!c}),w=c||!m&&!x&&!y,v=LP(e),[S,L]=k.useState(!1);k.useEffect(()=>{(!v.active||!w)&&L(!1)},[v.active,w]);const E=a&&v.total>0&&w,R=t.length>1||t.length===1&&t[0]?.id!==r,B=n&&t.length>0&&R&&w,z=Math.max(0,d?.top??0),O=Math.max(0,d?.right??0),$=Math.max(0,d?.bottom??0),V=Math.max(0,d?.left??0),Z=k.useCallback(()=>OP(c,l,{top:z,right:O,bottom:$,left:V}),[l,c,$,V,O,z]),le=k.useRef({attention:pb(hb,BP),running:pb(fb,QP)}),be=k.useCallback(()=>{const Ie=Z(),Ge=lb(Ie,le.current.attention),Ce=lb(Ie,le.current.running);return{attention:Ge,running:E&&B?ub(Ie,Ce,Ge):Ce}},[E,Z,B]),[pe,ee]=k.useState(()=>be()),_e=k.useRef(pe);_e.current=pe;const[ze,Y]=k.useState(null),ce=k.useRef(null),[qe,we]=k.useState("idle"),[ye,Le]=k.useState(null),Be=k.useRef(null),ne=k.useRef({attention:!1,running:!1});k.useEffect(()=>()=>{const Ie=Be.current?.longPressTimer;Ie!=null&&window.clearTimeout(Ie)},[]),k.useEffect(()=>{if(B)return;const Ie=Be.current?.longPressTimer;Ie!=null&&window.clearTimeout(Ie),Be.current=null,we("idle"),Le(null)},[B]),k.useLayoutEffect(()=>{const Ie=()=>{const Ce=be();_e.current=Ce,ee(Ce)};Ie(),window.addEventListener("resize",Ie),window.addEventListener("orientationchange",Ie),window.visualViewport?.addEventListener("resize",Ie);const Ge=typeof ResizeObserver>"u"?null:new ResizeObserver(Ie);return l&&Ge?.observe(l),()=>{window.removeEventListener("resize",Ie),window.removeEventListener("orientationchange",Ie),window.visualViewport?.removeEventListener("resize",Ie),Ge?.disconnect()}},[l,be]);const Fe=k.useCallback(Ie=>Ie==="attention"?B:E,[E,B]),ke=k.useCallback((Ie,Ge)=>{if(!Fe(Ie))return Ge;const Ce=Ie==="attention"?"running":"attention";return ub(Z(),Ge,_e.current[Ce])},[Z,Fe]),Ee=k.useCallback((Ie,Ge,Ce,H)=>{const ae=Z(),Ae=Ge.moved?Hc(ae,{x:Ge.startX+(Ce-Ge.originX),y:Ge.startY+(H-Ge.originY)}):_e.current[Ie],Ye=cb(ae,Ae),et=ke(Ie,Ye.position),St=cb(ae,et);le.current[Ie]=St.preference,PP(Ie==="attention"?hb:fb,St.preference);const Gt={..._e.current,[Ie]:St.position};_e.current=Gt,ee(Gt)},[ke,Z]),Pe=k.useCallback(Ie=>{ne.current[Ie]=!0,window.setTimeout(()=>{ne.current[Ie]=!1},0)},[]),Ne=k.useCallback(Ie=>{const Ge=ce.current;!Ge||Ge.kind!=="attention"||Ge.pointerId!==Ie.pointerId||(ce.current=null,Y(null),Ee("attention",Ge,Ie.clientX,Ie.clientY),Ge.moved&&Pe("attention"))},[Ee,Pe]),oe={onPointerDown:Ie=>{Ie.stopPropagation(),Ie.currentTarget.setPointerCapture(Ie.pointerId),ce.current={kind:"attention",pointerId:Ie.pointerId,originX:Ie.clientX,originY:Ie.clientY,startX:pe.attention.x,startY:pe.attention.y,moved:!1}},onPointerMove:Ie=>{const Ge=ce.current;if(!Ge||Ge.kind!=="attention"||Ge.pointerId!==Ie.pointerId)return;const Ce=Ie.clientX-Ge.originX,H=Ie.clientY-Ge.originY;if(!Ge.moved&&Math.hypot(Ce,H)<5)return;Ge.moved=!0,Y("attention");const ae=Z(),Ae=ke("attention",Hc(ae,{x:Ge.startX+Ce,y:Ge.startY+H})),Ye={..._e.current,attention:Ae};_e.current=Ye,ee(Ye)},onPointerUp:Ne,onPointerCancel:Ne},We=l?GP(pe.running,Z(),t.length):null,nt=Ie=>{Ie.longPressTimer!==null&&(window.clearTimeout(Ie.longPressTimer),Ie.longPressTimer=null)},gt={onPointerDown:Ie=>{Ie.stopPropagation(),Ie.currentTarget.setPointerCapture(Ie.pointerId);const Ge=Ie.pointerId,Ce={pointerId:Ge,originX:Ie.clientX,originY:Ie.clientY,startX:pe.running.x,startY:pe.running.y,mode:"pressing",moved:!1,selectedIndex:null,longPressTimer:null};Ce.longPressTimer=window.setTimeout(()=>{const H=Be.current;!H||H.pointerId!==Ge||H.mode!=="pressing"||(H.longPressTimer=null,H.mode="dragging",ne.current.running=!0,we("dragging"))},HP),Be.current=Ce,we("pressing"),Le(null)},onPointerMove:Ie=>{const Ge=Be.current;if(!Ge||Ge.pointerId!==Ie.pointerId)return;const Ce=Ie.clientX-Ge.originX,H=Ie.clientY-Ge.originY;if(Ge.mode==="pressing")if(Math.abs(Ce)>=gb&&Math.abs(Ce)>=Math.abs(H))nt(Ge),Ge.mode="selecting",ne.current.running=!0,we("selecting");else if(Math.hypot(Ce,H)>=gb){nt(Ge),Ge.mode="cancelled",ne.current.running=!0,we("idle");return}else return;if(Ge.mode==="selecting"){const et=We?xb(We,Ie.clientX,Ie.clientY,t.length):null;Ge.selectedIndex=et,Le(et);return}if(Ge.mode!=="dragging"||!Ge.moved&&Math.hypot(Ce,H)<5)return;Ge.moved=!0;const ae=Z(),Ae=ke("running",Hc(ae,{x:Ge.startX+Ce,y:Ge.startY+H})),Ye={..._e.current,running:Ae};_e.current=Ye,ee(Ye)},onPointerUp:Ie=>{const Ge=Be.current;if(!Ge||Ge.pointerId!==Ie.pointerId)return;nt(Ge);const Ce=Ge.mode;if(Ce==="selecting"){const H=We?xb(We,Ie.clientX,Ie.clientY,t.length):Ge.selectedIndex,ae=H===null?null:t[H]?.id;ae&&mb(ae)}else Ce==="dragging"&&Ee("running",Ge,Ie.clientX,Ie.clientY);Be.current=null,we("idle"),Le(null),Ce!=="pressing"&&Pe("running")},onPointerCancel:Ie=>{const Ge=Be.current;!Ge||Ge.pointerId!==Ie.pointerId||(nt(Ge),Be.current=null,we("idle"),Le(null),Pe("running"))}},ue=(Ie,Ge)=>s.jsx("span",{className:`pointer-events-none absolute -right-1 -top-1 z-10 flex h-[18px] min-w-[18px] items-center justify-center rounded-full bg-surface px-1 text-[9px] font-bold tabular-nums ring-2 ring-[var(--chrome-bg)] ${Ge==="attention"?"text-[color:var(--warning)]":"text-[color:var(--success)]"}`,children:Ie>9?"9+":Ie}),Ze=()=>{const Ie=v.hasOtherAttention?p("serviceAttention.title"):p("agent.jumpToNext"),Ge=pe.attention,Ce=ze==="attention";return s.jsxs("button",{type:"button","data-attention-button":!0,"data-mobile-attention-button":!0,...oe,onClick:H=>{H.stopPropagation(),!ne.current.attention&&(v.hasOtherAttention?L(!0):B6())},className:`fixed z-chrome-hint inline-flex items-center justify-center rounded-full bg-[var(--warning)] text-[color:var(--warning-foreground)] shadow-[0_8px_24px_var(--app-shadow-strong)] ring-1 ring-[rgb(var(--warning-rgb)_/_0.35)] animate-fade-in ${Ce?"cursor-grabbing scale-[1.04] shadow-[0_12px_30px_var(--app-shadow-strong)]":"cursor-grab transition-[left,top,transform,box-shadow] duration-200 active:scale-95"}`,style:{display:S?"none":void 0,left:Ge.x,top:Ge.y,width:Ua,height:Ua,touchAction:"none"},"aria-label":`${Ie}: ${v.total}`,"aria-haspopup":v.hasOtherAttention?"dialog":void 0,title:Ie,children:[s.jsx(cc,{size:17,className:"shrink-0"}),ue(v.total,"attention")]},"attention")},at=()=>{const Ie=t.length,Ge=pe.running,Ce=qe==="selecting",H=qe==="dragging";return s.jsxs(k.Fragment,{children:[s.jsxs("button",{type:"button","data-running-session-button":!0,"data-running-session-gesture":qe,...gt,onClick:ae=>{if(ae.stopPropagation(),ne.current.running)return;const Ae=VP(t,r);Ae&&mb(Ae)},className:`fixed z-chrome-hint inline-flex select-none items-center justify-center rounded-full bg-[var(--success)] text-[color:var(--success-foreground)] shadow-[0_8px_24px_var(--app-shadow-strong)] ring-1 ring-[rgb(var(--success-rgb)_/_0.35)] animate-fade-in ${H?"cursor-grabbing scale-[1.04] shadow-[0_12px_30px_var(--app-shadow-strong)]":Ce?"cursor-ew-resize scale-[1.04] ring-2 ring-[rgb(var(--success-rgb)_/_0.55)]":"cursor-grab transition-[left,top,transform,box-shadow] duration-200 active:scale-95"}`,style:{left:Ge.x,top:Ge.y,width:Ua,height:Ua,touchAction:"none"},"aria-label":`${p("agent.jumpToNextRunning")}: ${Ie}`,title:p("agent.runningSessionGestureHint"),children:[s.jsx(_n,{size:18,className:"shrink-0 animate-spin"}),ue(Ie,"running")]}),Ce&&We&&s.jsx("div",{role:"listbox","data-running-session-rail":!0,"data-side":We.side,"aria-label":p("agent.selectRunningSession"),className:"pointer-events-none fixed z-popover flex overflow-hidden rounded-full border border-border/15 bg-surface/95 p-1 shadow-[0_18px_48px_var(--app-shadow-soft)] backdrop-blur animate-fade-in",style:{left:We.left,top:We.top,width:We.width,height:We.height},children:t.map((ae,Ae)=>{const Ye=Ae===ye,et=ae.id===r,St=`${ae.label}${ae.detail?` · ${ae.detail}`:""}${et?` · ${p("agent.currentSession")}`:""}`;return s.jsxs("div",{role:"option","aria-selected":Ye,"data-running-session-option":ae.id,"data-selected":Ye?"true":"false",title:St,className:`relative flex min-w-0 flex-1 items-center justify-center gap-1.5 rounded-full px-2 transition-[background-color,color,transform] duration-100 ${Ye?"scale-[1.02] bg-[var(--success)] text-[color:var(--success-foreground)]":et?"bg-primary/15 text-primary ring-1 ring-primary/30":"text-foreground"}`,children:[s.jsx("span",{className:`inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-[9px] font-bold tabular-nums ${Ye?"bg-surface/25":"bg-surface-2 text-muted-foreground"}`,children:Ae+1}),s.jsx("span",{className:"truncate text-[10px] font-medium",children:ae.label})]},ae.id)})})]},"running")};return!E&&!B&&!S||l===null||typeof document>"u"?null:s.jsxs(M8,{children:[E&&Ze(),B&&!S&&at(),S&&v.active&&w&&s.jsx(IP,{groups:v.groups,currentKey:v.currentKey,onClose:()=>L(!1)})]})}function YP(){const{t:e}=Ur();return s.jsxs("div",{role:"status",className:"td-loading-skeleton overflow-hidden px-3 py-2",children:[s.jsx("span",{className:"sr-only",children:e("common.loading")}),s.jsx("div",{"aria-hidden":"true",children:["w-2/5","w-3/5","w-1/3","w-1/2","w-2/5","w-1/3"].map((t,r)=>s.jsxs("div",{className:"flex h-8 items-center gap-2",style:{paddingLeft:r>1&&r<5?20:0},children:[s.jsx("div",{className:"h-3 w-3 shrink-0 rounded-sm bg-surface-2"}),s.jsx("div",{className:`h-2 rounded bg-surface-2 ${t}`})]},r))})]})}const ZP=new Set([".ts",".tsx",".js",".jsx",".py",".rs",".go",".java",".c",".cpp",".h",".rb",".php",".swift",".kt",".sh",".css",".scss",".html",".json",".yaml",".yml",".toml",".md"]),bb=120,yb=120,KP=new Set,XP=[],JP={added:{label:"A",className:"text-[color:var(--diff-insert-strong)]",title:"Added"},modified:{label:"M",className:"text-[color:var(--diff-hunk-accent)]",title:"Modified"},deleted:{label:"D",className:"text-[color:var(--diff-delete-strong)]",title:"Deleted"},renamed:{label:"R",className:"text-muted-foreground",title:"Renamed"},copied:{label:"C",className:"text-[color:var(--diff-insert-strong)]",title:"Copied"},untracked:{label:"U",className:"text-[color:var(--diff-insert-strong)]",title:"Untracked (new file)"},conflicted:{label:"!",className:"text-destructive",title:"Conflicted"},unknown:{label:"?",className:"text-muted-foreground",title:"Unknown"}};function kg(e,t){if(t==="directory")return null;if(B8(e))return s.jsx(DA,{size:14});if(Q8(e))return s.jsx(Wy,{size:14});const r=e.lastIndexOf(".")>=0?e.slice(e.lastIndexOf(".")):"";return ZP.has(r)?s.jsx(lT,{size:14}):s.jsx(Qy,{size:14})}function O6({path:e}){const r=Wt(a=>a.changedFiles.get(e))?.status;if(!r)return null;const n=JP[r]??{label:"?",className:"text-muted-foreground",title:r};return s.jsx("span",{className:`w-4 shrink-0 text-center text-[10px] font-mono font-bold ${n.className}`,title:n.title,children:n.label})}function Zu(e){return e?"ml-1 w-6 opacity-100":"ml-1 w-6 opacity-100 sm:ml-0 sm:w-0 sm:overflow-hidden sm:opacity-0 sm:group-hover:ml-1 sm:group-hover:w-6 sm:group-hover:opacity-100 sm:group-focus-within:ml-1 sm:group-focus-within:w-6 sm:group-focus-within:overflow-visible sm:group-focus-within:opacity-100"}function Lg(e){return Zu(e)}const eO=b.memo(function({path:t}){const{t:r}=Ur(),[n,a]=b.useState("idle"),[c,l]=b.useState(null),d=b.useCallback(async p=>{if(p.stopPropagation(),n!=="pending"){a("pending"),l(null);try{await Cy(t),a("idle")}catch(m){a("error"),l(m instanceof Error?m.message:r("rightSidebar.downloadFailed"))}}},[t,n,r]);return s.jsx("button",{type:"button",disabled:n==="pending","aria-label":r("rightSidebar.downloadFile"),onClick:p=>{d(p)},className:`inline-flex h-6 shrink-0 select-none items-center justify-center rounded-md text-muted-foreground transition focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-primary active:scale-95 ${Zu(n==="pending")} ${n==="pending"?"bg-surface-elevated text-foreground":"bg-surface-2 hover:bg-surface-elevated hover:text-foreground"}`,title:n==="error"?c??r("rightSidebar.downloadFailed"):r("rightSidebar.downloadFile"),children:n==="pending"?s.jsx(_n,{size:12,className:"animate-spin"}):s.jsx(g0,{size:12})})});function F6(){const{t:e}=Ur(),[t,r]=b.useState({status:"idle"}),n=b.useCallback(async a=>{r({status:"pending"});try{await Cy(a),r({status:"idle"})}catch(c){r({status:"error",message:c instanceof Error?c.message:e("rightSidebar.downloadFailed")})}},[e]);return{state:t,run:n}}function _1(e){return e instanceof DOMException&&e.name==="AbortError"}function jf(){if(typeof window>"u")return!1;const e=window.getSelection();return!!(e&&!e.isCollapsed&&e.toString().trim())}function $6(e){return e.button===2||e.ctrlKey}const tO=176,rO=160,Qd=8;function vb(e,t,r,n){const a=window.visualViewport,c=a?.offsetLeft??0,l=a?.offsetTop??0,d=c+(a?.width??window.innerWidth),p=l+(a?.height??window.innerHeight),m=c+Qd,x=l+Qd,y=Math.max(m,d-r-Qd),w=Math.max(x,p-n-Qd),v=t+n<=p-Qd?t:t-n;return{anchorX:e,anchorY:t,left:Math.min(Math.max(e,m),y),top:Math.min(Math.max(v,x),w)}}function U6(e){const[t,r]=b.useState(null),n=b.useRef(null),a=b.useCallback((c,l)=>{r(vb(c,l,tO,rO))},[]);return b.useLayoutEffect(()=>{if(!e||!t||!n.current)return;const c=n.current.getBoundingClientRect();if(c.width<=0||c.height<=0)return;const l=vb(t.anchorX,t.anchorY,c.width,c.height);l.left===t.left&&l.top===t.top||r(l)},[e,t]),{position:t,menuRef:n,openAt:a,clearPosition:()=>r(null)}}function z6(e,t){return t&&typeof document<"u"?Xs.createPortal(e,document.body):e}function nO(e,t){return t?`${e.name} ${e.path}`.toLowerCase().includes(t):!0}function Ig(e,t,r){if(!t||nO(e,t))return!0;const n=r.get(e.path);return n?n.some(a=>Ig(a,t,r)):!1}function k1(e){return e.map(t=>({name:t.name,path:t.path,type:t.type,isSymlink:t.isSymlink,modified:t.modified,expanded:!1,loaded:!1,children:t.type==="directory"?[]:void 0}))}function L1(e,t){return!e||!t.startsWith(e)?t:t.slice(e.length).replace(/^\/+/,"")||t}const sO=b.memo(function e({node:t,depth:r,onFileSelect:n,directoriesOnly:a=!1,onPathReference:c,referenceSelection:l,getReferenceText:d,onReferenceCopied:p,insertedReferenceKey:m,copiedReferenceKey:x,onDirectoryRoot:y,onSearchFromDirectory:w,onDirectoryPinToggle:v,onFilePinToggle:S,onOpenInFileBrowser:L,canOpenInFileBrowser:E,pinnedPaths:R,selectedFilePath:B,queryLower:z,onDirectoryDropFiles:O,onFileDeleteRequest:$,deletingFilePath:V,revealedDirectoryPath:Z,gitIgnoreRoot:le}){const{t:be}=Ur(),pe=Wt(xt=>xt.expandedPaths.has(t.path)),ee=Wt(xt=>xt.directoryCache.get(t.path)),_e=Wt(xt=>xt.showHiddenFiles),ze=Wt(xt=>xt.toggleExpanded),Y=Wt(xt=>xt.setDirectoryCache),ce=Wt(xt=>xt.fileSortModes[t.path]??"name"),qe=Wt(xt=>xt.setDirectorySortMode),[we,ye]=b.useState(!1),[Le,Be]=b.useState(!1),{position:ne,menuRef:Fe,openAt:ke,clearPosition:Ee}=U6(Le),[Pe,Ne]=b.useState(!1),oe=b.useRef(0),We=b.useRef(null),nt=`file-tree-reference:${b.useId()}:${t.path}`;Gc(Fe,Le&&!!l,()=>Be(!1));const gt=b.useRef(null),ue=t.path===B||t.path===Z,Ze=t.type==="directory"&&(pe||!!z),at=t.type==="directory",Ie=R.has(t.path),Ge=!at&&!!S,Ce=!!(E&&L),H=`path:${t.path}`,ae=m===H||!!l?.paths.has(t.path),Ae=x===H,Ye=d?.(t.path)??t.path,et=O1(p,!!l),{state:St,run:Gt}=F6(),Qt=V===t.path,wt=at&&!a&&!!(y||w||v||Ce),zt=b.useMemo(()=>{if(!ee)return;if(!z)return ee;const xt=Wt.getState().directoryCache;return ee.filter(Rt=>(!a||Rt.type==="directory")&&Ig(Rt,z,xt))},[ee,a,z]),Vt=b.useCallback(async()=>{if(!Wt.getState().directoryCache.has(t.path)&&!we){const Rt=l?nt:`file-tree:${t.path}`;We.current?.abort(),Fm(Rt);const Ct=new AbortController;We.current=Ct,ye(!0);try{const fr=await D1(t.path,Ct.signal,_e,"expand_directory",Rt,ce,le);if(Ct.signal.aborted)return;const Yt=k1(fr.entries);Y(t.path,Yt)}catch(fr){_1(fr)}finally{We.current===Ct&&(We.current=null),ye(!1)}}},[t.path,we,Y,_e,ce,le,!!l,nt]),Kt=b.useCallback(async()=>{if(t.type!=="directory"){n(t.path);return}if(a&&y){y(t.path);return}const xt=!Wt.getState().expandedPaths.has(t.path);ze(t.path),xt&&await Vt()},[a,t.path,t.type,Vt,y,ze,n]);b.useEffect(()=>{t.type==="directory"&&pe&&!ee&&!we&&Vt()},[ee,pe,Vt,we,t.type]);const Ot=b.useCallback(xt=>{xt.stopPropagation(),c?.(t.path,H)},[c,t.path,H]),It=b.useCallback(xt=>{xt.stopPropagation(),y?.(t.path),Be(!1)},[t.path,y]),xe=b.useCallback(xt=>{xt.stopPropagation(),w?.(t.path),Be(!1)},[t.path,w]),Ve=b.useCallback(xt=>{xt.stopPropagation(),v?.(t.path),Be(!1)},[t.path,v]),ht=b.useCallback(xt=>{xt.stopPropagation(),qe(t.path,ce==="modified"?"name":"modified"),Be(!1)},[t.path,qe,ce]),q=b.useCallback(xt=>{xt.stopPropagation(),S?.(t.path),Be(!1)},[t.path,S]),ut=b.useCallback(xt=>{xt.stopPropagation(),Be(!1),Gt(t.path)},[t.path,Gt]),qt=b.useCallback(xt=>{xt.stopPropagation(),Be(!1),$(t)},[t,$]),tt=b.useCallback(xt=>{xt.stopPropagation(),L?.(t.path),Be(!1)},[t.path,L]),De=b.useCallback(xt=>{!at||!O||!xt.dataTransfer.types.includes("Files")||(xt.preventDefault(),xt.stopPropagation(),oe.current+=1,Ne(!0))},[at,O]),nr=b.useCallback(xt=>{!at||!O||!xt.dataTransfer.types.includes("Files")||(xt.preventDefault(),xt.stopPropagation(),xt.dataTransfer.dropEffect="copy",Ne(!0))},[at,O]),Ke=b.useCallback(xt=>{!at||!O||(xt.preventDefault(),xt.stopPropagation(),oe.current-=1,oe.current<=0&&(oe.current=0,Ne(!1)))},[at,O]),_t=b.useCallback(xt=>{if(!at||!O)return;xt.preventDefault(),xt.stopPropagation(),oe.current=0,Ne(!1);const Rt=Array.from(xt.dataTransfer.files);Rt.length>0&&O(t.path,Rt)},[at,t.path,O]),$t=b.useCallback(xt=>{xt.stopPropagation(),l?ke(xt.clientX,xt.clientY):Ee(),Be(Rt=>!Rt)},[Ee,ke,!!l]),yt=b.useCallback(xt=>{!wt||!$6(xt)||(xt.preventDefault(),xt.stopPropagation(),ke(xt.clientX,xt.clientY),Be(!0))},[wt,ke]);return b.useEffect(()=>{if(!Le)return;const xt=Ct=>{const fr=Ct.target;fr instanceof Node&&(gt.current?.contains(fr)||Fe.current?.contains(fr))||Be(!1)},Rt=Ct=>{Ct.key==="Escape"&&Be(!1)};return document.addEventListener("pointerdown",xt),document.addEventListener("keydown",Rt),()=>{document.removeEventListener("pointerdown",xt),document.removeEventListener("keydown",Rt)}},[Le,Fe]),b.useEffect(()=>()=>{We.current?.abort()},[]),s.jsxs("div",{style:!Ze&&!Le?{contentVisibility:"auto",containIntrinsicSize:"auto 32px"}:void 0,children:[s.jsxs("div",{ref:gt,className:"relative",children:[et.popoverNode,s.jsxs("div",{"data-file-tree-path":t.path,"data-sort-mode":ce,role:"button",tabIndex:0,onClick:()=>{jf()||Kt()},onContextMenu:yt,onKeyDown:xt=>{xt.target!==xt.currentTarget||xt.key!=="Enter"&&xt.key!==" "||(xt.preventDefault(),Kt())},onDragEnter:De,onDragOver:nr,onDragLeave:Ke,onDrop:_t,className:`group relative flex w-full cursor-pointer items-center gap-1 rounded px-2 py-1 text-[13px] transition ${Pe?"scale-[1.015] bg-primary/15 text-foreground shadow-[0_0_0_1px_rgb(var(--primary-rgb)_/_0.45)]":ue?"bg-surface-elevated text-foreground":"text-muted-foreground hover:bg-surface-2 hover:text-foreground"}`,title:t.path,children:[r>0&&s.jsx("span",{"aria-hidden":"true",className:"shrink-0",style:{width:`${r*14-4}px`}}),Pe&&s.jsx("span",{className:"pointer-events-none absolute right-2 top-1/2 z-10 -translate-y-1/2 rounded-full bg-primary px-2 py-0.5 text-[10px] font-semibold text-primary-foreground shadow-md",children:be("fileTree.dropToUploadHere")}),t.type==="directory"?s.jsxs(s.Fragment,{children:[Ze?s.jsx(ul,{size:14,className:"shrink-0 text-muted-foreground/80"}):s.jsx(Ks,{size:14,className:"shrink-0 text-muted-foreground/80"}),Ze?s.jsx(Du,{size:14,className:"shrink-0 text-[color:var(--folder)]"}):s.jsx(Vc,{size:14,className:"shrink-0 text-[color:var(--folder)]"})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-[14px] shrink-0"}),s.jsx("span",{className:ue?"text-primary":"text-muted-foreground/80",children:kg(t.name,t.type)})]}),s.jsxs("span",{className:`flex-1 select-text whitespace-nowrap text-left leading-snug ${ue?"font-medium":""}`,children:[t.name,ce==="modified"&&s.jsx("span",{className:"ml-1 inline-flex align-middle text-primary",title:be("fileTree.sortedByModified"),"aria-label":be("fileTree.sortedByModified"),children:s.jsx(m0,{size:11})}),t.isSymlink&&s.jsx("span",{className:"ml-1 inline-flex align-middle text-muted-foreground/70",title:be("fileTree.symbolicLink"),children:s.jsx(Uu,{size:11})})]}),s.jsxs("div",{className:`sticky right-0 z-20 flex shrink-0 items-center rounded pl-1 ${ue?"bg-surface-elevated":"bg-surface group-hover:bg-surface-2"}`,onClick:xt=>xt.stopPropagation(),children:[we&&s.jsx(_n,{size:12,className:"shrink-0 animate-spin text-muted-foreground"}),s.jsx(O6,{path:t.path}),wt&&s.jsx("button",{type:"button",onClick:$t,className:`inline-flex h-6 shrink-0 select-none items-center justify-center rounded-md text-muted-foreground transition focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-primary active:scale-95 ${Zu(Le)} ${Le?"bg-surface-elevated text-foreground":"bg-surface-2 hover:bg-surface-elevated hover:text-foreground"}`,"aria-label":be("fileTree.moreDirActions"),"aria-expanded":Le,title:be("fileTree.moreDirActions"),children:s.jsx(To,{size:13})}),!at&&!l&&s.jsx("button",{type:"button",onClick:$t,className:`inline-flex h-6 shrink-0 select-none items-center justify-center rounded-md text-muted-foreground transition focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-primary active:scale-95 ${Zu(Le||St.status==="pending"||Qt||Ie)} ${Le?"bg-surface-elevated text-foreground":Ie?"bg-primary/15 text-primary":"bg-surface-2 hover:bg-surface-elevated hover:text-foreground"}`,"aria-label":be("fileTree.moreFileActions"),"aria-expanded":Le,title:St.status==="error"?St.message??be("rightSidebar.downloadFailed"):be("fileTree.moreFileActions"),children:St.status==="pending"||Qt?s.jsx(_n,{size:13,className:"animate-spin"}):s.jsx(To,{size:13})}),c&&s.jsx("button",{type:"button",onClick:Ot,...et(Ye,H),className:`inline-flex h-6 shrink-0 select-none items-center justify-center rounded-md text-[11px] font-semibold transition focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-primary active:scale-95 ${l?"ml-1 min-h-11 min-w-11":Lg(ae||Ae)} ${ae||Ae?"bg-surface-elevated text-foreground":"bg-primary/10 text-primary"}`,"aria-label":l?`${l.label}: ${t.name}`:be(Ae?"rightSidebar.copied":ae?"rightSidebar.inserted":"fileTree.insertRefTitle"),"aria-pressed":l?ae:void 0,disabled:!!l?.disabled&&!ae,title:l?`${l.label}: ${t.name}`:be(Ae?"rightSidebar.copied":ae?"rightSidebar.inserted":"fileTree.insertRefTitle"),children:Ae||ae?s.jsx(pi,{size:12}):s.jsx(Uu,{size:12})}),wt&&Le&&z6(s.jsxs("div",{ref:Fe,className:`${ne?l?"fixed z-popover":"fixed z-menu-panel":"absolute right-2 top-[calc(100%+2px)] z-30"} w-44 overflow-hidden rounded-xl border border-border/15 bg-surface/98 p-1 text-[12px] shadow-xl shadow-[0_18px_48px_var(--app-shadow-soft)] backdrop-blur animate-fade-in`,style:ne?{left:ne.left,top:ne.top}:void 0,children:[Ce&&s.jsxs("button",{type:"button",onClick:tt,className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left font-medium text-foreground transition hover:bg-surface-2 active:scale-[0.99]",title:be("fileTree.openInFileBrowserTitle"),children:[s.jsx(Du,{size:13,className:"shrink-0 text-[color:var(--folder)]"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:be("fileTree.openInFileBrowser")})]}),y&&s.jsxs("button",{type:"button",onClick:It,className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left font-medium text-foreground transition hover:bg-surface-2 active:scale-[0.99]",title:be("fileTree.openDirRootTitle"),children:[s.jsx(Du,{size:13,className:"shrink-0 text-[color:var(--folder)]"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:be("fileTree.openDirRoot")})]}),w&&s.jsxs("button",{type:"button",onClick:xe,className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left font-medium text-foreground transition hover:bg-surface-2 active:scale-[0.99]",title:be("fileTree.searchFromDirTitle"),children:[s.jsx(F1,{size:13,className:"shrink-0 text-primary"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:be("fileTree.searchFromDir")})]}),v&&s.jsxs("button",{type:"button",onClick:Ve,className:`flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left font-medium transition active:scale-[0.99] ${Ie?"text-primary hover:bg-primary/10":"text-foreground hover:bg-surface-2"}`,title:be(Ie?"fileTree.unpinDirTitle":"fileTree.pinDirTitle"),children:[Ie?s.jsx(b0,{size:13,className:"shrink-0"}):s.jsx(x0,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:be(Ie?"fileTree.unpinDir":"fileTree.pinDir")})]}),s.jsxs("button",{type:"button",onClick:ht,className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left font-medium text-foreground transition hover:bg-surface-2 active:scale-[0.99]",children:[ce==="modified"?s.jsx(LA,{size:13,className:"shrink-0"}):s.jsx(m0,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:be(ce==="modified"?"fileTree.sortByName":"fileTree.sortByModified")})]})]}),!!ne),!at&&!l&&Le&&s.jsxs("div",{className:"absolute right-2 top-[calc(100%+2px)] z-30 w-44 overflow-hidden rounded-xl border border-border/15 bg-surface/98 p-1 text-[12px] shadow-xl shadow-[0_18px_48px_var(--app-shadow-soft)] backdrop-blur animate-fade-in",children:[Ce&&s.jsxs("button",{type:"button",onClick:tt,className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left font-medium text-foreground transition hover:bg-surface-2 active:scale-[0.99]",title:be("fileTree.openInFileBrowserTitle"),children:[s.jsx(Qy,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:be("fileTree.openInFileBrowser")})]}),s.jsxs("button",{type:"button",onClick:ut,className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left font-medium text-foreground transition hover:bg-surface-2 active:scale-[0.99]",title:be("rightSidebar.downloadFile"),children:[s.jsx(g0,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:be("rightSidebar.downloadFile")})]}),Ge&&s.jsxs("button",{type:"button",onClick:q,className:`flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left font-medium transition active:scale-[0.99] ${Ie?"text-primary hover:bg-primary/10":"text-foreground hover:bg-surface-2"}`,title:be(Ie?"fileTree.unpinFileTitle":"fileTree.pinFileTitle"),children:[Ie?s.jsx(b0,{size:13,className:"shrink-0"}):s.jsx(x0,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:be(Ie?"fileTree.unpinFile":"fileTree.pinFile")})]}),s.jsxs("button",{type:"button",onClick:qt,disabled:Qt,className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left font-medium text-destructive transition hover:bg-destructive/10 active:scale-[0.99] disabled:opacity-50",title:be("fileTree.deleteFile"),children:[Qt?s.jsx(_n,{size:13,className:"shrink-0 animate-spin"}):s.jsx(Rs,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:be("fileTree.deleteFile")})]})]})]})]})]}),Ze&&zt&&zt.length>0&&s.jsx("div",{className:r===0?"mt-0.5":"",children:zt.map(xt=>s.jsx(e,{node:xt,depth:r+1,onFileSelect:n,directoriesOnly:a,onPathReference:c,referenceSelection:l,getReferenceText:d,onReferenceCopied:p,onDirectoryRoot:y,onSearchFromDirectory:w,onDirectoryPinToggle:v,onFilePinToggle:S,onOpenInFileBrowser:L,canOpenInFileBrowser:E,pinnedPaths:R,selectedFilePath:B,queryLower:z,insertedReferenceKey:m,copiedReferenceKey:x,onDirectoryDropFiles:O,onFileDeleteRequest:$,deletingFilePath:V,gitIgnoreRoot:le,revealedDirectoryPath:Z},xt.path))})]})}),iO=b.memo(function({node:t,rootPath:r,onFileSelect:n,onPathReference:a,referenceSelection:c,getReferenceText:l,onReferenceCopied:d,insertedReferenceKey:p,copiedReferenceKey:m,onDirectoryRoot:x,onSearchFromDirectory:y,onDirectoryPinToggle:w,onFilePinToggle:v,pinnedPaths:S,selectedFilePath:L,onFileDeleteRequest:E,deletingFilePath:R}){const{t:B}=Ur(),z=t.path===L,O=t.type==="directory",$=S.has(t.path),V=!O&&!!v,Z=`path:${t.path}`,le=p===Z||!!c?.paths.has(t.path),be=m===Z,pe=l?.(t.path)??t.path,ee=O1(d,!!c),{state:_e,run:ze}=F6(),[Y,ce]=b.useState(!1),{position:qe,menuRef:we,openAt:ye,clearPosition:Le}=U6(Y);Gc(we,Y&&!!c,()=>ce(!1));const Be=b.useRef(null),ne=R===t.path,Fe=O&&!!(x||y||w),ke=b.useCallback(()=>{jf()||(t.type==="directory"?x?.(t.path):n(t.path))},[t.path,t.type,x,n]),Ee=b.useCallback(ue=>{ue.stopPropagation(),a?.(t.path,Z)},[a,t.path,Z]),Pe=b.useCallback(ue=>{ue.stopPropagation(),w?.(t.path),ce(!1)},[t.path,w]),Ne=b.useCallback(ue=>{ue.stopPropagation(),v?.(t.path),ce(!1)},[t.path,v]),oe=b.useCallback(ue=>{ue.stopPropagation(),ce(!1),ze(t.path)},[t.path,ze]),We=b.useCallback(ue=>{ue.stopPropagation(),ce(!1),E(t)},[t,E]),nt=b.useCallback(ue=>{ue.stopPropagation(),c?ye(ue.clientX,ue.clientY):Le(),ce(Ze=>!Ze)},[Le,ye,!!c]),gt=b.useCallback(ue=>{!Fe||!$6(ue)||(ue.preventDefault(),ue.stopPropagation(),ye(ue.clientX,ue.clientY),ce(!0))},[Fe,ye]);return b.useEffect(()=>{if(!Y)return;const ue=at=>{const Ie=at.target;Ie instanceof Node&&(Be.current?.contains(Ie)||we.current?.contains(Ie))||ce(!1)},Ze=at=>{at.key==="Escape"&&ce(!1)};return document.addEventListener("pointerdown",ue),document.addEventListener("keydown",Ze),()=>{document.removeEventListener("pointerdown",ue),document.removeEventListener("keydown",Ze)}},[Y,we]),s.jsxs("div",{ref:Be,className:"relative border-b border-border/10 last:border-b-0",children:[ee.popoverNode,s.jsxs("div",{role:"button",tabIndex:0,onClick:ke,onContextMenu:gt,onKeyDown:ue=>{ue.target!==ue.currentTarget||ue.key!=="Enter"&&ue.key!==" "||(ue.preventDefault(),ke())},className:`group flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-2 text-left text-[13px] transition ${z?"bg-surface-elevated text-foreground":"text-muted-foreground hover:bg-surface-2 hover:text-foreground"}`,title:t.path,children:[t.type==="directory"?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-[14px] shrink-0"}),s.jsx(Vc,{size:14,className:"shrink-0 text-[color:var(--folder)]"})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-[14px] shrink-0"}),s.jsx("span",{className:z?"text-primary":"text-muted-foreground/80",children:kg(t.name,t.type)})]}),s.jsxs("span",{className:"min-w-0 flex-1 select-text",children:[s.jsxs("span",{className:`block whitespace-normal break-all font-medium leading-snug ${z?"text-primary":"text-foreground"}`,children:[t.name,t.isSymlink&&s.jsx("span",{className:"ml-1 inline-flex align-middle text-muted-foreground/70",title:B("fileTree.symbolicLink"),children:s.jsx(Uu,{size:11})})]}),s.jsx("span",{className:"mt-0.5 block truncate font-mono text-[10px] text-muted-foreground/80",children:L1(r,t.path)})]}),s.jsx(O6,{path:t.path}),t.type==="directory"&&(w||y)&&s.jsx("button",{type:"button",onClick:nt,className:`inline-flex h-6 shrink-0 select-none items-center justify-center rounded-md text-muted-foreground transition focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-primary active:scale-95 ${Zu(Y)} ${Y?"bg-surface-elevated text-foreground":"bg-surface-2 hover:bg-surface-elevated hover:text-foreground"}`,"aria-label":B("fileTree.moreDirActions"),"aria-expanded":Y,title:B("fileTree.moreDirActions"),children:s.jsx(To,{size:13})}),!O&&!c&&s.jsx("button",{type:"button",onClick:nt,className:`inline-flex h-6 shrink-0 select-none items-center justify-center rounded-md text-muted-foreground transition focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-primary active:scale-95 ${Zu(Y||_e.status==="pending"||ne||$)} ${Y?"bg-surface-elevated text-foreground":$?"bg-primary/15 text-primary":"bg-surface-2 hover:bg-surface-elevated hover:text-foreground"}`,"aria-label":B("fileTree.moreFileActions"),"aria-expanded":Y,title:_e.status==="error"?_e.message??B("rightSidebar.downloadFailed"):B("fileTree.moreFileActions"),children:_e.status==="pending"||ne?s.jsx(_n,{size:13,className:"animate-spin"}):s.jsx(To,{size:13})}),a&&s.jsx("button",{type:"button",onClick:Ee,...ee(pe,Z),className:`inline-flex h-6 shrink-0 select-none items-center justify-center rounded-md text-[11px] font-semibold transition focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-primary active:scale-95 ${c?"ml-1 min-h-11 min-w-11":Lg(le||be)} ${le||be?"bg-surface-elevated text-foreground":"bg-primary/10 text-primary"}`,"aria-label":c?`${c.label}: ${t.name}`:B(be?"rightSidebar.copied":le?"rightSidebar.inserted":"fileTree.insertRefTitle"),"aria-pressed":c?le:void 0,disabled:!!c?.disabled&&!le,title:c?`${c.label}: ${t.name}`:B(be?"rightSidebar.copied":le?"rightSidebar.inserted":"fileTree.insertRefTitle"),children:be||le?s.jsx(pi,{size:12}):s.jsx(Uu,{size:12})})]}),Fe&&Y&&z6(s.jsxs("div",{ref:we,className:`${qe?c?"fixed z-popover":"fixed z-menu-panel":"absolute right-2 top-[calc(100%+2px)] z-30"} w-44 overflow-hidden rounded-xl border border-border/15 bg-surface/98 p-1 text-[12px] shadow-xl shadow-[0_18px_48px_var(--app-shadow-soft)] backdrop-blur animate-fade-in`,style:qe?{left:qe.left,top:qe.top}:void 0,children:[x&&s.jsxs("button",{type:"button",onClick:ue=>{ue.stopPropagation(),x(t.path),ce(!1)},className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left font-medium text-foreground transition hover:bg-surface-2 active:scale-[0.99]",title:B("fileTree.openDirRootTitle"),children:[s.jsx(Du,{size:13,className:"shrink-0 text-[color:var(--folder)]"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:B("fileTree.openDirRoot")})]}),y&&s.jsxs("button",{type:"button",onClick:ue=>{ue.stopPropagation(),y(t.path),ce(!1)},className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left font-medium text-foreground transition hover:bg-surface-2 active:scale-[0.99]",children:[s.jsx(F1,{size:13,className:"shrink-0 text-primary"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:B("fileTree.searchFromDir")})]}),w&&s.jsxs("button",{type:"button",onClick:Pe,className:`flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left font-medium transition active:scale-[0.99] ${$?"text-primary hover:bg-primary/10":"text-foreground hover:bg-surface-2"}`,title:B($?"fileTree.unpinDirTitle":"fileTree.pinDirTitle"),children:[$?s.jsx(b0,{size:13,className:"shrink-0"}):s.jsx(x0,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:B($?"fileTree.unpinDir":"fileTree.pinDir")})]})]}),!!qe),!O&&!c&&Y&&s.jsxs("div",{className:"absolute right-2 top-[calc(100%+2px)] z-30 w-44 overflow-hidden rounded-xl border border-border/15 bg-surface/98 p-1 text-[12px] shadow-xl shadow-[0_18px_48px_var(--app-shadow-soft)] backdrop-blur animate-fade-in",children:[s.jsxs("button",{type:"button",onClick:oe,className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left font-medium text-foreground transition hover:bg-surface-2 active:scale-[0.99]",title:B("rightSidebar.downloadFile"),children:[s.jsx(g0,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:B("rightSidebar.downloadFile")})]}),V&&s.jsxs("button",{type:"button",onClick:Ne,className:`flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left font-medium transition active:scale-[0.99] ${$?"text-primary hover:bg-primary/10":"text-foreground hover:bg-surface-2"}`,title:B($?"fileTree.unpinFileTitle":"fileTree.pinFileTitle"),children:[$?s.jsx(b0,{size:13,className:"shrink-0"}):s.jsx(x0,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:B($?"fileTree.unpinFile":"fileTree.pinFile")})]}),s.jsxs("button",{type:"button",onClick:We,disabled:ne,className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left font-medium text-destructive transition hover:bg-destructive/10 active:scale-[0.99] disabled:opacity-50",title:B("fileTree.deleteFile"),children:[ne?s.jsx(_n,{size:13,className:"shrink-0 animate-spin"}):s.jsx(Rs,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:B("fileTree.deleteFile")})]})]})]})}),aO=60,wb=60,oO=20;function Ab({count:e,loading:t,engine:r,limited:n,scope:a,content:c}){const{t:l}=Ur();return s.jsxs("div",{className:"sticky top-0 z-10 -mx-2 -mt-2 mb-2 border-b border-border/15 bg-surface/95 px-3 py-2.5 backdrop-blur",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-2 text-[12px] font-semibold text-foreground",children:[s.jsx(F1,{size:14,className:"shrink-0 text-primary"}),s.jsx("span",{children:c?l("fileTree.contentMatchesCount",{count:e}):l("fileTree.searchResults",{count:e})})]}),r&&s.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1 rounded-full bg-surface-2 px-2 py-0.5 text-[9px] uppercase tracking-[0.12em] text-muted-foreground",children:[t&&s.jsx(_n,{size:9,className:"animate-spin"}),r,n?" · limited":""]})]}),s.jsxs("div",{className:"mt-1 flex min-w-0 items-center gap-1.5 text-[10px] text-muted-foreground",children:[s.jsx("span",{className:"shrink-0",children:l("fileTree.searchScope")}),s.jsx("span",{className:"min-w-0 truncate font-mono text-foreground/75",title:a,children:a}),t&&s.jsx("span",{className:"ml-auto shrink-0",children:l("fileTree.searching")})]})]})}function lO(e,t){if(!t)return e;const r=e.toLowerCase(),n=t.toLowerCase(),a=[];let c=0,l=r.indexOf(n,c),d=0;for(;l>=0&&n;)l>c&&a.push(e.slice(c,l)),a.push(s.jsx("mark",{className:"rounded-sm bg-[rgb(var(--warning-rgb)_/_0.30)] px-0.5 text-foreground",children:e.slice(l,l+n.length)},`m-${d++}`)),c=l+n.length,l=r.indexOf(n,c);return c<e.length&&a.push(e.slice(c)),a.length>0?a:e}const cO=b.memo(function({entry:t,rootPath:r,selectedFilePath:n,query:a,onContentMatchSelect:c,onPathReference:l,referenceSelection:d,getReferenceText:p,onReferenceCopied:m,insertedReferenceKey:x,copiedReferenceKey:y}){const{t:w}=Ur(),[v,S]=b.useState(!0),L=t.path===n,E=v?t.matches.slice(0,oO):[],R=t.matches.length-E.length,B=`path:${t.path}`,z=x===B||!!d?.paths.has(t.path),O=y===B,$=p?.(t.path)??t.path,V=O1(m,!!d);return s.jsxs("div",{className:"border-b border-border/10 last:border-b-0",children:[V.popoverNode,s.jsxs("div",{role:"button",tabIndex:0,onClick:()=>{jf()||S(Z=>!Z)},onKeyDown:Z=>{Z.target!==Z.currentTarget||Z.key!=="Enter"&&Z.key!==" "||(Z.preventDefault(),S(le=>!le))},className:`group flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-2 text-left text-[13px] transition ${L?"bg-surface-elevated text-foreground":"text-muted-foreground hover:bg-surface-2 hover:text-foreground"}`,title:t.path,children:[v?s.jsx(ul,{size:14,className:"shrink-0 text-muted-foreground/80"}):s.jsx(Ks,{size:14,className:"shrink-0 text-muted-foreground/80"}),s.jsx("span",{className:L?"text-primary":"text-muted-foreground/80",children:kg(t.name,"file")}),s.jsxs("span",{className:"min-w-0 flex-1 select-text",children:[s.jsx("span",{className:"block whitespace-normal break-all font-medium leading-snug",children:t.name}),s.jsx("span",{className:"mt-0.5 block truncate font-mono text-[10px] text-muted-foreground/80",children:L1(r,t.path)})]}),s.jsx("span",{className:"shrink-0 select-none rounded-full bg-surface-2 px-1.5 py-0.5 text-[10px] text-muted-foreground",children:t.matches.length}),!d&&s.jsx(eO,{path:t.path}),l&&s.jsx("button",{type:"button",onClick:Z=>{Z.stopPropagation(),l(t.path,B)},...V($,B),className:`inline-flex h-6 shrink-0 select-none items-center justify-center rounded-md text-[11px] font-semibold transition focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-primary active:scale-95 ${d?"ml-1 min-h-11 min-w-11":Lg(z||O)} ${z||O?"bg-surface-elevated text-foreground":"bg-primary/10 text-primary"}`,"aria-label":d?`${d.label}: ${t.name}`:w(O?"rightSidebar.copied":z?"rightSidebar.inserted":"fileTree.insertRefTitle"),"aria-pressed":d?z:void 0,disabled:!!d?.disabled&&!z,title:d?`${d.label}: ${t.name}`:w(O?"rightSidebar.copied":z?"rightSidebar.inserted":"fileTree.insertRefTitle"),children:O||z?s.jsx(pi,{size:12}):s.jsx(Uu,{size:12})})]}),v&&s.jsxs("div",{className:"mb-1 ml-3 border-l border-border/20 pl-1",children:[E.map((Z,le)=>s.jsxs("div",{role:"button",tabIndex:0,onClick:()=>{jf()||c?.(t.path,Z.line)},onKeyDown:be=>{be.target!==be.currentTarget||be.key!=="Enter"&&be.key!==" "||(be.preventDefault(),c?.(t.path,Z.line))},className:"flex w-full cursor-pointer items-start gap-2 rounded px-2 py-1 text-left font-mono text-[11px] text-muted-foreground transition hover:bg-surface-2 hover:text-foreground",title:`${L1(r,t.path)}:${Z.line}`,children:[s.jsx("span",{className:"shrink-0 select-none tabular-nums text-muted-foreground/60",children:Z.line}),s.jsx("span",{className:"min-w-0 flex-1 truncate whitespace-pre select-text",children:lO(Z.text,a)})]},`${Z.line}-${le}`)),R>0&&s.jsx("div",{className:"px-2 py-1 text-[10px] text-muted-foreground/70",children:w("fileTree.moreMatches",{count:R})})]})]})});function uO({rootPath:e,onFileSelect:t,directoriesOnly:r=!1,onPathReference:n,referenceSelection:a,getReferenceText:c,onReferenceCopied:l,insertedReferenceKey:d,copiedReferenceKey:p,onDirectoryRoot:m,onSearchFromDirectory:x,onDirectoryPinToggle:y,onFilePinToggle:w,onOpenInFileBrowser:v,canOpenInFileBrowser:S=!1,pinnedPaths:L=KP,selectedFilePath:E,query:R="",searchRootPath:B,searchOptions:z={},searchMode:O="name",onContentMatchSelect:$,onDirectoryDropFiles:V,revealDirectory:Z}){const{t:le}=Ur(),be=b.useId(),pe=a?`file-tree-reference-root:${be}:${e}`:`file-tree-root:${e}`,ee=Wt(tt=>e?tt.directoryCache.get(e):void 0),_e=Wt(tt=>tt.setDirectoryCache),ze=Wt(tt=>tt.showHiddenFiles),Y=Wt(tt=>tt.fileSortModesHydrated),ce=Wt(tt=>tt.fileSortModes[e]??"name"),qe=Wt(tt=>tt.hydrateFileSortModes),we=Wt(tt=>tt.hydrateHideGitIgnoredRoots),ye=Wt(tt=>!!tt.hideGitIgnoredRoots[e]),Le=Wt(tt=>tt.hideGitIgnoredRootsHydrated),Be=Wt(tt=>JSON.stringify(tt.gitIgnoreExceptions[e]??[])),ne=Wt(tt=>tt.invalidateDirectoryCache),Fe=`${e}:${ye}:${Be}`,[ke,Ee]=b.useState("");b.useLayoutEffect(()=>{e&&ne(e,!0),Ee(Fe)},[e,ye,Be,ne,Fe]);const[Pe,Ne]=b.useState(!1),[oe,We]=b.useState(null),[nt,gt]=b.useState(!1),[ue,Ze]=b.useState(!1),[at,Ie]=b.useState(null),[Ge,Ce]=b.useState(Y&&Le),H=Y&&Le||Ge;b.useEffect(()=>{let tt=!1;return Promise.all([qe(),we()]).catch(()=>{}).finally(()=>{tt||Ce(!0)}),()=>{tt=!0}},[qe,we]);const[ae,Ae]=b.useState([]),[Ye,et]=b.useState(null),[St,Gt]=b.useState(bb),[Qt,wt]=b.useState([]),[zt,Vt]=b.useState(null),Kt=b.useRef(null),Ot=b.useRef(0),It=R.trim().toLowerCase(),xe=O==="content",Ve=B||e,ht=z.excludePatterns??XP,q=ht.join(`
|
|
137
137
|
`);b.useEffect(()=>{const tt=Z?.path;if(!tt||!tt.startsWith(`${e}/`)&&tt!==e)return;const De=tt.slice(e.length).replace(/^\/+/,""),nr=De?De.split("/"):[],Ke=nr.map((fr,Yt)=>`${e}/${nr.slice(0,Yt+1).join("/")}`),_t=Wt.getState(),$t=Ke.filter(fr=>!_t.expandedPaths.has(fr));$t.length>0&&Wt.setState(fr=>({expandedPaths:new Set([...fr.expandedPaths,...$t])}));let yt=!1,xt=0;const Rt=()=>{if(yt)return;const fr=Array.from(document.querySelectorAll("[data-file-tree-path]")).find(Yt=>Yt.dataset.fileTreePath===tt);if(fr){fr.scrollIntoView({block:"center",behavior:"smooth"});return}xt+=1,xt<80&&window.setTimeout(Rt,50)},Ct=window.requestAnimationFrame(Rt);return()=>{yt=!0,window.cancelAnimationFrame(Ct)}},[Z?.nonce,Z?.path,e]);const ut=b.useCallback(async tt=>{if(!(zt||tt.type==="directory")&&window.confirm(le("fileTree.deleteFileConfirm",{name:tt.name}))){Vt(tt.path);try{await j8(tt.path),Wt.getState().applyFileWatchEvents([{type:"deleted",path:tt.path}]),Ae(De=>De.filter(nr=>nr.path!==tt.path)),wt(De=>De.filter(nr=>nr.path!==tt.path)),L.has(tt.path)&&w?.(tt.path)}catch(De){const nr=De instanceof Error?De.message:String(De);window.alert(le("fileTree.deleteFileFailed",{message:nr}))}finally{Vt(null)}}},[zt,w,L,le]);b.useEffect(()=>{if(!e||!H||ke!==Fe)return;if(It){Ne(!1);return}if(Wt.getState().directoryCache.has(e)){Ne(!1);return}let tt=!1;const De=new AbortController;return Ne(!0),We(null),D1(e,De.signal,ze,"load_file_tree_root",pe,ce,e).then(nr=>{if(tt)return;const Ke=k1(nr.entries);gt(!!nr.truncated),_e(e,Ke)}).catch(nr=>{tt||_1(nr)||We(nr instanceof Error?nr.message:"Failed to load directory")}).finally(()=>{tt||Ne(!1)}),()=>{tt=!0,De.abort(),Fm(pe)}},[It,ee,e,ce,_e,ze,H,ye,Be,pe,ke,Fe]),b.useEffect(()=>{if(!Ve||!It){Ze(!1),Ie(null),Ae([]),wt([]),et(null);return}let tt=!1;const De=new AbortController,nr=new Set;Ze(!0),Ie(null),Ae([]),wt([]),Gt(xe?aO:bb),et({truncated:!1,total:0,engine:"rg",limited:!1,done:!1});const Ke=`file-search:${a?be+":":""}${Ve}:${++Ot.current}`;return D8(Ve,R.trim(),_t=>{if(!tt){if(_t.engine&&et($t=>({truncated:$t?.truncated??!1,total:$t?.total??0,engine:_t.engine,limited:_t.limited??$t?.limited??!1,done:$t?.done??!1})),_t.entries?.length){const $t=_t.entries.filter(yt=>nr.has(yt.path)?!1:(nr.add(yt.path),!0));$t.length>0&&(Ae(yt=>[...yt,...k1($t)]),et(yt=>yt?{...yt,total:nr.size}:{truncated:!1,total:nr.size,engine:"rg",limited:!1,done:!1}))}if(_t.contentEntries?.length){const $t=_t.contentEntries.filter(yt=>nr.has(yt.path)?!1:(nr.add(yt.path),!0));$t.length>0&&(wt(yt=>[...yt,...$t]),et(yt=>yt?{...yt,total:nr.size}:{truncated:!1,total:nr.size,engine:"rg",limited:!1,done:!1}))}_t.done&&et($t=>({truncated:!!_t.truncated,total:typeof _t.total=="number"?_t.total:nr.size,engine:_t.engine??$t?.engine??"rg",limited:!!_t.limited,done:!0}))}},De.signal,ze,O,Ke,{excludePatterns:ht,caseSensitive:z.caseSensitive,wholeWord:z.wholeWord,regex:z.regex}).catch(_t=>{tt||_1(_t)||(Ie(_t instanceof Error?_t.message:"Failed to search files"),Ae([]),wt([]),et(null))}).finally(()=>{tt||Ze(!1)}),()=>{tt=!0,De.abort(),Fm(Ke)}},[Ve,q,xe,R,It,O,z.caseSensitive,z.regex,z.wholeWord,ze,!!a,be]),b.useEffect(()=>{if(!It)return;const tt=Kt.current;if(!tt)return;const De=xe?Qt.length:ae.length,nr=xe?wb:yb,Ke=new IntersectionObserver(_t=>{_t.some($t=>$t.isIntersecting)&&Gt($t=>Math.min($t+nr,De))},{rootMargin:"160px 0px"});return Ke.observe(tt),()=>Ke.disconnect()},[It,ae.length,Qt.length,xe]);const qt=b.useMemo(()=>{if(!ee)return;if(!It)return r?ee.filter(De=>De.type==="directory"):ee;const tt=Wt.getState().directoryCache;return ee.filter(De=>(!r||De.type==="directory")&&Ig(De,It,tt))},[r,It,ee]);if(!e)return s.jsx("div",{className:"px-4 py-8 text-center text-sm text-muted-foreground",children:le("fileTree.noWorkingDir")});if(Pe||!H)return s.jsx(YP,{});if(It&&xe){const tt=Ye?.total??Qt.length,De=Qt.slice(0,St),nr=St<Qt.length;return s.jsxs("div",{className:"termdock-native-select min-h-full space-y-px bg-surface px-2 py-2",children:[s.jsx(Ab,{count:tt,loading:ue,engine:Ye?.engine,limited:Ye?.limited,scope:Ve,content:!0}),at?s.jsxs("div",{className:"mx-1 mt-3 rounded-xl border border-border/15 bg-surface-2 px-4 py-5 text-center text-sm text-muted-foreground",children:[le("fileTree.contentSearchNeedsRipgrep"),s.jsx("div",{className:"mt-1 break-words text-[11px] text-muted-foreground/70",children:at})]}):ue&&Qt.length===0?s.jsx(p0,{label:le("fileTree.searching"),className:"py-8"}):Qt.length===0?s.jsx("div",{className:"mx-1 mt-3 overflow-hidden rounded-xl border border-border/15 bg-surface-2 px-4 py-8 text-center text-sm text-muted-foreground",children:le("fileTree.noContentMatches")}):s.jsxs(s.Fragment,{children:[Ye?.limited&&s.jsx("div",{className:"mb-2 rounded-xl bg-[rgb(var(--warning-rgb)_/_0.12)] px-3 py-2 text-[11px] text-[color:var(--warning)]",children:le("fileTree.searchTruncatedHint",{count:Ye.total})}),De.map(Ke=>s.jsx(cO,{entry:Ke,rootPath:Ve,selectedFilePath:E,query:R.trim(),onContentMatchSelect:$,onPathReference:n,referenceSelection:a,getReferenceText:c,onReferenceCopied:l,insertedReferenceKey:d,copiedReferenceKey:p},Ke.path)),s.jsx("div",{ref:Kt,className:"py-2 text-center text-[11px] text-muted-foreground",children:nr?s.jsx("button",{type:"button",onClick:()=>Gt(Ke=>Math.min(Ke+wb,Qt.length)),className:"rounded-full bg-surface-2 px-3 py-1 hover:bg-surface-elevated hover:text-foreground",children:le("fileTree.loadMoreSearchResults",{shown:De.length,total:Qt.length})}):ue?s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(_n,{size:10,className:"animate-spin"}),le("fileTree.searchStillRunning")]}):De.length>0?s.jsx("span",{children:le("fileTree.showingSearchResults",{shown:De.length,total:tt})}):null})]})]})}if(It){const tt=Ye?.total??ae.length,De=ae.slice(0,St),nr=St<ae.length;return s.jsxs("div",{className:"termdock-native-select min-h-full space-y-px bg-surface px-2 py-2",children:[s.jsx(Ab,{count:tt,loading:ue,engine:Ye?.engine,limited:Ye?.limited,scope:Ve,content:!1}),ue&&ae.length===0?s.jsx(p0,{label:le("fileTree.searching"),className:"py-8"}):at?s.jsx("div",{className:"px-4 py-4 text-sm text-destructive",children:at}):ae.length===0?s.jsx("div",{className:"mx-1 mt-3 overflow-hidden rounded-xl border border-border/15 bg-surface-2 px-4 py-8 text-center text-sm text-muted-foreground",children:le("fileTree.noMatchingFiles")}):s.jsxs(s.Fragment,{children:[Ye?.limited&&s.jsx("div",{className:"mb-2 rounded-xl bg-[rgb(var(--warning-rgb)_/_0.12)] px-3 py-2 text-[11px] text-[color:var(--warning)]",children:le("fileTree.searchTruncatedHint",{count:Ye.total})}),De.map(Ke=>s.jsx(iO,{node:Ke,rootPath:Ve,onFileSelect:t,onPathReference:n,referenceSelection:a,getReferenceText:c,onReferenceCopied:l,onDirectoryRoot:m,onSearchFromDirectory:x,onDirectoryPinToggle:y,onFilePinToggle:w,pinnedPaths:L,selectedFilePath:E,insertedReferenceKey:d,copiedReferenceKey:p,onFileDeleteRequest:ut,deletingFilePath:zt},Ke.path)),s.jsx("div",{ref:Kt,className:"py-2 text-center text-[11px] text-muted-foreground",children:nr?s.jsx("button",{type:"button",onClick:()=>Gt(Ke=>Math.min(Ke+yb,ae.length)),className:"rounded-full bg-surface-2 px-3 py-1 hover:bg-surface-elevated hover:text-foreground",children:le("fileTree.loadMoreSearchResults",{shown:De.length,total:ae.length})}):ue?s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(_n,{size:10,className:"animate-spin"}),le("fileTree.searchStillRunning")]}):De.length>0?s.jsx("span",{children:le("fileTree.showingSearchResults",{shown:De.length,total:tt})}):null})]})]})}return oe?s.jsx("div",{role:a?"alert":void 0,className:"px-4 py-4 text-sm text-destructive",children:oe}):!ee||ee.length===0?s.jsx("div",{className:"px-4 py-8 text-center text-sm text-muted-foreground",children:le("fileTree.emptyDir")}):!qt||qt.length===0?s.jsx("div",{className:"mx-3 mt-3 overflow-hidden rounded-xl border border-border/15 bg-surface-2 px-4 py-8 text-center text-sm text-muted-foreground",children:le("fileTree.noMatchingFiles")}):s.jsxs("div",{className:"termdock-native-select w-max min-w-full space-y-px px-2 py-2",children:[nt&&s.jsx("div",{className:"mb-2 rounded-xl bg-[rgb(var(--warning-rgb)_/_0.12)] px-3 py-2 text-[11px] text-[color:var(--warning)]",children:le("fileTree.truncatedHint")}),qt.map(tt=>s.jsx(sO,{node:tt,gitIgnoreRoot:e,depth:0,onFileSelect:t,directoriesOnly:r,onPathReference:n,referenceSelection:a,getReferenceText:c,onReferenceCopied:l,onDirectoryRoot:m,onSearchFromDirectory:x,onDirectoryPinToggle:y,onFilePinToggle:w,onOpenInFileBrowser:v,canOpenInFileBrowser:S,pinnedPaths:L,selectedFilePath:E,queryLower:It,insertedReferenceKey:d,copiedReferenceKey:p,onDirectoryDropFiles:V,onFileDeleteRequest:ut,deletingFilePath:zt,revealedDirectoryPath:Z?.path},tt.path))]})}function I1(e){return e.trim().replace(/\/+$/,"")||"/"}function dO(e){const t=I1(e);if(t==="/")return"/";const r=t.lastIndexOf("/");return r<=0?"/":t.slice(0,r)}function rp({open:e,initialPath:t,title:r,labels:n,onCancel:a,onConfirm:c}){const{t:l}=Ur(),d={hint:n?.hint??l("sidebar.directoryPickerHint"),cancel:n?.cancel??l("common.cancel"),confirm:n?.confirm??l("sidebar.useThisFolder"),close:n?.close??l("common.close"),parent:n?.parent??l("rightSidebar.parentFolder")},p=b.useRef(null);Gc(p,e,a);const[m,x]=b.useState(()=>I1(t));return b.useEffect(()=>{e&&x(I1(t))},[t,e]),b.useEffect(()=>{if(!e)return;const y=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=y}},[e]),e?Xs.createPortal(s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"fixed inset-0 z-modal-backdrop cursor-default bg-[var(--app-backdrop)] backdrop-blur-sm",onClick:a,"aria-label":d.cancel}),s.jsxs("section",{ref:p,tabIndex:-1,role:"dialog","aria-modal":"true","aria-labelledby":"directory-picker-title",className:"fixed bottom-[max(0.75rem,env(safe-area-inset-bottom,0px))] left-[max(0.75rem,env(safe-area-inset-left,0px))] right-[max(0.75rem,env(safe-area-inset-right,0px))] top-[max(0.75rem,env(safe-area-inset-top,0px))] z-modal-panel flex flex-col overflow-hidden rounded-2xl border border-border/15 bg-surface shadow-[0_28px_70px_var(--app-shadow-strong),0_14px_32px_var(--app-shadow-soft)] sm:bottom-auto sm:left-1/2 sm:right-auto sm:top-1/2 sm:h-[min(72svh,36rem)] sm:w-[min(36rem,calc(100vw-2rem))] sm:-translate-x-1/2 sm:-translate-y-1/2",children:[s.jsxs("header",{className:"flex shrink-0 items-center gap-3 border-b border-border/15 px-4 py-3",children:[s.jsx("span",{className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/15 text-primary",children:s.jsx(mT,{size:15})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("h2",{id:"directory-picker-title",className:"text-[13px] font-semibold text-foreground",children:r}),s.jsx("p",{className:"mt-0.5 text-[10px] text-muted-foreground",children:d.hint})]}),s.jsx("button",{type:"button",onClick:a,className:"inline-flex h-9 w-9 items-center justify-center rounded-lg text-muted-foreground transition hover:bg-surface-2 hover:text-foreground","aria-label":d.close,children:s.jsx(In,{size:15})})]}),s.jsxs("div",{className:"flex min-h-11 shrink-0 items-center gap-2 border-b border-border/15 px-3 py-1.5",children:[s.jsx("button",{type:"button",disabled:m==="/",onClick:()=>x(dO(m)),className:"inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition hover:bg-surface-2 hover:text-foreground disabled:opacity-30","aria-label":d.parent,children:s.jsx(jy,{size:14})}),s.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-[10.5px] text-foreground",title:m,children:m})]}),s.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto overscroll-contain py-1",children:s.jsx(uO,{rootPath:m,directoriesOnly:!0,onFileSelect:()=>{},onDirectoryRoot:x,selectedFilePath:t||null})}),s.jsxs("footer",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border/15 bg-surface-elevated px-3 py-3",children:[s.jsx("button",{type:"button",onClick:a,className:"min-h-10 rounded-lg bg-surface-2 px-4 text-[11px] font-medium text-foreground transition hover:bg-surface",children:d.cancel}),s.jsxs("button",{type:"button",onClick:()=>c(m),className:"inline-flex min-h-10 items-center gap-1.5 rounded-lg bg-primary px-4 text-[11px] font-semibold text-primary-foreground transition hover:bg-primary/90",children:[s.jsx(pi,{size:13}),d.confirm]})]})]})]}),document.body):null}const hO=Object.freeze(Object.defineProperty({__proto__:null,DirectoryPickerDialog:rp},Symbol.toStringTag,{value:"Module"})),E1="termdock:new-session-commands:v1",ac="__saved_command__:";function kh(e){return[...new Set(Object.entries(e).filter(([t])=>t.startsWith(ac)||t==="__custom__"||t==="__terminal__").map(([,t])=>t.trim()).filter(Boolean))]}function Pd(){try{const e=JSON.parse(localStorage.getItem(E1)||"{}");return!e||typeof e!="object"||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(t=>typeof t[1]=="string"))}catch{return{}}}function fO({directories:e,tmuxAvailable:t,options:r,agents:n,selectedAgent:a,detecting:c,resumeHistory:l,resumeHistoryLoading:d,resumeHistoryPendingId:p,resumeHistoryError:m,onRefreshAgents:x,onSelectAgent:y,onLaunchAgent:w,onResumeHistory:v,onRemoveResumeHistory:S,onClose:L,onOptionsChange:E,additionalContent:R,footerActions:B,launchPending:z=!1,launchError:O}){const{t:$,locale:V}=Ur(),Z=b.useRef(null);Gc(Z,!0,L,()=>document.querySelector('[aria-controls="sidebar-launch-options"]'));const[le,be]=b.useState(a),[pe,ee]=b.useState(!1),[_e,ze]=b.useState(!1),[Y,ce]=b.useState(Pd),[qe,we]=b.useState(()=>kh(Pd())),[ye,Le]=b.useState(null),[Be,ne]=b.useState("idle"),Fe=_e?"__custom__":le?.slug??"__terminal__",ke=le?.command??"",Ee=_e?Y.__custom__??Y.__terminal__??"":le?Y[Fe]??ke:"",Pe=()=>{const Ce=Ee.trim()||ke;if(!(_e&&!Ce))try{const H={...Pd(),[Fe]:Ce};if(_e){for(const ae of kh(Pd()))H[ac+ae]=ae;H[ac+Ce]=Ce}localStorage.setItem(E1,JSON.stringify(H)),we(kh(H)),_e&&Le(Ce),ne("saved")}catch{ne("error")}},Ne=()=>{if(ye)try{const Ce=Pd();for(const[H,ae]of Object.entries(Ce))(H.startsWith(ac)||H==="__custom__"||H==="__terminal__")&&ae.trim()===ye&&delete Ce[H];localStorage.setItem(E1,JSON.stringify(Ce)),we(kh(Ce)),ce(H=>({...H,__custom__:""})),Le(null),ne("idle")}catch{ne("error")}},oe=()=>{const Ce=Ee.trim()||ke;z||_e&&!Ce||(Pe(),w(le,Ce))},We=b.useMemo(()=>[...new Set(e.filter(Boolean))].slice(0,5),[e]),nt=_e?ye?ac+ye:"__custom__":le?.slug??"__terminal__",gt=Ce=>{ne("idle");const H=Ce.startsWith(ac)?Ce.slice(ac.length):null;Le(H),ze(Ce==="__custom__"||H!==null),(H!==null||Ce==="__custom__")&&ce(ae=>({...ae,__custom__:H??""})),be(n.find(ae=>ae.slug===Ce)??null)},ue=_e?ye??$("sidebar.customStartupCommand"):le?.displayName??"Terminal",Ze=a?.displayName??"Terminal",at=!_e&&(le===null?a===null:a?.slug===le.slug);b.useEffect(()=>{if(pe)return;const Ce=H=>{H.target instanceof Node&&(Z.current?.contains(H.target)||H.target instanceof Element&&H.target.closest("[data-sidebar-composer-popover]")?.getAttribute("data-sidebar-composer-popover")===Z.current?.id||H.target instanceof Element&&H.target.closest('[aria-controls="sidebar-launch-options"]')||L())};return document.addEventListener("pointerdown",Ce,!0),()=>document.removeEventListener("pointerdown",Ce,!0)},[pe,L]);const Ie=Ce=>{E({...r,cwd:Ce}),ee(!1)},Ge=Ce=>new Intl.DateTimeFormat(V==="zh"?"zh-CN":"en",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}).format(new Date(Ce));return s.jsxs("section",{ref:Z,tabIndex:-1,"aria-busy":z,id:"sidebar-launch-options",className:`absolute inset-x-3 bottom-3 z-30 flex flex-col overflow-hidden rounded-2xl border border-border bg-surface shadow-[0_18px_50px_var(--app-shadow-strong),0_4px_14px_var(--app-shadow-soft)] animate-slide-down ${B?"max-h-[min(70svh,42rem,calc(100%_-_4.5rem))]":"max-h-[min(56svh,36rem,calc(100%_-_4.5rem))]"}`,"aria-label":$("sidebar.newSessionComposerTitle"),children:[s.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-3 px-3 py-1.5",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-2.5",children:[s.jsx("span",{className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg text-muted-foreground",children:s.jsx($o,{size:14})}),s.jsx("div",{className:"min-w-0",children:s.jsx("div",{className:"text-[12px] font-semibold text-foreground",children:$("sidebar.newSessionComposerTitle")})})]}),s.jsx("button",{type:"button",onClick:L,className:"inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition hover:bg-surface-2 hover:text-foreground","aria-label":$("common.close"),children:s.jsx(In,{size:14})})]}),s.jsxs("fieldset",{disabled:z,className:"min-h-0 min-w-0 flex-1 overflow-y-auto overscroll-contain border-0 px-3 pb-1",children:[s.jsxs("div",{className:"flex min-h-11 items-center justify-between gap-3",children:[s.jsx("span",{className:"shrink-0 text-[11px] text-muted-foreground",children:$("sidebar.sessionMode")}),s.jsx("div",{className:"grid grid-cols-2 gap-1 rounded-lg bg-surface p-0.5",children:["shell","tmux"].map(Ce=>s.jsx("button",{type:"button",disabled:Ce==="tmux"&&!t,onClick:()=>E({...r,mode:Ce}),"aria-pressed":r.mode===Ce,title:Ce==="tmux"?$(t?"sidebar.tmuxKeepsRunning":"sidebar.newTmuxDisabled"):void 0,className:`min-h-9 rounded-md px-4 text-[11px] font-medium transition ${r.mode===Ce?"bg-surface-2 text-foreground":"text-muted-foreground hover:text-foreground"} disabled:cursor-not-allowed disabled:opacity-40`,children:$(Ce==="shell"?"sidebar.newShell":"sidebar.newTmux")},Ce))})]}),s.jsxs("div",{className:"mt-1 flex items-center justify-between",children:[s.jsx("span",{className:"text-[11px] text-muted-foreground",children:$("sidebar.startupCommand")}),s.jsx("button",{type:"button",onClick:x,disabled:c,className:"inline-flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground transition hover:bg-surface hover:text-foreground disabled:opacity-50",title:$("sidebar.detectAgents"),"aria-label":$("sidebar.detectAgents"),children:s.jsx(bn,{size:12,className:c?"animate-spin":""})})]}),s.jsxs("div",{role:"radiogroup","aria-label":$("sidebar.startupCommand"),className:"flex flex-wrap gap-1",children:[n.map(Ce=>{const H=!_e&&le?.slug===Ce.slug;return s.jsxs("button",{type:"button",role:"radio","aria-checked":H,onClick:()=>gt(Ce.slug),className:`inline-flex min-h-7 items-center gap-1 rounded-md px-2 text-[10.5px] font-medium transition ${H?"bg-surface-2 text-foreground ring-1 ring-inset ring-primary/50":"bg-surface text-muted-foreground hover:bg-surface-2 hover:text-foreground"}`,children:[s.jsx(Wc,{agent:Ce,size:12}),s.jsx("span",{className:"max-w-[9rem] truncate",children:Ce.displayName}),a?.slug===Ce.slug&&s.jsx("span",{className:"ml-0.5 text-[9px] text-muted-foreground",children:$("sidebar.defaultAgent")})]},Ce.slug)}),qe.map(Ce=>{const H=_e&&ye===Ce;return s.jsxs("button",{type:"button",role:"radio","aria-checked":H,onClick:()=>gt(ac+Ce),title:Ce,className:`inline-flex min-h-7 items-center gap-1 rounded-md px-2 transition ${H?"bg-surface-2 text-foreground ring-1 ring-inset ring-primary/50":"bg-surface text-muted-foreground hover:bg-surface-2 hover:text-foreground"}`,children:[s.jsx(Qc,{size:10,className:"shrink-0"}),s.jsx("span",{className:"max-w-[9rem] truncate font-mono text-[10px]",children:Ce})]},Ce)}),s.jsxs("button",{type:"button",role:"radio","aria-checked":nt==="__terminal__",onClick:()=>gt("__terminal__"),className:`inline-flex min-h-7 items-center gap-1 rounded-md px-2 text-[10.5px] font-medium transition ${nt==="__terminal__"?"bg-surface-2 text-foreground ring-1 ring-inset ring-primary/50":"bg-surface text-muted-foreground hover:bg-surface-2 hover:text-foreground"}`,children:[s.jsx($o,{size:11,className:"shrink-0"}),s.jsx("span",{children:"Terminal"}),a===null&&s.jsx("span",{className:"ml-0.5 text-[9px] font-normal text-muted-foreground",children:$("sidebar.defaultAgent")})]}),s.jsxs("button",{type:"button",role:"radio","aria-checked":nt==="__custom__",onClick:()=>gt("__custom__"),className:`inline-flex min-h-7 items-center gap-0.5 rounded-md px-2 text-[10.5px] font-medium transition ${nt==="__custom__"?"bg-surface-2 text-foreground ring-1 ring-inset ring-primary/50":"bg-surface text-muted-foreground hover:bg-surface-2 hover:text-foreground"}`,children:[s.jsx(zs,{size:10,className:"shrink-0"}),s.jsx("span",{children:$("sidebar.addStartupCommand")})]})]}),!at&&!_e&&s.jsxs("div",{className:"mt-1 flex min-h-8 items-center justify-between gap-2 px-0.5 text-[10px]",children:[s.jsx("span",{className:"truncate text-muted-foreground",children:$("sidebar.currentDefaultAgent",{name:Ze})}),s.jsx("button",{type:"button",onClick:()=>y(le),className:"relative z-10 shrink-0 rounded-md px-2 py-1.5 font-medium text-primary transition hover:bg-primary/10",children:$("sidebar.makeDefault")})]}),Be==="error"&&s.jsx("p",{role:"alert",className:"text-[10px] text-destructive",children:$("sidebar.saveStartupCommandFailed")}),(le||_e)&&s.jsxs("details",{open:_e&&!ye||void 0,className:"group/command mt-0.5",children:[s.jsxs("summary",{className:"ml-auto flex min-h-8 w-fit cursor-pointer list-none items-center gap-1 rounded-md px-1 text-[10px] text-muted-foreground transition hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50 [&::-webkit-details-marker]:hidden",children:[$(_e&&!ye?"sidebar.customStartupCommand":"sidebar.changeStartupCommand"),s.jsx(ul,{size:11,className:"transition-transform group-open/command:rotate-180"})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2",children:[s.jsx("label",{htmlFor:"new-session-command",className:"sr-only",children:$("sidebar.startupCommand")}),le&&Ee!==ke&&s.jsx("button",{type:"button",onClick:()=>{ce(Ce=>({...Ce,[Fe]:ke})),ne("idle")},className:"min-h-8 rounded-md px-2 text-[10px] text-primary transition hover:bg-primary/10",children:$("sidebar.resetStartupCommand")})]}),s.jsx("input",{id:"new-session-command",value:Ee,onChange:Ce=>{ce(H=>({...H,[Fe]:Ce.target.value})),ne("idle")},placeholder:ke||$("sidebar.startupCommandPlaceholder"),autoCapitalize:"none",autoCorrect:"off",spellCheck:!1,autoComplete:"off",className:"min-h-10 w-full rounded-lg border-0 bg-surface px-3 font-mono text-[16px] text-foreground outline-none ring-1 ring-inset ring-border transition focus:ring-primary/50 sm:text-[11px]"}),s.jsxs("div",{className:"mt-1 flex items-center justify-end gap-2","aria-live":"polite",children:[_e&&ye&&s.jsxs("button",{type:"button",onClick:Ne,className:"mr-auto inline-flex min-h-9 items-center gap-1 rounded-md px-2 text-[10px] text-muted-foreground transition hover:text-destructive","aria-label":$("sidebar.deleteStartupCommand"),children:[s.jsx(Rs,{size:11}),$("sidebar.deleteStartupCommand")]}),s.jsx("button",{type:"button",onClick:Pe,disabled:Be==="saved"||_e&&!Ee.trim(),className:"min-h-8 rounded-md px-2 text-[10px] font-medium text-primary transition hover:bg-primary/10 disabled:cursor-default disabled:opacity-50",children:$(Be==="saved"?"sidebar.startupCommandSaved":"sidebar.saveStartupCommand")})]}),s.jsx("p",{className:"mb-2 mt-1.5 px-0.5 text-[10px] leading-relaxed text-muted-foreground",children:$(le?"sidebar.agentStartupCommandHint":"sidebar.terminalStartupCommandHint")})]},ye??Fe),s.jsx("label",{htmlFor:"new-session-directory",className:"mt-2 block text-[11px] text-muted-foreground",children:$("sidebar.workingDirectory")}),s.jsxs("button",{id:"new-session-directory",type:"button","aria-haspopup":"dialog",onClick:()=>ee(!0),className:"mt-1 flex min-h-11 w-full items-center gap-2 rounded-lg border border-transparent bg-surface px-2.5 font-mono text-[11px] text-foreground outline-none transition hover:bg-surface-2 focus-visible:border-primary",children:[s.jsx(Vc,{size:12,className:"shrink-0 text-muted-foreground"}),s.jsx("span",{className:`min-w-0 flex-1 truncate text-left ${r.cwd?"":"text-muted-foreground"}`,children:r.cwd||$("sidebar.directoryPlaceholder")})]}),We.length>0&&s.jsx("div",{className:"mt-1.5 flex gap-1 overflow-x-auto pb-0.5","aria-label":$("sidebar.recentDirectories"),children:We.map(Ce=>s.jsx("button",{type:"button",onClick:()=>Ie(Ce),title:Ce,className:"min-h-8 shrink-0 rounded-md px-2 text-[10px] text-muted-foreground transition hover:bg-surface hover:text-foreground",children:Ku(Ce)||Ce},Ce))}),(l.length>0||m)&&s.jsxs("details",{className:"mt-1",children:[s.jsxs("summary",{className:"flex min-h-9 cursor-pointer list-none items-center gap-2 rounded-md px-1 text-[10px] font-medium uppercase tracking-[0.12em] text-muted-foreground transition hover:text-foreground",children:[s.jsx(Qc,{size:11}),s.jsx("span",{className:"flex-1",children:$("sidebar.resumeHistory")}),d&&s.jsx(_n,{size:10,className:"animate-spin"}),l.length>0&&s.jsx("span",{className:"normal-case tracking-normal",children:$("sidebar.resumeHistoryCount",{n:l.length})}),s.jsx(ul,{size:11})]}),l.length>0&&s.jsx("div",{className:"mt-1 divide-y divide-border overflow-hidden rounded-lg border border-border bg-surface",children:l.slice(0,6).map(Ce=>{const H=p===Ce.id;return s.jsxs("div",{className:"group flex min-w-0 items-stretch transition hover:bg-surface-2",children:[s.jsxs("button",{type:"button",disabled:p!==null,onClick:()=>v(Ce),className:"flex min-h-11 min-w-0 flex-1 items-center gap-2.5 px-2.5 py-2 text-left disabled:cursor-wait disabled:opacity-60","aria-label":$("sidebar.resumeHistoryAction",{title:Ce.title}),children:[s.jsx("span",{className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary",children:H?s.jsx(_n,{size:13,className:"animate-spin"}):s.jsx(Wc,{agent:Ce.agent,size:14})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block truncate text-[11px] font-semibold text-foreground",children:Ce.title}),s.jsxs("span",{className:"block truncate text-[9.5px] text-muted-foreground",children:[Ce.agent.displayName," · ",Ge(Ce.closedAt)]})]}),s.jsx(Uy,{size:12,className:"shrink-0 text-muted-foreground transition group-hover:text-primary"})]}),s.jsxs("button",{type:"button",disabled:p!==null,onClick:()=>S(Ce.id),className:"relative inline-flex w-11 shrink-0 items-center justify-center text-muted-foreground transition hover:text-destructive disabled:opacity-40","aria-label":$("sidebar.resumeHistoryRemove",{title:Ce.title}),children:[s.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-y-2 left-0 w-px bg-border opacity-30"}),s.jsx(Rs,{size:12})]})]},Ce.id)})}),m&&s.jsx("div",{role:"alert",className:"mt-1.5 px-1 text-[10px] text-destructive",children:m})]}),R]}),s.jsxs("div",{className:"shrink-0 bg-surface px-3 pb-3 pt-2",children:[O&&s.jsx("p",{role:"alert",className:"mb-2 text-[11px] leading-relaxed text-destructive",children:O}),s.jsxs("button",{type:"button",onClick:oe,disabled:z||_e&&!Ee.trim(),className:"flex min-h-11 w-full items-center justify-center gap-2 rounded-lg bg-primary px-3 text-[12px] font-semibold text-primary-foreground transition hover:brightness-110 active:scale-[0.99] disabled:cursor-not-allowed disabled:opacity-40","aria-label":$("sidebar.launchSessionWith",{name:ue}),children:[z?s.jsx(_n,{size:14}):le?s.jsx(Wc,{agent:le,size:15}):s.jsx($o,{size:14}),s.jsx("span",{className:"truncate",children:z?$("sidebar.sessionCreating"):$("sidebar.launchSessionWith",{name:ue})})]}),B]}),s.jsx(rp,{open:pe,initialPath:r.cwd?.trim()||We[0]||"/",title:$("sidebar.chooseDirectory"),onCancel:()=>ee(!1),onConfirm:Ie})]})}const H6="termdock:new-session-agent:v1";function pO(){if(typeof window>"u")return null;try{const e=JSON.parse(window.localStorage.getItem(H6)||"null");return!e||typeof e.slug!="string"||typeof e.command!="string"?null:{slug:e.slug,command:e.command,displayName:typeof e.displayName=="string"?e.displayName:e.slug,capabilities:Array.isArray(e.capabilities)?e.capabilities.filter(t=>typeof t=="string"):void 0,accentColor:typeof e.accentColor=="string"?e.accentColor:"var(--muted-foreground)",icon:typeof e.icon=="string"?e.icon:null,isPlugin:e.isPlugin===!0,iconMode:e.iconMode==="native"?"native":e.iconMode==="mask"?"mask":void 0,iconVersion:typeof e.iconVersion=="number"?e.iconVersion:void 0}}catch{return null}}function Am(e){if(!(typeof window>"u"))try{window.localStorage.setItem(H6,JSON.stringify(e))}catch{}}function mO(e,t){return e?t.find(r=>r.slug===e)??null:null}function gO(){const[e,t]=b.useState(pO),[r,n]=b.useState([]),[a,c]=b.useState(!0),l=b.useCallback(async()=>{c(!0);try{const[p,m]=await Promise.all([fc(),_y()]),x=mO(p.newSessionAgentSlug,m);n(m),t(x),Am(x)}finally{c(!1)}},[]);b.useEffect(()=>{const p=()=>{l().catch(()=>{})};if(performance.getEntriesByName("termdock:startup:initial-viewport-presented").length>0){p();return}return window.addEventListener("termdock:initial-viewport-presented",p,{once:!0}),()=>window.removeEventListener("termdock:initial-viewport-presented",p)},[l]);const d=b.useCallback(async p=>{const m=e;t(p),Am(p);try{await La({newSessionAgentSlug:p?.slug??null})}catch(x){throw t(m),Am(m),x}},[e]);return{preference:e,agents:r,detecting:a,refresh:l,selectAgent:d}}function xO({groups:e,sessions:t,busy:r,onOpen:n,onSettings:a,onCreate:c}){const[l,d]=b.useState(""),p=e.filter(m=>!l.trim()||`${m.name} ${m.sessionIds.map(x=>t.find(y=>y.sessionId===x)?.name??"").join(" ")}`.toLowerCase().includes(l.trim().toLowerCase()));return s.jsxs("section",{"aria-label":"协作组列表",className:"space-y-3",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsx("p",{className:"text-xs leading-6 text-muted-foreground",children:"成员消息用于日常交流;看板用于目标、交付与验收。"}),s.jsxs("button",{type:"button",disabled:r,className:"inline-flex min-h-11 shrink-0 items-center gap-1.5 rounded-lg bg-primary px-3 text-xs font-medium text-primary-foreground disabled:opacity-40",onClick:c,children:[s.jsx(zs,{size:14}),"新建协作组"]})]}),(e.length>5||l)&&s.jsxs("label",{className:"relative block",children:[s.jsx("span",{className:"sr-only",children:"搜索协作组"}),s.jsx(jl,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),s.jsx("input",{type:"search",value:l,onChange:m=>d(m.target.value),placeholder:"搜索组名或成员",className:"min-h-11 w-full rounded-lg border border-border/20 bg-surface-2 py-2 pl-9 pr-3 text-xs text-foreground outline-none focus:border-primary/60"})]}),s.jsxs("div",{className:"divide-y divide-border/15 rounded-xl border border-border/15",children:[p.map(m=>{const x=m.sessionIds.flatMap(y=>{const w=t.find(v=>v.sessionId===y);return w?[w]:[]});return s.jsxs("article",{"aria-label":m.name,className:"p-3 sm:flex sm:items-center sm:gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("h3",{className:"break-words text-sm font-medium leading-6 text-foreground",children:m.name}),s.jsx("p",{className:"mt-1 break-words text-[11px] leading-5 text-muted-foreground",children:m.sessionIds.length?`${m.sessionIds.length} 位成员${x.length?` · ${x.slice(0,2).map(y=>Iu(y,x)).join("、")}${x.length>2?"等":""}`:""}`:"尚未添加成员,可以稍后配置"})]}),s.jsxs("div",{className:"mt-2 flex shrink-0 items-center gap-1 sm:mt-0",children:[s.jsxs("button",{type:"button","aria-label":`成员消息:${m.name}`,disabled:r,className:"inline-flex min-h-11 items-center justify-center gap-1.5 rounded-lg bg-surface-2 px-3 text-xs text-foreground hover:bg-surface-elevated disabled:opacity-40",onClick:()=>n(m.id,"messages"),children:[s.jsx(Xu,{size:14}),"成员消息"]}),s.jsxs("button",{type:"button","aria-label":`看板:${m.name}`,disabled:r,className:"inline-flex min-h-11 items-center justify-center gap-1.5 rounded-lg px-3 text-xs text-muted-foreground hover:bg-surface-2 disabled:opacity-40",onClick:()=>n(m.id,"tasks"),children:[s.jsx(_T,{size:14}),"看板"]}),s.jsx("button",{type:"button","aria-label":`设置:${m.name}`,title:"组设置",disabled:r,className:"inline-flex min-h-11 min-w-11 items-center justify-center rounded-lg text-muted-foreground hover:bg-surface-2 disabled:opacity-40",onClick:y=>a(m.id,y.currentTarget),children:s.jsx(ju,{size:14})})]})]},m.id)}),!p.length&&s.jsx("p",{className:"px-3 py-6 text-xs text-muted-foreground",children:"没有匹配的协作组,试试其他名称。"})]})]})}const jc="min-h-11 w-full rounded-lg border border-border/20 bg-surface px-3 py-2 text-xs text-foreground outline-none focus:border-primary",Lh="inline-flex min-h-11 items-center justify-center gap-2 rounded-lg px-3 text-xs disabled:opacity-40",Ih=e=>({profiles:e.launchProfiles??[],defaultId:e.defaultLaunchProfileId??"",group:e}),Tm=new Map,Od=e=>JSON.stringify(e.profiles)!==JSON.stringify(e.group.launchProfiles??[])||e.defaultId!==(e.group.defaultLaunchProfileId??"");function bO({group:e,value:t,onChange:r,disabled:n}){if(!e.launchProfiles?.length&&!t)return null;const a=e.launchProfiles?.find(c=>c.id===t);return s.jsxs("div",{className:"mt-3 space-y-1",children:[s.jsxs("label",{className:"block space-y-1 text-xs text-muted-foreground",children:["启动方案",s.jsxs("select",{"aria-label":"启动方案",className:jc,value:t,disabled:n,onChange:c=>r(c.target.value),children:[s.jsx("option",{value:"",children:"Agent 默认命令"}),e.launchProfiles?.map(c=>s.jsx("option",{value:c.id,children:c.name},c.id))]})]}),a&&s.jsxs("p",{className:"whitespace-pre-wrap break-words text-xs leading-5 text-muted-foreground",children:[a.notes||"未填写使用备注",s.jsx("code",{className:"block break-all",children:a.command})]}),t&&!a&&s.jsx("p",{role:"alert",className:"text-xs text-destructive",children:"原方案已删除,请重新选择。"})]})}function yO({group:e,agents:t,busy:r,setBusy:n,refresh:a}){const c=`${window.location.origin}:${e.id}`,[l,d]=b.useState(()=>Tm.get(c)??Ih(e)),p=b.useRef(l);p.current=l;const[m,x]=b.useState(l.profiles[0]?.id??""),[y,w]=b.useState(null),[v,S]=b.useState(""),L=($,V=!0)=>{p.current=$,d($),Od($)?Tm.set(c,$):Tm.delete(c),V&&S("")};b.useEffect(()=>{!Od(p.current)&&e.updatedAt>=p.current.group.updatedAt&&L(Ih(e),!1)},[e.updatedAt]);const E=l.profiles.find($=>$.id===m),R=$=>L({...l,profiles:l.profiles.map(V=>V.id===m?{...V,...$}:V)}),B=l.profiles.every($=>$.name.trim()&&$.agentSlug&&$.command.trim()&&!/[\x00-\x1f\x7f]/.test($.command)),z=()=>{const $=t[0],V={id:`profile-${crypto.randomUUID()}`,name:"",agentSlug:$?.slug??"",command:$?.command??"",notes:""};L({...l,profiles:[...l.profiles,V]}),x(V.id)},O=async()=>{if(!(r||!B||!Od(l))){n("launch-profiles"),w(null),S("");try{const{group:$}=await Ml({id:e.id,name:l.group.name,sessionIds:l.group.sessionIds,expectedUpdatedAt:l.group.updatedAt,launchProfiles:l.profiles,defaultLaunchProfileId:l.defaultId||null});L(Ih($)),S("启动方案已保存。新会话使用所选方案,正在运行的成员保持原配置。"),await a()}catch($){w($ instanceof Error?$.message:"保存失败")}finally{n(null)}}};return s.jsxs("details",{className:"mt-3 border-t border-border/15 pt-2",children:[s.jsxs("summary",{className:"min-h-11 cursor-pointer py-3 text-xs font-medium text-foreground",children:["Agent 启动方案 · ",l.profiles.length," 个",Od(l)?" · 未保存":""]}),s.jsxs("section",{"aria-label":"Agent 启动方案",className:"space-y-3",children:[s.jsx("p",{className:"text-xs leading-5 text-muted-foreground",children:"保存不同模型和参数的启动命令,填写适用场景,让协调者按备注选择。保存配置不会启动 Agent。"}),s.jsxs("fieldset",{disabled:!!r,className:"space-y-3",children:[s.jsxs("label",{className:"block space-y-1 text-xs text-muted-foreground",children:["默认启动方案",s.jsxs("select",{"aria-label":"默认启动方案",className:jc,value:l.defaultId,onChange:$=>L({...l,defaultId:$.target.value}),children:[s.jsx("option",{value:"",children:"使用 Agent 默认命令"}),l.profiles.map($=>s.jsx("option",{value:$.id,children:$.name||"未命名方案"},$.id))]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("label",{className:"min-w-0 flex-1 text-xs text-muted-foreground",children:["编辑方案",s.jsxs("select",{"aria-label":"编辑方案",className:`${jc} mt-1`,value:m,onChange:$=>x($.target.value),children:[s.jsx("option",{value:"",children:"选择方案"}),l.profiles.map($=>s.jsx("option",{value:$.id,children:$.name||"未命名方案"},$.id))]})]}),s.jsxs("button",{type:"button",className:`${Lh} self-end bg-surface text-foreground`,disabled:l.profiles.length>=20,onClick:z,children:[s.jsx(zs,{size:14}),"新增方案"]})]}),E?s.jsxs("div",{className:"space-y-3 rounded-lg border border-border/20 p-3",children:[s.jsxs("label",{className:"block space-y-1 text-xs text-muted-foreground",children:["方案名称",s.jsx("input",{className:jc,value:E.name,maxLength:100,onChange:$=>R({name:$.target.value}),placeholder:"例如:快速排查、深度实现"})]}),s.jsxs("label",{className:"block space-y-1 text-xs text-muted-foreground",children:["Agent 类型",s.jsxs("select",{"aria-label":"Agent 类型",className:jc,value:E.agentSlug,onChange:$=>R({agentSlug:$.target.value,command:t.find(V=>V.slug===$.target.value)?.command??""}),children:[!t.some($=>$.slug===E.agentSlug)&&s.jsxs("option",{value:E.agentSlug,children:[E.agentSlug||"选择 Agent","(当前不可用)"]}),t.map($=>s.jsx("option",{value:$.slug,children:$.displayName},$.slug))]})]}),s.jsxs("label",{className:"block space-y-1 text-xs text-muted-foreground",children:["启动命令",s.jsx("input",{className:`${jc} font-mono`,value:E.command,maxLength:4096,onChange:$=>R({command:$.target.value}),placeholder:"填写完整命令,包括模型和启动参数"})]}),s.jsxs("label",{className:"block space-y-1 text-xs text-muted-foreground",children:["使用备注",s.jsx("textarea",{"aria-label":"使用备注",className:`${jc} min-h-24 resize-y`,value:E.notes,maxLength:2e3,onChange:$=>R({notes:$.target.value}),placeholder:"适合哪些任务、何时不要使用;协调者会读取这些备注。"})]}),s.jsxs("details",{className:"text-[11px] text-muted-foreground",children:[s.jsx("summary",{className:"min-h-11 cursor-pointer py-3",children:"CLI 方案标识"}),s.jsx("code",{className:"break-all",children:E.id})]}),s.jsxs("button",{type:"button",className:`${Lh} text-destructive hover:bg-destructive/10`,onClick:()=>{const $=l.profiles.filter(V=>V.id!==m);L({...l,profiles:$,defaultId:l.defaultId===m?"":l.defaultId}),x($[0]?.id??"")},children:[s.jsx(Rs,{size:14}),"移除方案(保存后生效)"]})]}):s.jsx("p",{className:"text-xs text-muted-foreground",children:"尚未选择方案。新增后可填写模型、参数和备注。"})]}),y&&s.jsxs("p",{role:"alert",className:"text-xs leading-5 text-destructive",children:[y,"。草稿已保留;重新载入会放弃草稿。"]}),v&&s.jsx("p",{role:"status",className:"text-xs leading-5 text-primary",children:v}),s.jsxs("div",{className:"flex flex-wrap justify-between gap-2",children:[s.jsx("button",{type:"button",className:`${Lh} bg-surface text-muted-foreground`,disabled:!!r,onClick:()=>{L(Ih(e)),x(e.launchProfiles?.[0]?.id??""),w(null)},children:"重新载入(放弃方案草稿)"}),s.jsx("button",{type:"button",disabled:!!r||!B||!Od(l),className:`${Lh} bg-primary text-primary-foreground`,onClick:()=>{O()},children:r==="launch-profiles"?"保存中…":"保存启动方案"})]})]})]})}function vO(e,t){const r=t.events.filter(p=>p.kind==="retry"&&!e.events.some(m=>m.id===p.id)).at(-1),n=new Set(e.deliveries.filter(p=>p.status==="delivered").map(p=>p.id)),a=new Set(e.outbox.filter(p=>!n.has(p.id)).map(p=>p.id)),c=r&&t.deliveries.some(p=>a.has(p.id)&&p.status==="delivered"&&p.deliveredAt!==null&&p.deliveredAt>=r.createdAt);let l=c?"重试请求已保存,匹配本次请求的投递已写入终端。":"重试请求已保存,服务将重新检查现有投递与协调条件。";!t.outbox.length&&!c&&(l+=" 当前没有待重试的投递记录。"),t.workflow?.paused&&(l+=" 后续自动安排仍已暂停。");const d=t.attempts.find(p=>p.id===t.activeAttemptId)?.report;return d&&["blocked","failed"].includes(d.status)&&(l+=" 成员原报告仍保留;请补齐条件并通知成员,收到新的明确回复后更新报告。"),l}function wO(e,t){const r=Math.floor(Math.max(0,t-e)/6e4);return r<1?"刚刚更新":r<60?`${r} 分钟前更新`:r<1440?`${Math.floor(r/60)} 小时前更新`:r<10080?`${Math.floor(r/1440)} 天前更新`:`${new Date(e).toLocaleDateString([],{month:"numeric",day:"numeric"})} 更新`}function Tb(e){return new Date(e).toLocaleString([],{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1})}function Df({task:e,now:t,compact:r=!1}){const n=w6(e),a=Number.isFinite(e.updatedAt)&&e.updatedAt>0&&Number.isFinite(new Date(e.updatedAt).getTime());return r&&!n?null:s.jsxs("span",{className:"mt-1 block space-y-1 text-[11px] leading-5 text-muted-foreground",children:[s.jsx("span",{className:"block break-words",children:n?s.jsxs(s.Fragment,{children:["最近明确报告:",n.label," · ",n.createdAt===null?"报告时间未提供":s.jsx("time",{dateTime:new Date(n.createdAt).toISOString(),title:new Date(n.createdAt).toLocaleString(),children:Tb(n.createdAt)})]}):"暂无明确报告"}),!r&&s.jsx("span",{className:"block",children:a?s.jsxs(s.Fragment,{children:["记录更新:",s.jsx("time",{dateTime:new Date(e.updatedAt).toISOString(),title:t===void 0?new Date(e.updatedAt).toLocaleString():wO(e.updatedAt,t),children:Tb(e.updatedAt)})]}):"记录更新时间未提供"})]})}function W6(e,t){const r=e.trim().split(/\n\s*\n/),n=l=>{const d=r.findIndex(m=>l.test(m.trim()));return d<0?"":r[d].trim().replace(l,"").trim()||r[d+1]?.trim()||""},a=t?.trim()||n(/^(?:#{1,6}\s*)?(?:结论|Summary|Conclusion|结果摘要)(?:[::]\s*|\s*$)/i),c=n(/^(?:#{1,6}\s*)?(?:限制与变更|限制|Limitations)(?:[::]\s*|\s*$)/i);return{summary:a||e.trim(),limitations:a?c:"",condensed:!!a&&a!==e.trim(),explicit:!!t?.trim()}}function Jh({inputKey:e,paneKey:t,label:r,value:n,onChange:a,active:c=!0,disabled:l=!1,required:d,autoFocus:p,placeholder:m,className:x,onUploadChange:y}){const w=b.useId(),v=b.useRef(null),S=b.useRef(null),L=b.useRef({value:n,onChange:a,onUploadChange:y});L.current={value:n,onChange:a,onUploadChange:y};const[E,R]=b.useState(0),[B,z]=b.useState(""),O=b.useRef(Promise.resolve());b.useEffect(()=>{const ee=v.current;ee&&ee.setSelectionRange(ee.value.length,ee.value.length)},[e]);const $=()=>({value:L.current.value,start:v.current?.selectionStart??n.length,end:v.current?.selectionEnd??n.length}),V=(ee,_e=$())=>{L.current.onChange(ze=>ze!==_e.value?ze+(ze&&!/\s$/.test(ze)?`
|
|
138
138
|
`:"")+ee:ze.slice(0,_e.start)+ee+ze.slice(_e.end))};b.useEffect(()=>{if(!c)return;const ee=ky(_e=>V(_e.replace(/\r\n?/g,`
|
|
139
|
-
`)),e,!!t,t);return t||s0(e),ee},[c,e,t]);const Z=()=>{const ee=f0();return`${location.origin}:${ee?.targetPeerId??""}:${ee?.serviceOrigin??""}`},le=ee=>{const _e=$(),ze=Z(),Y=L.current.onUploadChange;z(""),R(ce=>ce+1),Y?.(1),O.current=O.current.then(async()=>{try{if(ze!==Z())throw new Error("目标服务已切换,请重新添加附件");const ce=await ee();if(ze!==Z())throw new Error("目标服务已切换,请重新添加附件");Array.isArray(ce)?V(ce.map(Dc).join(" ")+" ",_e):ce&&V(ce,_e)}catch(ce){const qe=ce instanceof Error?ce.message:"附件准备失败,请重试";z(qe.includes("Upload did not return")?"附件上传未返回完整路径,请重试":qe)}finally{R(ce=>ce-1),Y?.(-1)}})},be=async ee=>ee.length===1&&ee[0].type.startsWith("image/")?[await a3(ee[0])]:c3(ee),pe=ee=>{const _e=ee.clipboardData.files.length?Array.from(ee.clipboardData.files):Array.from(ee.clipboardData.items??[]).filter(ce=>ce.kind==="file").map(ce=>ce.getAsFile()).filter(ce=>ce!==null),ze=ee.clipboardData.getData("text/plain"),Y=vo();!Y?.readClipboardFiles&&!_e.length&&ze||!Y&&!_e.length&&typeof navigator.clipboard?.read!="function"||(ee.preventDefault(),le(async()=>{const ce=Z();let qe;if(Y?.readClipboardFiles)try{const we=await l3();if(we.paths.length||we.files.length)return[...we.paths,...await be(we.files)]}catch(we){if(we instanceof o0)throw we;qe=we}if(ce!==Z())throw new Error("目标服务已切换,请重新粘贴");if(_e.length)return be(_e);if(ze)return ze;if(typeof navigator.clipboard?.read=="function"){const we=await navigator.clipboard.read(),ye={read:async()=>we},Le=await o3(ye);if(Le.length)return be(Le);const Be=await ff(ye);if(Be)return be([Be]);for(const ne of we)if(ne.types.includes("text/plain"))return(await ne.getType("text/plain")).text()}else{const we=await ff();if(we)return be([we])}if(qe)throw qe;return null}))};return s.jsxs("div",{className:"space-y-1.5",onFocusCapture:()=>s0(e),onPointerDownCapture:()=>s0(e),children:[s.jsx("label",{htmlFor:w,className:"block text-xs text-muted-foreground",children:r}),s.jsx("textarea",{ref:v,id:w,value:n,required:d,disabled:l,autoFocus:p,"aria-describedby":E||B?`${w}-status`:void 0,placeholder:m,className:x,onChange:ee=>a(ee.target.value),onPaste:pe,onDragOver:ee=>{!l&&ee.dataTransfer.types.includes("Files")&&ee.preventDefault()},onDrop:ee=>{const _e=Array.from(ee.dataTransfer.files);!_e.length||l||(ee.preventDefault(),ee.stopPropagation(),le(()=>be(_e)))}}),s.jsxs("div",{className:"flex min-h-9 items-center gap-2",children:[s.jsx("input",{ref:S,type:"file",multiple:!0,hidden:!0,"aria-label":`选择附件:${r}`,onChange:ee=>{const _e=Array.from(ee.target.files??[]);ee.target.value="",_e.length&&le(()=>be(_e))}}),s.jsxs("button",{type:"button","aria-label":`添加附件:${r}`,title:"添加附件",disabled:l,className:"inline-flex min-h-9 shrink-0 items-center gap-1.5 rounded-lg px-2 text-xs text-muted-foreground hover:bg-surface-2 disabled:opacity-40 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary",onClick:()=>S.current?.click(),children:[s.jsx(ZT,{size:14}),"附件"]}),E>0?s.jsxs("span",{id:`${w}-status`,role:"status",className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[s.jsx(bn,{size:12,className:"animate-spin"}),"正在准备附件…"]}):B?s.jsx("span",{id:`${w}-status`,role:"alert",className:"break-words text-xs text-destructive",children:B}):s.jsx("span",{className:"text-[11px] text-muted-foreground/70",children:"可粘贴图片、文件或拖入附件"})]})]})}function Sb(e,t=!1,r=""){e=e.filter(d=>d.purpose!=="automation");const n=new Map(e.map(d=>[d.id,d])),a=d=>n.get(d.parentTaskId??d.workflow?.rootTaskId??""),c=d=>{const p=[];let m=d;for(;;){const x=p.findIndex(w=>w.id===m.id);if(x!==-1)return p.slice(x).sort((w,v)=>w.id.localeCompare(v.id))[0];p.push(m);const y=a(m);if(!y||y.status==="closed"&&m.status!=="closed")return m;m=y}},l=new Map(e.map(d=>[d.id,c(d).id]));return e.filter(d=>t||!!r.trim()||l.get(d.id)===d.id).map(d=>{const p=t||r.trim()?[]:e.filter(y=>y.id!==d.id&&l.get(y.id)===d.id&&y.status!=="closed"),m=d.status==="open"&&!Ui(d)?p.find(y=>y.decisions.some(w=>w.status==="pending"))??p.find(y=>Ui(y)||y.workflow?.paused):void 0,x=p.filter(y=>Ui(y)||y.workflow?.paused).length;return{task:d,children:p,attention:m,attentionCount:x,rootId:l.get(d.id)}})}function G6(e,t=[]){const r=Kc(e),n={已验收:"已完成 · 你已验收",独立评审通过:"执行交付已评审",需要你回答:"请回答成员的问题",需要你确认方案:"请确认方案",等待你验收:"请查看结果并验收",成员报告受阻:"需要补充条件",成员报告失败:"成员报告执行失败",成员确认接手:"已接手 · 等待后续报告",成员报告进行中:"成员报告:进行中",等待独立评审:"结果已提交 · 等待评审","评审通过 · 等待接续":"交付已评审 · 等待接续","已要求跟进 · 等待新结果":"已提出跟进 · 等待新结果"};return e.status==="open"&&t.length&&!Ui(e)&&!e.artifacts.some(a=>a.kind==="result"&&a.attemptId===e.activeAttemptId)?t.every(a=>a.status==="accepted")?"执行交付已评审 · 等待总结果":"目标未完成 · 执行交付待齐":n[r]??r}function AO({task:e,children:t,onSelect:r}){const n=new Map(t.map(m=>[m.id,m])),a=(t.length?t:e.children??[]).filter(m=>m.status!=="closed");if(!a.length)return null;const c=(m,x)=>{const y=n.get(m);return y&&(Ui(y)||y.workflow?.paused)?0:x?2:1},l=[...a].sort((m,x)=>c(m.id,m.status==="accepted")-c(x.id,x.status==="accepted")||(n.get(x.id)?.updatedAt??0)-(n.get(m.id)?.updatedAt??0)),d=a.filter(m=>m.status==="accepted").length,p=m=>{const x=n.get(m.id),y=m.status==="accepted",w=x&&(Ui(x)||x.workflow?.paused),v=x?G6(x):y?m.completionMode==="reviewed"?"执行交付已评审":"已验收":"等待报告",S=y?zu:Hu;return s.jsxs("button",{type:"button",className:"flex min-h-11 w-full items-start gap-2 rounded-lg px-1 py-2 text-left hover:bg-surface-2 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary",onClick:()=>r(m.id),children:[s.jsx(S,{size:14,className:`mt-0.5 shrink-0 ${y||w?"text-primary":"text-muted-foreground"}`}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{title:m.title,className:"block line-clamp-2 break-words text-xs leading-5 text-foreground",children:m.title}),s.jsx("span",{className:`block text-[11px] leading-5 ${w?"text-primary":"text-muted-foreground"}`,children:v})]}),s.jsx(Ks,{size:12,className:"mt-1 shrink-0 text-muted-foreground"})]},m.id)};return s.jsxs("section",{"aria-label":"执行事项",className:"mx-4 border-t border-border/15 py-2",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2 text-[11px] text-muted-foreground",children:[s.jsx("span",{children:"执行事项"}),s.jsxs("span",{children:[d,"/",a.length," 项已完成"]})]}),l.slice(0,3).map(p),l.length>3&&s.jsxs("details",{children:[s.jsxs("summary",{className:"min-h-11 cursor-pointer py-3 text-[11px] text-muted-foreground",children:["展开其余 ",l.length-3," 项"]}),l.slice(3).map(p)]})]})}function Cb(e){return e.status!=="open"?"done":Ui(e)||e.workflow?.paused?"attention":e.activeAttemptId?"running":"backlog"}const Sl=[{id:"backlog",label:"待开始",icon:Hu,hint:"等待分派或依赖完成"},{id:"running",label:"执行中",icon:lf,hint:"分派后的任务会出现在这里"},{id:"attention",label:"需要你",icon:Xu,hint:"问题、方案与验收都在这里"},{id:"done",label:"已完成",icon:zu,hint:"验收后的结果会保留在这里"}];function TO({tasks:e,selectedId:t,onSelect:r,name:n,storage:a,action:c,navigation:l,settings:d}){const p=b.useRef(null),m=b.useRef(null),x=b.useRef("backlog"),y=b.useRef(0),w=b.useRef(null),[v,S]=b.useState(Date.now);b.useEffect(()=>{const H=setInterval(()=>S(Date.now()),3e4);return()=>clearInterval(H)},[]);const[L,E]=b.useState(!1);b.useEffect(()=>{const H=new ResizeObserver(ae=>{const Ae=ae[0].contentRect.width;E(Ae>=760),Ae!==y.current&&Ae<760&&m.current&&(m.current.scrollLeft=Sl.findIndex(Ye=>Ye.id===x.current)*m.current.clientWidth),y.current=Ae});return p.current&&H.observe(p.current),()=>H.disconnect()},[]);const[R]=b.useState(()=>{try{return JSON.parse(localStorage.getItem(`${a}:board`)??"null")}catch{return null}}),[B,z]=b.useState(()=>{if(Sl.some(Ae=>Ae.id===R?.lane))return R.lane;const ae=Sb(e,R?.showSteps===!0,R?.query??"").map(Ae=>Ae.attention?"attention":Cb(Ae.task));return ae.includes("attention")?"attention":ae.includes("running")?"running":ae.includes("backlog")?"backlog":"done"});x.current=B;function O(H,ae=!0){z(H);const Ae=m.current;if(!Ae||!Ae.clientWidth)return;w.current=H;const Ye=Sl.findIndex(St=>St.id===H)*Ae.clientWidth,et=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;Ae.scrollTo?Ae.scrollTo({left:Ye,behavior:ae&&!et?"smooth":"auto"}):Ae.scrollLeft=Ye}b.useEffect(()=>{L||O(x.current,!1)},[L]);const[$,V]=b.useState(typeof R?.scope=="string"?R.scope:"all"),[Z,le]=b.useState(typeof R?.query=="string"?R.query:""),[be,pe]=b.useState(R?.closed===!0),[ee,_e]=b.useState(R?.showSteps===!0),[ze,Y]=b.useState(!!R?.query),[ce,qe]=b.useState(!1),[we,ye]=b.useState(!1),Le=b.useRef(null),Be=b.useRef(null);b.useEffect(()=>{if(!we)return;Le.current?.querySelector('[aria-label="看板更多操作"] button')?.focus();const H=Ae=>{Le.current?.contains(Ae.target)||ye(!1)},ae=Ae=>{Ae.key==="Escape"&&(Ae.preventDefault(),Ae.stopPropagation(),ye(!1),Be.current?.focus())};return document.addEventListener("pointerdown",H),document.addEventListener("keydown",ae),()=>{document.removeEventListener("pointerdown",H),document.removeEventListener("keydown",ae)}},[we]);const ne=b.useRef(null),Fe=b.useRef(null),ke=b.useRef(null),Ee=b.useRef(null);b.useEffect(()=>{ze&&ne.current?.focus()},[ze]),b.useEffect(()=>{if(!ce)return;ke.current?.querySelector("select")?.focus();const H=Ae=>{ke.current?.contains(Ae.target)||qe(!1)},ae=Ae=>{Ae.key==="Escape"&&(Ae.preventDefault(),Ae.stopPropagation(),qe(!1),(L?Ee:Be).current?.focus())};return document.addEventListener("pointerdown",H),document.addEventListener("keydown",ae),()=>{document.removeEventListener("pointerdown",H),document.removeEventListener("keydown",ae)}},[ce]),b.useEffect(()=>{try{localStorage.setItem(`${a}:board`,JSON.stringify({lane:B,scope:$,query:Z,closed:be,showSteps:ee}))}catch{}},[a,B,$,Z,be,ee]);const Pe=e.filter(H=>H.workflow?.kind==="goal"),Ne=Sb(e,ee,Z),oe=new Map(Ne.map(H=>[H.task.id,H])),We=H=>oe.get(H.id)?.attention?"attention":Cb(H),nt=t?Ne.find(H=>H.task.id===t||H.children.some(ae=>ae.id===t)):void 0,gt=nt?We(nt.task):void 0;b.useEffect(()=>{gt&&O(gt,!1)},[t,gt]);const ue=Ne.map(H=>H.task).filter(H=>(be||H.status!=="closed")&&($==="all"||H.id===$||oe.get(H.id)?.rootId===$)&&(!Z.trim()||`${H.title} ${H.spec} ${H.attempts.map(ae=>n(H,ae.assignee)).join(" ")}`.toLocaleLowerCase().includes(Z.trim().toLocaleLowerCase()))),Ze=+($!=="all")+Number(be)+Number(ee),at="inline-flex min-h-11 min-w-11 shrink-0 items-center justify-center gap-1.5 rounded-lg px-2 text-xs text-muted-foreground hover:bg-surface-2 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary",Ie="flex min-h-11 w-full items-center justify-start gap-3 rounded-lg px-3 text-left text-sm font-medium text-foreground hover:bg-surface-2 active:bg-surface-elevated focus-visible:bg-surface-2 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary",Ge=s.jsxs("div",{className:`relative flex min-w-0 items-center ${L?"flex-1 max-w-[240px]":"w-full"}`,children:[s.jsx("span",{className:"sr-only",children:"搜索任务"}),s.jsx(jl,{"aria-hidden":"true",size:15,className:"pointer-events-none absolute left-3 text-muted-foreground"}),s.jsx("input",{ref:ne,"aria-label":"搜索任务",type:"search",value:Z,onChange:H=>le(H.target.value),onKeyDown:H=>{H.key==="Escape"&&(H.preventDefault(),H.stopPropagation(),Z?le(""):(Y(!1),requestAnimationFrame(()=>(L?Fe:Be).current?.focus())))},placeholder:"搜索任务或负责人",className:"min-h-11 w-full rounded-lg border border-border/20 bg-transparent pl-9 pr-9 text-xs outline-none focus:border-primary"}),s.jsx("button",{type:"button","aria-label":"关闭搜索",className:"absolute right-0 flex min-h-11 w-9 items-center justify-center text-muted-foreground",onClick:()=>{le(""),Y(!1),requestAnimationFrame(()=>(L?Fe:Be).current?.focus())},children:s.jsx(In,{size:14})})]}),Ce=s.jsxs("div",{"aria-label":"任务筛选",className:"absolute right-0 top-full z-30 mt-1 w-64 space-y-3 rounded-xl border border-border/30 bg-surface p-3 shadow-xl",children:[s.jsxs("label",{className:"block space-y-1 text-xs text-muted-foreground",children:[s.jsx("span",{children:"目标范围"}),s.jsxs("select",{"aria-label":"按目标查看",value:$,onChange:H=>V(H.target.value),className:"min-h-11 w-full rounded-lg border border-border/20 bg-surface-2 px-3 text-xs text-foreground",children:[s.jsx("option",{value:"all",children:"所有目标"}),Pe.map(H=>s.jsx("option",{value:H.id,children:H.title},H.id))]})]}),s.jsxs("label",{className:"flex min-h-11 items-center gap-2 text-xs text-muted-foreground",children:[s.jsx("input",{type:"checkbox",checked:be,onChange:H=>pe(H.target.checked)}),"含已关闭"]}),s.jsxs("label",{className:"flex min-h-11 items-center gap-2 text-xs text-muted-foreground",children:[s.jsx("input",{type:"checkbox",checked:ee,onChange:H=>_e(H.target.checked)}),"显示执行子任务"]}),Ze>0&&s.jsx("button",{type:"button",className:"min-h-11 w-full rounded-lg text-xs text-primary hover:bg-surface-2",onClick:()=>{V("all"),pe(!1),_e(!1)},children:"清除筛选"})]});return s.jsxs("div",{ref:p,className:"flex min-h-0 min-w-0 flex-1 flex-col gap-2",children:[s.jsx("div",{ref:L?void 0:ke,"aria-label":"看板工具栏",className:"relative z-20 flex shrink-0 flex-wrap items-center gap-1.5 border-b border-border/15 pb-2",children:L?s.jsxs(s.Fragment,{children:[l&&s.jsx("div",{className:"flex min-w-0 items-center mr-auto",children:l}),ze?Ge:s.jsx("button",{ref:Fe,type:"button","aria-label":"搜索任务",title:"搜索任务",className:`${at} ${l?"":"ml-auto"}`,onClick:()=>Y(!0),children:s.jsx(jl,{size:16})}),s.jsxs("div",{ref:ke,className:"relative shrink-0",children:[s.jsxs("button",{ref:Ee,type:"button","aria-label":Ze?`筛选任务,${Ze} 项已启用`:"筛选任务","aria-expanded":ce,className:`${at} ${Ze?"text-primary":""}`,onClick:()=>qe(H=>!H),children:[s.jsx(Um,{size:15}),s.jsx("span",{children:"筛选"}),Ze>0&&s.jsx("span",{className:"tabular-nums text-primary",children:Ze})]}),ce&&Ce]}),d,c&&s.jsx("div",{className:"shrink-0",children:c})]}):s.jsxs(s.Fragment,{children:[l&&s.jsx("div",{className:"mr-auto flex min-w-0 items-center",children:l}),c&&s.jsx("div",{className:"shrink-0",children:c}),s.jsxs("div",{ref:Le,className:"relative shrink-0",children:[s.jsxs("button",{ref:Be,type:"button","aria-label":"更多看板操作","aria-expanded":we,className:`${at} ${we?"bg-surface-2 text-foreground":Ze||Z.trim()?"text-primary":""}`,onClick:()=>{ye(H=>!H),qe(!1)},children:[s.jsx(To,{size:18}),Ze>0&&s.jsx("span",{className:"text-[10px]",children:Ze})]}),we&&s.jsxs("div",{role:"group","aria-label":"看板更多操作",className:"absolute right-0 top-full z-30 mt-2 flex w-52 max-w-[calc(100vw-2rem)] flex-col gap-0.5 rounded-xl border border-border/40 bg-surface p-1.5 shadow-xl",onClick:()=>ye(!1),children:[s.jsxs("button",{ref:Fe,type:"button","aria-label":"搜索任务",className:Ie,onClick:()=>Y(!0),children:[s.jsx(jl,{size:18,className:"shrink-0 text-muted-foreground"}),"搜索任务"]}),s.jsxs("button",{ref:Ee,type:"button","aria-label":Ze?`筛选任务,${Ze} 项已启用`:"筛选任务",className:Ie,onClick:()=>qe(!0),children:[s.jsx(Um,{size:18,className:"shrink-0 text-muted-foreground"}),"筛选任务",Ze>0&&s.jsx("span",{className:"ml-auto rounded bg-primary/10 px-1.5 text-xs tabular-nums text-primary",children:Ze})]}),d&&s.jsx("div",{className:"mt-1 border-t border-border/30 pt-1 [&>button]:min-h-11 [&>button]:w-full [&>button]:justify-start [&>button]:gap-3 [&>button]:px-3 [&>button]:text-left [&>button]:text-sm [&>button]:text-foreground [&>button:hover]:bg-surface-2 [&>button:active]:bg-surface-elevated [&>button:focus-visible]:bg-surface-2 [&>button>svg]:h-[18px] [&>button>svg]:w-[18px] [&>button>svg]:shrink-0 [&>button>svg]:text-muted-foreground [&>button>span]:not-sr-only",children:d})]})]}),ze&&Ge,ce&&Ce]})}),s.jsx("p",{className:"px-1 text-[11px] leading-5 text-muted-foreground",children:ee?"包含执行子任务,可在筛选中切回目标视图。":"每张卡片对应一个目标,待完成事项和最近交付直接显示在卡片中。"}),s.jsx("nav",{hidden:L,"aria-label":"看板阶段",className:`${L?"hidden":"grid"} shrink-0 grid-cols-4 gap-1`,children:Sl.map(H=>s.jsxs("button",{type:"button","aria-pressed":B===H.id,className:`min-h-11 rounded-lg px-1 text-xs ${B===H.id?"bg-surface-2 text-foreground":"text-muted-foreground"}`,onClick:()=>O(H.id),children:[H.label,s.jsx("span",{className:"ml-1 tabular-nums",children:ue.filter(ae=>We(ae)===H.id).length})]},H.id))}),s.jsxs("div",{ref:L?void 0:m,"data-kanban-scroll":!0,onPointerDown:()=>{w.current=null},onWheel:()=>{w.current=null},"aria-label":L?void 0:"可左右滑动的任务看板",onScroll:L?void 0:H=>{if(H.target!==H.currentTarget||!H.currentTarget.clientWidth)return;const ae=w.current;if(ae){const Ye=Sl.findIndex(et=>et.id===ae)*H.currentTarget.clientWidth;if(Math.abs(H.currentTarget.scrollLeft-Ye)>2)return;w.current=null}const Ae=Math.max(0,Math.min(Sl.length-1,Math.round(H.currentTarget.scrollLeft/H.currentTarget.clientWidth)));z(Sl[Ae].id)},className:L?"min-h-0 flex-1 overflow-auto pb-3":"min-h-0 flex-1 snap-x snap-mandatory overflow-x-auto overflow-y-hidden overscroll-x-contain [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:[L&&s.jsx("div",{"aria-label":"看板列标题",className:"sticky top-0 z-10 grid min-w-[1000px] grid-cols-4 gap-4 border-b border-border/15 bg-[var(--chrome-bg)] pb-2",children:Sl.map(H=>{const ae=H.icon;return s.jsxs("h4",{className:`flex items-center gap-2 px-3 py-2 text-[13px] font-medium ${H.id==="attention"?"text-primary":"text-muted-foreground"}`,children:[s.jsx(ae,{size:15}),H.label,s.jsx("span",{className:"ml-auto tabular-nums text-xs",children:ue.filter(Ae=>We(Ae)===H.id).length})]},H.id)})}),s.jsx("div",{className:L?"grid min-h-full min-w-[1000px] grid-cols-4 items-start gap-4 pt-2":"flex h-full",children:Sl.map(H=>{const ae=ue.filter(Ae=>We(Ae)===H.id).sort((Ae,Ye)=>Ye.updatedAt-Ae.updatedAt);return s.jsx("section",{"aria-label":`${H.label}任务`,"aria-hidden":!L&&B!==H.id?!0:void 0,ref:Ae=>{Ae&&(Ae.inert=!L&&B!==H.id)},style:L?void 0:{width:"100%"},className:L?"min-w-0 px-1":"h-full min-w-0 shrink-0 snap-start snap-always overflow-y-auto overscroll-y-contain px-1 pb-3 pt-2",children:s.jsxs("div",{className:"space-y-2",children:[ae.map(Ae=>{const Ye=oe.get(Ae.id),et=Ye.attention??Ae,St=et.attempts.find(tt=>tt.id===et.activeAttemptId),Gt=et.decisions.find(tt=>tt.status==="pending"),Qt=Kc(et),wt=G6(et,Ye.children),zt=Jf(et),Vt=zt[0],Kt=zt.find(tt=>tt.source==="system"),Ot=zt.find(tt=>tt.source==="unknown"),It=Kt?.content,xe=H.id==="attention",Ve=Gt?"回答问题":Ot?"查看详情核对记录":Vt?.source==="member"&&Kt?"查看条件与异常处理":Vt?.source==="member"?"查看阻塞并补充条件":It?"查看原因与处理":Qt==="等待你验收"?"查看结果并验收":Qt==="需要你确认方案"?"查看并确认方案":"查看任务并处理",ht=et.artifacts.filter(tt=>tt.kind==="result"&&tt.attemptId===et.activeAttemptId).at(-1),q=et.events.filter(tt=>tt.kind==="revise"&&tt.source==="user"&&tt.attemptId===et.activeAttemptId&&(!ht||tt.createdAt>=ht.createdAt)).at(-1),ut=Gt?Gt.question||"成员提出了一个问题,打开后可查看并回答。":Vt?.summary||q?.content||ht?.summary||(St?.report?.content?W6(St.report.content).summary:St?.report?.summary||""),qt=e.find(tt=>tt.id===Ae.parentTaskId);return s.jsxs("article",{"aria-label":Ae.title,className:`overflow-hidden rounded-xl border bg-surface text-left shadow-sm ${t===Ae.id?"border-primary/60":It?"border-destructive/35":"border-border/20"}`,children:[s.jsxs("button",{type:"button","data-task-id":Ae.id,"aria-pressed":t===Ae.id,className:"block w-full rounded-xl p-4 text-left transition hover:bg-surface-2/40 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary",onClick:()=>r(et.id),children:[qt&&s.jsx("span",{className:"mb-2 block truncate text-[10px] text-muted-foreground",children:qt.title}),s.jsx("span",{title:Ae.title,className:"block line-clamp-3 break-words text-sm font-medium leading-6 text-foreground",children:Ae.title}),s.jsxs("span",{className:`mt-3 flex items-center gap-1.5 text-xs ${It&&Vt?.source!=="member"?"text-destructive":xe?"text-primary":"text-muted-foreground"}`,children:[It&&Vt?.source!=="member"&&s.jsx(P1,{size:13,className:"shrink-0"}),wt]}),Ye.attention&&s.jsxs("span",{className:"mt-2 block truncate text-[11px] text-muted-foreground",children:["来自执行任务:",Ye.attention.title]}),Ye.attention&&Ye.attentionCount>1&&s.jsxs("span",{className:"mt-1 block text-[11px] text-primary",children:["共 ",Ye.attentionCount," 项执行需要你处理"]}),ut&&s.jsx("span",{className:"mt-2 line-clamp-3 break-words text-xs leading-5 text-foreground/80",children:ut}),Kt&&Vt?.source==="member"&&s.jsxs("span",{className:"mt-2 block line-clamp-2 break-words text-xs leading-5 text-destructive",children:[Kt.label,":",Kt.summary]}),Ot&&s.jsxs("span",{className:"mt-2 block line-clamp-2 break-words text-xs leading-5 text-muted-foreground",children:[Ot.label,":",Ot.summary]}),xe&&s.jsxs("span",{className:`mt-4 flex min-h-9 items-center justify-between rounded-lg px-2.5 text-xs font-medium ${It?"bg-destructive/10 text-destructive":"bg-primary/10 text-primary"}`,children:[Ve,s.jsx($m,{size:14})]}),!xe&&(Ae.status==="accepted"||Ae.artifacts.some(tt=>tt.kind==="result"&&tt.attemptId===Ae.activeAttemptId))&&s.jsxs("span",{className:"mt-3 flex min-h-9 items-center justify-between text-xs font-medium text-primary",children:[q?"查看跟进":"查看结果",s.jsx($m,{size:14})]})]}),s.jsx(AO,{task:Ae,children:Ye.children,onSelect:r}),s.jsxs("div",{className:"mx-4 border-t border-border/10 py-3 text-[11px] text-muted-foreground",children:[s.jsxs("span",{className:"block truncate",children:[Ye.attention?"待处理任务负责人:":Ae.workflow?.kind==="goal"?"协调者:":"负责人:",St?n(et,St.assignee):et.scheduledAssignee?n(et,et.scheduledAssignee):"未分派"]}),s.jsx(Df,{task:et,now:v,compact:!0})]})]},Ae.id)}),!ae.length&&s.jsx("p",{className:"px-2 py-3 text-xs leading-6 text-muted-foreground/70",children:Z||$!=="all"?"没有匹配的任务":e.length?"暂无任务":H.hint})]})},H.id)})})]})]})}const Rl=hc((e,t)=>({views:{},details:{},ensureDetail:(r,n)=>{const a=t().details[r];return a||(e(c=>({details:{...c.details,[r]:n}})),n)},updateDetail:(r,n,a)=>e(c=>{const l=c.details[r];if(!l)return c;const d=typeof a=="function"?a(l[n]):a;return Object.is(l[n],d)?c:{details:{...c.details,[r]:{...l,[n]:d}}}}),ensure:(r,n)=>{const a=t().views[r];return a||(e(c=>({views:{...c.views,[r]:n}})),n)},update:(r,n,a)=>e(c=>{const l=c.views[r];if(!l)return c;const d=typeof a=="function"?a(l[n]):a;return Object.is(l[n],d)?c:{views:{...c.views,[r]:{...l,[n]:d}}}})}));function Eh(e,t){return r=>Rl.getState().update(e,t,r)}function Sm(e,t){return r=>Rl.getState().updateDetail(e,t,r)}const SO=b.lazy(()=>Oc(()=>Promise.resolve().then(()=>hO),void 0).then(e=>({default:e.DirectoryPickerDialog}))),CO=b.lazy(()=>Oc(()=>import("./CollaborationTaskContent-BwHxwcOP.js"),__vite__mapDeps([6,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17]))),ca="inline-flex min-h-11 items-center justify-center gap-2 rounded-lg px-3 text-[13px] transition disabled:cursor-not-allowed disabled:opacity-40 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary",Ps="w-full min-h-11 rounded-lg border border-border/30 bg-surface-2 px-3 py-2 text-sm text-foreground outline-none focus:border-primary",cl=`${ca} bg-primary text-primary-foreground`,ai=`${ca} bg-surface-2 text-foreground hover:bg-surface-2/80`,_O={created:"创建任务",assigned:"分派",report:"成员报告",respond:"答复",question:"提出问题",answer:"回答问题","submit-plan":"提交方案",review:"提交评审","request-review":"请求独立评审","approve-plan":"用户确认方案",accepted:"用户验收",revise:"要求修改",comment:"补充说明",coordinator:"协调者变更",close:"关闭",reopen:"重新打开",scheduled:"等待自动分派",coordinate:"协调说明","child-update":"子任务更新","review-passed":"独立评审通过","review-blocked":"评审受阻","automation-blocked":"自动安排受阻",pause:"暂停安排",resume:"继续安排",retry:"请求重新检查"},Ou=e=>`${e.serviceId}:${e.sessionId}`,Sa=e=>new Date(e).toLocaleString([],{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit"});function go(e,t){try{const r=JSON.parse(localStorage.getItem(e)??"null");return r===null||t!==null&&(typeof r!=typeof t||Array.isArray(r)!==Array.isArray(t))?t:r}catch{return t}}function Fi(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch{}}const t0={mode:"goal",isolated:!0,title:"",spec:"",constraints:"",acceptance:"",assignee:"",coordinator:"",parent:"",dependencies:[]},_b="__new_coordinator__";function kO(e){const t={...t0,...go(e,t0)};return!t||!Array.isArray(t.dependencies)||t.dependencies.some(r=>typeof r!="string")||Object.keys(t0).some(r=>!["dependencies","isolated"].includes(r)&&typeof t[r]!="string")?t0:{...t,mode:t.mode==="task"?"task":"goal",isolated:t.isolated!==!1}}function V6(e,t){const r=e.workflow?.rootTaskId?t.find(c=>c.id===e.workflow?.rootTaskId):null;if(r?.workflow?.paused)return r;const n=new Set([e.id]);let a=e.parentTaskId;for(;a&&!n.has(a);){n.add(a);const c=t.find(l=>l.id===a);if(!c)break;if(c.workflow?.kind==="goal"&&c.workflow.paused)return c;a=c.parentTaskId}return e.workflow?.paused?e:null}function LO({group:e,sessions:t,active:r,onOpenSession:n,onAttentionChange:a,onManageMembers:c,board:l=!1,boardNavigation:d,boardSettings:p,paneKey:m,agents:x=[],defaultCwd:y,onTeamReady:w}){const v=`termdock:tasks:${location.origin}:${e.id}`,[S,L]=b.useState([]),E=b.useRef(S);E.current=S;const[R,B]=b.useState(null),[z]=b.useState(()=>Rl.getState().ensure(v,{draft:kO(`${v}:draft`),selectedId:go(`${v}:selected`,null),creating:!1,mobileDetail:!1})),{selectedId:O,mobileDetail:$,creating:V,draft:Z}=Rl(re=>re.views[v]??z),le=Eh(v,"selectedId"),be=Eh(v,"mobileDetail"),pe=Eh(v,"creating"),ee=Eh(v,"draft"),[_e,ze]=b.useState(!1),[Y,ce]=b.useState(!1),qe=b.useRef(null),we=b.useRef(null),ye=b.useRef(!1),Le=b.useCallback(re=>{!re&&we.current===document.activeElement&&(ye.current=!0),we.current=re,re&&ye.current&&(ye.current=!1,re.focus())},[]);b.useEffect(()=>{const re=qe.current;if(!re)return;const mt=new ResizeObserver(Mt=>ze(Mt[0].contentRect.width>=(l?1100:760)));return mt.observe(re),()=>mt.disconnect()},[l]);const[Be,ne]=b.useState(!1),[Fe,ke]=b.useState(null),Ee=Ly(),[Pe,Ne]=b.useState(0),[oe,We]=b.useState(null),[nt,gt]=b.useState(!1),[ue,Ze]=b.useState(0),at=re=>Ze(mt=>Math.max(0,mt+re)),[Ie,Ge]=b.useState("");b.useEffect(()=>{if(!Ie)return;const re=setTimeout(()=>Ge(""),5e3);return()=>clearTimeout(re)},[Ie]);const[Ce,H]=b.useState("open"),[ae,Ae]=b.useState(""),Ye=b.useRef(!1),et=b.useRef(!0),St=b.useRef(new Map),Gt=b.useRef(!1),Qt=e.sessionIds.flatMap(re=>{const mt=t.find(Mt=>Mt.sessionId===re);return mt?[mt]:[]}),wt=Qt.map(re=>({...re,name:Iu(re,Qt)})),zt=Z.coordinator===_b,Vt=Z.coordinator||go(`${v}:lead`,""),Kt=wt.find(re=>re.sessionId===Z.coordinator&&re.agent),Ot=!!Z.coordinator&&!zt&&!Kt,It=zt||Ot?"":Kt?.sessionId||wt.find(re=>re.sessionId===Vt&&re.agent)?.sessionId||wt.find(re=>re.agent)?.sessionId||"",xe=wt.filter(re=>re.sessionId!==It&&re.agent).map(re=>re.sessionId),[Ve,ht]=b.useState(!1),[q,ut]=b.useState(!1),[qt,tt]=b.useState(()=>go(`${v}:agent`,"")),[De,nr]=b.useState(()=>go(`${v}:launch-profile`,e.defaultLaunchProfileId??"")),Ke=e.launchProfiles?.find(re=>re.id===De),_t=wt.flatMap(re=>re.agent&&x.some(mt=>mt.slug===re.agent.slug)?[re.agent.slug]:[]),$t=[...new Set(_t)].sort((re,mt)=>_t.filter(Mt=>Mt===mt).length-_t.filter(Mt=>Mt===re).length)[0],yt=x.find(re=>re.slug===Kt?.agent?.slug)?.slug??$t??x[0]?.slug??"",xt=Ke?.agentSlug??(qt||yt),[Rt,Ct]=b.useState(()=>go(`${v}:cwd`,wt[0]?.cwd??y??"")),fr=!wt.find(re=>re.sessionId===It)?.agent||!xe.length,[Yt,Sr]=b.useState(null),pn=!!Z.spec.trim()&&(!!Yt||!Ot&&(!fr||!e.federated&&(!De||!!Ke)&&!!x.find(re=>re.slug===xt)&&!!Rt.trim())),dr=S.find(re=>re.id===O)??null,me=R?.id===O?R:null;b.useEffect(()=>(et.current=!0,()=>{et.current=!1}),[]),b.useEffect(()=>{Fi(`${v}:draft`,Z)},[v,Z]),b.useEffect(()=>{Fi(`${v}:selected`,O)},[v,O]),b.useEffect(()=>{const re=Mt=>{const rr=Mt.detail;rr?.groupId===e.id&&(Fi(`${v}:open-task`,null),le(rr.taskId),be(!0),pe(!1),H("all"),Gr())};window.addEventListener("open-collaboration-task",re);const mt=go(`${v}:open-task`,null);return mt&&(le(mt),be(!0),H("all"),Fi(`${v}:open-task`,null)),()=>window.removeEventListener("open-collaboration-task",re)},[e.id]),b.useEffect(()=>{if(!r||!dr||R?.id===dr.id&&R.revision===dr.revision)return;let re=!1;return P8(dr.id).then(mt=>{re||(B(mt.task),ke(null))}).catch(mt=>{re||ke(mt instanceof Error?mt.message:"任务详情加载失败")}),()=>{re=!0}},[r,dr?.id,dr?.revision,R?.id,R?.revision,Pe]);const Gr=async()=>{if(!Gt.current){Gt.current=!0;try{const re=await Sy(e.id);et.current&&(L(re.tasks),ne(!0),ke(null),Ne(mt=>mt+1))}catch(re){et.current&&ke(re instanceof Error?re.message:"任务加载失败")}finally{Gt.current=!1}}};b.useEffect(()=>{if(!r)return;Gr();const re=()=>{!document.hidden&&navigator.onLine!==!1&&Gr()},mt=setInterval(re,2500);return document.addEventListener("visibilitychange",re),window.addEventListener(sf,re),window.addEventListener("pageshow",re),()=>{clearInterval(mt),document.removeEventListener("visibilitychange",re),window.removeEventListener(sf,re),window.removeEventListener("pageshow",re)}},[r,e.id]);const ot=re=>{const mt=JSON.stringify(re),Mt=go(`${v}:request`,null);let rr=St.current.get(mt)??(Mt?.fingerprint===mt?Mt.key:void 0);return rr||(rr=crypto.randomUUID(),St.current.set(mt,rr)),Fi(`${v}:request`,{fingerprint:mt,key:rr}),rr},pt=re=>{St.current.delete(JSON.stringify(re)),Fi(`${v}:request`,null)},ir=async(re,mt)=>{if(nt||Ye.current)return{ok:!1,error:"已有操作正在提交,请稍候。"};Ye.current=!0,gt(!0),We(null),Ge("");let Mt={...mt,expectedRevision:re.revision};if(["comment","revise"].includes(mt.kind)){const rr=go(`${v}:request`,null);try{const[Ar,Fr]=JSON.parse(rr?.fingerprint??"null"),{expectedRevision:Xt,...Zr}=Fr;Ar===re.id&&JSON.stringify(Zr)===JSON.stringify(mt)&&(Mt=Fr)}catch{}}try{const rr=await $8(re.id,{...Mt,idempotencyKey:ot([re.id,Mt])});if(pt([re.id,Mt]),Lu.getState().refresh(),et.current){const Ar=E.current.find(Jt=>Jt.id===rr.task.id),Fr=Ar&&Ar.revision>rr.task.revision?Ar:rr.task;L(Jt=>Jt.map(Pr=>Pr.id===rr.task.id&&Pr.revision<=rr.task.revision?rr.task:Pr)),B(Jt=>Jt?.id===rr.task.id&&Jt.revision>rr.task.revision?Jt:rr.task);const Xt=V6(Fr,E.current),Zr=`${mt.kind==="answer"?"回答已保存":"方案确认已保存"},${Xt?Xt.workflow?.kind==="goal"?"目标仍暂停;恢复目标后才能投递。":"任务仍暂停;继续安排后才能投递。":"投递状态请查看任务记录。"}`;Ge(["comment","revise"].includes(mt.kind)?"":mt.kind==="retry"?vO(re,rr.task):["answer","approve-plan"].includes(mt.kind)?Zr:mt.kind==="accept"?"已验收此版本结果。":"记录已保存。")}return{ok:!0}}catch(rr){const Ar=rr instanceof Error?rr.message:"操作失败";return Ar.includes("任务已更新")&&pt([re.id,Mt]),et.current&&(We(["comment","revise"].includes(mt.kind)?null:Ar),Gr()),{ok:!1,error:Ar}}finally{Ye.current=!1,et.current&>(!1)}},Mn=async re=>{if(re.preventDefault(),nt||ue>0||(Z.mode==="goal"?!pn:!Z.title.trim()||!Z.spec.trim())||Ye.current)return;Ye.current=!0,gt(!0),We(null);const mt=Z.mode==="goal",Mt={groupId:e.id,title:Z.title.trim()||Z.spec.trim().split(`
|
|
139
|
+
`)),e,!!t,t);return t||s0(e),ee},[c,e,t]);const Z=()=>{const ee=f0();return`${location.origin}:${ee?.targetPeerId??""}:${ee?.serviceOrigin??""}`},le=ee=>{const _e=$(),ze=Z(),Y=L.current.onUploadChange;z(""),R(ce=>ce+1),Y?.(1),O.current=O.current.then(async()=>{try{if(ze!==Z())throw new Error("目标服务已切换,请重新添加附件");const ce=await ee();if(ze!==Z())throw new Error("目标服务已切换,请重新添加附件");Array.isArray(ce)?V(ce.map(Dc).join(" ")+" ",_e):ce&&V(ce,_e)}catch(ce){const qe=ce instanceof Error?ce.message:"附件准备失败,请重试";z(qe.includes("Upload did not return")?"附件上传未返回完整路径,请重试":qe)}finally{R(ce=>ce-1),Y?.(-1)}})},be=async ee=>ee.length===1&&ee[0].type.startsWith("image/")?[await a3(ee[0])]:c3(ee),pe=ee=>{const _e=ee.clipboardData.files.length?Array.from(ee.clipboardData.files):Array.from(ee.clipboardData.items??[]).filter(ce=>ce.kind==="file").map(ce=>ce.getAsFile()).filter(ce=>ce!==null),ze=ee.clipboardData.getData("text/plain"),Y=vo();!Y?.readClipboardFiles&&!_e.length&&ze||!Y&&!_e.length&&typeof navigator.clipboard?.read!="function"||(ee.preventDefault(),le(async()=>{const ce=Z();let qe;if(Y?.readClipboardFiles)try{const we=await l3();if(we.paths.length||we.files.length)return[...we.paths,...await be(we.files)]}catch(we){if(we instanceof o0)throw we;qe=we}if(ce!==Z())throw new Error("目标服务已切换,请重新粘贴");if(_e.length)return be(_e);if(ze)return ze;if(typeof navigator.clipboard?.read=="function"){const we=await navigator.clipboard.read(),ye={read:async()=>we},Le=await o3(ye);if(Le.length)return be(Le);const Be=await ff(ye);if(Be)return be([Be]);for(const ne of we)if(ne.types.includes("text/plain"))return(await ne.getType("text/plain")).text()}else{const we=await ff();if(we)return be([we])}if(qe)throw qe;return null}))};return s.jsxs("div",{className:"space-y-1.5",onFocusCapture:()=>s0(e),onPointerDownCapture:()=>s0(e),children:[s.jsx("label",{htmlFor:w,className:"block text-xs text-muted-foreground",children:r}),s.jsx("textarea",{ref:v,id:w,value:n,required:d,disabled:l,autoFocus:p,"aria-describedby":E||B?`${w}-status`:void 0,placeholder:m,className:x,onChange:ee=>a(ee.target.value),onPaste:pe,onDragOver:ee=>{!l&&ee.dataTransfer.types.includes("Files")&&ee.preventDefault()},onDrop:ee=>{const _e=Array.from(ee.dataTransfer.files);!_e.length||l||(ee.preventDefault(),ee.stopPropagation(),le(()=>be(_e)))}}),s.jsxs("div",{className:"flex min-h-9 items-center gap-2",children:[s.jsx("input",{ref:S,type:"file",multiple:!0,hidden:!0,"aria-label":`选择附件:${r}`,onChange:ee=>{const _e=Array.from(ee.target.files??[]);ee.target.value="",_e.length&&le(()=>be(_e))}}),s.jsxs("button",{type:"button","aria-label":`添加附件:${r}`,title:"添加附件",disabled:l,className:"inline-flex min-h-9 shrink-0 items-center gap-1.5 rounded-lg px-2 text-xs text-muted-foreground hover:bg-surface-2 disabled:opacity-40 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary",onClick:()=>S.current?.click(),children:[s.jsx(ZT,{size:14}),"附件"]}),E>0?s.jsxs("span",{id:`${w}-status`,role:"status",className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[s.jsx(bn,{size:12,className:"animate-spin"}),"正在准备附件…"]}):B?s.jsx("span",{id:`${w}-status`,role:"alert",className:"break-words text-xs text-destructive",children:B}):s.jsx("span",{className:"text-[11px] text-muted-foreground/70",children:"可粘贴图片、文件或拖入附件"})]})]})}function Sb(e,t=!1,r=""){e=e.filter(d=>d.purpose!=="automation");const n=new Map(e.map(d=>[d.id,d])),a=d=>n.get(d.parentTaskId??d.workflow?.rootTaskId??""),c=d=>{const p=[];let m=d;for(;;){const x=p.findIndex(w=>w.id===m.id);if(x!==-1)return p.slice(x).sort((w,v)=>w.id.localeCompare(v.id))[0];p.push(m);const y=a(m);if(!y||y.status==="closed"&&m.status!=="closed")return m;m=y}},l=new Map(e.map(d=>[d.id,c(d).id]));return e.filter(d=>t||!!r.trim()||l.get(d.id)===d.id).map(d=>{const p=t||r.trim()?[]:e.filter(y=>y.id!==d.id&&l.get(y.id)===d.id&&y.status!=="closed"),m=d.status==="open"&&!Ui(d)?p.find(y=>y.decisions.some(w=>w.status==="pending"))??p.find(y=>Ui(y)||y.workflow?.paused):void 0,x=p.filter(y=>Ui(y)||y.workflow?.paused).length;return{task:d,children:p,attention:m,attentionCount:x,rootId:l.get(d.id)}})}function G6(e,t=[]){const r=Kc(e),n={已验收:"已完成 · 你已验收",独立评审通过:"执行交付已评审",需要你回答:"请回答成员的问题",需要你确认方案:"请确认方案",等待你验收:"请查看结果并验收",成员报告受阻:"需要补充条件",成员报告失败:"成员报告执行失败",成员确认接手:"已接手 · 等待后续报告",成员报告进行中:"成员报告:进行中",等待独立评审:"结果已提交 · 等待评审","评审通过 · 等待接续":"交付已评审 · 等待接续","已要求跟进 · 等待新结果":"已提出跟进 · 等待新结果"};return e.status==="open"&&t.length&&!Ui(e)&&!e.artifacts.some(a=>a.kind==="result"&&a.attemptId===e.activeAttemptId)?t.every(a=>a.status==="accepted")?"执行交付已评审 · 等待总结果":"目标未完成 · 执行交付待齐":n[r]??r}function AO({task:e,children:t,onSelect:r}){const n=new Map(t.map(m=>[m.id,m])),a=(t.length?t:e.children??[]).filter(m=>m.status!=="closed");if(!a.length)return null;const c=(m,x)=>{const y=n.get(m);return y&&(Ui(y)||y.workflow?.paused)?0:x?2:1},l=[...a].sort((m,x)=>c(m.id,m.status==="accepted")-c(x.id,x.status==="accepted")||(n.get(x.id)?.updatedAt??0)-(n.get(m.id)?.updatedAt??0)),d=a.filter(m=>m.status==="accepted").length,p=m=>{const x=n.get(m.id),y=m.status==="accepted",w=x&&(Ui(x)||x.workflow?.paused),v=x?G6(x):y?m.completionMode==="reviewed"?"执行交付已评审":"已验收":"等待报告",S=y?zu:Hu;return s.jsxs("button",{type:"button",className:"flex min-h-11 w-full items-start gap-2 rounded-lg px-1 py-2 text-left hover:bg-surface-2 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary",onClick:()=>r(m.id),children:[s.jsx(S,{size:14,className:`mt-0.5 shrink-0 ${y||w?"text-primary":"text-muted-foreground"}`}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{title:m.title,className:"block line-clamp-2 break-words text-xs leading-5 text-foreground",children:m.title}),s.jsx("span",{className:`block text-[11px] leading-5 ${w?"text-primary":"text-muted-foreground"}`,children:v})]}),s.jsx(Ks,{size:12,className:"mt-1 shrink-0 text-muted-foreground"})]},m.id)};return s.jsxs("section",{"aria-label":"执行事项",className:"mx-4 border-t border-border/15 py-2",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2 text-[11px] text-muted-foreground",children:[s.jsx("span",{children:"执行事项"}),s.jsxs("span",{children:[d,"/",a.length," 项已完成"]})]}),l.slice(0,3).map(p),l.length>3&&s.jsxs("details",{children:[s.jsxs("summary",{className:"min-h-11 cursor-pointer py-3 text-[11px] text-muted-foreground",children:["展开其余 ",l.length-3," 项"]}),l.slice(3).map(p)]})]})}function Cb(e){return e.status!=="open"?"done":Ui(e)||e.workflow?.paused?"attention":e.activeAttemptId?"running":"backlog"}const Sl=[{id:"backlog",label:"待开始",icon:Hu,hint:"等待分派或依赖完成"},{id:"running",label:"执行中",icon:lf,hint:"分派后的任务会出现在这里"},{id:"attention",label:"需要你",icon:Xu,hint:"问题、方案与验收都在这里"},{id:"done",label:"已完成",icon:zu,hint:"验收后的结果会保留在这里"}];function TO({tasks:e,selectedId:t,onSelect:r,name:n,storage:a,action:c,navigation:l,settings:d}){const p=b.useRef(null),m=b.useRef(null),x=b.useRef("backlog"),y=b.useRef(0),w=b.useRef(null),[v,S]=b.useState(Date.now);b.useEffect(()=>{const H=setInterval(()=>S(Date.now()),3e4);return()=>clearInterval(H)},[]);const[L,E]=b.useState(!1);b.useEffect(()=>{const H=new ResizeObserver(ae=>{const Ae=ae[0].contentRect.width;E(Ae>=760),Ae!==y.current&&Ae<760&&m.current&&(m.current.scrollLeft=Sl.findIndex(Ye=>Ye.id===x.current)*m.current.clientWidth),y.current=Ae});return p.current&&H.observe(p.current),()=>H.disconnect()},[]);const[R]=b.useState(()=>{try{return JSON.parse(localStorage.getItem(`${a}:board`)??"null")}catch{return null}}),[B,z]=b.useState(()=>{if(Sl.some(Ae=>Ae.id===R?.lane))return R.lane;const ae=Sb(e,R?.showSteps===!0,R?.query??"").map(Ae=>Ae.attention?"attention":Cb(Ae.task));return ae.includes("attention")?"attention":ae.includes("running")?"running":ae.includes("backlog")?"backlog":"done"});x.current=B;function O(H,ae=!0){z(H);const Ae=m.current;if(!Ae||!Ae.clientWidth)return;w.current=H;const Ye=Sl.findIndex(St=>St.id===H)*Ae.clientWidth,et=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;Ae.scrollTo?Ae.scrollTo({left:Ye,behavior:ae&&!et?"smooth":"auto"}):Ae.scrollLeft=Ye}b.useEffect(()=>{L||O(x.current,!1)},[L]);const[$,V]=b.useState(typeof R?.scope=="string"?R.scope:"all"),[Z,le]=b.useState(typeof R?.query=="string"?R.query:""),[be,pe]=b.useState(R?.closed===!0),[ee,_e]=b.useState(R?.showSteps===!0),[ze,Y]=b.useState(!!R?.query),[ce,qe]=b.useState(!1),[we,ye]=b.useState(!1),Le=b.useRef(null),Be=b.useRef(null);b.useEffect(()=>{if(!we)return;Le.current?.querySelector('[aria-label="看板更多操作"] button')?.focus();const H=Ae=>{Le.current?.contains(Ae.target)||ye(!1)},ae=Ae=>{Ae.key==="Escape"&&(Ae.preventDefault(),Ae.stopPropagation(),ye(!1),Be.current?.focus())};return document.addEventListener("pointerdown",H),document.addEventListener("keydown",ae),()=>{document.removeEventListener("pointerdown",H),document.removeEventListener("keydown",ae)}},[we]);const ne=b.useRef(null),Fe=b.useRef(null),ke=b.useRef(null),Ee=b.useRef(null);b.useEffect(()=>{ze&&ne.current?.focus()},[ze]),b.useEffect(()=>{if(!ce)return;ke.current?.querySelector("select")?.focus();const H=Ae=>{ke.current?.contains(Ae.target)||qe(!1)},ae=Ae=>{Ae.key==="Escape"&&(Ae.preventDefault(),Ae.stopPropagation(),qe(!1),(L?Ee:Be).current?.focus())};return document.addEventListener("pointerdown",H),document.addEventListener("keydown",ae),()=>{document.removeEventListener("pointerdown",H),document.removeEventListener("keydown",ae)}},[ce]),b.useEffect(()=>{try{localStorage.setItem(`${a}:board`,JSON.stringify({lane:B,scope:$,query:Z,closed:be,showSteps:ee}))}catch{}},[a,B,$,Z,be,ee]);const Pe=e.filter(H=>H.workflow?.kind==="goal"),Ne=Sb(e,ee,Z),oe=new Map(Ne.map(H=>[H.task.id,H])),We=H=>oe.get(H.id)?.attention?"attention":Cb(H),nt=t?Ne.find(H=>H.task.id===t||H.children.some(ae=>ae.id===t)):void 0,gt=nt?We(nt.task):void 0;b.useEffect(()=>{gt&&O(gt,!1)},[t,gt]);const ue=Ne.map(H=>H.task).filter(H=>(be||H.status!=="closed")&&($==="all"||H.id===$||oe.get(H.id)?.rootId===$)&&(!Z.trim()||`${H.title} ${H.spec} ${H.attempts.map(ae=>n(H,ae.assignee)).join(" ")}`.toLocaleLowerCase().includes(Z.trim().toLocaleLowerCase()))),Ze=+($!=="all")+Number(be)+Number(ee),at="inline-flex min-h-11 min-w-11 shrink-0 items-center justify-center gap-1.5 rounded-lg px-2 text-xs text-muted-foreground hover:bg-surface-2 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary",Ie="flex min-h-11 w-full items-center justify-start gap-3 rounded-lg px-3 text-left text-sm font-medium text-foreground hover:bg-surface-2 active:bg-surface-elevated focus-visible:bg-surface-2 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary",Ge=s.jsxs("div",{className:`relative flex min-w-0 items-center ${L?"flex-1 max-w-[240px]":"w-full"}`,children:[s.jsx("span",{className:"sr-only",children:"搜索任务"}),s.jsx(jl,{"aria-hidden":"true",size:15,className:"pointer-events-none absolute left-3 text-muted-foreground"}),s.jsx("input",{ref:ne,"aria-label":"搜索任务",type:"search",value:Z,onChange:H=>le(H.target.value),onKeyDown:H=>{H.key==="Escape"&&(H.preventDefault(),H.stopPropagation(),Z?le(""):(Y(!1),requestAnimationFrame(()=>(L?Fe:Be).current?.focus())))},placeholder:"搜索任务或负责人",className:"min-h-11 w-full rounded-lg border border-border/20 bg-transparent pl-9 pr-9 text-xs outline-none focus:border-primary"}),s.jsx("button",{type:"button","aria-label":"关闭搜索",className:"absolute right-0 flex min-h-11 w-9 items-center justify-center text-muted-foreground",onClick:()=>{le(""),Y(!1),requestAnimationFrame(()=>(L?Fe:Be).current?.focus())},children:s.jsx(In,{size:14})})]}),Ce=s.jsxs("div",{"aria-label":"任务筛选",className:"absolute right-0 top-full z-30 mt-1 w-64 space-y-3 rounded-xl border border-border/30 bg-surface p-3 shadow-xl",children:[s.jsxs("label",{className:"block space-y-1 text-xs text-muted-foreground",children:[s.jsx("span",{children:"目标范围"}),s.jsxs("select",{"aria-label":"按目标查看",value:$,onChange:H=>V(H.target.value),className:"min-h-11 w-full rounded-lg border border-border/20 bg-surface-2 px-3 text-xs text-foreground",children:[s.jsx("option",{value:"all",children:"所有目标"}),Pe.map(H=>s.jsx("option",{value:H.id,children:H.title},H.id))]})]}),s.jsxs("label",{className:"flex min-h-11 items-center gap-2 text-xs text-muted-foreground",children:[s.jsx("input",{type:"checkbox",checked:be,onChange:H=>pe(H.target.checked)}),"含已关闭"]}),s.jsxs("label",{className:"flex min-h-11 items-center gap-2 text-xs text-muted-foreground",children:[s.jsx("input",{type:"checkbox",checked:ee,onChange:H=>_e(H.target.checked)}),"显示执行子任务"]}),Ze>0&&s.jsx("button",{type:"button",className:"min-h-11 w-full rounded-lg text-xs text-primary hover:bg-surface-2",onClick:()=>{V("all"),pe(!1),_e(!1)},children:"清除筛选"})]});return s.jsxs("div",{ref:p,className:"flex min-h-0 min-w-0 flex-1 flex-col gap-2",children:[s.jsx("div",{ref:L?void 0:ke,"aria-label":"看板工具栏",className:"relative z-20 flex shrink-0 flex-wrap items-center gap-1.5 border-b border-border/15 pb-2",children:L?s.jsxs(s.Fragment,{children:[l&&s.jsx("div",{className:"flex min-w-0 items-center mr-auto",children:l}),ze?Ge:s.jsx("button",{ref:Fe,type:"button","aria-label":"搜索任务",title:"搜索任务",className:`${at} ${l?"":"ml-auto"}`,onClick:()=>Y(!0),children:s.jsx(jl,{size:16})}),s.jsxs("div",{ref:ke,className:"relative shrink-0",children:[s.jsxs("button",{ref:Ee,type:"button","aria-label":Ze?`筛选任务,${Ze} 项已启用`:"筛选任务","aria-expanded":ce,className:`${at} ${Ze?"text-primary":""}`,onClick:()=>qe(H=>!H),children:[s.jsx(Um,{size:15}),s.jsx("span",{children:"筛选"}),Ze>0&&s.jsx("span",{className:"tabular-nums text-primary",children:Ze})]}),ce&&Ce]}),d,c&&s.jsx("div",{className:"shrink-0",children:c})]}):s.jsxs(s.Fragment,{children:[l&&s.jsx("div",{className:"mr-auto flex min-w-0 items-center",children:l}),c&&s.jsx("div",{className:"shrink-0",children:c}),s.jsxs("div",{ref:Le,className:"relative shrink-0",children:[s.jsxs("button",{ref:Be,type:"button","aria-label":"更多看板操作","aria-expanded":we,className:`${at} ${we?"bg-surface-2 text-foreground":Ze||Z.trim()?"text-primary":""}`,onClick:()=>{ye(H=>!H),qe(!1)},children:[s.jsx(To,{size:18}),Ze>0&&s.jsx("span",{className:"text-[10px]",children:Ze})]}),we&&s.jsxs("div",{role:"group","aria-label":"看板更多操作",className:"absolute right-0 top-full z-30 mt-2 flex w-52 max-w-[calc(100vw-2rem)] flex-col gap-0.5 rounded-xl border border-border/40 bg-surface p-1.5 shadow-xl",onClick:()=>ye(!1),children:[s.jsxs("button",{ref:Fe,type:"button","aria-label":"搜索任务",className:Ie,onClick:()=>Y(!0),children:[s.jsx(jl,{size:18,className:"shrink-0 text-muted-foreground"}),"搜索任务"]}),s.jsxs("button",{ref:Ee,type:"button","aria-label":Ze?`筛选任务,${Ze} 项已启用`:"筛选任务",className:Ie,onClick:()=>qe(!0),children:[s.jsx(Um,{size:18,className:"shrink-0 text-muted-foreground"}),"筛选任务",Ze>0&&s.jsx("span",{className:"ml-auto rounded bg-primary/10 px-1.5 text-xs tabular-nums text-primary",children:Ze})]}),d&&s.jsx("div",{className:"mt-1 border-t border-border/30 pt-1 [&>button]:min-h-11 [&>button]:w-full [&>button]:justify-start [&>button]:gap-3 [&>button]:px-3 [&>button]:text-left [&>button]:text-sm [&>button]:text-foreground [&>button:hover]:bg-surface-2 [&>button:active]:bg-surface-elevated [&>button:focus-visible]:bg-surface-2 [&>button>svg]:h-[18px] [&>button>svg]:w-[18px] [&>button>svg]:shrink-0 [&>button>svg]:text-muted-foreground [&>button>span]:not-sr-only",children:d})]})]}),ze&&Ge,ce&&Ce]})}),s.jsx("p",{className:"px-1 text-[11px] leading-5 text-muted-foreground",children:ee?"包含执行子任务,可在筛选中切回目标视图。":"每张卡片对应一个目标,待完成事项和最近交付直接显示在卡片中。"}),s.jsx("nav",{hidden:L,"aria-label":"看板阶段",className:`${L?"hidden":"grid"} shrink-0 grid-cols-4 gap-1`,children:Sl.map(H=>s.jsxs("button",{type:"button","aria-pressed":B===H.id,className:`min-h-11 rounded-lg px-1 text-xs ${B===H.id?"bg-surface-2 text-foreground":"text-muted-foreground"}`,onClick:()=>O(H.id),children:[H.label,s.jsx("span",{className:"ml-1 tabular-nums",children:ue.filter(ae=>We(ae)===H.id).length})]},H.id))}),s.jsxs("div",{ref:L?void 0:m,"data-kanban-scroll":!0,onPointerDown:()=>{w.current=null},onWheel:()=>{w.current=null},"aria-label":L?void 0:"可左右滑动的任务看板",onScroll:L?void 0:H=>{if(H.target!==H.currentTarget||!H.currentTarget.clientWidth)return;const ae=w.current;if(ae){const Ye=Sl.findIndex(et=>et.id===ae)*H.currentTarget.clientWidth;if(Math.abs(H.currentTarget.scrollLeft-Ye)>2)return;w.current=null}const Ae=Math.max(0,Math.min(Sl.length-1,Math.round(H.currentTarget.scrollLeft/H.currentTarget.clientWidth)));z(Sl[Ae].id)},className:L?"min-h-0 flex-1 overflow-auto pb-3":"min-h-0 flex-1 snap-x snap-mandatory overflow-x-auto overflow-y-hidden overscroll-x-contain [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:[L&&s.jsx("div",{"aria-label":"看板列标题",className:"sticky top-0 z-10 grid min-w-[1000px] grid-cols-4 gap-4 border-b border-border/15 bg-[var(--chrome-bg)] pb-2",children:Sl.map(H=>{const ae=H.icon;return s.jsxs("h4",{className:`flex items-center gap-2 px-3 py-2 text-[13px] font-medium ${H.id==="attention"?"text-primary":"text-muted-foreground"}`,children:[s.jsx(ae,{size:15}),H.label,s.jsx("span",{className:"ml-auto tabular-nums text-xs",children:ue.filter(Ae=>We(Ae)===H.id).length})]},H.id)})}),s.jsx("div",{className:L?"grid min-h-full min-w-[1000px] grid-cols-4 items-start gap-4 pt-2":"flex h-full",children:Sl.map(H=>{const ae=ue.filter(Ae=>We(Ae)===H.id).sort((Ae,Ye)=>Ye.updatedAt-Ae.updatedAt);return s.jsx("section",{"aria-label":`${H.label}任务`,"aria-hidden":!L&&B!==H.id?!0:void 0,ref:Ae=>{Ae&&(Ae.inert=!L&&B!==H.id)},style:L?void 0:{width:"100%"},className:L?"min-w-0 px-1":"h-full min-w-0 shrink-0 snap-start snap-always overflow-y-auto overscroll-y-contain px-1 pb-3 pt-2",children:s.jsxs("div",{className:"space-y-2",children:[ae.map(Ae=>{const Ye=oe.get(Ae.id),et=Ye.attention??Ae,St=et.attempts.find(tt=>tt.id===et.activeAttemptId),Gt=et.decisions.find(tt=>tt.status==="pending"),Qt=Kc(et),wt=G6(et,Ye.children),zt=Jf(et),Vt=zt[0],Kt=zt.find(tt=>tt.source==="system"),Ot=zt.find(tt=>tt.source==="unknown"),It=Kt?.content,xe=H.id==="attention",Ve=Gt?"回答问题":Ot?"查看详情核对记录":Vt?.source==="member"&&Kt?"查看条件与异常处理":Vt?.source==="member"?"查看阻塞并补充条件":It?"查看原因与处理":Qt==="等待你验收"?"查看结果并验收":Qt==="需要你确认方案"?"查看并确认方案":"查看任务并处理",ht=et.artifacts.filter(tt=>tt.kind==="result"&&tt.attemptId===et.activeAttemptId).at(-1),q=et.events.filter(tt=>tt.kind==="revise"&&tt.source==="user"&&tt.attemptId===et.activeAttemptId&&(!ht||tt.createdAt>=ht.createdAt)).at(-1),ut=Gt?Gt.question||"成员提出了一个问题,打开后可查看并回答。":Vt?.summary||q?.content||ht?.summary||(St?.report?.content?W6(St.report.content).summary:St?.report?.summary||""),qt=e.find(tt=>tt.id===Ae.parentTaskId);return s.jsxs("article",{"aria-label":Ae.title,className:`overflow-hidden rounded-xl border bg-surface text-left shadow-sm ${t===Ae.id?"border-primary/60":It?"border-destructive/35":"border-border/20"}`,children:[s.jsxs("button",{type:"button","data-task-id":Ae.id,"aria-pressed":t===Ae.id,className:"block w-full rounded-xl p-4 text-left transition hover:bg-surface-2/40 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary",onClick:()=>r(et.id),children:[qt&&s.jsx("span",{className:"mb-2 block truncate text-[10px] text-muted-foreground",children:qt.title}),s.jsx("span",{title:Ae.title,className:"block line-clamp-3 break-words text-sm font-medium leading-6 text-foreground",children:Ae.title}),s.jsxs("span",{className:`mt-3 flex items-center gap-1.5 text-xs ${It&&Vt?.source!=="member"?"text-destructive":xe?"text-primary":"text-muted-foreground"}`,children:[It&&Vt?.source!=="member"&&s.jsx(P1,{size:13,className:"shrink-0"}),wt]}),Ye.attention&&s.jsxs("span",{className:"mt-2 block truncate text-[11px] text-muted-foreground",children:["来自执行任务:",Ye.attention.title]}),Ye.attention&&Ye.attentionCount>1&&s.jsxs("span",{className:"mt-1 block text-[11px] text-primary",children:["共 ",Ye.attentionCount," 项执行需要你处理"]}),ut&&s.jsx("span",{className:"mt-2 line-clamp-3 break-words text-xs leading-5 text-foreground/80",children:ut}),Kt&&Vt?.source==="member"&&s.jsxs("span",{className:"mt-2 block line-clamp-2 break-words text-xs leading-5 text-destructive",children:[Kt.label,":",Kt.summary]}),Ot&&s.jsxs("span",{className:"mt-2 block line-clamp-2 break-words text-xs leading-5 text-muted-foreground",children:[Ot.label,":",Ot.summary]}),xe&&s.jsxs("span",{className:`mt-4 flex min-h-9 items-center justify-between rounded-lg px-2.5 text-xs font-medium ${It?"bg-destructive/10 text-destructive":"bg-primary/10 text-primary"}`,children:[Ve,s.jsx($m,{size:14})]}),!xe&&(Ae.status==="accepted"||Ae.artifacts.some(tt=>tt.kind==="result"&&tt.attemptId===Ae.activeAttemptId))&&s.jsxs("span",{className:"mt-3 flex min-h-9 items-center justify-between text-xs font-medium text-primary",children:[q?"查看跟进":"查看结果",s.jsx($m,{size:14})]})]}),s.jsx(AO,{task:Ae,children:Ye.children,onSelect:r}),s.jsxs("div",{className:"mx-4 border-t border-border/10 py-3 text-[11px] text-muted-foreground",children:[s.jsxs("span",{className:"block truncate",children:[Ye.attention?"待处理任务负责人:":Ae.workflow?.kind==="goal"?"协调者:":"负责人:",St?n(et,St.assignee):et.scheduledAssignee?n(et,et.scheduledAssignee):"未分派"]}),s.jsx(Df,{task:et,now:v,compact:!0})]})]},Ae.id)}),!ae.length&&s.jsx("p",{className:"px-2 py-3 text-xs leading-6 text-muted-foreground/70",children:Z||$!=="all"?"没有匹配的任务":e.length?"暂无任务":H.hint})]})},H.id)})})]})]})}const Rl=hc((e,t)=>({views:{},details:{},ensureDetail:(r,n)=>{const a=t().details[r];return a||(e(c=>({details:{...c.details,[r]:n}})),n)},updateDetail:(r,n,a)=>e(c=>{const l=c.details[r];if(!l)return c;const d=typeof a=="function"?a(l[n]):a;return Object.is(l[n],d)?c:{details:{...c.details,[r]:{...l,[n]:d}}}}),ensure:(r,n)=>{const a=t().views[r];return a||(e(c=>({views:{...c.views,[r]:n}})),n)},update:(r,n,a)=>e(c=>{const l=c.views[r];if(!l)return c;const d=typeof a=="function"?a(l[n]):a;return Object.is(l[n],d)?c:{views:{...c.views,[r]:{...l,[n]:d}}}})}));function Eh(e,t){return r=>Rl.getState().update(e,t,r)}function Sm(e,t){return r=>Rl.getState().updateDetail(e,t,r)}const SO=b.lazy(()=>Oc(()=>Promise.resolve().then(()=>hO),void 0).then(e=>({default:e.DirectoryPickerDialog}))),CO=b.lazy(()=>Oc(()=>import("./CollaborationTaskContent-WQ5CC-0d.js"),__vite__mapDeps([6,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17]))),ca="inline-flex min-h-11 items-center justify-center gap-2 rounded-lg px-3 text-[13px] transition disabled:cursor-not-allowed disabled:opacity-40 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary",Ps="w-full min-h-11 rounded-lg border border-border/30 bg-surface-2 px-3 py-2 text-sm text-foreground outline-none focus:border-primary",cl=`${ca} bg-primary text-primary-foreground`,ai=`${ca} bg-surface-2 text-foreground hover:bg-surface-2/80`,_O={created:"创建任务",assigned:"分派",report:"成员报告",respond:"答复",question:"提出问题",answer:"回答问题","submit-plan":"提交方案",review:"提交评审","request-review":"请求独立评审","approve-plan":"用户确认方案",accepted:"用户验收",revise:"要求修改",comment:"补充说明",coordinator:"协调者变更",close:"关闭",reopen:"重新打开",scheduled:"等待自动分派",coordinate:"协调说明","child-update":"子任务更新","review-passed":"独立评审通过","review-blocked":"评审受阻","automation-blocked":"自动安排受阻",pause:"暂停安排",resume:"继续安排",retry:"请求重新检查"},Ou=e=>`${e.serviceId}:${e.sessionId}`,Sa=e=>new Date(e).toLocaleString([],{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit"});function go(e,t){try{const r=JSON.parse(localStorage.getItem(e)??"null");return r===null||t!==null&&(typeof r!=typeof t||Array.isArray(r)!==Array.isArray(t))?t:r}catch{return t}}function Fi(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch{}}const t0={mode:"goal",isolated:!0,title:"",spec:"",constraints:"",acceptance:"",assignee:"",coordinator:"",parent:"",dependencies:[]},_b="__new_coordinator__";function kO(e){const t={...t0,...go(e,t0)};return!t||!Array.isArray(t.dependencies)||t.dependencies.some(r=>typeof r!="string")||Object.keys(t0).some(r=>!["dependencies","isolated"].includes(r)&&typeof t[r]!="string")?t0:{...t,mode:t.mode==="task"?"task":"goal",isolated:t.isolated!==!1}}function V6(e,t){const r=e.workflow?.rootTaskId?t.find(c=>c.id===e.workflow?.rootTaskId):null;if(r?.workflow?.paused)return r;const n=new Set([e.id]);let a=e.parentTaskId;for(;a&&!n.has(a);){n.add(a);const c=t.find(l=>l.id===a);if(!c)break;if(c.workflow?.kind==="goal"&&c.workflow.paused)return c;a=c.parentTaskId}return e.workflow?.paused?e:null}function LO({group:e,sessions:t,active:r,onOpenSession:n,onAttentionChange:a,onManageMembers:c,board:l=!1,boardNavigation:d,boardSettings:p,paneKey:m,agents:x=[],defaultCwd:y,onTeamReady:w}){const v=`termdock:tasks:${location.origin}:${e.id}`,[S,L]=b.useState([]),E=b.useRef(S);E.current=S;const[R,B]=b.useState(null),[z]=b.useState(()=>Rl.getState().ensure(v,{draft:kO(`${v}:draft`),selectedId:go(`${v}:selected`,null),creating:!1,mobileDetail:!1})),{selectedId:O,mobileDetail:$,creating:V,draft:Z}=Rl(re=>re.views[v]??z),le=Eh(v,"selectedId"),be=Eh(v,"mobileDetail"),pe=Eh(v,"creating"),ee=Eh(v,"draft"),[_e,ze]=b.useState(!1),[Y,ce]=b.useState(!1),qe=b.useRef(null),we=b.useRef(null),ye=b.useRef(!1),Le=b.useCallback(re=>{!re&&we.current===document.activeElement&&(ye.current=!0),we.current=re,re&&ye.current&&(ye.current=!1,re.focus())},[]);b.useEffect(()=>{const re=qe.current;if(!re)return;const mt=new ResizeObserver(Mt=>ze(Mt[0].contentRect.width>=(l?1100:760)));return mt.observe(re),()=>mt.disconnect()},[l]);const[Be,ne]=b.useState(!1),[Fe,ke]=b.useState(null),Ee=Ly(),[Pe,Ne]=b.useState(0),[oe,We]=b.useState(null),[nt,gt]=b.useState(!1),[ue,Ze]=b.useState(0),at=re=>Ze(mt=>Math.max(0,mt+re)),[Ie,Ge]=b.useState("");b.useEffect(()=>{if(!Ie)return;const re=setTimeout(()=>Ge(""),5e3);return()=>clearTimeout(re)},[Ie]);const[Ce,H]=b.useState("open"),[ae,Ae]=b.useState(""),Ye=b.useRef(!1),et=b.useRef(!0),St=b.useRef(new Map),Gt=b.useRef(!1),Qt=e.sessionIds.flatMap(re=>{const mt=t.find(Mt=>Mt.sessionId===re);return mt?[mt]:[]}),wt=Qt.map(re=>({...re,name:Iu(re,Qt)})),zt=Z.coordinator===_b,Vt=Z.coordinator||go(`${v}:lead`,""),Kt=wt.find(re=>re.sessionId===Z.coordinator&&re.agent),Ot=!!Z.coordinator&&!zt&&!Kt,It=zt||Ot?"":Kt?.sessionId||wt.find(re=>re.sessionId===Vt&&re.agent)?.sessionId||wt.find(re=>re.agent)?.sessionId||"",xe=wt.filter(re=>re.sessionId!==It&&re.agent).map(re=>re.sessionId),[Ve,ht]=b.useState(!1),[q,ut]=b.useState(!1),[qt,tt]=b.useState(()=>go(`${v}:agent`,"")),[De,nr]=b.useState(()=>go(`${v}:launch-profile`,e.defaultLaunchProfileId??"")),Ke=e.launchProfiles?.find(re=>re.id===De),_t=wt.flatMap(re=>re.agent&&x.some(mt=>mt.slug===re.agent.slug)?[re.agent.slug]:[]),$t=[...new Set(_t)].sort((re,mt)=>_t.filter(Mt=>Mt===mt).length-_t.filter(Mt=>Mt===re).length)[0],yt=x.find(re=>re.slug===Kt?.agent?.slug)?.slug??$t??x[0]?.slug??"",xt=Ke?.agentSlug??(qt||yt),[Rt,Ct]=b.useState(()=>go(`${v}:cwd`,wt[0]?.cwd??y??"")),fr=!wt.find(re=>re.sessionId===It)?.agent||!xe.length,[Yt,Sr]=b.useState(null),pn=!!Z.spec.trim()&&(!!Yt||!Ot&&(!fr||!e.federated&&(!De||!!Ke)&&!!x.find(re=>re.slug===xt)&&!!Rt.trim())),dr=S.find(re=>re.id===O)??null,me=R?.id===O?R:null;b.useEffect(()=>(et.current=!0,()=>{et.current=!1}),[]),b.useEffect(()=>{Fi(`${v}:draft`,Z)},[v,Z]),b.useEffect(()=>{Fi(`${v}:selected`,O)},[v,O]),b.useEffect(()=>{const re=Mt=>{const rr=Mt.detail;rr?.groupId===e.id&&(Fi(`${v}:open-task`,null),le(rr.taskId),be(!0),pe(!1),H("all"),Gr())};window.addEventListener("open-collaboration-task",re);const mt=go(`${v}:open-task`,null);return mt&&(le(mt),be(!0),H("all"),Fi(`${v}:open-task`,null)),()=>window.removeEventListener("open-collaboration-task",re)},[e.id]),b.useEffect(()=>{if(!r||!dr||R?.id===dr.id&&R.revision===dr.revision)return;let re=!1;return P8(dr.id).then(mt=>{re||(B(mt.task),ke(null))}).catch(mt=>{re||ke(mt instanceof Error?mt.message:"任务详情加载失败")}),()=>{re=!0}},[r,dr?.id,dr?.revision,R?.id,R?.revision,Pe]);const Gr=async()=>{if(!Gt.current){Gt.current=!0;try{const re=await Sy(e.id);et.current&&(L(re.tasks),ne(!0),ke(null),Ne(mt=>mt+1))}catch(re){et.current&&ke(re instanceof Error?re.message:"任务加载失败")}finally{Gt.current=!1}}};b.useEffect(()=>{if(!r)return;Gr();const re=()=>{!document.hidden&&navigator.onLine!==!1&&Gr()},mt=setInterval(re,2500);return document.addEventListener("visibilitychange",re),window.addEventListener(sf,re),window.addEventListener("pageshow",re),()=>{clearInterval(mt),document.removeEventListener("visibilitychange",re),window.removeEventListener(sf,re),window.removeEventListener("pageshow",re)}},[r,e.id]);const ot=re=>{const mt=JSON.stringify(re),Mt=go(`${v}:request`,null);let rr=St.current.get(mt)??(Mt?.fingerprint===mt?Mt.key:void 0);return rr||(rr=crypto.randomUUID(),St.current.set(mt,rr)),Fi(`${v}:request`,{fingerprint:mt,key:rr}),rr},pt=re=>{St.current.delete(JSON.stringify(re)),Fi(`${v}:request`,null)},ir=async(re,mt)=>{if(nt||Ye.current)return{ok:!1,error:"已有操作正在提交,请稍候。"};Ye.current=!0,gt(!0),We(null),Ge("");let Mt={...mt,expectedRevision:re.revision};if(["comment","revise"].includes(mt.kind)){const rr=go(`${v}:request`,null);try{const[Ar,Fr]=JSON.parse(rr?.fingerprint??"null"),{expectedRevision:Xt,...Zr}=Fr;Ar===re.id&&JSON.stringify(Zr)===JSON.stringify(mt)&&(Mt=Fr)}catch{}}try{const rr=await $8(re.id,{...Mt,idempotencyKey:ot([re.id,Mt])});if(pt([re.id,Mt]),Lu.getState().refresh(),et.current){const Ar=E.current.find(Jt=>Jt.id===rr.task.id),Fr=Ar&&Ar.revision>rr.task.revision?Ar:rr.task;L(Jt=>Jt.map(Pr=>Pr.id===rr.task.id&&Pr.revision<=rr.task.revision?rr.task:Pr)),B(Jt=>Jt?.id===rr.task.id&&Jt.revision>rr.task.revision?Jt:rr.task);const Xt=V6(Fr,E.current),Zr=`${mt.kind==="answer"?"回答已保存":"方案确认已保存"},${Xt?Xt.workflow?.kind==="goal"?"目标仍暂停;恢复目标后才能投递。":"任务仍暂停;继续安排后才能投递。":"投递状态请查看任务记录。"}`;Ge(["comment","revise"].includes(mt.kind)?"":mt.kind==="retry"?vO(re,rr.task):["answer","approve-plan"].includes(mt.kind)?Zr:mt.kind==="accept"?"已验收此版本结果。":"记录已保存。")}return{ok:!0}}catch(rr){const Ar=rr instanceof Error?rr.message:"操作失败";return Ar.includes("任务已更新")&&pt([re.id,Mt]),et.current&&(We(["comment","revise"].includes(mt.kind)?null:Ar),Gr()),{ok:!1,error:Ar}}finally{Ye.current=!1,et.current&>(!1)}},Mn=async re=>{if(re.preventDefault(),nt||ue>0||(Z.mode==="goal"?!pn:!Z.title.trim()||!Z.spec.trim())||Ye.current)return;Ye.current=!0,gt(!0),We(null);const mt=Z.mode==="goal",Mt={groupId:e.id,title:Z.title.trim()||Z.spec.trim().split(`
|
|
140
140
|
`)[0].slice(0,100),spec:Z.spec,constraints:Z.constraints,acceptance:Z.acceptance,assigneeSessionId:mt?void 0:Z.assignee||void 0,coordinatorSessionId:mt?It:Z.coordinator||void 0,parentTaskId:mt?void 0:Z.parent||void 0,dependsOn:mt?[]:Z.dependencies,managed:mt,isolated:Z.isolated,reviewerSessionIds:mt?xe:void 0};try{if(mt&&(fr||Yt)){ut(!0);const Ar=zt?go(`${v}:team-request`,"")||crypto.randomUUID():void 0;Ar&&Fi(`${v}:team-request`,Ar);const Fr=Yt??await O8(e.id,{agentSlug:xt,...De?{launchProfileId:De}:e.launchProfiles?.length?{launchProfileId:""}:{},cwd:Rt.trim(),...zt?{coordinatorSessionId:null,coordinatorCreationKey:Ar}:It?{coordinatorSessionId:It}:{}});ut(!1),Sr(Fr),Mt.coordinatorSessionId=Fr.coordinatorSessionId,Mt.reviewerSessionIds=Fr.reviewerSessionIds,Fi(`${v}:agent`,qt),Fi(`${v}:cwd`,Rt.trim()),Fi(`${v}:launch-profile`,De)}const{task:rr}=await F8({...Mt,idempotencyKey:ot(Mt)});pt(Mt),et.current&&(L(Ar=>[rr,...Ar.filter(Fr=>Fr.id!==rr.id)]),le(rr.id),be(!0),B(rr),mt&&Fi(`${v}:lead`,Mt.coordinatorSessionId),Fi(`${v}:team-request`,null),Sr(null),w?.(),ee(t0),pe(!1),H("open"),Ae(""),Ge(mt?"目标已提交,协调者收到后开始拆分与分派。后续评审和依赖由服务接续。":"任务已保存。分派后由服务端持续投递。"))}catch(rr){et.current&&We(rr instanceof Error?rr.message:"创建失败")}finally{Ye.current=!1,et.current&&(gt(!1),ut(!1))}},Xr=(re,mt)=>{if(!mt)return"用户";const Mt=re.memberSessions[Ou(mt)];return wt.find(rr=>rr.sessionId===Mt)?.name??t.find(rr=>rr.sessionId===Mt)?.name??"暂不可用的成员"},je=S.filter(re=>(Ce==="all"?!0:Ce==="archive"?re.status!=="open":re.status==="open")&&(Ce==="all"||Ce==="attention"||re.workflow?.kind!=="step")&&(Ce!=="attention"||Ui(re))&&(!ae.trim()||`${re.title} ${re.spec} ${re.attempts.map(mt=>Xr(re,mt.assignee)).join(" ")}`.toLowerCase().includes(ae.trim().toLowerCase()))),st=S.filter(Ui).length;b.useEffect(()=>{a?.(st)},[st,a]);const bt=!!dr&&(l?$:_e||$),Br=()=>{pe(!1),requestAnimationFrame(()=>we.current?.focus())},Vr=re=>{Rl.getState().updateDetail(`${v}:${re}`,"view","overview"),le(re),be(!0),Ge("")},Cr=S.filter(Ui).filter(re=>!ae.trim()||`${re.title} ${re.spec} ${re.attempts.map(mt=>Xr(re,mt.assignee)).join(" ")}`.toLowerCase().includes(ae.trim().toLowerCase())),qr=(re,mt=!1)=>{const Mt=re.attempts.find(Jt=>Jt.id===re.activeAttemptId),rr=re.children?.filter(Jt=>Jt.status==="accepted").length??0,Ar=re.children?.filter(Jt=>Jt.status!=="closed").length??0,Fr=Jf(re),Xt=Fr.length>1?Fr.find(Jt=>Jt.source!=="member"):null,Zr=(mt?re.decisions.find(Jt=>Jt.status==="pending")?.question:"")||Fr[0]?.summary||Mt?.report?.summary||Mt?.report?.content;return s.jsxs("button",{type:"button","aria-pressed":O===re.id,className:`group flex min-h-11 w-full items-start gap-3 rounded-xl p-3 text-left transition focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary ${O===re.id?"bg-surface-2":"hover:bg-surface-2/70"}`,onClick:()=>Vr(re.id),children:[s.jsx("span",{className:`mt-0.5 shrink-0 ${mt||re.status==="accepted"?"text-primary":"text-muted-foreground"}`,children:mt?s.jsx(Xu,{size:16}):re.status==="accepted"?s.jsx(zu,{size:16}):s.jsx(Hu,{size:16})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block break-words text-sm font-medium leading-5 text-foreground",children:re.title}),s.jsx("span",{className:`mt-1 block text-xs leading-5 ${mt?"text-primary":"text-muted-foreground"}`,children:Kc(re)}),Zr&&s.jsx("span",{className:"mt-1 block line-clamp-2 break-words text-xs leading-5 text-muted-foreground",children:Zr}),Xt&&s.jsxs("span",{className:`mt-1 block line-clamp-2 break-words text-xs leading-5 ${Xt.source==="system"?"text-destructive":"text-muted-foreground"}`,children:[Xt.label,":",Xt.summary]}),Ar>0&&s.jsxs("span",{className:"mt-2 flex items-center gap-2 text-[11px] text-muted-foreground",children:[s.jsx("span",{className:"flex gap-1","aria-hidden":"true",children:(re.children??[]).filter(Jt=>Jt.status!=="closed").slice(0,8).map(Jt=>s.jsx("span",{className:`h-1.5 w-3 rounded-full ${Jt.status==="accepted"?"bg-primary":"bg-border/30"}`},Jt.id))}),rr,"/",Ar," 子任务已验收"]}),s.jsxs("span",{className:"mt-2 block text-[11px] text-muted-foreground",children:[s.jsx("span",{className:"block truncate",children:Mt?Xr(re,Mt.assignee):"尚未分派"}),s.jsx(Df,{task:re})]})]}),s.jsx(Ks,{size:14,className:"mt-1 shrink-0 text-muted-foreground/60"})]},re.id)},mn=[],on=new Set([O]);let zr=dr?.parentTaskId;for(;zr&&!on.has(zr);){on.add(zr);const re=S.find(mt=>mt.id===zr);if(!re)break;mn.unshift(re),zr=re.parentTaskId}const un=()=>{const re=Array.from(qe.current?.querySelectorAll("button[data-task-id]")??[]).find(mt=>mt.dataset.taskId===O);be(!1),requestAnimationFrame(()=>{re&&!re.closest("[hidden]")?re.focus():we.current?.focus()})},Er=V||!l&&Be&&S.length===0;return s.jsxs("section",{ref:qe,"aria-label":"协作任务",className:l?"relative flex h-full min-h-0 min-w-0 flex-col gap-2":"space-y-5",children:[l&&(Er||!Be)&&d&&s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border/15 pb-2",children:[d,s.jsx("div",{className:"ml-auto",children:p})]}),(oe||Fe&&Ee==="ready"&&!af(Fe))&&s.jsxs("div",{role:"alert",className:"flex items-center gap-2 rounded-lg bg-destructive/10 px-3 py-2 text-xs text-destructive",children:[s.jsxs("span",{className:"min-w-0 flex-1 break-words",children:[oe||Fe,!oe&&Be?" · 显示最近保存的记录":""]}),s.jsxs("button",{type:"button",className:ca,onClick:()=>oe?We(null):void Gr(),children:[s.jsx(bn,{size:14}),oe?"关闭提示":"重试"]})]}),Fe&&af(Fe)&&!l&&s.jsx("p",{role:"status",className:"text-xs text-muted-foreground",children:"正在恢复任务同步,现有记录和草稿已保留"}),Ie&&s.jsx("p",{role:"status",className:"rounded-lg bg-primary/10 px-3 py-2 text-xs leading-5 text-primary",children:Ie}),Er?s.jsxs("form",{onSubmit:re=>{Mn(re)},className:`mx-auto w-full max-w-xl space-y-4 ${l?"overflow-auto px-1 py-5":""}`,onKeyDown:re=>{re.key==="Escape"&&V&&!re.defaultPrevented&&!re.nativeEvent.isComposing&&j1(re.currentTarget)&&(re.preventDefault(),re.stopPropagation(),nt||Br())},children:[s.jsxs("header",{className:"flex items-start gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("h3",{className:"text-lg font-semibold text-foreground",children:Z.mode==="goal"?"一起完成什么?":"新建手动任务"}),s.jsx("p",{className:"mt-1 text-xs leading-5 text-muted-foreground",children:Z.mode==="goal"?"交给协调者拆分,你在这里看交付、回答问题。":"选择负责人,保留分派和验收记录。"})]}),(S.length>0||l)&&s.jsx("button",{type:"button","aria-label":"取消创建,保留草稿",className:`${ca} shrink-0 px-2 text-muted-foreground hover:bg-surface-2`,disabled:nt,onClick:Br,children:s.jsx(In,{size:16})})]}),Z.mode==="task"&&s.jsx(mo,{label:"任务标题",children:s.jsx("input",{className:Ps,required:!0,maxLength:200,value:Z.title,onChange:re=>ee(mt=>({...mt,title:re.target.value})),placeholder:"要完成什么?"})}),s.jsx(Jh,{paneKey:m,inputKey:`${v}:spec`,active:r&&Er,label:Z.mode==="goal"?"协作目标":"目标与交付要求",className:`${Ps} ${fr&&Z.mode==="goal"?"min-h-24":"min-h-32"} resize-y text-sm leading-6`,autoFocus:V,required:!0,disabled:nt,value:Z.spec,onUploadChange:at,onChange:re=>ee(mt=>({...mt,spec:typeof re=="function"?re(mt.spec):re})),placeholder:"例如:完善附件预览体验,交付实现和评审结果,保留现有快捷键。"}),Z.mode==="goal"&&Yt&&s.jsxs("section",{role:"status","aria-label":"目标提交阶段",className:"space-y-2 rounded-lg bg-primary/10 px-3 py-2 text-xs leading-5",children:[s.jsx("p",{className:"text-primary",children:"成员已准备,目标尚未提交。重试会复用这些成员。"}),s.jsx("p",{className:"text-muted-foreground",children:"Agent 和工作目录已用于准备成员,因此暂时锁定;目标正文仍可修改。"}),c&&s.jsx("button",{type:"button",className:ai,disabled:nt,onClick:()=>{w?.(),c()},children:"查看已准备的成员"})]}),Z.mode==="goal"&&s.jsxs(mo,{label:"协调者",children:[s.jsxs("select",{"aria-label":"协调者",className:Ps,disabled:nt||!!Yt,value:Z.coordinator,onChange:re=>{Fi(`${v}:team-request`,null),ee(mt=>({...mt,coordinator:re.target.value}))},children:[s.jsx("option",{value:"",children:"自动选择(优先复用组内 Agent)"}),s.jsx("option",{value:_b,disabled:!!e.federated,children:"新建协调者"}),Ot&&s.jsx("option",{value:Z.coordinator,disabled:!0,children:"原协调者已不可用,请重新选择"}),wt.map(re=>s.jsxs("option",{value:re.sessionId,disabled:!re.agent,children:[re.name,re.agent?` · ${re.agent.displayName}`:"(需要启动 Agent)"]},re.sessionId))]}),Ot&&!Yt&&s.jsx("p",{role:"alert",className:"text-xs text-destructive",children:"所选协调者已离组或未运行 Agent,请重新选择。"})]}),Z.mode==="goal"&&(fr||Yt)?s.jsxs("fieldset",{disabled:nt||!!Yt,className:"space-y-3",children:[s.jsx("legend",{className:"mb-2 text-xs text-muted-foreground",children:Yt?"已用于准备成员的配置":"首次开始时配置 Agent"}),(!!e.launchProfiles?.length||!!De)&&s.jsxs(mo,{label:"启动方案",children:[s.jsxs("select",{"aria-label":"协作启动方案",className:Ps,value:De,onChange:re=>nr(re.target.value),children:[s.jsx("option",{value:"",children:"Agent 默认命令"}),e.launchProfiles?.map(re=>s.jsxs("option",{value:re.id,children:[re.name," · ",x.find(mt=>mt.slug===re.agentSlug)?.displayName??re.agentSlug]},re.id))]}),Ke&&s.jsxs("details",{className:"text-xs leading-5 text-muted-foreground",children:[s.jsx("summary",{className:"min-h-11 cursor-pointer py-2",children:s.jsx("span",{className:"line-clamp-2 break-words",children:Ke.notes||"查看启动命令与使用备注"})}),s.jsx("p",{"aria-label":"完整使用备注",className:"whitespace-pre-wrap break-words",children:Ke.notes}),s.jsx("code",{className:"mt-1 block break-all",children:Ke.command})]}),De&&!Ke&&s.jsx("p",{role:"alert",className:"text-xs text-destructive",children:"原方案已删除,请重新选择。"})]}),!Ke&&s.jsx(mo,{label:"Agent",children:s.jsxs("select",{"aria-label":"协作 Agent",className:Ps,disabled:!!Ke,value:xt,onChange:re=>tt(re.target.value),children:[s.jsx("option",{value:"",disabled:!0,children:"选择已安装的 Agent"}),x.map(re=>s.jsx("option",{value:re.slug,children:re.displayName},re.slug))]})}),s.jsxs(mo,{label:"工作目录",children:[s.jsxs("div",{className:"flex gap-2",children:[s.jsx("input",{"aria-label":"工作目录",className:`${Ps} min-w-0 flex-1`,value:Rt,onChange:re=>Ct(re.target.value),placeholder:"选择项目所在的目录"}),s.jsx("button",{type:"button",className:ai,onClick:()=>ht(!0),children:"浏览目录"})]}),Ve&&s.jsx(b.Suspense,{fallback:s.jsx("p",{className:"text-xs",children:"正在打开目录…"}),children:s.jsx(SO,{open:!0,initialPath:Rt.trim()||y||"/",title:"选择协作项目目录",onCancel:()=>ht(!1),onConfirm:re=>{Ct(re),ht(!1)}})})]}),!Yt&&s.jsx("p",{className:"text-xs leading-5 text-muted-foreground",children:zt?"开始时新建协调者,并补齐执行/评审成员。":"保留所选协调者,开始时补齐执行/评审成员;自动选择会优先复用组内 Agent。"}),e.federated&&s.jsxs("p",{role:"alert",className:"text-xs text-muted-foreground",children:["跨服务组请从成员设置添加 Agent。",c&&s.jsx("button",{type:"button",className:ai,onClick:c,children:"管理成员"})]}),!x.length&&s.jsxs("p",{role:"alert",className:"text-xs text-muted-foreground",children:["尚未检测到可启动的 Agent。安装后刷新,或从成员设置复用现有 Agent。",c&&s.jsx("button",{type:"button",className:ai,onClick:c,children:"管理成员"})]})]}):Z.mode==="task"&&s.jsx(mo,{label:"分派给",children:s.jsxs("select",{className:Ps,value:Z.assignee,onChange:re=>ee(mt=>({...mt,assignee:re.target.value})),children:[s.jsx("option",{value:"",children:"先保存,稍后分派"}),wt.map(re=>s.jsx("option",{value:re.sessionId,children:re.name},re.sessionId))]})}),s.jsxs("details",{className:"border-y border-border/15",children:[s.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center gap-2 text-xs text-muted-foreground",children:["验收标准与更多设置",(Z.acceptance||Z.constraints)&&s.jsx("span",{className:"text-primary",children:"已补充"})]}),s.jsxs("div",{className:"space-y-3 pb-4",children:[s.jsx(mo,{label:"验收标准(选填)",children:s.jsx("textarea",{className:`${Ps} min-h-20 resize-y`,value:Z.acceptance,onChange:re=>ee(mt=>({...mt,acceptance:re.target.value})),placeholder:"什么结果满足要求?"})}),s.jsx(mo,{label:"约束(选填)",children:s.jsx("textarea",{className:`${Ps} min-h-20 resize-y`,value:Z.constraints,onChange:re=>ee(mt=>({...mt,constraints:re.target.value})),placeholder:"必须保留什么?哪些操作需要先问你?"})}),Z.mode==="goal"?s.jsxs("label",{className:"flex min-h-11 items-start gap-2 text-xs leading-5 text-muted-foreground",children:[s.jsx("input",{type:"checkbox",className:"mt-1",checked:Z.isolated,onChange:re=>ee(mt=>({...mt,isolated:re.target.checked}))}),s.jsxs("span",{children:["代码任务使用独立目录",s.jsx("br",{}),s.jsx("span",{className:"text-[11px]",children:"协调者自动区分查询与代码任务;查询复用成员会话,只有代码需要目录与集成。"})]})]}):s.jsxs(s.Fragment,{children:[s.jsx(mo,{label:"协调者",children:s.jsxs("select",{className:Ps,value:Z.coordinator,onChange:re=>ee(mt=>({...mt,coordinator:re.target.value})),children:[s.jsx("option",{value:"",children:"由用户协调"}),wt.map(re=>s.jsx("option",{value:re.sessionId,children:re.name},re.sessionId))]})}),s.jsx(mo,{label:"父任务",children:s.jsxs("select",{className:Ps,value:Z.parent,onChange:re=>ee(mt=>({...mt,parent:re.target.value})),children:[s.jsx("option",{value:"",children:"独立任务"}),S.filter(re=>!re.workflow).map(re=>s.jsx("option",{value:re.id,children:re.title},re.id))]})}),s.jsxs("fieldset",{className:"space-y-1",children:[s.jsx("legend",{className:"text-xs text-muted-foreground",children:"需先验收的依赖任务"}),S.filter(re=>re.status!=="closed").map(re=>s.jsxs("label",{className:"flex min-h-11 items-center gap-2 text-xs text-foreground",children:[s.jsx("input",{type:"checkbox",checked:Z.dependencies.includes(re.id),onChange:mt=>ee(Mt=>({...Mt,dependencies:mt.target.checked?[...Mt.dependencies,re.id]:Mt.dependencies.filter(rr=>rr!==re.id)}))}),re.title]},re.id))]})]}),s.jsx("button",{type:"button",className:`${ca} text-muted-foreground hover:bg-surface-2`,onClick:()=>ee(re=>({...re,mode:re.mode==="goal"?"task":"goal"})),children:Z.mode==="goal"?"改为手动分派任务":"改为自动协作目标"})]})]}),s.jsxs("button",{className:`${cl} w-full`,disabled:nt||ue>0||(Z.mode==="goal"?!pn:!Z.title.trim()||!Z.spec.trim()),children:[nt?s.jsx(bn,{size:14,className:"animate-spin"}):s.jsx(i0,{size:14}),nt?q?"正在准备成员…":"提交中…":Z.mode==="goal"?Yt?"重试提交目标":"开始协作":Z.assignee?"创建并分派":"保存任务"]}),s.jsx("p",{className:"text-center text-[11px] leading-5 text-muted-foreground",children:Z.mode==="goal"?"拆分任务 → 执行与独立评审 → 你验收结果":"草稿自动保存,分派后保留投递与回复记录。"})]}):l&&Be?s.jsxs(s.Fragment,{children:[s.jsx("h3",{className:"sr-only",children:"任务看板"}),s.jsxs("div",{className:"flex min-h-0 min-w-0 flex-1 gap-5",children:[s.jsx("div",{hidden:bt,className:`${bt?"hidden":"flex"} min-h-0 min-w-0 flex-1`,children:s.jsx(TO,{navigation:d,settings:p,action:s.jsxs("button",{ref:Le,type:"button",className:cl,disabled:nt,onClick:()=>pe(!0),children:[s.jsx(zs,{size:14}),"新目标"]}),storage:v,tasks:S,selectedId:bt?O:null,name:Xr,onSelect:Vr})}),bt&&s.jsxs("aside",{"aria-label":"任务详情",className:"mx-auto flex min-h-0 min-w-0 w-full max-w-[1040px] flex-col",children:[s.jsx("nav",{"aria-label":"任务位置",className:"mb-2 shrink-0",children:s.jsxs("ol",{className:"flex min-w-0 items-center gap-1 text-xs text-muted-foreground",children:[s.jsx("li",{className:"shrink-0",children:s.jsx("button",{type:"button","aria-label":"返回看板",title:"查看此协作组的任务看板",className:`${ca} px-2 hover:bg-surface-2`,onClick:un,children:"看板"})}),mn.map(re=>s.jsxs("li",{className:"flex min-w-0 flex-1 items-center gap-1 sm:max-w-xs sm:flex-none",children:[s.jsx(Ks,{"aria-hidden":"true",size:12,className:"shrink-0"}),s.jsx("button",{type:"button","aria-label":`查看${re.workflow?.kind==="goal"?"目标":"父任务"}:${re.title}`,title:`查看${re.workflow?.kind==="goal"?"目标":"父任务"}:${re.title}`,className:`${ca} min-w-0 px-2 hover:bg-surface-2`,onClick:()=>Vr(re.id),children:s.jsxs("span",{className:"truncate",children:[re.workflow?.kind==="goal"?"目标":"父任务",":",re.title]})})]},re.id)),s.jsxs("li",{"aria-current":"page",className:"flex shrink-0 items-center gap-1",children:[s.jsx(Ks,{"aria-hidden":"true",size:12}),s.jsx("span",{className:"px-2",children:dr?.parentTaskId?"子任务详情":dr?.workflow?.kind==="goal"?"目标详情":"任务详情"})]})]})}),s.jsx("div",{className:"min-h-0 flex-1",children:me?s.jsx(kb,{reader:!0,paneKey:m,active:r,task:me,tasks:S,members:wt,busy:nt,name:re=>Xr(me,re),act:re=>ir(me,re),storage:v,onSelectTask:Vr,onOpenSession:async re=>{const mt=t.find(Mt=>Mt.sessionId===me.memberSessions[Ou(re)]);if(!mt){We("成员会话暂不可用,任务历史已保留。");return}try{await n(mt)}catch(Mt){We(Mt instanceof Error?Mt.message:"无法打开终端")}}},me.id):s.jsx("p",{role:"status",className:"py-8 text-center text-xs text-muted-foreground",children:"正在加载任务详情…"})})]})]})]}):!Be&&!S.length?s.jsxs("div",{role:"status",className:"space-y-3 py-8",children:[s.jsx("p",{className:"text-center text-xs text-muted-foreground",children:Fe?"任务暂时无法加载,请重试。":"正在加载目标…"}),!Fe&&[0,1,2].map(re=>s.jsx("div",{className:"h-14 animate-pulse rounded-lg bg-surface-2"},re))]}):s.jsxs(s.Fragment,{children:[(!bt||_e)&&s.jsxs("header",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-base font-semibold text-foreground",children:"协作目标"}),s.jsxs("p",{className:"mt-1 text-[11px] text-muted-foreground",children:[S.filter(re=>re.status==="open"&&re.workflow?.kind!=="step").length," 个进行中 · ",S.filter(re=>re.status==="accepted"&&re.workflow?.kind!=="step").length," 个已验收"]})]}),s.jsxs("button",{ref:Le,type:"button",className:cl,disabled:nt,onClick:()=>pe(!0),children:[s.jsx(zs,{size:14}),"新目标"]})]}),s.jsxs("div",{className:_e&&bt?"grid items-start gap-6 grid-cols-[260px_minmax(0,1fr)]":"",children:[(!bt||_e)&&s.jsxs("div",{className:"min-w-0 space-y-5",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("select",{"aria-label":"任务筛选",className:`${Ps} min-w-0 flex-1 border-transparent bg-transparent`,value:Ce,onChange:re=>H(re.target.value),children:[s.jsx("option",{value:"open",children:"进行中的目标"}),s.jsxs("option",{value:"attention",children:["需要你处理(",st,")"]}),s.jsx("option",{value:"archive",children:"已归档"}),s.jsx("option",{value:"all",children:"全部任务"})]}),s.jsx("button",{type:"button","aria-label":"搜索任务","aria-expanded":Y,className:`${ca} shrink-0 px-3 text-muted-foreground hover:bg-surface-2`,onClick:()=>{ce(re=>!re),Ae("")},children:s.jsx(jl,{size:16})})]}),Y&&s.jsx("input",{"aria-label":"搜索任务或负责人",autoFocus:!0,className:Ps,value:ae,onChange:re=>Ae(re.target.value),placeholder:"搜索目标、内容或负责人"}),Ce==="open"&&Cr.length>0&&s.jsxs("section",{"aria-label":"需要你处理",className:"rounded-xl bg-surface-2/40 p-1",children:[s.jsxs("h4",{className:"flex items-center justify-between px-3 pb-1 pt-3 text-xs font-medium text-primary",children:["需要你处理",s.jsx("span",{className:"rounded-md bg-primary/15 px-2 py-0.5",children:Cr.length})]}),Cr.map(re=>qr(re,!0))]}),(Ce!=="open"||je.some(re=>!Ui(re))||je.length===0)&&s.jsxs("section",{className:"space-y-1",children:[s.jsx("h4",{className:"px-3 text-[11px] font-medium text-muted-foreground",children:Ce==="attention"?"需要你处理":Ce==="archive"?"已归档":Ce==="all"?"全部任务":"当前目标"}),je.filter(re=>Ce!=="open"||!Ui(re)).map(re=>qr(re,Ce==="attention")),!je.length&&s.jsxs("div",{className:"px-3 py-6 text-center text-xs leading-5 text-muted-foreground",children:[ae.trim()?"没有匹配的任务。":Ce==="attention"?"目前没有需要你处理的任务。":Ce==="archive"?"还没有归档任务。":"当前没有进行中的目标。",(Ce!=="all"||ae)&&s.jsx("button",{type:"button",className:`${ca} mt-2 text-primary`,onClick:()=>{H("all"),Ae("")},children:"查看全部任务"})]})]})]}),bt&&s.jsxs("div",{className:"min-w-0",children:[!_e&&s.jsxs("button",{type:"button",className:`${ca} mb-4 -ml-2 text-muted-foreground hover:bg-surface-2`,onClick:()=>be(!1),children:[s.jsx(Iy,{size:14}),"全部目标"]}),me?s.jsx(kb,{paneKey:m,active:r,task:me,tasks:S,members:wt,busy:nt,name:re=>Xr(me,re),act:re=>ir(me,re),storage:v,onSelectTask:Vr,onOpenSession:async re=>{const mt=t.find(Mt=>Mt.sessionId===me.memberSessions[Ou(re)]);if(!mt){We("成员会话暂不可用,任务历史已保留。");return}try{await n(mt)}catch(Mt){We(Mt instanceof Error?Mt.message:"无法打开终端")}}},me.id):s.jsx("p",{role:"status",className:"py-8 text-center text-xs text-muted-foreground",children:"正在加载任务详情…"})]})]})]})]})}function mo({label:e,children:t}){return s.jsxs("label",{className:"block space-y-1.5",children:[s.jsx("span",{className:"text-xs text-muted-foreground",children:e}),t]})}function kb({reader:e=!1,active:t,paneKey:r,task:n,tasks:a,members:c,name:l,busy:d,act:p,storage:m,onOpenSession:x,onSelectTask:y}){const[w,v]=b.useState(""),[S,L]=b.useState(""),[E,R]=b.useState(""),[B,z]=b.useState(!1),[O,$]=b.useState(null),V=b.useRef(!1),Z=b.useRef(!0);b.useEffect(()=>(Z.current=!0,()=>{Z.current=!1}),[]);const le=b.useRef(null),be=b.useRef(null);b.useEffect(()=>{!e&&O&&O.state!=="pending"&&t&&requestAnimationFrame(()=>be.current?.scrollIntoView({block:"nearest"}))},[O]);const pe=b.useRef(null),[ee,_e]=b.useState(0),ze=q=>_e(ut=>Math.max(0,ut+q)),Y=b.useRef(null);b.useEffect(()=>{Y.current?.focus()},[]);const ce=`${m}:${n.id}`,[qe]=b.useState(()=>Rl.getState().ensureDetail(ce,{feedback:go(`${ce}:feedback`,""),answers:go(`${ce}:answers`,{}),view:"overview"})),{feedback:we,answers:ye,view:Le}=Rl(q=>q.details[ce]??qe),Be=Sm(ce,"feedback"),ne=Sm(ce,"answers"),Fe=Sm(ce,"view");b.useEffect(()=>{pe.current&&(pe.current.scrollTop=0)},[Le]),b.useEffect(()=>Fi(`${m}:${n.id}:answers`,ye),[m,n.id,ye]),b.useEffect(()=>Fi(`${m}:${n.id}:feedback`,we),[m,n.id,we]);const ke=n.attempts.find(q=>q.id===n.activeAttemptId),Ee=n.status==="open",Pe=V6(n,a),Ne=n.artifacts.filter(q=>q.kind==="result"&&q.attemptId===n.activeAttemptId).at(-1);b.useEffect(()=>{O?.state==="saved"&&Ne?.id!==O.resultId&&$(null)},[Ne?.id,O]);const oe=n.artifacts.filter(q=>q.kind==="plan"&&q.attemptId===n.activeAttemptId).at(-1),We=n.events.filter(q=>q.kind==="revise"&&q.source==="user"&&q.attemptId===n.activeAttemptId).at(-1),nt=Ne&&n.events.some(q=>q.kind==="revise"&&q.attemptId===n.activeAttemptId&&q.createdAt>=Ne.createdAt),gt=e&&Ee&&!!nt,ue=O?.state==="saved"&&O.kind==="revise"&&O.resultId===Ne?.id,Ze=n.decisions.filter(q=>q.status==="pending"&&q.attemptId===n.activeAttemptId),at=n.dependsOn.some(q=>a.find(ut=>ut.id===q)?.status!=="accepted"),Ie=!n.workflow||n.artifacts.filter(q=>q.kind==="review"&&q.reviewsArtifactId===Ne?.id).at(-1)?.verdict==="pass",Ge=n.children??[],Ce=n.workflow?.kind==="goal"&&Ge.some(q=>!["accepted","closed"].includes(q.status)),H=`任务:${n.title}
|
|
141
141
|
任务 ID:${n.id}
|
|
142
142
|
${n.spec}
|
|
@@ -159,7 +159,7 @@ ${Ze.map(q=>`待回答:${q.question}`).join(`
|
|
|
159
159
|
`))},Gr,me)},[w,e,n,y,pt?.id,me,Gr,Y,wt]),b.useEffect(()=>{const X=dr.current;if(!w||!X)return;const He=Nt=>pe(String(Nt.detail));return X.addEventListener("termdock:file-drop-error",He),()=>X.removeEventListener("termdock:file-drop-error",He)},[w,pt?.id,pe]);const zr=async X=>{const He=pt?.id;pe(null),Xr(Nt=>Nt+1);try{const Nt=await N0("/tmp",X);if(Nt.files.length!==X.length||Nt.files.some(tr=>!tr.path))throw new Error("文件路径准备失败,请重试");const Et=Nt.files.map(tr=>Dc(tr.path)).join(" ")+" ";if(bt.current===He)St(tr=>tr+(tr&&!/\s$/.test(tr)?`
|
|
160
160
|
`:"")+Et);else if(He){const tr=je.current.get(He)??{content:"",targets:null},jr={...tr,content:tr.content+`
|
|
161
161
|
`+Et};je.current.set(He,jr),on({drafts:{[He]:jr}})}}catch(Nt){pe(Nt instanceof Error?Nt.message:"文件上传失败")}finally{Xr(Nt=>Nt-1)}},un=new Set(L.filter(Cm).map(X=>X.sessionId)),Er=Fe.size,re=[...Fe].filter(X=>!un.has(X)),mt=FO(pt,L),Mt=Ee.trim().toLocaleLowerCase(),rr=L.filter(X=>!Mt||[Iu(X,L),X.name,X.serviceLabel??"",X.cwd,km(X.currentTask)].some(He=>He.toLocaleLowerCase().includes(Mt))),Ar=Nb(rr),Fr=Nb(mt),Xt=X=>!Mt&&Ne.has(X),Zr=X=>oe(He=>{const Nt=new Set(He);return Nt.has(X)?Nt.delete(X):Nt.add(X),Nt});b.useEffect(()=>{Qt(!1),Ot.current!==pt?.id&&zt(!1),Ot.current=null,we(!1),Ke(!1),nt(!1),De({}),q(new Set(pt?.sessionIds??[])),xt(pt?.defaultLaunchProfileId??"")},[pt?.id]),b.useEffect(()=>{!_t&&E[0]&&$t(E[0].slug)},[E,_t]),b.useEffect(()=>{at([]),H(null)},[pt?.id]),b.useEffect(()=>{if(!B||!n||w&&!y||!pt){Ge(!1);return}Ge(!0);let X=!1,He=0,Nt=!1;const Et=()=>{if(X||Nt||document.hidden||navigator.onLine===!1)return;Nt=!0;const jr=++He;ox(pt.id).then(cr=>{!X&&jr===He&&(at(cr.messages),H(null))}).catch(cr=>{!X&&jr===He&&H(cr instanceof Error?cr.message:"消息加载失败")}).finally(()=>{Nt=!1,!X&&jr===He&&Ge(!1)})};Et();const tr=window.setInterval(Et,3e3);return document.addEventListener("visibilitychange",Et),window.addEventListener(sf,Et),window.addEventListener("pageshow",Et),()=>{X=!0,window.clearInterval(tr),document.removeEventListener("visibilitychange",Et),window.removeEventListener(sf,Et),window.removeEventListener("pageshow",Et)}},[pt?.id,n,w,y]),b.useEffect(()=>{!B||pt?.id!==B||ot.current||(ot.current=!0,Y==="messages"&&dr.current?.scrollIntoView?.({block:"nearest"}))},[B,pt?.id]);const Jt=async()=>{be("create-group"),pe(null),ee(null);try{if(re.length)throw new Error("所选会话已变化,请先清除不可用选择");const X=await Ml({name:Be,sessionIds:[...Fe]});ne(""),Pe(""),x(X.group.id),await _e(),ee(`“${X.group.name}”已创建。`),r?await r(X.group.id,"messages"):$&&await $(X.group.id)}catch(X){pe(X instanceof Error?X.message:"创建失败")}finally{be(null)}},Pr=pt?.sessionIds.filter(X=>Ae===null||Ae.includes(X))??[],Hr=async()=>{if(!pt||le||Mn||!et.trim()||!Pr.length)return;const X=et,He=pt.id;be("send-message"),pe(null),ee(null);try{const Nt=await U8(pt.id,{fromSessionId:null,toSessionIds:Ae===null?void 0:Pr,kind:"message",content:et});if(bt.current===He){const cr=Cr.current,Cn=cr===X?"":cr.startsWith(X)?cr.slice(X.length).replace(/^\n/,""):cr;St(Cn),on({drafts:{[He]:{content:Cn,targets:Vr.current}}})}else{const cr=je.current.get(He);if(cr){const Cn={...cr,content:cr.content===X?"":cr.content.startsWith(X)?cr.content.slice(X.length).replace(/^\n/,""):cr.content};je.current.set(He,Cn),on({drafts:{[He]:Cn}})}}const Et=await ox(He).catch(()=>null);Et&&bt.current===He&&at(Et.messages);const tr=Nt.deliveries?.filter(cr=>cr.serviceUnavailable).length??0,jr=Nt.deliveries?.filter(cr=>cr.pending>0).length??0;ee(tr>0?`已保存消息;${tr} 个接收成员的服务不可达,尚未送达,等待重连`:jr>0?`已保存消息;${jr} 个成员等待投递确认`:`消息已送达 ${Nt.messages.length} 个会话`)}catch(Nt){pe(Nt instanceof Error?Nt.message:"发送失败")}finally{be(null)}},ps=async()=>{if(!pt)return;be(`delete:${pt.id}`),pe(null),ee(null);const X=pt.name;try{await Ey(pt.id,gt),x(null),nt(!1),await _e(),ee(`“${X}”已删除`)}catch(He){pe(He instanceof Error?He.message:"删除失败")}finally{be(null)}},Mr=async()=>{if(!pt)return;const X=[...ht];be("save-members"),pe(null),ee(null);try{const He=await Ml({id:pt.id,name:pt.name,sessionIds:X,expectedUpdatedAt:ut});x(He.group.id),Qt(!1),await _e(),ee(`“${pt.name}”成员已更新,共 ${X.length} 个会话`)}catch(He){pe(He instanceof Error?He.message:"成员更新失败")}finally{be(null)}},jn=async X=>{if(!pt||!pt.sessionIds.includes(X)){Ve(null);return}const He=L.find(Et=>Et.sessionId===X)?.name??X,Nt=pt.name;be(`remove-member:${X}`),pe(null),ee(null);try{await Ml({id:pt.id,name:Nt,sessionIds:pt.sessionIds.filter(Et=>Et!==X),expectedUpdatedAt:pt.updatedAt}),Ve(null),q(Et=>new Set([...Et].filter(tr=>tr!==X))),De(Et=>Object.fromEntries(Object.entries(Et).filter(([tr])=>tr!==X))),await _e(),ee(`已把“${He}”移出“${Nt}”`)}catch(Et){pe(Et instanceof Error?Et.message:"移出成员失败")}finally{be(null)}},Tr=async X=>{if(!pt)return;const He=tt[X]??"";be(`role:${X}`),pe(null),ee(null);try{await G8(pt.id,X,He.trim()||null),await _e(),ee(He.trim()?"定位已保存,该成员每次收到消息都会看到":"定位已清除")}catch(Nt){pe(Nt instanceof Error?Nt.message:"定位保存失败")}finally{be(null)}},Jr=()=>{xt(pt?.defaultLaunchProfileId??"");const X=L.find(He=>He.sessionId===R)?.cwd??L.find(He=>pt?.sessionIds.includes(He.sessionId))?.cwd??"";Yt(X),Ct(""),pn(""),Ke(!0),Qt(!1)},ln=async()=>{if(!(!pt||!_t||yt&&!pt.launchProfiles?.some(X=>X.id===yt))){be("spawn-agent"),pe(null),ee(null);try{const X=await z8(pt.id,{agentSlug:pt.launchProfiles?.find(He=>He.id===yt)?.agentSlug??_t,...yt||pt.launchProfiles?.length?{launchProfileId:yt}:{},name:Rt.trim()||void 0,cwd:fr.trim()||void 0,task:Sr.trim()||void 0,mode:Z});Ke(!1),await _e(),ee(`“${X.session.name}”已创建并加入“${X.group.name}”`)}catch(X){pe(X instanceof Error?X.message:"Agent Session 创建失败")}finally{be(null)}}},Qr=WO(Ze,L),ks=X=>s.jsxs("label",{className:"flex cursor-pointer items-start gap-3 px-2 py-2.5 transition hover:bg-surface-2",children:[s.jsx("input",{className:"mt-0.5",type:"checkbox",disabled:!Cm(X),checked:Fe.has(X.sessionId),onChange:()=>ke(He=>{const Nt=new Set(He);return Nt.has(X.sessionId)?Nt.delete(X.sessionId):Nt.add(X.sessionId),Nt})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"truncate text-[12px] text-foreground",children:Iu(X,L)}),s.jsx(_m,{session:X}),s.jsx("span",{className:"shrink-0 text-[9px] text-muted-foreground",children:rf(X)})]}),s.jsx("span",{className:"mt-0.5 block truncate text-[10px] text-muted-foreground",children:X.currentTask?`${km(X.currentTask)} · ${X.cwd}`:X.cwd||X.capability||"终端会话"})]})]},X.sessionId),Dr=X=>{const He=tt[X.sessionId]??"",Nt=pt?.roles?.[X.sessionId]??"";return s.jsxs("div",{className:"px-2 py-2 transition hover:bg-surface-2",children:[s.jsxs("label",{className:"flex cursor-pointer items-center gap-3",children:[s.jsx("input",{type:"checkbox",disabled:!pt?.sessionIds.includes(X.sessionId)&&!Cm(X),checked:ht.has(X.sessionId),onChange:()=>q(Et=>{const tr=new Set(Et);return tr.has(X.sessionId)?tr.delete(X.sessionId):tr.add(X.sessionId),tr})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block truncate text-[11px] text-foreground",children:X.name}),s.jsx(_m,{session:X}),s.jsxs("span",{className:"block truncate text-[9px] text-muted-foreground",children:[rf(X)," · ",X.cwd]})]})]}),s.jsxs("div",{className:"mt-2 flex items-center gap-2 pl-7",children:[s.jsx("span",{className:"shrink-0 text-[9px] text-muted-foreground",children:"定位"}),s.jsx("input",{"aria-label":`${X.name} 的定位`,className:`${$s} min-h-8 py-1 text-[10px]`,value:He,maxLength:200,placeholder:"成员收到的定位;清空后保存可移除",onChange:Et=>De(tr=>({...tr,[X.sessionId]:Et.target.value}))}),s.jsx("button",{"aria-label":`保存 ${X.name} 的定位`,title:He.trim()===Nt?"定位未变化":"保存此成员的定位",disabled:le!==null||He.trim()===Nt,className:`${vr} min-h-8 shrink-0 px-2 text-muted-foreground`,onClick:()=>{Tr(X.sessionId)},children:le===`role:${X.sessionId}`?s.jsx(bn,{size:12,className:"animate-spin"}):s.jsx(pi,{size:12})})]})]},X.sessionId)},en=s.jsx("nav",{"aria-label":"协作工作区",className:"flex shrink-0 items-center gap-1",children:[["tasks",e||ze?"看板":"目标"],["messages","成员与消息"]].map(([X,He])=>s.jsxs("button",{type:"button","aria-label":He,"aria-pressed":Y===X,className:`${vr} min-h-11 ${Y===X?"bg-surface-2 text-foreground":"text-muted-foreground hover:bg-surface-2"}`,onClick:Nt=>{if(ze&&X==="tasks"){$?.(pt.id).catch(jr=>pe(jr instanceof Error?jr.message:"无法打开看板"));return}const Et=Nt.currentTarget.closest("[data-collaboration-views]"),tr=Nt.currentTarget;ce(X),requestAnimationFrame(()=>{const jr=document.activeElement;jr!==tr&&jr!==document.body&&jr?.isConnected&&!jr.closest("[hidden]")||Array.from(Et?.querySelectorAll('nav[aria-label="协作工作区"] button')??[]).find(cr=>cr.getAttribute("aria-pressed")==="true"&&!cr.closest("[hidden]"))?.focus()})},children:[e&&X==="messages"?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"sm:hidden",children:"成员"}),s.jsx("span",{className:"hidden sm:inline",children:He})]}):He,!e&&X==="tasks"&&ye>0&&s.jsxs("span",{className:"rounded bg-primary/15 px-1.5 text-[11px] text-primary",children:[ye," 待处理"]})]},X))}),xn=s.jsxs("button",{type:"button","aria-label":"组设置",title:"组设置","aria-expanded":wt,className:`${vr} min-h-11 shrink-0 text-muted-foreground hover:bg-surface-2`,onClick:X=>{Kt.current=X.currentTarget,zt(He=>!He),pe(null),ee(null)},children:[s.jsx(ju,{size:14}),e&&s.jsx("span",{className:"sm:sr-only",children:"组设置"})]});return s.jsxs("div",{ref:Vt,className:e?"flex min-h-0 flex-1 flex-col gap-3":ze?void 0:"space-y-3",children:[Ce&&ae==="ready"&&!af(Ce)&&s.jsxs("p",{role:"alert",className:"rounded-lg bg-destructive/10 px-3 py-2 text-[11px] text-destructive",children:["消息同步暂时失败,正在自动重试:",Ce]}),Ce&&af(Ce)&&!e&&s.jsx("p",{role:"status",className:"text-[11px] text-muted-foreground",children:"正在恢复消息同步,现有记录已保留"}),s.jsxs("div",{className:e?wt?"min-h-0 flex-1 overflow-auto":"contents":void 0,children:[!B&&m!=="new"&&S.length>0&&s.jsx("div",{hidden:wt,children:s.jsx(xO,{groups:S,sessions:L,busy:le!==null,onOpen:(X,He)=>{r?.(X,He)},onSettings:(X,He)=>{Ot.current=X,x(X),Kt.current=He,zt(!0),pe(null),ee(null)},onCreate:()=>{x("new"),nt(!1),ee(null)}})}),!B&&(m==="new"||wt)&&S.length>0&&s.jsx("button",{type:"button",className:`${vr} min-h-11 text-muted-foreground hover:bg-surface-2`,onClick:()=>{wt?It():x(S[0].id)},children:"返回协作组"}),wt&&pt&&s.jsx(BO,{group:pt,agents:E,activeSessionId:R,sessions:L,busy:le,setBusy:be,setError:pe,setNotice:ee,refresh:_e,onClose:It},pt.id),!B&&v!=="loaded"&&!S.length&&s.jsx("p",{role:"status",className:"py-5 text-xs text-muted-foreground",children:v==="loading"?"正在加载协作组与会话…":"会话加载失败,请重试"}),!pt&&(B||m==="new"||v==="loaded")&&s.jsxs("section",{className:"border-y border-border/15 py-4",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("h4",{className:"text-[12px] font-medium text-foreground",children:"创建协作组"}),s.jsx("p",{className:"mt-1 text-[10px] leading-relaxed text-muted-foreground",children:"先给协作组命名。成员可以现在选择,也可以以后添加;消息和看板都能独立使用。"})]}),s.jsxs("span",{className:`shrink-0 text-[10px] ${Er>=2?"text-primary":"text-muted-foreground"}`,children:["已选 ",Er," 个"]})]}),s.jsxs("label",{className:"mt-4 block space-y-1 text-[10px] text-muted-foreground",children:["协作组名称",s.jsx("input",{className:$s,value:Be,onChange:X=>ne(X.target.value),placeholder:"例如:发布准备"})]}),s.jsxs("details",{className:"mt-3",children:[s.jsxs("summary",{className:"min-h-11 cursor-pointer py-3 text-xs text-muted-foreground",children:["复用已有会话(选填) · 已选 ",Er," 个"]}),L.length>5&&s.jsxs("label",{className:"relative mt-3 block",children:[s.jsx("span",{className:"sr-only",children:"筛选会话"}),s.jsx(jl,{size:13,className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),s.jsx("input",{className:`${$s} pl-8`,value:Ee,onChange:X=>Pe(X.target.value),placeholder:"按名称、目录或当前任务筛选"})]}),s.jsxs("div",{className:"mt-3 max-h-64 divide-y divide-border/10 overflow-y-auto border-y border-border/10",children:[Ar.length<=1?rr.map(ks):Ar.map(X=>{const He=Xt(X.key);return s.jsxs("div",{children:[s.jsx(Rb,{label:X.label,count:X.sessions.length,collapsed:He,onToggle:()=>Zr(X.key)}),!He&&s.jsx("div",{className:"divide-y divide-border/10",children:X.sessions.map(ks)})]},X.key)}),L.length===0&&s.jsx("p",{className:"px-3 py-6 text-center text-[11px] text-muted-foreground",children:v==="loading"?"正在加载会话…":v==="error"?"会话加载失败,请重试":"没有现有会话也可以创建,开始目标时会启动 Agent"}),L.length>0&&rr.length===0&&s.jsx("p",{className:"px-3 py-6 text-center text-[11px] text-muted-foreground",children:"没有符合筛选条件的会话"})]})]}),re.length>0&&s.jsxs("div",{role:"alert",className:"mt-2 text-[11px] text-destructive",children:["有 ",re.length," 个所选会话暂不可用。",s.jsx("button",{className:vr,onClick:()=>ke(X=>new Set([...X].filter(He=>un.has(He)))),children:"清除不可用选择"})]}),s.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row sm:items-center",children:[s.jsx("p",{className:`min-w-0 flex-1 text-[10px] ${Er<2?"text-muted-foreground":"text-primary"}`,children:Be.trim()?"创建后进入成员消息,看板可随时使用":"请填写协作组名称"}),s.jsxs("div",{className:"flex justify-end gap-2",children:[S.length>0&&s.jsx("button",{className:`${vr} bg-surface-2 text-foreground`,onClick:()=>x(S[0]?.id??null),children:"取消"}),s.jsxs("button",{disabled:le!==null||!Be.trim()||re.length>0,className:`${vr} bg-primary text-primary-foreground`,onClick:()=>{Jt()},children:[le==="create-group"?s.jsx(bn,{size:13,className:"animate-spin"}):s.jsx(zs,{size:13}),"创建协作组"]})]})]})]})]}),pt&&B&&s.jsxs("div",{"data-collaboration-views":!0,hidden:wt,className:e?`${wt?"hidden":"flex"} min-h-0 flex-1 flex-col gap-3`:ze?void 0:"space-y-3",children:[!ze&&(!e||Y==="messages")&&s.jsxs("div",{className:"flex shrink-0 items-center gap-1 border-b border-border/15 pb-2",children:[en,s.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[e&&Y==="messages"&&s.jsxs("button",{type:"button","aria-label":"放到终端旁",title:V?"在当前终端分屏中使用成员与消息":"先打开一个终端,再嵌入消息面板",disabled:!V||le!==null,className:`${vr} min-h-11 text-muted-foreground hover:bg-surface-2`,onClick:()=>{be("dock-messages"),pe(null),V?.().catch(X=>pe(X instanceof Error?X.message:"消息面板打开失败,草稿已保留")).finally(()=>be(null))},children:[s.jsx(Fc,{size:14}),s.jsx("span",{className:"hidden sm:inline",children:"放到终端旁"})]}),xn]})]}),!ze&&Y==="messages"&&s.jsx("div",{className:"flex gap-1 overflow-x-auto","aria-label":"工作组终端",children:ir.map(X=>s.jsx("button",{type:"button","aria-pressed":X.sessionId===R,title:`${X.name} · ${X.cwd||"终端会话"}`,className:`${vr} min-h-9 shrink-0 ${X.sessionId===R?"bg-primary/15 text-primary":"text-muted-foreground hover:bg-surface-2"}`,onClick:()=>{O(X).catch(He=>pe(He instanceof Error?He.message:"无法打开终端"))},children:Iu(X,ir)},X.sessionId))}),!ze&&s.jsx("div",{hidden:Y!=="tasks",className:e?`${Y==="tasks"?"flex":"hidden"} min-h-0 flex-1 flex-col`:void 0,children:s.jsx(LO,{paneKey:d?Gr:void 0,boardNavigation:e?en:void 0,boardSettings:e?xn:void 0,board:e,group:pt,sessions:L,agents:E,defaultCwd:L.find(X=>X.sessionId===R)?.cwd??void 0,onTeamReady:_e,active:n&&!wt&&Y==="tasks"&&(!w||y),onAttentionChange:Le,onManageMembers:()=>ce("messages"),onOpenSession:O},pt.id)}),s.jsxs("div",{hidden:Y!=="messages",className:e?"min-h-0 flex-1 overflow-auto":void 0,children:[s.jsxs("section",{onFocusCapture:()=>s0(Gr),onPointerDownCapture:()=>s0(Gr),"data-termdock-terminal-dropzone":w?R??"collaboration-composer":void 0,onDragOver:X=>{w&&X.preventDefault()},onDrop:X=>{if(!w)return;const He=Array.from(X.dataTransfer.files);if(!(He.length&&vo()))if(X.preventDefault(),X.stopPropagation(),He.length)zr(He);else{const Nt=X.dataTransfer.getData("text/plain")||X.dataTransfer.getData("text/uri-list");Nt&&St(Et=>Et+(Et?`
|
|
162
|
-
`:"")+Nt)}},ref:dr,className:w?"":"rounded-xl border border-primary/20 bg-primary/5 px-3 py-3",children:[!w&&s.jsxs("h4",{className:"truncate text-[12px] font-medium text-foreground",children:[pt.name," · 发送给成员"]}),s.jsxs("div",{className:w?"space-y-2":"mt-2 space-y-2",children:[ze&&s.jsxs("div",{className:"relative z-20 flex items-center justify-between gap-2",children:[s.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["发送给 ",s.jsx("span",{className:"text-[9px]",children:"· 可多选"})]}),s.jsxs("details",{className:"relative",onKeyDown:X=>{X.key==="Escape"&&(X.currentTarget.removeAttribute("open"),X.currentTarget.querySelector("summary")?.focus(),X.stopPropagation())},children:[s.jsx("summary",{"aria-label":"更多协作操作",className:"flex min-h-11 min-w-11 cursor-pointer list-none items-center justify-center rounded text-muted-foreground hover:bg-surface-2 sm:min-h-8 sm:min-w-8 [&::-webkit-details-marker]:hidden",children:s.jsx(To,{size:16})}),s.jsxs("div",{className:"absolute right-0 top-full z-30 w-44 rounded-lg border border-border/20 bg-surface-2 p-1 shadow-lg",children:[s.jsxs("button",{type:"button",className:`${vr} min-h-11 w-full justify-start text-foreground hover:bg-surface-elevated`,onClick:X=>{X.currentTarget.closest("details")?.removeAttribute("open"),$?.(pt.id).catch(He=>pe(He instanceof Error?He.message:"无法打开看板"))},children:[s.jsx(Fc,{size:14}),"看板"]}),s.jsx("button",{type:"button","aria-expanded":qe,className:`${vr} min-h-11 w-full justify-start text-foreground hover:bg-surface-elevated`,onClick:X=>{X.currentTarget.closest("details")?.removeAttribute("open"),we(He=>!He)},children:"成员管理"}),s.jsxs("button",{type:"button","aria-label":"组设置","aria-expanded":wt,className:`${vr} min-h-11 w-full justify-start text-foreground hover:bg-surface-elevated`,onClick:X=>{X.currentTarget.closest("details")?.removeAttribute("open"),Kt.current=X.currentTarget,zt(!0),pe(null),ee(null)},children:[s.jsx(ju,{size:14}),"组设置"]})]})]})]}),s.jsxs("fieldset",{className:"min-w-0",children:[s.jsx("legend",{className:ze?"sr-only":"mb-1 text-[10px] text-muted-foreground",children:"接收人(可多选)"}),s.jsx("div",{className:"flex flex-wrap gap-1",children:[{id:"*",label:"全组成员"},...pt.sessionIds.map(X=>({id:X,label:(()=>{const He=ir.find(Nt=>Nt.sessionId===X);return He?Iu(He,ir):void 0})()??`${X.slice(0,8)}(离线)`}))].map(({id:X,label:He})=>{const Nt=X==="*"?Ae===null:Ae?.includes(X)??!1,Et=L.find(tr=>tr.sessionId===X);return s.jsxs("span",{className:"inline-flex max-w-full items-center gap-0.5",children:[s.jsxs("button",{type:"button","aria-pressed":Nt,onClick:()=>Ye(tr=>X==="*"?null:tr?.includes(X)?tr.filter(jr=>jr!==X):[...tr??[],X]),className:`${N1} min-h-9 min-w-0 gap-1 sm:min-h-7 ${Nt?"border-primary/40 bg-primary/15 text-primary":"border-border/20 bg-surface-2 text-muted-foreground hover:text-foreground"}`,children:[Nt&&s.jsx(pi,{size:12,"aria-hidden":"true",className:"shrink-0"}),s.jsx("span",{className:"break-words text-left",children:He})]}),Et&&s.jsx("button",{type:"button","aria-label":`打开 ${He} 的终端`,title:`打开 ${He} 的终端`,className:"inline-flex h-9 w-8 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-surface-2 hover:text-primary sm:h-7 sm:w-6",onClick:()=>{z(Et).catch(tr=>pe(tr instanceof Error?tr.message:"无法打开会话"))},children:s.jsx(Fc,{size:12})})]},X)})})]})]}),s.jsxs("label",{className:"mt-2 block space-y-1 text-[9px] text-muted-foreground",children:[s.jsx("span",{className:ze?"sr-only":void 0,children:"内容"}),s.jsx("textarea",{onKeyDown:X=>{X.key==="Enter"&&(X.metaKey||X.ctrlKey)&&!X.nativeEvent.isComposing&&X.keyCode!==229&&(X.preventDefault(),Hr())},onPaste:X=>{const He=Array.from(X.clipboardData.files);He.length&&(X.preventDefault(),zr(He))},className:`${$s} min-h-16 max-h-48 resize-y`,value:et,onChange:X=>St(X.target.value),placeholder:"输入消息,可粘贴引用或文件…"})]}),s.jsxs("div",{className:"mt-2 flex items-center justify-between gap-3",children:[s.jsx("p",{role:"status","aria-live":"polite",title:w&&a?a:void 0,className:`min-w-0 flex-1 text-[9px] leading-relaxed ${w?"truncate":""} ${w&&a?"text-primary":"text-muted-foreground"}`,children:Mn>0?"正在准备文件路径…":w&&a?a:pt.federated?"消息由服务端后台投递,可查看送达结果;无需保持客户端在线。":"在线成员立即入队;离线成员上线后送达。"}),s.jsxs("button",{disabled:le!==null||Mn>0||!et.trim()||!Pr.length,className:`${vr} shrink-0 bg-primary text-primary-foreground`,title:"发送(⌘ / Ctrl + Enter)",onClick:()=>{Hr()},children:[le==="send-message"?s.jsx(bn,{size:13,className:"animate-spin"}):null,"发送"]})]})]}),s.jsxs("div",{children:[s.jsxs("details",{hidden:ze&&!qe,open:ze?qe:void 0,onToggle:X=>{ze&&we(X.currentTarget.open)},className:"mt-4 rounded-xl border border-border/15",children:[s.jsxs("summary",{className:"cursor-pointer px-3 py-3 text-[11px] font-medium text-foreground",children:["管理成员、角色与删除 · ",pt.sessionIds.length," 个成员"]}),s.jsxs("section",{className:"border-t border-border/15 p-3",children:[s.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h4",{className:"text-[13px] font-medium text-foreground",children:pt.name}),s.jsxs("p",{className:"mt-1 text-[10px] text-muted-foreground",children:[pt.sessionIds.length," 个成员 · 组 ID:",s.jsx("span",{className:"break-all font-mono",children:Y6(pt.id)})]})]}),We?s.jsxs("div",{className:"flex flex-wrap items-center gap-1 sm:justify-end",children:[s.jsx("button",{className:`${vr} bg-surface-2 px-2 text-foreground`,onClick:()=>nt(!1),children:"取消"}),s.jsxs("button",{disabled:le!==null,className:`${vr} bg-destructive px-2 text-destructive-foreground`,onClick:()=>{ps()},children:[le===`delete:${pt.id}`?s.jsx(bn,{size:13,className:"animate-spin"}):null,"确认删除"]})]}):s.jsxs("div",{className:"flex flex-wrap items-center gap-1 sm:justify-end",children:[s.jsxs("button",{className:`${vr} px-2 text-muted-foreground hover:bg-surface-2 hover:text-foreground`,onClick:()=>{q(new Set(pt.sessionIds)),qt(pt.updatedAt);const X=!Gt;Qt(X),X&&De(Object.fromEntries(pt.sessionIds.map(He=>[He,pt.roles?.[He]??""]))),Ke(!1)},children:[s.jsx(ju,{size:13}),"管理成员"]}),s.jsxs("button",{className:`${vr} px-2 text-primary hover:bg-primary/10`,onClick:Jr,children:[s.jsx(zs,{size:13}),"新建 Agent"]}),s.jsx("button",{"aria-label":`删除协作组 ${pt.name}`,title:"删除协作组",disabled:le!==null,className:"rounded-lg p-2 text-muted-foreground transition hover:bg-destructive/10 hover:text-destructive",onClick:()=>{ue(pt.updatedAt),nt(!0)},children:s.jsx(Rs,{size:14})})]})]}),We&&s.jsxs("p",{role:"alert",className:"mt-2 rounded-lg bg-destructive/10 px-3 py-2 text-[10px] leading-relaxed text-destructive",children:["将删除“",pt.name,"”协作组及其协作记录,",pt.sessionIds.length," 个成员的终端会话会保留。"]}),s.jsx("div",{className:"mt-3 grid divide-y divide-border/10 border-y border-border/10 sm:grid-cols-2 sm:divide-x sm:divide-y-0",children:pt.sessionIds.map(X=>{const He=L.find(tr=>tr.sessionId===X),Nt=pt.roles?.[X],Et=He?.name??X;return s.jsxs("div",{className:`flex min-w-0 items-stretch transition ${xe===X?"bg-destructive/5":"hover:bg-surface-2"}`,children:[s.jsxs("button",{disabled:!He,onClick:()=>He&&void z(He).catch(tr=>pe(tr instanceof Error?tr.message:"无法打开会话")),className:"min-w-0 flex-1 px-3 py-2.5 text-left disabled:cursor-default",children:[s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${He&&["ready","shell","terminal-connected","service-reachable","working","idle","done"].includes(He.status)&&He.serviceConnected!==!1?"bg-[var(--success)]":"bg-muted-foreground"}`}),s.jsx("span",{className:"truncate text-[11px] text-foreground",children:Et}),He&&s.jsx(_m,{session:He}),s.jsx("span",{className:"ml-auto shrink-0 text-[9px] text-muted-foreground",children:He?rf(He):"已离线"})]}),s.jsxs("span",{className:"mt-1 flex min-w-0 items-center gap-1 text-[9px] text-muted-foreground",children:[Nt?s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"min-w-0 truncate font-medium text-primary/80",children:["定位:",Nt]}),s.jsx("span",{className:"shrink-0 text-muted-foreground/50",children:"·"})]}):null,He?s.jsx("span",{className:"min-w-0 truncate",children:km(He.currentTask)}):s.jsx("span",{className:"shrink-0",children:"重新上线后可继续接收消息"})]})]}),s.jsx("button",{"aria-label":`把 ${Et} 移出协作组`,"aria-expanded":xe===X,title:"移出协作组",disabled:le!==null,className:`mr-1 shrink-0 self-center rounded-lg p-2 transition ${xe===X?"text-destructive":"text-muted-foreground hover:bg-destructive/10 hover:text-destructive"}`,onClick:()=>Ve(xe===X?null:X),children:s.jsx(Rs,{size:13})})]},X)})}),xe&&pt.sessionIds.includes(xe)&&(()=>{const X=L.find(Nt=>Nt.sessionId===xe)?.name??xe,He=le===`remove-member:${xe}`;return s.jsxs("div",{role:"group","aria-label":`确认移除成员 ${X}`,className:"flex flex-wrap items-center gap-x-3 gap-y-2 border-y border-destructive/25 bg-destructive/5 px-3 py-2.5",children:[s.jsx("p",{className:"min-w-0 flex-1 text-[10px] leading-relaxed text-destructive",children:`把“${X}”移出“${pt.name}”?移出后它不再收到这个组的消息,可以随时重新加入`}),s.jsxs("div",{className:"flex shrink-0 gap-2",children:[s.jsx("button",{className:`${vr} min-h-8 bg-surface-2 px-2 text-[10px] text-foreground`,onClick:()=>Ve(null),children:"取消"}),s.jsxs("button",{disabled:le!==null,className:`${vr} min-h-8 px-2 text-[10px] bg-destructive text-destructive-foreground`,onClick:()=>{jn(xe)},children:[He?s.jsx(bn,{size:12,className:"animate-spin"}):s.jsx(Rs,{size:12}),"移出"]})]})]})})(),Gt&&s.jsxs("div",{className:"mt-4 border-t border-border/15 pt-4",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("h5",{className:"text-[11px] font-medium text-foreground",children:"管理成员"}),s.jsx("p",{className:"mt-1 text-[9px] text-muted-foreground",children:"暂不可用的原成员会保留,只有取消勾选才会移出;定位(角色)在每行独立保存,成员收到消息时会看到自己的定位。"})]}),s.jsxs("span",{className:"text-[9px] text-muted-foreground",children:["已选 ",ht.size]})]}),s.jsx("div",{className:"mt-3 max-h-72 divide-y divide-border/10 overflow-y-auto border-y border-border/10",children:Fr.length<=1?mt.map(Dr):Fr.map(X=>{const He=Xt(X.key);return s.jsxs("div",{children:[s.jsx(Rb,{label:X.label,count:X.sessions.length,collapsed:He,onToggle:()=>Zr(X.key)}),!He&&s.jsx("div",{className:"divide-y divide-border/10",children:X.sessions.map(Dr)})]},X.key)})}),s.jsxs("div",{className:"mt-3 flex justify-end gap-2",children:[s.jsx("button",{className:`${vr} bg-surface-2 text-foreground`,onClick:()=>{Qt(!1),De({})},children:"取消"}),s.jsxs("button",{disabled:le!==null||v!=="loaded",className:`${vr} bg-primary text-primary-foreground`,onClick:()=>{Mr()},children:[le==="save-members"?s.jsx(bn,{size:13,className:"animate-spin"}):s.jsx(pi,{size:13}),"保存成员"]})]})]}),nr&&s.jsxs("div",{className:"mt-4 border-t border-primary/20 pt-4",children:[s.jsxs("div",{children:[s.jsx("h5",{className:"text-[11px] font-medium text-foreground",children:"创建 Agent Session"}),s.jsx("p",{className:"mt-1 text-[9px] text-muted-foreground",children:"新会话启动后自动加入本组,并收到初始任务和成员信息。"})]}),s.jsx(bO,{group:pt,value:yt,onChange:xt,disabled:le!==null}),s.jsxs("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:[s.jsxs("label",{className:"space-y-1 text-[9px] text-muted-foreground",children:["Agent / Plugin",s.jsx("select",{"aria-label":"新 Agent 类型",className:$s,disabled:!!yt,value:pt.launchProfiles?.find(X=>X.id===yt)?.agentSlug??_t,onChange:X=>$t(X.target.value),children:E.map(X=>s.jsxs("option",{value:X.slug,children:[X.displayName,X.isPlugin?" · Plugin":""]},X.slug))})]}),s.jsxs("label",{className:"space-y-1 text-[9px] text-muted-foreground",children:["会话名称",s.jsx("input",{"aria-label":"新 Agent 会话名称",className:$s,value:Rt,onChange:X=>Ct(X.target.value),placeholder:"留空则自动命名"})]})]}),s.jsxs("label",{className:"mt-2 block space-y-1 text-[9px] text-muted-foreground",children:["工作目录",s.jsx("input",{"aria-label":"新 Agent 工作目录",className:$s,value:fr,onChange:X=>Yt(X.target.value),placeholder:"默认继承当前会话"})]}),s.jsxs("label",{className:"mt-2 block space-y-1 text-[9px] text-muted-foreground",children:["初始任务",s.jsx("textarea",{"aria-label":"新 Agent 初始任务",className:`${$s} min-h-16 resize-y`,value:Sr,onChange:X=>pn(X.target.value),placeholder:"说明它加入后要先完成什么"})]}),s.jsxs("div",{className:"mt-3 flex justify-end gap-2",children:[s.jsx("button",{className:`${vr} bg-surface-2 text-foreground`,onClick:()=>Ke(!1),children:"取消"}),s.jsxs("button",{disabled:le!==null||!_t||!!yt&&!pt.launchProfiles?.some(X=>X.id===yt),className:`${vr} bg-primary text-primary-foreground`,onClick:()=>{ln()},children:[le==="spawn-agent"?s.jsx(bn,{size:13,className:"animate-spin"}):s.jsx(R0,{size:13}),"创建并加入"]})]})]})]})]},pt.id),s.jsxs("section",{className:"mt-4",children:[s.jsxs("div",{className:"mb-2 flex flex-wrap items-center justify-between gap-2",children:[s.jsx("h4",{className:"text-[11px] font-medium text-foreground",children:"协作记录"}),s.jsxs("span",{className:"text-[9px] text-muted-foreground",children:[Qr.length," 条"]})]}),s.jsxs("div",{className:"divide-y divide-border/10 border-y border-border/10 [overflow-wrap:anywhere]",children:[Qr.map(X=>s.jsxs("div",{className:"px-2 py-3",children:[s.jsxs("div",{className:"flex items-center gap-2 text-[9px] text-muted-foreground",children:[s.jsx("span",{className:"font-medium text-primary",children:X.responseKind==="ack"?"收到确认":X.responseKind==="progress"?"进展":X.responseKind==="result"?"结果":HO(X.kind)}),s.jsx("span",{children:X.fromName}),s.jsx("span",{children:"→"}),s.jsx("span",{className:"truncate",children:X.toNames.join("、")}),s.jsx("span",{className:"ml-auto shrink-0",children:new Date(X.createdAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),s.jsx("p",{className:"mt-1 whitespace-pre-wrap text-[11px] leading-relaxed text-foreground",children:X.content}),s.jsx("p",{className:"mt-1 text-[9px] text-muted-foreground",children:X.status==="pending"?"已入队 · 等待投递":X.status==="failed"?"投递失败":X.status==="expired"?"消息已过期,未继续投递":X.status==="stored"?"答复已持久保存 · 供后台接收":"已写入接收方终端 · 等待接手确认"}),(X.task||X.failureReason)&&s.jsxs("details",{className:"mt-2 text-[10px] text-muted-foreground",children:[s.jsx("summary",{className:"cursor-pointer",children:"任务详情与证据"}),s.jsx("pre",{className:"mt-1 max-h-40 overflow-auto whitespace-pre-wrap break-words",children:JSON.stringify(X.task??{failure_reason:X.failureReason},null,2)})]})]},X.key)),Qr.length===0&&s.jsx(JO,{text:Ie?"正在加载协作记录…":"还没有消息。可以直接给成员发送说明或问题。"})]})]})]})]})]})]})}function BO({group:e,agents:t,activeSessionId:r,sessions:n,busy:a,setBusy:c,setError:l,setNotice:d,refresh:p,onClose:m}){const x=n.filter(Y=>e.sessionIds.includes(Y.sessionId)&&!$u(Y.sessionId)),[y,w]=b.useState(()=>EO(e,r&&x.some(Y=>Y.sessionId===r)?r:"")),v=b.useRef(y),[S,L]=b.useState(null),E=Y=>{const ce={...v.current,...Y};v.current=ce,NO(e.id,ce),w(ce)},{name:R,rules:B,savedName:z,savedRules:O,rulesVersion:$,rulesMemberId:V}=y,Z=Qf(y),le=new TextEncoder().encode(B).length,be=x.some(Y=>Y.sessionId===V),pe=async()=>{if(!(a||!R.trim())){c("group-name"),l(null),d(null);try{const Y=await Ml({id:e.id,name:R.trim(),sessionIds:y.sessionIds??e.sessionIds,expectedUpdatedAt:y.updatedAt});L(null),E({savedName:Y.group.name,name:Y.group.name,updatedAt:Y.group.updatedAt,sessionIds:Y.group.sessionIds,...B===O?{rules:Y.group.instructions?.text??"",savedRules:Y.group.instructions?.text??"",rulesVersion:Y.group.instructions?.version??""}:{}}),await p(),d("协作组名称已更新")}catch(Y){L(null),l(Y instanceof n0&&Y.status===409?"组设置已被其他人修改。请查看最新状态并确认,名称与群规草稿仍保留。":Y instanceof Error?Y.message:"改名失败")}finally{c(null)}}},ee=async()=>{if(!(a||!be||le>8192)){c("group-rules"),l(null),d(null);try{const Y=await W8(e.id,{sessionId:V,text:B,expectedVersion:$});L(null),E({savedName:Y.group.name,...R===z?{name:Y.group.name}:{},updatedAt:Y.group.updatedAt,sessionIds:Y.group.sessionIds,rules:Y.group.instructions?.text??"",savedRules:Y.group.instructions?.text??"",rulesVersion:Y.group.instructions?.version??""}),await p(),d(B.trim()?"群规已保存,变更通知已入队":"群规已清空,变更通知已入队")}catch(Y){L(null),l(Y instanceof n0&&Y.status===409?"群规已被其他人修改。请查看最新状态并确认,名称与群规草稿仍保留。":Y instanceof Error?Y.message:"群规保存失败")}finally{c(null)}}},_e=()=>{E(Eg(e,V)),L(null),l(null)},ze=async()=>{if(!a){c("group-latest"),l(null),d(null),L(null);try{const ce=(await Q1()).groups.find(qe=>qe.id===e.id);if(!ce)throw new Error("协作组已删除;草稿仍保留,请返回看板查看。");L(ce)}catch(Y){l(Y instanceof Error?Y.message:"最新状态读取失败;草稿仍保留,请重试。")}finally{c(null)}}};return s.jsxs("section",{"aria-label":"协作组设置",onKeyDown:Y=>{Y.key!=="Escape"||Y.defaultPrevented||Y.nativeEvent.isComposing||(Y.preventDefault(),Y.stopPropagation(),a||m())},className:"mt-3 rounded-xl border border-border/20 bg-surface-2 p-3",children:[s.jsxs("div",{className:"mb-3 flex items-center justify-between gap-2",children:[s.jsx("h4",{className:"text-[12px] font-medium text-foreground",children:"组设置"}),s.jsx("button",{type:"button",disabled:!!a,"aria-label":"关闭组设置",className:"rounded-lg p-2 text-muted-foreground hover:bg-surface-elevated",onClick:m,children:s.jsx(In,{size:14})})]}),s.jsxs("label",{className:"block space-y-1 text-[10px] text-muted-foreground",children:["协作组名称",s.jsx("input",{autoFocus:!0,className:$s,value:R,maxLength:240,disabled:!!a,onChange:Y=>E({name:Y.target.value})})]}),s.jsx("div",{className:"mt-2 flex justify-end",children:s.jsx("button",{type:"button",disabled:!!a||!!S||!R.trim()||R.trim()===z,className:`${vr} min-h-9 bg-primary text-primary-foreground`,onClick:()=>{pe()},children:a==="group-name"?"保存中…":"保存名称"})}),s.jsx(yO,{group:e,agents:t,busy:a,setBusy:c,refresh:p}),s.jsxs("div",{className:"mt-3 space-y-2 border-t border-border/15 pt-3",children:[s.jsxs("label",{className:"block space-y-1 text-[10px] text-muted-foreground",children:["由本组成员发布群规变更",s.jsxs("select",{className:$s,value:V,disabled:!!a||!x.length,onChange:Y=>E({rulesMemberId:Y.target.value}),children:[s.jsx("option",{value:"",children:"选择当前服务的一个成员"}),!x.some(Y=>Y.sessionId===V)&&V&&s.jsx("option",{value:V,children:"原成员已不在组内,请重新选择"}),x.map(Y=>s.jsx("option",{value:Y.sessionId,children:Y.name},Y.sessionId))]})]}),s.jsxs("label",{className:"block space-y-1 text-[10px] text-muted-foreground",children:["群规与协作约定",s.jsx("textarea",{className:`${$s} min-h-24 resize-y`,value:B,maxLength:8192,disabled:!!a,onChange:Y=>E({rules:Y.target.value}),placeholder:"例如:说明分工、交接要求和结果格式。清空后保存可移除群规。"})]})]}),!be&&s.jsx("p",{className:"mt-1 text-[10px] text-muted-foreground",children:x.length?"选择发布变更的成员后即可保存,不需要关闭工作台。":"当前服务没有本组成员,请先添加成员或切换到成员所在的服务。已有群规可在此查看。"}),s.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2",children:[s.jsx("p",{className:`text-[9px] ${le>8192?"text-destructive":"text-muted-foreground"}`,children:le>8192?"内容过长,请缩短群规":"保存或清空群规会通知本组其他成员"}),s.jsx("button",{type:"button",disabled:!!a||!!S||!be||le>8192||B===O,className:`${vr} min-h-9 shrink-0 bg-primary text-primary-foreground`,onClick:()=>{ee()},children:a==="group-rules"?"保存中…":B.trim()?"保存群规":"清空群规"})]}),Z&&s.jsx("p",{role:"status",className:"mt-3 text-[11px] leading-5 text-muted-foreground",children:"有未保存修改。关闭、Escape 或切换组后,草稿仍保留在本标签页;名称与群规需分别保存。"}),Z&&s.jsx("button",{type:"button",disabled:!!a,className:`${vr} mt-2 min-h-11 text-primary hover:bg-surface-elevated`,onClick:()=>{ze()},children:a==="group-latest"?"读取中…":"查看最新状态并保留草稿"}),S&&s.jsxs("section",{"aria-label":"最新组设置",className:"mt-3 space-y-2 rounded-lg bg-surface p-3 text-[11px] leading-5",children:[s.jsx("p",{className:"font-medium text-foreground",children:"确认最新状态后,再分别保存草稿"}),s.jsxs("p",{className:"break-words text-muted-foreground",children:["当前名称:",S.name]}),s.jsxs("p",{className:"whitespace-pre-wrap break-words text-muted-foreground",children:["当前群规:",S.instructions?.text||"未设置"]}),s.jsxs("p",{className:"break-words text-muted-foreground",children:["当前成员(",S.sessionIds.length,"):",S.sessionIds.map(Y=>n.find(ce=>ce.sessionId===Y)?.name??Y6(Y)).join("、")||"暂无成员"]}),s.jsx("p",{className:"text-muted-foreground",children:"保留你的未保存内容;名称保存将保留以上成员,群规保存会通知当前成员。再次发生修改时仍会检查冲突。"}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",disabled:!!a,className:`${vr} min-h-11 bg-primary text-primary-foreground`,onClick:()=>{E(IO(v.current,S)),L(null),l(null),d("已确认最新状态,草稿仍保留;请分别保存名称与群规。")},children:"确认最新状态,保留草稿"}),s.jsx("button",{type:"button",className:`${vr} min-h-11 text-muted-foreground`,onClick:()=>L(null),children:"取消确认"})]})]}),s.jsxs("div",{className:"mt-3 flex justify-between gap-2 border-t border-border/15 pt-2",children:[s.jsxs("button",{type:"button",disabled:!!a,className:`${vr} min-h-9 text-muted-foreground hover:bg-surface-elevated`,onClick:_e,children:[s.jsx(bn,{size:12}),"重新载入",Z&&"(放弃草稿)"]}),s.jsx("button",{type:"button",disabled:!!a,className:`${vr} min-h-9 bg-surface text-foreground`,onClick:m,children:Z?"关闭并保留草稿":"关闭"})]})]})}function QO({peers:e,currentGroupId:t,busy:r,setBusy:n,setError:a,setNotice:c,onSelectGroup:l}){const[d,p]=b.useState(null),[m,x]=b.useState(!1),y=e.services??[],w=e.removedServices??[],v=y.filter(E=>!E.connected),S=v.some(E=>E.groups?.some(R=>R.id===t)),L=async(E,R)=>{if(!r){n(`peer:${E}`),a(null),c(null);try{R?await K8(E):await X8(E),p(null),x(!1),c(R?"协作连接已恢复,正在连接服务":"协作连接已移除,不会再自动重连;已有会话和消息保留")}catch(B){a(B instanceof Error?B.message:R?"重新连接失败":"移除连接失败")}finally{n(null)}}};return s.jsxs("details",{className:"mt-4 shrink-0 rounded-lg border border-border/15",open:S||void 0,children:[s.jsxs("summary",{className:"cursor-pointer px-3 py-2.5 text-[11px] text-muted-foreground",children:[s.jsx("span",{className:"font-medium text-foreground",children:"协作连接与管理"}),s.jsx("span",{className:"ml-2",children:e.state==="loading"?"正在加载…":`${y.length-v.length} 个已连接${v.length?` · ${v.length} 个离线`:""}`})]}),s.jsxs("div",{className:"max-h-64 overflow-y-auto border-t border-border/15 px-3 py-2",children:[y.length>0&&s.jsx("p",{className:"mb-1 text-[10px] leading-relaxed text-muted-foreground",children:"与以下服务进行跨服务协作,名称与服务切换器一致。"}),v.length>0&&s.jsx("p",{className:"mb-2 text-[10px] leading-relaxed text-muted-foreground",children:S?"当前协作组的部分服务不可达,消息会保留并等待重连。":"其他服务暂时离线;当前服务内的协作可以继续。不再使用的连接可移除。"}),e.error&&s.jsx("p",{role:"status",className:"mb-2 break-words text-[10px] text-destructive",children:e.error}),e.state==="unsupported"&&s.jsx("p",{className:"mb-2 text-[10px] text-muted-foreground",children:"请更新客户端以管理跨服务连接。"}),s.jsx("div",{className:"divide-y divide-border/10",children:y.map(E=>s.jsxs("div",{className:"py-2.5",children:[s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("p",{className:"text-[11px] text-foreground",children:[uc({serviceLabel:E.label,serviceOrigin:E.origin}),s.jsx("span",{className:`ml-2 text-[9px] ${E.connected?"text-[var(--success)]":"text-muted-foreground"}`,children:E.connected?"已连接":E.error==="CONNECTING"?"连接中":"暂时离线"})]}),s.jsx(PO,{service:E})]}),E.serviceId&&s.jsxs("button",{type:"button",disabled:!!r,"aria-label":`移除协作连接 ${E.origin}`,className:`${vr} min-h-9 shrink-0 text-muted-foreground hover:bg-destructive/10 hover:text-destructive`,onClick:()=>p(d===E.serviceId?null:E.serviceId),children:[s.jsx(Rs,{size:12}),"移除"]})]}),!!E.groups?.length&&s.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1 text-[9px] text-muted-foreground",children:[s.jsx("span",{children:"用于"}),E.groups.map(R=>s.jsx("button",{type:"button",className:"rounded px-1.5 py-1 text-primary hover:bg-primary/10",onClick:()=>l(R.id),children:R.name},R.id))]}),!E.connected&&E.error&&E.error!=="CONNECTING"&&s.jsxs("details",{className:"mt-1 text-[9px] text-muted-foreground",children:[s.jsx("summary",{className:"cursor-pointer",children:GO(E.error)}),s.jsx("p",{className:"mt-1 select-text break-words",children:E.error})]}),d===E.serviceId&&s.jsxs("div",{role:"group","aria-label":"确认移除协作连接",className:"mt-2 rounded-lg bg-surface-2 p-2.5",children:[s.jsx("p",{className:"text-[10px] leading-relaxed text-foreground",children:E.groups?.length?"请先处理上方协作组的成员,再移除这条连接。":"移除后停止与该服务协作,保留已有会话和消息;以后可重新连接。"}),s.jsxs("div",{className:"mt-2 flex justify-end gap-2",children:[s.jsx("button",{type:"button",disabled:!!r,className:`${vr} min-h-9 text-muted-foreground`,onClick:()=>p(null),children:"取消"}),s.jsx("button",{type:"button",disabled:!!r||!!E.groups?.length,className:`${vr} min-h-9 bg-destructive text-destructive-foreground`,onClick:()=>{L(E.serviceId,!1)},children:r===`peer:${E.serviceId}`?"正在移除…":"确认移除"})]})]})]},E.serviceId||E.origin))}),y.length===0&&e.state==="ready"&&s.jsx("p",{className:"py-2 text-[10px] text-muted-foreground",children:"当前没有其他协作服务,当前服务内仍可创建协作组。"}),v.length>0&&s.jsxs("button",{type:"button",className:`${vr} mt-1 min-h-9 text-primary hover:bg-primary/10`,onClick:Z8,children:[s.jsx(bn,{size:12}),"重试连接"]}),w.length>0&&s.jsxs("div",{className:"mt-2 border-t border-border/15 pt-1",children:[s.jsx("button",{type:"button","aria-expanded":m,className:`${vr} min-h-9 text-muted-foreground hover:bg-surface-2`,onClick:()=>x(E=>!E),children:m?"收起恢复列表":"恢复已移除连接"}),m&&s.jsxs("section",{"aria-label":"恢复已移除连接",className:"mt-1 rounded-lg bg-surface-2 px-2.5 py-2",children:[s.jsx("p",{className:"text-[10px] leading-relaxed text-muted-foreground",children:"以下是恢复记录,连接已停用,不会自动重连。点击恢复后才会重新启用协作。"}),s.jsx("div",{className:"mt-1 divide-y divide-border/10",children:w.map(E=>s.jsxs("div",{className:"flex items-start gap-2 py-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("p",{className:"break-words text-[10px] text-foreground",children:[uc({serviceLabel:E.label,serviceOrigin:E.origin}),s.jsx("span",{className:"ml-2 text-[9px] text-muted-foreground",children:"已停用"})]}),s.jsx("p",{className:"mt-0.5 select-text break-all text-[9px] text-muted-foreground",children:E.accessUrl||E.origin})]}),s.jsx("button",{type:"button",disabled:!!r||!E.serviceId,className:`${vr} min-h-9 shrink-0 text-primary hover:bg-primary/10`,onClick:()=>{L(E.serviceId,!0)},children:r===`peer:${E.serviceId}`?"恢复中…":"恢复连接"})]},E.serviceId||E.origin))})]})]})]})]},S?"affected":"other")}function PO({service:e}){let t=!1;try{t=["localhost","127.0.0.1","[::1]"].includes(new URL(e.origin).hostname)}catch{}const r=e.accessUrl||(t?"":e.origin);return s.jsxs("details",{className:"mt-1 text-[9px] text-muted-foreground",children:[s.jsx("summary",{className:"w-fit cursor-pointer py-1",children:"连接详情"}),s.jsxs("dl",{className:"mt-1 space-y-1 select-text break-all",children:[s.jsxs("div",{children:[s.jsx("dt",{className:"inline",children:"服务地址:"}),s.jsx("dd",{className:"inline",children:r||"暂未获取,请在服务切换器中查看"})]}),e.serviceId&&s.jsxs("div",{children:[s.jsx("dt",{className:"inline",children:"服务身份:"}),s.jsx("dd",{className:"inline",children:e.serviceId})]})]})]})}function Cm(e){return!$u(e.sessionId)||e.serviceConnected!==!1}function OO(e){return e.serviceOrigin?e.serviceOrigin===window.location.origin?"":e.serviceOrigin:$u(e.sessionId)?.origin??""}function Nb(e){const t=new Map;for(const r of e){const n=OO(r),a=t.get(n)??{key:n,label:n?uc(r):"本机服务",sessions:[]};n&&a.label==="远端服务"&&(a.label=uc(r)),a.sessions.push(r),t.set(n,a)}return[...t.values()].sort((r,n)=>(r.key?1:0)-(n.key?1:0)||r.label.localeCompare(n.label))}function Rb({label:e,count:t,collapsed:r,onToggle:n}){return s.jsxs("button",{type:"button","aria-expanded":!r,onClick:n,className:"flex w-full items-center gap-1.5 bg-surface-2/50 px-2 py-1.5 text-left text-muted-foreground transition hover:bg-surface-elevated",children:[s.jsx(ul,{size:12,className:`shrink-0 transition-transform ${r?"-rotate-90":""}`}),s.jsx("span",{className:"min-w-0 flex-1 truncate text-[10px] font-semibold uppercase tracking-wide",children:e}),s.jsx("span",{className:"shrink-0 text-[9px] text-muted-foreground/70",children:t})]})}function FO(e,t){const r=new Map(t.map(n=>[n.sessionId,n]));for(const n of e?.sessionIds??[]){if(r.has(n))continue;const a=e?.remoteSessions?.find(c=>c.sessionId===n);r.set(n,a?{...a,status:"offline",serviceConnected:!1}:{sessionId:n,name:n,backendSessionId:null,cwd:"",agent:null,status:"offline",capability:"",currentTask:"暂不可用,保留成员身份",updatedAt:0,...$u(n)?{serviceConnected:!1}:{}})}return[...r.values()]}function _m({session:e}){return!e.serviceOrigin||e.serviceOrigin===window.location.origin?null:s.jsxs("span",{className:"inline-flex max-w-28 shrink-0 items-center gap-1 rounded border border-border/20 px-1 py-0.5 text-[9px] text-muted-foreground",children:[s.jsx(Fc,{size:9}),s.jsx("span",{className:"truncate",children:uc(e)})]})}function rf(e){return e.serviceConnected===!1?"服务不可达":e.status==="recovering"&&e.route_error==="ROUTE_NOT_CHECKED"?"投递目标未检查":zO(e.status)}function $O(e,t=[]){if(!e)return;const r=t.some(a=>a.sessionId!==e.sessionId&&a.name.trim()===e.name.trim()),n=e.sessionId.startsWith("remote:")?uc(e):"本机服务";return r?`${e.name} · ${n}`:e.name}async function UO(e){e.sessionId.startsWith("remote:")?await A6(e.sessionId):window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:e.sessionId}))}function zO(e){return{ready:"终端可达",shell:"Shell 终端",recovering:"正在检查投递目标",unchecked:"投递目标未检查","terminal-connected":"终端已连接",detached:"终端未连接","agent-exited":"Agent 已退出",offline:"已离线",ambiguous:"需确认目标终端","identity-mismatch":"终端身份已变化",unavailable:"终端暂不可达","service-reachable":"服务可达","service-unreachable":"服务不可达"}[e]??"在线"}function km(e){if(!e)return"暂无任务摘要";try{const t=JSON.parse(e);if(typeof t.prompt=="string")return Pf(t.prompt)||"暂无任务摘要"}catch{}return Pf(e)||"暂无任务摘要"}function HO(e){return{message:"消息",ask:"问题",reply:"回复",task:"任务",handoff:"交接",done:"完成"}[e]}function WO(e,t){const r=new Map(t.map(a=>[a.sessionId,$O(a,t)])),n=new Map;for(const a of e){const c=`${a.threadId}:${a.createdAt}:${a.fromSessionId??a.integrationOrigin?.integrationId??"user"}:${a.kind}:${a.responseKind??""}:${JSON.stringify(a.task??null)}:${a.content}`,l=n.get(c),d=a.toPrincipalId?`后台接入 ${a.toPrincipalId}`:r.get(a.toSessionId)??a.toSessionId.slice(0,8);if(l){l.toNames.push(d);const p={failed:-2,expired:-1,pending:0,delivered:1,read:2,stored:3};p[a.status]<p[l.status]&&(l.status=a.status);continue}n.set(c,{key:c,kind:a.kind,content:a.content,createdAt:a.createdAt,fromName:a.fromSessionId?r.get(a.fromSessionId)??a.fromSessionId.slice(0,8):a.integrationOrigin?`后台接入 ${a.integrationOrigin.integrationId}`:"你",toNames:[d],status:a.status,responseKind:a.responseKind,task:a.task,failureReason:a.failureReason})}return[...n.values()].sort((a,c)=>c.createdAt-a.createdAt)}function GO(e){return/timeout|timed out|超时|operation was aborted/i.test(e)?"连接超时,暂时无法访问该服务。请确认远端服务已启动,并检查网络或 VPN 连接。":/ECONNREFUSED|connection refused/i.test(e)?"远端拒绝连接,请确认服务已启动且端口正确。":/ENOTFOUND|EHOSTUNREACH|ENETUNREACH/i.test(e)?"无法访问远端地址,请检查地址和网络连接。":/certificate|fingerprint|TLS|证书/i.test(e)?"远端证书校验失败,请检查服务连接授权。":"服务连接暂时不可用,可查看连接详情并重试。"}function Lm({value:e,query:t}){const r=t.trim().toLocaleLowerCase();if(!r)return s.jsx(s.Fragment,{children:e});const n=e.toLocaleLowerCase(),a=[];let c=0,l;for(;(l=n.indexOf(r,c))>=0;)a.push(e.slice(c,l)),a.push(s.jsx("mark",{className:"rounded bg-primary/15 text-primary",children:e.slice(l,l+r.length)},l)),c=l+r.length;return a.push(e.slice(c)),s.jsx(s.Fragment,{children:a})}function VO({active:e,onClose:t,onNewSession:r,setError:n}){const[a,c]=b.useState(""),[l,d]=b.useState([]),[p,m]=b.useState(0),[x,y]=b.useState(),[w,v]=b.useState(50),[S,L]=b.useState(0),[E,R]=b.useState(!1),[B,z]=b.useState(null),[O,$]=b.useState(null),V=b.useRef(null),Z=b.useRef(0);b.useEffect(()=>{e&&V.current?.focus({preventScroll:!0})},[e]),b.useEffect(()=>{if(!e)return;const pe=++Z.current,ee=new AbortController;let _e;z(null),R(!0);const ze=async()=>{try{const Y=await J8(a.trim(),w,ee.signal);if(pe!==Z.current)return;d(Y.results),m(Y.total??Y.results.length),y(Y.index),Y.index?.building&&(_e=window.setTimeout(()=>{ze()},2500))}catch(Y){pe===Z.current&&!ee.signal.aborted&&z(Y instanceof Error?Y.message:"搜索失败")}finally{pe===Z.current&&R(!1)}};return _e=window.setTimeout(()=>{ze()},a.trim()?250:0),()=>{window.clearTimeout(_e),ee.abort(),++Z.current}},[e,a,w,S]);const le=pe=>{n(null),c(pe),d([]),m(0),v(50)},be=async pe=>{if(!O){if(pe.live){window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:pe.sessionId})),t();return}if(!(!pe.nativeKey&&!pe.resumeHistoryId)){$(pe.sessionId),n(null);try{const ee=pe.nativeKey?await e9(pe.nativeKey):await Ry(pe.resumeHistoryId);if("sessionId"in ee&&ee.sessionId)window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:ee.sessionId}));else if(ee.command)r({mode:"shell",cwd:ee.cwd,command:ee.command});else throw new Error("这条会话暂时无法恢复,请重新搜索");t()}catch(ee){n(ee instanceof Error?ee.message:"恢复失败")}finally{$(null)}}}};return s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"sticky -top-4 z-20 -mx-4 -mt-4 border-b border-border/15 bg-surface px-4 py-3",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-[13px] font-medium text-foreground",children:"历史会话搜索"}),s.jsx("p",{className:"mt-1 text-[10px] leading-relaxed text-muted-foreground",children:"搜索当前服务的 Codex、Claude 历史对话和 Termdock 终端记录,未启动的会话也能找到并恢复。"})]}),s.jsxs("label",{className:"relative mt-3 block",children:[s.jsx("span",{className:"sr-only",children:"搜索历史会话"}),s.jsx(jl,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),s.jsx("input",{ref:V,maxLength:512,className:`${$s} pl-9 pr-9`,value:a,onChange:pe=>le(pe.target.value),placeholder:"搜索会话名称、对话关键词、目录或 session ID"}),E?s.jsx(bn,{size:13,className:"absolute right-3 top-1/2 -translate-y-1/2 animate-spin text-muted-foreground"}):a&&s.jsx("button",{type:"button","aria-label":"清空搜索",className:"absolute right-1.5 top-1/2 -translate-y-1/2 rounded-md p-1.5 text-muted-foreground hover:bg-surface-2 hover:text-foreground",onClick:()=>le(""),children:s.jsx(In,{size:13})})]}),x?.building&&s.jsxs("div",{role:"status",className:"mt-2 text-[10px] text-muted-foreground",children:["正在建立历史索引:",x.indexed,"/",x.total," 个会话。可以先搜名称和目录,对话结果会自动补齐。"]}),x?.warning&&s.jsx("p",{role:"status",className:"mt-2 text-[10px] text-destructive",children:x.warning}),!!x?.failed&&s.jsxs("p",{role:"status",className:"mt-2 text-[10px] text-destructive",children:[x.failed," 个会话暂未完成索引,其余结果可正常使用。请稍后刷新重试。"]})]}),s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("p",{className:"text-[11px] text-foreground",children:[a.trim()?`找到 ${p} 个会话`:"最近的会话",p>l.length?` · 显示 ${l.length} 个`:""]}),s.jsxs("button",{type:"button",disabled:E,className:`${vr} text-muted-foreground hover:bg-surface-2 hover:text-foreground`,onClick:()=>L(pe=>pe+1),children:[s.jsx(bn,{size:12}),"刷新"]})]}),!a.trim()&&s.jsx("p",{className:"text-[10px] text-muted-foreground",children:"记得之前讨论过什么?输入一句话中的关键词,就能找到对应会话。历史对话与索引保存在当前服务机器上。"}),s.jsx("div",{className:"divide-y divide-border/10 border-y border-border/10",children:l.map(pe=>{const ee=pe.live||!!(pe.nativeKey||pe.resumeHistoryId),_e=O===pe.sessionId?"正在恢复…":pe.live?"打开会话":ee?"恢复会话":"仅供查阅",ze=pe.source==="codex"||pe.source==="claude"?pe.snippet:qO(pe),Y=pe.source==="codex"?"Codex 历史":pe.source==="claude"?"Claude 历史":"终端记录",ce=s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"break-words text-[12px] font-medium text-foreground",children:s.jsx(Lm,{value:pe.title,query:a})}),s.jsx("p",{className:"mt-0.5 break-all text-[9px] text-muted-foreground",children:s.jsx(Lm,{value:pe.cwd||"项目目录待索引",query:a})})]}),s.jsx("span",{className:`shrink-0 text-[10px] ${pe.live?"text-[var(--success)]":ee?"text-primary":"text-muted-foreground"}`,children:_e})]}),ze&&s.jsx("p",{className:"mt-2 line-clamp-3 break-words text-[10px] leading-relaxed text-foreground/75",children:s.jsx(Lm,{value:ze,query:a})}),s.jsxs("p",{className:"mt-2 text-[9px] text-muted-foreground",children:[Y," · ",Of(pe.updatedAt),a.trim()?` · ${pe.matchCount>=999?"999+":pe.matchCount} 处匹配`:"",ee?"":" · 没有可恢复记录"]}),pe.agentNativeSessionId&&s.jsx("p",{className:"mt-1 select-text break-all text-[9px] text-muted-foreground",children:pe.agentNativeSessionId})]});return ee?s.jsx("button",{disabled:!!O,onClick:()=>{be(pe)},className:"block w-full px-2 py-3 text-left transition hover:bg-surface-2 focus-visible:bg-surface-2 focus-visible:outline-none",children:ce},pe.nativeKey||pe.sessionId):s.jsx("article",{className:"px-2 py-3",children:ce},pe.sessionId)})}),p>l.length&&w<5e3&&s.jsx("button",{type:"button",disabled:E,className:`${vr} w-full bg-surface-2 text-foreground`,onClick:()=>v(pe=>pe+50),children:E?"正在加载…":"加载更多会话"}),B&&s.jsxs("div",{role:"alert",className:"rounded-lg bg-destructive/10 p-3 text-[11px] text-destructive",children:["搜索失败:",B,s.jsx("button",{type:"button",className:`${vr} ml-2`,onClick:()=>L(pe=>pe+1),children:"重试"})]}),!E&&!B&&l.length===0&&s.jsxs("div",{className:"border-y border-border/15 py-8 text-center",children:[s.jsx("p",{className:"text-[12px] text-foreground",children:x?.building?"历史对话仍在索引,请稍候":x?.warning||x?.failed?"暂未找到结果,部分历史记录尚不可搜索":a.trim()?`没有找到“${a.trim()}”`:"当前服务还没有可搜索的历史会话"}),s.jsx("p",{className:"mt-1 text-[10px] text-muted-foreground",children:x?.building?"新结果会自动显示,也可以先搜会话名称或目录。":"可尝试更短的关键词、项目目录或 session ID;其他机器的历史需切换到对应服务搜索。"}),a.trim()&&s.jsx("button",{className:`${vr} mt-3 bg-surface-2 text-foreground`,onClick:()=>le(""),children:"查看最近会话"})]})]})}function Pf(e){return e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g," ").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g," ").replace(/\(B/g," ").replace(/<[^>]{1,120}>/g," ").replace(/[─━│┃┄┅┆┇┈┉┊┋┌┐└┘├┤┬┴┼╭╮╯╰═║╔╗╚╝╠╣╦╩╬]+/g," ").replace(/([^\p{L}\p{N}\s])\1{3,}/gu," ").replace(/([A-Za-z])\1{12,}/g," ").replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g," ").replace(/\s+/g," ").trim().slice(0,280)}function qO(e){let t=Pf(e.snippet);for(const r of[e.title,e.cwd,e.agentSlug])r&&(t=t.split(r).join(" "));return Pf(t)}function YO(e){if(e.schedule.kind==="interval")return e.schedule.everyMinutes===60?"每小时":e.schedule.everyMinutes===1440?"每天":`每 ${e.schedule.everyMinutes} 分钟`;const t=["日","一","二","三","四","五","六"];return`${e.schedule.weekdays.length===7?"每天":e.schedule.weekdays.map(n=>`周${t[n]}`).join("、")} ${e.schedule.time}`}function ZO(e,t=Date.now(),r=t){if(e.kind==="interval"){const c=e.everyMinutes*6e4,l=Math.max(0,t-r);return r+(Math.floor(l/c)+1)*c}const[n,a]=e.time.split(":").map(Number);for(let c=0;c<=7;c+=1){const l=new Date(t);if(l.setDate(l.getDate()+c),l.setHours(n,a,0,0),l.getTime()>t&&e.weekdays.includes(l.getDay()))return l.getTime()}return t}function Of(e){return new Intl.DateTimeFormat("zh-CN",{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(e)}function KO(e){return e==="running"?"投递中":e==="success"?"已投递":e==="failed"?"投递失败":""}function XO(e){return e==="running"?"text-[var(--warning)]":e==="success"?"text-[var(--success)]":e==="failed"?"text-destructive":"text-muted-foreground"}function JO({text:e}){return s.jsx("div",{className:"rounded-xl border border-dashed border-border/20 px-4 py-8 text-center text-[11px] text-muted-foreground",children:e})}function eF({onOpenSettings:e,serverAttention:t,actions:r}){const{t:n}=Ur(),[a,c]=b.useState(!1),l=b.useRef(null),d=b.useRef(null),p=b.useRef(null),m=b.useId();return b.useLayoutEffect(()=>{if(!a)return;const x=l.current,y=p.current;if(!x||!y)return;const w=window.visualViewport,v=()=>{const L=x.getBoundingClientRect(),E=(w?.offsetLeft??0)+8,R=(w?.offsetTop??0)+8,B=(w?.width??window.innerWidth)-16,z=(w?.offsetTop??0)+(w?.height??window.innerHeight)-8,O=Math.max(0,Math.min(256,B)),$=Math.max(0,L.top-R-4),V=Math.max(0,z-L.bottom-4),Z=$>=180||$>=V;Object.assign(y.style,{width:`${O}px`,left:`${Math.max(E,Math.min(L.right-O,E+B-O))}px`,top:`${Z?L.top-4:L.bottom+4}px`,maxHeight:`${Z?$:V}px`,transform:Z?"translateY(-100%)":"none"})};v();const S=typeof ResizeObserver>"u"?null:new ResizeObserver(v);return S?.observe(x),window.addEventListener("resize",v),window.addEventListener("scroll",v,!0),w?.addEventListener("resize",v),w?.addEventListener("scroll",v),()=>{S?.disconnect(),window.removeEventListener("resize",v),window.removeEventListener("scroll",v,!0),w?.removeEventListener("resize",v),w?.removeEventListener("scroll",v)}},[a]),b.useEffect(()=>{if(!a)return;p.current?.querySelector('[role="menuitem"]')?.focus({preventScroll:!0});const x=y=>{y.target instanceof Node&&!l.current?.contains(y.target)&&!p.current?.contains(y.target)&&c(!1)};return document.addEventListener("pointerdown",x),()=>document.removeEventListener("pointerdown",x)},[a]),s.jsxs("div",{ref:l,role:"group","data-sidebar-gesture-ignore":!0,"aria-label":n("sidebar.moreActions"),className:"relative z-20 mt-2 flex items-center justify-between gap-2",onKeyDown:x=>{a&&x.key==="Escape"&&(x.preventDefault(),x.stopPropagation(),c(!1),d.current?.focus({preventScroll:!0}))},children:[s.jsxs("button",{type:"button",onClick:e,title:t?n("sidebar.serverAttention"):void 0,className:"inline-flex min-h-9 items-center gap-1.5 whitespace-nowrap rounded-lg px-2 text-[11px] text-muted-foreground transition hover:bg-surface-2 hover:text-foreground focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary",children:[s.jsx(bS,{size:14,className:t?"text-destructive":void 0}),s.jsx("span",{children:n("sidebar.settings")})]}),s.jsxs("button",{ref:d,type:"button","aria-haspopup":"menu","aria-expanded":a,"aria-controls":a?m:void 0,onClick:()=>c(x=>!x),onKeyDown:x=>{(x.key==="ArrowDown"||x.key==="ArrowUp")&&(x.preventDefault(),c(!0))},className:`inline-flex min-h-9 items-center gap-1.5 whitespace-nowrap rounded-lg px-2 text-[11px] transition focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary ${a?"bg-surface-2 text-foreground":"text-muted-foreground hover:bg-surface-2 hover:text-foreground"}`,children:[s.jsx(To,{size:15}),s.jsx("span",{children:n("sidebar.moreActions")})]}),a&&Xs.createPortal(s.jsx("div",{ref:p,id:m,role:"menu","data-sidebar-gesture-ignore":!0,"data-sidebar-composer-popover":"sidebar-launch-options","aria-label":n("sidebar.moreActions"),className:"fixed z-popover overflow-y-auto overscroll-contain rounded-xl border border-border/15 bg-surface p-1 shadow-[0_12px_32px_var(--app-shadow-soft)] animate-fade-in",onKeyDown:x=>{const y=[...x.currentTarget.querySelectorAll('[role="menuitem"]')],w=y.indexOf(document.activeElement);let v;if(x.key==="ArrowDown")v=(w+1)%y.length;else if(x.key==="ArrowUp")v=(w-1+y.length)%y.length;else if(x.key==="Home")v=0;else if(x.key==="End")v=y.length-1;else if(x.key==="Tab"){c(!1);return}else return;x.preventDefault(),y[v]?.focus({preventScroll:!0})},children:r.map(({label:x,icon:y,onSelect:w,separated:v})=>s.jsxs("div",{role:"none",children:[v&&s.jsx("div",{role:"separator",className:"mx-2 my-1 h-px bg-border/40"}),s.jsxs("button",{type:"button",role:"menuitem",tabIndex:-1,onClick:()=>{c(!1),w()},className:"flex min-h-10 w-full items-center gap-2.5 whitespace-nowrap rounded-lg px-2.5 text-left text-[12px] text-foreground transition hover:bg-surface-2 focus:bg-surface-2 focus:outline-none",children:[s.jsx(y,{size:15,className:"shrink-0 text-muted-foreground"}),s.jsx("span",{children:x})]})]},x))}),document.body)]})}const Fd=64,Mb=10,tF=120;function rF({children:e,open:t,onOpenChange:r,onClose:n,closeLabel:a,closeTitle:c,compact:l}){const d=b.useRef(null),p=b.useRef(null),m=b.useRef(0),[x,y]=b.useState(null),w=x??(t?Fd:0);return b.useEffect(()=>{if(!t)return;const v=S=>{S.target instanceof Node&&!d.current?.contains(S.target)&&r(!1)};return document.addEventListener("pointerdown",v,!0),()=>document.removeEventListener("pointerdown",v,!0)},[t,r]),s.jsxs("div",{ref:d,"data-sidebar-gesture-ignore":!0,"data-session-swipe":!0,className:`relative flex min-w-0 flex-1 items-center ${l?"":"gap-1"}`,style:{touchAction:"pan-y"},onPointerDown:v=>{if(m.current=0,!(v.pointerType!=="touch"&&v.pointerType!=="pen")){if(v.isPrimary===!1){p.current=null,y(null);return}!(v.target instanceof Element)||!v.target.closest(".sidebar-session-primary")||(p.current={pointerId:v.pointerId,x:v.clientX,y:v.clientY,startedAt:Date.now(),initialOffset:t?Fd:0,offset:t?Fd:0,horizontal:!1})}},onPointerMove:v=>{const S=p.current;if(!S||S.pointerId!==v.pointerId)return;const L=v.clientX-S.x,E=v.clientY-S.y;if(!S.horizontal){if(v.defaultPrevented||Date.now()-S.startedAt>=tF||Math.abs(E)>Mb){p.current=null;return}if(Math.abs(L)<=Mb)return;if(Math.abs(L)<Math.abs(E)*1.5||!t&&L<0){p.current=null;return}S.horizontal=!0,v.currentTarget.setPointerCapture?.(v.pointerId)}v.preventDefault(),S.offset=Math.max(0,Math.min(Fd,S.initialOffset+L)),y(S.offset)},onPointerUp:v=>{const S=p.current;!S||S.pointerId!==v.pointerId||(p.current=null,S.horizontal&&(m.current=Date.now()+600,r(S.offset>=Fd/2),y(null)))},onPointerCancel:()=>{p.current?.horizontal&&(m.current=Date.now()+600),p.current=null,y(null)},onClickCapture:v=>{if(Date.now()<m.current){m.current=0,v.preventDefault(),v.stopPropagation();return}t&&v.target instanceof Element&&v.target.closest(".sidebar-session-primary")&&(r(!1),v.preventDefault(),v.stopPropagation())},onKeyDown:v=>{t&&v.key==="Escape"&&(v.stopPropagation(),r(!1))},children:[s.jsx("div",{className:"shrink-0 overflow-hidden rounded-md transition-[width] duration-150 ease-out motion-reduce:transition-none",style:{width:w,transition:x===null?void 0:"none"},children:w>0&&s.jsxs("button",{type:"button",tabIndex:t?0:-1,"aria-hidden":!t,"aria-label":c,className:"flex min-h-8 w-16 flex-col items-center justify-center gap-0.5 bg-destructive py-1 text-[10px] text-destructive-foreground",onClick:v=>{v.stopPropagation(),r(!1),n(v)},children:[s.jsx(Rs,{size:14}),a]})}),e]})}const jb="recoverable-tmux";function nF({sessions:e,loading:t,attachingName:r,onRefresh:n,onRestore:a,onClose:c}){const{t:l}=Ur(),d=Wt(R=>R.collapsedGroups.has(jb)),p=Wt(R=>R.toggleGroupCollapsed),[m,x]=b.useState(null),[y,w]=b.useState(null),[v,S]=b.useState(null),L=b.useRef(!1),E=async R=>{if(!(!c||L.current)){L.current=!0,w(R),S(null);try{await c(R),x(null)}catch(B){S(B instanceof Error?B.message:l("sidebar.closeRecoverableSessionFailed"))}finally{L.current=!1,w(null)}}};return e.length===0?null:s.jsxs("section",{className:"mb-2 shrink-0 rounded-lg bg-[rgb(var(--tmux-rgb)_/_0.07)] p-1","aria-label":l("sidebar.recoverableSessions"),children:[s.jsxs("div",{className:"flex items-center gap-1 text-[10.5px] font-semibold text-[color:var(--tmux)]",children:[s.jsxs("button",{type:"button","aria-expanded":!d,onClick:()=>p(jb),className:"flex min-h-11 min-w-0 flex-1 items-center gap-2 rounded-md px-2 text-left hover:bg-surface-elevated md:min-h-8",children:[s.jsx(Ks,{size:12,className:`shrink-0 ${d?"":"rotate-90"}`}),s.jsx(Qc,{size:12,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:l("sidebar.recoverableSessions")}),s.jsx("span",{className:"text-muted-foreground",children:e.length})]}),n&&s.jsx("button",{type:"button",onClick:n,disabled:t||y!==null,className:"inline-flex h-11 w-11 shrink-0 items-center justify-center rounded-md text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground disabled:opacity-50 md:h-7 md:w-7","aria-label":l("sidebar.refreshRecoverableSessions"),title:l("sidebar.refreshRecoverableSessions"),children:s.jsx(bn,{size:11,className:t?"animate-spin":""})})]}),!d&&s.jsx("div",{className:"space-y-0.5",children:e.map(R=>{const B=R.friendlyName?.trim()||R.label?.trim()||R.name,z=Ku(R.cwd??null),O=r===R.name,$=m===R.name;return s.jsxs("div",{children:[s.jsxs("div",{className:"flex min-w-0 items-center",children:[s.jsxs("button",{type:"button",disabled:r!==null||y!==null||$,onClick:()=>a(R),className:"group flex min-h-11 min-w-0 flex-1 items-center gap-2 rounded-md px-2 text-left text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground disabled:opacity-60 md:min-h-10","aria-label":l("sidebar.restoreRecoverableSession",{name:B}),title:R.cwd||R.name,children:[s.jsx("span",{className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-[rgb(var(--tmux-rgb)_/_0.11)] text-[color:var(--tmux)]",children:O?s.jsx(_n,{size:12,className:"animate-spin"}):s.jsx(qc,{size:12})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block truncate text-[11.5px] font-semibold text-foreground",children:B}),s.jsx("span",{className:"block truncate text-[9.5px] text-muted-foreground",children:[R.program,z].filter(Boolean).join(" · ")||`tmux:${R.name}`})]}),s.jsx("span",{className:"shrink-0 text-[10px] font-medium text-[color:var(--tmux)] group-hover:text-foreground",children:l(O?"sidebar.restoringRecoverableSession":"sidebar.restore")})]}),c&&s.jsx("button",{type:"button",disabled:r!==null||y!==null,onClick:()=>{x(R.name),S(null)},className:"inline-flex h-11 w-11 shrink-0 items-center justify-center rounded-md text-muted-foreground transition hover:bg-destructive/15 hover:text-destructive disabled:opacity-50 md:h-7 md:w-7","aria-label":l("sidebar.closeSession",{name:B}),title:l("sidebar.closeSession",{name:B}),children:s.jsx(In,{size:12})})]}),$&&s.jsxs("div",{role:"group","aria-label":l("sidebar.closeSession",{name:B}),className:"space-y-2 rounded-md bg-surface px-2 py-2",children:[s.jsx("p",{className:"text-[11px] text-foreground",children:l("sidebar.confirmCloseRecoverableSession",{name:B})}),v&&s.jsx("p",{role:"alert",className:"text-[11px] text-destructive",children:v}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{type:"button",disabled:y!==null,onClick:()=>{x(null),S(null)},className:"min-h-11 rounded-md px-2 text-[11px] text-muted-foreground hover:bg-surface-elevated disabled:opacity-50 md:min-h-8",children:l("common.cancel")}),s.jsx("button",{type:"button",disabled:y!==null,onClick:()=>{E(R.name)},className:"min-h-11 rounded-md bg-destructive/15 px-2 text-[11px] text-destructive hover:bg-destructive/25 disabled:opacity-50 md:min-h-8",children:y===R.name?l("common.loading"):l("sidebar.endRecoverableSession")})]})]})]},R.name)})})]})}const $d="flex min-h-11 w-full items-center gap-2.5 rounded-lg px-3 text-left text-xs transition hover:bg-surface-2 focus:bg-surface-2 focus:outline-none",Db="min-h-11 rounded-lg px-4 text-xs transition disabled:opacity-40 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary";function sF({group:e,collapsed:t,onOpen:r,onMessages:n,onToggleCollapsed:a,onChanged:c,children:l}){const[d,p]=b.useState(null),[m,x]=b.useState(null),[y,w]=b.useState(""),[v,S]=b.useState(!1),L=b.useRef(!1),[E,R]=b.useState(""),B=b.useRef(null),z=b.useRef(null),O=b.useRef(null),$=b.useRef(null),V=b.useRef(null),Z=b.useId(),le=Cg(),be=()=>V.current?.isConnected?V.current:z.current,pe=()=>{L.current||(x(null),R(""))};Gc(O,!!d,()=>p(null),be),Gc($,!!m,pe,be);const ee=ce=>{V.current=document.activeElement instanceof HTMLElement&&B.current?.contains(document.activeElement)?document.activeElement:z.current;const qe=z.current?.getBoundingClientRect();p(ce??{x:qe?.left??8,y:qe?.bottom??8})};b.useEffect(()=>{d&&O.current?.querySelector('[role="menuitem"]')?.focus({preventScroll:!0})},[d]),b.useEffect(()=>{if(!d)return;const ce=we=>{we.target instanceof Node&&!O.current?.contains(we.target)&&!B.current?.contains(we.target)&&p(null)},qe=we=>{we.target instanceof Node&&O.current?.contains(we.target)||p(null)};return document.addEventListener("pointerdown",ce),window.addEventListener("resize",qe),window.addEventListener("scroll",qe,!0),()=>{document.removeEventListener("pointerdown",ce),window.removeEventListener("resize",qe),window.removeEventListener("scroll",qe,!0)}},[d]),b.useLayoutEffect(()=>{if(!d||!O.current)return;const ce=window.visualViewport,qe=(ce?.offsetLeft??0)+8,we=(ce?.offsetTop??0)+8,ye=Math.min(240,(ce?.width??innerWidth)-16),Le=we+(ce?.height??innerHeight)-16;Object.assign(O.current.style,{width:`${ye}px`,maxHeight:`${Le-we}px`,left:`${Math.max(qe,Math.min(d.x,qe+(ce?.width??innerWidth)-16-ye))}px`,top:`${Math.max(we,Math.min(d.y,Le-O.current.offsetHeight))}px`})},[d]);const _e=ce=>{p(null),ce()},ze=ce=>{R(""),w(e.name),x({kind:ce,group:e})},Y=async()=>{if(!(!m||L.current||m.kind==="rename"&&!y.trim())){L.current=!0,S(!0),R("");try{const ce=m.group,qe=m.kind==="delete"?(await Ey(ce.id,ce.updatedAt),null):(await Ml({id:ce.id,name:y.trim(),sessionIds:ce.sessionIds,expectedUpdatedAt:ce.updatedAt})).group;x(null),c(qe)}catch(ce){const qe=ce instanceof Error?ce.message:"操作失败,请重试";R(qe.includes("协作组已变化")?"协作组刚刚发生变化,请取消后重新打开操作。":qe)}finally{L.current=!1,S(!1)}}};return s.jsxs("div",{ref:B,className:"flex min-w-0 items-center","data-sidebar-gesture-ignore":!0,...le(()=>ee()),onContextMenu:ce=>{ce.preventDefault(),ce.stopPropagation(),ee({x:ce.clientX,y:ce.clientY})},onKeyDown:ce=>{(ce.key==="ContextMenu"||ce.shiftKey&&ce.key==="F10")&&(ce.preventDefault(),ce.stopPropagation(),ee())},children:[l,s.jsx("button",{ref:z,type:"button","aria-label":`协作组操作:${e.name}`,title:"协作组操作","aria-haspopup":"menu","aria-expanded":!!d,"aria-controls":d?`${Z}-menu`:void 0,className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-surface-elevated hover:text-foreground focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary md:h-[30px] md:w-7",onClick:ce=>{ce.stopPropagation(),d?p(null):ee()},children:s.jsx(To,{size:14})}),d&&Xs.createPortal(s.jsxs("div",{ref:O,id:`${Z}-menu`,role:"menu",tabIndex:-1,"aria-label":`协作组操作:${e.name}`,"data-sidebar-gesture-ignore":!0,className:"fixed z-popover overflow-y-auto overscroll-contain rounded-xl border border-border/15 bg-surface p-1 shadow-[0_12px_32px_var(--app-shadow-soft)]",onKeyDown:ce=>{const qe=Array.from(ce.currentTarget.querySelectorAll('[role="menuitem"]:not(:disabled)')),we=qe.indexOf(document.activeElement),ye=ce.key==="ArrowDown"?(we+1)%qe.length:ce.key==="ArrowUp"?(we-1+qe.length)%qe.length:ce.key==="Home"?0:ce.key==="End"?qe.length-1:null;ye!==null&&(ce.preventDefault(),ce.stopPropagation(),qe[ye]?.focus({preventScroll:!0})),ce.key==="Tab"&&(ce.preventDefault(),p(null))},children:[s.jsxs("button",{role:"menuitem",tabIndex:-1,className:$d,onClick:()=>_e(r),children:[s.jsx(qc,{size:15}),"打开看板"]}),s.jsxs("button",{role:"menuitem",tabIndex:-1,disabled:!n,className:`${$d} disabled:opacity-40`,onClick:()=>_e(()=>n?.()),children:[s.jsx(Xu,{size:15}),"成员与消息"]}),s.jsxs("button",{role:"menuitem",tabIndex:-1,className:$d,onClick:()=>_e(a),children:[s.jsx(Ks,{size:15,className:t?"":"rotate-90"}),t?"展开成员会话":"收起成员会话"]}),s.jsxs("button",{role:"menuitem",tabIndex:-1,className:$d,onClick:()=>_e(()=>ze("rename")),children:[s.jsx(ju,{size:15}),"重命名协作组"]}),s.jsx("div",{role:"separator",className:"mx-2 my-1 h-px bg-border/30"}),s.jsxs("button",{role:"menuitem",tabIndex:-1,className:`${$d} text-destructive`,onClick:()=>_e(()=>ze("delete")),children:[s.jsx(Rs,{size:15}),"删除协作组"]})]}),document.body),m&&Xs.createPortal(s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-modal-backdrop bg-black/50 backdrop-blur-sm",onClick:pe}),s.jsxs("section",{ref:$,role:"dialog","aria-modal":"true","aria-labelledby":`${Z}-title`,"aria-describedby":`${Z}-description`,tabIndex:-1,className:"fixed left-1/2 top-1/2 z-modal-panel max-h-[calc(100dvh-2rem)] w-[min(24rem,calc(100vw-2rem))] -translate-x-1/2 -translate-y-1/2 overflow-y-auto rounded-2xl border border-border/15 bg-surface p-4 text-foreground shadow-[0_28px_70px_var(--app-shadow-strong)]",children:[s.jsxs("header",{className:"flex items-center gap-2",children:[s.jsx("h2",{id:`${Z}-title`,className:"min-w-0 flex-1 text-sm font-semibold",children:m.kind==="delete"?"删除协作组":"重命名协作组"}),s.jsx("button",{type:"button","aria-label":"关闭协作组操作",disabled:v,className:"flex h-11 w-11 items-center justify-center rounded-lg hover:bg-surface-2",onClick:pe,children:s.jsx(In,{size:16})})]}),s.jsx("p",{id:`${Z}-description`,className:"my-3 break-words text-xs leading-6 text-muted-foreground",children:m.kind==="delete"?s.jsxs(s.Fragment,{children:["确定删除“",m.group.name,"”?协作组及组内消息会被移除,成员终端会保留。此操作无法撤销。",m.group.federated&&"删除会同步到其他服务。"]}):"修改协作组的名称。"}),s.jsxs("form",{onSubmit:ce=>{ce.preventDefault(),Y()},children:[m.kind==="rename"&&s.jsxs("label",{className:"block text-xs text-muted-foreground",children:["协作组名称",s.jsx("input",{autoFocus:!0,required:!0,maxLength:256,disabled:v,className:"mt-2 min-h-11 w-full rounded-lg border border-border/30 bg-surface-2 px-3 text-sm text-foreground outline-none focus:border-primary",value:y,onChange:ce=>w(ce.target.value)})]}),E&&s.jsx("p",{role:"alert",className:"mt-3 break-words text-xs leading-5 text-destructive",children:E}),s.jsxs("footer",{className:"mt-4 flex justify-end gap-2",children:[s.jsx("button",{type:"button",disabled:v,className:`${Db} bg-surface-2`,onClick:pe,children:"取消"}),s.jsxs("button",{type:"submit",disabled:v||m.kind==="rename"&&!y.trim(),className:`${Db} inline-flex items-center gap-2 ${m.kind==="delete"?"bg-destructive text-destructive-foreground":"bg-primary text-primary-foreground"}`,children:[v&&s.jsx(bn,{size:14,className:"animate-spin"}),v?m.kind==="delete"?"正在删除…":"正在保存…":m.kind==="delete"?"确认删除":"保存名称"]})]})]})]})]}),document.body)]})}function iF(e,t){return qy(e,t)}function Ud(e,t){const r=new Set(e),n=t.filter(c=>c.sessionIds.length>=2&&c.sessionIds.every(l=>r.has(l))),a=new Set;return e.flatMap(c=>{const l=n.find(d=>d.sessionIds.includes(c));return l?a.has(l.id)?[]:(a.add(l.id),[{sessionIds:l.sessionIds,workspace:l}]):[{sessionIds:[c]}]})}function zd(e,t,r,n=[]){const a=new Map,c=new Map,l=new Set(e.map(x=>x.id));for(const x of n){const y=x.sessionIds.filter(v=>l.has(v));if(!y.length)continue;const w=y.length===x.sessionIds.length?x:{...x,sessionIds:y};y.forEach(v=>a.set(v,w))}for(const x of t)if(!(x.sessionIds.length<2||!x.sessionIds.every(y=>l.has(y)))&&!x.sessionIds.some(y=>a.has(y)))for(const y of x.sessionIds)c.set(y,x);const d=new Set,p=new Set,m=[];for(const x of e){const y=a.get(x.id);if(y){if(d.has(y.id))continue;d.add(y.id);const S=y.sessionIds.flatMap(L=>{const E=r.get(L);return E?[E]:[]});m.push({kind:"collaboration",id:`collaboration:${y.id}`,group:y,members:S,sessionIds:y.sessionIds});continue}const w=c.get(x.id);if(!w){m.push({kind:"session",id:`session:${x.id}`,session:x,sessionIds:[x.id]});continue}if(p.has(w.id))continue;p.add(w.id);const v=w.sessionIds.flatMap(S=>{const L=r.get(S);return L?[L]:[]});m.push({kind:"workspace",id:`workspace:${w.id}`,workspace:w,members:v,sessionIds:w.sessionIds})}return m}function Bb(e,t,r){const n=Math.min(e.length,Math.max(0,r)),a=e.slice(0,n).flatMap(l=>l.sessionIds.filter(d=>d!==t)),c=e.slice(n).flatMap(l=>l.sessionIds.filter(d=>d!==t));return[...a,t,...c]}function aF({status:e,detail:t,needsReview:r,inCopyMode:n}){return s.jsx(UP,{status:e,detail:t,needsReview:r,inCopyMode:n})}function Qb({isOpen:e,drawerWidthPx:t,onClose:r,onOpen:n,sessions:a,activeSessionId:c,sessionStates:l,onJumpToNextAttention:d,onNewSession:p,onCloseSession:m,onSplitSession:x,onCloseSplit:y,onRemoveFromSplit:w,splitWorkspaces:v,onSetSplitLayout:S,onReorderSplitWorkspace:L,onCombineSplitSessions:E,onReorderSessions:R,onSessionMenu:B,onOpenSettings:z,onOpenQuota:O,updateState:$,updateActionPending:V=!1,onConfirmUpdateRestart:Z,onRetryUpdate:le,serverHealthState:be,tmuxAvailable:pe=!0,defaultSessionMode:ee="shell",push:_e,pinned:ze,onTogglePinned:Y,recoverableTmuxSessions:ce=[],recoverableTmuxSessionsLoading:qe=!1,onRefreshRecoverableTmuxSessions:we,onCloseRecoverableTmuxSession:ye}){const{t:Le}=Ur(),[,Be]=b.useState(0),[ne,Fe]=b.useState(null),[ke,Ee]=b.useState(!1),[Pe,Ne]=b.useState(!1),[oe,We]=b.useState(null),nt=b.useRef(!1),gt=b.useRef(0),ue=b.useCallback(G=>{G||(gt.current+=1),Ee(G)},[]),[Ze,at]=b.useState(!1),Ie=Ei(G=>G.groupId),[Ge,Ce]=b.useState({}),H=Ze||Object.keys(Ge).length>0,ae=b.useRef(!1),Ae=b.useRef(!1),[Ye,et]=b.useState(null);b.useEffect(()=>{let G=!1;return fc().then(Me=>{G||ae.current||Ce(Object.fromEntries(r3(Me.collaborationPanels?.[Uf()]).map($e=>[$e,!0])))}).catch(()=>{}),()=>{G=!0}},[]);const St=async(G,Me)=>{ae.current=!0,await Fa({floatingGroupId:Me},G),Ce($e=>({...$e,[G]:Me!==null}))},[Gt,Qt]=b.useState([]),[wt,zt]=b.useState(!1),[Vt,Kt]=b.useState(null),[Ot,It]=b.useState(null),[xe,Ve]=b.useState(null),[ht,q]=b.useState(null),ut=Lu(G=>G.tasks),qt=Lu(G=>G.allTasks),[tt,De]=b.useState(0),[nr,Ke]=b.useState(null),_t=b.useRef(!1),[$t,yt]=b.useState({}),xt=Lu(G=>G.error),[Rt,Ct]=b.useState(!1);b.useEffect(()=>{const G=()=>{document.hidden||Lu.getState().refresh()};G();const Me=window.setInterval(G,5e3);return document.addEventListener("visibilitychange",G),()=>{clearInterval(Me),document.removeEventListener("visibilitychange",G)}},[]);const fr=async G=>(ue(!1),ae.current=!0,G?(Ei.getState().open(G),Qr(),!0):(at(!0),Qr(),!0)),Yt=df(G=>G.collaborationGroups),Sr=df(G=>G.setCollaborationGroups),[pn,dr]=b.useState({mode:ee}),{preference:me,agents:Gr,detecting:ot,refresh:pt,selectAgent:ir}=gO(),Mn=b.useRef(null),Xr=!!($?.latestVersion&&["installing","ready","restarting","error"].includes($.status)),je=!!be?.attention,st=[Le("sidebar.moreActions"),je?Le("sidebar.serverAttention"):null,Xr&&$?.latestVersion?Le("sidebar.updateAvailable",{version:$.latestVersion}):null].filter(Boolean).join(": "),bt=Wt(G=>G.groupByFolder),Br=Wt(G=>G.collapsedGroups),Vr=Wt(G=>G.toggleGroupCollapsed),Cr=b.useRef(null),qr=b.useRef(null),mn=b.useRef(null),on=b.useRef(0),zr=b.useRef(!1),un=b.useRef(null),Er=b.useRef(null),[re,mt]=b.useState(!1),Mt=b.useRef([]),rr=b.useRef(null),Ar=b.useRef(null),Fr=b.useRef(new Set),Xt=b.useRef(null),Zr=b.useMemo(()=>new Set(v.flatMap(G=>G.sessionIds)),[v]),Jt=b.useMemo(()=>new Map(a.map(G=>[G.id,G])),[a]),Pr=b.useMemo(()=>iF(Yt,new Set(Jt.keys())),[Yt,Jt]),Hr=b.useCallback(async()=>{const G=++on.current;try{const Me=await Q1();if(G!==on.current)return;Sr(Array.isArray(Me.groups)?Me.groups:[])}catch{}},[]);b.useEffect(()=>Ny(G=>Sr(G.groups)),[]),b.useEffect(()=>{Hr();const G=window.setInterval(()=>{Hr()},1e4),Me=()=>{Hr()};return window.addEventListener("focus",Me),()=>{on.current+=1,window.clearInterval(G),window.removeEventListener("focus",Me)}},[Hr]),b.useEffect(()=>{(e||!H)&&Hr()},[H,e,Hr]);const ps=b.useCallback(()=>{Mt.current=Array.from(document.querySelectorAll("[data-collaboration-member], [data-collaboration-background]")).flatMap(G=>{const Me=G.dataset.collaborationMember??"",$e=G.hasAttribute("data-collaboration-background"),Je=G.closest("[data-collaboration-group]")?.dataset.collaborationGroup;if(!Me&&!$e||!Je)return[];const it=[];for(let Tt=G.parentElement;Tt;Tt=Tt.parentElement)it.push({element:Tt,top:Tt.scrollTop,left:Tt.scrollLeft});return[{element:G,sessionId:Me,groupId:Je,background:$e,rect:G.getBoundingClientRect(),scrollParents:it}]})},[]),Mr=b.useCallback((G,Me)=>{if(!zr.current)return;document.querySelectorAll("[data-split-exit-drop-index]").forEach(K=>K.removeAttribute("data-active")),document.querySelectorAll("[data-drop-active]").forEach(K=>K.removeAttribute("data-drop-active"));const Je=document.elementsFromPoint(G,Me).map(K=>K.closest("[data-collaboration-background]")).find(Boolean)?.closest("[data-collaboration-group]");if(Je?.dataset.collaborationGroup){Je.dataset.dropActive="true",Ar.current={kind:"collaboration",groupId:Je.dataset.collaborationGroup,background:!0};return}const it=Mt.current.find(K=>{if(K.sessionId===Er.current||!K.element.isConnected)return!1;const fe=K.scrollParents.reduce((ve,lt)=>ve+lt.element.scrollLeft-lt.left,0),Qe=K.scrollParents.reduce((ve,lt)=>ve+lt.element.scrollTop-lt.top,0);return G>=K.rect.left-fe&&G<=K.rect.right-fe&&Me>=K.rect.top-Qe+K.rect.height*.25&&Me<=K.rect.bottom-Qe-K.rect.height*.25});if(it?.background){it.element.closest("[data-collaboration-group]")?.setAttribute("data-drop-active","true"),Ar.current={kind:"collaboration",groupId:it.groupId,background:!0};return}if(it&&!v.find(fe=>fe.sessionIds.includes(it.sessionId))?.sessionIds.includes(Er.current??"")){it.element.dataset.dropActive="true",Ar.current={kind:"split",sessionId:it.sessionId,groupId:it.groupId};return}const Tt=document.elementsFromPoint(G,Me).filter(K=>{const fe=K.closest("[data-rfd-draggable-id]");return!fe||!["session:","split-member:","collaboration-member:"].some(Qe=>fe.dataset.rfdDraggableId===`${Qe}${Er.current}`)}),kt=Tt.map(K=>K.closest("[data-collaboration-group]")).find(K=>K?.dataset.collaborationGroup);if(kt?.dataset.collaborationGroup){const K=kt.dataset.collaborationGroup,fe=Tt.map(vt=>vt.closest("[data-collaboration-split]")).find(Boolean),Qe=Tt.map(vt=>vt.closest("[data-collaboration-member]")).find(Boolean),ve=Qe?.dataset.collaborationMember??fe?.dataset.splitAnchor,lt=K===un.current&&v.some(vt=>vt.sessionIds.includes(ve??"")&&vt.sessionIds.includes(Er.current??""));if(ve&&!lt&&(K!==un.current||!Qe&&fe)){kt.dataset.dropActive="true";const vt=Qe??fe;vt&&(vt.dataset.dropActive="true"),Ar.current={kind:"split",sessionId:ve,groupId:K}}else{const vt=Tt.some(br=>br.closest("[data-collaboration-background]"));(K!==un.current||vt)&&(kt.dataset.dropActive="true"),Ar.current={kind:"collaboration",groupId:K,background:vt}}return}const ft=Array.from(document.querySelectorAll("[data-sidebar-entity-list-id]")).filter(K=>K.dataset.sidebarEntityListId===rr.current).find(K=>{const fe=K.getBoundingClientRect();return G>=fe.left&&G<=fe.right&&Me>=fe.top-8&&Me<=fe.bottom+8});if(!ft){Ar.current=null;return}const Bt=Array.from(ft.children).filter(K=>K instanceof HTMLElement&&K.hasAttribute("data-sidebar-entity-index")),W=Bt.findIndex(K=>{const fe=K.getBoundingClientRect();return Me<fe.top+fe.height/2}),N=W<0?Bt.length:W;Ar.current={kind:"list",listId:ft.dataset.sidebarEntityListId??"",index:N};const U=Array.from(ft.querySelectorAll(":scope > [data-sidebar-entity-index] > [data-split-exit-drop-index]")).find(K=>K.dataset.splitExitDropIndex===String(N));U instanceof HTMLElement&&(U.dataset.active="true")},[v]);b.useEffect(()=>{const G=$e=>Mr($e.clientX,$e.clientY),Me=$e=>{const Je=$e.touches[0];Je&&Mr(Je.clientX,Je.clientY)};return window.addEventListener("pointermove",G),window.addEventListener("touchmove",Me,{passive:!0}),()=>{window.removeEventListener("pointermove",G),window.removeEventListener("touchmove",Me)}},[Mr]);const jn=b.useCallback((G,Me)=>{try{G(Me)}finally{document.querySelectorAll("[data-sidebar-dragging]").forEach($e=>{delete $e.dataset.sidebarDragging}),zr.current=!1,Mt.current=[],mt(!1),un.current=null,Er.current=null,rr.current=null,Ar.current=null,document.querySelectorAll("[data-split-exit-drop-index]").forEach($e=>$e.removeAttribute("data-active")),document.querySelectorAll("[data-drop-active]").forEach($e=>$e.removeAttribute("data-drop-active"))}},[]),Tr=b.useMemo(()=>a.filter(G=>!Zr.has(G.id)),[a,Zr]),Jr=b.useMemo(()=>{let G=0;for(const Me of a)l.get(Me.id)?.agentStatus==="working"&&(G+=1);return G},[a,l]);b.useLayoutEffect(()=>{const G=Cr.current,Me=qr.current;if(!e||!G||!Me){mn.current=null;return}const $e=Me.getBoundingClientRect(),Je=G.getBoundingClientRect(),it={item:G,top:Math.round(Je.top-$e.top+Me.scrollTop),height:Math.round(Je.height),viewportHeight:Me.clientHeight},Tt=mn.current;if(mn.current=it,Tt?.item===it.item&&Tt.top===it.top&&Tt.height===it.height&&Tt.viewportHeight===it.viewportHeight||zr.current||Me.clientHeight===0)return;const kt=8,Dt=Je.top-$e.top,ft=Je.bottom-$e.top;Dt<kt?Me.scrollTop+=Dt-kt:ft>Me.clientHeight-kt&&(Me.scrollTop+=ft-Me.clientHeight+kt)});const ln=b.useMemo(()=>{if(!bt||!c)return null;const G=l.get(c)?.cwd??null;return HS(G)},[bt,c,l]);b.useEffect(()=>{if(!bt){Xt.current=null,Fr.current.clear();return}if(!c){Xt.current=null;return}const G=Wt.getState(),Me=Fr.current,$e=Xt.current,Je=ln;$e!==null&&$e!==Je&&Me.has($e)&&(G.collapsedGroups.has($e)||G.toggleGroupCollapsed($e),Me.delete($e)),Je!==null&&Je!==""&&G.collapsedGroups.has(Je)&&(G.toggleGroupCollapsed(Je),Me.add(Je)),Xt.current=Je},[bt,c,ln]),b.useEffect(()=>{e||ue(!1)},[e]),b.useEffect(()=>{dr(G=>({...G,command:me?.command}))},[me]),b.useEffect(()=>{if(!ke)return;let G=!1;return zt(!0),It(null),lx().then(Me=>{G||Qt(Me)}).catch(()=>{G||It(Le("sidebar.resumeHistoryLoadFailed"))}).finally(()=>{G||zt(!1)}),()=>{G=!0}},[ke,Le]),b.useEffect(()=>{if(!ne)return;const G=Me=>{Me instanceof KeyboardEvent&&Me.key!=="Escape"||Me instanceof PointerEvent&&Me.target instanceof Node&&Mn.current?.contains(Me.target)||Fe(null)};return window.addEventListener("pointerdown",G),window.addEventListener("keydown",G),()=>{window.removeEventListener("pointerdown",G),window.removeEventListener("keydown",G)}},[ne]);const Qr=()=>{!_e&&!ze&&r()};b.useEffect(()=>{const G=Me=>{ue(!1);const{groupId:$e,dock:Je}=Me.detail;ae.current=!0,Kn.getState().setDock($e,{...Je,preferredWidth:360}),Ce(it=>({...it,[$e]:!0})),Ei.getState().terminal(),Qr()};return window.addEventListener("termdock:open-collaboration-messages",G),()=>window.removeEventListener("termdock:open-collaboration-messages",G)},[Qr]);const ks=ee==="tmux"&&!pe?"shell":ee,Dr=(G,Me=!1)=>{if(nt.current)return;nt.current=!0,Ne(!0),We(null);const $e=gt.current;p({...G,shouldActivate:()=>$e===gt.current&&(G.shouldActivate?.()??!0),onResult:Je=>{if(nt.current=!1,Ne(!1),!Je.ok){We(Je.error);return}$e===gt.current&&(Me&&ue(!1),Qr())}})},en=()=>{Dr({mode:ks})},xn=()=>{me&&Dr({mode:ks,command:me.command})},X=G=>{ue(!1),Ve(G.name),p({mode:"tmux",tmuxSessionName:G.name,cwd:G.cwd??void 0}),Qr()};b.useEffect(()=>{xe&&(ce.some(G=>G.name===xe)||Ve(null))},[xe,ce]);const He=(G,Me)=>{Dr({...pn,cwd:pn.cwd?.trim()||void 0,command:Me??G?.command},!0)},Nt=async G=>{Kt(G.id),It(null);try{const Me=await Ry(G.id);Dr({mode:"shell",cwd:Me.cwd,command:Me.command},!0)}catch(Me){const $e=Me&&typeof Me=="object"&&"code"in Me?String(Me.code??""):"";It(Le($e==="AGENT_SESSION_ACTIVE_ELSEWHERE"?"tab.resumeAgentConflict":"sidebar.resumeHistoryFailed"))}finally{Kt(null)}},Et=async G=>{Qt(Me=>Me.filter($e=>$e.id!==G));try{await u9(G)}catch{It(Le("sidebar.resumeHistoryRemoveFailed")),lx().then(Qt).catch(()=>{})}},tr=()=>{if(ke){ue(!1);return}nt.current||(gt.current+=1,nt.current||We(null),dr({mode:ee==="tmux"&&!pe?"shell":ee,cwd:c?l.get(c)?.cwd??void 0:void 0,command:me?.command}),ue(!0))},jr=b.useCallback(G=>{const Me=l.get(G);return Me?.agentStatus==="waiting"||Me?.agentNeedsReview?"bg-[rgb(var(--warning-rgb)_/_0.10)] text-foreground":Me?.agentStatus==="working"?"bg-[rgb(var(--success-rgb)_/_0.08)] text-foreground":Me?.inCopyMode?"bg-[rgb(var(--tmux-rgb)_/_0.08)] text-foreground":null},[l]),cr=Cg(),[Cn,Ls]=b.useState(null);b.useEffect(()=>{e||Ls(null)},[e]);const Xn=b.useCallback((G,Me,$e,Je,it)=>{const Tt=!Ie&&G.id===c,kt=Zr.has(G.id),Dt=!!($e&&kt),ft=l.get(G.id),Bt=Ku(ft?.cwd??null),W=ft?.shellTitle??r9(G.id),N=W===ft?.cwd||W===Bt?null:W,U=n9(G,ft?.activeProgram??null,null,s9,N,ft?.promptState??null),K=!!(ft?.tuiProgress&&ft.tuiProgress.state!=="remove"),Qe=ft?.promptState==="running"||ft?.agentStatus==="working"||K?"bg-[var(--success)]":ft?.agentStatus==="waiting"||ft?.agentNeedsReview?"bg-[var(--warning)]":ft?.inCopyMode?"bg-[var(--tmux)]":"bg-primary";return s.jsxs(rF,{open:Cn===G.id,onOpenChange:ve=>Ls(lt=>ve?G.id:lt===G.id?null:lt),onClose:ve=>m(G.id,ve,{skipConfirmation:!0}),closeLabel:Le("common.close"),closeTitle:Le("sidebar.closeSession",{name:U}),compact:$e,children:[s.jsxs("button",{ref:Tt?Cr:null,type:"button",...Me??{},onContextMenu:ve=>{B&&(ve.preventDefault(),B(G.id,{x:ve.clientX,y:ve.clientY}))},onClick:()=>{ue(!1),Ei.getState().terminal(),window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:G.id})),Qr()},className:`sidebar-session-primary relative min-w-0 flex flex-1 items-center overflow-hidden text-left ${Me?"cursor-grab active:cursor-grabbing ":""}${$e?"gap-1.5 py-0.5 pl-1.5 pr-0.5":"gap-1.5 py-1 pl-2 pr-1"}`,title:ft?.cwd??G.name,children:[Tt&&s.jsx("span",{className:`absolute inset-y-2 left-0 w-0.5 rounded-full ${Qe}`}),s.jsxs("span",{className:`relative inline-flex shrink-0 items-center justify-center rounded-md ${$e?"h-5 w-[22px]":"h-[22px] w-[22px]"} ${Tt?G.mode==="tmux"?"bg-[rgb(var(--tmux-rgb)_/_0.15)] text-[color:var(--tmux)]":"bg-primary/15 text-primary":G.mode==="tmux"?"bg-surface text-[rgb(var(--tmux-rgb)_/_0.80)]":"bg-surface text-muted-foreground"}`,children:[ft?.isConnecting||K&&!ft?.agentStatus?s.jsx(_n,{size:$e?10:11,className:"animate-spin"}):ft?.agent??cx(G.id)?s.jsx(Wc,{agent:ft?.agent??cx(G.id),size:$e?13:15}):G.mode==="tmux"?s.jsx(qc,{size:$e?10:11}):s.jsx($o,{size:$e?10:11}),s.jsx(aF,{status:ft?.agentStatus??null,detail:ft?.agentStatusDetail,needsReview:ft?.agentNeedsReview,inCopyMode:ft?.inCopyMode})]}),s.jsx("span",{className:`min-w-0 flex-1 truncate leading-tight ${$e?"text-[11px]":"text-[12px]"} ${Tt?"font-medium text-foreground":""} ${ft?.inCopyMode?"text-[color:var(--tmux)]":""}`,children:U}),s.jsx($5,{sessionIds:[G.id]})]}),Je,s.jsx("button",{type:"button",onClick:ve=>{ve.stopPropagation(),Dt?w(G.id):kt?y(G.id):x(G.id)},className:`sidebar-session-action inline-flex shrink-0 items-center justify-center rounded-md transition hover:bg-primary/15 hover:text-primary active:scale-95 ${$e?"h-6 w-6":"h-[26px] w-[26px]"} ${kt?"bg-primary/15 text-primary":"text-muted-foreground/70"}`,"aria-label":`${Le(Dt?"tab.splitRemovePane":kt?"tab.splitClose":"tab.split")} ${U}`,title:Le(Dt?"tab.splitRemovePane":kt?"tab.splitClose":"tab.split"),children:Dt?s.jsx(MS,{size:11}):s.jsx(Il,{size:12})}),it??s.jsx("button",{type:"button",onClick:ve=>{ve.stopPropagation(),m(G.id,ve)},className:`sidebar-session-action inline-flex shrink-0 items-center justify-center rounded-md text-muted-foreground/70 transition hover:bg-destructive/15 hover:text-destructive active:scale-95 ${$e?"h-6 w-6":"h-[26px] w-[26px]"}`,"aria-label":Le("sidebar.closeSession",{name:U}),title:Le("common.close"),children:s.jsx(In,{size:$e?11:12})})]})},[c,Zr,l,m,x,y,w,B,Le,Cn]),cn=b.useMemo(()=>cf(a,G=>l.get(G.id)?.cwd??null,bt,Le("sidebar.ungrouped"),v,Pr).groups,[Pr,bt,a,l,v,Le]),dn=b.useMemo(()=>zd(a,v,Jt,Pr),[Pr,a,Jt,v]),_r=b.useCallback(G=>{mt(G.draggableId.startsWith("collaboration:")||G.draggableId.startsWith("workspace:"));const Me=G.draggableId.replace(/^split-member:/,"");Er.current=G.draggableId.replace(/^(?:session|split-member|collaboration-member):/,"");const $e=G.type==="split-member"?v.find(Dt=>Dt.sessionIds.includes(Me)):null,Je=G.type==="collaboration-member"?G.source.droppableId.replace(/^collaboration-members:/,""):null,it=Je?Pr.find(Dt=>Dt.id===Je):null;zr.current=!!($e||it||G.type==="session"&&G.draggableId.startsWith("session:")),zr.current&&document.querySelectorAll("[data-collaboration-group]").forEach(Dt=>{Dt.dataset.sidebarDragging="true"}),un.current=it?.id??null;const Tt=$e?.sessionIds??it?.sessionIds??[],kt=Tt.length>0?cn.find(Dt=>Tt.every(ft=>Dt.sessions.some(Bt=>Bt.id===ft))):null;rr.current=bt?kt?`group-sessions:${kt.key}`:null:Tt.length>0?"sidebar-entities":null,Ar.current=null},[Pr,cn,bt,v]),Or=b.useCallback((G,Me,$e)=>{if(Me===$e)return;const Je=Me?Yt.find(ft=>ft.id===Me):null,it=$e?Yt.find(ft=>ft.id===$e):null;if($e&&!it)return;if(it){const ft=a.map(W=>W.id).filter(W=>W!==G);let Bt=-1;ft.forEach((W,N)=>{it.sessionIds.includes(W)&&(Bt=N)}),Bt>=0&&(ft.splice(Bt+1,0,G),R(ft))}const Tt=Je?.sessionIds.filter(ft=>ft!==G)??[],kt=it?[...it.sessionIds.filter(ft=>ft!==G),G]:[];Sr(ft=>ft.flatMap(Bt=>Bt.id===Me?[{...Bt,sessionIds:Tt}]:Bt.id===$e?[{...Bt,sessionIds:kt}]:[Bt])),q(null),(Je&&it?i9({sourceGroupId:Je.id,targetGroupId:it.id,sessionId:G,expectedSourceUpdatedAt:Je.updatedAt,expectedTargetUpdatedAt:it.updatedAt}):Je?Ml({id:Je.id,name:Je.name,sessionIds:Tt,expectedUpdatedAt:Je.updatedAt}):it?Ml({id:it.id,name:it.name,sessionIds:kt,expectedUpdatedAt:it.updatedAt}):Promise.resolve()).then(()=>Hr(),ft=>(q(ft instanceof Error?ft.message:"协作成员移动失败"),Hr()))},[Yt,Hr,a,R]),Gn=b.useCallback((G,Me,$e,Je=!1)=>{const it=Yt.find(fe=>fe.id===G);if(!it||Me===$e)return;const Tt=it.sessionIds.filter(fe=>!fe.startsWith("remote:")),kt=Ud(Tt,v).flatMap(fe=>fe.sessionIds),Dt=O5(qt,it.id),ft=Je&&!$t[it.id]?kt.filter(fe=>!Dt.has(fe)||fe===c||Zr.has(fe)):kt.slice(),Bt=new Set(ft),[W]=ft.splice(Me,1);if(!W)return;ft.splice($e,0,W);let N=0;const U=kt.map(fe=>Bt.has(fe)?ft[N++]:fe),K=v.find(fe=>fe.sessionIds.includes(W));if(K&&K.sessionIds.every(fe=>it.sessionIds.includes(fe))){const fe=U.filter(Qe=>K.sessionIds.includes(Qe));L(K.id,fe)}U.push(...it.sessionIds.filter(fe=>fe.startsWith("remote:"))),Sr(fe=>fe.map(Qe=>Qe.id===G?{...Qe,sessionIds:U}:Qe)),q(null),Ml({id:it.id,name:it.name,sessionIds:U,expectedUpdatedAt:it.updatedAt}).then(()=>Hr(),fe=>(q(fe instanceof Error?fe.message:"成员排序失败"),Hr()))},[Yt,Hr,v,L,qt,$t,c,Zr]);b.useEffect(()=>{const G=Me=>{const{sourceId:$e,targetId:Je}=Me.detail;if(!$e||!Je||$e===Je)return;const it=cf(a,ve=>l.get(ve.id)?.cwd??null,bt,"",v,Pr).arranged.map(ve=>ve.id),Tt=it.indexOf($e),kt=it.indexOf(Je);if(Tt<0||kt<0)return;const Dt=Pr.find(ve=>ve.sessionIds.includes($e));if(Dt?.sessionIds.includes(Je)){const ve=Ud(Dt.sessionIds,v).flatMap(lt=>lt.sessionIds);Gn(Dt.id,ve.indexOf($e),ve.indexOf(Je));return}const ft=v.filter(ve=>ve.sessionIds.length>=2&&ve.sessionIds.every(lt=>Jt.has(lt))&&!Pr.some(lt=>ve.sessionIds.some(vt=>lt.sessionIds.includes(vt)))),Bt=ft.find(ve=>ve.sessionIds.includes($e));if(Bt?.sessionIds.includes(Je)){const ve=[...Bt.sessionIds];ve.splice(ve.indexOf($e),1),ve.splice(Bt.sessionIds.indexOf(Je),0,$e),L(Bt.id,ve);return}const W=ve=>Pr.find(lt=>lt.sessionIds.includes(ve))?.sessionIds??ft.find(lt=>lt.sessionIds.includes(ve))?.sessionIds??[ve],N=new Set(W($e)),U=new Set(W(Je)),K=it.filter(ve=>!N.has(ve)),fe=K.flatMap((ve,lt)=>U.has(ve)?[lt]:[]),Qe=Tt<kt?Math.max(...fe)+1:Math.min(...fe);K.splice(Qe,0,...it.filter(ve=>N.has(ve))),R(K)};return window.addEventListener("reorder-navigation-session",G),()=>window.removeEventListener("reorder-navigation-session",G)},[a,l,bt,v,Pr,Jt,Gn,L,R]);const Vn=b.useCallback(G=>{if(G.type!=="collaboration-member")return!1;if(G.reason==="CANCEL")return!0;const Me=G.source.droppableId.replace(/^collaboration-members:/,""),$e=G.draggableId.replace(/^collaboration-member:/,""),Je=Ar.current;if(Je?.kind==="split")return Or($e,Me,Je.groupId),E(Je.sessionId,$e),!0;if(Je?.kind==="collaboration"&&Je.groupId!==Me)return Or($e,Me,Je.groupId),!0;if(Je?.kind==="collaboration"&&Je.background)return Zr.has($e)&&w($e),!0;if(G.destination&&G.destination.droppableId!==G.source.droppableId){const it=G.destination.droppableId.replace(/^collaboration-members:/,"");if(Pr.some(Tt=>Tt.id===it))return Or($e,Me,it),!0}if(G.combine){const it=G.combine.droppableId.replace(/^collaboration-members:/,"");it!==Me&&Or($e,Me,it);const Tt=G.combine.draggableId.replace(/^collaboration-member:/,"");if(v.find(Dt=>Dt.sessionIds.includes($e))?.sessionIds.includes(Tt)){const Dt=Pr.find(Bt=>Bt.id===Me),ft=Dt?Ud(Dt.sessionIds,v).flatMap(Bt=>Bt.sessionIds).indexOf(Tt):-1;ft>=0&&Dt&&Gn(Me,Ud(Dt.sessionIds,v).flatMap(Bt=>Bt.sessionIds).indexOf($e),ft)}else Jt.has(Tt)&&E(Tt,$e);return!0}if(G.destination?.droppableId===G.source.droppableId)return Gn(Me,G.source.index,G.destination.index,!0),!0;if(Je?.kind!=="list")return!0;if(Je?.kind==="list"){const it=cn.find(kt=>`group-sessions:${kt.key}`===Je.listId),Tt=Je.listId==="sidebar-entities"?dn:it?zd(it.sessions,v,Jt,Pr):null;if(Tt){const kt=Bb(Tt,$e,Je.index);Je.listId==="sidebar-entities"?R(kt):it&&R(cn.flatMap(Dt=>Dt.key===it.key?kt:Dt.sessions.map(ft=>ft.id)))}}return Or($e,Me,null),!0},[Pr,dn,cn,Or,R,Gn,Jt,v,Zr,w,E]),gn=b.useCallback(G=>{if(G.type!=="split-member")return!1;if(G.reason==="CANCEL")return!0;const Me=G.draggableId.replace(/^split-member:/,""),$e=v.find(ft=>ft.sessionIds.includes(Me));if(!$e?.sessionIds.includes(Me))return!0;const Je=$e.id,it=Ar.current;if(it?.kind==="split")return Or(Me,null,it.groupId),E(it.sessionId,Me),!0;if(it?.kind==="collaboration")return Or(Me,null,it.groupId),!0;if(!G.destination&&it?.kind==="list"){const ft=cn.find(N=>`group-sessions:${N.key}`===it.listId),Bt=it.listId==="sidebar-entities"?dn:ft?zd(ft.sessions,v,Jt,Pr):null;if(!Bt)return!0;const W=Bb(Bt,Me,it.index);return w(Me),it.listId==="sidebar-entities"?R(W):ft&&R(cn.flatMap(N=>N.key===ft.key?W:N.sessions.map(U=>U.id))),!0}if(!G.destination)return!0;const Tt=G.destination.droppableId.replace(/^split-members:/,"");if(Tt!==Je){const Bt=v.find(W=>W.id===Tt)?.sessionIds[0];return Bt&&E(Bt,Me),!0}if(G.source.index===G.destination.index)return!0;const kt=[...$e.sessionIds],[Dt]=kt.splice(G.source.index,1);return Dt&&(kt.splice(G.destination.index,0,Dt),L(Je,kt)),!0},[Pr,dn,cn,Or,E,w,R,L,Jt,v]),Jn=(G,Me="top")=>s.jsx("div",{"data-split-exit-drop-index":G,className:`group/split-exit pointer-events-none absolute inset-x-0 z-10 h-2 ${Me==="top"?"-top-1":"-bottom-1"}`,children:s.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-x-1 top-1/2 h-px -translate-y-1/2 rounded-full bg-transparent transition-colors group-data-[active=true]/split-exit:bg-primary"})}),kr=b.useCallback((G,Me,$e)=>{if(Vn(G)||gn(G)||G.reason==="CANCEL")return;const Je=Me.find(ft=>ft.id===G.draggableId);if(!Je)return;const it=Ar.current;if(it?.kind==="split"&&Je.kind==="session"){Or(Je.session.id,null,it.groupId),E(it.sessionId,Je.session.id);return}if(it?.kind==="collaboration"&&Je.kind==="session"){Or(Je.session.id,null,it.groupId);return}if(G.combine&&Je.kind!=="session"){const ft=Me.findIndex(Bt=>Bt.id===G.combine?.draggableId);if(ft<0)return;G={...G,combine:null,destination:{...G.source,index:ft}}}if(G.combine){const ft=Me.find(K=>K.id===G.combine?.draggableId);if(!ft)return;const Bt=ft.kind==="workspace"?ft:Je.kind==="workspace"?Je:ft,W=Bt===Je?ft:Je,N=Bt.sessionIds[0],U=W.sessionIds[0];N&&U&&N!==U&&E(N,U);return}if(!G.destination||G.source.index===G.destination.index)return;const Tt=[...Me],[kt]=Tt.splice(G.source.index,1);if(!kt)return;Tt.splice(G.destination.index,0,kt);const Dt=Tt.flatMap(ft=>ft.sessionIds);if($e===void 0){R(Dt);return}R(cn.flatMap(ft=>ft.key===$e?Dt:ft.sessions.map(Bt=>Bt.id)))},[cn,Vn,gn,Or,E,R]),Lr=b.useCallback(G=>{if(G.reason==="CANCEL"||Vn(G)||gn(G))return;if(G.type==="group"){if(!G.destination||G.source.index===G.destination.index)return;R(Vy(cn,G.source.index,G.destination.index));return}const Me=G.source.droppableId.replace(/^group-sessions:/,""),$e=cn.find(it=>it.key===Me);if(!$e)return;const Je=zd($e.sessions,v,Jt,Pr);if(G.combine||Ar.current?.kind==="collaboration"||Ar.current?.kind==="split"){kr(G,Je,Me);return}!G.destination||G.destination.droppableId!==G.source.droppableId||kr(G,Je,Me)},[Pr,cn,Jt,v,Vn,kr,gn,R]),pr=G=>{const Me=ne===G.id,$e=[{layout:"horizontal",label:Le("tab.splitHorizontal"),icon:Il},{layout:"vertical",label:Le("tab.splitVertical"),icon:px},...G.sessionIds.length>=3||G.layout==="grid"?[{layout:"grid",label:Le("tab.splitGrid"),icon:fx}]:[]],Je=G.layout==="vertical"?px:G.layout==="grid"?fx:Il,it=$e.find(Tt=>Tt.layout===G.layout)?.label??Le("tab.splitHorizontal");return s.jsxs("div",{ref:Me?Mn:void 0,className:"relative shrink-0",onPointerDown:Tt=>Tt.stopPropagation(),children:[s.jsx("button",{type:"button",className:`sidebar-session-action inline-flex h-6 w-6 items-center justify-center rounded-md transition active:scale-95 ${Me?"bg-primary/15 text-primary":"text-muted-foreground/70 hover:bg-surface-2 hover:text-foreground"}`,"aria-label":`${Le("tab.splitLayout")}: ${it}`,"aria-haspopup":"menu","aria-expanded":Me,title:Le("tab.splitLayout"),onClick:Tt=>{Tt.stopPropagation(),Fe(kt=>kt===G.id?null:G.id)},children:s.jsx(Je,{size:12})}),Me&&s.jsx("div",{role:"menu","aria-label":Le("tab.splitLayout"),className:"absolute right-0 top-full z-30 mt-1 flex gap-0.5 rounded-md border border-border bg-surface-elevated p-1 shadow-lg",children:$e.map(Tt=>{const kt=Tt.icon,Dt=Tt.layout===G.layout;return s.jsx("button",{type:"button",role:"menuitemradio","aria-checked":Dt,"aria-label":Tt.label,title:Tt.label,className:`sidebar-session-action inline-flex h-7 w-7 items-center justify-center rounded-sm transition active:scale-95 ${Dt?"bg-primary/15 text-primary":"text-muted-foreground hover:bg-surface-2 hover:text-foreground"}`,onClick:ft=>{ft.stopPropagation(),S(G.sessionIds[0],Tt.layout),Fe(null)},children:s.jsx(kt,{size:13})},Tt.layout)})})]})},ns=(G,Me)=>Me&&s.jsx("button",{type:"button",...Me,"aria-label":G,title:G,onClick:$e=>$e.stopPropagation(),className:"absolute -left-2 inset-y-0 z-10 flex w-3 cursor-grab items-start justify-center pt-1.5 text-muted-foreground/60 transition hover:text-foreground focus-visible:text-foreground active:cursor-grabbing",children:s.jsx($f,{size:10})}),Un=(G,Me,$e=!1,Je=!1,it)=>{if(Me.length<2)return null;const Tt=Me.some(N=>N.id===c),kt=[],Dt=[],ft=[];for(const N of Me){const U=l.get(N.id);U?.agentStatus==="waiting"||U?.agentNeedsReview?kt.push(N):U?.agentStatus==="working"?Dt.push(N):U?.inCopyMode&&ft.push(N)}const Bt=G.name?.trim()||`${Le("tab.splitWorkspace")} ${v.findIndex(N=>N.id===G.id)+1}`,W=ne===G.id;return s.jsxs("section",{"data-split-workspace":G.id,"aria-label":Bt,className:`group/split relative rounded-md p-0.5 before:pointer-events-none before:absolute before:inset-0 before:rounded-md before:border before:border-border transition-colors ${Je?"bg-primary/15 ring-1 ring-primary/40":$e?"bg-surface-elevated opacity-90 shadow-lg":kt.length>0?"bg-[rgb(var(--warning-rgb)_/_0.08)] hover:bg-[rgb(var(--warning-rgb)_/_0.12)]":Dt.length>0?"bg-[rgb(var(--success-rgb)_/_0.06)] hover:bg-[rgb(var(--success-rgb)_/_0.10)]":ft.length>0?"bg-[rgb(var(--tmux-rgb)_/_0.07)] hover:bg-[rgb(var(--tmux-rgb)_/_0.11)]":Tt?"bg-primary/[0.07]":"hover:bg-surface-2"}`,children:[ns(`移动分屏组 ${Bt}`,it),s.jsx(Ll,{droppableId:`split-members:${G.id}`,type:"split-member",direction:"vertical",children:(N,U)=>s.jsxs("div",{ref:N.innerRef,...N.droppableProps,"data-split-members":!0,className:U.isDraggingOver?"rounded-sm bg-primary/10 ring-1 ring-primary/40":"",children:[Me.map((K,fe)=>s.jsx(kl,{draggableId:`split-member:${K.id}`,index:fe,disableInteractiveElementBlocking:!0,children:(Qe,ve)=>s.jsx("div",{ref:Qe.innerRef,...Qe.draggableProps,...B?cr(()=>B(K.id)):{},className:`${fe===0&&W?"relative z-20 ":"relative "}flex items-center rounded-sm pr-0.5 transition-colors ${ve.isDragging?"bg-surface-elevated opacity-90 shadow-lg ":""}${jr(K.id)??(K.id===c?"bg-surface-elevated/80 text-foreground":"text-muted-foreground hover:bg-surface-2")}`,children:Xn(K,Qe.dragHandleProps,!0,fe===0?pr(G):void 0)})},K.id)),N.placeholder]})})]})},En=(G,Me)=>{const $e=c??Me;Ae.current||!$e||(ue(!1),Ae.current=!0,et(G),q(null),dC(G,$e).catch(Je=>q(Je instanceof Error?Je.message:"消息面板打开失败,请重试")).finally(()=>{Ae.current=!1,et(null)}))},kn=(G,Me)=>{on.current+=1,Sr($e=>Me?$e.map(Je=>Je.id===G?Me:Je):$e.filter(Je=>Je.id!==G)),Me||(Ei.getState().groupId===G&&Ei.getState().terminal(),Kn.getState().setDock(G,null),Ce($e=>{const Je={...$e};return delete Je[G],Je}),requestAnimationFrame(()=>Cr.current?.focus({preventScroll:!0})),Fa({floatingGroupId:null},G).catch(()=>q("协作组已删除,面板布局保存失败,请刷新后检查。"))),Hr()},ss=(G,Me,$e,Je=!1,it=!1)=>{const Tt=`collaboration:${G.id}`,kt=Br.has(Tt),Dt=`collaboration-members-${G.id}`,ft=Ie===G.id||!Ie&&Me.some(ve=>ve.id===c),Bt=O5(qt,G.id),W=G.sessionIds.filter(ve=>Bt.has(ve)&&ve!==c&&!Zr.has(ve)),N=$t[G.id]===!0,U=N?G.sessionIds:G.sessionIds.filter(ve=>!W.includes(ve)),K=Ud(U,v),fe=K.flatMap(ve=>ve.sessionIds),Qe=K.length===1?K[0]?.workspace:void 0;return s.jsxs("section",{"data-collaboration-group":G.id,"data-collaboration-group-name":G.name,"aria-label":`Agent 工作组:${G.name}`,className:`group/collaboration relative rounded-md ${kt?"":"p-0.5 before:pointer-events-none before:absolute before:inset-0 before:rounded-md before:border before:border-border"} transition-colors data-[drop-active=true]:bg-primary/15 data-[drop-active=true]:ring-1 data-[drop-active=true]:ring-primary/40 ${it?"bg-primary/15 ring-1 ring-primary/40":Je?"bg-surface-elevated opacity-90 shadow-lg":ft?"bg-primary/[0.07]":"hover:bg-surface-2"}`,children:[ns(`移动工作组 ${G.name}`,$e),s.jsxs(sF,{group:Yt.find(ve=>ve.id===G.id)??G,collapsed:kt,onOpen:()=>{fr(G.id)},onMessages:Ye===null&&(c||Me.length)?()=>En(G.id,Me[0]?.id):void 0,onToggleCollapsed:()=>Vr(Tt),onChanged:ve=>kn(G.id,ve),children:[s.jsx("button",{type:"button","aria-label":`${kt?"展开":"收起"} ${G.name} 的成员会话`,"aria-expanded":!kt,"aria-controls":Dt,title:`${kt?"展开":"收起"}成员会话`,className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-surface-elevated hover:text-foreground focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary md:h-[30px] md:w-5",onClick:ve=>{ve.stopPropagation(),Vr(Tt)},children:s.jsx(Ks,{size:14,className:kt?"":"rotate-90"})}),s.jsxs("button",{type:"button",className:"flex min-h-11 min-w-0 flex-1 items-center gap-1.5 rounded-sm px-1 text-left text-xs font-medium text-foreground transition hover:text-primary md:min-h-[30px]",title:`打开 ${G.name} 的协作工作区`,"aria-label":`打开协作工作区:${G.name}`,"aria-current":Ie===G.id?"page":void 0,onClick:ve=>{ve.stopPropagation(),fr(G.id)},children:[s.jsx(nh,{size:14,className:"shrink-0 text-primary"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:G.name}),ut.some(ve=>ve.groupId===G.id)&&s.jsxs("span",{className:"shrink-0 text-[10px] font-normal text-primary",children:[ut.filter(ve=>ve.groupId===G.id).length," 待处理"]})]}),s.jsx("button",{type:"button","aria-label":`成员与消息:${G.name}`,title:"在终端旁打开成员与消息",disabled:Ye!==null||!c&&!Me.length,"aria-busy":Ye===G.id,className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-surface-elevated hover:text-primary disabled:opacity-40 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary md:h-[30px] md:w-7",onClick:ve=>{ve.stopPropagation(),En(G.id,Me[0]?.id)},children:Ye===G.id?s.jsx(bn,{size:14,className:"animate-spin"}):s.jsx(Xu,{size:14})})]}),s.jsx("div",{id:Dt,children:!kt&&s.jsxs(s.Fragment,{children:[W.length>0&&s.jsxs("button",{type:"button","aria-expanded":N,className:"flex min-h-11 w-full items-center gap-2 rounded-sm px-2 text-left text-[11px] text-muted-foreground hover:bg-surface-elevated md:min-h-8",title:"展开后可查看或归档执行会话,任务结果保留。",onClick:()=>yt(ve=>({...ve,[G.id]:!N})),children:[s.jsx(Ks,{size:12,className:N?"rotate-90":""}),"已完成的执行会话 · ",W.length]}),s.jsx(Ll,{droppableId:`collaboration-members:${G.id}`,type:"collaboration-member",direction:"vertical",isCombineEnabled:!0,children:(ve,lt)=>s.jsxs("div",{ref:ve.innerRef,...ve.droppableProps,"data-collaboration-members":!0,className:`${lt.isDraggingOver?"rounded-sm bg-primary/10":""}`,children:[K.map(vt=>s.jsx("div",{"data-collaboration-split":vt.workspace?.id,"data-split-anchor":vt.workspace?.sessionIds[0],role:vt.workspace?"region":void 0,"aria-label":vt.workspace?`${Le("tab.splitWorkspace")} · ${vt.sessionIds.length}`:void 0,className:vt.workspace&&!Qe?`relative my-0.5 rounded-sm before:pointer-events-none before:absolute before:inset-0 before:rounded-sm before:border before:border-border data-[drop-active=true]:ring-1 data-[drop-active=true]:ring-primary/40 ${vt.sessionIds.includes(c??"")?"bg-primary/[0.07]":"bg-surface/35"}`:void 0,children:vt.sessionIds.map(br=>{const Lt=Jt.get(br);return Lt?s.jsx(kl,{draggableId:`collaboration-member:${Lt.id}`,index:fe.indexOf(Lt.id),disableInteractiveElementBlocking:!0,children:(rn,yn)=>s.jsxs("div",{ref:rn.innerRef,...rn.draggableProps,"data-collaboration-member":Lt.id,"data-split-member":Zr.has(Lt.id)?"true":void 0,...B?cr(()=>B(Lt.id)):{},className:`${vt.workspace&&br===vt.sessionIds[0]&&ne===vt.workspace.id?"z-20 ":""}relative flex items-center rounded-sm pr-0.5 transition-colors data-[drop-active=true]:bg-primary/15 data-[drop-active=true]:ring-1 data-[drop-active=true]:ring-primary/40 ${yn.combineTargetFor?"bg-primary/15 ring-1 ring-primary/40 ":yn.isDragging?"bg-surface-elevated opacity-90 shadow-lg ":""}${jr(Lt.id)??(Lt.id===c?"bg-surface-elevated/80 text-foreground":Zr.has(Lt.id)?"bg-primary/[0.05] text-muted-foreground hover:bg-primary/[0.09]":"text-muted-foreground hover:bg-surface-2")}`,children:[Xn(Lt,rn.dragHandleProps,!0,vt.workspace&&br===vt.sessionIds[0]?pr(vt.workspace):void 0,Bt.has(br)?s.jsxs("button",{type:"button","aria-label":`归档 ${Lt.name}`,title:"保存 Agent 会话 ID 并停止终端;只回收干净的执行目录,结果和分支保留",disabled:nr!==null,className:"sidebar-session-action inline-flex h-11 min-w-11 shrink-0 items-center justify-center gap-1 rounded-md px-2 text-muted-foreground hover:bg-primary/15 hover:text-primary disabled:opacity-40 md:h-6 md:min-w-6 md:px-1",onClick:hn=>{hn.stopPropagation(),!_t.current&&(_t.current=!0,Ke(br),q(null),c9(br).then(async()=>{De(Dn=>Dn+1),await Hr()}).catch(Dn=>q(Dn instanceof Error?Dn.message:"归档失败,终端已保留")).finally(()=>{_t.current=!1,Ke(null)}))},children:[nr===br?s.jsx(bn,{size:13,className:"animate-spin"}):s.jsx(My,{size:13}),s.jsx("span",{className:"text-[10px] md:sr-only",children:"归档"})]}):void 0),!vt.workspace&&Zr.has(Lt.id)&&s.jsx("button",{type:"button",className:"shrink-0 px-1 text-[10px] text-primary",title:`与 ${v.find(hn=>hn.sessionIds.includes(Lt.id))?.sessionIds.filter(hn=>hn!==Lt.id).map(hn=>Jt.get(hn)?.name??hn).join("、")} 分屏`,"aria-label":`查看 ${Lt.name} 的跨组分屏`,onClick:()=>{ue(!1),Ei.getState().terminal(),window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:Lt.id})),Qr()},children:s.jsx(Il,{size:10})})]})},Lt.id):null})},vt.workspace?.id??vt.sessionIds[0])),ve.placeholder]})}),s.jsx(tQ,{groupId:G.id,version:tt,onRestore:async ve=>{ue(!1),window.dispatchEvent(new CustomEvent("new-terminal-session",{detail:{mode:"tmux",cwd:ve.cwd,preferredFrontendSessionId:ve.sessionId,requireExisting:!0}})),await Hr(),Ei.getState().terminal(),Qr()}}),G.remoteSessions?.map(ve=>s.jsxs("button",{type:"button",title:`${uc(ve)} · ${ve.serviceConnected===!1?"服务不可达,消息尚未送达":ve.status}`,className:"flex w-full min-w-0 items-center gap-1.5 rounded-sm px-2 py-1 text-left text-[11px] text-muted-foreground hover:bg-surface-2",onClick:()=>{ue(!1),A6(ve.sessionId).catch(()=>{fr(G.id)})},children:[s.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${ve.serviceConnected===!1?"bg-muted-foreground":"bg-primary"}`}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:ve.name}),s.jsx("span",{className:"max-w-20 truncate rounded border border-border/20 px-1 text-[9px]",children:uc(ve)}),ve.serviceConnected===!1&&s.jsx("span",{className:"shrink-0 text-[9px]",children:"不可达"})]},ve.sessionId))]})}),s.jsx("div",{"data-collaboration-background":!0,className:kt?"absolute inset-0 pointer-events-none":"h-1.5"})]})},Wr=(G,Me,$e)=>s.jsx(h0,{onBeforeCapture:ps,onDragStart:_r,onDragEnd:Je=>jn(it=>kr(it,G,$e),Je),children:s.jsx(Ll,{droppableId:Me,direction:"vertical",isCombineEnabled:!re,children:Je=>s.jsxs("div",{ref:Je.innerRef,...Je.droppableProps,"data-sidebar-entity-list-id":Me,className:"flex-1 space-y-0.5",children:[G.map((it,Tt)=>s.jsx(kl,{draggableId:it.id,index:Tt,disableInteractiveElementBlocking:!0,children:(kt,Dt)=>s.jsxs("div",{ref:kt.innerRef,...kt.draggableProps,"data-sidebar-gesture-ignore":!0,"data-sidebar-entity-index":Tt,className:"relative",children:[Jn(Tt),Tt===G.length-1&&Jn(G.length,"bottom"),it.kind==="workspace"?Un(it.workspace,it.members,Dt.isDragging,!!Dt.combineTargetFor,kt.dragHandleProps):it.kind==="collaboration"?ss(it.group,it.members,kt.dragHandleProps,Dt.isDragging,!!Dt.combineTargetFor):s.jsx("div",{...B?cr(()=>B(it.session.id)):{},className:`group relative flex items-center gap-1 rounded-md pr-1 transition-colors ${Dt.combineTargetFor?"bg-primary/15 text-foreground ring-1 ring-primary/40":Dt.isDragging?"bg-surface-elevated text-foreground opacity-90 shadow-lg":jr(it.session.id)??(!Ie&&it.session.id===c?"bg-surface-elevated text-foreground":"text-muted-foreground hover:bg-surface-2")} cursor-grab active:cursor-grabbing`,children:Xn(it.session,kt.dragHandleProps)})]})},it.id)),Je.placeholder]})})}),tn=s.jsxs("div",{className:"relative flex min-h-0 flex-1 flex-col",children:[s.jsxs("div",{"data-session-sidebar-header":!0,className:"relative z-20 shrink-0 px-3 py-0.5",children:[s.jsx("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-x-3 bottom-0 z-10 h-px bg-border opacity-40"}),s.jsxs("div",{className:"flex w-full items-center gap-1.5",children:[s.jsx("div",{className:"min-w-0 flex-1",children:s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:"text-[12px] font-medium text-muted-foreground",children:Le("sidebar.sessions")}),s.jsx("span",{className:"text-[11px] text-muted-foreground",children:a.length}),Jr>0&&s.jsx("span",{className:"ml-0.5 flex items-center",children:s.jsx(P6,{count:Jr,tone:"running",title:Le("agent.aiRunning")})})]})}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[s.jsx("button",{"data-session-sidebar-header-action":!0,type:"button",onClick:()=>{ue(!1),fr(null)},className:"inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition hover:bg-primary/15 hover:text-primary active:scale-95","aria-label":"Agent 工作台",title:"Agent 工作台",children:s.jsx(nh,{size:16})}),(!_e||ze)&&s.jsx("button",{"data-session-sidebar-header-action":!0,type:"button",onClick:r,className:"inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition hover:bg-destructive/20 hover:text-destructive active:scale-95","aria-label":Le("common.close"),children:s.jsx(In,{size:16})})]})]})]}),ht&&s.jsxs("div",{role:"alert",className:"mx-2 mt-2 flex items-start gap-2 rounded-lg bg-destructive/10 px-3 py-2 text-[11px] text-destructive",children:[s.jsx("span",{className:"min-w-0 flex-1",children:ht}),s.jsx("button",{type:"button","aria-label":"关闭协作错误提示",className:"shrink-0",onClick:()=>q(null),children:s.jsx(In,{size:14})})]}),s.jsxs("div",{ref:qr,className:"relative z-10 flex min-h-0 flex-1 flex-col overflow-y-auto overscroll-contain px-1.5 pt-0.5 pb-1.5",children:[(ut.length>0||xt)&&s.jsxs("section",{className:"mb-2 rounded-lg border border-primary/20 bg-primary/5","aria-label":"协作待处理事项",children:[s.jsxs("button",{type:"button",className:"flex min-h-11 w-full items-center gap-2 px-3 text-left text-xs text-primary","aria-expanded":Rt,onClick:()=>Ct(G=>!G),children:[s.jsx(nh,{size:14}),s.jsx("span",{className:"min-w-0 flex-1",children:"需要你处理"}),s.jsx("span",{children:ut.length}),s.jsx(Ks,{size:12,className:Rt?"rotate-90":""})]}),Rt&&s.jsxs("div",{className:"space-y-1 p-1 pt-0",children:[xt&&s.jsxs("p",{role:"alert",className:"px-2 py-2 text-[11px] text-destructive",children:[xt,s.jsx("button",{type:"button",className:"ml-2 text-primary",onClick:()=>{Lu.getState().refresh()},children:"重试"})]}),ut.map(G=>s.jsxs("button",{type:"button",className:"min-h-11 w-full rounded-md px-2 py-2 text-left hover:bg-surface-2",onClick:()=>{F5(G.groupId,G.id),fr(G.groupId).then(Me=>{Me&&F5(G.groupId,G.id)})},children:[s.jsx("span",{className:"block truncate text-xs text-foreground",children:G.title}),s.jsxs("span",{className:"mt-1 block truncate text-[10px] text-muted-foreground",children:[Yt.find(Me=>Me.id===G.groupId)?.name??"协作组"," · ",Kc(G)]})]},G.id))]})]}),s.jsx(nF,{sessions:ce,loading:qe,attachingName:xe,onRefresh:we,onRestore:X,onClose:ye}),Pr.filter(G=>!G.sessionIds.length).map(G=>s.jsx(h0,{onDragEnd:()=>{},children:ss(G,[])},G.id)),a.length===0?s.jsxs("div",{className:"rounded-xl bg-surface-2/60 px-4 py-8 text-center",children:[s.jsx($o,{size:26,className:"mx-auto mb-2 text-muted-foreground"}),s.jsx("p",{className:"text-[12px] text-muted-foreground",children:Le("sidebar.noSessions")})]}):Tr.length===0&&v.length===0?s.jsx("div",{className:"rounded-xl bg-surface-2/60 px-4 py-6 text-center",children:s.jsx("p",{className:"text-[12px] text-muted-foreground",children:Le("sidebar.noMatchingSessions")})}):bt?s.jsx("div",{className:"flex flex-1 flex-col",children:s.jsx(h0,{onBeforeCapture:ps,onDragStart:_r,onDragEnd:G=>jn(Lr,G),children:s.jsx(Ll,{droppableId:"sidebar-groups",type:"group",direction:"vertical",children:G=>s.jsxs("div",{ref:G.innerRef,...G.droppableProps,className:"flex flex-1 flex-col space-y-1.5",children:[cn.map((Me,$e)=>{const Je=Br.has(Me.key),it=!Je&&$e===cn.length-1,Tt=zd(Me.sessions,v,Jt,Pr);let kt=0,Dt=0;for(const Bt of Me.sessions){const W=l.get(Bt.id);W?.agentStatus==="working"&&(kt+=1),(W?.agentStatus==="waiting"||W?.agentNeedsReview)&&(Dt+=1)}const ft=Me.key==="";return s.jsx(kl,{draggableId:`sidebar-group:${Me.key||"__ungrouped__"}`,index:$e,isDragDisabled:ft,disableInteractiveElementBlocking:!0,children:(Bt,W)=>s.jsxs("div",{ref:Bt.innerRef,...Bt.draggableProps,className:`shrink-0 rounded-md transition-colors ${it?"flex flex-1 flex-col ":""}${W.isDragging?"bg-surface-elevated shadow-lg opacity-90":""}`,children:[s.jsxs("button",{type:"button",...ft?{}:Bt.dragHandleProps,onClick:()=>{Vr(Me.key),Fr.current.delete(Me.key)},className:`flex w-full shrink-0 items-center gap-1.5 rounded-md px-1.5 py-1 text-left text-muted-foreground transition hover:bg-surface-2 ${ft?"":"cursor-grab active:cursor-grabbing"}`,title:Me.key||Me.label,children:[s.jsx(Ks,{size:13,className:`shrink-0 transition-transform ${Je?"":"rotate-90"}`}),s.jsx("span",{className:"min-w-0 flex-1 truncate text-[11.5px] font-semibold uppercase tracking-wide",children:Me.label}),kt>0&&s.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--success)] animate-pulse"}),Dt>0&&s.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--warning)] animate-pulse"}),s.jsx($5,{sessionIds:Me.sessions.map(N=>N.id)}),s.jsx("span",{className:"shrink-0 text-[10.5px] text-muted-foreground/70",children:Me.sessions.length})]}),!Je&&s.jsx("div",{className:`mt-0.5 pl-2 ${it?"flex flex-1 flex-col":""}`,children:s.jsx(Ll,{droppableId:`group-sessions:${Me.key}`,type:"session",direction:"vertical",isCombineEnabled:!re,children:N=>s.jsxs("div",{ref:N.innerRef,...N.droppableProps,"data-sidebar-entity-list-id":`group-sessions:${Me.key}`,className:`${it?"flex-1 ":""}space-y-0.5`,children:[Tt.map((U,K)=>s.jsx(kl,{draggableId:U.id,index:K,disableInteractiveElementBlocking:!0,children:(fe,Qe)=>s.jsxs("div",{ref:fe.innerRef,...fe.draggableProps,"data-sidebar-gesture-ignore":!0,"data-sidebar-entity-index":K,className:"relative",children:[Jn(K),K===Tt.length-1&&Jn(Tt.length,"bottom"),U.kind==="workspace"?Un(U.workspace,U.members,Qe.isDragging,!!Qe.combineTargetFor,fe.dragHandleProps):U.kind==="collaboration"?ss(U.group,U.members,fe.dragHandleProps,Qe.isDragging,!!Qe.combineTargetFor):s.jsx("div",{...B?cr(()=>B(U.session.id)):{},className:`group relative flex items-center gap-1 rounded-md pr-1 transition-colors ${Qe.combineTargetFor?"bg-primary/15 text-foreground ring-1 ring-primary/40":Qe.isDragging?"bg-surface-elevated text-foreground opacity-90 shadow-lg":jr(U.session.id)??(!Ie&&U.session.id===c?"bg-surface-elevated text-foreground":"text-muted-foreground hover:bg-surface-2")} cursor-grab active:cursor-grabbing`,children:Xn(U.session,fe.dragHandleProps)})]})},U.id)),N.placeholder]})})})]})},Me.key||"__ungrouped__")}),G.placeholder]})})})}):Wr(dn,"sidebar-entities")]}),s.jsx(a9,{onReselect:()=>{d&&(mn.current=null,Be(G=>G+1),d())}}),ke&&s.jsx(fO,{directories:a.flatMap(G=>{const Me=l.get(G.id)?.cwd;return Me?[Me]:[]}),tmuxAvailable:pe,options:pn,launchPending:Pe,launchError:oe?Le(zm(oe)):null,agents:Gr,selectedAgent:me,detecting:ot,resumeHistory:Gt,resumeHistoryLoading:wt,resumeHistoryPendingId:Vt,resumeHistoryError:Ot,onRefreshAgents:()=>{pt().catch(()=>{})},onSelectAgent:G=>{ir(G).catch(()=>{})},onLaunchAgent:He,onResumeHistory:G=>{Nt(G)},onRemoveResumeHistory:G=>{Et(G)},onClose:()=>ue(!1),onOptionsChange:dr,additionalContent:Xr&&$?.latestVersion&&s.jsxs("div",{className:"mb-1 rounded-lg bg-[rgb(var(--warning-rgb)_/_0.10)] px-2.5 py-2.5 text-foreground",children:[s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx("span",{className:"mt-0.5 inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-md bg-[rgb(var(--warning-rgb)_/_0.16)] text-[color:var(--warning)]",children:s.jsx(bn,{size:13,className:$.status==="installing"||$.status==="restarting"?"animate-spin":""})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block font-semibold",children:Le("sidebar.updateAvailable",{version:$.latestVersion})}),s.jsx("span",{className:"mt-0.5 block text-[10.5px] leading-relaxed text-muted-foreground",children:$.status==="installing"?Le("sidebar.updateInstalling"):$.status==="ready"?Le("sidebar.updateReady"):$.status==="restarting"?Le("sidebar.updateRestarting"):Le("sidebar.updateFailed")})]})]}),$.status==="ready"&&Z&&s.jsx("button",{type:"button",disabled:V,onClick:Z,className:"mt-2 flex w-full items-center justify-center rounded-md bg-[var(--warning)] px-2 py-1.5 text-[11px] font-semibold text-[color:var(--bg)] transition hover:opacity-90 disabled:cursor-wait disabled:opacity-60",children:Le("sidebar.updateRestart")}),$.status==="error"&&le&&s.jsx("button",{type:"button",disabled:V,onClick:le,className:"mt-2 flex w-full items-center justify-center rounded-md bg-surface-elevated px-2 py-1.5 text-[11px] font-semibold text-foreground transition hover:bg-surface-2 disabled:cursor-wait disabled:opacity-60",children:Le("sidebar.updateRetry")})]}),footerActions:s.jsx(eF,{serverAttention:je,onOpenSettings:()=>{ue(!1),z()},actions:[...O?[{label:Le("sidebar.subscriptionQuota"),icon:zA,onSelect:()=>{ue(!1),O()}}]:[],{label:"Agent 工作台",icon:nh,onSelect:()=>{ue(!1),fr(null)}},{label:"服务与设备",icon:o9,onSelect:()=>{ue(!1),l9()}},...Y?[{label:Le(ze?"sidebar.unpinSidebar":"sidebar.pinSidebar"),icon:ze?b0:x0,separated:!0,onSelect:()=>{ue(!1),Y()}}]:[]]})}),Ze&&s.jsx(Lb,{onEnterGroup:async G=>{if(!await fr(G))throw new Error("协作组已保存,打开工作区失败,请重试");at(!1)},onFloatingChange:async G=>{if(G){if(!await fr(G))throw new Error("打开协作工作区失败");at(!1)}},activeSessionId:c,defaultSessionMode:ee,onClose:()=>at(!1),onNewSession:G=>p(G)}),Object.entries(Ge).map(([G,Me])=>s.jsx(Lb,{activeSessionId:c,initialCollaborationGroupId:G,initialFloating:Me,visible:!Ie,onEnterGroup:async $e=>{if($e===G){await fr($e);return}if(!await fr($e))throw new Error("协作组已保存,打开工作区失败,请重试");await Fa({floatingGroupId:null},G),Ce(Je=>{const it={...Je};return delete it[G],it})},onFloatingChange:$e=>St(G,$e),defaultSessionMode:ee,onClose:()=>{ae.current=!0,Ce($e=>{const Je={...$e};return delete Je[G],Je})},onNewSession:$e=>p($e)},G)),!ke&&s.jsxs("div",{className:"relative z-10 shrink-0 bg-[var(--chrome-bg)] px-3 pb-3 pt-1 md:border-t md:border-border md:p-2",children:[oe&&s.jsx("p",{role:"alert",className:"mb-2 text-[11px] leading-relaxed text-destructive",children:Le(zm(oe))}),s.jsxs("div",{className:`grid gap-1.5 [&>button]:min-h-11 [&>button]:shadow-none [&>button]:ring-0 md:[&>button]:min-h-0 ${me?"grid-cols-[minmax(0,1fr)_minmax(0,1fr)_2.5rem]":"grid-cols-[minmax(0,1fr)_2.5rem]"}`,children:[s.jsxs("button",{type:"button",onClick:en,disabled:Pe,"aria-busy":Pe,className:`flex min-w-0 items-center justify-center gap-2 rounded-lg px-2 py-2.5 text-[12px] font-semibold transition active:scale-[0.99] ${me?"bg-surface-elevated text-foreground ring-1 ring-border/30 hover:bg-surface-2":"bg-primary text-primary-foreground ring-1 ring-primary/40 shadow-md shadow-primary/25 hover:bg-primary/90"}`,title:Le("sidebar.newSession"),"aria-label":Le("sidebar.newSession"),children:[s.jsx($o,{size:15,className:"shrink-0"}),s.jsx("span",{className:"truncate",children:Pe?Le("sidebar.sessionCreating"):"Terminal"})]}),me&&s.jsxs("button",{type:"button",onClick:xn,disabled:Pe,"aria-busy":Pe,className:"flex min-w-0 items-center justify-center gap-2 rounded-lg bg-primary px-2 py-2.5 text-[12px] font-semibold text-primary-foreground ring-1 ring-primary/40 shadow-md shadow-primary/25 transition hover:bg-primary/90 active:scale-[0.99]",title:Le("sidebar.newSessionWithAgent",{agent:me.displayName}),"aria-label":Le("sidebar.newSessionWithAgent",{agent:me.displayName}),children:[s.jsx(Wc,{agent:me,size:15}),s.jsx("span",{className:"truncate",children:me.displayName})]}),s.jsxs("button",{type:"button",onClick:tr,disabled:Pe,className:"relative inline-flex w-10 shrink-0 items-center justify-center rounded-lg bg-surface-2 text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground active:scale-[0.97]",title:st,"aria-label":st,"aria-expanded":ke,"aria-controls":"sidebar-launch-options",children:[s.jsx(To,{size:15}),je&&s.jsx("span",{className:"absolute right-0.5 top-0.5 h-2 w-2 rounded-full bg-destructive ring-2 ring-[var(--chrome-bg)]","aria-hidden":"true"}),Xr&&s.jsx("span",{className:`absolute top-0.5 h-2 w-2 rounded-full bg-[var(--warning)] ring-2 ring-[var(--chrome-bg)] ${je?"right-3.5":"right-0.5"}`,"aria-hidden":"true"})]})]})]})]});return ze?s.jsx("div",{"data-session-sidebar-pinned":!0,className:"h-full flex flex-col app-chrome-bg border-r border-border",children:tn}):s.jsx(D6,{side:"left",isOpen:e,drawerWidthPx:t,onClose:r,onOpen:n,push:_e,children:tn})}function oF(){const{t:e}=Ur();return s.jsxs("div",{role:"status","aria-label":e("rightSidebar.loadingGitChanges"),className:"td-loading-skeleton flex h-full min-h-0 flex-col overflow-hidden bg-surface",children:[s.jsx("span",{className:"sr-only",children:e("rightSidebar.loadingGitChanges")}),s.jsxs("div",{"aria-hidden":"true",className:"shrink-0 border-b border-border/15 px-3 py-2",children:[s.jsxs("div",{className:"mb-2 flex h-5 items-center gap-1",children:[s.jsx("div",{className:"h-4 w-16 rounded bg-surface-2"}),s.jsx("div",{className:"h-4 w-7 rounded bg-surface-2"}),s.jsx("div",{className:"h-4 w-12 rounded bg-surface-2"})]}),s.jsxs("div",{className:"flex h-[15px] items-center justify-between",children:[s.jsx("div",{className:"h-2 w-14 rounded bg-surface-2"}),s.jsx("div",{className:"h-2 w-6 rounded bg-surface-2"})]}),s.jsxs("div",{className:"mt-2 flex h-7 items-center gap-1.5",children:[s.jsx("div",{className:"h-7 w-12 rounded-full bg-surface-2"}),s.jsx("div",{className:"h-7 w-16 rounded-full bg-surface-2"}),s.jsx("div",{className:"h-3 w-24 max-w-[30%] rounded bg-surface-2"}),s.jsx("div",{className:"ml-auto h-4 w-4 rounded-full bg-surface-2"})]})]}),s.jsxs("div",{"aria-hidden":"true",className:"overflow-hidden px-3 py-2",children:[s.jsxs("div",{className:"flex h-8 items-center gap-2",children:[s.jsx("div",{className:"h-3 w-3 rounded-sm bg-surface-2"}),s.jsx("div",{className:"h-2 w-32 max-w-[55%] rounded bg-surface-2"})]}),["w-3/5","w-2/5","w-1/2","w-1/3"].map((t,r)=>s.jsxs("div",{className:"flex h-9 items-center gap-2 pl-5",style:{opacity:1-r*.15},children:[s.jsx("div",{className:"h-3 w-3 shrink-0 rounded-sm bg-surface-2"}),s.jsx("div",{className:`h-2 rounded bg-surface-2 ${t}`})]},t))]})]})}function lF({slow:e=!1}){const{t}=Ur();return s.jsxs("div",{role:"status","aria-label":t("rightSidebar.loadingGitChanges"),className:"td-loading-skeleton relative h-full min-h-0 overflow-hidden bg-surface px-3",children:[s.jsx("span",{className:"sr-only",children:t("rightSidebar.loadingGitChanges")}),s.jsxs("div",{"aria-hidden":"true",children:[s.jsxs("div",{className:"flex h-[76px] items-center gap-2 border-b border-border/40 px-2",children:[s.jsx("div",{className:"h-6 w-6 rounded-md bg-surface-2"}),s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"h-3 w-16 rounded bg-surface-2"}),s.jsx("div",{className:"h-2 w-12 rounded bg-surface-2"})]})]}),s.jsxs("div",{className:"flex h-11 items-center gap-2 px-1 pt-3",children:[s.jsx("div",{className:"h-6 w-6 rounded-md bg-surface-2"}),s.jsx("div",{className:"h-3 w-16 rounded bg-surface-2"}),s.jsx("div",{className:"ml-auto h-4 w-12 rounded-full bg-surface-2"})]}),[!1,!0].map(r=>s.jsxs("div",{className:"border-b border-border/40 px-1 py-4",children:[s.jsxs("div",{className:"mb-2 flex h-8 items-center justify-between",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"h-3 w-14 rounded bg-surface-2"}),r&&s.jsx("div",{className:"h-2 w-28 rounded bg-surface-2"})]}),s.jsx("div",{className:"h-8 w-12 rounded-md bg-surface-2"})]}),s.jsx("div",{className:"h-10 rounded-md bg-surface-2"})]},String(r))),s.jsx("div",{className:"flex h-[69px] items-center border-b border-border/40 px-2",children:s.jsx("div",{className:"h-3 w-16 rounded bg-surface-2"})}),s.jsxs("div",{className:"space-y-2 px-1 py-4",children:[s.jsxs("div",{className:"flex h-8 items-center justify-between",children:[s.jsx("div",{className:"h-3 w-14 rounded bg-surface-2"}),s.jsx("div",{className:"h-8 w-28 rounded-md bg-surface-2"})]}),s.jsx("div",{className:"h-7 rounded-md bg-surface-2"}),s.jsx("div",{className:"h-10 rounded-md bg-surface-2"})]})]}),e&&s.jsx("div",{className:"absolute inset-x-3 bottom-3 rounded-md bg-surface-elevated px-3 py-2 text-xs text-muted-foreground",children:t("rightSidebar.loadingGitChangesSlow")})]})}const Z6=()=>Oc(()=>import("./RightSidebar-CXykcIPb.js").then(e=>e.R),__vite__mapDeps([7,1,2,3,4,5,8,9,10,11,12,13,14,15,16,17])).then(e=>({default:e.RightSidebar})),cF=b.lazy(Z6);function Pb(e){const t=b.useRef(!1);b.useEffect(()=>{const p=navigator.connection;if(!(p?.saveData||/2g|3g/.test(p?.effectiveType??"")))return U1(()=>{Z6().catch(()=>{})},3e3)},[]);const{t:r}=Ur(),n=Wt(p=>p.rootPath),a=Wt(p=>p.rightTab),c=Wt(p=>p.setRightTab),l=n?.replace(/\/+$/,"").split("/").pop()||r("rightSidebar.workspace");(e.isOpen||e.pinned)&&(t.current=!0);const d=s.jsx(D6,{side:"right",isOpen:e.isOpen,drawerWidthPx:e.drawerWidthPx,onClose:e.onClose,onOpen:e.onOpen,pinned:e.pinned,children:s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden",children:[s.jsxs("div",{className:"shrink-0 border-b border-border/15 bg-surface px-2 pt-2",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("div",{className:"min-w-0 flex-1 px-1",children:s.jsx("div",{className:"flex min-h-[1.25rem] items-baseline gap-1.5",children:s.jsx("span",{className:"truncate text-[13px] font-semibold text-foreground",children:l})})}),s.jsx("div",{"aria-hidden":"true",className:"flex items-center gap-1.5",children:[jl,rS,To].map((p,m)=>s.jsx("span",{className:"inline-flex h-8 w-8 items-center justify-center rounded-full bg-surface-2 text-muted-foreground",children:s.jsx(p,{size:14})},m))}),s.jsx("button",{type:"button",onClick:e.onClose,"aria-label":r("common.close"),className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-surface-2 text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground active:scale-95",children:s.jsx(In,{size:14})})]}),s.jsx("div",{className:"mt-2 grid grid-cols-5 gap-0.5 rounded-md bg-surface-2 p-0.5",children:[["git",TA,"rightSidebar.tabGit"],["diff",CA,"rightSidebar.tabChanges"],["files",Vc,"rightSidebar.tabFiles"],["architecture",$T,"architecture.tab"],["computer",d9,"rightSidebar.tabComputer"]].map(([p,m,x])=>s.jsxs("button",{type:"button",onClick:()=>c(p),className:`flex items-center justify-center gap-1 rounded px-2 py-1.5 text-[11px] font-medium ${a===p?"bg-surface-elevated text-foreground":"text-muted-foreground"}`,children:[s.jsx(m,{size:12}),r(x)]},p))}),s.jsx("div",{className:"h-2"})]}),s.jsx("div",{className:"min-h-0 flex-1 bg-surface",children:a==="architecture"?s.jsx("div",{role:"status",className:"p-3 text-xs text-muted-foreground",children:r("architecture.loading")}):a==="computer"?s.jsx("div",{className:"p-3 text-xs text-muted-foreground",children:r("computer.loading")}):a==="git"?s.jsx(lF,{}):s.jsx(oF,{})})]})});return t.current?s.jsx(b.Suspense,{fallback:d,children:s.jsx(cF,{...e})}):d}const Ob=hc(e=>({overlay:"off",setOverlay:t=>e({overlay:t})}));function uF(e){let t=1,r="terminal";for(;;){let n=!1;for(const a of e.values())if(a.name===r){n=!0;break}if(!n)break;r=`terminal-${t}`,t++}return r}const dF=hc((e,t)=>({sessions:new Map,activeSessionId:null,nextSessionNumber:1,createSession:r=>{const n=n3(),a=Date.now(),c=t().sessions,l=uF(c),d={id:n,cwd:r,sessionId:null,name:l,customName:!1,createdAt:a,lastActivity:a};return e(p=>{const m=new Map(p.sessions);return m.set(n,d),{sessions:m,activeSessionId:p.activeSessionId??n,nextSessionNumber:p.nextSessionNumber+1}}),n},closeSession:r=>{e(n=>{const a=new Map(n.sessions),c=n.activeSessionId===r;a.delete(r);let l=n.activeSessionId;if(c){const d=Array.from(a.keys());l=d.length>0?d[0]:null}return{sessions:a,activeSessionId:l}})},switchSession:r=>{e(n=>n.sessions.has(r)?{activeSessionId:r}:n)},updateSession:(r,n)=>{e(a=>{const c=a.sessions.get(r);if(!c)return a;const l=new Map(a.sessions);return l.set(r,{...c,...n,lastActivity:Date.now()}),{sessions:l}})},setTerminalSession:(r,n)=>{t().updateSession(r,{sessionId:n.sessionId})},getActiveSession:()=>{const r=t();if(r.activeSessionId)return r.sessions.get(r.activeSessionId)},getSessionCount:()=>t().sessions.size,clearAllSessions:()=>{e({sessions:new Map,activeSessionId:null,nextSessionNumber:1})}})),hF=[7e5,1e6,14e5,18e5,24e5,32e5,4e6,5e6,6e6,8e6,1e7,12e6].map(e=>({id:"auto",maxSize:1600,bitRate:e,maxFps:30}));class fF{level=6;badSince=null;goodSince=null;connectedAt=0;lastSample=-1/0;lastChange=-1/0;lastUpgrade=-1/0;upgradeAfter=0;failedProbes=0;baselineRtt=1/0;get quality(){return hF[this.level]}connected(t){this.connectedAt=t,this.badSince=this.goodSince=null,this.lastSample=-1/0}sample(t,r,n=1600){if(r-this.lastSample>2500&&(this.badSince=this.goodSince=null),this.lastSample=r,t.rttMs!==null&&(this.baselineRtt=Math.min(this.baselineRtt,t.rttMs)),r-this.connectedAt<3e3)return null;const a=t.rttMs!==null&&t.rttMs>this.baselineRtt+150,c=t.deliveryDelayMs>250||t.decodeQueue>=4||a&&t.frames>0&&t.deliveryDelayMs>100,l=t.deliveryDelayMs>800||t.decodeQueue>=8,d=t.rttMs!==null&&t.rttMs<this.baselineRtt+100&&t.deliveryDelayMs<80&&t.decodeQueue<=1;this.badSince=c?this.badSince??r:null,this.goodSince=d?this.goodSince??r:null;const p=n<=1080?7:n<=1600?9:11;if(this.badSince!==null&&r-this.badSince>=(l?1e3:2e3)&&r-this.lastChange>=(l?2e3:3e3)&&this.level>0){this.level=Math.max(0,this.level-(l?2:1));const m=r-this.lastUpgrade<2e4;this.failedProbes=m?this.failedProbes+1:0,this.upgradeAfter=r+(m?Math.min(3e4,8e3*2**(this.failedProbes-1)):5e3),this.lastUpgrade=-1/0}else if(this.goodSince!==null&&r-this.goodSince>=3e3&&r-this.lastChange>=4e3&&r>=this.upgradeAfter&&this.level<p)this.level++,this.lastUpgrade=r;else return null;return this.lastChange=r,this.badSince=this.goodSince=null,this.quality}}async function eu(e,t){const r=await fetch(e,{...t,headers:{"Content-Type":"application/json",Accept:"application/json",...t?.headers??{}}}),n=await r.json().catch(()=>null);if(!r.ok||!n){const a=n?.error||n?.code||`ANDROID_REQUEST_FAILED_${r.status}`;throw new Error(a)}return n}async function pF(){return eu("/api/android/devices")}async function mF(e){return eu("/api/android/connect",{method:"POST",body:JSON.stringify({address:e})})}const Ff=[{id:"low",maxSize:720,bitRate:12e5,maxFps:30},{id:"medium",maxSize:1080,bitRate:4e6,maxFps:30},{id:"high",maxSize:1600,bitRate:8e6,maxFps:60}],E0=Ff[1];function R1(e){if(!e||typeof e!="object")return E0;const t=e;if(t.id==="auto")return{id:"auto",maxSize:1600,bitRate:4e6,maxFps:30};const r=Ff.find(l=>l.id===t.id);if(r)return r;if(t.id!=="custom")return E0;const n=typeof t.maxSize=="number"?Math.max(360,Math.min(2160,Math.round(t.maxSize))):1080,a=typeof t.bitRate=="number"?Math.max(3e5,Math.min(3e7,Math.round(t.bitRate))):4e6,c=typeof t.maxFps=="number"?Math.max(0,Math.min(60,Math.round(t.maxFps))):30;return{id:"custom",maxSize:n,bitRate:a,maxFps:c}}function gF(e,t){if(!/^[0-9a-zA-Z_.:\-]{1,128}$/.test(e))throw new Error("INVALID_SERIAL");const r=new URLSearchParams;t&&(r.set("max_size",String(t.maxSize)),r.set("bit_rate",String(t.bitRate)),t.maxFps>0&&r.set("max_fps",String(t.maxFps)));const n=r.toString();return`/api/android/${e}/ws${n?`?${n}`:""}`}function Fb(e){const t={ADB_UNAVAILABLE:"本机没有可用的 adb,请先安装 Android platform-tools。",ADB_NOT_FOUND:"找不到 adb 可执行文件,可用 TERMDOCK_ADB_BIN 指定路径。",SCRCPY_NOT_FOUND:"本机没有 scrcpy,请先安装(含 scrcpy-server)。",SCRCPY_SERVER_NOT_FOUND:"找不到 scrcpy-server,可用 TERMDOCK_SCRCPY_SERVER 指定路径。",SCRCPY_VERSION_UNKNOWN:"无法读取 scrcpy 版本,请确认 scrcpy --version 可执行。",SCRCPY_CONNECT_TIMEOUT:"设备连接超时,请确认已授权 USB 调试并保持解锁。",SCRCPY_UNSUPPORTED_CODEC:"设备返回了不支持的视频编码。",INVALID_ADDRESS:"地址格式不正确,应为 ip:port。",API_NOT_ALLOWED:"当前设备权限不足:投屏需要全权服务授权。"};for(const[r,n]of Object.entries(t))if(e.includes(r))return n;return e}function xF(e){return eu(`/api/android/recordings?serial=${encodeURIComponent(e)}`)}function bF(e){return eu("/api/android/recordings",{method:"POST",body:JSON.stringify({serial:e})})}function yF(e){return eu(`/api/android/recordings/${encodeURIComponent(e)}/stop`,{method:"POST"})}function vF(e,t){return eu(`/api/android/recordings/${encodeURIComponent(e)}/save`,{method:"POST",body:JSON.stringify({directory:t})})}function wF(e){return eu(`/api/android/recordings/${encodeURIComponent(e)}`,{method:"DELETE"})}const AF=0,TF=1,SF=2,CF=3,_F=4,kF=5,LF=7,IF=10,EF=11,NF=16,$b=17,Ub=0,Im=1,RF=2,zb=3,Em=0,Hb=1,Wb=1,Tu=0xffffffffffffffffn,Nh=0xfffffffffffffffen,Hd={HOME:3,APP_SWITCH:187,POWER:26,VOLUME_UP:24,VOLUME_DOWN:25};function K6(e,t,r){e.setUint32(t,Math.max(0,Math.round(r.x))&4294967295),e.setUint32(t+4,Math.max(0,Math.round(r.y))&4294967295),e.setUint16(t+8,Math.min(65535,Math.round(r.screenWidth))),e.setUint16(t+10,Math.min(65535,Math.round(r.screenHeight)))}function MF(e,t,r,n,a,c){const l=new Uint8Array(32),d=new DataView(l.buffer);return d.setUint8(0,SF),d.setUint8(1,e),d.setBigUint64(2,t),K6(d,10,r),d.setUint16(22,Math.max(0,Math.min(65535,Math.round(n*65536)))),d.setUint32(24,a>>>0),d.setUint32(28,c>>>0),l}function Nm(e,t,r=0,n=0){const a=new Uint8Array(14),c=new DataView(a.buffer);return c.setUint8(0,AF),c.setUint8(1,e),c.setUint32(2,t>>>0),c.setUint32(6,r>>>0),c.setUint32(10,n>>>0),a}function jF(e,t,r,n=0){const a=new Uint8Array(21),c=new DataView(a.buffer);c.setUint8(0,CF),K6(c,1,e);const l=d=>Math.max(-32768,Math.min(32767,Math.round(Math.max(-1,Math.min(1,d/16))*32768)));return c.setInt16(13,l(t)),c.setInt16(15,l(r)),c.setUint32(17,n>>>0),a}function DF(e){const t=new TextEncoder().encode(e);if(!t.length)return null;const r=t.subarray(0,300),n=new Uint8Array(5+r.length),a=new DataView(n.buffer);return a.setUint8(0,TF),a.setUint32(1,r.length),n.set(r,5),n}function BF(e){const t=new TextEncoder().encode(e);if(!t.length||t.length>255)return null;const r=new Uint8Array(2+t.length);return r[0]=NF,r[1]=t.length,r.set(t,2),r}function Wd(e){return new Uint8Array([e])}function Gb(e){return new Uint8Array([_F,e])}function QF(e){return new Uint8Array([IF,e?1:0])}function PF(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}function OF(e){const t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function Rm(e){return e.toString(16).padStart(2,"0")}function X6(e,t,r){for(let n=0;n+4<e.length;n++){const a=e[n]===0&&e[n+1]===0&&e[n+2]===1,l=e[n]===0&&e[n+1]===0&&e[n+2]===0&&e[n+3]===1?n+4:a?n+3:-1;if(l<0||l>=e.length)continue;if((r?e[l]>>1&63:e[l]&31)!==t){n=l-1;continue}let p=l+1;for(;p+2<e.length&&!(e[p]===0&&e[p+1]===0&&(e[p+2]===1||e[p+2]===0&&e[p+3]===1));)p++;return e.subarray(l,Math.min(e.length,p))}return null}function FF(e){const t=e?X6(e,7,!1):null;return t&&t.length>=4?`avc1.${Rm(t[1])}${Rm(t[2])}${Rm(t[3])}`:"avc1.42e01e"}function $F(e){const t=e?X6(e,32,!0):null;if(t&&t.length>=13){const r=t[1]>>6&3,n=t[1]&31,a=t[12];return`hev1.${r}.${n}.L${a}.B0`}return"hev1.1.6.L120.B0"}class UF{constructor(t,r){this.canvas=t,this.callbacks=r}canvas;callbacks;liveBitrate=!1;bitrateFailureDetail;get lastBitrateFailure(){return this.bitrateFailureDetail}bitrateRequestId=0;bitratePending=null;get supportsLiveBitrate(){return this.liveBitrate}get canSetBitrate(){return this.liveBitrate&&!this.bitratePending&&this.socket?.readyState===1}setBitrate(t){return!this.canSetBitrate||!Number.isInteger(t)||t<3e5||t>3e7?Promise.resolve(!1):new Promise(r=>{const n=++this.bitrateRequestId,a=setTimeout(()=>this.finishBitrate(!1,`BITRATE_CLIENT_TIMEOUT: requested=${t} bps; no server confirmation within 4000ms`),4e3);this.bitratePending={id:n,value:t,resolve:r,timer:a},this.send({type:"bitrate",requestId:n,bitRate:t})})}finishBitrate(t,r){const n=this.bitratePending;n&&(this.bitratePending=null,clearTimeout(n.timer),t||(this.liveBitrate=!1,this.bitrateFailureDetail=r??this.bitrateFailureDetail??"BITRATE_REASON_UNAVAILABLE: server rejected adjustment without a diagnostic",this.closedByUser||this.callbacks.onBitrateSupport?.(!1,this.bitrateFailureDetail)),n.resolve(t))}socket=null;decoder=null;configured=!1;configData=null;header=null;closedByUser=!1;lastMessageAt=0;lastFrameAt=0;lastResetAt=0;heartbeat=null;statsTimer=null;stallTimer=null;pendingConfig=null;needsKeyframe=!1;frameCount=0;receivedFrames=0;decodedFrames=0;controlsSent=0;lastSeq=0;lastType="";bytesSinceSample=0;warnedUnsupported=!1;lastSampleAt=0;serial="";autoQuality=!1;pingAt=null;rttMs=null;rttAt=0;minimumFrameOffset=1/0;deliveryDelayMs=0;peakDecodeQueue=0;sampleFrames=0;get currentHeader(){return this.header}connect(t,r){this.liveBitrate=!1,this.bitrateFailureDetail=void 0,this.serial=t,this.autoQuality=r?.id==="auto",this.closedByUser=!1,this.callbacks.onState("connecting");let n;try{n=h9(gF(t,r))}catch(a){this.callbacks.onState("error",a instanceof Error?a.message:"ANDROID_STREAM_FAILED");return}this.socket=n,n.onopen=()=>{this.lastMessageAt=Date.now()},n.onmessage=a=>{this.closedByUser||this.handleMessage(a.data)},n.onerror=()=>{this.closedByUser||this.callbacks.onState("error","SCRCPY_CONNECTION_LOST")},n.onclose=()=>{this.finishBitrate(!1,"BITRATE_CONNECTION_CLOSED: preview connection closed"),this.liveBitrate=!1,this.teardownTimers(),this.closedByUser?this.callbacks.onState("idle"):this.callbacks.onState("error","SCRCPY_CONNECTION_CLOSED")},this.startTimers()}disconnect(){this.closedByUser=!0,this.finishBitrate(!1),this.liveBitrate=!1,this.teardownTimers();try{this.decoder?.close()}catch{}this.decoder=null,this.configured=!1;try{this.socket?.close()}catch{}this.socket=null,this.callbacks.onState("idle")}teardownTimers(){this.heartbeat&&clearInterval(this.heartbeat),this.statsTimer&&clearInterval(this.statsTimer),this.stallTimer&&clearInterval(this.stallTimer),this.heartbeat=null,this.statsTimer=null,this.stallTimer=null}startTimers(){this.lastSampleAt=Date.now(),this.heartbeat=setInterval(()=>{if(!(!this.socket||this.socket.readyState!==1)){if(Date.now()-this.lastMessageAt>45e3){try{this.socket.close()}catch{}return}this.pingAt===null&&(this.pingAt=performance.now(),this.send({type:"ping"}))}},this.autoQuality?2e3:15e3),this.stallTimer=setInterval(()=>{if(!this.header||this.closedByUser)return;const t=Date.now();t-this.lastFrameAt>8e3&&t-this.lastResetAt>8e3&&(this.lastResetAt=t,console.warn("[android] no frames for 8s; requesting keyframe reset"),this.sendControl(Wd($b)))},2e3),this.statsTimer=setInterval(()=>{const t=Date.now(),r=(t-this.lastSampleAt)/1e3;r<=0||(this.callbacks.onStats({fps:Math.round(this.frameCount/r*10)/10,kbps:Math.round(this.bytesSinceSample*8/r/1e3),width:this.header?.width??0,height:this.header?.height??0,received:this.receivedFrames,decoded:this.decodedFrames,controls:this.controlsSent,last:this.lastType,adaptation:this.autoQuality?{rttMs:this.pingAt!==null&&performance.now()-this.pingAt>2e3?performance.now()-this.pingAt:performance.now()-this.rttAt<6e3?this.rttMs:null,deliveryDelayMs:this.sampleFrames?this.deliveryDelayMs:0,decodeQueue:Math.max(this.peakDecodeQueue,this.decoder?.decodeQueueSize??0),frames:this.sampleFrames}:void 0}),this.sampleFrames=0,this.peakDecodeQueue=0,this.frameCount=0,this.bytesSinceSample=0,this.lastSampleAt=t)},1e3)}send(t){if(!(!this.socket||this.socket.readyState!==1))try{this.socket.send(JSON.stringify(t))}catch{}}sendControl(t){t&&(this.controlsSent++,this.send({type:"control",data:PF(t)}))}ack(){this.send({type:"ack",seq:this.lastSeq})}handleMessage(t){if(typeof t!="string")return;this.lastMessageAt=Date.now();let r;try{r=JSON.parse(t)}catch{return}this.lastType=`${r.type??"?"}${r.config?":cfg":""}${r.key?":key":""}`;try{this.dispatchMessage(r)}catch(n){console.warn("[android] message handling failed",n),this.callbacks.onWarning(`处理消息失败:${n instanceof Error?n.message:String(n)}`)}}dispatchMessage(t){switch(t.type){case"bitrate-support":this.liveBitrate=t.supported===!0,this.bitrateFailureDetail=this.liveBitrate?void 0:typeof t.detail=="string"?t.detail.slice(0,4096):"BITRATE_REASON_UNAVAILABLE: server did not provide diagnostics",this.liveBitrate||this.finishBitrate(!1,this.bitrateFailureDetail),this.callbacks.onBitrateSupport?.(this.liveBitrate,this.bitrateFailureDetail);break;case"bitrate-result":t.requestId===this.bitratePending?.id&&this.finishBitrate(t.applied===!0&&t.bitRate===this.bitratePending?.value,typeof t.detail=="string"?t.detail.slice(0,4096):void 0);break;case"header":this.header={deviceName:t.deviceName??this.serial,codec:t.codec??"h264",width:t.width??0,height:t.height??0},this.lastFrameAt=Date.now(),this.callbacks.onHeader(this.header),this.callbacks.onState("streaming");break;case"frame":this.handleFrame(t);break;case"error":this.callbacks.onState("error",t.message||"SCRCPY_ERROR");break;case"closed":this.callbacks.onState("error","SCRCPY_SESSION_CLOSED");break;case"pong":this.pingAt!==null&&(this.rttMs=performance.now()-this.pingAt,this.rttAt=performance.now(),this.pingAt=null);break}}handleFrame(t){if(typeof t.data!="string")return;typeof t.seq=="number"&&(this.lastSeq=t.seq);const r=OF(t.data);if(this.bytesSinceSample+=t.data.length,this.receivedFrames++,this.lastFrameAt=Date.now(),this.decoder?.state==="closed"&&(this.decoder=null,this.configured=!1),t.config){this.configData=r,this.pendingConfig=r,this.configureDecoder(),this.ack();return}this.sampleFrames++;const n=Number(t.pts);if(t.pts!==void 0&&Number.isFinite(n)){const l=performance.now()-n/1e3;this.minimumFrameOffset=Math.min(this.minimumFrameOffset,l),this.deliveryDelayMs=Math.max(0,l-this.minimumFrameOffset)}this.configured||this.configureDecoder();const a=t.key===!0;if(this.needsKeyframe&&!a){this.ack();return}let c=r;this.pendingConfig&&(c=new Uint8Array(this.pendingConfig.length+r.length),c.set(this.pendingConfig,0),c.set(r,this.pendingConfig.length),this.pendingConfig=null),a&&(this.needsKeyframe=!1),this.decode(c,a,t.pts),this.ack()}configureDecoder(){const t=this.header?.codec??"h264";if(!this.decoder||this.decoder.state==="closed"){if(typeof VideoDecoder>"u"){this.warnedUnsupported||(this.warnedUnsupported=!0,this.callbacks.onWarning("当前浏览器不支持 WebCodecs(VideoDecoder),无法解码投屏画面。")),this.callbacks.onState("error","VIDEO_DECODER_UNSUPPORTED");return}try{this.decoder=new VideoDecoder({output:c=>this.onDecodedFrame(c),error:c=>{this.configured=!1,console.warn("[android] video decoder error",c),this.callbacks.onState("error",c instanceof Error?c.message:"VIDEO_DECODER_ERROR"),this.sendControl(Wd($b))}})}catch(c){console.warn("[android] VideoDecoder unavailable",c),this.callbacks.onWarning(`创建 VideoDecoder 失败:${c instanceof Error?c.message:String(c)}`),this.callbacks.onState("error","VIDEO_DECODER_UNSUPPORTED");return}}const r={codec:"avc1.42e01e",optimizeForLatency:!0};let n;t==="h264"?(n=[FF(this.configData),"avc1.42e01e","avc1.4d401e","avc1.64001f"].filter((l,d,p)=>p.indexOf(l)===d),r.avc={format:"annexb"}):t==="h265"?(n=[$F(this.configData),"hev1.1.6.L120.B0","hvc1.1.6.L120.B0"],r.hevc={format:"annexb"}):n=["av01.0.04M.08"];const a=[];for(const c of n)try{this.decoder.configure({...r,codec:c}),this.configured=!0,this.needsKeyframe=!0,c!==n[0]&&console.warn("[android] decoder configured with fallback codec",c);return}catch(l){a.push(`${c}: ${l instanceof Error?l.message:String(l)}`),console.warn("[android] decoder configure failed",c,l)}this.callbacks.onWarning(`解码器配置失败(${a.join(";")})`),this.callbacks.onState("error","VIDEO_DECODER_UNSUPPORTED")}decode(t,r,n){if(!(!this.decoder||this.decoder.state!=="configured"))try{this.decoder.decode(new EncodedVideoChunk({type:r?"key":"delta",timestamp:n?Number(n):this.lastTimestamp+1,data:t})),this.peakDecodeQueue=Math.max(this.peakDecodeQueue,this.decoder.decodeQueueSize),this.lastTimestamp=n?Number(n):this.lastTimestamp+1}catch(a){this.decodeFailureCount++<3&&(console.warn("[android] decode threw",a),this.callbacks.onWarning(`送入解码器失败:${a instanceof Error?a.message:String(a)}`))}}decodeFailureCount=0;lastTimestamp=0;onDecodedFrame(t){this.frameCount++,this.decodedFrames++;const r=t.displayWidth||t.codedWidth,n=t.displayHeight||t.codedHeight,a=this.canvas;(a.width!==r||a.height!==n)&&(a.width=r,a.height=n,this.header&&(this.header={...this.header,width:r,height:n},this.callbacks.onHeader(this.header)));const c=a.getContext("2d");c&&c.drawImage(t,0,0,a.width,a.height),t.close()}pointerPoint(t,r){return{x:t,y:r,screenWidth:this.header?.width??0,screenHeight:this.header?.height??0}}touch(t,r,n,a){const c=t===Im||t===zb,l=c?0:1,d=a===Tu&&!c?Wb:0,p=(t===Ub||t===Im)&&a===Tu?Wb:0;this.sendControl(MF(t,a,this.pointerPoint(r,n),l,p,d))}pointerDown(t,r,n){this.touch(Ub,t,r,n==="mouse"?Tu:Nh)}pointerMove(t,r,n){this.touch(RF,t,r,n==="mouse"?Tu:Nh)}pointerUp(t,r,n){this.touch(Im,t,r,n==="mouse"?Tu:Nh)}pointerCancel(t,r,n){this.touch(zb,t,r,n==="mouse"?Tu:Nh)}scroll(t,r,n,a){this.sendControl(jF(this.pointerPoint(t,r),n,a))}key(t,r=Em){this.sendControl(Nm(r,t))}tapKey(t){this.sendControl(Nm(Em,t)),this.sendControl(Nm(Hb,t))}back(){this.sendControl(Gb(Em)),this.sendControl(Gb(Hb))}home(){this.tapKey(Hd.HOME)}recents(){this.tapKey(Hd.APP_SWITCH)}power(){this.tapKey(Hd.POWER)}volumeUp(){this.tapKey(Hd.VOLUME_UP)}volumeDown(){this.tapKey(Hd.VOLUME_DOWN)}rotate(){this.sendControl(Wd(EF))}expandNotifications(){this.sendControl(Wd(kF))}collapsePanels(){this.sendControl(Wd(LF))}setDisplayPower(t){this.sendControl(QF(t))}sendText(t){this.sendControl(DF(t))}startApp(t){this.sendControl(BF(t))}}function zF(){try{return crypto.randomUUID().slice(0,8)}catch{return Math.random().toString(36).slice(2,10)}}function HF(){return`termdock-mirror-shot-${new Date().toISOString().replace(/[-:T]/g,"").slice(0,14)}-${zF()}.png`}function Vb(e){const t=Math.max(0,Math.floor(e/1e3)),r=Math.floor(t/60),n=t%60;return`${String(r).padStart(2,"0")}:${String(n).padStart(2,"0")}`}async function WF(e,t=HF()){const r=e.width,n=e.height;if(!r||!n)throw new Error("投屏画面尚未就绪");const a=document.createElement("canvas");a.width=r,a.height=n;const c=a.getContext("2d");if(!c)throw new Error("无法读取投屏画面");c.drawImage(e,0,0);const l=await new Promise(d=>a.toBlob(d,"image/png"));if(!l||l.size===0)throw new Error("截图失败,请重试");return new File([l],t,{type:"image/png"})}function J6(e,t,r){const n=r.contentWidth*(t-1)/2,a=r.contentHeight*(t-1)/2;return{x:Math.max(-n,Math.min(n,e.x)),y:Math.max(-a,Math.min(a,e.y))}}function qb(e,t,r,n,a){const c=Math.max(1,Math.min(8,e.zoom*a)),l=c/e.zoom;return{zoom:c,pan:J6({x:n.x-t.cx-(r.x-t.cx-e.pan.x)*l,y:n.y-t.cy-(r.y-t.cy-e.pan.y)*l},c,t)}}function e4(e,t){return t?new Promise((r,n)=>{const a=crypto.randomUUID(),c=p=>{window.clearTimeout(d),window.removeEventListener("termdock-insert-reference-ack",l),p?r():n(new Error("目标终端不可用,内容尚未插入,请连接终端后重试"))},l=p=>{const m=p.detail;m?.nonce===a&&c(m.ok===!0)},d=window.setTimeout(()=>c(!1),1e4);window.addEventListener("termdock-insert-reference-ack",l),window.dispatchEvent(new CustomEvent("termdock-insert-reference",{detail:{text:e,sessionId:t,nonce:a,focus:!1,paste:!0}}))}):Promise.reject(new Error("没有可接收内容的终端"))}function Yb(e,t){return e4(c1(e,null),t)}const Mm=hc(e=>({pending:[],enqueue:(t,r,n="/",a)=>e(c=>c.pending.some(l=>l.file.id===t.id)?c:{pending:[...c.pending,{file:t,sessionId:r,initialPath:n,insert:a}]}),remove:t=>e(r=>({pending:r.pending.filter(n=>n.file.id!==t)}))}));function GF({file:e,initialPath:t,onInsert:r,onDone:n}){const{t:a}=Ur(),[c,l]=b.useState(!1),[d,p]=b.useState(!1),[m,x]=b.useState(!1),[y,w]=b.useState(!1),[v,S]=b.useState(null),L=b.useRef(!1),E=b.useRef(null),R=async()=>{if(!L.current){L.current=!0,p(!0),w(!0);try{await wF(e.id),n()}catch(z){S(z instanceof Error?z.message:String(z))}finally{L.current=!1,p(!1),w(!1)}}};b.useEffect(()=>{if(c)return;E.current?.focus();const z=O=>{if(O.stopPropagation(),O.key==="Escape"&&O.preventDefault(),O.key!=="Tab")return;const $=Array.from(E.current?.querySelectorAll("button:not(:disabled)")??[]),V=$[0],Z=$.at(-1);O.shiftKey&&(document.activeElement===V||document.activeElement===E.current)?(O.preventDefault(),Z?.focus()):!O.shiftKey&&document.activeElement===Z&&(O.preventDefault(),V?.focus())};return document.addEventListener("keydown",z,!0),()=>document.removeEventListener("keydown",z,!0)},[c]);const B=async z=>{if(!L.current){L.current=!0,p(!0),x(z!==void 0),l(!1),S(null);try{const O=await vF(e.id,z);z===void 0&&await r(O.path),n()}catch(O){S(O instanceof Error?O.message:String(O))}finally{L.current=!1,p(!1)}}};return c?s.jsx(rp,{open:!0,initialPath:t||"/",title:a("android.recordingSave"),onCancel:()=>l(!1),onConfirm:z=>{B(z)}}):Xs.createPortal(s.jsx("div",{className:"fixed inset-0 z-modal-panel flex items-center justify-center bg-[var(--app-backdrop)] p-4",children:s.jsxs("div",{ref:E,role:"dialog","aria-modal":"true","aria-labelledby":"recording-save-title",tabIndex:-1,"aria-busy":d,className:"w-full max-w-sm rounded-xl border border-border bg-surface p-4 text-foreground shadow-xl outline-none",children:[s.jsx("h2",{id:"recording-save-title",className:"text-sm font-semibold",children:a("android.recordingConfirm")}),s.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:a("android.recordingSaveHint")}),s.jsxs("p",{className:"mt-2 break-all text-xs text-muted-foreground",children:[e.name," · ",(e.size/1024/1024).toFixed(1)," MB"]}),(v||e.error)&&s.jsx("p",{role:"alert",className:"mt-3 break-words text-xs text-destructive",children:v||e.error}),d&&s.jsxs("p",{role:"status",className:"mt-3 flex items-center gap-2 text-sm text-primary",children:[s.jsx(_n,{size:16,className:"animate-spin"}),y?`${a("android.recordingDiscard")}…`:a(m?"android.recordingSaving":"android.captureInserting")]}),s.jsxs("div",{className:"mt-4 flex flex-col gap-2",children:[s.jsx("button",{type:"button",disabled:d||e.status!=="ready",onClick:()=>{B()},className:"min-h-10 rounded-lg bg-primary px-3 text-sm text-primary-foreground disabled:opacity-40",children:a("android.recordingInsert")}),s.jsx("button",{type:"button",disabled:d||e.status!=="ready",onClick:()=>l(!0),className:"min-h-10 rounded-lg bg-surface-2 px-3 text-sm disabled:opacity-40",children:a("android.recordingSave")}),s.jsx("button",{type:"button",disabled:d,onClick:()=>{R()},className:"min-h-10 rounded-lg px-3 text-sm text-muted-foreground disabled:opacity-40",children:a("android.recordingDiscard")})]})]})}),document.body)}const r0="android-mirror",Gd=r0,t4="termdock:android:quality:v1",jm=176,VF=204,_l=1,nf=8,Zb=[1,1.25,1.5,2,2.5,3,4,6,8],qF=e=>Math.max(_l,Math.min(nf,e));function YF(e){return`${Number.isInteger(e)?e:e.toFixed(1)}×`}function Rh(e){const t=e.parentElement;if(!t)return null;const r=t.getBoundingClientRect(),n=getComputedStyle(t),a=parseFloat(n.paddingLeft)||0,c=parseFloat(n.paddingTop)||0,l=t.clientWidth-a-(parseFloat(n.paddingRight)||0),d=t.clientHeight-c-(parseFloat(n.paddingBottom)||0);return{cx:r.left+t.clientLeft+a+l/2,cy:r.top+t.clientTop+c+d/2,width:l,height:d,contentWidth:e.offsetWidth,contentHeight:e.offsetHeight}}function ZF(e,t){try{e.setPointerCapture?.(t)}catch{}}function Kb(e,t){try{e.releasePointerCapture?.(t)}catch{}}const Xb=e=>typeof requestAnimationFrame=="function"?requestAnimationFrame(e):window.setTimeout(e,16),Mh=e=>{typeof cancelAnimationFrame=="function"?cancelAnimationFrame(e):window.clearTimeout(e)},Dm={auto:"android.qualityAuto",low:"android.qualityLow",medium:"android.qualityMedium",high:"android.qualityHigh",custom:"android.qualityCustom"},KF=()=>{try{const e=localStorage.getItem(t4);return e?R1(JSON.parse(e)):E0}catch{return E0}},Vd=e=>{try{localStorage.setItem(t4,JSON.stringify(e))}catch{}};function XF({sessionId:e,dockOnly:t=!1,onInsertPrompt:r,onInsertFile:n,onRecordingComplete:a,onCloseTab:c}){const{t:l}=Ur(),d=Ob(N=>N.overlay),p=Ob(N=>N.setOverlay),m=b.useRef(null),x=b.useRef(null),y=b.useRef(null),w=b.useMemo(KF,[]),v=b.useRef(w),S=b.useRef(null),L=b.useRef(null),[E,R]=b.useState(4e6),B=b.useRef(null),z=b.useRef(new Map),O=b.useRef(null),$=b.useRef(!1),[V,Z]=b.useState(_l),le=b.useRef(V),be=b.useRef({x:0,y:0}),pe=b.useRef(null),ee=b.useRef(0),_e=b.useRef(0),ze=b.useRef(null),Y=b.useRef(0),[ce,qe]=b.useState(null),[we,ye]=b.useState(null),[Le,Be]=b.useState(!0),[ne,Fe]=b.useState(""),[ke,Ee]=b.useState(w.id),[Pe,Ne]=b.useState([]),[oe,We]=b.useState(null),[nt,gt]=b.useState(""),[ue,Ze]=b.useState(!0),[at,Ie]=b.useState({maxSize:w.maxSize,bitRate:w.bitRate,maxFps:w.maxFps}),[Ge,Ce]=b.useState("idle"),[H,ae]=b.useState(null),[Ae,Ye]=b.useState(null),[et,St]=b.useState({fps:0,kbps:0,width:0,height:0,received:0,decoded:0,controls:0,last:""}),[Gt,Qt]=b.useState(null),[wt,zt]=b.useState(null),[Vt,Kt]=b.useState(!1),[Ot,It]=b.useState([]),[xe,Ve]=b.useState(null),[ht,q]=b.useState([]),[ut,qt]=b.useState(!1),tt=b.useRef(null),De=b.useRef(0),nr=b.useRef([]),[Ke,_t]=b.useState(!1),[$t,yt]=b.useState(""),[xt,Rt]=b.useState(!1),[Ct,fr]=b.useState(!1),[Yt,Sr]=b.useState(""),[pn,dr]=b.useState(null),[me,Gr]=b.useState(null),[ot,pt]=b.useState(!1),[ir,Mn]=b.useState(0),Xr=b.useRef(null),[je,st]=b.useState(!1),bt=b.useRef(!1),Br=b.useRef(new Set),Vr=b.useRef(null),Cr=b.useRef(null),qr=b.useRef(!1),[mn,on]=b.useState(!1),zr=b.useRef(a);zr.current=a;const[un,Er]=b.useState(!1),[re,mt]=b.useState(null),Mt=b.useRef(null),rr=b.useRef(null),Ar=dF(N=>N.activeSessionId??N.sessions.keys().next().value??null),Fr=e??Ar,Xt=Kn(N=>!!N.docks[Gd]),Zr=Kn(N=>N.hosts[Gd]),Jt=Kn(N=>N.setDock),Pr=b.useCallback(async()=>{Be(!0);try{const N=await pF();qe(N),ye(null)}catch(N){ye(N instanceof Error?N.message:"ADB_UNAVAILABLE")}finally{Be(!1)}},[]);b.useEffect(()=>{Pr()},[Pr]);const Hr=ce?.devices??[],ps=Hr.find(N=>N.serial===ne)??null,Mr=!!(we&&/ADB_NOT_FOUND|ADB_UNAVAILABLE/i.test(we)),jn=!!(ce?.adbAvailable&&!ce.scrcpyVersion),Tr=b.useCallback(()=>{const N=B.current,U=[...z.current.keys()];B.current=null,z.current.clear(),O.current=null,$.current=!1,tt.current=null,Mh(ee.current),ee.current=0,N&&x.current?.pointerCancel(N.x,N.y,N.type);const K=m.current;if(K)for(const fe of U)Kb(K,fe);Ve(null),qt(!1),q([]),Z(le.current)},[]);b.useEffect(()=>{const N=fe=>{z.current.has(fe.pointerId)&&(fe.type==="pointercancel"||fe.target!==m.current)&&Tr()},U=()=>Tr(),K=()=>{document.hidden&&Tr()};return window.addEventListener("pointerup",N,!0),window.addEventListener("pointercancel",N,!0),window.addEventListener("blur",U),document.addEventListener("visibilitychange",K),()=>{window.removeEventListener("pointerup",N,!0),window.removeEventListener("pointercancel",N,!0),window.removeEventListener("blur",U),document.removeEventListener("visibilitychange",K),Tr()}},[Tr]);const Jr=b.useCallback(()=>{Tr(),x.current?.disconnect(),x.current=null,Ce("idle"),ae(null),Ye(null)},[Tr]),ln=b.useCallback((N,U=!1)=>{const K=m.current;if(!K||!N)return;Tr(),x.current?.disconnect(),ae(null),!U&&y.current!==N&&Ye(null),y.current=N,zt(null),Qt(null);const fe=new UF(K,{onBitrateSupport:(ve,lt)=>{x.current!==fe||v.current.id!=="auto"||Qt(ve?null:lt??"BITRATE_REASON_UNAVAILABLE")},onState:(ve,lt)=>{x.current===fe&&(Ce(ve),ae(lt??null))},onHeader:ve=>{x.current===fe&&Ye(ve)},onStats:ve=>{x.current===fe&&St(ve)},onWarning:ve=>{x.current===fe&&zt(ve)}});x.current=fe;let Qe=v.current;Qe.id==="auto"?(S.current?.serial!==N&&(S.current={serial:N,policy:new fF}),S.current.policy.connected(performance.now()),Qe=S.current.policy.quality,R(Qe.bitRate)):S.current=null,L.current=Qe,fe.connect(N,Qe)},[Tr]);b.useEffect(()=>{if(ke!=="auto"||v.current.id!=="auto"||Ge!=="streaming"||!et.adaptation||document.hidden)return;const N=S.current,U=x.current;if(!N||N.serial!==ne||!U?.canSetBitrate)return;const K=m.current,fe=K?Math.max(K.clientWidth,K.clientHeight)*(window.devicePixelRatio||1)*le.current:1600,Qe=N.policy.sample(et.adaptation,performance.now(),fe||1600);Qe&&U.setBitrate(Qe.bitRate).then(ve=>{ve&&x.current===U&&(L.current=Qe,R(Qe.bitRate))})},[et,ke,Ge,ne,ln]);const Qr=b.useCallback(N=>{const U={...N.quality?{quality:{id:N.quality.id,maxSize:N.quality.maxSize,bitRate:N.quality.bitRate,maxFps:N.quality.maxFps}}:{},...N.activePresetId!==void 0?{activePresetId:N.activePresetId}:{},...N.presets!==void 0?{presets:N.presets}:{},...N.docked!==void 0?{docked:N.docked}:{},...N.deviceSerial!==void 0?{deviceSerial:N.deviceSerial}:{}};La({androidPanel:U}).catch(()=>{})},[]);b.useEffect(()=>{let N=!1;return fc().then(U=>{if(N)return;const K=U.androidPanel;if(K?.quality){const fe=R1(K.quality);v.current=fe,Ee(fe.id),Ie({maxSize:fe.maxSize,bitRate:fe.bitRate,maxFps:fe.maxFps}),Vd(fe)}Ne(K?.presets??[]),We(K?.activePresetId??null),K?.deviceSerial&&(ze.current=K.deviceSerial,Fe(K.deviceSerial))}).catch(()=>{}),()=>{N=!0}},[]);const ks=b.useCallback(N=>{const U=++De.current;It(fe=>[...fe,{id:U,left:N.left,top:N.top}]);const K=window.setTimeout(()=>{It(fe=>fe.filter(Qe=>Qe.id!==U)),nr.current=nr.current.filter(fe=>fe!==K)},300);nr.current.push(K)},[]),Dr=b.useCallback((N,U)=>{const K=x.current,fe=L.current;K?.supportsLiveBitrate&&y.current===N&&fe&&fe.maxSize===U.maxSize&&fe.maxFps===U.maxFps?K.setBitrate(U.bitRate).then(Qe=>{x.current===K&&(Qe?(L.current=U,Qt(null)):Qt(K.lastBitrateFailure??"BITRATE_REASON_UNAVAILABLE"))}):ln(N)},[ln,l]),en=b.useCallback(N=>{if(S.current=null,N.startsWith("user:")){const K=Pe.find(Qe=>Qe.id===N.slice(5));if(!K)return;const fe={id:"custom",maxSize:K.maxSize,bitRate:K.bitRate,maxFps:K.maxFps};v.current=fe,Ee("custom"),We(K.id),Ie({maxSize:K.maxSize,bitRate:K.bitRate,maxFps:K.maxFps}),Ze(!0),Vd(fe),Qr({quality:fe,activePresetId:K.id}),ne&&ln(ne);return}if(N==="custom"){const K=v.current;Ee("custom"),We(null),Ie({maxSize:K.maxSize,bitRate:K.bitRate,maxFps:K.maxFps}),Ze(!0);return}const U=N==="auto"?R1({id:"auto"}):Ff.find(K=>K.id===N)??E0;v.current=U,Ee(U.id),We(null),Vd(U),Qr({quality:U,activePresetId:null}),ne&&ln(ne)},[ln,ne,Pe,Qr]),xn=b.useCallback(()=>{const N={id:"custom",maxSize:at.maxSize,bitRate:at.bitRate,maxFps:at.maxFps};v.current=N,Vd(N),Qr({quality:N,activePresetId:null}),Ee("custom"),We(null),ne&&Dr(ne,N)},[Dr,ne,at,Qr]),X=b.useCallback(()=>{const N=nt.trim();if(!N)return;const U=`p${Date.now().toString(36)}${Math.random().toString(36).slice(2,6)}`,K={id:U,name:N,maxSize:at.maxSize,bitRate:at.bitRate,maxFps:at.maxFps},fe=[...Pe.filter(ve=>ve.name!==N),K].slice(-12),Qe={id:"custom",maxSize:at.maxSize,bitRate:at.bitRate,maxFps:at.maxFps};Ne(fe),gt(""),We(U),Ee("custom"),v.current=Qe,Vd(Qe),Qr({quality:Qe,activePresetId:U,presets:fe}),ne&&Dr(ne,Qe)},[nt,at,Pe,ne,Dr,Qr]),He=b.useCallback(()=>{if(!oe)return;const N=Pe.filter(U=>U.id!==oe);Ne(N),We(null),Qr({activePresetId:null,presets:N})},[oe,Pe,Qr]);b.useEffect(()=>()=>{x.current?.disconnect(),x.current=null;for(const N of nr.current)window.clearTimeout(N);nr.current=[]},[]),b.useEffect(()=>{if(d==="off")return;const N=U=>{U.key==="Escape"&&p("off")};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[d,p]),b.useEffect(()=>{const N=Hr.filter(K=>K.state==="device");if(ne||N.length!==1)return;const U=N[0].serial;ze.current!==U&&(ze.current=U,Fe(U))},[Hr,ne]),b.useEffect(()=>{ne&&ln(ne)},[ne,ln]),b.useEffect(()=>{if(Ge==="streaming"){Y.current=0,Kt(!1);return}if(Ge!=="error"||!ne||!e$(H??""))return;const N=Math.min(8e3,700*2**Y.current);Y.current+=1,Kt(!0);const U=window.setTimeout(()=>{Kt(!1),ln(ne)},N);return()=>window.clearTimeout(U)},[Ge,H,ne,ln]);const Nt=b.useCallback((N,U,K)=>{const fe=m.current,Qe=K??(fe?Rh(fe):null);return!fe||!Qe?{x:0,y:0}:J6(N,U,Qe)},[]),Et=b.useCallback(()=>{const N=m.current;if(!N)return;const{x:U,y:K}=be.current,fe=le.current,Qe=fe===_l&&U===0&&K===0?"":`translate3d(${U}px, ${K}px, 0) scale(${fe})`;N.style.transform!==Qe&&(N.style.transform=Qe);const ve=pe.current;ve&&(ve.textContent=fe>_l?YF(fe):"")},[]),tr=b.useCallback((N,U,K=!0)=>{const fe=m.current,Qe=le.current,ve=qF(N);if(!fe||ve===Qe)return;const lt=Rh(fe);if(!lt)return;const vt=U??{x:lt.cx,y:lt.cy},br=qb({zoom:Qe,pan:be.current},lt,vt,vt,ve/Qe);le.current=br.zoom,be.current=br.pan,K&&Et()},[Et]),jr=b.useCallback(()=>{const N=le.current;Z(U=>U<=_l+.01==N<=_l+.01&&U>=nf-.01==N>=nf-.01?U:N)},[]);b.useEffect(()=>()=>{Mh(ee.current),Mh(_e.current)},[]);const cr=()=>{let N=0,U=0;for(const fe of z.current.values())N+=fe.x,U+=fe.y;const K=z.current.size;return K?{x:N/K,y:U/K}:null},Cn=()=>{const[N,U]=Array.from(z.current.values());return N&&U?Math.hypot(N.x-U.x,N.y-U.y):0},Ls=()=>{const N=cr(),U=m.current?Rh(m.current):null;!N||!U||(O.current={startCentroid:N,startDistance:Cn(),box:U})},Xn=b.useCallback(()=>{const N=O.current,U=cr();if(!N||!U)return;const K=Cn(),fe=N.startDistance>0&&K>0?K/N.startDistance:1,Qe=qb({zoom:le.current,pan:be.current},N.box,N.startCentroid,U,fe);le.current=Qe.zoom,be.current=Qe.pan,N.startCentroid=U,N.startDistance=K},[]),cn=b.useCallback(()=>{ee.current||(ee.current=Xb(()=>{ee.current=0,Xn(),Et()}))},[Xn,Et]),dn=b.useCallback(()=>{ee.current&&(Mh(ee.current),ee.current=0,Xn(),Et())},[Xn,Et]);b.useEffect(()=>{const N=m.current;if(!N)return;const U=N.parentElement;if(!U)return;const K=Qe=>{if(Qe.ctrlKey||Qe.metaKey){if(Qe.preventDefault(),!Qe.deltaY||O.current)return;const vt=Qe.deltaMode===1?16:Qe.deltaMode===2?N.parentElement?.clientHeight||600:1,br=Math.max(-600,Math.min(600,Qe.deltaY*vt));tr(le.current*Math.exp(-br*.002),{x:Qe.clientX,y:Qe.clientY},!1),_e.current||(_e.current=Xb(()=>{_e.current=0,Et(),jr()}));return}const ve=x.current;if(!ve||Qe.target!==N)return;Qe.preventDefault();const lt=Dh(N,Qe.clientX,Qe.clientY);ve.scroll(lt.x,lt.y,Qe.deltaX,Qe.deltaY)},fe=Qe=>Qe.preventDefault();return U.addEventListener("wheel",K,{passive:!1}),U.addEventListener("gesturestart",fe,{passive:!1}),U.addEventListener("gesturechange",fe,{passive:!1}),()=>{U.removeEventListener("wheel",K),U.removeEventListener("gesturestart",fe),U.removeEventListener("gesturechange",fe)}},[tr,Et,jr]),b.useEffect(()=>{const N=m.current,U=N?.parentElement;if(!N||!U||typeof ResizeObserver>"u")return;const K=new ResizeObserver(()=>{O.current&&(O.current.box=Rh(N));const fe=Nt(be.current,le.current);fe.x===be.current.x&&fe.y===be.current.y||(be.current=fe,Et())});return K.observe(N),K.observe(U),()=>K.disconnect()},[Nt,Et]),b.useLayoutEffect(()=>{Et()});const _r=N=>{const U=x.current,K=m.current;if(!U||!K)return;if(N.pointerType==="mouse"&&N.button!==0){N.preventDefault(),N.button===2?U.back():N.button===1&&U.home();return}N.preventDefault(),K.closest(".android-mirror-panel")?.focus({preventScroll:!0}),Et(),jr(),dn(),ZF(K,N.pointerId),z.current.set(N.pointerId,{x:N.clientX,y:N.clientY});const fe=N.pointerType==="mouse"&&N.altKey;if(z.current.size>=2||fe){const lt=B.current;lt&&(U.pointerCancel(lt.x,lt.y,lt.type),B.current=null,tt.current=null,Ve(null),qt(!1),q([])),$.current=!0,Ls();return}if($.current)return;const Qe=Dh(K,N.clientX,N.clientY);B.current={id:N.pointerId,type:N.pointerType,x:Qe.x,y:Qe.y},U.pointerDown(Qe.x,Qe.y,N.pointerType);const ve=ny(K,N.clientX,N.clientY);ve&&(tt.current={left:ve.left,top:ve.top},q([]),qt(!1),Ve(ve))},Or=N=>{const U=x.current,K=m.current;if(!K||!z.current.has(N.pointerId))return;if(N.pointerType==="mouse"){const vt=K.getBoundingClientRect(),br=K.parentElement?.getBoundingClientRect()??vt;if(!(N.buttons&1)||N.clientX<Math.max(vt.left,br.left)||N.clientX>=Math.min(vt.right,br.right)||N.clientY<Math.max(vt.top,br.top)||N.clientY>=Math.min(vt.bottom,br.bottom)){Tr();return}}if(N.preventDefault(),z.current.set(N.pointerId,{x:N.clientX,y:N.clientY}),O.current){cn();return}const fe=B.current;if(!U||!fe||fe.id!==N.pointerId)return;const Qe=Dh(K,N.clientX,N.clientY);fe.x=Qe.x,fe.y=Qe.y,U.pointerMove(Qe.x,Qe.y,fe.type);const ve=ny(K,N.clientX,N.clientY),lt=tt.current;!ve||!lt||(Ve(ve),Math.hypot(ve.left-lt.left,ve.top-lt.top)>=6&&(qt(!0),q(vt=>{const br=vt[vt.length-1];if(br&&Math.hypot(ve.left-br.x,ve.top-br.y)<4)return vt;const Lt=[...vt,{x:ve.left,y:ve.top}];return Lt.length>12?Lt.slice(Lt.length-12):Lt})))},Gn=N=>{const U=x.current,K=m.current;if(!K||!z.current.has(N.pointerId))return;if(dn(),z.current.delete(N.pointerId),Kb(K,N.pointerId),z.current.size===0&&($.current=!1),O.current){z.current.size===0?(O.current=null,Z(le.current)):Ls();return}const fe=B.current;if(!fe||fe.id!==N.pointerId)return;const Qe=Dh(K,N.clientX,N.clientY);U?.pointerUp(Qe.x,Qe.y,fe.type),xe&&ks(xe),Ve(null),qt(!1),window.setTimeout(()=>q([]),200),B.current=null,tt.current=null},Vn=N=>{if(un||Ke||Ct)return;const U=x.current;U&&(N.key==="Backspace"?(N.preventDefault(),U.key(67)):N.key==="Escape"?(N.preventDefault(),U.back()):N.key==="Enter"&&(N.preventDefault(),U.key(66)))},gn=async()=>{const N=$t.trim();if(N){Rt(!0);try{const U=await mF(N);yt(""),_t(!1),await Pr(),Fe(U.serial)}catch(U){ye(U instanceof Error?U.message:"ADB_CONNECT_FAILED")}finally{Rt(!1)}}},Jn=()=>{const N=x.current,U=Yt;!N||!U||(N.sendText(U),Sr(""))},kr=b.useCallback(N=>{dr(N),Cr.current!==null&&window.clearTimeout(Cr.current),Cr.current=window.setTimeout(()=>{Cr.current=null,dr(null)},2500)},[]),Lr=b.useCallback(N=>{const U=le.current,K=N==="in"?Zb.find(fe=>fe>U+.01):[...Zb].reverse().find(fe=>fe<U-.01);K!==void 0&&(U<=_l&&K>_l&&kr(l("android.zoomPanHint")),dn(),tr(K),Z(K))},[tr,dn,kr,l]),pr=N=>{Promise.resolve().then(()=>r?.(N)).catch(U=>{Gr(U instanceof Error?U.message:String(U))})},ns=b.useCallback(async(N,U)=>{try{if(!n)throw new Error(l("android.captureUnavailable"));await n(N),kr(U)}catch(K){Gr(l("android.captureFailed")+(K instanceof Error?`:${K.message}`:""))}},[n,kr,l]),Un=async()=>{const N=m.current;if(!(!N||qr.current)){qr.current=!0,on(!0),Gr(null);try{const U=await WF(N);await ns(U,l("android.captureInserted"))}catch(U){Gr(U instanceof Error?U.message:String(U))}finally{qr.current=!1,on(!1)}}},En=b.useCallback(N=>{(N.status==="ready"||N.status==="error")&&zr.current&&!Br.current.has(N.id)&&(Br.current.add(N.id),zr.current?.(N))},[]),kn=b.useCallback(async N=>{const U=Xr.current;if(!(!U||bt.current)){bt.current=!0,st(!0),Gr(null);try{const K=await yF(U.id);Xr.current=null,pt(!1),En(K)}catch(K){Gr(K instanceof Error?K.message:String(K))}finally{bt.current=!1,st(!1)}}},[En]),ss=async()=>{if(!(!ne||bt.current||Xr.current)){bt.current=!0,st(!0),Gr(null);try{const N=await bF(ne);N.status==="recording"||N.status==="starting"||N.status==="stopping"?(Xr.current=N,pt(!0),Mn(Math.max(0,Date.now()-N.startedAt))):En(N)}catch(N){Gr(N instanceof Error?N.message:String(N))}finally{bt.current=!1,st(!1)}}};b.useEffect(()=>{let N=!1,U=!1;Xr.current=null,pt(!1);const K=async()=>{if(!(!ne||U||bt.current)){U=!0;try{const{recordings:Qe}=await xF(ne);if(N||bt.current)return;const ve=Qe.find(lt=>["starting","recording","stopping"].includes(lt.status));Xr.current=ve??null,pt(!!ve);for(const lt of Qe)En(lt)}catch{}finally{U=!1}}};K();const fe=window.setInterval(()=>{K()},2e3);return Vr.current=window.setInterval(()=>{Xr.current&&Mn(Math.max(0,Date.now()-Xr.current.startedAt))},500),()=>{N=!0,window.clearInterval(fe),Vr.current!==null&&window.clearInterval(Vr.current)}},[ne,En]),b.useEffect(()=>{if(!un)return;const N=()=>Er(!1),U=fe=>{const Qe=fe.target;Qe instanceof Node&&(Mt.current?.contains(Qe)||rr.current?.contains(Qe)||N())},K=fe=>{fe.key==="Escape"&&(fe.preventDefault(),fe.stopPropagation(),N())};return document.addEventListener("pointerdown",U,!0),document.addEventListener("keydown",K,!0),window.addEventListener("resize",N),()=>{document.removeEventListener("pointerdown",U,!0),document.removeEventListener("keydown",K,!0),window.removeEventListener("resize",N)}},[un]),b.useEffect(()=>()=>{Cr.current!==null&&window.clearTimeout(Cr.current)},[]);const Wr=Ge==="streaming",tn=Xt,G=tn?"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded hover:bg-surface-2 disabled:opacity-40":"rounded p-1.5 hover:bg-surface-2 disabled:opacity-40",Me=ps?(ps.model||ps.serial)+sy(ps,l):Hr.length?l("android.selectDevice"):l("android.noDevices"),Je=(oe?Pe.find(N=>N.id===oe):null)?.name??(ke==="auto"?`${l("android.qualityAuto")} · ${E/1e6} Mbps`:l(Dm[ke])),it=tn?"relative flex h-5 min-w-0 items-center rounded bg-surface-2 focus-within:ring-1 focus-within:ring-primary/50":"relative flex h-7 min-w-0 items-center rounded bg-surface-2 focus-within:ring-1 focus-within:ring-primary/50",Tt=tn?"pointer-events-none block min-w-0 truncate px-1 text-[10px] leading-none text-foreground":"pointer-events-none block min-w-0 truncate px-2 text-[11px] leading-none text-foreground",kt="absolute inset-0 h-full w-full cursor-pointer opacity-0",Dt=()=>{const N=Mt.current?.getBoundingClientRect();N&&mt({left:Math.max(8,Math.min(N.right-jm,window.innerWidth-jm-8)),top:Math.min(N.bottom+4,Math.max(8,window.innerHeight-VF-8))}),Er(!0)},ft=()=>{if(Xt){Jt(Gd,null),Qr({docked:null});return}if(!Fr)return;const N={sessionId:Fr,side:"right"};Jt(Gd,N),Qr({docked:N})},Bt=Ke||Xt||d!=="off",W=s.jsxs("div",{className:"android-mirror-panel flex h-full min-h-0 min-w-0 flex-col bg-surface text-foreground","data-sidebar-gesture-ignore":"true",onKeyDown:Vn,tabIndex:-1,children:[s.jsxs("div",{"data-panel-drag-title":Xt?"true":void 0,className:tn?"flex h-6 min-h-6 shrink-0 flex-nowrap items-center gap-1 overflow-hidden border-b border-border/15 bg-[var(--chrome-bg)] px-1.5 cursor-grab select-none active:cursor-grabbing":"flex flex-wrap items-center gap-1.5 border-b border-border px-2 py-2",children:[Xt&&s.jsx("span",{"data-panel-drag-title":"true",role:"button","aria-label":l("android.splitDrag"),title:l("android.splitDrag"),className:"flex h-4 w-4 shrink-0 cursor-grab items-center justify-center rounded text-muted-foreground hover:text-foreground active:cursor-grabbing",children:s.jsx($f,{size:12})}),s.jsx(f9,{size:tn?12:14,className:"shrink-0 text-muted-foreground"}),s.jsxs("div",{className:`${it} flex-1`,children:[s.jsx("span",{"aria-hidden":"true",className:`${Tt} w-full`,children:Me}),s.jsxs("select",{value:ne,onChange:N=>{const U=N.target.value;Fe(U),ze.current=U,U&&Qr({deviceSerial:U})},className:kt,"aria-label":l("android.device"),children:[s.jsx("option",{value:"",children:Hr.length?l("android.selectDevice"):l("android.noDevices")}),Hr.map(N=>s.jsx("option",{value:N.serial,children:(N.model||N.serial)+sy(N,l)},N.serial))]})]}),s.jsxs("div",{className:`${it} max-w-[45%] shrink-0`,children:[s.jsx("span",{"aria-hidden":"true",className:Tt,children:Je}),s.jsxs("select",{value:oe?`user:${oe}`:ke,onChange:N=>en(N.target.value),className:kt,title:l(ke==="auto"?"android.qualityAutoHint":"android.quality"),"aria-label":l("android.quality"),children:[s.jsxs("option",{value:"auto",children:[l("android.qualityAuto"),ke==="auto"?` · ${E/1e6} Mbps`:""]}),Ff.map(N=>s.jsx("option",{value:N.id,children:l(Dm[N.id])},N.id)),Pe.map(N=>s.jsx("option",{value:`user:${N.id}`,children:N.name},N.id)),s.jsx("option",{value:"custom",children:l(Dm.custom)})]})]}),s.jsx("button",{type:"button",onClick:()=>{Pr()},className:`${G} text-muted-foreground`,title:l("android.refresh"),children:Le?s.jsx(_n,{size:13,className:"animate-spin"}):s.jsx(bn,{size:13})}),Wr?s.jsx("button",{type:"button",onClick:Jr,className:`${G} text-destructive`,title:l("android.disconnect"),children:s.jsx(Hy,{size:13})}):s.jsx("button",{type:"button",onClick:()=>ne&&ln(ne),disabled:!ne,className:`${G} text-primary`,title:l("android.connect"),children:s.jsx(oS,{size:13})}),(Wr||ot)&&s.jsx("button",{type:"button",onClick:()=>{Un()},disabled:!n||mn,className:`${G} text-muted-foreground`,title:l(n?"android.screenshot":"android.captureUnavailable"),"aria-label":l("android.screenshot"),children:mn?s.jsx(_n,{size:tn?12:13,className:"animate-spin"}):s.jsx($A,{size:tn?12:13})}),(Wr||ot)&&s.jsx("button",{type:"button",onClick:()=>{ot?kn("manual"):ss()},disabled:je||!ot&&!a,className:`${G} ${ot?"text-destructive":"text-muted-foreground"}`,title:l(ot?"android.recordingStop":a?"android.recordingStart":"android.captureUnavailable"),"aria-label":l(ot?"android.recordingStop":"android.recordingStart"),children:je?s.jsx(_n,{className:"animate-spin",size:13}):ot?s.jsx(zy,{size:tn?10:11,fill:"currentColor"}):s.jsx(Wy,{size:tn?12:13})}),s.jsx("button",{ref:Mt,type:"button",onClick:()=>un?Er(!1):Dt(),"aria-haspopup":"menu","aria-expanded":un,className:`${G} ${Bt?"text-primary":"text-muted-foreground"}`,title:l("android.more"),"aria-label":l("android.more"),children:s.jsx(To,{size:tn?13:14})}),c&&!t&&s.jsx("button",{type:"button",onClick:()=>{Er(!1),p("off"),c()},className:`${G} text-muted-foreground hover:bg-destructive/20 hover:text-destructive`,title:l("android.closeTab"),"aria-label":l("android.closeTab"),children:s.jsx(In,{size:14})})]}),un&&re&&Xs.createPortal(s.jsxs("div",{ref:rr,role:"menu","aria-label":l("android.more"),style:{left:re.left,top:re.top,width:jm},className:"fixed z-popover overflow-hidden rounded-md border border-border bg-surface-elevated py-1 text-[11px] shadow-lg",children:[s.jsx(jh,{icon:s.jsx(ul,{size:13}),label:l("android.addDevice"),active:Ke,onSelect:()=>{_t(N=>!N),Er(!1)}}),s.jsx(jh,{icon:Xt?s.jsx(In,{size:13}):s.jsx(Il,{size:13}),label:l(Xt?"android.splitClose":"android.splitOpen"),active:Xt,disabled:!Xt&&!Fr,onSelect:()=>{ft(),Er(!1)}}),s.jsx(jh,{icon:d==="window"?s.jsx(MT,{size:13}):s.jsx(IT,{size:13}),label:l(d==="window"?"android.exitFullscreen":"android.fullscreen"),active:d==="window",onSelect:()=>{p(d==="window"?"off":"window"),Er(!1)}}),!t&&s.jsx(jh,{icon:d==="sidebar"?s.jsx(zT,{size:13}):s.jsx(VT,{size:13}),label:l(d==="sidebar"?"android.exitFullscreen":"android.fillSidebar"),active:d==="sidebar",onSelect:()=>{p(d==="sidebar"?"off":"sidebar"),Er(!1)}}),Ae&&s.jsxs("div",{className:"mt-1 border-t border-border px-3 py-2 text-[10px] leading-4 tabular-nums text-muted-foreground",children:[s.jsx("div",{className:"truncate",children:`${et.fps} fps · ${et.kbps} kbps`}),s.jsx("div",{className:"truncate",children:`${et.width}×${et.height}`})]})]}),document.body),(ke==="custom"||oe)&&s.jsxs("div",{className:"border-b border-border bg-surface-2/40 px-2 py-2 text-[11px]",children:[s.jsxs("button",{type:"button",onClick:()=>Ze(N=>!N),"aria-expanded":ue,className:"flex w-full items-center gap-1 rounded text-muted-foreground hover:text-foreground",children:[s.jsx(ul,{size:12,className:`transition-transform ${ue?"":"-rotate-90"}`}),s.jsxs("span",{children:[l("android.quality"),oe?` · ${Pe.find(N=>N.id===oe)?.name??""}`:""]})]}),ue&&s.jsxs("div",{className:"mt-2 grid gap-2",children:[s.jsx(ry,{label:l("android.qualityResolution"),display:`${at.maxSize}px`,min:360,max:2160,step:8,value:at.maxSize,onChange:N=>Ie(U=>({...U,maxSize:N}))}),s.jsx(ry,{label:l("android.qualityBitRate"),display:`${(at.bitRate/1e6).toFixed(1)} Mbps`,min:.5,max:20,step:.5,value:at.bitRate/1e6,onChange:N=>Ie(U=>({...U,bitRate:Math.round(N*1e6)}))}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"w-14 shrink-0 text-muted-foreground",children:l("android.qualityFrameRate")}),s.jsxs("div",{className:"flex gap-1",children:[[15,30,60].map(N=>s.jsx("button",{type:"button",onClick:()=>Ie(U=>({...U,maxFps:N})),className:`rounded px-2 py-0.5 ${at.maxFps===N?"bg-surface-elevated text-primary":"text-muted-foreground hover:bg-surface-2"}`,children:N},N)),s.jsx("button",{type:"button",onClick:()=>Ie(N=>({...N,maxFps:0})),className:`rounded px-2 py-0.5 ${at.maxFps===0?"bg-surface-elevated text-primary":"text-muted-foreground hover:bg-surface-2"}`,children:l("android.qualityAuto")})]}),s.jsx("button",{type:"button",onClick:xn,disabled:!ne,className:"ml-auto rounded bg-primary/15 px-2 py-1 text-primary disabled:opacity-40",children:l("android.qualityApply")})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{value:nt,onChange:N=>gt(N.target.value),onKeyDown:N=>{N.key==="Enter"&&!N.nativeEvent.isComposing&&X()},placeholder:l("android.presetNamePlaceholder"),maxLength:40,className:"min-w-0 flex-1 rounded bg-surface-2 px-2 py-1 text-[11px] outline-none placeholder:text-muted-foreground"}),s.jsx("button",{type:"button",onClick:X,disabled:!nt.trim(),className:"shrink-0 rounded bg-surface-2 px-2 py-1 text-primary disabled:opacity-40",children:l("android.presetSave")}),oe&&s.jsx("button",{type:"button",onClick:He,className:"shrink-0 rounded px-2 py-1 text-destructive hover:bg-surface-2",children:l("android.presetDelete")})]})]})]}),Ke&&s.jsxs("div",{className:"flex items-center gap-1.5 border-b border-border px-2 py-2",children:[s.jsx("input",{value:$t,onChange:N=>yt(N.target.value),onKeyDown:N=>{N.key==="Enter"&&gn()},placeholder:l("android.addressPlaceholder"),className:"min-w-0 flex-1 rounded bg-surface-2 px-2 py-1 text-[11px] outline-none placeholder:text-muted-foreground"}),s.jsx("button",{type:"button",onClick:()=>{gn()},disabled:xt,className:"rounded bg-surface-2 px-2 py-1 text-[11px] text-primary disabled:opacity-40",children:xt?s.jsx(_n,{size:12,className:"animate-spin"}):l("android.connect")})]}),Mr&&s.jsxs("div",{className:"flex items-start gap-2 border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-destructive",children:[s.jsx("span",{className:"min-w-0 flex-1",children:l("android.adbUnavailable")}),s.jsx(ey,{label:l("android.insertFixPrompt"),onClick:()=>pr(ty("adb",we??"")),enabled:!!r})]}),!Mr&&jn&&s.jsxs("div",{className:"flex items-start gap-2 border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-warning",children:[s.jsx("span",{className:"min-w-0 flex-1",children:l("android.scrcpyUnavailable")}),s.jsx(ey,{label:l("android.insertFixPrompt"),onClick:()=>pr(ty("scrcpy","")),enabled:!!r})]}),ps&&ps.state!=="device"&&s.jsx("div",{className:"border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-warning",children:t$(ps,l)}),we&&!Mr&&s.jsx("div",{className:"border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-destructive",children:Fb(we)}),Gt&&s.jsxs("details",{className:"border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-warning",children:[s.jsxs("summary",{className:"cursor-pointer",children:[l("android.qualityAutoUnavailable")," ",l(Gt.startsWith("SCRCPY_VERSION")?"android.qualityAutoVersionError":Gt.startsWith("SCRCPY_BUILD")?"android.qualityAutoBuildError":/EXTENSION|SERVER_READ|PUSH/.test(Gt.split(":")[0])?"android.qualityAutoExtensionError":/TIMEOUT/.test(Gt.split(":")[0])?"android.qualityAutoTimeoutError":/ENCODER_REJECTED/.test(Gt.split(":")[0])?"android.qualityAutoEncoderError":/CHANNEL|TUNNEL|LISTEN|PROTOCOL|CONNECTION/.test(Gt.split(":")[0])?"android.qualityAutoChannelError":"android.qualityAutoUnknownError")]}),s.jsx("pre",{className:"mt-1 select-text whitespace-pre-wrap break-all text-[10px]",children:Gt})]}),wt&&s.jsx("div",{className:"border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-warning",children:wt}),me&&s.jsx("div",{role:"alert",className:"border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-destructive",children:me}),s.jsxs("div",{className:"relative flex min-h-0 min-w-0 flex-1 touch-none items-center justify-center overflow-hidden bg-[var(--chrome-bg)] p-1",children:[s.jsx("canvas",{ref:m,className:"max-h-full max-w-full touch-none select-none rounded",style:{display:Wr||Ae?"block":"none",transformOrigin:"center",transition:"none"},onPointerDown:_r,onPointerMove:Or,onPointerUp:Gn,onPointerCancel:()=>Tr(),onLostPointerCapture:N=>{z.current.has(N.pointerId)&&Tr()},onPointerLeave:N=>{z.current.has(N.pointerId)&&!N.currentTarget.hasPointerCapture?.(N.pointerId)&&Tr()},onContextMenu:N=>N.preventDefault()}),xe&&s.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute h-3.5 w-3.5 -translate-x-1/2 -translate-y-1/2 rounded-full border border-primary/80 bg-primary/35",style:{left:xe.left,top:xe.top}}),ht.length>1&&s.jsx("svg",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0 h-full w-full",style:{opacity:ut?1:0,transition:"opacity 160ms linear"},children:ht.slice(1).map((N,U)=>{const K=ht[U],fe=(U+1)/(ht.length-1);return s.jsx("line",{x1:K.x,y1:K.y,x2:N.x,y2:N.y,stroke:"var(--primary)",strokeWidth:1+1.6*fe,strokeLinecap:"round",opacity:.06+.45*fe},U)})}),Ot.map(N=>s.jsx("span",{"aria-hidden":"true",className:"termdock-tap-fade pointer-events-none absolute h-4 w-4 rounded-full bg-primary",style:{left:N.left,top:N.top}},N.id)),!Wr&&s.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-2 text-center text-[11px] text-muted-foreground",children:[Ge==="connecting"&&s.jsxs(s.Fragment,{children:[s.jsx(_n,{size:18,className:"animate-spin"}),s.jsx("span",{children:l("android.connecting")})]}),Ge==="error"&&s.jsxs(s.Fragment,{children:[s.jsx(Hu,{size:14,className:"text-destructive"}),s.jsx("span",{className:"max-w-[80%] text-destructive",children:Vt?l("android.reconnecting"):Fb(H||"")}),ne&&s.jsx("button",{type:"button",onClick:()=>{Y.current=0,ln(ne)},className:"rounded bg-surface-2 px-2 py-1 text-foreground",children:l("android.retry")})]}),Ge==="idle"&&!Mr&&!jn&&s.jsxs(s.Fragment,{children:[s.jsx(DT,{size:22,className:"opacity-60"}),s.jsx("span",{children:Hr.length?l("android.idleHint"):l("android.noDevicesHint")})]})]})]}),s.jsxs("div",{className:`flex flex-wrap items-center gap-1 border-t border-border ${tn?"px-1.5 py-0.5":"px-2 py-1.5"}`,children:[s.jsx(Bo,{compact:tn,label:l("android.back"),onClick:()=>x.current?.back(),disabled:!Wr,children:s.jsx(Iy,{size:14})}),s.jsx(Bo,{compact:tn,label:l("android.home"),onClick:()=>x.current?.home(),disabled:!Wr,children:s.jsx(AT,{size:14})}),s.jsx(Bo,{compact:tn,label:l("android.recents"),onClick:()=>x.current?.recents(),disabled:!Wr,children:s.jsx(Oy,{size:14})}),s.jsx(Bo,{compact:tn,label:l("android.notifications"),onClick:()=>x.current?.expandNotifications(),disabled:!Wr,children:s.jsx(Dy,{size:14})}),s.jsx(Bo,{compact:tn,label:l("android.rotate"),onClick:()=>x.current?.rotate(),disabled:!Wr,children:s.jsx(fS,{size:14})}),s.jsx(Bo,{compact:tn,label:l("android.volumeDown"),onClick:()=>x.current?.volumeDown(),disabled:!Wr,children:s.jsx(QS,{size:14})}),s.jsx(Bo,{compact:tn,label:l("android.volumeUp"),onClick:()=>x.current?.volumeUp(),disabled:!Wr,children:s.jsx(OS,{size:14})}),s.jsx(Bo,{compact:tn,label:l("android.power"),onClick:()=>x.current?.power(),disabled:!Wr,children:s.jsx(cS,{size:14})}),s.jsx(Bo,{compact:tn,label:l("android.inputText"),active:Ct,onClick:()=>fr(N=>!N),disabled:!Wr,children:s.jsx(Py,{size:14})}),s.jsx(Bo,{compact:tn,label:l("android.zoomIn"),onClick:()=>Lr("in"),disabled:!Wr||V>=nf-.01,children:s.jsx(zs,{size:14})}),s.jsx(Bo,{compact:tn,label:l("android.zoomOut"),onClick:()=>Lr("out"),disabled:!Wr||V<=_l+.01,children:s.jsx(Fy,{size:14})}),s.jsxs("div",{className:"relative ml-auto h-5 w-24 min-w-0 max-w-full shrink-0","data-mirror-capture-status":!0,children:[s.jsx("span",{"aria-hidden":ot||!!pn||mn,className:`block truncate text-right text-[10px] leading-5 tabular-nums text-muted-foreground ${ot||pn||mn?"invisible":""}`,children:Ae?s.jsx(s.Fragment,{children:s.jsx("span",{ref:pe})}):""}),s.jsx("div",{className:"absolute inset-0 flex items-center justify-end overflow-hidden",children:s.jsx(JF,{recording:ot,elapsed:ir,status:mn?l("android.captureInserting"):pn,stopLabel:l("android.recordingStop"),onStop:()=>{kn("manual")}})})]})]}),Ct&&s.jsxs("div",{className:"flex items-center gap-1.5 border-t border-border px-2 py-1.5",children:[s.jsx("input",{value:Yt,onChange:N=>Sr(N.target.value),onKeyDown:N=>{N.key==="Enter"&&!N.nativeEvent.isComposing&&(N.preventDefault(),Jn())},placeholder:l("android.inputPlaceholder"),className:"min-w-0 flex-1 rounded bg-surface-2 px-2 py-1 text-[11px] outline-none placeholder:text-muted-foreground",autoFocus:!0}),s.jsx("button",{type:"button",onClick:Jn,disabled:!Yt,className:"rounded bg-surface-2 p-1.5 text-primary disabled:opacity-40",title:l("android.send"),children:s.jsx(i0,{size:13})})]})]});return d==="window"?Xs.createPortal(s.jsx("div",{className:"fixed inset-0 z-modal-panel flex flex-col bg-[var(--chrome-bg)]",style:{paddingTop:"var(--safe-top-inset, env(safe-area-inset-top, 0px))",paddingBottom:"var(--safe-bottom-inset, env(safe-area-inset-bottom, 0px))"},children:W}),document.body):t?Xt&&Zr?Xs.createPortal(W,Zr):null:Xt&&Zr?s.jsxs(s.Fragment,{children:[Xs.createPortal(W,Zr),s.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 p-4 text-center text-[11px] text-muted-foreground",children:[s.jsx(Il,{size:18,className:"opacity-60"}),s.jsx("span",{children:l("android.splitDockedHint")}),s.jsx("button",{type:"button",onClick:()=>{Jt(Gd,null),Qr({docked:null})},className:"rounded bg-surface-2 px-2 py-1 text-foreground",children:l("android.splitClose")})]})]}):W}function jh({icon:e,label:t,active:r=!1,disabled:n=!1,onSelect:a}){return s.jsxs("button",{type:"button",role:"menuitem",disabled:n,onClick:a,className:`flex w-full items-center gap-2 px-2.5 py-1.5 text-left transition hover:bg-surface-2 disabled:opacity-40 disabled:hover:bg-transparent ${r?"text-primary":"text-foreground"}`,children:[s.jsx("span",{"aria-hidden":"true",className:"shrink-0",children:e}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:t}),r&&s.jsx(pi,{size:12,className:"shrink-0"})]})}function JF({recording:e,elapsed:t,status:r,stopLabel:n,onStop:a}){return e?s.jsxs("span",{role:"status","aria-live":"polite",className:"ml-auto inline-flex shrink-0 items-center gap-1 whitespace-nowrap rounded bg-destructive/15 px-1.5 py-0.5 text-[10px] tabular-nums text-destructive",children:[s.jsx("span",{"aria-hidden":"true",className:"h-1.5 w-1.5 shrink-0 animate-pulse rounded-full bg-destructive"}),Vb(t),s.jsx("button",{type:"button",onClick:a,title:n,"aria-label":`${n} · ${Vb(t)}`,className:"ml-0.5 inline-flex h-4 w-4 items-center justify-center rounded hover:bg-destructive/25",children:s.jsx(zy,{size:8,fill:"currentColor"})})]}):r?s.jsx("span",{role:"status","aria-live":"polite",title:r,className:"ml-auto truncate text-[10px] text-primary",children:r}):null}function Jb({sessionId:e}){const t=Kn(x=>x.docks[r0]),r=!!t,n=t?.sessionId??e??null,c=Mm(x=>x.pending)[0],l=b.useCallback(async x=>{if(!n)throw new Error("没有可接收截图的终端");const w=(await N0("/tmp",[x])).files[0]?.path;if(!w)throw new Error("截图上传未返回文件路径");await Yb(w,n)},[n]),d=b.useCallback(x=>{Mm.getState().enqueue(x,n)},[n]),p=Kn(x=>!!x.hosts[r0]),m=b.useRef(!1);return b.useEffect(()=>{m.current||(m.current=!0,fc().then(x=>{const y=x.androidPanel?.docked;y&&(Kn.getState().docks[r0]||Kn.getState().setDock(r0,y))}).catch(()=>{}))},[]),s.jsxs(s.Fragment,{children:[r&&p&&s.jsx(XF,{sessionId:n,dockOnly:!0,onInsertFile:n?l:void 0,onInsertPrompt:n?x=>e4(x,n):void 0,onRecordingComplete:d}),c&&s.jsx(GF,{file:c.file,initialPath:c.initialPath,onInsert:x=>c.insert?c.insert(x):Yb(x,c.sessionId),onDone:()=>Mm.getState().remove(c.file.id)},c.file.id)]})}function ey({label:e,onClick:t,enabled:r}){return r?s.jsx("button",{type:"button",onClick:t,className:"shrink-0 rounded bg-surface px-1.5 py-0.5 text-[10px] text-foreground hover:bg-surface-elevated",children:e}):null}function ty(e,t){return[`Termdock 的“设备投屏”在当前服务端不可用:未找到 ${e==="adb"?"adb(Android platform-tools)":"scrcpy / scrcpy-server"}${t?`(错误:${t})`:""}。`,"请在本机安装并让 Termdock 恢复可用:","1) 安装依赖:"," - macOS: brew install android-platform-tools scrcpy"," - Ubuntu/Debian: sudo apt install adb scrcpy"," - Windows: winget install Google.PlatformTools && winget install Genymobile.scrcpy","2) 若不在 PATH,请在 ~/.termdock/.env 指定 TERMDOCK_ADB_BIN / TERMDOCK_SCRCPY_BIN / TERMDOCK_SCRCPY_SERVER。","3) 完成后重启 Termdock 服务,并用 adb version、scrcpy --version 验证。","边界:只做本机环境安装与配置,不要改动 Termdock 仓库代码。"].join(`
|
|
162
|
+
`:"")+Nt)}},ref:dr,className:w?"":"rounded-xl border border-primary/20 bg-primary/5 px-3 py-3",children:[!w&&s.jsxs("h4",{className:"truncate text-[12px] font-medium text-foreground",children:[pt.name," · 发送给成员"]}),s.jsxs("div",{className:w?"space-y-2":"mt-2 space-y-2",children:[ze&&s.jsxs("div",{className:"relative z-20 flex items-center justify-between gap-2",children:[s.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["发送给 ",s.jsx("span",{className:"text-[9px]",children:"· 可多选"})]}),s.jsxs("details",{className:"relative",onKeyDown:X=>{X.key==="Escape"&&(X.currentTarget.removeAttribute("open"),X.currentTarget.querySelector("summary")?.focus(),X.stopPropagation())},children:[s.jsx("summary",{"aria-label":"更多协作操作",className:"flex min-h-11 min-w-11 cursor-pointer list-none items-center justify-center rounded text-muted-foreground hover:bg-surface-2 sm:min-h-8 sm:min-w-8 [&::-webkit-details-marker]:hidden",children:s.jsx(To,{size:16})}),s.jsxs("div",{className:"absolute right-0 top-full z-30 w-44 rounded-lg border border-border/20 bg-surface-2 p-1 shadow-lg",children:[s.jsxs("button",{type:"button",className:`${vr} min-h-11 w-full justify-start text-foreground hover:bg-surface-elevated`,onClick:X=>{X.currentTarget.closest("details")?.removeAttribute("open"),$?.(pt.id).catch(He=>pe(He instanceof Error?He.message:"无法打开看板"))},children:[s.jsx(Fc,{size:14}),"看板"]}),s.jsx("button",{type:"button","aria-expanded":qe,className:`${vr} min-h-11 w-full justify-start text-foreground hover:bg-surface-elevated`,onClick:X=>{X.currentTarget.closest("details")?.removeAttribute("open"),we(He=>!He)},children:"成员管理"}),s.jsxs("button",{type:"button","aria-label":"组设置","aria-expanded":wt,className:`${vr} min-h-11 w-full justify-start text-foreground hover:bg-surface-elevated`,onClick:X=>{X.currentTarget.closest("details")?.removeAttribute("open"),Kt.current=X.currentTarget,zt(!0),pe(null),ee(null)},children:[s.jsx(ju,{size:14}),"组设置"]})]})]})]}),s.jsxs("fieldset",{className:"min-w-0",children:[s.jsx("legend",{className:ze?"sr-only":"mb-1 text-[10px] text-muted-foreground",children:"接收人(可多选)"}),s.jsx("div",{className:"flex flex-wrap gap-1",children:[{id:"*",label:"全组成员"},...pt.sessionIds.map(X=>({id:X,label:(()=>{const He=ir.find(Nt=>Nt.sessionId===X);return He?Iu(He,ir):void 0})()??`${X.slice(0,8)}(离线)`}))].map(({id:X,label:He})=>{const Nt=X==="*"?Ae===null:Ae?.includes(X)??!1,Et=L.find(tr=>tr.sessionId===X);return s.jsxs("span",{className:"inline-flex max-w-full items-center gap-0.5",children:[s.jsxs("button",{type:"button","aria-pressed":Nt,onClick:()=>Ye(tr=>X==="*"?null:tr?.includes(X)?tr.filter(jr=>jr!==X):[...tr??[],X]),className:`${N1} min-h-9 min-w-0 gap-1 sm:min-h-7 ${Nt?"border-primary/40 bg-primary/15 text-primary":"border-border/20 bg-surface-2 text-muted-foreground hover:text-foreground"}`,children:[Nt&&s.jsx(pi,{size:12,"aria-hidden":"true",className:"shrink-0"}),s.jsx("span",{className:"break-words text-left",children:He})]}),Et&&s.jsx("button",{type:"button","aria-label":`打开 ${He} 的终端`,title:`打开 ${He} 的终端`,className:"inline-flex h-9 w-8 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-surface-2 hover:text-primary sm:h-7 sm:w-6",onClick:()=>{z(Et).catch(tr=>pe(tr instanceof Error?tr.message:"无法打开会话"))},children:s.jsx(Fc,{size:12})})]},X)})})]})]}),s.jsxs("label",{className:"mt-2 block space-y-1 text-[9px] text-muted-foreground",children:[s.jsx("span",{className:ze?"sr-only":void 0,children:"内容"}),s.jsx("textarea",{onKeyDown:X=>{X.key==="Enter"&&(X.metaKey||X.ctrlKey)&&!X.nativeEvent.isComposing&&X.keyCode!==229&&(X.preventDefault(),Hr())},onPaste:X=>{const He=Array.from(X.clipboardData.files);He.length&&(X.preventDefault(),zr(He))},className:`${$s} min-h-16 max-h-48 resize-y`,value:et,onChange:X=>St(X.target.value),placeholder:"输入消息,可粘贴引用或文件…"})]}),s.jsxs("div",{className:"mt-2 flex items-center justify-between gap-3",children:[s.jsx("p",{role:"status","aria-live":"polite",title:w&&a?a:void 0,className:`min-w-0 flex-1 text-[9px] leading-relaxed ${w?"truncate":""} ${w&&a?"text-primary":"text-muted-foreground"}`,children:Mn>0?"正在准备文件路径…":w&&a?a:pt.federated?"消息由服务端后台投递,可查看送达结果;无需保持客户端在线。":"在线成员立即入队;离线成员上线后送达。"}),s.jsxs("button",{disabled:le!==null||Mn>0||!et.trim()||!Pr.length,className:`${vr} shrink-0 bg-primary text-primary-foreground`,title:"发送(⌘ / Ctrl + Enter)",onClick:()=>{Hr()},children:[le==="send-message"?s.jsx(bn,{size:13,className:"animate-spin"}):null,"发送"]})]})]}),s.jsxs("div",{children:[s.jsxs("details",{hidden:ze&&!qe,open:ze?qe:void 0,onToggle:X=>{ze&&we(X.currentTarget.open)},className:"mt-4 rounded-xl border border-border/15",children:[s.jsxs("summary",{className:"cursor-pointer px-3 py-3 text-[11px] font-medium text-foreground",children:["管理成员、角色与删除 · ",pt.sessionIds.length," 个成员"]}),s.jsxs("section",{className:"border-t border-border/15 p-3",children:[s.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h4",{className:"text-[13px] font-medium text-foreground",children:pt.name}),s.jsxs("p",{className:"mt-1 text-[10px] text-muted-foreground",children:[pt.sessionIds.length," 个成员 · 组 ID:",s.jsx("span",{className:"break-all font-mono",children:Y6(pt.id)})]})]}),We?s.jsxs("div",{className:"flex flex-wrap items-center gap-1 sm:justify-end",children:[s.jsx("button",{className:`${vr} bg-surface-2 px-2 text-foreground`,onClick:()=>nt(!1),children:"取消"}),s.jsxs("button",{disabled:le!==null,className:`${vr} bg-destructive px-2 text-destructive-foreground`,onClick:()=>{ps()},children:[le===`delete:${pt.id}`?s.jsx(bn,{size:13,className:"animate-spin"}):null,"确认删除"]})]}):s.jsxs("div",{className:"flex flex-wrap items-center gap-1 sm:justify-end",children:[s.jsxs("button",{className:`${vr} px-2 text-muted-foreground hover:bg-surface-2 hover:text-foreground`,onClick:()=>{q(new Set(pt.sessionIds)),qt(pt.updatedAt);const X=!Gt;Qt(X),X&&De(Object.fromEntries(pt.sessionIds.map(He=>[He,pt.roles?.[He]??""]))),Ke(!1)},children:[s.jsx(ju,{size:13}),"管理成员"]}),s.jsxs("button",{className:`${vr} px-2 text-primary hover:bg-primary/10`,onClick:Jr,children:[s.jsx(zs,{size:13}),"新建 Agent"]}),s.jsx("button",{"aria-label":`删除协作组 ${pt.name}`,title:"删除协作组",disabled:le!==null,className:"rounded-lg p-2 text-muted-foreground transition hover:bg-destructive/10 hover:text-destructive",onClick:()=>{ue(pt.updatedAt),nt(!0)},children:s.jsx(Rs,{size:14})})]})]}),We&&s.jsxs("p",{role:"alert",className:"mt-2 rounded-lg bg-destructive/10 px-3 py-2 text-[10px] leading-relaxed text-destructive",children:["将删除“",pt.name,"”协作组及其协作记录,",pt.sessionIds.length," 个成员的终端会话会保留。"]}),s.jsx("div",{className:"mt-3 grid divide-y divide-border/10 border-y border-border/10 sm:grid-cols-2 sm:divide-x sm:divide-y-0",children:pt.sessionIds.map(X=>{const He=L.find(tr=>tr.sessionId===X),Nt=pt.roles?.[X],Et=He?.name??X;return s.jsxs("div",{className:`flex min-w-0 items-stretch transition ${xe===X?"bg-destructive/5":"hover:bg-surface-2"}`,children:[s.jsxs("button",{disabled:!He,onClick:()=>He&&void z(He).catch(tr=>pe(tr instanceof Error?tr.message:"无法打开会话")),className:"min-w-0 flex-1 px-3 py-2.5 text-left disabled:cursor-default",children:[s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${He&&["ready","shell","terminal-connected","service-reachable","working","idle","done"].includes(He.status)&&He.serviceConnected!==!1?"bg-[var(--success)]":"bg-muted-foreground"}`}),s.jsx("span",{className:"truncate text-[11px] text-foreground",children:Et}),He&&s.jsx(_m,{session:He}),s.jsx("span",{className:"ml-auto shrink-0 text-[9px] text-muted-foreground",children:He?rf(He):"已离线"})]}),s.jsxs("span",{className:"mt-1 flex min-w-0 items-center gap-1 text-[9px] text-muted-foreground",children:[Nt?s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"min-w-0 truncate font-medium text-primary/80",children:["定位:",Nt]}),s.jsx("span",{className:"shrink-0 text-muted-foreground/50",children:"·"})]}):null,He?s.jsx("span",{className:"min-w-0 truncate",children:km(He.currentTask)}):s.jsx("span",{className:"shrink-0",children:"重新上线后可继续接收消息"})]})]}),s.jsx("button",{"aria-label":`把 ${Et} 移出协作组`,"aria-expanded":xe===X,title:"移出协作组",disabled:le!==null,className:`mr-1 shrink-0 self-center rounded-lg p-2 transition ${xe===X?"text-destructive":"text-muted-foreground hover:bg-destructive/10 hover:text-destructive"}`,onClick:()=>Ve(xe===X?null:X),children:s.jsx(Rs,{size:13})})]},X)})}),xe&&pt.sessionIds.includes(xe)&&(()=>{const X=L.find(Nt=>Nt.sessionId===xe)?.name??xe,He=le===`remove-member:${xe}`;return s.jsxs("div",{role:"group","aria-label":`确认移除成员 ${X}`,className:"flex flex-wrap items-center gap-x-3 gap-y-2 border-y border-destructive/25 bg-destructive/5 px-3 py-2.5",children:[s.jsx("p",{className:"min-w-0 flex-1 text-[10px] leading-relaxed text-destructive",children:`把“${X}”移出“${pt.name}”?移出后它不再收到这个组的消息,可以随时重新加入`}),s.jsxs("div",{className:"flex shrink-0 gap-2",children:[s.jsx("button",{className:`${vr} min-h-8 bg-surface-2 px-2 text-[10px] text-foreground`,onClick:()=>Ve(null),children:"取消"}),s.jsxs("button",{disabled:le!==null,className:`${vr} min-h-8 px-2 text-[10px] bg-destructive text-destructive-foreground`,onClick:()=>{jn(xe)},children:[He?s.jsx(bn,{size:12,className:"animate-spin"}):s.jsx(Rs,{size:12}),"移出"]})]})]})})(),Gt&&s.jsxs("div",{className:"mt-4 border-t border-border/15 pt-4",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("h5",{className:"text-[11px] font-medium text-foreground",children:"管理成员"}),s.jsx("p",{className:"mt-1 text-[9px] text-muted-foreground",children:"暂不可用的原成员会保留,只有取消勾选才会移出;定位(角色)在每行独立保存,成员收到消息时会看到自己的定位。"})]}),s.jsxs("span",{className:"text-[9px] text-muted-foreground",children:["已选 ",ht.size]})]}),s.jsx("div",{className:"mt-3 max-h-72 divide-y divide-border/10 overflow-y-auto border-y border-border/10",children:Fr.length<=1?mt.map(Dr):Fr.map(X=>{const He=Xt(X.key);return s.jsxs("div",{children:[s.jsx(Rb,{label:X.label,count:X.sessions.length,collapsed:He,onToggle:()=>Zr(X.key)}),!He&&s.jsx("div",{className:"divide-y divide-border/10",children:X.sessions.map(Dr)})]},X.key)})}),s.jsxs("div",{className:"mt-3 flex justify-end gap-2",children:[s.jsx("button",{className:`${vr} bg-surface-2 text-foreground`,onClick:()=>{Qt(!1),De({})},children:"取消"}),s.jsxs("button",{disabled:le!==null||v!=="loaded",className:`${vr} bg-primary text-primary-foreground`,onClick:()=>{Mr()},children:[le==="save-members"?s.jsx(bn,{size:13,className:"animate-spin"}):s.jsx(pi,{size:13}),"保存成员"]})]})]}),nr&&s.jsxs("div",{className:"mt-4 border-t border-primary/20 pt-4",children:[s.jsxs("div",{children:[s.jsx("h5",{className:"text-[11px] font-medium text-foreground",children:"创建 Agent Session"}),s.jsx("p",{className:"mt-1 text-[9px] text-muted-foreground",children:"新会话启动后自动加入本组,并收到初始任务和成员信息。"})]}),s.jsx(bO,{group:pt,value:yt,onChange:xt,disabled:le!==null}),s.jsxs("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:[s.jsxs("label",{className:"space-y-1 text-[9px] text-muted-foreground",children:["Agent / Plugin",s.jsx("select",{"aria-label":"新 Agent 类型",className:$s,disabled:!!yt,value:pt.launchProfiles?.find(X=>X.id===yt)?.agentSlug??_t,onChange:X=>$t(X.target.value),children:E.map(X=>s.jsxs("option",{value:X.slug,children:[X.displayName,X.isPlugin?" · Plugin":""]},X.slug))})]}),s.jsxs("label",{className:"space-y-1 text-[9px] text-muted-foreground",children:["会话名称",s.jsx("input",{"aria-label":"新 Agent 会话名称",className:$s,value:Rt,onChange:X=>Ct(X.target.value),placeholder:"留空则自动命名"})]})]}),s.jsxs("label",{className:"mt-2 block space-y-1 text-[9px] text-muted-foreground",children:["工作目录",s.jsx("input",{"aria-label":"新 Agent 工作目录",className:$s,value:fr,onChange:X=>Yt(X.target.value),placeholder:"默认继承当前会话"})]}),s.jsxs("label",{className:"mt-2 block space-y-1 text-[9px] text-muted-foreground",children:["初始任务",s.jsx("textarea",{"aria-label":"新 Agent 初始任务",className:`${$s} min-h-16 resize-y`,value:Sr,onChange:X=>pn(X.target.value),placeholder:"说明它加入后要先完成什么"})]}),s.jsxs("div",{className:"mt-3 flex justify-end gap-2",children:[s.jsx("button",{className:`${vr} bg-surface-2 text-foreground`,onClick:()=>Ke(!1),children:"取消"}),s.jsxs("button",{disabled:le!==null||!_t||!!yt&&!pt.launchProfiles?.some(X=>X.id===yt),className:`${vr} bg-primary text-primary-foreground`,onClick:()=>{ln()},children:[le==="spawn-agent"?s.jsx(bn,{size:13,className:"animate-spin"}):s.jsx(R0,{size:13}),"创建并加入"]})]})]})]})]},pt.id),s.jsxs("section",{className:"mt-4",children:[s.jsxs("div",{className:"mb-2 flex flex-wrap items-center justify-between gap-2",children:[s.jsx("h4",{className:"text-[11px] font-medium text-foreground",children:"协作记录"}),s.jsxs("span",{className:"text-[9px] text-muted-foreground",children:[Qr.length," 条"]})]}),s.jsxs("div",{className:"divide-y divide-border/10 border-y border-border/10 [overflow-wrap:anywhere]",children:[Qr.map(X=>s.jsxs("div",{className:"px-2 py-3",children:[s.jsxs("div",{className:"flex items-center gap-2 text-[9px] text-muted-foreground",children:[s.jsx("span",{className:"font-medium text-primary",children:X.responseKind==="ack"?"收到确认":X.responseKind==="progress"?"进展":X.responseKind==="result"?"结果":HO(X.kind)}),s.jsx("span",{children:X.fromName}),s.jsx("span",{children:"→"}),s.jsx("span",{className:"truncate",children:X.toNames.join("、")}),s.jsx("span",{className:"ml-auto shrink-0",children:new Date(X.createdAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),s.jsx("p",{className:"mt-1 whitespace-pre-wrap text-[11px] leading-relaxed text-foreground",children:X.content}),s.jsx("p",{className:"mt-1 text-[9px] text-muted-foreground",children:X.status==="pending"?"已入队 · 等待投递":X.status==="failed"?"投递失败":X.status==="expired"?"消息已过期,未继续投递":X.status==="stored"?"答复已持久保存 · 供后台接收":"已写入接收方终端 · 等待接手确认"}),(X.task||X.failureReason)&&s.jsxs("details",{className:"mt-2 text-[10px] text-muted-foreground",children:[s.jsx("summary",{className:"cursor-pointer",children:"任务详情与证据"}),s.jsx("pre",{className:"mt-1 max-h-40 overflow-auto whitespace-pre-wrap break-words",children:JSON.stringify(X.task??{failure_reason:X.failureReason},null,2)})]})]},X.key)),Qr.length===0&&s.jsx(JO,{text:Ie?"正在加载协作记录…":"还没有消息。可以直接给成员发送说明或问题。"})]})]})]})]})]})]})}function BO({group:e,agents:t,activeSessionId:r,sessions:n,busy:a,setBusy:c,setError:l,setNotice:d,refresh:p,onClose:m}){const x=n.filter(Y=>e.sessionIds.includes(Y.sessionId)&&!$u(Y.sessionId)),[y,w]=b.useState(()=>EO(e,r&&x.some(Y=>Y.sessionId===r)?r:"")),v=b.useRef(y),[S,L]=b.useState(null),E=Y=>{const ce={...v.current,...Y};v.current=ce,NO(e.id,ce),w(ce)},{name:R,rules:B,savedName:z,savedRules:O,rulesVersion:$,rulesMemberId:V}=y,Z=Qf(y),le=new TextEncoder().encode(B).length,be=x.some(Y=>Y.sessionId===V),pe=async()=>{if(!(a||!R.trim())){c("group-name"),l(null),d(null);try{const Y=await Ml({id:e.id,name:R.trim(),sessionIds:y.sessionIds??e.sessionIds,expectedUpdatedAt:y.updatedAt});L(null),E({savedName:Y.group.name,name:Y.group.name,updatedAt:Y.group.updatedAt,sessionIds:Y.group.sessionIds,...B===O?{rules:Y.group.instructions?.text??"",savedRules:Y.group.instructions?.text??"",rulesVersion:Y.group.instructions?.version??""}:{}}),await p(),d("协作组名称已更新")}catch(Y){L(null),l(Y instanceof n0&&Y.status===409?"组设置已被其他人修改。请查看最新状态并确认,名称与群规草稿仍保留。":Y instanceof Error?Y.message:"改名失败")}finally{c(null)}}},ee=async()=>{if(!(a||!be||le>8192)){c("group-rules"),l(null),d(null);try{const Y=await W8(e.id,{sessionId:V,text:B,expectedVersion:$});L(null),E({savedName:Y.group.name,...R===z?{name:Y.group.name}:{},updatedAt:Y.group.updatedAt,sessionIds:Y.group.sessionIds,rules:Y.group.instructions?.text??"",savedRules:Y.group.instructions?.text??"",rulesVersion:Y.group.instructions?.version??""}),await p(),d(B.trim()?"群规已保存,变更通知已入队":"群规已清空,变更通知已入队")}catch(Y){L(null),l(Y instanceof n0&&Y.status===409?"群规已被其他人修改。请查看最新状态并确认,名称与群规草稿仍保留。":Y instanceof Error?Y.message:"群规保存失败")}finally{c(null)}}},_e=()=>{E(Eg(e,V)),L(null),l(null)},ze=async()=>{if(!a){c("group-latest"),l(null),d(null),L(null);try{const ce=(await Q1()).groups.find(qe=>qe.id===e.id);if(!ce)throw new Error("协作组已删除;草稿仍保留,请返回看板查看。");L(ce)}catch(Y){l(Y instanceof Error?Y.message:"最新状态读取失败;草稿仍保留,请重试。")}finally{c(null)}}};return s.jsxs("section",{"aria-label":"协作组设置",onKeyDown:Y=>{Y.key!=="Escape"||Y.defaultPrevented||Y.nativeEvent.isComposing||(Y.preventDefault(),Y.stopPropagation(),a||m())},className:"mt-3 rounded-xl border border-border/20 bg-surface-2 p-3",children:[s.jsxs("div",{className:"mb-3 flex items-center justify-between gap-2",children:[s.jsx("h4",{className:"text-[12px] font-medium text-foreground",children:"组设置"}),s.jsx("button",{type:"button",disabled:!!a,"aria-label":"关闭组设置",className:"rounded-lg p-2 text-muted-foreground hover:bg-surface-elevated",onClick:m,children:s.jsx(In,{size:14})})]}),s.jsxs("label",{className:"block space-y-1 text-[10px] text-muted-foreground",children:["协作组名称",s.jsx("input",{autoFocus:!0,className:$s,value:R,maxLength:240,disabled:!!a,onChange:Y=>E({name:Y.target.value})})]}),s.jsx("div",{className:"mt-2 flex justify-end",children:s.jsx("button",{type:"button",disabled:!!a||!!S||!R.trim()||R.trim()===z,className:`${vr} min-h-9 bg-primary text-primary-foreground`,onClick:()=>{pe()},children:a==="group-name"?"保存中…":"保存名称"})}),s.jsx(yO,{group:e,agents:t,busy:a,setBusy:c,refresh:p}),s.jsxs("div",{className:"mt-3 space-y-2 border-t border-border/15 pt-3",children:[s.jsxs("label",{className:"block space-y-1 text-[10px] text-muted-foreground",children:["由本组成员发布群规变更",s.jsxs("select",{className:$s,value:V,disabled:!!a||!x.length,onChange:Y=>E({rulesMemberId:Y.target.value}),children:[s.jsx("option",{value:"",children:"选择当前服务的一个成员"}),!x.some(Y=>Y.sessionId===V)&&V&&s.jsx("option",{value:V,children:"原成员已不在组内,请重新选择"}),x.map(Y=>s.jsx("option",{value:Y.sessionId,children:Y.name},Y.sessionId))]})]}),s.jsxs("label",{className:"block space-y-1 text-[10px] text-muted-foreground",children:["群规与协作约定",s.jsx("textarea",{className:`${$s} min-h-24 resize-y`,value:B,maxLength:8192,disabled:!!a,onChange:Y=>E({rules:Y.target.value}),placeholder:"例如:说明分工、交接要求和结果格式。清空后保存可移除群规。"})]})]}),!be&&s.jsx("p",{className:"mt-1 text-[10px] text-muted-foreground",children:x.length?"选择发布变更的成员后即可保存,不需要关闭工作台。":"当前服务没有本组成员,请先添加成员或切换到成员所在的服务。已有群规可在此查看。"}),s.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2",children:[s.jsx("p",{className:`text-[9px] ${le>8192?"text-destructive":"text-muted-foreground"}`,children:le>8192?"内容过长,请缩短群规":"保存或清空群规会通知本组其他成员"}),s.jsx("button",{type:"button",disabled:!!a||!!S||!be||le>8192||B===O,className:`${vr} min-h-9 shrink-0 bg-primary text-primary-foreground`,onClick:()=>{ee()},children:a==="group-rules"?"保存中…":B.trim()?"保存群规":"清空群规"})]}),Z&&s.jsx("p",{role:"status",className:"mt-3 text-[11px] leading-5 text-muted-foreground",children:"有未保存修改。关闭、Escape 或切换组后,草稿仍保留在本标签页;名称与群规需分别保存。"}),Z&&s.jsx("button",{type:"button",disabled:!!a,className:`${vr} mt-2 min-h-11 text-primary hover:bg-surface-elevated`,onClick:()=>{ze()},children:a==="group-latest"?"读取中…":"查看最新状态并保留草稿"}),S&&s.jsxs("section",{"aria-label":"最新组设置",className:"mt-3 space-y-2 rounded-lg bg-surface p-3 text-[11px] leading-5",children:[s.jsx("p",{className:"font-medium text-foreground",children:"确认最新状态后,再分别保存草稿"}),s.jsxs("p",{className:"break-words text-muted-foreground",children:["当前名称:",S.name]}),s.jsxs("p",{className:"whitespace-pre-wrap break-words text-muted-foreground",children:["当前群规:",S.instructions?.text||"未设置"]}),s.jsxs("p",{className:"break-words text-muted-foreground",children:["当前成员(",S.sessionIds.length,"):",S.sessionIds.map(Y=>n.find(ce=>ce.sessionId===Y)?.name??Y6(Y)).join("、")||"暂无成员"]}),s.jsx("p",{className:"text-muted-foreground",children:"保留你的未保存内容;名称保存将保留以上成员,群规保存会通知当前成员。再次发生修改时仍会检查冲突。"}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",disabled:!!a,className:`${vr} min-h-11 bg-primary text-primary-foreground`,onClick:()=>{E(IO(v.current,S)),L(null),l(null),d("已确认最新状态,草稿仍保留;请分别保存名称与群规。")},children:"确认最新状态,保留草稿"}),s.jsx("button",{type:"button",className:`${vr} min-h-11 text-muted-foreground`,onClick:()=>L(null),children:"取消确认"})]})]}),s.jsxs("div",{className:"mt-3 flex justify-between gap-2 border-t border-border/15 pt-2",children:[s.jsxs("button",{type:"button",disabled:!!a,className:`${vr} min-h-9 text-muted-foreground hover:bg-surface-elevated`,onClick:_e,children:[s.jsx(bn,{size:12}),"重新载入",Z&&"(放弃草稿)"]}),s.jsx("button",{type:"button",disabled:!!a,className:`${vr} min-h-9 bg-surface text-foreground`,onClick:m,children:Z?"关闭并保留草稿":"关闭"})]})]})}function QO({peers:e,currentGroupId:t,busy:r,setBusy:n,setError:a,setNotice:c,onSelectGroup:l}){const[d,p]=b.useState(null),[m,x]=b.useState(!1),y=e.services??[],w=e.removedServices??[],v=y.filter(E=>!E.connected),S=v.some(E=>E.groups?.some(R=>R.id===t)),L=async(E,R)=>{if(!r){n(`peer:${E}`),a(null),c(null);try{R?await K8(E):await X8(E),p(null),x(!1),c(R?"协作连接已恢复,正在连接服务":"协作连接已移除,不会再自动重连;已有会话和消息保留")}catch(B){a(B instanceof Error?B.message:R?"重新连接失败":"移除连接失败")}finally{n(null)}}};return s.jsxs("details",{className:"mt-4 shrink-0 rounded-lg border border-border/15",open:S||void 0,children:[s.jsxs("summary",{className:"cursor-pointer px-3 py-2.5 text-[11px] text-muted-foreground",children:[s.jsx("span",{className:"font-medium text-foreground",children:"协作连接与管理"}),s.jsx("span",{className:"ml-2",children:e.state==="loading"?"正在加载…":`${y.length-v.length} 个已连接${v.length?` · ${v.length} 个离线`:""}`})]}),s.jsxs("div",{className:"max-h-64 overflow-y-auto border-t border-border/15 px-3 py-2",children:[y.length>0&&s.jsx("p",{className:"mb-1 text-[10px] leading-relaxed text-muted-foreground",children:"与以下服务进行跨服务协作,名称与服务切换器一致。"}),v.length>0&&s.jsx("p",{className:"mb-2 text-[10px] leading-relaxed text-muted-foreground",children:S?"当前协作组的部分服务不可达,消息会保留并等待重连。":"其他服务暂时离线;当前服务内的协作可以继续。不再使用的连接可移除。"}),e.error&&s.jsx("p",{role:"status",className:"mb-2 break-words text-[10px] text-destructive",children:e.error}),e.state==="unsupported"&&s.jsx("p",{className:"mb-2 text-[10px] text-muted-foreground",children:"请更新客户端以管理跨服务连接。"}),s.jsx("div",{className:"divide-y divide-border/10",children:y.map(E=>s.jsxs("div",{className:"py-2.5",children:[s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("p",{className:"text-[11px] text-foreground",children:[uc({serviceLabel:E.label,serviceOrigin:E.origin}),s.jsx("span",{className:`ml-2 text-[9px] ${E.connected?"text-[var(--success)]":"text-muted-foreground"}`,children:E.connected?"已连接":E.error==="CONNECTING"?"连接中":"暂时离线"})]}),s.jsx(PO,{service:E})]}),E.serviceId&&s.jsxs("button",{type:"button",disabled:!!r,"aria-label":`移除协作连接 ${E.origin}`,className:`${vr} min-h-9 shrink-0 text-muted-foreground hover:bg-destructive/10 hover:text-destructive`,onClick:()=>p(d===E.serviceId?null:E.serviceId),children:[s.jsx(Rs,{size:12}),"移除"]})]}),!!E.groups?.length&&s.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1 text-[9px] text-muted-foreground",children:[s.jsx("span",{children:"用于"}),E.groups.map(R=>s.jsx("button",{type:"button",className:"rounded px-1.5 py-1 text-primary hover:bg-primary/10",onClick:()=>l(R.id),children:R.name},R.id))]}),!E.connected&&E.error&&E.error!=="CONNECTING"&&s.jsxs("details",{className:"mt-1 text-[9px] text-muted-foreground",children:[s.jsx("summary",{className:"cursor-pointer",children:GO(E.error)}),s.jsx("p",{className:"mt-1 select-text break-words",children:E.error})]}),d===E.serviceId&&s.jsxs("div",{role:"group","aria-label":"确认移除协作连接",className:"mt-2 rounded-lg bg-surface-2 p-2.5",children:[s.jsx("p",{className:"text-[10px] leading-relaxed text-foreground",children:E.groups?.length?"请先处理上方协作组的成员,再移除这条连接。":"移除后停止与该服务协作,保留已有会话和消息;以后可重新连接。"}),s.jsxs("div",{className:"mt-2 flex justify-end gap-2",children:[s.jsx("button",{type:"button",disabled:!!r,className:`${vr} min-h-9 text-muted-foreground`,onClick:()=>p(null),children:"取消"}),s.jsx("button",{type:"button",disabled:!!r||!!E.groups?.length,className:`${vr} min-h-9 bg-destructive text-destructive-foreground`,onClick:()=>{L(E.serviceId,!1)},children:r===`peer:${E.serviceId}`?"正在移除…":"确认移除"})]})]})]},E.serviceId||E.origin))}),y.length===0&&e.state==="ready"&&s.jsx("p",{className:"py-2 text-[10px] text-muted-foreground",children:"当前没有其他协作服务,当前服务内仍可创建协作组。"}),v.length>0&&s.jsxs("button",{type:"button",className:`${vr} mt-1 min-h-9 text-primary hover:bg-primary/10`,onClick:Z8,children:[s.jsx(bn,{size:12}),"重试连接"]}),w.length>0&&s.jsxs("div",{className:"mt-2 border-t border-border/15 pt-1",children:[s.jsx("button",{type:"button","aria-expanded":m,className:`${vr} min-h-9 text-muted-foreground hover:bg-surface-2`,onClick:()=>x(E=>!E),children:m?"收起恢复列表":"恢复已移除连接"}),m&&s.jsxs("section",{"aria-label":"恢复已移除连接",className:"mt-1 rounded-lg bg-surface-2 px-2.5 py-2",children:[s.jsx("p",{className:"text-[10px] leading-relaxed text-muted-foreground",children:"以下是恢复记录,连接已停用,不会自动重连。点击恢复后才会重新启用协作。"}),s.jsx("div",{className:"mt-1 divide-y divide-border/10",children:w.map(E=>s.jsxs("div",{className:"flex items-start gap-2 py-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("p",{className:"break-words text-[10px] text-foreground",children:[uc({serviceLabel:E.label,serviceOrigin:E.origin}),s.jsx("span",{className:"ml-2 text-[9px] text-muted-foreground",children:"已停用"})]}),s.jsx("p",{className:"mt-0.5 select-text break-all text-[9px] text-muted-foreground",children:E.accessUrl||E.origin})]}),s.jsx("button",{type:"button",disabled:!!r||!E.serviceId,className:`${vr} min-h-9 shrink-0 text-primary hover:bg-primary/10`,onClick:()=>{L(E.serviceId,!0)},children:r===`peer:${E.serviceId}`?"恢复中…":"恢复连接"})]},E.serviceId||E.origin))})]})]})]})]},S?"affected":"other")}function PO({service:e}){let t=!1;try{t=["localhost","127.0.0.1","[::1]"].includes(new URL(e.origin).hostname)}catch{}const r=e.accessUrl||(t?"":e.origin);return s.jsxs("details",{className:"mt-1 text-[9px] text-muted-foreground",children:[s.jsx("summary",{className:"w-fit cursor-pointer py-1",children:"连接详情"}),s.jsxs("dl",{className:"mt-1 space-y-1 select-text break-all",children:[s.jsxs("div",{children:[s.jsx("dt",{className:"inline",children:"服务地址:"}),s.jsx("dd",{className:"inline",children:r||"暂未获取,请在服务切换器中查看"})]}),e.serviceId&&s.jsxs("div",{children:[s.jsx("dt",{className:"inline",children:"服务身份:"}),s.jsx("dd",{className:"inline",children:e.serviceId})]})]})]})}function Cm(e){return!$u(e.sessionId)||e.serviceConnected!==!1}function OO(e){return e.serviceOrigin?e.serviceOrigin===window.location.origin?"":e.serviceOrigin:$u(e.sessionId)?.origin??""}function Nb(e){const t=new Map;for(const r of e){const n=OO(r),a=t.get(n)??{key:n,label:n?uc(r):"本机服务",sessions:[]};n&&a.label==="远端服务"&&(a.label=uc(r)),a.sessions.push(r),t.set(n,a)}return[...t.values()].sort((r,n)=>(r.key?1:0)-(n.key?1:0)||r.label.localeCompare(n.label))}function Rb({label:e,count:t,collapsed:r,onToggle:n}){return s.jsxs("button",{type:"button","aria-expanded":!r,onClick:n,className:"flex w-full items-center gap-1.5 bg-surface-2/50 px-2 py-1.5 text-left text-muted-foreground transition hover:bg-surface-elevated",children:[s.jsx(ul,{size:12,className:`shrink-0 transition-transform ${r?"-rotate-90":""}`}),s.jsx("span",{className:"min-w-0 flex-1 truncate text-[10px] font-semibold uppercase tracking-wide",children:e}),s.jsx("span",{className:"shrink-0 text-[9px] text-muted-foreground/70",children:t})]})}function FO(e,t){const r=new Map(t.map(n=>[n.sessionId,n]));for(const n of e?.sessionIds??[]){if(r.has(n))continue;const a=e?.remoteSessions?.find(c=>c.sessionId===n);r.set(n,a?{...a,status:"offline",serviceConnected:!1}:{sessionId:n,name:n,backendSessionId:null,cwd:"",agent:null,status:"offline",capability:"",currentTask:"暂不可用,保留成员身份",updatedAt:0,...$u(n)?{serviceConnected:!1}:{}})}return[...r.values()]}function _m({session:e}){return!e.serviceOrigin||e.serviceOrigin===window.location.origin?null:s.jsxs("span",{className:"inline-flex max-w-28 shrink-0 items-center gap-1 rounded border border-border/20 px-1 py-0.5 text-[9px] text-muted-foreground",children:[s.jsx(Fc,{size:9}),s.jsx("span",{className:"truncate",children:uc(e)})]})}function rf(e){return e.serviceConnected===!1?"服务不可达":e.status==="recovering"&&e.route_error==="ROUTE_NOT_CHECKED"?"投递目标未检查":zO(e.status)}function $O(e,t=[]){if(!e)return;const r=t.some(a=>a.sessionId!==e.sessionId&&a.name.trim()===e.name.trim()),n=e.sessionId.startsWith("remote:")?uc(e):"本机服务";return r?`${e.name} · ${n}`:e.name}async function UO(e){e.sessionId.startsWith("remote:")?await A6(e.sessionId):window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:e.sessionId}))}function zO(e){return{ready:"终端可达",shell:"Shell 终端",recovering:"正在检查投递目标",unchecked:"投递目标未检查","terminal-connected":"终端已连接",detached:"终端未连接","agent-exited":"Agent 已退出",offline:"已离线",ambiguous:"需确认目标终端","identity-mismatch":"终端身份已变化",unavailable:"终端暂不可达","service-reachable":"服务可达","service-unreachable":"服务不可达"}[e]??"在线"}function km(e){if(!e)return"暂无任务摘要";try{const t=JSON.parse(e);if(typeof t.prompt=="string")return Pf(t.prompt)||"暂无任务摘要"}catch{}return Pf(e)||"暂无任务摘要"}function HO(e){return{message:"消息",ask:"问题",reply:"回复",task:"任务",handoff:"交接",done:"完成"}[e]}function WO(e,t){const r=new Map(t.map(a=>[a.sessionId,$O(a,t)])),n=new Map;for(const a of e){const c=`${a.threadId}:${a.createdAt}:${a.fromSessionId??a.integrationOrigin?.integrationId??"user"}:${a.kind}:${a.responseKind??""}:${JSON.stringify(a.task??null)}:${a.content}`,l=n.get(c),d=a.toPrincipalId?`后台接入 ${a.toPrincipalId}`:r.get(a.toSessionId)??a.toSessionId.slice(0,8);if(l){l.toNames.push(d);const p={failed:-2,expired:-1,pending:0,delivered:1,read:2,stored:3};p[a.status]<p[l.status]&&(l.status=a.status);continue}n.set(c,{key:c,kind:a.kind,content:a.content,createdAt:a.createdAt,fromName:a.fromSessionId?r.get(a.fromSessionId)??a.fromSessionId.slice(0,8):a.integrationOrigin?`后台接入 ${a.integrationOrigin.integrationId}`:"你",toNames:[d],status:a.status,responseKind:a.responseKind,task:a.task,failureReason:a.failureReason})}return[...n.values()].sort((a,c)=>c.createdAt-a.createdAt)}function GO(e){return/timeout|timed out|超时|operation was aborted/i.test(e)?"连接超时,暂时无法访问该服务。请确认远端服务已启动,并检查网络或 VPN 连接。":/ECONNREFUSED|connection refused/i.test(e)?"远端拒绝连接,请确认服务已启动且端口正确。":/ENOTFOUND|EHOSTUNREACH|ENETUNREACH/i.test(e)?"无法访问远端地址,请检查地址和网络连接。":/certificate|fingerprint|TLS|证书/i.test(e)?"远端证书校验失败,请检查服务连接授权。":"服务连接暂时不可用,可查看连接详情并重试。"}function Lm({value:e,query:t}){const r=t.trim().toLocaleLowerCase();if(!r)return s.jsx(s.Fragment,{children:e});const n=e.toLocaleLowerCase(),a=[];let c=0,l;for(;(l=n.indexOf(r,c))>=0;)a.push(e.slice(c,l)),a.push(s.jsx("mark",{className:"rounded bg-primary/15 text-primary",children:e.slice(l,l+r.length)},l)),c=l+r.length;return a.push(e.slice(c)),s.jsx(s.Fragment,{children:a})}function VO({active:e,onClose:t,onNewSession:r,setError:n}){const[a,c]=b.useState(""),[l,d]=b.useState([]),[p,m]=b.useState(0),[x,y]=b.useState(),[w,v]=b.useState(50),[S,L]=b.useState(0),[E,R]=b.useState(!1),[B,z]=b.useState(null),[O,$]=b.useState(null),V=b.useRef(null),Z=b.useRef(0);b.useEffect(()=>{e&&V.current?.focus({preventScroll:!0})},[e]),b.useEffect(()=>{if(!e)return;const pe=++Z.current,ee=new AbortController;let _e;z(null),R(!0);const ze=async()=>{try{const Y=await J8(a.trim(),w,ee.signal);if(pe!==Z.current)return;d(Y.results),m(Y.total??Y.results.length),y(Y.index),Y.index?.building&&(_e=window.setTimeout(()=>{ze()},2500))}catch(Y){pe===Z.current&&!ee.signal.aborted&&z(Y instanceof Error?Y.message:"搜索失败")}finally{pe===Z.current&&R(!1)}};return _e=window.setTimeout(()=>{ze()},a.trim()?250:0),()=>{window.clearTimeout(_e),ee.abort(),++Z.current}},[e,a,w,S]);const le=pe=>{n(null),c(pe),d([]),m(0),v(50)},be=async pe=>{if(!O){if(pe.live){window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:pe.sessionId})),t();return}if(!(!pe.nativeKey&&!pe.resumeHistoryId)){$(pe.sessionId),n(null);try{const ee=pe.nativeKey?await e9(pe.nativeKey):await Ry(pe.resumeHistoryId);if("sessionId"in ee&&ee.sessionId)window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:ee.sessionId}));else if(ee.command)r({mode:"shell",cwd:ee.cwd,command:ee.command});else throw new Error("这条会话暂时无法恢复,请重新搜索");t()}catch(ee){n(ee instanceof Error?ee.message:"恢复失败")}finally{$(null)}}}};return s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"sticky -top-4 z-20 -mx-4 -mt-4 border-b border-border/15 bg-surface px-4 py-3",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-[13px] font-medium text-foreground",children:"历史会话搜索"}),s.jsx("p",{className:"mt-1 text-[10px] leading-relaxed text-muted-foreground",children:"搜索当前服务的 Codex、Claude 历史对话和 Termdock 终端记录,未启动的会话也能找到并恢复。"})]}),s.jsxs("label",{className:"relative mt-3 block",children:[s.jsx("span",{className:"sr-only",children:"搜索历史会话"}),s.jsx(jl,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),s.jsx("input",{ref:V,maxLength:512,className:`${$s} pl-9 pr-9`,value:a,onChange:pe=>le(pe.target.value),placeholder:"搜索会话名称、对话关键词、目录或 session ID"}),E?s.jsx(bn,{size:13,className:"absolute right-3 top-1/2 -translate-y-1/2 animate-spin text-muted-foreground"}):a&&s.jsx("button",{type:"button","aria-label":"清空搜索",className:"absolute right-1.5 top-1/2 -translate-y-1/2 rounded-md p-1.5 text-muted-foreground hover:bg-surface-2 hover:text-foreground",onClick:()=>le(""),children:s.jsx(In,{size:13})})]}),x?.building&&s.jsxs("div",{role:"status",className:"mt-2 text-[10px] text-muted-foreground",children:["正在建立历史索引:",x.indexed,"/",x.total," 个会话。可以先搜名称和目录,对话结果会自动补齐。"]}),x?.warning&&s.jsx("p",{role:"status",className:"mt-2 text-[10px] text-destructive",children:x.warning}),!!x?.failed&&s.jsxs("p",{role:"status",className:"mt-2 text-[10px] text-destructive",children:[x.failed," 个会话暂未完成索引,其余结果可正常使用。请稍后刷新重试。"]})]}),s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("p",{className:"text-[11px] text-foreground",children:[a.trim()?`找到 ${p} 个会话`:"最近的会话",p>l.length?` · 显示 ${l.length} 个`:""]}),s.jsxs("button",{type:"button",disabled:E,className:`${vr} text-muted-foreground hover:bg-surface-2 hover:text-foreground`,onClick:()=>L(pe=>pe+1),children:[s.jsx(bn,{size:12}),"刷新"]})]}),!a.trim()&&s.jsx("p",{className:"text-[10px] text-muted-foreground",children:"记得之前讨论过什么?输入一句话中的关键词,就能找到对应会话。历史对话与索引保存在当前服务机器上。"}),s.jsx("div",{className:"divide-y divide-border/10 border-y border-border/10",children:l.map(pe=>{const ee=pe.live||!!(pe.nativeKey||pe.resumeHistoryId),_e=O===pe.sessionId?"正在恢复…":pe.live?"打开会话":ee?"恢复会话":"仅供查阅",ze=pe.source==="codex"||pe.source==="claude"?pe.snippet:qO(pe),Y=pe.source==="codex"?"Codex 历史":pe.source==="claude"?"Claude 历史":"终端记录",ce=s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"break-words text-[12px] font-medium text-foreground",children:s.jsx(Lm,{value:pe.title,query:a})}),s.jsx("p",{className:"mt-0.5 break-all text-[9px] text-muted-foreground",children:s.jsx(Lm,{value:pe.cwd||"项目目录待索引",query:a})})]}),s.jsx("span",{className:`shrink-0 text-[10px] ${pe.live?"text-[var(--success)]":ee?"text-primary":"text-muted-foreground"}`,children:_e})]}),ze&&s.jsx("p",{className:"mt-2 line-clamp-3 break-words text-[10px] leading-relaxed text-foreground/75",children:s.jsx(Lm,{value:ze,query:a})}),s.jsxs("p",{className:"mt-2 text-[9px] text-muted-foreground",children:[Y," · ",Of(pe.updatedAt),a.trim()?` · ${pe.matchCount>=999?"999+":pe.matchCount} 处匹配`:"",ee?"":" · 没有可恢复记录"]}),pe.agentNativeSessionId&&s.jsx("p",{className:"mt-1 select-text break-all text-[9px] text-muted-foreground",children:pe.agentNativeSessionId})]});return ee?s.jsx("button",{disabled:!!O,onClick:()=>{be(pe)},className:"block w-full px-2 py-3 text-left transition hover:bg-surface-2 focus-visible:bg-surface-2 focus-visible:outline-none",children:ce},pe.nativeKey||pe.sessionId):s.jsx("article",{className:"px-2 py-3",children:ce},pe.sessionId)})}),p>l.length&&w<5e3&&s.jsx("button",{type:"button",disabled:E,className:`${vr} w-full bg-surface-2 text-foreground`,onClick:()=>v(pe=>pe+50),children:E?"正在加载…":"加载更多会话"}),B&&s.jsxs("div",{role:"alert",className:"rounded-lg bg-destructive/10 p-3 text-[11px] text-destructive",children:["搜索失败:",B,s.jsx("button",{type:"button",className:`${vr} ml-2`,onClick:()=>L(pe=>pe+1),children:"重试"})]}),!E&&!B&&l.length===0&&s.jsxs("div",{className:"border-y border-border/15 py-8 text-center",children:[s.jsx("p",{className:"text-[12px] text-foreground",children:x?.building?"历史对话仍在索引,请稍候":x?.warning||x?.failed?"暂未找到结果,部分历史记录尚不可搜索":a.trim()?`没有找到“${a.trim()}”`:"当前服务还没有可搜索的历史会话"}),s.jsx("p",{className:"mt-1 text-[10px] text-muted-foreground",children:x?.building?"新结果会自动显示,也可以先搜会话名称或目录。":"可尝试更短的关键词、项目目录或 session ID;其他机器的历史需切换到对应服务搜索。"}),a.trim()&&s.jsx("button",{className:`${vr} mt-3 bg-surface-2 text-foreground`,onClick:()=>le(""),children:"查看最近会话"})]})]})}function Pf(e){return e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g," ").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g," ").replace(/\(B/g," ").replace(/<[^>]{1,120}>/g," ").replace(/[─━│┃┄┅┆┇┈┉┊┋┌┐└┘├┤┬┴┼╭╮╯╰═║╔╗╚╝╠╣╦╩╬]+/g," ").replace(/([^\p{L}\p{N}\s])\1{3,}/gu," ").replace(/([A-Za-z])\1{12,}/g," ").replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g," ").replace(/\s+/g," ").trim().slice(0,280)}function qO(e){let t=Pf(e.snippet);for(const r of[e.title,e.cwd,e.agentSlug])r&&(t=t.split(r).join(" "));return Pf(t)}function YO(e){if(e.schedule.kind==="interval")return e.schedule.everyMinutes===60?"每小时":e.schedule.everyMinutes===1440?"每天":`每 ${e.schedule.everyMinutes} 分钟`;const t=["日","一","二","三","四","五","六"];return`${e.schedule.weekdays.length===7?"每天":e.schedule.weekdays.map(n=>`周${t[n]}`).join("、")} ${e.schedule.time}`}function ZO(e,t=Date.now(),r=t){if(e.kind==="interval"){const c=e.everyMinutes*6e4,l=Math.max(0,t-r);return r+(Math.floor(l/c)+1)*c}const[n,a]=e.time.split(":").map(Number);for(let c=0;c<=7;c+=1){const l=new Date(t);if(l.setDate(l.getDate()+c),l.setHours(n,a,0,0),l.getTime()>t&&e.weekdays.includes(l.getDay()))return l.getTime()}return t}function Of(e){return new Intl.DateTimeFormat("zh-CN",{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(e)}function KO(e){return e==="running"?"投递中":e==="success"?"已投递":e==="failed"?"投递失败":""}function XO(e){return e==="running"?"text-[var(--warning)]":e==="success"?"text-[var(--success)]":e==="failed"?"text-destructive":"text-muted-foreground"}function JO({text:e}){return s.jsx("div",{className:"rounded-xl border border-dashed border-border/20 px-4 py-8 text-center text-[11px] text-muted-foreground",children:e})}function eF({onOpenSettings:e,serverAttention:t,actions:r}){const{t:n}=Ur(),[a,c]=b.useState(!1),l=b.useRef(null),d=b.useRef(null),p=b.useRef(null),m=b.useId();return b.useLayoutEffect(()=>{if(!a)return;const x=l.current,y=p.current;if(!x||!y)return;const w=window.visualViewport,v=()=>{const L=x.getBoundingClientRect(),E=(w?.offsetLeft??0)+8,R=(w?.offsetTop??0)+8,B=(w?.width??window.innerWidth)-16,z=(w?.offsetTop??0)+(w?.height??window.innerHeight)-8,O=Math.max(0,Math.min(256,B)),$=Math.max(0,L.top-R-4),V=Math.max(0,z-L.bottom-4),Z=$>=180||$>=V;Object.assign(y.style,{width:`${O}px`,left:`${Math.max(E,Math.min(L.right-O,E+B-O))}px`,top:`${Z?L.top-4:L.bottom+4}px`,maxHeight:`${Z?$:V}px`,transform:Z?"translateY(-100%)":"none"})};v();const S=typeof ResizeObserver>"u"?null:new ResizeObserver(v);return S?.observe(x),window.addEventListener("resize",v),window.addEventListener("scroll",v,!0),w?.addEventListener("resize",v),w?.addEventListener("scroll",v),()=>{S?.disconnect(),window.removeEventListener("resize",v),window.removeEventListener("scroll",v,!0),w?.removeEventListener("resize",v),w?.removeEventListener("scroll",v)}},[a]),b.useEffect(()=>{if(!a)return;p.current?.querySelector('[role="menuitem"]')?.focus({preventScroll:!0});const x=y=>{y.target instanceof Node&&!l.current?.contains(y.target)&&!p.current?.contains(y.target)&&c(!1)};return document.addEventListener("pointerdown",x),()=>document.removeEventListener("pointerdown",x)},[a]),s.jsxs("div",{ref:l,role:"group","data-sidebar-gesture-ignore":!0,"aria-label":n("sidebar.moreActions"),className:"relative z-20 mt-2 flex items-center justify-between gap-2",onKeyDown:x=>{a&&x.key==="Escape"&&(x.preventDefault(),x.stopPropagation(),c(!1),d.current?.focus({preventScroll:!0}))},children:[s.jsxs("button",{type:"button",onClick:e,title:t?n("sidebar.serverAttention"):void 0,className:"inline-flex min-h-9 items-center gap-1.5 whitespace-nowrap rounded-lg px-2 text-[11px] text-muted-foreground transition hover:bg-surface-2 hover:text-foreground focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary",children:[s.jsx(bS,{size:14,className:t?"text-destructive":void 0}),s.jsx("span",{children:n("sidebar.settings")})]}),s.jsxs("button",{ref:d,type:"button","aria-haspopup":"menu","aria-expanded":a,"aria-controls":a?m:void 0,onClick:()=>c(x=>!x),onKeyDown:x=>{(x.key==="ArrowDown"||x.key==="ArrowUp")&&(x.preventDefault(),c(!0))},className:`inline-flex min-h-9 items-center gap-1.5 whitespace-nowrap rounded-lg px-2 text-[11px] transition focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary ${a?"bg-surface-2 text-foreground":"text-muted-foreground hover:bg-surface-2 hover:text-foreground"}`,children:[s.jsx(To,{size:15}),s.jsx("span",{children:n("sidebar.moreActions")})]}),a&&Xs.createPortal(s.jsx("div",{ref:p,id:m,role:"menu","data-sidebar-gesture-ignore":!0,"data-sidebar-composer-popover":"sidebar-launch-options","aria-label":n("sidebar.moreActions"),className:"fixed z-popover overflow-y-auto overscroll-contain rounded-xl border border-border/15 bg-surface p-1 shadow-[0_12px_32px_var(--app-shadow-soft)] animate-fade-in",onKeyDown:x=>{const y=[...x.currentTarget.querySelectorAll('[role="menuitem"]')],w=y.indexOf(document.activeElement);let v;if(x.key==="ArrowDown")v=(w+1)%y.length;else if(x.key==="ArrowUp")v=(w-1+y.length)%y.length;else if(x.key==="Home")v=0;else if(x.key==="End")v=y.length-1;else if(x.key==="Tab"){c(!1);return}else return;x.preventDefault(),y[v]?.focus({preventScroll:!0})},children:r.map(({label:x,icon:y,onSelect:w,separated:v})=>s.jsxs("div",{role:"none",children:[v&&s.jsx("div",{role:"separator",className:"mx-2 my-1 h-px bg-border/40"}),s.jsxs("button",{type:"button",role:"menuitem",tabIndex:-1,onClick:()=>{c(!1),w()},className:"flex min-h-10 w-full items-center gap-2.5 whitespace-nowrap rounded-lg px-2.5 text-left text-[12px] text-foreground transition hover:bg-surface-2 focus:bg-surface-2 focus:outline-none",children:[s.jsx(y,{size:15,className:"shrink-0 text-muted-foreground"}),s.jsx("span",{children:x})]})]},x))}),document.body)]})}const Fd=64,Mb=10,tF=120;function rF({children:e,open:t,onOpenChange:r,onClose:n,closeLabel:a,closeTitle:c,compact:l}){const d=b.useRef(null),p=b.useRef(null),m=b.useRef(0),[x,y]=b.useState(null),w=x??(t?Fd:0);return b.useEffect(()=>{if(!t)return;const v=S=>{S.target instanceof Node&&!d.current?.contains(S.target)&&r(!1)};return document.addEventListener("pointerdown",v,!0),()=>document.removeEventListener("pointerdown",v,!0)},[t,r]),s.jsxs("div",{ref:d,"data-sidebar-gesture-ignore":!0,"data-session-swipe":!0,className:`relative flex min-w-0 flex-1 items-center ${l?"":"gap-1"}`,style:{touchAction:"pan-y"},onPointerDown:v=>{if(m.current=0,!(v.pointerType!=="touch"&&v.pointerType!=="pen")){if(v.isPrimary===!1){p.current=null,y(null);return}!(v.target instanceof Element)||!v.target.closest(".sidebar-session-primary")||(p.current={pointerId:v.pointerId,x:v.clientX,y:v.clientY,startedAt:Date.now(),initialOffset:t?Fd:0,offset:t?Fd:0,horizontal:!1})}},onPointerMove:v=>{const S=p.current;if(!S||S.pointerId!==v.pointerId)return;const L=v.clientX-S.x,E=v.clientY-S.y;if(!S.horizontal){if(v.defaultPrevented||Date.now()-S.startedAt>=tF||Math.abs(E)>Mb){p.current=null;return}if(Math.abs(L)<=Mb)return;if(Math.abs(L)<Math.abs(E)*1.5||!t&&L<0){p.current=null;return}S.horizontal=!0,v.currentTarget.setPointerCapture?.(v.pointerId)}v.preventDefault(),S.offset=Math.max(0,Math.min(Fd,S.initialOffset+L)),y(S.offset)},onPointerUp:v=>{const S=p.current;!S||S.pointerId!==v.pointerId||(p.current=null,S.horizontal&&(m.current=Date.now()+600,r(S.offset>=Fd/2),y(null)))},onPointerCancel:()=>{p.current?.horizontal&&(m.current=Date.now()+600),p.current=null,y(null)},onClickCapture:v=>{if(Date.now()<m.current){m.current=0,v.preventDefault(),v.stopPropagation();return}t&&v.target instanceof Element&&v.target.closest(".sidebar-session-primary")&&(r(!1),v.preventDefault(),v.stopPropagation())},onKeyDown:v=>{t&&v.key==="Escape"&&(v.stopPropagation(),r(!1))},children:[s.jsx("div",{className:"shrink-0 overflow-hidden rounded-md transition-[width] duration-150 ease-out motion-reduce:transition-none",style:{width:w,transition:x===null?void 0:"none"},children:w>0&&s.jsxs("button",{type:"button",tabIndex:t?0:-1,"aria-hidden":!t,"aria-label":c,className:"flex min-h-8 w-16 flex-col items-center justify-center gap-0.5 bg-destructive py-1 text-[10px] text-destructive-foreground",onClick:v=>{v.stopPropagation(),r(!1),n(v)},children:[s.jsx(Rs,{size:14}),a]})}),e]})}const jb="recoverable-tmux";function nF({sessions:e,loading:t,attachingName:r,onRefresh:n,onRestore:a,onClose:c}){const{t:l}=Ur(),d=Wt(R=>R.collapsedGroups.has(jb)),p=Wt(R=>R.toggleGroupCollapsed),[m,x]=b.useState(null),[y,w]=b.useState(null),[v,S]=b.useState(null),L=b.useRef(!1),E=async R=>{if(!(!c||L.current)){L.current=!0,w(R),S(null);try{await c(R),x(null)}catch(B){S(B instanceof Error?B.message:l("sidebar.closeRecoverableSessionFailed"))}finally{L.current=!1,w(null)}}};return e.length===0?null:s.jsxs("section",{className:"mb-2 shrink-0 rounded-lg bg-[rgb(var(--tmux-rgb)_/_0.07)] p-1","aria-label":l("sidebar.recoverableSessions"),children:[s.jsxs("div",{className:"flex items-center gap-1 text-[10.5px] font-semibold text-[color:var(--tmux)]",children:[s.jsxs("button",{type:"button","aria-expanded":!d,onClick:()=>p(jb),className:"flex min-h-11 min-w-0 flex-1 items-center gap-2 rounded-md px-2 text-left hover:bg-surface-elevated md:min-h-8",children:[s.jsx(Ks,{size:12,className:`shrink-0 ${d?"":"rotate-90"}`}),s.jsx(Qc,{size:12,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:l("sidebar.recoverableSessions")}),s.jsx("span",{className:"text-muted-foreground",children:e.length})]}),n&&s.jsx("button",{type:"button",onClick:n,disabled:t||y!==null,className:"inline-flex h-11 w-11 shrink-0 items-center justify-center rounded-md text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground disabled:opacity-50 md:h-7 md:w-7","aria-label":l("sidebar.refreshRecoverableSessions"),title:l("sidebar.refreshRecoverableSessions"),children:s.jsx(bn,{size:11,className:t?"animate-spin":""})})]}),!d&&s.jsx("div",{className:"space-y-0.5",children:e.map(R=>{const B=R.friendlyName?.trim()||R.label?.trim()||R.name,z=Ku(R.cwd??null),O=r===R.name,$=m===R.name;return s.jsxs("div",{children:[s.jsxs("div",{className:"flex min-w-0 items-center",children:[s.jsxs("button",{type:"button",disabled:r!==null||y!==null||$,onClick:()=>a(R),className:"group flex min-h-11 min-w-0 flex-1 items-center gap-2 rounded-md px-2 text-left text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground disabled:opacity-60 md:min-h-10","aria-label":l("sidebar.restoreRecoverableSession",{name:B}),title:R.cwd||R.name,children:[s.jsx("span",{className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-[rgb(var(--tmux-rgb)_/_0.11)] text-[color:var(--tmux)]",children:O?s.jsx(_n,{size:12,className:"animate-spin"}):s.jsx(qc,{size:12})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block truncate text-[11.5px] font-semibold text-foreground",children:B}),s.jsx("span",{className:"block truncate text-[9.5px] text-muted-foreground",children:[R.program,z].filter(Boolean).join(" · ")||`tmux:${R.name}`})]}),s.jsx("span",{className:"shrink-0 text-[10px] font-medium text-[color:var(--tmux)] group-hover:text-foreground",children:l(O?"sidebar.restoringRecoverableSession":"sidebar.restore")})]}),c&&s.jsx("button",{type:"button",disabled:r!==null||y!==null,onClick:()=>{x(R.name),S(null)},className:"inline-flex h-11 w-11 shrink-0 items-center justify-center rounded-md text-muted-foreground transition hover:bg-destructive/15 hover:text-destructive disabled:opacity-50 md:h-7 md:w-7","aria-label":l("sidebar.closeSession",{name:B}),title:l("sidebar.closeSession",{name:B}),children:s.jsx(In,{size:12})})]}),$&&s.jsxs("div",{role:"group","aria-label":l("sidebar.closeSession",{name:B}),className:"space-y-2 rounded-md bg-surface px-2 py-2",children:[s.jsx("p",{className:"text-[11px] text-foreground",children:l("sidebar.confirmCloseRecoverableSession",{name:B})}),v&&s.jsx("p",{role:"alert",className:"text-[11px] text-destructive",children:v}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{type:"button",disabled:y!==null,onClick:()=>{x(null),S(null)},className:"min-h-11 rounded-md px-2 text-[11px] text-muted-foreground hover:bg-surface-elevated disabled:opacity-50 md:min-h-8",children:l("common.cancel")}),s.jsx("button",{type:"button",disabled:y!==null,onClick:()=>{E(R.name)},className:"min-h-11 rounded-md bg-destructive/15 px-2 text-[11px] text-destructive hover:bg-destructive/25 disabled:opacity-50 md:min-h-8",children:y===R.name?l("common.loading"):l("sidebar.endRecoverableSession")})]})]})]},R.name)})})]})}const $d="flex min-h-11 w-full items-center gap-2.5 rounded-lg px-3 text-left text-xs transition hover:bg-surface-2 focus:bg-surface-2 focus:outline-none",Db="min-h-11 rounded-lg px-4 text-xs transition disabled:opacity-40 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary";function sF({group:e,collapsed:t,onOpen:r,onMessages:n,onToggleCollapsed:a,onChanged:c,children:l}){const[d,p]=b.useState(null),[m,x]=b.useState(null),[y,w]=b.useState(""),[v,S]=b.useState(!1),L=b.useRef(!1),[E,R]=b.useState(""),B=b.useRef(null),z=b.useRef(null),O=b.useRef(null),$=b.useRef(null),V=b.useRef(null),Z=b.useId(),le=Cg(),be=()=>V.current?.isConnected?V.current:z.current,pe=()=>{L.current||(x(null),R(""))};Gc(O,!!d,()=>p(null),be),Gc($,!!m,pe,be);const ee=ce=>{V.current=document.activeElement instanceof HTMLElement&&B.current?.contains(document.activeElement)?document.activeElement:z.current;const qe=z.current?.getBoundingClientRect();p(ce??{x:qe?.left??8,y:qe?.bottom??8})};b.useEffect(()=>{d&&O.current?.querySelector('[role="menuitem"]')?.focus({preventScroll:!0})},[d]),b.useEffect(()=>{if(!d)return;const ce=we=>{we.target instanceof Node&&!O.current?.contains(we.target)&&!B.current?.contains(we.target)&&p(null)},qe=we=>{we.target instanceof Node&&O.current?.contains(we.target)||p(null)};return document.addEventListener("pointerdown",ce),window.addEventListener("resize",qe),window.addEventListener("scroll",qe,!0),()=>{document.removeEventListener("pointerdown",ce),window.removeEventListener("resize",qe),window.removeEventListener("scroll",qe,!0)}},[d]),b.useLayoutEffect(()=>{if(!d||!O.current)return;const ce=window.visualViewport,qe=(ce?.offsetLeft??0)+8,we=(ce?.offsetTop??0)+8,ye=Math.min(240,(ce?.width??innerWidth)-16),Le=we+(ce?.height??innerHeight)-16;Object.assign(O.current.style,{width:`${ye}px`,maxHeight:`${Le-we}px`,left:`${Math.max(qe,Math.min(d.x,qe+(ce?.width??innerWidth)-16-ye))}px`,top:`${Math.max(we,Math.min(d.y,Le-O.current.offsetHeight))}px`})},[d]);const _e=ce=>{p(null),ce()},ze=ce=>{R(""),w(e.name),x({kind:ce,group:e})},Y=async()=>{if(!(!m||L.current||m.kind==="rename"&&!y.trim())){L.current=!0,S(!0),R("");try{const ce=m.group,qe=m.kind==="delete"?(await Ey(ce.id,ce.updatedAt),null):(await Ml({id:ce.id,name:y.trim(),sessionIds:ce.sessionIds,expectedUpdatedAt:ce.updatedAt})).group;x(null),c(qe)}catch(ce){const qe=ce instanceof Error?ce.message:"操作失败,请重试";R(qe.includes("协作组已变化")?"协作组刚刚发生变化,请取消后重新打开操作。":qe)}finally{L.current=!1,S(!1)}}};return s.jsxs("div",{ref:B,className:"flex min-w-0 items-center","data-sidebar-gesture-ignore":!0,...le(()=>ee()),onContextMenu:ce=>{ce.preventDefault(),ce.stopPropagation(),ee({x:ce.clientX,y:ce.clientY})},onKeyDown:ce=>{(ce.key==="ContextMenu"||ce.shiftKey&&ce.key==="F10")&&(ce.preventDefault(),ce.stopPropagation(),ee())},children:[l,s.jsx("button",{ref:z,type:"button","aria-label":`协作组操作:${e.name}`,title:"协作组操作","aria-haspopup":"menu","aria-expanded":!!d,"aria-controls":d?`${Z}-menu`:void 0,className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-surface-elevated hover:text-foreground focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary md:h-[30px] md:w-7",onClick:ce=>{ce.stopPropagation(),d?p(null):ee()},children:s.jsx(To,{size:14})}),d&&Xs.createPortal(s.jsxs("div",{ref:O,id:`${Z}-menu`,role:"menu",tabIndex:-1,"aria-label":`协作组操作:${e.name}`,"data-sidebar-gesture-ignore":!0,className:"fixed z-popover overflow-y-auto overscroll-contain rounded-xl border border-border/15 bg-surface p-1 shadow-[0_12px_32px_var(--app-shadow-soft)]",onKeyDown:ce=>{const qe=Array.from(ce.currentTarget.querySelectorAll('[role="menuitem"]:not(:disabled)')),we=qe.indexOf(document.activeElement),ye=ce.key==="ArrowDown"?(we+1)%qe.length:ce.key==="ArrowUp"?(we-1+qe.length)%qe.length:ce.key==="Home"?0:ce.key==="End"?qe.length-1:null;ye!==null&&(ce.preventDefault(),ce.stopPropagation(),qe[ye]?.focus({preventScroll:!0})),ce.key==="Tab"&&(ce.preventDefault(),p(null))},children:[s.jsxs("button",{role:"menuitem",tabIndex:-1,className:$d,onClick:()=>_e(r),children:[s.jsx(qc,{size:15}),"打开看板"]}),s.jsxs("button",{role:"menuitem",tabIndex:-1,disabled:!n,className:`${$d} disabled:opacity-40`,onClick:()=>_e(()=>n?.()),children:[s.jsx(Xu,{size:15}),"成员与消息"]}),s.jsxs("button",{role:"menuitem",tabIndex:-1,className:$d,onClick:()=>_e(a),children:[s.jsx(Ks,{size:15,className:t?"":"rotate-90"}),t?"展开成员会话":"收起成员会话"]}),s.jsxs("button",{role:"menuitem",tabIndex:-1,className:$d,onClick:()=>_e(()=>ze("rename")),children:[s.jsx(ju,{size:15}),"重命名协作组"]}),s.jsx("div",{role:"separator",className:"mx-2 my-1 h-px bg-border/30"}),s.jsxs("button",{role:"menuitem",tabIndex:-1,className:`${$d} text-destructive`,onClick:()=>_e(()=>ze("delete")),children:[s.jsx(Rs,{size:15}),"删除协作组"]})]}),document.body),m&&Xs.createPortal(s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-modal-backdrop bg-black/50 backdrop-blur-sm",onClick:pe}),s.jsxs("section",{ref:$,role:"dialog","aria-modal":"true","aria-labelledby":`${Z}-title`,"aria-describedby":`${Z}-description`,tabIndex:-1,className:"fixed left-1/2 top-1/2 z-modal-panel max-h-[calc(100dvh-2rem)] w-[min(24rem,calc(100vw-2rem))] -translate-x-1/2 -translate-y-1/2 overflow-y-auto rounded-2xl border border-border/15 bg-surface p-4 text-foreground shadow-[0_28px_70px_var(--app-shadow-strong)]",children:[s.jsxs("header",{className:"flex items-center gap-2",children:[s.jsx("h2",{id:`${Z}-title`,className:"min-w-0 flex-1 text-sm font-semibold",children:m.kind==="delete"?"删除协作组":"重命名协作组"}),s.jsx("button",{type:"button","aria-label":"关闭协作组操作",disabled:v,className:"flex h-11 w-11 items-center justify-center rounded-lg hover:bg-surface-2",onClick:pe,children:s.jsx(In,{size:16})})]}),s.jsx("p",{id:`${Z}-description`,className:"my-3 break-words text-xs leading-6 text-muted-foreground",children:m.kind==="delete"?s.jsxs(s.Fragment,{children:["确定删除“",m.group.name,"”?协作组及组内消息会被移除,成员终端会保留。此操作无法撤销。",m.group.federated&&"删除会同步到其他服务。"]}):"修改协作组的名称。"}),s.jsxs("form",{onSubmit:ce=>{ce.preventDefault(),Y()},children:[m.kind==="rename"&&s.jsxs("label",{className:"block text-xs text-muted-foreground",children:["协作组名称",s.jsx("input",{autoFocus:!0,required:!0,maxLength:256,disabled:v,className:"mt-2 min-h-11 w-full rounded-lg border border-border/30 bg-surface-2 px-3 text-sm text-foreground outline-none focus:border-primary",value:y,onChange:ce=>w(ce.target.value)})]}),E&&s.jsx("p",{role:"alert",className:"mt-3 break-words text-xs leading-5 text-destructive",children:E}),s.jsxs("footer",{className:"mt-4 flex justify-end gap-2",children:[s.jsx("button",{type:"button",disabled:v,className:`${Db} bg-surface-2`,onClick:pe,children:"取消"}),s.jsxs("button",{type:"submit",disabled:v||m.kind==="rename"&&!y.trim(),className:`${Db} inline-flex items-center gap-2 ${m.kind==="delete"?"bg-destructive text-destructive-foreground":"bg-primary text-primary-foreground"}`,children:[v&&s.jsx(bn,{size:14,className:"animate-spin"}),v?m.kind==="delete"?"正在删除…":"正在保存…":m.kind==="delete"?"确认删除":"保存名称"]})]})]})]})]}),document.body)]})}function iF(e,t){return qy(e,t)}function Ud(e,t){const r=new Set(e),n=t.filter(c=>c.sessionIds.length>=2&&c.sessionIds.every(l=>r.has(l))),a=new Set;return e.flatMap(c=>{const l=n.find(d=>d.sessionIds.includes(c));return l?a.has(l.id)?[]:(a.add(l.id),[{sessionIds:l.sessionIds,workspace:l}]):[{sessionIds:[c]}]})}function zd(e,t,r,n=[]){const a=new Map,c=new Map,l=new Set(e.map(x=>x.id));for(const x of n){const y=x.sessionIds.filter(v=>l.has(v));if(!y.length)continue;const w=y.length===x.sessionIds.length?x:{...x,sessionIds:y};y.forEach(v=>a.set(v,w))}for(const x of t)if(!(x.sessionIds.length<2||!x.sessionIds.every(y=>l.has(y)))&&!x.sessionIds.some(y=>a.has(y)))for(const y of x.sessionIds)c.set(y,x);const d=new Set,p=new Set,m=[];for(const x of e){const y=a.get(x.id);if(y){if(d.has(y.id))continue;d.add(y.id);const S=y.sessionIds.flatMap(L=>{const E=r.get(L);return E?[E]:[]});m.push({kind:"collaboration",id:`collaboration:${y.id}`,group:y,members:S,sessionIds:y.sessionIds});continue}const w=c.get(x.id);if(!w){m.push({kind:"session",id:`session:${x.id}`,session:x,sessionIds:[x.id]});continue}if(p.has(w.id))continue;p.add(w.id);const v=w.sessionIds.flatMap(S=>{const L=r.get(S);return L?[L]:[]});m.push({kind:"workspace",id:`workspace:${w.id}`,workspace:w,members:v,sessionIds:w.sessionIds})}return m}function Bb(e,t,r){const n=Math.min(e.length,Math.max(0,r)),a=e.slice(0,n).flatMap(l=>l.sessionIds.filter(d=>d!==t)),c=e.slice(n).flatMap(l=>l.sessionIds.filter(d=>d!==t));return[...a,t,...c]}function aF({status:e,detail:t,needsReview:r,inCopyMode:n}){return s.jsx(UP,{status:e,detail:t,needsReview:r,inCopyMode:n})}function Qb({isOpen:e,drawerWidthPx:t,onClose:r,onOpen:n,sessions:a,activeSessionId:c,sessionStates:l,onJumpToNextAttention:d,onNewSession:p,onCloseSession:m,onSplitSession:x,onCloseSplit:y,onRemoveFromSplit:w,splitWorkspaces:v,onSetSplitLayout:S,onReorderSplitWorkspace:L,onCombineSplitSessions:E,onReorderSessions:R,onSessionMenu:B,onOpenSettings:z,onOpenQuota:O,updateState:$,updateActionPending:V=!1,onConfirmUpdateRestart:Z,onRetryUpdate:le,serverHealthState:be,tmuxAvailable:pe=!0,defaultSessionMode:ee="shell",push:_e,pinned:ze,onTogglePinned:Y,recoverableTmuxSessions:ce=[],recoverableTmuxSessionsLoading:qe=!1,onRefreshRecoverableTmuxSessions:we,onCloseRecoverableTmuxSession:ye}){const{t:Le}=Ur(),[,Be]=b.useState(0),[ne,Fe]=b.useState(null),[ke,Ee]=b.useState(!1),[Pe,Ne]=b.useState(!1),[oe,We]=b.useState(null),nt=b.useRef(!1),gt=b.useRef(0),ue=b.useCallback(G=>{G||(gt.current+=1),Ee(G)},[]),[Ze,at]=b.useState(!1),Ie=Ei(G=>G.groupId),[Ge,Ce]=b.useState({}),H=Ze||Object.keys(Ge).length>0,ae=b.useRef(!1),Ae=b.useRef(!1),[Ye,et]=b.useState(null);b.useEffect(()=>{let G=!1;return fc().then(Me=>{G||ae.current||Ce(Object.fromEntries(r3(Me.collaborationPanels?.[Uf()]).map($e=>[$e,!0])))}).catch(()=>{}),()=>{G=!0}},[]);const St=async(G,Me)=>{ae.current=!0,await Fa({floatingGroupId:Me},G),Ce($e=>({...$e,[G]:Me!==null}))},[Gt,Qt]=b.useState([]),[wt,zt]=b.useState(!1),[Vt,Kt]=b.useState(null),[Ot,It]=b.useState(null),[xe,Ve]=b.useState(null),[ht,q]=b.useState(null),ut=Lu(G=>G.tasks),qt=Lu(G=>G.allTasks),[tt,De]=b.useState(0),[nr,Ke]=b.useState(null),_t=b.useRef(!1),[$t,yt]=b.useState({}),xt=Lu(G=>G.error),[Rt,Ct]=b.useState(!1);b.useEffect(()=>{const G=()=>{document.hidden||Lu.getState().refresh()};G();const Me=window.setInterval(G,5e3);return document.addEventListener("visibilitychange",G),()=>{clearInterval(Me),document.removeEventListener("visibilitychange",G)}},[]);const fr=async G=>(ue(!1),ae.current=!0,G?(Ei.getState().open(G),Qr(),!0):(at(!0),Qr(),!0)),Yt=df(G=>G.collaborationGroups),Sr=df(G=>G.setCollaborationGroups),[pn,dr]=b.useState({mode:ee}),{preference:me,agents:Gr,detecting:ot,refresh:pt,selectAgent:ir}=gO(),Mn=b.useRef(null),Xr=!!($?.latestVersion&&["installing","ready","restarting","error"].includes($.status)),je=!!be?.attention,st=[Le("sidebar.moreActions"),je?Le("sidebar.serverAttention"):null,Xr&&$?.latestVersion?Le("sidebar.updateAvailable",{version:$.latestVersion}):null].filter(Boolean).join(": "),bt=Wt(G=>G.groupByFolder),Br=Wt(G=>G.collapsedGroups),Vr=Wt(G=>G.toggleGroupCollapsed),Cr=b.useRef(null),qr=b.useRef(null),mn=b.useRef(null),on=b.useRef(0),zr=b.useRef(!1),un=b.useRef(null),Er=b.useRef(null),[re,mt]=b.useState(!1),Mt=b.useRef([]),rr=b.useRef(null),Ar=b.useRef(null),Fr=b.useRef(new Set),Xt=b.useRef(null),Zr=b.useMemo(()=>new Set(v.flatMap(G=>G.sessionIds)),[v]),Jt=b.useMemo(()=>new Map(a.map(G=>[G.id,G])),[a]),Pr=b.useMemo(()=>iF(Yt,new Set(Jt.keys())),[Yt,Jt]),Hr=b.useCallback(async()=>{const G=++on.current;try{const Me=await Q1();if(G!==on.current)return;Sr(Array.isArray(Me.groups)?Me.groups:[])}catch{}},[]);b.useEffect(()=>Ny(G=>Sr(G.groups)),[]),b.useEffect(()=>{Hr();const G=window.setInterval(()=>{Hr()},1e4),Me=()=>{Hr()};return window.addEventListener("focus",Me),()=>{on.current+=1,window.clearInterval(G),window.removeEventListener("focus",Me)}},[Hr]),b.useEffect(()=>{(e||!H)&&Hr()},[H,e,Hr]);const ps=b.useCallback(()=>{Mt.current=Array.from(document.querySelectorAll("[data-collaboration-member], [data-collaboration-background]")).flatMap(G=>{const Me=G.dataset.collaborationMember??"",$e=G.hasAttribute("data-collaboration-background"),Je=G.closest("[data-collaboration-group]")?.dataset.collaborationGroup;if(!Me&&!$e||!Je)return[];const it=[];for(let Tt=G.parentElement;Tt;Tt=Tt.parentElement)it.push({element:Tt,top:Tt.scrollTop,left:Tt.scrollLeft});return[{element:G,sessionId:Me,groupId:Je,background:$e,rect:G.getBoundingClientRect(),scrollParents:it}]})},[]),Mr=b.useCallback((G,Me)=>{if(!zr.current)return;document.querySelectorAll("[data-split-exit-drop-index]").forEach(K=>K.removeAttribute("data-active")),document.querySelectorAll("[data-drop-active]").forEach(K=>K.removeAttribute("data-drop-active"));const Je=document.elementsFromPoint(G,Me).map(K=>K.closest("[data-collaboration-background]")).find(Boolean)?.closest("[data-collaboration-group]");if(Je?.dataset.collaborationGroup){Je.dataset.dropActive="true",Ar.current={kind:"collaboration",groupId:Je.dataset.collaborationGroup,background:!0};return}const it=Mt.current.find(K=>{if(K.sessionId===Er.current||!K.element.isConnected)return!1;const fe=K.scrollParents.reduce((ve,lt)=>ve+lt.element.scrollLeft-lt.left,0),Qe=K.scrollParents.reduce((ve,lt)=>ve+lt.element.scrollTop-lt.top,0);return G>=K.rect.left-fe&&G<=K.rect.right-fe&&Me>=K.rect.top-Qe+K.rect.height*.25&&Me<=K.rect.bottom-Qe-K.rect.height*.25});if(it?.background){it.element.closest("[data-collaboration-group]")?.setAttribute("data-drop-active","true"),Ar.current={kind:"collaboration",groupId:it.groupId,background:!0};return}if(it&&!v.find(fe=>fe.sessionIds.includes(it.sessionId))?.sessionIds.includes(Er.current??"")){it.element.dataset.dropActive="true",Ar.current={kind:"split",sessionId:it.sessionId,groupId:it.groupId};return}const Tt=document.elementsFromPoint(G,Me).filter(K=>{const fe=K.closest("[data-rfd-draggable-id]");return!fe||!["session:","split-member:","collaboration-member:"].some(Qe=>fe.dataset.rfdDraggableId===`${Qe}${Er.current}`)}),kt=Tt.map(K=>K.closest("[data-collaboration-group]")).find(K=>K?.dataset.collaborationGroup);if(kt?.dataset.collaborationGroup){const K=kt.dataset.collaborationGroup,fe=Tt.map(vt=>vt.closest("[data-collaboration-split]")).find(Boolean),Qe=Tt.map(vt=>vt.closest("[data-collaboration-member]")).find(Boolean),ve=Qe?.dataset.collaborationMember??fe?.dataset.splitAnchor,lt=K===un.current&&v.some(vt=>vt.sessionIds.includes(ve??"")&&vt.sessionIds.includes(Er.current??""));if(ve&&!lt&&(K!==un.current||!Qe&&fe)){kt.dataset.dropActive="true";const vt=Qe??fe;vt&&(vt.dataset.dropActive="true"),Ar.current={kind:"split",sessionId:ve,groupId:K}}else{const vt=Tt.some(br=>br.closest("[data-collaboration-background]"));(K!==un.current||vt)&&(kt.dataset.dropActive="true"),Ar.current={kind:"collaboration",groupId:K,background:vt}}return}const ft=Array.from(document.querySelectorAll("[data-sidebar-entity-list-id]")).filter(K=>K.dataset.sidebarEntityListId===rr.current).find(K=>{const fe=K.getBoundingClientRect();return G>=fe.left&&G<=fe.right&&Me>=fe.top-8&&Me<=fe.bottom+8});if(!ft){Ar.current=null;return}const Bt=Array.from(ft.children).filter(K=>K instanceof HTMLElement&&K.hasAttribute("data-sidebar-entity-index")),W=Bt.findIndex(K=>{const fe=K.getBoundingClientRect();return Me<fe.top+fe.height/2}),N=W<0?Bt.length:W;Ar.current={kind:"list",listId:ft.dataset.sidebarEntityListId??"",index:N};const U=Array.from(ft.querySelectorAll(":scope > [data-sidebar-entity-index] > [data-split-exit-drop-index]")).find(K=>K.dataset.splitExitDropIndex===String(N));U instanceof HTMLElement&&(U.dataset.active="true")},[v]);b.useEffect(()=>{const G=$e=>Mr($e.clientX,$e.clientY),Me=$e=>{const Je=$e.touches[0];Je&&Mr(Je.clientX,Je.clientY)};return window.addEventListener("pointermove",G),window.addEventListener("touchmove",Me,{passive:!0}),()=>{window.removeEventListener("pointermove",G),window.removeEventListener("touchmove",Me)}},[Mr]);const jn=b.useCallback((G,Me)=>{try{G(Me)}finally{document.querySelectorAll("[data-sidebar-dragging]").forEach($e=>{delete $e.dataset.sidebarDragging}),zr.current=!1,Mt.current=[],mt(!1),un.current=null,Er.current=null,rr.current=null,Ar.current=null,document.querySelectorAll("[data-split-exit-drop-index]").forEach($e=>$e.removeAttribute("data-active")),document.querySelectorAll("[data-drop-active]").forEach($e=>$e.removeAttribute("data-drop-active"))}},[]),Tr=b.useMemo(()=>a.filter(G=>!Zr.has(G.id)),[a,Zr]),Jr=b.useMemo(()=>{let G=0;for(const Me of a)l.get(Me.id)?.agentStatus==="working"&&(G+=1);return G},[a,l]);b.useLayoutEffect(()=>{const G=Cr.current,Me=qr.current;if(!e||!G||!Me){mn.current=null;return}const $e=Me.getBoundingClientRect(),Je=G.getBoundingClientRect(),it={item:G,top:Math.round(Je.top-$e.top+Me.scrollTop),height:Math.round(Je.height),viewportHeight:Me.clientHeight},Tt=mn.current;if(mn.current=it,Tt?.item===it.item&&Tt.top===it.top&&Tt.height===it.height&&Tt.viewportHeight===it.viewportHeight||zr.current||Me.clientHeight===0)return;const kt=8,Dt=Je.top-$e.top,ft=Je.bottom-$e.top;Dt<kt?Me.scrollTop+=Dt-kt:ft>Me.clientHeight-kt&&(Me.scrollTop+=ft-Me.clientHeight+kt)});const ln=b.useMemo(()=>{if(!bt||!c)return null;const G=l.get(c)?.cwd??null;return HS(G)},[bt,c,l]);b.useEffect(()=>{if(!bt){Xt.current=null,Fr.current.clear();return}if(!c){Xt.current=null;return}const G=Wt.getState(),Me=Fr.current,$e=Xt.current,Je=ln;$e!==null&&$e!==Je&&Me.has($e)&&(G.collapsedGroups.has($e)||G.toggleGroupCollapsed($e),Me.delete($e)),Je!==null&&Je!==""&&G.collapsedGroups.has(Je)&&(G.toggleGroupCollapsed(Je),Me.add(Je)),Xt.current=Je},[bt,c,ln]),b.useEffect(()=>{e||ue(!1)},[e]),b.useEffect(()=>{dr(G=>({...G,command:me?.command}))},[me]),b.useEffect(()=>{if(!ke)return;let G=!1;return zt(!0),It(null),lx().then(Me=>{G||Qt(Me)}).catch(()=>{G||It(Le("sidebar.resumeHistoryLoadFailed"))}).finally(()=>{G||zt(!1)}),()=>{G=!0}},[ke,Le]),b.useEffect(()=>{if(!ne)return;const G=Me=>{Me instanceof KeyboardEvent&&Me.key!=="Escape"||Me instanceof PointerEvent&&Me.target instanceof Node&&Mn.current?.contains(Me.target)||Fe(null)};return window.addEventListener("pointerdown",G),window.addEventListener("keydown",G),()=>{window.removeEventListener("pointerdown",G),window.removeEventListener("keydown",G)}},[ne]);const Qr=()=>{!_e&&!ze&&r()};b.useEffect(()=>{const G=Me=>{ue(!1);const{groupId:$e,dock:Je}=Me.detail;ae.current=!0,Kn.getState().setDock($e,{...Je,preferredWidth:360}),Ce(it=>({...it,[$e]:!0})),Ei.getState().terminal(),Qr()};return window.addEventListener("termdock:open-collaboration-messages",G),()=>window.removeEventListener("termdock:open-collaboration-messages",G)},[Qr]);const ks=ee==="tmux"&&!pe?"shell":ee,Dr=(G,Me=!1)=>{if(nt.current)return;nt.current=!0,Ne(!0),We(null);const $e=gt.current;p({...G,shouldActivate:()=>$e===gt.current&&(G.shouldActivate?.()??!0),onResult:Je=>{if(nt.current=!1,Ne(!1),!Je.ok){We(Je.error);return}$e===gt.current&&(Me&&ue(!1),Qr())}})},en=()=>{Dr({mode:ks})},xn=()=>{me&&Dr({mode:ks,command:me.command})},X=G=>{ue(!1),Ve(G.name),p({mode:"tmux",tmuxSessionName:G.name,cwd:G.cwd??void 0}),Qr()};b.useEffect(()=>{xe&&(ce.some(G=>G.name===xe)||Ve(null))},[xe,ce]);const He=(G,Me)=>{Dr({...pn,cwd:pn.cwd?.trim()||void 0,command:Me??G?.command},!0)},Nt=async G=>{Kt(G.id),It(null);try{const Me=await Ry(G.id);Dr({mode:"shell",cwd:Me.cwd,command:Me.command},!0)}catch(Me){const $e=Me&&typeof Me=="object"&&"code"in Me?String(Me.code??""):"";It(Le($e==="AGENT_SESSION_ACTIVE_ELSEWHERE"?"tab.resumeAgentConflict":"sidebar.resumeHistoryFailed"))}finally{Kt(null)}},Et=async G=>{Qt(Me=>Me.filter($e=>$e.id!==G));try{await u9(G)}catch{It(Le("sidebar.resumeHistoryRemoveFailed")),lx().then(Qt).catch(()=>{})}},tr=()=>{if(ke){ue(!1);return}nt.current||(gt.current+=1,nt.current||We(null),dr({mode:ee==="tmux"&&!pe?"shell":ee,cwd:c?l.get(c)?.cwd??void 0:void 0,command:me?.command}),ue(!0))},jr=b.useCallback(G=>{const Me=l.get(G);return Me?.agentStatus==="waiting"||Me?.agentNeedsReview?"bg-[rgb(var(--warning-rgb)_/_0.10)] text-foreground":Me?.agentStatus==="working"?"bg-[rgb(var(--success-rgb)_/_0.08)] text-foreground":Me?.inCopyMode?"bg-[rgb(var(--tmux-rgb)_/_0.08)] text-foreground":null},[l]),cr=Cg(),[Cn,Ls]=b.useState(null);b.useEffect(()=>{e||Ls(null)},[e]);const Xn=b.useCallback((G,Me,$e,Je,it)=>{const Tt=!Ie&&G.id===c,kt=Zr.has(G.id),Dt=!!($e&&kt),ft=l.get(G.id),Bt=Ku(ft?.cwd??null),W=ft?.shellTitle??r9(G.id),N=W===ft?.cwd||W===Bt?null:W,U=n9(G,ft?.activeProgram??null,null,s9,N,ft?.promptState??null),K=!!(ft?.tuiProgress&&ft.tuiProgress.state!=="remove"),Qe=ft?.promptState==="running"||ft?.agentStatus==="working"||K?"bg-[var(--success)]":ft?.agentStatus==="waiting"||ft?.agentNeedsReview?"bg-[var(--warning)]":ft?.inCopyMode?"bg-[var(--tmux)]":"bg-primary";return s.jsxs(rF,{open:Cn===G.id,onOpenChange:ve=>Ls(lt=>ve?G.id:lt===G.id?null:lt),onClose:ve=>m(G.id,ve,{skipConfirmation:!0}),closeLabel:Le("common.close"),closeTitle:Le("sidebar.closeSession",{name:U}),compact:$e,children:[s.jsxs("button",{ref:Tt?Cr:null,type:"button",...Me??{},onContextMenu:ve=>{B&&(ve.preventDefault(),B(G.id,{x:ve.clientX,y:ve.clientY}))},onClick:()=>{ue(!1),Ei.getState().terminal(),window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:G.id})),Qr()},className:`sidebar-session-primary relative min-w-0 flex flex-1 items-center overflow-hidden text-left ${Me?"cursor-grab active:cursor-grabbing ":""}${$e?"gap-1.5 py-0.5 pl-1.5 pr-0.5":"gap-1.5 py-1 pl-2 pr-1"}`,title:ft?.cwd??G.name,children:[Tt&&s.jsx("span",{className:`absolute inset-y-2 left-0 w-0.5 rounded-full ${Qe}`}),s.jsxs("span",{className:`relative inline-flex shrink-0 items-center justify-center rounded-md ${$e?"h-5 w-[22px]":"h-[22px] w-[22px]"} ${Tt?G.mode==="tmux"?"bg-[rgb(var(--tmux-rgb)_/_0.15)] text-[color:var(--tmux)]":"bg-primary/15 text-primary":G.mode==="tmux"?"bg-surface text-[rgb(var(--tmux-rgb)_/_0.80)]":"bg-surface text-muted-foreground"}`,children:[ft?.isConnecting||K&&!ft?.agentStatus?s.jsx(_n,{size:$e?10:11,className:"animate-spin"}):ft?.agent??cx(G.id)?s.jsx(Wc,{agent:ft?.agent??cx(G.id),size:$e?13:15}):G.mode==="tmux"?s.jsx(qc,{size:$e?10:11}):s.jsx($o,{size:$e?10:11}),s.jsx(aF,{status:ft?.agentStatus??null,detail:ft?.agentStatusDetail,needsReview:ft?.agentNeedsReview,inCopyMode:ft?.inCopyMode})]}),s.jsx("span",{className:`min-w-0 flex-1 truncate leading-tight ${$e?"text-[11px]":"text-[12px]"} ${Tt?"font-medium text-foreground":""} ${ft?.inCopyMode?"text-[color:var(--tmux)]":""}`,children:U}),s.jsx($5,{sessionIds:[G.id]})]}),Je,s.jsx("button",{type:"button",onClick:ve=>{ve.stopPropagation(),Dt?w(G.id):kt?y(G.id):x(G.id)},className:`sidebar-session-action inline-flex shrink-0 items-center justify-center rounded-md transition hover:bg-primary/15 hover:text-primary active:scale-95 ${$e?"h-6 w-6":"h-[26px] w-[26px]"} ${kt?"bg-primary/15 text-primary":"text-muted-foreground/70"}`,"aria-label":`${Le(Dt?"tab.splitRemovePane":kt?"tab.splitClose":"tab.split")} ${U}`,title:Le(Dt?"tab.splitRemovePane":kt?"tab.splitClose":"tab.split"),children:Dt?s.jsx(MS,{size:11}):s.jsx(Il,{size:12})}),it??s.jsx("button",{type:"button",onClick:ve=>{ve.stopPropagation(),m(G.id,ve)},className:`sidebar-session-action inline-flex shrink-0 items-center justify-center rounded-md text-muted-foreground/70 transition hover:bg-destructive/15 hover:text-destructive active:scale-95 ${$e?"h-6 w-6":"h-[26px] w-[26px]"}`,"aria-label":Le("sidebar.closeSession",{name:U}),title:Le("common.close"),children:s.jsx(In,{size:$e?11:12})})]})},[c,Zr,l,m,x,y,w,B,Le,Cn]),cn=b.useMemo(()=>cf(a,G=>l.get(G.id)?.cwd??null,bt,Le("sidebar.ungrouped"),v,Pr).groups,[Pr,bt,a,l,v,Le]),dn=b.useMemo(()=>zd(a,v,Jt,Pr),[Pr,a,Jt,v]),_r=b.useCallback(G=>{mt(G.draggableId.startsWith("collaboration:")||G.draggableId.startsWith("workspace:"));const Me=G.draggableId.replace(/^split-member:/,"");Er.current=G.draggableId.replace(/^(?:session|split-member|collaboration-member):/,"");const $e=G.type==="split-member"?v.find(Dt=>Dt.sessionIds.includes(Me)):null,Je=G.type==="collaboration-member"?G.source.droppableId.replace(/^collaboration-members:/,""):null,it=Je?Pr.find(Dt=>Dt.id===Je):null;zr.current=!!($e||it||G.type==="session"&&G.draggableId.startsWith("session:")),zr.current&&document.querySelectorAll("[data-collaboration-group]").forEach(Dt=>{Dt.dataset.sidebarDragging="true"}),un.current=it?.id??null;const Tt=$e?.sessionIds??it?.sessionIds??[],kt=Tt.length>0?cn.find(Dt=>Tt.every(ft=>Dt.sessions.some(Bt=>Bt.id===ft))):null;rr.current=bt?kt?`group-sessions:${kt.key}`:null:Tt.length>0?"sidebar-entities":null,Ar.current=null},[Pr,cn,bt,v]),Or=b.useCallback((G,Me,$e)=>{if(Me===$e)return;const Je=Me?Yt.find(ft=>ft.id===Me):null,it=$e?Yt.find(ft=>ft.id===$e):null;if($e&&!it)return;if(it){const ft=a.map(W=>W.id).filter(W=>W!==G);let Bt=-1;ft.forEach((W,N)=>{it.sessionIds.includes(W)&&(Bt=N)}),Bt>=0&&(ft.splice(Bt+1,0,G),R(ft))}const Tt=Je?.sessionIds.filter(ft=>ft!==G)??[],kt=it?[...it.sessionIds.filter(ft=>ft!==G),G]:[];Sr(ft=>ft.flatMap(Bt=>Bt.id===Me?[{...Bt,sessionIds:Tt}]:Bt.id===$e?[{...Bt,sessionIds:kt}]:[Bt])),q(null),(Je&&it?i9({sourceGroupId:Je.id,targetGroupId:it.id,sessionId:G,expectedSourceUpdatedAt:Je.updatedAt,expectedTargetUpdatedAt:it.updatedAt}):Je?Ml({id:Je.id,name:Je.name,sessionIds:Tt,expectedUpdatedAt:Je.updatedAt}):it?Ml({id:it.id,name:it.name,sessionIds:kt,expectedUpdatedAt:it.updatedAt}):Promise.resolve()).then(()=>Hr(),ft=>(q(ft instanceof Error?ft.message:"协作成员移动失败"),Hr()))},[Yt,Hr,a,R]),Gn=b.useCallback((G,Me,$e,Je=!1)=>{const it=Yt.find(fe=>fe.id===G);if(!it||Me===$e)return;const Tt=it.sessionIds.filter(fe=>!fe.startsWith("remote:")),kt=Ud(Tt,v).flatMap(fe=>fe.sessionIds),Dt=O5(qt,it.id),ft=Je&&!$t[it.id]?kt.filter(fe=>!Dt.has(fe)||fe===c||Zr.has(fe)):kt.slice(),Bt=new Set(ft),[W]=ft.splice(Me,1);if(!W)return;ft.splice($e,0,W);let N=0;const U=kt.map(fe=>Bt.has(fe)?ft[N++]:fe),K=v.find(fe=>fe.sessionIds.includes(W));if(K&&K.sessionIds.every(fe=>it.sessionIds.includes(fe))){const fe=U.filter(Qe=>K.sessionIds.includes(Qe));L(K.id,fe)}U.push(...it.sessionIds.filter(fe=>fe.startsWith("remote:"))),Sr(fe=>fe.map(Qe=>Qe.id===G?{...Qe,sessionIds:U}:Qe)),q(null),Ml({id:it.id,name:it.name,sessionIds:U,expectedUpdatedAt:it.updatedAt}).then(()=>Hr(),fe=>(q(fe instanceof Error?fe.message:"成员排序失败"),Hr()))},[Yt,Hr,v,L,qt,$t,c,Zr]);b.useEffect(()=>{const G=Me=>{const{sourceId:$e,targetId:Je}=Me.detail;if(!$e||!Je||$e===Je)return;const it=cf(a,ve=>l.get(ve.id)?.cwd??null,bt,"",v,Pr).arranged.map(ve=>ve.id),Tt=it.indexOf($e),kt=it.indexOf(Je);if(Tt<0||kt<0)return;const Dt=Pr.find(ve=>ve.sessionIds.includes($e));if(Dt?.sessionIds.includes(Je)){const ve=Ud(Dt.sessionIds,v).flatMap(lt=>lt.sessionIds);Gn(Dt.id,ve.indexOf($e),ve.indexOf(Je));return}const ft=v.filter(ve=>ve.sessionIds.length>=2&&ve.sessionIds.every(lt=>Jt.has(lt))&&!Pr.some(lt=>ve.sessionIds.some(vt=>lt.sessionIds.includes(vt)))),Bt=ft.find(ve=>ve.sessionIds.includes($e));if(Bt?.sessionIds.includes(Je)){const ve=[...Bt.sessionIds];ve.splice(ve.indexOf($e),1),ve.splice(Bt.sessionIds.indexOf(Je),0,$e),L(Bt.id,ve);return}const W=ve=>Pr.find(lt=>lt.sessionIds.includes(ve))?.sessionIds??ft.find(lt=>lt.sessionIds.includes(ve))?.sessionIds??[ve],N=new Set(W($e)),U=new Set(W(Je)),K=it.filter(ve=>!N.has(ve)),fe=K.flatMap((ve,lt)=>U.has(ve)?[lt]:[]),Qe=Tt<kt?Math.max(...fe)+1:Math.min(...fe);K.splice(Qe,0,...it.filter(ve=>N.has(ve))),R(K)};return window.addEventListener("reorder-navigation-session",G),()=>window.removeEventListener("reorder-navigation-session",G)},[a,l,bt,v,Pr,Jt,Gn,L,R]);const Vn=b.useCallback(G=>{if(G.type!=="collaboration-member")return!1;if(G.reason==="CANCEL")return!0;const Me=G.source.droppableId.replace(/^collaboration-members:/,""),$e=G.draggableId.replace(/^collaboration-member:/,""),Je=Ar.current;if(Je?.kind==="split")return Or($e,Me,Je.groupId),E(Je.sessionId,$e),!0;if(Je?.kind==="collaboration"&&Je.groupId!==Me)return Or($e,Me,Je.groupId),!0;if(Je?.kind==="collaboration"&&Je.background)return Zr.has($e)&&w($e),!0;if(G.destination&&G.destination.droppableId!==G.source.droppableId){const it=G.destination.droppableId.replace(/^collaboration-members:/,"");if(Pr.some(Tt=>Tt.id===it))return Or($e,Me,it),!0}if(G.combine){const it=G.combine.droppableId.replace(/^collaboration-members:/,"");it!==Me&&Or($e,Me,it);const Tt=G.combine.draggableId.replace(/^collaboration-member:/,"");if(v.find(Dt=>Dt.sessionIds.includes($e))?.sessionIds.includes(Tt)){const Dt=Pr.find(Bt=>Bt.id===Me),ft=Dt?Ud(Dt.sessionIds,v).flatMap(Bt=>Bt.sessionIds).indexOf(Tt):-1;ft>=0&&Dt&&Gn(Me,Ud(Dt.sessionIds,v).flatMap(Bt=>Bt.sessionIds).indexOf($e),ft)}else Jt.has(Tt)&&E(Tt,$e);return!0}if(G.destination?.droppableId===G.source.droppableId)return Gn(Me,G.source.index,G.destination.index,!0),!0;if(Je?.kind!=="list")return!0;if(Je?.kind==="list"){const it=cn.find(kt=>`group-sessions:${kt.key}`===Je.listId),Tt=Je.listId==="sidebar-entities"?dn:it?zd(it.sessions,v,Jt,Pr):null;if(Tt){const kt=Bb(Tt,$e,Je.index);Je.listId==="sidebar-entities"?R(kt):it&&R(cn.flatMap(Dt=>Dt.key===it.key?kt:Dt.sessions.map(ft=>ft.id)))}}return Or($e,Me,null),!0},[Pr,dn,cn,Or,R,Gn,Jt,v,Zr,w,E]),gn=b.useCallback(G=>{if(G.type!=="split-member")return!1;if(G.reason==="CANCEL")return!0;const Me=G.draggableId.replace(/^split-member:/,""),$e=v.find(ft=>ft.sessionIds.includes(Me));if(!$e?.sessionIds.includes(Me))return!0;const Je=$e.id,it=Ar.current;if(it?.kind==="split")return Or(Me,null,it.groupId),E(it.sessionId,Me),!0;if(it?.kind==="collaboration")return Or(Me,null,it.groupId),!0;if(!G.destination&&it?.kind==="list"){const ft=cn.find(N=>`group-sessions:${N.key}`===it.listId),Bt=it.listId==="sidebar-entities"?dn:ft?zd(ft.sessions,v,Jt,Pr):null;if(!Bt)return!0;const W=Bb(Bt,Me,it.index);return w(Me),it.listId==="sidebar-entities"?R(W):ft&&R(cn.flatMap(N=>N.key===ft.key?W:N.sessions.map(U=>U.id))),!0}if(!G.destination)return!0;const Tt=G.destination.droppableId.replace(/^split-members:/,"");if(Tt!==Je){const Bt=v.find(W=>W.id===Tt)?.sessionIds[0];return Bt&&E(Bt,Me),!0}if(G.source.index===G.destination.index)return!0;const kt=[...$e.sessionIds],[Dt]=kt.splice(G.source.index,1);return Dt&&(kt.splice(G.destination.index,0,Dt),L(Je,kt)),!0},[Pr,dn,cn,Or,E,w,R,L,Jt,v]),Jn=(G,Me="top")=>s.jsx("div",{"data-split-exit-drop-index":G,className:`group/split-exit pointer-events-none absolute inset-x-0 z-10 h-2 ${Me==="top"?"-top-1":"-bottom-1"}`,children:s.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-x-1 top-1/2 h-px -translate-y-1/2 rounded-full bg-transparent transition-colors group-data-[active=true]/split-exit:bg-primary"})}),kr=b.useCallback((G,Me,$e)=>{if(Vn(G)||gn(G)||G.reason==="CANCEL")return;const Je=Me.find(ft=>ft.id===G.draggableId);if(!Je)return;const it=Ar.current;if(it?.kind==="split"&&Je.kind==="session"){Or(Je.session.id,null,it.groupId),E(it.sessionId,Je.session.id);return}if(it?.kind==="collaboration"&&Je.kind==="session"){Or(Je.session.id,null,it.groupId);return}if(G.combine&&Je.kind!=="session"){const ft=Me.findIndex(Bt=>Bt.id===G.combine?.draggableId);if(ft<0)return;G={...G,combine:null,destination:{...G.source,index:ft}}}if(G.combine){const ft=Me.find(K=>K.id===G.combine?.draggableId);if(!ft)return;const Bt=ft.kind==="workspace"?ft:Je.kind==="workspace"?Je:ft,W=Bt===Je?ft:Je,N=Bt.sessionIds[0],U=W.sessionIds[0];N&&U&&N!==U&&E(N,U);return}if(!G.destination||G.source.index===G.destination.index)return;const Tt=[...Me],[kt]=Tt.splice(G.source.index,1);if(!kt)return;Tt.splice(G.destination.index,0,kt);const Dt=Tt.flatMap(ft=>ft.sessionIds);if($e===void 0){R(Dt);return}R(cn.flatMap(ft=>ft.key===$e?Dt:ft.sessions.map(Bt=>Bt.id)))},[cn,Vn,gn,Or,E,R]),Lr=b.useCallback(G=>{if(G.reason==="CANCEL"||Vn(G)||gn(G))return;if(G.type==="group"){if(!G.destination||G.source.index===G.destination.index)return;R(Vy(cn,G.source.index,G.destination.index));return}const Me=G.source.droppableId.replace(/^group-sessions:/,""),$e=cn.find(it=>it.key===Me);if(!$e)return;const Je=zd($e.sessions,v,Jt,Pr);if(G.combine||Ar.current?.kind==="collaboration"||Ar.current?.kind==="split"){kr(G,Je,Me);return}!G.destination||G.destination.droppableId!==G.source.droppableId||kr(G,Je,Me)},[Pr,cn,Jt,v,Vn,kr,gn,R]),pr=G=>{const Me=ne===G.id,$e=[{layout:"horizontal",label:Le("tab.splitHorizontal"),icon:Il},{layout:"vertical",label:Le("tab.splitVertical"),icon:px},...G.sessionIds.length>=3||G.layout==="grid"?[{layout:"grid",label:Le("tab.splitGrid"),icon:fx}]:[]],Je=G.layout==="vertical"?px:G.layout==="grid"?fx:Il,it=$e.find(Tt=>Tt.layout===G.layout)?.label??Le("tab.splitHorizontal");return s.jsxs("div",{ref:Me?Mn:void 0,className:"relative shrink-0",onPointerDown:Tt=>Tt.stopPropagation(),children:[s.jsx("button",{type:"button",className:`sidebar-session-action inline-flex h-6 w-6 items-center justify-center rounded-md transition active:scale-95 ${Me?"bg-primary/15 text-primary":"text-muted-foreground/70 hover:bg-surface-2 hover:text-foreground"}`,"aria-label":`${Le("tab.splitLayout")}: ${it}`,"aria-haspopup":"menu","aria-expanded":Me,title:Le("tab.splitLayout"),onClick:Tt=>{Tt.stopPropagation(),Fe(kt=>kt===G.id?null:G.id)},children:s.jsx(Je,{size:12})}),Me&&s.jsx("div",{role:"menu","aria-label":Le("tab.splitLayout"),className:"absolute right-0 top-full z-30 mt-1 flex gap-0.5 rounded-md border border-border bg-surface-elevated p-1 shadow-lg",children:$e.map(Tt=>{const kt=Tt.icon,Dt=Tt.layout===G.layout;return s.jsx("button",{type:"button",role:"menuitemradio","aria-checked":Dt,"aria-label":Tt.label,title:Tt.label,className:`sidebar-session-action inline-flex h-7 w-7 items-center justify-center rounded-sm transition active:scale-95 ${Dt?"bg-primary/15 text-primary":"text-muted-foreground hover:bg-surface-2 hover:text-foreground"}`,onClick:ft=>{ft.stopPropagation(),S(G.sessionIds[0],Tt.layout),Fe(null)},children:s.jsx(kt,{size:13})},Tt.layout)})})]})},ns=(G,Me)=>Me&&s.jsx("button",{type:"button",...Me,"aria-label":G,title:G,onClick:$e=>$e.stopPropagation(),className:"absolute -left-2 inset-y-0 z-10 flex w-3 cursor-grab items-start justify-center pt-1.5 text-muted-foreground/60 transition hover:text-foreground focus-visible:text-foreground active:cursor-grabbing",children:s.jsx($f,{size:10})}),Un=(G,Me,$e=!1,Je=!1,it)=>{if(Me.length<2)return null;const Tt=Me.some(N=>N.id===c),kt=[],Dt=[],ft=[];for(const N of Me){const U=l.get(N.id);U?.agentStatus==="waiting"||U?.agentNeedsReview?kt.push(N):U?.agentStatus==="working"?Dt.push(N):U?.inCopyMode&&ft.push(N)}const Bt=G.name?.trim()||`${Le("tab.splitWorkspace")} ${v.findIndex(N=>N.id===G.id)+1}`,W=ne===G.id;return s.jsxs("section",{"data-split-workspace":G.id,"aria-label":Bt,className:`group/split relative rounded-md p-0.5 before:pointer-events-none before:absolute before:inset-0 before:rounded-md before:border before:border-border transition-colors ${Je?"bg-primary/15 ring-1 ring-primary/40":$e?"bg-surface-elevated opacity-90 shadow-lg":kt.length>0?"bg-[rgb(var(--warning-rgb)_/_0.08)] hover:bg-[rgb(var(--warning-rgb)_/_0.12)]":Dt.length>0?"bg-[rgb(var(--success-rgb)_/_0.06)] hover:bg-[rgb(var(--success-rgb)_/_0.10)]":ft.length>0?"bg-[rgb(var(--tmux-rgb)_/_0.07)] hover:bg-[rgb(var(--tmux-rgb)_/_0.11)]":Tt?"bg-primary/[0.07]":"hover:bg-surface-2"}`,children:[ns(`移动分屏组 ${Bt}`,it),s.jsx(Ll,{droppableId:`split-members:${G.id}`,type:"split-member",direction:"vertical",children:(N,U)=>s.jsxs("div",{ref:N.innerRef,...N.droppableProps,"data-split-members":!0,className:U.isDraggingOver?"rounded-sm bg-primary/10 ring-1 ring-primary/40":"",children:[Me.map((K,fe)=>s.jsx(kl,{draggableId:`split-member:${K.id}`,index:fe,disableInteractiveElementBlocking:!0,children:(Qe,ve)=>s.jsx("div",{ref:Qe.innerRef,...Qe.draggableProps,...B?cr(()=>B(K.id)):{},className:`${fe===0&&W?"relative z-20 ":"relative "}flex items-center rounded-sm pr-0.5 transition-colors ${ve.isDragging?"bg-surface-elevated opacity-90 shadow-lg ":""}${jr(K.id)??(K.id===c?"bg-surface-elevated/80 text-foreground":"text-muted-foreground hover:bg-surface-2")}`,children:Xn(K,Qe.dragHandleProps,!0,fe===0?pr(G):void 0)})},K.id)),N.placeholder]})})]})},En=(G,Me)=>{const $e=c??Me;Ae.current||!$e||(ue(!1),Ae.current=!0,et(G),q(null),dC(G,$e).catch(Je=>q(Je instanceof Error?Je.message:"消息面板打开失败,请重试")).finally(()=>{Ae.current=!1,et(null)}))},kn=(G,Me)=>{on.current+=1,Sr($e=>Me?$e.map(Je=>Je.id===G?Me:Je):$e.filter(Je=>Je.id!==G)),Me||(Ei.getState().groupId===G&&Ei.getState().terminal(),Kn.getState().setDock(G,null),Ce($e=>{const Je={...$e};return delete Je[G],Je}),requestAnimationFrame(()=>Cr.current?.focus({preventScroll:!0})),Fa({floatingGroupId:null},G).catch(()=>q("协作组已删除,面板布局保存失败,请刷新后检查。"))),Hr()},ss=(G,Me,$e,Je=!1,it=!1)=>{const Tt=`collaboration:${G.id}`,kt=Br.has(Tt),Dt=`collaboration-members-${G.id}`,ft=Ie===G.id||!Ie&&Me.some(ve=>ve.id===c),Bt=O5(qt,G.id),W=G.sessionIds.filter(ve=>Bt.has(ve)&&ve!==c&&!Zr.has(ve)),N=$t[G.id]===!0,U=N?G.sessionIds:G.sessionIds.filter(ve=>!W.includes(ve)),K=Ud(U,v),fe=K.flatMap(ve=>ve.sessionIds),Qe=K.length===1?K[0]?.workspace:void 0;return s.jsxs("section",{"data-collaboration-group":G.id,"data-collaboration-group-name":G.name,"aria-label":`Agent 工作组:${G.name}`,className:`group/collaboration relative rounded-md ${kt?"":"p-0.5 before:pointer-events-none before:absolute before:inset-0 before:rounded-md before:border before:border-border"} transition-colors data-[drop-active=true]:bg-primary/15 data-[drop-active=true]:ring-1 data-[drop-active=true]:ring-primary/40 ${it?"bg-primary/15 ring-1 ring-primary/40":Je?"bg-surface-elevated opacity-90 shadow-lg":ft?"bg-primary/[0.07]":"hover:bg-surface-2"}`,children:[ns(`移动工作组 ${G.name}`,$e),s.jsxs(sF,{group:Yt.find(ve=>ve.id===G.id)??G,collapsed:kt,onOpen:()=>{fr(G.id)},onMessages:Ye===null&&(c||Me.length)?()=>En(G.id,Me[0]?.id):void 0,onToggleCollapsed:()=>Vr(Tt),onChanged:ve=>kn(G.id,ve),children:[s.jsx("button",{type:"button","aria-label":`${kt?"展开":"收起"} ${G.name} 的成员会话`,"aria-expanded":!kt,"aria-controls":Dt,title:`${kt?"展开":"收起"}成员会话`,className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-surface-elevated hover:text-foreground focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary md:h-[30px] md:w-5",onClick:ve=>{ve.stopPropagation(),Vr(Tt)},children:s.jsx(Ks,{size:14,className:kt?"":"rotate-90"})}),s.jsxs("button",{type:"button",className:"flex min-h-11 min-w-0 flex-1 items-center gap-1.5 rounded-sm px-1 text-left text-xs font-medium text-foreground transition hover:text-primary md:min-h-[30px]",title:`打开 ${G.name} 的协作工作区`,"aria-label":`打开协作工作区:${G.name}`,"aria-current":Ie===G.id?"page":void 0,onClick:ve=>{ve.stopPropagation(),fr(G.id)},children:[s.jsx(nh,{size:14,className:"shrink-0 text-primary"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:G.name}),ut.some(ve=>ve.groupId===G.id)&&s.jsxs("span",{className:"shrink-0 text-[10px] font-normal text-primary",children:[ut.filter(ve=>ve.groupId===G.id).length," 待处理"]})]}),s.jsx("button",{type:"button","aria-label":`成员与消息:${G.name}`,title:"在终端旁打开成员与消息",disabled:Ye!==null||!c&&!Me.length,"aria-busy":Ye===G.id,className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-surface-elevated hover:text-primary disabled:opacity-40 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary md:h-[30px] md:w-7",onClick:ve=>{ve.stopPropagation(),En(G.id,Me[0]?.id)},children:Ye===G.id?s.jsx(bn,{size:14,className:"animate-spin"}):s.jsx(Xu,{size:14})})]}),s.jsx("div",{id:Dt,children:!kt&&s.jsxs(s.Fragment,{children:[W.length>0&&s.jsxs("button",{type:"button","aria-expanded":N,className:"flex min-h-11 w-full items-center gap-2 rounded-sm px-2 text-left text-[11px] text-muted-foreground hover:bg-surface-elevated md:min-h-8",title:"展开后可查看或归档执行会话,任务结果保留。",onClick:()=>yt(ve=>({...ve,[G.id]:!N})),children:[s.jsx(Ks,{size:12,className:N?"rotate-90":""}),"已完成的执行会话 · ",W.length]}),s.jsx(Ll,{droppableId:`collaboration-members:${G.id}`,type:"collaboration-member",direction:"vertical",isCombineEnabled:!0,children:(ve,lt)=>s.jsxs("div",{ref:ve.innerRef,...ve.droppableProps,"data-collaboration-members":!0,className:`${lt.isDraggingOver?"rounded-sm bg-primary/10":""}`,children:[K.map(vt=>s.jsx("div",{"data-collaboration-split":vt.workspace?.id,"data-split-anchor":vt.workspace?.sessionIds[0],role:vt.workspace?"region":void 0,"aria-label":vt.workspace?`${Le("tab.splitWorkspace")} · ${vt.sessionIds.length}`:void 0,className:vt.workspace&&!Qe?`relative my-0.5 rounded-sm before:pointer-events-none before:absolute before:inset-0 before:rounded-sm before:border before:border-border data-[drop-active=true]:ring-1 data-[drop-active=true]:ring-primary/40 ${vt.sessionIds.includes(c??"")?"bg-primary/[0.07]":"bg-surface/35"}`:void 0,children:vt.sessionIds.map(br=>{const Lt=Jt.get(br);return Lt?s.jsx(kl,{draggableId:`collaboration-member:${Lt.id}`,index:fe.indexOf(Lt.id),disableInteractiveElementBlocking:!0,children:(rn,yn)=>s.jsxs("div",{ref:rn.innerRef,...rn.draggableProps,"data-collaboration-member":Lt.id,"data-split-member":Zr.has(Lt.id)?"true":void 0,...B?cr(()=>B(Lt.id)):{},className:`${vt.workspace&&br===vt.sessionIds[0]&&ne===vt.workspace.id?"z-20 ":""}relative flex items-center rounded-sm pr-0.5 transition-colors data-[drop-active=true]:bg-primary/15 data-[drop-active=true]:ring-1 data-[drop-active=true]:ring-primary/40 ${yn.combineTargetFor?"bg-primary/15 ring-1 ring-primary/40 ":yn.isDragging?"bg-surface-elevated opacity-90 shadow-lg ":""}${jr(Lt.id)??(Lt.id===c?"bg-surface-elevated/80 text-foreground":Zr.has(Lt.id)?"bg-primary/[0.05] text-muted-foreground hover:bg-primary/[0.09]":"text-muted-foreground hover:bg-surface-2")}`,children:[Xn(Lt,rn.dragHandleProps,!0,vt.workspace&&br===vt.sessionIds[0]?pr(vt.workspace):void 0,Bt.has(br)?s.jsxs("button",{type:"button","aria-label":`归档 ${Lt.name}`,title:"保存 Agent 会话 ID 并停止终端;只回收干净的执行目录,结果和分支保留",disabled:nr!==null,className:"sidebar-session-action inline-flex h-11 min-w-11 shrink-0 items-center justify-center gap-1 rounded-md px-2 text-muted-foreground hover:bg-primary/15 hover:text-primary disabled:opacity-40 md:h-6 md:min-w-6 md:px-1",onClick:hn=>{hn.stopPropagation(),!_t.current&&(_t.current=!0,Ke(br),q(null),c9(br).then(async()=>{De(Dn=>Dn+1),await Hr()}).catch(Dn=>q(Dn instanceof Error?Dn.message:"归档失败,终端已保留")).finally(()=>{_t.current=!1,Ke(null)}))},children:[nr===br?s.jsx(bn,{size:13,className:"animate-spin"}):s.jsx(My,{size:13}),s.jsx("span",{className:"text-[10px] md:sr-only",children:"归档"})]}):void 0),!vt.workspace&&Zr.has(Lt.id)&&s.jsx("button",{type:"button",className:"shrink-0 px-1 text-[10px] text-primary",title:`与 ${v.find(hn=>hn.sessionIds.includes(Lt.id))?.sessionIds.filter(hn=>hn!==Lt.id).map(hn=>Jt.get(hn)?.name??hn).join("、")} 分屏`,"aria-label":`查看 ${Lt.name} 的跨组分屏`,onClick:()=>{ue(!1),Ei.getState().terminal(),window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:Lt.id})),Qr()},children:s.jsx(Il,{size:10})})]})},Lt.id):null})},vt.workspace?.id??vt.sessionIds[0])),ve.placeholder]})}),s.jsx(tQ,{groupId:G.id,version:tt,onRestore:async ve=>{ue(!1),window.dispatchEvent(new CustomEvent("new-terminal-session",{detail:{mode:"tmux",cwd:ve.cwd,preferredFrontendSessionId:ve.sessionId,requireExisting:!0}})),await Hr(),Ei.getState().terminal(),Qr()}}),G.remoteSessions?.map(ve=>s.jsxs("button",{type:"button",title:`${uc(ve)} · ${ve.serviceConnected===!1?"服务不可达,消息尚未送达":ve.status}`,className:"flex w-full min-w-0 items-center gap-1.5 rounded-sm px-2 py-1 text-left text-[11px] text-muted-foreground hover:bg-surface-2",onClick:()=>{ue(!1),A6(ve.sessionId).catch(()=>{fr(G.id)})},children:[s.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${ve.serviceConnected===!1?"bg-muted-foreground":"bg-primary"}`}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:ve.name}),s.jsx("span",{className:"max-w-20 truncate rounded border border-border/20 px-1 text-[9px]",children:uc(ve)}),ve.serviceConnected===!1&&s.jsx("span",{className:"shrink-0 text-[9px]",children:"不可达"})]},ve.sessionId))]})}),s.jsx("div",{"data-collaboration-background":!0,className:kt?"absolute inset-0 pointer-events-none":"h-1.5"})]})},Wr=(G,Me,$e)=>s.jsx(h0,{onBeforeCapture:ps,onDragStart:_r,onDragEnd:Je=>jn(it=>kr(it,G,$e),Je),children:s.jsx(Ll,{droppableId:Me,direction:"vertical",isCombineEnabled:!re,children:Je=>s.jsxs("div",{ref:Je.innerRef,...Je.droppableProps,"data-sidebar-entity-list-id":Me,className:"flex-1 space-y-0.5",children:[G.map((it,Tt)=>s.jsx(kl,{draggableId:it.id,index:Tt,disableInteractiveElementBlocking:!0,children:(kt,Dt)=>s.jsxs("div",{ref:kt.innerRef,...kt.draggableProps,"data-sidebar-gesture-ignore":!0,"data-sidebar-entity-index":Tt,className:"relative",children:[Jn(Tt),Tt===G.length-1&&Jn(G.length,"bottom"),it.kind==="workspace"?Un(it.workspace,it.members,Dt.isDragging,!!Dt.combineTargetFor,kt.dragHandleProps):it.kind==="collaboration"?ss(it.group,it.members,kt.dragHandleProps,Dt.isDragging,!!Dt.combineTargetFor):s.jsx("div",{...B?cr(()=>B(it.session.id)):{},className:`group relative flex items-center gap-1 rounded-md pr-1 transition-colors ${Dt.combineTargetFor?"bg-primary/15 text-foreground ring-1 ring-primary/40":Dt.isDragging?"bg-surface-elevated text-foreground opacity-90 shadow-lg":jr(it.session.id)??(!Ie&&it.session.id===c?"bg-surface-elevated text-foreground":"text-muted-foreground hover:bg-surface-2")} cursor-grab active:cursor-grabbing`,children:Xn(it.session,kt.dragHandleProps)})]})},it.id)),Je.placeholder]})})}),tn=s.jsxs("div",{className:"relative flex min-h-0 flex-1 flex-col",children:[s.jsxs("div",{"data-session-sidebar-header":!0,className:"relative z-20 shrink-0 px-3 py-0.5",children:[s.jsx("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-x-3 bottom-0 z-10 h-px bg-border opacity-40"}),s.jsxs("div",{className:"flex w-full items-center gap-1.5",children:[s.jsx("div",{className:"min-w-0 flex-1",children:s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:"text-[12px] font-medium text-muted-foreground",children:Le("sidebar.sessions")}),s.jsx("span",{className:"text-[11px] text-muted-foreground",children:a.length}),Jr>0&&s.jsx("span",{className:"ml-0.5 flex items-center",children:s.jsx(P6,{count:Jr,tone:"running",title:Le("agent.aiRunning")})})]})}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[s.jsx("button",{"data-session-sidebar-header-action":!0,type:"button",onClick:()=>{ue(!1),fr(null)},className:"inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition hover:bg-primary/15 hover:text-primary active:scale-95","aria-label":"Agent 工作台",title:"Agent 工作台",children:s.jsx(nh,{size:16})}),(!_e||ze)&&s.jsx("button",{"data-session-sidebar-header-action":!0,type:"button",onClick:r,className:"inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition hover:bg-destructive/20 hover:text-destructive active:scale-95","aria-label":Le("common.close"),children:s.jsx(In,{size:16})})]})]})]}),ht&&s.jsxs("div",{role:"alert",className:"mx-2 mt-2 flex items-start gap-2 rounded-lg bg-destructive/10 px-3 py-2 text-[11px] text-destructive",children:[s.jsx("span",{className:"min-w-0 flex-1",children:ht}),s.jsx("button",{type:"button","aria-label":"关闭协作错误提示",className:"shrink-0",onClick:()=>q(null),children:s.jsx(In,{size:14})})]}),s.jsxs("div",{ref:qr,className:"relative z-10 flex min-h-0 flex-1 flex-col overflow-y-auto overscroll-contain px-1.5 pt-0.5 pb-1.5",children:[(ut.length>0||xt)&&s.jsxs("section",{className:"mb-2 rounded-lg border border-primary/20 bg-primary/5","aria-label":"协作待处理事项",children:[s.jsxs("button",{type:"button",className:"flex min-h-11 w-full items-center gap-2 px-3 text-left text-xs text-primary","aria-expanded":Rt,onClick:()=>Ct(G=>!G),children:[s.jsx(nh,{size:14}),s.jsx("span",{className:"min-w-0 flex-1",children:"需要你处理"}),s.jsx("span",{children:ut.length}),s.jsx(Ks,{size:12,className:Rt?"rotate-90":""})]}),Rt&&s.jsxs("div",{className:"space-y-1 p-1 pt-0",children:[xt&&s.jsxs("p",{role:"alert",className:"px-2 py-2 text-[11px] text-destructive",children:[xt,s.jsx("button",{type:"button",className:"ml-2 text-primary",onClick:()=>{Lu.getState().refresh()},children:"重试"})]}),ut.map(G=>s.jsxs("button",{type:"button",className:"min-h-11 w-full rounded-md px-2 py-2 text-left hover:bg-surface-2",onClick:()=>{F5(G.groupId,G.id),fr(G.groupId).then(Me=>{Me&&F5(G.groupId,G.id)})},children:[s.jsx("span",{className:"block truncate text-xs text-foreground",children:G.title}),s.jsxs("span",{className:"mt-1 block truncate text-[10px] text-muted-foreground",children:[Yt.find(Me=>Me.id===G.groupId)?.name??"协作组"," · ",Kc(G)]})]},G.id))]})]}),s.jsx(nF,{sessions:ce,loading:qe,attachingName:xe,onRefresh:we,onRestore:X,onClose:ye}),Pr.filter(G=>!G.sessionIds.length).map(G=>s.jsx(h0,{onDragEnd:()=>{},children:ss(G,[])},G.id)),a.length===0?s.jsxs("div",{className:"rounded-xl bg-surface-2/60 px-4 py-8 text-center",children:[s.jsx($o,{size:26,className:"mx-auto mb-2 text-muted-foreground"}),s.jsx("p",{className:"text-[12px] text-muted-foreground",children:Le("sidebar.noSessions")})]}):Tr.length===0&&v.length===0?s.jsx("div",{className:"rounded-xl bg-surface-2/60 px-4 py-6 text-center",children:s.jsx("p",{className:"text-[12px] text-muted-foreground",children:Le("sidebar.noMatchingSessions")})}):bt?s.jsx("div",{className:"flex flex-1 flex-col",children:s.jsx(h0,{onBeforeCapture:ps,onDragStart:_r,onDragEnd:G=>jn(Lr,G),children:s.jsx(Ll,{droppableId:"sidebar-groups",type:"group",direction:"vertical",children:G=>s.jsxs("div",{ref:G.innerRef,...G.droppableProps,className:"flex flex-1 flex-col space-y-1.5",children:[cn.map((Me,$e)=>{const Je=Br.has(Me.key),it=!Je&&$e===cn.length-1,Tt=zd(Me.sessions,v,Jt,Pr);let kt=0,Dt=0;for(const Bt of Me.sessions){const W=l.get(Bt.id);W?.agentStatus==="working"&&(kt+=1),(W?.agentStatus==="waiting"||W?.agentNeedsReview)&&(Dt+=1)}const ft=Me.key==="";return s.jsx(kl,{draggableId:`sidebar-group:${Me.key||"__ungrouped__"}`,index:$e,isDragDisabled:ft,disableInteractiveElementBlocking:!0,children:(Bt,W)=>s.jsxs("div",{ref:Bt.innerRef,...Bt.draggableProps,className:`shrink-0 rounded-md transition-colors ${it?"flex flex-1 flex-col ":""}${W.isDragging?"bg-surface-elevated shadow-lg opacity-90":""}`,children:[s.jsxs("button",{type:"button",...ft?{}:Bt.dragHandleProps,onClick:()=>{Vr(Me.key),Fr.current.delete(Me.key)},className:`flex w-full shrink-0 items-center gap-1.5 rounded-md px-1.5 py-1 text-left text-muted-foreground transition hover:bg-surface-2 ${ft?"":"cursor-grab active:cursor-grabbing"}`,title:Me.key||Me.label,children:[s.jsx(Ks,{size:13,className:`shrink-0 transition-transform ${Je?"":"rotate-90"}`}),s.jsx("span",{className:"min-w-0 flex-1 truncate text-[11.5px] font-semibold uppercase tracking-wide",children:Me.label}),kt>0&&s.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--success)] animate-pulse"}),Dt>0&&s.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--warning)] animate-pulse"}),s.jsx($5,{sessionIds:Me.sessions.map(N=>N.id)}),s.jsx("span",{className:"shrink-0 text-[10.5px] text-muted-foreground/70",children:Me.sessions.length})]}),!Je&&s.jsx("div",{className:`mt-0.5 pl-2 ${it?"flex flex-1 flex-col":""}`,children:s.jsx(Ll,{droppableId:`group-sessions:${Me.key}`,type:"session",direction:"vertical",isCombineEnabled:!re,children:N=>s.jsxs("div",{ref:N.innerRef,...N.droppableProps,"data-sidebar-entity-list-id":`group-sessions:${Me.key}`,className:`${it?"flex-1 ":""}space-y-0.5`,children:[Tt.map((U,K)=>s.jsx(kl,{draggableId:U.id,index:K,disableInteractiveElementBlocking:!0,children:(fe,Qe)=>s.jsxs("div",{ref:fe.innerRef,...fe.draggableProps,"data-sidebar-gesture-ignore":!0,"data-sidebar-entity-index":K,className:"relative",children:[Jn(K),K===Tt.length-1&&Jn(Tt.length,"bottom"),U.kind==="workspace"?Un(U.workspace,U.members,Qe.isDragging,!!Qe.combineTargetFor,fe.dragHandleProps):U.kind==="collaboration"?ss(U.group,U.members,fe.dragHandleProps,Qe.isDragging,!!Qe.combineTargetFor):s.jsx("div",{...B?cr(()=>B(U.session.id)):{},className:`group relative flex items-center gap-1 rounded-md pr-1 transition-colors ${Qe.combineTargetFor?"bg-primary/15 text-foreground ring-1 ring-primary/40":Qe.isDragging?"bg-surface-elevated text-foreground opacity-90 shadow-lg":jr(U.session.id)??(!Ie&&U.session.id===c?"bg-surface-elevated text-foreground":"text-muted-foreground hover:bg-surface-2")} cursor-grab active:cursor-grabbing`,children:Xn(U.session,fe.dragHandleProps)})]})},U.id)),N.placeholder]})})})]})},Me.key||"__ungrouped__")}),G.placeholder]})})})}):Wr(dn,"sidebar-entities")]}),s.jsx(a9,{onReselect:()=>{d&&(mn.current=null,Be(G=>G+1),d())}}),ke&&s.jsx(fO,{directories:a.flatMap(G=>{const Me=l.get(G.id)?.cwd;return Me?[Me]:[]}),tmuxAvailable:pe,options:pn,launchPending:Pe,launchError:oe?Le(zm(oe)):null,agents:Gr,selectedAgent:me,detecting:ot,resumeHistory:Gt,resumeHistoryLoading:wt,resumeHistoryPendingId:Vt,resumeHistoryError:Ot,onRefreshAgents:()=>{pt().catch(()=>{})},onSelectAgent:G=>{ir(G).catch(()=>{})},onLaunchAgent:He,onResumeHistory:G=>{Nt(G)},onRemoveResumeHistory:G=>{Et(G)},onClose:()=>ue(!1),onOptionsChange:dr,additionalContent:Xr&&$?.latestVersion&&s.jsxs("div",{className:"mb-1 rounded-lg bg-[rgb(var(--warning-rgb)_/_0.10)] px-2.5 py-2.5 text-foreground",children:[s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx("span",{className:"mt-0.5 inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-md bg-[rgb(var(--warning-rgb)_/_0.16)] text-[color:var(--warning)]",children:s.jsx(bn,{size:13,className:$.status==="installing"||$.status==="restarting"?"animate-spin":""})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block font-semibold",children:Le("sidebar.updateAvailable",{version:$.latestVersion})}),s.jsx("span",{className:"mt-0.5 block text-[10.5px] leading-relaxed text-muted-foreground",children:$.status==="installing"?Le("sidebar.updateInstalling"):$.status==="ready"?Le("sidebar.updateReady"):$.status==="restarting"?Le("sidebar.updateRestarting"):Le("sidebar.updateFailed")})]})]}),$.status==="ready"&&Z&&s.jsx("button",{type:"button",disabled:V,onClick:Z,className:"mt-2 flex w-full items-center justify-center rounded-md bg-[var(--warning)] px-2 py-1.5 text-[11px] font-semibold text-[color:var(--bg)] transition hover:opacity-90 disabled:cursor-wait disabled:opacity-60",children:Le("sidebar.updateRestart")}),$.status==="error"&&le&&s.jsx("button",{type:"button",disabled:V,onClick:le,className:"mt-2 flex w-full items-center justify-center rounded-md bg-surface-elevated px-2 py-1.5 text-[11px] font-semibold text-foreground transition hover:bg-surface-2 disabled:cursor-wait disabled:opacity-60",children:Le("sidebar.updateRetry")})]}),footerActions:s.jsx(eF,{serverAttention:je,onOpenSettings:()=>{ue(!1),z()},actions:[...O?[{label:Le("sidebar.subscriptionQuota"),icon:zA,onSelect:()=>{ue(!1),O()}}]:[],{label:"Agent 工作台",icon:nh,onSelect:()=>{ue(!1),fr(null)}},{label:"服务与设备",icon:o9,onSelect:()=>{ue(!1),l9()}},...Y?[{label:Le(ze?"sidebar.unpinSidebar":"sidebar.pinSidebar"),icon:ze?b0:x0,separated:!0,onSelect:()=>{ue(!1),Y()}}]:[]]})}),Ze&&s.jsx(Lb,{onEnterGroup:async G=>{if(!await fr(G))throw new Error("协作组已保存,打开工作区失败,请重试");at(!1)},onFloatingChange:async G=>{if(G){if(!await fr(G))throw new Error("打开协作工作区失败");at(!1)}},activeSessionId:c,defaultSessionMode:ee,onClose:()=>at(!1),onNewSession:G=>p(G)}),Object.entries(Ge).map(([G,Me])=>s.jsx(Lb,{activeSessionId:c,initialCollaborationGroupId:G,initialFloating:Me,visible:!Ie,onEnterGroup:async $e=>{if($e===G){await fr($e);return}if(!await fr($e))throw new Error("协作组已保存,打开工作区失败,请重试");await Fa({floatingGroupId:null},G),Ce(Je=>{const it={...Je};return delete it[G],it})},onFloatingChange:$e=>St(G,$e),defaultSessionMode:ee,onClose:()=>{ae.current=!0,Ce($e=>{const Je={...$e};return delete Je[G],Je})},onNewSession:$e=>p($e)},G)),!ke&&s.jsxs("div",{className:"relative z-10 shrink-0 bg-[var(--chrome-bg)] px-3 pb-3 pt-1 md:border-t md:border-border md:p-2",children:[oe&&s.jsx("p",{role:"alert",className:"mb-2 text-[11px] leading-relaxed text-destructive",children:Le(zm(oe))}),s.jsxs("div",{className:`grid gap-1.5 [&>button]:min-h-11 [&>button]:shadow-none [&>button]:ring-0 md:[&>button]:min-h-0 ${me?"grid-cols-[minmax(0,1fr)_minmax(0,1fr)_2.5rem]":"grid-cols-[minmax(0,1fr)_2.5rem]"}`,children:[s.jsxs("button",{type:"button",onClick:en,disabled:Pe,"aria-busy":Pe,className:`flex min-w-0 items-center justify-center gap-2 rounded-lg px-2 py-2.5 text-[12px] font-semibold transition active:scale-[0.99] ${me?"bg-surface-elevated text-foreground ring-1 ring-border/30 hover:bg-surface-2":"bg-primary text-primary-foreground ring-1 ring-primary/40 shadow-md shadow-primary/25 hover:bg-primary/90"}`,title:Le("sidebar.newSession"),"aria-label":Le("sidebar.newSession"),children:[s.jsx($o,{size:15,className:"shrink-0"}),s.jsx("span",{className:"truncate",children:Pe?Le("sidebar.sessionCreating"):"Terminal"})]}),me&&s.jsxs("button",{type:"button",onClick:xn,disabled:Pe,"aria-busy":Pe,className:"flex min-w-0 items-center justify-center gap-2 rounded-lg bg-primary px-2 py-2.5 text-[12px] font-semibold text-primary-foreground ring-1 ring-primary/40 shadow-md shadow-primary/25 transition hover:bg-primary/90 active:scale-[0.99]",title:Le("sidebar.newSessionWithAgent",{agent:me.displayName}),"aria-label":Le("sidebar.newSessionWithAgent",{agent:me.displayName}),children:[s.jsx(Wc,{agent:me,size:15}),s.jsx("span",{className:"truncate",children:me.displayName})]}),s.jsxs("button",{type:"button",onClick:tr,disabled:Pe,className:"relative inline-flex w-10 shrink-0 items-center justify-center rounded-lg bg-surface-2 text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground active:scale-[0.97]",title:st,"aria-label":st,"aria-expanded":ke,"aria-controls":"sidebar-launch-options",children:[s.jsx(To,{size:15}),je&&s.jsx("span",{className:"absolute right-0.5 top-0.5 h-2 w-2 rounded-full bg-destructive ring-2 ring-[var(--chrome-bg)]","aria-hidden":"true"}),Xr&&s.jsx("span",{className:`absolute top-0.5 h-2 w-2 rounded-full bg-[var(--warning)] ring-2 ring-[var(--chrome-bg)] ${je?"right-3.5":"right-0.5"}`,"aria-hidden":"true"})]})]})]})]});return ze?s.jsx("div",{"data-session-sidebar-pinned":!0,className:"h-full flex flex-col app-chrome-bg border-r border-border",children:tn}):s.jsx(D6,{side:"left",isOpen:e,drawerWidthPx:t,onClose:r,onOpen:n,push:_e,children:tn})}function oF(){const{t:e}=Ur();return s.jsxs("div",{role:"status","aria-label":e("rightSidebar.loadingGitChanges"),className:"td-loading-skeleton flex h-full min-h-0 flex-col overflow-hidden bg-surface",children:[s.jsx("span",{className:"sr-only",children:e("rightSidebar.loadingGitChanges")}),s.jsxs("div",{"aria-hidden":"true",className:"shrink-0 border-b border-border/15 px-3 py-2",children:[s.jsxs("div",{className:"mb-2 flex h-5 items-center gap-1",children:[s.jsx("div",{className:"h-4 w-16 rounded bg-surface-2"}),s.jsx("div",{className:"h-4 w-7 rounded bg-surface-2"}),s.jsx("div",{className:"h-4 w-12 rounded bg-surface-2"})]}),s.jsxs("div",{className:"flex h-[15px] items-center justify-between",children:[s.jsx("div",{className:"h-2 w-14 rounded bg-surface-2"}),s.jsx("div",{className:"h-2 w-6 rounded bg-surface-2"})]}),s.jsxs("div",{className:"mt-2 flex h-7 items-center gap-1.5",children:[s.jsx("div",{className:"h-7 w-12 rounded-full bg-surface-2"}),s.jsx("div",{className:"h-7 w-16 rounded-full bg-surface-2"}),s.jsx("div",{className:"h-3 w-24 max-w-[30%] rounded bg-surface-2"}),s.jsx("div",{className:"ml-auto h-4 w-4 rounded-full bg-surface-2"})]})]}),s.jsxs("div",{"aria-hidden":"true",className:"overflow-hidden px-3 py-2",children:[s.jsxs("div",{className:"flex h-8 items-center gap-2",children:[s.jsx("div",{className:"h-3 w-3 rounded-sm bg-surface-2"}),s.jsx("div",{className:"h-2 w-32 max-w-[55%] rounded bg-surface-2"})]}),["w-3/5","w-2/5","w-1/2","w-1/3"].map((t,r)=>s.jsxs("div",{className:"flex h-9 items-center gap-2 pl-5",style:{opacity:1-r*.15},children:[s.jsx("div",{className:"h-3 w-3 shrink-0 rounded-sm bg-surface-2"}),s.jsx("div",{className:`h-2 rounded bg-surface-2 ${t}`})]},t))]})]})}function lF({slow:e=!1}){const{t}=Ur();return s.jsxs("div",{role:"status","aria-label":t("rightSidebar.loadingGitChanges"),className:"td-loading-skeleton relative h-full min-h-0 overflow-hidden bg-surface px-3",children:[s.jsx("span",{className:"sr-only",children:t("rightSidebar.loadingGitChanges")}),s.jsxs("div",{"aria-hidden":"true",children:[s.jsxs("div",{className:"flex h-[76px] items-center gap-2 border-b border-border/40 px-2",children:[s.jsx("div",{className:"h-6 w-6 rounded-md bg-surface-2"}),s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"h-3 w-16 rounded bg-surface-2"}),s.jsx("div",{className:"h-2 w-12 rounded bg-surface-2"})]})]}),s.jsxs("div",{className:"flex h-11 items-center gap-2 px-1 pt-3",children:[s.jsx("div",{className:"h-6 w-6 rounded-md bg-surface-2"}),s.jsx("div",{className:"h-3 w-16 rounded bg-surface-2"}),s.jsx("div",{className:"ml-auto h-4 w-12 rounded-full bg-surface-2"})]}),[!1,!0].map(r=>s.jsxs("div",{className:"border-b border-border/40 px-1 py-4",children:[s.jsxs("div",{className:"mb-2 flex h-8 items-center justify-between",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"h-3 w-14 rounded bg-surface-2"}),r&&s.jsx("div",{className:"h-2 w-28 rounded bg-surface-2"})]}),s.jsx("div",{className:"h-8 w-12 rounded-md bg-surface-2"})]}),s.jsx("div",{className:"h-10 rounded-md bg-surface-2"})]},String(r))),s.jsx("div",{className:"flex h-[69px] items-center border-b border-border/40 px-2",children:s.jsx("div",{className:"h-3 w-16 rounded bg-surface-2"})}),s.jsxs("div",{className:"space-y-2 px-1 py-4",children:[s.jsxs("div",{className:"flex h-8 items-center justify-between",children:[s.jsx("div",{className:"h-3 w-14 rounded bg-surface-2"}),s.jsx("div",{className:"h-8 w-28 rounded-md bg-surface-2"})]}),s.jsx("div",{className:"h-7 rounded-md bg-surface-2"}),s.jsx("div",{className:"h-10 rounded-md bg-surface-2"})]})]}),e&&s.jsx("div",{className:"absolute inset-x-3 bottom-3 rounded-md bg-surface-elevated px-3 py-2 text-xs text-muted-foreground",children:t("rightSidebar.loadingGitChangesSlow")})]})}const Z6=()=>Oc(()=>import("./RightSidebar-7C9-PfhA.js").then(e=>e.R),__vite__mapDeps([7,1,2,3,4,5,8,9,10,11,12,13,14,15,16,17])).then(e=>({default:e.RightSidebar})),cF=b.lazy(Z6);function Pb(e){const t=b.useRef(!1);b.useEffect(()=>{const p=navigator.connection;if(!(p?.saveData||/2g|3g/.test(p?.effectiveType??"")))return U1(()=>{Z6().catch(()=>{})},3e3)},[]);const{t:r}=Ur(),n=Wt(p=>p.rootPath),a=Wt(p=>p.rightTab),c=Wt(p=>p.setRightTab),l=n?.replace(/\/+$/,"").split("/").pop()||r("rightSidebar.workspace");(e.isOpen||e.pinned)&&(t.current=!0);const d=s.jsx(D6,{side:"right",isOpen:e.isOpen,drawerWidthPx:e.drawerWidthPx,onClose:e.onClose,onOpen:e.onOpen,pinned:e.pinned,children:s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden",children:[s.jsxs("div",{className:"shrink-0 border-b border-border/15 bg-surface px-2 pt-2",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("div",{className:"min-w-0 flex-1 px-1",children:s.jsx("div",{className:"flex min-h-[1.25rem] items-baseline gap-1.5",children:s.jsx("span",{className:"truncate text-[13px] font-semibold text-foreground",children:l})})}),s.jsx("div",{"aria-hidden":"true",className:"flex items-center gap-1.5",children:[jl,rS,To].map((p,m)=>s.jsx("span",{className:"inline-flex h-8 w-8 items-center justify-center rounded-full bg-surface-2 text-muted-foreground",children:s.jsx(p,{size:14})},m))}),s.jsx("button",{type:"button",onClick:e.onClose,"aria-label":r("common.close"),className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-surface-2 text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground active:scale-95",children:s.jsx(In,{size:14})})]}),s.jsx("div",{className:"mt-2 grid grid-cols-5 gap-0.5 rounded-md bg-surface-2 p-0.5",children:[["git",TA,"rightSidebar.tabGit"],["diff",CA,"rightSidebar.tabChanges"],["files",Vc,"rightSidebar.tabFiles"],["architecture",$T,"architecture.tab"],["computer",d9,"rightSidebar.tabComputer"]].map(([p,m,x])=>s.jsxs("button",{type:"button",onClick:()=>c(p),className:`flex items-center justify-center gap-1 rounded px-2 py-1.5 text-[11px] font-medium ${a===p?"bg-surface-elevated text-foreground":"text-muted-foreground"}`,children:[s.jsx(m,{size:12}),r(x)]},p))}),s.jsx("div",{className:"h-2"})]}),s.jsx("div",{className:"min-h-0 flex-1 bg-surface",children:a==="architecture"?s.jsx("div",{role:"status",className:"p-3 text-xs text-muted-foreground",children:r("architecture.loading")}):a==="computer"?s.jsx("div",{className:"p-3 text-xs text-muted-foreground",children:r("computer.loading")}):a==="git"?s.jsx(lF,{}):s.jsx(oF,{})})]})});return t.current?s.jsx(b.Suspense,{fallback:d,children:s.jsx(cF,{...e})}):d}const Ob=hc(e=>({overlay:"off",setOverlay:t=>e({overlay:t})}));function uF(e){let t=1,r="terminal";for(;;){let n=!1;for(const a of e.values())if(a.name===r){n=!0;break}if(!n)break;r=`terminal-${t}`,t++}return r}const dF=hc((e,t)=>({sessions:new Map,activeSessionId:null,nextSessionNumber:1,createSession:r=>{const n=n3(),a=Date.now(),c=t().sessions,l=uF(c),d={id:n,cwd:r,sessionId:null,name:l,customName:!1,createdAt:a,lastActivity:a};return e(p=>{const m=new Map(p.sessions);return m.set(n,d),{sessions:m,activeSessionId:p.activeSessionId??n,nextSessionNumber:p.nextSessionNumber+1}}),n},closeSession:r=>{e(n=>{const a=new Map(n.sessions),c=n.activeSessionId===r;a.delete(r);let l=n.activeSessionId;if(c){const d=Array.from(a.keys());l=d.length>0?d[0]:null}return{sessions:a,activeSessionId:l}})},switchSession:r=>{e(n=>n.sessions.has(r)?{activeSessionId:r}:n)},updateSession:(r,n)=>{e(a=>{const c=a.sessions.get(r);if(!c)return a;const l=new Map(a.sessions);return l.set(r,{...c,...n,lastActivity:Date.now()}),{sessions:l}})},setTerminalSession:(r,n)=>{t().updateSession(r,{sessionId:n.sessionId})},getActiveSession:()=>{const r=t();if(r.activeSessionId)return r.sessions.get(r.activeSessionId)},getSessionCount:()=>t().sessions.size,clearAllSessions:()=>{e({sessions:new Map,activeSessionId:null,nextSessionNumber:1})}})),hF=[7e5,1e6,14e5,18e5,24e5,32e5,4e6,5e6,6e6,8e6,1e7,12e6].map(e=>({id:"auto",maxSize:1600,bitRate:e,maxFps:30}));class fF{level=6;badSince=null;goodSince=null;connectedAt=0;lastSample=-1/0;lastChange=-1/0;lastUpgrade=-1/0;upgradeAfter=0;failedProbes=0;baselineRtt=1/0;get quality(){return hF[this.level]}connected(t){this.connectedAt=t,this.badSince=this.goodSince=null,this.lastSample=-1/0}sample(t,r,n=1600){if(r-this.lastSample>2500&&(this.badSince=this.goodSince=null),this.lastSample=r,t.rttMs!==null&&(this.baselineRtt=Math.min(this.baselineRtt,t.rttMs)),r-this.connectedAt<3e3)return null;const a=t.rttMs!==null&&t.rttMs>this.baselineRtt+150,c=t.deliveryDelayMs>250||t.decodeQueue>=4||a&&t.frames>0&&t.deliveryDelayMs>100,l=t.deliveryDelayMs>800||t.decodeQueue>=8,d=t.rttMs!==null&&t.rttMs<this.baselineRtt+100&&t.deliveryDelayMs<80&&t.decodeQueue<=1;this.badSince=c?this.badSince??r:null,this.goodSince=d?this.goodSince??r:null;const p=n<=1080?7:n<=1600?9:11;if(this.badSince!==null&&r-this.badSince>=(l?1e3:2e3)&&r-this.lastChange>=(l?2e3:3e3)&&this.level>0){this.level=Math.max(0,this.level-(l?2:1));const m=r-this.lastUpgrade<2e4;this.failedProbes=m?this.failedProbes+1:0,this.upgradeAfter=r+(m?Math.min(3e4,8e3*2**(this.failedProbes-1)):5e3),this.lastUpgrade=-1/0}else if(this.goodSince!==null&&r-this.goodSince>=3e3&&r-this.lastChange>=4e3&&r>=this.upgradeAfter&&this.level<p)this.level++,this.lastUpgrade=r;else return null;return this.lastChange=r,this.badSince=this.goodSince=null,this.quality}}async function eu(e,t){const r=await fetch(e,{...t,headers:{"Content-Type":"application/json",Accept:"application/json",...t?.headers??{}}}),n=await r.json().catch(()=>null);if(!r.ok||!n){const a=n?.error||n?.code||`ANDROID_REQUEST_FAILED_${r.status}`;throw new Error(a)}return n}async function pF(){return eu("/api/android/devices")}async function mF(e){return eu("/api/android/connect",{method:"POST",body:JSON.stringify({address:e})})}const Ff=[{id:"low",maxSize:720,bitRate:12e5,maxFps:30},{id:"medium",maxSize:1080,bitRate:4e6,maxFps:30},{id:"high",maxSize:1600,bitRate:8e6,maxFps:60}],E0=Ff[1];function R1(e){if(!e||typeof e!="object")return E0;const t=e;if(t.id==="auto")return{id:"auto",maxSize:1600,bitRate:4e6,maxFps:30};const r=Ff.find(l=>l.id===t.id);if(r)return r;if(t.id!=="custom")return E0;const n=typeof t.maxSize=="number"?Math.max(360,Math.min(2160,Math.round(t.maxSize))):1080,a=typeof t.bitRate=="number"?Math.max(3e5,Math.min(3e7,Math.round(t.bitRate))):4e6,c=typeof t.maxFps=="number"?Math.max(0,Math.min(60,Math.round(t.maxFps))):30;return{id:"custom",maxSize:n,bitRate:a,maxFps:c}}function gF(e,t){if(!/^[0-9a-zA-Z_.:\-]{1,128}$/.test(e))throw new Error("INVALID_SERIAL");const r=new URLSearchParams;t&&(r.set("max_size",String(t.maxSize)),r.set("bit_rate",String(t.bitRate)),t.maxFps>0&&r.set("max_fps",String(t.maxFps)));const n=r.toString();return`/api/android/${e}/ws${n?`?${n}`:""}`}function Fb(e){const t={ADB_UNAVAILABLE:"本机没有可用的 adb,请先安装 Android platform-tools。",ADB_NOT_FOUND:"找不到 adb 可执行文件,可用 TERMDOCK_ADB_BIN 指定路径。",SCRCPY_NOT_FOUND:"本机没有 scrcpy,请先安装(含 scrcpy-server)。",SCRCPY_SERVER_NOT_FOUND:"找不到 scrcpy-server,可用 TERMDOCK_SCRCPY_SERVER 指定路径。",SCRCPY_VERSION_UNKNOWN:"无法读取 scrcpy 版本,请确认 scrcpy --version 可执行。",SCRCPY_CONNECT_TIMEOUT:"设备连接超时,请确认已授权 USB 调试并保持解锁。",SCRCPY_UNSUPPORTED_CODEC:"设备返回了不支持的视频编码。",INVALID_ADDRESS:"地址格式不正确,应为 ip:port。",API_NOT_ALLOWED:"当前设备权限不足:投屏需要全权服务授权。"};for(const[r,n]of Object.entries(t))if(e.includes(r))return n;return e}function xF(e){return eu(`/api/android/recordings?serial=${encodeURIComponent(e)}`)}function bF(e){return eu("/api/android/recordings",{method:"POST",body:JSON.stringify({serial:e})})}function yF(e){return eu(`/api/android/recordings/${encodeURIComponent(e)}/stop`,{method:"POST"})}function vF(e,t){return eu(`/api/android/recordings/${encodeURIComponent(e)}/save`,{method:"POST",body:JSON.stringify({directory:t})})}function wF(e){return eu(`/api/android/recordings/${encodeURIComponent(e)}`,{method:"DELETE"})}const AF=0,TF=1,SF=2,CF=3,_F=4,kF=5,LF=7,IF=10,EF=11,NF=16,$b=17,Ub=0,Im=1,RF=2,zb=3,Em=0,Hb=1,Wb=1,Tu=0xffffffffffffffffn,Nh=0xfffffffffffffffen,Hd={HOME:3,APP_SWITCH:187,POWER:26,VOLUME_UP:24,VOLUME_DOWN:25};function K6(e,t,r){e.setUint32(t,Math.max(0,Math.round(r.x))&4294967295),e.setUint32(t+4,Math.max(0,Math.round(r.y))&4294967295),e.setUint16(t+8,Math.min(65535,Math.round(r.screenWidth))),e.setUint16(t+10,Math.min(65535,Math.round(r.screenHeight)))}function MF(e,t,r,n,a,c){const l=new Uint8Array(32),d=new DataView(l.buffer);return d.setUint8(0,SF),d.setUint8(1,e),d.setBigUint64(2,t),K6(d,10,r),d.setUint16(22,Math.max(0,Math.min(65535,Math.round(n*65536)))),d.setUint32(24,a>>>0),d.setUint32(28,c>>>0),l}function Nm(e,t,r=0,n=0){const a=new Uint8Array(14),c=new DataView(a.buffer);return c.setUint8(0,AF),c.setUint8(1,e),c.setUint32(2,t>>>0),c.setUint32(6,r>>>0),c.setUint32(10,n>>>0),a}function jF(e,t,r,n=0){const a=new Uint8Array(21),c=new DataView(a.buffer);c.setUint8(0,CF),K6(c,1,e);const l=d=>Math.max(-32768,Math.min(32767,Math.round(Math.max(-1,Math.min(1,d/16))*32768)));return c.setInt16(13,l(t)),c.setInt16(15,l(r)),c.setUint32(17,n>>>0),a}function DF(e){const t=new TextEncoder().encode(e);if(!t.length)return null;const r=t.subarray(0,300),n=new Uint8Array(5+r.length),a=new DataView(n.buffer);return a.setUint8(0,TF),a.setUint32(1,r.length),n.set(r,5),n}function BF(e){const t=new TextEncoder().encode(e);if(!t.length||t.length>255)return null;const r=new Uint8Array(2+t.length);return r[0]=NF,r[1]=t.length,r.set(t,2),r}function Wd(e){return new Uint8Array([e])}function Gb(e){return new Uint8Array([_F,e])}function QF(e){return new Uint8Array([IF,e?1:0])}function PF(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}function OF(e){const t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function Rm(e){return e.toString(16).padStart(2,"0")}function X6(e,t,r){for(let n=0;n+4<e.length;n++){const a=e[n]===0&&e[n+1]===0&&e[n+2]===1,l=e[n]===0&&e[n+1]===0&&e[n+2]===0&&e[n+3]===1?n+4:a?n+3:-1;if(l<0||l>=e.length)continue;if((r?e[l]>>1&63:e[l]&31)!==t){n=l-1;continue}let p=l+1;for(;p+2<e.length&&!(e[p]===0&&e[p+1]===0&&(e[p+2]===1||e[p+2]===0&&e[p+3]===1));)p++;return e.subarray(l,Math.min(e.length,p))}return null}function FF(e){const t=e?X6(e,7,!1):null;return t&&t.length>=4?`avc1.${Rm(t[1])}${Rm(t[2])}${Rm(t[3])}`:"avc1.42e01e"}function $F(e){const t=e?X6(e,32,!0):null;if(t&&t.length>=13){const r=t[1]>>6&3,n=t[1]&31,a=t[12];return`hev1.${r}.${n}.L${a}.B0`}return"hev1.1.6.L120.B0"}class UF{constructor(t,r){this.canvas=t,this.callbacks=r}canvas;callbacks;liveBitrate=!1;bitrateFailureDetail;get lastBitrateFailure(){return this.bitrateFailureDetail}bitrateRequestId=0;bitratePending=null;get supportsLiveBitrate(){return this.liveBitrate}get canSetBitrate(){return this.liveBitrate&&!this.bitratePending&&this.socket?.readyState===1}setBitrate(t){return!this.canSetBitrate||!Number.isInteger(t)||t<3e5||t>3e7?Promise.resolve(!1):new Promise(r=>{const n=++this.bitrateRequestId,a=setTimeout(()=>this.finishBitrate(!1,`BITRATE_CLIENT_TIMEOUT: requested=${t} bps; no server confirmation within 4000ms`),4e3);this.bitratePending={id:n,value:t,resolve:r,timer:a},this.send({type:"bitrate",requestId:n,bitRate:t})})}finishBitrate(t,r){const n=this.bitratePending;n&&(this.bitratePending=null,clearTimeout(n.timer),t||(this.liveBitrate=!1,this.bitrateFailureDetail=r??this.bitrateFailureDetail??"BITRATE_REASON_UNAVAILABLE: server rejected adjustment without a diagnostic",this.closedByUser||this.callbacks.onBitrateSupport?.(!1,this.bitrateFailureDetail)),n.resolve(t))}socket=null;decoder=null;configured=!1;configData=null;header=null;closedByUser=!1;lastMessageAt=0;lastFrameAt=0;lastResetAt=0;heartbeat=null;statsTimer=null;stallTimer=null;pendingConfig=null;needsKeyframe=!1;frameCount=0;receivedFrames=0;decodedFrames=0;controlsSent=0;lastSeq=0;lastType="";bytesSinceSample=0;warnedUnsupported=!1;lastSampleAt=0;serial="";autoQuality=!1;pingAt=null;rttMs=null;rttAt=0;minimumFrameOffset=1/0;deliveryDelayMs=0;peakDecodeQueue=0;sampleFrames=0;get currentHeader(){return this.header}connect(t,r){this.liveBitrate=!1,this.bitrateFailureDetail=void 0,this.serial=t,this.autoQuality=r?.id==="auto",this.closedByUser=!1,this.callbacks.onState("connecting");let n;try{n=h9(gF(t,r))}catch(a){this.callbacks.onState("error",a instanceof Error?a.message:"ANDROID_STREAM_FAILED");return}this.socket=n,n.onopen=()=>{this.lastMessageAt=Date.now()},n.onmessage=a=>{this.closedByUser||this.handleMessage(a.data)},n.onerror=()=>{this.closedByUser||this.callbacks.onState("error","SCRCPY_CONNECTION_LOST")},n.onclose=()=>{this.finishBitrate(!1,"BITRATE_CONNECTION_CLOSED: preview connection closed"),this.liveBitrate=!1,this.teardownTimers(),this.closedByUser?this.callbacks.onState("idle"):this.callbacks.onState("error","SCRCPY_CONNECTION_CLOSED")},this.startTimers()}disconnect(){this.closedByUser=!0,this.finishBitrate(!1),this.liveBitrate=!1,this.teardownTimers();try{this.decoder?.close()}catch{}this.decoder=null,this.configured=!1;try{this.socket?.close()}catch{}this.socket=null,this.callbacks.onState("idle")}teardownTimers(){this.heartbeat&&clearInterval(this.heartbeat),this.statsTimer&&clearInterval(this.statsTimer),this.stallTimer&&clearInterval(this.stallTimer),this.heartbeat=null,this.statsTimer=null,this.stallTimer=null}startTimers(){this.lastSampleAt=Date.now(),this.heartbeat=setInterval(()=>{if(!(!this.socket||this.socket.readyState!==1)){if(Date.now()-this.lastMessageAt>45e3){try{this.socket.close()}catch{}return}this.pingAt===null&&(this.pingAt=performance.now(),this.send({type:"ping"}))}},this.autoQuality?2e3:15e3),this.stallTimer=setInterval(()=>{if(!this.header||this.closedByUser)return;const t=Date.now();t-this.lastFrameAt>8e3&&t-this.lastResetAt>8e3&&(this.lastResetAt=t,console.warn("[android] no frames for 8s; requesting keyframe reset"),this.sendControl(Wd($b)))},2e3),this.statsTimer=setInterval(()=>{const t=Date.now(),r=(t-this.lastSampleAt)/1e3;r<=0||(this.callbacks.onStats({fps:Math.round(this.frameCount/r*10)/10,kbps:Math.round(this.bytesSinceSample*8/r/1e3),width:this.header?.width??0,height:this.header?.height??0,received:this.receivedFrames,decoded:this.decodedFrames,controls:this.controlsSent,last:this.lastType,adaptation:this.autoQuality?{rttMs:this.pingAt!==null&&performance.now()-this.pingAt>2e3?performance.now()-this.pingAt:performance.now()-this.rttAt<6e3?this.rttMs:null,deliveryDelayMs:this.sampleFrames?this.deliveryDelayMs:0,decodeQueue:Math.max(this.peakDecodeQueue,this.decoder?.decodeQueueSize??0),frames:this.sampleFrames}:void 0}),this.sampleFrames=0,this.peakDecodeQueue=0,this.frameCount=0,this.bytesSinceSample=0,this.lastSampleAt=t)},1e3)}send(t){if(!(!this.socket||this.socket.readyState!==1))try{this.socket.send(JSON.stringify(t))}catch{}}sendControl(t){t&&(this.controlsSent++,this.send({type:"control",data:PF(t)}))}ack(){this.send({type:"ack",seq:this.lastSeq})}handleMessage(t){if(typeof t!="string")return;this.lastMessageAt=Date.now();let r;try{r=JSON.parse(t)}catch{return}this.lastType=`${r.type??"?"}${r.config?":cfg":""}${r.key?":key":""}`;try{this.dispatchMessage(r)}catch(n){console.warn("[android] message handling failed",n),this.callbacks.onWarning(`处理消息失败:${n instanceof Error?n.message:String(n)}`)}}dispatchMessage(t){switch(t.type){case"bitrate-support":this.liveBitrate=t.supported===!0,this.bitrateFailureDetail=this.liveBitrate?void 0:typeof t.detail=="string"?t.detail.slice(0,4096):"BITRATE_REASON_UNAVAILABLE: server did not provide diagnostics",this.liveBitrate||this.finishBitrate(!1,this.bitrateFailureDetail),this.callbacks.onBitrateSupport?.(this.liveBitrate,this.bitrateFailureDetail);break;case"bitrate-result":t.requestId===this.bitratePending?.id&&this.finishBitrate(t.applied===!0&&t.bitRate===this.bitratePending?.value,typeof t.detail=="string"?t.detail.slice(0,4096):void 0);break;case"header":this.header={deviceName:t.deviceName??this.serial,codec:t.codec??"h264",width:t.width??0,height:t.height??0},this.lastFrameAt=Date.now(),this.callbacks.onHeader(this.header),this.callbacks.onState("streaming");break;case"frame":this.handleFrame(t);break;case"error":this.callbacks.onState("error",t.message||"SCRCPY_ERROR");break;case"closed":this.callbacks.onState("error","SCRCPY_SESSION_CLOSED");break;case"pong":this.pingAt!==null&&(this.rttMs=performance.now()-this.pingAt,this.rttAt=performance.now(),this.pingAt=null);break}}handleFrame(t){if(typeof t.data!="string")return;typeof t.seq=="number"&&(this.lastSeq=t.seq);const r=OF(t.data);if(this.bytesSinceSample+=t.data.length,this.receivedFrames++,this.lastFrameAt=Date.now(),this.decoder?.state==="closed"&&(this.decoder=null,this.configured=!1),t.config){this.configData=r,this.pendingConfig=r,this.configureDecoder(),this.ack();return}this.sampleFrames++;const n=Number(t.pts);if(t.pts!==void 0&&Number.isFinite(n)){const l=performance.now()-n/1e3;this.minimumFrameOffset=Math.min(this.minimumFrameOffset,l),this.deliveryDelayMs=Math.max(0,l-this.minimumFrameOffset)}this.configured||this.configureDecoder();const a=t.key===!0;if(this.needsKeyframe&&!a){this.ack();return}let c=r;this.pendingConfig&&(c=new Uint8Array(this.pendingConfig.length+r.length),c.set(this.pendingConfig,0),c.set(r,this.pendingConfig.length),this.pendingConfig=null),a&&(this.needsKeyframe=!1),this.decode(c,a,t.pts),this.ack()}configureDecoder(){const t=this.header?.codec??"h264";if(!this.decoder||this.decoder.state==="closed"){if(typeof VideoDecoder>"u"){this.warnedUnsupported||(this.warnedUnsupported=!0,this.callbacks.onWarning("当前浏览器不支持 WebCodecs(VideoDecoder),无法解码投屏画面。")),this.callbacks.onState("error","VIDEO_DECODER_UNSUPPORTED");return}try{this.decoder=new VideoDecoder({output:c=>this.onDecodedFrame(c),error:c=>{this.configured=!1,console.warn("[android] video decoder error",c),this.callbacks.onState("error",c instanceof Error?c.message:"VIDEO_DECODER_ERROR"),this.sendControl(Wd($b))}})}catch(c){console.warn("[android] VideoDecoder unavailable",c),this.callbacks.onWarning(`创建 VideoDecoder 失败:${c instanceof Error?c.message:String(c)}`),this.callbacks.onState("error","VIDEO_DECODER_UNSUPPORTED");return}}const r={codec:"avc1.42e01e",optimizeForLatency:!0};let n;t==="h264"?(n=[FF(this.configData),"avc1.42e01e","avc1.4d401e","avc1.64001f"].filter((l,d,p)=>p.indexOf(l)===d),r.avc={format:"annexb"}):t==="h265"?(n=[$F(this.configData),"hev1.1.6.L120.B0","hvc1.1.6.L120.B0"],r.hevc={format:"annexb"}):n=["av01.0.04M.08"];const a=[];for(const c of n)try{this.decoder.configure({...r,codec:c}),this.configured=!0,this.needsKeyframe=!0,c!==n[0]&&console.warn("[android] decoder configured with fallback codec",c);return}catch(l){a.push(`${c}: ${l instanceof Error?l.message:String(l)}`),console.warn("[android] decoder configure failed",c,l)}this.callbacks.onWarning(`解码器配置失败(${a.join(";")})`),this.callbacks.onState("error","VIDEO_DECODER_UNSUPPORTED")}decode(t,r,n){if(!(!this.decoder||this.decoder.state!=="configured"))try{this.decoder.decode(new EncodedVideoChunk({type:r?"key":"delta",timestamp:n?Number(n):this.lastTimestamp+1,data:t})),this.peakDecodeQueue=Math.max(this.peakDecodeQueue,this.decoder.decodeQueueSize),this.lastTimestamp=n?Number(n):this.lastTimestamp+1}catch(a){this.decodeFailureCount++<3&&(console.warn("[android] decode threw",a),this.callbacks.onWarning(`送入解码器失败:${a instanceof Error?a.message:String(a)}`))}}decodeFailureCount=0;lastTimestamp=0;onDecodedFrame(t){this.frameCount++,this.decodedFrames++;const r=t.displayWidth||t.codedWidth,n=t.displayHeight||t.codedHeight,a=this.canvas;(a.width!==r||a.height!==n)&&(a.width=r,a.height=n,this.header&&(this.header={...this.header,width:r,height:n},this.callbacks.onHeader(this.header)));const c=a.getContext("2d");c&&c.drawImage(t,0,0,a.width,a.height),t.close()}pointerPoint(t,r){return{x:t,y:r,screenWidth:this.header?.width??0,screenHeight:this.header?.height??0}}touch(t,r,n,a){const c=t===Im||t===zb,l=c?0:1,d=a===Tu&&!c?Wb:0,p=(t===Ub||t===Im)&&a===Tu?Wb:0;this.sendControl(MF(t,a,this.pointerPoint(r,n),l,p,d))}pointerDown(t,r,n){this.touch(Ub,t,r,n==="mouse"?Tu:Nh)}pointerMove(t,r,n){this.touch(RF,t,r,n==="mouse"?Tu:Nh)}pointerUp(t,r,n){this.touch(Im,t,r,n==="mouse"?Tu:Nh)}pointerCancel(t,r,n){this.touch(zb,t,r,n==="mouse"?Tu:Nh)}scroll(t,r,n,a){this.sendControl(jF(this.pointerPoint(t,r),n,a))}key(t,r=Em){this.sendControl(Nm(r,t))}tapKey(t){this.sendControl(Nm(Em,t)),this.sendControl(Nm(Hb,t))}back(){this.sendControl(Gb(Em)),this.sendControl(Gb(Hb))}home(){this.tapKey(Hd.HOME)}recents(){this.tapKey(Hd.APP_SWITCH)}power(){this.tapKey(Hd.POWER)}volumeUp(){this.tapKey(Hd.VOLUME_UP)}volumeDown(){this.tapKey(Hd.VOLUME_DOWN)}rotate(){this.sendControl(Wd(EF))}expandNotifications(){this.sendControl(Wd(kF))}collapsePanels(){this.sendControl(Wd(LF))}setDisplayPower(t){this.sendControl(QF(t))}sendText(t){this.sendControl(DF(t))}startApp(t){this.sendControl(BF(t))}}function zF(){try{return crypto.randomUUID().slice(0,8)}catch{return Math.random().toString(36).slice(2,10)}}function HF(){return`termdock-mirror-shot-${new Date().toISOString().replace(/[-:T]/g,"").slice(0,14)}-${zF()}.png`}function Vb(e){const t=Math.max(0,Math.floor(e/1e3)),r=Math.floor(t/60),n=t%60;return`${String(r).padStart(2,"0")}:${String(n).padStart(2,"0")}`}async function WF(e,t=HF()){const r=e.width,n=e.height;if(!r||!n)throw new Error("投屏画面尚未就绪");const a=document.createElement("canvas");a.width=r,a.height=n;const c=a.getContext("2d");if(!c)throw new Error("无法读取投屏画面");c.drawImage(e,0,0);const l=await new Promise(d=>a.toBlob(d,"image/png"));if(!l||l.size===0)throw new Error("截图失败,请重试");return new File([l],t,{type:"image/png"})}function J6(e,t,r){const n=r.contentWidth*(t-1)/2,a=r.contentHeight*(t-1)/2;return{x:Math.max(-n,Math.min(n,e.x)),y:Math.max(-a,Math.min(a,e.y))}}function qb(e,t,r,n,a){const c=Math.max(1,Math.min(8,e.zoom*a)),l=c/e.zoom;return{zoom:c,pan:J6({x:n.x-t.cx-(r.x-t.cx-e.pan.x)*l,y:n.y-t.cy-(r.y-t.cy-e.pan.y)*l},c,t)}}function e4(e,t){return t?new Promise((r,n)=>{const a=crypto.randomUUID(),c=p=>{window.clearTimeout(d),window.removeEventListener("termdock-insert-reference-ack",l),p?r():n(new Error("目标终端不可用,内容尚未插入,请连接终端后重试"))},l=p=>{const m=p.detail;m?.nonce===a&&c(m.ok===!0)},d=window.setTimeout(()=>c(!1),1e4);window.addEventListener("termdock-insert-reference-ack",l),window.dispatchEvent(new CustomEvent("termdock-insert-reference",{detail:{text:e,sessionId:t,nonce:a,focus:!1,paste:!0}}))}):Promise.reject(new Error("没有可接收内容的终端"))}function Yb(e,t){return e4(c1(e,null),t)}const Mm=hc(e=>({pending:[],enqueue:(t,r,n="/",a)=>e(c=>c.pending.some(l=>l.file.id===t.id)?c:{pending:[...c.pending,{file:t,sessionId:r,initialPath:n,insert:a}]}),remove:t=>e(r=>({pending:r.pending.filter(n=>n.file.id!==t)}))}));function GF({file:e,initialPath:t,onInsert:r,onDone:n}){const{t:a}=Ur(),[c,l]=b.useState(!1),[d,p]=b.useState(!1),[m,x]=b.useState(!1),[y,w]=b.useState(!1),[v,S]=b.useState(null),L=b.useRef(!1),E=b.useRef(null),R=async()=>{if(!L.current){L.current=!0,p(!0),w(!0);try{await wF(e.id),n()}catch(z){S(z instanceof Error?z.message:String(z))}finally{L.current=!1,p(!1),w(!1)}}};b.useEffect(()=>{if(c)return;E.current?.focus();const z=O=>{if(O.stopPropagation(),O.key==="Escape"&&O.preventDefault(),O.key!=="Tab")return;const $=Array.from(E.current?.querySelectorAll("button:not(:disabled)")??[]),V=$[0],Z=$.at(-1);O.shiftKey&&(document.activeElement===V||document.activeElement===E.current)?(O.preventDefault(),Z?.focus()):!O.shiftKey&&document.activeElement===Z&&(O.preventDefault(),V?.focus())};return document.addEventListener("keydown",z,!0),()=>document.removeEventListener("keydown",z,!0)},[c]);const B=async z=>{if(!L.current){L.current=!0,p(!0),x(z!==void 0),l(!1),S(null);try{const O=await vF(e.id,z);z===void 0&&await r(O.path),n()}catch(O){S(O instanceof Error?O.message:String(O))}finally{L.current=!1,p(!1)}}};return c?s.jsx(rp,{open:!0,initialPath:t||"/",title:a("android.recordingSave"),onCancel:()=>l(!1),onConfirm:z=>{B(z)}}):Xs.createPortal(s.jsx("div",{className:"fixed inset-0 z-modal-panel flex items-center justify-center bg-[var(--app-backdrop)] p-4",children:s.jsxs("div",{ref:E,role:"dialog","aria-modal":"true","aria-labelledby":"recording-save-title",tabIndex:-1,"aria-busy":d,className:"w-full max-w-sm rounded-xl border border-border bg-surface p-4 text-foreground shadow-xl outline-none",children:[s.jsx("h2",{id:"recording-save-title",className:"text-sm font-semibold",children:a("android.recordingConfirm")}),s.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:a("android.recordingSaveHint")}),s.jsxs("p",{className:"mt-2 break-all text-xs text-muted-foreground",children:[e.name," · ",(e.size/1024/1024).toFixed(1)," MB"]}),(v||e.error)&&s.jsx("p",{role:"alert",className:"mt-3 break-words text-xs text-destructive",children:v||e.error}),d&&s.jsxs("p",{role:"status",className:"mt-3 flex items-center gap-2 text-sm text-primary",children:[s.jsx(_n,{size:16,className:"animate-spin"}),y?`${a("android.recordingDiscard")}…`:a(m?"android.recordingSaving":"android.captureInserting")]}),s.jsxs("div",{className:"mt-4 flex flex-col gap-2",children:[s.jsx("button",{type:"button",disabled:d||e.status!=="ready",onClick:()=>{B()},className:"min-h-10 rounded-lg bg-primary px-3 text-sm text-primary-foreground disabled:opacity-40",children:a("android.recordingInsert")}),s.jsx("button",{type:"button",disabled:d||e.status!=="ready",onClick:()=>l(!0),className:"min-h-10 rounded-lg bg-surface-2 px-3 text-sm disabled:opacity-40",children:a("android.recordingSave")}),s.jsx("button",{type:"button",disabled:d,onClick:()=>{R()},className:"min-h-10 rounded-lg px-3 text-sm text-muted-foreground disabled:opacity-40",children:a("android.recordingDiscard")})]})]})}),document.body)}const r0="android-mirror",Gd=r0,t4="termdock:android:quality:v1",jm=176,VF=204,_l=1,nf=8,Zb=[1,1.25,1.5,2,2.5,3,4,6,8],qF=e=>Math.max(_l,Math.min(nf,e));function YF(e){return`${Number.isInteger(e)?e:e.toFixed(1)}×`}function Rh(e){const t=e.parentElement;if(!t)return null;const r=t.getBoundingClientRect(),n=getComputedStyle(t),a=parseFloat(n.paddingLeft)||0,c=parseFloat(n.paddingTop)||0,l=t.clientWidth-a-(parseFloat(n.paddingRight)||0),d=t.clientHeight-c-(parseFloat(n.paddingBottom)||0);return{cx:r.left+t.clientLeft+a+l/2,cy:r.top+t.clientTop+c+d/2,width:l,height:d,contentWidth:e.offsetWidth,contentHeight:e.offsetHeight}}function ZF(e,t){try{e.setPointerCapture?.(t)}catch{}}function Kb(e,t){try{e.releasePointerCapture?.(t)}catch{}}const Xb=e=>typeof requestAnimationFrame=="function"?requestAnimationFrame(e):window.setTimeout(e,16),Mh=e=>{typeof cancelAnimationFrame=="function"?cancelAnimationFrame(e):window.clearTimeout(e)},Dm={auto:"android.qualityAuto",low:"android.qualityLow",medium:"android.qualityMedium",high:"android.qualityHigh",custom:"android.qualityCustom"},KF=()=>{try{const e=localStorage.getItem(t4);return e?R1(JSON.parse(e)):E0}catch{return E0}},Vd=e=>{try{localStorage.setItem(t4,JSON.stringify(e))}catch{}};function XF({sessionId:e,dockOnly:t=!1,onInsertPrompt:r,onInsertFile:n,onRecordingComplete:a,onCloseTab:c}){const{t:l}=Ur(),d=Ob(N=>N.overlay),p=Ob(N=>N.setOverlay),m=b.useRef(null),x=b.useRef(null),y=b.useRef(null),w=b.useMemo(KF,[]),v=b.useRef(w),S=b.useRef(null),L=b.useRef(null),[E,R]=b.useState(4e6),B=b.useRef(null),z=b.useRef(new Map),O=b.useRef(null),$=b.useRef(!1),[V,Z]=b.useState(_l),le=b.useRef(V),be=b.useRef({x:0,y:0}),pe=b.useRef(null),ee=b.useRef(0),_e=b.useRef(0),ze=b.useRef(null),Y=b.useRef(0),[ce,qe]=b.useState(null),[we,ye]=b.useState(null),[Le,Be]=b.useState(!0),[ne,Fe]=b.useState(""),[ke,Ee]=b.useState(w.id),[Pe,Ne]=b.useState([]),[oe,We]=b.useState(null),[nt,gt]=b.useState(""),[ue,Ze]=b.useState(!0),[at,Ie]=b.useState({maxSize:w.maxSize,bitRate:w.bitRate,maxFps:w.maxFps}),[Ge,Ce]=b.useState("idle"),[H,ae]=b.useState(null),[Ae,Ye]=b.useState(null),[et,St]=b.useState({fps:0,kbps:0,width:0,height:0,received:0,decoded:0,controls:0,last:""}),[Gt,Qt]=b.useState(null),[wt,zt]=b.useState(null),[Vt,Kt]=b.useState(!1),[Ot,It]=b.useState([]),[xe,Ve]=b.useState(null),[ht,q]=b.useState([]),[ut,qt]=b.useState(!1),tt=b.useRef(null),De=b.useRef(0),nr=b.useRef([]),[Ke,_t]=b.useState(!1),[$t,yt]=b.useState(""),[xt,Rt]=b.useState(!1),[Ct,fr]=b.useState(!1),[Yt,Sr]=b.useState(""),[pn,dr]=b.useState(null),[me,Gr]=b.useState(null),[ot,pt]=b.useState(!1),[ir,Mn]=b.useState(0),Xr=b.useRef(null),[je,st]=b.useState(!1),bt=b.useRef(!1),Br=b.useRef(new Set),Vr=b.useRef(null),Cr=b.useRef(null),qr=b.useRef(!1),[mn,on]=b.useState(!1),zr=b.useRef(a);zr.current=a;const[un,Er]=b.useState(!1),[re,mt]=b.useState(null),Mt=b.useRef(null),rr=b.useRef(null),Ar=dF(N=>N.activeSessionId??N.sessions.keys().next().value??null),Fr=e??Ar,Xt=Kn(N=>!!N.docks[Gd]),Zr=Kn(N=>N.hosts[Gd]),Jt=Kn(N=>N.setDock),Pr=b.useCallback(async()=>{Be(!0);try{const N=await pF();qe(N),ye(null)}catch(N){ye(N instanceof Error?N.message:"ADB_UNAVAILABLE")}finally{Be(!1)}},[]);b.useEffect(()=>{Pr()},[Pr]);const Hr=ce?.devices??[],ps=Hr.find(N=>N.serial===ne)??null,Mr=!!(we&&/ADB_NOT_FOUND|ADB_UNAVAILABLE/i.test(we)),jn=!!(ce?.adbAvailable&&!ce.scrcpyVersion),Tr=b.useCallback(()=>{const N=B.current,U=[...z.current.keys()];B.current=null,z.current.clear(),O.current=null,$.current=!1,tt.current=null,Mh(ee.current),ee.current=0,N&&x.current?.pointerCancel(N.x,N.y,N.type);const K=m.current;if(K)for(const fe of U)Kb(K,fe);Ve(null),qt(!1),q([]),Z(le.current)},[]);b.useEffect(()=>{const N=fe=>{z.current.has(fe.pointerId)&&(fe.type==="pointercancel"||fe.target!==m.current)&&Tr()},U=()=>Tr(),K=()=>{document.hidden&&Tr()};return window.addEventListener("pointerup",N,!0),window.addEventListener("pointercancel",N,!0),window.addEventListener("blur",U),document.addEventListener("visibilitychange",K),()=>{window.removeEventListener("pointerup",N,!0),window.removeEventListener("pointercancel",N,!0),window.removeEventListener("blur",U),document.removeEventListener("visibilitychange",K),Tr()}},[Tr]);const Jr=b.useCallback(()=>{Tr(),x.current?.disconnect(),x.current=null,Ce("idle"),ae(null),Ye(null)},[Tr]),ln=b.useCallback((N,U=!1)=>{const K=m.current;if(!K||!N)return;Tr(),x.current?.disconnect(),ae(null),!U&&y.current!==N&&Ye(null),y.current=N,zt(null),Qt(null);const fe=new UF(K,{onBitrateSupport:(ve,lt)=>{x.current!==fe||v.current.id!=="auto"||Qt(ve?null:lt??"BITRATE_REASON_UNAVAILABLE")},onState:(ve,lt)=>{x.current===fe&&(Ce(ve),ae(lt??null))},onHeader:ve=>{x.current===fe&&Ye(ve)},onStats:ve=>{x.current===fe&&St(ve)},onWarning:ve=>{x.current===fe&&zt(ve)}});x.current=fe;let Qe=v.current;Qe.id==="auto"?(S.current?.serial!==N&&(S.current={serial:N,policy:new fF}),S.current.policy.connected(performance.now()),Qe=S.current.policy.quality,R(Qe.bitRate)):S.current=null,L.current=Qe,fe.connect(N,Qe)},[Tr]);b.useEffect(()=>{if(ke!=="auto"||v.current.id!=="auto"||Ge!=="streaming"||!et.adaptation||document.hidden)return;const N=S.current,U=x.current;if(!N||N.serial!==ne||!U?.canSetBitrate)return;const K=m.current,fe=K?Math.max(K.clientWidth,K.clientHeight)*(window.devicePixelRatio||1)*le.current:1600,Qe=N.policy.sample(et.adaptation,performance.now(),fe||1600);Qe&&U.setBitrate(Qe.bitRate).then(ve=>{ve&&x.current===U&&(L.current=Qe,R(Qe.bitRate))})},[et,ke,Ge,ne,ln]);const Qr=b.useCallback(N=>{const U={...N.quality?{quality:{id:N.quality.id,maxSize:N.quality.maxSize,bitRate:N.quality.bitRate,maxFps:N.quality.maxFps}}:{},...N.activePresetId!==void 0?{activePresetId:N.activePresetId}:{},...N.presets!==void 0?{presets:N.presets}:{},...N.docked!==void 0?{docked:N.docked}:{},...N.deviceSerial!==void 0?{deviceSerial:N.deviceSerial}:{}};La({androidPanel:U}).catch(()=>{})},[]);b.useEffect(()=>{let N=!1;return fc().then(U=>{if(N)return;const K=U.androidPanel;if(K?.quality){const fe=R1(K.quality);v.current=fe,Ee(fe.id),Ie({maxSize:fe.maxSize,bitRate:fe.bitRate,maxFps:fe.maxFps}),Vd(fe)}Ne(K?.presets??[]),We(K?.activePresetId??null),K?.deviceSerial&&(ze.current=K.deviceSerial,Fe(K.deviceSerial))}).catch(()=>{}),()=>{N=!0}},[]);const ks=b.useCallback(N=>{const U=++De.current;It(fe=>[...fe,{id:U,left:N.left,top:N.top}]);const K=window.setTimeout(()=>{It(fe=>fe.filter(Qe=>Qe.id!==U)),nr.current=nr.current.filter(fe=>fe!==K)},300);nr.current.push(K)},[]),Dr=b.useCallback((N,U)=>{const K=x.current,fe=L.current;K?.supportsLiveBitrate&&y.current===N&&fe&&fe.maxSize===U.maxSize&&fe.maxFps===U.maxFps?K.setBitrate(U.bitRate).then(Qe=>{x.current===K&&(Qe?(L.current=U,Qt(null)):Qt(K.lastBitrateFailure??"BITRATE_REASON_UNAVAILABLE"))}):ln(N)},[ln,l]),en=b.useCallback(N=>{if(S.current=null,N.startsWith("user:")){const K=Pe.find(Qe=>Qe.id===N.slice(5));if(!K)return;const fe={id:"custom",maxSize:K.maxSize,bitRate:K.bitRate,maxFps:K.maxFps};v.current=fe,Ee("custom"),We(K.id),Ie({maxSize:K.maxSize,bitRate:K.bitRate,maxFps:K.maxFps}),Ze(!0),Vd(fe),Qr({quality:fe,activePresetId:K.id}),ne&&ln(ne);return}if(N==="custom"){const K=v.current;Ee("custom"),We(null),Ie({maxSize:K.maxSize,bitRate:K.bitRate,maxFps:K.maxFps}),Ze(!0);return}const U=N==="auto"?R1({id:"auto"}):Ff.find(K=>K.id===N)??E0;v.current=U,Ee(U.id),We(null),Vd(U),Qr({quality:U,activePresetId:null}),ne&&ln(ne)},[ln,ne,Pe,Qr]),xn=b.useCallback(()=>{const N={id:"custom",maxSize:at.maxSize,bitRate:at.bitRate,maxFps:at.maxFps};v.current=N,Vd(N),Qr({quality:N,activePresetId:null}),Ee("custom"),We(null),ne&&Dr(ne,N)},[Dr,ne,at,Qr]),X=b.useCallback(()=>{const N=nt.trim();if(!N)return;const U=`p${Date.now().toString(36)}${Math.random().toString(36).slice(2,6)}`,K={id:U,name:N,maxSize:at.maxSize,bitRate:at.bitRate,maxFps:at.maxFps},fe=[...Pe.filter(ve=>ve.name!==N),K].slice(-12),Qe={id:"custom",maxSize:at.maxSize,bitRate:at.bitRate,maxFps:at.maxFps};Ne(fe),gt(""),We(U),Ee("custom"),v.current=Qe,Vd(Qe),Qr({quality:Qe,activePresetId:U,presets:fe}),ne&&Dr(ne,Qe)},[nt,at,Pe,ne,Dr,Qr]),He=b.useCallback(()=>{if(!oe)return;const N=Pe.filter(U=>U.id!==oe);Ne(N),We(null),Qr({activePresetId:null,presets:N})},[oe,Pe,Qr]);b.useEffect(()=>()=>{x.current?.disconnect(),x.current=null;for(const N of nr.current)window.clearTimeout(N);nr.current=[]},[]),b.useEffect(()=>{if(d==="off")return;const N=U=>{U.key==="Escape"&&p("off")};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[d,p]),b.useEffect(()=>{const N=Hr.filter(K=>K.state==="device");if(ne||N.length!==1)return;const U=N[0].serial;ze.current!==U&&(ze.current=U,Fe(U))},[Hr,ne]),b.useEffect(()=>{ne&&ln(ne)},[ne,ln]),b.useEffect(()=>{if(Ge==="streaming"){Y.current=0,Kt(!1);return}if(Ge!=="error"||!ne||!e$(H??""))return;const N=Math.min(8e3,700*2**Y.current);Y.current+=1,Kt(!0);const U=window.setTimeout(()=>{Kt(!1),ln(ne)},N);return()=>window.clearTimeout(U)},[Ge,H,ne,ln]);const Nt=b.useCallback((N,U,K)=>{const fe=m.current,Qe=K??(fe?Rh(fe):null);return!fe||!Qe?{x:0,y:0}:J6(N,U,Qe)},[]),Et=b.useCallback(()=>{const N=m.current;if(!N)return;const{x:U,y:K}=be.current,fe=le.current,Qe=fe===_l&&U===0&&K===0?"":`translate3d(${U}px, ${K}px, 0) scale(${fe})`;N.style.transform!==Qe&&(N.style.transform=Qe);const ve=pe.current;ve&&(ve.textContent=fe>_l?YF(fe):"")},[]),tr=b.useCallback((N,U,K=!0)=>{const fe=m.current,Qe=le.current,ve=qF(N);if(!fe||ve===Qe)return;const lt=Rh(fe);if(!lt)return;const vt=U??{x:lt.cx,y:lt.cy},br=qb({zoom:Qe,pan:be.current},lt,vt,vt,ve/Qe);le.current=br.zoom,be.current=br.pan,K&&Et()},[Et]),jr=b.useCallback(()=>{const N=le.current;Z(U=>U<=_l+.01==N<=_l+.01&&U>=nf-.01==N>=nf-.01?U:N)},[]);b.useEffect(()=>()=>{Mh(ee.current),Mh(_e.current)},[]);const cr=()=>{let N=0,U=0;for(const fe of z.current.values())N+=fe.x,U+=fe.y;const K=z.current.size;return K?{x:N/K,y:U/K}:null},Cn=()=>{const[N,U]=Array.from(z.current.values());return N&&U?Math.hypot(N.x-U.x,N.y-U.y):0},Ls=()=>{const N=cr(),U=m.current?Rh(m.current):null;!N||!U||(O.current={startCentroid:N,startDistance:Cn(),box:U})},Xn=b.useCallback(()=>{const N=O.current,U=cr();if(!N||!U)return;const K=Cn(),fe=N.startDistance>0&&K>0?K/N.startDistance:1,Qe=qb({zoom:le.current,pan:be.current},N.box,N.startCentroid,U,fe);le.current=Qe.zoom,be.current=Qe.pan,N.startCentroid=U,N.startDistance=K},[]),cn=b.useCallback(()=>{ee.current||(ee.current=Xb(()=>{ee.current=0,Xn(),Et()}))},[Xn,Et]),dn=b.useCallback(()=>{ee.current&&(Mh(ee.current),ee.current=0,Xn(),Et())},[Xn,Et]);b.useEffect(()=>{const N=m.current;if(!N)return;const U=N.parentElement;if(!U)return;const K=Qe=>{if(Qe.ctrlKey||Qe.metaKey){if(Qe.preventDefault(),!Qe.deltaY||O.current)return;const vt=Qe.deltaMode===1?16:Qe.deltaMode===2?N.parentElement?.clientHeight||600:1,br=Math.max(-600,Math.min(600,Qe.deltaY*vt));tr(le.current*Math.exp(-br*.002),{x:Qe.clientX,y:Qe.clientY},!1),_e.current||(_e.current=Xb(()=>{_e.current=0,Et(),jr()}));return}const ve=x.current;if(!ve||Qe.target!==N)return;Qe.preventDefault();const lt=Dh(N,Qe.clientX,Qe.clientY);ve.scroll(lt.x,lt.y,Qe.deltaX,Qe.deltaY)},fe=Qe=>Qe.preventDefault();return U.addEventListener("wheel",K,{passive:!1}),U.addEventListener("gesturestart",fe,{passive:!1}),U.addEventListener("gesturechange",fe,{passive:!1}),()=>{U.removeEventListener("wheel",K),U.removeEventListener("gesturestart",fe),U.removeEventListener("gesturechange",fe)}},[tr,Et,jr]),b.useEffect(()=>{const N=m.current,U=N?.parentElement;if(!N||!U||typeof ResizeObserver>"u")return;const K=new ResizeObserver(()=>{O.current&&(O.current.box=Rh(N));const fe=Nt(be.current,le.current);fe.x===be.current.x&&fe.y===be.current.y||(be.current=fe,Et())});return K.observe(N),K.observe(U),()=>K.disconnect()},[Nt,Et]),b.useLayoutEffect(()=>{Et()});const _r=N=>{const U=x.current,K=m.current;if(!U||!K)return;if(N.pointerType==="mouse"&&N.button!==0){N.preventDefault(),N.button===2?U.back():N.button===1&&U.home();return}N.preventDefault(),K.closest(".android-mirror-panel")?.focus({preventScroll:!0}),Et(),jr(),dn(),ZF(K,N.pointerId),z.current.set(N.pointerId,{x:N.clientX,y:N.clientY});const fe=N.pointerType==="mouse"&&N.altKey;if(z.current.size>=2||fe){const lt=B.current;lt&&(U.pointerCancel(lt.x,lt.y,lt.type),B.current=null,tt.current=null,Ve(null),qt(!1),q([])),$.current=!0,Ls();return}if($.current)return;const Qe=Dh(K,N.clientX,N.clientY);B.current={id:N.pointerId,type:N.pointerType,x:Qe.x,y:Qe.y},U.pointerDown(Qe.x,Qe.y,N.pointerType);const ve=ny(K,N.clientX,N.clientY);ve&&(tt.current={left:ve.left,top:ve.top},q([]),qt(!1),Ve(ve))},Or=N=>{const U=x.current,K=m.current;if(!K||!z.current.has(N.pointerId))return;if(N.pointerType==="mouse"){const vt=K.getBoundingClientRect(),br=K.parentElement?.getBoundingClientRect()??vt;if(!(N.buttons&1)||N.clientX<Math.max(vt.left,br.left)||N.clientX>=Math.min(vt.right,br.right)||N.clientY<Math.max(vt.top,br.top)||N.clientY>=Math.min(vt.bottom,br.bottom)){Tr();return}}if(N.preventDefault(),z.current.set(N.pointerId,{x:N.clientX,y:N.clientY}),O.current){cn();return}const fe=B.current;if(!U||!fe||fe.id!==N.pointerId)return;const Qe=Dh(K,N.clientX,N.clientY);fe.x=Qe.x,fe.y=Qe.y,U.pointerMove(Qe.x,Qe.y,fe.type);const ve=ny(K,N.clientX,N.clientY),lt=tt.current;!ve||!lt||(Ve(ve),Math.hypot(ve.left-lt.left,ve.top-lt.top)>=6&&(qt(!0),q(vt=>{const br=vt[vt.length-1];if(br&&Math.hypot(ve.left-br.x,ve.top-br.y)<4)return vt;const Lt=[...vt,{x:ve.left,y:ve.top}];return Lt.length>12?Lt.slice(Lt.length-12):Lt})))},Gn=N=>{const U=x.current,K=m.current;if(!K||!z.current.has(N.pointerId))return;if(dn(),z.current.delete(N.pointerId),Kb(K,N.pointerId),z.current.size===0&&($.current=!1),O.current){z.current.size===0?(O.current=null,Z(le.current)):Ls();return}const fe=B.current;if(!fe||fe.id!==N.pointerId)return;const Qe=Dh(K,N.clientX,N.clientY);U?.pointerUp(Qe.x,Qe.y,fe.type),xe&&ks(xe),Ve(null),qt(!1),window.setTimeout(()=>q([]),200),B.current=null,tt.current=null},Vn=N=>{if(un||Ke||Ct)return;const U=x.current;U&&(N.key==="Backspace"?(N.preventDefault(),U.key(67)):N.key==="Escape"?(N.preventDefault(),U.back()):N.key==="Enter"&&(N.preventDefault(),U.key(66)))},gn=async()=>{const N=$t.trim();if(N){Rt(!0);try{const U=await mF(N);yt(""),_t(!1),await Pr(),Fe(U.serial)}catch(U){ye(U instanceof Error?U.message:"ADB_CONNECT_FAILED")}finally{Rt(!1)}}},Jn=()=>{const N=x.current,U=Yt;!N||!U||(N.sendText(U),Sr(""))},kr=b.useCallback(N=>{dr(N),Cr.current!==null&&window.clearTimeout(Cr.current),Cr.current=window.setTimeout(()=>{Cr.current=null,dr(null)},2500)},[]),Lr=b.useCallback(N=>{const U=le.current,K=N==="in"?Zb.find(fe=>fe>U+.01):[...Zb].reverse().find(fe=>fe<U-.01);K!==void 0&&(U<=_l&&K>_l&&kr(l("android.zoomPanHint")),dn(),tr(K),Z(K))},[tr,dn,kr,l]),pr=N=>{Promise.resolve().then(()=>r?.(N)).catch(U=>{Gr(U instanceof Error?U.message:String(U))})},ns=b.useCallback(async(N,U)=>{try{if(!n)throw new Error(l("android.captureUnavailable"));await n(N),kr(U)}catch(K){Gr(l("android.captureFailed")+(K instanceof Error?`:${K.message}`:""))}},[n,kr,l]),Un=async()=>{const N=m.current;if(!(!N||qr.current)){qr.current=!0,on(!0),Gr(null);try{const U=await WF(N);await ns(U,l("android.captureInserted"))}catch(U){Gr(U instanceof Error?U.message:String(U))}finally{qr.current=!1,on(!1)}}},En=b.useCallback(N=>{(N.status==="ready"||N.status==="error")&&zr.current&&!Br.current.has(N.id)&&(Br.current.add(N.id),zr.current?.(N))},[]),kn=b.useCallback(async N=>{const U=Xr.current;if(!(!U||bt.current)){bt.current=!0,st(!0),Gr(null);try{const K=await yF(U.id);Xr.current=null,pt(!1),En(K)}catch(K){Gr(K instanceof Error?K.message:String(K))}finally{bt.current=!1,st(!1)}}},[En]),ss=async()=>{if(!(!ne||bt.current||Xr.current)){bt.current=!0,st(!0),Gr(null);try{const N=await bF(ne);N.status==="recording"||N.status==="starting"||N.status==="stopping"?(Xr.current=N,pt(!0),Mn(Math.max(0,Date.now()-N.startedAt))):En(N)}catch(N){Gr(N instanceof Error?N.message:String(N))}finally{bt.current=!1,st(!1)}}};b.useEffect(()=>{let N=!1,U=!1;Xr.current=null,pt(!1);const K=async()=>{if(!(!ne||U||bt.current)){U=!0;try{const{recordings:Qe}=await xF(ne);if(N||bt.current)return;const ve=Qe.find(lt=>["starting","recording","stopping"].includes(lt.status));Xr.current=ve??null,pt(!!ve);for(const lt of Qe)En(lt)}catch{}finally{U=!1}}};K();const fe=window.setInterval(()=>{K()},2e3);return Vr.current=window.setInterval(()=>{Xr.current&&Mn(Math.max(0,Date.now()-Xr.current.startedAt))},500),()=>{N=!0,window.clearInterval(fe),Vr.current!==null&&window.clearInterval(Vr.current)}},[ne,En]),b.useEffect(()=>{if(!un)return;const N=()=>Er(!1),U=fe=>{const Qe=fe.target;Qe instanceof Node&&(Mt.current?.contains(Qe)||rr.current?.contains(Qe)||N())},K=fe=>{fe.key==="Escape"&&(fe.preventDefault(),fe.stopPropagation(),N())};return document.addEventListener("pointerdown",U,!0),document.addEventListener("keydown",K,!0),window.addEventListener("resize",N),()=>{document.removeEventListener("pointerdown",U,!0),document.removeEventListener("keydown",K,!0),window.removeEventListener("resize",N)}},[un]),b.useEffect(()=>()=>{Cr.current!==null&&window.clearTimeout(Cr.current)},[]);const Wr=Ge==="streaming",tn=Xt,G=tn?"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded hover:bg-surface-2 disabled:opacity-40":"rounded p-1.5 hover:bg-surface-2 disabled:opacity-40",Me=ps?(ps.model||ps.serial)+sy(ps,l):Hr.length?l("android.selectDevice"):l("android.noDevices"),Je=(oe?Pe.find(N=>N.id===oe):null)?.name??(ke==="auto"?`${l("android.qualityAuto")} · ${E/1e6} Mbps`:l(Dm[ke])),it=tn?"relative flex h-5 min-w-0 items-center rounded bg-surface-2 focus-within:ring-1 focus-within:ring-primary/50":"relative flex h-7 min-w-0 items-center rounded bg-surface-2 focus-within:ring-1 focus-within:ring-primary/50",Tt=tn?"pointer-events-none block min-w-0 truncate px-1 text-[10px] leading-none text-foreground":"pointer-events-none block min-w-0 truncate px-2 text-[11px] leading-none text-foreground",kt="absolute inset-0 h-full w-full cursor-pointer opacity-0",Dt=()=>{const N=Mt.current?.getBoundingClientRect();N&&mt({left:Math.max(8,Math.min(N.right-jm,window.innerWidth-jm-8)),top:Math.min(N.bottom+4,Math.max(8,window.innerHeight-VF-8))}),Er(!0)},ft=()=>{if(Xt){Jt(Gd,null),Qr({docked:null});return}if(!Fr)return;const N={sessionId:Fr,side:"right"};Jt(Gd,N),Qr({docked:N})},Bt=Ke||Xt||d!=="off",W=s.jsxs("div",{className:"android-mirror-panel flex h-full min-h-0 min-w-0 flex-col bg-surface text-foreground","data-sidebar-gesture-ignore":"true",onKeyDown:Vn,tabIndex:-1,children:[s.jsxs("div",{"data-panel-drag-title":Xt?"true":void 0,className:tn?"flex h-6 min-h-6 shrink-0 flex-nowrap items-center gap-1 overflow-hidden border-b border-border/15 bg-[var(--chrome-bg)] px-1.5 cursor-grab select-none active:cursor-grabbing":"flex flex-wrap items-center gap-1.5 border-b border-border px-2 py-2",children:[Xt&&s.jsx("span",{"data-panel-drag-title":"true",role:"button","aria-label":l("android.splitDrag"),title:l("android.splitDrag"),className:"flex h-4 w-4 shrink-0 cursor-grab items-center justify-center rounded text-muted-foreground hover:text-foreground active:cursor-grabbing",children:s.jsx($f,{size:12})}),s.jsx(f9,{size:tn?12:14,className:"shrink-0 text-muted-foreground"}),s.jsxs("div",{className:`${it} flex-1`,children:[s.jsx("span",{"aria-hidden":"true",className:`${Tt} w-full`,children:Me}),s.jsxs("select",{value:ne,onChange:N=>{const U=N.target.value;Fe(U),ze.current=U,U&&Qr({deviceSerial:U})},className:kt,"aria-label":l("android.device"),children:[s.jsx("option",{value:"",children:Hr.length?l("android.selectDevice"):l("android.noDevices")}),Hr.map(N=>s.jsx("option",{value:N.serial,children:(N.model||N.serial)+sy(N,l)},N.serial))]})]}),s.jsxs("div",{className:`${it} max-w-[45%] shrink-0`,children:[s.jsx("span",{"aria-hidden":"true",className:Tt,children:Je}),s.jsxs("select",{value:oe?`user:${oe}`:ke,onChange:N=>en(N.target.value),className:kt,title:l(ke==="auto"?"android.qualityAutoHint":"android.quality"),"aria-label":l("android.quality"),children:[s.jsxs("option",{value:"auto",children:[l("android.qualityAuto"),ke==="auto"?` · ${E/1e6} Mbps`:""]}),Ff.map(N=>s.jsx("option",{value:N.id,children:l(Dm[N.id])},N.id)),Pe.map(N=>s.jsx("option",{value:`user:${N.id}`,children:N.name},N.id)),s.jsx("option",{value:"custom",children:l(Dm.custom)})]})]}),s.jsx("button",{type:"button",onClick:()=>{Pr()},className:`${G} text-muted-foreground`,title:l("android.refresh"),children:Le?s.jsx(_n,{size:13,className:"animate-spin"}):s.jsx(bn,{size:13})}),Wr?s.jsx("button",{type:"button",onClick:Jr,className:`${G} text-destructive`,title:l("android.disconnect"),children:s.jsx(Hy,{size:13})}):s.jsx("button",{type:"button",onClick:()=>ne&&ln(ne),disabled:!ne,className:`${G} text-primary`,title:l("android.connect"),children:s.jsx(oS,{size:13})}),(Wr||ot)&&s.jsx("button",{type:"button",onClick:()=>{Un()},disabled:!n||mn,className:`${G} text-muted-foreground`,title:l(n?"android.screenshot":"android.captureUnavailable"),"aria-label":l("android.screenshot"),children:mn?s.jsx(_n,{size:tn?12:13,className:"animate-spin"}):s.jsx($A,{size:tn?12:13})}),(Wr||ot)&&s.jsx("button",{type:"button",onClick:()=>{ot?kn("manual"):ss()},disabled:je||!ot&&!a,className:`${G} ${ot?"text-destructive":"text-muted-foreground"}`,title:l(ot?"android.recordingStop":a?"android.recordingStart":"android.captureUnavailable"),"aria-label":l(ot?"android.recordingStop":"android.recordingStart"),children:je?s.jsx(_n,{className:"animate-spin",size:13}):ot?s.jsx(zy,{size:tn?10:11,fill:"currentColor"}):s.jsx(Wy,{size:tn?12:13})}),s.jsx("button",{ref:Mt,type:"button",onClick:()=>un?Er(!1):Dt(),"aria-haspopup":"menu","aria-expanded":un,className:`${G} ${Bt?"text-primary":"text-muted-foreground"}`,title:l("android.more"),"aria-label":l("android.more"),children:s.jsx(To,{size:tn?13:14})}),c&&!t&&s.jsx("button",{type:"button",onClick:()=>{Er(!1),p("off"),c()},className:`${G} text-muted-foreground hover:bg-destructive/20 hover:text-destructive`,title:l("android.closeTab"),"aria-label":l("android.closeTab"),children:s.jsx(In,{size:14})})]}),un&&re&&Xs.createPortal(s.jsxs("div",{ref:rr,role:"menu","aria-label":l("android.more"),style:{left:re.left,top:re.top,width:jm},className:"fixed z-popover overflow-hidden rounded-md border border-border bg-surface-elevated py-1 text-[11px] shadow-lg",children:[s.jsx(jh,{icon:s.jsx(ul,{size:13}),label:l("android.addDevice"),active:Ke,onSelect:()=>{_t(N=>!N),Er(!1)}}),s.jsx(jh,{icon:Xt?s.jsx(In,{size:13}):s.jsx(Il,{size:13}),label:l(Xt?"android.splitClose":"android.splitOpen"),active:Xt,disabled:!Xt&&!Fr,onSelect:()=>{ft(),Er(!1)}}),s.jsx(jh,{icon:d==="window"?s.jsx(MT,{size:13}):s.jsx(IT,{size:13}),label:l(d==="window"?"android.exitFullscreen":"android.fullscreen"),active:d==="window",onSelect:()=>{p(d==="window"?"off":"window"),Er(!1)}}),!t&&s.jsx(jh,{icon:d==="sidebar"?s.jsx(zT,{size:13}):s.jsx(VT,{size:13}),label:l(d==="sidebar"?"android.exitFullscreen":"android.fillSidebar"),active:d==="sidebar",onSelect:()=>{p(d==="sidebar"?"off":"sidebar"),Er(!1)}}),Ae&&s.jsxs("div",{className:"mt-1 border-t border-border px-3 py-2 text-[10px] leading-4 tabular-nums text-muted-foreground",children:[s.jsx("div",{className:"truncate",children:`${et.fps} fps · ${et.kbps} kbps`}),s.jsx("div",{className:"truncate",children:`${et.width}×${et.height}`})]})]}),document.body),(ke==="custom"||oe)&&s.jsxs("div",{className:"border-b border-border bg-surface-2/40 px-2 py-2 text-[11px]",children:[s.jsxs("button",{type:"button",onClick:()=>Ze(N=>!N),"aria-expanded":ue,className:"flex w-full items-center gap-1 rounded text-muted-foreground hover:text-foreground",children:[s.jsx(ul,{size:12,className:`transition-transform ${ue?"":"-rotate-90"}`}),s.jsxs("span",{children:[l("android.quality"),oe?` · ${Pe.find(N=>N.id===oe)?.name??""}`:""]})]}),ue&&s.jsxs("div",{className:"mt-2 grid gap-2",children:[s.jsx(ry,{label:l("android.qualityResolution"),display:`${at.maxSize}px`,min:360,max:2160,step:8,value:at.maxSize,onChange:N=>Ie(U=>({...U,maxSize:N}))}),s.jsx(ry,{label:l("android.qualityBitRate"),display:`${(at.bitRate/1e6).toFixed(1)} Mbps`,min:.5,max:20,step:.5,value:at.bitRate/1e6,onChange:N=>Ie(U=>({...U,bitRate:Math.round(N*1e6)}))}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"w-14 shrink-0 text-muted-foreground",children:l("android.qualityFrameRate")}),s.jsxs("div",{className:"flex gap-1",children:[[15,30,60].map(N=>s.jsx("button",{type:"button",onClick:()=>Ie(U=>({...U,maxFps:N})),className:`rounded px-2 py-0.5 ${at.maxFps===N?"bg-surface-elevated text-primary":"text-muted-foreground hover:bg-surface-2"}`,children:N},N)),s.jsx("button",{type:"button",onClick:()=>Ie(N=>({...N,maxFps:0})),className:`rounded px-2 py-0.5 ${at.maxFps===0?"bg-surface-elevated text-primary":"text-muted-foreground hover:bg-surface-2"}`,children:l("android.qualityAuto")})]}),s.jsx("button",{type:"button",onClick:xn,disabled:!ne,className:"ml-auto rounded bg-primary/15 px-2 py-1 text-primary disabled:opacity-40",children:l("android.qualityApply")})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{value:nt,onChange:N=>gt(N.target.value),onKeyDown:N=>{N.key==="Enter"&&!N.nativeEvent.isComposing&&X()},placeholder:l("android.presetNamePlaceholder"),maxLength:40,className:"min-w-0 flex-1 rounded bg-surface-2 px-2 py-1 text-[11px] outline-none placeholder:text-muted-foreground"}),s.jsx("button",{type:"button",onClick:X,disabled:!nt.trim(),className:"shrink-0 rounded bg-surface-2 px-2 py-1 text-primary disabled:opacity-40",children:l("android.presetSave")}),oe&&s.jsx("button",{type:"button",onClick:He,className:"shrink-0 rounded px-2 py-1 text-destructive hover:bg-surface-2",children:l("android.presetDelete")})]})]})]}),Ke&&s.jsxs("div",{className:"flex items-center gap-1.5 border-b border-border px-2 py-2",children:[s.jsx("input",{value:$t,onChange:N=>yt(N.target.value),onKeyDown:N=>{N.key==="Enter"&&gn()},placeholder:l("android.addressPlaceholder"),className:"min-w-0 flex-1 rounded bg-surface-2 px-2 py-1 text-[11px] outline-none placeholder:text-muted-foreground"}),s.jsx("button",{type:"button",onClick:()=>{gn()},disabled:xt,className:"rounded bg-surface-2 px-2 py-1 text-[11px] text-primary disabled:opacity-40",children:xt?s.jsx(_n,{size:12,className:"animate-spin"}):l("android.connect")})]}),Mr&&s.jsxs("div",{className:"flex items-start gap-2 border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-destructive",children:[s.jsx("span",{className:"min-w-0 flex-1",children:l("android.adbUnavailable")}),s.jsx(ey,{label:l("android.insertFixPrompt"),onClick:()=>pr(ty("adb",we??"")),enabled:!!r})]}),!Mr&&jn&&s.jsxs("div",{className:"flex items-start gap-2 border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-warning",children:[s.jsx("span",{className:"min-w-0 flex-1",children:l("android.scrcpyUnavailable")}),s.jsx(ey,{label:l("android.insertFixPrompt"),onClick:()=>pr(ty("scrcpy","")),enabled:!!r})]}),ps&&ps.state!=="device"&&s.jsx("div",{className:"border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-warning",children:t$(ps,l)}),we&&!Mr&&s.jsx("div",{className:"border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-destructive",children:Fb(we)}),Gt&&s.jsxs("details",{className:"border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-warning",children:[s.jsxs("summary",{className:"cursor-pointer",children:[l("android.qualityAutoUnavailable")," ",l(Gt.startsWith("SCRCPY_VERSION")?"android.qualityAutoVersionError":Gt.startsWith("SCRCPY_BUILD")?"android.qualityAutoBuildError":/EXTENSION|SERVER_READ|PUSH/.test(Gt.split(":")[0])?"android.qualityAutoExtensionError":/TIMEOUT/.test(Gt.split(":")[0])?"android.qualityAutoTimeoutError":/ENCODER_REJECTED/.test(Gt.split(":")[0])?"android.qualityAutoEncoderError":/CHANNEL|TUNNEL|LISTEN|PROTOCOL|CONNECTION/.test(Gt.split(":")[0])?"android.qualityAutoChannelError":"android.qualityAutoUnknownError")]}),s.jsx("pre",{className:"mt-1 select-text whitespace-pre-wrap break-all text-[10px]",children:Gt})]}),wt&&s.jsx("div",{className:"border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-warning",children:wt}),me&&s.jsx("div",{role:"alert",className:"border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-destructive",children:me}),s.jsxs("div",{className:"relative flex min-h-0 min-w-0 flex-1 touch-none items-center justify-center overflow-hidden bg-[var(--chrome-bg)] p-1",children:[s.jsx("canvas",{ref:m,className:"max-h-full max-w-full touch-none select-none rounded",style:{display:Wr||Ae?"block":"none",transformOrigin:"center",transition:"none"},onPointerDown:_r,onPointerMove:Or,onPointerUp:Gn,onPointerCancel:()=>Tr(),onLostPointerCapture:N=>{z.current.has(N.pointerId)&&Tr()},onPointerLeave:N=>{z.current.has(N.pointerId)&&!N.currentTarget.hasPointerCapture?.(N.pointerId)&&Tr()},onContextMenu:N=>N.preventDefault()}),xe&&s.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute h-3.5 w-3.5 -translate-x-1/2 -translate-y-1/2 rounded-full border border-primary/80 bg-primary/35",style:{left:xe.left,top:xe.top}}),ht.length>1&&s.jsx("svg",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0 h-full w-full",style:{opacity:ut?1:0,transition:"opacity 160ms linear"},children:ht.slice(1).map((N,U)=>{const K=ht[U],fe=(U+1)/(ht.length-1);return s.jsx("line",{x1:K.x,y1:K.y,x2:N.x,y2:N.y,stroke:"var(--primary)",strokeWidth:1+1.6*fe,strokeLinecap:"round",opacity:.06+.45*fe},U)})}),Ot.map(N=>s.jsx("span",{"aria-hidden":"true",className:"termdock-tap-fade pointer-events-none absolute h-4 w-4 rounded-full bg-primary",style:{left:N.left,top:N.top}},N.id)),!Wr&&s.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-2 text-center text-[11px] text-muted-foreground",children:[Ge==="connecting"&&s.jsxs(s.Fragment,{children:[s.jsx(_n,{size:18,className:"animate-spin"}),s.jsx("span",{children:l("android.connecting")})]}),Ge==="error"&&s.jsxs(s.Fragment,{children:[s.jsx(Hu,{size:14,className:"text-destructive"}),s.jsx("span",{className:"max-w-[80%] text-destructive",children:Vt?l("android.reconnecting"):Fb(H||"")}),ne&&s.jsx("button",{type:"button",onClick:()=>{Y.current=0,ln(ne)},className:"rounded bg-surface-2 px-2 py-1 text-foreground",children:l("android.retry")})]}),Ge==="idle"&&!Mr&&!jn&&s.jsxs(s.Fragment,{children:[s.jsx(DT,{size:22,className:"opacity-60"}),s.jsx("span",{children:Hr.length?l("android.idleHint"):l("android.noDevicesHint")})]})]})]}),s.jsxs("div",{className:`flex flex-wrap items-center gap-1 border-t border-border ${tn?"px-1.5 py-0.5":"px-2 py-1.5"}`,children:[s.jsx(Bo,{compact:tn,label:l("android.back"),onClick:()=>x.current?.back(),disabled:!Wr,children:s.jsx(Iy,{size:14})}),s.jsx(Bo,{compact:tn,label:l("android.home"),onClick:()=>x.current?.home(),disabled:!Wr,children:s.jsx(AT,{size:14})}),s.jsx(Bo,{compact:tn,label:l("android.recents"),onClick:()=>x.current?.recents(),disabled:!Wr,children:s.jsx(Oy,{size:14})}),s.jsx(Bo,{compact:tn,label:l("android.notifications"),onClick:()=>x.current?.expandNotifications(),disabled:!Wr,children:s.jsx(Dy,{size:14})}),s.jsx(Bo,{compact:tn,label:l("android.rotate"),onClick:()=>x.current?.rotate(),disabled:!Wr,children:s.jsx(fS,{size:14})}),s.jsx(Bo,{compact:tn,label:l("android.volumeDown"),onClick:()=>x.current?.volumeDown(),disabled:!Wr,children:s.jsx(QS,{size:14})}),s.jsx(Bo,{compact:tn,label:l("android.volumeUp"),onClick:()=>x.current?.volumeUp(),disabled:!Wr,children:s.jsx(OS,{size:14})}),s.jsx(Bo,{compact:tn,label:l("android.power"),onClick:()=>x.current?.power(),disabled:!Wr,children:s.jsx(cS,{size:14})}),s.jsx(Bo,{compact:tn,label:l("android.inputText"),active:Ct,onClick:()=>fr(N=>!N),disabled:!Wr,children:s.jsx(Py,{size:14})}),s.jsx(Bo,{compact:tn,label:l("android.zoomIn"),onClick:()=>Lr("in"),disabled:!Wr||V>=nf-.01,children:s.jsx(zs,{size:14})}),s.jsx(Bo,{compact:tn,label:l("android.zoomOut"),onClick:()=>Lr("out"),disabled:!Wr||V<=_l+.01,children:s.jsx(Fy,{size:14})}),s.jsxs("div",{className:"relative ml-auto h-5 w-24 min-w-0 max-w-full shrink-0","data-mirror-capture-status":!0,children:[s.jsx("span",{"aria-hidden":ot||!!pn||mn,className:`block truncate text-right text-[10px] leading-5 tabular-nums text-muted-foreground ${ot||pn||mn?"invisible":""}`,children:Ae?s.jsx(s.Fragment,{children:s.jsx("span",{ref:pe})}):""}),s.jsx("div",{className:"absolute inset-0 flex items-center justify-end overflow-hidden",children:s.jsx(JF,{recording:ot,elapsed:ir,status:mn?l("android.captureInserting"):pn,stopLabel:l("android.recordingStop"),onStop:()=>{kn("manual")}})})]})]}),Ct&&s.jsxs("div",{className:"flex items-center gap-1.5 border-t border-border px-2 py-1.5",children:[s.jsx("input",{value:Yt,onChange:N=>Sr(N.target.value),onKeyDown:N=>{N.key==="Enter"&&!N.nativeEvent.isComposing&&(N.preventDefault(),Jn())},placeholder:l("android.inputPlaceholder"),className:"min-w-0 flex-1 rounded bg-surface-2 px-2 py-1 text-[11px] outline-none placeholder:text-muted-foreground",autoFocus:!0}),s.jsx("button",{type:"button",onClick:Jn,disabled:!Yt,className:"rounded bg-surface-2 p-1.5 text-primary disabled:opacity-40",title:l("android.send"),children:s.jsx(i0,{size:13})})]})]});return d==="window"?Xs.createPortal(s.jsx("div",{className:"fixed inset-0 z-modal-panel flex flex-col bg-[var(--chrome-bg)]",style:{paddingTop:"var(--safe-top-inset, env(safe-area-inset-top, 0px))",paddingBottom:"var(--safe-bottom-inset, env(safe-area-inset-bottom, 0px))"},children:W}),document.body):t?Xt&&Zr?Xs.createPortal(W,Zr):null:Xt&&Zr?s.jsxs(s.Fragment,{children:[Xs.createPortal(W,Zr),s.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 p-4 text-center text-[11px] text-muted-foreground",children:[s.jsx(Il,{size:18,className:"opacity-60"}),s.jsx("span",{children:l("android.splitDockedHint")}),s.jsx("button",{type:"button",onClick:()=>{Jt(Gd,null),Qr({docked:null})},className:"rounded bg-surface-2 px-2 py-1 text-foreground",children:l("android.splitClose")})]})]}):W}function jh({icon:e,label:t,active:r=!1,disabled:n=!1,onSelect:a}){return s.jsxs("button",{type:"button",role:"menuitem",disabled:n,onClick:a,className:`flex w-full items-center gap-2 px-2.5 py-1.5 text-left transition hover:bg-surface-2 disabled:opacity-40 disabled:hover:bg-transparent ${r?"text-primary":"text-foreground"}`,children:[s.jsx("span",{"aria-hidden":"true",className:"shrink-0",children:e}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:t}),r&&s.jsx(pi,{size:12,className:"shrink-0"})]})}function JF({recording:e,elapsed:t,status:r,stopLabel:n,onStop:a}){return e?s.jsxs("span",{role:"status","aria-live":"polite",className:"ml-auto inline-flex shrink-0 items-center gap-1 whitespace-nowrap rounded bg-destructive/15 px-1.5 py-0.5 text-[10px] tabular-nums text-destructive",children:[s.jsx("span",{"aria-hidden":"true",className:"h-1.5 w-1.5 shrink-0 animate-pulse rounded-full bg-destructive"}),Vb(t),s.jsx("button",{type:"button",onClick:a,title:n,"aria-label":`${n} · ${Vb(t)}`,className:"ml-0.5 inline-flex h-4 w-4 items-center justify-center rounded hover:bg-destructive/25",children:s.jsx(zy,{size:8,fill:"currentColor"})})]}):r?s.jsx("span",{role:"status","aria-live":"polite",title:r,className:"ml-auto truncate text-[10px] text-primary",children:r}):null}function Jb({sessionId:e}){const t=Kn(x=>x.docks[r0]),r=!!t,n=t?.sessionId??e??null,c=Mm(x=>x.pending)[0],l=b.useCallback(async x=>{if(!n)throw new Error("没有可接收截图的终端");const w=(await N0("/tmp",[x])).files[0]?.path;if(!w)throw new Error("截图上传未返回文件路径");await Yb(w,n)},[n]),d=b.useCallback(x=>{Mm.getState().enqueue(x,n)},[n]),p=Kn(x=>!!x.hosts[r0]),m=b.useRef(!1);return b.useEffect(()=>{m.current||(m.current=!0,fc().then(x=>{const y=x.androidPanel?.docked;y&&(Kn.getState().docks[r0]||Kn.getState().setDock(r0,y))}).catch(()=>{}))},[]),s.jsxs(s.Fragment,{children:[r&&p&&s.jsx(XF,{sessionId:n,dockOnly:!0,onInsertFile:n?l:void 0,onInsertPrompt:n?x=>e4(x,n):void 0,onRecordingComplete:d}),c&&s.jsx(GF,{file:c.file,initialPath:c.initialPath,onInsert:x=>c.insert?c.insert(x):Yb(x,c.sessionId),onDone:()=>Mm.getState().remove(c.file.id)},c.file.id)]})}function ey({label:e,onClick:t,enabled:r}){return r?s.jsx("button",{type:"button",onClick:t,className:"shrink-0 rounded bg-surface px-1.5 py-0.5 text-[10px] text-foreground hover:bg-surface-elevated",children:e}):null}function ty(e,t){return[`Termdock 的“设备投屏”在当前服务端不可用:未找到 ${e==="adb"?"adb(Android platform-tools)":"scrcpy / scrcpy-server"}${t?`(错误:${t})`:""}。`,"请在本机安装并让 Termdock 恢复可用:","1) 安装依赖:"," - macOS: brew install android-platform-tools scrcpy"," - Ubuntu/Debian: sudo apt install adb scrcpy"," - Windows: winget install Google.PlatformTools && winget install Genymobile.scrcpy","2) 若不在 PATH,请在 ~/.termdock/.env 指定 TERMDOCK_ADB_BIN / TERMDOCK_SCRCPY_BIN / TERMDOCK_SCRCPY_SERVER。","3) 完成后重启 Termdock 服务,并用 adb version、scrcpy --version 验证。","边界:只做本机环境安装与配置,不要改动 Termdock 仓库代码。"].join(`
|
|
163
163
|
`)}function ry({label:e,display:t,min:r,max:n,step:a,value:c,onChange:l}){return s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"w-14 shrink-0 text-muted-foreground",children:e}),s.jsx("input",{type:"range",min:r,max:n,step:a,value:c,onChange:d=>l(Number(d.target.value)),className:"h-1 min-w-0 flex-1 accent-primary","aria-label":e}),s.jsx("span",{className:"w-16 shrink-0 text-right tabular-nums text-muted-foreground",children:t})]})}function Bo({label:e,onClick:t,disabled:r,active:n,compact:a,children:c}){return s.jsx("button",{type:"button",onClick:t,disabled:r,title:e,"aria-label":e,className:`${a?"inline-flex h-5 w-5 items-center justify-center":"p-1.5"} rounded transition active:scale-95 disabled:opacity-30 ${n?"bg-surface-elevated text-primary":"text-muted-foreground hover:bg-surface-2"}`,children:c})}function ny(e,t,r){const n=e.parentElement;if(!n)return null;const a=e.getBoundingClientRect(),c=n.getBoundingClientRect();return{left:a.left-c.left+(t-a.left),top:a.top-c.top+(r-a.top)}}function Dh(e,t,r){const n=e.getBoundingClientRect(),a=e.width||n.width,c=e.height||n.height,l=n.width?(t-n.left)/n.width*a:0,d=n.height?(r-n.top)/n.height*c:0;return{x:Math.max(0,Math.min(a,l)),y:Math.max(0,Math.min(c,d))}}function e$(e){return!(/ADB_NOT_FOUND|SCRCPY_NOT_FOUND|SCRCPY_SERVER_NOT_FOUND|SCRCPY_VERSION_UNKNOWN|SCRCPY_UNSUPPORTED_CODEC|VIDEO_DECODER_UNSUPPORTED|decoder|decode/i.test(e)||/INVALID_SERIAL|INVALID_ADDRESS|API_NOT_ALLOWED|AUTHORIZATION_DENIED/i.test(e))}function sy(e,t){return e.state==="device"?e.androidVersion?` · Android ${e.androidVersion}`:"":e.state==="unauthorized"?` · ${t("android.stateUnauthorized")}`:e.state==="offline"?` · ${t("android.stateOffline")}`:` · ${t("android.stateUnknown")}`}function t$(e,t){return e.state==="unauthorized"?t("android.unauthorizedHint"):e.state==="offline"?t("android.offlineHint"):t("android.stateUnknown")}function r$(e){return e>=90?"var(--destructive)":e>=70?"var(--warning)":"var(--success)"}function n$(e){return e>=90?"var(--destructive)/0.15":e>=70?"var(--warning)/0.15":"var(--success)/0.12"}function s$(e){if(!e)return"";const t=new Date(e),r=Date.now(),n=t.getTime()-r;if(n<=0)return"";const a=Math.floor(n/6e4),c=Math.floor(a/60),l=Math.floor(c/24),d=c%24,p=a%60,m=t.toLocaleDateString(void 0,{month:"short",day:"numeric"}),x=t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"});let y;return l>0?y=`${l}d ${d}h`:d>0?y=`${d}h ${p}m`:p>0?y=`${p}m`:y="soon",`resets in ${y} (${m} ${x})`}function i$(e){return{claude:"🧠",codex:"✨",kimi:"🌙",copilot:"🐙",grok:"🚀",gemini:"💎"}[e]||"📊"}function a$({result:e}){const{t}=Ur(),r=e.windows.filter(d=>d.percent===0&&!d.resetAt),n=e.windows.filter(d=>d.percent>0||d.resetAt),a=r.length>0?r.map(d=>d.label).join(" · "):"",c=!!e.error;let l=null;return!c&&e.entitlement&&(e.usagePercent>=90?l=t("quota.exhausted"):e.remaining!==void 0&&e.remaining<e.entitlement?l=t("quota.left",{n:e.remaining}):l=`${Math.round(e.usagePercent)}%`),s.jsxs("div",{className:"rounded-xl border border-border/15 bg-surface-2 p-3 sm:p-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 text-[13px] font-semibold text-foreground",children:[s.jsx("span",{className:"shrink-0",children:i$(e.slug)}),s.jsx("span",{className:"truncate",children:e.displayName}),a&&s.jsx("span",{className:"shrink-0 rounded-full bg-surface-elevated px-2 py-0.5 text-[10px] font-normal text-muted-foreground",children:a})]}),l&&s.jsx("span",{className:"shrink-0 text-[11px] tabular-nums text-muted-foreground",children:l})]}),n.length>0?s.jsx("div",{className:"mt-2.5 space-y-2",children:n.map(d=>{const p=Math.max(0,Math.min(100,d.percent));return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 text-[12px]",children:[s.jsx("span",{className:"w-14 shrink-0 truncate text-muted-foreground sm:w-16",children:d.label}),s.jsx("div",{className:"flex-1",children:s.jsx("div",{className:"h-2 rounded-full",style:{background:n$(d.percent)},children:s.jsx("div",{className:"h-full rounded-full transition-all duration-500",style:{width:`${p}%`,background:r$(d.percent)}})})}),s.jsxs("span",{className:"w-9 shrink-0 text-right tabular-nums font-medium text-foreground",children:[Math.round(d.percent),"%"]})]}),d.resetAt&&s.jsx("p",{className:"mt-1 pl-14 text-[10px] text-muted-foreground sm:pl-16",children:s$(d.resetAt)})]},d.label)})}):c?s.jsx("p",{className:"mt-2 text-[11px] text-muted-foreground",children:e.error}):null]})}function o$({isOpen:e,onClose:t}){const{t:r}=Ur(),[n,a]=b.useState([]),[c,l]=b.useState(!1),d=async(x=!1)=>{l(!0);try{const y=x?await p9():await m9();a(y.providers||[])}catch{}finally{l(!1)}};if(b.useEffect(()=>{e&&d()},[e]),b.useEffect(()=>{if(!e)return;const x=y=>{const w=y.detail;Array.isArray(w)&&a(w)};return window.addEventListener("termdock:quota-update",x),()=>{window.removeEventListener("termdock:quota-update",x)}},[e]),!e)return null;const p=n.filter(x=>!x.error),m=p.length>0?new Date(Math.max(...p.map(x=>x.fetchedAt||0))):null;return s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"fixed inset-0 z-modal-backdrop bg-[var(--app-backdrop)] backdrop-blur-sm cursor-default",onClick:t}),s.jsxs("div",{className:"fixed inset-x-3 z-modal-panel mx-auto flex max-w-lg flex-col overflow-hidden rounded-2xl bg-surface border border-border/15 shadow-[0_28px_70px_var(--app-shadow-strong),0_14px_32px_var(--app-shadow-soft)]",style:{top:"max(1.5rem, env(safe-area-inset-top, 0px))",bottom:"max(1.5rem, env(safe-area-inset-bottom, 0px))"},children:[s.jsxs("div",{className:"flex shrink-0 items-center justify-between border-b border-border/15 px-3 py-2.5 sm:px-6 sm:py-3",children:[s.jsx("h2",{className:"text-[14px] font-semibold text-foreground sm:text-base",children:r("quota.title")}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("button",{type:"button",onClick:()=>d(!0),disabled:c,className:"shrink-0 rounded-full bg-surface-2 p-2 text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground disabled:opacity-50","aria-label":r("quota.refresh"),children:s.jsx(bn,{size:15,className:c?"animate-spin":""})}),s.jsx("button",{type:"button",onClick:t,className:"shrink-0 rounded-full bg-surface-2 p-2 text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground","aria-label":r("quota.close"),children:s.jsx(In,{size:17})})]})]}),s.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto p-3 sm:p-5",children:[c&&p.length===0?s.jsx(p0,{label:r("common.loading"),className:"py-12"}):p.length===0?s.jsxs("div",{className:"py-8 text-center text-[13px] text-muted-foreground",children:[s.jsx("p",{children:r("quota.noProviders")}),s.jsx("p",{className:"mt-1.5 text-[11px]",children:r("quota.noProvidersHint")})]}):s.jsx("div",{className:"space-y-2.5",children:p.map(x=>s.jsx(a$,{result:x},x.slug))}),m&&s.jsx("p",{className:"mt-3 text-center text-[10px] text-muted-foreground",children:r("quota.updated",{time:m.toLocaleTimeString()})})]})]})]})}const iy=[{label:"Esc",sequence:"\\u001b"},{label:"Tab",sequence:"\\t"},{label:"Enter",sequence:"\\r"},{label:"S-Tab",sequence:"\\u001b[Z"},{label:"C-c",sequence:"\\u0003"},{label:"C-d",sequence:"\\u0004"},{label:"C-l",sequence:"\\u000c"},{label:"C-r",sequence:"\\u0012"},{label:"C-z",sequence:"\\u001a"},{label:"C-w",sequence:"\\u0017"},{label:"Up",sequence:"\\u001b[A"},{label:"Down",sequence:"\\u001b[B"},{label:"Left",sequence:"\\u001b[D"},{label:"Right",sequence:"\\u001b[C"},{label:"PgUp",sequence:"\\u001b[5~"},{label:"PgDn",sequence:"\\u001b[6~"}],l$=2,c$=20;function u$({label:e}){return s.jsx("div",{className:"h-7 rounded-full bg-surface-2 px-3 text-[11px] leading-7 text-center text-muted-foreground truncate",children:e})}function d$({value:e,onChange:t,placeholder:r}){const{t:n}=Ur(),[a,c]=k.useState(""),l=y=>{const w=[];let v="",S=!1;const L=()=>{const R=v.trim();R&&w.push(R),v=""};for(let R=0;R<y.length;R+=1){const B=y[R];if(!S&&B==="/"&&v.trim().length===0){S=!0,v+=B;continue}if(S){if(v+=B,B==="/"&&y[R-1]!=="\\"&&v.length>1){for(;R+1<y.length&&/[gimsuy]/.test(y[R+1]??"");)R+=1,v+=y[R];L(),S=!1}continue}if(B===","||/\s/.test(B)){L();continue}v+=B}if(L(),w.length===0)return;const E=[...e];for(const R of w){const B=X3(R);B&&(E.includes(B)||E.push(B))}t(E),c("")},d=y=>{t(e.filter(w=>w!==y))},p=a.trim(),m=p.length>0&&j2(p),x=m&&!yf(p);return s.jsx("div",{className:"rounded-2xl bg-surface px-3 py-2 ring-1 ring-border/15 focus-within:ring-accent/40",children:s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.map(y=>{const w=j2(y),v=w&&!yf(y);return s.jsxs("span",{className:`inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-[11px] ${v?"bg-destructive/15 text-destructive":w?"bg-accent/15 font-mono text-accent":"bg-surface-elevated text-foreground"}`,title:w?v?n("settings.invalidRegex"):"Regex match":"Substring match (case-insensitive)",children:[w&&s.jsx("span",{className:"text-[10px] opacity-70",children:"re"}),y,s.jsx("button",{type:"button",onClick:()=>d(y),className:"rounded-full p-0.5 text-muted-foreground hover:bg-destructive/20 hover:text-destructive","aria-label":n("toolbarPresets.removeAction",{name:y}),children:s.jsx(In,{size:12})})]},y)}),s.jsx("input",{type:"text",value:a,onChange:y=>c(y.target.value),onKeyDown:y=>{y.key==="Enter"||y.key===","&&!m?(y.preventDefault(),l(a)):y.key==="Backspace"&&a.length===0&&e.length>0&&d(e[e.length-1])},onBlur:()=>l(a),placeholder:e.length===0?r:"",className:`min-w-[8ch] flex-1 bg-transparent py-1 text-sm outline-none placeholder:text-muted/60 ${m?"font-mono":""} ${x?"text-destructive":""}`,autoCapitalize:"off",autoCorrect:"off",autoComplete:"off"})]})})}function h$({value:e,min:t,max:r,onChange:n}){const{t:a}=Ur();return s.jsxs("div",{className:"inline-flex items-center gap-1 rounded-full bg-surface px-1 py-1 ring-1 ring-border/15",children:[s.jsx("button",{type:"button",onClick:()=>n(Math.max(t,e-1)),disabled:e<=t,className:"h-7 w-7 rounded-full bg-surface-2 text-muted-foreground transition hover:bg-surface-elevated disabled:opacity-40 inline-flex items-center justify-center","aria-label":a("common.decrease"),children:s.jsx(Fy,{size:14})}),s.jsx("span",{className:"w-6 text-center text-sm font-medium tabular-nums text-foreground",children:e}),s.jsx("button",{type:"button",onClick:()=>n(Math.min(r,e+1)),disabled:e>=r,className:"h-7 w-7 rounded-full bg-surface-2 text-muted-foreground transition hover:bg-surface-elevated disabled:opacity-40 inline-flex items-center justify-center","aria-label":a("common.increase"),children:s.jsx(zs,{size:14})})]})}const f$=({presets:e,selectedPresetId:t,onSelectPreset:r,onUpdatePreset:n,onAddPreset:a,onRemovePreset:c,onResetDefaults:l})=>{const{t:d}=Ur(),p=e.find(R=>R.id===t)??e[0]??null,[m,x]=k.useState(null);if(!p)return null;const y=p.actions.length>0,w=[{id:"preview-auto",label:p.label,kind:"preset"},...p.includeAlt?[{id:"preview-alt",label:"Alt"}]:[],...y?p.actions.map((R,B)=>({id:R.id,label:o1(R,B)})):["Enter","Home","End","Ctrl-C","Ctrl-D"].map(R=>({id:R,label:R}))],v=J3(w,p.rowLayout),S=(R,B)=>{n(p.id,z=>{const O=z.actions.findIndex(Z=>Z.id===R);if(O===-1)return z;const $=O+B;if($<0||$>=z.actions.length)return z;const V=[...z.actions];return[V[O],V[$]]=[V[$],V[O]],{...z,actions:V}})},L=p.rowLayout.reduce((R,B)=>R+B,0),E=1+(p.includeAlt?1:0);return s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"sticky top-[-1rem] sm:top-[-1.5rem] z-10 -mx-4 -mt-4 sm:-mx-6 sm:-mt-6 border-b border-border/15 bg-surface/95 backdrop-blur px-4 py-3 sm:px-6",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[s.jsx("span",{className:"ui-kicker",children:d("toolbarPresets.preview")}),s.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[p.actions.length," button",p.actions.length===1?"":"s"," · ",L," slot",L===1?"":"s"]})]}),s.jsx("div",{className:"space-y-1 rounded-2xl bg-surface-2/60 p-2",children:v.map((R,B)=>{const z=R.items[0]?.kind==="preset",O=Math.max(2,R.columns),$=z?`${ev}px repeat(${Math.max(1,O-1)}, minmax(0, 1fr))`:`repeat(${O}, minmax(0, 1fr))`;return s.jsx("div",{className:"grid gap-1",style:{gridTemplateColumns:$},children:R.items.map(V=>V.kind==="preset"?s.jsx(tv,{mode:"auto",presetLabel:V.label,title:`Auto preset · ${V.label}`,disabled:!0},V.id):s.jsx(u$,{label:V.label},V.id))},`preview-row-${B}`)})}),p.actions.length>L-E&&s.jsx("p",{className:"mt-1.5 text-[10px] text-muted-foreground",children:d("toolbarPresets.overCapacityHint")})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"ui-kicker",children:d("toolbarPresets.presets")}),s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsxs("button",{type:"button",onClick:a,className:"inline-flex items-center gap-1 rounded-full bg-surface-2 px-3 py-2 text-xs font-medium hover:bg-surface-elevated transition",children:[s.jsx(zs,{size:14}),d("toolbarPresets.new")]}),s.jsxs("button",{type:"button",onClick:l,className:"inline-flex items-center gap-1 rounded-full bg-surface-2 px-3 py-2 text-xs font-medium hover:bg-surface-elevated transition",children:[s.jsx(bn,{size:14}),d("toolbarPresets.reset")]})]})]}),s.jsx("div",{className:"-mx-1 flex flex-wrap gap-1.5 px-1",children:e.map(R=>s.jsxs("button",{type:"button",onClick:()=>r(R.id),className:`rounded-full px-3 py-2 text-xs font-medium transition ${R.id===p.id?"bg-primary/20 text-primary ring-1 ring-primary/30":"bg-surface-2 text-muted-foreground hover:bg-surface-elevated"}`,children:[R.label,R.actions.length>0&&s.jsx("span",{className:"ml-1.5 text-[10px] text-muted-foreground",children:R.actions.length})]},R.id))})]}),s.jsxs("div",{className:"space-y-4 rounded-2xl bg-surface p-4 ring-1 ring-border/10",children:[s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("span",{className:"ui-kicker",children:d("toolbarPresets.label")}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:p.label,onChange:R=>n(p.id,B=>({...B,label:R.target.value})),className:"flex-1 rounded-full bg-surface-2 px-4 py-2.5 text-sm placeholder:text-muted/60 outline-none ring-1 ring-transparent focus:ring-accent/40",placeholder:d("toolbarPresets.presetLabelPlaceholder"),autoCapitalize:"off",autoCorrect:"off"}),p.id!=="default"&&s.jsx("button",{type:"button",onClick:()=>c(p.id),className:"shrink-0 rounded-full bg-surface-2 px-3 py-2.5 text-destructive hover:bg-destructive/15","aria-label":d("toolbarPresets.deletePreset",{name:p.label}),children:s.jsx(Rs,{size:14})})]})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"ui-kicker",children:d("toolbarPresets.matchPrograms")}),s.jsx("span",{className:"text-[10px] text-muted-foreground",children:d("toolbarPresets.typeEnterHint")})]}),s.jsx(d$,{value:p.programs,onChange:R=>n(p.id,B=>({...B,programs:R})),placeholder:d("toolbarPresets.programsPlaceholder")}),s.jsx("p",{className:"text-[10px] text-muted-foreground",children:d("toolbarPresets.programsHelp")})]}),s.jsxs("button",{type:"button",onClick:()=>n(p.id,R=>({...R,includeAlt:!R.includeAlt})),className:"flex w-full items-center justify-between rounded-2xl bg-surface-2 px-4 py-3 text-sm transition hover:bg-surface-elevated",children:[s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-foreground",children:d("toolbarPresets.altSlot")}),s.jsx("span",{className:"block text-[11px] text-muted-foreground",children:d("toolbarPresets.altSlotHint")})]}),s.jsx(ll,{checked:p.includeAlt})]}),s.jsxs("button",{type:"button",onClick:()=>n(p.id,R=>({...R,showOnDesktop:!R.showOnDesktop})),className:"flex w-full items-center justify-between rounded-2xl bg-surface-2 px-4 py-3 text-sm transition hover:bg-surface-elevated",children:[s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-foreground",children:d("toolbarPresets.desktopVisibility")}),s.jsx("span",{className:"block text-[11px] text-muted-foreground",children:d("toolbarPresets.desktopVisibilityHint")})]}),s.jsx(ll,{checked:p.showOnDesktop===!0})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("span",{className:"ui-kicker",children:d("toolbarPresets.rowLayout")}),s.jsx("p",{className:"text-[11px] text-muted-foreground",children:d("toolbarPresets.rowLayoutHint")})]}),s.jsxs("button",{type:"button",onClick:()=>n(p.id,R=>({...R,rowLayout:[...J1(R.rowLayout),3]})),className:"inline-flex items-center gap-1 rounded-full bg-surface-2 px-3 py-1.5 text-xs font-medium hover:bg-surface-elevated",children:[s.jsx(zs,{size:12}),d("toolbarPresets.addRow")]})]}),s.jsx("div",{className:"space-y-2",children:p.rowLayout.map((R,B)=>s.jsxs("div",{className:"flex items-center gap-3 rounded-2xl bg-surface-2 px-3 py-2",children:[s.jsx("span",{className:"w-12 shrink-0 text-xs text-muted-foreground",children:d("toolbarPresets.rowN",{n:B+1})}),s.jsx("div",{className:"flex-1"}),s.jsx(h$,{value:R,min:l$,max:c$,onChange:z=>n(p.id,O=>({...O,rowLayout:O.rowLayout.map(($,V)=>V===B?z:$)}))}),p.rowLayout.length>1&&s.jsx("button",{type:"button",onClick:()=>n(p.id,z=>({...z,rowLayout:z.rowLayout.filter((O,$)=>$!==B)})),className:"rounded-full bg-surface px-2.5 py-1 text-[11px] text-muted-foreground hover:bg-destructive/15 hover:text-destructive","aria-label":d("toolbarPresets.removeRow",{n:B+1}),children:d("toolbarPresets.del")})]},`row-${B}`))})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("span",{className:"ui-kicker",children:d("toolbarPresets.buttons")}),s.jsx("p",{className:"text-[11px] text-muted-foreground",children:d("toolbarPresets.buttonsHint")})]}),s.jsxs("button",{type:"button",onClick:()=>{const R=`${p.id}-action-${Date.now()}`;n(p.id,B=>({...B,actions:[...B.actions,{id:R,label:`Key ${B.actions.length+1}`,sequence:""}]})),x(R)},className:"inline-flex items-center gap-1 rounded-full bg-primary/15 px-3 py-1.5 text-xs font-medium text-primary hover:bg-primary/25",children:[s.jsx(zs,{size:12}),d("toolbarPresets.addButton")]})]}),p.actions.length===0&&s.jsx("div",{className:"rounded-2xl bg-surface-2/60 px-4 py-6 text-center text-[11px] text-muted-foreground",children:d("toolbarPresets.noCustomButtons")}),p.actions.map((R,B)=>{const z=m===R.id;return s.jsxs("div",{className:`rounded-2xl bg-surface-2 transition ${z?"ring-1 ring-accent/40":""}`,children:[s.jsxs("div",{className:"flex items-center gap-2 px-3 py-2",children:[s.jsxs("div",{className:"flex flex-col gap-0.5",children:[s.jsx("button",{type:"button",onClick:()=>S(R.id,-1),disabled:B===0,className:"h-6 w-6 rounded-full bg-surface text-muted-foreground hover:bg-surface-elevated disabled:opacity-30 inline-flex items-center justify-center","aria-label":d("toolbarPresets.moveUp"),children:s.jsx(jy,{size:12})}),s.jsx("button",{type:"button",onClick:()=>S(R.id,1),disabled:B===p.actions.length-1,className:"h-6 w-6 rounded-full bg-surface text-muted-foreground hover:bg-surface-elevated disabled:opacity-30 inline-flex items-center justify-center","aria-label":d("toolbarPresets.moveDown"),children:s.jsx(EA,{size:12})})]}),s.jsxs("button",{type:"button",onClick:()=>x(z?null:R.id),className:"min-w-0 flex-1 text-left",children:[s.jsx("div",{className:"truncate text-sm font-medium text-foreground",children:o1(R,B)}),s.jsxs("div",{className:"truncate text-[11px] text-muted-foreground",children:[R.sequence?R.sequence:d("toolbarPresets.noSequence"),R.doubleTapSequence&&s.jsxs("span",{className:"ml-1 text-accent/70",children:["· 2× ",R.doubleTapSequence]})]})]}),s.jsx("button",{type:"button",onClick:()=>n(p.id,O=>({...O,actions:O.actions.filter($=>$.id!==R.id)})),className:"shrink-0 rounded-full bg-surface p-2 text-muted-foreground hover:bg-destructive/15 hover:text-destructive","aria-label":d("toolbarPresets.removeAction",{name:R.label}),children:s.jsx(Rs,{size:14})})]}),z&&s.jsxs("div",{className:"space-y-3 border-t border-border/10 px-3 py-3",children:[s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("span",{className:"text-[11px] uppercase tracking-wider text-muted-foreground",children:d("toolbarPresets.labelField")}),s.jsx("input",{type:"text",value:R.label,onChange:O=>n(p.id,$=>({...$,actions:$.actions.map(V=>V.id===R.id?{...V,label:O.target.value}:V)})),className:"w-full rounded-full bg-surface px-4 py-2.5 text-sm outline-none ring-1 ring-transparent focus:ring-accent/40",placeholder:d("toolbarPresets.labelPlaceholder"),autoCapitalize:"off",autoCorrect:"off"})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("span",{className:"text-[11px] uppercase tracking-wider text-muted-foreground",children:d("toolbarPresets.sequence")}),s.jsx("input",{type:"text",value:R.sequence,onChange:O=>n(p.id,$=>({...$,actions:$.actions.map(V=>V.id===R.id?{...V,sequence:O.target.value}:V)})),className:"w-full rounded-full bg-surface px-4 py-2.5 font-mono text-sm outline-none ring-1 ring-transparent focus:ring-accent/40",placeholder:d("toolbarPresets.sequencePlaceholder"),autoCapitalize:"off",autoCorrect:"off",spellCheck:!1}),s.jsx("div",{className:"flex flex-wrap gap-1.5 pt-1",children:iy.map(O=>s.jsx("button",{type:"button",onClick:()=>n(p.id,$=>({...$,actions:$.actions.map(V=>V.id===R.id?{...V,sequence:O.sequence}:V)})),className:"rounded-full bg-surface px-2.5 py-1 text-[11px] font-medium text-muted-foreground hover:bg-surface-elevated hover:text-foreground",children:O.label},O.label))})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-[11px] uppercase tracking-wider text-muted-foreground",children:d("toolbarPresets.doubleTap")}),!R.doubleTapSequence&&s.jsx("button",{type:"button",onClick:()=>n(p.id,O=>({...O,actions:O.actions.map($=>$.id===R.id?{...$,doubleTapSequence:""}:$)})),className:"text-[10px] text-accent hover:text-accent/80",children:d("toolbarPresets.doubleTapAdd")})]}),R.doubleTapSequence!==void 0&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:R.doubleTapSequence,onChange:O=>n(p.id,$=>({...$,actions:$.actions.map(V=>V.id===R.id?{...V,doubleTapSequence:O.target.value}:V)})),className:"w-full rounded-full bg-surface px-4 py-2.5 font-mono text-sm outline-none ring-1 ring-transparent focus:ring-accent/40",placeholder:d("toolbarPresets.doubleTapPlaceholder"),autoCapitalize:"off",autoCorrect:"off",spellCheck:!1}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 pt-1",children:[iy.map(O=>s.jsx("button",{type:"button",onClick:()=>n(p.id,$=>({...$,actions:$.actions.map(V=>V.id===R.id?{...V,doubleTapSequence:(V.doubleTapSequence??"")+O.sequence}:V)})),className:"rounded-full bg-surface px-2.5 py-1 text-[11px] font-medium text-muted-foreground hover:bg-surface-elevated hover:text-foreground",children:O.label},O.label)),s.jsx("button",{type:"button",onClick:()=>n(p.id,O=>({...O,actions:O.actions.map($=>{if($.id!==R.id)return $;const{doubleTapSequence:V,...Z}=$;return Z})})),className:"rounded-full bg-destructive/10 px-2.5 py-1 text-[11px] font-medium text-destructive/70 hover:bg-destructive/20 hover:text-destructive",children:d("toolbarPresets.remove")})]})]})]})]})]},R.id)})]})]})]})},p$={installed:"text-[color:var(--success)]",outdated:"text-[color:var(--warning)]","needs-approval":"text-[color:var(--warning)]","not-installed":"text-muted-foreground"};function m$(){const{t:e}=Ur(),[t,r]=k.useState(null),[n,a]=k.useState(null),[c,l]=k.useState(null),[d,p]=k.useState(null),[m,x]=k.useState(!1),[y,w]=k.useState(!1),[v,S]=k.useState(""),[L,E]=k.useState(""),[R,B]=k.useState(null),[z,O]=k.useState([]),[$,V]=k.useState([]),[Z,le]=k.useState(null),[be,pe]=k.useState(new Set),[ee,_e]=k.useState(null),[ze,Y]=k.useState("auto"),[ce,qe]=k.useState({}),[we,ye]=k.useState(null),[Le,Be]=k.useState(null),[ne,Fe]=k.useState(10),[ke,Ee]=k.useState(""),[Pe,Ne]=k.useState(""),[oe,We]=k.useState(12e3),[nt,gt]=k.useState(null),[ue,Ze]=k.useState(null),at=k.useCallback(async()=>{const[xe,Ve,ht,q]=await Promise.allSettled([g9(),x9(),fc(),fd()]);if(r(xe.status==="fulfilled"?xe.value:[]),Ve.status==="fulfilled"){const ut=Ve.value;O(ut.plugins??[]),V(ut.errors??[])}else O([]),V([]);if(ht.status==="fulfilled"){const ut=ht.value;pe(new Set(ut.autoRenameAgents??[])),Y(ut.autoRenameNamer??"auto"),qe(ut.autoRenameModels??{}),Fe(ut.autoRenameIntervalMinutes??10),Ee(ut.autoRenamePromptPreference??""),Ne(ut.autoRenamePromptPreference??""),We(ut.autoRenamePromptPayloadChars??12e3)}else pe(new Set);ye(q.status==="fulfilled"?q.value:[])},[]);k.useEffect(()=>{at()},[at]);const Ie=async(xe,Ve)=>{a(xe),l(null);try{Ve==="install"?(await b9(xe)).devMode&&p(xe):(await y9(xe),d===xe&&p(null)),await at()}catch(ht){l(ht instanceof Error?ht.message:String(ht))}finally{a(null)}},Ge=xe=>e(xe==="installed"?"settings.agentHooksInstalled":xe==="outdated"?"settings.agentHooksOutdated":xe==="needs-approval"?"settings.agentHooksNeedsApproval":"settings.agentHooksNotInstalled"),Ce=async()=>{B(null);let xe;try{xe=JSON.parse(L)}catch{B("Invalid JSON");return}try{await C9(xe),E(""),x(!1),await at()}catch(Ve){if(Ve instanceof _9&&Ve.migration){V(ht=>[{slug:typeof xe.slug=="string"?xe.slug:"manifest.json",errors:Ve.message.split(`
|
|
164
164
|
`),code:Ve.code,migration:Ve.migration},...ht.filter(q=>q.slug!==xe.slug)]);return}B(Ve instanceof Error?Ve.message:String(Ve))}},H=async()=>{const xe=v.trim();if(xe){gt("install"),B(null);try{await v9(xe),S(""),w(!1),await at()}catch(Ve){B(Ve instanceof Error?Ve.message:String(Ve))}finally{gt(null)}}},ae=async xe=>{gt(`remove:${xe}`);try{await S9(xe),Ze(Ve=>Ve?.slug===xe?null:Ve),await at()}catch(Ve){l(Ve instanceof Error?Ve.message:String(Ve))}finally{gt(null)}},Ae=async xe=>{gt(`check:${xe}`),l(null);try{await T9(xe),await at()}catch(Ve){l(Ve instanceof Error?Ve.message:String(Ve))}finally{gt(null)}},Ye=async xe=>{gt(`update:${xe}`),l(null);try{const Ve=await A9(xe),ht=[Ve.hookWarning,Ve.titleWarning].filter(Boolean).join(" ");ht&&l(ht),Ze(q=>q?.slug===xe?null:q),await at()}catch(Ve){l(Ve instanceof Error?Ve.message:String(Ve))}finally{gt(null)}},et=async xe=>{gt(`doctor:${xe}`),l(null),Ze(null);try{const Ve=await w9(xe);Ze(Ve),ye(await fd())}catch(Ve){l(Ve instanceof Error?Ve.message:String(Ve))}finally{gt(null)}},St=async xe=>{const Ve=xe.migration?.aiPrompt??xe.errors.join(`
|
|
165
165
|
`);try{await navigator.clipboard.writeText(Ve),le(xe.slug),window.setTimeout(()=>le(ht=>ht===xe.slug?null:ht),1800)}catch{B(Ve)}},Gt=async xe=>{if(ee)return;const Ve=be,ht=new Set(Ve);ht.has(xe)?ht.delete(xe):ht.add(xe),pe(ht),_e(xe),l(null);try{const q=await La({autoRenameAgents:[...ht]});pe(new Set(q.autoRenameAgents??[])),ye(await fd(!0))}catch(q){pe(Ve),l(q instanceof Error?q.message:String(q))}finally{_e(null)}},Qt=async xe=>{const Ve=ze;Y(xe),Be("namer"),l(null);try{const ht=await La({autoRenameNamer:xe});Y(ht.autoRenameNamer??"auto"),ye(await fd(!0))}catch(ht){Y(Ve),l(ht instanceof Error?ht.message:String(ht))}finally{Be(null)}},wt=async(xe,Ve)=>{const ht=ce,q={...ht};Ve?q[xe]=Ve:delete q[xe],qe(q),Be(xe),l(null);try{const ut=await La({autoRenameModels:q});qe(ut.autoRenameModels??{})}catch(ut){qe(ht),l(ut instanceof Error?ut.message:String(ut))}finally{Be(null)}},zt=async xe=>{const Ve=ne;Fe(xe),Be("interval"),l(null);try{const ht=await La({autoRenameIntervalMinutes:xe});Fe(ht.autoRenameIntervalMinutes??10)}catch(ht){Fe(Ve),l(ht instanceof Error?ht.message:String(ht))}finally{Be(null)}},Vt=async()=>{const xe=ke.trim();if(xe!==Pe){Be("preference"),l(null);try{const ht=(await La({autoRenamePromptPreference:xe})).autoRenamePromptPreference??"";Ee(ht),Ne(ht)}catch(Ve){Ee(Pe),l(Ve instanceof Error?Ve.message:String(Ve))}finally{Be(null)}}},Kt=async xe=>{const Ve=Math.max(1e3,Math.min(64e3,Math.round(xe||12e3))),ht=oe;We(Ve),Be("payload-limit"),l(null);try{const q=await La({autoRenamePromptPayloadChars:Ve});We(q.autoRenamePromptPayloadChars??12e3)}catch(q){We(ht),l(q instanceof Error?q.message:String(q))}finally{Be(null)}},Ot=new Set(z.map(xe=>xe.slug)),It=ue?{ok:e("settings.agentPluginDoctorStatusOk"),"missing-title-namer":e("settings.agentPluginDoctorStatusMissing"),"cli-default":e("settings.agentPluginDoctorStatusCliDefault"),"no-models":e("settings.agentPluginDoctorStatusNoModels"),"probe-failed":e("settings.agentPluginDoctorStatusFailed")}[ue.status]:"";return s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"rounded-xl bg-surface-2 px-3 py-2.5",children:[s.jsx("div",{className:"text-[12px] font-medium text-foreground",children:e("settings.agentAutoRename")}),s.jsx("p",{className:"mt-1 text-[10px] text-muted-foreground",children:e("settings.agentAutoRenameHint")}),s.jsxs("label",{className:"mt-2 flex items-center justify-between gap-3",children:[s.jsx("span",{className:"text-[11px] text-muted-foreground",children:e("settings.agentAutoRenameNamer")}),s.jsxs("select",{value:ze,disabled:Le!==null,onChange:xe=>{Qt(xe.target.value)},className:"min-w-0 rounded-lg bg-surface px-2.5 py-1.5 text-[11px] text-foreground outline-none disabled:opacity-50",children:[s.jsx("option",{value:"auto",children:e("settings.agentAutoRenameFollow")}),we?.filter(xe=>xe.available).map(xe=>s.jsx("option",{value:xe.slug,children:xe.displayName},xe.slug))]})]}),s.jsxs("label",{className:"mt-2 flex items-center justify-between gap-3",children:[s.jsx("span",{className:"text-[11px] text-muted-foreground",children:e("settings.agentAutoRenameInterval")}),s.jsx("select",{value:ne,disabled:Le!==null,onChange:xe=>{zt(Number(xe.target.value))},className:"min-w-0 rounded-lg bg-surface px-2.5 py-1.5 text-[11px] text-foreground outline-none disabled:opacity-50",children:[5,10,30,60].map(xe=>s.jsxs("option",{value:xe,children:[xe," ",e("settings.agentAutoRenameMinutes")]},xe))})]}),s.jsxs("details",{className:"mt-2 border-t border-border/40 pt-2",children:[s.jsx("summary",{className:"cursor-pointer select-none text-[11px] text-muted-foreground transition hover:text-foreground",children:e("settings.agentAutoRenameAdvanced")}),s.jsxs("label",{className:"mt-2 block",children:[s.jsx("span",{className:"text-[11px] font-medium text-foreground",children:e("settings.agentAutoRenamePreference")}),s.jsx("span",{className:"mt-0.5 block text-[10px] text-muted-foreground",children:e("settings.agentAutoRenamePreferenceHint")}),s.jsx("textarea",{value:ke,maxLength:2e3,rows:3,disabled:Le!==null,placeholder:e("settings.agentAutoRenamePreferencePlaceholder"),onChange:xe=>Ee(xe.target.value),onBlur:()=>{Vt()},className:"mt-1.5 w-full resize-y rounded-lg bg-surface px-2.5 py-2 text-[11px] text-foreground outline-none placeholder:text-muted-foreground/70 focus:ring-1 focus:ring-primary/50 disabled:opacity-50"}),s.jsx("span",{className:"mt-1 block text-right text-[10px] text-muted-foreground",children:Le==="preference"?e("settings.saving"):`${ke.length}/2000`})]}),s.jsxs("label",{className:"mt-2 block",children:[s.jsx("span",{className:"text-[11px] font-medium text-foreground",children:e("settings.agentAutoRenamePayloadLimit")}),s.jsx("span",{className:"mt-0.5 block text-[10px] text-muted-foreground",children:e("settings.agentAutoRenamePayloadLimitHint")}),s.jsx("input",{type:"number",min:1e3,max:64e3,step:1e3,value:oe,disabled:Le!==null,onChange:xe=>We(Number(xe.target.value)),onBlur:xe=>{Kt(Number(xe.target.value))},className:"mt-1.5 w-full rounded-lg bg-surface px-2.5 py-2 text-[11px] text-foreground outline-none focus:ring-1 focus:ring-primary/50 disabled:opacity-50"})]})]}),s.jsxs("div",{className:"mt-2 space-y-1.5 border-t border-border/40 pt-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[10px] text-muted-foreground",children:e("settings.agentAutoRenameModelsFromCli")}),s.jsx("button",{type:"button",onClick:async()=>{ye(null);try{ye(await fd(!0))}catch{ye([])}},className:"rounded p-1 text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground",title:e("settings.agentAutoRenameRefreshModels"),children:s.jsx(bn,{size:11,className:we===null?"animate-spin":""})})]}),we?.filter(xe=>xe.available).map(xe=>{const Ve=xe.models.find(ht=>ht.id===xe.recommendedModel);return s.jsxs("label",{className:"flex items-center justify-between gap-3",children:[s.jsx("span",{className:"text-[11px] text-muted-foreground",children:xe.displayName}),s.jsxs("select",{value:ce[xe.slug]??"",disabled:Le!==null,onChange:ht=>{wt(xe.slug,ht.target.value)},className:"min-w-0 max-w-[68%] rounded-lg bg-surface px-2.5 py-1.5 text-[11px] text-foreground outline-none disabled:opacity-50",children:[s.jsx("option",{value:"",children:Ve?`${e("settings.agentAutoRenameAutomatic")} · ${Ve.displayName}`:e("settings.agentAutoRenameCliDefault")}),xe.models.map(ht=>s.jsx("option",{value:ht.id,children:ht.displayName},ht.id))]})]},xe.slug)}),we?.length===0&&s.jsx("div",{className:"text-[10px] text-[color:var(--warning)]",children:e("settings.agentAutoRenameNoCli")})]})]}),t===null&&s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground",children:[s.jsx(_n,{size:12,className:"animate-spin"})," …"]}),t?.map(xe=>{const Ve=n===xe.slug,ht=xe.state!=="not-installed",q=Ot.has(xe.slug);return s.jsxs("div",{className:"flex items-center gap-3 rounded-xl bg-surface-2 px-3 py-2.5",children:[s.jsx(Wc,{agent:{slug:xe.slug,displayName:xe.displayName,accentColor:xe.accentColor??"#878580",icon:xe.icon,isPlugin:q,iconMode:xe.iconMode,iconVersion:xe.iconVersion??void 0},size:18}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-[13px] font-medium text-foreground",children:xe.displayName}),q&&s.jsx("span",{className:"rounded bg-[rgb(var(--success-rgb)_/_0.12)] px-1 py-px text-[9px] font-medium text-[color:var(--success)]",children:"plugin"}),s.jsxs("span",{className:`text-[10px] ${p$[xe.state]}`,children:[xe.state==="installed"&&s.jsx(zu,{size:10,className:"mr-0.5 inline"}),(xe.state==="outdated"||xe.state==="needs-approval")&&s.jsx(P1,{size:10,className:"mr-0.5 inline"}),Ge(xe.state)]})]}),s.jsxs("div",{className:"truncate text-[10px] text-muted-foreground",title:xe.targetDisplay,children:[e("settings.agentHooksTarget")," ",xe.targetDisplay]}),d===xe.slug&&s.jsx("div",{className:"mt-0.5 text-[10px] text-[color:var(--warning)]",children:e("settings.agentHooksDevMode")}),xe.state==="needs-approval"&&s.jsx("div",{className:"mt-0.5 text-[10px] text-[color:var(--warning)]",children:e("settings.agentHooksApprovalHint")})]}),s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsxs("button",{type:"button",disabled:ee!==null,onClick:()=>{Gt(xe.slug)},className:"flex shrink-0 items-center gap-1.5 rounded-full px-2 py-1 text-[10px] text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground disabled:opacity-50","aria-pressed":be.has(xe.slug),title:e("settings.agentAutoRenameToggle"),children:[s.jsx("span",{children:e("settings.agentAutoRenameShort")}),s.jsx(ll,{checked:be.has(xe.slug),disabled:ee!==null,size:"sm"})]}),s.jsxs("button",{type:"button",disabled:Ve,onClick:()=>{Ie(xe.slug,ht?"uninstall":"install")},className:`flex shrink-0 items-center gap-1 rounded-full px-2.5 py-1 text-[11px] font-medium transition ${ht?"bg-surface text-muted-foreground hover:bg-surface-elevated hover:text-foreground":"bg-[rgb(var(--success-rgb)_/_0.14)] text-[color:var(--success)] hover:bg-[rgb(var(--success-rgb)_/_0.22)]"} disabled:opacity-50`,children:[Ve?s.jsx(_n,{size:11,className:"animate-spin"}):ht?s.jsx(Rs,{size:11}):xe.state==="outdated"?s.jsx(bn,{size:11}):s.jsx(g0,{size:11}),Ve?"…":ht?e("settings.agentHooksUninstall"):xe.state==="outdated"?e("settings.agentHooksReinstall"):e("settings.agentHooksInstall")]})]})]},xe.slug)}),c&&s.jsx("div",{className:"rounded-xl bg-[rgb(var(--warning-rgb)_/_0.10)] px-3 py-2 text-[11px] text-[color:var(--warning)]",children:c}),s.jsxs("div",{className:"rounded-xl bg-surface-2 px-3 py-2.5",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-[12px] font-medium text-foreground",children:e("settings.agentPlugins")}),s.jsxs("button",{type:"button",onClick:()=>w(!y),className:"flex items-center gap-1 rounded-full bg-[rgb(var(--success-rgb)_/_0.14)] px-2.5 py-1 text-[11px] font-medium text-[color:var(--success)] hover:bg-[rgb(var(--success-rgb)_/_0.22)] transition",children:[s.jsx(zs,{size:11}),e("settings.agentPluginAdd")]})]}),s.jsx("p",{className:"mt-1 text-[10px] text-muted-foreground",children:e("settings.agentPluginHint")}),y&&s.jsxs("div",{className:"mt-2 space-y-2",children:[s.jsxs("div",{className:"flex gap-2",children:[s.jsx("input",{value:v,onChange:xe=>S(xe.target.value),onKeyDown:xe=>{xe.key==="Enter"&&H()},className:"min-w-0 flex-1 rounded-lg bg-surface px-3 py-2 font-mono text-[11px] text-foreground placeholder:text-muted-foreground outline-none",placeholder:e("settings.agentPluginSourcePlaceholder")}),s.jsxs("button",{type:"button",disabled:!v.trim()||nt!==null,onClick:()=>{H()},className:"flex items-center gap-1 rounded-full bg-[rgb(var(--success-rgb)_/_0.14)] px-3 py-1 text-[11px] font-medium text-[color:var(--success)] transition hover:bg-[rgb(var(--success-rgb)_/_0.22)] disabled:opacity-50",children:[nt==="install"?s.jsx(_n,{size:11,className:"animate-spin"}):s.jsx(g0,{size:11}),e("settings.agentPluginInstallPackage")]})]}),s.jsx("button",{type:"button",onClick:()=>x(!m),className:"text-[10px] text-muted-foreground transition hover:text-foreground",children:e("settings.agentPluginAdvancedManifest")})]}),z.map(xe=>{const Ve=xe.revision?.slice(0,8),ht=nt?.endsWith(`:${xe.slug}`)===!0;return s.jsxs("div",{className:"mt-2 flex items-center gap-2 border-t border-border/40 pt-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] font-medium text-foreground",children:[s.jsx("span",{className:"truncate",children:xe.displayName}),xe.updateAvailable&&s.jsx("span",{className:"text-[9px] text-[color:var(--warning)]",children:e("settings.agentPluginUpdateAvailable")})]}),s.jsxs("div",{className:"truncate text-[9px] text-muted-foreground",title:xe.source??void 0,children:[xe.source??e("settings.agentPluginManualSource"),Ve?` · ${Ve}`:""]})]}),s.jsxs("button",{type:"button",disabled:nt!==null,onClick:()=>{et(xe.slug)},className:"flex items-center gap-1 rounded-full bg-surface px-2 py-1 text-[10px] text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground disabled:opacity-50",title:e("settings.agentPluginDoctorHint"),children:[nt===`doctor:${xe.slug}`?s.jsx(_n,{size:10,className:"animate-spin"}):s.jsx(_S,{size:10}),e("settings.agentPluginDoctor")]}),xe.updateSupported&&s.jsxs("button",{type:"button",disabled:nt!==null,onClick:()=>{xe.updateAvailable?Ye(xe.slug):Ae(xe.slug)},className:"flex items-center gap-1 rounded-full bg-surface px-2 py-1 text-[10px] text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground disabled:opacity-50",children:[ht?s.jsx(_n,{size:10,className:"animate-spin"}):s.jsx(bn,{size:10}),xe.updateAvailable?e("settings.agentPluginUpdate"):e("settings.agentPluginCheck")]}),s.jsx("button",{type:"button",disabled:nt!==null,onClick:()=>{ae(xe.slug)},className:"rounded-full p-1 text-muted-foreground transition hover:bg-surface-elevated hover:text-[color:var(--warning)] disabled:opacity-50",title:e("settings.agentPluginDelete"),children:s.jsx(Rs,{size:11})})]},xe.slug)}),ue&&s.jsxs("div",{className:`mt-2 rounded-lg px-3 py-2 text-[10px] ${ue.status==="ok"||ue.status==="cli-default"?"bg-[rgb(var(--success-rgb)_/_0.10)] text-[color:var(--success)]":"bg-[rgb(var(--warning-rgb)_/_0.10)] text-[color:var(--warning)]"}`,children:[s.jsxs("div",{className:"font-medium",children:[ue.displayName,": ",It]}),s.jsx("div",{className:"mt-1 text-muted-foreground",children:ue.models.length>0?`${ue.models.length} ${e("settings.agentPluginDoctorModels")}${ue.recommendedModel?` · ${e("settings.agentPluginDoctorAutomatic")} ${ue.recommendedModel}`:""}`:e("settings.agentPluginDoctorCliDefault")}),ue.error&&s.jsx("div",{className:"mt-1 break-words",children:ue.error}),ue.warnings.length>0&&s.jsx("div",{className:"mt-1 space-y-0.5 text-muted-foreground",children:ue.warnings.map(xe=>s.jsxs("div",{children:["• ",xe]},xe))}),ue.nextSteps.length>0&&s.jsx("div",{className:"mt-1 space-y-0.5 text-muted-foreground",children:ue.nextSteps.map(xe=>s.jsxs("div",{children:["→ ",xe]},xe))})]}),$.map(xe=>s.jsxs("div",{className:"mt-2 rounded-lg bg-[rgb(var(--warning-rgb)_/_0.10)] px-3 py-2 text-[10px] text-[color:var(--warning)]",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("span",{className:"font-medium",children:[xe.slug,": ",xe.code??e("settings.agentPluginInvalid")]}),s.jsxs("button",{type:"button",onClick:()=>{St(xe)},className:"flex shrink-0 items-center gap-1 rounded-full bg-[rgb(var(--warning-rgb)_/_0.14)] px-2 py-1 font-medium transition hover:bg-[rgb(var(--warning-rgb)_/_0.22)]",children:[Z===xe.slug?s.jsx(zu,{size:10}):s.jsx(By,{size:10}),Z===xe.slug?e("settings.agentPluginCopied"):e("settings.agentPluginCopyAiPrompt")]})]}),s.jsx("div",{className:"mt-1 whitespace-pre-wrap break-words text-muted-foreground",children:xe.errors.join(`
|
|
@@ -182,5 +182,5 @@ ${Ze.map(q=>`待回答:${q.question}`).join(`
|
|
|
182
182
|
{ "hook": "Stop", "event": "stop", "status": "complete" }
|
|
183
183
|
]
|
|
184
184
|
}
|
|
185
|
-
}`}),R&&s.jsx("div",{className:"whitespace-pre-wrap break-words text-[10px] text-[color:var(--warning)]",children:R}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("button",{type:"button",onClick:()=>{Ce()},className:"flex items-center gap-1 rounded-full bg-[rgb(var(--success-rgb)_/_0.14)] px-3 py-1 text-[11px] font-medium text-[color:var(--success)] hover:bg-[rgb(var(--success-rgb)_/_0.22)] transition",children:[s.jsx(tT,{size:11}),e("settings.agentPluginCreate")]}),s.jsx("button",{type:"button",onClick:()=>{x(!1),E(""),B(null)},className:"rounded-full px-3 py-1 text-[11px] text-muted-foreground hover:text-foreground transition",children:e("common.cancel")})]})]})]})]})}function g$({state:e,pending:t,onCheck:r,onConfirmRestart:n,desktopState:a,desktopPending:c=!1,desktopSnapshot:l,desktopActions:d,onCheckDesktop:p,onInstallDesktop:m}){const{t:x}=Ur(),y=e?.status??"idle",w=t||y==="checking"||y==="installing"||y==="restarting",v=y==="ready"&&!!e?.latestVersion,S=y==="checking"?x("settings.updateChecking"):y==="installing"?x("sidebar.updateInstalling"):y==="ready"?x("sidebar.updateReady"):y==="restarting"?x("sidebar.updateRestarting"):y==="current"?x("settings.updateCurrent"):y==="error"?e?.error||x("sidebar.updateFailed"):x("settings.updateHint"),L=a?.currentVersion||l?.appVersion,E=a?.status??"idle",R=c||E==="checking"||E==="downloading"||E==="installing",B=E==="ready",z=a?.error||(E==="unsupported"?x("settings.desktopUpdateUnsupported"):E==="checking"?x("settings.desktopUpdateChecking"):E==="current"?x("settings.desktopUpdateCurrent"):E==="downloading"?x("settings.desktopUpdateDownloading"):E==="ready"?x("settings.desktopUpdateReady"):E==="installing"?x("settings.desktopUpdateInstalling"):E==="error"&&a?.error||x("settings.desktopUpdateHint"));return s.jsxs("section",{className:"mt-3 overflow-hidden rounded-xl bg-surface-2","aria-labelledby":"termdock-update-title",children:[s.jsx("div",{id:"termdock-update-title",className:"px-3 pt-3 text-[12px] font-semibold text-foreground",children:x("settings.updateTitle")}),s.jsxs("div",{className:"flex items-start justify-between gap-3 px-3 py-3",children:[s.jsxs("div",{className:"flex min-w-0 items-start gap-2.5",children:[s.jsx("span",{className:`mt-0.5 inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${v?"bg-[rgb(var(--warning-rgb)_/_0.16)] text-[color:var(--warning)]":"bg-primary/15 text-primary"}`,children:s.jsx(bn,{size:15,className:w?"animate-spin":""})}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12px] font-medium text-foreground",children:x("settings.updateRuntimeTitle")}),s.jsx("div",{className:"mt-0.5 text-[10px] leading-relaxed text-muted-foreground",children:S}),e&&s.jsx("div",{className:"mt-1 text-[10px] tabular-nums text-muted-foreground/75",children:v&&e.latestVersion?`${e.currentVersion} → ${e.latestVersion}`:`v${e.currentVersion}`})]})]}),v?s.jsx("button",{type:"button",disabled:w,onClick:n,className:"shrink-0 rounded-full bg-[var(--warning)] px-3 py-1.5 text-[11px] font-semibold text-[color:var(--bg)] transition hover:opacity-90 disabled:cursor-wait disabled:opacity-60",children:x("sidebar.updateRestart")}):s.jsx("button",{type:"button",disabled:w,onClick:r,className:"shrink-0 rounded-full bg-surface px-3 py-1.5 text-[11px] font-medium text-foreground transition hover:bg-surface-elevated disabled:cursor-wait disabled:opacity-60",children:x(y==="checking"?"settings.updateCheckingShort":y==="installing"?"settings.updateInstallingShort":y==="error"?"sidebar.updateRetry":y==="current"?"settings.updateCheckAgain":"settings.updateCheck")})]}),(a||d)&&s.jsxs("div",{className:"flex items-start justify-between gap-3 border-t border-border/10 px-3 py-3",children:[s.jsxs("div",{className:"flex min-w-0 items-start gap-2.5",children:[s.jsx("span",{className:`mt-0.5 inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${B?"bg-[rgb(var(--warning-rgb)_/_0.16)] text-[color:var(--warning)]":"bg-primary/15 text-primary"}`,children:s.jsx(bn,{size:15,className:R?"animate-spin":""})}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12px] font-medium text-foreground",children:x("settings.desktopUpdateTitle")}),s.jsx("div",{className:`mt-0.5 text-[10px] leading-relaxed ${a?.error?"text-destructive":"text-muted-foreground"}`,role:a?.error?"alert":void 0,children:a?z:x(p?"settings.desktopStatusLoading":"settings.desktopUpdateUnsupported")}),s.jsx("div",{className:"mt-1 text-[10px] tabular-nums text-muted-foreground/75",children:B&&a?.latestVersion?`${a.currentVersion} → ${a.latestVersion}`:L?`v${L}`:null})]})]}),B?s.jsx("button",{type:"button",disabled:R||!m,onClick:m,className:"shrink-0 rounded-full bg-[var(--warning)] px-3 py-1.5 text-[11px] font-semibold text-[color:var(--bg)] transition hover:opacity-90 disabled:cursor-wait disabled:opacity-60",children:x("settings.desktopUpdateRestart")}):s.jsx("button",{type:"button",disabled:!a||R||E==="unsupported"||!p,onClick:p,className:"shrink-0 rounded-full bg-surface px-3 py-1.5 text-[11px] font-medium text-foreground transition hover:bg-surface-elevated disabled:cursor-wait disabled:opacity-60",children:x(E==="installing"?"settings.updateInstallingShort":E==="downloading"?"settings.desktopUpdateDownloadingShort":E==="checking"?"settings.updateCheckingShort":E==="current"||E==="error"?"settings.desktopUpdateCheckAgain":"settings.desktopUpdateCheck")})]}),d]})}function x$({quality:e}){const{locale:t}=Ur(),r=(d,p)=>t==="zh"?d:p,n=d=>d==null||!Number.isFinite(d)?"—":`${d.toFixed(1)} ms`,a=e?.diagnostics,c=d=>s.jsx("dl",{className:"grid grid-cols-[minmax(0,1fr)_auto] gap-x-3 gap-y-1.5 tabular-nums",children:d.map(([p,m])=>s.jsxs(k.Fragment,{children:[s.jsx("dt",{children:p}),s.jsx("dd",{className:"text-right text-foreground break-all",children:m})]},p))}),l=(d,p)=>s.jsxs("section",{className:"mt-3 border-t border-border/30 pt-3",children:[s.jsx("h3",{className:"mb-2 font-medium text-foreground",children:d}),p]});return s.jsxs("div",{className:"text-[11px] leading-relaxed",children:[l(r("往返统计","Round-trip statistics"),s.jsxs(s.Fragment,{children:[c([[r("平均延迟","Average latency"),n(e?.average)],["P95",n(e?.p95)],[r("服务端回包处理","Server reply handler"),n(e?.handlerMs)]]),s.jsx("p",{className:"mt-2",children:r("8 秒未响应计为超时,不等于网络丢包。回包处理仅含消息解析至构造回复,不含解密、排队和发包。","A probe times out after 8s; this is not packet loss. Handler timing covers parsing through reply creation, excluding decryption, queues and transmission.")})]})),l(r("当前发送与排队","Current buffers and queues"),a?s.jsxs(s.Fragment,{children:[c([[r("传输层发送缓冲","Transport send buffer"),`${a.bufferedBytes} B`],[r("加密通道待发送","Channel writes pending"),a.pendingWrites?r("有","Yes"):r("无","No")],[r("进行中的非终端请求","Active non-terminal requests"),a.activeRequests],[r("等待通道的请求","Requests waiting for capacity"),a.waitingRequests]]),s.jsx("p",{className:"mt-2",children:r("属于此服务共用的连接,包含文件等其他请求。","Shared by this service, including file transfers and other requests.")})]}):s.jsx("p",{children:r("尚无连接记录。","No connection record yet.")})),l(r("本次连接建立 · 历史耗时","Connection setup · recorded timings"),s.jsxs(s.Fragment,{children:[c([[r("传输通道就绪","Transport ready"),n(a?.transportOpenMs)],...a?.relay?[[r("其中:连上入口 WebSocket","Within transport: entry WebSocket"),n(a.relay.entryOpenMs)],[r("其中:请求中转至通道打开","Within transport: relay open request"),n(a.relay.routeOpenMs)]]:[],[r("Noise 加密握手","Noise handshake"),n(a?.handshakeMs)],[r("终端逻辑通道就绪","Terminal logical channel ready"),n(a?.socketOpenMs)],[r("其中:等待本地通道名额","Within logical open: local capacity wait"),n(a?.socketQueueMs)]]),s.jsx("p",{className:"mt-2",children:r("这是建链时的历史耗时,不代表当前延迟。“其中”为子项,不能重复相加;中转耗时含处理和建链,不含之前的授权。","Recorded setup timings, not live latency. “Within” rows are subsets, not additive. Relay timing includes processing and setup, excluding earlier authorization.")})]}))]})}function b$({backendSessionId:e}){const{locale:t}=Ur(),r=t==="zh",[n,a]=k.useState(null),[c,l]=k.useState(!1);k.useEffect(()=>{if(a(null),!c||!e)return;const y=()=>a(k9(e));y();const w=setInterval(y,1e3);return document.addEventListener("visibilitychange",y),()=>{clearInterval(w),document.removeEventListener("visibilitychange",y)}},[e,c]);const d=n?.diagnostics,p=n?.rtt,m=n?.connected?n.waiting?r?"等待响应…":"Waiting for reply…":p==null?r?"测量中…":"Measuring…":`${p} ms · ${p<150?r?"流畅":"Low latency":p<300?r?"有延迟":"Moderate latency":r?"高延迟":"High latency"}`:r?"未连接":"Disconnected",x=y=>y==null?"—":`${Math.round(y)} ms`;return s.jsxs("div",{className:"mt-3 rounded-xl bg-surface-2 px-3 text-muted-foreground",children:[s.jsxs("button",{type:"button","aria-expanded":c,onClick:()=>l(y=>!y),className:"flex min-h-11 w-full items-center gap-2 py-2 text-[12px] tabular-nums hover:text-foreground","aria-label":`${r?"连接质量":"Connection quality"}${c?`: ${m}`:""}`,children:[s.jsx("span",{"aria-hidden":"true",className:`h-1.5 w-1.5 rounded-full ${c&&n&&(!n.connected||n.waiting||p!=null&&p>=300)?"bg-destructive":"bg-current"}`}),s.jsxs("span",{className:"flex-1 text-left",children:[r?"连接质量":"Connection quality",c?` · ${m}`:""]}),s.jsx("span",{"aria-hidden":"true",children:c?"▾":"▸"})]}),c&&s.jsxs("div",{className:"pb-3 text-[11px] leading-relaxed",children:[!e&&s.jsx("p",{children:r?"请先打开一个终端会话,再查看连接质量。":"Open a terminal session to measure connection quality."}),s.jsxs("dl",{className:"grid grid-cols-[auto_minmax(0,1fr)] gap-x-4 gap-y-2 tabular-nums",children:[s.jsx("dt",{children:r?"近期延迟":"Recent latency"}),s.jsx("dd",{className:"text-right text-foreground",children:n?.minimum==null?"—":`${Math.round(n.minimum)}–${Math.round(n.maximum??n.minimum)} ms`}),s.jsx("dt",{children:r?"波动":"Jitter"}),s.jsx("dd",{className:"text-right text-foreground",children:x(n?.jitter)}),s.jsx("dt",{children:r?"探测超时":"Probe timeouts"}),s.jsx("dd",{className:"text-right text-foreground",children:n?.samples?`${n.timeouts} / ${n.samples}`:"—"}),s.jsx("dt",{children:r?"连接路径":"Connection route"}),s.jsx("dd",{className:"text-right text-foreground break-words",children:d?`${d.path==="relay"?r?"经入口中转":"Via relay":r?"直连":"Direct"} · ${d.endpoint}`:"—"})]}),s.jsx("p",{className:"mt-2",children:r?"每 5 秒更新,统计最近 20 次;波动越小越稳定。":"Updates every 5s, using the last 20 probes. Lower jitter means more consistent latency."}),s.jsxs("details",{className:"mt-3 border-t border-border/30 pt-2",children:[s.jsx("summary",{className:"cursor-pointer py-1 hover:text-foreground",children:r?"诊断详情":"Diagnostics"}),s.jsx(x$,{quality:n})]})]})]})}const ay={"startup-failure":"settings.serverHealthEventStartupFailure",crash:"settings.serverHealthEventCrash","crash-native":"settings.serverHealthEventCrashNative",killed:"settings.serverHealthEventKilled",wedge:"settings.serverHealthEventWedge","port-conflict":"settings.serverHealthEventPortConflict","gave-up":"settings.serverHealthEventGaveUp","exit-zero-unexpected":"settings.serverHealthEventExitZero","terminated-externally":"settings.serverHealthEventTerminated","supervisor-lost":"settings.serverHealthEventSupervisorLost","uncaught-exception":"settings.serverHealthEventUncaughtException","unhandled-rejection":"settings.serverHealthEventUnhandledRejection","exit-nonzero":"settings.serverHealthEventExitNonzero"};function y$(e){return e<1e3?`${e}ms`:e<6e4?`${Math.round(e/1e3)}s`:e<36e5?`${Math.round(e/6e4)}m`:`${Math.round(e/36e5)}h`}function v$({state:e,onDismiss:t}){const{t:r}=Ur(),[n,a]=b.useState(!1),[c,l]=b.useState(!1),d=b.useRef(!1),p=b.useRef(!0);b.useEffect(()=>(p.current=!0,()=>{p.current=!1}),[]),b.useEffect(()=>{e?.supervised&&(d.current=!1,a(!1),l(!1))},[e?.supervised]),b.useEffect(()=>{if(!n)return;const z=window.setTimeout(()=>{d.current=!1,a(!1),l(!0)},45e3);return()=>window.clearTimeout(z)},[n]);const m=async()=>{if(!d.current){d.current=!0,l(!1),a(!0);try{await L9()}catch{if(!p.current)return;d.current=!1,a(!1),l(!0)}}};if(!e)return null;const x=e.incident,y=!e.supervised&&e.supervisor?.phase==="gave-up",w=!e.supervised&&e.supervisor!==null&&!e.supervisor.alive,v=y||w||e.attention,S=e.supervised&&e.supervisor?.alive&&e.supervisor.phase==="running",L=y?r("settings.serverHealthGaveUp",{count:e.supervisor?.consecutiveCrashes??0}):w?r("settings.serverHealthSupervisorLost"):e.supervised?r("settings.serverHealthSupervised"):r("settings.serverHealthUnsupervised"),E=x?r(ay[x.event]??"settings.serverHealthUnknownEvent"):"",R=x?.causeEvent?r(ay[x.causeEvent]??"settings.serverHealthUnknownEvent"):"",B=x?[new Date(x.at).toLocaleString(),x.uptimeMs!==null?r("settings.serverHealthUptime",{duration:y$(x.uptimeMs)}):null,x.signal?`signal ${x.signal}`:null,x.exitCode!==null?`exit ${x.exitCode}`:null].filter(Boolean).join(" · "):"";return s.jsxs("section",{className:"mt-3 overflow-hidden rounded-xl bg-surface-2","aria-labelledby":"server-health-title",children:[s.jsx("div",{id:"server-health-title",className:"px-3 pt-3 text-[12px] font-semibold text-foreground",children:r("settings.serverHealthTitle")}),s.jsxs("div",{className:"flex items-start justify-between gap-3 px-3 py-3",children:[s.jsxs("div",{className:"flex min-w-0 items-start gap-2.5",children:[s.jsx("span",{className:`mt-0.5 inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${v?"bg-destructive/15 text-destructive":"bg-primary/15 text-primary"}`,children:v?s.jsx(vS,{size:15}):s.jsx(AS,{size:15})}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12px] font-medium text-foreground",children:L}),s.jsx("div",{className:"mt-0.5 text-[10px] leading-relaxed text-muted-foreground",children:x?`${r(S?"settings.serverHealthHistory":"settings.serverHealthLastIncident")}: ${E}${R?` · ${R}`:""}`:r("settings.serverHealthClean")}),x&&S&&s.jsx("div",{className:"mt-1 text-[11px] text-primary",children:r("settings.serverHealthRunningNow")}),x&&s.jsx("div",{className:"mt-1 text-[10px] tabular-nums text-muted-foreground/75",children:B}),x?.detail&&s.jsx("div",{className:"mt-1 break-words text-[10px] text-muted-foreground/75",children:x.detail}),x?.oomSuspect&&s.jsx("div",{className:"mt-1 text-[10px] text-[color:var(--warning)]",children:r("settings.serverHealthOomNote")}),e.supervisor&&e.supervisor.restarts>0&&!y&&s.jsx("div",{className:"mt-1 text-[10px] tabular-nums text-muted-foreground/75",children:r("settings.serverHealthRestarted",{count:e.supervisor.restarts})})]})]}),e.attention&&s.jsx("button",{type:"button",onClick:t,className:"shrink-0 rounded-full bg-surface px-3 py-1.5 text-[11px] font-medium text-foreground transition hover:bg-surface-elevated",children:r("settings.serverHealthDismiss")})]}),!e.supervised&&s.jsxs("div",{className:"border-t border-border px-3 py-3",children:[s.jsx("p",{className:"text-[11px] leading-relaxed text-muted-foreground",children:e.canEnableSupervision?r("settings.serverHealthEnableHint"):r("settings.serverHealthEnableUnavailable")}),e.canEnableSupervision&&s.jsx("button",{type:"button",onClick:m,disabled:n,className:"mt-2 min-h-11 rounded-lg bg-primary px-3 text-[12px] font-medium text-primary-foreground disabled:opacity-60",children:r(n?"settings.serverHealthEnabling":"settings.serverHealthEnable")}),n&&s.jsx("p",{role:"status",className:"mt-2 text-[11px] text-muted-foreground",children:r("settings.serverHealthEnablePending")}),c&&s.jsx("p",{role:"alert",className:"mt-2 text-[11px] text-destructive",children:r("settings.serverHealthEnableError")})]})]})}const w$=()=>()=>{},A$=()=>1/0;function T$(){const{t:e}=Ur(),t=b.useId(),r=Po(),n=b.useSyncExternalStore(r?.subscribe??w$,r?.retentionLimit??A$);if(!r)return null;const a=I9+1,c=n===1/0?e("settings.workspaceUnlimited"):String(n);return s.jsxs("div",{className:"space-y-1.5 rounded-xl bg-surface-2 px-2.5 py-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("label",{htmlFor:t,className:"shrink-0 text-[12px] font-medium text-foreground/90",children:e("settings.workspaceLimit")}),s.jsx("input",{id:t,type:"range",min:3,max:a,step:1,value:n===1/0?a:n,"aria-valuetext":c,"aria-describedby":`${t}-hint`,onChange:l=>{const d=Number(l.target.value);r.setRetentionLimit(d===a?1/0:d)},className:"h-8 min-w-0 flex-1"}),s.jsx("output",{htmlFor:t,className:"min-w-12 shrink-0 text-right text-[11px] tabular-nums text-muted-foreground",children:c})]}),s.jsx("p",{id:`${t}-hint`,className:"text-[11px] leading-relaxed text-muted-foreground",children:e("settings.workspaceLimitHint")})]})}const M1="mobile-session-destroy";function S$(e,t){return t&&e.type==="session"&&e.destination?.droppableId===M1}const Ca="termdock-program-rules-cache",Bh="termdock-toolbar-presets-cache",qd="termdock-settings-cache",oy="termdock-color-theme",ly="termdock:right-sidebar:file-preview-open-by-session:v2",Yd="termdock:running-session-button-enabled:v1",Zd="termdock:attention-button-enabled:v1",C$=60,cy=320,uy=420,Qo=8;function dy(e,t,r){return Math.min(Math.max(e,t),r)}function hy(e){if(typeof window>"u")return{left:Qo,top:Qo};const t=window.innerWidth/2,r=Math.min(64,window.innerHeight/4),n=e?.x??t,a=e?.y??r,c=Math.max(Qo,window.innerWidth-cy-Qo),l=Math.max(Qo,window.innerHeight-uy-Qo);return{left:dy(n+Qo,Qo,c),top:dy(a+Qo,Qo,l),width:cy,maxHeight:`min(${uy}px, calc(100vh - ${Qo*2}px))`}}function _$(e){return e==="dark"||e==="light"}function k$(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.entries(e).every(([t,r])=>{if(!t||!r||typeof r!="object"||Array.isArray(r))return!1;const n=r;return typeof n.updatedAt=="number"&&Number.isFinite(n.updatedAt)})}function Bm(e){const t=Object.entries(e).filter(([r,n])=>r&&Number.isFinite(n.updatedAt)).sort(([,r],[,n])=>n.updatedAt-r.updatedAt).slice(0,C$);return Object.fromEntries(t)}function L$(e){return Array.isArray(e)&&e.every(t=>{if(!t||typeof t!="object")return!1;const r=t;return typeof r.id=="string"&&typeof r.pattern=="string"&&typeof r.output=="string"&&(r.matchType==="exact"||r.matchType==="includes"||r.matchType==="prefix"||r.matchType==="regex")})}function I$(e){return typeof e=="object"&&e!==null&&typeof e.version=="number"&&Array.isArray(e.presets)}function E$(e,t){const r=w0(),n=new Set(xE()),a=Array.isArray(e)?e:[],c=Ru(a),l=t<e0;if(c.length===0)return r;if(l){const p=new Map(c.map(w=>[w.id,w])),m=new Map(a.map(w=>[typeof w.id=="string"?w.id.trim().toLowerCase().replace(/[^a-z0-9_-]/g,"-"):"",w])),x=c.filter(w=>!n.has(w.id));return[...r.map(w=>{const v=p.get(w.id),S=m.get(w.id);return v?{...w,rowLayout:v.rowLayout,showOnDesktop:typeof S?.showOnDesktop=="boolean"?S.showOnDesktop:w.showOnDesktop}:w}),...x]}const d=new Set(c.map(p=>p.id));return[...c,...r.filter(p=>!d.has(p.id))]}function N$(e){return typeof e=="object"&&e!==null&&typeof e.preventSleep=="boolean"&&typeof e.networkAvailable=="boolean"}const R$={name:"",source:"auto",hostname:"",fallbackHostname:"",url:"",fallbackUrl:"",onboardingUrl:null,status:"disabled",reason:null,httpsEnabled:!1,caAvailable:!1,lanAddresses:[],interfaces:[]},np="__termdockOverlay",sp="__termdockBaseAnchor",ip="__termdockBaseGuard",M$=3,fy=250,j$="termdock-notification-target-v1",py="/__termdock-notification-target",my=3e4;function D$(e){return e==="left-sidebar"||e==="right-sidebar"||e==="right-sidebar-repo-picker"||e==="right-sidebar-file-preview"||e==="settings"||e==="markdown-outline"||e==="markdown-image-lightbox"}function Su(e){if(!e||typeof e!="object")return null;const t=e[np];return D$(t)?t:null}function Ng(e){return e&&typeof e=="object"?{...e}:{}}function r4(e){const t=Ng(e);return delete t[np],t}function B$(e){const t=r4(e);return delete t[ip],{...t,[sp]:!0}}function Q$(){typeof window>"u"||window.history.pushState({...r4(window.history.state),[sp]:!0,[ip]:!0},"",window.location.href)}function n4(){for(let e=0;e<M$;e+=1)Q$()}function Qh(){typeof window>"u"||(window.history.replaceState(B$(window.history.state),"",window.location.href),n4())}function Kd(e){typeof window>"u"||window.history.pushState({...Ng(window.history.state),[sp]:!0,[np]:e,[ip]:!1},"",window.location.href)}function P$(e){typeof window>"u"||window.history.replaceState({...Ng(window.history.state),[sp]:!0,[np]:e,[ip]:!1},"",window.location.href)}const s4=["bash","zsh","fish","sh","dash","ksh","tcsh","csh","nu"];let _a=new Set(s4);function gy(e){const t=new Map;for(const[r,n]of e)t.set(r,{cwd:n.cwd,activeProgram:n.activeProgram,activeProgramRaw:n.activeProgramRaw,inCopyMode:n.inCopyMode,isConnecting:n.isConnecting,agentStatus:n.agentStatus,agentIndicator:n.agentIndicator,agentStatusDetail:n.agentStatusDetail,agent:n.agent,agentMessage:n.agentMessage,agentNativeSessionId:n.agentNativeSessionId,agentResumeRecovered:n.agentResumeRecovered,terminalSessionId:n.terminalSessionId,agentNeedsReview:n.agentNeedsReview,gitStatus:n.gitStatus,shellTitle:n.shellTitle,promptState:n.promptState,tuiProgress:n.tuiProgress});return t}function O$(e,t){if(e.size!==t.size)return!1;for(const[r,n]of t){const a=e.get(r);if(!a||a.cwd!==n.cwd||a.activeProgram!==n.activeProgram||a.activeProgramRaw!==n.activeProgramRaw||a.inCopyMode!==n.inCopyMode||a.isConnecting!==n.isConnecting||a.agentStatus!==n.agentStatus||a.agentIndicator!==n.agentIndicator||a.agentStatusDetail!==n.agentStatusDetail||a.agent!==n.agent||a.agentMessage!==n.agentMessage||a.agentNativeSessionId!==n.agentNativeSessionId||a.agentResumeRecovered!==n.agentResumeRecovered||a.terminalSessionId!==n.terminalSessionId||a.agentNeedsReview!==n.agentNeedsReview||a.gitStatus!==n.gitStatus||a.shellTitle!==n.shellTitle||a.promptState!==n.promptState||a.tuiProgress?.state!==n.tuiProgress?.state||a.tuiProgress?.progress!==n.tuiProgress?.progress)return!1}return!0}function xy(e,t){return s.jsx($P,{sessionMode:e,state:t})}function F$(e,t){const r=new Map(e.map(l=>[l.id,l])),n=t.map(l=>r.get(l)).filter(l=>l!==void 0),a=new Set(t),c=e.filter(l=>!a.has(l.id));return[...n,...c]}const $$=k.lazy(()=>Oc(()=>import("./CollaborationMainWorkspace-BJzMdyZc.js"),__vite__mapDeps([18,1,2,3,4,5,8,9,15,13])));function U$(){const{t:e,locale:t,setLocale:r}=Ur(),n="env(safe-area-inset-top, 0px)",a="env(safe-area-inset-bottom, 0px)";E9();const c=k.useMemo(()=>typeof window>"u"?!1:/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,[]),[l,d]=k.useState(!1),[p,m]=k.useState(()=>Tc(oy,_$)??"dark"),x=k.useRef(Tc(qd,N$)).current,[y,w]=k.useState(x?.preventSleep??!1),[v,S]=k.useState(x?.networkAvailable??!0),[L,E]=k.useState(N9),[R,B]=k.useState(R9),[z,O]=k.useState(M9),[$,V]=k.useState(j9),[Z,le]=k.useState(Tp),[be,pe]=k.useState(x?.localAccess??R$),[ee,_e]=k.useState(x?.localAccess?.name??""),[ze,Y]=k.useState(!1),[ce,qe]=k.useState(null),[we,ye]=k.useState(null),[Le,Be]=k.useState(null),[ne,Fe]=k.useState(!1),[ke,Ee]=k.useState(null),Pe=k.useMemo(()=>vo(),[]),Ne=!!(Pe?.desktopUpdateState&&Pe.checkDesktopUpdate&&Pe.installDesktopUpdate),[oe,We]=k.useState(null),[nt,gt]=k.useState(null),[ue,Ze]=k.useState(!1),[at,Ie]=k.useState(null),[Ge,Ce]=k.useState(!1),[H,ae]=k.useState(()=>Bm(Tc(ly,k$)??{})),[Ae,Ye]=k.useState(0),[et,St]=k.useState(!1),[Gt,Qt]=k.useState(0),[wt,zt]=k.useState(!1),[Vt,Kt]=k.useState(0),[Ot,It]=k.useState(!1),[xe,Ve]=k.useState(0),ht=k.useRef(null),[q,ut]=k.useState({}),{terminalSettings:qt,updateTerminalSettings:tt}=qB(),De=qt.fontSize,nr=qt.rendererMode,[Ke,_t]=k.useState(!1),$t=k.useRef(D9()).current,[yt,xt]=b.useState(()=>$t.sessions.map(C=>({id:C.sessionId,name:C.name,customName:C.customName,mode:C.mode,tmuxSessionName:C.tmuxSessionName}))),Rt=Ei(C=>C.groupId);k.useEffect(()=>{const C=()=>Ei.getState().terminal();return window.addEventListener("switch-terminal-session",C),()=>window.removeEventListener("switch-terminal-session",C)},[]);const[Ct,fr]=k.useState($t.activeSessionId),[Yt,Sr]=k.useState(!1);k.useEffect(()=>{Yt&&B9({rendered:!0})},[Yt]);const[pn,dr]=k.useState(null),[me,Gr]=k.useState(null),[ot,pt]=k.useState([]),[ir,Mn]=b.useState(()=>{const C=Yr.getState();return $t.sessions.forEach(P=>{P.backendSessionId&&C.setTerminalSession(P.sessionId,{sessionId:P.backendSessionId,cols:80,rows:24,mode:P.mode,tmuxSessionName:P.tmuxSessionName}),P.activeProgram!=null&&C.setSessionActiveProgram(P.sessionId,P.activeProgram),P.cwd!=null&&C.setSessionCwd(P.sessionId,P.cwd),P.shellTitle!=null&&C.setSessionShellTitle(P.sessionId,P.shellTitle)}),Mu("session-chrome-hydrated"),gy(Yr.getState().sessions)});b.useEffect(()=>{!Pe||!Ke||Promise.all([Pe.snapshot(),Pe.desktopUpdateState?.()??Promise.resolve(null)]).then(([C,P])=>{We(C),gt(P)}).catch(C=>Ie(C instanceof Error?C.message:String(C)))},[Pe,Ke]),b.useEffect(()=>{Pe?.onDesktopUpdateState&&Pe.onDesktopUpdateState(gt)},[Pe]),b.useEffect(()=>Yr.subscribe(C=>{const P=gy(C.sessions);Mn(de=>O$(de,P)?de:P)}),[]);const Xr=b.useCallback(async(C,P)=>{Gr(null),dr({sessionId:C,status:"submitting",error:null});try{await Q9(P),dr(de=>de?.sessionId===C?{...de,status:"waiting",error:null}:de)}catch(de){const At=(de&&typeof de=="object"&&"code"in de?String(de.code??""):"")==="AGENT_SESSION_ACTIVE_ELSEWHERE"?e("tab.resumeAgentConflict"):de instanceof Error&&/busy/i.test(de.message)?e("tab.resumeAgentBusy"):e("tab.resumeAgentFailed");dr(Zt=>Zt?.sessionId===C?{...Zt,error:At}:Zt),Gr({tone:"error",message:At})}},[e]);b.useEffect(()=>{if(!pn||pn.status!=="waiting")return;const C=ir.get(pn.sessionId);if(!C||C.agentResumeRecovered||C.agentStatus===null&&!C.agent)return;const P=C.agent?.displayName??"Agent";dr(null),Gr({tone:"success",message:e("tab.resumeAgentSuccess",{agent:P})})},[pn,ir,e]),b.useEffect(()=>{if(!pn||pn.status!=="waiting"||pn.error)return;const C=pn.sessionId,P=window.setTimeout(()=>{const de=e("tab.resumeAgentTimeout");dr(rt=>rt?.sessionId===C&&rt.status==="waiting"?{...rt,error:de}:rt),Gr({tone:"error",message:de})},15e3);return()=>window.clearTimeout(P)},[pn,e]),b.useEffect(()=>{if(me?.tone!=="success")return;const C=window.setTimeout(()=>Gr(null),3200);return()=>window.clearTimeout(C)},[me]),b.useEffect(()=>{let C=!1;P9().then(de=>{C||Be(de)}).catch(()=>{}),O9().then(de=>{C||Ee(de)}).catch(()=>{});const P=ux(de=>{C||(de.type==="update-state"?Be(de.state):de.type==="server-health"&&Ee(de.state))});return()=>{C=!0,P()}},[]);const je=b.useCallback(async()=>{try{Ee(await F9())}catch(C){window.alert(C instanceof Error?C.message:String(C))}},[]),st=b.useCallback(async()=>{const C=Le?.latestVersion;if(!(!C||ne)&&window.confirm(e("sidebar.updateRestartConfirm",{version:C}))){Fe(!0);try{Be(await $9())}catch(P){window.alert(P instanceof Error?P.message:String(P))}finally{Fe(!1)}}},[Le?.latestVersion,e,ne]),bt=b.useCallback(async()=>{if(!ne){Fe(!0);try{Be(await U9())}catch(C){window.alert(C instanceof Error?C.message:String(C))}finally{Fe(!1)}}},[ne]),Br=b.useCallback(async()=>{if(!(!Pe?.checkDesktopUpdate||ue)){Ze(!0);try{gt(await Pe.checkDesktopUpdate())}catch(C){Ie(C instanceof Error?C.message:String(C))}finally{Ze(!1)}}},[Pe,ue]),Vr=b.useCallback(async()=>{if(!(!Pe?.installDesktopUpdate||ue||nt?.status!=="ready")&&window.confirm(e("settings.desktopUpdateRestartConfirm"))){Ze(!0);try{gt(await Pe.installDesktopUpdate())}catch(C){Ie(C instanceof Error?C.message:String(C))}finally{Ze(!1)}}},[Pe,ue,nt?.status,e]);b.useEffect(()=>{document.documentElement.dataset.theme=p,z9(p),Fn(oy,p)},[p]),b.useEffect(()=>{Fn(ly,Bm(H))},[H]);const Cr=Wt(C=>C.leftOpen),qr=Wt(C=>C.rightOpen),mn=Wt(C=>C.leftPinned),on=Wt(C=>C.leftSidebarWidth),zr=Wt(C=>C.rightPinned),un=Wt(C=>C.rightSidebarWidth),Er=Wt(C=>C.rootPath),re=Wt(C=>C.contextKey),mt=Wt(C=>C.selectedFilePath),Mt=Wt(C=>C.groupByFolder),rr=df(C=>C.collaborationGroups),Ar=Wt(C=>C.collapsedGroups),Fr=Wt(C=>C.toggleGroupCollapsed),[Xt,Zr]=b.useState(()=>typeof window>"u"?!0:window.matchMedia("(min-width: 1024px)").matches),[Jt,Pr]=b.useState(()=>typeof window>"u"?1024:window.innerWidth),[Hr,ps]=b.useState(()=>typeof window>"u"?!1:window.matchMedia("(orientation: landscape)").matches),[Mr,jn]=b.useState([]),[Tr,Jr]=b.useState({available:!0,version:null,reason:null}),[ln,Qr]=b.useState(!1),[ks,Dr]=b.useState(null),[en,xn]=b.useState(null),[X,He]=b.useState(null),[Nt,Et]=b.useState(null),[tr,jr]=b.useState(null),[cr,Cn]=b.useState(null),[Ls,Xn]=b.useState(null),[,cn]=b.useState(0),[dn,_r]=b.useState(null),[Or,Gn]=b.useState(null),[Vn,gn]=b.useState(null),[Jn,kr]=b.useState(!1),[Lr,pr]=b.useState(()=>Tc(Yd,C=>typeof C=="boolean")??!1),ns=b.useCallback(async C=>{const P=Lr;pr(C),Fn(Yd,C);try{const de=await La({runningSessionButtonEnabled:C});pr(de.runningSessionButtonEnabled),Fn(Yd,de.runningSessionButtonEnabled)}catch{pr(P),Fn(Yd,P)}},[Lr]),[Un,En]=b.useState(()=>Tc(Zd,C=>typeof C=="boolean")??!0),kn=b.useCallback(async C=>{const P=Un;En(C),Fn(Zd,C);try{const de=await La({attentionButtonEnabled:C});En(de.attentionButtonEnabled),Fn(Zd,de.attentionButtonEnabled)}catch{En(P),Fn(Zd,P)}},[Un]),[ss,Wr]=b.useState(null),tn=b.useCallback(C=>{Wr(C)},[]),G=b.useRef(!1),[Me,$e]=b.useState(null),[Je,it]=b.useState(null),Tt=k.useRef(null),kt=k.useRef(!1),Dt=k.useRef(null),ft=k.useRef(!1),Bt=b.useCallback(()=>{Cn(null),Xn(null)},[]),W=k.useRef(typeof window>"u"?null:new URLSearchParams(window.location.search).get("session")),[N,U]=k.useState(W.current),[K,fe]=k.useState(!0),Qe=k.useRef(W.current),ve=k.useRef(typeof window>"u"?null:new URLSearchParams(window.location.search).get("_notifTrace"));b.useEffect(()=>{if(typeof window>"u")return;const C=window.matchMedia("(min-width: 1024px)"),P=()=>{Zr(C.matches),Pr(window.innerWidth)};return P(),C.addEventListener("change",P),window.addEventListener("resize",P),()=>{C.removeEventListener("change",P),window.removeEventListener("resize",P)}},[]),b.useEffect(()=>{if(typeof window>"u")return;const C=window.matchMedia("(orientation: landscape)"),P=()=>ps(C.matches);return P(),C.addEventListener("change",P),()=>C.removeEventListener("change",P)},[]);const lt=k.useMemo(()=>Ct?ot.find(C=>C.sessionIds.includes(Ct))??null:null,[Ct,ot]),vt=lt?.id??null,br=lt?.sessionIds[0]??Ct,Lt=k.useRef([]);k.useLayoutEffect(()=>{const C=Lt.current;if(Lt.current=ot,C.length===0)return;const P=new Set(ot.flatMap(de=>de.sessionIds));for(const de of C){const rt=de.sessionIds.filter(At=>!P.has(At)).map(At=>({sessionId:At,rootPath:Yr.getState().sessions.get(At)?.cwd??null}));rt.length>0&&Wt.getState().inheritRightSidebarStateFromSplitWorkspace(de.id,rt)}},[ot]),k.useLayoutEffect(()=>((()=>{const P=br?Yr.getState().sessions.get(br)?.cwd??null:null;Wt.getState().setRootPath(P,br,vt)})(),Yr.subscribe((P,de)=>{const rt=br?P.sessions.get(br)?.cwd??null:null,At=br?de.sessions.get(br)?.cwd??null:null;rt!==At&&Wt.getState().setRootPath(rt,br,vt)})),[vt,br]);const rn=k.useRef(Xy(window.location.search)??rC(Sc()?.targetPeerId)),[yn,hn]=k.useState("");k.useEffect(()=>{const C=rn.current;if(!C)return;if(C.peerId&&C.peerId!==Sc()?.targetPeerId){const rt=H9().find(At=>At.targetPeerId===C.peerId);if(rt&&Po()){try{tC(C)}catch{hn(t==="zh"?"无法在此浏览器打开架构链接。":"Cannot open this architecture link in this browser.");return}if(W9(rt)){rn.current=null;const At=new URL(window.location.href);At.searchParams.delete("architecture"),window.history.replaceState(window.history.state,"",At);return}}hn(t==="zh"?`此架构属于 ${C.serviceName??C.peerId}。请先连接该 Termdock 服务,再打开链接。`:`This architecture belongs to ${C.serviceName??C.peerId}. Connect to that Termdock service, then open this link.`);return}hn("");try{sessionStorage.setItem(`termdock.architecture.selection:${C.root}`,C.file)}catch{}const P=Wt.getState();P.setRootPath(C.root,br,vt),P.setRightTab("architecture"),P.openRight();const de=new URL(window.location.href);de.searchParams.delete("architecture"),window.history.replaceState(window.history.state,"",de),br&&(rn.current=null)},[br,vt,t]);const Dn=Xt||Hr,zn=Jt*.95,hr=Dn?Math.min(Math.max(Jt*.22,280),340):Math.min(Jt*.86,380),jt=Ct&&Er?`${Ct}\0${Er}`:"",Bn=!!(jt&&mt&&H[jt]),qn=b.useCallback(C=>{jt&&(C&&!Wt.getState().selectedFilePath||ae(P=>{if(!!P[jt]===C)return P;if(C)return Bm({...P,[jt]:{updatedAt:Date.now()}});const rt={...P};return delete rt[jt],rt}))},[jt]);b.useEffect(()=>{eQ(jt,re,mt)&&ae(C=>{if(!C[jt])return C;const P={...C};return delete P[jt],P})},[jt,re,mt]);const Qn=Ot?"markdown-image-lightbox":wt?"markdown-outline":et?"right-sidebar-repo-picker":qr&&Bn?"right-sidebar-file-preview":Ke?"settings":qr&&!(zr&&Xt)?"right-sidebar":Cr&&!(mn&&Xt)?"left-sidebar":null,is=k.useRef(Qn),zi=k.useRef(Qn),da=k.useRef(!1),bs=k.useRef(!1),Ga=b.useCallback(()=>{if(typeof window>"u")return;const C=window.matchMedia("(hover: hover) and (pointer: fine)").matches;!Xt||!C||navigator.maxTouchPoints>0||window.setTimeout(()=>{window.dispatchEvent(new CustomEvent("focus-active-terminal-session"))},0)},[Xt]),So=b.useCallback(C=>{if(C==="markdown-image-lightbox"){It(!1),Ve(P=>P+1);return}if(C==="markdown-outline"){zt(!1),Kt(P=>P+1);return}if(C==="right-sidebar-file-preview"){zt(!1),Kt(P=>P+1),qn(!1),Ye(P=>P+1);return}if(C==="right-sidebar-repo-picker"){St(!1),Qt(P=>P+1);return}if(C==="settings"){_t(!1),ws(!1),ni(!1),cs(!1);return}if(C==="left-sidebar"){Wt.getState().closeLeft();return}zt(!1),Kt(P=>P+1),St(!1),Qt(P=>P+1),It(!1),Ve(P=>P+1),Wt.getState().closeRight()},[qn]),Hn=b.useCallback(C=>{if(!c&&typeof window<"u"&&is.current===C&&Su(window.history.state)===C){window.history.back();return}So(C)},[So,c]),ha=b.useCallback(()=>{_t(!1);const C=Wt.getState();C.closeRight(),C.openLeft()},[]),ms=b.useCallback(()=>{_t(!1);const C=Wt.getState();C.closeLeft(),C.openRight()},[]),Ia=b.useCallback(()=>{_t(!1);const C=Wt.getState();C.closeLeft(),C.openRight(),C.setRightTab("files"),C.openRightSearch()},[]),as=b.useCallback(()=>{const C=Wt.getState();if(C.leftPinned){C.setLeftPinned(!1),C.closeLeft();return}if(Cr){Hn("left-sidebar");return}ha()},[ha,Hn,Cr]),Va=b.useCallback(()=>{const C=Wt.getState();C.leftPinned?(C.setLeftPinned(!1),C.openLeft()):(C.setLeftPinned(!0),C.openLeft())},[]),Js=b.useCallback(()=>{const C=Wt.getState();C.setLeftPinned(!1),C.closeLeft()},[]),ei=b.useCallback(()=>{const C=Wt.getState();C.rightPinned?(C.setRightPinned(!1),C.openRight()):(C.setRightPinned(!0),C.openRight())},[]),Hs=b.useCallback(()=>{const C=Wt.getState();C.setRightPinned(!1),C.closeRight()},[]),qa=b.useRef(0),Is=b.useRef(0),fa=b.useRef(null),dl=b.useCallback(C=>{C.preventDefault(),qa.current=C.clientX,Is.current=Wt.getState().leftSidebarWidth;const P=rt=>{fa.current===null&&(fa.current=requestAnimationFrame(()=>{fa.current=null;const At=rt.clientX-qa.current;Wt.getState().setLeftSidebarWidth(Is.current+At)}))},de=()=>{window.removeEventListener("mousemove",P),window.removeEventListener("mouseup",de),fa.current!==null&&(cancelAnimationFrame(fa.current),fa.current=null),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",window.addEventListener("mousemove",P),window.addEventListener("mouseup",de)},[]),Ya=b.useRef(0),os=b.useRef(0),Ms=b.useRef(null),Hi=b.useCallback(C=>{C.preventDefault(),Ya.current=C.clientX;const P=Wt.getState(),de=P.leftPinned?P.leftSidebarWidth:0;os.current=Oh(P.rightSidebarWidth,window.innerWidth,de);const rt=Zt=>{Ms.current===null&&(Ms.current=requestAnimationFrame(()=>{Ms.current=null;const Nr=Ya.current-Zt.clientX,An=Wt.getState(),Nn=An.leftPinned?An.leftSidebarWidth:0;An.setRightSidebarWidth(Oh(os.current+Nr,window.innerWidth,Nn))}))},At=()=>{window.removeEventListener("mousemove",rt),window.removeEventListener("mouseup",At),Ms.current!==null&&(cancelAnimationFrame(Ms.current),Ms.current=null),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",window.addEventListener("mousemove",rt),window.addEventListener("mouseup",At)},[]),xi=b.useCallback(()=>{const C=Wt.getState();if(C.rightPinned){C.setRightPinned(!1),C.closeRight();return}if(qr){Hn("right-sidebar");return}ms()},[ms,Hn,qr]),bi=b.useCallback(()=>{!Bn&&!c&&typeof window<"u"&&is.current==="right-sidebar"&&Su(window.history.state)==="right-sidebar"&&(Kd("right-sidebar-file-preview"),zi.current="right-sidebar-file-preview"),qn(!0)},[Bn,c,qn]),hl=b.useCallback(()=>{Hn("right-sidebar-file-preview")},[Hn]),ti=b.useCallback(()=>{!et&&!c&&typeof window<"u"&&is.current==="right-sidebar"&&Su(window.history.state)==="right-sidebar"&&(Kd("right-sidebar-repo-picker"),zi.current="right-sidebar-repo-picker"),St(!0)},[et,c]),Uo=b.useCallback(()=>{Hn("right-sidebar-repo-picker")},[Hn]),pa=b.useCallback(()=>{!wt&&!c&&typeof window<"u"&&is.current&&Su(window.history.state)===is.current&&(Kd("markdown-outline"),zi.current="markdown-outline"),zt(!0)},[wt,c]),fl=b.useCallback(()=>{Hn("markdown-outline")},[Hn]),pl=b.useCallback(()=>{!c&&typeof window<"u"&&is.current&&Su(window.history.state)===is.current&&(Kd("markdown-image-lightbox"),zi.current="markdown-image-lightbox"),It(!0)},[c]),ls=b.useCallback(()=>{Hn("markdown-image-lightbox")},[Hn]),js=b.useCallback(()=>{!c&&typeof window<"u"&&is.current&&Su(window.history.state)===is.current&&(P$("settings"),zi.current="settings"),Wt.getState().closeAll(),_t(!0)},[c]),Ri=b.useCallback(()=>{Hn("settings")},[Hn]);b.useEffect(()=>{if(!Pe)return;const C=()=>js();return window.addEventListener("termdock:open-settings",C),()=>window.removeEventListener("termdock:open-settings",C)},[Pe,js]);const zo=b.useCallback(()=>{Ce(!0),ht.current!==null&&(window.clearTimeout(ht.current),ht.current=null)},[]),Dl=b.useCallback(()=>{ht.current!==null&&(window.clearTimeout(ht.current),ht.current=null),Ce(!1),bs.current=!0,Qh(),bs.current},[]);b.useEffect(()=>()=>{ht.current!==null&&window.clearTimeout(ht.current)},[]),b.useEffect(()=>{c||Qh()},[c]),b.useEffect(()=>{if(typeof window>"u"||c)return;let C=null;const P=()=>{C!==null&&(window.clearTimeout(C),C=null)},de=An=>{if(is.current,bs.current,is.current){is.current;return}!An?.force&&bs.current||(An?.userActivated&&(bs.current=!0),Qh(),bs.current,void 0)},rt=()=>{P(),C=window.setTimeout(()=>{C=null,de({force:!0})},fy)},At=()=>{de({userActivated:!0})},Zt=()=>{rt()},Nr=()=>{document.visibilityState==="visible"&&rt()};return window.addEventListener("pointerdown",At,{capture:!0,passive:!0}),window.addEventListener("touchstart",At,{capture:!0,passive:!0}),window.addEventListener("keydown",At,{capture:!0}),window.addEventListener("pageshow",Zt),document.addEventListener("visibilitychange",Nr),()=>{P(),window.removeEventListener("pointerdown",At,{capture:!0}),window.removeEventListener("touchstart",At,{capture:!0}),window.removeEventListener("keydown",At,{capture:!0}),window.removeEventListener("pageshow",Zt),document.removeEventListener("visibilitychange",Nr)}},[c]),b.useEffect(()=>{is.current=Qn},[Qn]),b.useEffect(()=>{if(typeof window>"u"||Qn||c)return;const C=window.setTimeout(()=>{is.current?(is.current,void 0):Qh()},fy);return()=>window.clearTimeout(C)},[Qn,c]),b.useEffect(()=>{if(typeof window>"u"||c)return;const C=zi.current;da.current,Qn&&Qn!==C&&!da.current&&Kd(Qn),!Qn&&C&&Ga(),zi.current=Qn,!Qn&&da.current&&window.setTimeout(()=>{da.current=!1},0)},[Qn,c,Ga]),b.useEffect(()=>{if(typeof window>"u"||c)return;const C=()=>{const P=is.current;if(bs.current,!P){bs.current=!1,bs.current,zo(),n4();return}da.current=!0,So(P)};return window.addEventListener("popstate",C),()=>window.removeEventListener("popstate",C)},[So,zo,c]),b.useEffect(()=>{const C=P=>{const de=P.metaKey||P.ctrlKey;if(de&&P.key==="b"&&!P.shiftKey&&(P.preventDefault(),as()),de&&P.shiftKey&&P.key==="E"&&(P.preventDefault(),xi()),de&&P.shiftKey&&P.key==="P"&&(P.preventDefault(),Ia()),de&&!P.shiftKey&&P.altKey&&(P.key==="ArrowLeft"||P.key==="ArrowRight")){P.preventDefault();const rt=P.key==="ArrowRight"?"next":"prev";window.dispatchEvent(new CustomEvent("cycle-terminal-session",{detail:{direction:rt}}));return}if(de&&P.shiftKey&&!P.altKey&&(P.code==="BracketLeft"||P.code==="BracketRight")){P.preventDefault();const rt=P.code==="BracketRight"?"next":"prev";window.dispatchEvent(new CustomEvent("cycle-terminal-session",{detail:{direction:rt}}));return}};return document.addEventListener("keydown",C),()=>{document.removeEventListener("keydown",C)}},[as,xi,Ia]);const Es=b.useCallback(async()=>{Y(!0),qe(null);try{const C=await La({localAccess:{name:ee}});pe(C.localAccess),_e(C.localAccess.name),Fn(qd,{preventSleep:C.preventSleep,networkAvailable:C.networkAvailable,localAccess:C.localAccess})}catch(C){qe(C instanceof Error?C.message:"Failed to save local access name")}finally{Y(!1)}},[ee]),Ea=b.useCallback(async()=>{Y(!0),qe(null);try{const C=await La({localAccess:{reset:!0}});pe(C.localAccess),_e(C.localAccess.name),Fn(qd,{preventSleep:C.preventSleep,networkAvailable:C.networkAvailable,localAccess:C.localAccess})}catch(C){qe(C instanceof Error?C.message:"Failed to reset local access name")}finally{Y(!1)}},[]),ml=b.useCallback(async(C,P="url")=>{if(C)try{if(typeof navigator<"u"&&navigator.clipboard)await navigator.clipboard.writeText(C);else{const de=document.createElement("textarea");de.value=C,de.style.position="fixed",de.style.left="-9999px",document.body.appendChild(de),de.focus(),de.select(),document.execCommand("copy"),document.body.removeChild(de)}ye(P),window.setTimeout(()=>ye(de=>de===P?null:de),1600)}catch{ye(null)}},[]),es=b.useCallback(C=>{const P=F$(yt,C);P.map(de=>de.id).join("\0")!==yt.map(de=>de.id).join("\0")&&(xt(P),window.dispatchEvent(new CustomEvent("reorder-terminal-session",{detail:{sessionIds:P.map(de=>de.id)}})))},[yt]),Wi=b.useCallback(C=>{Xt||C.type!=="session"||(G.current=!1,kr(!1),gn(C.draggableId))},[Xt]),Mi=b.useCallback(C=>{if(Xt||C.type!=="session")return;const P=C.destination?.droppableId===M1;P!==G.current&&(G.current=P,kr(P),P&&navigator.vibrate?.(20))},[Xt]),Gi=b.useCallback(C=>{const P=S$(C,!Xt);if(G.current=!1,kr(!1),gn(null),!P)return!1;const de=yt.find(At=>At.id===C.draggableId),rt=de?ir.get(de.id):null;return de&&P5({mode:de.mode,activeProgram:rt?.activeProgram??null,promptState:rt?.promptState??null,shellNames:_a})?(it(null),$e(de.id),He(null)):de&&window.dispatchEvent(new CustomEvent("close-terminal-session",{detail:{sessionId:de.id,source:"other",closeMode:de.mode==="tmux"?"destroy":"auto"}})),!0},[Xt,yt,ir]),{groups:gs,arranged:Ws}=k.useMemo(()=>cf(yt,C=>ir.get(C.id)?.cwd??null,Mt,e("sidebar.ungrouped"),ot,rr),[yt,ir,Mt,e,ot,rr]),Bl=b.useCallback(C=>{Gi(C)||!C.destination||C.source.index===C.destination.index||window.dispatchEvent(new CustomEvent("reorder-navigation-session",{detail:{sourceId:Ws[C.source.index]?.id,targetId:Ws[C.destination.index]?.id}}))},[Gi,Ws]),Vi=b.useCallback((C,P)=>{const de=P.trim();de&&window.dispatchEvent(new CustomEvent("rename-terminal-session",{detail:{sessionId:C,name:de}}))},[]),qi=b.useCallback(C=>{window.dispatchEvent(new CustomEvent("reset-terminal-session-name",{detail:{sessionId:C}}))},[]),{newSessionMode:fn,newSessionTmuxName:ma,userSelectedNewSessionMode:Yi,setNewSessionMode:Na}=KB(),[ji,Di]=b.useState(null),[ri,ws]=k.useState(!1),[Gs,Bi]=k.useState(!1),[Ra,ni]=k.useState(!1),[ys,Za]=k.useState("idle"),Ka=k.useRef(Tc(Bh,I$)).current,[As,Xa]=k.useState(()=>{const C=Ka?.presets;if(C&&C.length>0){const P=Ru(C);if(P.length>0)return P}return w0()}),[Ql,Ho]=k.useState(!1),[Co,ga]=k.useState("default"),Ma=k.useRef(typeof Ka?.updatedAt=="number"?Ka.updatedAt:null),Wo=k.useRef(!1),[xa,cs]=k.useState(!1),[Go,Zi]=k.useState(!1),gl=k.useRef(Tc(Ca,L$)).current,[se,T]=k.useState(gl??[]),[j,Q]=k.useState(gl!==null),[F,ge]=k.useState(!1),Se=!Rt&&!Qn&&!Gs&&!Ra&&!ri&&!xa&&!Go&&!cr&&!Me&&!ji,Oe=k.useCallback(C=>{const P=typeof C.version=="number"?C.version:0,de=E$(Array.isArray(C.presets)?C.presets:[],P);Ma.current=typeof C.updatedAt=="number"?C.updatedAt:null,Xa(rt=>G9(rt,de)?rt:(Wo.current=!0,de)),Fn(Bh,{version:e0,presets:de,updatedAt:Ma.current??void 0})},[]);b.useEffect(()=>{const C=P=>{if(P.key!=="Escape"||P.defaultPrevented||P.isComposing||B1())return;if(Gs){P.preventDefault(),Bi(!1);return}if(Ra){P.preventDefault(),ni(!1);return}if(ri){P.preventDefault(),ws(!1);return}if(xa){P.preventDefault(),cs(!1);return}if(Go){P.preventDefault(),Zi(!1);return}if(cr){P.preventDefault(),Bt();return}if(dn){P.preventDefault(),jr(null),_r(null);return}if(Ke){P.preventDefault(),Ri();return}if(qr&&!(zr&&Xt)){P.preventDefault(),Hn("right-sidebar");return}Cr&&!(mn&&Xt)&&(P.preventDefault(),Hn("left-sidebar"))};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[Gs,Ra,ri,xa,cr,Bt,Ke,qr,zr,Cr,mn,Xt,Ri,Hn]),b.useEffect(()=>{Q(!0)},[]);const[Xe,dt]=k.useState({genericProgramNames:[],wrapperScriptNames:[],shellNames:s4}),[,er]=k.useState(!1),or=k.useCallback(()=>V9().then(C=>{dt(C),_a=new Set(C.shellNames),er(!0)}).catch(()=>{}),[]);b.useEffect(()=>{or()},[or]),b.useEffect(()=>ux(C=>{if(C.type==="config-updated"){if(C.key==="toolbar-presets"){dx().then(P=>Oe(P)).catch(P=>{console.warn("[toolbar-presets] Failed to refresh after remote update:",P)});return}C.key==="program-detection"&&or()}}),[Oe,or]),b.useEffect(()=>{let C=!1;return(async()=>{try{const P=await dx();if(C)return;Oe(P)}catch(P){console.warn("[toolbar-presets] Failed to load from server:",P)}finally{C||Ho(!0)}})(),()=>{C=!0}},[Oe]),b.useEffect(()=>{if(Ql){if(Wo.current){Wo.current=!1;return}Fn(Bh,{version:e0,presets:As,updatedAt:Ma.current??void 0}),q9({version:e0,presets:As,baseUpdatedAt:Ma.current??void 0}).then(C=>{Ma.current=typeof C.updatedAt=="number"?C.updatedAt:null,Fn(Bh,{version:e0,presets:As,updatedAt:Ma.current??void 0})}).catch(C=>{const P=C instanceof Error&&"current"in C?C.current:null;P&&typeof P=="object"&&Oe(P),console.warn("[toolbar-presets] Failed to save to server:",C)})}},[Oe,As,Ql]),b.useEffect(()=>{fc().then(C=>{w(P=>P===C.preventSleep?P:C.preventSleep),S(P=>P===C.networkAvailable?P:C.networkAvailable),pe(C.localAccess),_e(C.localAccess.name),pr(C.runningSessionButtonEnabled),Fn(Yd,C.runningSessionButtonEnabled),En(C.attentionButtonEnabled),Fn(Zd,C.attentionButtonEnabled),Fn(qd,{preventSleep:C.preventSleep,networkAvailable:C.networkAvailable,localAccess:C.localAccess})}).catch(()=>{})},[]),b.useEffect(()=>{if(!L)return;const C=Tp();le(C),C!=="granted"&&(E(!1),th(!1))},[L]),b.useEffect(()=>{if(!L)return;pd();const C=()=>{document.visibilityState==="visible"&&(pd(),oA())},P=window.setInterval(()=>{pd()},360*60*1e3);return document.addEventListener("visibilitychange",C),window.addEventListener("focus",C),()=>{window.clearInterval(P),document.removeEventListener("visibilitychange",C),window.removeEventListener("focus",C)}},[L]);const $r=b.useCallback(async()=>{if(L){E(!1),th(!1),Y9(),le(Tp());return}const C=await Z9();if(le(C),C!=="granted"){E(!1),th(!1);return}E(!0),th(!0),await pd(!0,!0),Za("idle")},[L]),nn=b.useCallback(async()=>{Za("checking"),await vo()?.prepareNotificationTest?.();const C=await K9({title:"Termdock",body:e("settings.notificationsTestBody"),tag:"termdock-notification-test",requireHidden:!1,data:{url:"/"}});Za(C?"delivered":"failed")},[e]),Pn=b.useCallback(C=>{B(C),X9(C),Sp()},[]),yr=b.useCallback(C=>{O(C),J9(C),Sp()},[]),wn=b.useCallback(C=>{V(C),eA(C),Sp()},[]);b.useEffect(()=>{As.some(C=>C.id===Co)||ga(As[0]?.id??"default")},[Co,As]),b.useEffect(()=>{if(!Tr.available&&fn==="tmux"){Na("shell",{userInitiated:!1});return}Tr.available&&Yi!=="shell"&&fn!=="tmux"&&Na("tmux",{userInitiated:!1})},[fn,Tr.available,Yi,Na]),b.useEffect(()=>{Di(null)},[Ke,fn,Tr.available]),b.useEffect(()=>{const C={};typeof navigator<"u"&&(C.userAgent=navigator.userAgent,C.platform=navigator.platform,C.maxTouchPoints=navigator.maxTouchPoints,C.hasTouch=navigator.maxTouchPoints>0||"ontouchstart"in window,C.vendor=navigator.vendor),typeof window<"u"&&(C.screenWidth=window.innerWidth,C.screenHeight=window.innerHeight,C.pixelRatio=window.devicePixelRatio,C.orientation=window.screen?.orientation?.type||"unknown",C.hasVisualViewport=!!window.visualViewport,C.visualViewportHeight=window.visualViewport?.height,C.visualViewportWidth=window.visualViewport?.width,C.location=window.location.href),C.timestamp=new Date().toISOString(),C.isIOS=/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,C.isAndroid=/Android/.test(navigator.userAgent),ut(C)},[]);const us=b.useCallback(C=>{if(Gi(C)||!C.destination)return;if(C.type==="group"){if(C.source.index===C.destination.index)return;es(Vy(gs,C.source.index,C.destination.index));return}if(C.source.droppableId!==C.destination.droppableId||C.source.index===C.destination.index)return;const P=C.source.droppableId.replace(/^group-sessions:/,""),de=gs.find(rt=>rt.key===P);de&&window.dispatchEvent(new CustomEvent("reorder-navigation-session",{detail:{sourceId:de.sessions[C.source.index]?.id,targetId:de.sessions[C.destination.index]?.id}}))},[gs,es,Gi]),Ds=k.useMemo(()=>Ws.flatMap(C=>{const P=ir.get(C.id);if(P?.agentStatus!=="working")return[];const{primary:de,secondary:rt}=il(C,P?.activeProgram??null,P?.cwd??null,_a,P?.shellTitle??null,P?.promptState??null);return[{id:C.id,label:de,detail:rt}]}),[Ws,ir]),pc=Ct?Ws.findIndex(C=>C.id===Ct):-1,Vs=Ws.length>0&&pc>=0?`${pc+1}/${Ws.length}`:`${Ws.length}`,Ki=k.useMemo(()=>{let C=0;for(const P of yt){const de=ir.get(P.id);(de?.agentStatus==="waiting"||de?.agentNeedsReview)&&(C+=1)}return{running:Ds.length,review:C}},[Ds.length,yt,ir]),_o=k.useMemo(()=>Ws.flatMap(C=>{const P=ir.get(C.id);if(P?.agentStatus!=="waiting"&&!P?.agentNeedsReview)return[];const{primary:de}=il(C,P.activeProgram,P.cwd,_a,P.shellTitle,P.promptState);return[{id:P.terminalSessionId??C.id,label:de,waiting:P.agentStatus==="waiting"}]}),[Ws,ir]);tA(Ki.running,Ki.review,_o);const yi=Ct?yt.find(C=>C.id===Ct)??null:null,ko=yi?ir.get(yi.id):void 0,tu=!!(yi&&ko?.agentResumeRecovered&&ko.agentNativeSessionId&&ko.terminalSessionId),vi=yi&&pn?.sessionId===yi.id?pn:null;k.useLayoutEffect(()=>{if(!K)return;const C=Dt.current;if(!C)return;const P=!ft.current;C.scrollIntoView({inline:"nearest",block:"nearest",behavior:P?"auto":"smooth"}),ft.current=!0,P&&Mu("active-tab-positioned")},[Ct,K]),b.useEffect(()=>{tr&&Tt.current&&(Tt.current.scrollIntoView({block:"nearest",inline:"nearest"}),Tt.current.focus(),Tt.current.select()),tr||(kt.current=!1)},[tr]);const F0=b.useCallback(C=>{window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:C}))},[]),wi=b.useCallback((C,P)=>{Xn(P??null),Cn(C)},[]),sd=Cg(),Ja=b.useCallback(C=>{if(!C)return;U(C),ve.current&&ka("info","PWA_NOTIFICATION_CLICK app-focus-request",{traceId:ve.current,requestedSessionId:C,activeSessionId:Ct,sessions:yt.map(de=>({id:de.id,terminalSessionId:ir.get(de.id)?.terminalSessionId??null}))}),rA(C);const P=yt.find(de=>de.id===C||ir.get(de.id)?.terminalSessionId===C);P?(Qe.current=null,ve.current&&ka("info","PWA_NOTIFICATION_CLICK app-focus-dispatch",{traceId:ve.current,requestedSessionId:C,targetSessionId:P.id}),window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:P.id}))):(Qe.current=C,ve.current&&ka("info","PWA_NOTIFICATION_CLICK app-focus-pending",{traceId:ve.current,requestedSessionId:C}))},[Ct,yt,ir]);b.useEffect(()=>{if(typeof window>"u"||typeof caches>"u")return;let C=!1;const P=async()=>{if(window.parent!==window&&Po()){fe(!0);return}try{const rt=await caches.open(j$),At=await rt.match(py);if(!At)return;await rt.delete(py);const Zt=await At.json();if(C)return;const Nr=typeof Zt.sessionId=="string"?Zt.sessionId:null,An=typeof Zt.traceId=="string"?Zt.traceId:null,Nn=typeof Zt.clickedAt=="number"?Zt.clickedAt:0,Ln=Date.now()-Nn;ka("info","PWA_NOTIFICATION_CLICK app-cache-consumed",{traceId:An,sessionId:Nr,ageMs:Ln,valid:!!(Nr&&Ln>=0&&Ln<=my),visibilityState:document.visibilityState}),Nr&&Ln>=0&&Ln<=my&&(ve.current=An,typeof Zt.targetPeerId=="string"&&Zt.targetPeerId!==Sc()?.targetPeerId?Po()?.focusSession(Zt.targetPeerId,Nr):Ja(Nr))}catch(rt){ka("warn","PWA_NOTIFICATION_CLICK app-cache-failed",{error:rt instanceof Error?rt.message:String(rt)})}finally{C||fe(!0)}},de=()=>{document.visibilityState==="visible"&&P()};return P(),document.addEventListener("visibilitychange",de),window.addEventListener("pageshow",P),()=>{C=!0,document.removeEventListener("visibilitychange",de),window.removeEventListener("pageshow",P)}},[Ja]),b.useEffect(()=>{if(typeof window>"u")return;const C=new URLSearchParams(window.location.search),P=C.get("session");if(!P)return;ka("info","PWA_NOTIFICATION_CLICK app-url-received",{traceId:ve.current,targetSessionId:P,href:window.location.href,visibilityState:document.visibilityState});const de=C.get("service");de&&de!==Sc()?.targetPeerId?Po()?.focusSession(de,P):Qe.current=P,C.delete("service"),C.delete("session"),C.delete("_notifTrace");const rt=C.toString(),At=`${window.location.pathname}${rt?`?${rt}`:""}${window.location.hash}`;window.history.replaceState(window.history.state,"",At)},[]),b.useEffect(()=>{if(typeof window>"u")return;const C=new URLSearchParams(window.location.search);if(C.get("_notif")!=="1")return;const P=C.get("session");C.delete("_notif");const de=C.toString(),rt=`${window.location.pathname}${de?`?${de}`:""}${window.location.hash}`;if(window.history.replaceState(window.history.state,"",rt),window.parent!==window&&Po())return;const At=new BroadcastChannel("termdock:notif");let Zt=!1;const Nr=Nn=>{Nn.data?.type==="termdock:notif-pong"&&!Zt&&(Zt=!0,At.close(),window.close())};At.addEventListener("message",Nr),At.postMessage({type:"termdock:notif-ping",sessionId:P,targetPeerId:C.get("service")});const An=setTimeout(()=>{Zt||At.close()},500);return()=>{clearTimeout(An),Zt||At.close()}},[]),b.useEffect(()=>{if(typeof window>"u"||window.parent!==window&&Po())return;const C=new BroadcastChannel("termdock:notif"),P=de=>{de.data?.type==="termdock:notif-ping"&&(C.postMessage({type:"termdock:notif-pong"}),typeof de.data.sessionId=="string"&&(typeof de.data.targetPeerId=="string"&&de.data.targetPeerId!==Sc()?.targetPeerId?Po()?.focusSession(de.data.targetPeerId,de.data.sessionId):Ja(de.data.sessionId)))};return C.addEventListener("message",P),()=>C.close()},[Ja]),b.useEffect(()=>{if(typeof navigator>"u"||!("serviceWorker"in navigator))return;const C=P=>{const de=P.data;if(de&&de.type==="termdock:focus-session"&&typeof de.sessionId=="string"){if(typeof de.targetPeerId=="string"&&de.targetPeerId!==Sc()?.targetPeerId){Po()?.focusSession(de.targetPeerId,de.sessionId)&&P.ports[0]?.postMessage({type:"termdock:focus-session-ack"});return}P.ports[0]?.postMessage({type:"termdock:focus-session-ack"}),Ja(de.sessionId)}else de?.type==="termdock:push-subscription-changed"?pd(!0):de?.type};return navigator.serviceWorker.addEventListener("message",C),()=>navigator.serviceWorker.removeEventListener("message",C)},[Ja]),b.useEffect(()=>{const C=P=>{const de=P.detail;typeof de=="string"&&Ja(de)};return window.addEventListener("termdock:focus-session",C),()=>window.removeEventListener("termdock:focus-session",C)},[Ja]),b.useEffect(()=>{const C=()=>{const P=lA(Sc()?.targetPeerId);P&&Ja(P)};return C(),window.addEventListener("termdock:workspace-session",C),()=>window.removeEventListener("termdock:workspace-session",C)},[Ja]),b.useEffect(()=>{const C=Qe.current;if(!C)return;const P=yt.find(de=>de.id===C||ir.get(de.id)?.terminalSessionId===C);P?(Qe.current=null,ve.current&&ka("info","PWA_NOTIFICATION_CLICK app-pending-dispatch",{traceId:ve.current,requestedSessionId:C,targetSessionId:P.id,activeSessionId:Ct}),window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:P.id}))):ve.current&&ka("info","PWA_NOTIFICATION_CLICK app-pending-unmatched",{traceId:ve.current,requestedSessionId:C,activeSessionId:Ct,sessions:yt.map(de=>({id:de.id,terminalSessionId:ir.get(de.id)?.terminalSessionId??null}))})},[Ct,yt,ir]);const ba=k.useMemo(()=>{const C=[];for(const P of yt){const de=ir.get(P.id);(de?.agentStatus==="waiting"||de?.agentNeedsReview)&&C.push(P.id)}return C},[yt,ir]),Pl=b.useCallback(()=>{if(ba.length===0)return;Ct&&Yr.getState().clearAgentNeedsReview(Ct);const C=Ct?yt.findIndex(de=>de.id===Ct):-1,P=ba.find(de=>yt.findIndex(rt=>rt.id===de)>C)??ba[0];P&&window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:P}))},[ba,yt,Ct]),ru=b.useCallback(()=>{if(ba.length===0)return;Ct&&Yr.getState().clearAgentNeedsReview(Ct);const C=Ct?yt.findIndex(de=>de.id===Ct):yt.length,P=[...ba].reverse().find(de=>yt.findIndex(rt=>rt.id===de)<C)??ba[ba.length-1];P&&window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:P}))},[ba,yt,Ct]);b.useEffect(()=>{const C=P=>{!P.altKey||!P.shiftKey||P.metaKey||P.ctrlKey||P.key!=="ArrowUp"&&P.key!=="ArrowDown"||(P.preventDefault(),P.key==="ArrowUp"?ru():Pl())};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[Pl,ru]);const ap=b.useCallback(async C=>{const de=Yr.getState().sessions.get(C)?.cwd;if(de)try{await navigator.clipboard?.writeText(de),Gn(de),window.setTimeout(()=>{Gn(rt=>rt===de?null:rt)},1400)}catch{}},[]),op=b.useCallback(C=>{xt(C.sessions),fr(C.activeSessionId),pt(C.splitWorkspaces),Yr.getState().setActiveSessionId(C.activeSessionId)},[]),lp=b.useCallback(()=>{Sr(!0)},[]),cp=b.useCallback(()=>{Sr(!0),window.requestAnimationFrame(()=>{window.dispatchEvent(new Event("termdock:initial-viewport-presented"))})},[]);b.useEffect(()=>{if(!N||!Ct)return;yt.find(P=>P.id===N||ir.get(P.id)?.terminalSessionId===N)?.id===Ct&&U(null)},[Ct,N,yt,ir]);const id=b.useRef(!1),[nu,$0]=b.useState(!1),ja=b.useCallback(C=>{const P=!C?.onResult;if(P&&id.current)return;P&&(id.current=!0,$0(!0));const de=C?.mode??fn,rt=de==="tmux"&&(C?.tmuxSessionName?.trim()||ma.trim())||void 0,At=C?.cwd||(Ct?Yr.getState().sessions.get(Ct)?.cwd:void 0);window.dispatchEvent(new CustomEvent("new-terminal-session",{detail:{mode:de,tmuxSessionName:rt,cwd:At,command:C?.command,shouldActivate:C?.shouldActivate,onResult:C?.onResult??(Zt=>{id.current=!1,$0(!1),Zt.ok||Gr({tone:"error",message:e(zm(Zt.error))})})}}))},[fn,ma,Ct,e]),Vo=b.useCallback(async()=>{Qr(!0);try{const C=await Qm();if(Jr(C),!C.available){jn([]);return}const P=await Pm();jn(P)}catch{Jr({available:!1,version:null,reason:"tmux integration is unavailable with the current server build."}),jn([])}finally{Qr(!1)}},[]),mc=b.useCallback(async C=>{const{cleanedSessions:P}=await Ty(C);for(const de of P)window.dispatchEvent(new CustomEvent("close-terminal-session-by-backend",{detail:de}));await Vo()},[Vo]),su=b.useCallback(async C=>{xn(C),He(null);try{await mc(C),Dr(null)}catch(P){He(P instanceof Error?P.message:"Failed to kill tmux session")}finally{xn(null)}},[mc]);b.useEffect(()=>{if(!Nt)return;if(Mr.find(de=>de.name===Nt&&(de.connected||de.boundFrontendSessionId))){Et(null);return}const P=setTimeout(()=>Et(null),1e4);return()=>clearTimeout(P)},[Nt,Mr]);const gc=b.useCallback(C=>{window.dispatchEvent(new CustomEvent("close-terminal-session",{detail:C}))},[]),iu=b.useCallback(C=>{const P=C??Ct;P&&window.dispatchEvent(new CustomEvent("open-terminal-split-chooser",{detail:P}))},[Ct]),ad=b.useCallback((C,P)=>{window.dispatchEvent(new CustomEvent("set-terminal-split-direction",{detail:{sessionId:C,layout:P}}))},[]),U0=b.useCallback((C,P)=>{window.dispatchEvent(new CustomEvent("reorder-terminal-split-workspace",{detail:{workspaceId:C,sessionIds:P}}))},[]),z0=b.useCallback((C,P)=>{window.dispatchEvent(new CustomEvent("rename-terminal-split-workspace",{detail:{workspaceId:C,name:P}}))},[]),H0=b.useCallback((C,P)=>{window.dispatchEvent(new CustomEvent("combine-terminal-split-sessions",{detail:{primaryId:C,secondaryId:P}}))},[]),Ol=b.useCallback((C,P,de)=>{const rt=yt.find(Zt=>Zt.id===C);if(!rt)return;const At=ir.get(C);if(de?.skipConfirmation||!P5({mode:rt.mode,activeProgram:At?.activeProgram??null,promptState:At?.promptState??null,shellNames:_a})){gc({sessionId:C,source:"sidebar",closeMode:rt.mode==="tmux"?"destroy":"auto"});return}it(P?{x:P.clientX,y:P.clientY}:null),$e(C),He(null)},[yt,ir,gc]);b.useEffect(()=>{if(!Pe)return;const C=P=>{const de=P.detail;de==="new-session"?ja():de==="close-session"?Ct&&Ol(Ct):de==="previous-session"||de==="next-session"?window.dispatchEvent(new CustomEvent("cycle-terminal-session",{detail:{direction:de==="next-session"?"next":"prev"}})):de==="toggle-left-sidebar"?as():de==="toggle-right-sidebar"?xi():de==="previous-attention"?ru():de==="next-attention"&&Pl()};return window.addEventListener("termdock:native-command",C),()=>window.removeEventListener("termdock:native-command",C)},[Ct,Pe,ja,Ol,as,xi,Pl,ru]);const eo=k.useMemo(()=>yt.find(C=>C.id===Me)??null,[yt,Me]),od=b.useCallback(()=>{eo&&(gc({sessionId:eo.id,source:"sidebar",closeMode:"destroy"}),$e(null),it(null))},[eo,gc]);b.useEffect(()=>{if(!eo)return;const C=P=>{if(P.key==="Escape"){P.preventDefault(),P.stopImmediatePropagation(),$e(null),it(null),He(null);return}P.key!=="Enter"||P.isComposing||P.keyCode===229||P.altKey||P.ctrlKey||P.metaKey||P.shiftKey||(P.preventDefault(),P.stopImmediatePropagation(),P.repeat||od())};return window.addEventListener("keydown",C,!0),()=>window.removeEventListener("keydown",C,!0)},[eo,od]);const W0=k.useMemo(()=>{if(!eo)return"";const C=ir.get(eo.id);return il(eo,C?.activeProgram??null,C?.cwd??null,_a,C?.shellTitle??null,C?.promptState??null).primary},[eo,ir]);b.useEffect(()=>{if(!Ke)return;let C=!1,P=!1;const de=async()=>{if(!P)try{const At=await Qm();if(C||Jr(At),!At.available){C||jn([]);return}const Zt=await Pm();C||jn(Zt)}catch{P=!0,C||(Jr({available:!1,version:null,reason:"tmux integration is unavailable with the current server build."}),jn([]))}};de();const rt=setInterval(()=>{de()},4e3);return()=>{C=!0,clearInterval(rt)}},[Ke]);const xc=ji??fn,Fl=xc==="shell",au=xc==="tmux"&&Tr.available,xl=k.useMemo(()=>Gy(Mr.map(C=>({...C,id:C.name})),C=>C.cwd??null,e("sidebar.ungrouped")),[Mr,e]),ld=k.useMemo(()=>Mr.filter(C=>C.recoveryCandidate===!0&&!C.connected&&!C.boundFrontendSessionId).sort((C,P)=>(P.lastActiveAt??P.createdAt??0)-(C.lastActiveAt??C.createdAt??0)),[Mr]);b.useEffect(()=>{!Cr&&!(mn&&Xt)||Vo()},[Cr,mn,Xt,yt.length,Vo]);const bc=(C,P,de,rt=!1)=>{const At=C.id===Ct,Zt=C.id===tr,Nr=ir.get(C.id),{primary:An,secondary:Nn}=il(C,Nr?.activeProgram??null,Nr?.cwd??null,_a,Nr?.shellTitle??null,Nr?.promptState??null),Ln=Ku(Nr?.cwd??null),Ai=P?Nn??(Ln&&Ln!==An?Ln:null):null,Tn=Nr?.gitStatus,Xi=`${Nr?.cwd||C.name}${Tn?`
|
|
185
|
+
}`}),R&&s.jsx("div",{className:"whitespace-pre-wrap break-words text-[10px] text-[color:var(--warning)]",children:R}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("button",{type:"button",onClick:()=>{Ce()},className:"flex items-center gap-1 rounded-full bg-[rgb(var(--success-rgb)_/_0.14)] px-3 py-1 text-[11px] font-medium text-[color:var(--success)] hover:bg-[rgb(var(--success-rgb)_/_0.22)] transition",children:[s.jsx(tT,{size:11}),e("settings.agentPluginCreate")]}),s.jsx("button",{type:"button",onClick:()=>{x(!1),E(""),B(null)},className:"rounded-full px-3 py-1 text-[11px] text-muted-foreground hover:text-foreground transition",children:e("common.cancel")})]})]})]})]})}function g$({state:e,pending:t,onCheck:r,onConfirmRestart:n,desktopState:a,desktopPending:c=!1,desktopSnapshot:l,desktopActions:d,onCheckDesktop:p,onInstallDesktop:m}){const{t:x}=Ur(),y=e?.status??"idle",w=t||y==="checking"||y==="installing"||y==="restarting",v=y==="ready"&&!!e?.latestVersion,S=y==="checking"?x("settings.updateChecking"):y==="installing"?x("sidebar.updateInstalling"):y==="ready"?x("sidebar.updateReady"):y==="restarting"?x("sidebar.updateRestarting"):y==="current"?x("settings.updateCurrent"):y==="error"?e?.error||x("sidebar.updateFailed"):x("settings.updateHint"),L=a?.currentVersion||l?.appVersion,E=a?.status??"idle",R=c||E==="checking"||E==="downloading"||E==="installing",B=E==="ready",z=a?.error||(E==="unsupported"?x("settings.desktopUpdateUnsupported"):E==="checking"?x("settings.desktopUpdateChecking"):E==="current"?x("settings.desktopUpdateCurrent"):E==="downloading"?x("settings.desktopUpdateDownloading"):E==="ready"?x("settings.desktopUpdateReady"):E==="installing"?x("settings.desktopUpdateInstalling"):E==="error"&&a?.error||x("settings.desktopUpdateHint"));return s.jsxs("section",{className:"mt-3 overflow-hidden rounded-xl bg-surface-2","aria-labelledby":"termdock-update-title",children:[s.jsx("div",{id:"termdock-update-title",className:"px-3 pt-3 text-[12px] font-semibold text-foreground",children:x("settings.updateTitle")}),s.jsxs("div",{className:"flex items-start justify-between gap-3 px-3 py-3",children:[s.jsxs("div",{className:"flex min-w-0 items-start gap-2.5",children:[s.jsx("span",{className:`mt-0.5 inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${v?"bg-[rgb(var(--warning-rgb)_/_0.16)] text-[color:var(--warning)]":"bg-primary/15 text-primary"}`,children:s.jsx(bn,{size:15,className:w?"animate-spin":""})}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12px] font-medium text-foreground",children:x("settings.updateRuntimeTitle")}),s.jsx("div",{className:"mt-0.5 text-[10px] leading-relaxed text-muted-foreground",children:S}),e&&s.jsx("div",{className:"mt-1 text-[10px] tabular-nums text-muted-foreground/75",children:v&&e.latestVersion?`${e.currentVersion} → ${e.latestVersion}`:`v${e.currentVersion}`})]})]}),v?s.jsx("button",{type:"button",disabled:w,onClick:n,className:"shrink-0 rounded-full bg-[var(--warning)] px-3 py-1.5 text-[11px] font-semibold text-[color:var(--bg)] transition hover:opacity-90 disabled:cursor-wait disabled:opacity-60",children:x("sidebar.updateRestart")}):s.jsx("button",{type:"button",disabled:w,onClick:r,className:"shrink-0 rounded-full bg-surface px-3 py-1.5 text-[11px] font-medium text-foreground transition hover:bg-surface-elevated disabled:cursor-wait disabled:opacity-60",children:x(y==="checking"?"settings.updateCheckingShort":y==="installing"?"settings.updateInstallingShort":y==="error"?"sidebar.updateRetry":y==="current"?"settings.updateCheckAgain":"settings.updateCheck")})]}),(a||d)&&s.jsxs("div",{className:"flex items-start justify-between gap-3 border-t border-border/10 px-3 py-3",children:[s.jsxs("div",{className:"flex min-w-0 items-start gap-2.5",children:[s.jsx("span",{className:`mt-0.5 inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${B?"bg-[rgb(var(--warning-rgb)_/_0.16)] text-[color:var(--warning)]":"bg-primary/15 text-primary"}`,children:s.jsx(bn,{size:15,className:R?"animate-spin":""})}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12px] font-medium text-foreground",children:x("settings.desktopUpdateTitle")}),s.jsx("div",{className:`mt-0.5 text-[10px] leading-relaxed ${a?.error?"text-destructive":"text-muted-foreground"}`,role:a?.error?"alert":void 0,children:a?z:x(p?"settings.desktopStatusLoading":"settings.desktopUpdateUnsupported")}),s.jsx("div",{className:"mt-1 text-[10px] tabular-nums text-muted-foreground/75",children:B&&a?.latestVersion?`${a.currentVersion} → ${a.latestVersion}`:L?`v${L}`:null})]})]}),B?s.jsx("button",{type:"button",disabled:R||!m,onClick:m,className:"shrink-0 rounded-full bg-[var(--warning)] px-3 py-1.5 text-[11px] font-semibold text-[color:var(--bg)] transition hover:opacity-90 disabled:cursor-wait disabled:opacity-60",children:x("settings.desktopUpdateRestart")}):s.jsx("button",{type:"button",disabled:!a||R||E==="unsupported"||!p,onClick:p,className:"shrink-0 rounded-full bg-surface px-3 py-1.5 text-[11px] font-medium text-foreground transition hover:bg-surface-elevated disabled:cursor-wait disabled:opacity-60",children:x(E==="installing"?"settings.updateInstallingShort":E==="downloading"?"settings.desktopUpdateDownloadingShort":E==="checking"?"settings.updateCheckingShort":E==="current"||E==="error"?"settings.desktopUpdateCheckAgain":"settings.desktopUpdateCheck")})]}),d]})}function x$({quality:e}){const{locale:t}=Ur(),r=(d,p)=>t==="zh"?d:p,n=d=>d==null||!Number.isFinite(d)?"—":`${d.toFixed(1)} ms`,a=e?.diagnostics,c=d=>s.jsx("dl",{className:"grid grid-cols-[minmax(0,1fr)_auto] gap-x-3 gap-y-1.5 tabular-nums",children:d.map(([p,m])=>s.jsxs(k.Fragment,{children:[s.jsx("dt",{children:p}),s.jsx("dd",{className:"text-right text-foreground break-all",children:m})]},p))}),l=(d,p)=>s.jsxs("section",{className:"mt-3 border-t border-border/30 pt-3",children:[s.jsx("h3",{className:"mb-2 font-medium text-foreground",children:d}),p]});return s.jsxs("div",{className:"text-[11px] leading-relaxed",children:[l(r("往返统计","Round-trip statistics"),s.jsxs(s.Fragment,{children:[c([[r("平均延迟","Average latency"),n(e?.average)],["P95",n(e?.p95)],[r("服务端回包处理","Server reply handler"),n(e?.handlerMs)]]),s.jsx("p",{className:"mt-2",children:r("8 秒未响应计为超时,不等于网络丢包。回包处理仅含消息解析至构造回复,不含解密、排队和发包。","A probe times out after 8s; this is not packet loss. Handler timing covers parsing through reply creation, excluding decryption, queues and transmission.")})]})),l(r("当前发送与排队","Current buffers and queues"),a?s.jsxs(s.Fragment,{children:[c([[r("传输层发送缓冲","Transport send buffer"),`${a.bufferedBytes} B`],[r("加密通道待发送","Channel writes pending"),a.pendingWrites?r("有","Yes"):r("无","No")],[r("进行中的非终端请求","Active non-terminal requests"),a.activeRequests],[r("等待通道的请求","Requests waiting for capacity"),a.waitingRequests]]),s.jsx("p",{className:"mt-2",children:r("属于此服务共用的连接,包含文件等其他请求。","Shared by this service, including file transfers and other requests.")})]}):s.jsx("p",{children:r("尚无连接记录。","No connection record yet.")})),l(r("本次连接建立 · 历史耗时","Connection setup · recorded timings"),s.jsxs(s.Fragment,{children:[c([[r("传输通道就绪","Transport ready"),n(a?.transportOpenMs)],...a?.relay?[[r("其中:连上入口 WebSocket","Within transport: entry WebSocket"),n(a.relay.entryOpenMs)],[r("其中:请求中转至通道打开","Within transport: relay open request"),n(a.relay.routeOpenMs)]]:[],[r("Noise 加密握手","Noise handshake"),n(a?.handshakeMs)],[r("终端逻辑通道就绪","Terminal logical channel ready"),n(a?.socketOpenMs)],[r("其中:等待本地通道名额","Within logical open: local capacity wait"),n(a?.socketQueueMs)]]),s.jsx("p",{className:"mt-2",children:r("这是建链时的历史耗时,不代表当前延迟。“其中”为子项,不能重复相加;中转耗时含处理和建链,不含之前的授权。","Recorded setup timings, not live latency. “Within” rows are subsets, not additive. Relay timing includes processing and setup, excluding earlier authorization.")})]}))]})}function b$({backendSessionId:e}){const{locale:t}=Ur(),r=t==="zh",[n,a]=k.useState(null),[c,l]=k.useState(!1);k.useEffect(()=>{if(a(null),!c||!e)return;const y=()=>a(k9(e));y();const w=setInterval(y,1e3);return document.addEventListener("visibilitychange",y),()=>{clearInterval(w),document.removeEventListener("visibilitychange",y)}},[e,c]);const d=n?.diagnostics,p=n?.rtt,m=n?.connected?n.waiting?r?"等待响应…":"Waiting for reply…":p==null?r?"测量中…":"Measuring…":`${p} ms · ${p<150?r?"流畅":"Low latency":p<300?r?"有延迟":"Moderate latency":r?"高延迟":"High latency"}`:r?"未连接":"Disconnected",x=y=>y==null?"—":`${Math.round(y)} ms`;return s.jsxs("div",{className:"mt-3 rounded-xl bg-surface-2 px-3 text-muted-foreground",children:[s.jsxs("button",{type:"button","aria-expanded":c,onClick:()=>l(y=>!y),className:"flex min-h-11 w-full items-center gap-2 py-2 text-[12px] tabular-nums hover:text-foreground","aria-label":`${r?"连接质量":"Connection quality"}${c?`: ${m}`:""}`,children:[s.jsx("span",{"aria-hidden":"true",className:`h-1.5 w-1.5 rounded-full ${c&&n&&(!n.connected||n.waiting||p!=null&&p>=300)?"bg-destructive":"bg-current"}`}),s.jsxs("span",{className:"flex-1 text-left",children:[r?"连接质量":"Connection quality",c?` · ${m}`:""]}),s.jsx("span",{"aria-hidden":"true",children:c?"▾":"▸"})]}),c&&s.jsxs("div",{className:"pb-3 text-[11px] leading-relaxed",children:[!e&&s.jsx("p",{children:r?"请先打开一个终端会话,再查看连接质量。":"Open a terminal session to measure connection quality."}),s.jsxs("dl",{className:"grid grid-cols-[auto_minmax(0,1fr)] gap-x-4 gap-y-2 tabular-nums",children:[s.jsx("dt",{children:r?"近期延迟":"Recent latency"}),s.jsx("dd",{className:"text-right text-foreground",children:n?.minimum==null?"—":`${Math.round(n.minimum)}–${Math.round(n.maximum??n.minimum)} ms`}),s.jsx("dt",{children:r?"波动":"Jitter"}),s.jsx("dd",{className:"text-right text-foreground",children:x(n?.jitter)}),s.jsx("dt",{children:r?"探测超时":"Probe timeouts"}),s.jsx("dd",{className:"text-right text-foreground",children:n?.samples?`${n.timeouts} / ${n.samples}`:"—"}),s.jsx("dt",{children:r?"连接路径":"Connection route"}),s.jsx("dd",{className:"text-right text-foreground break-words",children:d?`${d.path==="relay"?r?"经入口中转":"Via relay":r?"直连":"Direct"} · ${d.endpoint}`:"—"})]}),s.jsx("p",{className:"mt-2",children:r?"每 5 秒更新,统计最近 20 次;波动越小越稳定。":"Updates every 5s, using the last 20 probes. Lower jitter means more consistent latency."}),s.jsxs("details",{className:"mt-3 border-t border-border/30 pt-2",children:[s.jsx("summary",{className:"cursor-pointer py-1 hover:text-foreground",children:r?"诊断详情":"Diagnostics"}),s.jsx(x$,{quality:n})]})]})]})}const ay={"startup-failure":"settings.serverHealthEventStartupFailure",crash:"settings.serverHealthEventCrash","crash-native":"settings.serverHealthEventCrashNative",killed:"settings.serverHealthEventKilled",wedge:"settings.serverHealthEventWedge","port-conflict":"settings.serverHealthEventPortConflict","gave-up":"settings.serverHealthEventGaveUp","exit-zero-unexpected":"settings.serverHealthEventExitZero","terminated-externally":"settings.serverHealthEventTerminated","supervisor-lost":"settings.serverHealthEventSupervisorLost","uncaught-exception":"settings.serverHealthEventUncaughtException","unhandled-rejection":"settings.serverHealthEventUnhandledRejection","exit-nonzero":"settings.serverHealthEventExitNonzero"};function y$(e){return e<1e3?`${e}ms`:e<6e4?`${Math.round(e/1e3)}s`:e<36e5?`${Math.round(e/6e4)}m`:`${Math.round(e/36e5)}h`}function v$({state:e,onDismiss:t}){const{t:r}=Ur(),[n,a]=b.useState(!1),[c,l]=b.useState(!1),d=b.useRef(!1),p=b.useRef(!0);b.useEffect(()=>(p.current=!0,()=>{p.current=!1}),[]),b.useEffect(()=>{e?.supervised&&(d.current=!1,a(!1),l(!1))},[e?.supervised]),b.useEffect(()=>{if(!n)return;const z=window.setTimeout(()=>{d.current=!1,a(!1),l(!0)},45e3);return()=>window.clearTimeout(z)},[n]);const m=async()=>{if(!d.current){d.current=!0,l(!1),a(!0);try{await L9()}catch{if(!p.current)return;d.current=!1,a(!1),l(!0)}}};if(!e)return null;const x=e.incident,y=!e.supervised&&e.supervisor?.phase==="gave-up",w=!e.supervised&&e.supervisor!==null&&!e.supervisor.alive,v=y||w||e.attention,S=e.supervised&&e.supervisor?.alive&&e.supervisor.phase==="running",L=y?r("settings.serverHealthGaveUp",{count:e.supervisor?.consecutiveCrashes??0}):w?r("settings.serverHealthSupervisorLost"):e.supervised?r("settings.serverHealthSupervised"):r("settings.serverHealthUnsupervised"),E=x?r(ay[x.event]??"settings.serverHealthUnknownEvent"):"",R=x?.causeEvent?r(ay[x.causeEvent]??"settings.serverHealthUnknownEvent"):"",B=x?[new Date(x.at).toLocaleString(),x.uptimeMs!==null?r("settings.serverHealthUptime",{duration:y$(x.uptimeMs)}):null,x.signal?`signal ${x.signal}`:null,x.exitCode!==null?`exit ${x.exitCode}`:null].filter(Boolean).join(" · "):"";return s.jsxs("section",{className:"mt-3 overflow-hidden rounded-xl bg-surface-2","aria-labelledby":"server-health-title",children:[s.jsx("div",{id:"server-health-title",className:"px-3 pt-3 text-[12px] font-semibold text-foreground",children:r("settings.serverHealthTitle")}),s.jsxs("div",{className:"flex items-start justify-between gap-3 px-3 py-3",children:[s.jsxs("div",{className:"flex min-w-0 items-start gap-2.5",children:[s.jsx("span",{className:`mt-0.5 inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${v?"bg-destructive/15 text-destructive":"bg-primary/15 text-primary"}`,children:v?s.jsx(vS,{size:15}):s.jsx(AS,{size:15})}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12px] font-medium text-foreground",children:L}),s.jsx("div",{className:"mt-0.5 text-[10px] leading-relaxed text-muted-foreground",children:x?`${r(S?"settings.serverHealthHistory":"settings.serverHealthLastIncident")}: ${E}${R?` · ${R}`:""}`:r("settings.serverHealthClean")}),x&&S&&s.jsx("div",{className:"mt-1 text-[11px] text-primary",children:r("settings.serverHealthRunningNow")}),x&&s.jsx("div",{className:"mt-1 text-[10px] tabular-nums text-muted-foreground/75",children:B}),x?.detail&&s.jsx("div",{className:"mt-1 break-words text-[10px] text-muted-foreground/75",children:x.detail}),x?.oomSuspect&&s.jsx("div",{className:"mt-1 text-[10px] text-[color:var(--warning)]",children:r("settings.serverHealthOomNote")}),e.supervisor&&e.supervisor.restarts>0&&!y&&s.jsx("div",{className:"mt-1 text-[10px] tabular-nums text-muted-foreground/75",children:r("settings.serverHealthRestarted",{count:e.supervisor.restarts})})]})]}),e.attention&&s.jsx("button",{type:"button",onClick:t,className:"shrink-0 rounded-full bg-surface px-3 py-1.5 text-[11px] font-medium text-foreground transition hover:bg-surface-elevated",children:r("settings.serverHealthDismiss")})]}),!e.supervised&&s.jsxs("div",{className:"border-t border-border px-3 py-3",children:[s.jsx("p",{className:"text-[11px] leading-relaxed text-muted-foreground",children:e.canEnableSupervision?r("settings.serverHealthEnableHint"):r("settings.serverHealthEnableUnavailable")}),e.canEnableSupervision&&s.jsx("button",{type:"button",onClick:m,disabled:n,className:"mt-2 min-h-11 rounded-lg bg-primary px-3 text-[12px] font-medium text-primary-foreground disabled:opacity-60",children:r(n?"settings.serverHealthEnabling":"settings.serverHealthEnable")}),n&&s.jsx("p",{role:"status",className:"mt-2 text-[11px] text-muted-foreground",children:r("settings.serverHealthEnablePending")}),c&&s.jsx("p",{role:"alert",className:"mt-2 text-[11px] text-destructive",children:r("settings.serverHealthEnableError")})]})]})}const w$=()=>()=>{},A$=()=>1/0;function T$(){const{t:e}=Ur(),t=b.useId(),r=Po(),n=b.useSyncExternalStore(r?.subscribe??w$,r?.retentionLimit??A$);if(!r)return null;const a=I9+1,c=n===1/0?e("settings.workspaceUnlimited"):String(n);return s.jsxs("div",{className:"space-y-1.5 rounded-xl bg-surface-2 px-2.5 py-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("label",{htmlFor:t,className:"shrink-0 text-[12px] font-medium text-foreground/90",children:e("settings.workspaceLimit")}),s.jsx("input",{id:t,type:"range",min:3,max:a,step:1,value:n===1/0?a:n,"aria-valuetext":c,"aria-describedby":`${t}-hint`,onChange:l=>{const d=Number(l.target.value);r.setRetentionLimit(d===a?1/0:d)},className:"h-8 min-w-0 flex-1"}),s.jsx("output",{htmlFor:t,className:"min-w-12 shrink-0 text-right text-[11px] tabular-nums text-muted-foreground",children:c})]}),s.jsx("p",{id:`${t}-hint`,className:"text-[11px] leading-relaxed text-muted-foreground",children:e("settings.workspaceLimitHint")})]})}const M1="mobile-session-destroy";function S$(e,t){return t&&e.type==="session"&&e.destination?.droppableId===M1}const Ca="termdock-program-rules-cache",Bh="termdock-toolbar-presets-cache",qd="termdock-settings-cache",oy="termdock-color-theme",ly="termdock:right-sidebar:file-preview-open-by-session:v2",Yd="termdock:running-session-button-enabled:v1",Zd="termdock:attention-button-enabled:v1",C$=60,cy=320,uy=420,Qo=8;function dy(e,t,r){return Math.min(Math.max(e,t),r)}function hy(e){if(typeof window>"u")return{left:Qo,top:Qo};const t=window.innerWidth/2,r=Math.min(64,window.innerHeight/4),n=e?.x??t,a=e?.y??r,c=Math.max(Qo,window.innerWidth-cy-Qo),l=Math.max(Qo,window.innerHeight-uy-Qo);return{left:dy(n+Qo,Qo,c),top:dy(a+Qo,Qo,l),width:cy,maxHeight:`min(${uy}px, calc(100vh - ${Qo*2}px))`}}function _$(e){return e==="dark"||e==="light"}function k$(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.entries(e).every(([t,r])=>{if(!t||!r||typeof r!="object"||Array.isArray(r))return!1;const n=r;return typeof n.updatedAt=="number"&&Number.isFinite(n.updatedAt)})}function Bm(e){const t=Object.entries(e).filter(([r,n])=>r&&Number.isFinite(n.updatedAt)).sort(([,r],[,n])=>n.updatedAt-r.updatedAt).slice(0,C$);return Object.fromEntries(t)}function L$(e){return Array.isArray(e)&&e.every(t=>{if(!t||typeof t!="object")return!1;const r=t;return typeof r.id=="string"&&typeof r.pattern=="string"&&typeof r.output=="string"&&(r.matchType==="exact"||r.matchType==="includes"||r.matchType==="prefix"||r.matchType==="regex")})}function I$(e){return typeof e=="object"&&e!==null&&typeof e.version=="number"&&Array.isArray(e.presets)}function E$(e,t){const r=w0(),n=new Set(xE()),a=Array.isArray(e)?e:[],c=Ru(a),l=t<e0;if(c.length===0)return r;if(l){const p=new Map(c.map(w=>[w.id,w])),m=new Map(a.map(w=>[typeof w.id=="string"?w.id.trim().toLowerCase().replace(/[^a-z0-9_-]/g,"-"):"",w])),x=c.filter(w=>!n.has(w.id));return[...r.map(w=>{const v=p.get(w.id),S=m.get(w.id);return v?{...w,rowLayout:v.rowLayout,showOnDesktop:typeof S?.showOnDesktop=="boolean"?S.showOnDesktop:w.showOnDesktop}:w}),...x]}const d=new Set(c.map(p=>p.id));return[...c,...r.filter(p=>!d.has(p.id))]}function N$(e){return typeof e=="object"&&e!==null&&typeof e.preventSleep=="boolean"&&typeof e.networkAvailable=="boolean"}const R$={name:"",source:"auto",hostname:"",fallbackHostname:"",url:"",fallbackUrl:"",onboardingUrl:null,status:"disabled",reason:null,httpsEnabled:!1,caAvailable:!1,lanAddresses:[],interfaces:[]},np="__termdockOverlay",sp="__termdockBaseAnchor",ip="__termdockBaseGuard",M$=3,fy=250,j$="termdock-notification-target-v1",py="/__termdock-notification-target",my=3e4;function D$(e){return e==="left-sidebar"||e==="right-sidebar"||e==="right-sidebar-repo-picker"||e==="right-sidebar-file-preview"||e==="settings"||e==="markdown-outline"||e==="markdown-image-lightbox"}function Su(e){if(!e||typeof e!="object")return null;const t=e[np];return D$(t)?t:null}function Ng(e){return e&&typeof e=="object"?{...e}:{}}function r4(e){const t=Ng(e);return delete t[np],t}function B$(e){const t=r4(e);return delete t[ip],{...t,[sp]:!0}}function Q$(){typeof window>"u"||window.history.pushState({...r4(window.history.state),[sp]:!0,[ip]:!0},"",window.location.href)}function n4(){for(let e=0;e<M$;e+=1)Q$()}function Qh(){typeof window>"u"||(window.history.replaceState(B$(window.history.state),"",window.location.href),n4())}function Kd(e){typeof window>"u"||window.history.pushState({...Ng(window.history.state),[sp]:!0,[np]:e,[ip]:!1},"",window.location.href)}function P$(e){typeof window>"u"||window.history.replaceState({...Ng(window.history.state),[sp]:!0,[np]:e,[ip]:!1},"",window.location.href)}const s4=["bash","zsh","fish","sh","dash","ksh","tcsh","csh","nu"];let _a=new Set(s4);function gy(e){const t=new Map;for(const[r,n]of e)t.set(r,{cwd:n.cwd,activeProgram:n.activeProgram,activeProgramRaw:n.activeProgramRaw,inCopyMode:n.inCopyMode,isConnecting:n.isConnecting,agentStatus:n.agentStatus,agentIndicator:n.agentIndicator,agentStatusDetail:n.agentStatusDetail,agent:n.agent,agentMessage:n.agentMessage,agentNativeSessionId:n.agentNativeSessionId,agentResumeRecovered:n.agentResumeRecovered,terminalSessionId:n.terminalSessionId,agentNeedsReview:n.agentNeedsReview,gitStatus:n.gitStatus,shellTitle:n.shellTitle,promptState:n.promptState,tuiProgress:n.tuiProgress});return t}function O$(e,t){if(e.size!==t.size)return!1;for(const[r,n]of t){const a=e.get(r);if(!a||a.cwd!==n.cwd||a.activeProgram!==n.activeProgram||a.activeProgramRaw!==n.activeProgramRaw||a.inCopyMode!==n.inCopyMode||a.isConnecting!==n.isConnecting||a.agentStatus!==n.agentStatus||a.agentIndicator!==n.agentIndicator||a.agentStatusDetail!==n.agentStatusDetail||a.agent!==n.agent||a.agentMessage!==n.agentMessage||a.agentNativeSessionId!==n.agentNativeSessionId||a.agentResumeRecovered!==n.agentResumeRecovered||a.terminalSessionId!==n.terminalSessionId||a.agentNeedsReview!==n.agentNeedsReview||a.gitStatus!==n.gitStatus||a.shellTitle!==n.shellTitle||a.promptState!==n.promptState||a.tuiProgress?.state!==n.tuiProgress?.state||a.tuiProgress?.progress!==n.tuiProgress?.progress)return!1}return!0}function xy(e,t){return s.jsx($P,{sessionMode:e,state:t})}function F$(e,t){const r=new Map(e.map(l=>[l.id,l])),n=t.map(l=>r.get(l)).filter(l=>l!==void 0),a=new Set(t),c=e.filter(l=>!a.has(l.id));return[...n,...c]}const $$=k.lazy(()=>Oc(()=>import("./CollaborationMainWorkspace-CS_o2iYt.js"),__vite__mapDeps([18,1,2,3,4,5,8,9,15,13])));function U$(){const{t:e,locale:t,setLocale:r}=Ur(),n="env(safe-area-inset-top, 0px)",a="env(safe-area-inset-bottom, 0px)";E9();const c=k.useMemo(()=>typeof window>"u"?!1:/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,[]),[l,d]=k.useState(!1),[p,m]=k.useState(()=>Tc(oy,_$)??"dark"),x=k.useRef(Tc(qd,N$)).current,[y,w]=k.useState(x?.preventSleep??!1),[v,S]=k.useState(x?.networkAvailable??!0),[L,E]=k.useState(N9),[R,B]=k.useState(R9),[z,O]=k.useState(M9),[$,V]=k.useState(j9),[Z,le]=k.useState(Tp),[be,pe]=k.useState(x?.localAccess??R$),[ee,_e]=k.useState(x?.localAccess?.name??""),[ze,Y]=k.useState(!1),[ce,qe]=k.useState(null),[we,ye]=k.useState(null),[Le,Be]=k.useState(null),[ne,Fe]=k.useState(!1),[ke,Ee]=k.useState(null),Pe=k.useMemo(()=>vo(),[]),Ne=!!(Pe?.desktopUpdateState&&Pe.checkDesktopUpdate&&Pe.installDesktopUpdate),[oe,We]=k.useState(null),[nt,gt]=k.useState(null),[ue,Ze]=k.useState(!1),[at,Ie]=k.useState(null),[Ge,Ce]=k.useState(!1),[H,ae]=k.useState(()=>Bm(Tc(ly,k$)??{})),[Ae,Ye]=k.useState(0),[et,St]=k.useState(!1),[Gt,Qt]=k.useState(0),[wt,zt]=k.useState(!1),[Vt,Kt]=k.useState(0),[Ot,It]=k.useState(!1),[xe,Ve]=k.useState(0),ht=k.useRef(null),[q,ut]=k.useState({}),{terminalSettings:qt,updateTerminalSettings:tt}=qB(),De=qt.fontSize,nr=qt.rendererMode,[Ke,_t]=k.useState(!1),$t=k.useRef(D9()).current,[yt,xt]=b.useState(()=>$t.sessions.map(C=>({id:C.sessionId,name:C.name,customName:C.customName,mode:C.mode,tmuxSessionName:C.tmuxSessionName}))),Rt=Ei(C=>C.groupId);k.useEffect(()=>{const C=()=>Ei.getState().terminal();return window.addEventListener("switch-terminal-session",C),()=>window.removeEventListener("switch-terminal-session",C)},[]);const[Ct,fr]=k.useState($t.activeSessionId),[Yt,Sr]=k.useState(!1);k.useEffect(()=>{Yt&&B9({rendered:!0})},[Yt]);const[pn,dr]=k.useState(null),[me,Gr]=k.useState(null),[ot,pt]=k.useState([]),[ir,Mn]=b.useState(()=>{const C=Yr.getState();return $t.sessions.forEach(P=>{P.backendSessionId&&C.setTerminalSession(P.sessionId,{sessionId:P.backendSessionId,cols:80,rows:24,mode:P.mode,tmuxSessionName:P.tmuxSessionName}),P.activeProgram!=null&&C.setSessionActiveProgram(P.sessionId,P.activeProgram),P.cwd!=null&&C.setSessionCwd(P.sessionId,P.cwd),P.shellTitle!=null&&C.setSessionShellTitle(P.sessionId,P.shellTitle)}),Mu("session-chrome-hydrated"),gy(Yr.getState().sessions)});b.useEffect(()=>{!Pe||!Ke||Promise.all([Pe.snapshot(),Pe.desktopUpdateState?.()??Promise.resolve(null)]).then(([C,P])=>{We(C),gt(P)}).catch(C=>Ie(C instanceof Error?C.message:String(C)))},[Pe,Ke]),b.useEffect(()=>{Pe?.onDesktopUpdateState&&Pe.onDesktopUpdateState(gt)},[Pe]),b.useEffect(()=>Yr.subscribe(C=>{const P=gy(C.sessions);Mn(de=>O$(de,P)?de:P)}),[]);const Xr=b.useCallback(async(C,P)=>{Gr(null),dr({sessionId:C,status:"submitting",error:null});try{await Q9(P),dr(de=>de?.sessionId===C?{...de,status:"waiting",error:null}:de)}catch(de){const At=(de&&typeof de=="object"&&"code"in de?String(de.code??""):"")==="AGENT_SESSION_ACTIVE_ELSEWHERE"?e("tab.resumeAgentConflict"):de instanceof Error&&/busy/i.test(de.message)?e("tab.resumeAgentBusy"):e("tab.resumeAgentFailed");dr(Zt=>Zt?.sessionId===C?{...Zt,error:At}:Zt),Gr({tone:"error",message:At})}},[e]);b.useEffect(()=>{if(!pn||pn.status!=="waiting")return;const C=ir.get(pn.sessionId);if(!C||C.agentResumeRecovered||C.agentStatus===null&&!C.agent)return;const P=C.agent?.displayName??"Agent";dr(null),Gr({tone:"success",message:e("tab.resumeAgentSuccess",{agent:P})})},[pn,ir,e]),b.useEffect(()=>{if(!pn||pn.status!=="waiting"||pn.error)return;const C=pn.sessionId,P=window.setTimeout(()=>{const de=e("tab.resumeAgentTimeout");dr(rt=>rt?.sessionId===C&&rt.status==="waiting"?{...rt,error:de}:rt),Gr({tone:"error",message:de})},15e3);return()=>window.clearTimeout(P)},[pn,e]),b.useEffect(()=>{if(me?.tone!=="success")return;const C=window.setTimeout(()=>Gr(null),3200);return()=>window.clearTimeout(C)},[me]),b.useEffect(()=>{let C=!1;P9().then(de=>{C||Be(de)}).catch(()=>{}),O9().then(de=>{C||Ee(de)}).catch(()=>{});const P=ux(de=>{C||(de.type==="update-state"?Be(de.state):de.type==="server-health"&&Ee(de.state))});return()=>{C=!0,P()}},[]);const je=b.useCallback(async()=>{try{Ee(await F9())}catch(C){window.alert(C instanceof Error?C.message:String(C))}},[]),st=b.useCallback(async()=>{const C=Le?.latestVersion;if(!(!C||ne)&&window.confirm(e("sidebar.updateRestartConfirm",{version:C}))){Fe(!0);try{Be(await $9())}catch(P){window.alert(P instanceof Error?P.message:String(P))}finally{Fe(!1)}}},[Le?.latestVersion,e,ne]),bt=b.useCallback(async()=>{if(!ne){Fe(!0);try{Be(await U9())}catch(C){window.alert(C instanceof Error?C.message:String(C))}finally{Fe(!1)}}},[ne]),Br=b.useCallback(async()=>{if(!(!Pe?.checkDesktopUpdate||ue)){Ze(!0);try{gt(await Pe.checkDesktopUpdate())}catch(C){Ie(C instanceof Error?C.message:String(C))}finally{Ze(!1)}}},[Pe,ue]),Vr=b.useCallback(async()=>{if(!(!Pe?.installDesktopUpdate||ue||nt?.status!=="ready")&&window.confirm(e("settings.desktopUpdateRestartConfirm"))){Ze(!0);try{gt(await Pe.installDesktopUpdate())}catch(C){Ie(C instanceof Error?C.message:String(C))}finally{Ze(!1)}}},[Pe,ue,nt?.status,e]);b.useEffect(()=>{document.documentElement.dataset.theme=p,z9(p),Fn(oy,p)},[p]),b.useEffect(()=>{Fn(ly,Bm(H))},[H]);const Cr=Wt(C=>C.leftOpen),qr=Wt(C=>C.rightOpen),mn=Wt(C=>C.leftPinned),on=Wt(C=>C.leftSidebarWidth),zr=Wt(C=>C.rightPinned),un=Wt(C=>C.rightSidebarWidth),Er=Wt(C=>C.rootPath),re=Wt(C=>C.contextKey),mt=Wt(C=>C.selectedFilePath),Mt=Wt(C=>C.groupByFolder),rr=df(C=>C.collaborationGroups),Ar=Wt(C=>C.collapsedGroups),Fr=Wt(C=>C.toggleGroupCollapsed),[Xt,Zr]=b.useState(()=>typeof window>"u"?!0:window.matchMedia("(min-width: 1024px)").matches),[Jt,Pr]=b.useState(()=>typeof window>"u"?1024:window.innerWidth),[Hr,ps]=b.useState(()=>typeof window>"u"?!1:window.matchMedia("(orientation: landscape)").matches),[Mr,jn]=b.useState([]),[Tr,Jr]=b.useState({available:!0,version:null,reason:null}),[ln,Qr]=b.useState(!1),[ks,Dr]=b.useState(null),[en,xn]=b.useState(null),[X,He]=b.useState(null),[Nt,Et]=b.useState(null),[tr,jr]=b.useState(null),[cr,Cn]=b.useState(null),[Ls,Xn]=b.useState(null),[,cn]=b.useState(0),[dn,_r]=b.useState(null),[Or,Gn]=b.useState(null),[Vn,gn]=b.useState(null),[Jn,kr]=b.useState(!1),[Lr,pr]=b.useState(()=>Tc(Yd,C=>typeof C=="boolean")??!1),ns=b.useCallback(async C=>{const P=Lr;pr(C),Fn(Yd,C);try{const de=await La({runningSessionButtonEnabled:C});pr(de.runningSessionButtonEnabled),Fn(Yd,de.runningSessionButtonEnabled)}catch{pr(P),Fn(Yd,P)}},[Lr]),[Un,En]=b.useState(()=>Tc(Zd,C=>typeof C=="boolean")??!0),kn=b.useCallback(async C=>{const P=Un;En(C),Fn(Zd,C);try{const de=await La({attentionButtonEnabled:C});En(de.attentionButtonEnabled),Fn(Zd,de.attentionButtonEnabled)}catch{En(P),Fn(Zd,P)}},[Un]),[ss,Wr]=b.useState(null),tn=b.useCallback(C=>{Wr(C)},[]),G=b.useRef(!1),[Me,$e]=b.useState(null),[Je,it]=b.useState(null),Tt=k.useRef(null),kt=k.useRef(!1),Dt=k.useRef(null),ft=k.useRef(!1),Bt=b.useCallback(()=>{Cn(null),Xn(null)},[]),W=k.useRef(typeof window>"u"?null:new URLSearchParams(window.location.search).get("session")),[N,U]=k.useState(W.current),[K,fe]=k.useState(!0),Qe=k.useRef(W.current),ve=k.useRef(typeof window>"u"?null:new URLSearchParams(window.location.search).get("_notifTrace"));b.useEffect(()=>{if(typeof window>"u")return;const C=window.matchMedia("(min-width: 1024px)"),P=()=>{Zr(C.matches),Pr(window.innerWidth)};return P(),C.addEventListener("change",P),window.addEventListener("resize",P),()=>{C.removeEventListener("change",P),window.removeEventListener("resize",P)}},[]),b.useEffect(()=>{if(typeof window>"u")return;const C=window.matchMedia("(orientation: landscape)"),P=()=>ps(C.matches);return P(),C.addEventListener("change",P),()=>C.removeEventListener("change",P)},[]);const lt=k.useMemo(()=>Ct?ot.find(C=>C.sessionIds.includes(Ct))??null:null,[Ct,ot]),vt=lt?.id??null,br=lt?.sessionIds[0]??Ct,Lt=k.useRef([]);k.useLayoutEffect(()=>{const C=Lt.current;if(Lt.current=ot,C.length===0)return;const P=new Set(ot.flatMap(de=>de.sessionIds));for(const de of C){const rt=de.sessionIds.filter(At=>!P.has(At)).map(At=>({sessionId:At,rootPath:Yr.getState().sessions.get(At)?.cwd??null}));rt.length>0&&Wt.getState().inheritRightSidebarStateFromSplitWorkspace(de.id,rt)}},[ot]),k.useLayoutEffect(()=>((()=>{const P=br?Yr.getState().sessions.get(br)?.cwd??null:null;Wt.getState().setRootPath(P,br,vt)})(),Yr.subscribe((P,de)=>{const rt=br?P.sessions.get(br)?.cwd??null:null,At=br?de.sessions.get(br)?.cwd??null:null;rt!==At&&Wt.getState().setRootPath(rt,br,vt)})),[vt,br]);const rn=k.useRef(Xy(window.location.search)??rC(Sc()?.targetPeerId)),[yn,hn]=k.useState("");k.useEffect(()=>{const C=rn.current;if(!C)return;if(C.peerId&&C.peerId!==Sc()?.targetPeerId){const rt=H9().find(At=>At.targetPeerId===C.peerId);if(rt&&Po()){try{tC(C)}catch{hn(t==="zh"?"无法在此浏览器打开架构链接。":"Cannot open this architecture link in this browser.");return}if(W9(rt)){rn.current=null;const At=new URL(window.location.href);At.searchParams.delete("architecture"),window.history.replaceState(window.history.state,"",At);return}}hn(t==="zh"?`此架构属于 ${C.serviceName??C.peerId}。请先连接该 Termdock 服务,再打开链接。`:`This architecture belongs to ${C.serviceName??C.peerId}. Connect to that Termdock service, then open this link.`);return}hn("");try{sessionStorage.setItem(`termdock.architecture.selection:${C.root}`,C.file)}catch{}const P=Wt.getState();P.setRootPath(C.root,br,vt),P.setRightTab("architecture"),P.openRight();const de=new URL(window.location.href);de.searchParams.delete("architecture"),window.history.replaceState(window.history.state,"",de),br&&(rn.current=null)},[br,vt,t]);const Dn=Xt||Hr,zn=Jt*.95,hr=Dn?Math.min(Math.max(Jt*.22,280),340):Math.min(Jt*.86,380),jt=Ct&&Er?`${Ct}\0${Er}`:"",Bn=!!(jt&&mt&&H[jt]),qn=b.useCallback(C=>{jt&&(C&&!Wt.getState().selectedFilePath||ae(P=>{if(!!P[jt]===C)return P;if(C)return Bm({...P,[jt]:{updatedAt:Date.now()}});const rt={...P};return delete rt[jt],rt}))},[jt]);b.useEffect(()=>{eQ(jt,re,mt)&&ae(C=>{if(!C[jt])return C;const P={...C};return delete P[jt],P})},[jt,re,mt]);const Qn=Ot?"markdown-image-lightbox":wt?"markdown-outline":et?"right-sidebar-repo-picker":qr&&Bn?"right-sidebar-file-preview":Ke?"settings":qr&&!(zr&&Xt)?"right-sidebar":Cr&&!(mn&&Xt)?"left-sidebar":null,is=k.useRef(Qn),zi=k.useRef(Qn),da=k.useRef(!1),bs=k.useRef(!1),Ga=b.useCallback(()=>{if(typeof window>"u")return;const C=window.matchMedia("(hover: hover) and (pointer: fine)").matches;!Xt||!C||navigator.maxTouchPoints>0||window.setTimeout(()=>{window.dispatchEvent(new CustomEvent("focus-active-terminal-session"))},0)},[Xt]),So=b.useCallback(C=>{if(C==="markdown-image-lightbox"){It(!1),Ve(P=>P+1);return}if(C==="markdown-outline"){zt(!1),Kt(P=>P+1);return}if(C==="right-sidebar-file-preview"){zt(!1),Kt(P=>P+1),qn(!1),Ye(P=>P+1);return}if(C==="right-sidebar-repo-picker"){St(!1),Qt(P=>P+1);return}if(C==="settings"){_t(!1),ws(!1),ni(!1),cs(!1);return}if(C==="left-sidebar"){Wt.getState().closeLeft();return}zt(!1),Kt(P=>P+1),St(!1),Qt(P=>P+1),It(!1),Ve(P=>P+1),Wt.getState().closeRight()},[qn]),Hn=b.useCallback(C=>{if(!c&&typeof window<"u"&&is.current===C&&Su(window.history.state)===C){window.history.back();return}So(C)},[So,c]),ha=b.useCallback(()=>{_t(!1);const C=Wt.getState();C.closeRight(),C.openLeft()},[]),ms=b.useCallback(()=>{_t(!1);const C=Wt.getState();C.closeLeft(),C.openRight()},[]),Ia=b.useCallback(()=>{_t(!1);const C=Wt.getState();C.closeLeft(),C.openRight(),C.setRightTab("files"),C.openRightSearch()},[]),as=b.useCallback(()=>{const C=Wt.getState();if(C.leftPinned){C.setLeftPinned(!1),C.closeLeft();return}if(Cr){Hn("left-sidebar");return}ha()},[ha,Hn,Cr]),Va=b.useCallback(()=>{const C=Wt.getState();C.leftPinned?(C.setLeftPinned(!1),C.openLeft()):(C.setLeftPinned(!0),C.openLeft())},[]),Js=b.useCallback(()=>{const C=Wt.getState();C.setLeftPinned(!1),C.closeLeft()},[]),ei=b.useCallback(()=>{const C=Wt.getState();C.rightPinned?(C.setRightPinned(!1),C.openRight()):(C.setRightPinned(!0),C.openRight())},[]),Hs=b.useCallback(()=>{const C=Wt.getState();C.setRightPinned(!1),C.closeRight()},[]),qa=b.useRef(0),Is=b.useRef(0),fa=b.useRef(null),dl=b.useCallback(C=>{C.preventDefault(),qa.current=C.clientX,Is.current=Wt.getState().leftSidebarWidth;const P=rt=>{fa.current===null&&(fa.current=requestAnimationFrame(()=>{fa.current=null;const At=rt.clientX-qa.current;Wt.getState().setLeftSidebarWidth(Is.current+At)}))},de=()=>{window.removeEventListener("mousemove",P),window.removeEventListener("mouseup",de),fa.current!==null&&(cancelAnimationFrame(fa.current),fa.current=null),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",window.addEventListener("mousemove",P),window.addEventListener("mouseup",de)},[]),Ya=b.useRef(0),os=b.useRef(0),Ms=b.useRef(null),Hi=b.useCallback(C=>{C.preventDefault(),Ya.current=C.clientX;const P=Wt.getState(),de=P.leftPinned?P.leftSidebarWidth:0;os.current=Oh(P.rightSidebarWidth,window.innerWidth,de);const rt=Zt=>{Ms.current===null&&(Ms.current=requestAnimationFrame(()=>{Ms.current=null;const Nr=Ya.current-Zt.clientX,An=Wt.getState(),Nn=An.leftPinned?An.leftSidebarWidth:0;An.setRightSidebarWidth(Oh(os.current+Nr,window.innerWidth,Nn))}))},At=()=>{window.removeEventListener("mousemove",rt),window.removeEventListener("mouseup",At),Ms.current!==null&&(cancelAnimationFrame(Ms.current),Ms.current=null),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",window.addEventListener("mousemove",rt),window.addEventListener("mouseup",At)},[]),xi=b.useCallback(()=>{const C=Wt.getState();if(C.rightPinned){C.setRightPinned(!1),C.closeRight();return}if(qr){Hn("right-sidebar");return}ms()},[ms,Hn,qr]),bi=b.useCallback(()=>{!Bn&&!c&&typeof window<"u"&&is.current==="right-sidebar"&&Su(window.history.state)==="right-sidebar"&&(Kd("right-sidebar-file-preview"),zi.current="right-sidebar-file-preview"),qn(!0)},[Bn,c,qn]),hl=b.useCallback(()=>{Hn("right-sidebar-file-preview")},[Hn]),ti=b.useCallback(()=>{!et&&!c&&typeof window<"u"&&is.current==="right-sidebar"&&Su(window.history.state)==="right-sidebar"&&(Kd("right-sidebar-repo-picker"),zi.current="right-sidebar-repo-picker"),St(!0)},[et,c]),Uo=b.useCallback(()=>{Hn("right-sidebar-repo-picker")},[Hn]),pa=b.useCallback(()=>{!wt&&!c&&typeof window<"u"&&is.current&&Su(window.history.state)===is.current&&(Kd("markdown-outline"),zi.current="markdown-outline"),zt(!0)},[wt,c]),fl=b.useCallback(()=>{Hn("markdown-outline")},[Hn]),pl=b.useCallback(()=>{!c&&typeof window<"u"&&is.current&&Su(window.history.state)===is.current&&(Kd("markdown-image-lightbox"),zi.current="markdown-image-lightbox"),It(!0)},[c]),ls=b.useCallback(()=>{Hn("markdown-image-lightbox")},[Hn]),js=b.useCallback(()=>{!c&&typeof window<"u"&&is.current&&Su(window.history.state)===is.current&&(P$("settings"),zi.current="settings"),Wt.getState().closeAll(),_t(!0)},[c]),Ri=b.useCallback(()=>{Hn("settings")},[Hn]);b.useEffect(()=>{if(!Pe)return;const C=()=>js();return window.addEventListener("termdock:open-settings",C),()=>window.removeEventListener("termdock:open-settings",C)},[Pe,js]);const zo=b.useCallback(()=>{Ce(!0),ht.current!==null&&(window.clearTimeout(ht.current),ht.current=null)},[]),Dl=b.useCallback(()=>{ht.current!==null&&(window.clearTimeout(ht.current),ht.current=null),Ce(!1),bs.current=!0,Qh(),bs.current},[]);b.useEffect(()=>()=>{ht.current!==null&&window.clearTimeout(ht.current)},[]),b.useEffect(()=>{c||Qh()},[c]),b.useEffect(()=>{if(typeof window>"u"||c)return;let C=null;const P=()=>{C!==null&&(window.clearTimeout(C),C=null)},de=An=>{if(is.current,bs.current,is.current){is.current;return}!An?.force&&bs.current||(An?.userActivated&&(bs.current=!0),Qh(),bs.current,void 0)},rt=()=>{P(),C=window.setTimeout(()=>{C=null,de({force:!0})},fy)},At=()=>{de({userActivated:!0})},Zt=()=>{rt()},Nr=()=>{document.visibilityState==="visible"&&rt()};return window.addEventListener("pointerdown",At,{capture:!0,passive:!0}),window.addEventListener("touchstart",At,{capture:!0,passive:!0}),window.addEventListener("keydown",At,{capture:!0}),window.addEventListener("pageshow",Zt),document.addEventListener("visibilitychange",Nr),()=>{P(),window.removeEventListener("pointerdown",At,{capture:!0}),window.removeEventListener("touchstart",At,{capture:!0}),window.removeEventListener("keydown",At,{capture:!0}),window.removeEventListener("pageshow",Zt),document.removeEventListener("visibilitychange",Nr)}},[c]),b.useEffect(()=>{is.current=Qn},[Qn]),b.useEffect(()=>{if(typeof window>"u"||Qn||c)return;const C=window.setTimeout(()=>{is.current?(is.current,void 0):Qh()},fy);return()=>window.clearTimeout(C)},[Qn,c]),b.useEffect(()=>{if(typeof window>"u"||c)return;const C=zi.current;da.current,Qn&&Qn!==C&&!da.current&&Kd(Qn),!Qn&&C&&Ga(),zi.current=Qn,!Qn&&da.current&&window.setTimeout(()=>{da.current=!1},0)},[Qn,c,Ga]),b.useEffect(()=>{if(typeof window>"u"||c)return;const C=()=>{const P=is.current;if(bs.current,!P){bs.current=!1,bs.current,zo(),n4();return}da.current=!0,So(P)};return window.addEventListener("popstate",C),()=>window.removeEventListener("popstate",C)},[So,zo,c]),b.useEffect(()=>{const C=P=>{const de=P.metaKey||P.ctrlKey;if(de&&P.key==="b"&&!P.shiftKey&&(P.preventDefault(),as()),de&&P.shiftKey&&P.key==="E"&&(P.preventDefault(),xi()),de&&P.shiftKey&&P.key==="P"&&(P.preventDefault(),Ia()),de&&!P.shiftKey&&P.altKey&&(P.key==="ArrowLeft"||P.key==="ArrowRight")){P.preventDefault();const rt=P.key==="ArrowRight"?"next":"prev";window.dispatchEvent(new CustomEvent("cycle-terminal-session",{detail:{direction:rt}}));return}if(de&&P.shiftKey&&!P.altKey&&(P.code==="BracketLeft"||P.code==="BracketRight")){P.preventDefault();const rt=P.code==="BracketRight"?"next":"prev";window.dispatchEvent(new CustomEvent("cycle-terminal-session",{detail:{direction:rt}}));return}};return document.addEventListener("keydown",C),()=>{document.removeEventListener("keydown",C)}},[as,xi,Ia]);const Es=b.useCallback(async()=>{Y(!0),qe(null);try{const C=await La({localAccess:{name:ee}});pe(C.localAccess),_e(C.localAccess.name),Fn(qd,{preventSleep:C.preventSleep,networkAvailable:C.networkAvailable,localAccess:C.localAccess})}catch(C){qe(C instanceof Error?C.message:"Failed to save local access name")}finally{Y(!1)}},[ee]),Ea=b.useCallback(async()=>{Y(!0),qe(null);try{const C=await La({localAccess:{reset:!0}});pe(C.localAccess),_e(C.localAccess.name),Fn(qd,{preventSleep:C.preventSleep,networkAvailable:C.networkAvailable,localAccess:C.localAccess})}catch(C){qe(C instanceof Error?C.message:"Failed to reset local access name")}finally{Y(!1)}},[]),ml=b.useCallback(async(C,P="url")=>{if(C)try{if(typeof navigator<"u"&&navigator.clipboard)await navigator.clipboard.writeText(C);else{const de=document.createElement("textarea");de.value=C,de.style.position="fixed",de.style.left="-9999px",document.body.appendChild(de),de.focus(),de.select(),document.execCommand("copy"),document.body.removeChild(de)}ye(P),window.setTimeout(()=>ye(de=>de===P?null:de),1600)}catch{ye(null)}},[]),es=b.useCallback(C=>{const P=F$(yt,C);P.map(de=>de.id).join("\0")!==yt.map(de=>de.id).join("\0")&&(xt(P),window.dispatchEvent(new CustomEvent("reorder-terminal-session",{detail:{sessionIds:P.map(de=>de.id)}})))},[yt]),Wi=b.useCallback(C=>{Xt||C.type!=="session"||(G.current=!1,kr(!1),gn(C.draggableId))},[Xt]),Mi=b.useCallback(C=>{if(Xt||C.type!=="session")return;const P=C.destination?.droppableId===M1;P!==G.current&&(G.current=P,kr(P),P&&navigator.vibrate?.(20))},[Xt]),Gi=b.useCallback(C=>{const P=S$(C,!Xt);if(G.current=!1,kr(!1),gn(null),!P)return!1;const de=yt.find(At=>At.id===C.draggableId),rt=de?ir.get(de.id):null;return de&&P5({mode:de.mode,activeProgram:rt?.activeProgram??null,promptState:rt?.promptState??null,shellNames:_a})?(it(null),$e(de.id),He(null)):de&&window.dispatchEvent(new CustomEvent("close-terminal-session",{detail:{sessionId:de.id,source:"other",closeMode:de.mode==="tmux"?"destroy":"auto"}})),!0},[Xt,yt,ir]),{groups:gs,arranged:Ws}=k.useMemo(()=>cf(yt,C=>ir.get(C.id)?.cwd??null,Mt,e("sidebar.ungrouped"),ot,rr),[yt,ir,Mt,e,ot,rr]),Bl=b.useCallback(C=>{Gi(C)||!C.destination||C.source.index===C.destination.index||window.dispatchEvent(new CustomEvent("reorder-navigation-session",{detail:{sourceId:Ws[C.source.index]?.id,targetId:Ws[C.destination.index]?.id}}))},[Gi,Ws]),Vi=b.useCallback((C,P)=>{const de=P.trim();de&&window.dispatchEvent(new CustomEvent("rename-terminal-session",{detail:{sessionId:C,name:de}}))},[]),qi=b.useCallback(C=>{window.dispatchEvent(new CustomEvent("reset-terminal-session-name",{detail:{sessionId:C}}))},[]),{newSessionMode:fn,newSessionTmuxName:ma,userSelectedNewSessionMode:Yi,setNewSessionMode:Na}=KB(),[ji,Di]=b.useState(null),[ri,ws]=k.useState(!1),[Gs,Bi]=k.useState(!1),[Ra,ni]=k.useState(!1),[ys,Za]=k.useState("idle"),Ka=k.useRef(Tc(Bh,I$)).current,[As,Xa]=k.useState(()=>{const C=Ka?.presets;if(C&&C.length>0){const P=Ru(C);if(P.length>0)return P}return w0()}),[Ql,Ho]=k.useState(!1),[Co,ga]=k.useState("default"),Ma=k.useRef(typeof Ka?.updatedAt=="number"?Ka.updatedAt:null),Wo=k.useRef(!1),[xa,cs]=k.useState(!1),[Go,Zi]=k.useState(!1),gl=k.useRef(Tc(Ca,L$)).current,[se,T]=k.useState(gl??[]),[j,Q]=k.useState(gl!==null),[F,ge]=k.useState(!1),Se=!Rt&&!Qn&&!Gs&&!Ra&&!ri&&!xa&&!Go&&!cr&&!Me&&!ji,Oe=k.useCallback(C=>{const P=typeof C.version=="number"?C.version:0,de=E$(Array.isArray(C.presets)?C.presets:[],P);Ma.current=typeof C.updatedAt=="number"?C.updatedAt:null,Xa(rt=>G9(rt,de)?rt:(Wo.current=!0,de)),Fn(Bh,{version:e0,presets:de,updatedAt:Ma.current??void 0})},[]);b.useEffect(()=>{const C=P=>{if(P.key!=="Escape"||P.defaultPrevented||P.isComposing||B1())return;if(Gs){P.preventDefault(),Bi(!1);return}if(Ra){P.preventDefault(),ni(!1);return}if(ri){P.preventDefault(),ws(!1);return}if(xa){P.preventDefault(),cs(!1);return}if(Go){P.preventDefault(),Zi(!1);return}if(cr){P.preventDefault(),Bt();return}if(dn){P.preventDefault(),jr(null),_r(null);return}if(Ke){P.preventDefault(),Ri();return}if(qr&&!(zr&&Xt)){P.preventDefault(),Hn("right-sidebar");return}Cr&&!(mn&&Xt)&&(P.preventDefault(),Hn("left-sidebar"))};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[Gs,Ra,ri,xa,cr,Bt,Ke,qr,zr,Cr,mn,Xt,Ri,Hn]),b.useEffect(()=>{Q(!0)},[]);const[Xe,dt]=k.useState({genericProgramNames:[],wrapperScriptNames:[],shellNames:s4}),[,er]=k.useState(!1),or=k.useCallback(()=>V9().then(C=>{dt(C),_a=new Set(C.shellNames),er(!0)}).catch(()=>{}),[]);b.useEffect(()=>{or()},[or]),b.useEffect(()=>ux(C=>{if(C.type==="config-updated"){if(C.key==="toolbar-presets"){dx().then(P=>Oe(P)).catch(P=>{console.warn("[toolbar-presets] Failed to refresh after remote update:",P)});return}C.key==="program-detection"&&or()}}),[Oe,or]),b.useEffect(()=>{let C=!1;return(async()=>{try{const P=await dx();if(C)return;Oe(P)}catch(P){console.warn("[toolbar-presets] Failed to load from server:",P)}finally{C||Ho(!0)}})(),()=>{C=!0}},[Oe]),b.useEffect(()=>{if(Ql){if(Wo.current){Wo.current=!1;return}Fn(Bh,{version:e0,presets:As,updatedAt:Ma.current??void 0}),q9({version:e0,presets:As,baseUpdatedAt:Ma.current??void 0}).then(C=>{Ma.current=typeof C.updatedAt=="number"?C.updatedAt:null,Fn(Bh,{version:e0,presets:As,updatedAt:Ma.current??void 0})}).catch(C=>{const P=C instanceof Error&&"current"in C?C.current:null;P&&typeof P=="object"&&Oe(P),console.warn("[toolbar-presets] Failed to save to server:",C)})}},[Oe,As,Ql]),b.useEffect(()=>{fc().then(C=>{w(P=>P===C.preventSleep?P:C.preventSleep),S(P=>P===C.networkAvailable?P:C.networkAvailable),pe(C.localAccess),_e(C.localAccess.name),pr(C.runningSessionButtonEnabled),Fn(Yd,C.runningSessionButtonEnabled),En(C.attentionButtonEnabled),Fn(Zd,C.attentionButtonEnabled),Fn(qd,{preventSleep:C.preventSleep,networkAvailable:C.networkAvailable,localAccess:C.localAccess})}).catch(()=>{})},[]),b.useEffect(()=>{if(!L)return;const C=Tp();le(C),C!=="granted"&&(E(!1),th(!1))},[L]),b.useEffect(()=>{if(!L)return;pd();const C=()=>{document.visibilityState==="visible"&&(pd(),oA())},P=window.setInterval(()=>{pd()},360*60*1e3);return document.addEventListener("visibilitychange",C),window.addEventListener("focus",C),()=>{window.clearInterval(P),document.removeEventListener("visibilitychange",C),window.removeEventListener("focus",C)}},[L]);const $r=b.useCallback(async()=>{if(L){E(!1),th(!1),Y9(),le(Tp());return}const C=await Z9();if(le(C),C!=="granted"){E(!1),th(!1);return}E(!0),th(!0),await pd(!0,!0),Za("idle")},[L]),nn=b.useCallback(async()=>{Za("checking"),await vo()?.prepareNotificationTest?.();const C=await K9({title:"Termdock",body:e("settings.notificationsTestBody"),tag:"termdock-notification-test",requireHidden:!1,data:{url:"/"}});Za(C?"delivered":"failed")},[e]),Pn=b.useCallback(C=>{B(C),X9(C),Sp()},[]),yr=b.useCallback(C=>{O(C),J9(C),Sp()},[]),wn=b.useCallback(C=>{V(C),eA(C),Sp()},[]);b.useEffect(()=>{As.some(C=>C.id===Co)||ga(As[0]?.id??"default")},[Co,As]),b.useEffect(()=>{if(!Tr.available&&fn==="tmux"){Na("shell",{userInitiated:!1});return}Tr.available&&Yi!=="shell"&&fn!=="tmux"&&Na("tmux",{userInitiated:!1})},[fn,Tr.available,Yi,Na]),b.useEffect(()=>{Di(null)},[Ke,fn,Tr.available]),b.useEffect(()=>{const C={};typeof navigator<"u"&&(C.userAgent=navigator.userAgent,C.platform=navigator.platform,C.maxTouchPoints=navigator.maxTouchPoints,C.hasTouch=navigator.maxTouchPoints>0||"ontouchstart"in window,C.vendor=navigator.vendor),typeof window<"u"&&(C.screenWidth=window.innerWidth,C.screenHeight=window.innerHeight,C.pixelRatio=window.devicePixelRatio,C.orientation=window.screen?.orientation?.type||"unknown",C.hasVisualViewport=!!window.visualViewport,C.visualViewportHeight=window.visualViewport?.height,C.visualViewportWidth=window.visualViewport?.width,C.location=window.location.href),C.timestamp=new Date().toISOString(),C.isIOS=/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,C.isAndroid=/Android/.test(navigator.userAgent),ut(C)},[]);const us=b.useCallback(C=>{if(Gi(C)||!C.destination)return;if(C.type==="group"){if(C.source.index===C.destination.index)return;es(Vy(gs,C.source.index,C.destination.index));return}if(C.source.droppableId!==C.destination.droppableId||C.source.index===C.destination.index)return;const P=C.source.droppableId.replace(/^group-sessions:/,""),de=gs.find(rt=>rt.key===P);de&&window.dispatchEvent(new CustomEvent("reorder-navigation-session",{detail:{sourceId:de.sessions[C.source.index]?.id,targetId:de.sessions[C.destination.index]?.id}}))},[gs,es,Gi]),Ds=k.useMemo(()=>Ws.flatMap(C=>{const P=ir.get(C.id);if(P?.agentStatus!=="working")return[];const{primary:de,secondary:rt}=il(C,P?.activeProgram??null,P?.cwd??null,_a,P?.shellTitle??null,P?.promptState??null);return[{id:C.id,label:de,detail:rt}]}),[Ws,ir]),pc=Ct?Ws.findIndex(C=>C.id===Ct):-1,Vs=Ws.length>0&&pc>=0?`${pc+1}/${Ws.length}`:`${Ws.length}`,Ki=k.useMemo(()=>{let C=0;for(const P of yt){const de=ir.get(P.id);(de?.agentStatus==="waiting"||de?.agentNeedsReview)&&(C+=1)}return{running:Ds.length,review:C}},[Ds.length,yt,ir]),_o=k.useMemo(()=>Ws.flatMap(C=>{const P=ir.get(C.id);if(P?.agentStatus!=="waiting"&&!P?.agentNeedsReview)return[];const{primary:de}=il(C,P.activeProgram,P.cwd,_a,P.shellTitle,P.promptState);return[{id:P.terminalSessionId??C.id,label:de,waiting:P.agentStatus==="waiting"}]}),[Ws,ir]);tA(Ki.running,Ki.review,_o);const yi=Ct?yt.find(C=>C.id===Ct)??null:null,ko=yi?ir.get(yi.id):void 0,tu=!!(yi&&ko?.agentResumeRecovered&&ko.agentNativeSessionId&&ko.terminalSessionId),vi=yi&&pn?.sessionId===yi.id?pn:null;k.useLayoutEffect(()=>{if(!K)return;const C=Dt.current;if(!C)return;const P=!ft.current;C.scrollIntoView({inline:"nearest",block:"nearest",behavior:P?"auto":"smooth"}),ft.current=!0,P&&Mu("active-tab-positioned")},[Ct,K]),b.useEffect(()=>{tr&&Tt.current&&(Tt.current.scrollIntoView({block:"nearest",inline:"nearest"}),Tt.current.focus(),Tt.current.select()),tr||(kt.current=!1)},[tr]);const F0=b.useCallback(C=>{window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:C}))},[]),wi=b.useCallback((C,P)=>{Xn(P??null),Cn(C)},[]),sd=Cg(),Ja=b.useCallback(C=>{if(!C)return;U(C),ve.current&&ka("info","PWA_NOTIFICATION_CLICK app-focus-request",{traceId:ve.current,requestedSessionId:C,activeSessionId:Ct,sessions:yt.map(de=>({id:de.id,terminalSessionId:ir.get(de.id)?.terminalSessionId??null}))}),rA(C);const P=yt.find(de=>de.id===C||ir.get(de.id)?.terminalSessionId===C);P?(Qe.current=null,ve.current&&ka("info","PWA_NOTIFICATION_CLICK app-focus-dispatch",{traceId:ve.current,requestedSessionId:C,targetSessionId:P.id}),window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:P.id}))):(Qe.current=C,ve.current&&ka("info","PWA_NOTIFICATION_CLICK app-focus-pending",{traceId:ve.current,requestedSessionId:C}))},[Ct,yt,ir]);b.useEffect(()=>{if(typeof window>"u"||typeof caches>"u")return;let C=!1;const P=async()=>{if(window.parent!==window&&Po()){fe(!0);return}try{const rt=await caches.open(j$),At=await rt.match(py);if(!At)return;await rt.delete(py);const Zt=await At.json();if(C)return;const Nr=typeof Zt.sessionId=="string"?Zt.sessionId:null,An=typeof Zt.traceId=="string"?Zt.traceId:null,Nn=typeof Zt.clickedAt=="number"?Zt.clickedAt:0,Ln=Date.now()-Nn;ka("info","PWA_NOTIFICATION_CLICK app-cache-consumed",{traceId:An,sessionId:Nr,ageMs:Ln,valid:!!(Nr&&Ln>=0&&Ln<=my),visibilityState:document.visibilityState}),Nr&&Ln>=0&&Ln<=my&&(ve.current=An,typeof Zt.targetPeerId=="string"&&Zt.targetPeerId!==Sc()?.targetPeerId?Po()?.focusSession(Zt.targetPeerId,Nr):Ja(Nr))}catch(rt){ka("warn","PWA_NOTIFICATION_CLICK app-cache-failed",{error:rt instanceof Error?rt.message:String(rt)})}finally{C||fe(!0)}},de=()=>{document.visibilityState==="visible"&&P()};return P(),document.addEventListener("visibilitychange",de),window.addEventListener("pageshow",P),()=>{C=!0,document.removeEventListener("visibilitychange",de),window.removeEventListener("pageshow",P)}},[Ja]),b.useEffect(()=>{if(typeof window>"u")return;const C=new URLSearchParams(window.location.search),P=C.get("session");if(!P)return;ka("info","PWA_NOTIFICATION_CLICK app-url-received",{traceId:ve.current,targetSessionId:P,href:window.location.href,visibilityState:document.visibilityState});const de=C.get("service");de&&de!==Sc()?.targetPeerId?Po()?.focusSession(de,P):Qe.current=P,C.delete("service"),C.delete("session"),C.delete("_notifTrace");const rt=C.toString(),At=`${window.location.pathname}${rt?`?${rt}`:""}${window.location.hash}`;window.history.replaceState(window.history.state,"",At)},[]),b.useEffect(()=>{if(typeof window>"u")return;const C=new URLSearchParams(window.location.search);if(C.get("_notif")!=="1")return;const P=C.get("session");C.delete("_notif");const de=C.toString(),rt=`${window.location.pathname}${de?`?${de}`:""}${window.location.hash}`;if(window.history.replaceState(window.history.state,"",rt),window.parent!==window&&Po())return;const At=new BroadcastChannel("termdock:notif");let Zt=!1;const Nr=Nn=>{Nn.data?.type==="termdock:notif-pong"&&!Zt&&(Zt=!0,At.close(),window.close())};At.addEventListener("message",Nr),At.postMessage({type:"termdock:notif-ping",sessionId:P,targetPeerId:C.get("service")});const An=setTimeout(()=>{Zt||At.close()},500);return()=>{clearTimeout(An),Zt||At.close()}},[]),b.useEffect(()=>{if(typeof window>"u"||window.parent!==window&&Po())return;const C=new BroadcastChannel("termdock:notif"),P=de=>{de.data?.type==="termdock:notif-ping"&&(C.postMessage({type:"termdock:notif-pong"}),typeof de.data.sessionId=="string"&&(typeof de.data.targetPeerId=="string"&&de.data.targetPeerId!==Sc()?.targetPeerId?Po()?.focusSession(de.data.targetPeerId,de.data.sessionId):Ja(de.data.sessionId)))};return C.addEventListener("message",P),()=>C.close()},[Ja]),b.useEffect(()=>{if(typeof navigator>"u"||!("serviceWorker"in navigator))return;const C=P=>{const de=P.data;if(de&&de.type==="termdock:focus-session"&&typeof de.sessionId=="string"){if(typeof de.targetPeerId=="string"&&de.targetPeerId!==Sc()?.targetPeerId){Po()?.focusSession(de.targetPeerId,de.sessionId)&&P.ports[0]?.postMessage({type:"termdock:focus-session-ack"});return}P.ports[0]?.postMessage({type:"termdock:focus-session-ack"}),Ja(de.sessionId)}else de?.type==="termdock:push-subscription-changed"?pd(!0):de?.type};return navigator.serviceWorker.addEventListener("message",C),()=>navigator.serviceWorker.removeEventListener("message",C)},[Ja]),b.useEffect(()=>{const C=P=>{const de=P.detail;typeof de=="string"&&Ja(de)};return window.addEventListener("termdock:focus-session",C),()=>window.removeEventListener("termdock:focus-session",C)},[Ja]),b.useEffect(()=>{const C=()=>{const P=lA(Sc()?.targetPeerId);P&&Ja(P)};return C(),window.addEventListener("termdock:workspace-session",C),()=>window.removeEventListener("termdock:workspace-session",C)},[Ja]),b.useEffect(()=>{const C=Qe.current;if(!C)return;const P=yt.find(de=>de.id===C||ir.get(de.id)?.terminalSessionId===C);P?(Qe.current=null,ve.current&&ka("info","PWA_NOTIFICATION_CLICK app-pending-dispatch",{traceId:ve.current,requestedSessionId:C,targetSessionId:P.id,activeSessionId:Ct}),window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:P.id}))):ve.current&&ka("info","PWA_NOTIFICATION_CLICK app-pending-unmatched",{traceId:ve.current,requestedSessionId:C,activeSessionId:Ct,sessions:yt.map(de=>({id:de.id,terminalSessionId:ir.get(de.id)?.terminalSessionId??null}))})},[Ct,yt,ir]);const ba=k.useMemo(()=>{const C=[];for(const P of yt){const de=ir.get(P.id);(de?.agentStatus==="waiting"||de?.agentNeedsReview)&&C.push(P.id)}return C},[yt,ir]),Pl=b.useCallback(()=>{if(ba.length===0)return;Ct&&Yr.getState().clearAgentNeedsReview(Ct);const C=Ct?yt.findIndex(de=>de.id===Ct):-1,P=ba.find(de=>yt.findIndex(rt=>rt.id===de)>C)??ba[0];P&&window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:P}))},[ba,yt,Ct]),ru=b.useCallback(()=>{if(ba.length===0)return;Ct&&Yr.getState().clearAgentNeedsReview(Ct);const C=Ct?yt.findIndex(de=>de.id===Ct):yt.length,P=[...ba].reverse().find(de=>yt.findIndex(rt=>rt.id===de)<C)??ba[ba.length-1];P&&window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:P}))},[ba,yt,Ct]);b.useEffect(()=>{const C=P=>{!P.altKey||!P.shiftKey||P.metaKey||P.ctrlKey||P.key!=="ArrowUp"&&P.key!=="ArrowDown"||(P.preventDefault(),P.key==="ArrowUp"?ru():Pl())};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[Pl,ru]);const ap=b.useCallback(async C=>{const de=Yr.getState().sessions.get(C)?.cwd;if(de)try{await navigator.clipboard?.writeText(de),Gn(de),window.setTimeout(()=>{Gn(rt=>rt===de?null:rt)},1400)}catch{}},[]),op=b.useCallback(C=>{xt(C.sessions),fr(C.activeSessionId),pt(C.splitWorkspaces),Yr.getState().setActiveSessionId(C.activeSessionId)},[]),lp=b.useCallback(()=>{Sr(!0)},[]),cp=b.useCallback(()=>{Sr(!0),window.requestAnimationFrame(()=>{window.dispatchEvent(new Event("termdock:initial-viewport-presented"))})},[]);b.useEffect(()=>{if(!N||!Ct)return;yt.find(P=>P.id===N||ir.get(P.id)?.terminalSessionId===N)?.id===Ct&&U(null)},[Ct,N,yt,ir]);const id=b.useRef(!1),[nu,$0]=b.useState(!1),ja=b.useCallback(C=>{const P=!C?.onResult;if(P&&id.current)return;P&&(id.current=!0,$0(!0));const de=C?.mode??fn,rt=de==="tmux"&&(C?.tmuxSessionName?.trim()||ma.trim())||void 0,At=C?.cwd||(Ct?Yr.getState().sessions.get(Ct)?.cwd:void 0);window.dispatchEvent(new CustomEvent("new-terminal-session",{detail:{mode:de,tmuxSessionName:rt,cwd:At,command:C?.command,shouldActivate:C?.shouldActivate,onResult:C?.onResult??(Zt=>{id.current=!1,$0(!1),Zt.ok||Gr({tone:"error",message:e(zm(Zt.error))})})}}))},[fn,ma,Ct,e]),Vo=b.useCallback(async()=>{Qr(!0);try{const C=await Qm();if(Jr(C),!C.available){jn([]);return}const P=await Pm();jn(P)}catch{Jr({available:!1,version:null,reason:"tmux integration is unavailable with the current server build."}),jn([])}finally{Qr(!1)}},[]),mc=b.useCallback(async C=>{const{cleanedSessions:P}=await Ty(C);for(const de of P)window.dispatchEvent(new CustomEvent("close-terminal-session-by-backend",{detail:de}));await Vo()},[Vo]),su=b.useCallback(async C=>{xn(C),He(null);try{await mc(C),Dr(null)}catch(P){He(P instanceof Error?P.message:"Failed to kill tmux session")}finally{xn(null)}},[mc]);b.useEffect(()=>{if(!Nt)return;if(Mr.find(de=>de.name===Nt&&(de.connected||de.boundFrontendSessionId))){Et(null);return}const P=setTimeout(()=>Et(null),1e4);return()=>clearTimeout(P)},[Nt,Mr]);const gc=b.useCallback(C=>{window.dispatchEvent(new CustomEvent("close-terminal-session",{detail:C}))},[]),iu=b.useCallback(C=>{const P=C??Ct;P&&window.dispatchEvent(new CustomEvent("open-terminal-split-chooser",{detail:P}))},[Ct]),ad=b.useCallback((C,P)=>{window.dispatchEvent(new CustomEvent("set-terminal-split-direction",{detail:{sessionId:C,layout:P}}))},[]),U0=b.useCallback((C,P)=>{window.dispatchEvent(new CustomEvent("reorder-terminal-split-workspace",{detail:{workspaceId:C,sessionIds:P}}))},[]),z0=b.useCallback((C,P)=>{window.dispatchEvent(new CustomEvent("rename-terminal-split-workspace",{detail:{workspaceId:C,name:P}}))},[]),H0=b.useCallback((C,P)=>{window.dispatchEvent(new CustomEvent("combine-terminal-split-sessions",{detail:{primaryId:C,secondaryId:P}}))},[]),Ol=b.useCallback((C,P,de)=>{const rt=yt.find(Zt=>Zt.id===C);if(!rt)return;const At=ir.get(C);if(de?.skipConfirmation||!P5({mode:rt.mode,activeProgram:At?.activeProgram??null,promptState:At?.promptState??null,shellNames:_a})){gc({sessionId:C,source:"sidebar",closeMode:rt.mode==="tmux"?"destroy":"auto"});return}it(P?{x:P.clientX,y:P.clientY}:null),$e(C),He(null)},[yt,ir,gc]);b.useEffect(()=>{if(!Pe)return;const C=P=>{const de=P.detail;de==="new-session"?ja():de==="close-session"?Ct&&Ol(Ct):de==="previous-session"||de==="next-session"?window.dispatchEvent(new CustomEvent("cycle-terminal-session",{detail:{direction:de==="next-session"?"next":"prev"}})):de==="toggle-left-sidebar"?as():de==="toggle-right-sidebar"?xi():de==="previous-attention"?ru():de==="next-attention"&&Pl()};return window.addEventListener("termdock:native-command",C),()=>window.removeEventListener("termdock:native-command",C)},[Ct,Pe,ja,Ol,as,xi,Pl,ru]);const eo=k.useMemo(()=>yt.find(C=>C.id===Me)??null,[yt,Me]),od=b.useCallback(()=>{eo&&(gc({sessionId:eo.id,source:"sidebar",closeMode:"destroy"}),$e(null),it(null))},[eo,gc]);b.useEffect(()=>{if(!eo)return;const C=P=>{if(P.key==="Escape"){P.preventDefault(),P.stopImmediatePropagation(),$e(null),it(null),He(null);return}P.key!=="Enter"||P.isComposing||P.keyCode===229||P.altKey||P.ctrlKey||P.metaKey||P.shiftKey||(P.preventDefault(),P.stopImmediatePropagation(),P.repeat||od())};return window.addEventListener("keydown",C,!0),()=>window.removeEventListener("keydown",C,!0)},[eo,od]);const W0=k.useMemo(()=>{if(!eo)return"";const C=ir.get(eo.id);return il(eo,C?.activeProgram??null,C?.cwd??null,_a,C?.shellTitle??null,C?.promptState??null).primary},[eo,ir]);b.useEffect(()=>{if(!Ke)return;let C=!1,P=!1;const de=async()=>{if(!P)try{const At=await Qm();if(C||Jr(At),!At.available){C||jn([]);return}const Zt=await Pm();C||jn(Zt)}catch{P=!0,C||(Jr({available:!1,version:null,reason:"tmux integration is unavailable with the current server build."}),jn([]))}};de();const rt=setInterval(()=>{de()},4e3);return()=>{C=!0,clearInterval(rt)}},[Ke]);const xc=ji??fn,Fl=xc==="shell",au=xc==="tmux"&&Tr.available,xl=k.useMemo(()=>Gy(Mr.map(C=>({...C,id:C.name})),C=>C.cwd??null,e("sidebar.ungrouped")),[Mr,e]),ld=k.useMemo(()=>Mr.filter(C=>C.recoveryCandidate===!0&&!C.connected&&!C.boundFrontendSessionId).sort((C,P)=>(P.lastActiveAt??P.createdAt??0)-(C.lastActiveAt??C.createdAt??0)),[Mr]);b.useEffect(()=>{!Cr&&!(mn&&Xt)||Vo()},[Cr,mn,Xt,yt.length,Vo]);const bc=(C,P,de,rt=!1)=>{const At=C.id===Ct,Zt=C.id===tr,Nr=ir.get(C.id),{primary:An,secondary:Nn}=il(C,Nr?.activeProgram??null,Nr?.cwd??null,_a,Nr?.shellTitle??null,Nr?.promptState??null),Ln=Ku(Nr?.cwd??null),Ai=P?Nn??(Ln&&Ln!==An?Ln:null):null,Tn=Nr?.gitStatus,Xi=`${Nr?.cwd||C.name}${Tn?`
|
|
186
186
|
⎇ ${Tn.branch} +${Tn.added} −${Tn.removed}`:""}`,Io=!!(Nr?.tuiProgress&&Nr.tuiProgress.state!=="remove"),Eo=Nr?.agentStatus==="working"||Io?"var(--success)":Nr?.agentStatus==="waiting"||Nr?.agentNeedsReview?"var(--warning)":Nr?.inCopyMode?"var(--tmux)":null;if(Zt&&Xt&&!dn){const Ba=C.customName?C.name:An,Qi=(to,up)=>{const dd=up.trim();dd?dd!==Ba&&Vi(to,dd):qi(to),jr(null)};return s.jsx("input",{ref:to=>{Tt.current=to},type:"text",defaultValue:Ba,className:"h-8 shrink-0 rounded-md bg-surface-elevated px-2 text-[12px] leading-none text-foreground outline-none ring-1 ring-primary/50 sm:h-8 min-w-[5rem]",style:{width:`${Math.max(Ba.length,5)}ch`},onKeyDown:to=>{to.key==="Enter"?Qi(C.id,to.target.value):to.key==="Escape"&&jr(null)},onBlur:to=>Qi(C.id,to.target.value)})}return s.jsx("div",{ref:At?Dt:null,onContextMenu:Ba=>{Ba.preventDefault(),Xn({x:Ba.clientX,y:Ba.clientY}),Cn(C.id)},...sd(()=>wi(C.id)),className:rt?`group relative inline-flex h-5 shrink-0 items-center rounded-sm text-[11px] leading-none transition ${At?"bg-surface-elevated text-foreground shadow-sm":"text-muted-foreground hover:bg-surface-elevated/40 hover:text-foreground"}`:`group relative inline-flex h-8 shrink-0 items-center rounded-md text-[12px] leading-none transition sm:h-8 ${At?"bg-surface-elevated text-foreground shadow-sm":"text-muted-foreground hover:bg-surface-elevated/50 hover:text-foreground"}`,style:!rt&&At&&Eo?{boxShadow:`inset 2px 0 0 0 ${Eo}`}:!rt&&At?{boxShadow:"inset 2px 0 0 0 rgb(var(--primary-rgb, 99 102 241))"}:void 0,title:Xi,children:s.jsx("button",{type:"button",...de??{},onClick:()=>F0(C.id),className:`inline-flex min-w-0 flex-1 items-center gap-1 overflow-hidden text-left ${rt?"px-1":"py-1 pl-1 pr-1.5 sm:pl-1.5 sm:pr-2"} ${de?"cursor-grab active:cursor-grabbing":""}`,title:Xi,children:s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1 overflow-hidden",children:[s.jsxs("span",{className:"inline-flex shrink-0 items-center",children:[xy(C.mode,Nr),Nr?.agentResumeRecovered&&s.jsx(Qc,{size:rt?9:10,className:"-ml-0.5 shrink-0 text-[color:var(--warning)]","aria-label":e("tab.resumeAgentAvailable")}),Io&&!Nr?.agentStatus&&s.jsx(_n,{size:rt?9:10,className:"-ml-0.5 shrink-0 animate-spin text-[color:var(--success)]"})]}),Ai?s.jsxs("span",{className:"flex min-w-0 flex-col justify-center leading-[0.82rem] sm:leading-[0.85rem]",children:[s.jsx("span",{className:`whitespace-nowrap text-[11px] sm:text-[12px] ${Nr?.inCopyMode?"text-[color:var(--tmux)]":""}`,children:An}),s.jsx("span",{className:"truncate text-[9px] text-muted-foreground/80 sm:text-[9.5px]",children:Ai})]}):s.jsx("span",{className:`whitespace-nowrap text-[11px] sm:text-[12px] ${Nr?.inCopyMode?"text-[color:var(--tmux)]":""}`,children:An})]})})})},cd=()=>s.jsx(Ll,{droppableId:M1,type:"session",isDropDisabled:Xt,children:(C,P)=>{const de=Jn||P.isDraggingOver;return s.jsxs("div",{ref:C.innerRef,...C.droppableProps,className:"pointer-events-none fixed left-1/2 top-[42%] z-toast flex h-32 w-32 -translate-x-1/2 -translate-y-1/2 items-center justify-center",role:"status","aria-live":"polite","aria-hidden":!Vn,"data-mobile-session-destroy-target":"","data-active":de?"true":"false",children:[s.jsxs("div",{className:`flex h-28 w-28 flex-col items-center justify-center gap-2 rounded-full border bg-surface-elevated/95 shadow-2xl backdrop-blur transition duration-200 ${Vn?de?"scale-110 border-destructive bg-destructive text-destructive-foreground opacity-100":"scale-100 border-destructive/50 text-destructive opacity-100":"scale-75 border-transparent opacity-0"}`,children:[s.jsx(Rs,{size:28,strokeWidth:1.8}),s.jsx("span",{className:"px-2 text-center text-[11px] font-semibold leading-tight",children:e(de?"tab.releaseToClose":"tab.dragToClose")})]}),C.placeholder]})}}),ya=mn&&Xt,$l=zr&&Xt,ud=Oh(un,Jt,ya?on:0),yc=$l?ud+Ay:0,Ul=ya?yt.find(C=>C.id===Ct):null,Bs=Ul?ir.get(Ul.id):void 0,G0=Ul?il(Ul,Bs?.activeProgram??null,Bs?.cwd??null,_a,Bs?.shellTitle??null,Bs?.promptState??null).primary:"",Da=Xt?lt:null,Lo=ya&&!Da&&Bs?Bs.agentStatus==="working"?"bg-gradient-to-r from-[rgb(var(--success-rgb)_/_0.08)] to-transparent":Bs.agentStatus==="waiting"?"bg-gradient-to-r from-[rgb(var(--warning-rgb)_/_0.14)] to-transparent":Bs.agentNeedsReview?"bg-gradient-to-r from-[rgb(var(--warning-rgb)_/_0.08)] to-transparent":Bs.inCopyMode?"bg-gradient-to-r from-[rgb(var(--tmux-rgb)_/_0.07)] to-transparent":"":"",zl=s.jsxs("div",{className:"w-full h-full flex flex-col app-chrome-bg text-foreground",children:[yn&&s.jsxs("div",{role:"alert",className:"flex shrink-0 items-center gap-2 bg-surface-2 px-3 py-2 text-xs",children:[s.jsx("p",{className:"min-w-0 flex-1 break-words",children:yn}),s.jsx("button",{type:"button",className:"min-h-11 px-2 text-primary",onClick:()=>hn(""),children:e("common.close")})]}),s.jsx("main",{className:"relative min-h-0 flex-1 overflow-visible px-0 pb-0 pt-0",children:s.jsxs(sC,{rightInset:yc,workspace:Rt&&s.jsx(k.Suspense,{fallback:s.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-[var(--chrome-bg)] text-sm text-muted-foreground",children:"正在打开协作工作区…"}),children:s.jsx($$,{groupId:Rt,activeSessionId:Ct,defaultSessionMode:fn,onOpenSidebar:as,leftSidebarVisible:Cr||ya,onToggleRightSidebar:xi,rightSidebarOpen:qr||$l},Rt)}),children:[s.jsxs("div",{className:`${Xt?"absolute inset-x-0 top-0 z-20":"relative"} shrink-0 items-center gap-1 app-chrome-bg px-1 sm:px-1.5 transition-colors duration-500 ${ya?"flex justify-end":"flex justify-between"} ${Mt?"h-10 sm:h-10":"h-9 sm:h-10"} ${Lo}`,style:{position:Xt?"absolute":void 0,marginRight:yc||void 0,display:Da?"none":void 0},children:[!ya&&s.jsxs("button",{type:"button",onClick:as,className:"relative inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-surface-2 text-muted-foreground ring-1 ring-border/10 transition hover:bg-surface-elevated hover:text-foreground sm:h-8 sm:w-8","aria-label":e("tab.sessionsTitle"),title:`${e("tab.sessionsTitle")} · ${e("agent.aiRunning")}: ${Ki.running} · ${e("agent.needsReview")}: ${Ki.review}`,children:[s.jsx(WT,{size:14}),s.jsx(zP,{runningCount:Ki.running,reviewCount:Ki.review,className:"sm:hidden"})]}),ya?s.jsx("div",{className:"absolute left-1/2 flex max-w-[40%] min-w-0 -translate-x-1/2 items-center justify-center gap-1.5 overflow-hidden",children:Ul?s.jsxs(s.Fragment,{children:[xy(Ul.mode,Bs),s.jsx("span",{className:`truncate text-[12px] font-medium ${Bs?.inCopyMode?"text-[color:var(--tmux)]":"text-foreground"}`,children:G0}),Bs?.agentStatus==="working"&&s.jsx("span",{title:Bs?.agentMessage??void 0,children:s.jsx(_n,{size:12,className:"shrink-0 animate-spin text-[color:var(--success)]"})}),Bs?.agentStatus==="waiting"&&s.jsx("span",{title:Bs?.agentMessage??void 0,children:s.jsx(of,{size:12,className:"shrink-0 animate-bounce-y text-[color:var(--warning)]"})}),!Bs?.agentStatus&&Bs?.agentNeedsReview&&s.jsx("span",{title:Bs?.agentMessage??void 0,children:s.jsx(cc,{size:13,className:"shrink-0 animate-pulse text-[color:var(--warning)]"})})]}):s.jsx("span",{className:"truncate px-2 text-[12px] text-muted-foreground",children:e("sidebar.sessions")})}):Mt?s.jsxs(h0,{onDragStart:Wi,onDragUpdate:Mi,onDragEnd:us,children:[cd(),s.jsx(Ll,{droppableId:"groups",type:"group",direction:"horizontal",children:C=>s.jsxs("div",{ref:C.innerRef,...C.droppableProps,className:"scrollbar-hidden flex h-full min-w-0 flex-1 items-center gap-1 overflow-x-auto overflow-y-hidden whitespace-nowrap px-0.5 py-0.5",style:{touchAction:"pan-x"},children:[gs.map((P,de)=>{let rt=0,At=0;for(const Nn of P.sessions){const Ln=ir.get(Nn.id);Ln?.agentStatus==="working"&&(rt+=1),(Ln?.agentStatus==="waiting"||Ln?.agentNeedsReview)&&(At+=1)}const Zt=P.sessions.some(Nn=>Nn.id===Ct),Nr=Ar.has(P.key),An=P.key==="";return s.jsx(kl,{draggableId:`group-${P.key||"__ungrouped__"}`,index:de,isDragDisabled:An,disableInteractiveElementBlocking:!0,children:(Nn,Ln)=>s.jsxs("div",{ref:Nn.innerRef,...Nn.draggableProps,className:`flex w-fit shrink-0 flex-col justify-center gap-px rounded-md py-0.5 px-1 ring-1 transition-colors ${Ln.isDragging?"bg-surface-elevated ring-primary/30 shadow-lg opacity-90":Zt?"bg-primary/[0.06] ring-primary/20":"bg-surface-2/40 ring-border/10"}`,children:[s.jsxs("button",{type:"button",...An?{}:Nn.dragHandleProps,onClick:()=>Fr(P.key),className:`flex ${Nr?"":P.sessions.length>1?"w-0 min-w-full":""} items-center gap-0.5 rounded text-[9px] font-semibold uppercase tracking-[0.08em] leading-none transition hover:bg-surface-elevated/40 ${An?"":"cursor-grab active:cursor-grabbing"} ${Zt?"text-primary/80":"text-muted-foreground/55"}`,title:P.key||P.label,children:[s.jsx(Ks,{size:9,className:`shrink-0 opacity-70 transition-transform ${Nr?"":"rotate-90"}`}),s.jsx("span",{className:"min-w-0 truncate",children:P.label}),rt>0&&s.jsx("span",{className:"ml-auto h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--success)]"}),At>0&&s.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--warning)] ${rt>0?"":"ml-auto"}`})]}),Nr?s.jsx("span",{className:"flex h-5 items-center text-[10px] leading-none text-muted-foreground/50",children:e("tab.sessionCount",{count:P.sessions.length})}):s.jsx(Ll,{droppableId:`group-sessions:${P.key}`,type:"session",direction:"horizontal",children:Ai=>s.jsxs("div",{ref:Ai.innerRef,...Ai.droppableProps,className:"flex items-center gap-px",children:[P.sessions.map((Tn,Xi)=>s.jsx(kl,{draggableId:Tn.id,index:Xi,disableInteractiveElementBlocking:!0,children:(Io,Eo)=>s.jsx("div",{ref:Io.innerRef,...Io.draggableProps,className:`flex shrink-0 items-center ${Eo.isDragging?"opacity-70":""}`,children:bc(Tn,!1,Io.dragHandleProps,!0)})},Tn.id)),Ai.placeholder]})})]})},P.key||"__ungrouped__")}),C.placeholder,s.jsx("button",{type:"button",onClick:()=>ja(),disabled:nu,"aria-busy":nu,className:"my-auto inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-surface-2 text-muted-foreground ring-1 ring-border/10 transition hover:bg-primary/15 hover:text-primary active:scale-95","aria-label":e("tab.new"),title:e("tab.new"),children:s.jsx(zs,{size:14})})]})})]}):s.jsxs(h0,{onDragStart:Wi,onDragUpdate:Mi,onDragEnd:Bl,children:[cd(),s.jsx(Ll,{droppableId:"tabs",type:"session",direction:"horizontal",children:C=>s.jsxs("div",{ref:C.innerRef,...C.droppableProps,className:"scrollbar-hidden flex h-full min-w-0 flex-1 items-center gap-1 overflow-x-auto overflow-y-hidden whitespace-nowrap",style:{touchAction:"pan-x"},children:[Ws.map((P,de)=>P.id===tr?s.jsx(k.Fragment,{children:s.jsx(kl,{draggableId:P.id,index:de,isDragDisabled:!0,children:At=>s.jsx("div",{ref:At.innerRef,...At.draggableProps,className:"flex h-full items-center",children:bc(P,!0)})})},P.id):s.jsx(k.Fragment,{children:s.jsx(kl,{draggableId:P.id,index:de,disableInteractiveElementBlocking:!0,children:(At,Zt)=>s.jsx("div",{ref:At.innerRef,...At.draggableProps,className:`flex h-full shrink-0 items-center ${Zt.isDragging?"opacity-70":""}`,children:bc(P,!0,At.dragHandleProps)})})},P.id)),s.jsx("button",{type:"button",onClick:()=>ja(),disabled:nu,"aria-busy":nu,className:"ml-1 inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-surface-2 text-muted-foreground ring-1 ring-border/10 transition hover:bg-primary/15 hover:text-primary active:scale-95","aria-label":e("tab.new"),title:e("tab.new"),children:s.jsx(zs,{size:14})}),C.placeholder]})})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[!ya&&Ki.running>0&&s.jsx("span",{className:"hidden items-center gap-1 sm:inline-flex",children:s.jsx(P6,{count:Ki.running,tone:"running",title:e("agent.aiRunning")})}),!ya&&yt.length>0&&s.jsx("span",{className:"inline-flex shrink-0 items-center px-1 text-[10px] uppercase tracking-[0.16em] text-muted-foreground sm:text-[11px]",title:`Session ${pc+1} of ${yt.length}`,children:Vs}),!$l&&s.jsx("button",{type:"button",onClick:xi,className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-surface-2 text-muted-foreground ring-1 ring-border/10 transition hover:bg-surface-elevated hover:text-foreground sm:h-8 sm:w-8","aria-label":e("tab.explorerTitle"),title:e("tab.explorerTitle"),children:s.jsx($y,{size:14})})]})]}),tu&&yi&&ko?.terminalSessionId&&s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border/15 bg-surface/80 px-3 py-2 animate-fade-in sm:px-4",style:{marginRight:yc||void 0},role:"status","data-testid":"agent-resume-recovery-banner",children:[s.jsx("span",{className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-[rgb(var(--warning-rgb)_/_0.14)] text-[color:var(--warning)]",children:!vi?.error&&(vi?.status==="submitting"||vi?.status==="waiting")?s.jsx(_n,{size:14,className:"animate-spin"}):s.jsx(Qc,{size:14})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"truncate text-[12px] font-medium text-foreground",children:e("tab.resumeAgentRecoveredTitle",{agent:ko.agent?.displayName??"Agent"})}),s.jsx("div",{className:`truncate text-[10px] sm:text-[11px] ${vi?.error?"text-destructive":"text-muted-foreground"}`,children:vi?.error??(vi?.status==="submitting"?e("tab.resumeAgentSubmitting"):vi?.status==="waiting"?e("tab.resumeAgentWaiting"):e("tab.resumeAgentRecoveredHint"))})]}),s.jsx("button",{type:"button",disabled:!vi?.error&&(vi?.status==="submitting"||vi?.status==="waiting"),onClick:()=>{Xr(yi.id,ko.terminalSessionId)},className:"shrink-0 rounded-full bg-primary px-3 py-1.5 text-[11px] font-semibold text-primary-foreground transition hover:opacity-90 active:scale-95 disabled:cursor-wait disabled:opacity-60 sm:text-[12px]",children:vi?.error?e("common.retry"):e("tab.resumeAgentNow")}),s.jsx("button",{type:"button",onClick:()=>{Yr.getState().setAgentResumeRecovered(yi.id,!1),dr(C=>C?.sessionId===yi.id?null:C)},className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-muted-foreground transition hover:bg-surface-2 hover:text-foreground","aria-label":e("tab.resumeAgentLater"),title:e("tab.resumeAgentLater"),children:s.jsx(In,{size:13})})]}),s.jsx("div",{ref:tn,className:"min-h-0 flex-1 flex overflow-hidden app-chrome-bg",children:s.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:s.jsx(LN,{terminalSettings:qt,colorTheme:p,toolbarPresets:As,showDebug:l&&Xt,terminalFocusAvailable:Se,defaultSessionMode:fn,defaultTmuxSessionName:ma,connectionPrioritySessionId:N,connectionPriorityReady:K,desktopRightSidebarEnabled:Xt,onToggleRightSidebar:xi,desktopFloatingTitle:Xt,desktopPinnedLeftSidebarWidth:ya?on:0,desktopViewportWidth:Jt,onSessionDataUpdate:op,onInitialViewportReady:cp,onInitialRecoveryRequired:lp})})})]})}),!Rt&&s.jsx(qP,{reviewCount:Ki.review,runningSessions:Ds,activeSessionId:Ct,runningButtonEnabled:Lr,attentionButtonEnabled:Un,isDesktopLayout:Xt,containerElement:ss,occlusionInsets:{right:yc}}),Ke&&s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"fixed inset-0 z-drawer-backdrop bg-[var(--app-backdrop)] backdrop-blur-sm animate-fade-in cursor-default",onClick:Ri,"aria-label":e("settings.closeSettings")}),s.jsx("div",{role:"dialog","aria-modal":"true","aria-labelledby":"settings-dialog-title",className:"pointer-events-none fixed inset-0 z-drawer-panel flex items-stretch justify-center p-0 animate-fade-in sm:p-4 md:p-6",children:s.jsxs("div",{className:"pointer-events-auto flex h-full w-full max-w-5xl flex-col overflow-hidden bg-surface shadow-[0_28px_90px_var(--app-shadow-strong),0_14px_34px_var(--app-shadow-soft)] sm:max-h-[calc(100dvh-3rem)] sm:rounded-3xl sm:border sm:border-border/15",style:{paddingTop:n,paddingBottom:a},children:[s.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border/15 px-4 py-3 sm:px-6 sm:py-4",children:[s.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[s.jsx("span",{className:"inline-flex h-8 w-8 items-center justify-center rounded-full bg-primary/15 text-primary sm:h-9 sm:w-9",children:s.jsx(Um,{size:15})}),s.jsx("h2",{id:"settings-dialog-title",className:"text-[15px] font-semibold text-foreground sm:text-[16px]",children:e("settings.title")})]}),s.jsx("button",{type:"button",onClick:Ri,className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-surface-2 text-muted-foreground transition hover:bg-destructive/20 hover:text-destructive","aria-label":e("common.close"),children:s.jsx(In,{size:16})})]}),s.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto bg-background/25 px-3 py-3 sm:px-6 sm:py-5 md:px-8",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-surface-2 px-2.5 py-2",children:[s.jsx("span",{className:"text-[12px] font-medium text-foreground/90 w-14 shrink-0",children:e("settings.font")}),s.jsx("button",{type:"button",onClick:()=>tt({fontSize:Math.max(8,De-1)}),className:"h-8 w-8 shrink-0 rounded-md bg-surface text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground active:scale-95",children:"−"}),s.jsx("input",{type:"range",min:"8",max:"32",value:De,onChange:C=>tt({fontSize:parseInt(C.target.value,10)}),className:"min-w-0 flex-1","aria-label":e("settings.font")}),s.jsx("button",{type:"button",onClick:()=>tt({fontSize:Math.min(32,De+1)}),className:"h-8 w-8 shrink-0 rounded-md bg-surface text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground active:scale-95",children:"+"}),s.jsxs("span",{className:"w-8 shrink-0 text-right text-[11px] tabular-nums text-muted-foreground",children:[De,"px"]})]}),s.jsx(T$,{}),s.jsx("div",{className:"space-y-1.5 rounded-xl bg-surface-2 px-2.5 py-2",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-[12px] font-medium text-foreground/90 w-14 shrink-0",children:e("settings.render")}),s.jsx("div",{className:"flex flex-1 items-center gap-1 rounded-md bg-surface p-0.5",children:["auto","webgl","canvas"].map(C=>{const P=nr===C;return s.jsx("button",{type:"button",onClick:()=>tt({rendererMode:C}),className:`flex-1 rounded px-2 py-1 text-[11px] font-medium transition ${P?"bg-primary/20 text-primary":"text-muted-foreground hover:bg-surface-elevated"}`,children:e(C==="auto"?"settings.auto":C==="webgl"?"settings.webgl":"settings.canvas")},C)})})]})}),s.jsx("div",{className:"space-y-1.5 rounded-xl bg-surface-2 px-2.5 py-2",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-[12px] font-medium text-foreground/90 w-14 shrink-0",children:e("settings.theme")}),s.jsx("div",{className:"flex flex-1 items-center gap-1 rounded-md bg-surface p-0.5",children:[["dark",QT,e("settings.darkTheme")],["light",LS,e("settings.lightTheme")]].map(([C,P,de])=>{const rt=p===C;return s.jsxs("button",{type:"button",onClick:()=>m(C),className:`flex flex-1 items-center justify-center gap-1 rounded px-2 py-1 text-[11px] font-medium transition ${rt?"bg-primary/20 text-primary":"text-muted-foreground hover:bg-surface-elevated"}`,children:[s.jsx(P,{size:12}),s.jsx("span",{children:de})]},C)})})]})}),s.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-surface-2 px-2.5 py-2",children:[s.jsx("span",{className:"text-[12px] font-medium text-foreground/90 w-14 shrink-0",children:e("settings.newTab")}),s.jsx("div",{className:"flex flex-1 items-center gap-1 rounded-md bg-surface p-0.5",children:["shell","tmux"].map(C=>{const P=fn===C,de=C==="tmux"&&!Tr.available;return s.jsx("button",{type:"button",disabled:de,onClick:()=>Na(C,{userInitiated:!0}),className:`flex-1 rounded px-2 py-1 text-[11px] font-medium transition ${P?"bg-primary/20 text-primary":de?"cursor-not-allowed text-muted-foreground/40":"text-muted-foreground hover:bg-surface-elevated"}`,title:de?Tr.reason||e("settings.installTmuxHint"):void 0,children:e(C==="shell"?"settings.shell":"settings.tmux")},C)})})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[s.jsxs("button",{type:"button",onClick:()=>d(!l),className:`flex items-center justify-between rounded-xl px-3 py-2 text-[12px] transition ${l?"bg-primary/15 text-primary":"bg-surface-2 text-foreground hover:bg-surface-elevated"}`,children:[s.jsx("span",{className:"font-medium",children:e("settings.debug")}),s.jsx(ll,{checked:l,size:"sm"})]}),s.jsxs("button",{type:"button",onClick:async()=>{const C=!y;w(C);try{const P=await La({preventSleep:C});w(P.preventSleep),S(P.networkAvailable),pe(P.localAccess),Fn(qd,{preventSleep:P.preventSleep,networkAvailable:P.networkAvailable,localAccess:P.localAccess})}catch{w(!C)}},className:`flex items-center justify-between rounded-xl px-3 py-2 text-[12px] transition ${y?"bg-[rgb(var(--success-rgb)_/_0.15)] text-[color:var(--success)]":"bg-surface-2 text-foreground hover:bg-surface-elevated"}`,title:!v&&y?e("settings.noSleepUnavailable"):void 0,children:[s.jsx("span",{className:"font-medium truncate",children:e("settings.noSleep")}),s.jsx(ll,{checked:y,size:"sm"})]})]})]}),s.jsxs("div",{className:"mt-3 space-y-2",children:[s.jsxs("button",{type:"button",role:"switch","aria-checked":Lr,"aria-label":e("sidebar.runningSessionButton"),onClick:()=>{ns(!Lr)},className:"flex w-full items-center gap-2 rounded-xl bg-surface-2 px-3 py-2.5 text-left text-[13px] transition hover:bg-surface-elevated",children:[s.jsx(lf,{size:14,className:Lr?"shrink-0 text-[color:var(--success)]":"shrink-0 text-muted-foreground"}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block font-medium text-foreground",children:e("sidebar.runningSessionButton")}),s.jsx("span",{className:"mt-0.5 block text-[10px] leading-tight text-muted-foreground",children:e("sidebar.runningSessionButtonHint")})]}),s.jsx(ll,{checked:Lr,size:"sm"})]}),s.jsxs("button",{type:"button",role:"switch","aria-checked":Un,"aria-label":e("sidebar.attentionButton"),onClick:()=>{kn(!Un)},className:"flex w-full items-center gap-2 rounded-xl bg-surface-2 px-3 py-2.5 text-left text-[13px] transition hover:bg-surface-elevated",children:[s.jsx(cc,{size:14,className:Un?"shrink-0 text-[color:var(--warning)]":"shrink-0 text-muted-foreground"}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block font-medium text-foreground",children:e("sidebar.attentionButton")}),s.jsx("span",{className:"mt-0.5 block text-[10px] leading-tight text-muted-foreground",children:e("sidebar.attentionButtonHint")})]}),s.jsx(ll,{checked:Un,size:"sm"})]})]}),s.jsxs("button",{type:"button",onClick:()=>ni(!0),className:"mt-3 flex w-full items-center justify-between gap-2 rounded-xl bg-surface-2 px-3 py-2.5 text-left text-[13px] transition hover:bg-surface-elevated",children:[s.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[s.jsx(Dy,{size:14,className:L?"shrink-0 text-primary":"shrink-0 text-muted-foreground"}),s.jsxs("span",{className:"min-w-0",children:[s.jsx("span",{className:"block font-medium text-foreground",children:e("settings.notifications")}),s.jsx("span",{className:"block truncate text-[10px] text-muted-foreground",children:e(L?R&&z?"settings.notificationsBothOnSummary":R?"settings.notificationsAiOnSummary":z?"settings.notificationsExitOnSummary":"settings.notificationsNoEventsSummary":"settings.notificationsOffSummary")})]})]}),s.jsxs("span",{className:"flex shrink-0 items-center gap-1.5 text-[11px] text-muted-foreground",children:[s.jsx("span",{children:e(L?"common.on":"common.off")}),s.jsx("span",{children:"›"})]})]}),s.jsxs("button",{type:"button",onClick:()=>Bi(!0),className:"mt-3 flex w-full items-center justify-between gap-3 rounded-xl bg-surface-2 px-3 py-3 text-left transition hover:bg-surface-elevated",children:[s.jsxs("span",{children:[s.jsx("span",{className:"block text-[12px] font-medium text-foreground/90",children:e("settings.localAccess")}),s.jsx("span",{className:"mt-0.5 block text-[10px] text-muted-foreground",children:e("settings.localAccessHint")})]}),s.jsx(Ks,{size:16,className:"shrink-0 text-muted-foreground"})]}),s.jsx(g$,{state:Le,pending:ne,onCheck:()=>{bt()},onConfirmRestart:()=>{st()},desktopState:Ne?nt:void 0,desktopPending:ue,onCheckDesktop:Ne?()=>{Br()}:void 0,onInstallDesktop:()=>{Vr()},desktopSnapshot:oe,desktopActions:Pe?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-1 gap-px border-t border-border/10 bg-border/10 sm:grid-cols-2",children:[s.jsxs("button",{type:"button",onClick:()=>{Pe.showConnectionCenter()},className:"flex items-center gap-2 bg-surface-2 px-3 py-2.5 text-left text-[11px] text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground",children:[s.jsx(QA,{size:13,className:"shrink-0 text-primary"}),e("settings.desktopSwitchService")]}),s.jsxs("button",{type:"button",onClick:()=>{Ie(null),Pe.revealDataDirectory().catch(C=>Ie(C instanceof Error?C.message:String(C)))},className:"flex items-center gap-2 bg-surface-2 px-3 py-2.5 text-left text-[11px] text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground",children:[s.jsx(Du,{size:13,className:"shrink-0 text-primary"}),e("settings.desktopOpenDataDirectory")]})]}),at&&s.jsx("div",{className:"border-t border-border/10 px-3 py-2 text-[10px] text-muted-foreground",children:at})]}):void 0}),s.jsx(b$,{backendSessionId:Ct?ir.get(Ct)?.terminalSessionId??null:null}),s.jsx(v$,{state:ke,onDismiss:()=>{je()}}),s.jsxs("div",{className:"mt-3 flex gap-2",children:[s.jsxs("button",{type:"button",onClick:()=>{Di(null),ja({mode:"shell"}),Ri()},className:`flex min-w-0 items-center justify-center gap-1.5 rounded-xl text-[13px] font-semibold transition active:scale-[0.98] ${Fl?"flex-[2.7] bg-primary px-3 py-2.5 text-primary-foreground ring-1 ring-primary/40 shadow-md shadow-primary/25 hover:bg-primary/90":"flex-[0.78] bg-surface-2 px-2 py-2 text-muted-foreground hover:bg-surface-elevated hover:text-foreground"}`,title:e(ji==="shell"?"sidebar.confirmNewShell":"settings.shell"),children:[s.jsx(zs,{size:14,className:Fl?"shrink-0":"hidden"}),s.jsx($o,{size:12}),s.jsx("span",{className:Fl?"whitespace-nowrap":"hidden",children:e(ji==="shell"?"sidebar.confirmNewShell":"settings.shell")})]}),s.jsxs("button",{type:"button",disabled:!Tr.available,onClick:()=>{Tr.available&&(Di(null),ja({mode:"tmux"}),Ri())},className:`flex min-w-0 items-center justify-center gap-1.5 rounded-xl text-[13px] font-semibold transition active:scale-[0.98] ${Tr.available?au?"flex-[2.7] bg-primary px-3 py-2.5 text-primary-foreground ring-1 ring-primary/40 shadow-md shadow-primary/25 hover:bg-primary/90":"flex-[0.78] bg-surface-2 px-2 py-2 text-muted-foreground hover:bg-surface-elevated hover:text-foreground":"flex-1 bg-surface-2/50 text-muted-foreground/50 cursor-not-allowed"}`,title:Tr.available?e(ji==="tmux"?"sidebar.confirmNewTmux":"settings.tmux"):Tr.reason||e("settings.installTmuxHint"),children:[s.jsx(zs,{size:14,className:au?"shrink-0":"hidden"}),s.jsx(qc,{size:12}),s.jsx("span",{className:au?"whitespace-nowrap":"hidden",children:e(ji==="tmux"?"sidebar.confirmNewTmux":"settings.tmux")})]})]}),(Tr.available||Mr.length>0)&&s.jsxs("details",{className:"mt-3 group rounded-xl bg-surface-2 [&[open]]:bg-surface-2",children:[s.jsxs("summary",{className:"flex cursor-pointer items-center justify-between rounded-xl px-3 py-2.5 text-[13px] hover:bg-surface-elevated",children:[s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`inline-flex h-2 w-2 rounded-full ${Tr.available?"bg-primary":"bg-destructive"}`}),s.jsx("span",{className:"font-medium",children:e("settings.tmuxServer")}),s.jsx("span",{className:"text-[11px] text-muted-foreground",children:Tr.available?e("settings.sessions",{n:Mr.length}):e("settings.tmuxUnavailable")})]}),s.jsx("button",{type:"button",onClick:C=>{C.preventDefault(),Vo()},disabled:ln,className:"inline-flex h-7 w-7 items-center justify-center rounded-full text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground disabled:opacity-50","aria-label":e("settings.refresh"),children:s.jsx(bn,{size:12,className:ln?"animate-spin":""})})]}),s.jsx("div",{className:"px-2 pb-2",children:Tr.available?Mr.length===0?s.jsx("p",{className:"px-2 py-1.5 text-[11px] text-muted-foreground",children:e("settings.noTmuxSessions")}):s.jsxs("div",{className:"space-y-2",children:[xl.map(C=>s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-2 px-1.5 py-1 text-[10px] text-muted-foreground",children:[s.jsx(Vc,{size:11,className:"shrink-0 text-muted-foreground/70"}),s.jsx("span",{className:"shrink-0 font-medium text-foreground/75",children:C.label}),s.jsx("span",{className:"shrink-0 text-muted-foreground/70",children:e("settings.sessions",{n:C.sessions.length})}),C.key&&s.jsx("span",{className:"min-w-0 truncate text-muted-foreground/60",children:C.key})]}),C.sessions.map(P=>{const de=P.boundFrontendSessionId??null,rt=!!(P.connected||de),At=de?yt.find(Qi=>Qi.id===de)??null:null,Zt=P.friendlyName?.trim()||null,Nr=P.label&&P.label!==P.name?P.label:null,An=Zt||Nr||P.name,Nn=Zt||Nr?`tmux:${P.name}`:null,Ln=P.clientCount&&P.clientCount>0?t==="zh"?`网页连接 ${P.clientCount}`:`Web clients ${P.clientCount}`:null,Ai=P.attached>0?t==="zh"?`原生 tmux ${P.attached}`:`Native tmux ${P.attached}`:null,Tn=[Nn,rt?P.restorable?e("settings.restorable"):e("settings.attached"):null,Ln,Ai].filter(Qi=>!!Qi),Xi=[e("settings.windows",{n:P.windows}),P.createdAt?new Date(P.createdAt).toLocaleDateString():null].filter(Qi=>!!Qi),Io=ks===P.name,Eo=en===P.name,Ba=Nt===P.name;return s.jsxs("div",{className:`flex items-start gap-2 rounded-lg px-2.5 py-2 ${Io?"bg-destructive/10 ring-1 ring-destructive/40":"bg-surface"}`,children:[s.jsx(qc,{size:13,className:rt?"mt-0.5 shrink-0 text-primary":"mt-0.5 shrink-0 text-muted-foreground"}),s.jsxs("div",{className:"min-w-0 flex-1 space-y-1",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[s.jsx("div",{className:"truncate text-[12px] font-semibold text-foreground",children:An}),P.friendlyName&&s.jsx("span",{className:"shrink-0 rounded-full bg-primary/10 px-1.5 py-0.5 text-[9px] font-medium text-primary",children:t==="zh"?"自定义":"custom"})]}),Tn.length>0&&s.jsx("div",{className:"flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 text-[10px] text-muted-foreground",children:Tn.map(Qi=>s.jsx("span",{className:"max-w-full truncate",children:Qi},Qi))}),(P.program||P.cwd)&&s.jsxs("div",{className:"grid min-w-0 gap-0.5 text-[10px] text-muted-foreground",children:[P.program&&s.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[s.jsx(yT,{size:10,className:"shrink-0 text-muted-foreground/70"}),s.jsx("span",{className:"truncate text-foreground/75",children:P.program})]}),P.cwd&&s.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[s.jsx(Vc,{size:10,className:"shrink-0 text-muted-foreground/70"}),s.jsx("span",{className:"truncate",children:P.cwd})]})]}),s.jsx("div",{className:"flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 text-[10px] text-muted-foreground/80",children:Xi.map(Qi=>s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(JA,{size:10,className:"shrink-0 text-muted-foreground/60"}),Qi]},Qi))})]}),Io?s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",disabled:Eo,onClick:()=>{su(P.name)},className:"shrink-0 rounded-full bg-destructive/90 px-2.5 py-1 text-[11px] font-medium text-destructive-foreground transition hover:bg-destructive disabled:opacity-50",children:Eo?"…":e("settings.destroy")}),s.jsx("button",{type:"button",disabled:Eo,onClick:()=>{Dr(null),He(null)},className:"shrink-0 rounded-full bg-surface-2 px-2.5 py-1 text-[11px] font-medium text-foreground transition hover:bg-surface-elevated",children:e("common.cancel")})]}):s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",onClick:()=>{At?F0(At.id):(Et(P.name),ja({mode:"tmux",tmuxSessionName:P.name}))},disabled:Ba,className:`shrink-0 inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-[11px] font-medium transition disabled:opacity-50 ${rt?"bg-surface text-foreground hover:bg-surface-elevated":Ba?"bg-primary/10 text-primary":"bg-primary/15 text-primary hover:bg-primary/25"}`,children:Ba?s.jsxs(s.Fragment,{children:[s.jsx(_n,{size:10,className:"animate-spin"}),e("settings.attaching")]}):e(rt?"settings.attached":"settings.attach")}),s.jsx("button",{type:"button",disabled:Eo,onClick:()=>{He(null),Dr(P.name)},className:"shrink-0 inline-flex h-7 w-7 items-center justify-center rounded-full text-muted-foreground transition hover:bg-destructive/15 hover:text-destructive","aria-label":`Kill tmux session ${P.name}`,children:s.jsx(Rs,{size:12})})]})]},P.name)})]},C.key||"__ungrouped_tmux__")),X&&s.jsx("p",{className:"px-2 text-[11px] text-destructive",children:X})]}):s.jsx("p",{className:"px-2 py-1.5 text-[11px] text-muted-foreground",children:Tr.reason||e("settings.installTmuxHint")})})]}),s.jsxs("button",{type:"button",onClick:()=>ws(!0),className:"mt-2 flex w-full items-center justify-between gap-2 rounded-xl bg-surface-2 px-3 py-2.5 text-left text-[13px] transition hover:bg-surface-elevated",children:[s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx(Py,{size:14,className:"text-muted-foreground"}),s.jsx("span",{className:"font-medium text-foreground",children:e("settings.keyboardToolbar")})]}),s.jsxs("span",{className:"flex items-center gap-1.5 text-[11px] text-muted-foreground",children:[s.jsx("span",{children:e("settings.sessions",{n:As.length})}),s.jsx("span",{children:"›"})]})]}),s.jsxs("button",{type:"button",onClick:()=>cs(!0),className:"mt-2 flex w-full items-center justify-between gap-2 rounded-xl bg-surface-2 px-3 py-2.5 text-left text-[13px] transition hover:bg-surface-elevated",children:[s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx(R0,{size:14,className:"text-muted-foreground"}),s.jsx("span",{className:"font-medium text-foreground",children:e("settings.aiAgentDetection")})]}),s.jsxs("span",{className:"flex items-center gap-1.5 text-[11px] text-muted-foreground",children:[s.jsx("span",{children:"hooks"}),s.jsx("span",{children:"›"})]})]}),s.jsxs("div",{className:"mt-3 flex items-center gap-2 rounded-xl bg-surface-2 px-2.5 py-2",children:[s.jsx("span",{className:"text-[12px] font-medium text-foreground/90 w-14 shrink-0",children:e("settings.language")}),s.jsx("div",{className:"flex flex-1 items-center gap-1 rounded-md bg-surface p-0.5",children:[{code:"en",label:"English"},{code:"zh",label:"中文"}].map(C=>{const P=t===C.code;return s.jsx("button",{type:"button",onClick:()=>r(C.code),className:`flex-1 rounded px-2 py-1 text-[11px] font-medium transition ${P?"bg-primary/20 text-primary":"text-muted-foreground hover:bg-surface-elevated"}`,children:C.label},C.code)})})]}),s.jsxs("button",{type:"button",onClick:async()=>{try{await nA()}catch{}window.dispatchEvent(new CustomEvent("auth:unauthorized"))},className:"mt-3 flex w-full items-center justify-center gap-2 rounded-xl bg-destructive/10 px-3 py-2.5 text-[13px] font-medium text-destructive transition hover:bg-destructive/20 active:scale-[0.98]",children:[s.jsx(Hy,{size:14}),e("settings.signOut")]})]})]})})]}),eo&&s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"fixed inset-0 z-menu-backdrop bg-[var(--app-backdrop-soft)] backdrop-blur-sm cursor-default animate-fade-in",onClick:()=>{$e(null),it(null),He(null)},"aria-label":e("common.close")}),s.jsxs("div",{className:`fixed z-menu-panel rounded-2xl bg-surface-elevated border border-border/15 shadow-[0_18px_48px_var(--app-shadow-soft)] animate-fade-in ${Je&&Xt?"":"inset-x-3 bottom-6 mx-auto max-w-sm sm:bottom-auto sm:top-[15%]"}`,style:Je&&Xt?{...hy(Je),paddingBottom:a}:{paddingBottom:a},children:[s.jsxs("div",{className:"border-b border-border/15 px-4 py-3",children:[s.jsx("div",{className:"text-[11px] uppercase tracking-[0.14em] text-muted-foreground",children:e("tab.closeChooserTitle")}),s.jsx("div",{className:"mt-0.5 truncate text-[14px] font-medium text-foreground",children:W0}),s.jsx("div",{className:"mt-0.5 text-[11px] text-muted-foreground/80",children:e("tab.closeChooserDescription")})]}),s.jsxs("div",{className:"flex flex-col py-1",children:[s.jsxs("button",{type:"button",onClick:od,className:"flex items-center gap-3 px-4 py-3 text-left text-[13px] text-destructive transition hover:bg-destructive/10",children:[s.jsx("span",{className:"inline-flex h-7 w-7 items-center justify-center rounded-full bg-destructive/15 text-destructive",children:s.jsx(Rs,{size:14})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block font-medium",children:e("tab.confirmDestroySession")}),s.jsx("span",{className:"block text-[11px] text-muted-foreground",children:e("tab.destroySessionHint")})]})]}),X&&s.jsx("p",{className:"px-4 py-2 text-[11px] text-destructive",children:X})]}),s.jsx("div",{className:"border-t border-border/15 px-3 py-2",children:s.jsx("button",{type:"button",onClick:()=>{$e(null),it(null),He(null)},className:"w-full rounded-full bg-surface-2 px-3 py-2 text-[12px] font-medium text-muted-foreground transition hover:bg-surface hover:text-foreground",children:e("common.cancel")})})]})]}),cr&&(()=>{const C=yt.find(Ln=>Ln.id===cr);if(!C)return null;const P=ir.get(C.id),{primary:de}=il(C,P?.activeProgram??null,P?.cwd??null,_a),rt=Xt,At=rt?hy(Ls):{paddingBottom:a},Zt=rt?"fixed z-menu-panel overflow-y-auto overflow-x-hidden rounded-lg bg-surface-elevated border border-border/15 shadow-[0_18px_48px_var(--app-shadow-soft)] animate-fade-in":"fixed inset-x-3 bottom-6 z-menu-panel mx-auto max-w-sm rounded-2xl bg-surface-elevated border border-border/15 shadow-[0_18px_48px_var(--app-shadow-soft)] animate-fade-in sm:bottom-auto sm:top-[15%]",Nr=rt?"border-b border-border/15 px-3 py-2":"border-b border-border/15 px-4 py-3",An=rt?"flex items-center gap-2 px-3 py-2 text-left text-[12px] transition":"flex items-center gap-3 px-4 py-3 text-left text-[13px] transition",Nn=rt?"inline-flex h-6 w-6 items-center justify-center rounded-md":"inline-flex h-7 w-7 items-center justify-center rounded-full";return s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:`fixed inset-0 z-menu-backdrop cursor-default animate-fade-in ${rt?"bg-transparent":"bg-[var(--app-backdrop-soft)] backdrop-blur-sm"}`,onClick:Bt,"aria-label":"Close menu"}),s.jsxs("div",{className:Zt,style:At,children:[s.jsxs("div",{className:Nr,children:[s.jsx("div",{className:"text-[11px] uppercase tracking-[0.14em] text-muted-foreground",children:e("tab.session")}),s.jsx("div",{className:"mt-0.5 truncate text-[14px] font-medium text-foreground",children:de}),P?.cwd&&s.jsx("div",{className:"mt-0.5 truncate text-[11px] text-muted-foreground/80",children:P.cwd})]}),s.jsxs("div",{className:"flex flex-col py-1",children:[s.jsxs("button",{type:"button",onClick:()=>{const Ln=Ls;Bt(),_r(Ln),jr(C.id)},className:`${An} text-foreground hover:bg-surface-2`,children:[s.jsx("span",{className:`${Nn} bg-primary/15 text-primary`,children:s.jsx(eS,{size:14})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block font-medium",children:e("tab.rename")}),s.jsx("span",{className:"block text-[11px] text-muted-foreground",children:e("tab.renameHint")})]})]}),s.jsxs("button",{type:"button",disabled:!P?.cwd,onClick:()=>{ap(C.id),Bt()},className:`${An} ${P?.cwd?"text-foreground hover:bg-surface-2":"text-muted-foreground/50 cursor-not-allowed"}`,children:[s.jsx("span",{className:`${Nn} bg-surface-2 text-muted-foreground`,children:s.jsx(Oy,{size:14})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block font-medium",children:e("tab.copyCwd")}),s.jsx("span",{className:"block text-[11px] text-muted-foreground",children:e("tab.copyCwdHint")})]}),Or&&Or===P?.cwd&&s.jsx("span",{className:"ml-auto text-[11px] text-primary",children:e("tab.copied")})]}),(()=>{const Ln=Om(C.id),Ai=Ln??De;return s.jsxs("div",{className:`${An} text-foreground`,children:[s.jsx("span",{className:`${Nn} bg-surface-2 text-muted-foreground`,children:s.jsx(NS,{size:14})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block font-medium",children:e("tab.fontSize")}),s.jsx("span",{className:"block text-[11px] text-muted-foreground",children:e("tab.fontSizeHint")})]}),s.jsxs("span",{className:"flex shrink-0 items-center gap-1",children:[s.jsx("button",{type:"button",onClick:()=>{Ph(C.id,Ai-1),cn(Tn=>Tn+1)},className:"h-7 w-7 shrink-0 rounded-md bg-surface text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground active:scale-95","aria-label":`${e("tab.fontSize")} -1`,children:"−"}),s.jsxs("span",{className:"w-8 text-center text-[11px] tabular-nums text-muted-foreground",children:[Ai,"px"]}),s.jsx("button",{type:"button",onClick:()=>{Ph(C.id,Ai+1),cn(Tn=>Tn+1)},className:"h-7 w-7 shrink-0 rounded-md bg-surface text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground active:scale-95","aria-label":`${e("tab.fontSize")} +1`,children:"+"}),Ln!==null&&s.jsx("button",{type:"button",onClick:()=>{Ph(C.id,null),cn(Tn=>Tn+1)},className:"ml-1 shrink-0 rounded-md px-1.5 py-1 text-[11px] text-primary transition hover:bg-primary/10",children:e("tab.fontSizeReset")})]})]})})(),P?.agentNativeSessionId&&P.agentStatus!=="working"&&P.agentStatus!=="waiting"&&P.terminalSessionId&&s.jsxs("button",{type:"button",onClick:()=>{const Ln=P.terminalSessionId;Ln&&(Bt(),Xr(C.id,Ln))},className:`${An} text-foreground hover:bg-surface-2`,children:[s.jsx("span",{className:`${Nn} bg-[rgb(var(--success-rgb)_/_0.14)] text-[color:var(--success)]`,children:s.jsx(Qc,{size:14})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsxs("span",{className:"block font-medium",children:[e("tab.resumeAgent"),P.agent?.displayName?` · ${P.agent.displayName}`:""]}),s.jsx("span",{className:"block text-[11px] text-muted-foreground",children:e("tab.resumeAgentHint")})]})]}),s.jsx("div",{className:"my-1 border-t border-border/15"}),C.mode==="tmux"?s.jsxs("button",{type:"button",onClick:()=>{Bt(),Ol(C.id)},className:`${An} text-destructive hover:bg-destructive/10`,children:[s.jsx("span",{className:`${Nn} bg-destructive/15 text-destructive`,children:s.jsx(Rs,{size:14})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block font-medium",children:e("tab.destroySession")}),s.jsx("span",{className:"block text-[11px] text-muted-foreground",children:e("tab.destroySessionHint")})]})]}):s.jsxs("button",{type:"button",onClick:()=>{Bt(),gc({sessionId:C.id,source:"tab-menu",closeMode:"auto"})},className:`${An} text-destructive hover:bg-destructive/10`,children:[s.jsx("span",{className:`${Nn} bg-destructive/15 text-destructive`,children:s.jsx(In,{size:14})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block font-medium",children:e("tab.close")}),s.jsx("span",{className:"block text-[11px] text-muted-foreground",children:e("tab.closeHint")})]})]}),!rt&&s.jsx("button",{type:"button",className:"flex items-center justify-center px-4 py-2 text-[11px] text-muted-foreground/80 transition hover:text-foreground",onClick:()=>{Bt()},children:e("tab.longPressTip")})]}),!rt&&s.jsx("div",{className:"border-t border-border/15 px-3 py-2",children:s.jsx("button",{type:"button",onClick:Bt,className:"w-full rounded-full bg-surface-2 px-3 py-2 text-[12px] font-medium text-muted-foreground transition hover:bg-surface hover:text-foreground",children:e("common.cancel")})})]})]})})(),tr&&dn&&Xt&&(()=>{const C=yt.find(Tn=>Tn.id===tr);if(!C)return null;const P=ir.get(C.id),{primary:de}=il(C,P?.activeProgram??null,P?.cwd??null,_a,P?.shellTitle??null,P?.promptState??null),rt=C.customName?C.name:de,At=Tn=>{const Xi=Tn.trim();Xi?Xi!==rt&&Vi(C.id,Xi):qi(C.id),jr(null),_r(null)},Zt=300,Nr=160,An=dn.x,Nn=dn.y,Ln=Math.min(Math.max(An-Zt/2,12),window.innerWidth-Zt-12),Ai=Nn+Nr+20>window.innerHeight?Math.max(Nn-Nr-12,12):Nn+12;return s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"fixed inset-0 z-menu-backdrop cursor-default animate-fade-in bg-transparent",onClick:()=>{jr(null),_r(null)},"aria-label":e("common.cancel")}),s.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":e("tab.rename"),className:"fixed z-menu-panel w-[300px] rounded-xl bg-surface-elevated border border-border/15 shadow-[0_12px_36px_var(--app-shadow-soft)] animate-fade-in",style:{left:`${Ln}px`,top:`${Ai}px`},children:[s.jsxs("div",{className:"border-b border-border/15 px-3 py-2.5",children:[s.jsx("div",{className:"text-[11px] uppercase tracking-[0.14em] text-muted-foreground",children:e("tab.rename")}),s.jsx("div",{className:"mt-0.5 truncate text-[13px] font-medium text-foreground",children:de}),P?.cwd&&s.jsx("div",{className:"mt-0.5 truncate text-[11px] text-muted-foreground/70",children:P.cwd})]}),s.jsxs("form",{className:"px-3 py-2.5",onSubmit:Tn=>{Tn.preventDefault();const Xi=new FormData(Tn.currentTarget).get("session-name");At(typeof Xi=="string"?Xi:"")},children:[s.jsx("input",{ref:Tn=>{Tt.current=Tn,Tn&&!kt.current&&(kt.current=!0,Tn.focus({preventScroll:!0}),Tn.select())},type:"text",name:"session-name",defaultValue:rt,placeholder:e("tab.renamePlaceholder"),autoComplete:"off",autoCapitalize:"off",autoCorrect:"off",spellCheck:!1,className:"w-full rounded-lg bg-surface-2 px-3 py-2 text-[13px] leading-snug text-foreground outline-none ring-1 ring-primary/40 placeholder:text-muted-foreground/60 focus:ring-primary/70",onKeyDown:Tn=>{Tn.key==="Escape"&&(Tn.stopPropagation(),jr(null),_r(null))}}),s.jsxs("div",{className:"mt-2.5 flex gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{jr(null),_r(null)},className:"flex-1 rounded-full bg-surface-2 px-3 py-1.5 text-[12px] font-medium text-muted-foreground transition hover:bg-surface hover:text-foreground",children:e("common.cancel")}),s.jsx("button",{type:"submit",className:"flex-1 rounded-full bg-primary px-3 py-1.5 text-[12px] font-semibold text-primary-foreground transition hover:bg-primary/90 active:scale-[0.97]",children:e("common.save")})]})]})]})]})})(),tr&&!Xt&&(()=>{const C=yt.find(Zt=>Zt.id===tr);if(!C)return null;const P=ir.get(C.id),{primary:de}=il(C,P?.activeProgram??null,P?.cwd??null,_a,P?.shellTitle??null,P?.promptState??null),rt=C.customName?C.name:de,At=Zt=>{const Nr=Zt.trim();Nr?Nr!==rt&&Vi(C.id,Nr):qi(C.id),jr(null)};return s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"fixed inset-0 z-menu-backdrop cursor-default animate-fade-in bg-[var(--app-backdrop-soft)] backdrop-blur-sm",onClick:()=>jr(null),"aria-label":e("common.cancel")}),s.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":e("tab.rename"),className:"fixed inset-x-3 z-menu-panel mx-auto max-w-sm rounded-2xl bg-surface-elevated border border-border/15 shadow-[0_18px_48px_var(--app-shadow-soft)] animate-fade-in",style:{top:`calc(${n} + 3.5rem)`},children:[s.jsxs("div",{className:"border-b border-border/15 px-4 py-3",children:[s.jsx("div",{className:"text-[11px] uppercase tracking-[0.14em] text-muted-foreground",children:e("tab.session")}),s.jsx("div",{className:"mt-0.5 text-[14px] font-medium text-foreground",children:e("tab.rename")})]}),s.jsxs("form",{className:"px-4 py-3",onSubmit:Zt=>{Zt.preventDefault();const Nr=new FormData(Zt.currentTarget).get("session-name");At(typeof Nr=="string"?Nr:"")},children:[s.jsx("input",{ref:Zt=>{Tt.current=Zt,Zt&&!kt.current&&(kt.current=!0,Zt.focus({preventScroll:!0}),Zt.select())},type:"text",name:"session-name",defaultValue:rt,placeholder:e("tab.renamePlaceholder"),autoComplete:"off",autoCapitalize:"off",autoCorrect:"off",spellCheck:!1,enterKeyHint:"done",className:"w-full rounded-lg bg-surface-2 px-3 py-2.5 text-[16px] leading-snug text-foreground outline-none ring-1 ring-primary/40 placeholder:text-muted-foreground/60 focus:ring-primary/70",onKeyDown:Zt=>{Zt.key==="Escape"&&(Zt.stopPropagation(),jr(null))}}),s.jsxs("div",{className:"mt-3 flex gap-2",children:[s.jsx("button",{type:"button",onClick:()=>jr(null),className:"flex-1 rounded-full bg-surface-2 px-3 py-2 text-[12px] font-medium text-muted-foreground transition hover:bg-surface hover:text-foreground",children:e("common.cancel")}),s.jsx("button",{type:"submit",className:"flex-1 rounded-full bg-primary/20 px-3 py-2 text-[12px] font-medium text-primary transition hover:bg-primary/30",children:e("common.save")})]})]})]})]})})(),Gs&&s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button","aria-label":e("common.close"),className:"fixed inset-0 z-modal-backdrop bg-[var(--app-backdrop)] backdrop-blur-sm",onClick:()=>Bi(!1)}),s.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"local-access-title",className:"fixed inset-x-3 top-[max(1.5rem,env(safe-area-inset-top,0px))] bottom-[max(1.5rem,env(safe-area-inset-bottom,0px))] z-modal-panel mx-auto flex max-w-xl flex-col overflow-hidden rounded-2xl border border-border/15 bg-surface sm:top-[10%] sm:bottom-auto sm:max-h-[80vh]",children:[s.jsxs("div",{className:"flex shrink-0 items-center justify-between border-b border-border/15 p-4",children:[s.jsx("h2",{id:"local-access-title",className:"section-title",children:e("settings.localAccess")}),s.jsx("button",{autoFocus:!0,type:"button","aria-label":e("common.close"),onClick:()=>Bi(!1),className:"rounded-full bg-surface-2 p-2 text-muted-foreground",children:s.jsx(In,{size:18})})]}),s.jsxs("div",{className:"overflow-y-auto overscroll-contain p-4",children:[s.jsx(iC,{state:be,onCopy:C=>{ml(C,"setup")},copied:we==="setup"}),s.jsxs("div",{className:"mt-3 flex items-center overflow-hidden rounded-lg bg-surface ring-1 ring-border/10 focus-within:ring-primary/40",children:[s.jsx("input",{value:ee,onChange:C=>_e(C.target.value.toLowerCase()),className:"min-w-0 flex-1 bg-transparent px-2.5 py-2 text-[12px] text-foreground outline-none",placeholder:"jovn",spellCheck:!1}),s.jsx("span",{className:"shrink-0 border-l border-border/10 px-2.5 py-2 text-[11px] text-muted-foreground",children:".termdock.local"})]}),s.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",disabled:ze,onClick:()=>{Es()},className:"rounded-full bg-primary/15 px-3 py-1.5 text-[11px] font-medium text-primary transition hover:bg-primary/25 disabled:opacity-50",children:e(ze?"settings.saving":"common.save")}),s.jsx("button",{type:"button",disabled:ze,onClick:()=>{Ea()},className:"rounded-full bg-surface px-3 py-1.5 text-[11px] font-medium text-muted-foreground transition hover:bg-surface-elevated disabled:opacity-50",children:e("settings.resetAutoName")})]}),s.jsxs("div",{className:"mt-3 space-y-1.5 text-[11px]",children:[be.url&&s.jsxs("button",{type:"button",onClick:()=>{ml(be.url,"lan")},className:"flex w-full items-center justify-between gap-2 rounded-lg bg-surface px-2.5 py-2 text-left text-muted-foreground transition hover:bg-surface-elevated",children:[s.jsxs("span",{className:"min-w-0 truncate",children:["Branded: ",be.url]}),s.jsx("span",{className:"shrink-0 rounded-full bg-primary/10 px-2 py-0.5 text-[10px] font-medium",children:we==="lan"?"Copied":e("common.copy")})]}),be.interfaces.length>0&&s.jsxs("details",{className:"rounded-lg bg-surface px-2.5 py-2 text-muted-foreground",open:!1,children:[s.jsx("summary",{className:"cursor-pointer text-[11px] font-medium text-foreground/80",children:"IP fallback addresses"}),s.jsx("div",{className:"mt-2 grid grid-cols-1 gap-2 sm:grid-cols-2",children:be.interfaces.map(C=>{const P=C.url??`${be.httpsEnabled?"https":"http"}://${C.address}:9834`;return s.jsxs("div",{className:"rounded-lg bg-surface-2 p-2",children:[s.jsxs("div",{className:"text-[11px] font-medium text-foreground/85",children:[C.label," (",C.name,")"]}),s.jsx("div",{className:"mt-0.5 text-[10px] text-muted-foreground",children:C.address}),C.qrDataUrl&&s.jsx("div",{className:"mt-2 inline-block rounded-lg bg-[var(--background)] p-1.5",children:s.jsx("img",{src:C.qrDataUrl,alt:`QR code for ${P}`,className:"h-28 w-28"})}),s.jsxs("button",{type:"button",onClick:()=>{ml(P,`ip-${C.address}`)},className:"mt-2 flex w-full items-center justify-between gap-2 rounded-md bg-surface px-2 py-1.5 text-left text-[11px] transition hover:bg-surface-elevated",children:[s.jsx("span",{className:"min-w-0 truncate",children:P}),s.jsx("span",{className:"shrink-0 text-[10px]",children:we===`ip-${C.address}`?"Copied":e("common.copy")})]})]},`${C.name}-${C.address}`)})})]}),s.jsxs("div",{className:"text-muted-foreground",children:[be.httpsEnabled?e("settings.httpsActive"):e("settings.httpsInactive"),!be.caAvailable&&` · ${e("settings.caMissing")}`]}),be.reason&&s.jsx("div",{className:"text-[color:var(--warning)]",children:be.reason}),ce&&s.jsx("div",{className:"text-destructive",children:ce})]})]})]})]}),Ra&&s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"fixed inset-0 z-modal-backdrop bg-[var(--app-backdrop)] backdrop-blur-sm cursor-default",onClick:()=>ni(!1)}),s.jsxs("div",{className:"fixed left-[max(0.75rem,env(safe-area-inset-left,0px))] right-[max(0.75rem,env(safe-area-inset-right,0px))] top-[max(1.5rem,env(safe-area-inset-top,0px))] bottom-[max(1.5rem,env(safe-area-inset-bottom,0px))] z-modal-panel mx-auto flex max-w-xl flex-col overflow-hidden rounded-2xl bg-surface border border-border/15 shadow-[0_28px_70px_var(--app-shadow-strong),0_14px_32px_var(--app-shadow-soft)] sm:top-[10%] sm:bottom-auto sm:max-h-[80vh]",children:[s.jsxs("div",{className:"flex shrink-0 items-center justify-between border-b border-border/15 px-4 py-4 sm:px-6",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"ui-kicker",children:e("settings.notifications")}),s.jsx("h2",{className:"section-title mt-1",children:e("settings.notificationsTitle")})]}),s.jsx("button",{type:"button",onClick:()=>ni(!1),className:"shrink-0 rounded-full bg-surface-2 p-2 text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground","aria-label":"Close notifications settings",children:s.jsx(In,{size:18})})]}),s.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto p-4 sm:p-6",children:[s.jsx("p",{className:"text-[12px] leading-relaxed text-muted-foreground",children:e("settings.notificationsPageHint")}),s.jsxs("div",{className:"mt-4 rounded-2xl bg-surface-2 p-3",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[13px] font-semibold text-foreground",children:e("settings.notificationsMaster")}),s.jsx("div",{className:"mt-1 text-[11px] leading-relaxed text-muted-foreground",children:Z==="denied"?e("settings.notificationsDenied"):rh()?e("settings.notificationsMasterHint"):e("settings.notificationsUnsupported")}),rh()&&!sA()&&s.jsx("div",{className:"mt-1.5 text-[11px] leading-relaxed text-[var(--warning)]",children:e("settings.notificationsIOSInstallHint")})]}),s.jsx("button",{type:"button",onClick:()=>{$r()},disabled:!rh()||Z==="denied",className:"shrink-0 transition disabled:cursor-not-allowed","aria-pressed":L,children:s.jsx(ll,{checked:L,disabled:!rh()||Z==="denied"})})]}),s.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2 text-[11px]",children:[s.jsxs("span",{className:`rounded-full px-2 py-0.5 ${Z==="granted"?"bg-primary/15 text-primary":"bg-surface text-muted-foreground"}`,children:[e("settings.notificationsPermission"),": ",vo()?e("settings.notificationsPermissionSystem"):Z]}),s.jsx("button",{type:"button",disabled:!L||Z!=="granted"||ys==="checking",onClick:()=>{nn()},className:"rounded-full bg-surface px-3 py-1.5 font-medium text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",children:e(ys==="checking"?"settings.notificationsTestChecking":"settings.notificationsTest")}),vo()?.openNotificationSettings&&s.jsx("button",{type:"button",onClick:()=>{vo()?.openNotificationSettings?.()},className:"rounded-full bg-surface px-3 py-1.5 font-medium text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground",children:e("settings.notificationsOpenSystemSettings")})]}),ys!=="idle"&&ys!=="checking"&&s.jsx("div",{className:`mt-2 text-[11px] leading-relaxed ${ys==="delivered"?"text-primary":"text-[var(--warning)]"}`,children:e(ys==="delivered"?"settings.notificationsTestDelivered":"settings.notificationsTestFailed")})]}),s.jsxs("div",{className:"mt-4 rounded-2xl bg-surface-2 p-3",children:[s.jsx("div",{className:"text-[13px] font-semibold text-foreground",children:e("settings.notificationsAlertStyle")}),s.jsx("div",{className:"mt-1 text-[11px] leading-relaxed text-muted-foreground",children:e("settings.notificationsAlertStyleHint")}),s.jsx("div",{className:"mt-3 grid grid-cols-3 gap-1 rounded-xl bg-surface p-1",children:[["normal",e("settings.notificationsStyleNormal"),e("settings.notificationsStyleNormalHint")],["quiet",e("settings.notificationsStyleQuiet"),e("settings.notificationsStyleQuietHint")],["persistent",e("settings.notificationsStylePersistent"),e("settings.notificationsStylePersistentHint")]].map(([C,P,de])=>{const rt=$===C;return s.jsxs("button",{type:"button",disabled:!L,onClick:()=>wn(C),className:`min-w-0 rounded-lg px-2 py-2 text-left transition ${rt&&L?"bg-primary/15 text-primary":L?"text-muted-foreground hover:bg-surface-elevated hover:text-foreground":"cursor-not-allowed text-muted-foreground/40"}`,title:de,children:[s.jsx("span",{className:"block truncate text-[11px] font-semibold",children:P}),s.jsx("span",{className:"mt-0.5 block truncate text-[9px] opacity-80",children:de})]},C)})})]}),s.jsxs("div",{className:"mt-4",children:[s.jsx("div",{className:"ui-kicker",children:e("settings.notificationsEvents")}),s.jsxs("div",{className:"mt-2 rounded-2xl bg-surface-2 p-3",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[13px] font-semibold text-foreground",children:e("settings.notificationsAiFinished")}),s.jsx("div",{className:"mt-1 text-[11px] leading-relaxed text-muted-foreground",children:e("settings.notificationsAiFinishedHint")})]}),s.jsx("button",{type:"button",disabled:!L,onClick:()=>Pn(!R),className:"shrink-0 transition disabled:cursor-not-allowed","aria-pressed":R&&L,children:s.jsx(ll,{checked:R&&L,disabled:!L})})]}),s.jsxs("div",{className:"mt-3 flex items-start justify-between gap-3 border-t border-border/10 pt-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[13px] font-semibold text-foreground",children:e("settings.notificationsSessionExited")}),s.jsx("div",{className:"mt-1 text-[11px] leading-relaxed text-muted-foreground",children:e("settings.notificationsSessionExitedHint")})]}),s.jsx("button",{type:"button",disabled:!L,onClick:()=>yr(!z),className:"shrink-0 transition disabled:cursor-not-allowed","aria-pressed":z&&L,children:s.jsx(ll,{checked:z&&L,disabled:!L})})]})]}),s.jsx("p",{className:"mt-2 text-[10px] text-muted-foreground",children:e("settings.notificationsFutureHint")})]})]})]})]}),ri&&s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"fixed inset-0 z-modal-backdrop bg-[var(--app-backdrop)] backdrop-blur-sm cursor-default",onClick:()=>ws(!1)}),s.jsxs("div",{className:"fixed left-[max(0.75rem,env(safe-area-inset-left,0px))] right-[max(0.75rem,env(safe-area-inset-right,0px))] top-[max(1.5rem,env(safe-area-inset-top,0px))] bottom-[max(1.5rem,env(safe-area-inset-bottom,0px))] z-modal-panel mx-auto flex max-w-4xl flex-col overflow-hidden rounded-2xl bg-surface border border-border/15 shadow-[0_28px_70px_var(--app-shadow-strong),0_14px_32px_var(--app-shadow-soft)]",children:[s.jsxs("div",{className:"flex shrink-0 items-center justify-between border-b border-border/15 px-4 py-4 sm:px-6",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"ui-kicker",children:e("settings.mobileKeyboard")}),s.jsx("h2",{className:"section-title mt-1",children:e("settings.toolbarPresets")})]}),s.jsx("button",{type:"button",onClick:()=>ws(!1),className:"shrink-0 rounded-full bg-surface-2 p-2 text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground","aria-label":"Close toolbar presets",children:s.jsx(In,{size:18})})]}),s.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto p-4 sm:p-6",children:s.jsx(f$,{presets:As,selectedPresetId:Co,onSelectPreset:ga,onUpdatePreset:(C,P)=>{Xa(de=>Ru(de.map(rt=>rt.id===C?P(rt):rt)))},onAddPreset:()=>{const C=`preset-${Date.now()}`;Xa(P=>Ru([...P,{id:C,label:`Preset ${P.length}`,programs:[],includeAlt:!1,rowLayout:[3,3],actions:[],showOnDesktop:!1}])),ga(C)},onRemovePreset:C=>{Xa(P=>Ru(P.filter(de=>de.id!==C)))},onResetDefaults:()=>{Xa(w0()),ga("default")}})})]})]}),xa&&s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"fixed inset-0 z-modal-backdrop bg-[var(--app-backdrop)] backdrop-blur-sm cursor-default",onClick:()=>cs(!1)}),s.jsxs("div",{className:"fixed left-[max(0.75rem,env(safe-area-inset-left,0px))] right-[max(0.75rem,env(safe-area-inset-right,0px))] top-[max(1.5rem,env(safe-area-inset-top,0px))] bottom-[max(1.5rem,env(safe-area-inset-bottom,0px))] z-modal-panel mx-auto flex max-w-4xl flex-col overflow-hidden rounded-2xl bg-surface border border-border/15 shadow-[0_28px_70px_var(--app-shadow-strong),0_14px_32px_var(--app-shadow-soft)]",children:[s.jsxs("div",{className:"flex shrink-0 items-center justify-between border-b border-border/15 px-4 py-4 sm:px-6",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"ui-kicker",children:e("settings.aiAgentDetection")}),s.jsx("h2",{className:"section-title mt-1",children:e("settings.detectionRules")})]}),s.jsx("div",{className:"flex items-center gap-2",children:s.jsx("button",{type:"button",onClick:()=>cs(!1),className:"shrink-0 rounded-full bg-surface-2 p-2 text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground","aria-label":"Close agent rules",children:s.jsx(In,{size:18})})})]}),s.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto p-4 sm:p-6",children:[s.jsx("p",{className:"mb-4 text-[11px] text-muted-foreground",children:e("settings.agentHooksHint")}),s.jsx(m$,{}),s.jsxs("div",{className:"mt-6 border-t border-border/15 pt-4",children:[s.jsx("div",{className:"ui-kicker",children:e("settings.programLabelResolution")}),s.jsx("h3",{className:"mt-1 text-sm font-semibold text-foreground",children:e("settings.rawCommandMapping")}),s.jsx("p",{className:"mt-1 text-[11px] text-muted-foreground",children:e("settings.rawCommandMappingHint")}),s.jsx("div",{className:"mt-3 space-y-2 rounded-xl bg-surface-2 p-3",children:yt.map(C=>{const P=ir.get(C.id),de=P?.activeProgramRaw??null,rt=P?.activeProgram??null;return s.jsxs("div",{className:"rounded-lg bg-surface/60 px-2.5 py-2",children:[s.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:C.name}),s.jsxs("div",{className:"mt-0.5 text-[11px] text-foreground",children:[s.jsx("span",{className:"text-muted-foreground",children:"display:"})," ",rt||"—"]}),s.jsxs("div",{className:"mt-0.5 break-all font-mono text-[10px] text-muted-foreground",children:[s.jsx("span",{className:"text-muted-foreground/80",children:"raw:"})," ",de||"—"]})]},`raw-${C.id}`)})}),s.jsxs("div",{className:"mt-3 space-y-3",children:[[{key:"genericProgramNames",label:e("settings.genericProgramNames"),hint:e("settings.genericProgramNamesHint")},{key:"wrapperScriptNames",label:e("settings.wrapperScriptNames"),hint:e("settings.wrapperScriptNamesHint")},{key:"shellNames",label:e("settings.shellNamesConfig"),hint:e("settings.shellNamesHint")}].map(({key:C,label:P,hint:de})=>s.jsxs("div",{children:[s.jsx("div",{className:"mb-0.5 text-[11px] font-medium text-foreground",children:P}),s.jsx("div",{className:"text-[10px] text-muted-foreground",children:de}),s.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1",children:[Xe[C].map(rt=>s.jsxs("span",{className:"inline-flex items-center gap-0.5 rounded-full bg-surface-2 px-2 py-0.5 text-[11px] font-mono text-foreground",children:[rt,s.jsx("button",{type:"button",onClick:()=>{const At={...Xe,[C]:Xe[C].filter(Zt=>Zt!==rt)};dt(At),C==="shellNames"&&(_a=new Set(At.shellNames)),hx(At).catch(()=>{})},className:"ml-0.5 text-muted-foreground hover:text-destructive",children:"×"})]},rt)),s.jsx("input",{placeholder:e("settings.addTag"),className:"w-16 rounded bg-surface px-1.5 py-0.5 text-[11px] font-mono",onKeyDown:rt=>{if(rt.key!=="Enter")return;const At=rt.target.value.trim().toLowerCase();if(!At||Xe[C].includes(At))return;const Zt={...Xe,[C]:[...Xe[C],At]};dt(Zt),C==="shellNames"&&(_a=new Set(Zt.shellNames)),rt.target.value="",hx(Zt).catch(()=>{})}})]})]},C)),s.jsx("button",{type:"button",onClick:()=>{iA().then(C=>{dt(C),_a=new Set(C.shellNames)}).catch(()=>{})},className:"rounded-full bg-surface-2 px-3 py-1 text-[11px] text-muted-foreground hover:bg-surface-elevated hover:text-foreground",children:e("settings.resetDefaults")})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"mb-1 text-[11px] font-medium text-foreground",children:e("settings.customRules")}),se.map((C,P)=>s.jsx("div",{className:"mb-2 rounded-lg bg-surface-2 p-2.5",children:s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("input",{type:"checkbox",checked:C.enabled!==!1,onChange:de=>{const rt=se.map((At,Zt)=>Zt===P?{...At,enabled:de.target.checked}:At);T(rt),Fn(Ca,rt),ge(!0),uu(rt).then(At=>{T(At),Fn(Ca,At)}).catch(()=>{}).finally(()=>ge(!1))}}),s.jsxs("select",{value:C.matchType,onChange:de=>{const rt=se.map((At,Zt)=>Zt===P?{...At,matchType:de.target.value}:At);T(rt),Fn(Ca,rt),ge(!0),uu(rt).then(At=>{T(At),Fn(Ca,At)}).catch(()=>{}).finally(()=>ge(!1))},className:"rounded bg-surface px-2 py-1 text-[11px]",children:[s.jsx("option",{value:"includes",children:"includes"}),s.jsx("option",{value:"exact",children:"exact"}),s.jsx("option",{value:"prefix",children:"prefix"}),s.jsx("option",{value:"regex",children:"regex"})]}),s.jsx("input",{value:C.pattern,onChange:de=>{const rt=se.map((At,Zt)=>Zt===P?{...At,pattern:de.target.value}:At);T(rt),Fn(Ca,rt)},onBlur:()=>{ge(!0),uu(se).then(de=>{T(de),Fn(Ca,de)}).catch(()=>{}).finally(()=>ge(!1))},placeholder:"pattern",className:"min-w-[180px] flex-1 rounded bg-surface px-2 py-1 text-[11px] font-mono"}),s.jsx("input",{value:C.output,onChange:de=>{const rt=se.map((At,Zt)=>Zt===P?{...At,output:de.target.value}:At);T(rt),Fn(Ca,rt)},onBlur:()=>{ge(!0),uu(se).then(de=>{T(de),Fn(Ca,de)}).catch(()=>{}).finally(()=>ge(!1))},placeholder:"output",className:"w-28 rounded bg-surface px-2 py-1 text-[11px]"}),s.jsx("button",{type:"button",onClick:()=>{const de=se.filter((rt,At)=>At!==P);T(de),Fn(Ca,de),ge(!0),uu(de).then(rt=>{T(rt),Fn(Ca,rt)}).catch(()=>{}).finally(()=>ge(!1))},className:"rounded bg-surface px-2 py-1 text-[11px] text-muted-foreground hover:text-destructive",children:e("common.delete")})]})},C.id)),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{const C=[...se,{id:`rule-${Date.now()}`,enabled:!0,priority:100,matchType:"includes",pattern:"",output:""}];T(C),Fn(Ca,C),ge(!0),uu(C).then(P=>{T(P),Fn(Ca,P)}).catch(()=>{}).finally(()=>ge(!1))},className:"rounded-full bg-primary/15 px-3 py-1.5 text-[11px] font-medium text-primary hover:bg-primary/25",children:e("settings.addRule")}),s.jsx("button",{type:"button",onClick:()=>{ge(!0),aA().then(C=>{T(C),Fn(Ca,C)}).catch(()=>{}).finally(()=>ge(!1))},className:"rounded-full bg-surface-2 px-3 py-1.5 text-[11px] font-medium text-muted-foreground hover:bg-surface-elevated hover:text-foreground",children:e("settings.resetDefaults")}),s.jsx("span",{className:"text-[11px] text-muted-foreground",children:F?e("settings.saving"):j?`${se.length} rules`:"…"})]})]})]})]})]})]}),Go&&s.jsx(o$,{isOpen:Go,onClose:()=>Zi(!1)}),!ya&&s.jsx(Qb,{isOpen:Cr,drawerWidthPx:hr,onClose:()=>Hn("left-sidebar"),onOpen:ha,sessions:yt,activeSessionId:Ct,sessionStates:ir,onNewSession:C=>ja(C),recoverableTmuxSessions:ld,recoverableTmuxSessionsLoading:ln,onRefreshRecoverableTmuxSessions:()=>{Vo()},onCloseRecoverableTmuxSession:mc,onCloseSession:Ol,onSplitSession:iu,onCloseSplit:C=>window.dispatchEvent(new CustomEvent("close-terminal-split",{detail:C})),onRemoveFromSplit:C=>window.dispatchEvent(new CustomEvent("remove-terminal-split-pane",{detail:C})),splitWorkspaces:ot,onSetSplitLayout:ad,onReorderSplitWorkspace:U0,onRenameSplitWorkspace:z0,onCombineSplitSessions:H0,onReorderSessions:es,onSessionMenu:wi,onOpenSettings:js,onJumpToNextAttention:ba.length>0?Pl:void 0,onOpenQuota:()=>Zi(!0),updateState:Le,updateActionPending:ne,onConfirmUpdateRestart:st,onRetryUpdate:bt,serverHealthState:ke,tmuxAvailable:Tr.available,defaultSessionMode:fn,onTogglePinned:Xt?Va:void 0}),!$l&&s.jsx(Pb,{isOpen:qr,sessionId:Ct,drawerWidthPx:zn,onClose:()=>Hn("right-sidebar"),onOpen:ms,rightSidebarFilePreviewOpen:Bn,rightSidebarFilePreviewCloseSignal:Ae,onOpenRightSidebarFilePreview:bi,onCloseRightSidebarFilePreview:hl,rightSidebarRepoPickerOpen:et,rightSidebarRepoPickerCloseSignal:Gt,onOpenRightSidebarRepoPicker:ti,onCloseRightSidebarRepoPicker:Uo,markdownOutlineOpen:wt,markdownOutlineCloseSignal:Vt,onOpenMarkdownOutline:pa,onCloseMarkdownOutline:fl,markdownImageLightboxOpen:Ot,markdownImageLightboxCloseSignal:xe,onOpenMarkdownImageLightbox:pl,onCloseMarkdownImageLightbox:ls,onTogglePinned:Xt?ei:void 0}),Ge&&!c&&s.jsx("button",{type:"button",onClick:Dl,className:"fixed inset-0 z-toast flex cursor-default items-center justify-center bg-[var(--app-backdrop-soft)] px-6 text-left backdrop-blur-[1px]","aria-label":t==="zh"?"继续使用 Termdock":"Continue using Termdock",children:s.jsxs("div",{className:"max-w-[18rem] rounded-2xl border border-border/15 bg-surface/95 px-5 py-4 text-center shadow-[0_18px_50px_var(--app-shadow-strong)] backdrop-blur animate-fade-in",children:[s.jsx("div",{className:"text-[14px] font-semibold text-foreground",children:t==="zh"?"建议使用 Home":"Use Home instead"}),s.jsx("div",{className:"mt-1.5 text-[12px] leading-relaxed text-muted-foreground",children:t==="zh"?"按 Home 退后台,点任意位置继续。":"Use Home to leave. Tap anywhere to continue."}),s.jsx("div",{className:"mt-3 text-[11px] font-medium text-muted-foreground/80",children:t==="zh"?"轻点关闭提示":"Tap to dismiss"})]})}),me&&s.jsxs("div",{className:`fixed inset-x-3 bottom-4 z-toast mx-auto flex max-w-md items-center gap-2 rounded-xl border px-4 py-3 text-[12px] shadow-lg animate-fade-in ${me.tone==="success"?"border-[rgb(var(--success-rgb)_/_0.24)] bg-surface-elevated text-foreground":"border-destructive/30 bg-surface-elevated text-destructive"}`,role:me.tone==="error"?"alert":"status",children:[me.tone==="success"?s.jsx(Qc,{size:14,className:"shrink-0 text-[color:var(--success)]"}):s.jsx(of,{size:14,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1",children:me.message}),s.jsx("button",{type:"button",onClick:()=>Gr(null),className:"inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-full text-muted-foreground transition hover:bg-surface-2 hover:text-foreground","aria-label":e("common.close"),children:s.jsx(In,{size:12})})]}),l&&s.jsxs(s.Fragment,{children:[!Xt&&s.jsx(aC,{onClose:()=>d(!1)}),s.jsxs("div",{className:"fixed bottom-0 left-0 right-0 z-toast hidden max-h-48 overflow-y-auto border-t border-border/15 bg-surface p-3 animate-fade-in md:block",children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsx("h4",{className:"ui-kicker",children:"Debug Info"}),s.jsx("button",{type:"button",onClick:()=>d(!1),className:"text-xs text-muted-foreground hover:text-foreground",children:"Close"})]}),s.jsx("pre",{className:"text-xs font-mono whitespace-pre-wrap break-all",children:JSON.stringify(q,null,2)})]})]})]}),Hl=Yt?null:s.jsx(cA,{className:"z-modal-panel",status:"正在恢复终端…"});return Xt?s.jsxs("div",{className:"w-screen h-full flex flex-row",children:[ya&&s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{width:on,flexShrink:0,height:"100%"},children:s.jsx(Qb,{isOpen:Cr,drawerWidthPx:on,onClose:Js,onOpen:ha,sessions:yt,activeSessionId:Ct,sessionStates:ir,onNewSession:C=>ja(C),recoverableTmuxSessions:ld,recoverableTmuxSessionsLoading:ln,onRefreshRecoverableTmuxSessions:()=>{Vo()},onCloseRecoverableTmuxSession:mc,onCloseSession:Ol,onSplitSession:iu,onCloseSplit:C=>window.dispatchEvent(new CustomEvent("close-terminal-split",{detail:C})),onRemoveFromSplit:C=>window.dispatchEvent(new CustomEvent("remove-terminal-split-pane",{detail:C})),splitWorkspaces:ot,onSetSplitLayout:ad,onReorderSplitWorkspace:U0,onRenameSplitWorkspace:z0,onCombineSplitSessions:H0,onReorderSessions:es,onSessionMenu:wi,onOpenSettings:js,onJumpToNextAttention:ba.length>0?Pl:void 0,onOpenQuota:()=>Zi(!0),updateState:Le,updateActionPending:ne,onConfirmUpdateRestart:st,onRetryUpdate:bt,serverHealthState:ke,tmuxAvailable:Tr.available,defaultSessionMode:fn,pinned:!0,onTogglePinned:Va})}),s.jsx("div",{role:"separator",tabIndex:-1,className:"shrink-0 w-[5px] h-full cursor-col-resize bg-border/10 hover:bg-primary/30 active:bg-primary/50 transition-colors",onMouseDown:dl})]}),s.jsxs("div",{className:"relative flex-1 min-w-0 h-full overflow-hidden",children:[zl,$l&&s.jsxs("div",{className:"absolute inset-y-0 right-0 z-20 flex",style:{width:yc},children:[s.jsx("div",{role:"separator",tabIndex:-1,className:"h-full w-[5px] shrink-0 cursor-col-resize bg-border/10 transition-colors hover:bg-primary/30 active:bg-primary/50",onMouseDown:Hi}),s.jsx("div",{style:{width:ud,flexShrink:0,height:"100%"},children:s.jsx(Pb,{isOpen:!0,sessionId:Ct,drawerWidthPx:ud,onClose:Hs,onOpen:ms,pinned:!0,onTogglePinned:ei,rightSidebarFilePreviewOpen:Bn,rightSidebarFilePreviewCloseSignal:Ae,onOpenRightSidebarFilePreview:bi,onCloseRightSidebarFilePreview:hl,rightSidebarRepoPickerOpen:et,rightSidebarRepoPickerCloseSignal:Gt,onOpenRightSidebarRepoPicker:ti,onCloseRightSidebarRepoPicker:Uo,markdownOutlineOpen:wt,markdownOutlineCloseSignal:Vt,onOpenMarkdownOutline:pa,onCloseMarkdownOutline:fl,markdownImageLightboxOpen:Ot,markdownImageLightboxCloseSignal:xe,onOpenMarkdownImageLightbox:pl,onCloseMarkdownImageLightbox:ls})})]})]}),s.jsx(Jb,{sessionId:Ct}),Hl]}):s.jsxs(s.Fragment,{children:[zl,s.jsx(Jb,{sessionId:Ct}),Hl]})}const BU=Object.freeze(Object.defineProperty({__proto__:null,default:U$},Symbol.toStringTag,{value:"Module"}));export{X$ as $,r0 as A,b0 as B,oF as C,YS as D,lf as E,Qy as F,lF as G,Qc as H,Uy as I,fS as J,Py as K,Oy as L,IT as M,$T as N,i0 as O,WT as P,D6 as Q,bn as R,jl as S,Um as T,LS as U,_I as V,Rs as W,Hy as X,OS as Y,nh as Z,JS as _,ZS as a,Z$ as a0,Ky as a1,eU as a2,tU as a3,J$ as a4,nv as a5,jU as a6,F2 as a7,c1 as a8,Uf as a9,Yb as aa,Zy as ab,Fh as ac,$1 as ad,dC as ae,UO as af,K$ as ag,$2 as ah,KE as ai,Ob as aj,Mm as ak,Ei as al,DU as am,n3 as an,uf as b,XF as c,BU as d,XS as e,My as f,EA as g,LA as h,jy as i,By as j,m0 as k,DO as l,sT as m,g0 as n,uO as o,Du as p,F1 as q,AT as r,MT as s,Fy as t,QT as u,$y as v,XT as w,eS as x,rS as y,x0 as z};
|