termdock 1.4.315 → 1.4.317
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-B2SFV3qg.js → App-BF_s1-_u.js} +6 -6
- package/dist/client/assets/App-BF_s1-_u.js.br +0 -0
- package/dist/client/assets/App-BF_s1-_u.js.gz +0 -0
- package/dist/client/assets/{ArchitecturePanel-Cj7za6DZ.js → ArchitecturePanel-CdgUQsVD.js} +2 -2
- package/dist/client/assets/ArchitecturePanel-CdgUQsVD.js.br +0 -0
- package/dist/client/assets/ArchitecturePanel-CdgUQsVD.js.gz +0 -0
- package/dist/client/assets/{ChangeWalkthroughPanel-BB52iLLC.js → ChangeWalkthroughPanel-DHp5r1k9.js} +1 -1
- package/dist/client/assets/ChangeWalkthroughPanel-DHp5r1k9.js.br +0 -0
- package/dist/client/assets/ChangeWalkthroughPanel-DHp5r1k9.js.gz +0 -0
- package/dist/client/assets/{CollaborationMainWorkspace-D5WKV3rA.js → CollaborationMainWorkspace-P_jXjsT-.js} +1 -1
- package/dist/client/assets/CollaborationMainWorkspace-P_jXjsT-.js.br +0 -0
- package/dist/client/assets/CollaborationMainWorkspace-P_jXjsT-.js.gz +0 -0
- package/dist/client/assets/CollaborationTaskContent-DSkxOlKQ.js +2 -0
- package/dist/client/assets/{ComputerControlView-Dkc4R1IU.js → ComputerControlView-B5Yng8Dt.js} +2 -2
- package/dist/client/assets/ComputerControlView-B5Yng8Dt.js.br +0 -0
- package/dist/client/assets/ComputerControlView-B5Yng8Dt.js.gz +0 -0
- package/dist/client/assets/{DagPlayground-BHY3l8UG.js → DagPlayground-rZE40fcL.js} +1 -1
- package/dist/client/assets/DagPlayground-rZE40fcL.js.br +0 -0
- package/dist/client/assets/DagPlayground-rZE40fcL.js.gz +0 -0
- package/dist/client/assets/{DiffLab-BSQiKfBJ.js → DiffLab-3sIn0W3p.js} +1 -1
- package/dist/client/assets/DiffLab-3sIn0W3p.js.br +0 -0
- package/dist/client/assets/DiffLab-3sIn0W3p.js.gz +0 -0
- package/dist/client/assets/{DiffReview-CYrBBq0V.js → DiffReview-CBf8-Tli.js} +1 -1
- package/dist/client/assets/DiffReview-CBf8-Tli.js.br +0 -0
- package/dist/client/assets/DiffReview-CBf8-Tli.js.gz +0 -0
- package/dist/client/assets/{DiffReviewLab-VSIbEnxm.js → DiffReviewLab-BXhskTlx.js} +1 -1
- package/dist/client/assets/DiffReviewLab-BXhskTlx.js.br +0 -0
- package/dist/client/assets/DiffReviewLab-BXhskTlx.js.gz +0 -0
- package/dist/client/assets/{DiffViewer-Cx5fyiMB.js → DiffViewer-DZfgjOBh.js} +1 -1
- package/dist/client/assets/DiffViewer-DZfgjOBh.js.br +0 -0
- package/dist/client/assets/DiffViewer-DZfgjOBh.js.gz +0 -0
- package/dist/client/assets/{ModelPreview-B22odexG.js → ModelPreview-Bzdi_sPh.js} +1 -1
- package/dist/client/assets/ModelPreview-Bzdi_sPh.js.br +0 -0
- package/dist/client/assets/ModelPreview-Bzdi_sPh.js.gz +0 -0
- package/dist/client/assets/{RightSidebar-DKA0jXPW.js → RightSidebar-DaRdlJzn.js} +42 -42
- package/dist/client/assets/RightSidebar-DaRdlJzn.js.br +0 -0
- package/dist/client/assets/RightSidebar-DaRdlJzn.js.gz +0 -0
- package/dist/client/assets/{abnfDiagram-VCTEODGH-sbUSsiPn.js → abnfDiagram-VCTEODGH-CarKrfAf.js} +1 -1
- package/dist/client/assets/abnfDiagram-VCTEODGH-CarKrfAf.js.br +0 -0
- package/dist/client/assets/abnfDiagram-VCTEODGH-CarKrfAf.js.gz +0 -0
- package/dist/client/assets/{app-CYOLJycb.js → app-BCTEfclM.js} +3 -3
- package/dist/client/assets/app-BCTEfclM.js.br +0 -0
- package/dist/client/assets/app-BCTEfclM.js.gz +0 -0
- package/dist/client/assets/{arc-GhJ9aeQ3.js → arc-B6Qdq2Vw.js} +1 -1
- package/dist/client/assets/arc-B6Qdq2Vw.js.br +0 -0
- package/dist/client/assets/arc-B6Qdq2Vw.js.gz +0 -0
- package/dist/client/assets/{architectureDiagram-5GKGNRK7-BYmAIJBx.js → architectureDiagram-5GKGNRK7-DgPJ0l9i.js} +1 -1
- package/dist/client/assets/architectureDiagram-5GKGNRK7-DgPJ0l9i.js.br +0 -0
- package/dist/client/assets/architectureDiagram-5GKGNRK7-DgPJ0l9i.js.gz +0 -0
- package/dist/client/assets/{blockDiagram-I7D4REHJ-CZNZT_ez.js → blockDiagram-I7D4REHJ-BsorvNo4.js} +1 -1
- package/dist/client/assets/blockDiagram-I7D4REHJ-BsorvNo4.js.br +0 -0
- package/dist/client/assets/blockDiagram-I7D4REHJ-BsorvNo4.js.gz +0 -0
- package/dist/client/assets/{c4Diagram-7LVT6UL2-6xcSowLn.js → c4Diagram-7LVT6UL2-Bbpi62ab.js} +1 -1
- package/dist/client/assets/c4Diagram-7LVT6UL2-Bbpi62ab.js.br +0 -0
- package/dist/client/assets/c4Diagram-7LVT6UL2-Bbpi62ab.js.gz +0 -0
- package/dist/client/assets/channel-uZtI4GD8.js +1 -0
- package/dist/client/assets/{chunk-2Q5K7J3B-C06nkhUQ.js → chunk-2Q5K7J3B-Cm7mDz66.js} +1 -1
- package/dist/client/assets/{chunk-5VM5RSS4-BHY43hJO.js → chunk-5VM5RSS4-BMERXU_m.js} +1 -1
- package/dist/client/assets/{chunk-F27PBJKO-Dl8JYcZO.js → chunk-F27PBJKO-fe9Yw7OI.js} +1 -1
- package/dist/client/assets/chunk-F27PBJKO-fe9Yw7OI.js.br +0 -0
- package/dist/client/assets/chunk-F27PBJKO-fe9Yw7OI.js.gz +0 -0
- package/dist/client/assets/{chunk-IMKFNOWR-BALi4Q3g.js → chunk-IMKFNOWR-QquKV9k-.js} +1 -1
- package/dist/client/assets/chunk-IMKFNOWR-QquKV9k-.js.br +0 -0
- package/dist/client/assets/chunk-IMKFNOWR-QquKV9k-.js.gz +0 -0
- package/dist/client/assets/{chunk-JWPE2WC7-BBD2d7j7.js → chunk-JWPE2WC7-CVe8_YO4.js} +1 -1
- package/dist/client/assets/{chunk-POPQ4Y6H-CZN0_ndj.js → chunk-POPQ4Y6H-DT8PalJ4.js} +1 -1
- package/dist/client/assets/{chunk-SVP7TREG-CD-Zf9rn.js → chunk-SVP7TREG-BUQulipE.js} +1 -1
- package/dist/client/assets/chunk-SVP7TREG-BUQulipE.js.br +0 -0
- package/dist/client/assets/chunk-SVP7TREG-BUQulipE.js.gz +0 -0
- package/dist/client/assets/{chunk-TICWLB2K-Clpg1zwp.js → chunk-TICWLB2K-fubKwUCg.js} +1 -1
- package/dist/client/assets/chunk-TICWLB2K-fubKwUCg.js.br +0 -0
- package/dist/client/assets/chunk-TICWLB2K-fubKwUCg.js.gz +0 -0
- package/dist/client/assets/{chunk-XXDRQBXY-BanPVnIr.js → chunk-XXDRQBXY-CdwTi82y.js} +1 -1
- package/dist/client/assets/classDiagram-ZZMXUADV-CgJJ1J4J.js +1 -0
- package/dist/client/assets/classDiagram-v2-VYDZK3BY-CgJJ1J4J.js +1 -0
- package/dist/client/assets/{cose-bilkent-JH36ORCC-431u7cfU.js → cose-bilkent-JH36ORCC-DmEDc2ee.js} +1 -1
- package/dist/client/assets/cose-bilkent-JH36ORCC-DmEDc2ee.js.br +0 -0
- package/dist/client/assets/cose-bilkent-JH36ORCC-DmEDc2ee.js.gz +0 -0
- package/dist/client/assets/{cynefin-OW5HDTMX-BuLFGx14.js → cynefin-OW5HDTMX-C-mfarRX.js} +1 -1
- package/dist/client/assets/cynefin-OW5HDTMX-C-mfarRX.js.br +0 -0
- package/dist/client/assets/cynefin-OW5HDTMX-C-mfarRX.js.gz +0 -0
- package/dist/client/assets/{cynefinDiagram-5FMLGOSQ-qLzjwMMG.js → cynefinDiagram-5FMLGOSQ-CgVmp8od.js} +1 -1
- package/dist/client/assets/cynefinDiagram-5FMLGOSQ-CgVmp8od.js.br +0 -0
- package/dist/client/assets/cynefinDiagram-5FMLGOSQ-CgVmp8od.js.gz +0 -0
- package/dist/client/assets/{dagre-GXQ25YYZ-CUdd5M5g.js → dagre-GXQ25YYZ-WU_d2fSU.js} +1 -1
- package/dist/client/assets/dagre-GXQ25YYZ-WU_d2fSU.js.br +0 -0
- package/dist/client/assets/dagre-GXQ25YYZ-WU_d2fSU.js.gz +0 -0
- package/dist/client/assets/{diagram-S7CK7UJ4-DLQClBzm.js → diagram-S7CK7UJ4-Dtikk80Z.js} +1 -1
- package/dist/client/assets/diagram-S7CK7UJ4-Dtikk80Z.js.br +0 -0
- package/dist/client/assets/diagram-S7CK7UJ4-Dtikk80Z.js.gz +0 -0
- package/dist/client/assets/{diagram-UQ7AKVKN-1RGASXU_.js → diagram-UQ7AKVKN-DuTCB36P.js} +1 -1
- package/dist/client/assets/diagram-UQ7AKVKN-DuTCB36P.js.br +0 -0
- package/dist/client/assets/diagram-UQ7AKVKN-DuTCB36P.js.gz +0 -0
- package/dist/client/assets/{diagram-VSXAHHWV-DqnCzn2R.js → diagram-VSXAHHWV-DSLAcWi6.js} +1 -1
- package/dist/client/assets/diagram-VSXAHHWV-DSLAcWi6.js.br +0 -0
- package/dist/client/assets/diagram-VSXAHHWV-DSLAcWi6.js.gz +0 -0
- package/dist/client/assets/{diagram-VX7I27RA-CMXsPqTS.js → diagram-VX7I27RA-DyQOu10m.js} +1 -1
- package/dist/client/assets/diagram-VX7I27RA-DyQOu10m.js.br +0 -0
- package/dist/client/assets/diagram-VX7I27RA-DyQOu10m.js.gz +0 -0
- package/dist/client/assets/{diagram-Z3DM3KII-BM0N1kCR.js → diagram-Z3DM3KII-CuMI1k1t.js} +1 -1
- package/dist/client/assets/diagram-Z3DM3KII-CuMI1k1t.js.br +0 -0
- package/dist/client/assets/diagram-Z3DM3KII-CuMI1k1t.js.gz +0 -0
- package/dist/client/assets/{ebnfDiagram-PWID7BFC-CvaVo-wh.js → ebnfDiagram-PWID7BFC-Di8RxhNL.js} +1 -1
- package/dist/client/assets/ebnfDiagram-PWID7BFC-Di8RxhNL.js.br +0 -0
- package/dist/client/assets/ebnfDiagram-PWID7BFC-Di8RxhNL.js.gz +0 -0
- package/dist/client/assets/{erDiagram-RLTQ6QDP-okw-AY7i.js → erDiagram-RLTQ6QDP-C1wPuBtH.js} +1 -1
- package/dist/client/assets/erDiagram-RLTQ6QDP-C1wPuBtH.js.br +0 -0
- package/dist/client/assets/erDiagram-RLTQ6QDP-C1wPuBtH.js.gz +0 -0
- package/dist/client/assets/{flowDiagram-HODETNUW-B_DWtzOe.js → flowDiagram-HODETNUW-D0SIEpUy.js} +1 -1
- package/dist/client/assets/flowDiagram-HODETNUW-D0SIEpUy.js.br +0 -0
- package/dist/client/assets/flowDiagram-HODETNUW-D0SIEpUy.js.gz +0 -0
- package/dist/client/assets/{ganttDiagram-EL5Y4UJY-Bm4nYUVg.js → ganttDiagram-EL5Y4UJY-DgeD2fKd.js} +1 -1
- package/dist/client/assets/ganttDiagram-EL5Y4UJY-DgeD2fKd.js.br +0 -0
- package/dist/client/assets/{ganttDiagram-EL5Y4UJY-Bm4nYUVg.js.gz → ganttDiagram-EL5Y4UJY-DgeD2fKd.js.gz} +0 -0
- package/dist/client/assets/{gestureArbiter-XalN4TaN.js → gestureArbiter-Xl7awIrX.js} +1 -1
- package/dist/client/assets/gestureArbiter-Xl7awIrX.js.br +0 -0
- package/dist/client/assets/gestureArbiter-Xl7awIrX.js.gz +0 -0
- package/dist/client/assets/{gitGraphDiagram-WWUBYQGX-B7LAo8S2.js → gitGraphDiagram-WWUBYQGX-CzFKSKK_.js} +1 -1
- package/dist/client/assets/gitGraphDiagram-WWUBYQGX-CzFKSKK_.js.br +0 -0
- package/dist/client/assets/gitGraphDiagram-WWUBYQGX-CzFKSKK_.js.gz +0 -0
- package/dist/client/assets/{infoDiagram-27XIBGKW-DXncUrwz.js → infoDiagram-27XIBGKW-C9mmJGhv.js} +1 -1
- package/dist/client/assets/{ishikawaDiagram-5VMMS53U-Ds28H7pI.js → ishikawaDiagram-5VMMS53U-D9uVb4Og.js} +1 -1
- package/dist/client/assets/ishikawaDiagram-5VMMS53U-D9uVb4Og.js.br +0 -0
- package/dist/client/assets/ishikawaDiagram-5VMMS53U-D9uVb4Og.js.gz +0 -0
- package/dist/client/assets/{journeyDiagram-3NMN7TZE-WeF_efZ2.js → journeyDiagram-3NMN7TZE-BMKNUyUx.js} +1 -1
- package/dist/client/assets/journeyDiagram-3NMN7TZE-BMKNUyUx.js.br +0 -0
- package/dist/client/assets/journeyDiagram-3NMN7TZE-BMKNUyUx.js.gz +0 -0
- package/dist/client/assets/{kanban-definition-UXKFOSKX-CMbZcy6U.js → kanban-definition-UXKFOSKX-8i7nyqix.js} +1 -1
- package/dist/client/assets/{kanban-definition-UXKFOSKX-CMbZcy6U.js.br → kanban-definition-UXKFOSKX-8i7nyqix.js.br} +0 -0
- package/dist/client/assets/kanban-definition-UXKFOSKX-8i7nyqix.js.gz +0 -0
- package/dist/client/assets/{layout-DNapC8T-.js → layout-BS5SCHbc.js} +1 -1
- package/dist/client/assets/layout-BS5SCHbc.js.br +0 -0
- package/dist/client/assets/layout-BS5SCHbc.js.gz +0 -0
- package/dist/client/assets/{linear-B9AFx-TF.js → linear-fo2zkK6T.js} +1 -1
- package/dist/client/assets/linear-fo2zkK6T.js.br +0 -0
- package/dist/client/assets/linear-fo2zkK6T.js.gz +0 -0
- package/dist/client/assets/{mermaid.core-Ddh1Z0hf.js → mermaid.core-B8k3pAmc.js} +5 -5
- package/dist/client/assets/mermaid.core-B8k3pAmc.js.br +0 -0
- package/dist/client/assets/mermaid.core-B8k3pAmc.js.gz +0 -0
- package/dist/client/assets/{mindmap-definition-YA3MSWOX-B0xMGUol.js → mindmap-definition-YA3MSWOX-BwgQTj2Q.js} +1 -1
- package/dist/client/assets/mindmap-definition-YA3MSWOX-BwgQTj2Q.js.br +0 -0
- package/dist/client/assets/mindmap-definition-YA3MSWOX-BwgQTj2Q.js.gz +0 -0
- package/dist/client/assets/{passwordBootstrap-DQRd5vCF.js → passwordBootstrap-DvQk0qYt.js} +1 -1
- package/dist/client/assets/passwordBootstrap-DvQk0qYt.js.br +0 -0
- package/dist/client/assets/passwordBootstrap-DvQk0qYt.js.gz +0 -0
- package/dist/client/assets/{pegDiagram-XKGWAZYB-BVZ-3kEF.js → pegDiagram-XKGWAZYB-CumSoxLr.js} +1 -1
- package/dist/client/assets/pegDiagram-XKGWAZYB-CumSoxLr.js.br +0 -0
- package/dist/client/assets/pegDiagram-XKGWAZYB-CumSoxLr.js.gz +0 -0
- package/dist/client/assets/{pieDiagram-E7YTZNPT-Cim4Hk3I.js → pieDiagram-E7YTZNPT-Dc3txkBL.js} +1 -1
- package/dist/client/assets/pieDiagram-E7YTZNPT-Dc3txkBL.js.br +0 -0
- package/dist/client/assets/pieDiagram-E7YTZNPT-Dc3txkBL.js.gz +0 -0
- package/dist/client/assets/{quadrantDiagram-AXDQQJYC-CYiEj5sp.js → quadrantDiagram-AXDQQJYC-D92mwZnT.js} +1 -1
- package/dist/client/assets/quadrantDiagram-AXDQQJYC-D92mwZnT.js.br +0 -0
- package/dist/client/assets/quadrantDiagram-AXDQQJYC-D92mwZnT.js.gz +0 -0
- package/dist/client/assets/{railroadDiagram-O6MQD6OU-DjNNfYra.js → railroadDiagram-O6MQD6OU-O1UOZ30Y.js} +1 -1
- package/dist/client/assets/railroadDiagram-O6MQD6OU-O1UOZ30Y.js.br +0 -0
- package/dist/client/assets/railroadDiagram-O6MQD6OU-O1UOZ30Y.js.gz +0 -0
- package/dist/client/assets/{rdpSession-DEzSQAuN.js → rdpSession-Dr_tPwzx.js} +1 -1
- package/dist/client/assets/rdpSession-Dr_tPwzx.js.br +0 -0
- package/dist/client/assets/rdpSession-Dr_tPwzx.js.gz +0 -0
- package/dist/client/assets/{referenceLongPress-BjyTtoDY.js → referenceLongPress-YuGU-PYw.js} +1 -1
- package/dist/client/assets/referenceLongPress-YuGU-PYw.js.br +0 -0
- package/dist/client/assets/referenceLongPress-YuGU-PYw.js.gz +0 -0
- package/dist/client/assets/{requirementDiagram-BXWQKSXE-ZwiKdiI3.js → requirementDiagram-BXWQKSXE-uD1cgrxA.js} +1 -1
- package/dist/client/assets/requirementDiagram-BXWQKSXE-uD1cgrxA.js.br +0 -0
- package/dist/client/assets/requirementDiagram-BXWQKSXE-uD1cgrxA.js.gz +0 -0
- package/dist/client/assets/{sankeyDiagram-P5KCCOFB-BYR7ctps.js → sankeyDiagram-P5KCCOFB-CIJE4-pc.js} +1 -1
- package/dist/client/assets/sankeyDiagram-P5KCCOFB-CIJE4-pc.js.br +0 -0
- package/dist/client/assets/sankeyDiagram-P5KCCOFB-CIJE4-pc.js.gz +0 -0
- package/dist/client/assets/{sequenceDiagram-WJ2MYXX4-DxYCvK80.js → sequenceDiagram-WJ2MYXX4-BT6LG37W.js} +1 -1
- package/dist/client/assets/sequenceDiagram-WJ2MYXX4-BT6LG37W.js.br +0 -0
- package/dist/client/assets/sequenceDiagram-WJ2MYXX4-BT6LG37W.js.gz +0 -0
- package/dist/client/assets/{sizeCapture-INFHLROL-CXruk8Ko.js → sizeCapture-INFHLROL-DoYY94Rj.js} +1 -1
- package/dist/client/assets/sizeCapture-INFHLROL-DoYY94Rj.js.br +0 -0
- package/dist/client/assets/sizeCapture-INFHLROL-DoYY94Rj.js.gz +0 -0
- package/dist/client/assets/{sparkles-DRH97PDH.js → sparkles-DFYGpezN.js} +1 -1
- package/dist/client/assets/{stateDiagram-D77RDMKH-CENDGrxr.js → stateDiagram-D77RDMKH-C4xmgR_-.js} +1 -1
- package/dist/client/assets/stateDiagram-D77RDMKH-C4xmgR_-.js.br +0 -0
- package/dist/client/assets/stateDiagram-D77RDMKH-C4xmgR_-.js.gz +0 -0
- package/dist/client/assets/stateDiagram-v2-MP3YSRHH-BLHH60cg.js +1 -0
- package/dist/client/assets/{swimlanes-42K2YHIH-BZQeVFeA.js → swimlanes-42K2YHIH-mRdmZmAA.js} +1 -1
- package/dist/client/assets/swimlanes-42K2YHIH-mRdmZmAA.js.br +0 -0
- package/dist/client/assets/swimlanes-42K2YHIH-mRdmZmAA.js.gz +0 -0
- package/dist/client/assets/swimlanesDiagram-VR7AAH4N-D-lNPW5d.js +8 -0
- package/dist/client/assets/{timeline-definition-24CTP7MA-DiJ9i33g.js → timeline-definition-24CTP7MA-BFFrD5kR.js} +1 -1
- package/dist/client/assets/timeline-definition-24CTP7MA-BFFrD5kR.js.br +0 -0
- package/dist/client/assets/timeline-definition-24CTP7MA-BFFrD5kR.js.gz +0 -0
- package/dist/client/assets/{triangle-alert-DECoBoOV.js → triangle-alert-BwJ6Q_Y0.js} +1 -1
- package/dist/client/assets/{vennDiagram-4TSXK5OY-DBiEJQ9Y.js → vennDiagram-4TSXK5OY-Dy59OxIM.js} +1 -1
- package/dist/client/assets/vennDiagram-4TSXK5OY-Dy59OxIM.js.br +0 -0
- package/dist/client/assets/vennDiagram-4TSXK5OY-Dy59OxIM.js.gz +0 -0
- package/dist/client/assets/{videoCompression-8r1jOza9.js → videoCompression-DrQ47oZA.js} +1 -1
- package/dist/client/assets/videoCompression-DrQ47oZA.js.br +0 -0
- package/dist/client/assets/videoCompression-DrQ47oZA.js.gz +0 -0
- package/dist/client/assets/{wardleyDiagram-VM6X3IG4-B6wCSfya.js → wardleyDiagram-VM6X3IG4-B-BKlX7o.js} +1 -1
- package/dist/client/assets/wardleyDiagram-VM6X3IG4-B-BKlX7o.js.br +0 -0
- package/dist/client/assets/wardleyDiagram-VM6X3IG4-B-BKlX7o.js.gz +0 -0
- package/dist/client/assets/{xychartDiagram-S5SC5T6Z-DlNQayU5.js → xychartDiagram-S5SC5T6Z-79qktI_4.js} +1 -1
- package/dist/client/assets/xychartDiagram-S5SC5T6Z-79qktI_4.js.br +0 -0
- package/dist/client/assets/xychartDiagram-S5SC5T6Z-79qktI_4.js.gz +0 -0
- package/dist/client/index.html +1 -1
- 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/agent/collaborationPrompt.js +1 -1
- package/dist/server/agent/collaborationProtocol.js +2 -0
- package/dist/server/agent/collaborationStore.js +47 -3
- package/dist/server/agent/integrationCli.js +30 -0
- package/dist/server/agent/integrationServer.js +9 -0
- package/dist/server/routes/terminal.js +5 -1
- package/dist/server/utils/settings.js +14 -0
- package/docs/integrations.md +67 -0
- package/package.json +1 -1
- package/runtime-manifest.json +3 -3
- package/dist/client/assets/App-B2SFV3qg.js.br +0 -0
- package/dist/client/assets/App-B2SFV3qg.js.gz +0 -0
- package/dist/client/assets/ArchitecturePanel-Cj7za6DZ.js.br +0 -0
- package/dist/client/assets/ArchitecturePanel-Cj7za6DZ.js.gz +0 -0
- package/dist/client/assets/ChangeWalkthroughPanel-BB52iLLC.js.br +0 -0
- package/dist/client/assets/ChangeWalkthroughPanel-BB52iLLC.js.gz +0 -0
- package/dist/client/assets/CollaborationMainWorkspace-D5WKV3rA.js.br +0 -0
- package/dist/client/assets/CollaborationMainWorkspace-D5WKV3rA.js.gz +0 -0
- package/dist/client/assets/CollaborationTaskContent-MwUgcmG_.js +0 -2
- package/dist/client/assets/ComputerControlView-Dkc4R1IU.js.br +0 -0
- package/dist/client/assets/ComputerControlView-Dkc4R1IU.js.gz +0 -0
- package/dist/client/assets/DagPlayground-BHY3l8UG.js.br +0 -0
- package/dist/client/assets/DagPlayground-BHY3l8UG.js.gz +0 -0
- package/dist/client/assets/DiffLab-BSQiKfBJ.js.br +0 -0
- package/dist/client/assets/DiffLab-BSQiKfBJ.js.gz +0 -0
- package/dist/client/assets/DiffReview-CYrBBq0V.js.br +0 -0
- package/dist/client/assets/DiffReview-CYrBBq0V.js.gz +0 -0
- package/dist/client/assets/DiffReviewLab-VSIbEnxm.js.br +0 -0
- package/dist/client/assets/DiffReviewLab-VSIbEnxm.js.gz +0 -0
- package/dist/client/assets/DiffViewer-Cx5fyiMB.js.br +0 -0
- package/dist/client/assets/DiffViewer-Cx5fyiMB.js.gz +0 -0
- package/dist/client/assets/ModelPreview-B22odexG.js.br +0 -0
- package/dist/client/assets/ModelPreview-B22odexG.js.gz +0 -0
- package/dist/client/assets/RightSidebar-DKA0jXPW.js.br +0 -0
- package/dist/client/assets/RightSidebar-DKA0jXPW.js.gz +0 -0
- package/dist/client/assets/abnfDiagram-VCTEODGH-sbUSsiPn.js.br +0 -0
- package/dist/client/assets/abnfDiagram-VCTEODGH-sbUSsiPn.js.gz +0 -0
- package/dist/client/assets/app-CYOLJycb.js.br +0 -0
- package/dist/client/assets/app-CYOLJycb.js.gz +0 -0
- package/dist/client/assets/arc-GhJ9aeQ3.js.br +0 -0
- package/dist/client/assets/arc-GhJ9aeQ3.js.gz +0 -0
- package/dist/client/assets/architectureDiagram-5GKGNRK7-BYmAIJBx.js.br +0 -0
- package/dist/client/assets/architectureDiagram-5GKGNRK7-BYmAIJBx.js.gz +0 -0
- package/dist/client/assets/blockDiagram-I7D4REHJ-CZNZT_ez.js.br +0 -0
- package/dist/client/assets/blockDiagram-I7D4REHJ-CZNZT_ez.js.gz +0 -0
- package/dist/client/assets/c4Diagram-7LVT6UL2-6xcSowLn.js.br +0 -0
- package/dist/client/assets/c4Diagram-7LVT6UL2-6xcSowLn.js.gz +0 -0
- package/dist/client/assets/channel-C1FwyjiU.js +0 -1
- package/dist/client/assets/chunk-F27PBJKO-Dl8JYcZO.js.br +0 -0
- package/dist/client/assets/chunk-F27PBJKO-Dl8JYcZO.js.gz +0 -0
- package/dist/client/assets/chunk-IMKFNOWR-BALi4Q3g.js.br +0 -0
- package/dist/client/assets/chunk-IMKFNOWR-BALi4Q3g.js.gz +0 -0
- package/dist/client/assets/chunk-SVP7TREG-CD-Zf9rn.js.br +0 -0
- package/dist/client/assets/chunk-SVP7TREG-CD-Zf9rn.js.gz +0 -0
- package/dist/client/assets/chunk-TICWLB2K-Clpg1zwp.js.br +0 -0
- package/dist/client/assets/chunk-TICWLB2K-Clpg1zwp.js.gz +0 -0
- package/dist/client/assets/classDiagram-ZZMXUADV-FyKDan8T.js +0 -1
- package/dist/client/assets/classDiagram-v2-VYDZK3BY-FyKDan8T.js +0 -1
- package/dist/client/assets/cose-bilkent-JH36ORCC-431u7cfU.js.br +0 -0
- package/dist/client/assets/cose-bilkent-JH36ORCC-431u7cfU.js.gz +0 -0
- package/dist/client/assets/cynefin-OW5HDTMX-BuLFGx14.js.br +0 -0
- package/dist/client/assets/cynefin-OW5HDTMX-BuLFGx14.js.gz +0 -0
- package/dist/client/assets/cynefinDiagram-5FMLGOSQ-qLzjwMMG.js.br +0 -0
- package/dist/client/assets/cynefinDiagram-5FMLGOSQ-qLzjwMMG.js.gz +0 -0
- package/dist/client/assets/dagre-GXQ25YYZ-CUdd5M5g.js.br +0 -0
- package/dist/client/assets/dagre-GXQ25YYZ-CUdd5M5g.js.gz +0 -0
- package/dist/client/assets/diagram-S7CK7UJ4-DLQClBzm.js.br +0 -0
- package/dist/client/assets/diagram-S7CK7UJ4-DLQClBzm.js.gz +0 -0
- package/dist/client/assets/diagram-UQ7AKVKN-1RGASXU_.js.br +0 -0
- package/dist/client/assets/diagram-UQ7AKVKN-1RGASXU_.js.gz +0 -0
- package/dist/client/assets/diagram-VSXAHHWV-DqnCzn2R.js.br +0 -0
- package/dist/client/assets/diagram-VSXAHHWV-DqnCzn2R.js.gz +0 -0
- package/dist/client/assets/diagram-VX7I27RA-CMXsPqTS.js.br +0 -0
- package/dist/client/assets/diagram-VX7I27RA-CMXsPqTS.js.gz +0 -0
- package/dist/client/assets/diagram-Z3DM3KII-BM0N1kCR.js.br +0 -0
- package/dist/client/assets/diagram-Z3DM3KII-BM0N1kCR.js.gz +0 -0
- package/dist/client/assets/ebnfDiagram-PWID7BFC-CvaVo-wh.js.br +0 -0
- package/dist/client/assets/ebnfDiagram-PWID7BFC-CvaVo-wh.js.gz +0 -0
- package/dist/client/assets/erDiagram-RLTQ6QDP-okw-AY7i.js.br +0 -0
- package/dist/client/assets/erDiagram-RLTQ6QDP-okw-AY7i.js.gz +0 -0
- package/dist/client/assets/flowDiagram-HODETNUW-B_DWtzOe.js.br +0 -0
- package/dist/client/assets/flowDiagram-HODETNUW-B_DWtzOe.js.gz +0 -0
- package/dist/client/assets/ganttDiagram-EL5Y4UJY-Bm4nYUVg.js.br +0 -0
- package/dist/client/assets/gestureArbiter-XalN4TaN.js.br +0 -0
- package/dist/client/assets/gestureArbiter-XalN4TaN.js.gz +0 -0
- package/dist/client/assets/gitGraphDiagram-WWUBYQGX-B7LAo8S2.js.br +0 -0
- package/dist/client/assets/gitGraphDiagram-WWUBYQGX-B7LAo8S2.js.gz +0 -0
- package/dist/client/assets/ishikawaDiagram-5VMMS53U-Ds28H7pI.js.br +0 -0
- package/dist/client/assets/ishikawaDiagram-5VMMS53U-Ds28H7pI.js.gz +0 -0
- package/dist/client/assets/journeyDiagram-3NMN7TZE-WeF_efZ2.js.br +0 -0
- package/dist/client/assets/journeyDiagram-3NMN7TZE-WeF_efZ2.js.gz +0 -0
- package/dist/client/assets/kanban-definition-UXKFOSKX-CMbZcy6U.js.gz +0 -0
- package/dist/client/assets/layout-DNapC8T-.js.br +0 -0
- package/dist/client/assets/layout-DNapC8T-.js.gz +0 -0
- package/dist/client/assets/linear-B9AFx-TF.js.br +0 -0
- package/dist/client/assets/linear-B9AFx-TF.js.gz +0 -0
- package/dist/client/assets/mermaid.core-Ddh1Z0hf.js.br +0 -0
- package/dist/client/assets/mermaid.core-Ddh1Z0hf.js.gz +0 -0
- package/dist/client/assets/mindmap-definition-YA3MSWOX-B0xMGUol.js.br +0 -0
- package/dist/client/assets/mindmap-definition-YA3MSWOX-B0xMGUol.js.gz +0 -0
- package/dist/client/assets/passwordBootstrap-DQRd5vCF.js.br +0 -0
- package/dist/client/assets/passwordBootstrap-DQRd5vCF.js.gz +0 -0
- package/dist/client/assets/pegDiagram-XKGWAZYB-BVZ-3kEF.js.br +0 -0
- package/dist/client/assets/pegDiagram-XKGWAZYB-BVZ-3kEF.js.gz +0 -0
- package/dist/client/assets/pieDiagram-E7YTZNPT-Cim4Hk3I.js.br +0 -0
- package/dist/client/assets/pieDiagram-E7YTZNPT-Cim4Hk3I.js.gz +0 -0
- package/dist/client/assets/quadrantDiagram-AXDQQJYC-CYiEj5sp.js.br +0 -0
- package/dist/client/assets/quadrantDiagram-AXDQQJYC-CYiEj5sp.js.gz +0 -0
- package/dist/client/assets/railroadDiagram-O6MQD6OU-DjNNfYra.js.br +0 -0
- package/dist/client/assets/railroadDiagram-O6MQD6OU-DjNNfYra.js.gz +0 -0
- package/dist/client/assets/rdpSession-DEzSQAuN.js.br +0 -0
- package/dist/client/assets/rdpSession-DEzSQAuN.js.gz +0 -0
- package/dist/client/assets/referenceLongPress-BjyTtoDY.js.br +0 -0
- package/dist/client/assets/referenceLongPress-BjyTtoDY.js.gz +0 -0
- package/dist/client/assets/requirementDiagram-BXWQKSXE-ZwiKdiI3.js.br +0 -0
- package/dist/client/assets/requirementDiagram-BXWQKSXE-ZwiKdiI3.js.gz +0 -0
- package/dist/client/assets/sankeyDiagram-P5KCCOFB-BYR7ctps.js.br +0 -0
- package/dist/client/assets/sankeyDiagram-P5KCCOFB-BYR7ctps.js.gz +0 -0
- package/dist/client/assets/sequenceDiagram-WJ2MYXX4-DxYCvK80.js.br +0 -0
- package/dist/client/assets/sequenceDiagram-WJ2MYXX4-DxYCvK80.js.gz +0 -0
- package/dist/client/assets/sizeCapture-INFHLROL-CXruk8Ko.js.br +0 -0
- package/dist/client/assets/sizeCapture-INFHLROL-CXruk8Ko.js.gz +0 -0
- package/dist/client/assets/stateDiagram-D77RDMKH-CENDGrxr.js.br +0 -0
- package/dist/client/assets/stateDiagram-D77RDMKH-CENDGrxr.js.gz +0 -0
- package/dist/client/assets/stateDiagram-v2-MP3YSRHH-De-tGy_n.js +0 -1
- package/dist/client/assets/swimlanes-42K2YHIH-BZQeVFeA.js.br +0 -0
- package/dist/client/assets/swimlanes-42K2YHIH-BZQeVFeA.js.gz +0 -0
- package/dist/client/assets/swimlanesDiagram-VR7AAH4N-D1YMLrIO.js +0 -8
- package/dist/client/assets/timeline-definition-24CTP7MA-DiJ9i33g.js.br +0 -0
- package/dist/client/assets/timeline-definition-24CTP7MA-DiJ9i33g.js.gz +0 -0
- package/dist/client/assets/vennDiagram-4TSXK5OY-DBiEJQ9Y.js.br +0 -0
- package/dist/client/assets/vennDiagram-4TSXK5OY-DBiEJQ9Y.js.gz +0 -0
- package/dist/client/assets/videoCompression-8r1jOza9.js.br +0 -0
- package/dist/client/assets/videoCompression-8r1jOza9.js.gz +0 -0
- package/dist/client/assets/wardleyDiagram-VM6X3IG4-B6wCSfya.js.br +0 -0
- package/dist/client/assets/wardleyDiagram-VM6X3IG4-B6wCSfya.js.gz +0 -0
- package/dist/client/assets/xychartDiagram-S5SC5T6Z-DlNQayU5.js.br +0 -0
- package/dist/client/assets/xychartDiagram-S5SC5T6Z-DlNQayU5.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 Yu,by as s,ac as hc,da as zr,H as q8,dk as sl,d6 as ka,d8 as es,b1 as fc,a7 as J0,az as py,bp as M1,cN as Y8,d7 as L0,cy as u0,b6 as xo,j as d0,af as Qu,co as vp,cV as Z8,as as Dc,bx as Tu,g as K8,cI as Qh,Z as X8,bb as Bm,bI as Qm,cE as J8,ax as ew,ch as tw,a5 as my,cf as rw,cC as gy,aa as nw,ah as sw,L as Cn,C as hi,X as Rn,f as iw,d as ul,bg as aw,b0 as Pm,dc as ow,dh as Yr,bG as j1,dg as Gt,aD as lw,dq as cw,v as uw,bN as dw,c0 as hw,a4 as _a,bR as fw,cA as Jg,cB as e2,cD as t2,W as r2,b$ as pw,cO as mw,t as Jd,bo as D1,d5 as gw,_ as Oc,b9 as xw,i as bw,dj as xy,a_ as il,T as Fo,db as I0,df as yw,ci as vw,an as ww,aY as Aw,bZ as Tw,b_ as Sw,P as by,V as n2,bO as s2,bA as yy,n as Us,$ as Ph,cW as wp,bH as Cw,ck as _w,bF as vy,de as kw,bf as Bo,dm as Lw,B as cc,e as fi,u as Iw,ak as Ew,N as Om,cv as Nw,h as $o,bt as Rw,bu as Mw,ap as wy,aB as Ay,a6 as ku,m as e0,cs as ac,c2 as Ty,aw as t0,c as Fm,d9 as Sy,aJ as jw,S as nf,bm as sf,a as Cy,ar as Dw,ae as Bw,d3 as Qw,c3 as Pu,a8 as uc,bE as i2,cz as Pw,c7 as Ow,cS as Fw,cU as _y,bB as $w,bD as B1,cG as Uw,cH as zw,c4 as Hw,cF as Ww,cp as Gw,cm as Vw,cj as qw,c6 as Yw,cw as Zw,bQ as Kw,bP as ky,cr as Xw,bC as a2,aH as Jw,a$ as e9,D as t9,aG as o2,bK as r9,q as n9,p as s9,bM as i9,F as a9,c5 as o9,l as l9,cx as c9,r as u9,c1 as d9,au as h9,aA as f9,aC as p9,ba as ud,bk as m9,d0 as g9,bl as x9,ao as b9,d2 as y9,Q as v9,aj as w9,ad as A9,A as T9,b8 as S9,aq as C9,M as _9,di as k9,bT as Tc,b5 as L9,b2 as I9,b3 as E9,b4 as N9,aW as Ap,bU as R9,cb as M9,cl as j9,b7 as D9,aZ as B9,cT as l2,am as Q9,a9 as P9,Y as O9,c_ as F9,dn as On,cu as Sc,bS as $9,w as U9,cQ as z9,aV as H9,bc as c2,ca as W9,cM as eh,cZ as dd,d1 as G9,cc as V9,cR as q9,cJ as Y9,cY as Tp,cK as Z9,cL as K9,dd as X9,al as J9,bJ as eA,bw as th,bv as tA,c8 as u2,cd as rA,c9 as lu,ce as nA,a3 as sA,ab as iA,s as aA}from"./app-CYOLJycb.js";import{b,R as k,r as Ii,a as oA}from"./dnd-BCFAPC0L.js";import{b as lA,c as cA,F as Gc,S as uA,e as dA,h as hA,r as fA,y as pA,d as mA,u as gA}from"./gestureArbiter-XalN4TaN.js";import{L as xA,l as bA}from"./terminal-C7X98Amf.js";import{T as Q1,L as Ou,C as Fu,M as yA,G as vA}from"./triangle-alert-DECoBoOV.js";import{r as wA}from"./react-XDCjal2T.js";import{u as P1,G as AA}from"./referenceLongPress-BjyTtoDY.js";const TA=[["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"}]],Ly=Ut("archive",TA);const SA=[["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"}]],CA=Ut("arrow-down-a-z",SA);const _A=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],kA=Ut("arrow-down",_A);const LA=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Iy=Ut("arrow-up",LA);const IA=[["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"}]],Ey=Ut("bell",IA);const EA=[["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"}]],E0=Ut("bot",EA);const NA=[["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"}]],RA=Ut("box",NA);const MA=[["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"}]],jA=Ut("cable",MA);const DA=[["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"}]],BA=Ut("calendar-clock",DA);const QA=[["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"}]],PA=Ut("camera",QA);const OA=[["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"}]],FA=Ut("chart-bar",OA);const $A=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],UA=Ut("circle-dot",$A);const zA=[["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"}]],af=Ut("circle-question-mark",zA);const HA=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],$u=Ut("circle",HA);const WA=[["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"}]],GA=Ut("clipboard-paste",WA);const VA=[["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"}]],Ny=Ut("clipboard",VA);const qA=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6h4",key:"135r8i"}]],h0=Ut("clock-3",qA);const YA=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],ZA=Ut("clock",YA);const KA=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],XA=Ut("code",KA);const JA=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 3v18",key:"108xh3"}]],Il=Ut("columns-2",JA);const eT=[["path",{d:"M20 4v7a4 4 0 0 1-4 4H4",key:"6o5b7l"}],["path",{d:"m9 10-5 5 5 5",key:"1kshq7"}]],tT=Ut("corner-down-left",eT);const rT=[["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"}]],f0=Ut("download",rT);const nT=[["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",nT);const sT=[["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"}]],iT=Ut("file-code",sT);const aT=[["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"}]],oT=Ut("file-up",aT);const lT=[["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"}]],Ry=Ut("file",lT);const cT=[["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"}]],Ru=Ut("folder-open",cT);const uT=[["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"}]],O1=Ut("folder-search",uT);const dT=[["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"}]],hT=Ut("folder-tree",dT);const fT=[["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"}]],d2=Ut("grid-2x2",fT);const pT=[["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"}]],Ff=Ut("grip-vertical",pT);const mT=[["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"}]],gT=Ut("hash",mT);const xT=[["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",xT);const bT=[["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"}]],yT=Ut("house",bT);const vT=[["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"}]],My=Ut("keyboard",vT);const wT=[["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"}]],jy=Ut("layers",wT);const AT=[["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"}]],TT=Ut("layout-dashboard",AT);const ST=[["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"}]],Uu=Ut("layout-grid",ST);const CT=[["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"}]],_T=Ut("maximize",CT);const kT=[["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"}]],N0=Ut("message-circle",kT);const LT=[["path",{d:"M5 12h14",key:"1ays0h"}]],Dy=Ut("minus",LT);const IT=[["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"}]],ET=Ut("minimize",IT);const NT=[["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"}]],RT=Ut("monitor-smartphone",NT);const MT=[["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"}]],jT=Ut("moon",MT);const DT=[["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"}]],BT=Ut("move",DT);const QT=[["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"}]],PT=Ut("network",QT);const OT=[["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"}]],FT=Ut("panel-right-close",OT);const $T=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],UT=Ut("panel-left",$T);const zT=[["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"}]],HT=Ut("panel-right-open",zT);const WT=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],By=Ut("panel-right",WT);const GT=[["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"}]],VT=Ut("paperclip",GT);const qT=[["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"}]],YT=Ut("pause",qT);const ZT=[["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"}]],KT=Ut("pen-line",ZT);const XT=[["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"}]],JT=Ut("pencil-line",XT);const eS=[["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"}]],p0=Ut("pin",eS);const tS=[["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"}]],m0=Ut("pin-off",tS);const rS=[["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"}]],of=Ut("play",rS);const nS=[["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"}]],sS=Ut("plug",nS);const iS=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],aS=Ut("power",iS);const oS=[["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"}]],gn=Ut("refresh-cw",oS);const lS=[["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"}]],Qy=Ut("rotate-ccw",lS);const cS=[["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"}]],uS=Ut("rotate-cw",cS);const dS=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 12h18",key:"1i2n21"}]],h2=Ut("rows-2",dS);const hS=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Ml=Ut("search",hS);const fS=[["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"}]],r0=Ut("send",fS);const pS=[["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"}]],mS=Ut("settings",pS);const gS=[["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"}]],xS=Ut("shield-alert",gS);const bS=[["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"}]],yS=Ut("shield-check",bS);const vS=[["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"}]],$m=Ut("sliders-horizontal",vS);const wS=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],Py=Ut("square",wS);const AS=[["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"}]],TS=Ut("stethoscope",AS);const SS=[["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"}]],CS=Ut("sun",SS);const _S=[["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"}]],zs=Ut("trash-2",_S);const kS=[["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"}]],LS=Ut("type",kS);const IS=[["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"}]],ES=Ut("unlink",IS);const NS=[["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"}]],Oy=Ut("unplug",NS);const RS=[["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"}]],Fy=Ut("video",RS);const MS=[["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"}]],jS=Ut("volume-1",MS);const DS=[["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"}]],BS=Ut("volume-2",DS);const QS=[["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"}]],PS=Ut("wand-sparkles",QS);const OS=[["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"}]],rh=Ut("workflow",OS);function FS(e,t){return e==="webgl"&&t}function $y(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?Yu(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 $S(e){return e&&e.trim().length>0?e:""}function Uy(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 zy(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 lf(e,t,r,n,a=[],c=[]){const l=new Map(e.map(S=>[S.id,S])),d=zy(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 W of x)W.sessionIds.every(F=>L.has(F))&&W.sessionIds.forEach(F=>E.set(F,W.sessionIds));const R=new Set,B=S.sessionIds.flatMap(W=>{if(R.has(W))return[];const F=E.get(W)??[W];return F.forEach(U=>R.add(U)),F});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=$y(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 US(e){return e.isActive&&e.viewportFocused&&e.documentVisible&&e.windowFocused&&e.streamReady}function zS(e){return e.isActive&&e.documentVisible&&e.streamReady&&(!e.isDesktop||e.windowFocused)}function HS(e){return e.isActive&&!e.isMobile&&e.documentVisible&&!e.activeElementIsEditable}function WS(e,t){return!e&&t}const cf=".termdock/architecture.json",Hy=".termdock/architectures",GS={kind:"project",target:"",paths:[],depth:"boundary",focus:""},VS=["description","diagram","context","constraint","concern","todo","note"],qS=/^[a-zA-Z][a-zA-Z0-9_-]{0,79}$/;class YS extends Error{}function ds(){throw new YS("Invalid architecture document")}function Cl(e){return(!e||typeof e!="object"||Array.isArray(e))&&ds(),e}function ii(e,t=8e3){return(typeof e!="string"||e.length>t)&&ds(),e}function Cc(e){const t=ii(e,80);return qS.test(t)||ds(),t}function tc(e,t){return(!Array.isArray(e)||e.length>t)&&ds(),e}function f2(e){return Object.fromEntries(VS.filter(t=>e[t]!==void 0).map(t=>[t,ii(e[t],1e5)]))}function cu(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]=ii(t[n],n==="previousDiagram"?1e5:200));return t.updateCount!==void 0&&((!Number.isSafeInteger(t.updateCount)||t.updateCount<0)&&ds(),r.updateCount=t.updateCount),r}function Oh(e){return!!e&&!/[:\\\x00-\x1f]/.test(e)&&!e.startsWith("/")&&e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function F1(e){(!["project","module","feature"].includes(e.kind)||!["boundary","dependencies"].includes(e.depth))&&ds();const t=e.kind==="project"?[]:[...new Set(tc(e.paths,20).map(a=>ii(a,1024).trim()))].sort();t.some(a=>!Oh(a))&&ds();const r=ii(e.target,1e3).trim(),n=ii(e.focus,2e3).trim();return(e.kind==="module"&&!t.length||e.kind==="feature"&&!r)&&ds(),{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-DrQ47oZA.js","assets/app-BCTEfclM.js","assets/react-XDCjal2T.js","assets/dnd-BCFAPC0L.js","assets/terminal-C7X98Amf.js","assets/index-BObjbh2R.css","assets/CollaborationTaskContent-DSkxOlKQ.js","assets/RightSidebar-DaRdlJzn.js","assets/gestureArbiter-Xl7awIrX.js","assets/gestureArbiter-C2J0D0kV.css","assets/DiffReview-CBf8-Tli.js","assets/sparkles-DFYGpezN.js","assets/DiffViewer-DZfgjOBh.js","assets/referenceLongPress-YuGU-PYw.js","assets/DiffViewer-T3uj2-aP.css","assets/triangle-alert-BwJ6Q_Y0.js","assets/ChangeWalkthroughPanel-DHp5r1k9.js","assets/RightSidebar-DW-JEgm2.css","assets/CollaborationMainWorkspace-P_jXjsT-.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{ag as Ut,aN as Yu,by as s,ac as hc,da as zr,H as q8,dk as sl,d6 as ka,d8 as es,b1 as fc,a7 as J0,az as py,bp as M1,cN as Y8,d7 as L0,cy as u0,b6 as xo,j as d0,af as Qu,co as vp,cV as Z8,as as Dc,bx as Tu,g as K8,cI as Qh,Z as X8,bb as Bm,bI as Qm,cE as J8,ax as ew,ch as tw,a5 as my,cf as rw,cC as gy,aa as nw,ah as sw,L as Cn,C as hi,X as Rn,f as iw,d as ul,bg as aw,b0 as Pm,dc as ow,dh as Yr,bG as j1,dg as Gt,aD as lw,dq as cw,v as uw,bN as dw,c0 as hw,a4 as _a,bR as fw,cA as Jg,cB as e2,cD as t2,W as r2,b$ as pw,cO as mw,t as Jd,bo as D1,d5 as gw,_ as Oc,b9 as xw,i as bw,dj as xy,a_ as il,T as Fo,db as I0,df as yw,ci as vw,an as ww,aY as Aw,bZ as Tw,b_ as Sw,P as by,V as n2,bO as s2,bA as yy,n as Us,$ as Ph,cW as wp,bH as Cw,ck as _w,bF as vy,de as kw,bf as Bo,dm as Lw,B as cc,e as fi,u as Iw,ak as Ew,N as Om,cv as Nw,h as $o,bt as Rw,bu as Mw,ap as wy,aB as Ay,a6 as ku,m as e0,cs as ac,c2 as Ty,aw as t0,c as Fm,d9 as Sy,aJ as jw,S as nf,bm as sf,a as Cy,ar as Dw,ae as Bw,d3 as Qw,c3 as Pu,a8 as uc,bE as i2,cz as Pw,c7 as Ow,cS as Fw,cU as _y,bB as $w,bD as B1,cG as Uw,cH as zw,c4 as Hw,cF as Ww,cp as Gw,cm as Vw,cj as qw,c6 as Yw,cw as Zw,bQ as Kw,bP as ky,cr as Xw,bC as a2,aH as Jw,a$ as e9,D as t9,aG as o2,bK as r9,q as n9,p as s9,bM as i9,F as a9,c5 as o9,l as l9,cx as c9,r as u9,c1 as d9,au as h9,aA as f9,aC as p9,ba as ud,bk as m9,d0 as g9,bl as x9,ao as b9,d2 as y9,Q as v9,aj as w9,ad as A9,A as T9,b8 as S9,aq as C9,M as _9,di as k9,bT as Tc,b5 as L9,b2 as I9,b3 as E9,b4 as N9,aW as Ap,bU as R9,cb as M9,cl as j9,b7 as D9,aZ as B9,cT as l2,am as Q9,a9 as P9,Y as O9,c_ as F9,dn as On,cu as Sc,bS as $9,w as U9,cQ as z9,aV as H9,bc as c2,ca as W9,cM as eh,cZ as dd,d1 as G9,cc as V9,cR as q9,cJ as Y9,cY as Tp,cK as Z9,cL as K9,dd as X9,al as J9,bJ as eA,bw as th,bv as tA,c8 as u2,cd as rA,c9 as lu,ce as nA,a3 as sA,ab as iA,s as aA}from"./app-BCTEfclM.js";import{b,R as k,r as Ii,a as oA}from"./dnd-BCFAPC0L.js";import{b as lA,c as cA,F as Gc,S as uA,e as dA,h as hA,r as fA,y as pA,d as mA,u as gA}from"./gestureArbiter-Xl7awIrX.js";import{L as xA,l as bA}from"./terminal-C7X98Amf.js";import{T as Q1,L as Ou,C as Fu,M as yA,G as vA}from"./triangle-alert-BwJ6Q_Y0.js";import{r as wA}from"./react-XDCjal2T.js";import{u as P1,G as AA}from"./referenceLongPress-YuGU-PYw.js";const TA=[["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"}]],Ly=Ut("archive",TA);const SA=[["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"}]],CA=Ut("arrow-down-a-z",SA);const _A=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],kA=Ut("arrow-down",_A);const LA=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Iy=Ut("arrow-up",LA);const IA=[["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"}]],Ey=Ut("bell",IA);const EA=[["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"}]],E0=Ut("bot",EA);const NA=[["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"}]],RA=Ut("box",NA);const MA=[["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"}]],jA=Ut("cable",MA);const DA=[["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"}]],BA=Ut("calendar-clock",DA);const QA=[["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"}]],PA=Ut("camera",QA);const OA=[["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"}]],FA=Ut("chart-bar",OA);const $A=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],UA=Ut("circle-dot",$A);const zA=[["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"}]],af=Ut("circle-question-mark",zA);const HA=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],$u=Ut("circle",HA);const WA=[["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"}]],GA=Ut("clipboard-paste",WA);const VA=[["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"}]],Ny=Ut("clipboard",VA);const qA=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6h4",key:"135r8i"}]],h0=Ut("clock-3",qA);const YA=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],ZA=Ut("clock",YA);const KA=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],XA=Ut("code",KA);const JA=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 3v18",key:"108xh3"}]],Il=Ut("columns-2",JA);const eT=[["path",{d:"M20 4v7a4 4 0 0 1-4 4H4",key:"6o5b7l"}],["path",{d:"m9 10-5 5 5 5",key:"1kshq7"}]],tT=Ut("corner-down-left",eT);const rT=[["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"}]],f0=Ut("download",rT);const nT=[["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",nT);const sT=[["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"}]],iT=Ut("file-code",sT);const aT=[["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"}]],oT=Ut("file-up",aT);const lT=[["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"}]],Ry=Ut("file",lT);const cT=[["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"}]],Ru=Ut("folder-open",cT);const uT=[["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"}]],O1=Ut("folder-search",uT);const dT=[["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"}]],hT=Ut("folder-tree",dT);const fT=[["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"}]],d2=Ut("grid-2x2",fT);const pT=[["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"}]],Ff=Ut("grip-vertical",pT);const mT=[["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"}]],gT=Ut("hash",mT);const xT=[["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",xT);const bT=[["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"}]],yT=Ut("house",bT);const vT=[["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"}]],My=Ut("keyboard",vT);const wT=[["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"}]],jy=Ut("layers",wT);const AT=[["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"}]],TT=Ut("layout-dashboard",AT);const ST=[["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"}]],Uu=Ut("layout-grid",ST);const CT=[["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"}]],_T=Ut("maximize",CT);const kT=[["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"}]],N0=Ut("message-circle",kT);const LT=[["path",{d:"M5 12h14",key:"1ays0h"}]],Dy=Ut("minus",LT);const IT=[["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"}]],ET=Ut("minimize",IT);const NT=[["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"}]],RT=Ut("monitor-smartphone",NT);const MT=[["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"}]],jT=Ut("moon",MT);const DT=[["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"}]],BT=Ut("move",DT);const QT=[["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"}]],PT=Ut("network",QT);const OT=[["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"}]],FT=Ut("panel-right-close",OT);const $T=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],UT=Ut("panel-left",$T);const zT=[["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"}]],HT=Ut("panel-right-open",zT);const WT=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],By=Ut("panel-right",WT);const GT=[["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"}]],VT=Ut("paperclip",GT);const qT=[["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"}]],YT=Ut("pause",qT);const ZT=[["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"}]],KT=Ut("pen-line",ZT);const XT=[["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"}]],JT=Ut("pencil-line",XT);const eS=[["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"}]],p0=Ut("pin",eS);const tS=[["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"}]],m0=Ut("pin-off",tS);const rS=[["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"}]],of=Ut("play",rS);const nS=[["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"}]],sS=Ut("plug",nS);const iS=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],aS=Ut("power",iS);const oS=[["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"}]],gn=Ut("refresh-cw",oS);const lS=[["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"}]],Qy=Ut("rotate-ccw",lS);const cS=[["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"}]],uS=Ut("rotate-cw",cS);const dS=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 12h18",key:"1i2n21"}]],h2=Ut("rows-2",dS);const hS=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Ml=Ut("search",hS);const fS=[["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"}]],r0=Ut("send",fS);const pS=[["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"}]],mS=Ut("settings",pS);const gS=[["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"}]],xS=Ut("shield-alert",gS);const bS=[["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"}]],yS=Ut("shield-check",bS);const vS=[["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"}]],$m=Ut("sliders-horizontal",vS);const wS=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],Py=Ut("square",wS);const AS=[["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"}]],TS=Ut("stethoscope",AS);const SS=[["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"}]],CS=Ut("sun",SS);const _S=[["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"}]],zs=Ut("trash-2",_S);const kS=[["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"}]],LS=Ut("type",kS);const IS=[["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"}]],ES=Ut("unlink",IS);const NS=[["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"}]],Oy=Ut("unplug",NS);const RS=[["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"}]],Fy=Ut("video",RS);const MS=[["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"}]],jS=Ut("volume-1",MS);const DS=[["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"}]],BS=Ut("volume-2",DS);const QS=[["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"}]],PS=Ut("wand-sparkles",QS);const OS=[["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"}]],rh=Ut("workflow",OS);function FS(e,t){return e==="webgl"&&t}function $y(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?Yu(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 $S(e){return e&&e.trim().length>0?e:""}function Uy(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 zy(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 lf(e,t,r,n,a=[],c=[]){const l=new Map(e.map(S=>[S.id,S])),d=zy(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 W of x)W.sessionIds.every(F=>L.has(F))&&W.sessionIds.forEach(F=>E.set(F,W.sessionIds));const R=new Set,B=S.sessionIds.flatMap(W=>{if(R.has(W))return[];const F=E.get(W)??[W];return F.forEach(U=>R.add(U)),F});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=$y(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 US(e){return e.isActive&&e.viewportFocused&&e.documentVisible&&e.windowFocused&&e.streamReady}function zS(e){return e.isActive&&e.documentVisible&&e.streamReady&&(!e.isDesktop||e.windowFocused)}function HS(e){return e.isActive&&!e.isMobile&&e.documentVisible&&!e.activeElementIsEditable}function WS(e,t){return!e&&t}const cf=".termdock/architecture.json",Hy=".termdock/architectures",GS={kind:"project",target:"",paths:[],depth:"boundary",focus:""},VS=["description","diagram","context","constraint","concern","todo","note"],qS=/^[a-zA-Z][a-zA-Z0-9_-]{0,79}$/;class YS extends Error{}function ds(){throw new YS("Invalid architecture document")}function Cl(e){return(!e||typeof e!="object"||Array.isArray(e))&&ds(),e}function ii(e,t=8e3){return(typeof e!="string"||e.length>t)&&ds(),e}function Cc(e){const t=ii(e,80);return qS.test(t)||ds(),t}function tc(e,t){return(!Array.isArray(e)||e.length>t)&&ds(),e}function f2(e){return Object.fromEntries(VS.filter(t=>e[t]!==void 0).map(t=>[t,ii(e[t],1e5)]))}function cu(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]=ii(t[n],n==="previousDiagram"?1e5:200));return t.updateCount!==void 0&&((!Number.isSafeInteger(t.updateCount)||t.updateCount<0)&&ds(),r.updateCount=t.updateCount),r}function Oh(e){return!!e&&!/[:\\\x00-\x1f]/.test(e)&&!e.startsWith("/")&&e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function F1(e){(!["project","module","feature"].includes(e.kind)||!["boundary","dependencies"].includes(e.depth))&&ds();const t=e.kind==="project"?[]:[...new Set(tc(e.paths,20).map(a=>ii(a,1024).trim()))].sort();t.some(a=>!Oh(a))&&ds();const r=ii(e.target,1e3).trim(),n=ii(e.focus,2e3).trim();return(e.kind==="module"&&!t.length||e.kind==="feature"&&!r)&&ds(),{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 ZS(e){const t=F1(e);if(t.kind==="project")return cf;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`${Hy}/${t.kind}-${a}-${(n>>>0).toString(16).padStart(8,"0")}.json`}function Wy(e){return e===".omm"||e===cf||new RegExp(`^${Hy.replace(".","\\.")}/(?:module|feature)-[\\p{L}\\p{N}_-]{1,48}-[a-f0-9]{8}\\.json$`,"u").test(e)}function G$(e){return e.split("/").pop()?.replace(/^(module|feature)-/,"").replace(/-[a-f0-9]{8}\.json$/,"").replace(/-/g," ")??e}function V$(e){new TextEncoder().encode(e).byteLength>5e6&&ds();let t;try{t=JSON.parse(e)}catch{ds()}const r=Cl(t);r.version!==1&&ds();const n=ii(r.generatedAt,80);Number.isFinite(Date.parse(n))||ds();const a=tc(r.perspectives,12).map(d=>{const p=Cl(d),m=tc(p.nodes,200).map(w=>{const v=Cl(w),S=tc(v.files,40).map(E=>{const R=Cl(E),B=ii(R.path,1024);return Oh(B)||ds(),R.line!==void 0&&(!Number.isSafeInteger(R.line)||R.line<1)&&ds(),{path:B,...R.line!==void 0?{line:R.line}:{}}}),L=v.references===void 0?void 0:tc(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&&!Oh(ii(v.documentPath,1024))&&ds(),v.role!==void 0&&!["external","concern","entry","store"].includes(v.role)&&ds(),{id:Cc(v.id),title:ii(v.title,160),summary:ii(v.summary),files:S,...f2(v),...v.parentId!==void 0?{parentId:Cc(v.parentId)}:{},...v.documentPath!==void 0?{documentPath:ii(v.documentPath,1024)}:{},...cu(v.meta)?{meta:cu(v.meta)}:{},...L?{references:L}:{},...v.role!==void 0?{role:v.role}:{}}});m.length||ds();const x=new Map(m.map(w=>[w.id,w]));x.size!==m.length&&ds();for(const w of m){const v=new Set([w.id]);let S=w.parentId;for(;S;)(v.has(S)||!x.has(S))&&ds(),v.add(S),S=x.get(S)?.parentId}const y=tc(p.edges,600).map(w=>{const v=Cl(w),S=Cc(v.from),L=Cc(v.to);return(!x.has(S)||!x.has(L))&&ds(),{from:S,to:L,label:ii(v.label,200)}});return{id:Cc(p.id),title:ii(p.title,160),summary:ii(p.summary),nodes:m,edges:y,...f2(p),...cu(p.meta)?{meta:cu(p.meta)}:{}}});(!a.length||new Set(a.map(d=>d.id)).size!==a.length)&&ds();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))&&ds()}const c=r.analysis===void 0?void 0:F1(Cl(r.analysis));let l;if(r.details!==void 0){const d=Cl(r.details),p=tc(d.analyzedPaths,200).map(x=>{const y=ii(x,1024);return Oh(y)||ds(),y}),m=tc(d.limitations,30).map(x=>ii(x,2e3));l={analyzedPaths:p,limitations:m}}return r.origin!==void 0&&!["termdock","omm"].includes(r.origin)&&ds(),{version:1,generatedAt:n,summary:ii(r.summary),perspectives:a,...c?{analysis:c}:{},...l?{details:l}:{},...r.origin?{origin:r.origin}:{},...cu(r.meta)?{meta:cu(r.meta)}:{}}}function Gy(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 Sp(e){return e.slice(0,100).replace(/[&<>"\[\]{}|`#;\\\r\n]/g," ").trim()||"…"}function q$(e,t,r=0){const n=Gy(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}["${Sp(S.title)}"]`),m(S.id,v+1),d.push("end")):d.push(`${L}["${Sp(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(W=>W.id===R);for(;B?.parentId;){if(B.parentId===E)return!0;B=e.nodes.find(W=>W.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)} -->|"${Sp(w.label)}"| ${l.get(w.to)}`).join(`
|
|
4
4
|
`)}}function Y$(e,t,r=GS,n){const a=F1(r),c=n??ZS(a);if(c===".omm")return KS(e,t);(!Wy(c)||a.kind!=="project"&&c===cf||a.kind==="project"&&c!==cf)&&ds();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 jx="||",mE=120;function gE(e){return e.includes(jx)?e.split(jx).filter(t=>t.length>0):[e]}function Eu(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=>V3(p)).filter(p=>!!p):[],includeAlt:typeof a.includeAlt=="boolean"?!!a.includeAlt:!1,rowLayout:X1(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=b0()[0];return n&&!r.some(a=>a.id==="default")&&r.unshift(n),r}function xE(e,t){const r=G3(e);if(!r)return"default";for(const n of t)if(n.id!=="default")for(const a of n.programs){const c=bf(a);if(c){if(c.test(r))return n.id}else if(r.includes(a))return n.id}return"default"}function Dx(e,t){return e.find(r=>r.id===t)??e.find(r=>r.id==="default")??b0()[0]}function bE(e){return[{id:"auto",label:"Auto"},...e.map(t=>({id:t.id,label:t.label}))]}function yE(e){return[{id:"auto",label:"Auto"},...e.filter(t=>t.id==="default"||t.showOnDesktop===!0).map(t=>({id:t.id,label:t.label}))]}function q3(e,t){const r=X1(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 Y3=28,Z3=({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(PS,{size:14}):(t.charAt(0)||"?").toUpperCase()}),vE={esc:"\x1B",enter:"\r",home:"\x1B[H",end:"\x1B[F","ctrl-c":"","ctrl-d":"","ctrl-w":"","ctrl-u":""},Id=8;function wE(e,t){return vE[e]??null}const AE=({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:W="idle",fileUploadProgress:F=0,longPressMode:U="arrows",copyFeedback:V="idle",onLongPressModeToggle:Z,onModifierToggle:ce,onPresetSelect:xe,onExpandedChange:pe})=>{const{t:te}=zr(),[ke,$e]=k.useState(l),[Y,Ae]=k.useState(!1),lt=k.useRef(null),Se=r==="desktop-actions",ye=Se||ke,[_e,je]=k.useState(!1),[re,Oe]=k.useState(null),Ce=c||!e||!t,Ee=c||!e,Be=k.useRef(null),Ne=k.useRef(null),le=k.useRef(null),He=k.useRef(null),rt=k.useRef(null),mt=k.useRef(V),ue=k.useRef(null),Ye=k.useRef(0),st=k.useRef(null),Ie=k.useRef(!1),We=k.useCallback(et=>{if(Ce)return;const Ct=et.target;if(!(Ct instanceof Element))return;const Nt=Ct.closest("button"),gt=Nt?.hasAttribute("data-mobile-native-action")===!0;Nt&&!gt?(et.preventDefault(),po(Id)):Nt&&po(Id)},[Ce]),Te=k.useCallback(et=>{et.preventDefault()},[]),H=k.useCallback(et=>{const Ct=et.target;Ce||Ct instanceof HTMLElement&&Ct.closest("button")&&Ct.blur()},[Ce]);k.useEffect(()=>{$e(l)},[l]),k.useEffect(()=>{Se||pe?.(ke)},[Se,pe,ke]),k.useEffect(()=>{Ce&&(ue.current!==null&&(window.clearTimeout(ue.current.timer),ue.current=null),je(!1),Oe(null))},[Ce]),k.useEffect(()=>{e||(je(!1),Oe(null))},[e]),k.useEffect(()=>{if(!_e)return;const et=()=>{const Ct=Be.current?.getBoundingClientRect();Ct&&Oe({left:Math.max(8,Ct.left),top:Math.max(8,Ct.top-8)})};return et(),window.addEventListener("resize",et),window.addEventListener("scroll",et,!0),()=>{window.removeEventListener("resize",et),window.removeEventListener("scroll",et,!0)}},[_e]),k.useEffect(()=>{const et=mt.current;if(mt.current=V,V==="idle"||V===et)return;if(rt.current!==null&&window.clearTimeout(rt.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 Nt=[{opacity:0,transform:"scale(0.65)"},{opacity:.75,transform:"scale(0.9)",offset:.18},{opacity:0,transform:"scale(1.65)"}];le.current?.animate?.(Nt,{duration:760,easing:"ease-out"}),He.current?.animate?.(Nt,{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"});po(Id),V==="copied"&&(rt.current=window.setTimeout(()=>{po(Id),rt.current=null},90),U==="copy"&&Z?.())},[V,U,Z]),k.useEffect(()=>()=>{rt.current!==null&&window.clearTimeout(rt.current)},[]);const oe=k.useCallback((et,Ct)=>{Ce||(et.preventDefault(),S(Ct))},[S,Ce]),be=k.useCallback((et,Ct)=>{Ce||(et.preventDefault(),ce(Ct))},[ce,Ce]),Ze=k.useCallback(et=>{Ce||(et.preventDefault(),$e(Ct=>{const Nt=!Ct;return Nt&&(Ae(!0),lt.current!==null&&window.clearTimeout(lt.current),lt.current=window.setTimeout(()=>{Ae(!1),lt.current=null},350)),Nt}))},[Ce]),Je=k.useCallback(()=>{const et=typeof performance<"u"?performance.now():Date.now();et-Ye.current<350||(Ye.current=et,E?.())},[E]),St=k.useCallback(et=>{Ce||(et.stopPropagation(),et.pointerType!=="touch"&&(et.preventDefault(),Je()))},[Ce,Je]),Vt=k.useCallback(et=>{Ce||(et.preventDefault(),et.stopPropagation(),Je())},[Ce,Je]),jt=k.useCallback(et=>{Ce||W==="uploading"||!R||(et.preventDefault(),et.stopPropagation(),Ie.current||R(),Ie.current=!1)},[W,R,Ce]),vt=k.useCallback(()=>{st.current!==null&&window.clearTimeout(st.current),st.current=null},[]),Zt=k.useCallback(et=>{et.stopPropagation(),!(Ce||W==="uploading"||!B)&&(Ie.current=!1,st.current=window.setTimeout(()=>{st.current=null,Ie.current=!0,po(Id),B()},500))},[W,B,Ce]);k.useEffect(()=>()=>vt(),[vt]);const Pt=k.useCallback(et=>{Ce||et.stopPropagation()},[Ce]),Xt=250,zt=k.useCallback(()=>{ue.current!==null&&(window.clearTimeout(ue.current.timer),ue.current=null)},[]);k.useEffect(()=>()=>{zt(),lt.current!==null&&(window.clearTimeout(lt.current),lt.current=null)},[zt]);const Lt=k.useCallback((et,Ct)=>{if(Ce)return;if(et.preventDefault(),!Ct.doubleTapSequence){L(Ct.sequence);return}const Nt=ue.current;if(Nt!==null&&Nt.actionId===Ct.id){window.clearTimeout(Nt.timer),ue.current=null,L(Ct.doubleTapSequence);return}zt();const gt=window.setTimeout(()=>{ue.current=null,L(Ct.sequence)},Xt);ue.current={actionId:Ct.id,timer:gt}},[zt,L,Ce]),me=k.useCallback(et=>{Ce||(et.preventDefault(),et.stopPropagation(),Z?.())},[Z,Ce]),Ge=k.useCallback(et=>{Ce||et.stopPropagation()},[Ce]),pt=k.useCallback(et=>{if(Ce)return;et.preventDefault();const Ct=et.currentTarget.getBoundingClientRect();Oe({left:Math.max(8,Ct.left),top:Math.max(8,Ct.top-8)}),je(Nt=>!Nt)},[Ce]),q=k.useCallback((et,Ct)=>{Ce||(et.preventDefault(),je(!1),Oe(null),xe(Ct))},[xe,Ce]),at=v.length>0,qt=k.useMemo(()=>{const et=[{id:"preset",kind:"preset"}];if(!Se&&y&&et.push({id:"alt",kind:"alt"}),at){const Ct=v.map(Nt=>({id:Nt.id,kind:"text",action:Nt}));return et.concat(Ct)}return Se?et.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"}]):et.concat([{id:"home",kind:"key",keyName:"home"},{id:"end",kind:"key",keyName:"end"},{id:"ctrl-d",kind:"key",keyName:"ctrl-d"}])},[v,at,y,Se]),Ve=k.useMemo(()=>q3(qt,Se&&!at?[6]:w),[qt,at,Se,w]),De=`${Se?"space-y-1":"mt-1 space-y-1"}${Y?" pointer-events-none":""}`,er=_e&&re?Ii.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:re.left,top:re.top},children:s.jsx("div",{className:"grid gap-1",children:x.map(et=>s.jsx("button",{type:"button",onPointerDown:Ct=>q(Ct,et.id),tabIndex:-1,disabled:Ee,className:`h-7 rounded-full px-3 text-left text-xs font-medium transition-colors disabled:opacity-50 ${et.id===m?"bg-primary text-primary-foreground":"bg-surface-2 hover:bg-surface-elevated text-muted-foreground hover:text-foreground"}`,children:et.label},et.id))})}),document.body):null;return s.jsxs(s.Fragment,{children:[er,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?Se?"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:We,onPointerDownCapture:We,onContextMenuCapture:Te,onFocusCapture:H,children:s.jsxs("div",{className:"rounded-2xl bg-surface-elevated p-0.5 space-y-0.5",children:[!Se&&s.jsxs("div",{"data-mobile-keyboard-primary-row":"true",className:"grid grid-cols-10 gap-1",children:[s.jsx("button",{type:"button",onPointerDown:et=>oe(et,"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:et=>be(et,"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:et=>oe(et,"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:et=>oe(et,"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:vt,onPointerCancel:vt,onClick:jt,tabIndex:-1,disabled:Ee||!R||W==="uploading",title:W==="uploading"?`${te("rightSidebar.uploading")} ${Math.round(F)}%`:te(W==="inserted"?"rightSidebar.inserted":W==="failed"?"rightSidebar.uploadFailed":"rightSidebar.insertLocalFile"),"aria-label":te("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 ${W==="inserted"?"bg-primary/15 text-primary":W==="failed"?"bg-destructive/15 text-destructive":"bg-surface-2"}`,children:[W==="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,F))}%`}}),s.jsx("span",{className:"relative z-10 flex items-center justify-center",children:W==="uploading"?s.jsx(Cn,{size:15,className:"animate-spin"}):W==="inserted"?s.jsx(hi,{size:15}):W==="failed"?s.jsx(Rn,{size:15}):s.jsx(oT,{size:15})}),W!=="idle"&&s.jsx("span",{className:"sr-only",role:"status","aria-live":"polite",children:W==="uploading"?`${te("rightSidebar.uploading")} ${Math.round(F)}%`:te(W==="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:et=>oe(et,"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(tT,{size:16})}),s.jsxs("button",{ref:Ne,type:"button","data-mobile-copy-button":"true","data-mobile-native-action":"true",onPointerDown:Ge,onTouchStart:Ge,onClick:me,tabIndex:-1,disabled:Ee,title:te(V==="copied"?"terminal.copied":V==="failed"?"terminal.copyFailed":U==="copy"?"terminal.longPressSelectsText":"terminal.longPressSendsArrows"),"aria-label":te(U==="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":U==="copy"?"bg-primary/15 text-primary":"bg-surface-2"}`,children:[s.jsx("span",{ref:le,"aria-hidden":"true",className:"pointer-events-none absolute inset-0 z-0 rounded-full border border-primary/70 opacity-0"}),s.jsx("span",{ref:He,"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(hi,{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(Rn,{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(Ny,{size:15,className:`absolute inset-0 transition-[opacity,transform] duration-300 ease-out motion-reduce:transition-none ${V==="idle"&&U==="copy"?"scale-100 opacity-100":"scale-50 opacity-0"}`}),s.jsx(BT,{size:15,className:`absolute inset-0 transition-[opacity,transform] duration-300 ease-out motion-reduce:transition-none ${V==="idle"&&U==="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"?`${te("terminal.copied")} · ${te("terminal.longPressSendsArrows")}`:`${te("terminal.copyFailed")} · ${te("terminal.longPressSelectsText")}`})]}),s.jsx("button",{type:"button","data-mobile-copy-button":"true","data-mobile-native-action":"true",onPointerDown:St,onPointerUp:Pt,onTouchStart:Pt,onTouchEnd:Pt,onClick:Vt,tabIndex:-1,disabled:Ee,title:te("terminal.paste"),"aria-label":te("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(GA,{size:15})}),s.jsx("button",{type:"button",onPointerDown:Ze,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:ke?s.jsx(iw,{size:16}):s.jsx(ul,{size:16})})]}),ye&&s.jsx("div",{className:De,children:Ve.map((et,Ct)=>{const Nt=et.items[0]?.kind==="preset",gt=Math.max(2,et.columns),bt=Nt?`${Y3}px repeat(${Math.max(1,gt-1)}, minmax(0, 1fr))`:`repeat(${gt}, minmax(0, 1fr))`;return s.jsx("div",{className:"relative grid gap-1",style:{gridTemplateColumns:bt},children:et.items.map(It=>It.kind==="preset"?s.jsx(Z3,{buttonRef:It.id==="preset"?Be:void 0,mode:m,presetLabel:d,title:p,disabled:Ee,onPointerDown:pt},It.id):It.kind==="alt"?s.jsx("button",{type:"button",onPointerDown:yt=>be(yt,"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"})},It.id):It.kind==="text"?s.jsxs("button",{type:"button",onPointerDown:yt=>Lt(yt,It.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:[It.action.label,It.action.doubleTapSequence&&s.jsx("span",{className:"absolute top-0.5 right-1.5 h-1 w-1 rounded-full bg-accent/60"})]},It.id):s.jsx("button",{type:"button",onPointerDown:yt=>oe(yt,It.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:It.keyName==="esc"?"Esc":It.keyName==="ctrl-c"?"Ctrl-C":It.keyName==="ctrl-d"?"Ctrl-D":It.keyName==="home"?"Home":"End"},It.id))},`row-${Ct}`)})})]})})]})},TE=({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"})})]})},SE=/^Reconnecting/i,CE=({connectionError:e,isFatalError:t,isRestarting:r,isConnecting:n,onHardRestart:a})=>{const{t:c}=zr(),l=!!e&&SE.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(d0,{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},_E=120,kE=80,LE=400;function Bx(){if(typeof window>"u"||document.visibilityState!=="visible"||!aw())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 K3(e){const{enabled:t,openThresholdPx:r=_E,closeThresholdPx:n=kE,settleDelayMs:a=LE}=e,c=k.useMemo(()=>Qu("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=Bx();let Z=l.current;if(V>=r?Z=!0:V<=n&&(Z=!1),l.current=Z,Z){const ce=Math.abs(V-p.current);p.current=V,ce>10&&(d.current!==null&&clearTimeout(d.current),d.current=setTimeout(()=>{d.current=null,x(xe=>xe.isSettled?xe:{...xe,isSettled:!0})},a))}else d.current!==null&&(clearTimeout(d.current),d.current=null);x(ce=>{const xe=Z?ce.isSettled:!1;return ce.isOpen===Z&&ce.keyboardHeight===V&&ce.isSettled===xe?ce:(c("sync",{keyboardHeight:V,isOpen:Z,isSettled:xe,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:xe,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 W=V=>{c("resume",{source:V,keyboardHeight:Bx(),hidden:document.hidden}),v(`${V}:now`),window.setTimeout(()=>v(`${V}:50ms`),50),window.setTimeout(()=>v(`${V}:200ms`),200)},F=()=>{document.hidden||W("visibilitychange")},U=()=>W("pageshow");return document.addEventListener("visibilitychange",F),window.addEventListener("pageshow",U),()=>{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",F),window.removeEventListener("pageshow",U),y!==null&&window.cancelAnimationFrame(y),d.current!==null&&(clearTimeout(d.current),d.current=null)}},[c,t,r,n,a]),m}const Vh=300,IE=120,EE=2e3,NE=250,RE=6e4;function ME(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 Jp(e,t){return t?e.find(r=>r.id===t||r.backendSessionId===t)?.id??null:null}function bh(e){return e.prioritySessionId??e.activeSessionId??e.persistedActiveSessionId??e.firstSessionId}function jE(e){return e.foregroundSessionId===null||e.isVisible===!0||e.sessionId===e.foregroundSessionId||e.foregroundReady}function DE(e){return e.sessionId===e.foregroundSessionId||e.visibleSessionIds.has(e.sessionId)||e.deferredViewportSessionIds.has(e.sessionId)}function BE(e){return e.isMobile&&(!e.viewportReady||!e.streamReady||!e.contentReady)}function QE(e){return e.writtenChunkId!==null&&e.initialTargetChunkId!==null&&e.writtenChunkId>=e.initialTargetChunkId}function PE(e){return!e.initialConnectionPending}function OE(e){return!e}function FE(e){return e.requestToken===0||e.isVisible===!0||e.foregroundSessionId===null||e.isVisible===void 0&&e.sessionId===e.foregroundSessionId||e.foregroundCompletedToken===e.requestToken}function $E(e,t){return[...e].every(r=>t.has(r))}function UE(e,t){return e===null||t-e>=NE}function zE(e){return!1}function HE(e){return!e.isActive||e.isStreamReady||e.reconnectStartedAt===null?null:Math.max(0,RE-(e.now-e.reconnectStartedAt))}function WE(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,Vh+n*IE),n+=1}return r}const GE="Session not found on server",qh="Terminal session not found",VE="STALE_SESSION_RESTORE_REJECTED";function Qx(e){return o1(e)?!1:e?.message===GE||e?.status===404&&e.message===qh}function o1(e){return e?.code===VE}function qE(e,t){if(!e||e.startsWith("/"))return e;const r=e.replace(/^\.\//,"");return t?`${t.replace(/\/+$/,"")}/${r}`:r}function X3(e,t){return qE(e,t).replace(/ /g,"\\ ")}function l1(e,t){return`${X3(e,t)} `}function Px(e,t){return X3(e,t)}function EU(e,t,r){if(!r)return Px(e,t);const n=r.start===r.end?`${r.start}`:`${r.start}-${r.end}`;return`${Px(e,t)}:${n}`}const YE="/tmp";async function ZE(e,t,r){const a=(await t(YE,[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 yf(a)}if(!c)throw new yf(a);return a}class yf extends Error{constructor(t){super("File uploaded, but its reference was not accepted"),this.uploaded=t,this.name="UploadedReferenceRejectedError"}uploaded}function Ox(e,t,r,n,a){if(!e||!t||!r())return Promise.resolve(!1);const c=n?mC(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&&gC(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 J3=[640,960,1280,1600,2048,2560,3072,4096],ev=[240,360,480,540,720,1080,1440,2160],i0={min:.1,max:1,step:.01},a0={min:25e4,max:2e7,step:25e4},eg="termdock:mobile-media-compression-v1",bu={showResultToast:!0,imageEnabled:!1,imageMaxDimension:2048,imageQuality:.8,videoEnabled:!1,videoMaxHeight:720,videoBitrate:25e5};function tv(){try{const e=JSON.parse(localStorage.getItem(eg)||"null");return!e||typeof e!="object"?bu:{showResultToast:e.showResultToast!==!1,imageEnabled:e.imageEnabled===!0,imageMaxDimension:J3.includes(e.imageMaxDimension)?e.imageMaxDimension:bu.imageMaxDimension,imageQuality:typeof e.imageQuality=="number"&&e.imageQuality>=i0.min&&e.imageQuality<=i0.max?e.imageQuality:bu.imageQuality,videoEnabled:e.videoEnabled===!0,videoMaxHeight:ev.includes(e.videoMaxHeight)?e.videoMaxHeight:bu.videoMaxHeight,videoBitrate:typeof e.videoBitrate=="number"&&e.videoBitrate>=a0.min&&e.videoBitrate<=a0.max?e.videoBitrate:bu.videoBitrate}}catch{return bu}}const tg=hc((e,t)=>({preferences:tv(),saveFailed:!1,update:r=>{const n={...t().preferences,...r};let a=!1;try{localStorage.setItem(eg,JSON.stringify(n))}catch{a=!0}e({preferences:n,saveFailed:a})}}));typeof window<"u"&&window.addEventListener("storage",e=>{(e.key===eg||e.key===null)&&tg.setState({preferences:tv(),saveFailed:!1})});function yh(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 KE({result:e,message:t,onClose:r}){const{locale:n}=zr(),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(Rn,{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 XE({result:e,onDismiss:t}){const{locale:r}=zr(),n=r==="zh",a=tg(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?`已尝试压缩 · 保留原图 ${yh(p.uploadedSize)},已上传`:`Compression tried · original ${yh(p.uploadedSize)} uploaded`:`${v} · ${yh(p.originalSize)} → ${yh(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(hi,{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&&Ii.createPortal(s.jsx(KE,{result:l.result,message:l.message,onClose:()=>d(null)}),document.body)]})}const JE=320,Fx="termdock:mobile-keyboard-expanded",$x="termdock:mobile-keyboard-preset-mode",Ux="termdock:mobile-long-press-mode",eN=80;function tN(e){return/\.(?:jpe?g|png|heic|heif)$/i.test(e.name)||/^(?:image\/jpeg|image\/png|image\/heic|image\/heif)$/i.test(e.type)}function zx(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 rN(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 em(){return xy()}const nN={retry:{maxRetries:60,initialDelayMs:1e3,maxDelayMs:2e4},connectionTimeoutMs:15e3},sN=({sessionId:e,mode:t,tmuxSessionName:r=null,terminalSettings:n=K1(),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:W,onViewportReadyChange:F,onContentReadyChange:U,onKeyboardVisibilityChange:V,suppressKeyboard:Z=!1,keyboardPortalTarget:ce=null,sharedMobileKeyboardLayout:xe=!1,suppressPageFlipRefresh:pe=!1,showDebug:te,onStatusChange:ke})=>{const{t:$e}=zr(),[Y]=k.useState(e||Xy()),[Ae,lt]=k.useState(()=>(e?Pm(e):null)??n.fontSize),Se=k.useMemo(()=>oE(),[]),ye=k.useMemo(()=>Qu("session"),[]),_e=k.useMemo(()=>Qu("keyboard"),[]),je=k.useRef(null),re=k.useRef(null);k.useEffect(()=>{Pm(Y)===null&<(n.fontSize)},[n.fontSize,Y]);const Oe=k.useMemo(()=>({...n,fontSize:Ae}),[n,Ae]),Ce=ow(),Ee=d||Ce,[Be,Ne]=k.useState(em),[le,He]=k.useState(!1),[rt,mt]=k.useState(!1),[ue,Ye]=k.useState(!1),[st,Ie]=k.useState(()=>typeof document>"u"?!0:!document.hidden&&Tu()),[We,Te]=k.useState(()=>typeof document>"u"?!0:document.hasFocus()),[H,oe]=k.useState(!1),be=k.useRef(H);be.current=H;const[Ze,Je]=k.useState(!1),[St,Vt]=k.useState(!1),[jt,vt]=k.useState(!1),[Zt,Pt]=k.useState(!0),{isOpen:Xt,keyboardHeight:zt}=K3({enabled:Be&&l}),[Lt,me]=k.useState(null),[Ge,pt]=k.useState(null),[q,at]=k.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(Fx)==="true"),[qt,Ve]=k.useState(()=>{if(typeof window>"u")return"auto";const se=window.localStorage.getItem($x);return se&&se.length>0?se:"auto"}),[De,er]=k.useState(()=>typeof window>"u"?"arrows":window.localStorage.getItem(Ux)==="copy"?"copy":"arrows"),[et,Ct]=k.useState("idle"),[Nt,gt]=k.useState("idle"),[bt,It]=k.useState(0),[yt,pr]=k.useState(null),[nr,Cr]=k.useState(null),[cn,Lr]=k.useState(null),ge=k.useCallback(()=>Lr(null),[]),{preferences:Vr,update:it,saveFailed:dt}=tg(),{videoEnabled:sr,videoMaxHeight:xn,videoBitrate:an,imageEnabled:Me,imageMaxDimension:nt,imageQuality:wt}=Vr,[Rr,rn]=k.useState(!1),[Ir,ne]=k.useState(null),[ht,Ht]=k.useState(null),Ot=Yr(se=>se.sessions.get(Y)),{setTerminalSession:Tr,setConnecting:mr,appendToBuffer:Hr,replaceBuffer:_n,clearTerminalSession:dr,removeTerminalSession:bn,clearBuffer:hn,setSessionActiveProgram:Tn,setSessionCwd:ir,setSessionCopyMode:pn,setSessionAgentStatus:Pr,setSessionShellTitle:qr,setSessionPromptState:Wr,clearAgentNeedsReview:fs}=Yr.getState(),Br=k.useMemo(()=>`wt-${Y.replace(/[^a-zA-Z0-9_-]/g,"").slice(0,12)}`,[Y]),Mn=Ot?.terminalSessionId??null,Sr=Ot?.mode??"shell",Kr=Ot?.activeProgram??null,nn=k.useMemo(()=>Eu(c),[c]),Fr=Sr==="tmux",ks=Ot?.bufferChunks??[],Or=Ot?.isConnecting??!1,Xr=Mn,fn=k.useCallback(async(se,T)=>{const j=II(se,Ot?.cwd||Ot?.directory);if(!j)return;let Q=j,O="directory";try{Q=(await j1(j)).path}catch(fe){if(!(fe instanceof Error)||fe.message!=="Path is not a directory")return;O="file"}try{const fe=Gt.getState();fe.setRightTab("files"),fe.openRight(),window.dispatchEvent(new CustomEvent(TI,{detail:{path:Q,kind:O,line:T}}))}catch{}},[Ot?.cwd,Ot?.directory]),K=t??Ot?.mode??"shell",Ue=K==="tmux"?r??Ot?.tmuxSessionName??null:null,[Et,kt]=k.useState(null),tr=k.useRef(!1),[Qr,cr]=k.useState(!1),[Sn,Ls]=k.useState(!1),[Zn,sn]=k.useState(null),[on,_r]=k.useState(0),[$r,Wn]=k.useState(null),Gn=te!==void 0?te:!1,un=k.useRef(null),Kn=k.useRef(null),kr=k.useRef(null),Er=k.useRef(null),gr=k.useRef(null),rs=k.useRef(!1),$n=k.useRef(null),kn=k.useRef([]),Ln=k.useRef(0),ps=k.useRef(!1),G=k.useRef(null),Le=k.useRef(null),Ke=k.useRef(-1),ct=k.useRef(null),qe=k.useRef(0),At=k.useRef(null),Rt=k.useRef(null),Bt=k.useRef(0),ot=k.useRef(0),Ft=k.useRef(!1),hr=k.useRef(null),Kt=k.useRef(null),z=k.useRef(!1),N=k.useRef(0),$=k.useRef(!1),ee=k.useRef(!1),ie=k.useRef(!1),Qe=k.useRef(null),ze=k.useRef(null),xt=k.useRef(null),_t=k.useRef(l);_t.current=l;const Mr=k.useRef(Ee);Mr.current=Ee;const Dt=k.useRef(d);Dt.current=d;const Gr=k.useRef(Be),dn=k.useRef(null),jn=k.useRef(null),ns=k.useRef(null),Un=k.useRef(null),fr=k.useRef(null),Mt=k.useRef(null),Dn=k.useRef(null),Vn=k.useCallback(()=>{const se=++N.current,T=()=>{se===N.current&&Je(!0)};if(typeof window>"u"){T();return}window.requestAnimationFrame(()=>window.requestAnimationFrame(T))},[]),Ha=k.useCallback(se=>{if($.current){if(ze.current!==null&&(window.clearTimeout(ze.current),ze.current=null),se.x===0&&se.y>=se.rows-1){Pt(!1);return}ze.current=window.setTimeout(()=>{ze.current=null,Pt(!0)},eN)}},[]),Bn=k.useRef(null);k.useEffect(()=>()=>{Bn.current?.()},[]);const ss=k.useCallback(()=>{Bn.current||(Bn.current=$1(()=>{Bn.current=null;const se=Yr.getState(),T=kr.current,j=se.getTerminalSession(Y);if(!T||j?.mode!=="shell"||se.hasPendingBufferWrites(Y))return;const Q=lw(T),O=gr.current?.getDimensions();if(!Q||!O)return;const fe=gr.current?.serializeSnapshot();fe&&cw({id:T,version:1,...Q,...O,data:fe,savedAt:Date.now()})},2e3))},[Y]),$i=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)&&(uw(kr.current),ss()),!Ft.current||!QE({writtenChunkId:se,initialTargetChunkId:hr.current}))return;const Q=Kt.current;Kt.current=null,Q!==null&&gr.current?.notifyScreenSynchronized(Q),Ft.current=!1,hr.current=null,Vn()},[Vn,ss,Y]),ua=k.useCallback(se=>{if(!$.current)return;const T=Qe.current;T&&T.x===se.x&&T.y===se.y&&T.rows===se.rows||(Qe.current=se,ze.current!==null&&(window.clearTimeout(ze.current),ze.current=null),se.x===0&&se.y>=se.rows-1&&Pt(!1))},[]);k.useEffect(()=>{if(!p){ee.current=!1;return}ee.current||(ee.current=!0,ie.current=!1,$.current=!0,Qe.current=null,Pt(!1),ze.current!==null&&(window.clearTimeout(ze.current),ze.current=null),xt.current!==null&&window.clearTimeout(xt.current),xt.current=window.setTimeout(()=>{xt.current=null,ze.current!==null&&typeof window<"u"&&window.clearTimeout(ze.current),ze.current=null,$.current=!1,Pt(!0)},15e3))},[p]);const bs=k.useCallback(()=>{Un.current=null;const se=ns.current;ns.current=null,se&&qr(se.sessionId,se.title)},[qr]),Wa=k.useCallback((se,T)=>{if(ns.current={sessionId:se,title:T},Un.current===null){if(typeof window>"u"){bs();return}Un.current=window.requestAnimationFrame(bs)}},[bs]),wo=k.useCallback(()=>{Un.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(Un.current),Un.current=null,ns.current=null},[]),zn=k.useCallback(async()=>{const se=K;return(await dw({preferredFrontendSessionId:Y,mode:se,tmuxSessionName:se==="tmux"?Ue||Br:void 0,termType:"xterm-256color",requireExisting:!0})).terminalSession},[K,Ue,Br,Y]),da=k.useRef(l);k.useEffect(()=>{if(!l){gr.current?.blur(),da.current=!1;return}if(da.current)return;da.current=!0;const se=zL(Be,pe);if(se==="single"){gr.current?.requestRefresh("focus",{skipResizePush:!0,skipScrollToBottom:!0});return}se!=="none"&&gr.current?.requestRefresh("page-flip",{reconcileServerSize:!0,skipScrollToBottom:!0})},[l,Be,pe,Xr]),k.useEffect(()=>{Gr.current=Be},[Be]);const ms=k.useCallback(()=>{!_t.current||Mr.current||gr.current?.focus()},[]);k.useLayoutEffect(()=>{Ee&&gr.current?.blur()},[Ee]),k.useEffect(()=>{if(!l||Ee||Zt||ie.current)return;ie.current=!0;const se=window.requestAnimationFrame(()=>{gr.current?.requestPtyRedraw()});return()=>window.cancelAnimationFrame(se)},[Ee,l,Zt]);const La=k.useCallback(se=>{typeof window>"u"||typeof document>"u"||!_t.current||Mr.current||Gr.current||document.hidden||!Tu()||(dn.current!==null&&window.clearTimeout(dn.current),dn.current=window.setTimeout(()=>{if(dn.current=null,!_t.current||Mr.current||Gr.current||document.hidden||!Tu())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){_e("desktop resume focus skipped: editable active",{reason:se});return}_e("desktop resume focus",{reason:se}),gr.current?.requestRefresh("focus",{force:!0,forceRedraw:!0,skipResizePush:!0,skipScrollToBottom:!0}),gr.current?.focus()},50))},[_e]);k.useEffect(()=>()=>{dn.current!==null&&typeof window<"u"&&window.clearTimeout(dn.current),dn.current=null,jn.current!==null&&typeof window<"u"&&window.clearTimeout(jn.current),jn.current=null,fr.current!==null&&typeof window<"u"&&window.clearTimeout(fr.current),fr.current=null,Mt.current!==null&&typeof window<"u"&&window.clearTimeout(Mt.current),Mt.current=null,xt.current!==null&&typeof window<"u"&&window.clearTimeout(xt.current),xt.current=null,ze.current!==null&&typeof window<"u"&&window.clearTimeout(ze.current),ze.current=null},[]),k.useEffect(()=>{if(typeof document>"u"||typeof window>"u")return;const se=()=>{jn.current!==null&&window.clearTimeout(jn.current),jn.current=window.setTimeout(()=>{jn.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));HS({isActive:_t.current&&!Mr.current,isMobile:Gr.current,documentVisible:!document.hidden,activeElementIsEditable:Q})&&ms()},0)};return document.addEventListener("pointerup",se),()=>{document.removeEventListener("pointerup",se),jn.current!==null&&(window.clearTimeout(jn.current),jn.current=null)}},[ms]);const is=k.useCallback(()=>{Ui.current=!1,_r(se=>se+1)},[]),Ga=k.useCallback((se,T,j)=>{const Q=kr.current,O=Date.now();if(Q&&T&&hw(Q)){re.current={startedAt:O,strategy:"reconnect",reason:se},_a("info","PWA_RESUME terminal-start",{frontendSessionId:Y,backendSessionId:Q,strategy:"reconnect",reason:se,active:_t.current});return}if(Q&&fw(Q,()=>{const fe=re.current;_a("info","PWA_RESUME terminal-responsive",{frontendSessionId:Y,backendSessionId:Q,durationMs:fe?Date.now()-fe.startedAt:null,strategy:fe?.strategy??"probe",reason:fe?.reason??se}),re.current=null,W?.(Y)},{visible:j})){re.current={startedAt:O,strategy:"probe",reason:se},_a("info","PWA_RESUME terminal-start",{frontendSessionId:Y,backendSessionId:Q,strategy:"probe",reason:se,active:_t.current}),ye("[Terminal] resume probe sent",{reason:se,backendSessionId:Q,active:_t.current});return}if(ye("[Terminal] resume probe missing connection, restarting ensureSession",{reason:se,backendSessionId:Q,active:_t.current}),!PE({initialConnectionPending:z.current})){ye("[Terminal] resume probe deferred during initial websocket handshake",{reason:se,backendSessionId:Q});return}is()},[ye,W,is,Y]),Ks=k.useCallback((se,T)=>{const j=kr.current;j&&$n.current!==se&&($n.current=se,Jg(j,se,T),ye("[Terminal] flow-control state sent",{backendSessionId:j,paused:se,reason:T}))},[ye]),Xs=k.useCallback((se,T)=>{const j=kr.current;j&&At.current!==se&&(At.current=se,e2(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&&Rt.current!==se&&(Rt.current=se,t2(j,se,T),ye("[Terminal] viewing state sent",{backendSessionId:j,viewing:se,reason:T}))},[ye]),Va=US({isActive:l&&!Ee,viewportFocused:ue,documentVisible:st,windowFocused:We,streamReady:H}),Is=zS({isActive:l,documentVisible:st,windowFocused:We,streamReady:H,isDesktop:xo()!==null}),ha=k.useRef(Va),dl=k.useRef(Is);k.useEffect(()=>{ha.current=Va,Xs(Va,"logical-focus-change")},[Va,Xs,Xr]),k.useEffect(()=>{dl.current=Is,Hs(Is,"logical-viewing-change")},[Is,Hs,Xr]),vC(Xr,st,H),k.useEffect(()=>{const se=T=>{const j=T.detail;!j||j.sessionId!==Y||lt(j.fontSize??n.fontSize)};return window.addEventListener("termfontchange",se),()=>window.removeEventListener("termfontchange",se)},[Y,n.fontSize]),k.useEffect(()=>{const se=()=>{const O=!document.hidden&&Tu();Ie(O),O&&l&&La("visibility")},T=O=>{l&&La(O.persisted?"bfcache":"pageshow")},j=()=>{Te(!0),La("window-focus")},Q=()=>Te(!1);return document.addEventListener("visibilitychange",se),window.addEventListener(r2,se),window.addEventListener("pageshow",T),window.addEventListener("focus",j),window.addEventListener("blur",Q),()=>{document.removeEventListener("visibilitychange",se),window.removeEventListener(r2,se),window.removeEventListener("pageshow",T),window.removeEventListener("focus",j),window.removeEventListener("blur",Q)}},[l,La]),k.useEffect(()=>{if(!y||!R||!gi.current)return;const se=v,T=se<=0,j=je.current;if(j?.token===y&&(j.visible||!T))return;const Q=()=>{je.current={token:y,visible:T},gr.current?.requestRefresh(w,{skipScrollToBottom:!0}),Ga(se>0?"global-resume-background":"global-resume-visible",se<=0&&S,T)};if(se<=0){Q();return}const O=window.setTimeout(Q,se);return()=>window.clearTimeout(O)},[y,w,R,v,S,Ga]);const qa=k.useRef(0);k.useEffect(()=>{if(H){qa.current=0;return}if(!Qr||Et==="Authentication required"||Et===qh)return;const se=qa.current,T=Math.min(2e3*Math.pow(2,Math.min(se,4)),3e4),j=setTimeout(()=>{qa.current+=1,ye("[Terminal] fatal self-heal: auto restarting ensureSession",{attempt:qa.current,backendSessionId:kr.current}),kt("Reconnecting..."),cr(!1),is()},T);return()=>clearTimeout(j)},[Et,Qr,H,on,ye,is]),k.useEffect(()=>{if(typeof window>"u"){He(!1);return}const se=/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1;He(se)},[]),k.useEffect(()=>{(!l||!Be)&&mt(!1),l||Ye(!1)},[l,Be]),k.useEffect(()=>{kr.current=Xr,Ke.current=-1,Kt.current=null,At.current=null,Rt.current=null,$n.current=null},[Xr]),k.useEffect(()=>{B?.(Y,H)},[H,B,Y]),k.useEffect(()=>{U?.(Y,H&&Ze&&St)},[Ze,St,H,U,Y]),k.useEffect(()=>{Fr||(ps.current=!1,G.current=null,Le.current&&(clearTimeout(Le.current),Le.current=null))},[Fr]),k.useEffect(()=>{Xr&&gr.current?.requestRefresh("session-key-change",{force:!0})},[Xr]),k.useEffect(()=>{const se=l&&Be&&Xt;_e("visibility signal",{sessionId:Y,isActive:l,isMobile:Be,isInputFocused:rt,isViewportKeyboardOpen:Xt,viewportKeyboardHeight:zt,visible:se}),V?.(Y,se)},[V,Y,l,Be,Xt,zt,_e]),k.useEffect(()=>{l&&x&&x!==qe.current&&(qe.current=x,ms())},[x,ms,l]),k.useEffect(()=>{Er.current=Y},[Y]),k.useEffect(()=>{!Be&&(Lt!==null||Ge!==null)&&(me(null),pt(null),ct.current=null)},[Be,Lt,Ge]),k.useEffect(()=>{!Xr&&(Lt!==null||Ge!==null)&&(me(null),pt(null),ct.current=null)},[Xr,Lt,Ge]),k.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(Fx,q?"true":"false")},[q]),k.useEffect(()=>{typeof window>"u"||window.localStorage.setItem($x,qt)},[qt]),k.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(Ux,De)},[De]),k.useEffect(()=>{Ne(em());const se=()=>{Ne(em())};return window.addEventListener("resize",se),()=>window.removeEventListener("resize",se)},[]);const as=k.useCallback(()=>{Bt.current+=1,ot.current+=1,bs(),wo();const se=un.current;un.current=null,Kn.current=null,z.current=!1,be.current=!1,oe(!1),gr.current?.setSessionReady(!1);const T=kr.current;T&&Jg(T,!1,"stream-disconnect"),rs.current=!1,$n.current=null,kn.current=[],se?.()},[wo,bs]),Rs=k.useCallback(async se=>{if(Kn.current===se){ye(`[startStream] Skipping - already connected to ${se}`);return}ye(`[startStream] Starting stream for frontendSessionId=${Y} backendSessionId=${se}`),sn(null),N.current+=1,Ft.current=!1,hr.current=null,Je(!1),Vt(!1),as();const T=Bt.current+1;Bt.current=T,z.current=!0;const j=Yr.getState().getTerminalSession(Y);if(j?.mode==="shell"&&!j.bufferChunks.length){const O=await Promise.race([pw(se),new Promise(fe=>window.setTimeout(()=>fe(null),75))]);if(Bt.current!==T||Er.current!==Y)return;if(O&&!Yr.getState().getTerminalSession(Y)?.bufferChunks.length){Yr.getState().replaceBuffer(Y,[O.data]);const fe=gr.current?.getDimensions();fe?.cols===O.cols&&fe.rows===O.rows&&mw(se,O.seq,O.epoch)}}const Q=Se.connect(se,{onEvent:O=>{if(Bt.current!==T)return;const fe=Y;if(fe)switch(O.type){case"connected":{ot.current+=1,z.current=!1;const we=re.current;we&&(_a("info","PWA_RESUME terminal-connected",{frontendSessionId:fe,backendSessionId:kr.current,durationMs:Date.now()-we.startedAt,strategy:we.strategy,reason:we.reason}),re.current=null),W?.(fe),(O.runtime||O.ptyBackend)&&ye(`[Terminal] connected frontendSessionId=${fe} backendSessionId=${kr.current} runtime=${O.runtime??"unknown"} pty=${O.ptyBackend??"unknown"} cwd=${O.cwd??"unknown"}`),mr(fe,!1),kt(null),cr(!1),sn(null),be.current=!0,oe(!0),kr.current&&(e2(kr.current,ha.current,"stream-connected"),t2(kr.current,dl.current,"stream-connected")),gr.current?.setSessionReady(!0),$n.current=null,Ks(rs.current,"stream-connected"),O.tuiProgress!==void 0&&Yr.getState().setSessionTuiProgress(fe,O.tuiProgress??null),O.shellTitle!==void 0&&Yr.getState().setSessionShellTitle(fe,O.shellTitle??null),O.promptState!==void 0&&O.promptState!==null&&Yr.getState().setSessionPromptState(fe,O.promptState);const Pe=Yr.getState().getTerminalSession(fe);if(Pe?.terminalSessionId&&O.mode&&Yr.getState().setTerminalSession(fe,{sessionId:Pe.terminalSessionId,cols:80,rows:24,mode:O.mode,tmuxSessionName:O.tmuxSessionName??null,cwd:O.cwd??null}),O.activeProgram!==void 0&&Tn(fe,O.activeProgram??null,O.activeProgramSource??null,O.activeProgramRaw??null),gr.current?.requestRefresh("connected",{force:!0,reconcileServerSize:_t.current}),O.mode!=="tmux"&&(Wn(null),pn(fe,!1)),ye("[Terminal] Connected event received:",{frontendSessionId:fe,backendSessionId:kr.current,storeHasState:!!Pe,storeTerminalId:Pe?.terminalSessionId,hasHistoryInStore:!!Pe?.history?.length,historyLength:Pe?.history?.length??0}),Pe?.history&&Pe.history.length>0){ye(`[Terminal] Restoring ${Pe.history.length} history chunks to frontend session ${fe}`);const Jt=Pe.history.reduce((Ur,Jr)=>Ur+Jr.length,0),or=Math.max(300,Math.min(2e3,Math.ceil(Jt/200)));Ln.current=Date.now()+or,Pe.history.forEach(Ur=>{Hr(fe,Ur,{markActivity:!1})}),Yr.getState().setSessionHistory(fe,[]),ye(`[Terminal] History restoration complete for ${fe}`)}else ye(`[Terminal] No history to restore for ${fe}`);const Xe=O.replayChunks,ft=!!Pe?.history?.length||!!Xe?.length;if(ft?Ft.current=!0:Vn(),Xe&&Xe.length>0){let Jt=null;if(O.replayOutOfWindow)ye(`[Terminal] Replay out-of-window, atomically replacing buffer (${Xe.length} chunks)`),Jt=_n(fe,LC(Xe));else{ye(`[Terminal] Replay incremental: ${Xe.length} chunks`);for(const Jr of Xe)Hr(fe,Jr)}const or=Xe.reduce((Jr,Qn)=>Jr+Qn.length,0),Ur=Math.max(200,Math.min(1500,Math.ceil(or/200)));Ln.current=Math.max(Ln.current,Date.now()+Ur),hr.current=Jt}ft&&hr.current===null&&(hr.current=Yr.getState().flushPendingBufferWrites(fe),hr.current===null&&(Ft.current=!1,Vn()));break}case"reconnecting":{be.current=!1,oe(!1),sn(we=>we??Date.now()),kt("Reconnecting..."),cr(!1);break}case"data":{O.data&&(rs.current?kn.current.push(O.data):Hr(fe,O.data));break}case"tmux-layout":{Wn(O.layout??null),O.layout&&pn(fe,O.layout.inCopyMode);break}case"tmux-screen-sync":{const we=O.generation??0;if(we<Ke.current)break;Ke.current=we,N.current+=1,Ft.current=!0,Je(!1),kn.current=[],gr.current?.prepareScreenReplacement(),Kt.current=we,hr.current=_n(fe,IC(O.chunks??[])),hr.current===null&&(Kt.current=null,gr.current?.notifyScreenSynchronized(we),Ft.current=!1,Vn()),typeof O.cols=="number"&&typeof O.rows=="number"&&gr.current?.notifyServerSize(O.cols,O.rows,"tmux-screen-sync");break}case"active-program":{Tn(fe,O.activeProgram??null,O.activeProgramSource??null,O.activeProgramRaw??null);break}case"cwd":{ir(fe,O.cwd??null);break}case"agent-status":{Pr(fe,{agentStatus:O.agentStatus??null,agentIndicator:O.agentIndicator??null,agentStatusDetail:O.agentStatusDetail??null,agent:O.agent??null,agentMessage:O.agentMessage??null,agentNativeSessionId:O.agentNativeSessionId??null,agentResumeRecovered:O.agentResumeRecovered===!0,agentRich:O.agentRich===!0,agentActivity:O.agentActivity??0,agentCwd:O.agentCwd??null,reviewed:O.reviewed??null});break}case"git-status":{Yr.getState().setSessionGitStatus(fe,O.gitStatus??null);break}case"focus-mode":{ye("[Terminal] focus tracking mode",{backendSessionId:kr.current,requested:O.focusTrackingRequested===!0});break}case"resize-ack":{gr.current?.acknowledgeResize({seq:O.seq,ok:O.ok!==!1,cols:O.cols,rows:O.rows,screenSyncPending:O.screenSyncPending,screenSyncGeneration:O.screenSyncGeneration});break}case"pty-size":{typeof O.cols=="number"&&typeof O.rows=="number"&&gr.current?.notifyServerSize(O.cols,O.rows,O.source);break}case"shell-title":{Wa(fe,O.title??null);break}case"prompt-state":{Wr(fe,O.state??"idle",O.exitCode??null);break}case"tui-progress":{Yr.getState().setSessionTuiProgress(fe,O.tuiProgress??null);break}case"exit":{const we=typeof O.exitCode=="number"?O.exitCode:null,Pe=typeof O.signal=="number"?O.signal:null;Hr(fe,`\r
|
|
76
76
|
[Process exited${we!==null?` with code ${we}`:""}${Pe!==null?` (signal ${Pe})`:""}]\r
|
|
77
|
-
`),dr(fe),mr(fe,!1),kt("Terminal session ended"),oe(!1),cr(!1),sn(null),Wn(null),pn(fe,!1),as();break}}},onError:(O,fe)=>{if(Bt.current!==T)return;const we=Y;if(!we)return;z.current=!1,be.current=!1,oe(!1);const Pe=fe&&O.message==="Authentication required",Xe=Qx(O),ft=Pe?O.message:Xe||fe?"Reconnecting...":O.message||"Terminal stream connection error";console.error(`[Terminal] Stream error (fatal=${fe}):`,ft),Xe&&console.warn("[Terminal] SESSION_NOT_FOUND_DETECTED",{terminalIdAtError:kr.current,frontendSessionId:we,isActive:l,isMobile:Be,fatal:fe,stack:new Error().stack}),kt(ft),cr(!!fe),fe&&(sn(null),mr(we,!1),as(),Xe&&(ye("[onError] Session lost, auto-recreating"),kt("Reconnecting..."),cr(!1),dr(we),hn(we),kr.current=null,Ui.current=!1,is()))}},{...nN,getDimensions:()=>gr.current?.getDimensions()??null});un.current=()=>{Q.close(),Bt.current===T&&(Kn.current=null)},Kn.current=se},[Hr,hn,dr,ye,as,Vn,W,Ks,is,Wa,mr,Tn,Pr,pn,ir,Wr,Se,Y]);k.useEffect(()=>{const se=HE({isActive:l,isStreamReady:H,reconnectStartedAt:Zn,now:Date.now()});if(se===null)return;const T=window.setTimeout(()=>{ye("[Terminal] visible reconnect watchdog expired",{backendSessionId:kr.current,reconnectStartedAt:Zn}),as(),mr(Y,!1),kt("Reconnecting..."),cr(!1),sn(Date.now()),is()},se);return()=>window.clearTimeout(T)},[ye,as,l,H,Zn,is,Y,mr]);const Ui=k.useRef(!1),gi=k.useRef(!1),xi=k.useRef(0);k.useEffect(()=>()=>{xi.current+=1,Ui.current=!1,as()},[as]);const hl=k.useRef(K),Js=k.useRef(Ue);k.useEffect(()=>{const se=hl.current,T=Js.current;hl.current=K,Js.current=Ue,Er.current===Y&&(se===K&&T===Ue||(Ui.current=!1,as(),_r(j=>j+1)))},[K,Ue,as,Y]),k.useEffect(()=>{if(Er.current!==Y&&(ye(`[useEffect] sessionId changed from ${Er.current} to ${Y}, allowing reinitialization`),Ui.current=!1,gi.current=!1),Ui.current&&Er.current===Y){ye(`[useEffect] Already initialized for sessionId=${Y}, skipping`);return}if(!jt)return;const se=async fe=>{if(ye(`[ensureSession] Starting for sessionId=${Y}, runId=${fe}`),!Er.current||Er.current!==Y){ye(`[ensureSession] SessionId mismatch or stale run (current=${Er.current}, target=${Y}), skipping`);return}if(fe!==xi.current){ye(`[ensureSession] Stale run detected (runId=${fe}, currentRunId=${xi.current}), skipping`);return}const we=Yr.getState(),Pe=we.getTerminalSession(Y),Xe=Pe?.mode??K;ye("[ensureSession] Current state from store:",{terminalSessionId:Pe?.terminalSessionId,mode:Pe?.mode,tmuxSessionName:Pe?.tmuxSessionName,isConnecting:Pe?.isConnecting});let ft=Pe?.terminalSessionId??null,Jt=!ft;if(ft&&Xe!==K?(ye(`[ensureSession] Store mode mismatch for ${ft}: current=${Xe} desired=${K}, will create new session`),Jt=!0,we.clearTerminalSession(Y),ft=null):ft&&K==="tmux"&&Ue&&Pe?.tmuxSessionName!==Ue&&(ye(`[ensureSession] Store tmux name mismatch for ${ft}: current=${Pe?.tmuxSessionName} desired=${Ue}, will create new session`),Jt=!0,we.clearTerminalSession(Y),ft=null),ft&&Se.checkHealth&&!_t.current){ye(`[ensureSession] Checking health of existing session ${ft}`);try{const or=await Se.checkHealth(ft);if(ye("[ensureSession] Health check result:",or),!or.healthy)ye(`[ensureSession] Session ${ft} is NOT healthy (healthy=${or.healthy}), will create new session`),ye("[ensureSession] Health check details:",or),Jt=!0,or.mode&&Pe?.terminalSessionId&&we.setTerminalSession(Y,{sessionId:Pe.terminalSessionId,cols:80,rows:24,mode:or.mode,tmuxSessionName:or.tmuxSessionName??null}),we.clearTerminalSession(Y),ye("[ensureSession] Cleared unhealthy session from store");else{ye(`[ensureSession] Session ${ft} is healthy, reusing it, cwd=${or.cwd}, clients=${or.clients}, lastActivity=${Date.now()-(or.lastActivity||0)}ms ago`),or.mode&&Pe?.terminalSessionId&&we.setTerminalSession(Y,{sessionId:Pe.terminalSessionId,cols:80,rows:24,mode:or.mode,tmuxSessionName:or.tmuxSessionName??null}),ye(`[ensureSession] Setting terminalIdRef to ${ft} and starting stream`),kr.current=ft,Rs(ft),ye(`[ensureSession] Successfully reused healthy session ${ft}, returning early`);return}}catch(or){ye(`[ensureSession] Failed to check health of session ${ft}:`,or),ye("[ensureSession] Health check API call failed, proceeding as if session might be unhealthy")}}if(ye(`[ensureSession] Decision: shouldCreateNewSession=${Jt}, terminalId=${ft}`),Jt){ye(`[ensureSession] Creating new session, shouldCreateNewSession=${Jt}, runId=${fe}`),kt(null),cr(!1),we.setConnecting(Y,!0);const Ur=Yr.getState().getTerminalSession(Y),Qn=(Ur?.mode??K)===K&&(K!=="tmux"||!Ue||Ur?.tmuxSessionName===Ue);if(Ur?.terminalSessionId&&Qn)ye(`[ensureSession] Race condition avoided: another instance already created session ${Ur.terminalSessionId}`),we.setConnecting(Y,!1),ft=Ur.terminalSessionId,Jt=!1;else try{const vr=await zn();if(ye(`[ensureSession] Opened managed backend session ${vr.sessionId}`),fe!==xi.current){ye(`[ensureSession] Stale run after session creation (runId=${fe}, currentRunId=${xi.current}), leaving ${vr.sessionId} for sibling`);return}we.setTerminalSession(Y,vr),ye(`[ensureSession] Updated store with new session ${vr.sessionId}`),ft=vr.sessionId}catch(vr){if(fe!==xi.current){ye("[ensureSession] Stale run after session creation failed, skipping error handling");return}if(vr instanceof Jd&&o1(vr)){ye("[ensureSession] Confirmed missing persisted session:",{sessionId:Y,error:vr.message}),we.clearTerminalSession(Y),kt(qh),cr(!0),we.setConnecting(Y,!1);return}kt("Reconnecting..."),cr(!0),we.setConnecting(Y,!1);return}}if(fe!==xi.current){ye(`[ensureSession] Stale run before starting stream (runId=${fe}, currentRunId=${xi.current}), skipping`);return}if(!ft){ye(`[ensureSession] No terminalId, terminalId=${ft}`);return}ye(`[ensureSession] Starting stream for session ${ft}`),kr.current=ft,Rs(ft),ye(`[ensureSession] ensureSession completed for sessionId=${Y}, terminalId=${ft}`)};let T=null,j=null;const Q=()=>{j=null,!(Ui.current&&Er.current===Y)&&(ye(`[useEffect] Running ensureSession for sessionId=${Y}, hasInitialized=${Ui.current}`),Ui.current=!0,gi.current=!0,T=++xi.current,se(T))};if(!E&&!gi.current){ye(`[useEffect] Holding background connection until the selected session is ready: ${Y}`);return}const O=gi.current?0:Math.max(0,L);return O>0?(ye(`[useEffect] Delaying initial connection for sessionId=${Y} by ${O}ms`),j=window.setTimeout(Q,O)):Q(),()=>{j!==null&&window.clearTimeout(j),ye(`[useEffect] Cleanup for sessionId=${Y}, runId=${T??"pending"}`)}},[Y,on,Rs,as,Se,ye,K,Ue,Br,L,E,jt]);const Uo=k.useCallback(async()=>{if(Y&&!Sn){Ls(!0),kt(null),cr(!1),sn(null),as();try{Se.forceKill&&await Se.forceKill({sessionId:Y})}catch{}bn(Y),hn(Y),gr.current?.clear(),await new Promise(se=>setTimeout(se,100));try{mr(Y,!0);const se=await zn();Tr(Y,se),kr.current=se.sessionId,Rs(se.sessionId)}catch(se){kt(se instanceof Jd&&o1(se)?qh:"Reconnecting..."),cr(!0),mr(Y,!1)}finally{Ls(!1)}}},[Y,Sn,as,Se,bn,hn,mr,Tr,Rs,zn]),fa=k.useCallback((se,T,j,Q)=>{if(!(kr.current!==T||ot.current!==j)){if(se instanceof Jd&&Qx(se)){ye("[Terminal] operation backend missing, recovering",{terminalId:T,sessionId:Y}),kt("Reconnecting..."),cr(!1),as(),dr(Y),kr.current=null,mr(Y,!0),is();return}kt(se instanceof Error?se.message:Q)}},[dr,ye,as,is,Y,mr]),fl=k.useCallback((se,T)=>{const j=T?.ownedPaste?bC(T.ownedPaste,Y,se):!1;if(T?.ownedPaste&&!j||Dt.current||(Mr.current||D1())&&!j)return Promise.resolve(!1);const Q=()=>!!T?.ownedPaste&&yC(T.ownedPaste,Y)&&_t.current&&!Dt.current&&be.current&&!tr.current&&!document.hidden&&navigator.onLine!==!1&&Tu();if(j&&!Q())return Promise.resolve(!1);if(!_t.current&&!T?.targeted||!se)return;const O=hE(se),fe=/^(\x1b\[<6[45];[0-9]+;[0-9]+M)+$/.test(se);if(Fr&&fe&&(ps.current=!0),Date.now()<Ln.current)return;let we=se,Pe=T?.consumeModifier??!1;if(!T?.skipModifierTransform&&Lt&&se.length>0){const Ur=se[0];if(Ur.length===1&&/[a-zA-Z]/.test(Ur)){const Jr=Ur.toUpperCase();Lt==="ctrl"?(we=String.fromCharCode(Jr.charCodeAt(0)&31),Pe=!0):Lt==="alt"&&(we=`\x1B${se}`,Pe=!0)}Pe||(Lt==="alt"&&(we=`\x1B${se}`),Pe=!0)}const Xe=kr.current;if(!Xe)return;const ft=ot.current,or=(async()=>{try{if(Fr&&!O&&ps.current&&Se.tmuxAction){ps.current=!1;try{await Se.tmuxAction(Xe,{action:"copy-mode",enabled:!1})}catch{}if(kr.current!==Xe||ot.current!==ft)return!1;if(fE(we))return!0}return j&&(!Q()||kr.current!==Xe||ot.current!==ft)||(await Se.sendInput(Xe,we),j&&(!Q()||kr.current!==Xe||ot.current!==ft))?!1:(fs(Y),!0)}catch(Ur){return fa(Ur,Xe,ft,"Failed to send input"),!1}})();return Pe&&(Ge||me(null),ms()),or},[Lt,fs,ms,fa,Fr,Ge,Y,Se]);k.useEffect(()=>{const se=T=>{const j=T,Q=j.detail?.sessionId;if(Q?Q!==Y:!_t.current)return;const O=j.detail?.text;if(!O)return;const fe=j.detail?.nonce;if(tr.current||!gr.current){fe&&window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:fe,ok:!1}}));return}const we=xC(j.detail,Y),Pe=j.detail?.ownedPaste&&!we?Promise.resolve(!1):gr.current.sendSequence(O,{paste:j.detail?.paste,submitAfterPaste:j.detail?.submitAfterPaste,targeted:!!Q,ownedPaste:we??void 0});fe&&Promise.resolve(Pe).then(Xe=>{window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:fe,ok:Xe===!0}}))},()=>{window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:fe,ok:!1}}))}),WS(Gr.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){_e("xterm resize push skipped: no terminalId",{cols:se,rows:T});return}_e("xterm resize push",{cols:se,rows:T}),Se.resize({sessionId:Q,cols:se,rows:T,seq:j}).catch(O=>{gr.current?.acknowledgeResize({seq:j,ok:!1}),O&&/session not found/i.test(String(O.message||O))&&console.warn("[Terminal] resize 404 session not found",{sessionId:Q,cols:se,rows:T,stack:new Error().stack})})},[Se,_e]),os=k.useCallback(async se=>{const T=kr.current;if(!T||!Se.tmuxAction)return;const j=ot.current;try{const Q=await Se.tmuxAction(T,se);if(kr.current!==T||ot.current!==j)return;Q.layout&&(Wn(Q.layout),se.action==="switch-session"&&(Tr(Y,{sessionId:T,cols:80,rows:24,mode:"tmux",tmuxSessionName:Q.layout.sessionName}),gw(Y,{tmuxSessionName:Q.layout.sessionName}).catch(O=>{console.warn("[Terminal] failed to update inventory after tmux switch",O)})))}catch(Q){fa(Q,T,j,"Failed to execute tmux action")}},[fa,Y,Tr,Se]);k.useEffect(()=>{if(!$r||!Xr)return;const T=$r.windows.find(j=>j.id===$r.activeWindowId)?.panes.find(j=>j.id===$r.activePaneId);T&&gr.current?.requestRefresh("tmux-layout",{skipScrollToBottom:!0,dedupeKey:`${Xr}:${$r.sessionId}:${T.id}:${T.width}x${T.height}`})},[$r,Xr]);const Ms=k.useCallback((se,T=5)=>{const j=Math.max(1,Math.min(Math.floor(T)||1,40));ps.current=!0;const Q=G.current;if(Q&&Q.direction===se){Q.lines+=j;return}Q&&os({action:"scroll",direction:Q.direction,lines:Q.lines}).finally(()=>{ms()}),G.current={direction:se,lines:j},Le.current&&clearTimeout(Le.current),Le.current=setTimeout(()=>{const O=G.current;O&&(G.current=null,os({action:"scroll",direction:O.direction,lines:O.lines}).finally(()=>{ms()}))},0)},[ms,os]),Ni=k.useCallback(se=>{const T=Date.now(),j=ct.current,Q=j!==null&&j.modifier===se&&T-j.timestamp<=JE;if(ct.current={modifier:se,timestamp:T},Ge===se){pt(null),me(null);return}if(Q){pt(se),me(se);return}Ge!==null&&Ge!==se&&pt(null),me(O=>O===se?null:se)},[Ge]),zo=k.useCallback(se=>{if(Ye(se&&_t.current),_e("input focus changed",{focused:se,isActive:_t.current,isMobile:Gr.current}),!Gr.current||!_t.current){mt(!1);return}mt(T=>T===se?T:se)},[_e]),jl=k.useCallback(se=>{if(rs.current=se,Ks(se,"viewport-watermark"),!se&&kn.current.length>0){const T=Y;if(T){const j=kn.current;kn.current=[];for(const Q of j)Hr(T,Q)}}},[Hr,Ks,Y]),Es=k.useCallback(se=>{_t.current&&gr.current?.ensureSizeMatches(se)},[]),Ia=k.useRef(null);k.useEffect(()=>{if(!l)return;const se=Ia.current;if(!se)return;const T=()=>Es("pointerdown"),j=()=>Es("keydown"),Q=()=>Es("touchstart"),O=()=>Es("wheel");return se.addEventListener("pointerdown",T),se.addEventListener("keydown",j),se.addEventListener("touchstart",Q,{passive:!0}),se.addEventListener("wheel",O,{passive:!0}),()=>{se.removeEventListener("pointerdown",T),se.removeEventListener("keydown",j),se.removeEventListener("touchstart",Q),se.removeEventListener("wheel",O)}},[l,Es]);const ml=k.useCallback(se=>{gr.current=se},[]),Xn=k.useCallback(se=>{vt(se),F?.(Y,se)},[F,Y]),zi=k.useCallback(se=>{const T=wE(se);if(!T)return;const j=Lt!==null;gr.current?.sendSequence(T,{consumeModifier:j})},[Lt]),Ri=k.useCallback(se=>{const T=gE(se);if(T.length===0)return;const j=Lt!==null;gr.current?.sendSequence(Mx(T[0]),{consumeModifier:j});for(let Q=1;Q<T.length;Q+=1){const O=T[Q];window.setTimeout(()=>{gr.current?.sendSequence(Mx(O))},mE*Q)}},[Lt]),Hi=k.useCallback(()=>{gr.current?.pasteClipboardText()},[]),gs=k.useCallback(se=>{Mt.current!==null&&(window.clearTimeout(Mt.current),Mt.current=null),gt(se),(se==="inserted"||se==="failed")&&(Mt.current=window.setTimeout(()=>{Mt.current=null,gt("idle")},1400))},[]),Ws=k.useCallback(()=>{gs("idle"),It(0),Dn.current?.click()},[gs]),Dl=k.useCallback(()=>{rn(!0)},[]),Wi=k.useCallback(se=>{const T=se.currentTarget.files?.[0];if(se.currentTarget.value="",!T)return;const j=Y;Cr(null),pr(null),Lr(null),It(0),gs("uploading");const Q=sr&&T.type.startsWith("video/")?{maxHeight:xn,videoBitrate:an,onProgress:It}:null,O=Me&&tN(T)?{maxDimension:nt,quality:wt}:null;let fe=Q?"视频压缩":O?"图片压缩":"文件上传";(async()=>{const we=Q?await(await Oc(async()=>{const{compressVideoLocally:Pe}=await import("./videoCompression-8r1jOza9.js");return{compressVideoLocally:Pe}},__vite__mapDeps([0,1,2,3,4,5]))).compressVideoLocally(T,Q):O?await(await Oc(async()=>{const{compressImageLocally:Pe}=await import("./imageCompression-DaUBNTq-.js");return{compressImageLocally:Pe}},[])).compressImageLocally(T,O):T;fe="文件上传",await ZE(we,(Pe,Xe)=>L0(Pe,Xe,void 0,It),Pe=>(fe="插入终端",Ox(l1(Pe,null),j,()=>_t.current&&!tr.current&&Er.current===j&&Yr.getState().activeSessionId===j))),(Q||O)&&Lr({file:we,kind:Q?"video":"image",originalSize:T.size,uploadedSize:we.size,originalRetained:we===T})})().then(()=>gs("inserted"),we=>{we instanceof yf&&Cr({path:we.uploaded.path,sessionId:j});const Pe=we instanceof yf?we.uploaded.path:zx(we);pr({stage:fe,detail:Pe}),rn(!0),gs("failed"),_a("warn","MOBILE_MEDIA_UPLOAD failed",{stage:fe,detail:Pe})})},[an,sr,xn,Me,nt,wt,Y,gs]),Gi=k.useCallback(async()=>{const se=nr;if(!se||se.sessionId!==Y)return;rn(!1),await new Promise(j=>window.requestAnimationFrame(()=>j())),gs("uploading"),await Ox(l1(se.path,null),se.sessionId,()=>_t.current&&!tr.current&&Er.current===se.sessionId&&Yr.getState().activeSessionId===se.sessionId)?(Cr(null),pr(null),gs("inserted")):(rn(!0),gs("failed"))},[nr,Y,gs]);k.useEffect(()=>{if(!Rr||!sr)return;let se=!0;return Ht(null),ne({phase:"checking-cache"}),Oc(async()=>{const{prepareLocalVideoCompression:T}=await import("./videoCompression-8r1jOza9.js");return{prepareLocalVideoCompression:T}},__vite__mapDeps([0,1,2,3,4,5])).then(({prepareLocalVideoCompression:T})=>{if(se)return T(j=>{se&&ne(j)})}).catch(T=>{se&&Ht(zx(T))}),()=>{se=!1}},[Rr,sr]);const ln=Or||Et!==null;tr.current=ln;const pa=k.useRef(Kr);ln||(pa.current=Kr);const Vi=ln?pa.current:Kr,Ea=k.useMemo(()=>xE(Vi,nn),[Vi,nn]),Mi=k.useMemo(()=>Dx(nn,qt),[qt,nn]),ji=!Be&&qt!=="auto"&&Mi.id!=="default"&&Mi.showOnDesktop!==!0?"auto":qt,ei=ji==="auto"?Ea:ji,ws=k.useMemo(()=>Dx(nn,ei),[ei,nn]),Gs=k.useMemo(()=>ws.actions.filter(se=>se.sequence.trim().length>0).map((se,T)=>({...se,label:a1(se,T)})),[ws.actions]),Di=k.useMemo(()=>G3(Kr),[Kr]),Na=ws.label,ti=k.useMemo(()=>ji!=="auto"?`Manual preset: ${ws.label}`:Di?`Auto preset · ${ws.label} (${Di})`:"Auto preset",[Di,ji,ws.label]),ys=k.useCallback(se=>{Ve(se)},[]),Ya=k.useCallback(()=>{er(se=>se==="copy"?"arrows":"copy"),Ct("idle")},[]),Za=k.useCallback(()=>{typeof window>"u"||(fr.current!==null&&window.clearTimeout(fr.current),fr.current=window.setTimeout(()=>{fr.current=null,Ct("idle")},1200))},[]),As=k.useCallback(se=>{fr.current!==null&&typeof window<"u"&&(window.clearTimeout(fr.current),fr.current=null),Ct(se?"copied":"failed"),Za()},[Za]),Ka=k.useCallback(se=>{at(se)},[]),Bl=k.useMemo(()=>Be?bE(nn):yE(nn),[Be,nn]),Ho=k.useMemo(()=>xw(a),[a]);k.useEffect(()=>{if(!Fr||!H||!jt||!Xr)return;const se=EC(Ho);se&&Se.sendInput(Xr,se).catch(T=>{console.warn("[Terminal] Failed to synchronize tmux default colors:",T)})},[Fr,H,jt,Xr,Se,Ho]);const Ao=k.useMemo(()=>`terminal::${Y}`,[Y]);k.useEffect(()=>{ke?.({isConnecting:Or,isRestarting:Sn,hasError:!!Et,sessionId:Xr})},[Or,Sn,Et,Xr,ke]);const ma=!Xr||Or||Sn,Ra=k.useCallback((se,T)=>{if(ma)return;const j=Math.max(1,Math.min(Math.floor(T)||1,40));Ms(se,j)},[Ms,ma]);k.useEffect(()=>{if(!l||!Be)return;gr.current?.requestRefresh("resize",{skipScrollToBottom:!Xt,force:!0})},[l,Be,Xt,zt,Y]),k.useEffect(()=>{if(!l||!Be)return;const se=T=>{const j=T.detail;gr.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,Be,Y]);const Wo=!Z&&(Be||ws.id==="default"||ws.showOnDesktop===!0),ga=l,ls=Be&&!xe?{transform:"translateY(var(--kb-translate-y, 0px))",transition:"none"}:void 0,Go=Be&&!xe?{marginTop:"var(--kb-margin-top, 0px)",transition:"none"}:void 0,qi=s.jsx(AE,{visible:Wo,interactive:ga,presentation:Be?"mobile":"desktop-actions",activeModifier:Lt,lockedModifier:Ge,disabled:ma,defaultShowExtended:q,presetLabel:Na,presetModeLabel:ti,presetMode:ji,presetOptions:Bl,includeAlt:ws.includeAlt,presetRowLayout:ws.rowLayout,extraActions:Gs,onKeyPress:zi,onTextPress:Ri,onPastePress:Be?Hi:void 0,onFilePress:Be?Ws:void 0,onFileLongPress:Be?Dl:void 0,fileUploadState:Nt,fileUploadProgress:bt,longPressMode:De,copyFeedback:et,onLongPressModeToggle:Ya,onModifierToggle:Ni,onPresetSelect:ys,onExpandedChange:Ka}),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:ls,children:[s.jsx("input",{ref:Dn,type:"file",className:"hidden",onChange:Wi}),Rr&&Ii.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:()=>rn(!1),"aria-label":$e("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:()=>rn(!1),children:$e("common.close")})]}),yt&&s.jsxs("div",{role:"alert",className:"mt-3 rounded-lg bg-destructive/10 p-3 text-xs text-destructive",children:[s.jsxs("p",{children:[yt.stage,"失败。",yt.stage.endsWith("压缩")?"原文件未上传。":yt.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:yt.detail})]}),nr&&s.jsx("button",{type:"button",onClick:()=>{Gi()},disabled:Nt==="uploading"||nr.sessionId!==Y,className:"mt-2 rounded-lg bg-surface-2 px-3 py-2 text-foreground disabled:opacity-50",children:$e("common.retry")})]}),dt&&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:Vr.showResultToast,onChange:se=>it({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:Me,onChange:se=>it({imageEnabled:se.target.checked}),className:"h-4 w-4 accent-primary"})]}),Me&&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:nt,onChange:se=>it({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:J3.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(wt*100),"%",s.jsx("input",{type:"range",min:i0.min,max:i0.max,step:i0.step,value:wt,onChange:se=>it({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:sr,onChange:se=>it({videoEnabled:se.target.checked}),className:"h-4 w-4 accent-primary"})]}),sr&&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:xn,onChange:se=>it({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:ev.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:["目标视频码率:",an/1e6," Mbps",s.jsx("input",{type:"range",min:a0.min,max:a0.max,step:a0.step,value:an,onChange:se=>it({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:ht?"本地转码器准备失败,请关闭开关后重试。":rN(Ir)}),Ir?.saved===!1&&s.jsx("p",{className:"text-[11px] text-destructive",children:"本机未能保存转码器,重新打开后可能需要重新下载。"}),ht&&s.jsx("p",{className:"text-[11px] text-destructive",children:ht})]})]})]}),document.body),Gn&&s.jsx(TE,{isMobile:Be,isInputFocused:rt,isIOS:le,isConnecting:Or,connectionError:Et,terminalSessionId:Xr}),s.jsxs("div",{className:"relative min-h-0 flex-1 overflow-hidden",style:{backgroundColor:Ho.background,...Go},children:[s.jsx("div",{ref:Ia,className:"h-full w-full box-border",children:s.jsx(bw,{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:$e("terminal.componentFailed")})]})}),children:s.jsx(iE,{ref:ml,sessionKey:Ao,sessionId:Y,isLayoutVisible:m,chunks:ks,onInput:fl,onResize:pl,onFlowControl:jl,onTmuxScroll:Fr?Ra:void 0,tmuxScrollSensitivity:.38,onDoubleTap:Be?()=>{gr.current?.sendSequence(" ")}:void 0,onInputFocusChange:zo,onMobileLongPressCopyResult:As,onReadyChange:Xn,onSizeSynchronizedChange:Vt,onWritesSettled:Ha,onWriteProgress:$i,onCursorPositionChange:ua,onDirectoryLinkActivate:fn,terminalSettings:Oe,theme:Ho,enableTouchScroll:Be,mobileLongPressMode:De,autoFocus:!Ee&&!Be&&!gl,cursorVisible:!Ee&&Zt,suppressSmoothScroll:!Ze||!St,className:Ee||!Zt?"terminal-focus-suspended":void 0},Ao)})}),s.jsx(XE,{result:cn,onDismiss:ge}),s.jsx(CE,{connectionError:Et,isFatalError:Qr,isRestarting:Sn,isConnecting:Or,onHardRestart:Uo})]}),ce?Z?null:Ii.createPortal(qi,ce):qi]})};function iN({session:e,active:t,onActivate:r,onToggleRightSidebar:n}){const{t:a}=zr(),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(Fo,{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(Ff,{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(By,{size:14})})]})}const aN="termdock:startup:";function Nu(e){if(typeof performance>"u"||typeof performance.mark!="function")return;const t=`${aN}${e}`;performance.getEntriesByName(t,"mark").length>0||performance.mark(t)}function Hx(e,t){e||Ii.flushSync(t)}const c1="horizontal";function Du(e){return e<=0?[]:Array.from({length:e},()=>1/e)}function Yh(e,t){if(!Array.isArray(e)||e.length!==t)return Du(t);const r=e.map(Number);if(r.some(a=>!Number.isFinite(a)||a<=0))return Du(t);const n=r.reduce((a,c)=>a+c,0);return n<=0?Du(t):r.map(a=>a/n)}function oN(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 lN(e){return e==="horizontal"||e==="vertical"||e==="grid"}function cN(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=oN(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:lN(c.layout)?c.layout:c1,ratios:Yh(c.ratios,d.length),...c.gridColumnRatios!==void 0?{gridColumnRatios:Yh(c.gridColumnRatios,p.columns)}:{},...c.gridRowRatios!==void 0?{gridRowRatios:Yh(c.gridRowRatios,p.rows)}:{}})}return n}function uN(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?Yh(n.ratios,a.length):Du(a.length)}]})}function y0(e,t){if(t)return e.find(r=>r.sessionIds.includes(t))}function tm(e,t,r){if(!t||!r||t===r)return e;const n=y0(e,t),a=y0(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===c1)?"grid":n?.layout??c1,ratios:Du(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 dN(e,t){const r=y0(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:Du(n.length)}:a)}function hN(e,t){const r=y0(e,t);return r?e.filter(n=>n.id!==r.id):e}function fN(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 pN(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 u1=320,rv=1,mN=u1+120,d1="termdock:split-workspaces:v2",nv="termdock:split-workspace:v1",gN=.1,xN=.9;function rm(){if(typeof window>"u")return{mobile:!1,landscape:!1};const e=xy();return{mobile:e,landscape:e&&window.innerWidth>window.innerHeight}}function bN(){if(typeof window>"u")return[];try{const e=window.localStorage.getItem(d1);if(e)return cN(JSON.parse(e));const t=JSON.parse(window.localStorage.getItem(nv)||"null");if(t&&typeof t.primaryId=="string"&&typeof t.secondaryId=="string"&&t.primaryId!==t.secondaryId){const r=Math.min(xN,Math.max(gN,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 yN(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 Wx(e){const t=e.wrapperEl;if(t)try{t.getAnimations().forEach(r=>r.cancel())}catch{}}function vh(e,t){const r=vf(e,t);if(r===null)return;const n=e.wrapperEl;Wx(e),n&&(n.style.transitionDuration="0ms");try{const a=e;a.setTransition?.(0),a.setTranslate?.(r),Wx(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 h1(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 vf(e,t){const r=e.snapGrid,n=Array.isArray(r)?r[t]:void 0;return typeof n!="number"||!Number.isFinite(n)?null:-n}function vN(e,t){const r=h1(e),n=vf(e,t);return r!==null&&n!==null&&Math.abs(r-n)<=rv}function wN(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 sv(e){const t=new Map;for(const r of e)t.set(r.id,r);return Array.from(t.values())}function iv(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 AN(e,t){const r=sv(e),n=r.findIndex(a=>a.id===t.id);if(n>=0){const a=[...r];return a[n]=t,a}return[...r,t]}function Gx(e,t){const r=new Map(e.map(n=>[n.id,n]));return t.map(n=>{const a=r.get(n.sessionId);return{...iv(n),history:a?.history}})}function Vx(e,t){return e.length===0?null:t&&e.some(r=>r.sessionId===t)?t:e[0]?.sessionId??null}function qx(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 Yx(e){const t=new Map;for(const[r,n]of e)t.set(r,n.cwd??null);return t}function TN(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 SN(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 CN=({terminalSettings:e=K1(),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}=zr(),W=b.useMemo(()=>Qu("session"),[]),F=b.useMemo(()=>Qu("terminal"),[]),[U,V]=b.useState([]),[Z,ce]=b.useState(null),xe=b.useRef(0),pe=b.useRef(0),te=es(z=>z.activePaneId);b.useEffect(()=>{es.getState().setActivePane(Z)},[Z]);const[ke,$e]=b.useState(null),[Y,Ae]=b.useState(!0),[lt,Se]=b.useState({token:0,reason:"visibility",forceForegroundReconnect:!1}),[ye,_e]=b.useState(()=>new Set),[je,re]=b.useState(()=>({token:0,completed:new Set})),[Oe,Ce]=b.useState(0),[Ee,Be]=b.useState(()=>new Set),[Ne,le]=b.useState(()=>new Set),He=b.useRef(new Map),[rt,mt]=b.useState(()=>new Set),ue=b.useRef(!1),Ye=b.useRef(null),st=b.useRef({}),[Ie,We]=b.useState(null),[Te,H]=b.useState(()=>bN()),[oe,be]=b.useState(!1),Ze=b.useCallback(z=>{xe.current+=1,be(z)},[]),Je=b.useRef(null),St=b.useRef(oe);St.current=oe,I0(Je,oe&&!!Z,()=>Ze(!1));const[Vt,jt]=b.useState(null),[vt,Zt]=b.useState(null),Pt=b.useRef(new Set),[Xt,zt]=b.useState(null),[Lt,me]=b.useState(null),[Ge,pt]=b.useState(!1),[q,at]=b.useState(()=>rm().mobile),[qt,Ve]=b.useState(()=>rm().landscape),[De,er]=b.useState(null),[et,Ct]=b.useState(null),Nt=b.useRef(a),gt=b.useRef(!1),bt=b.useRef(!1),It=b.useRef(null),yt=b.useRef(null),pr=b.useRef(q),nr=b.useRef(null),Cr=b.useCallback(z=>{z!==nr.current&&(xe.current+=1),nr.current=z,ce(z)},[]);b.useEffect(()=>Gt.subscribe((z,N)=>{(z.rightOpen!==N.rightOpen||z.rightTab!==N.rightTab)&&(xe.current+=1)}),[]);const cn=b.useRef(0),Lr=b.useRef([]),ge=b.useRef(0),Vr=b.useRef(null),it=b.useRef(!1),dt=b.useRef(!0),sr=b.useRef(null),xn=b.useRef(""),an=b.useRef(0);b.useEffect(()=>{if(typeof window>"u")return;const z=()=>{const N=rm();pr.current=N.mobile,at(N.mobile),Ve(N.landscape)};return z(),window.addEventListener("resize",z),()=>window.removeEventListener("resize",z)},[]);const{sessions:Me,inventory:nt,activeSessionId:wt,isLoading:Rr,openSession:rn,setActiveSession:Ir,removeSession:ne,renameSession:ht,resetSessionCustomName:Ht,reorderSessions:Ot,restoreSessions:Tr}=yw(),mr=nt?.tmuxRecovery??null;b.useEffect(()=>{mr&&R?.()},[mr,R]),b.useEffect(()=>{me(null),zt(null)},[mr?.id]);const Hr=b.useCallback(async()=>{zt("restore"),me(null);try{const z=await vw();await Tr(),z.failed>0&&me(B("tab.tmuxRecoveryPartial",{restored:z.restored,failed:z.failed}))}catch{me(B("tab.tmuxRecoveryFailed"))}finally{zt(null)}},[Tr,B]),_n=b.useCallback(async()=>{zt("dismiss"),me(null);try{await ww(),await Tr()}catch{me(B("tab.tmuxRecoveryDismissFailed"))}finally{zt(null)}},[Tr,B]),dr=Gt(z=>z.groupByFolder),bn=uf(z=>z.collaborationGroups),hn=Gt(z=>z.leftOpen||z.rightOpen),Tn=Gt(z=>z.rightSidebarWidthContextKey),ir=Gt(z=>z.rightSidebarWidth),pn=Gt(z=>z.rightPinned),[Pr,qr]=b.useState(()=>Yx(Yr.getState().sessions));b.useEffect(()=>Yr.subscribe(z=>{const N=Yx(z.sessions);qr($=>TN($,N)?$:N)}),[]);const{arranged:Wr}=b.useMemo(()=>lf(U,z=>Pr.get(z.id)??null,dr,"",Te,bn),[U,Pr,dr,Te,bn]),fs=b.useRef(Wr);fs.current=Wr;const Br=b.useMemo(()=>yN(Wr,Te),[Wr,Te]),Mn=b.useRef(Br);Mn.current=Br;const Sr=b.useMemo(()=>y0(Te,Z),[Z,Te]),Kr=b.useMemo(()=>{const z=Br.find(N=>N.sessions.some($=>$.id===Z));return new Set(z?.sessions.map(N=>N.id)??[])},[Z,Br]),nn=b.useMemo(()=>{const z=new Map;if(!m||v<=0)return z;for(const N of Br){const $=N.sessions[0];if(!$)continue;const ee=Aw($.id,Pr.get($.id)??null,N.workspace?.id??null);if(!(ee===Tn?pn:Tw($.id,Pr.get($.id)??null,N.workspace?.id??null)))continue;const Qe=ee===Tn?ir:Sw($.id,Pr.get($.id)??null,N.workspace?.id??null),ze=Ph(Qe,v,w);z.set(N.key,ze+by)}return z},[Pr,w,m,pn,Tn,ir,v,Br]),Fr=b.useMemo(()=>Jp(U.map(z=>({id:z.id,backendSessionId:z.sessionId})),d),[d,U]),ks=b.useMemo(()=>Vx(Me,wt),[wt,Me]),Or=bh({prioritySessionId:Fr,activeSessionId:ke??Z,persistedActiveSessionId:ks,firstSessionId:U[0]?.id??null}),Xr=b.useMemo(()=>WE(Br.flatMap(z=>z.sessions.map(N=>N.id)),Kr),[Kr,Br]),fn=Or!==null&&ye.has(Or),K=b.useMemo(()=>{const z=new Set(Kr);return ke&&z.add(ke),!z.size&&Or&&z.add(Or),z},[Kr,ke,Or]),Ue=je.token===lt.token&&$E(K,je.completed),Et=Ue||Oe===lt.token?lt.token:-1;b.useEffect(()=>{if(!lt.token||Ue)return;const z=window.setTimeout(()=>Ce(lt.token),EE);return()=>window.clearTimeout(z)},[lt.token,Ue]);const kt=b.useCallback((z,N)=>{_e($=>{if($.has(z)===N)return $;const ie=new Set($);return N?ie.add(z):ie.delete(z),ie})},[]),tr=b.useCallback(z=>{const N=cn.current;re(ee=>{if(ee.token===N&&ee.completed.has(z))return ee;const ie=new Set(ee.token===N?ee.completed:[]);return ie.add(z),{token:N,completed:ie}});const $=Fr??ke??nr.current;z===$&&Nu("foreground-stream-connected")},[ke,Fr]),Qr=b.useCallback((z,N)=>{Be($=>{if($.has(z)===N)return $;const ee=new Set($);return N?ee.add(z):ee.delete(z),ee})},[]),cr=b.useCallback((z,N)=>{le($=>{if($.has(z)===N)return $;const ee=new Set($);return N?ee.add(z):ee.delete(z),ee})},[]);b.useEffect(()=>{for(const[z,N]of He.current){const $=U.find(ee=>ee.id===z);if(!$||$.sessionId!==N.backendSessionId){He.current.delete(z);continue}!ye.has(z)||!Ee.has(z)||!Ne.has(z)||(He.current.delete(z),gy(N.backendSessionId,`${N.command}\r`).catch(ee=>{console.error("[Session] Failed to send startup command:",ee)}))}},[U,ye,Ee,Ne]);const Sn=Or!==null&&Ee.has(Or),Ls=Or!==null&&Ne.has(Or);b.useEffect(()=>{Sn&&Nu("foreground-viewport-ready")},[Sn]),b.useEffect(()=>{Ls&&Nu("foreground-content-ready")},[Ls]),b.useEffect(()=>{if(!E)return;if(!Y&&U.length===0){E();return}if(!Sn||!fn||!Ls)return;const z=[...Kr].every(Qe=>Ee.has(Qe)&&ye.has(Qe)&&Ne.has(Qe));let N=0,$=0;const ee=()=>{N=requestAnimationFrame(()=>{$=requestAnimationFrame(()=>{Nu("initial-viewport-presented"),E()})})};z&&ee();const ie=z?void 0:window.setTimeout(ee,8e3);return()=>{cancelAnimationFrame(N),cancelAnimationFrame($),clearTimeout(ie)}},[fn,Ls,Sn,Y,E,U.length,Kr,Ee,ye,Ne]);const Zn=b.useMemo(()=>q?ME({slides:Br.map(z=>z.sessions.map(N=>N.id)),visibleSessionIds:Kr,foregroundSessionId:Or}):rt,[q,Br,Kr,Or,rt]);b.useEffect(()=>{if(q||Kr.size===0)return;const z=new Set(Kr),N=Br.findIndex($=>$.sessions.some(ee=>Kr.has(ee.id)));for(let $=-2;$<=2;$+=1)$!==0&&Br[N+$]?.sessions.forEach(ee=>z.add(ee.id));mt($=>{let ee=!1;const ie=new Set($);for(const Qe of z)ie.has(Qe)||(ie.add(Qe),ee=!0);return ee?ie:$})},[q,Kr,Br]);const sn=hC(Zn);b.useEffect(()=>{if(!ke)return;if(!U.some(N=>N.id===ke)){$e(null);return}if(!Ee.has(ke)||!ye.has(ke)||!Ne.has(ke))return;const z=window.setTimeout(()=>{$e(N=>N===ke?null:N),Nt.current&&!pr.current&&We({sessionId:ke,token:Date.now()})},80);return()=>window.clearTimeout(z)},[Ne,ke,ye,U,Ee]),b.useEffect(()=>{typeof window>"u"||(Te.length>0?(window.localStorage.setItem(d1,JSON.stringify(Te)),window.localStorage.removeItem(nv)):window.localStorage.removeItem(d1))},[Te]),b.useEffect(()=>{Rr||Y||Te.length===0||H(z=>uN(z,U.map(N=>N.id)))},[Rr,Y,U,Te.length]),b.useEffect(()=>{if(!Vt)return;const z=window.setTimeout(()=>jt(null),3200);return()=>window.clearTimeout(z)},[Vt]),nr.current=Z,cn.current=lt.token,Lr.current=U,Vr.current=wt,it.current=Rr,dt.current=Y,Nt.current=a;const on=b.useCallback((z=Ye.current)=>{const N=ge.current,$=typeof window<"u"?window.visualViewport:null,ee=z?h1(z):null,ie=z?vf(z,N):null;return{sessionsLength:Lr.current.length,workspaceSlidesLength:Mn.current.length,sessionIds:Lr.current.map(Qe=>Qe.id),activeSessionId:nr.current,activeSessionIndex:N,persistedActiveId:Vr.current,isLoading:it.current,isRestoring:dt.current,activeIndex:z?.activeIndex??null,previousIndex:z?.previousIndex??null,animating:z?.animating??null,allowTouchMove:z?.allowTouchMove??null,width:z?.width??null,translate:ee,targetTranslate:ie,translateDelta:ee!==null&&ie!==null?ee-ie:null,snapGridLength:z?.snapGrid?.length??null,targetSnap:z?.snapGrid?.[N]??null,visualViewport:$?{width:Math.round($.width),height:Math.round($.height),offsetTop:Math.round($.offsetTop)}:null}},[]),_r=b.useCallback((z,N)=>{W(z,{...on(),...N})},[W,on]);b.useEffect(()=>{Rr||Y||Z!==wt&&Ir(Z)},[Z,Rr,Y,wt,Ir]);const $r=b.useMemo(()=>{if(Wr.length===0||!Z)return 0;const z=Br.findIndex(N=>N.sessions.some($=>$.id===Z));return z>=0?z:0},[Br,Z]);ge.current=$r;const Wn=b.useCallback(()=>{It.current&&(clearTimeout(It.current),It.current=null)},[]),Gn=b.useCallback(z=>{Wn(),It.current=setTimeout(()=>{It.current=null,gt.current=!1,_r("[swiper:touch-guard-clear]",{reason:z})},mN)},[Wn,_r]),un=b.useCallback((z,N={})=>{const $=Ye.current,ee=ge.current,ie=Mn.current;if(!$||ie.length===0||ee<0||ee>=ie.length)return;if(gt.current){_r("[swiper:sync-skip-touch]",{reason:z});return}if($.animating){_r("[swiper:sync-skip-animating]",{reason:z});return}const Qe=h1($),ze=vf($,ee),xt=Qe!==null&&ze!==null&&Math.abs(Qe-ze)<=rv,_t=$.activeIndex===ee;if(_r("[swiper:sync-check]",{reason:z,activeIndexAligned:_t,translateAligned:xt,immediate:N.immediate===!0}),!(_t&&xt)){if(_t){vh($,ee),_r("[swiper:sync-forced-active]",{reason:z,translateAligned:xt,immediate:N.immediate===!0});return}N.immediate?(vh($,ee),$.slideTo(ee,0,!1),vh($,ee)):$.slideTo(ee,u1,!1),_r("[swiper:sync-applied]",{reason:z,activeIndexAligned:_t,translateAligned:xt,immediate:N.immediate===!0})}},[_r]);b.useEffect(()=>{const z=N=>{const $=N;Ye.current&&(Ye.current.allowTouchMove=!$.detail.locked),_r("[swiper:gesture-lock]",{locked:$.detail.locked})};return document.addEventListener("termdock:gesture-lock",z),()=>document.removeEventListener("termdock:gesture-lock",z)},[_r]),b.useEffect(()=>{if(U.length===0){Z!==null&&Cr(null);return}if(!Z){if(!p)return;Cr(bh({prioritySessionId:Fr,activeSessionId:null,persistedActiveSessionId:ks,firstSessionId:U[0]?.id??null}));return}U.some(N=>N.id===Z)||Cr(U[0].id)},[U,Z,p,Fr,ks]);const Kn=b.useCallback((z,N)=>{if(N&&Date.now()<an.current){st.current[z]=!1;return}st.current[z]=N,Ct($=>N?z:$===z?null:$)},[]),kr=b.useCallback(z=>{if(!gt.current&&z.activeIndex!==ge.current){_r("[swiper:slide-change-ignored-layout]",{instanceActiveIndex:z.activeIndex,expectedActiveIndex:ge.current}),requestAnimationFrame(()=>un("ignored-layout-slide-change",{immediate:!0}));return}const N=Mn.current[z.activeIndex],$=N?.sessions.some(Qe=>Qe.id===Z)?Z:N?.sessions[0]?.id;if(_r("[swiper:slide-change]",{nextSessionId:$??null,instanceActiveIndex:z.activeIndex}),!$||$===Z)return;const ee=!!Z&&st.current[Z]===!0,ie=Nt.current&&(!pr.current||ee);if(yt.current=$,Cr($),ie){We({sessionId:$,token:Date.now()});return}We(null)},[U,Z,_r,un]);b.useLayoutEffect(()=>{if(yt.current===Z){_r("[swiper:sync-skip-swiper-driven]",{activeSessionId:Z}),yt.current=null;return}un("active-session-index",{immediate:!0})},[Z,$r,U.length,un,_r]),b.useEffect(()=>{const z=Ye.current;if(!z)return;const N=Br.length>1&&!hn&&!oe;z.allowTouchMove!==N&&(z.allowTouchMove=N,_r("[swiper:allow-touch-sync]",{nextAllow:N,sidebarOverlayOpen:hn}))},[Br.length,_r,hn,oe]);const Er=b.useCallback(z=>{const N=Ye.current;if(!N)return;const $=N.el;if(_r("[swiper:layout-before]",{reason:z,scrollLeft:$?.scrollLeft??null}),$&&($.scrollLeft=0),N.updateSize(),N.updateSlides(),N.updateProgress(),N.updateSlidesClasses(),$&&($.scrollLeft=0),_r("[swiper:layout-after]",{reason:z,scrollLeft:$?.scrollLeft??null}),gt.current||N.animating){_r("[swiper:layout-skip-sync-motion]",{reason:z});return}un(`layout:${z}`,{immediate:!0}),requestAnimationFrame(()=>{const ee=Ye.current;ee&&(gt.current||ee.animating||vh(ee,ge.current))})},[_r,un]);b.useEffect(()=>()=>Wn(),[Wn]);const gr=Br.map(z=>z.key).join("\0");b.useEffect(()=>{requestAnimationFrame(()=>Er("group-change"))},[dr,gr,Er]),b.useEffect(()=>{let z=null,N="mount";const $=xt=>{N=xt,z===null&&(z=requestAnimationFrame(()=>{z=null,Er(`viewport-change:${N}`)}))},ee=()=>$("window-resize"),ie=()=>$("visual-viewport-resize"),Qe=()=>$("visual-viewport-scroll"),ze=xt=>{$(`measured:${xt.detail?.source??"unknown"}`)};return window.addEventListener("resize",ee),window.visualViewport?.addEventListener("resize",ie),window.visualViewport?.addEventListener("scroll",Qe),document.addEventListener(n2,ze),$("mount"),()=>{window.removeEventListener("resize",ee),window.visualViewport?.removeEventListener("resize",ie),window.visualViewport?.removeEventListener("scroll",Qe),document.removeEventListener(n2,ze),z!==null&&cancelAnimationFrame(z)}},[Er]),b.useEffect(()=>{if(typeof document>"u")return;let z=null,N=null;const $=_t=>{if(_t!=="online"&&document.hidden)return;const Mr=performance.now();if(!UE(N,Mr))return;N=Mr;const Dt=_t==="bfcache"||_t==="online"?_t:"visibility",Gr=zE();wp(),_a("info","PWA_RESUME scheduled",{source:_t,forceForegroundReconnect:Gr,activeSessionId:nr.current}),Se(dn=>({token:dn.token+1,reason:Dt,forceForegroundReconnect:Gr})),requestAnimationFrame(()=>Er(`resume:${_t}:raf`)),z&&clearTimeout(z),z=setTimeout(()=>{z=null,Er(`resume:${_t}:settled`)},320)},ee=()=>{if(document.hidden){wp();return}$("visibility")},ie=()=>{wp()},Qe=_t=>{$(_t.persisted?"bfcache":"pageshow")},ze=()=>$("online"),xt=()=>$("focus");return document.addEventListener("visibilitychange",ee),window.addEventListener("pagehide",ie),window.addEventListener("pageshow",Qe),window.addEventListener("online",ze),window.addEventListener("focus",xt),()=>{document.removeEventListener("visibilitychange",ee),window.removeEventListener("pagehide",ie),window.removeEventListener("pageshow",Qe),window.removeEventListener("online",ze),window.removeEventListener("focus",xt),z&&clearTimeout(z)}},[Er]),b.useLayoutEffect(()=>{if(!OE(Y))return;const z=wN(U),N=JSON.stringify(z);z.length>0&&N!==xn.current?(xn.current=N,console.warn("[session-invariant] duplicate mapping detected",z)):z.length===0&&xn.current&&(xn.current=""),L?.({sessions:U.map($=>({id:$.id,name:$.name,customName:$.customName,mode:$.mode,tmuxSessionName:$.tmuxSessionName})),activeSessionId:Z,splitWorkspaces:Te.map(({id:$,name:ee,sessionIds:ie,layout:Qe})=>({id:$,...ee?{name:ee}:{},sessionIds:ie,layout:Qe}))})},[U,Z,Te,L,Y]),b.useEffect(()=>{if(Rr||ue.current)return;ue.current=!0;const z=Jp(Me.map(Qe=>({id:Qe.sessionId,backendSessionId:Qe.backendSessionId??null})),d),N=Vx(Me,wt),$=bh({prioritySessionId:p?z:null,activeSessionId:null,persistedActiveSessionId:N,firstSessionId:Me[0]?.sessionId??null}),ee=sv(Me.map(iv));if(W("[Session] Restoring",ee.length,"persisted sessions (one-shot)"),_r("[swiper:restore-start]",{persistedSessionIds:Me.map(Qe=>Qe.sessionId),nextActiveSessionId:$}),ee.length>0){const Qe=Yr.getState();ee.forEach(xt=>{xt.sessionId&&Qe.setTerminalSession(xt.id,{sessionId:xt.sessionId,cols:80,rows:24,mode:xt.mode,tmuxSessionName:xt.tmuxSessionName,history:xt.history})}),Me.forEach(xt=>{xt.agent!==void 0&&Qe.setSessionAgentIdentity(xt.sessionId,xt.agent),xt.activeProgram!=null&&Qe.setSessionActiveProgram(xt.sessionId,xt.activeProgram),xt.cwd!=null&&Qe.setSessionCwd(xt.sessionId,xt.cwd),xt.shellTitle!=null&&Qe.setSessionShellTitle(xt.sessionId,xt.shellTitle)}),V(ee);const ze=$||ee[0]?.id||null;Cr(ze),_r("[swiper:restore-complete]",{restoredSessionIds:ee.map(xt=>xt.id),nextActiveSessionId:ze})}(async()=>(ee.length===0&&await sr.current?.({createIfEmpty:!0}),Ae(!1),requestAnimationFrame(()=>un("restore-finished",{immediate:!0}))))()},[Rr,Me,wt,W,_r,un,p,d]),b.useEffect(()=>{if(!p||Y||U.length===0)return;const z=Jp(U.map($=>({id:$.id,backendSessionId:$.sessionId})),d),N=bh({prioritySessionId:z,activeSessionId:nr.current,persistedActiveSessionId:ks,firstSessionId:U[0]?.id??null});N&&N!==nr.current&&Cr(N)},[p,d,Y,ks,U]);const rs=b.useRef([]),$n=b.useRef(!1);nr.current=Z,b.useEffect(()=>{if(Y)return;const z=rs.current,N=Me,$=new Map(z.map(Dt=>[Dt.sessionId,Dt])),ee=Yr.getState();for(const Dt of N){const Gr=$.get(Dt.sessionId),dn=Yr.getState().sessions.get(Dt.sessionId);Dt.agent!==void 0&&JSON.stringify(Dt.agent)!==JSON.stringify(dn?.agent)&&(dn?.agent==null||JSON.stringify(Dt.agent)!==JSON.stringify(Gr?.agent))&&ee.setSessionAgentIdentity(Dt.sessionId,Dt.agent),Dt.activeProgram!=null&&Dt.activeProgram!==dn?.activeProgram&&(dn?.activeProgram==null||Dt.activeProgram!==Gr?.activeProgram)&&ee.setSessionActiveProgram(Dt.sessionId,Dt.activeProgram),Dt.cwd!=null&&Dt.cwd!==dn?.cwd&&(dn?.cwd==null||Dt.cwd!==Gr?.cwd)&&ee.setSessionCwd(Dt.sessionId,Dt.cwd),Dt.shellTitle!=null&&Dt.shellTitle!==dn?.shellTitle&&(dn?.shellTitle==null||Dt.shellTitle!==Gr?.shellTitle)&&ee.setSessionShellTitle(Dt.sessionId,Dt.shellTitle)}if(!$n.current){V(Dt=>Gx(Dt,N)),rs.current=N,$n.current=!0;return}const ie=new Set(z.map(Dt=>Dt.sessionId)),Qe=new Set(N.map(Dt=>Dt.sessionId)),ze=new Map(z.map(Dt=>[Dt.sessionId,Dt.name]));rs.current=N,V(Dt=>{const Gr=Gx(Dt,N);return(!nr.current||!Gr.some(dn=>dn.id===nr.current))&&Cr(Gr[0]?.id??null),Gr});const xt=N.filter(Dt=>!ie.has(Dt.sessionId)),_t=[...ie].filter(Dt=>!Qe.has(Dt)),Mr=N.filter(Dt=>ie.has(Dt.sessionId)&&ze.get(Dt.sessionId)!==Dt.name);(xt.length>0||_t.length>0||Mr.length>0)&&W("[Session] Synced persisted sessions:",{newSessionIds:xt.map(Dt=>Dt.sessionId),removedSessionIds:_t,renamedSessionIds:Mr.map(Dt=>Dt.sessionId),currentSessionIds:N.map(Dt=>Dt.sessionId)});for(const Dt of N){if(!Dt.backendSessionId)continue;Yr.getState().setTerminalSession(Dt.sessionId,{sessionId:Dt.backendSessionId,cols:80,rows:24,mode:Dt.mode,tmuxSessionName:Dt.tmuxSessionName})}},[Me,Y,W]);const kn=b.useCallback(async z=>{const N=++pe.current,$=xe.current,ee=()=>N===pe.current&&$===xe.current&&(z?.shouldActivate?.()??!0);try{const ie=Gt.getState(),Qe=Z?{rightOpen:ie.rightOpen,rightPinned:ie.rightPinned,rightSidebarWidth:ie.rightSidebarWidth,rightTab:ie.rightTab}:null,ze=z?.mode==="tmux"||z?.mode==="shell"?z.mode:c,xt=(z?.tmuxSessionName||"").trim(),_t=l.trim(),Mr=ze==="tmux"?xt||_t||SN():null,Dt=typeof z?.cwd=="string"?z.cwd:null,Gr=Z?Yr.getState().sessions.get(Z)?.cwd??null:null,dn=typeof Dt=="string"&&Dt.trim().length>0?Dt:typeof Gr=="string"&&Gr.trim().length>0?Gr:void 0,jn=await rn({preferredFrontendSessionId:z?.preferredFrontendSessionId,requireExisting:z?.requireExisting===!0,mode:ze,tmuxSessionName:Mr,cwd:dn,termType:"xterm-256color",createIfEmpty:z?.createIfEmpty===!0},{shouldActivate:ee});if(jn.discarded)return z?.onResult?.({ok:!1,error:"unknown"}),null;const ns=jn.session,Un=jn.terminalSession;!jn.reused&&Qe&&Gt.getState().initializeRightSidebarForSession(ns.sessionId,Un.cwd??dn??null,Qe);const fr={id:ns.sessionId,name:ns.name,customName:ns.customName===!0,sessionId:Un.sessionId,mode:Un.mode??ns.mode,tmuxSessionName:Un.tmuxSessionName??ns.tmuxSessionName},Mt=z?.command?.trim();return Mt&&He.current.set(fr.id,{backendSessionId:Un.sessionId,command:Mt}),V(Vn=>AN(Vn,fr)),ee()&&Cr(fr.id),Yr.getState().setTerminalSession(fr.id,{sessionId:Un.sessionId,cols:80,rows:24,mode:fr.mode,tmuxSessionName:fr.tmuxSessionName,activeProgram:Un.activeProgram,activeProgramRaw:Un.activeProgramRaw,activeProgramSource:Un.activeProgramSource,cwd:Un.cwd}),W("[Session] Inventory opened session:",{frontendSessionId:fr.id,backendSessionId:Un.sessionId,reused:jn.reused,mode:fr.mode,tmuxSessionName:fr.tmuxSessionName}),z?.onResult?.({ok:!0,sessionId:fr.id}),fr.id}catch(ie){return console.error("[Session] Failed to create new session:",ie),z?.onResult?.({ok:!1,error:eC(ie)}),null}},[c,l,Z,rn,W]);sr.current=kn;const Ln=b.useCallback((z,N={})=>{xe.current+=1,es.getState().setActivePane(z);const $=nr.current,ee=!!$&&st.current[$]===!0;if(Cr(z),pr.current&&N.preserveMobileKeyboard===!1){an.current=Date.now()+600,$&&(st.current[$]=!1),Ct(null),We(null);const ie=document.activeElement;ie instanceof HTMLTextAreaElement&&ie.closest(".terminal-viewport-container")&&ie.blur();return}ee&&pr.current&&Ct(z),Nt.current&&(!pr.current||ee)&&We({sessionId:z,token:Date.now()})},[]),ps=b.useCallback(z=>{Cr(z),Ze(!0),jt(null)},[]),G=b.useCallback(z=>{const N=nr.current;!N||N===z||(H($=>tm($,N,z)),Ze(!1),Ln(N,{preserveMobileKeyboard:!1}))},[Ln]),Le=b.useCallback(async()=>{const z=nr.current;if(!z||Ge)return;const N=xe.current;pt(!0);const $=Yr.getState().sessions.get(z)?.cwd??void 0,ee=await kn({cwd:$||void 0,mode:c,shouldActivate:()=>!1});if(pt(!1),!ee){jt(B("common.error"));return}!St.current||N!==xe.current||!Lr.current.some(ie=>ie.id===z)||(H(ie=>tm(ie,z,ee)),Ze(!1),Ln(z,{preserveMobileKeyboard:!1}))},[Ln,c,kn,Ge,B]),Ke=b.useCallback(z=>{H(N=>hN(N,z)),z&&Ln(z,{preserveMobileKeyboard:!1})},[Ln]),ct=b.useCallback(z=>{H(N=>dN(N,z)),Ln(z,{preserveMobileKeyboard:!1})},[Ln]),qe=b.useCallback(z=>{if(U.find($=>$.id===z)){if(xe.current+=1,es.getState().setActivePane(z),z===nr.current)return;if(Cr(z),!BE({isMobile:pr.current,viewportReady:Ee.has(z),streamReady:ye.has(z),contentReady:Ne.has(z)})){$e(null),Nt.current&&We({sessionId:z,token:Date.now()}),W("[Session] Switched to session:",z);return}mt(ee=>{if(ee.has(z))return ee;const ie=new Set(ee);return ie.add(z),ie}),$e(z),W("[Session] Switched to session:",z)}},[Ne,W,ye,U,Ee]),At=b.useCallback((z,N)=>{N.trim()&&(V($=>$.map(ee=>ee.id===z?{...ee,name:N.trim(),customName:!0}:ee)),ht(z,N.trim()))},[ht]),Rt=b.useCallback(z=>{V(N=>N.map($=>$.id===z?{...$,customName:!1}:$)),Ht(z)},[Ht]),Bt=b.useCallback(z=>{V(N=>{const $=new Map(N.map(ze=>[ze.id,ze])),ee=z.map(ze=>$.get(ze)).filter(ze=>ze!==void 0),ie=new Set(z),Qe=N.filter(ze=>!ie.has(ze.id));return[...ee,...Qe]}),Ot(z),W("[Session] Reordered sessions:",z),requestAnimationFrame(()=>{Ye.current?.update()})},[Ot,W]),ot=b.useCallback(async z=>{const N=typeof z=="string"?z:z.sessionId,$=typeof z=="string"?"auto":z.closeMode??"auto",ee=U.find(xt=>xt.id===N);if(!ee||Pt.current.has(N))return;Pt.current.add(N),xe.current+=1;const ie=s2(Wr,N,xt=>xt.id);try{$==="destroy"&&ee.mode==="tmux"&&ee.tmuxSessionName?(await yy(ee.tmuxSessionName),W("[Session] Destroyed tmux session:",{frontendSessionId:ee.id,tmuxSessionName:ee.tmuxSessionName})):ee.sessionId&&(await my(ee.sessionId),W("[Session] Closed backend terminal:",ee.sessionId))}catch(xt){console.error("[Session] Failed to close backend terminal:",xt),Zt({sessionId:N,closeMode:$});return}finally{Pt.current.delete(N)}Zt(xt=>xt?.sessionId===N?null:xt);const ze=Lr.current.filter(xt=>xt.id!==N).some(xt=>xt.id===ie)?ie:s2(Lr.current,N,xt=>xt.id);nr.current===N&&Cr(ze),V(xt=>xt.filter(_t=>_t.id!==N)),ne(N,ze),delete st.current[N],W("[Session] Closed session:",{sessionId:N,closeMode:$})},[U,Wr,ne,W]),Ft=b.useCallback(z=>{if(!z)return;const N=U.filter($=>$.sessionId===z);if(N.length!==0){N.length>1&&console.warn("[session-invariant] backend matched multiple frontend sessions during cleanup",{backendSessionId:z,frontendSessionIds:N.map($=>$.id)}),V($=>{const ee=$.filter(ie=>ie.sessionId!==z);return ee.length!==$.length&&!ee.some(Qe=>Qe.id===Z)&&Cr(ee.length>0?ee[0].id:null),ee});for(const $ of N)ne($.id),delete st.current[$.id];W("[Session] Backend gone, dropped local session(s):",N.map($=>$.id))}},[U,Z,ne,W]);b.useEffect(()=>{const z=fr=>{kn(fr.detail)},N=fr=>{qe(fr.detail)},$=()=>{const fr=nr.current;!fr||pr.current||We({sessionId:fr,token:Date.now()})},ee=fr=>{const Mt=fr;Mt.detail&&ps(Mt.detail)},ie=fr=>{const Mt=fr.detail;Ke(Mt??nr.current??void 0)},Qe=fr=>{const Mt=fr.detail;Mt&&ct(Mt)},ze=fr=>{const Mt=fr.detail,Dn=typeof Mt=="string"?Mt:Mt?.layout,Vn=typeof Mt=="string"?nr.current:Mt?.sessionId;Dn!=="horizontal"&&Dn!=="vertical"&&Dn!=="grid"||H(Ha=>Ha.map(Bn=>Bn.sessionIds.includes(Vn??"")?{...Bn,layout:Dn}:Bn))},xt=fr=>{const Dn=fr.detail?.direction;if(Dn!=="prev"&&Dn!=="next")return;const Vn=fs.current;if(Vn.length<=1)return;const Ha=nr.current,Bn=Ha?Vn.findIndex(Wa=>Wa.id===Ha):-1,ua=((Bn>=0?Bn:0)+(Dn==="next"?1:-1)+Vn.length)%Vn.length,bs=Vn[ua]?.id;bs&&bs!==Ha&&qe(bs)},_t=fr=>{ot(fr.detail)},Mr=fr=>{Ft(fr.detail)},Dt=fr=>{const Mt=fr;!Mt.detail?.sessionId||!Mt.detail?.name||At(Mt.detail.sessionId,Mt.detail.name)},Gr=fr=>{const Mt=fr;Mt.detail?.sessionId&&Rt(Mt.detail.sessionId)},dn=fr=>{const Mt=fr;Mt.detail?.sessionIds&&Bt(Mt.detail.sessionIds)},jn=fr=>{const Mt=fr.detail;!Mt?.workspaceId||!Array.isArray(Mt.sessionIds)||H(Dn=>fN(Dn,Mt.workspaceId,Mt.sessionIds))},ns=fr=>{const Mt=fr.detail;!Mt?.workspaceId||typeof Mt.name!="string"||H(Dn=>pN(Dn,Mt.workspaceId,Mt.name))},Un=fr=>{const Mt=fr.detail;!Mt?.primaryId||!Mt.secondaryId||Mt.primaryId===Mt.secondaryId||(H(Dn=>tm(Dn,Mt.primaryId,Mt.secondaryId)),Ln(Mt.primaryId,{preserveMobileKeyboard:!1}))};return window.addEventListener("new-terminal-session",z),window.addEventListener("switch-terminal-session",N),window.addEventListener("focus-active-terminal-session",$),window.addEventListener("open-terminal-split-chooser",ee),window.addEventListener("close-terminal-split",ie),window.addEventListener("remove-terminal-split-pane",Qe),window.addEventListener("set-terminal-split-direction",ze),window.addEventListener("cycle-terminal-session",xt),window.addEventListener("close-terminal-session",_t),window.addEventListener("close-terminal-session-by-backend",Mr),window.addEventListener("rename-terminal-session",Dt),window.addEventListener("reset-terminal-session-name",Gr),window.addEventListener("reorder-terminal-session",dn),window.addEventListener("reorder-terminal-split-workspace",jn),window.addEventListener("rename-terminal-split-workspace",ns),window.addEventListener("combine-terminal-split-sessions",Un),()=>{window.removeEventListener("new-terminal-session",z),window.removeEventListener("switch-terminal-session",N),window.removeEventListener("focus-active-terminal-session",$),window.removeEventListener("open-terminal-split-chooser",ee),window.removeEventListener("close-terminal-split",ie),window.removeEventListener("remove-terminal-split-pane",Qe),window.removeEventListener("set-terminal-split-direction",ze),window.removeEventListener("cycle-terminal-session",xt),window.removeEventListener("close-terminal-session",_t),window.removeEventListener("close-terminal-session-by-backend",Mr),window.removeEventListener("rename-terminal-session",Dt),window.removeEventListener("reset-terminal-session-name",Gr),window.removeEventListener("reorder-terminal-session",dn),window.removeEventListener("reorder-terminal-split-workspace",jn),window.removeEventListener("rename-terminal-split-workspace",ns),window.removeEventListener("combine-terminal-split-sessions",Un)}},[Ln,kn,qe,ps,Ke,ct,ot,Ft,At,Rt,Bt]),b.useEffect(()=>{if(!Sr||q)return;const z=N=>{if(!fC(N,D1())||!(N.ctrlKey||N.metaKey)||!N.shiftKey)return;if(Sr.layout==="horizontal"?N.key==="ArrowLeft"||N.key==="ArrowRight":Sr.layout==="vertical"?N.key==="ArrowUp"||N.key==="ArrowDown":N.key.startsWith("Arrow")){N.preventDefault(),N.stopPropagation();const ee=Sr.sessionIds.indexOf(nr.current??""),ie=N.key==="ArrowLeft"||N.key==="ArrowUp"?-1:1,Qe=(Math.max(0,ee)+ie+Sr.sessionIds.length)%Sr.sessionIds.length,ze=Sr.sessionIds[Qe];if(!ze)return;Ln(ze);return}N.key==="Backspace"&&(N.preventDefault(),N.stopPropagation(),Ke(nr.current??void 0))};return window.addEventListener("keydown",z,!0),()=>window.removeEventListener("keydown",z,!0)},[Ln,Sr,Ke,q]);const hr=z=>{const N=Yr.getState().sessions.get(z.id);return il(z,N?.activeProgram??null,N?.cwd??null,void 0,N?.shellTitle??null,N?.promptState??null)},Kt=(z,N={})=>{const $=z.id===Z&&!te?.startsWith("@collaboration:"),ee=Kr.has(z.id)&&!N.hidden,ie=p&&DE({sessionId:z.id,foregroundSessionId:Or,visibleSessionIds:Kr,deferredViewportSessionIds:q?sn:Zn}),Qe=jE({sessionId:z.id,foregroundSessionId:Or,foregroundReady:fn,isVisible:ee})&&p,ze=FE({sessionId:z.id,foregroundSessionId:Or,requestToken:lt.token,foregroundCompletedToken:Et,isVisible:K.has(z.id)})&&p,xt=ee||z.id===Or||Zn.has(z.id)?0:Xr.get(z.id)??Vh;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:()=>{ee&&Hx($,()=>Ln(z.id))},onWheelCapture:()=>{Hx($,()=>Ln(z.id))},children:[N.showPaneTitle&&s.jsx(iN,{session:z,active:$,onActivate:()=>Ln(z.id),onToggleRightSidebar:$?x:void 0}),s.jsx("div",{className:"min-h-0 flex-1 app-chrome-bg",children:ie&&s.jsx(sN,{sessionId:z.id,mode:z.mode,tmuxSessionName:z.tmuxSessionName,terminalSettings:e,colorTheme:t,toolbarPresets:r,isActive:$,focusSuspended:ke!==null,deferCursorUntilPositioned:ke===z.id||z.mode==="tmux"&&!Ne.has(z.id),isLayoutVisible:ee,initialConnectEnabled:Qe&&ze,resumeRequestEnabled:ze,suppressKeyboard:N.suppressKeyboard,keyboardPortalTarget:N.keyboardPortalTarget,sharedMobileKeyboardLayout:N.sharedMobileKeyboardLayout,suppressPageFlipRefresh:N.suppressPageFlipRefresh,focusRequestToken:Ie?.sessionId===z.id?Ie.token:0,resumeRequestToken:lt.token,resumeRequestReason:lt.reason,forceResumeReconnect:lt.forceForegroundReconnect&&K.has(z.id),resumeRequestDelayMs:K.has(z.id)?0:N.hidden?Vh:Xr.get(z.id)??Vh,initialConnectDelayMs:xt,onStreamReadyChange:kt,onStreamConnected:tr,onViewportReadyChange:Qr,onContentReadyChange:cr,onKeyboardVisibilityChange:Kn,showDebug:n,onStatusChange:$?S:void 0})})]},z.id)};return s.jsxs("div",{className:"relative h-full flex flex-col",children:[vt&&U.some(z=>z.id===vt.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:U.find(z=>z.id===vt.sessionId).name})}),s.jsx("button",{type:"button",className:"shrink-0 rounded-lg px-2 py-1 text-primary hover:bg-surface-2",onClick:()=>{ot(vt)},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(Rn,{size:16})})]}),mr&&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(Q1,{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:mr.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:mr.sessions.map(z=>z.name).join(" · ")}),Lt&&s.jsx("p",{className:"mt-2 text-[10px] text-destructive",children:Lt}),s.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[s.jsxs("button",{type:"button",disabled:Xt!==null,onClick:()=>{Hr()},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(Qy,{size:13,className:Xt==="restore"?"animate-spin":""}),B(Xt==="restore"?"tab.tmuxRecoveryRestoring":"tab.tmuxRecoveryRestoreAll")]}),s.jsx("button",{type:"button",disabled:Xt!==null,onClick:()=>{_n()},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(lA,{onSwiper:z=>{Ye.current=z,z.allowTouchMove=Br.length>1&&!hn&&!oe,_r("[swiper:on-swiper]",{allowTouchMove:z.allowTouchMove}),requestAnimationFrame(()=>Er("on-swiper"))},onSlideChange:kr,onTouchStart:(z,N)=>{const $=qx(N),ee=$==="touch"||$==="pen"||$==="unknown";F("[swipe:touch-start]",{pointerType:$,allowed:ee}),_r("[swiper:touch-start]",{pointerType:$,allowed:ee}),ee&&(Wn(),bt.current=!0,gt.current=!0)},onTouchEnd:(z,N)=>{const $=qx(N),ee=$==="touch"||$==="pen"||$==="unknown";F("[swipe:touch-end]",{pointerType:$,allowed:ee}),_r("[swiper:touch-end]",{pointerType:$,allowed:ee}),ee&&(bt.current=!1,Gn("touch-end"))},onTransitionEnd:()=>{const z=Ye.current;if(bt.current){_r("[swiper:transition-end-during-touch]");return}if(gt.current&&z&&!vN(z,ge.current)){_r("[swiper:transition-end-deferred]");return}Wn(),gt.current=!1,_r("[swiper:transition-end]")},initialSlide:Math.max(0,$r),speed:u1,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:Br.map(z=>{const N=z.workspace,$=!!N&&z.sessions.length>=2,ee=q?qt?"horizontal":"vertical":N?.layout??"horizontal",ie=q&&et?z.sessions.some(ze=>ze.id===et):!1,Qe=z.sessions.some(ze=>ze.id===Z)?Z:z.sessions[0]?.id;return s.jsx(cA,{className:"h-full",children:s.jsx("div",{className:"h-full min-w-0","data-pinned-right-sidebar-inset":nn.get(z.key)??0,style:{paddingRight:nn.get(z.key)??0,paddingTop:y&&!$?"2.5rem":void 0},children:$?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(b2,{layoutId:z.key,preset:N?.layout??"horizontal",initialTree:aC(z.sessions.map(ze=>ze.id),ee,N?.ratios,N?.gridColumnRatios,N?.gridRowRatios),mobile:q,focusId:ie?et:null,panes:z.sessions.map(ze=>({id:ze.id,content:Kt(ze,{showPaneTitle:!q,suppressKeyboard:q&&ze.id!==Qe,keyboardPortalTarget:q?De:null,sharedMobileKeyboardLayout:q,suppressPageFlipRefresh:!0})}))}),q&&s.jsx("div",{ref:er,className:"relative shrink-0 app-chrome-bg","data-split-keyboard-host":"true"})]}):s.jsx(b2,{layoutId:z.key,preset:N?.layout??"horizontal",mobile:q,panes:[{id:z.sessions[0].id,content:Kt(z.sessions[0])}]})})},z.key)})})}),oe&&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:()=>Ze(!1),"aria-label":B("common.close")}),s.jsxs("section",{ref:Je,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:()=>Ze(!1),"aria-label":B("common.close"),children:s.jsx(Rn,{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:Ge,onClick:()=>{Le()},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(Us,{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")})]})]}),Te.filter(z=>z.id!==Sr?.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")}),Te.filter(z=>z.id!==Sr?.id).map((z,N)=>{const $=z.sessionIds.flatMap(Qe=>{const ze=U.find(xt=>xt.id===Qe);return ze?[ze]:[]});if($.length<2)return null;const ee=z.name||`${B("tab.splitWorkspace")} ${N+1}`,ie=$.map(Qe=>hr(Qe).primary).join(" · ");return s.jsxs("button",{type:"button",onClick:()=>G($[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:ee}),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:$.length})," · ",ie]})]}),s.jsx(hi,{size:14,className:"text-primary opacity-0 transition group-hover:opacity-100"})]},z.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")}),U.filter(z=>!Te.some(N=>N.sessionIds.includes(z.id))&&z.id!==Z).length===0&&Te.filter(z=>z.id!==Sr?.id).length===0?s.jsx("p",{className:"px-3 py-4 text-[12px] text-muted-foreground",children:B("tab.splitNoOtherSessions")}):U.filter(z=>!Te.some(N=>N.sessionIds.includes(z.id))&&z.id!==Z).map(z=>{const N=Pr.get(z.id)??null,$=hr(z);return s.jsxs("button",{type:"button",onClick:()=>G(z.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(Gc,{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:$.primary}),s.jsx("span",{className:"mt-0.5 block truncate text-[10px] text-muted-foreground",children:N?Yu(N)??N:z.name})]}),s.jsx(hi,{size:14,className:"text-primary opacity-0 transition group-hover:opacity-100"})]},z.id)})]})]})]}),Vt&&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:Vt})]})},_N={sm:"h-4 w-7",md:"h-6 w-10"},kN={sm:"h-3 w-3",md:"h-5 w-5"},LN={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 ${_N[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 ${kN[r]} ${e?LN[r]:""}`})})}function aa(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 IN=typeof Symbol=="function"&&Symbol.observable||"@@observable",Zx=IN,Kx=()=>Math.random().toString(36).substring(7).split("").join("."),EN={INIT:`@@redux/INIT${Kx()}`,REPLACE:`@@redux/REPLACE${Kx()}`},Xx=EN;function NN(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 av(e,t,r){if(typeof e!="function")throw new Error(aa(2));if(typeof t=="function"&&typeof r=="function"||typeof r=="function"&&typeof arguments[3]=="function")throw new Error(aa(0));if(typeof t=="function"&&typeof r>"u"&&(r=t,t=void 0),typeof r<"u"){if(typeof r!="function")throw new Error(aa(1));return r(av)(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(aa(3));return a}function y(E){if(typeof E!="function")throw new Error(aa(4));if(p)throw new Error(aa(5));let R=!0;m();const B=d++;return l.set(B,E),function(){if(R){if(p)throw new Error(aa(6));R=!1,m(),l.delete(B),c=null}}}function w(E){if(!NN(E))throw new Error(aa(7));if(typeof E.type>"u")throw new Error(aa(8));if(typeof E.type!="string")throw new Error(aa(17));if(p)throw new Error(aa(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(aa(10));n=E,w({type:Xx.REPLACE})}function S(){const E=y;return{subscribe(R){if(typeof R!="object"||R===null)throw new Error(aa(11));function B(){const F=R;F.next&&F.next(x())}return B(),{unsubscribe:E(B)}},[Zx](){return this}}}return w({type:Xx.INIT}),{dispatch:w,subscribe:y,getState:x,replaceReducer:v,[Zx]:S}}function Jx(e,t){return function(...r){return t(e.apply(this,r))}}function e5(e,t){if(typeof e=="function")return Jx(e,t);if(typeof e!="object"||e===null)throw new Error(aa(16));const r={};for(const n in e){const a=e[n];typeof a=="function"&&(r[n]=Jx(a,t))}return r}function ov(...e){return e.length===0?t=>t:e.length===1?e[0]:e.reduce((t,r)=>(...n)=>t(r(...n)))}function RN(...e){return t=>(r,n)=>{const a=t(r,n);let c=()=>{throw new Error(aa(15))};const l={getState:a.getState,dispatch:(p,...m)=>c(p,...m)},d=e.map(p=>p(l));return c=ov(...d)(a.dispatch),{...a,dispatch:c}}}var nm={exports:{}},sm={};var t5;function MN(){if(t5)return sm;t5=1;var e=wA();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 sm.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(U){if(!R){if(R=!0,B=U,U=y(U),w!==void 0&&S.hasValue){var V=S.value;if(w(V,U))return W=V}return W=U}if(V=W,r(B,U))return V;var Z=y(U);return w!==void 0&&w(V,Z)?(B=U,V):(B=U,W=Z)}var R=!1,B,W,F=x===void 0?null:x;return[function(){return E(m())},F===null?void 0:function(){return E(F())}]},[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},sm}var r5;function jN(){return r5||(r5=1,nm.exports=MN()),nm.exports}jN();var DN=b.version.startsWith("19"),BN=Symbol.for(DN?"react.transitional.element":"react.element"),QN=Symbol.for("react.portal"),PN=Symbol.for("react.fragment"),ON=Symbol.for("react.strict_mode"),FN=Symbol.for("react.profiler"),$N=Symbol.for("react.consumer"),UN=Symbol.for("react.context"),lv=Symbol.for("react.forward_ref"),zN=Symbol.for("react.suspense"),HN=Symbol.for("react.suspense_list"),rg=Symbol.for("react.memo"),WN=Symbol.for("react.lazy"),GN=lv,VN=rg;function qN(e){if(typeof e=="object"&&e!==null){const{$$typeof:t}=e;switch(t){case BN:switch(e=e.type,e){case PN:case FN:case ON:case zN:case HN:return e;default:switch(e=e&&e.$$typeof,e){case UN:case lv:case WN:case rg:return e;case $N:return e;default:return t}}case QN:return t}}}function YN(e){return qN(e)===rg}function ZN(e,t,r,n,{areStatesEqual:a,areOwnPropsEqual:c,areStatePropsEqual:l}){let d=!1,p,m,x,y,w;function v(B,W){return p=B,m=W,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),W=!l(B,x);return x=B,W&&(w=r(x,y,m)),w}function R(B,W){const F=!c(W,m),U=!a(B,p,W,m);return p=B,m=W,F&&U?S():F?L():U?E():w}return function(W,F){return d?R(W,F):v(W,F)}}function KN(e,{initMapStateToProps:t,initMapDispatchToProps:r,initMergeProps:n,...a}){const c=t(e,a),l=r(e,a),d=n(e,a);return ZN(c,l,d,e,a)}function XN(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 f1(e){return function(r){const n=e(r);function a(){return n}return a.dependsOnOwnProps=!1,a}}function n5(e){return e.dependsOnOwnProps?!!e.dependsOnOwnProps:e.length!==1}function cv(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=n5(e);let m=c(d,p);return typeof m=="function"&&(c.mapToProps=m,c.dependsOnOwnProps=n5(m),m=c(d,p)),m},c}}function ng(e,t){return(r,n)=>{throw new Error(`Invalid value of type ${typeof e} for ${t} argument when connecting component ${n.wrappedComponentName}.`)}}function JN(e){return e&&typeof e=="object"?f1(t=>XN(e,t)):e?typeof e=="function"?cv(e):ng(e,"mapDispatchToProps"):f1(t=>({dispatch:t}))}function eR(e){return e?typeof e=="function"?cv(e):ng(e,"mapStateToProps"):f1(()=>({}))}function tR(e,t,r){return{...r,...e,...t}}function rR(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 nR(e){return e?typeof e=="function"?rR(e):ng(e,"mergeProps"):()=>tR}function sR(e){e()}function iR(){let e=null,t=null;return{clear(){e=null,t=null},notify(){sR(()=>{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 s5={notify(){},get:()=>[]};function uv(e,t){let r,n=s5,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=iR())}function y(){a--,r&&a===0&&(r(),r=void 0,n.clear(),n=s5)}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 aR=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",oR=aR(),lR=()=>typeof navigator<"u"&&navigator.product==="ReactNative",cR=lR(),uR=()=>oR||cR?b.useLayoutEffect:b.useEffect,wf=uR();function i5(e,t){return e===t?e!==0||t!==0||1/e===1/t:e!==e&&t!==t}function im(e,t){if(i5(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])||!i5(e[r[a]],t[r[a]]))return!1;return!0}var dR={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},hR={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},fR={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},dv={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},pR={[GN]:fR,[VN]:dv};function a5(e){return YN(e)?dv:pR[e.$$typeof]||dR}var mR=Object.defineProperty,gR=Object.getOwnPropertyNames,o5=Object.getOwnPropertySymbols,xR=Object.getOwnPropertyDescriptor,bR=Object.getPrototypeOf,l5=Object.prototype;function p1(e,t){if(typeof t!="string"){if(l5){const c=bR(t);c&&c!==l5&&p1(e,c)}let r=gR(t);o5&&(r=r.concat(o5(t)));const n=a5(e),a=a5(t);for(let c=0;c<r.length;++c){const l=r[c];if(!hR[l]&&!(a&&a[l])&&!(n&&n[l])){const d=xR(t,l);try{mR(e,l,d)}catch{}}}}return e}var yR=Symbol.for("react-redux-context"),vR=typeof globalThis<"u"?globalThis:{};function wR(){if(!b.createContext)return{};const e=vR[yR]??=new Map;let t=e.get(b.createContext);return t||(t=b.createContext(null),e.set(b.createContext,t)),t}var hv=wR(),AR=[null,null];function TR(e,t,r){wf(()=>e(...t),r)}function SR(e,t,r,n,a,c){e.current=n,r.current=!1,a.current&&(a.current=null,c())}function CR(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 _R(e,t){return e===t}function kR(e,t,r,{pure:n,areStatesEqual:a=_R,areOwnPropsEqual:c=im,areStatePropsEqual:l=im,areMergedPropsEqual:d=im,forwardRef:p=!1,context:m=hv}={}){const x=m,y=eR(e),w=JN(t),v=nR(r),S=!!e;return E=>{const R=E.displayName||E.name||"Component",B=`Connect(${R})`,W={shouldHandleStateChanges:S,displayName:B,wrappedComponentName:R,WrappedComponent:E,initMapStateToProps:y,initMapDispatchToProps:w,initMergeProps:v,areStatesEqual:a,areStatePropsEqual:l,areOwnPropsEqual:c,areMergedPropsEqual:d};function F(Z){const[ce,xe,pe]=b.useMemo(()=>{const{reactReduxForwardedRef:Ye,...st}=Z;return[Z.context,Ye,st]},[Z]),te=b.useMemo(()=>{let Ye=x;return ce?.Consumer,Ye},[ce,x]),ke=b.useContext(te),$e=!!Z.store&&!!Z.store.getState&&!!Z.store.dispatch,Y=!!ke&&!!ke.store,Ae=$e?Z.store:ke.store,lt=Y?ke.getServerState:Ae.getState,Se=b.useMemo(()=>KN(Ae.dispatch,W),[Ae]),[ye,_e]=b.useMemo(()=>{if(!S)return AR;const Ye=uv(Ae,$e?void 0:ke.subscription),st=Ye.notifyNestedSubs.bind(Ye);return[Ye,st]},[Ae,$e,ke]),je=b.useMemo(()=>$e?ke:{...ke,subscription:ye},[$e,ke,ye]),re=b.useRef(void 0),Oe=b.useRef(pe),Ce=b.useRef(void 0),Ee=b.useRef(!1),Be=b.useRef(!1),Ne=b.useRef(void 0);wf(()=>(Be.current=!0,()=>{Be.current=!1}),[]);const le=b.useMemo(()=>()=>Ce.current&&pe===Oe.current?Ce.current:Se(Ae.getState(),pe),[Ae,pe]),He=b.useMemo(()=>st=>ye?CR(S,Ae,ye,Se,Oe,re,Ee,Be,Ce,_e,st):()=>{},[ye]);TR(SR,[Oe,re,Ee,pe,Ce,_e]);let rt;try{rt=b.useSyncExternalStore(He,le,lt?()=>Se(lt(),pe):le)}catch(Ye){throw Ne.current&&(Ye.message+=`
|
|
77
|
+
`),dr(fe),mr(fe,!1),kt("Terminal session ended"),oe(!1),cr(!1),sn(null),Wn(null),pn(fe,!1),as();break}}},onError:(O,fe)=>{if(Bt.current!==T)return;const we=Y;if(!we)return;z.current=!1,be.current=!1,oe(!1);const Pe=fe&&O.message==="Authentication required",Xe=Qx(O),ft=Pe?O.message:Xe||fe?"Reconnecting...":O.message||"Terminal stream connection error";console.error(`[Terminal] Stream error (fatal=${fe}):`,ft),Xe&&console.warn("[Terminal] SESSION_NOT_FOUND_DETECTED",{terminalIdAtError:kr.current,frontendSessionId:we,isActive:l,isMobile:Be,fatal:fe,stack:new Error().stack}),kt(ft),cr(!!fe),fe&&(sn(null),mr(we,!1),as(),Xe&&(ye("[onError] Session lost, auto-recreating"),kt("Reconnecting..."),cr(!1),dr(we),hn(we),kr.current=null,Ui.current=!1,is()))}},{...nN,getDimensions:()=>gr.current?.getDimensions()??null});un.current=()=>{Q.close(),Bt.current===T&&(Kn.current=null)},Kn.current=se},[Hr,hn,dr,ye,as,Vn,W,Ks,is,Wa,mr,Tn,Pr,pn,ir,Wr,Se,Y]);k.useEffect(()=>{const se=HE({isActive:l,isStreamReady:H,reconnectStartedAt:Zn,now:Date.now()});if(se===null)return;const T=window.setTimeout(()=>{ye("[Terminal] visible reconnect watchdog expired",{backendSessionId:kr.current,reconnectStartedAt:Zn}),as(),mr(Y,!1),kt("Reconnecting..."),cr(!1),sn(Date.now()),is()},se);return()=>window.clearTimeout(T)},[ye,as,l,H,Zn,is,Y,mr]);const Ui=k.useRef(!1),gi=k.useRef(!1),xi=k.useRef(0);k.useEffect(()=>()=>{xi.current+=1,Ui.current=!1,as()},[as]);const hl=k.useRef(K),Js=k.useRef(Ue);k.useEffect(()=>{const se=hl.current,T=Js.current;hl.current=K,Js.current=Ue,Er.current===Y&&(se===K&&T===Ue||(Ui.current=!1,as(),_r(j=>j+1)))},[K,Ue,as,Y]),k.useEffect(()=>{if(Er.current!==Y&&(ye(`[useEffect] sessionId changed from ${Er.current} to ${Y}, allowing reinitialization`),Ui.current=!1,gi.current=!1),Ui.current&&Er.current===Y){ye(`[useEffect] Already initialized for sessionId=${Y}, skipping`);return}if(!jt)return;const se=async fe=>{if(ye(`[ensureSession] Starting for sessionId=${Y}, runId=${fe}`),!Er.current||Er.current!==Y){ye(`[ensureSession] SessionId mismatch or stale run (current=${Er.current}, target=${Y}), skipping`);return}if(fe!==xi.current){ye(`[ensureSession] Stale run detected (runId=${fe}, currentRunId=${xi.current}), skipping`);return}const we=Yr.getState(),Pe=we.getTerminalSession(Y),Xe=Pe?.mode??K;ye("[ensureSession] Current state from store:",{terminalSessionId:Pe?.terminalSessionId,mode:Pe?.mode,tmuxSessionName:Pe?.tmuxSessionName,isConnecting:Pe?.isConnecting});let ft=Pe?.terminalSessionId??null,Jt=!ft;if(ft&&Xe!==K?(ye(`[ensureSession] Store mode mismatch for ${ft}: current=${Xe} desired=${K}, will create new session`),Jt=!0,we.clearTerminalSession(Y),ft=null):ft&&K==="tmux"&&Ue&&Pe?.tmuxSessionName!==Ue&&(ye(`[ensureSession] Store tmux name mismatch for ${ft}: current=${Pe?.tmuxSessionName} desired=${Ue}, will create new session`),Jt=!0,we.clearTerminalSession(Y),ft=null),ft&&Se.checkHealth&&!_t.current){ye(`[ensureSession] Checking health of existing session ${ft}`);try{const or=await Se.checkHealth(ft);if(ye("[ensureSession] Health check result:",or),!or.healthy)ye(`[ensureSession] Session ${ft} is NOT healthy (healthy=${or.healthy}), will create new session`),ye("[ensureSession] Health check details:",or),Jt=!0,or.mode&&Pe?.terminalSessionId&&we.setTerminalSession(Y,{sessionId:Pe.terminalSessionId,cols:80,rows:24,mode:or.mode,tmuxSessionName:or.tmuxSessionName??null}),we.clearTerminalSession(Y),ye("[ensureSession] Cleared unhealthy session from store");else{ye(`[ensureSession] Session ${ft} is healthy, reusing it, cwd=${or.cwd}, clients=${or.clients}, lastActivity=${Date.now()-(or.lastActivity||0)}ms ago`),or.mode&&Pe?.terminalSessionId&&we.setTerminalSession(Y,{sessionId:Pe.terminalSessionId,cols:80,rows:24,mode:or.mode,tmuxSessionName:or.tmuxSessionName??null}),ye(`[ensureSession] Setting terminalIdRef to ${ft} and starting stream`),kr.current=ft,Rs(ft),ye(`[ensureSession] Successfully reused healthy session ${ft}, returning early`);return}}catch(or){ye(`[ensureSession] Failed to check health of session ${ft}:`,or),ye("[ensureSession] Health check API call failed, proceeding as if session might be unhealthy")}}if(ye(`[ensureSession] Decision: shouldCreateNewSession=${Jt}, terminalId=${ft}`),Jt){ye(`[ensureSession] Creating new session, shouldCreateNewSession=${Jt}, runId=${fe}`),kt(null),cr(!1),we.setConnecting(Y,!0);const Ur=Yr.getState().getTerminalSession(Y),Qn=(Ur?.mode??K)===K&&(K!=="tmux"||!Ue||Ur?.tmuxSessionName===Ue);if(Ur?.terminalSessionId&&Qn)ye(`[ensureSession] Race condition avoided: another instance already created session ${Ur.terminalSessionId}`),we.setConnecting(Y,!1),ft=Ur.terminalSessionId,Jt=!1;else try{const vr=await zn();if(ye(`[ensureSession] Opened managed backend session ${vr.sessionId}`),fe!==xi.current){ye(`[ensureSession] Stale run after session creation (runId=${fe}, currentRunId=${xi.current}), leaving ${vr.sessionId} for sibling`);return}we.setTerminalSession(Y,vr),ye(`[ensureSession] Updated store with new session ${vr.sessionId}`),ft=vr.sessionId}catch(vr){if(fe!==xi.current){ye("[ensureSession] Stale run after session creation failed, skipping error handling");return}if(vr instanceof Jd&&o1(vr)){ye("[ensureSession] Confirmed missing persisted session:",{sessionId:Y,error:vr.message}),we.clearTerminalSession(Y),kt(qh),cr(!0),we.setConnecting(Y,!1);return}kt("Reconnecting..."),cr(!0),we.setConnecting(Y,!1);return}}if(fe!==xi.current){ye(`[ensureSession] Stale run before starting stream (runId=${fe}, currentRunId=${xi.current}), skipping`);return}if(!ft){ye(`[ensureSession] No terminalId, terminalId=${ft}`);return}ye(`[ensureSession] Starting stream for session ${ft}`),kr.current=ft,Rs(ft),ye(`[ensureSession] ensureSession completed for sessionId=${Y}, terminalId=${ft}`)};let T=null,j=null;const Q=()=>{j=null,!(Ui.current&&Er.current===Y)&&(ye(`[useEffect] Running ensureSession for sessionId=${Y}, hasInitialized=${Ui.current}`),Ui.current=!0,gi.current=!0,T=++xi.current,se(T))};if(!E&&!gi.current){ye(`[useEffect] Holding background connection until the selected session is ready: ${Y}`);return}const O=gi.current?0:Math.max(0,L);return O>0?(ye(`[useEffect] Delaying initial connection for sessionId=${Y} by ${O}ms`),j=window.setTimeout(Q,O)):Q(),()=>{j!==null&&window.clearTimeout(j),ye(`[useEffect] Cleanup for sessionId=${Y}, runId=${T??"pending"}`)}},[Y,on,Rs,as,Se,ye,K,Ue,Br,L,E,jt]);const Uo=k.useCallback(async()=>{if(Y&&!Sn){Ls(!0),kt(null),cr(!1),sn(null),as();try{Se.forceKill&&await Se.forceKill({sessionId:Y})}catch{}bn(Y),hn(Y),gr.current?.clear(),await new Promise(se=>setTimeout(se,100));try{mr(Y,!0);const se=await zn();Tr(Y,se),kr.current=se.sessionId,Rs(se.sessionId)}catch(se){kt(se instanceof Jd&&o1(se)?qh:"Reconnecting..."),cr(!0),mr(Y,!1)}finally{Ls(!1)}}},[Y,Sn,as,Se,bn,hn,mr,Tr,Rs,zn]),fa=k.useCallback((se,T,j,Q)=>{if(!(kr.current!==T||ot.current!==j)){if(se instanceof Jd&&Qx(se)){ye("[Terminal] operation backend missing, recovering",{terminalId:T,sessionId:Y}),kt("Reconnecting..."),cr(!1),as(),dr(Y),kr.current=null,mr(Y,!0),is();return}kt(se instanceof Error?se.message:Q)}},[dr,ye,as,is,Y,mr]),fl=k.useCallback((se,T)=>{const j=T?.ownedPaste?bC(T.ownedPaste,Y,se):!1;if(T?.ownedPaste&&!j||Dt.current||(Mr.current||D1())&&!j)return Promise.resolve(!1);const Q=()=>!!T?.ownedPaste&&yC(T.ownedPaste,Y)&&_t.current&&!Dt.current&&be.current&&!tr.current&&!document.hidden&&navigator.onLine!==!1&&Tu();if(j&&!Q())return Promise.resolve(!1);if(!_t.current&&!T?.targeted||!se)return;const O=hE(se),fe=/^(\x1b\[<6[45];[0-9]+;[0-9]+M)+$/.test(se);if(Fr&&fe&&(ps.current=!0),Date.now()<Ln.current)return;let we=se,Pe=T?.consumeModifier??!1;if(!T?.skipModifierTransform&&Lt&&se.length>0){const Ur=se[0];if(Ur.length===1&&/[a-zA-Z]/.test(Ur)){const Jr=Ur.toUpperCase();Lt==="ctrl"?(we=String.fromCharCode(Jr.charCodeAt(0)&31),Pe=!0):Lt==="alt"&&(we=`\x1B${se}`,Pe=!0)}Pe||(Lt==="alt"&&(we=`\x1B${se}`),Pe=!0)}const Xe=kr.current;if(!Xe)return;const ft=ot.current,or=(async()=>{try{if(Fr&&!O&&ps.current&&Se.tmuxAction){ps.current=!1;try{await Se.tmuxAction(Xe,{action:"copy-mode",enabled:!1})}catch{}if(kr.current!==Xe||ot.current!==ft)return!1;if(fE(we))return!0}return j&&(!Q()||kr.current!==Xe||ot.current!==ft)||(await Se.sendInput(Xe,we),j&&(!Q()||kr.current!==Xe||ot.current!==ft))?!1:(fs(Y),!0)}catch(Ur){return fa(Ur,Xe,ft,"Failed to send input"),!1}})();return Pe&&(Ge||me(null),ms()),or},[Lt,fs,ms,fa,Fr,Ge,Y,Se]);k.useEffect(()=>{const se=T=>{const j=T,Q=j.detail?.sessionId;if(Q?Q!==Y:!_t.current)return;const O=j.detail?.text;if(!O)return;const fe=j.detail?.nonce;if(tr.current||!gr.current){fe&&window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:fe,ok:!1}}));return}const we=xC(j.detail,Y),Pe=j.detail?.ownedPaste&&!we?Promise.resolve(!1):gr.current.sendSequence(O,{paste:j.detail?.paste,submitAfterPaste:j.detail?.submitAfterPaste,targeted:!!Q,ownedPaste:we??void 0});fe&&Promise.resolve(Pe).then(Xe=>{window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:fe,ok:Xe===!0}}))},()=>{window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:fe,ok:!1}}))}),WS(Gr.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){_e("xterm resize push skipped: no terminalId",{cols:se,rows:T});return}_e("xterm resize push",{cols:se,rows:T}),Se.resize({sessionId:Q,cols:se,rows:T,seq:j}).catch(O=>{gr.current?.acknowledgeResize({seq:j,ok:!1}),O&&/session not found/i.test(String(O.message||O))&&console.warn("[Terminal] resize 404 session not found",{sessionId:Q,cols:se,rows:T,stack:new Error().stack})})},[Se,_e]),os=k.useCallback(async se=>{const T=kr.current;if(!T||!Se.tmuxAction)return;const j=ot.current;try{const Q=await Se.tmuxAction(T,se);if(kr.current!==T||ot.current!==j)return;Q.layout&&(Wn(Q.layout),se.action==="switch-session"&&(Tr(Y,{sessionId:T,cols:80,rows:24,mode:"tmux",tmuxSessionName:Q.layout.sessionName}),gw(Y,{tmuxSessionName:Q.layout.sessionName}).catch(O=>{console.warn("[Terminal] failed to update inventory after tmux switch",O)})))}catch(Q){fa(Q,T,j,"Failed to execute tmux action")}},[fa,Y,Tr,Se]);k.useEffect(()=>{if(!$r||!Xr)return;const T=$r.windows.find(j=>j.id===$r.activeWindowId)?.panes.find(j=>j.id===$r.activePaneId);T&&gr.current?.requestRefresh("tmux-layout",{skipScrollToBottom:!0,dedupeKey:`${Xr}:${$r.sessionId}:${T.id}:${T.width}x${T.height}`})},[$r,Xr]);const Ms=k.useCallback((se,T=5)=>{const j=Math.max(1,Math.min(Math.floor(T)||1,40));ps.current=!0;const Q=G.current;if(Q&&Q.direction===se){Q.lines+=j;return}Q&&os({action:"scroll",direction:Q.direction,lines:Q.lines}).finally(()=>{ms()}),G.current={direction:se,lines:j},Le.current&&clearTimeout(Le.current),Le.current=setTimeout(()=>{const O=G.current;O&&(G.current=null,os({action:"scroll",direction:O.direction,lines:O.lines}).finally(()=>{ms()}))},0)},[ms,os]),Ni=k.useCallback(se=>{const T=Date.now(),j=ct.current,Q=j!==null&&j.modifier===se&&T-j.timestamp<=JE;if(ct.current={modifier:se,timestamp:T},Ge===se){pt(null),me(null);return}if(Q){pt(se),me(se);return}Ge!==null&&Ge!==se&&pt(null),me(O=>O===se?null:se)},[Ge]),zo=k.useCallback(se=>{if(Ye(se&&_t.current),_e("input focus changed",{focused:se,isActive:_t.current,isMobile:Gr.current}),!Gr.current||!_t.current){mt(!1);return}mt(T=>T===se?T:se)},[_e]),jl=k.useCallback(se=>{if(rs.current=se,Ks(se,"viewport-watermark"),!se&&kn.current.length>0){const T=Y;if(T){const j=kn.current;kn.current=[];for(const Q of j)Hr(T,Q)}}},[Hr,Ks,Y]),Es=k.useCallback(se=>{_t.current&&gr.current?.ensureSizeMatches(se)},[]),Ia=k.useRef(null);k.useEffect(()=>{if(!l)return;const se=Ia.current;if(!se)return;const T=()=>Es("pointerdown"),j=()=>Es("keydown"),Q=()=>Es("touchstart"),O=()=>Es("wheel");return se.addEventListener("pointerdown",T),se.addEventListener("keydown",j),se.addEventListener("touchstart",Q,{passive:!0}),se.addEventListener("wheel",O,{passive:!0}),()=>{se.removeEventListener("pointerdown",T),se.removeEventListener("keydown",j),se.removeEventListener("touchstart",Q),se.removeEventListener("wheel",O)}},[l,Es]);const ml=k.useCallback(se=>{gr.current=se},[]),Xn=k.useCallback(se=>{vt(se),F?.(Y,se)},[F,Y]),zi=k.useCallback(se=>{const T=wE(se);if(!T)return;const j=Lt!==null;gr.current?.sendSequence(T,{consumeModifier:j})},[Lt]),Ri=k.useCallback(se=>{const T=gE(se);if(T.length===0)return;const j=Lt!==null;gr.current?.sendSequence(Mx(T[0]),{consumeModifier:j});for(let Q=1;Q<T.length;Q+=1){const O=T[Q];window.setTimeout(()=>{gr.current?.sendSequence(Mx(O))},mE*Q)}},[Lt]),Hi=k.useCallback(()=>{gr.current?.pasteClipboardText()},[]),gs=k.useCallback(se=>{Mt.current!==null&&(window.clearTimeout(Mt.current),Mt.current=null),gt(se),(se==="inserted"||se==="failed")&&(Mt.current=window.setTimeout(()=>{Mt.current=null,gt("idle")},1400))},[]),Ws=k.useCallback(()=>{gs("idle"),It(0),Dn.current?.click()},[gs]),Dl=k.useCallback(()=>{rn(!0)},[]),Wi=k.useCallback(se=>{const T=se.currentTarget.files?.[0];if(se.currentTarget.value="",!T)return;const j=Y;Cr(null),pr(null),Lr(null),It(0),gs("uploading");const Q=sr&&T.type.startsWith("video/")?{maxHeight:xn,videoBitrate:an,onProgress:It}:null,O=Me&&tN(T)?{maxDimension:nt,quality:wt}:null;let fe=Q?"视频压缩":O?"图片压缩":"文件上传";(async()=>{const we=Q?await(await Oc(async()=>{const{compressVideoLocally:Pe}=await import("./videoCompression-DrQ47oZA.js");return{compressVideoLocally:Pe}},__vite__mapDeps([0,1,2,3,4,5]))).compressVideoLocally(T,Q):O?await(await Oc(async()=>{const{compressImageLocally:Pe}=await import("./imageCompression-DaUBNTq-.js");return{compressImageLocally:Pe}},[])).compressImageLocally(T,O):T;fe="文件上传",await ZE(we,(Pe,Xe)=>L0(Pe,Xe,void 0,It),Pe=>(fe="插入终端",Ox(l1(Pe,null),j,()=>_t.current&&!tr.current&&Er.current===j&&Yr.getState().activeSessionId===j))),(Q||O)&&Lr({file:we,kind:Q?"video":"image",originalSize:T.size,uploadedSize:we.size,originalRetained:we===T})})().then(()=>gs("inserted"),we=>{we instanceof yf&&Cr({path:we.uploaded.path,sessionId:j});const Pe=we instanceof yf?we.uploaded.path:zx(we);pr({stage:fe,detail:Pe}),rn(!0),gs("failed"),_a("warn","MOBILE_MEDIA_UPLOAD failed",{stage:fe,detail:Pe})})},[an,sr,xn,Me,nt,wt,Y,gs]),Gi=k.useCallback(async()=>{const se=nr;if(!se||se.sessionId!==Y)return;rn(!1),await new Promise(j=>window.requestAnimationFrame(()=>j())),gs("uploading"),await Ox(l1(se.path,null),se.sessionId,()=>_t.current&&!tr.current&&Er.current===se.sessionId&&Yr.getState().activeSessionId===se.sessionId)?(Cr(null),pr(null),gs("inserted")):(rn(!0),gs("failed"))},[nr,Y,gs]);k.useEffect(()=>{if(!Rr||!sr)return;let se=!0;return Ht(null),ne({phase:"checking-cache"}),Oc(async()=>{const{prepareLocalVideoCompression:T}=await import("./videoCompression-DrQ47oZA.js");return{prepareLocalVideoCompression:T}},__vite__mapDeps([0,1,2,3,4,5])).then(({prepareLocalVideoCompression:T})=>{if(se)return T(j=>{se&&ne(j)})}).catch(T=>{se&&Ht(zx(T))}),()=>{se=!1}},[Rr,sr]);const ln=Or||Et!==null;tr.current=ln;const pa=k.useRef(Kr);ln||(pa.current=Kr);const Vi=ln?pa.current:Kr,Ea=k.useMemo(()=>xE(Vi,nn),[Vi,nn]),Mi=k.useMemo(()=>Dx(nn,qt),[qt,nn]),ji=!Be&&qt!=="auto"&&Mi.id!=="default"&&Mi.showOnDesktop!==!0?"auto":qt,ei=ji==="auto"?Ea:ji,ws=k.useMemo(()=>Dx(nn,ei),[ei,nn]),Gs=k.useMemo(()=>ws.actions.filter(se=>se.sequence.trim().length>0).map((se,T)=>({...se,label:a1(se,T)})),[ws.actions]),Di=k.useMemo(()=>G3(Kr),[Kr]),Na=ws.label,ti=k.useMemo(()=>ji!=="auto"?`Manual preset: ${ws.label}`:Di?`Auto preset · ${ws.label} (${Di})`:"Auto preset",[Di,ji,ws.label]),ys=k.useCallback(se=>{Ve(se)},[]),Ya=k.useCallback(()=>{er(se=>se==="copy"?"arrows":"copy"),Ct("idle")},[]),Za=k.useCallback(()=>{typeof window>"u"||(fr.current!==null&&window.clearTimeout(fr.current),fr.current=window.setTimeout(()=>{fr.current=null,Ct("idle")},1200))},[]),As=k.useCallback(se=>{fr.current!==null&&typeof window<"u"&&(window.clearTimeout(fr.current),fr.current=null),Ct(se?"copied":"failed"),Za()},[Za]),Ka=k.useCallback(se=>{at(se)},[]),Bl=k.useMemo(()=>Be?bE(nn):yE(nn),[Be,nn]),Ho=k.useMemo(()=>xw(a),[a]);k.useEffect(()=>{if(!Fr||!H||!jt||!Xr)return;const se=EC(Ho);se&&Se.sendInput(Xr,se).catch(T=>{console.warn("[Terminal] Failed to synchronize tmux default colors:",T)})},[Fr,H,jt,Xr,Se,Ho]);const Ao=k.useMemo(()=>`terminal::${Y}`,[Y]);k.useEffect(()=>{ke?.({isConnecting:Or,isRestarting:Sn,hasError:!!Et,sessionId:Xr})},[Or,Sn,Et,Xr,ke]);const ma=!Xr||Or||Sn,Ra=k.useCallback((se,T)=>{if(ma)return;const j=Math.max(1,Math.min(Math.floor(T)||1,40));Ms(se,j)},[Ms,ma]);k.useEffect(()=>{if(!l||!Be)return;gr.current?.requestRefresh("resize",{skipScrollToBottom:!Xt,force:!0})},[l,Be,Xt,zt,Y]),k.useEffect(()=>{if(!l||!Be)return;const se=T=>{const j=T.detail;gr.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,Be,Y]);const Wo=!Z&&(Be||ws.id==="default"||ws.showOnDesktop===!0),ga=l,ls=Be&&!xe?{transform:"translateY(var(--kb-translate-y, 0px))",transition:"none"}:void 0,Go=Be&&!xe?{marginTop:"var(--kb-margin-top, 0px)",transition:"none"}:void 0,qi=s.jsx(AE,{visible:Wo,interactive:ga,presentation:Be?"mobile":"desktop-actions",activeModifier:Lt,lockedModifier:Ge,disabled:ma,defaultShowExtended:q,presetLabel:Na,presetModeLabel:ti,presetMode:ji,presetOptions:Bl,includeAlt:ws.includeAlt,presetRowLayout:ws.rowLayout,extraActions:Gs,onKeyPress:zi,onTextPress:Ri,onPastePress:Be?Hi:void 0,onFilePress:Be?Ws:void 0,onFileLongPress:Be?Dl:void 0,fileUploadState:Nt,fileUploadProgress:bt,longPressMode:De,copyFeedback:et,onLongPressModeToggle:Ya,onModifierToggle:Ni,onPresetSelect:ys,onExpandedChange:Ka}),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:ls,children:[s.jsx("input",{ref:Dn,type:"file",className:"hidden",onChange:Wi}),Rr&&Ii.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:()=>rn(!1),"aria-label":$e("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:()=>rn(!1),children:$e("common.close")})]}),yt&&s.jsxs("div",{role:"alert",className:"mt-3 rounded-lg bg-destructive/10 p-3 text-xs text-destructive",children:[s.jsxs("p",{children:[yt.stage,"失败。",yt.stage.endsWith("压缩")?"原文件未上传。":yt.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:yt.detail})]}),nr&&s.jsx("button",{type:"button",onClick:()=>{Gi()},disabled:Nt==="uploading"||nr.sessionId!==Y,className:"mt-2 rounded-lg bg-surface-2 px-3 py-2 text-foreground disabled:opacity-50",children:$e("common.retry")})]}),dt&&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:Vr.showResultToast,onChange:se=>it({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:Me,onChange:se=>it({imageEnabled:se.target.checked}),className:"h-4 w-4 accent-primary"})]}),Me&&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:nt,onChange:se=>it({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:J3.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(wt*100),"%",s.jsx("input",{type:"range",min:i0.min,max:i0.max,step:i0.step,value:wt,onChange:se=>it({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:sr,onChange:se=>it({videoEnabled:se.target.checked}),className:"h-4 w-4 accent-primary"})]}),sr&&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:xn,onChange:se=>it({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:ev.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:["目标视频码率:",an/1e6," Mbps",s.jsx("input",{type:"range",min:a0.min,max:a0.max,step:a0.step,value:an,onChange:se=>it({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:ht?"本地转码器准备失败,请关闭开关后重试。":rN(Ir)}),Ir?.saved===!1&&s.jsx("p",{className:"text-[11px] text-destructive",children:"本机未能保存转码器,重新打开后可能需要重新下载。"}),ht&&s.jsx("p",{className:"text-[11px] text-destructive",children:ht})]})]})]}),document.body),Gn&&s.jsx(TE,{isMobile:Be,isInputFocused:rt,isIOS:le,isConnecting:Or,connectionError:Et,terminalSessionId:Xr}),s.jsxs("div",{className:"relative min-h-0 flex-1 overflow-hidden",style:{backgroundColor:Ho.background,...Go},children:[s.jsx("div",{ref:Ia,className:"h-full w-full box-border",children:s.jsx(bw,{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:$e("terminal.componentFailed")})]})}),children:s.jsx(iE,{ref:ml,sessionKey:Ao,sessionId:Y,isLayoutVisible:m,chunks:ks,onInput:fl,onResize:pl,onFlowControl:jl,onTmuxScroll:Fr?Ra:void 0,tmuxScrollSensitivity:.38,onDoubleTap:Be?()=>{gr.current?.sendSequence(" ")}:void 0,onInputFocusChange:zo,onMobileLongPressCopyResult:As,onReadyChange:Xn,onSizeSynchronizedChange:Vt,onWritesSettled:Ha,onWriteProgress:$i,onCursorPositionChange:ua,onDirectoryLinkActivate:fn,terminalSettings:Oe,theme:Ho,enableTouchScroll:Be,mobileLongPressMode:De,autoFocus:!Ee&&!Be&&!gl,cursorVisible:!Ee&&Zt,suppressSmoothScroll:!Ze||!St,className:Ee||!Zt?"terminal-focus-suspended":void 0},Ao)})}),s.jsx(XE,{result:cn,onDismiss:ge}),s.jsx(CE,{connectionError:Et,isFatalError:Qr,isRestarting:Sn,isConnecting:Or,onHardRestart:Uo})]}),ce?Z?null:Ii.createPortal(qi,ce):qi]})};function iN({session:e,active:t,onActivate:r,onToggleRightSidebar:n}){const{t:a}=zr(),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(Fo,{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(Ff,{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(By,{size:14})})]})}const aN="termdock:startup:";function Nu(e){if(typeof performance>"u"||typeof performance.mark!="function")return;const t=`${aN}${e}`;performance.getEntriesByName(t,"mark").length>0||performance.mark(t)}function Hx(e,t){e||Ii.flushSync(t)}const c1="horizontal";function Du(e){return e<=0?[]:Array.from({length:e},()=>1/e)}function Yh(e,t){if(!Array.isArray(e)||e.length!==t)return Du(t);const r=e.map(Number);if(r.some(a=>!Number.isFinite(a)||a<=0))return Du(t);const n=r.reduce((a,c)=>a+c,0);return n<=0?Du(t):r.map(a=>a/n)}function oN(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 lN(e){return e==="horizontal"||e==="vertical"||e==="grid"}function cN(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=oN(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:lN(c.layout)?c.layout:c1,ratios:Yh(c.ratios,d.length),...c.gridColumnRatios!==void 0?{gridColumnRatios:Yh(c.gridColumnRatios,p.columns)}:{},...c.gridRowRatios!==void 0?{gridRowRatios:Yh(c.gridRowRatios,p.rows)}:{}})}return n}function uN(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?Yh(n.ratios,a.length):Du(a.length)}]})}function y0(e,t){if(t)return e.find(r=>r.sessionIds.includes(t))}function tm(e,t,r){if(!t||!r||t===r)return e;const n=y0(e,t),a=y0(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===c1)?"grid":n?.layout??c1,ratios:Du(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 dN(e,t){const r=y0(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:Du(n.length)}:a)}function hN(e,t){const r=y0(e,t);return r?e.filter(n=>n.id!==r.id):e}function fN(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 pN(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 u1=320,rv=1,mN=u1+120,d1="termdock:split-workspaces:v2",nv="termdock:split-workspace:v1",gN=.1,xN=.9;function rm(){if(typeof window>"u")return{mobile:!1,landscape:!1};const e=xy();return{mobile:e,landscape:e&&window.innerWidth>window.innerHeight}}function bN(){if(typeof window>"u")return[];try{const e=window.localStorage.getItem(d1);if(e)return cN(JSON.parse(e));const t=JSON.parse(window.localStorage.getItem(nv)||"null");if(t&&typeof t.primaryId=="string"&&typeof t.secondaryId=="string"&&t.primaryId!==t.secondaryId){const r=Math.min(xN,Math.max(gN,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 yN(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 Wx(e){const t=e.wrapperEl;if(t)try{t.getAnimations().forEach(r=>r.cancel())}catch{}}function vh(e,t){const r=vf(e,t);if(r===null)return;const n=e.wrapperEl;Wx(e),n&&(n.style.transitionDuration="0ms");try{const a=e;a.setTransition?.(0),a.setTranslate?.(r),Wx(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 h1(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 vf(e,t){const r=e.snapGrid,n=Array.isArray(r)?r[t]:void 0;return typeof n!="number"||!Number.isFinite(n)?null:-n}function vN(e,t){const r=h1(e),n=vf(e,t);return r!==null&&n!==null&&Math.abs(r-n)<=rv}function wN(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 sv(e){const t=new Map;for(const r of e)t.set(r.id,r);return Array.from(t.values())}function iv(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 AN(e,t){const r=sv(e),n=r.findIndex(a=>a.id===t.id);if(n>=0){const a=[...r];return a[n]=t,a}return[...r,t]}function Gx(e,t){const r=new Map(e.map(n=>[n.id,n]));return t.map(n=>{const a=r.get(n.sessionId);return{...iv(n),history:a?.history}})}function Vx(e,t){return e.length===0?null:t&&e.some(r=>r.sessionId===t)?t:e[0]?.sessionId??null}function qx(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 Yx(e){const t=new Map;for(const[r,n]of e)t.set(r,n.cwd??null);return t}function TN(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 SN(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 CN=({terminalSettings:e=K1(),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}=zr(),W=b.useMemo(()=>Qu("session"),[]),F=b.useMemo(()=>Qu("terminal"),[]),[U,V]=b.useState([]),[Z,ce]=b.useState(null),xe=b.useRef(0),pe=b.useRef(0),te=es(z=>z.activePaneId);b.useEffect(()=>{es.getState().setActivePane(Z)},[Z]);const[ke,$e]=b.useState(null),[Y,Ae]=b.useState(!0),[lt,Se]=b.useState({token:0,reason:"visibility",forceForegroundReconnect:!1}),[ye,_e]=b.useState(()=>new Set),[je,re]=b.useState(()=>({token:0,completed:new Set})),[Oe,Ce]=b.useState(0),[Ee,Be]=b.useState(()=>new Set),[Ne,le]=b.useState(()=>new Set),He=b.useRef(new Map),[rt,mt]=b.useState(()=>new Set),ue=b.useRef(!1),Ye=b.useRef(null),st=b.useRef({}),[Ie,We]=b.useState(null),[Te,H]=b.useState(()=>bN()),[oe,be]=b.useState(!1),Ze=b.useCallback(z=>{xe.current+=1,be(z)},[]),Je=b.useRef(null),St=b.useRef(oe);St.current=oe,I0(Je,oe&&!!Z,()=>Ze(!1));const[Vt,jt]=b.useState(null),[vt,Zt]=b.useState(null),Pt=b.useRef(new Set),[Xt,zt]=b.useState(null),[Lt,me]=b.useState(null),[Ge,pt]=b.useState(!1),[q,at]=b.useState(()=>rm().mobile),[qt,Ve]=b.useState(()=>rm().landscape),[De,er]=b.useState(null),[et,Ct]=b.useState(null),Nt=b.useRef(a),gt=b.useRef(!1),bt=b.useRef(!1),It=b.useRef(null),yt=b.useRef(null),pr=b.useRef(q),nr=b.useRef(null),Cr=b.useCallback(z=>{z!==nr.current&&(xe.current+=1),nr.current=z,ce(z)},[]);b.useEffect(()=>Gt.subscribe((z,N)=>{(z.rightOpen!==N.rightOpen||z.rightTab!==N.rightTab)&&(xe.current+=1)}),[]);const cn=b.useRef(0),Lr=b.useRef([]),ge=b.useRef(0),Vr=b.useRef(null),it=b.useRef(!1),dt=b.useRef(!0),sr=b.useRef(null),xn=b.useRef(""),an=b.useRef(0);b.useEffect(()=>{if(typeof window>"u")return;const z=()=>{const N=rm();pr.current=N.mobile,at(N.mobile),Ve(N.landscape)};return z(),window.addEventListener("resize",z),()=>window.removeEventListener("resize",z)},[]);const{sessions:Me,inventory:nt,activeSessionId:wt,isLoading:Rr,openSession:rn,setActiveSession:Ir,removeSession:ne,renameSession:ht,resetSessionCustomName:Ht,reorderSessions:Ot,restoreSessions:Tr}=yw(),mr=nt?.tmuxRecovery??null;b.useEffect(()=>{mr&&R?.()},[mr,R]),b.useEffect(()=>{me(null),zt(null)},[mr?.id]);const Hr=b.useCallback(async()=>{zt("restore"),me(null);try{const z=await vw();await Tr(),z.failed>0&&me(B("tab.tmuxRecoveryPartial",{restored:z.restored,failed:z.failed}))}catch{me(B("tab.tmuxRecoveryFailed"))}finally{zt(null)}},[Tr,B]),_n=b.useCallback(async()=>{zt("dismiss"),me(null);try{await ww(),await Tr()}catch{me(B("tab.tmuxRecoveryDismissFailed"))}finally{zt(null)}},[Tr,B]),dr=Gt(z=>z.groupByFolder),bn=uf(z=>z.collaborationGroups),hn=Gt(z=>z.leftOpen||z.rightOpen),Tn=Gt(z=>z.rightSidebarWidthContextKey),ir=Gt(z=>z.rightSidebarWidth),pn=Gt(z=>z.rightPinned),[Pr,qr]=b.useState(()=>Yx(Yr.getState().sessions));b.useEffect(()=>Yr.subscribe(z=>{const N=Yx(z.sessions);qr($=>TN($,N)?$:N)}),[]);const{arranged:Wr}=b.useMemo(()=>lf(U,z=>Pr.get(z.id)??null,dr,"",Te,bn),[U,Pr,dr,Te,bn]),fs=b.useRef(Wr);fs.current=Wr;const Br=b.useMemo(()=>yN(Wr,Te),[Wr,Te]),Mn=b.useRef(Br);Mn.current=Br;const Sr=b.useMemo(()=>y0(Te,Z),[Z,Te]),Kr=b.useMemo(()=>{const z=Br.find(N=>N.sessions.some($=>$.id===Z));return new Set(z?.sessions.map(N=>N.id)??[])},[Z,Br]),nn=b.useMemo(()=>{const z=new Map;if(!m||v<=0)return z;for(const N of Br){const $=N.sessions[0];if(!$)continue;const ee=Aw($.id,Pr.get($.id)??null,N.workspace?.id??null);if(!(ee===Tn?pn:Tw($.id,Pr.get($.id)??null,N.workspace?.id??null)))continue;const Qe=ee===Tn?ir:Sw($.id,Pr.get($.id)??null,N.workspace?.id??null),ze=Ph(Qe,v,w);z.set(N.key,ze+by)}return z},[Pr,w,m,pn,Tn,ir,v,Br]),Fr=b.useMemo(()=>Jp(U.map(z=>({id:z.id,backendSessionId:z.sessionId})),d),[d,U]),ks=b.useMemo(()=>Vx(Me,wt),[wt,Me]),Or=bh({prioritySessionId:Fr,activeSessionId:ke??Z,persistedActiveSessionId:ks,firstSessionId:U[0]?.id??null}),Xr=b.useMemo(()=>WE(Br.flatMap(z=>z.sessions.map(N=>N.id)),Kr),[Kr,Br]),fn=Or!==null&&ye.has(Or),K=b.useMemo(()=>{const z=new Set(Kr);return ke&&z.add(ke),!z.size&&Or&&z.add(Or),z},[Kr,ke,Or]),Ue=je.token===lt.token&&$E(K,je.completed),Et=Ue||Oe===lt.token?lt.token:-1;b.useEffect(()=>{if(!lt.token||Ue)return;const z=window.setTimeout(()=>Ce(lt.token),EE);return()=>window.clearTimeout(z)},[lt.token,Ue]);const kt=b.useCallback((z,N)=>{_e($=>{if($.has(z)===N)return $;const ie=new Set($);return N?ie.add(z):ie.delete(z),ie})},[]),tr=b.useCallback(z=>{const N=cn.current;re(ee=>{if(ee.token===N&&ee.completed.has(z))return ee;const ie=new Set(ee.token===N?ee.completed:[]);return ie.add(z),{token:N,completed:ie}});const $=Fr??ke??nr.current;z===$&&Nu("foreground-stream-connected")},[ke,Fr]),Qr=b.useCallback((z,N)=>{Be($=>{if($.has(z)===N)return $;const ee=new Set($);return N?ee.add(z):ee.delete(z),ee})},[]),cr=b.useCallback((z,N)=>{le($=>{if($.has(z)===N)return $;const ee=new Set($);return N?ee.add(z):ee.delete(z),ee})},[]);b.useEffect(()=>{for(const[z,N]of He.current){const $=U.find(ee=>ee.id===z);if(!$||$.sessionId!==N.backendSessionId){He.current.delete(z);continue}!ye.has(z)||!Ee.has(z)||!Ne.has(z)||(He.current.delete(z),gy(N.backendSessionId,`${N.command}\r`).catch(ee=>{console.error("[Session] Failed to send startup command:",ee)}))}},[U,ye,Ee,Ne]);const Sn=Or!==null&&Ee.has(Or),Ls=Or!==null&&Ne.has(Or);b.useEffect(()=>{Sn&&Nu("foreground-viewport-ready")},[Sn]),b.useEffect(()=>{Ls&&Nu("foreground-content-ready")},[Ls]),b.useEffect(()=>{if(!E)return;if(!Y&&U.length===0){E();return}if(!Sn||!fn||!Ls)return;const z=[...Kr].every(Qe=>Ee.has(Qe)&&ye.has(Qe)&&Ne.has(Qe));let N=0,$=0;const ee=()=>{N=requestAnimationFrame(()=>{$=requestAnimationFrame(()=>{Nu("initial-viewport-presented"),E()})})};z&&ee();const ie=z?void 0:window.setTimeout(ee,8e3);return()=>{cancelAnimationFrame(N),cancelAnimationFrame($),clearTimeout(ie)}},[fn,Ls,Sn,Y,E,U.length,Kr,Ee,ye,Ne]);const Zn=b.useMemo(()=>q?ME({slides:Br.map(z=>z.sessions.map(N=>N.id)),visibleSessionIds:Kr,foregroundSessionId:Or}):rt,[q,Br,Kr,Or,rt]);b.useEffect(()=>{if(q||Kr.size===0)return;const z=new Set(Kr),N=Br.findIndex($=>$.sessions.some(ee=>Kr.has(ee.id)));for(let $=-2;$<=2;$+=1)$!==0&&Br[N+$]?.sessions.forEach(ee=>z.add(ee.id));mt($=>{let ee=!1;const ie=new Set($);for(const Qe of z)ie.has(Qe)||(ie.add(Qe),ee=!0);return ee?ie:$})},[q,Kr,Br]);const sn=hC(Zn);b.useEffect(()=>{if(!ke)return;if(!U.some(N=>N.id===ke)){$e(null);return}if(!Ee.has(ke)||!ye.has(ke)||!Ne.has(ke))return;const z=window.setTimeout(()=>{$e(N=>N===ke?null:N),Nt.current&&!pr.current&&We({sessionId:ke,token:Date.now()})},80);return()=>window.clearTimeout(z)},[Ne,ke,ye,U,Ee]),b.useEffect(()=>{typeof window>"u"||(Te.length>0?(window.localStorage.setItem(d1,JSON.stringify(Te)),window.localStorage.removeItem(nv)):window.localStorage.removeItem(d1))},[Te]),b.useEffect(()=>{Rr||Y||Te.length===0||H(z=>uN(z,U.map(N=>N.id)))},[Rr,Y,U,Te.length]),b.useEffect(()=>{if(!Vt)return;const z=window.setTimeout(()=>jt(null),3200);return()=>window.clearTimeout(z)},[Vt]),nr.current=Z,cn.current=lt.token,Lr.current=U,Vr.current=wt,it.current=Rr,dt.current=Y,Nt.current=a;const on=b.useCallback((z=Ye.current)=>{const N=ge.current,$=typeof window<"u"?window.visualViewport:null,ee=z?h1(z):null,ie=z?vf(z,N):null;return{sessionsLength:Lr.current.length,workspaceSlidesLength:Mn.current.length,sessionIds:Lr.current.map(Qe=>Qe.id),activeSessionId:nr.current,activeSessionIndex:N,persistedActiveId:Vr.current,isLoading:it.current,isRestoring:dt.current,activeIndex:z?.activeIndex??null,previousIndex:z?.previousIndex??null,animating:z?.animating??null,allowTouchMove:z?.allowTouchMove??null,width:z?.width??null,translate:ee,targetTranslate:ie,translateDelta:ee!==null&&ie!==null?ee-ie:null,snapGridLength:z?.snapGrid?.length??null,targetSnap:z?.snapGrid?.[N]??null,visualViewport:$?{width:Math.round($.width),height:Math.round($.height),offsetTop:Math.round($.offsetTop)}:null}},[]),_r=b.useCallback((z,N)=>{W(z,{...on(),...N})},[W,on]);b.useEffect(()=>{Rr||Y||Z!==wt&&Ir(Z)},[Z,Rr,Y,wt,Ir]);const $r=b.useMemo(()=>{if(Wr.length===0||!Z)return 0;const z=Br.findIndex(N=>N.sessions.some($=>$.id===Z));return z>=0?z:0},[Br,Z]);ge.current=$r;const Wn=b.useCallback(()=>{It.current&&(clearTimeout(It.current),It.current=null)},[]),Gn=b.useCallback(z=>{Wn(),It.current=setTimeout(()=>{It.current=null,gt.current=!1,_r("[swiper:touch-guard-clear]",{reason:z})},mN)},[Wn,_r]),un=b.useCallback((z,N={})=>{const $=Ye.current,ee=ge.current,ie=Mn.current;if(!$||ie.length===0||ee<0||ee>=ie.length)return;if(gt.current){_r("[swiper:sync-skip-touch]",{reason:z});return}if($.animating){_r("[swiper:sync-skip-animating]",{reason:z});return}const Qe=h1($),ze=vf($,ee),xt=Qe!==null&&ze!==null&&Math.abs(Qe-ze)<=rv,_t=$.activeIndex===ee;if(_r("[swiper:sync-check]",{reason:z,activeIndexAligned:_t,translateAligned:xt,immediate:N.immediate===!0}),!(_t&&xt)){if(_t){vh($,ee),_r("[swiper:sync-forced-active]",{reason:z,translateAligned:xt,immediate:N.immediate===!0});return}N.immediate?(vh($,ee),$.slideTo(ee,0,!1),vh($,ee)):$.slideTo(ee,u1,!1),_r("[swiper:sync-applied]",{reason:z,activeIndexAligned:_t,translateAligned:xt,immediate:N.immediate===!0})}},[_r]);b.useEffect(()=>{const z=N=>{const $=N;Ye.current&&(Ye.current.allowTouchMove=!$.detail.locked),_r("[swiper:gesture-lock]",{locked:$.detail.locked})};return document.addEventListener("termdock:gesture-lock",z),()=>document.removeEventListener("termdock:gesture-lock",z)},[_r]),b.useEffect(()=>{if(U.length===0){Z!==null&&Cr(null);return}if(!Z){if(!p)return;Cr(bh({prioritySessionId:Fr,activeSessionId:null,persistedActiveSessionId:ks,firstSessionId:U[0]?.id??null}));return}U.some(N=>N.id===Z)||Cr(U[0].id)},[U,Z,p,Fr,ks]);const Kn=b.useCallback((z,N)=>{if(N&&Date.now()<an.current){st.current[z]=!1;return}st.current[z]=N,Ct($=>N?z:$===z?null:$)},[]),kr=b.useCallback(z=>{if(!gt.current&&z.activeIndex!==ge.current){_r("[swiper:slide-change-ignored-layout]",{instanceActiveIndex:z.activeIndex,expectedActiveIndex:ge.current}),requestAnimationFrame(()=>un("ignored-layout-slide-change",{immediate:!0}));return}const N=Mn.current[z.activeIndex],$=N?.sessions.some(Qe=>Qe.id===Z)?Z:N?.sessions[0]?.id;if(_r("[swiper:slide-change]",{nextSessionId:$??null,instanceActiveIndex:z.activeIndex}),!$||$===Z)return;const ee=!!Z&&st.current[Z]===!0,ie=Nt.current&&(!pr.current||ee);if(yt.current=$,Cr($),ie){We({sessionId:$,token:Date.now()});return}We(null)},[U,Z,_r,un]);b.useLayoutEffect(()=>{if(yt.current===Z){_r("[swiper:sync-skip-swiper-driven]",{activeSessionId:Z}),yt.current=null;return}un("active-session-index",{immediate:!0})},[Z,$r,U.length,un,_r]),b.useEffect(()=>{const z=Ye.current;if(!z)return;const N=Br.length>1&&!hn&&!oe;z.allowTouchMove!==N&&(z.allowTouchMove=N,_r("[swiper:allow-touch-sync]",{nextAllow:N,sidebarOverlayOpen:hn}))},[Br.length,_r,hn,oe]);const Er=b.useCallback(z=>{const N=Ye.current;if(!N)return;const $=N.el;if(_r("[swiper:layout-before]",{reason:z,scrollLeft:$?.scrollLeft??null}),$&&($.scrollLeft=0),N.updateSize(),N.updateSlides(),N.updateProgress(),N.updateSlidesClasses(),$&&($.scrollLeft=0),_r("[swiper:layout-after]",{reason:z,scrollLeft:$?.scrollLeft??null}),gt.current||N.animating){_r("[swiper:layout-skip-sync-motion]",{reason:z});return}un(`layout:${z}`,{immediate:!0}),requestAnimationFrame(()=>{const ee=Ye.current;ee&&(gt.current||ee.animating||vh(ee,ge.current))})},[_r,un]);b.useEffect(()=>()=>Wn(),[Wn]);const gr=Br.map(z=>z.key).join("\0");b.useEffect(()=>{requestAnimationFrame(()=>Er("group-change"))},[dr,gr,Er]),b.useEffect(()=>{let z=null,N="mount";const $=xt=>{N=xt,z===null&&(z=requestAnimationFrame(()=>{z=null,Er(`viewport-change:${N}`)}))},ee=()=>$("window-resize"),ie=()=>$("visual-viewport-resize"),Qe=()=>$("visual-viewport-scroll"),ze=xt=>{$(`measured:${xt.detail?.source??"unknown"}`)};return window.addEventListener("resize",ee),window.visualViewport?.addEventListener("resize",ie),window.visualViewport?.addEventListener("scroll",Qe),document.addEventListener(n2,ze),$("mount"),()=>{window.removeEventListener("resize",ee),window.visualViewport?.removeEventListener("resize",ie),window.visualViewport?.removeEventListener("scroll",Qe),document.removeEventListener(n2,ze),z!==null&&cancelAnimationFrame(z)}},[Er]),b.useEffect(()=>{if(typeof document>"u")return;let z=null,N=null;const $=_t=>{if(_t!=="online"&&document.hidden)return;const Mr=performance.now();if(!UE(N,Mr))return;N=Mr;const Dt=_t==="bfcache"||_t==="online"?_t:"visibility",Gr=zE();wp(),_a("info","PWA_RESUME scheduled",{source:_t,forceForegroundReconnect:Gr,activeSessionId:nr.current}),Se(dn=>({token:dn.token+1,reason:Dt,forceForegroundReconnect:Gr})),requestAnimationFrame(()=>Er(`resume:${_t}:raf`)),z&&clearTimeout(z),z=setTimeout(()=>{z=null,Er(`resume:${_t}:settled`)},320)},ee=()=>{if(document.hidden){wp();return}$("visibility")},ie=()=>{wp()},Qe=_t=>{$(_t.persisted?"bfcache":"pageshow")},ze=()=>$("online"),xt=()=>$("focus");return document.addEventListener("visibilitychange",ee),window.addEventListener("pagehide",ie),window.addEventListener("pageshow",Qe),window.addEventListener("online",ze),window.addEventListener("focus",xt),()=>{document.removeEventListener("visibilitychange",ee),window.removeEventListener("pagehide",ie),window.removeEventListener("pageshow",Qe),window.removeEventListener("online",ze),window.removeEventListener("focus",xt),z&&clearTimeout(z)}},[Er]),b.useLayoutEffect(()=>{if(!OE(Y))return;const z=wN(U),N=JSON.stringify(z);z.length>0&&N!==xn.current?(xn.current=N,console.warn("[session-invariant] duplicate mapping detected",z)):z.length===0&&xn.current&&(xn.current=""),L?.({sessions:U.map($=>({id:$.id,name:$.name,customName:$.customName,mode:$.mode,tmuxSessionName:$.tmuxSessionName})),activeSessionId:Z,splitWorkspaces:Te.map(({id:$,name:ee,sessionIds:ie,layout:Qe})=>({id:$,...ee?{name:ee}:{},sessionIds:ie,layout:Qe}))})},[U,Z,Te,L,Y]),b.useEffect(()=>{if(Rr||ue.current)return;ue.current=!0;const z=Jp(Me.map(Qe=>({id:Qe.sessionId,backendSessionId:Qe.backendSessionId??null})),d),N=Vx(Me,wt),$=bh({prioritySessionId:p?z:null,activeSessionId:null,persistedActiveSessionId:N,firstSessionId:Me[0]?.sessionId??null}),ee=sv(Me.map(iv));if(W("[Session] Restoring",ee.length,"persisted sessions (one-shot)"),_r("[swiper:restore-start]",{persistedSessionIds:Me.map(Qe=>Qe.sessionId),nextActiveSessionId:$}),ee.length>0){const Qe=Yr.getState();ee.forEach(xt=>{xt.sessionId&&Qe.setTerminalSession(xt.id,{sessionId:xt.sessionId,cols:80,rows:24,mode:xt.mode,tmuxSessionName:xt.tmuxSessionName,history:xt.history})}),Me.forEach(xt=>{xt.agent!==void 0&&Qe.setSessionAgentIdentity(xt.sessionId,xt.agent),xt.activeProgram!=null&&Qe.setSessionActiveProgram(xt.sessionId,xt.activeProgram),xt.cwd!=null&&Qe.setSessionCwd(xt.sessionId,xt.cwd),xt.shellTitle!=null&&Qe.setSessionShellTitle(xt.sessionId,xt.shellTitle)}),V(ee);const ze=$||ee[0]?.id||null;Cr(ze),_r("[swiper:restore-complete]",{restoredSessionIds:ee.map(xt=>xt.id),nextActiveSessionId:ze})}(async()=>(ee.length===0&&await sr.current?.({createIfEmpty:!0}),Ae(!1),requestAnimationFrame(()=>un("restore-finished",{immediate:!0}))))()},[Rr,Me,wt,W,_r,un,p,d]),b.useEffect(()=>{if(!p||Y||U.length===0)return;const z=Jp(U.map($=>({id:$.id,backendSessionId:$.sessionId})),d),N=bh({prioritySessionId:z,activeSessionId:nr.current,persistedActiveSessionId:ks,firstSessionId:U[0]?.id??null});N&&N!==nr.current&&Cr(N)},[p,d,Y,ks,U]);const rs=b.useRef([]),$n=b.useRef(!1);nr.current=Z,b.useEffect(()=>{if(Y)return;const z=rs.current,N=Me,$=new Map(z.map(Dt=>[Dt.sessionId,Dt])),ee=Yr.getState();for(const Dt of N){const Gr=$.get(Dt.sessionId),dn=Yr.getState().sessions.get(Dt.sessionId);Dt.agent!==void 0&&JSON.stringify(Dt.agent)!==JSON.stringify(dn?.agent)&&(dn?.agent==null||JSON.stringify(Dt.agent)!==JSON.stringify(Gr?.agent))&&ee.setSessionAgentIdentity(Dt.sessionId,Dt.agent),Dt.activeProgram!=null&&Dt.activeProgram!==dn?.activeProgram&&(dn?.activeProgram==null||Dt.activeProgram!==Gr?.activeProgram)&&ee.setSessionActiveProgram(Dt.sessionId,Dt.activeProgram),Dt.cwd!=null&&Dt.cwd!==dn?.cwd&&(dn?.cwd==null||Dt.cwd!==Gr?.cwd)&&ee.setSessionCwd(Dt.sessionId,Dt.cwd),Dt.shellTitle!=null&&Dt.shellTitle!==dn?.shellTitle&&(dn?.shellTitle==null||Dt.shellTitle!==Gr?.shellTitle)&&ee.setSessionShellTitle(Dt.sessionId,Dt.shellTitle)}if(!$n.current){V(Dt=>Gx(Dt,N)),rs.current=N,$n.current=!0;return}const ie=new Set(z.map(Dt=>Dt.sessionId)),Qe=new Set(N.map(Dt=>Dt.sessionId)),ze=new Map(z.map(Dt=>[Dt.sessionId,Dt.name]));rs.current=N,V(Dt=>{const Gr=Gx(Dt,N);return(!nr.current||!Gr.some(dn=>dn.id===nr.current))&&Cr(Gr[0]?.id??null),Gr});const xt=N.filter(Dt=>!ie.has(Dt.sessionId)),_t=[...ie].filter(Dt=>!Qe.has(Dt)),Mr=N.filter(Dt=>ie.has(Dt.sessionId)&&ze.get(Dt.sessionId)!==Dt.name);(xt.length>0||_t.length>0||Mr.length>0)&&W("[Session] Synced persisted sessions:",{newSessionIds:xt.map(Dt=>Dt.sessionId),removedSessionIds:_t,renamedSessionIds:Mr.map(Dt=>Dt.sessionId),currentSessionIds:N.map(Dt=>Dt.sessionId)});for(const Dt of N){if(!Dt.backendSessionId)continue;Yr.getState().setTerminalSession(Dt.sessionId,{sessionId:Dt.backendSessionId,cols:80,rows:24,mode:Dt.mode,tmuxSessionName:Dt.tmuxSessionName})}},[Me,Y,W]);const kn=b.useCallback(async z=>{const N=++pe.current,$=xe.current,ee=()=>N===pe.current&&$===xe.current&&(z?.shouldActivate?.()??!0);try{const ie=Gt.getState(),Qe=Z?{rightOpen:ie.rightOpen,rightPinned:ie.rightPinned,rightSidebarWidth:ie.rightSidebarWidth,rightTab:ie.rightTab}:null,ze=z?.mode==="tmux"||z?.mode==="shell"?z.mode:c,xt=(z?.tmuxSessionName||"").trim(),_t=l.trim(),Mr=ze==="tmux"?xt||_t||SN():null,Dt=typeof z?.cwd=="string"?z.cwd:null,Gr=Z?Yr.getState().sessions.get(Z)?.cwd??null:null,dn=typeof Dt=="string"&&Dt.trim().length>0?Dt:typeof Gr=="string"&&Gr.trim().length>0?Gr:void 0,jn=await rn({preferredFrontendSessionId:z?.preferredFrontendSessionId,requireExisting:z?.requireExisting===!0,mode:ze,tmuxSessionName:Mr,cwd:dn,termType:"xterm-256color",createIfEmpty:z?.createIfEmpty===!0},{shouldActivate:ee});if(jn.discarded)return z?.onResult?.({ok:!1,error:"unknown"}),null;const ns=jn.session,Un=jn.terminalSession;!jn.reused&&Qe&&Gt.getState().initializeRightSidebarForSession(ns.sessionId,Un.cwd??dn??null,Qe);const fr={id:ns.sessionId,name:ns.name,customName:ns.customName===!0,sessionId:Un.sessionId,mode:Un.mode??ns.mode,tmuxSessionName:Un.tmuxSessionName??ns.tmuxSessionName},Mt=z?.command?.trim();return Mt&&He.current.set(fr.id,{backendSessionId:Un.sessionId,command:Mt}),V(Vn=>AN(Vn,fr)),ee()&&Cr(fr.id),Yr.getState().setTerminalSession(fr.id,{sessionId:Un.sessionId,cols:80,rows:24,mode:fr.mode,tmuxSessionName:fr.tmuxSessionName,activeProgram:Un.activeProgram,activeProgramRaw:Un.activeProgramRaw,activeProgramSource:Un.activeProgramSource,cwd:Un.cwd}),W("[Session] Inventory opened session:",{frontendSessionId:fr.id,backendSessionId:Un.sessionId,reused:jn.reused,mode:fr.mode,tmuxSessionName:fr.tmuxSessionName}),z?.onResult?.({ok:!0,sessionId:fr.id}),fr.id}catch(ie){return console.error("[Session] Failed to create new session:",ie),z?.onResult?.({ok:!1,error:eC(ie)}),null}},[c,l,Z,rn,W]);sr.current=kn;const Ln=b.useCallback((z,N={})=>{xe.current+=1,es.getState().setActivePane(z);const $=nr.current,ee=!!$&&st.current[$]===!0;if(Cr(z),pr.current&&N.preserveMobileKeyboard===!1){an.current=Date.now()+600,$&&(st.current[$]=!1),Ct(null),We(null);const ie=document.activeElement;ie instanceof HTMLTextAreaElement&&ie.closest(".terminal-viewport-container")&&ie.blur();return}ee&&pr.current&&Ct(z),Nt.current&&(!pr.current||ee)&&We({sessionId:z,token:Date.now()})},[]),ps=b.useCallback(z=>{Cr(z),Ze(!0),jt(null)},[]),G=b.useCallback(z=>{const N=nr.current;!N||N===z||(H($=>tm($,N,z)),Ze(!1),Ln(N,{preserveMobileKeyboard:!1}))},[Ln]),Le=b.useCallback(async()=>{const z=nr.current;if(!z||Ge)return;const N=xe.current;pt(!0);const $=Yr.getState().sessions.get(z)?.cwd??void 0,ee=await kn({cwd:$||void 0,mode:c,shouldActivate:()=>!1});if(pt(!1),!ee){jt(B("common.error"));return}!St.current||N!==xe.current||!Lr.current.some(ie=>ie.id===z)||(H(ie=>tm(ie,z,ee)),Ze(!1),Ln(z,{preserveMobileKeyboard:!1}))},[Ln,c,kn,Ge,B]),Ke=b.useCallback(z=>{H(N=>hN(N,z)),z&&Ln(z,{preserveMobileKeyboard:!1})},[Ln]),ct=b.useCallback(z=>{H(N=>dN(N,z)),Ln(z,{preserveMobileKeyboard:!1})},[Ln]),qe=b.useCallback(z=>{if(U.find($=>$.id===z)){if(xe.current+=1,es.getState().setActivePane(z),z===nr.current)return;if(Cr(z),!BE({isMobile:pr.current,viewportReady:Ee.has(z),streamReady:ye.has(z),contentReady:Ne.has(z)})){$e(null),Nt.current&&We({sessionId:z,token:Date.now()}),W("[Session] Switched to session:",z);return}mt(ee=>{if(ee.has(z))return ee;const ie=new Set(ee);return ie.add(z),ie}),$e(z),W("[Session] Switched to session:",z)}},[Ne,W,ye,U,Ee]),At=b.useCallback((z,N)=>{N.trim()&&(V($=>$.map(ee=>ee.id===z?{...ee,name:N.trim(),customName:!0}:ee)),ht(z,N.trim()))},[ht]),Rt=b.useCallback(z=>{V(N=>N.map($=>$.id===z?{...$,customName:!1}:$)),Ht(z)},[Ht]),Bt=b.useCallback(z=>{V(N=>{const $=new Map(N.map(ze=>[ze.id,ze])),ee=z.map(ze=>$.get(ze)).filter(ze=>ze!==void 0),ie=new Set(z),Qe=N.filter(ze=>!ie.has(ze.id));return[...ee,...Qe]}),Ot(z),W("[Session] Reordered sessions:",z),requestAnimationFrame(()=>{Ye.current?.update()})},[Ot,W]),ot=b.useCallback(async z=>{const N=typeof z=="string"?z:z.sessionId,$=typeof z=="string"?"auto":z.closeMode??"auto",ee=U.find(xt=>xt.id===N);if(!ee||Pt.current.has(N))return;Pt.current.add(N),xe.current+=1;const ie=s2(Wr,N,xt=>xt.id);try{$==="destroy"&&ee.mode==="tmux"&&ee.tmuxSessionName?(await yy(ee.tmuxSessionName),W("[Session] Destroyed tmux session:",{frontendSessionId:ee.id,tmuxSessionName:ee.tmuxSessionName})):ee.sessionId&&(await my(ee.sessionId),W("[Session] Closed backend terminal:",ee.sessionId))}catch(xt){console.error("[Session] Failed to close backend terminal:",xt),Zt({sessionId:N,closeMode:$});return}finally{Pt.current.delete(N)}Zt(xt=>xt?.sessionId===N?null:xt);const ze=Lr.current.filter(xt=>xt.id!==N).some(xt=>xt.id===ie)?ie:s2(Lr.current,N,xt=>xt.id);nr.current===N&&Cr(ze),V(xt=>xt.filter(_t=>_t.id!==N)),ne(N,ze),delete st.current[N],W("[Session] Closed session:",{sessionId:N,closeMode:$})},[U,Wr,ne,W]),Ft=b.useCallback(z=>{if(!z)return;const N=U.filter($=>$.sessionId===z);if(N.length!==0){N.length>1&&console.warn("[session-invariant] backend matched multiple frontend sessions during cleanup",{backendSessionId:z,frontendSessionIds:N.map($=>$.id)}),V($=>{const ee=$.filter(ie=>ie.sessionId!==z);return ee.length!==$.length&&!ee.some(Qe=>Qe.id===Z)&&Cr(ee.length>0?ee[0].id:null),ee});for(const $ of N)ne($.id),delete st.current[$.id];W("[Session] Backend gone, dropped local session(s):",N.map($=>$.id))}},[U,Z,ne,W]);b.useEffect(()=>{const z=fr=>{kn(fr.detail)},N=fr=>{qe(fr.detail)},$=()=>{const fr=nr.current;!fr||pr.current||We({sessionId:fr,token:Date.now()})},ee=fr=>{const Mt=fr;Mt.detail&&ps(Mt.detail)},ie=fr=>{const Mt=fr.detail;Ke(Mt??nr.current??void 0)},Qe=fr=>{const Mt=fr.detail;Mt&&ct(Mt)},ze=fr=>{const Mt=fr.detail,Dn=typeof Mt=="string"?Mt:Mt?.layout,Vn=typeof Mt=="string"?nr.current:Mt?.sessionId;Dn!=="horizontal"&&Dn!=="vertical"&&Dn!=="grid"||H(Ha=>Ha.map(Bn=>Bn.sessionIds.includes(Vn??"")?{...Bn,layout:Dn}:Bn))},xt=fr=>{const Dn=fr.detail?.direction;if(Dn!=="prev"&&Dn!=="next")return;const Vn=fs.current;if(Vn.length<=1)return;const Ha=nr.current,Bn=Ha?Vn.findIndex(Wa=>Wa.id===Ha):-1,ua=((Bn>=0?Bn:0)+(Dn==="next"?1:-1)+Vn.length)%Vn.length,bs=Vn[ua]?.id;bs&&bs!==Ha&&qe(bs)},_t=fr=>{ot(fr.detail)},Mr=fr=>{Ft(fr.detail)},Dt=fr=>{const Mt=fr;!Mt.detail?.sessionId||!Mt.detail?.name||At(Mt.detail.sessionId,Mt.detail.name)},Gr=fr=>{const Mt=fr;Mt.detail?.sessionId&&Rt(Mt.detail.sessionId)},dn=fr=>{const Mt=fr;Mt.detail?.sessionIds&&Bt(Mt.detail.sessionIds)},jn=fr=>{const Mt=fr.detail;!Mt?.workspaceId||!Array.isArray(Mt.sessionIds)||H(Dn=>fN(Dn,Mt.workspaceId,Mt.sessionIds))},ns=fr=>{const Mt=fr.detail;!Mt?.workspaceId||typeof Mt.name!="string"||H(Dn=>pN(Dn,Mt.workspaceId,Mt.name))},Un=fr=>{const Mt=fr.detail;!Mt?.primaryId||!Mt.secondaryId||Mt.primaryId===Mt.secondaryId||(H(Dn=>tm(Dn,Mt.primaryId,Mt.secondaryId)),Ln(Mt.primaryId,{preserveMobileKeyboard:!1}))};return window.addEventListener("new-terminal-session",z),window.addEventListener("switch-terminal-session",N),window.addEventListener("focus-active-terminal-session",$),window.addEventListener("open-terminal-split-chooser",ee),window.addEventListener("close-terminal-split",ie),window.addEventListener("remove-terminal-split-pane",Qe),window.addEventListener("set-terminal-split-direction",ze),window.addEventListener("cycle-terminal-session",xt),window.addEventListener("close-terminal-session",_t),window.addEventListener("close-terminal-session-by-backend",Mr),window.addEventListener("rename-terminal-session",Dt),window.addEventListener("reset-terminal-session-name",Gr),window.addEventListener("reorder-terminal-session",dn),window.addEventListener("reorder-terminal-split-workspace",jn),window.addEventListener("rename-terminal-split-workspace",ns),window.addEventListener("combine-terminal-split-sessions",Un),()=>{window.removeEventListener("new-terminal-session",z),window.removeEventListener("switch-terminal-session",N),window.removeEventListener("focus-active-terminal-session",$),window.removeEventListener("open-terminal-split-chooser",ee),window.removeEventListener("close-terminal-split",ie),window.removeEventListener("remove-terminal-split-pane",Qe),window.removeEventListener("set-terminal-split-direction",ze),window.removeEventListener("cycle-terminal-session",xt),window.removeEventListener("close-terminal-session",_t),window.removeEventListener("close-terminal-session-by-backend",Mr),window.removeEventListener("rename-terminal-session",Dt),window.removeEventListener("reset-terminal-session-name",Gr),window.removeEventListener("reorder-terminal-session",dn),window.removeEventListener("reorder-terminal-split-workspace",jn),window.removeEventListener("rename-terminal-split-workspace",ns),window.removeEventListener("combine-terminal-split-sessions",Un)}},[Ln,kn,qe,ps,Ke,ct,ot,Ft,At,Rt,Bt]),b.useEffect(()=>{if(!Sr||q)return;const z=N=>{if(!fC(N,D1())||!(N.ctrlKey||N.metaKey)||!N.shiftKey)return;if(Sr.layout==="horizontal"?N.key==="ArrowLeft"||N.key==="ArrowRight":Sr.layout==="vertical"?N.key==="ArrowUp"||N.key==="ArrowDown":N.key.startsWith("Arrow")){N.preventDefault(),N.stopPropagation();const ee=Sr.sessionIds.indexOf(nr.current??""),ie=N.key==="ArrowLeft"||N.key==="ArrowUp"?-1:1,Qe=(Math.max(0,ee)+ie+Sr.sessionIds.length)%Sr.sessionIds.length,ze=Sr.sessionIds[Qe];if(!ze)return;Ln(ze);return}N.key==="Backspace"&&(N.preventDefault(),N.stopPropagation(),Ke(nr.current??void 0))};return window.addEventListener("keydown",z,!0),()=>window.removeEventListener("keydown",z,!0)},[Ln,Sr,Ke,q]);const hr=z=>{const N=Yr.getState().sessions.get(z.id);return il(z,N?.activeProgram??null,N?.cwd??null,void 0,N?.shellTitle??null,N?.promptState??null)},Kt=(z,N={})=>{const $=z.id===Z&&!te?.startsWith("@collaboration:"),ee=Kr.has(z.id)&&!N.hidden,ie=p&&DE({sessionId:z.id,foregroundSessionId:Or,visibleSessionIds:Kr,deferredViewportSessionIds:q?sn:Zn}),Qe=jE({sessionId:z.id,foregroundSessionId:Or,foregroundReady:fn,isVisible:ee})&&p,ze=FE({sessionId:z.id,foregroundSessionId:Or,requestToken:lt.token,foregroundCompletedToken:Et,isVisible:K.has(z.id)})&&p,xt=ee||z.id===Or||Zn.has(z.id)?0:Xr.get(z.id)??Vh;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:()=>{ee&&Hx($,()=>Ln(z.id))},onWheelCapture:()=>{Hx($,()=>Ln(z.id))},children:[N.showPaneTitle&&s.jsx(iN,{session:z,active:$,onActivate:()=>Ln(z.id),onToggleRightSidebar:$?x:void 0}),s.jsx("div",{className:"min-h-0 flex-1 app-chrome-bg",children:ie&&s.jsx(sN,{sessionId:z.id,mode:z.mode,tmuxSessionName:z.tmuxSessionName,terminalSettings:e,colorTheme:t,toolbarPresets:r,isActive:$,focusSuspended:ke!==null,deferCursorUntilPositioned:ke===z.id||z.mode==="tmux"&&!Ne.has(z.id),isLayoutVisible:ee,initialConnectEnabled:Qe&&ze,resumeRequestEnabled:ze,suppressKeyboard:N.suppressKeyboard,keyboardPortalTarget:N.keyboardPortalTarget,sharedMobileKeyboardLayout:N.sharedMobileKeyboardLayout,suppressPageFlipRefresh:N.suppressPageFlipRefresh,focusRequestToken:Ie?.sessionId===z.id?Ie.token:0,resumeRequestToken:lt.token,resumeRequestReason:lt.reason,forceResumeReconnect:lt.forceForegroundReconnect&&K.has(z.id),resumeRequestDelayMs:K.has(z.id)?0:N.hidden?Vh:Xr.get(z.id)??Vh,initialConnectDelayMs:xt,onStreamReadyChange:kt,onStreamConnected:tr,onViewportReadyChange:Qr,onContentReadyChange:cr,onKeyboardVisibilityChange:Kn,showDebug:n,onStatusChange:$?S:void 0})})]},z.id)};return s.jsxs("div",{className:"relative h-full flex flex-col",children:[vt&&U.some(z=>z.id===vt.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:U.find(z=>z.id===vt.sessionId).name})}),s.jsx("button",{type:"button",className:"shrink-0 rounded-lg px-2 py-1 text-primary hover:bg-surface-2",onClick:()=>{ot(vt)},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(Rn,{size:16})})]}),mr&&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(Q1,{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:mr.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:mr.sessions.map(z=>z.name).join(" · ")}),Lt&&s.jsx("p",{className:"mt-2 text-[10px] text-destructive",children:Lt}),s.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[s.jsxs("button",{type:"button",disabled:Xt!==null,onClick:()=>{Hr()},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(Qy,{size:13,className:Xt==="restore"?"animate-spin":""}),B(Xt==="restore"?"tab.tmuxRecoveryRestoring":"tab.tmuxRecoveryRestoreAll")]}),s.jsx("button",{type:"button",disabled:Xt!==null,onClick:()=>{_n()},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(lA,{onSwiper:z=>{Ye.current=z,z.allowTouchMove=Br.length>1&&!hn&&!oe,_r("[swiper:on-swiper]",{allowTouchMove:z.allowTouchMove}),requestAnimationFrame(()=>Er("on-swiper"))},onSlideChange:kr,onTouchStart:(z,N)=>{const $=qx(N),ee=$==="touch"||$==="pen"||$==="unknown";F("[swipe:touch-start]",{pointerType:$,allowed:ee}),_r("[swiper:touch-start]",{pointerType:$,allowed:ee}),ee&&(Wn(),bt.current=!0,gt.current=!0)},onTouchEnd:(z,N)=>{const $=qx(N),ee=$==="touch"||$==="pen"||$==="unknown";F("[swipe:touch-end]",{pointerType:$,allowed:ee}),_r("[swiper:touch-end]",{pointerType:$,allowed:ee}),ee&&(bt.current=!1,Gn("touch-end"))},onTransitionEnd:()=>{const z=Ye.current;if(bt.current){_r("[swiper:transition-end-during-touch]");return}if(gt.current&&z&&!vN(z,ge.current)){_r("[swiper:transition-end-deferred]");return}Wn(),gt.current=!1,_r("[swiper:transition-end]")},initialSlide:Math.max(0,$r),speed:u1,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:Br.map(z=>{const N=z.workspace,$=!!N&&z.sessions.length>=2,ee=q?qt?"horizontal":"vertical":N?.layout??"horizontal",ie=q&&et?z.sessions.some(ze=>ze.id===et):!1,Qe=z.sessions.some(ze=>ze.id===Z)?Z:z.sessions[0]?.id;return s.jsx(cA,{className:"h-full",children:s.jsx("div",{className:"h-full min-w-0","data-pinned-right-sidebar-inset":nn.get(z.key)??0,style:{paddingRight:nn.get(z.key)??0,paddingTop:y&&!$?"2.5rem":void 0},children:$?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(b2,{layoutId:z.key,preset:N?.layout??"horizontal",initialTree:aC(z.sessions.map(ze=>ze.id),ee,N?.ratios,N?.gridColumnRatios,N?.gridRowRatios),mobile:q,focusId:ie?et:null,panes:z.sessions.map(ze=>({id:ze.id,content:Kt(ze,{showPaneTitle:!q,suppressKeyboard:q&&ze.id!==Qe,keyboardPortalTarget:q?De:null,sharedMobileKeyboardLayout:q,suppressPageFlipRefresh:!0})}))}),q&&s.jsx("div",{ref:er,className:"relative shrink-0 app-chrome-bg","data-split-keyboard-host":"true"})]}):s.jsx(b2,{layoutId:z.key,preset:N?.layout??"horizontal",mobile:q,panes:[{id:z.sessions[0].id,content:Kt(z.sessions[0])}]})})},z.key)})})}),oe&&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:()=>Ze(!1),"aria-label":B("common.close")}),s.jsxs("section",{ref:Je,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:()=>Ze(!1),"aria-label":B("common.close"),children:s.jsx(Rn,{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:Ge,onClick:()=>{Le()},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(Us,{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")})]})]}),Te.filter(z=>z.id!==Sr?.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")}),Te.filter(z=>z.id!==Sr?.id).map((z,N)=>{const $=z.sessionIds.flatMap(Qe=>{const ze=U.find(xt=>xt.id===Qe);return ze?[ze]:[]});if($.length<2)return null;const ee=z.name||`${B("tab.splitWorkspace")} ${N+1}`,ie=$.map(Qe=>hr(Qe).primary).join(" · ");return s.jsxs("button",{type:"button",onClick:()=>G($[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:ee}),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:$.length})," · ",ie]})]}),s.jsx(hi,{size:14,className:"text-primary opacity-0 transition group-hover:opacity-100"})]},z.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")}),U.filter(z=>!Te.some(N=>N.sessionIds.includes(z.id))&&z.id!==Z).length===0&&Te.filter(z=>z.id!==Sr?.id).length===0?s.jsx("p",{className:"px-3 py-4 text-[12px] text-muted-foreground",children:B("tab.splitNoOtherSessions")}):U.filter(z=>!Te.some(N=>N.sessionIds.includes(z.id))&&z.id!==Z).map(z=>{const N=Pr.get(z.id)??null,$=hr(z);return s.jsxs("button",{type:"button",onClick:()=>G(z.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(Gc,{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:$.primary}),s.jsx("span",{className:"mt-0.5 block truncate text-[10px] text-muted-foreground",children:N?Yu(N)??N:z.name})]}),s.jsx(hi,{size:14,className:"text-primary opacity-0 transition group-hover:opacity-100"})]},z.id)})]})]})]}),Vt&&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:Vt})]})},_N={sm:"h-4 w-7",md:"h-6 w-10"},kN={sm:"h-3 w-3",md:"h-5 w-5"},LN={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 ${_N[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 ${kN[r]} ${e?LN[r]:""}`})})}function aa(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 IN=typeof Symbol=="function"&&Symbol.observable||"@@observable",Zx=IN,Kx=()=>Math.random().toString(36).substring(7).split("").join("."),EN={INIT:`@@redux/INIT${Kx()}`,REPLACE:`@@redux/REPLACE${Kx()}`},Xx=EN;function NN(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 av(e,t,r){if(typeof e!="function")throw new Error(aa(2));if(typeof t=="function"&&typeof r=="function"||typeof r=="function"&&typeof arguments[3]=="function")throw new Error(aa(0));if(typeof t=="function"&&typeof r>"u"&&(r=t,t=void 0),typeof r<"u"){if(typeof r!="function")throw new Error(aa(1));return r(av)(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(aa(3));return a}function y(E){if(typeof E!="function")throw new Error(aa(4));if(p)throw new Error(aa(5));let R=!0;m();const B=d++;return l.set(B,E),function(){if(R){if(p)throw new Error(aa(6));R=!1,m(),l.delete(B),c=null}}}function w(E){if(!NN(E))throw new Error(aa(7));if(typeof E.type>"u")throw new Error(aa(8));if(typeof E.type!="string")throw new Error(aa(17));if(p)throw new Error(aa(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(aa(10));n=E,w({type:Xx.REPLACE})}function S(){const E=y;return{subscribe(R){if(typeof R!="object"||R===null)throw new Error(aa(11));function B(){const F=R;F.next&&F.next(x())}return B(),{unsubscribe:E(B)}},[Zx](){return this}}}return w({type:Xx.INIT}),{dispatch:w,subscribe:y,getState:x,replaceReducer:v,[Zx]:S}}function Jx(e,t){return function(...r){return t(e.apply(this,r))}}function e5(e,t){if(typeof e=="function")return Jx(e,t);if(typeof e!="object"||e===null)throw new Error(aa(16));const r={};for(const n in e){const a=e[n];typeof a=="function"&&(r[n]=Jx(a,t))}return r}function ov(...e){return e.length===0?t=>t:e.length===1?e[0]:e.reduce((t,r)=>(...n)=>t(r(...n)))}function RN(...e){return t=>(r,n)=>{const a=t(r,n);let c=()=>{throw new Error(aa(15))};const l={getState:a.getState,dispatch:(p,...m)=>c(p,...m)},d=e.map(p=>p(l));return c=ov(...d)(a.dispatch),{...a,dispatch:c}}}var nm={exports:{}},sm={};var t5;function MN(){if(t5)return sm;t5=1;var e=wA();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 sm.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(U){if(!R){if(R=!0,B=U,U=y(U),w!==void 0&&S.hasValue){var V=S.value;if(w(V,U))return W=V}return W=U}if(V=W,r(B,U))return V;var Z=y(U);return w!==void 0&&w(V,Z)?(B=U,V):(B=U,W=Z)}var R=!1,B,W,F=x===void 0?null:x;return[function(){return E(m())},F===null?void 0:function(){return E(F())}]},[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},sm}var r5;function jN(){return r5||(r5=1,nm.exports=MN()),nm.exports}jN();var DN=b.version.startsWith("19"),BN=Symbol.for(DN?"react.transitional.element":"react.element"),QN=Symbol.for("react.portal"),PN=Symbol.for("react.fragment"),ON=Symbol.for("react.strict_mode"),FN=Symbol.for("react.profiler"),$N=Symbol.for("react.consumer"),UN=Symbol.for("react.context"),lv=Symbol.for("react.forward_ref"),zN=Symbol.for("react.suspense"),HN=Symbol.for("react.suspense_list"),rg=Symbol.for("react.memo"),WN=Symbol.for("react.lazy"),GN=lv,VN=rg;function qN(e){if(typeof e=="object"&&e!==null){const{$$typeof:t}=e;switch(t){case BN:switch(e=e.type,e){case PN:case FN:case ON:case zN:case HN:return e;default:switch(e=e&&e.$$typeof,e){case UN:case lv:case WN:case rg:return e;case $N:return e;default:return t}}case QN:return t}}}function YN(e){return qN(e)===rg}function ZN(e,t,r,n,{areStatesEqual:a,areOwnPropsEqual:c,areStatePropsEqual:l}){let d=!1,p,m,x,y,w;function v(B,W){return p=B,m=W,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),W=!l(B,x);return x=B,W&&(w=r(x,y,m)),w}function R(B,W){const F=!c(W,m),U=!a(B,p,W,m);return p=B,m=W,F&&U?S():F?L():U?E():w}return function(W,F){return d?R(W,F):v(W,F)}}function KN(e,{initMapStateToProps:t,initMapDispatchToProps:r,initMergeProps:n,...a}){const c=t(e,a),l=r(e,a),d=n(e,a);return ZN(c,l,d,e,a)}function XN(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 f1(e){return function(r){const n=e(r);function a(){return n}return a.dependsOnOwnProps=!1,a}}function n5(e){return e.dependsOnOwnProps?!!e.dependsOnOwnProps:e.length!==1}function cv(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=n5(e);let m=c(d,p);return typeof m=="function"&&(c.mapToProps=m,c.dependsOnOwnProps=n5(m),m=c(d,p)),m},c}}function ng(e,t){return(r,n)=>{throw new Error(`Invalid value of type ${typeof e} for ${t} argument when connecting component ${n.wrappedComponentName}.`)}}function JN(e){return e&&typeof e=="object"?f1(t=>XN(e,t)):e?typeof e=="function"?cv(e):ng(e,"mapDispatchToProps"):f1(t=>({dispatch:t}))}function eR(e){return e?typeof e=="function"?cv(e):ng(e,"mapStateToProps"):f1(()=>({}))}function tR(e,t,r){return{...r,...e,...t}}function rR(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 nR(e){return e?typeof e=="function"?rR(e):ng(e,"mergeProps"):()=>tR}function sR(e){e()}function iR(){let e=null,t=null;return{clear(){e=null,t=null},notify(){sR(()=>{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 s5={notify(){},get:()=>[]};function uv(e,t){let r,n=s5,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=iR())}function y(){a--,r&&a===0&&(r(),r=void 0,n.clear(),n=s5)}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 aR=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",oR=aR(),lR=()=>typeof navigator<"u"&&navigator.product==="ReactNative",cR=lR(),uR=()=>oR||cR?b.useLayoutEffect:b.useEffect,wf=uR();function i5(e,t){return e===t?e!==0||t!==0||1/e===1/t:e!==e&&t!==t}function im(e,t){if(i5(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])||!i5(e[r[a]],t[r[a]]))return!1;return!0}var dR={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},hR={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},fR={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},dv={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},pR={[GN]:fR,[VN]:dv};function a5(e){return YN(e)?dv:pR[e.$$typeof]||dR}var mR=Object.defineProperty,gR=Object.getOwnPropertyNames,o5=Object.getOwnPropertySymbols,xR=Object.getOwnPropertyDescriptor,bR=Object.getPrototypeOf,l5=Object.prototype;function p1(e,t){if(typeof t!="string"){if(l5){const c=bR(t);c&&c!==l5&&p1(e,c)}let r=gR(t);o5&&(r=r.concat(o5(t)));const n=a5(e),a=a5(t);for(let c=0;c<r.length;++c){const l=r[c];if(!hR[l]&&!(a&&a[l])&&!(n&&n[l])){const d=xR(t,l);try{mR(e,l,d)}catch{}}}}return e}var yR=Symbol.for("react-redux-context"),vR=typeof globalThis<"u"?globalThis:{};function wR(){if(!b.createContext)return{};const e=vR[yR]??=new Map;let t=e.get(b.createContext);return t||(t=b.createContext(null),e.set(b.createContext,t)),t}var hv=wR(),AR=[null,null];function TR(e,t,r){wf(()=>e(...t),r)}function SR(e,t,r,n,a,c){e.current=n,r.current=!1,a.current&&(a.current=null,c())}function CR(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 _R(e,t){return e===t}function kR(e,t,r,{pure:n,areStatesEqual:a=_R,areOwnPropsEqual:c=im,areStatePropsEqual:l=im,areMergedPropsEqual:d=im,forwardRef:p=!1,context:m=hv}={}){const x=m,y=eR(e),w=JN(t),v=nR(r),S=!!e;return E=>{const R=E.displayName||E.name||"Component",B=`Connect(${R})`,W={shouldHandleStateChanges:S,displayName:B,wrappedComponentName:R,WrappedComponent:E,initMapStateToProps:y,initMapDispatchToProps:w,initMergeProps:v,areStatesEqual:a,areStatePropsEqual:l,areOwnPropsEqual:c,areMergedPropsEqual:d};function F(Z){const[ce,xe,pe]=b.useMemo(()=>{const{reactReduxForwardedRef:Ye,...st}=Z;return[Z.context,Ye,st]},[Z]),te=b.useMemo(()=>{let Ye=x;return ce?.Consumer,Ye},[ce,x]),ke=b.useContext(te),$e=!!Z.store&&!!Z.store.getState&&!!Z.store.dispatch,Y=!!ke&&!!ke.store,Ae=$e?Z.store:ke.store,lt=Y?ke.getServerState:Ae.getState,Se=b.useMemo(()=>KN(Ae.dispatch,W),[Ae]),[ye,_e]=b.useMemo(()=>{if(!S)return AR;const Ye=uv(Ae,$e?void 0:ke.subscription),st=Ye.notifyNestedSubs.bind(Ye);return[Ye,st]},[Ae,$e,ke]),je=b.useMemo(()=>$e?ke:{...ke,subscription:ye},[$e,ke,ye]),re=b.useRef(void 0),Oe=b.useRef(pe),Ce=b.useRef(void 0),Ee=b.useRef(!1),Be=b.useRef(!1),Ne=b.useRef(void 0);wf(()=>(Be.current=!0,()=>{Be.current=!1}),[]);const le=b.useMemo(()=>()=>Ce.current&&pe===Oe.current?Ce.current:Se(Ae.getState(),pe),[Ae,pe]),He=b.useMemo(()=>st=>ye?CR(S,Ae,ye,Se,Oe,re,Ee,Be,Ce,_e,st):()=>{},[ye]);TR(SR,[Oe,re,Ee,pe,Ce,_e]);let rt;try{rt=b.useSyncExternalStore(He,le,lt?()=>Se(lt(),pe):le)}catch(Ye){throw Ne.current&&(Ye.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:Ef[t.status]??"成员明确报告",createdAt:l?t.createdAt:null,content:r,summary:c?c.slice(0,512):"报告摘要未提供,请查看详情中的原始报告"}}function Xf(e){if(e.status!=="open")return[];const t=x6(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 JB(e){return Xf(e)[0]??null}function Yc(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=JB(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?Ef[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 Fi(e){return e.purpose!=="automation"&&e.status==="open"&&["需要你回答","需要你确认方案","等待你验收","执行准备受阻","自动安排受阻","成员报告受阻","成员报告失败","投递未成功","投递需要关注","投递需要处理"].includes(Yc(e))}const _u=hc(e=>{let t=!1;return{tasks:[],allTasks:[],error:null,refresh:async()=>{if(!t){t=!0;try{const{tasks:r}=await vy();e({tasks:r.filter(Fi),allTasks:r,error:null})}catch(r){e({error:r instanceof Error?r.message:"协作待处理事项加载失败"})}finally{t=!1}}}}});function P5(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 O5({sessionIds:e}){const t=kw(a=>e.reduce((c,l)=>c+(a.unread[l]?.length??0),0)),{locale:r}=zr();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 eQ(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 b6(e){const t=eQ(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 tQ(e,t,r){return Math.max(t,Math.min(e,r))}const hs={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 F5(e,t,r){return t===0||Math.abs(t)===1/0?Math.pow(e,r*5):e*t*r/(t+r*e)}function $5(e,t,r,n=.15){return n===0?tQ(e,t,r):e<t?-F5(t-e,r-t,n)+t:e>r?+F5(e-r,r-t,n)+r:e}function rQ(e,[t,r],[n,a]){const[[c,l],[d,p]]=e;return[$5(t,c,l,n),$5(r,d,p,a)]}function nQ(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 sQ(e){var t=nQ(e,"string");return typeof t=="symbol"?t:String(t)}function Ps(e,t,r){return t=sQ(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function U5(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?U5(Object(r),!0).forEach(function(n){Ps(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):U5(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}const y6={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 z5(e){return e?e[0].toUpperCase()+e.slice(1):""}const iQ=["enter","leave"];function aQ(e=!1,t){return e&&!iQ.includes(t)}function oQ(e,t="",r=!1){const n=y6[e],a=n&&n[t]||t;return"on"+z5(e)+z5(a)+(aQ(r,a)?"Capture":"")}const lQ=["gotpointercapture","lostpointercapture"];function cQ(e){let t=e.substring(2).toLowerCase();const r=!!~t.indexOf("passive");r&&(t=t.replace("passive",""));const n=lQ.includes(t)?"capturecapture":"capture",a=!!~t.indexOf(n);return a&&(t=t.replace("capture","")),{device:t,capture:a,passive:r}}function uQ(e,t=""){const r=y6[e],n=r&&r[t]||t;return e+n}function Jf(e){return"touches"in e}function v6(e){return Jf(e)?"touch":"pointerType"in e?e.pointerType:"mouse"}function dQ(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 hQ(e){return e.type==="touchend"||e.type==="touchcancel"?e.changedTouches:e.targetTouches}function w6(e){return Jf(e)?hQ(e)[0]:e}function A1(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 fQ(e){return dQ(e).map(t=>t.identifier)}function H5(e,t){const[r,n]=Array.from(e.touches).filter(a=>t.includes(a.identifier));return A1(r,n)}function gm(e){const t=w6(e);return Jf(e)?t.identifier:t.pointerId}function Vu(e){const t=w6(e);return[t.clientX,t.clientY]}const W5=40,G5=800;function A6(e){let{deltaX:t,deltaY:r,deltaMode:n}=e;return n===1?(t*=W5,r*=W5):n===2&&(t*=G5,r*=G5),[t,r]}function pQ(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 mQ(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 Nf(e,...t){return typeof e=="function"?e(...t):e}function gQ(){}function xQ(...e){return e.length===0?gQ:e.length===1?e[0]:function(){let t;for(const r of e)t=r.apply(this,arguments)||t;return t}}function V5(e,t){return Object.assign({},t,e||{})}const bQ=32;class T6{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?Nf(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,mQ(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);hs.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=Nf(n.bounds,r)),this.setup&&this.setup()),r.movement=w,this.computeOffset()));const[L,E]=r.offset,[[R,B],[W,F]]=r._bounds;r.overflow=[L<R?-1:L>B?1:0,E<W?-1:E>F?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 U=r._active?n.rubberband||[0,0]:[0,0];if(r.offset=rQ(r._bounds,r.offset,U),r.delta=hs.sub(r.offset,v),this.computeMovement(),S&&(!r.last||c>bQ)){r.delta=hs.sub(r.offset,v);const V=r.delta.map(Math.abs);hs.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 yQ([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 Q0 extends T6{constructor(...t){super(...t),Ps(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=hs.add(this.state.lastOffset,this.state.movement)}computeMovement(){this.state.movement=hs.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[v6(t)]:n.axisThreshold;r.axis=yQ(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 vQ=e=>e,q5=.15,S6={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[q5,q5];case!1:return[0,0];default:return hs.toVector(e)}},from(e){if(typeof e=="function")return e;if(e!=null)return hs.toVector(e)},transform(e,t,r){const n=e||r.shared.transform;return this.hasCustomTransform=!!n,n||vQ},threshold(e){return hs.toVector(e,0)}},wQ=0,Kc=vs(vs({},S6),{},{axis(e,t,{axis:r}){if(this.lockDirection=r==="lock",!this.lockDirection)return r},axisThreshold(e=wQ){return e},bounds(e={}){if(typeof e=="function")return c=>Kc.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]]}}),Y5={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 AQ extends Q0{constructor(...t){super(...t),Ps(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=Kc.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=gm(t),n._pointerActive=!0,this.computeValues(Vu(t)),this.computeInitial(),r.preventScrollAxis&&v6(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=gm(t);if(r._pointerId!==void 0&&a!==r._pointerId)return;const c=Vu(t);if(document.pointerLockElement===t.target?r._delta=[t.movementX,t.movementY]:(r._delta=hs.sub(c,r._values),this.computeValues(c)),hs.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=gm(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,TQ(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=Y5[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,hs.addTo(n._movement,n._delta),this.compute(t),this.emit()}}keyUp(t){t.key in Y5&&(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 TQ(e){"persist"in e&&typeof e.persist=="function"&&e.persist()}const P0=typeof window<"u"&&window.document&&window.document.createElement;function C6(){return P0&&"ontouchstart"in window}function SQ(){return C6()||P0&&window.navigator.maxTouchPoints>1}function CQ(){return P0&&"onpointerdown"in window}function _Q(){return P0&&"exitPointerLock"in window.document}function kQ(){try{return"constructor"in GestureEvent}catch{return!1}}const go={isBrowser:P0,gesture:kQ(),touch:C6(),touchscreen:SQ(),pointer:CQ(),pointerLock:_Q()},LQ=250,IQ=180,EQ=.5,NQ=50,RQ=250,MQ=10,Z5={mouse:0,touch:0,pen:8},jQ=vs(vs({},Kc),{},{device(e,t,{pointer:{touch:r=!1,lock:n=!1,mouse:a=!1}={}}){return this.pointerLock=n&&go.pointerLock,go.touch&&r?"touch":this.pointerLock?"mouse":go.pointer&&!a?"pointer":go.touch?"touch":"mouse"},preventScrollAxis(e,t,{preventScroll:r}){if(this.preventScrollDelay=typeof r=="number"?r:r||r===void 0&&e?LQ:void 0,!(!go.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=hs.toVector(e,r?n:a?1:0);return this.filterTaps=r,this.tapsThreshold=n,c},swipe({velocity:e=EQ,distance:t=NQ,duration:r=RQ}={}){return{velocity:this.transform(hs.toVector(e)),distance:this.transform(hs.toVector(t)),duration:r}},delay(e=0){switch(e){case!0:return IQ;case!1:return 0;default:return e}},axisThreshold(e){return e?vs(vs({},Z5),e):Z5},keyboardDisplacement(e=MQ){return e}});function _6(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 DQ=30,BQ=100;class QQ extends T6{constructor(...t){super(...t),Ps(this,"ingKey","pinching"),Ps(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=hs.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)*DQ-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=H5(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=A1(...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=H5(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=A1(...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=hs.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=[-A6(t)[1]/BQ*n.offset[0],0],hs.addTo(n._movement,n._delta),_6(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 PQ=vs(vs({},S6),{},{device(e,t,{shared:r,pointer:{touch:n=!1}={}}){if(r.target&&!go.touch&&go.gesture)return"gesture";if(go.touch&&n)return"touch";if(go.touchscreen){if(go.pointer)return"pointer";if(go.touch)return"touch"}},bounds(e,t,{scaleBounds:r={},angleBounds:n={}}){const a=l=>{const d=V5(Nf(r,l),{min:-1/0,max:1/0});return[d.min,d.max]},c=l=>{const d=V5(Nf(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",hs.toVector(e,this.lockDirection?[.1,3]:0)},modifierKey(e){return e===void 0?"ctrlKey":e},pinchOnWheel(e=!0){return e}});class OQ extends Q0{constructor(...t){super(...t),Ps(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(Vu(t)),this.compute(t),this.computeInitial(),this.emit()}moveChange(t){if(!this.state._active)return;const r=Vu(t),n=this.state;n._delta=hs.sub(r,n._values),hs.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 FQ=vs(vs({},Kc),{},{mouseOnly:(e=!0)=>e});class $Q extends Q0{constructor(...t){super(...t),Ps(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=pQ(t);r._delta=hs.sub(n,r._values),hs.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 UQ=Kc;class zQ extends Q0{constructor(...t){super(...t),Ps(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=A6(t),hs.addTo(r._movement,r._delta),_6(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 HQ=Kc;class WQ extends Q0{constructor(...t){super(...t),Ps(this,"ingKey","hovering")}enter(t){this.config.mouseOnly&&t.pointerType!=="mouse"||(this.start(t),this.computeValues(Vu(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=Vu(t);r._movement=r._delta=hs.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 GQ=vs(vs({},Kc),{},{mouseOnly:(e=!0)=>e}),Sg=new Map,T1=new Map;function k6(e){Sg.set(e.key,e.engine),T1.set(e.key,e.resolver)}const L6={key:"drag",engine:AQ,resolver:jQ},VQ={key:"hover",engine:WQ,resolver:GQ},qQ={key:"move",engine:OQ,resolver:FQ},YQ={key:"pinch",engine:QQ,resolver:PQ},ZQ={key:"scroll",engine:$Q,resolver:UQ},KQ={key:"wheel",engine:zQ,resolver:HQ};function XQ(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 JQ(e,t){if(e==null)return{};var r=XQ(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 eP={target(e){if(e)return()=>"current"in e?e.current:e},enabled(e=!0){return e},window(e=go.isBrowser?window:void 0){return e},eventOptions({passive:e=!0,capture:t=!1}={}){return{passive:e,capture:t}},transform(e){return e}},tP=["target","eventOptions","window","enabled","transform"];function Kh(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]=Kh(e[n],a);break;case"boolean":a&&(r[n]=e[n]);break}return r}function rP(e,t,r={}){const n=e,{target:a,eventOptions:c,window:l,enabled:d,transform:p}=n,m=JQ(n,tP);if(r.shared=Kh({target:a,eventOptions:c,window:l,enabled:d,transform:p},eP),t){const x=T1.get(t);r[t]=Kh(vs({shared:r.shared},m),x)}else for(const x in m){const y=T1.get(x);y&&(r[x]=Kh(vs({shared:r.shared},m[x]),y))}return r}class I6{constructor(t,r){Ps(this,"_listeners",new Set),this._ctrl=t,this._gestureKey=r}add(t,r,n,a,c){const l=this._listeners,d=uQ(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 nP{constructor(){Ps(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 sP{constructor(t){Ps(this,"gestures",new Set),Ps(this,"_targetEventStore",new I6(this)),Ps(this,"gestureEventStores",{}),Ps(this,"gestureTimeoutStores",{}),Ps(this,"handlers",{}),Ps(this,"config",{}),Ps(this,"pointerIds",new Set),Ps(this,"touchIds",new Set),Ps(this,"state",{shared:{shiftKey:!1,metaKey:!1,ctrlKey:!1,altKey:!1}}),iP(this,t)}setEventIds(t){if(Jf(t))return this.touchIds=new Set(fQ(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=rP(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=K5(n,d.eventOptions,!!a);if(d.enabled){const m=Sg.get(l);new m(this,t,l).bind(p)}}const c=K5(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]=xQ(...n[c]);if(!a)return n;for(const c in n){const{device:l,capture:d,passive:p}=cQ(c);this._targetEventStore.add(a,l,"",n[c],{capture:d,passive:p})}}}}function yu(e,t){e.gestures.add(t),e.gestureEventStores[t]=new I6(e,t),e.gestureTimeoutStores[t]=new nP}function iP(e,t){t.drag&&yu(e,"drag"),t.wheel&&yu(e,"wheel"),t.scroll&&yu(e,"scroll"),t.move&&yu(e,"move"),t.pinch&&yu(e,"pinch"),t.hover&&yu(e,"hover")}const K5=(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:oQ(n,a,x);r&&y&&(w+="Passive"),e[w]=e[w]||[],e[w].push(c)},aP=/^on(Drag|Wheel|Scroll|Move|Pinch|Hover)/;function oP(e){const t={},r={},n=new Set;for(let a in e)aP.test(a)?(n.add(RegExp.lastMatch),r[a]=e[a]):t[a]=e[a];return[r,t,n]}function vu(e,t,r,n,a,c){if(!e.has(r)||!Sg.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 lP(e,t){const[r,n,a]=oP(e),c={};return vu(a,r,"onDrag","drag",c,t),vu(a,r,"onWheel","wheel",c,t),vu(a,r,"onScroll","scroll",c,t),vu(a,r,"onPinch","pinch",c,t),vu(a,r,"onMove","move",c,t),vu(a,r,"onHover","hover",c,t),{handlers:c,config:t,nativeHandlers:n}}function E6(e,t={},r,n){const a=k.useMemo(()=>new sP(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 X5(e,t){return k6(L6),E6({drag:e},t||{},"drag")}function cP(e){return e.forEach(k6),function(r,n){const{handlers:a,nativeHandlers:c,config:l}=lP(r,n||{});return E6(a,l,void 0,c)}}function NU(e,t){return cP([L6,YQ,ZQ,KQ,qQ,VQ])(e,t||{})}const J5={dampingRatio:.8,response:.3},uP=.998;function dP(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 hP(e,t=uP){return e/1e3*(t/(1-t))}function eb(e,t,r=.55){return e*t*r/(t+r*Math.abs(e))}function fP(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}const pP=.1,mP=5;function gP(e,t,r,n,a){const c=dP(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)<pP&&Math.abs(w)<mP)break}return p.push(a?a(n):n),{frames:p,durationMs:(p.length-1)*l,solver:c}}const xP='input:not([type="hidden"]), textarea, select, [contenteditable]:not([contenteditable="false"])';function bP(){if(typeof document>"u")return;const e=document.activeElement;e instanceof HTMLElement&&e.matches(xP)&&e.blur()}const yP=18,tb=8,rb={touch:tb,pen:tb},vP=500,xm=200,nb=50,wP=`[${uA}]`;function bm(e,t,r){return Math.min(r,Math.max(t,e))}function sb(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 ib(e){if(!e||typeof e!="object")return!1;const t=e.target;return t instanceof Element&&!!t.closest(wP)}function Md(...e){typeof window<"u"&&window.__SIDEBAR_DEBUG__&&console.log("[Sidebar]",...e)}const N6=k.forwardRef(function({side:t,isOpen:r,drawerWidthPx:n,onClose:a,onOpen:c,children:l,pinned:d=!1},p){const{t:m}=zr(),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),W=b.useRef(null),F=b.useRef(!1),U=b.useRef(null),V=b.useRef(!1),Z=b.useRef([]),ce=b.useRef(null),xe=b.useRef(S.current),pe=b.useRef(r?1:0),te=b.useRef(r);te.current=r;const ke=b.useRef(y);ke.current=y;const $e=b.useRef(n);$e.current=n;const Y=b.useRef(x);Y.current=x;const Ae=b.useRef(a);Ae.current=a;const lt=b.useRef(c);lt.current=c;const Se=b.useCallback(oe=>{w.current=oe,typeof p=="function"?p(oe):p&&(p.current=oe)},[p]),ye=b.useCallback(()=>{E.current!==null&&(window.cancelAnimationFrame(E.current),E.current=null),L.current=null},[]),_e=b.useCallback(oe=>{const be=$e.current;return Y.current?(oe+be)/be:(be-oe)/be},[]),je=b.useCallback(oe=>{const be=v.current;be&&(be.style.opacity=String(bm(_e(oe),0,1)))},[_e]),re=b.useCallback(oe=>{S.current=oe;const be=w.current;be&&(be.style.transform=`translateX(${oe}px)`,je(oe))},[je]),Oe=b.useCallback(oe=>{L.current=oe,E.current===null&&(E.current=window.requestAnimationFrame(()=>{E.current=null;const be=L.current;L.current=null,be!==null&&re(be)}))},[re]),Ce=b.useCallback(()=>{E.current!==null&&(window.cancelAnimationFrame(E.current),E.current=null);const oe=L.current;L.current=null,oe!==null&&re(oe)},[re]),Ee=b.useCallback(oe=>{const be=ke.current;return bm(oe,Math.min(0,be),Math.max(0,be))},[]),Be=b.useCallback(()=>{const oe=B.current;if(!oe)return null;B.current=null;const be=(performance.now()-oe.startTime)/1e3,Ze={value:oe.solver.value(be),velocity:oe.solver.velocity(be)};return oe.animations.forEach(Je=>Je.cancel()),Ze},[]),Ne=b.useCallback(()=>{W.current!==null&&(window.clearTimeout(W.current),W.current=null)},[]),le=b.useCallback(()=>{ce.current?.(),ce.current=null},[]),He=b.useCallback(()=>{Ce(),Ne();const oe=Be();oe&&re(Ee(oe.value));const be=w.current,Ze=v.current;be?.getAnimations().forEach(Je=>Je.cancel()),be&&(be.style.transition="none",be.style.opacity="1"),Ze?.getAnimations().forEach(Je=>Je.cancel()),Ze&&(Ze.style.transition="none")},[re,Ne,Ee,Ce,Be]),rt=b.useCallback((oe,be)=>{Ce(),Ne();const Ze=w.current,Je=v.current,St=oe?0:ke.current;Je&&(Je.style.pointerEvents=oe?"auto":"none");const Vt=Be(),jt=Vt?Ee(Vt.value):S.current,vt=be?.velocity??Vt?.velocity??0;if(fP())return S.current=St,Ze&&(Ze.style.transition=`opacity ${xm}ms ease`,Ze.style.opacity=oe?"1":"0",Ze.style.transform=`translateX(${St}px)`),Je&&(Je.style.transition=`opacity ${xm}ms ease`,Je.style.opacity=oe?"1":"0"),xm;Ze&&(Ze.style.transition="none",Ze.style.opacity="1"),Je&&(Je.style.transition="none");const Zt=Math.abs(be?.velocity??0)>vP,{frames:Pt,durationMs:Xt,solver:zt}=gP({dampingRatio:Zt?J5.dampingRatio:1,response:J5.response},jt,vt,St,Ee);if(!Ze||Math.abs(jt-St)<.5&&Math.abs(vt)<5)return re(St),0;const Lt=Ze.animate(Pt.map(Ge=>({transform:`translateX(${Ge}px)`})),{duration:Xt,easing:"linear",fill:"forwards"}),me=[Lt];return Je&&me.push(Je.animate(Pt.map(Ge=>({opacity:String(bm(_e(Ge),0,1))})),{duration:Xt,easing:"linear",fill:"forwards"})),B.current={solver:zt,startTime:performance.now(),target:St,animations:me},Md("spring start",{startX:jt,startVelocity:vt,targetX:St,frames:Pt.length,durationMs:Xt}),Lt.onfinish=()=>{const Ge=B.current;!Ge||!Ge.animations.includes(Lt)||(B.current=null,re(St),Ge.animations.forEach(pt=>pt.cancel()),Md("spring finish",{targetX:St}))},Xt},[re,Ne,Ee,Ce,_e,Be]),mt=b.useCallback(oe=>{Ce();const be=oe,Ze=0,Je=ke.current,St=S.current+hP(be),Vt=Math.abs(St-Ze)<=Math.abs(St-Je);Md("decideSnap",{velocity:be,currentX:S.current,projected:St,shouldOpen:Vt});const jt=rt(Vt,{velocity:be});return Vt&&!te.current?W.current=window.setTimeout(()=>{W.current=null,lt.current?.()},jt+nb):!Vt&&te.current&&(W.current=window.setTimeout(()=>{W.current=null,Ae.current()},jt+nb)),Vt},[rt,Ce]),ue=b.useCallback(oe=>{const be=ke.current,Ze=Math.min(0,be),Je=Math.max(0,be),St=$e.current;return oe<Ze?Ze-eb(Ze-oe,St):oe>Je?Je+eb(oe-Je,St):oe},[]),Ye=b.useCallback(oe=>{const be=Z.current,Ze=performance.now();be.push({t:Ze,x:oe});const Je=Ze-120;for(;be.length>0&&be[0].t<Je;)be.shift()},[]),st=b.useCallback(()=>{const oe=Z.current;if(oe.length<2)return 0;const be=oe[oe.length-1];if(performance.now()-be.t>60)return 0;const Ze=oe[0],Je=(be.t-Ze.t)/1e3;return Je<.016?0:(be.x-Ze.x)/Je},[]);b.useEffect(()=>{Ne();const oe=B.current,be=r?0:ke.current;oe&&oe.target===be||rt(r)},[r,rt,Ne]),b.useEffect(()=>{He(),Oe(te.current?0:y)},[y,He,Oe]),b.useEffect(()=>()=>{ye(),Ne(),Be(),le()},[Ne,ye,le,Be]);const Ie=X5(({active:oe,cancel:be,first:Ze,last:Je,movement:[St],event:Vt})=>{if(Md("bindPanel",{active:oe,first:Ze,last:Je,mx:St}),!sb(Vt)){be();return}if(Ze){if(le(),F.current=!1,U.current=null,Z.current=[],ib(Vt)){be();return}const jt=w.current,vt=jt?dA(Vt.target,jt):null;if(!vt||hA()){be();return}const Zt=fA(vt,St,Y.current?-1:1);if(Md("arbitrate",{owner:Zt.kind,mx:St}),Zt.kind==="swiper"){ce.current=pA(Zt.instance),be();return}if(Zt.kind==="scroller"){const Pt=mA(Zt.element);if(Pt)U.current=Pt;else{be();return}}U.current||(F.current=!0,He(),R.current=S.current)}if(!oe){U.current=null,F.current&&(F.current=!1,mt(st()));return}if(U.current){gA(U.current,St);return}if(F.current){const jt=ue(R.current+St);Ye(jt),Oe(jt)}},{axis:"x",axisThreshold:rb,filterTaps:!0,pointer:{touch:!0}}),We=X5(({active:oe,cancel:be,first:Ze,movement:[Je],event:St})=>{if(!sb(St)){be();return}if(te.current){be();return}if(Ze&&(V.current=!0,Z.current=[],He(),R.current=S.current),!oe){V.current&&(V.current=!1,mt(st())&&bP());return}if(V.current){const Vt=ue(R.current+Je);Ye(Vt),Oe(Vt)}},{axis:"x",axisThreshold:rb,filterTaps:!0,pointer:{touch:!0}}),Te=b.useCallback(oe=>{oe.preventDefault(),oe.stopPropagation(),te.current||lt.current?.()},[]);if(d)return s.jsx("aside",{ref:Se,"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",{...We(),style:{position:"fixed",top:"1.5rem",bottom:"10rem",...x?{left:0}:{right:0},width:yP,zIndex:"var(--z-chrome-hint)",touchAction:"none",pointerEvents:r?"none":"auto"},onClick:Te,"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:oe=>{ib(oe)||H.onClickCapture?.(oe)},ref:Se,"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(${xe.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})]})}),AP={activeKey:"root",items:[]},TP=()=>()=>{},SP=()=>AP;function CP(e){const t=Bo(),r=b.useSyncExternalStore(t?.subscribe??TP,t?.snapshot??SP),n=Lw(),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 _P({groups:e,currentKey:t,onClose:r}){const{t:n}=zr(),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],W=R[R.length-1],F=!c.current?.contains(document.activeElement);E.shiftKey&&(document.activeElement===B||F)?(E.preventDefault(),W?.focus()):!E.shiftKey&&(document.activeElement===W||F)&&(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=Bo(),R=E?.snapshot().items.find(W=>W.key===S.key);if(!R?.reviewCount||L&&!R.attentionSessions?.some(W=>W.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(Rn,{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(fi,{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 kP(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 LP(e){return e.agentStatus==="waiting"||e.agentNeedsReview===!0}function IP(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 EP(e,t,r="next"){return IP(e,t,LP,r)}const $a=42,Rf=20,NP=10;function S1(e,t,r){return Math.min(r,Math.max(t,e))}function ep(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+Rf,d=Math.max(l,e.width-r-Rf-$a),p=Math.max(t+12,52),m=Math.max(p,e.height-n-c-$a);return{minX:l,maxX:d,minY:p,maxY:m}}function ab(e,t){const r=ep(e),n=S1(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=ep(e);return{x:S1(t.x,r.minX,r.maxX),y:S1(t.y,r.minY,r.maxY)}}function ob(e,t){const r=ep(e),n=Hc(e,t),a=(r.minX+r.maxX+$a)/2,c=n.x+$a/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 lb(e,t,r){const n=Hc(e,t),a=$a+NP,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=ep(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 ym="var(--warning)",RP="var(--success)",cb="var(--tmux)",ub="termdock:mobile-attention-position:v1",db="termdock:running-session-position:v1",MP={side:"right",yRatio:.68},jP={side:"right",yRatio:.54};function hb(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 DP(e,t){try{window.localStorage.setItem(e,JSON.stringify(t))}catch{}}function Sh(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 BP(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(Sh("--safe-top-inset"),(d?Math.max(0,l.top):0)+Math.max(0,r.top??0)),safeRight:Math.max(Sh("--safe-right-inset"),(d?Math.max(0,a-l.right):0)+Math.max(0,r.right??0)),safeBottom:Math.max(Sh("--safe-bottom-inset"),(d?Math.max(0,c-l.bottom):0)+Math.max(0,r.bottom??0)),safeLeft:Math.max(Sh("--safe-left-inset"),(d?Math.max(0,l.left):0)+Math.max(0,r.left??0)),bottomClearance:e?Rf:72}}function R6(){const e=Yr.getState(),t=Array.from(e.sessions.values()),r=EP(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 fb(e){window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:e}))}function M6(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 QP({indicator:e,tone:t,size:r}){const n=M6(t);switch(e){case"spinner":return s.jsx(Cn,{size:r,className:"shrink-0 animate-spin",style:{color:n}});case"question":return s.jsx(af,{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(Fo,{size:r,className:"shrink-0",style:{color:n}});case"pulse":return s.jsx(UA,{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=kP(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(E0,{size:r,className:"text-white"})})}function PP({sessionMode:e,state:t,size:r=11}){const n=t?.agent?s.jsx(Wc,{agent:t.agent,size:r+1}):e==="tmux"?s.jsx(Uu,{size:r,className:"shrink-0"}):s.jsx(Fo,{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(QP,{indicator:t.agentIndicator,tone:t.agentStatusDetail.tone,size:r})}):t?.agentStatus==="working"?s.jsx("span",{title:t.agentMessage??t.agent?.displayName,children:s.jsx(Cn,{size:r,className:"shrink-0 animate-spin",style:{color:RP}})}):t?.agentStatus==="waiting"?s.jsx("span",{title:t.agentMessage??void 0,children:s.jsx(af,{size:r,className:"shrink-0 animate-bounce-y",style:{color:ym}})}):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:ym}})}):t?.agentNeedsReview?s.jsx("span",{title:t.agentMessage??void 0,children:s.jsx(cc,{size:r+1,className:"shrink-0 animate-pulse",style:{color:ym}})}):t?.inCopyMode?e==="tmux"?s.jsx(Uu,{size:r,className:"shrink-0 animate-pulse",style:{color:cb}}):s.jsx(Fo,{size:r,className:"shrink-0 animate-pulse",style:{color:cb}}):n}function OP({status:e,detail:t,needsReview:r,inCopyMode:n}){const{t:a}=zr();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:M6(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 j6({count:e,tone:t,title:r}){const{t:n}=zr();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:R6,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 FP({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 $P=380,pb=10,Ch=10,vm=52,UP=104;function zP(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=Rf,p=e.x+$a/2>=n+(a-n)/2,m=p?e.x-Ch-n-d:a-d-e.x-$a-Ch,x=Math.max(1,Math.min(Math.max(0,m),Math.max(168,r*UP))),y=p?e.x-Ch-x:e.x+$a+Ch,w=Math.min(Math.max(y,n+d),Math.max(n+d,a-d-x)),v=e.y+$a/2-vm/2,S=Math.min(Math.max(v,c+d),Math.max(c+d,l-d-vm));return{left:w,top:S,width:x,height:vm,itemWidth:x/Math.max(1,r),side:p?"left":"right"}}function mb(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 HP(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 WP({reviewCount:e,runningSessions:t,activeSessionId:r,runningButtonEnabled:n,attentionButtonEnabled:a=!0,isDesktopLayout:c,containerElement:l,occlusionInsets:d}){const{t:p}=zr(),m=Gt(Ie=>Ie.leftOpen),x=Gt(Ie=>Ie.rightOpen),{isOpen:y}=K3({enabled:!c}),w=c||!m&&!x&&!y,v=CP(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,W=Math.max(0,d?.top??0),F=Math.max(0,d?.right??0),U=Math.max(0,d?.bottom??0),V=Math.max(0,d?.left??0),Z=k.useCallback(()=>BP(c,l,{top:W,right:F,bottom:U,left:V}),[l,c,U,V,F,W]),ce=k.useRef({attention:hb(ub,MP),running:hb(db,jP)}),xe=k.useCallback(()=>{const Ie=Z(),We=ab(Ie,ce.current.attention),Te=ab(Ie,ce.current.running);return{attention:We,running:E&&B?lb(Ie,Te,We):Te}},[E,Z,B]),[pe,te]=k.useState(()=>xe()),ke=k.useRef(pe);ke.current=pe;const[$e,Y]=k.useState(null),Ae=k.useRef(null),[lt,Se]=k.useState("idle"),[ye,_e]=k.useState(null),je=k.useRef(null),re=k.useRef({attention:!1,running:!1});k.useEffect(()=>()=>{const Ie=je.current?.longPressTimer;Ie!=null&&window.clearTimeout(Ie)},[]),k.useEffect(()=>{if(B)return;const Ie=je.current?.longPressTimer;Ie!=null&&window.clearTimeout(Ie),je.current=null,Se("idle"),_e(null)},[B]),k.useLayoutEffect(()=>{const Ie=()=>{const Te=xe();ke.current=Te,te(Te)};Ie(),window.addEventListener("resize",Ie),window.addEventListener("orientationchange",Ie),window.visualViewport?.addEventListener("resize",Ie);const We=typeof ResizeObserver>"u"?null:new ResizeObserver(Ie);return l&&We?.observe(l),()=>{window.removeEventListener("resize",Ie),window.removeEventListener("orientationchange",Ie),window.visualViewport?.removeEventListener("resize",Ie),We?.disconnect()}},[l,xe]);const Oe=k.useCallback(Ie=>Ie==="attention"?B:E,[E,B]),Ce=k.useCallback((Ie,We)=>{if(!Oe(Ie))return We;const Te=Ie==="attention"?"running":"attention";return lb(Z(),We,ke.current[Te])},[Z,Oe]),Ee=k.useCallback((Ie,We,Te,H)=>{const oe=Z(),be=We.moved?Hc(oe,{x:We.startX+(Te-We.originX),y:We.startY+(H-We.originY)}):ke.current[Ie],Ze=ob(oe,be),Je=Ce(Ie,Ze.position),St=ob(oe,Je);ce.current[Ie]=St.preference,DP(Ie==="attention"?ub:db,St.preference);const Vt={...ke.current,[Ie]:St.position};ke.current=Vt,te(Vt)},[Ce,Z]),Be=k.useCallback(Ie=>{re.current[Ie]=!0,window.setTimeout(()=>{re.current[Ie]=!1},0)},[]),Ne=k.useCallback(Ie=>{const We=Ae.current;!We||We.kind!=="attention"||We.pointerId!==Ie.pointerId||(Ae.current=null,Y(null),Ee("attention",We,Ie.clientX,Ie.clientY),We.moved&&Be("attention"))},[Ee,Be]),le={onPointerDown:Ie=>{Ie.stopPropagation(),Ie.currentTarget.setPointerCapture(Ie.pointerId),Ae.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 We=Ae.current;if(!We||We.kind!=="attention"||We.pointerId!==Ie.pointerId)return;const Te=Ie.clientX-We.originX,H=Ie.clientY-We.originY;if(!We.moved&&Math.hypot(Te,H)<5)return;We.moved=!0,Y("attention");const oe=Z(),be=Ce("attention",Hc(oe,{x:We.startX+Te,y:We.startY+H})),Ze={...ke.current,attention:be};ke.current=Ze,te(Ze)},onPointerUp:Ne,onPointerCancel:Ne},He=l?zP(pe.running,Z(),t.length):null,rt=Ie=>{Ie.longPressTimer!==null&&(window.clearTimeout(Ie.longPressTimer),Ie.longPressTimer=null)},mt={onPointerDown:Ie=>{Ie.stopPropagation(),Ie.currentTarget.setPointerCapture(Ie.pointerId);const We=Ie.pointerId,Te={pointerId:We,originX:Ie.clientX,originY:Ie.clientY,startX:pe.running.x,startY:pe.running.y,mode:"pressing",moved:!1,selectedIndex:null,longPressTimer:null};Te.longPressTimer=window.setTimeout(()=>{const H=je.current;!H||H.pointerId!==We||H.mode!=="pressing"||(H.longPressTimer=null,H.mode="dragging",re.current.running=!0,Se("dragging"))},$P),je.current=Te,Se("pressing"),_e(null)},onPointerMove:Ie=>{const We=je.current;if(!We||We.pointerId!==Ie.pointerId)return;const Te=Ie.clientX-We.originX,H=Ie.clientY-We.originY;if(We.mode==="pressing")if(Math.abs(Te)>=pb&&Math.abs(Te)>=Math.abs(H))rt(We),We.mode="selecting",re.current.running=!0,Se("selecting");else if(Math.hypot(Te,H)>=pb){rt(We),We.mode="cancelled",re.current.running=!0,Se("idle");return}else return;if(We.mode==="selecting"){const Je=He?mb(He,Ie.clientX,Ie.clientY,t.length):null;We.selectedIndex=Je,_e(Je);return}if(We.mode!=="dragging"||!We.moved&&Math.hypot(Te,H)<5)return;We.moved=!0;const oe=Z(),be=Ce("running",Hc(oe,{x:We.startX+Te,y:We.startY+H})),Ze={...ke.current,running:be};ke.current=Ze,te(Ze)},onPointerUp:Ie=>{const We=je.current;if(!We||We.pointerId!==Ie.pointerId)return;rt(We);const Te=We.mode;if(Te==="selecting"){const H=He?mb(He,Ie.clientX,Ie.clientY,t.length):We.selectedIndex,oe=H===null?null:t[H]?.id;oe&&fb(oe)}else Te==="dragging"&&Ee("running",We,Ie.clientX,Ie.clientY);je.current=null,Se("idle"),_e(null),Te!=="pressing"&&Be("running")},onPointerCancel:Ie=>{const We=je.current;!We||We.pointerId!==Ie.pointerId||(rt(We),je.current=null,Se("idle"),_e(null),Be("running"))}},ue=(Ie,We)=>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)] ${We==="attention"?"text-[color:var(--warning)]":"text-[color:var(--success)]"}`,children:Ie>9?"9+":Ie}),Ye=()=>{const Ie=v.hasOtherAttention?p("serviceAttention.title"):p("agent.jumpToNext"),We=pe.attention,Te=$e==="attention";return s.jsxs("button",{type:"button","data-attention-button":!0,"data-mobile-attention-button":!0,...le,onClick:H=>{H.stopPropagation(),!re.current.attention&&(v.hasOtherAttention?L(!0):R6())},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 ${Te?"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:We.x,top:We.y,width:$a,height:$a,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")},st=()=>{const Ie=t.length,We=pe.running,Te=lt==="selecting",H=lt==="dragging";return s.jsxs(k.Fragment,{children:[s.jsxs("button",{type:"button","data-running-session-button":!0,"data-running-session-gesture":lt,...mt,onClick:oe=>{if(oe.stopPropagation(),re.current.running)return;const be=HP(t,r);be&&fb(be)},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)]":Te?"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:We.x,top:We.y,width:$a,height:$a,touchAction:"none"},"aria-label":`${p("agent.jumpToNextRunning")}: ${Ie}`,title:p("agent.runningSessionGestureHint"),children:[s.jsx(Cn,{size:18,className:"shrink-0 animate-spin"}),ue(Ie,"running")]}),Te&&He&&s.jsx("div",{role:"listbox","data-running-session-rail":!0,"data-side":He.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:He.left,top:He.top,width:He.width,height:He.height},children:t.map((oe,be)=>{const Ze=be===ye,Je=oe.id===r,St=`${oe.label}${oe.detail?` · ${oe.detail}`:""}${Je?` · ${p("agent.currentSession")}`:""}`;return s.jsxs("div",{role:"option","aria-selected":Ze,"data-running-session-option":oe.id,"data-selected":Ze?"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 ${Ze?"scale-[1.02] bg-[var(--success)] text-[color:var(--success-foreground)]":Je?"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 ${Ze?"bg-surface/25":"bg-surface-2 text-muted-foreground"}`,children:be+1}),s.jsx("span",{className:"truncate text-[10px] font-medium",children:oe.label})]},oe.id)})})]},"running")};return!E&&!B&&!S||l===null||typeof document>"u"?null:s.jsxs(Iw,{children:[E&&Ye(),B&&!S&&st(),S&&v.active&&w&&s.jsx(_P,{groups:v.groups,currentKey:v.currentKey,onClose:()=>L(!1)})]})}function GP(){const{t:e}=zr();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 VP=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"]),gb=120,xb=120,qP=new Set,YP=[],ZP={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 Cg(e,t){if(t==="directory")return null;if(Rw(e))return s.jsx(RA,{size:14});if(Mw(e))return s.jsx(Fy,{size:14});const r=e.lastIndexOf(".")>=0?e.slice(e.lastIndexOf(".")):"";return VP.has(r)?s.jsx(iT,{size:14}):s.jsx(Ry,{size:14})}function D6({path:e}){const r=Gt(a=>a.changedFiles.get(e))?.status;if(!r)return null;const n=ZP[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 qu(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 _g(e){return qu(e)}const KP=b.memo(function({path:t}){const{t:r}=zr(),[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 wy(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 ${qu(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(Cn,{size:12,className:"animate-spin"}):s.jsx(f0,{size:12})})});function B6(){const{t:e}=zr(),[t,r]=b.useState({status:"idle"}),n=b.useCallback(async a=>{r({status:"pending"});try{await wy(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 C1(e){return e instanceof DOMException&&e.name==="AbortError"}function Mf(){if(typeof window>"u")return!1;const e=window.getSelection();return!!(e&&!e.isCollapsed&&e.toString().trim())}function Q6(e){return e.button===2||e.ctrlKey}const XP=176,JP=160,jd=8;function bb(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+jd,x=l+jd,y=Math.max(m,d-r-jd),w=Math.max(x,p-n-jd),v=t+n<=p-jd?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 P6(e){const[t,r]=b.useState(null),n=b.useRef(null),a=b.useCallback((c,l)=>{r(bb(c,l,XP,JP))},[]);return b.useLayoutEffect(()=>{if(!e||!t||!n.current)return;const c=n.current.getBoundingClientRect();if(c.width<=0||c.height<=0)return;const l=bb(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 O6(e,t){return t&&typeof document<"u"?Ii.createPortal(e,document.body):e}function eO(e,t){return t?`${e.name} ${e.path}`.toLowerCase().includes(t):!0}function kg(e,t,r){if(!t||eO(e,t))return!0;const n=r.get(e.path);return n?n.some(a=>kg(a,t,r)):!1}function _1(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 k1(e,t){return!e||!t.startsWith(e)?t:t.slice(e.length).replace(/^\/+/,"")||t}const tO=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:W,onDirectoryDropFiles:F,onFileDeleteRequest:U,deletingFilePath:V,revealedDirectoryPath:Z,gitIgnoreRoot:ce}){const{t:xe}=zr(),pe=Gt(bt=>bt.expandedPaths.has(t.path)),te=Gt(bt=>bt.directoryCache.get(t.path)),ke=Gt(bt=>bt.showHiddenFiles),$e=Gt(bt=>bt.toggleExpanded),Y=Gt(bt=>bt.setDirectoryCache),Ae=Gt(bt=>bt.fileSortModes[t.path]??"name"),lt=Gt(bt=>bt.setDirectorySortMode),[Se,ye]=b.useState(!1),[_e,je]=b.useState(!1),{position:re,menuRef:Oe,openAt:Ce,clearPosition:Ee}=P6(_e),[Be,Ne]=b.useState(!1),le=b.useRef(0),He=b.useRef(null),rt=`file-tree-reference:${b.useId()}:${t.path}`;I0(Oe,_e&&!!l,()=>je(!1));const mt=b.useRef(null),ue=t.path===B||t.path===Z,Ye=t.type==="directory"&&(pe||!!W),st=t.type==="directory",Ie=R.has(t.path),We=!st&&!!S,Te=!!(E&&L),H=`path:${t.path}`,oe=m===H||!!l?.paths.has(t.path),be=x===H,Ze=d?.(t.path)??t.path,Je=P1(p,!!l),{state:St,run:Vt}=B6(),jt=V===t.path,vt=st&&!a&&!!(y||w||v||Te),Zt=b.useMemo(()=>{if(!te)return;if(!W)return te;const bt=Gt.getState().directoryCache;return te.filter(It=>(!a||It.type==="directory")&&kg(It,W,bt))},[te,a,W]),Pt=b.useCallback(async()=>{if(!Gt.getState().directoryCache.has(t.path)&&!Se){const It=l?rt:`file-tree:${t.path}`;He.current?.abort(),Om(It);const yt=new AbortController;He.current=yt,ye(!0);try{const pr=await j1(t.path,yt.signal,ke,"expand_directory",It,Ae,ce);if(yt.signal.aborted)return;const nr=_1(pr.entries);Y(t.path,nr)}catch(pr){C1(pr)}finally{He.current===yt&&(He.current=null),ye(!1)}}},[t.path,Se,Y,ke,Ae,ce,!!l,rt]),Xt=b.useCallback(async()=>{if(t.type!=="directory"){n(t.path);return}if(a&&y){y(t.path);return}const bt=!Gt.getState().expandedPaths.has(t.path);$e(t.path),bt&&await Pt()},[a,t.path,t.type,Pt,y,$e,n]);b.useEffect(()=>{t.type==="directory"&&pe&&!te&&!Se&&Pt()},[te,pe,Pt,Se,t.type]);const zt=b.useCallback(bt=>{bt.stopPropagation(),c?.(t.path,H)},[c,t.path,H]),Lt=b.useCallback(bt=>{bt.stopPropagation(),y?.(t.path),je(!1)},[t.path,y]),me=b.useCallback(bt=>{bt.stopPropagation(),w?.(t.path),je(!1)},[t.path,w]),Ge=b.useCallback(bt=>{bt.stopPropagation(),v?.(t.path),je(!1)},[t.path,v]),pt=b.useCallback(bt=>{bt.stopPropagation(),lt(t.path,Ae==="modified"?"name":"modified"),je(!1)},[t.path,lt,Ae]),q=b.useCallback(bt=>{bt.stopPropagation(),S?.(t.path),je(!1)},[t.path,S]),at=b.useCallback(bt=>{bt.stopPropagation(),je(!1),Vt(t.path)},[t.path,Vt]),qt=b.useCallback(bt=>{bt.stopPropagation(),je(!1),U(t)},[t,U]),Ve=b.useCallback(bt=>{bt.stopPropagation(),L?.(t.path),je(!1)},[t.path,L]),De=b.useCallback(bt=>{!st||!F||!bt.dataTransfer.types.includes("Files")||(bt.preventDefault(),bt.stopPropagation(),le.current+=1,Ne(!0))},[st,F]),er=b.useCallback(bt=>{!st||!F||!bt.dataTransfer.types.includes("Files")||(bt.preventDefault(),bt.stopPropagation(),bt.dataTransfer.dropEffect="copy",Ne(!0))},[st,F]),et=b.useCallback(bt=>{!st||!F||(bt.preventDefault(),bt.stopPropagation(),le.current-=1,le.current<=0&&(le.current=0,Ne(!1)))},[st,F]),Ct=b.useCallback(bt=>{if(!st||!F)return;bt.preventDefault(),bt.stopPropagation(),le.current=0,Ne(!1);const It=Array.from(bt.dataTransfer.files);It.length>0&&F(t.path,It)},[st,t.path,F]),Nt=b.useCallback(bt=>{bt.stopPropagation(),l?Ce(bt.clientX,bt.clientY):Ee(),je(It=>!It)},[Ee,Ce,!!l]),gt=b.useCallback(bt=>{!vt||!Q6(bt)||(bt.preventDefault(),bt.stopPropagation(),Ce(bt.clientX,bt.clientY),je(!0))},[vt,Ce]);return b.useEffect(()=>{if(!_e)return;const bt=yt=>{const pr=yt.target;pr instanceof Node&&(mt.current?.contains(pr)||Oe.current?.contains(pr))||je(!1)},It=yt=>{yt.key==="Escape"&&je(!1)};return document.addEventListener("pointerdown",bt),document.addEventListener("keydown",It),()=>{document.removeEventListener("pointerdown",bt),document.removeEventListener("keydown",It)}},[_e,Oe]),b.useEffect(()=>()=>{He.current?.abort()},[]),s.jsxs("div",{style:!Ye&&!_e?{contentVisibility:"auto",containIntrinsicSize:"auto 32px"}:void 0,children:[s.jsxs("div",{ref:mt,className:"relative",children:[Je.popoverNode,s.jsxs("div",{"data-file-tree-path":t.path,"data-sort-mode":Ae,role:"button",tabIndex:0,onClick:()=>{Mf()||Xt()},onContextMenu:gt,onKeyDown:bt=>{bt.target!==bt.currentTarget||bt.key!=="Enter"&&bt.key!==" "||(bt.preventDefault(),Xt())},onDragEnter:De,onDragOver:er,onDragLeave:et,onDrop:Ct,className:`group relative flex w-full cursor-pointer items-center gap-1 rounded px-2 py-1 text-[13px] transition ${Be?"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`}}),Be&&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:xe("fileTree.dropToUploadHere")}),t.type==="directory"?s.jsxs(s.Fragment,{children:[Ye?s.jsx(ul,{size:14,className:"shrink-0 text-muted-foreground/80"}):s.jsx(fi,{size:14,className:"shrink-0 text-muted-foreground/80"}),Ye?s.jsx(Ru,{size:14,className:"shrink-0 text-[color:var(--folder)]"}):s.jsx(Gc,{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:Cg(t.name,t.type)})]}),s.jsxs("span",{className:`flex-1 select-text whitespace-nowrap text-left leading-snug ${ue?"font-medium":""}`,children:[t.name,Ae==="modified"&&s.jsx("span",{className:"ml-1 inline-flex align-middle text-primary",title:xe("fileTree.sortedByModified"),"aria-label":xe("fileTree.sortedByModified"),children:s.jsx(h0,{size:11})}),t.isSymlink&&s.jsx("span",{className:"ml-1 inline-flex align-middle text-muted-foreground/70",title:xe("fileTree.symbolicLink"),children:s.jsx(Ou,{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:bt=>bt.stopPropagation(),children:[Se&&s.jsx(Cn,{size:12,className:"shrink-0 animate-spin text-muted-foreground"}),s.jsx(D6,{path:t.path}),vt&&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 ${qu(_e)} ${_e?"bg-surface-elevated text-foreground":"bg-surface-2 hover:bg-surface-elevated hover:text-foreground"}`,"aria-label":xe("fileTree.moreDirActions"),"aria-expanded":_e,title:xe("fileTree.moreDirActions"),children:s.jsx($o,{size:13})}),!st&&!l&&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 ${qu(_e||St.status==="pending"||jt||Ie)} ${_e?"bg-surface-elevated text-foreground":Ie?"bg-primary/15 text-primary":"bg-surface-2 hover:bg-surface-elevated hover:text-foreground"}`,"aria-label":xe("fileTree.moreFileActions"),"aria-expanded":_e,title:St.status==="error"?St.message??xe("rightSidebar.downloadFailed"):xe("fileTree.moreFileActions"),children:St.status==="pending"||jt?s.jsx(Cn,{size:13,className:"animate-spin"}):s.jsx($o,{size:13})}),c&&s.jsx("button",{type:"button",onClick:zt,...Je(Ze,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":_g(oe||be)} ${oe||be?"bg-surface-elevated text-foreground":"bg-primary/10 text-primary"}`,"aria-label":l?`${l.label}: ${t.name}`:xe(be?"rightSidebar.copied":oe?"rightSidebar.inserted":"fileTree.insertRefTitle"),"aria-pressed":l?oe:void 0,disabled:!!l?.disabled&&!oe,title:l?`${l.label}: ${t.name}`:xe(be?"rightSidebar.copied":oe?"rightSidebar.inserted":"fileTree.insertRefTitle"),children:be||oe?s.jsx(hi,{size:12}):s.jsx(Ou,{size:12})}),vt&&_e&&O6(s.jsxs("div",{ref:Oe,className:`${re?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:re?{left:re.left,top:re.top}:void 0,children:[Te&&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 text-foreground transition hover:bg-surface-2 active:scale-[0.99]",title:xe("fileTree.openInFileBrowserTitle"),children:[s.jsx(Ru,{size:13,className:"shrink-0 text-[color:var(--folder)]"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:xe("fileTree.openInFileBrowser")})]}),y&&s.jsxs("button",{type:"button",onClick:Lt,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:xe("fileTree.openDirRootTitle"),children:[s.jsx(Ru,{size:13,className:"shrink-0 text-[color:var(--folder)]"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:xe("fileTree.openDirRoot")})]}),w&&s.jsxs("button",{type:"button",onClick:me,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:xe("fileTree.searchFromDirTitle"),children:[s.jsx(O1,{size:13,className:"shrink-0 text-primary"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:xe("fileTree.searchFromDir")})]}),v&&s.jsxs("button",{type:"button",onClick:Ge,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:xe(Ie?"fileTree.unpinDirTitle":"fileTree.pinDirTitle"),children:[Ie?s.jsx(m0,{size:13,className:"shrink-0"}):s.jsx(p0,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:xe(Ie?"fileTree.unpinDir":"fileTree.pinDir")})]}),s.jsxs("button",{type:"button",onClick:pt,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:[Ae==="modified"?s.jsx(CA,{size:13,className:"shrink-0"}):s.jsx(h0,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:xe(Ae==="modified"?"fileTree.sortByName":"fileTree.sortByModified")})]})]}),!!re),!st&&!l&&_e&&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:[Te&&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 text-foreground transition hover:bg-surface-2 active:scale-[0.99]",title:xe("fileTree.openInFileBrowserTitle"),children:[s.jsx(Ry,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:xe("fileTree.openInFileBrowser")})]}),s.jsxs("button",{type:"button",onClick:at,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:xe("rightSidebar.downloadFile"),children:[s.jsx(f0,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:xe("rightSidebar.downloadFile")})]}),We&&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:xe(Ie?"fileTree.unpinFileTitle":"fileTree.pinFileTitle"),children:[Ie?s.jsx(m0,{size:13,className:"shrink-0"}):s.jsx(p0,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:xe(Ie?"fileTree.unpinFile":"fileTree.pinFile")})]}),s.jsxs("button",{type:"button",onClick:qt,disabled:jt,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:xe("fileTree.deleteFile"),children:[jt?s.jsx(Cn,{size:13,className:"shrink-0 animate-spin"}):s.jsx(zs,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:xe("fileTree.deleteFile")})]})]})]})]})]}),Ye&&Zt&&Zt.length>0&&s.jsx("div",{className:r===0?"mt-0.5":"",children:Zt.map(bt=>s.jsx(e,{node:bt,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:W,insertedReferenceKey:m,copiedReferenceKey:x,onDirectoryDropFiles:F,onFileDeleteRequest:U,deletingFilePath:V,gitIgnoreRoot:ce,revealedDirectoryPath:Z},bt.path))})]})}),rO=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}=zr(),W=t.path===L,F=t.type==="directory",U=S.has(t.path),V=!F&&!!v,Z=`path:${t.path}`,ce=p===Z||!!c?.paths.has(t.path),xe=m===Z,pe=l?.(t.path)??t.path,te=P1(d,!!c),{state:ke,run:$e}=B6(),[Y,Ae]=b.useState(!1),{position:lt,menuRef:Se,openAt:ye,clearPosition:_e}=P6(Y);I0(Se,Y&&!!c,()=>Ae(!1));const je=b.useRef(null),re=R===t.path,Oe=F&&!!(x||y||w),Ce=b.useCallback(()=>{Mf()||(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]),Be=b.useCallback(ue=>{ue.stopPropagation(),w?.(t.path),Ae(!1)},[t.path,w]),Ne=b.useCallback(ue=>{ue.stopPropagation(),v?.(t.path),Ae(!1)},[t.path,v]),le=b.useCallback(ue=>{ue.stopPropagation(),Ae(!1),$e(t.path)},[t.path,$e]),He=b.useCallback(ue=>{ue.stopPropagation(),Ae(!1),E(t)},[t,E]),rt=b.useCallback(ue=>{ue.stopPropagation(),c?ye(ue.clientX,ue.clientY):_e(),Ae(Ye=>!Ye)},[_e,ye,!!c]),mt=b.useCallback(ue=>{!Oe||!Q6(ue)||(ue.preventDefault(),ue.stopPropagation(),ye(ue.clientX,ue.clientY),Ae(!0))},[Oe,ye]);return b.useEffect(()=>{if(!Y)return;const ue=st=>{const Ie=st.target;Ie instanceof Node&&(je.current?.contains(Ie)||Se.current?.contains(Ie))||Ae(!1)},Ye=st=>{st.key==="Escape"&&Ae(!1)};return document.addEventListener("pointerdown",ue),document.addEventListener("keydown",Ye),()=>{document.removeEventListener("pointerdown",ue),document.removeEventListener("keydown",Ye)}},[Y,Se]),s.jsxs("div",{ref:je,className:"relative border-b border-border/10 last:border-b-0",children:[te.popoverNode,s.jsxs("div",{role:"button",tabIndex:0,onClick:Ce,onContextMenu:mt,onKeyDown:ue=>{ue.target!==ue.currentTarget||ue.key!=="Enter"&&ue.key!==" "||(ue.preventDefault(),Ce())},className:`group flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-2 text-left text-[13px] transition ${W?"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(Gc,{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:W?"text-primary":"text-muted-foreground/80",children:Cg(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 ${W?"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(Ou,{size:11})})]}),s.jsx("span",{className:"mt-0.5 block truncate font-mono text-[10px] text-muted-foreground/80",children:k1(r,t.path)})]}),s.jsx(D6,{path:t.path}),t.type==="directory"&&(w||y)&&s.jsx("button",{type:"button",onClick:rt,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 ${qu(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($o,{size:13})}),!F&&!c&&s.jsx("button",{type:"button",onClick:rt,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 ${qu(Y||ke.status==="pending"||re||U)} ${Y?"bg-surface-elevated text-foreground":U?"bg-primary/15 text-primary":"bg-surface-2 hover:bg-surface-elevated hover:text-foreground"}`,"aria-label":B("fileTree.moreFileActions"),"aria-expanded":Y,title:ke.status==="error"?ke.message??B("rightSidebar.downloadFailed"):B("fileTree.moreFileActions"),children:ke.status==="pending"||re?s.jsx(Cn,{size:13,className:"animate-spin"}):s.jsx($o,{size:13})}),a&&s.jsx("button",{type:"button",onClick:Ee,...te(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":_g(ce||xe)} ${ce||xe?"bg-surface-elevated text-foreground":"bg-primary/10 text-primary"}`,"aria-label":c?`${c.label}: ${t.name}`:B(xe?"rightSidebar.copied":ce?"rightSidebar.inserted":"fileTree.insertRefTitle"),"aria-pressed":c?ce:void 0,disabled:!!c?.disabled&&!ce,title:c?`${c.label}: ${t.name}`:B(xe?"rightSidebar.copied":ce?"rightSidebar.inserted":"fileTree.insertRefTitle"),children:xe||ce?s.jsx(hi,{size:12}):s.jsx(Ou,{size:12})})]}),Oe&&Y&&O6(s.jsxs("div",{ref:Se,className:`${lt?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:lt?{left:lt.left,top:lt.top}:void 0,children:[x&&s.jsxs("button",{type:"button",onClick:ue=>{ue.stopPropagation(),x(t.path),Ae(!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(Ru,{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),Ae(!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(O1,{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:Be,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] ${U?"text-primary hover:bg-primary/10":"text-foreground hover:bg-surface-2"}`,title:B(U?"fileTree.unpinDirTitle":"fileTree.pinDirTitle"),children:[U?s.jsx(m0,{size:13,className:"shrink-0"}):s.jsx(p0,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:B(U?"fileTree.unpinDir":"fileTree.pinDir")})]})]}),!!lt),!F&&!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:le,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(f0,{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] ${U?"text-primary hover:bg-primary/10":"text-foreground hover:bg-surface-2"}`,title:B(U?"fileTree.unpinFileTitle":"fileTree.pinFileTitle"),children:[U?s.jsx(m0,{size:13,className:"shrink-0"}):s.jsx(p0,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:B(U?"fileTree.unpinFile":"fileTree.pinFile")})]}),s.jsxs("button",{type:"button",onClick:He,disabled:re,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:[re?s.jsx(Cn,{size:13,className:"shrink-0 animate-spin"}):s.jsx(zs,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:B("fileTree.deleteFile")})]})]})]})}),nO=60,yb=60,sO=20;function vb({count:e,loading:t,engine:r,limited:n,scope:a,content:c}){const{t:l}=zr();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(O1,{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(Cn,{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 iO(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 aO=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}=zr(),[v,S]=b.useState(!0),L=t.path===n,E=v?t.matches.slice(0,sO):[],R=t.matches.length-E.length,B=`path:${t.path}`,W=x===B||!!d?.paths.has(t.path),F=y===B,U=p?.(t.path)??t.path,V=P1(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:()=>{Mf()||S(Z=>!Z)},onKeyDown:Z=>{Z.target!==Z.currentTarget||Z.key!=="Enter"&&Z.key!==" "||(Z.preventDefault(),S(ce=>!ce))},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(fi,{size:14,className:"shrink-0 text-muted-foreground/80"}),s.jsx("span",{className:L?"text-primary":"text-muted-foreground/80",children:Cg(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:k1(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(KP,{path:t.path}),l&&s.jsx("button",{type:"button",onClick:Z=>{Z.stopPropagation(),l(t.path,B)},...V(U,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":_g(W||F)} ${W||F?"bg-surface-elevated text-foreground":"bg-primary/10 text-primary"}`,"aria-label":d?`${d.label}: ${t.name}`:w(F?"rightSidebar.copied":W?"rightSidebar.inserted":"fileTree.insertRefTitle"),"aria-pressed":d?W:void 0,disabled:!!d?.disabled&&!W,title:d?`${d.label}: ${t.name}`:w(F?"rightSidebar.copied":W?"rightSidebar.inserted":"fileTree.insertRefTitle"),children:F||W?s.jsx(hi,{size:12}):s.jsx(Ou,{size:12})})]}),v&&s.jsxs("div",{className:"mb-1 ml-3 border-l border-border/20 pl-1",children:[E.map((Z,ce)=>s.jsxs("div",{role:"button",tabIndex:0,onClick:()=>{Mf()||c?.(t.path,Z.line)},onKeyDown:xe=>{xe.target!==xe.currentTarget||xe.key!=="Enter"&&xe.key!==" "||(xe.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:`${k1(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:iO(Z.text,a)})]},`${Z.line}-${ce}`)),R>0&&s.jsx("div",{className:"px-2 py-1 text-[10px] text-muted-foreground/70",children:w("fileTree.moreMatches",{count:R})})]})]})});function oO({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=qP,selectedFilePath:E,query:R="",searchRootPath:B,searchOptions:W={},searchMode:F="name",onContentMatchSelect:U,onDirectoryDropFiles:V,revealDirectory:Z}){const{t:ce}=zr(),xe=b.useId(),pe=a?`file-tree-reference-root:${xe}:${e}`:`file-tree-root:${e}`,te=Gt(Ve=>e?Ve.directoryCache.get(e):void 0),ke=Gt(Ve=>Ve.setDirectoryCache),$e=Gt(Ve=>Ve.showHiddenFiles),Y=Gt(Ve=>Ve.fileSortModesHydrated),Ae=Gt(Ve=>Ve.fileSortModes[e]??"name"),lt=Gt(Ve=>Ve.hydrateFileSortModes),Se=Gt(Ve=>Ve.hydrateHideGitIgnoredRoots),ye=Gt(Ve=>!!Ve.hideGitIgnoredRoots[e]),_e=Gt(Ve=>Ve.hideGitIgnoredRootsHydrated),je=Gt(Ve=>JSON.stringify(Ve.gitIgnoreExceptions[e]??[])),re=Gt(Ve=>Ve.invalidateDirectoryCache),Oe=`${e}:${ye}:${je}`,[Ce,Ee]=b.useState("");b.useLayoutEffect(()=>{e&&re(e,!0),Ee(Oe)},[e,ye,je,re,Oe]);const[Be,Ne]=b.useState(!1),[le,He]=b.useState(null),[rt,mt]=b.useState(!1),[ue,Ye]=b.useState(!1),[st,Ie]=b.useState(null),[We,Te]=b.useState(Y&&_e),H=Y&&_e||We;b.useEffect(()=>{let Ve=!1;return Promise.all([lt(),Se()]).catch(()=>{}).finally(()=>{Ve||Te(!0)}),()=>{Ve=!0}},[lt,Se]);const[oe,be]=b.useState([]),[Ze,Je]=b.useState(null),[St,Vt]=b.useState(gb),[jt,vt]=b.useState([]),[Zt,Pt]=b.useState(null),Xt=b.useRef(null),zt=b.useRef(0),Lt=R.trim().toLowerCase(),me=F==="content",Ge=B||e,pt=W.excludePatterns??YP,q=pt.join(`
|
|
137
137
|
`);b.useEffect(()=>{const Ve=Z?.path;if(!Ve||!Ve.startsWith(`${e}/`)&&Ve!==e)return;const De=Ve.slice(e.length).replace(/^\/+/,""),er=De?De.split("/"):[],et=er.map((pr,nr)=>`${e}/${er.slice(0,nr+1).join("/")}`),Ct=Gt.getState(),Nt=et.filter(pr=>!Ct.expandedPaths.has(pr));Nt.length>0&&Gt.setState(pr=>({expandedPaths:new Set([...pr.expandedPaths,...Nt])}));let gt=!1,bt=0;const It=()=>{if(gt)return;const pr=Array.from(document.querySelectorAll("[data-file-tree-path]")).find(nr=>nr.dataset.fileTreePath===Ve);if(pr){pr.scrollIntoView({block:"center",behavior:"smooth"});return}bt+=1,bt<80&&window.setTimeout(It,50)},yt=window.requestAnimationFrame(It);return()=>{gt=!0,window.cancelAnimationFrame(yt)}},[Z?.nonce,Z?.path,e]);const at=b.useCallback(async Ve=>{if(!(Zt||Ve.type==="directory")&&window.confirm(ce("fileTree.deleteFileConfirm",{name:Ve.name}))){Pt(Ve.path);try{await Ew(Ve.path),Gt.getState().applyFileWatchEvents([{type:"deleted",path:Ve.path}]),be(De=>De.filter(er=>er.path!==Ve.path)),vt(De=>De.filter(er=>er.path!==Ve.path)),L.has(Ve.path)&&w?.(Ve.path)}catch(De){const er=De instanceof Error?De.message:String(De);window.alert(ce("fileTree.deleteFileFailed",{message:er}))}finally{Pt(null)}}},[Zt,w,L,ce]);b.useEffect(()=>{if(!e||!H||Ce!==Oe)return;if(Lt){Ne(!1);return}if(Gt.getState().directoryCache.has(e)){Ne(!1);return}let Ve=!1;const De=new AbortController;return Ne(!0),He(null),j1(e,De.signal,$e,"load_file_tree_root",pe,Ae,e).then(er=>{if(Ve)return;const et=_1(er.entries);mt(!!er.truncated),ke(e,et)}).catch(er=>{Ve||C1(er)||He(er instanceof Error?er.message:"Failed to load directory")}).finally(()=>{Ve||Ne(!1)}),()=>{Ve=!0,De.abort(),Om(pe)}},[Lt,te,e,Ae,ke,$e,H,ye,je,pe,Ce,Oe]),b.useEffect(()=>{if(!Ge||!Lt){Ye(!1),Ie(null),be([]),vt([]),Je(null);return}let Ve=!1;const De=new AbortController,er=new Set;Ye(!0),Ie(null),be([]),vt([]),Vt(me?nO:gb),Je({truncated:!1,total:0,engine:"rg",limited:!1,done:!1});const et=`file-search:${a?xe+":":""}${Ge}:${++zt.current}`;return Nw(Ge,R.trim(),Ct=>{if(!Ve){if(Ct.engine&&Je(Nt=>({truncated:Nt?.truncated??!1,total:Nt?.total??0,engine:Ct.engine,limited:Ct.limited??Nt?.limited??!1,done:Nt?.done??!1})),Ct.entries?.length){const Nt=Ct.entries.filter(gt=>er.has(gt.path)?!1:(er.add(gt.path),!0));Nt.length>0&&(be(gt=>[...gt,..._1(Nt)]),Je(gt=>gt?{...gt,total:er.size}:{truncated:!1,total:er.size,engine:"rg",limited:!1,done:!1}))}if(Ct.contentEntries?.length){const Nt=Ct.contentEntries.filter(gt=>er.has(gt.path)?!1:(er.add(gt.path),!0));Nt.length>0&&(vt(gt=>[...gt,...Nt]),Je(gt=>gt?{...gt,total:er.size}:{truncated:!1,total:er.size,engine:"rg",limited:!1,done:!1}))}Ct.done&&Je(Nt=>({truncated:!!Ct.truncated,total:typeof Ct.total=="number"?Ct.total:er.size,engine:Ct.engine??Nt?.engine??"rg",limited:!!Ct.limited,done:!0}))}},De.signal,$e,F,et,{excludePatterns:pt,caseSensitive:W.caseSensitive,wholeWord:W.wholeWord,regex:W.regex}).catch(Ct=>{Ve||C1(Ct)||(Ie(Ct instanceof Error?Ct.message:"Failed to search files"),be([]),vt([]),Je(null))}).finally(()=>{Ve||Ye(!1)}),()=>{Ve=!0,De.abort(),Om(et)}},[Ge,q,me,R,Lt,F,W.caseSensitive,W.regex,W.wholeWord,$e,!!a,xe]),b.useEffect(()=>{if(!Lt)return;const Ve=Xt.current;if(!Ve)return;const De=me?jt.length:oe.length,er=me?yb:xb,et=new IntersectionObserver(Ct=>{Ct.some(Nt=>Nt.isIntersecting)&&Vt(Nt=>Math.min(Nt+er,De))},{rootMargin:"160px 0px"});return et.observe(Ve),()=>et.disconnect()},[Lt,oe.length,jt.length,me]);const qt=b.useMemo(()=>{if(!te)return;if(!Lt)return r?te.filter(De=>De.type==="directory"):te;const Ve=Gt.getState().directoryCache;return te.filter(De=>(!r||De.type==="directory")&&kg(De,Lt,Ve))},[r,Lt,te]);if(!e)return s.jsx("div",{className:"px-4 py-8 text-center text-sm text-muted-foreground",children:ce("fileTree.noWorkingDir")});if(Be||!H)return s.jsx(GP,{});if(Lt&&me){const Ve=Ze?.total??jt.length,De=jt.slice(0,St),er=St<jt.length;return s.jsxs("div",{className:"termdock-native-select min-h-full space-y-px bg-surface px-2 py-2",children:[s.jsx(vb,{count:Ve,loading:ue,engine:Ze?.engine,limited:Ze?.limited,scope:Ge,content:!0}),st?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:[ce("fileTree.contentSearchNeedsRipgrep"),s.jsx("div",{className:"mt-1 break-words text-[11px] text-muted-foreground/70",children:st})]}):ue&&jt.length===0?s.jsx(d0,{label:ce("fileTree.searching"),className:"py-8"}):jt.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:ce("fileTree.noContentMatches")}):s.jsxs(s.Fragment,{children:[Ze?.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:ce("fileTree.searchTruncatedHint",{count:Ze.total})}),De.map(et=>s.jsx(aO,{entry:et,rootPath:Ge,selectedFilePath:E,query:R.trim(),onContentMatchSelect:U,onPathReference:n,referenceSelection:a,getReferenceText:c,onReferenceCopied:l,insertedReferenceKey:d,copiedReferenceKey:p},et.path)),s.jsx("div",{ref:Xt,className:"py-2 text-center text-[11px] text-muted-foreground",children:er?s.jsx("button",{type:"button",onClick:()=>Vt(et=>Math.min(et+yb,jt.length)),className:"rounded-full bg-surface-2 px-3 py-1 hover:bg-surface-elevated hover:text-foreground",children:ce("fileTree.loadMoreSearchResults",{shown:De.length,total:jt.length})}):ue?s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(Cn,{size:10,className:"animate-spin"}),ce("fileTree.searchStillRunning")]}):De.length>0?s.jsx("span",{children:ce("fileTree.showingSearchResults",{shown:De.length,total:Ve})}):null})]})]})}if(Lt){const Ve=Ze?.total??oe.length,De=oe.slice(0,St),er=St<oe.length;return s.jsxs("div",{className:"termdock-native-select min-h-full space-y-px bg-surface px-2 py-2",children:[s.jsx(vb,{count:Ve,loading:ue,engine:Ze?.engine,limited:Ze?.limited,scope:Ge,content:!1}),ue&&oe.length===0?s.jsx(d0,{label:ce("fileTree.searching"),className:"py-8"}):st?s.jsx("div",{className:"px-4 py-4 text-sm text-destructive",children:st}):oe.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:ce("fileTree.noMatchingFiles")}):s.jsxs(s.Fragment,{children:[Ze?.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:ce("fileTree.searchTruncatedHint",{count:Ze.total})}),De.map(et=>s.jsx(rO,{node:et,rootPath:Ge,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:at,deletingFilePath:Zt},et.path)),s.jsx("div",{ref:Xt,className:"py-2 text-center text-[11px] text-muted-foreground",children:er?s.jsx("button",{type:"button",onClick:()=>Vt(et=>Math.min(et+xb,oe.length)),className:"rounded-full bg-surface-2 px-3 py-1 hover:bg-surface-elevated hover:text-foreground",children:ce("fileTree.loadMoreSearchResults",{shown:De.length,total:oe.length})}):ue?s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(Cn,{size:10,className:"animate-spin"}),ce("fileTree.searchStillRunning")]}):De.length>0?s.jsx("span",{children:ce("fileTree.showingSearchResults",{shown:De.length,total:Ve})}):null})]})]})}return le?s.jsx("div",{role:a?"alert":void 0,className:"px-4 py-4 text-sm text-destructive",children:le}):!te||te.length===0?s.jsx("div",{className:"px-4 py-8 text-center text-sm text-muted-foreground",children:ce("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:ce("fileTree.noMatchingFiles")}):s.jsxs("div",{className:"termdock-native-select w-max min-w-full space-y-px px-2 py-2",children:[rt&&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:ce("fileTree.truncatedHint")}),qt.map(Ve=>s.jsx(tO,{node:Ve,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:Lt,insertedReferenceKey:d,copiedReferenceKey:p,onDirectoryDropFiles:V,onFileDeleteRequest:at,deletingFilePath:Zt,revealedDirectoryPath:Z?.path},Ve.path))]})}function L1(e){return e.trim().replace(/\/+$/,"")||"/"}function lO(e){const t=L1(e);if(t==="/")return"/";const r=t.lastIndexOf("/");return r<=0?"/":t.slice(0,r)}function tp({open:e,initialPath:t,title:r,labels:n,onCancel:a,onConfirm:c}){const{t:l}=zr(),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);I0(p,e,a);const[m,x]=b.useState(()=>L1(t));return b.useEffect(()=>{e&&x(L1(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?Ii.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(hT,{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(Rn,{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(lO(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(Iy,{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(oO,{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(hi,{size:13}),d.confirm]})]})]})]}),document.body):null}const cO=Object.freeze(Object.defineProperty({__proto__:null,DirectoryPickerDialog:tp},Symbol.toStringTag,{value:"Module"})),I1="termdock:new-session-commands:v1",ic="__saved_command__:";function _h(e){return[...new Set(Object.entries(e).filter(([t])=>t.startsWith(ic)||t==="__custom__"||t==="__terminal__").map(([,t])=>t.trim()).filter(Boolean))]}function Dd(){try{const e=JSON.parse(localStorage.getItem(I1)||"{}");return!e||typeof e!="object"||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(t=>typeof t[1]=="string"))}catch{return{}}}function uO({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:W=!1,launchError:F}){const{t:U,locale:V}=zr(),Z=b.useRef(null);I0(Z,!0,L,()=>document.querySelector('[aria-controls="sidebar-launch-options"]'));const[ce,xe]=b.useState(a),[pe,te]=b.useState(!1),[ke,$e]=b.useState(!1),[Y,Ae]=b.useState(Dd),[lt,Se]=b.useState(()=>_h(Dd())),[ye,_e]=b.useState(null),[je,re]=b.useState("idle"),Oe=ke?"__custom__":ce?.slug??"__terminal__",Ce=ce?.command??"",Ee=ke?Y.__custom__??Y.__terminal__??"":ce?Y[Oe]??Ce:"",Be=()=>{const Te=Ee.trim()||Ce;if(!(ke&&!Te))try{const H={...Dd(),[Oe]:Te};if(ke){for(const oe of _h(Dd()))H[ic+oe]=oe;H[ic+Te]=Te}localStorage.setItem(I1,JSON.stringify(H)),Se(_h(H)),ke&&_e(Te),re("saved")}catch{re("error")}},Ne=()=>{if(ye)try{const Te=Dd();for(const[H,oe]of Object.entries(Te))(H.startsWith(ic)||H==="__custom__"||H==="__terminal__")&&oe.trim()===ye&&delete Te[H];localStorage.setItem(I1,JSON.stringify(Te)),Se(_h(Te)),Ae(H=>({...H,__custom__:""})),_e(null),re("idle")}catch{re("error")}},le=()=>{const Te=Ee.trim()||Ce;W||ke&&!Te||(Be(),w(ce,Te))},He=b.useMemo(()=>[...new Set(e.filter(Boolean))].slice(0,5),[e]),rt=ke?ye?ic+ye:"__custom__":ce?.slug??"__terminal__",mt=Te=>{re("idle");const H=Te.startsWith(ic)?Te.slice(ic.length):null;_e(H),$e(Te==="__custom__"||H!==null),(H!==null||Te==="__custom__")&&Ae(oe=>({...oe,__custom__:H??""})),xe(n.find(oe=>oe.slug===Te)??null)},ue=ke?ye??U("sidebar.customStartupCommand"):ce?.displayName??"Terminal",Ye=a?.displayName??"Terminal",st=!ke&&(ce===null?a===null:a?.slug===ce.slug);b.useEffect(()=>{if(pe)return;const Te=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",Te,!0),()=>document.removeEventListener("pointerdown",Te,!0)},[pe,L]);const Ie=Te=>{E({...r,cwd:Te}),te(!1)},We=Te=>new Intl.DateTimeFormat(V==="zh"?"zh-CN":"en",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}).format(new Date(Te));return s.jsxs("section",{ref:Z,tabIndex:-1,"aria-busy":W,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":U("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(Fo,{size:14})}),s.jsx("div",{className:"min-w-0",children:s.jsx("div",{className:"text-[12px] font-semibold text-foreground",children:U("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":U("common.close"),children:s.jsx(Rn,{size:14})})]}),s.jsxs("fieldset",{disabled:W,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:U("sidebar.sessionMode")}),s.jsx("div",{className:"grid grid-cols-2 gap-1 rounded-lg bg-surface p-0.5",children:["shell","tmux"].map(Te=>s.jsx("button",{type:"button",disabled:Te==="tmux"&&!t,onClick:()=>E({...r,mode:Te}),"aria-pressed":r.mode===Te,title:Te==="tmux"?U(t?"sidebar.tmuxKeepsRunning":"sidebar.newTmuxDisabled"):void 0,className:`min-h-9 rounded-md px-4 text-[11px] font-medium transition ${r.mode===Te?"bg-surface-2 text-foreground":"text-muted-foreground hover:text-foreground"} disabled:cursor-not-allowed disabled:opacity-40`,children:U(Te==="shell"?"sidebar.newShell":"sidebar.newTmux")},Te))})]}),s.jsxs("div",{className:"mt-1 flex items-center justify-between",children:[s.jsx("span",{className:"text-[11px] text-muted-foreground",children:U("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:U("sidebar.detectAgents"),"aria-label":U("sidebar.detectAgents"),children:s.jsx(gn,{size:12,className:c?"animate-spin":""})})]}),s.jsxs("div",{role:"radiogroup","aria-label":U("sidebar.startupCommand"),className:"flex flex-wrap gap-1",children:[n.map(Te=>{const H=!ke&&ce?.slug===Te.slug;return s.jsxs("button",{type:"button",role:"radio","aria-checked":H,onClick:()=>mt(Te.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:Te,size:12}),s.jsx("span",{className:"max-w-[9rem] truncate",children:Te.displayName}),a?.slug===Te.slug&&s.jsx("span",{className:"ml-0.5 text-[9px] text-muted-foreground",children:U("sidebar.defaultAgent")})]},Te.slug)}),lt.map(Te=>{const H=ke&&ye===Te;return s.jsxs("button",{type:"button",role:"radio","aria-checked":H,onClick:()=>mt(ic+Te),title:Te,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:Te})]},Te)}),s.jsxs("button",{type:"button",role:"radio","aria-checked":rt==="__terminal__",onClick:()=>mt("__terminal__"),className:`inline-flex min-h-7 items-center gap-1 rounded-md px-2 text-[10.5px] font-medium transition ${rt==="__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(Fo,{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:U("sidebar.defaultAgent")})]}),s.jsxs("button",{type:"button",role:"radio","aria-checked":rt==="__custom__",onClick:()=>mt("__custom__"),className:`inline-flex min-h-7 items-center gap-0.5 rounded-md px-2 text-[10.5px] font-medium transition ${rt==="__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(Us,{size:10,className:"shrink-0"}),s.jsx("span",{children:U("sidebar.addStartupCommand")})]})]}),!st&&!ke&&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:U("sidebar.currentDefaultAgent",{name:Ye})}),s.jsx("button",{type:"button",onClick:()=>y(ce),className:"relative z-10 shrink-0 rounded-md px-2 py-1.5 font-medium text-primary transition hover:bg-primary/10",children:U("sidebar.makeDefault")})]}),je==="error"&&s.jsx("p",{role:"alert",className:"text-[10px] text-destructive",children:U("sidebar.saveStartupCommandFailed")}),(ce||ke)&&s.jsxs("details",{open:ke&&!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:[U(ke&&!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:U("sidebar.startupCommand")}),ce&&Ee!==Ce&&s.jsx("button",{type:"button",onClick:()=>{Ae(Te=>({...Te,[Oe]:Ce})),re("idle")},className:"min-h-8 rounded-md px-2 text-[10px] text-primary transition hover:bg-primary/10",children:U("sidebar.resetStartupCommand")})]}),s.jsx("input",{id:"new-session-command",value:Ee,onChange:Te=>{Ae(H=>({...H,[Oe]:Te.target.value})),re("idle")},placeholder:Ce||U("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:[ke&&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":U("sidebar.deleteStartupCommand"),children:[s.jsx(zs,{size:11}),U("sidebar.deleteStartupCommand")]}),s.jsx("button",{type:"button",onClick:Be,disabled:je==="saved"||ke&&!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:U(je==="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:U(ce?"sidebar.agentStartupCommandHint":"sidebar.terminalStartupCommandHint")})]},ye??Oe),s.jsx("label",{htmlFor:"new-session-directory",className:"mt-2 block text-[11px] text-muted-foreground",children:U("sidebar.workingDirectory")}),s.jsxs("button",{id:"new-session-directory",type:"button","aria-haspopup":"dialog",onClick:()=>te(!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(Gc,{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||U("sidebar.directoryPlaceholder")})]}),He.length>0&&s.jsx("div",{className:"mt-1.5 flex gap-1 overflow-x-auto pb-0.5","aria-label":U("sidebar.recentDirectories"),children:He.map(Te=>s.jsx("button",{type:"button",onClick:()=>Ie(Te),title:Te,className:"min-h-8 shrink-0 rounded-md px-2 text-[10px] text-muted-foreground transition hover:bg-surface hover:text-foreground",children:Yu(Te)||Te},Te))}),(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:U("sidebar.resumeHistory")}),d&&s.jsx(Cn,{size:10,className:"animate-spin"}),l.length>0&&s.jsx("span",{className:"normal-case tracking-normal",children:U("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(Te=>{const H=p===Te.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(Te),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":U("sidebar.resumeHistoryAction",{title:Te.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(Cn,{size:13,className:"animate-spin"}):s.jsx(Wc,{agent:Te.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:Te.title}),s.jsxs("span",{className:"block truncate text-[9.5px] text-muted-foreground",children:[Te.agent.displayName," · ",We(Te.closedAt)]})]}),s.jsx(Qy,{size:12,className:"shrink-0 text-muted-foreground transition group-hover:text-primary"})]}),s.jsxs("button",{type:"button",disabled:p!==null,onClick:()=>S(Te.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":U("sidebar.resumeHistoryRemove",{title:Te.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(zs,{size:12})]})]},Te.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:[F&&s.jsx("p",{role:"alert",className:"mb-2 text-[11px] leading-relaxed text-destructive",children:F}),s.jsxs("button",{type:"button",onClick:le,disabled:W||ke&&!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":U("sidebar.launchSessionWith",{name:ue}),children:[W?s.jsx(Cn,{size:14}):ce?s.jsx(Wc,{agent:ce,size:15}):s.jsx(Fo,{size:14}),s.jsx("span",{className:"truncate",children:W?U("sidebar.sessionCreating"):U("sidebar.launchSessionWith",{name:ue})})]}),B]}),s.jsx(tp,{open:pe,initialPath:r.cwd?.trim()||He[0]||"/",title:U("sidebar.chooseDirectory"),onCancel:()=>te(!1),onConfirm:Ie})]})}const F6="termdock:new-session-agent:v1";function dO(){if(typeof window>"u")return null;try{const e=JSON.parse(window.localStorage.getItem(F6)||"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 wm(e){if(!(typeof window>"u"))try{window.localStorage.setItem(F6,JSON.stringify(e))}catch{}}function hO(e,t){return e?t.find(r=>r.slug===e)??null:null}function fO(){const[e,t]=b.useState(dO),[r,n]=b.useState([]),[a,c]=b.useState(!0),l=b.useCallback(async()=>{c(!0);try{const[p,m]=await Promise.all([fc(),Ay()]),x=hO(p.newSessionAgentSlug,m);n(m),t(x),wm(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),wm(p);try{await ka({newSessionAgentSlug:p?.slug??null})}catch(x){throw t(m),wm(m),x}},[e]);return{preference:e,agents:r,detecting:a,refresh:l,selectAgent:d}}function pO({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(Us,{size:14}),"新建协作组"]})]}),(e.length>5||l)&&s.jsxs("label",{className:"relative block",children:[s.jsx("span",{className:"sr-only",children:"搜索协作组"}),s.jsx(Ml,{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=>ku(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(N0,{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(TT,{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(e0,{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",kh="inline-flex min-h-11 items-center justify-center gap-2 rounded-lg px-3 text-xs disabled:opacity-40",Lh=e=>({profiles:e.launchProfiles??[],defaultId:e.defaultLaunchProfileId??"",group:e}),Am=new Map,Bd=e=>JSON.stringify(e.profiles)!==JSON.stringify(e.group.launchProfiles??[])||e.defaultId!==(e.group.defaultLaunchProfileId??"");function mO({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 gO({group:e,agents:t,busy:r,setBusy:n,refresh:a}){const c=`${window.location.origin}:${e.id}`,[l,d]=b.useState(()=>Am.get(c)??Lh(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=(U,V=!0)=>{p.current=U,d(U),Bd(U)?Am.set(c,U):Am.delete(c),V&&S("")};b.useEffect(()=>{!Bd(p.current)&&e.updatedAt>=p.current.group.updatedAt&&L(Lh(e),!1)},[e.updatedAt]);const E=l.profiles.find(U=>U.id===m),R=U=>L({...l,profiles:l.profiles.map(V=>V.id===m?{...V,...U}:V)}),B=l.profiles.every(U=>U.name.trim()&&U.agentSlug&&U.command.trim()&&!/[\x00-\x1f\x7f]/.test(U.command)),W=()=>{const U=t[0],V={id:`profile-${crypto.randomUUID()}`,name:"",agentSlug:U?.slug??"",command:U?.command??"",notes:""};L({...l,profiles:[...l.profiles,V]}),x(V.id)},F=async()=>{if(!(r||!B||!Bd(l))){n("launch-profiles"),w(null),S("");try{const{group:U}=await ac({id:e.id,name:l.group.name,sessionIds:l.group.sessionIds,expectedUpdatedAt:l.group.updatedAt,launchProfiles:l.profiles,defaultLaunchProfileId:l.defaultId||null});L(Lh(U)),S("启动方案已保存。新会话使用所选方案,正在运行的成员保持原配置。"),await a()}catch(U){w(U instanceof Error?U.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," 个",Bd(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:U=>L({...l,defaultId:U.target.value}),children:[s.jsx("option",{value:"",children:"使用 Agent 默认命令"}),l.profiles.map(U=>s.jsx("option",{value:U.id,children:U.name||"未命名方案"},U.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:U=>x(U.target.value),children:[s.jsx("option",{value:"",children:"选择方案"}),l.profiles.map(U=>s.jsx("option",{value:U.id,children:U.name||"未命名方案"},U.id))]})]}),s.jsxs("button",{type:"button",className:`${kh} self-end bg-surface text-foreground`,disabled:l.profiles.length>=20,onClick:W,children:[s.jsx(Us,{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:U=>R({name:U.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:U=>R({agentSlug:U.target.value,command:t.find(V=>V.slug===U.target.value)?.command??""}),children:[!t.some(U=>U.slug===E.agentSlug)&&s.jsxs("option",{value:E.agentSlug,children:[E.agentSlug||"选择 Agent","(当前不可用)"]}),t.map(U=>s.jsx("option",{value:U.slug,children:U.displayName},U.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:U=>R({command:U.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:U=>R({notes:U.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:`${kh} text-destructive hover:bg-destructive/10`,onClick:()=>{const U=l.profiles.filter(V=>V.id!==m);L({...l,profiles:U,defaultId:l.defaultId===m?"":l.defaultId}),x(U[0]?.id??"")},children:[s.jsx(zs,{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:`${kh} bg-surface text-muted-foreground`,disabled:!!r,onClick:()=>{L(Lh(e)),x(e.launchProfiles?.[0]?.id??""),w(null)},children:"重新载入(放弃方案草稿)"}),s.jsx("button",{type:"button",disabled:!!r||!B||!Bd(l),className:`${kh} bg-primary text-primary-foreground`,onClick:()=>{F()},children:r==="launch-profiles"?"保存中…":"保存启动方案"})]})]})]})}function xO(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 bO(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 wb(e){return new Date(e).toLocaleString([],{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1})}function jf({task:e,now:t,compact:r=!1}){const n=x6(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:wb(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():bO(e.updatedAt,t),children:wb(e.updatedAt)})]}):"记录更新时间未提供"})]})}function $6(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 Xh({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,W]=b.useState(""),F=b.useRef(Promise.resolve());b.useEffect(()=>{const te=v.current;te&&te.setSelectionRange(te.value.length,te.value.length)},[e]);const U=()=>({value:L.current.value,start:v.current?.selectionStart??n.length,end:v.current?.selectionEnd??n.length}),V=(te,ke=U())=>{L.current.onChange($e=>$e!==ke.value?$e+($e&&!/\s$/.test($e)?`
|
|
138
138
|
`:"")+te:$e.slice(0,ke.start)+te+$e.slice(ke.end))};b.useEffect(()=>{if(!c)return;const te=Ty(ke=>V(ke.replace(/\r\n?/g,`
|
|
139
|
-
`)),e,!!t,t);return t||t0(e),te},[c,e,t]);const Z=()=>{const te=u0();return`${location.origin}:${te?.targetPeerId??""}:${te?.serviceOrigin??""}`},ce=te=>{const ke=U(),$e=Z(),Y=L.current.onUploadChange;W(""),R(Ae=>Ae+1),Y?.(1),F.current=F.current.then(async()=>{try{if($e!==Z())throw new Error("目标服务已切换,请重新添加附件");const Ae=await te();if($e!==Z())throw new Error("目标服务已切换,请重新添加附件");Array.isArray(Ae)?V(Ae.map(Dc).join(" ")+" ",ke):Ae&&V(Ae,ke)}catch(Ae){const lt=Ae instanceof Error?Ae.message:"附件准备失败,请重试";W(lt.includes("Upload did not return")?"附件上传未返回完整路径,请重试":lt)}finally{R(Ae=>Ae-1),Y?.(-1)}})},xe=async te=>te.length===1&&te[0].type.startsWith("image/")?[await t3(te[0])]:s3(te),pe=te=>{const ke=te.clipboardData.files.length?Array.from(te.clipboardData.files):Array.from(te.clipboardData.items??[]).filter(Ae=>Ae.kind==="file").map(Ae=>Ae.getAsFile()).filter(Ae=>Ae!==null),$e=te.clipboardData.getData("text/plain"),Y=xo();!Y?.readClipboardFiles&&!ke.length&&$e||!Y&&!ke.length&&typeof navigator.clipboard?.read!="function"||(te.preventDefault(),ce(async()=>{const Ae=Z();let lt;if(Y?.readClipboardFiles)try{const Se=await n3();if(Se.paths.length||Se.files.length)return[...Se.paths,...await xe(Se.files)]}catch(Se){if(Se instanceof s0)throw Se;lt=Se}if(Ae!==Z())throw new Error("目标服务已切换,请重新粘贴");if(ke.length)return xe(ke);if($e)return $e;if(typeof navigator.clipboard?.read=="function"){const Se=await navigator.clipboard.read(),ye={read:async()=>Se},_e=await r3(ye);if(_e.length)return xe(_e);const je=await hf(ye);if(je)return xe([je]);for(const re of Se)if(re.types.includes("text/plain"))return(await re.getType("text/plain")).text()}else{const Se=await hf();if(Se)return xe([Se])}if(lt)throw lt;return null}))};return s.jsxs("div",{className:"space-y-1.5",onFocusCapture:()=>t0(e),onPointerDownCapture:()=>t0(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:te=>a(te.target.value),onPaste:pe,onDragOver:te=>{!l&&te.dataTransfer.types.includes("Files")&&te.preventDefault()},onDrop:te=>{const ke=Array.from(te.dataTransfer.files);!ke.length||l||(te.preventDefault(),te.stopPropagation(),ce(()=>xe(ke)))}}),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:te=>{const ke=Array.from(te.target.files??[]);te.target.value="",ke.length&&ce(()=>xe(ke))}}),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(VT,{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(gn,{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 Ab(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"&&!Fi(d)?p.find(y=>y.decisions.some(w=>w.status==="pending"))??p.find(y=>Fi(y)||y.workflow?.paused):void 0,x=p.filter(y=>Fi(y)||y.workflow?.paused).length;return{task:d,children:p,attention:m,attentionCount:x,rootId:l.get(d.id)}})}function U6(e,t=[]){const r=Yc(e),n={已验收:"已完成 · 你已验收",独立评审通过:"执行交付已评审",需要你回答:"请回答成员的问题",需要你确认方案:"请确认方案",等待你验收:"请查看结果并验收",成员报告受阻:"需要补充条件",成员报告失败:"成员报告执行失败",成员确认接手:"已接手 · 等待后续报告",成员报告进行中:"成员报告:进行中",等待独立评审:"结果已提交 · 等待评审","评审通过 · 等待接续":"交付已评审 · 等待接续","已要求跟进 · 等待新结果":"已提出跟进 · 等待新结果"};return e.status==="open"&&t.length&&!Fi(e)&&!e.artifacts.some(a=>a.kind==="result"&&a.attemptId===e.activeAttemptId)?t.every(a=>a.status==="accepted")?"执行交付已评审 · 等待总结果":"目标未完成 · 执行交付待齐":n[r]??r}function yO({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&&(Fi(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&&(Fi(x)||x.workflow?.paused),v=x?U6(x):y?m.completionMode==="reviewed"?"执行交付已评审":"已验收":"等待报告",S=y?Fu:$u;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(fi,{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 Tb(e){return e.status!=="open"?"done":Fi(e)||e.workflow?.paused?"attention":e.activeAttemptId?"running":"backlog"}const Sl=[{id:"backlog",label:"待开始",icon:$u,hint:"等待分派或依赖完成"},{id:"running",label:"执行中",icon:of,hint:"分派后的任务会出现在这里"},{id:"attention",label:"需要你",icon:N0,hint:"问题、方案与验收都在这里"},{id:"done",label:"已完成",icon:Fu,hint:"验收后的结果会保留在这里"}];function vO({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(oe=>{const be=oe[0].contentRect.width;E(be>=760),be!==y.current&&be<760&&m.current&&(m.current.scrollLeft=Sl.findIndex(Ze=>Ze.id===x.current)*m.current.clientWidth),y.current=be});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,W]=b.useState(()=>{if(Sl.some(be=>be.id===R?.lane))return R.lane;const oe=Ab(e,R?.showSteps===!0,R?.query??"").map(be=>be.attention?"attention":Tb(be.task));return oe.includes("attention")?"attention":oe.includes("running")?"running":oe.includes("backlog")?"backlog":"done"});x.current=B;function F(H,oe=!0){W(H);const be=m.current;if(!be||!be.clientWidth)return;w.current=H;const Ze=Sl.findIndex(St=>St.id===H)*be.clientWidth,Je=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;be.scrollTo?be.scrollTo({left:Ze,behavior:oe&&!Je?"smooth":"auto"}):be.scrollLeft=Ze}b.useEffect(()=>{L||F(x.current,!1)},[L]);const[U,V]=b.useState(typeof R?.scope=="string"?R.scope:"all"),[Z,ce]=b.useState(typeof R?.query=="string"?R.query:""),[xe,pe]=b.useState(R?.closed===!0),[te,ke]=b.useState(R?.showSteps===!0),[$e,Y]=b.useState(!!R?.query),[Ae,lt]=b.useState(!1),[Se,ye]=b.useState(!1),_e=b.useRef(null),je=b.useRef(null);b.useEffect(()=>{if(!Se)return;_e.current?.querySelector('[aria-label="看板更多操作"] button')?.focus();const H=be=>{_e.current?.contains(be.target)||ye(!1)},oe=be=>{be.key==="Escape"&&(be.preventDefault(),be.stopPropagation(),ye(!1),je.current?.focus())};return document.addEventListener("pointerdown",H),document.addEventListener("keydown",oe),()=>{document.removeEventListener("pointerdown",H),document.removeEventListener("keydown",oe)}},[Se]);const re=b.useRef(null),Oe=b.useRef(null),Ce=b.useRef(null),Ee=b.useRef(null);b.useEffect(()=>{$e&&re.current?.focus()},[$e]),b.useEffect(()=>{if(!Ae)return;Ce.current?.querySelector("select")?.focus();const H=be=>{Ce.current?.contains(be.target)||lt(!1)},oe=be=>{be.key==="Escape"&&(be.preventDefault(),be.stopPropagation(),lt(!1),(L?Ee:je).current?.focus())};return document.addEventListener("pointerdown",H),document.addEventListener("keydown",oe),()=>{document.removeEventListener("pointerdown",H),document.removeEventListener("keydown",oe)}},[Ae]),b.useEffect(()=>{try{localStorage.setItem(`${a}:board`,JSON.stringify({lane:B,scope:U,query:Z,closed:xe,showSteps:te}))}catch{}},[a,B,U,Z,xe,te]);const Be=e.filter(H=>H.workflow?.kind==="goal"),Ne=Ab(e,te,Z),le=new Map(Ne.map(H=>[H.task.id,H])),He=H=>le.get(H.id)?.attention?"attention":Tb(H),rt=t?Ne.find(H=>H.task.id===t||H.children.some(oe=>oe.id===t)):void 0,mt=rt?He(rt.task):void 0;b.useEffect(()=>{mt&&F(mt,!1)},[t,mt]);const ue=Ne.map(H=>H.task).filter(H=>(xe||H.status!=="closed")&&(U==="all"||H.id===U||le.get(H.id)?.rootId===U)&&(!Z.trim()||`${H.title} ${H.spec} ${H.attempts.map(oe=>n(H,oe.assignee)).join(" ")}`.toLocaleLowerCase().includes(Z.trim().toLocaleLowerCase()))),Ye=+(U!=="all")+Number(xe)+Number(te),st="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",We=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(Ml,{"aria-hidden":"true",size:15,className:"pointer-events-none absolute left-3 text-muted-foreground"}),s.jsx("input",{ref:re,"aria-label":"搜索任务",type:"search",value:Z,onChange:H=>ce(H.target.value),onKeyDown:H=>{H.key==="Escape"&&(H.preventDefault(),H.stopPropagation(),Z?ce(""):(Y(!1),requestAnimationFrame(()=>(L?Oe:je).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:()=>{ce(""),Y(!1),requestAnimationFrame(()=>(L?Oe:je).current?.focus())},children:s.jsx(Rn,{size:14})})]}),Te=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:U,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:"所有目标"}),Be.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:xe,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:te,onChange:H=>ke(H.target.checked)}),"显示执行子任务"]}),Ye>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),ke(!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:Ce,"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}),$e?We:s.jsx("button",{ref:Oe,type:"button","aria-label":"搜索任务",title:"搜索任务",className:`${st} ${l?"":"ml-auto"}`,onClick:()=>Y(!0),children:s.jsx(Ml,{size:16})}),s.jsxs("div",{ref:Ce,className:"relative shrink-0",children:[s.jsxs("button",{ref:Ee,type:"button","aria-label":Ye?`筛选任务,${Ye} 项已启用`:"筛选任务","aria-expanded":Ae,className:`${st} ${Ye?"text-primary":""}`,onClick:()=>lt(H=>!H),children:[s.jsx($m,{size:15}),s.jsx("span",{children:"筛选"}),Ye>0&&s.jsx("span",{className:"tabular-nums text-primary",children:Ye})]}),Ae&&Te]}),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:_e,className:"relative shrink-0",children:[s.jsxs("button",{ref:je,type:"button","aria-label":"更多看板操作","aria-expanded":Se,className:`${st} ${Se?"bg-surface-2 text-foreground":Ye||Z.trim()?"text-primary":""}`,onClick:()=>{ye(H=>!H),lt(!1)},children:[s.jsx($o,{size:18}),Ye>0&&s.jsx("span",{className:"text-[10px]",children:Ye})]}),Se&&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:Oe,type:"button","aria-label":"搜索任务",className:Ie,onClick:()=>Y(!0),children:[s.jsx(Ml,{size:18,className:"shrink-0 text-muted-foreground"}),"搜索任务"]}),s.jsxs("button",{ref:Ee,type:"button","aria-label":Ye?`筛选任务,${Ye} 项已启用`:"筛选任务",className:Ie,onClick:()=>lt(!0),children:[s.jsx($m,{size:18,className:"shrink-0 text-muted-foreground"}),"筛选任务",Ye>0&&s.jsx("span",{className:"ml-auto rounded bg-primary/10 px-1.5 text-xs tabular-nums text-primary",children:Ye})]}),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})]})]}),$e&&We,Ae&&Te]})}),s.jsx("p",{className:"px-1 text-[11px] leading-5 text-muted-foreground",children:te?"包含执行子任务,可在筛选中切回目标视图。":"每张卡片对应一个目标,待完成事项和最近交付直接显示在卡片中。"}),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:()=>F(H.id),children:[H.label,s.jsx("span",{className:"ml-1 tabular-nums",children:ue.filter(oe=>He(oe)===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 oe=w.current;if(oe){const Ze=Sl.findIndex(Je=>Je.id===oe)*H.currentTarget.clientWidth;if(Math.abs(H.currentTarget.scrollLeft-Ze)>2)return;w.current=null}const be=Math.max(0,Math.min(Sl.length-1,Math.round(H.currentTarget.scrollLeft/H.currentTarget.clientWidth)));W(Sl[be].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 oe=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(oe,{size:15}),H.label,s.jsx("span",{className:"ml-auto tabular-nums text-xs",children:ue.filter(be=>He(be)===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 oe=ue.filter(be=>He(be)===H.id).sort((be,Ze)=>Ze.updatedAt-be.updatedAt);return s.jsx("section",{"aria-label":`${H.label}任务`,"aria-hidden":!L&&B!==H.id?!0:void 0,ref:be=>{be&&(be.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:[oe.map(be=>{const Ze=le.get(be.id),Je=Ze.attention??be,St=Je.attempts.find(Ve=>Ve.id===Je.activeAttemptId),Vt=Je.decisions.find(Ve=>Ve.status==="pending"),jt=Yc(Je),vt=U6(Je,Ze.children),Zt=Xf(Je),Pt=Zt[0],Xt=Zt.find(Ve=>Ve.source==="system"),zt=Zt.find(Ve=>Ve.source==="unknown"),Lt=Xt?.content,me=H.id==="attention",Ge=Vt?"回答问题":zt?"查看详情核对记录":Pt?.source==="member"&&Xt?"查看条件与异常处理":Pt?.source==="member"?"查看阻塞并补充条件":Lt?"查看原因与处理":jt==="等待你验收"?"查看结果并验收":jt==="需要你确认方案"?"查看并确认方案":"查看任务并处理",pt=Je.artifacts.filter(Ve=>Ve.kind==="result"&&Ve.attemptId===Je.activeAttemptId).at(-1),q=Je.events.filter(Ve=>Ve.kind==="revise"&&Ve.source==="user"&&Ve.attemptId===Je.activeAttemptId&&(!pt||Ve.createdAt>=pt.createdAt)).at(-1),at=Vt?Vt.question||"成员提出了一个问题,打开后可查看并回答。":Pt?.summary||q?.content||pt?.summary||(St?.report?.content?$6(St.report.content).summary:St?.report?.summary||""),qt=e.find(Ve=>Ve.id===be.parentTaskId);return s.jsxs("article",{"aria-label":be.title,className:`overflow-hidden rounded-xl border bg-surface text-left shadow-sm ${t===be.id?"border-primary/60":Lt?"border-destructive/35":"border-border/20"}`,children:[s.jsxs("button",{type:"button","data-task-id":be.id,"aria-pressed":t===be.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(Je.id),children:[qt&&s.jsx("span",{className:"mb-2 block truncate text-[10px] text-muted-foreground",children:qt.title}),s.jsx("span",{title:be.title,className:"block line-clamp-3 break-words text-sm font-medium leading-6 text-foreground",children:be.title}),s.jsxs("span",{className:`mt-3 flex items-center gap-1.5 text-xs ${Lt&&Pt?.source!=="member"?"text-destructive":me?"text-primary":"text-muted-foreground"}`,children:[Lt&&Pt?.source!=="member"&&s.jsx(Q1,{size:13,className:"shrink-0"}),vt]}),Ze.attention&&s.jsxs("span",{className:"mt-2 block truncate text-[11px] text-muted-foreground",children:["来自执行任务:",Ze.attention.title]}),Ze.attention&&Ze.attentionCount>1&&s.jsxs("span",{className:"mt-1 block text-[11px] text-primary",children:["共 ",Ze.attentionCount," 项执行需要你处理"]}),at&&s.jsx("span",{className:"mt-2 line-clamp-3 break-words text-xs leading-5 text-foreground/80",children:at}),Xt&&Pt?.source==="member"&&s.jsxs("span",{className:"mt-2 block line-clamp-2 break-words text-xs leading-5 text-destructive",children:[Xt.label,":",Xt.summary]}),zt&&s.jsxs("span",{className:"mt-2 block line-clamp-2 break-words text-xs leading-5 text-muted-foreground",children:[zt.label,":",zt.summary]}),me&&s.jsxs("span",{className:`mt-4 flex min-h-9 items-center justify-between rounded-lg px-2.5 text-xs font-medium ${Lt?"bg-destructive/10 text-destructive":"bg-primary/10 text-primary"}`,children:[Ge,s.jsx(Fm,{size:14})]}),!me&&(be.status==="accepted"||be.artifacts.some(Ve=>Ve.kind==="result"&&Ve.attemptId===be.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(Fm,{size:14})]})]}),s.jsx(yO,{task:be,children:Ze.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:[Ze.attention?"待处理任务负责人:":be.workflow?.kind==="goal"?"协调者:":"负责人:",St?n(Je,St.assignee):Je.scheduledAssignee?n(Je,Je.scheduledAssignee):"未分派"]}),s.jsx(jf,{task:Je,now:v,compact:!0})]})]},be.id)}),!oe.length&&s.jsx("p",{className:"px-2 py-3 text-xs leading-6 text-muted-foreground/70",children:Z||U!=="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 Ih(e,t){return r=>Rl.getState().update(e,t,r)}function Tm(e,t){return r=>Rl.getState().updateDetail(e,t,r)}const wO=b.lazy(()=>Oc(()=>Promise.resolve().then(()=>cO),void 0).then(e=>({default:e.DirectoryPickerDialog}))),AO=b.lazy(()=>Oc(()=>import("./CollaborationTaskContent-MwUgcmG_.js"),__vite__mapDeps([6,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17]))),oa="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",Qs="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=`${oa} bg-primary text-primary-foreground`,si=`${oa} bg-surface-2 text-foreground hover:bg-surface-2/80`,TO={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:"请求重新检查"},Bu=e=>`${e.serviceId}:${e.sessionId}`,Ta=e=>new Date(e).toLocaleString([],{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit"});function Qo(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 Oa(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch{}}const Kd={mode:"goal",isolated:!0,title:"",spec:"",constraints:"",acceptance:"",assignee:"",coordinator:"",parent:"",dependencies:[]};function SO(e){const t={...Kd,...Qo(e,Kd)};return!t||!Array.isArray(t.dependencies)||t.dependencies.some(r=>typeof r!="string")||Object.keys(Kd).some(r=>!["dependencies","isolated"].includes(r)&&typeof t[r]!="string")?Kd:{...t,mode:t.mode==="task"?"task":"goal",isolated:t.isolated!==!1}}function z6(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 CO({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),[W]=b.useState(()=>Rl.getState().ensure(v,{draft:SO(`${v}:draft`),selectedId:Qo(`${v}:selected`,null),creating:!1,mobileDetail:!1})),{selectedId:F,mobileDetail:U,creating:V,draft:Z}=Rl(ne=>ne.views[v]??W),ce=Ih(v,"selectedId"),xe=Ih(v,"mobileDetail"),pe=Ih(v,"creating"),te=Ih(v,"draft"),[ke,$e]=b.useState(!1),[Y,Ae]=b.useState(!1),lt=b.useRef(null),Se=b.useRef(null),ye=b.useRef(!1),_e=b.useCallback(ne=>{!ne&&Se.current===document.activeElement&&(ye.current=!0),Se.current=ne,ne&&ye.current&&(ye.current=!1,ne.focus())},[]);b.useEffect(()=>{const ne=lt.current;if(!ne)return;const ht=new ResizeObserver(Ht=>$e(Ht[0].contentRect.width>=(l?1100:760)));return ht.observe(ne),()=>ht.disconnect()},[l]);const[je,re]=b.useState(!1),[Oe,Ce]=b.useState(null),Ee=Sy(),[Be,Ne]=b.useState(0),[le,He]=b.useState(null),[rt,mt]=b.useState(!1),[ue,Ye]=b.useState(0),st=ne=>Ye(ht=>Math.max(0,ht+ne)),[Ie,We]=b.useState("");b.useEffect(()=>{if(!Ie)return;const ne=setTimeout(()=>We(""),5e3);return()=>clearTimeout(ne)},[Ie]);const[Te,H]=b.useState("open"),[oe,be]=b.useState(""),Ze=b.useRef(!1),Je=b.useRef(!0),St=b.useRef(new Map),Vt=b.useRef(!1),jt=e.sessionIds.flatMap(ne=>{const ht=t.find(Ht=>Ht.sessionId===ne);return ht?[ht]:[]}),vt=jt.map(ne=>({...ne,name:ku(ne,jt)})),Zt=Z.coordinator||Qo(`${v}:lead`,""),Pt=vt.find(ne=>ne.sessionId===Zt)?.sessionId||vt.find(ne=>ne.agent)?.sessionId||vt[0]?.sessionId||"",Xt=vt.filter(ne=>ne.sessionId!==Pt&&ne.agent).map(ne=>ne.sessionId),[zt,Lt]=b.useState(!1),[me,Ge]=b.useState(!1),[pt,q]=b.useState(()=>Qo(`${v}:agent`,x[0]?.slug??"")),[at,qt]=b.useState(()=>Qo(`${v}:launch-profile`,e.defaultLaunchProfileId??"")),Ve=e.launchProfiles?.find(ne=>ne.id===at),De=Ve?.agentSlug??pt,[er,et]=b.useState(()=>Qo(`${v}:cwd`,vt[0]?.cwd??y??""));b.useEffect(()=>{!pt&&x[0]&&q(x[0].slug)},[x,pt]);const Ct=!vt.find(ne=>ne.sessionId===Pt)?.agent||!Xt.length,[Nt,gt]=b.useState(null),bt=!!Z.spec.trim()&&(!!Nt||!Ct||!e.federated&&(!at||!!Ve)&&!!x.find(ne=>ne.slug===De)&&!!er.trim()),It=S.find(ne=>ne.id===F)??null,yt=R?.id===F?R:null;b.useEffect(()=>(Je.current=!0,()=>{Je.current=!1}),[]),b.useEffect(()=>{Oa(`${v}:draft`,Z)},[v,Z]),b.useEffect(()=>{Oa(`${v}:selected`,F)},[v,F]),b.useEffect(()=>{const ne=Ht=>{const Ot=Ht.detail;Ot?.groupId===e.id&&(Oa(`${v}:open-task`,null),ce(Ot.taskId),xe(!0),pe(!1),H("all"),pr())};window.addEventListener("open-collaboration-task",ne);const ht=Qo(`${v}:open-task`,null);return ht&&(ce(ht),xe(!0),H("all"),Oa(`${v}:open-task`,null)),()=>window.removeEventListener("open-collaboration-task",ne)},[e.id]),b.useEffect(()=>{if(!r||!It||R?.id===It.id&&R.revision===It.revision)return;let ne=!1;return jw(It.id).then(ht=>{ne||(B(ht.task),Ce(null))}).catch(ht=>{ne||Ce(ht instanceof Error?ht.message:"任务详情加载失败")}),()=>{ne=!0}},[r,It?.id,It?.revision,R?.id,R?.revision,Be]);const pr=async()=>{if(!Vt.current){Vt.current=!0;try{const ne=await vy(e.id);Je.current&&(L(ne.tasks),re(!0),Ce(null),Ne(ht=>ht+1))}catch(ne){Je.current&&Ce(ne instanceof Error?ne.message:"任务加载失败")}finally{Vt.current=!1}}};b.useEffect(()=>{if(!r)return;pr();const ne=()=>{!document.hidden&&navigator.onLine!==!1&&pr()},ht=setInterval(ne,2500);return document.addEventListener("visibilitychange",ne),window.addEventListener(nf,ne),window.addEventListener("pageshow",ne),()=>{clearInterval(ht),document.removeEventListener("visibilitychange",ne),window.removeEventListener(nf,ne),window.removeEventListener("pageshow",ne)}},[r,e.id]);const nr=ne=>{const ht=JSON.stringify(ne),Ht=Qo(`${v}:request`,null);let Ot=St.current.get(ht)??(Ht?.fingerprint===ht?Ht.key:void 0);return Ot||(Ot=crypto.randomUUID(),St.current.set(ht,Ot)),Oa(`${v}:request`,{fingerprint:ht,key:Ot}),Ot},Cr=ne=>{St.current.delete(JSON.stringify(ne)),Oa(`${v}:request`,null)},cn=async(ne,ht)=>{if(rt||Ze.current)return{ok:!1,error:"已有操作正在提交,请稍候。"};Ze.current=!0,mt(!0),He(null),We("");let Ht={...ht,expectedRevision:ne.revision};if(["comment","revise"].includes(ht.kind)){const Ot=Qo(`${v}:request`,null);try{const[Tr,mr]=JSON.parse(Ot?.fingerprint??"null"),{expectedRevision:Hr,..._n}=mr;Tr===ne.id&&JSON.stringify(_n)===JSON.stringify(ht)&&(Ht=mr)}catch{}}try{const Ot=await Qw(ne.id,{...Ht,idempotencyKey:nr([ne.id,Ht])});if(Cr([ne.id,Ht]),_u.getState().refresh(),Je.current){const Tr=E.current.find(dr=>dr.id===Ot.task.id),mr=Tr&&Tr.revision>Ot.task.revision?Tr:Ot.task;L(dr=>dr.map(bn=>bn.id===Ot.task.id&&bn.revision<=Ot.task.revision?Ot.task:bn)),B(dr=>dr?.id===Ot.task.id&&dr.revision>Ot.task.revision?dr:Ot.task);const Hr=z6(mr,E.current),_n=`${ht.kind==="answer"?"回答已保存":"方案确认已保存"},${Hr?Hr.workflow?.kind==="goal"?"目标仍暂停;恢复目标后才能投递。":"任务仍暂停;继续安排后才能投递。":"投递状态请查看任务记录。"}`;We(["comment","revise"].includes(ht.kind)?"":ht.kind==="retry"?xO(ne,Ot.task):["answer","approve-plan"].includes(ht.kind)?_n:ht.kind==="accept"?"已验收此版本结果。":"记录已保存。")}return{ok:!0}}catch(Ot){const Tr=Ot instanceof Error?Ot.message:"操作失败";return Tr.includes("任务已更新")&&Cr([ne.id,Ht]),Je.current&&(He(["comment","revise"].includes(ht.kind)?null:Tr),pr()),{ok:!1,error:Tr}}finally{Ze.current=!1,Je.current&&mt(!1)}},Lr=async ne=>{if(ne.preventDefault(),rt||ue>0||(Z.mode==="goal"?!bt:!Z.title.trim()||!Z.spec.trim())||Ze.current)return;Ze.current=!0,mt(!0),He(null);const ht=Z.mode==="goal",Ht={groupId:e.id,title:Z.title.trim()||Z.spec.trim().split(`
|
|
139
|
+
`)),e,!!t,t);return t||t0(e),te},[c,e,t]);const Z=()=>{const te=u0();return`${location.origin}:${te?.targetPeerId??""}:${te?.serviceOrigin??""}`},ce=te=>{const ke=U(),$e=Z(),Y=L.current.onUploadChange;W(""),R(Ae=>Ae+1),Y?.(1),F.current=F.current.then(async()=>{try{if($e!==Z())throw new Error("目标服务已切换,请重新添加附件");const Ae=await te();if($e!==Z())throw new Error("目标服务已切换,请重新添加附件");Array.isArray(Ae)?V(Ae.map(Dc).join(" ")+" ",ke):Ae&&V(Ae,ke)}catch(Ae){const lt=Ae instanceof Error?Ae.message:"附件准备失败,请重试";W(lt.includes("Upload did not return")?"附件上传未返回完整路径,请重试":lt)}finally{R(Ae=>Ae-1),Y?.(-1)}})},xe=async te=>te.length===1&&te[0].type.startsWith("image/")?[await t3(te[0])]:s3(te),pe=te=>{const ke=te.clipboardData.files.length?Array.from(te.clipboardData.files):Array.from(te.clipboardData.items??[]).filter(Ae=>Ae.kind==="file").map(Ae=>Ae.getAsFile()).filter(Ae=>Ae!==null),$e=te.clipboardData.getData("text/plain"),Y=xo();!Y?.readClipboardFiles&&!ke.length&&$e||!Y&&!ke.length&&typeof navigator.clipboard?.read!="function"||(te.preventDefault(),ce(async()=>{const Ae=Z();let lt;if(Y?.readClipboardFiles)try{const Se=await n3();if(Se.paths.length||Se.files.length)return[...Se.paths,...await xe(Se.files)]}catch(Se){if(Se instanceof s0)throw Se;lt=Se}if(Ae!==Z())throw new Error("目标服务已切换,请重新粘贴");if(ke.length)return xe(ke);if($e)return $e;if(typeof navigator.clipboard?.read=="function"){const Se=await navigator.clipboard.read(),ye={read:async()=>Se},_e=await r3(ye);if(_e.length)return xe(_e);const je=await hf(ye);if(je)return xe([je]);for(const re of Se)if(re.types.includes("text/plain"))return(await re.getType("text/plain")).text()}else{const Se=await hf();if(Se)return xe([Se])}if(lt)throw lt;return null}))};return s.jsxs("div",{className:"space-y-1.5",onFocusCapture:()=>t0(e),onPointerDownCapture:()=>t0(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:te=>a(te.target.value),onPaste:pe,onDragOver:te=>{!l&&te.dataTransfer.types.includes("Files")&&te.preventDefault()},onDrop:te=>{const ke=Array.from(te.dataTransfer.files);!ke.length||l||(te.preventDefault(),te.stopPropagation(),ce(()=>xe(ke)))}}),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:te=>{const ke=Array.from(te.target.files??[]);te.target.value="",ke.length&&ce(()=>xe(ke))}}),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(VT,{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(gn,{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 Ab(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"&&!Fi(d)?p.find(y=>y.decisions.some(w=>w.status==="pending"))??p.find(y=>Fi(y)||y.workflow?.paused):void 0,x=p.filter(y=>Fi(y)||y.workflow?.paused).length;return{task:d,children:p,attention:m,attentionCount:x,rootId:l.get(d.id)}})}function U6(e,t=[]){const r=Yc(e),n={已验收:"已完成 · 你已验收",独立评审通过:"执行交付已评审",需要你回答:"请回答成员的问题",需要你确认方案:"请确认方案",等待你验收:"请查看结果并验收",成员报告受阻:"需要补充条件",成员报告失败:"成员报告执行失败",成员确认接手:"已接手 · 等待后续报告",成员报告进行中:"成员报告:进行中",等待独立评审:"结果已提交 · 等待评审","评审通过 · 等待接续":"交付已评审 · 等待接续","已要求跟进 · 等待新结果":"已提出跟进 · 等待新结果"};return e.status==="open"&&t.length&&!Fi(e)&&!e.artifacts.some(a=>a.kind==="result"&&a.attemptId===e.activeAttemptId)?t.every(a=>a.status==="accepted")?"执行交付已评审 · 等待总结果":"目标未完成 · 执行交付待齐":n[r]??r}function yO({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&&(Fi(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&&(Fi(x)||x.workflow?.paused),v=x?U6(x):y?m.completionMode==="reviewed"?"执行交付已评审":"已验收":"等待报告",S=y?Fu:$u;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(fi,{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 Tb(e){return e.status!=="open"?"done":Fi(e)||e.workflow?.paused?"attention":e.activeAttemptId?"running":"backlog"}const Sl=[{id:"backlog",label:"待开始",icon:$u,hint:"等待分派或依赖完成"},{id:"running",label:"执行中",icon:of,hint:"分派后的任务会出现在这里"},{id:"attention",label:"需要你",icon:N0,hint:"问题、方案与验收都在这里"},{id:"done",label:"已完成",icon:Fu,hint:"验收后的结果会保留在这里"}];function vO({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(oe=>{const be=oe[0].contentRect.width;E(be>=760),be!==y.current&&be<760&&m.current&&(m.current.scrollLeft=Sl.findIndex(Ze=>Ze.id===x.current)*m.current.clientWidth),y.current=be});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,W]=b.useState(()=>{if(Sl.some(be=>be.id===R?.lane))return R.lane;const oe=Ab(e,R?.showSteps===!0,R?.query??"").map(be=>be.attention?"attention":Tb(be.task));return oe.includes("attention")?"attention":oe.includes("running")?"running":oe.includes("backlog")?"backlog":"done"});x.current=B;function F(H,oe=!0){W(H);const be=m.current;if(!be||!be.clientWidth)return;w.current=H;const Ze=Sl.findIndex(St=>St.id===H)*be.clientWidth,Je=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;be.scrollTo?be.scrollTo({left:Ze,behavior:oe&&!Je?"smooth":"auto"}):be.scrollLeft=Ze}b.useEffect(()=>{L||F(x.current,!1)},[L]);const[U,V]=b.useState(typeof R?.scope=="string"?R.scope:"all"),[Z,ce]=b.useState(typeof R?.query=="string"?R.query:""),[xe,pe]=b.useState(R?.closed===!0),[te,ke]=b.useState(R?.showSteps===!0),[$e,Y]=b.useState(!!R?.query),[Ae,lt]=b.useState(!1),[Se,ye]=b.useState(!1),_e=b.useRef(null),je=b.useRef(null);b.useEffect(()=>{if(!Se)return;_e.current?.querySelector('[aria-label="看板更多操作"] button')?.focus();const H=be=>{_e.current?.contains(be.target)||ye(!1)},oe=be=>{be.key==="Escape"&&(be.preventDefault(),be.stopPropagation(),ye(!1),je.current?.focus())};return document.addEventListener("pointerdown",H),document.addEventListener("keydown",oe),()=>{document.removeEventListener("pointerdown",H),document.removeEventListener("keydown",oe)}},[Se]);const re=b.useRef(null),Oe=b.useRef(null),Ce=b.useRef(null),Ee=b.useRef(null);b.useEffect(()=>{$e&&re.current?.focus()},[$e]),b.useEffect(()=>{if(!Ae)return;Ce.current?.querySelector("select")?.focus();const H=be=>{Ce.current?.contains(be.target)||lt(!1)},oe=be=>{be.key==="Escape"&&(be.preventDefault(),be.stopPropagation(),lt(!1),(L?Ee:je).current?.focus())};return document.addEventListener("pointerdown",H),document.addEventListener("keydown",oe),()=>{document.removeEventListener("pointerdown",H),document.removeEventListener("keydown",oe)}},[Ae]),b.useEffect(()=>{try{localStorage.setItem(`${a}:board`,JSON.stringify({lane:B,scope:U,query:Z,closed:xe,showSteps:te}))}catch{}},[a,B,U,Z,xe,te]);const Be=e.filter(H=>H.workflow?.kind==="goal"),Ne=Ab(e,te,Z),le=new Map(Ne.map(H=>[H.task.id,H])),He=H=>le.get(H.id)?.attention?"attention":Tb(H),rt=t?Ne.find(H=>H.task.id===t||H.children.some(oe=>oe.id===t)):void 0,mt=rt?He(rt.task):void 0;b.useEffect(()=>{mt&&F(mt,!1)},[t,mt]);const ue=Ne.map(H=>H.task).filter(H=>(xe||H.status!=="closed")&&(U==="all"||H.id===U||le.get(H.id)?.rootId===U)&&(!Z.trim()||`${H.title} ${H.spec} ${H.attempts.map(oe=>n(H,oe.assignee)).join(" ")}`.toLocaleLowerCase().includes(Z.trim().toLocaleLowerCase()))),Ye=+(U!=="all")+Number(xe)+Number(te),st="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",We=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(Ml,{"aria-hidden":"true",size:15,className:"pointer-events-none absolute left-3 text-muted-foreground"}),s.jsx("input",{ref:re,"aria-label":"搜索任务",type:"search",value:Z,onChange:H=>ce(H.target.value),onKeyDown:H=>{H.key==="Escape"&&(H.preventDefault(),H.stopPropagation(),Z?ce(""):(Y(!1),requestAnimationFrame(()=>(L?Oe:je).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:()=>{ce(""),Y(!1),requestAnimationFrame(()=>(L?Oe:je).current?.focus())},children:s.jsx(Rn,{size:14})})]}),Te=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:U,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:"所有目标"}),Be.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:xe,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:te,onChange:H=>ke(H.target.checked)}),"显示执行子任务"]}),Ye>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),ke(!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:Ce,"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}),$e?We:s.jsx("button",{ref:Oe,type:"button","aria-label":"搜索任务",title:"搜索任务",className:`${st} ${l?"":"ml-auto"}`,onClick:()=>Y(!0),children:s.jsx(Ml,{size:16})}),s.jsxs("div",{ref:Ce,className:"relative shrink-0",children:[s.jsxs("button",{ref:Ee,type:"button","aria-label":Ye?`筛选任务,${Ye} 项已启用`:"筛选任务","aria-expanded":Ae,className:`${st} ${Ye?"text-primary":""}`,onClick:()=>lt(H=>!H),children:[s.jsx($m,{size:15}),s.jsx("span",{children:"筛选"}),Ye>0&&s.jsx("span",{className:"tabular-nums text-primary",children:Ye})]}),Ae&&Te]}),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:_e,className:"relative shrink-0",children:[s.jsxs("button",{ref:je,type:"button","aria-label":"更多看板操作","aria-expanded":Se,className:`${st} ${Se?"bg-surface-2 text-foreground":Ye||Z.trim()?"text-primary":""}`,onClick:()=>{ye(H=>!H),lt(!1)},children:[s.jsx($o,{size:18}),Ye>0&&s.jsx("span",{className:"text-[10px]",children:Ye})]}),Se&&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:Oe,type:"button","aria-label":"搜索任务",className:Ie,onClick:()=>Y(!0),children:[s.jsx(Ml,{size:18,className:"shrink-0 text-muted-foreground"}),"搜索任务"]}),s.jsxs("button",{ref:Ee,type:"button","aria-label":Ye?`筛选任务,${Ye} 项已启用`:"筛选任务",className:Ie,onClick:()=>lt(!0),children:[s.jsx($m,{size:18,className:"shrink-0 text-muted-foreground"}),"筛选任务",Ye>0&&s.jsx("span",{className:"ml-auto rounded bg-primary/10 px-1.5 text-xs tabular-nums text-primary",children:Ye})]}),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})]})]}),$e&&We,Ae&&Te]})}),s.jsx("p",{className:"px-1 text-[11px] leading-5 text-muted-foreground",children:te?"包含执行子任务,可在筛选中切回目标视图。":"每张卡片对应一个目标,待完成事项和最近交付直接显示在卡片中。"}),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:()=>F(H.id),children:[H.label,s.jsx("span",{className:"ml-1 tabular-nums",children:ue.filter(oe=>He(oe)===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 oe=w.current;if(oe){const Ze=Sl.findIndex(Je=>Je.id===oe)*H.currentTarget.clientWidth;if(Math.abs(H.currentTarget.scrollLeft-Ze)>2)return;w.current=null}const be=Math.max(0,Math.min(Sl.length-1,Math.round(H.currentTarget.scrollLeft/H.currentTarget.clientWidth)));W(Sl[be].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 oe=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(oe,{size:15}),H.label,s.jsx("span",{className:"ml-auto tabular-nums text-xs",children:ue.filter(be=>He(be)===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 oe=ue.filter(be=>He(be)===H.id).sort((be,Ze)=>Ze.updatedAt-be.updatedAt);return s.jsx("section",{"aria-label":`${H.label}任务`,"aria-hidden":!L&&B!==H.id?!0:void 0,ref:be=>{be&&(be.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:[oe.map(be=>{const Ze=le.get(be.id),Je=Ze.attention??be,St=Je.attempts.find(Ve=>Ve.id===Je.activeAttemptId),Vt=Je.decisions.find(Ve=>Ve.status==="pending"),jt=Yc(Je),vt=U6(Je,Ze.children),Zt=Xf(Je),Pt=Zt[0],Xt=Zt.find(Ve=>Ve.source==="system"),zt=Zt.find(Ve=>Ve.source==="unknown"),Lt=Xt?.content,me=H.id==="attention",Ge=Vt?"回答问题":zt?"查看详情核对记录":Pt?.source==="member"&&Xt?"查看条件与异常处理":Pt?.source==="member"?"查看阻塞并补充条件":Lt?"查看原因与处理":jt==="等待你验收"?"查看结果并验收":jt==="需要你确认方案"?"查看并确认方案":"查看任务并处理",pt=Je.artifacts.filter(Ve=>Ve.kind==="result"&&Ve.attemptId===Je.activeAttemptId).at(-1),q=Je.events.filter(Ve=>Ve.kind==="revise"&&Ve.source==="user"&&Ve.attemptId===Je.activeAttemptId&&(!pt||Ve.createdAt>=pt.createdAt)).at(-1),at=Vt?Vt.question||"成员提出了一个问题,打开后可查看并回答。":Pt?.summary||q?.content||pt?.summary||(St?.report?.content?$6(St.report.content).summary:St?.report?.summary||""),qt=e.find(Ve=>Ve.id===be.parentTaskId);return s.jsxs("article",{"aria-label":be.title,className:`overflow-hidden rounded-xl border bg-surface text-left shadow-sm ${t===be.id?"border-primary/60":Lt?"border-destructive/35":"border-border/20"}`,children:[s.jsxs("button",{type:"button","data-task-id":be.id,"aria-pressed":t===be.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(Je.id),children:[qt&&s.jsx("span",{className:"mb-2 block truncate text-[10px] text-muted-foreground",children:qt.title}),s.jsx("span",{title:be.title,className:"block line-clamp-3 break-words text-sm font-medium leading-6 text-foreground",children:be.title}),s.jsxs("span",{className:`mt-3 flex items-center gap-1.5 text-xs ${Lt&&Pt?.source!=="member"?"text-destructive":me?"text-primary":"text-muted-foreground"}`,children:[Lt&&Pt?.source!=="member"&&s.jsx(Q1,{size:13,className:"shrink-0"}),vt]}),Ze.attention&&s.jsxs("span",{className:"mt-2 block truncate text-[11px] text-muted-foreground",children:["来自执行任务:",Ze.attention.title]}),Ze.attention&&Ze.attentionCount>1&&s.jsxs("span",{className:"mt-1 block text-[11px] text-primary",children:["共 ",Ze.attentionCount," 项执行需要你处理"]}),at&&s.jsx("span",{className:"mt-2 line-clamp-3 break-words text-xs leading-5 text-foreground/80",children:at}),Xt&&Pt?.source==="member"&&s.jsxs("span",{className:"mt-2 block line-clamp-2 break-words text-xs leading-5 text-destructive",children:[Xt.label,":",Xt.summary]}),zt&&s.jsxs("span",{className:"mt-2 block line-clamp-2 break-words text-xs leading-5 text-muted-foreground",children:[zt.label,":",zt.summary]}),me&&s.jsxs("span",{className:`mt-4 flex min-h-9 items-center justify-between rounded-lg px-2.5 text-xs font-medium ${Lt?"bg-destructive/10 text-destructive":"bg-primary/10 text-primary"}`,children:[Ge,s.jsx(Fm,{size:14})]}),!me&&(be.status==="accepted"||be.artifacts.some(Ve=>Ve.kind==="result"&&Ve.attemptId===be.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(Fm,{size:14})]})]}),s.jsx(yO,{task:be,children:Ze.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:[Ze.attention?"待处理任务负责人:":be.workflow?.kind==="goal"?"协调者:":"负责人:",St?n(Je,St.assignee):Je.scheduledAssignee?n(Je,Je.scheduledAssignee):"未分派"]}),s.jsx(jf,{task:Je,now:v,compact:!0})]})]},be.id)}),!oe.length&&s.jsx("p",{className:"px-2 py-3 text-xs leading-6 text-muted-foreground/70",children:Z||U!=="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 Ih(e,t){return r=>Rl.getState().update(e,t,r)}function Tm(e,t){return r=>Rl.getState().updateDetail(e,t,r)}const wO=b.lazy(()=>Oc(()=>Promise.resolve().then(()=>cO),void 0).then(e=>({default:e.DirectoryPickerDialog}))),AO=b.lazy(()=>Oc(()=>import("./CollaborationTaskContent-DSkxOlKQ.js"),__vite__mapDeps([6,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17]))),oa="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",Qs="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=`${oa} bg-primary text-primary-foreground`,si=`${oa} bg-surface-2 text-foreground hover:bg-surface-2/80`,TO={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:"请求重新检查"},Bu=e=>`${e.serviceId}:${e.sessionId}`,Ta=e=>new Date(e).toLocaleString([],{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit"});function Qo(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 Oa(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch{}}const Kd={mode:"goal",isolated:!0,title:"",spec:"",constraints:"",acceptance:"",assignee:"",coordinator:"",parent:"",dependencies:[]};function SO(e){const t={...Kd,...Qo(e,Kd)};return!t||!Array.isArray(t.dependencies)||t.dependencies.some(r=>typeof r!="string")||Object.keys(Kd).some(r=>!["dependencies","isolated"].includes(r)&&typeof t[r]!="string")?Kd:{...t,mode:t.mode==="task"?"task":"goal",isolated:t.isolated!==!1}}function z6(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 CO({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),[W]=b.useState(()=>Rl.getState().ensure(v,{draft:SO(`${v}:draft`),selectedId:Qo(`${v}:selected`,null),creating:!1,mobileDetail:!1})),{selectedId:F,mobileDetail:U,creating:V,draft:Z}=Rl(ne=>ne.views[v]??W),ce=Ih(v,"selectedId"),xe=Ih(v,"mobileDetail"),pe=Ih(v,"creating"),te=Ih(v,"draft"),[ke,$e]=b.useState(!1),[Y,Ae]=b.useState(!1),lt=b.useRef(null),Se=b.useRef(null),ye=b.useRef(!1),_e=b.useCallback(ne=>{!ne&&Se.current===document.activeElement&&(ye.current=!0),Se.current=ne,ne&&ye.current&&(ye.current=!1,ne.focus())},[]);b.useEffect(()=>{const ne=lt.current;if(!ne)return;const ht=new ResizeObserver(Ht=>$e(Ht[0].contentRect.width>=(l?1100:760)));return ht.observe(ne),()=>ht.disconnect()},[l]);const[je,re]=b.useState(!1),[Oe,Ce]=b.useState(null),Ee=Sy(),[Be,Ne]=b.useState(0),[le,He]=b.useState(null),[rt,mt]=b.useState(!1),[ue,Ye]=b.useState(0),st=ne=>Ye(ht=>Math.max(0,ht+ne)),[Ie,We]=b.useState("");b.useEffect(()=>{if(!Ie)return;const ne=setTimeout(()=>We(""),5e3);return()=>clearTimeout(ne)},[Ie]);const[Te,H]=b.useState("open"),[oe,be]=b.useState(""),Ze=b.useRef(!1),Je=b.useRef(!0),St=b.useRef(new Map),Vt=b.useRef(!1),jt=e.sessionIds.flatMap(ne=>{const ht=t.find(Ht=>Ht.sessionId===ne);return ht?[ht]:[]}),vt=jt.map(ne=>({...ne,name:ku(ne,jt)})),Zt=Z.coordinator||Qo(`${v}:lead`,""),Pt=vt.find(ne=>ne.sessionId===Zt)?.sessionId||vt.find(ne=>ne.agent)?.sessionId||vt[0]?.sessionId||"",Xt=vt.filter(ne=>ne.sessionId!==Pt&&ne.agent).map(ne=>ne.sessionId),[zt,Lt]=b.useState(!1),[me,Ge]=b.useState(!1),[pt,q]=b.useState(()=>Qo(`${v}:agent`,x[0]?.slug??"")),[at,qt]=b.useState(()=>Qo(`${v}:launch-profile`,e.defaultLaunchProfileId??"")),Ve=e.launchProfiles?.find(ne=>ne.id===at),De=Ve?.agentSlug??pt,[er,et]=b.useState(()=>Qo(`${v}:cwd`,vt[0]?.cwd??y??""));b.useEffect(()=>{!pt&&x[0]&&q(x[0].slug)},[x,pt]);const Ct=!vt.find(ne=>ne.sessionId===Pt)?.agent||!Xt.length,[Nt,gt]=b.useState(null),bt=!!Z.spec.trim()&&(!!Nt||!Ct||!e.federated&&(!at||!!Ve)&&!!x.find(ne=>ne.slug===De)&&!!er.trim()),It=S.find(ne=>ne.id===F)??null,yt=R?.id===F?R:null;b.useEffect(()=>(Je.current=!0,()=>{Je.current=!1}),[]),b.useEffect(()=>{Oa(`${v}:draft`,Z)},[v,Z]),b.useEffect(()=>{Oa(`${v}:selected`,F)},[v,F]),b.useEffect(()=>{const ne=Ht=>{const Ot=Ht.detail;Ot?.groupId===e.id&&(Oa(`${v}:open-task`,null),ce(Ot.taskId),xe(!0),pe(!1),H("all"),pr())};window.addEventListener("open-collaboration-task",ne);const ht=Qo(`${v}:open-task`,null);return ht&&(ce(ht),xe(!0),H("all"),Oa(`${v}:open-task`,null)),()=>window.removeEventListener("open-collaboration-task",ne)},[e.id]),b.useEffect(()=>{if(!r||!It||R?.id===It.id&&R.revision===It.revision)return;let ne=!1;return jw(It.id).then(ht=>{ne||(B(ht.task),Ce(null))}).catch(ht=>{ne||Ce(ht instanceof Error?ht.message:"任务详情加载失败")}),()=>{ne=!0}},[r,It?.id,It?.revision,R?.id,R?.revision,Be]);const pr=async()=>{if(!Vt.current){Vt.current=!0;try{const ne=await vy(e.id);Je.current&&(L(ne.tasks),re(!0),Ce(null),Ne(ht=>ht+1))}catch(ne){Je.current&&Ce(ne instanceof Error?ne.message:"任务加载失败")}finally{Vt.current=!1}}};b.useEffect(()=>{if(!r)return;pr();const ne=()=>{!document.hidden&&navigator.onLine!==!1&&pr()},ht=setInterval(ne,2500);return document.addEventListener("visibilitychange",ne),window.addEventListener(nf,ne),window.addEventListener("pageshow",ne),()=>{clearInterval(ht),document.removeEventListener("visibilitychange",ne),window.removeEventListener(nf,ne),window.removeEventListener("pageshow",ne)}},[r,e.id]);const nr=ne=>{const ht=JSON.stringify(ne),Ht=Qo(`${v}:request`,null);let Ot=St.current.get(ht)??(Ht?.fingerprint===ht?Ht.key:void 0);return Ot||(Ot=crypto.randomUUID(),St.current.set(ht,Ot)),Oa(`${v}:request`,{fingerprint:ht,key:Ot}),Ot},Cr=ne=>{St.current.delete(JSON.stringify(ne)),Oa(`${v}:request`,null)},cn=async(ne,ht)=>{if(rt||Ze.current)return{ok:!1,error:"已有操作正在提交,请稍候。"};Ze.current=!0,mt(!0),He(null),We("");let Ht={...ht,expectedRevision:ne.revision};if(["comment","revise"].includes(ht.kind)){const Ot=Qo(`${v}:request`,null);try{const[Tr,mr]=JSON.parse(Ot?.fingerprint??"null"),{expectedRevision:Hr,..._n}=mr;Tr===ne.id&&JSON.stringify(_n)===JSON.stringify(ht)&&(Ht=mr)}catch{}}try{const Ot=await Qw(ne.id,{...Ht,idempotencyKey:nr([ne.id,Ht])});if(Cr([ne.id,Ht]),_u.getState().refresh(),Je.current){const Tr=E.current.find(dr=>dr.id===Ot.task.id),mr=Tr&&Tr.revision>Ot.task.revision?Tr:Ot.task;L(dr=>dr.map(bn=>bn.id===Ot.task.id&&bn.revision<=Ot.task.revision?Ot.task:bn)),B(dr=>dr?.id===Ot.task.id&&dr.revision>Ot.task.revision?dr:Ot.task);const Hr=z6(mr,E.current),_n=`${ht.kind==="answer"?"回答已保存":"方案确认已保存"},${Hr?Hr.workflow?.kind==="goal"?"目标仍暂停;恢复目标后才能投递。":"任务仍暂停;继续安排后才能投递。":"投递状态请查看任务记录。"}`;We(["comment","revise"].includes(ht.kind)?"":ht.kind==="retry"?xO(ne,Ot.task):["answer","approve-plan"].includes(ht.kind)?_n:ht.kind==="accept"?"已验收此版本结果。":"记录已保存。")}return{ok:!0}}catch(Ot){const Tr=Ot instanceof Error?Ot.message:"操作失败";return Tr.includes("任务已更新")&&Cr([ne.id,Ht]),Je.current&&(He(["comment","revise"].includes(ht.kind)?null:Tr),pr()),{ok:!1,error:Tr}}finally{Ze.current=!1,Je.current&&mt(!1)}},Lr=async ne=>{if(ne.preventDefault(),rt||ue>0||(Z.mode==="goal"?!bt:!Z.title.trim()||!Z.spec.trim())||Ze.current)return;Ze.current=!0,mt(!0),He(null);const ht=Z.mode==="goal",Ht={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:ht?void 0:Z.assignee||void 0,coordinatorSessionId:ht?Pt:Z.coordinator||void 0,parentTaskId:ht?void 0:Z.parent||void 0,dependsOn:ht?[]:Z.dependencies,managed:ht,isolated:Z.isolated,reviewerSessionIds:ht?Xt:void 0};try{if(ht&&(Ct||Nt)){Ge(!0);const Tr=Nt??await Dw(e.id,{agentSlug:De,...at?{launchProfileId:at}:e.launchProfiles?.length?{launchProfileId:""}:{},cwd:er.trim()});Ge(!1),gt(Tr),Ht.coordinatorSessionId=Tr.coordinatorSessionId,Ht.reviewerSessionIds=Tr.reviewerSessionIds,Oa(`${v}:agent`,pt),Oa(`${v}:cwd`,er.trim()),Oa(`${v}:launch-profile`,at)}const{task:Ot}=await Bw({...Ht,idempotencyKey:nr(Ht)});Cr(Ht),Je.current&&(L(Tr=>[Ot,...Tr.filter(mr=>mr.id!==Ot.id)]),ce(Ot.id),xe(!0),B(Ot),ht&&Oa(`${v}:lead`,Ht.coordinatorSessionId),gt(null),w?.(),te(Kd),pe(!1),H("open"),be(""),We(ht?"目标已提交,协调者收到后开始拆分与分派。后续评审和依赖由服务接续。":"任务已保存。分派后由服务端持续投递。"))}catch(Ot){Je.current&&He(Ot instanceof Error?Ot.message:"创建失败")}finally{Ze.current=!1,Je.current&&(mt(!1),Ge(!1))}},ge=(ne,ht)=>{if(!ht)return"用户";const Ht=ne.memberSessions[Bu(ht)];return vt.find(Ot=>Ot.sessionId===Ht)?.name??t.find(Ot=>Ot.sessionId===Ht)?.name??"暂不可用的成员"},Vr=S.filter(ne=>(Te==="all"?!0:Te==="archive"?ne.status!=="open":ne.status==="open")&&(Te==="all"||Te==="attention"||ne.workflow?.kind!=="step")&&(Te!=="attention"||Fi(ne))&&(!oe.trim()||`${ne.title} ${ne.spec} ${ne.attempts.map(ht=>ge(ne,ht.assignee)).join(" ")}`.toLowerCase().includes(oe.trim().toLowerCase()))),it=S.filter(Fi).length;b.useEffect(()=>{a?.(it)},[it,a]);const dt=!!It&&(l?U:ke||U),sr=()=>{pe(!1),requestAnimationFrame(()=>Se.current?.focus())},xn=ne=>{Rl.getState().updateDetail(`${v}:${ne}`,"view","overview"),ce(ne),xe(!0),We("")},an=S.filter(Fi).filter(ne=>!oe.trim()||`${ne.title} ${ne.spec} ${ne.attempts.map(ht=>ge(ne,ht.assignee)).join(" ")}`.toLowerCase().includes(oe.trim().toLowerCase())),Me=(ne,ht=!1)=>{const Ht=ne.attempts.find(dr=>dr.id===ne.activeAttemptId),Ot=ne.children?.filter(dr=>dr.status==="accepted").length??0,Tr=ne.children?.filter(dr=>dr.status!=="closed").length??0,mr=Xf(ne),Hr=mr.length>1?mr.find(dr=>dr.source!=="member"):null,_n=(ht?ne.decisions.find(dr=>dr.status==="pending")?.question:"")||mr[0]?.summary||Ht?.report?.summary||Ht?.report?.content;return s.jsxs("button",{type:"button","aria-pressed":F===ne.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 ${F===ne.id?"bg-surface-2":"hover:bg-surface-2/70"}`,onClick:()=>xn(ne.id),children:[s.jsx("span",{className:`mt-0.5 shrink-0 ${ht||ne.status==="accepted"?"text-primary":"text-muted-foreground"}`,children:ht?s.jsx(N0,{size:16}):ne.status==="accepted"?s.jsx(Fu,{size:16}):s.jsx($u,{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:ne.title}),s.jsx("span",{className:`mt-1 block text-xs leading-5 ${ht?"text-primary":"text-muted-foreground"}`,children:Yc(ne)}),_n&&s.jsx("span",{className:"mt-1 block line-clamp-2 break-words text-xs leading-5 text-muted-foreground",children:_n}),Hr&&s.jsxs("span",{className:`mt-1 block line-clamp-2 break-words text-xs leading-5 ${Hr.source==="system"?"text-destructive":"text-muted-foreground"}`,children:[Hr.label,":",Hr.summary]}),Tr>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:(ne.children??[]).filter(dr=>dr.status!=="closed").slice(0,8).map(dr=>s.jsx("span",{className:`h-1.5 w-3 rounded-full ${dr.status==="accepted"?"bg-primary":"bg-border/30"}`},dr.id))}),Ot,"/",Tr," 子任务已验收"]}),s.jsxs("span",{className:"mt-2 block text-[11px] text-muted-foreground",children:[s.jsx("span",{className:"block truncate",children:Ht?ge(ne,Ht.assignee):"尚未分派"}),s.jsx(jf,{task:ne})]})]}),s.jsx(fi,{size:14,className:"mt-1 shrink-0 text-muted-foreground/60"})]},ne.id)},nt=[],wt=new Set([F]);let Rr=It?.parentTaskId;for(;Rr&&!wt.has(Rr);){wt.add(Rr);const ne=S.find(ht=>ht.id===Rr);if(!ne)break;nt.unshift(ne),Rr=ne.parentTaskId}const rn=()=>{const ne=Array.from(lt.current?.querySelectorAll("button[data-task-id]")??[]).find(ht=>ht.dataset.taskId===F);xe(!1),requestAnimationFrame(()=>{ne&&!ne.closest("[hidden]")?ne.focus():Se.current?.focus()})},Ir=V||!l&&je&&S.length===0;return s.jsxs("section",{ref:lt,"aria-label":"协作任务",className:l?"relative flex h-full min-h-0 min-w-0 flex-col gap-2":"space-y-5",children:[l&&(Ir||!je)&&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})]}),(le||Oe&&Ee==="ready"&&!sf(Oe))&&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:[le||Oe,!le&&je?" · 显示最近保存的记录":""]}),s.jsxs("button",{type:"button",className:oa,onClick:()=>le?He(null):void pr(),children:[s.jsx(gn,{size:14}),le?"关闭提示":"重试"]})]}),Oe&&sf(Oe)&&!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}),Ir?s.jsxs("form",{onSubmit:ne=>{Lr(ne)},className:`mx-auto w-full max-w-xl space-y-4 ${l?"overflow-auto px-1 py-5":""}`,onKeyDown:ne=>{ne.key==="Escape"&&V&&!ne.defaultPrevented&&!ne.nativeEvent.isComposing&&M1(ne.currentTarget)&&(ne.preventDefault(),ne.stopPropagation(),rt||sr())},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:`${oa} shrink-0 px-2 text-muted-foreground hover:bg-surface-2`,disabled:rt,onClick:sr,children:s.jsx(Rn,{size:16})})]}),Z.mode==="task"&&s.jsx(Do,{label:"任务标题",children:s.jsx("input",{className:Qs,required:!0,maxLength:200,value:Z.title,onChange:ne=>te(ht=>({...ht,title:ne.target.value})),placeholder:"要完成什么?"})}),s.jsx(Xh,{paneKey:m,inputKey:`${v}:spec`,active:r&&Ir,label:Z.mode==="goal"?"协作目标":"目标与交付要求",className:`${Qs} ${Ct&&Z.mode==="goal"?"min-h-24":"min-h-32"} resize-y text-sm leading-6`,autoFocus:V,required:!0,disabled:rt,value:Z.spec,onUploadChange:st,onChange:ne=>te(ht=>({...ht,spec:typeof ne=="function"?ne(ht.spec):ne})),placeholder:"例如:完善附件预览体验,交付实现和评审结果,保留现有快捷键。"}),Z.mode==="goal"&&Nt&&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:si,disabled:rt,onClick:()=>{w?.(),c()},children:"查看已准备的成员"})]}),Z.mode==="goal"&&(Ct||Nt)?s.jsxs("fieldset",{disabled:rt||!!Nt,className:"space-y-3",children:[s.jsx("legend",{className:"mb-2 text-xs text-muted-foreground",children:Nt?"已用于准备成员的配置":"首次开始时配置 Agent"}),(!!e.launchProfiles?.length||!!at)&&s.jsxs(Do,{label:"启动方案",children:[s.jsxs("select",{"aria-label":"协作启动方案",className:Qs,value:at,onChange:ne=>qt(ne.target.value),children:[s.jsx("option",{value:"",children:"Agent 默认命令"}),e.launchProfiles?.map(ne=>s.jsxs("option",{value:ne.id,children:[ne.name," · ",x.find(ht=>ht.slug===ne.agentSlug)?.displayName??ne.agentSlug]},ne.id))]}),Ve&&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:Ve.notes||"查看启动命令与使用备注"})}),s.jsx("p",{"aria-label":"完整使用备注",className:"whitespace-pre-wrap break-words",children:Ve.notes}),s.jsx("code",{className:"mt-1 block break-all",children:Ve.command})]}),at&&!Ve&&s.jsx("p",{role:"alert",className:"text-xs text-destructive",children:"原方案已删除,请重新选择。"})]}),!Ve&&s.jsx(Do,{label:"Agent",children:s.jsxs("select",{"aria-label":"协作 Agent",className:Qs,disabled:!!Ve,value:De,onChange:ne=>q(ne.target.value),children:[s.jsx("option",{value:"",disabled:!0,children:"选择已安装的 Agent"}),x.map(ne=>s.jsx("option",{value:ne.slug,children:ne.displayName},ne.slug))]})}),s.jsxs(Do,{label:"工作目录",children:[s.jsxs("div",{className:"flex gap-2",children:[s.jsx("input",{"aria-label":"工作目录",className:`${Qs} min-w-0 flex-1`,value:er,onChange:ne=>et(ne.target.value),placeholder:"选择项目所在的目录"}),s.jsx("button",{type:"button",className:si,onClick:()=>Lt(!0),children:"浏览目录"})]}),zt&&s.jsx(b.Suspense,{fallback:s.jsx("p",{className:"text-xs",children:"正在打开目录…"}),children:s.jsx(wO,{open:!0,initialPath:er.trim()||y||"/",title:"选择协作项目目录",onCancel:()=>Lt(!1),onConfirm:ne=>{et(ne),Lt(!1)}})})]}),!Nt&&s.jsx("p",{className:"text-xs leading-5 text-muted-foreground",children:"开始时配置协调者与执行/评审成员,后续目标复用。"}),e.federated&&s.jsxs("p",{role:"alert",className:"text-xs text-muted-foreground",children:["跨服务组请从成员设置添加 Agent。",c&&s.jsx("button",{type:"button",className:si,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:si,onClick:c,children:"管理成员"})]})]}):Z.mode==="goal"?s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"shrink-0 text-xs text-muted-foreground",children:"协调者"}),s.jsx("select",{"aria-label":"协调者",className:`${Qs} min-w-0 flex-1`,value:Pt,onChange:ne=>te(ht=>({...ht,coordinator:ne.target.value})),children:vt.map(ne=>s.jsxs("option",{value:ne.sessionId,disabled:!ne.agent,children:[ne.name,ne.agent?"":"(需要启动 Agent)"]},ne.sessionId))})]}):s.jsx(Do,{label:"分派给",children:s.jsxs("select",{className:Qs,value:Z.assignee,onChange:ne=>te(ht=>({...ht,assignee:ne.target.value})),children:[s.jsx("option",{value:"",children:"先保存,稍后分派"}),vt.map(ne=>s.jsx("option",{value:ne.sessionId,children:ne.name},ne.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(Do,{label:"验收标准(选填)",children:s.jsx("textarea",{className:`${Qs} min-h-20 resize-y`,value:Z.acceptance,onChange:ne=>te(ht=>({...ht,acceptance:ne.target.value})),placeholder:"什么结果满足要求?"})}),s.jsx(Do,{label:"约束(选填)",children:s.jsx("textarea",{className:`${Qs} min-h-20 resize-y`,value:Z.constraints,onChange:ne=>te(ht=>({...ht,constraints:ne.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:ne=>te(ht=>({...ht,isolated:ne.target.checked}))}),s.jsxs("span",{children:["代码任务使用独立目录",s.jsx("br",{}),s.jsx("span",{className:"text-[11px]",children:"协调者自动区分查询与代码任务;查询复用成员会话,只有代码需要目录与集成。"})]})]}):s.jsxs(s.Fragment,{children:[s.jsx(Do,{label:"协调者",children:s.jsxs("select",{className:Qs,value:Z.coordinator,onChange:ne=>te(ht=>({...ht,coordinator:ne.target.value})),children:[s.jsx("option",{value:"",children:"由用户协调"}),vt.map(ne=>s.jsx("option",{value:ne.sessionId,children:ne.name},ne.sessionId))]})}),s.jsx(Do,{label:"父任务",children:s.jsxs("select",{className:Qs,value:Z.parent,onChange:ne=>te(ht=>({...ht,parent:ne.target.value})),children:[s.jsx("option",{value:"",children:"独立任务"}),S.filter(ne=>!ne.workflow).map(ne=>s.jsx("option",{value:ne.id,children:ne.title},ne.id))]})}),s.jsxs("fieldset",{className:"space-y-1",children:[s.jsx("legend",{className:"text-xs text-muted-foreground",children:"需先验收的依赖任务"}),S.filter(ne=>ne.status!=="closed").map(ne=>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(ne.id),onChange:ht=>te(Ht=>({...Ht,dependencies:ht.target.checked?[...Ht.dependencies,ne.id]:Ht.dependencies.filter(Ot=>Ot!==ne.id)}))}),ne.title]},ne.id))]})]}),s.jsx("button",{type:"button",className:`${oa} text-muted-foreground hover:bg-surface-2`,onClick:()=>te(ne=>({...ne,mode:ne.mode==="goal"?"task":"goal"})),children:Z.mode==="goal"?"改为手动分派任务":"改为自动协作目标"})]})]}),s.jsxs("button",{className:`${cl} w-full`,disabled:rt||ue>0||(Z.mode==="goal"?!bt:!Z.title.trim()||!Z.spec.trim()),children:[rt?s.jsx(gn,{size:14,className:"animate-spin"}):s.jsx(r0,{size:14}),rt?me?"正在准备成员…":"提交中…":Z.mode==="goal"?Nt?"重试提交目标":"开始协作":Z.assignee?"创建并分派":"保存任务"]}),s.jsx("p",{className:"text-center text-[11px] leading-5 text-muted-foreground",children:Z.mode==="goal"?"拆分任务 → 执行与独立评审 → 你验收结果":"草稿自动保存,分派后保留投递与回复记录。"})]}):l&&je?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:dt,className:`${dt?"hidden":"flex"} min-h-0 min-w-0 flex-1`,children:s.jsx(vO,{navigation:d,settings:p,action:s.jsxs("button",{ref:_e,type:"button",className:cl,disabled:rt,onClick:()=>pe(!0),children:[s.jsx(Us,{size:14}),"新目标"]}),storage:v,tasks:S,selectedId:dt?F:null,name:ge,onSelect:xn})}),dt&&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:`${oa} px-2 hover:bg-surface-2`,onClick:rn,children:"看板"})}),nt.map(ne=>s.jsxs("li",{className:"flex min-w-0 flex-1 items-center gap-1 sm:max-w-xs sm:flex-none",children:[s.jsx(fi,{"aria-hidden":"true",size:12,className:"shrink-0"}),s.jsx("button",{type:"button","aria-label":`查看${ne.workflow?.kind==="goal"?"目标":"父任务"}:${ne.title}`,title:`查看${ne.workflow?.kind==="goal"?"目标":"父任务"}:${ne.title}`,className:`${oa} min-w-0 px-2 hover:bg-surface-2`,onClick:()=>xn(ne.id),children:s.jsxs("span",{className:"truncate",children:[ne.workflow?.kind==="goal"?"目标":"父任务",":",ne.title]})})]},ne.id)),s.jsxs("li",{"aria-current":"page",className:"flex shrink-0 items-center gap-1",children:[s.jsx(fi,{"aria-hidden":"true",size:12}),s.jsx("span",{className:"px-2",children:It?.parentTaskId?"子任务详情":It?.workflow?.kind==="goal"?"目标详情":"任务详情"})]})]})}),s.jsx("div",{className:"min-h-0 flex-1",children:yt?s.jsx(Sb,{reader:!0,paneKey:m,active:r,task:yt,tasks:S,members:vt,busy:rt,name:ne=>ge(yt,ne),act:ne=>cn(yt,ne),storage:v,onSelectTask:xn,onOpenSession:async ne=>{const ht=t.find(Ht=>Ht.sessionId===yt.memberSessions[Bu(ne)]);if(!ht){He("成员会话暂不可用,任务历史已保留。");return}try{await n(ht)}catch(Ht){He(Ht instanceof Error?Ht.message:"无法打开终端")}}},yt.id):s.jsx("p",{role:"status",className:"py-8 text-center text-xs text-muted-foreground",children:"正在加载任务详情…"})})]})]})]}):!je&&!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:Oe?"任务暂时无法加载,请重试。":"正在加载目标…"}),!Oe&&[0,1,2].map(ne=>s.jsx("div",{className:"h-14 animate-pulse rounded-lg bg-surface-2"},ne))]}):s.jsxs(s.Fragment,{children:[(!dt||ke)&&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(ne=>ne.status==="open"&&ne.workflow?.kind!=="step").length," 个进行中 · ",S.filter(ne=>ne.status==="accepted"&&ne.workflow?.kind!=="step").length," 个已验收"]})]}),s.jsxs("button",{ref:_e,type:"button",className:cl,disabled:rt,onClick:()=>pe(!0),children:[s.jsx(Us,{size:14}),"新目标"]})]}),s.jsxs("div",{className:ke&&dt?"grid items-start gap-6 grid-cols-[260px_minmax(0,1fr)]":"",children:[(!dt||ke)&&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:`${Qs} min-w-0 flex-1 border-transparent bg-transparent`,value:Te,onChange:ne=>H(ne.target.value),children:[s.jsx("option",{value:"open",children:"进行中的目标"}),s.jsxs("option",{value:"attention",children:["需要你处理(",it,")"]}),s.jsx("option",{value:"archive",children:"已归档"}),s.jsx("option",{value:"all",children:"全部任务"})]}),s.jsx("button",{type:"button","aria-label":"搜索任务","aria-expanded":Y,className:`${oa} shrink-0 px-3 text-muted-foreground hover:bg-surface-2`,onClick:()=>{Ae(ne=>!ne),be("")},children:s.jsx(Ml,{size:16})})]}),Y&&s.jsx("input",{"aria-label":"搜索任务或负责人",autoFocus:!0,className:Qs,value:oe,onChange:ne=>be(ne.target.value),placeholder:"搜索目标、内容或负责人"}),Te==="open"&&an.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:an.length})]}),an.map(ne=>Me(ne,!0))]}),(Te!=="open"||Vr.some(ne=>!Fi(ne))||Vr.length===0)&&s.jsxs("section",{className:"space-y-1",children:[s.jsx("h4",{className:"px-3 text-[11px] font-medium text-muted-foreground",children:Te==="attention"?"需要你处理":Te==="archive"?"已归档":Te==="all"?"全部任务":"当前目标"}),Vr.filter(ne=>Te!=="open"||!Fi(ne)).map(ne=>Me(ne,Te==="attention")),!Vr.length&&s.jsxs("div",{className:"px-3 py-6 text-center text-xs leading-5 text-muted-foreground",children:[oe.trim()?"没有匹配的任务。":Te==="attention"?"目前没有需要你处理的任务。":Te==="archive"?"还没有归档任务。":"当前没有进行中的目标。",(Te!=="all"||oe)&&s.jsx("button",{type:"button",className:`${oa} mt-2 text-primary`,onClick:()=>{H("all"),be("")},children:"查看全部任务"})]})]})]}),dt&&s.jsxs("div",{className:"min-w-0",children:[!ke&&s.jsxs("button",{type:"button",className:`${oa} mb-4 -ml-2 text-muted-foreground hover:bg-surface-2`,onClick:()=>xe(!1),children:[s.jsx(Cy,{size:14}),"全部目标"]}),yt?s.jsx(Sb,{paneKey:m,active:r,task:yt,tasks:S,members:vt,busy:rt,name:ne=>ge(yt,ne),act:ne=>cn(yt,ne),storage:v,onSelectTask:xn,onOpenSession:async ne=>{const ht=t.find(Ht=>Ht.sessionId===yt.memberSessions[Bu(ne)]);if(!ht){He("成员会话暂不可用,任务历史已保留。");return}try{await n(ht)}catch(Ht){He(Ht instanceof Error?Ht.message:"无法打开终端")}}},yt.id):s.jsx("p",{role:"status",className:"py-8 text-center text-xs text-muted-foreground",children:"正在加载任务详情…"})]})]})]})]})}function Do({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 Sb({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,W]=b.useState(!1),[F,U]=b.useState(null),V=b.useRef(!1),Z=b.useRef(!0);b.useEffect(()=>(Z.current=!0,()=>{Z.current=!1}),[]);const ce=b.useRef(null),xe=b.useRef(null);b.useEffect(()=>{!e&&F&&F.state!=="pending"&&t&&requestAnimationFrame(()=>xe.current?.scrollIntoView({block:"nearest"}))},[F]);const pe=b.useRef(null),[te,ke]=b.useState(0),$e=q=>ke(at=>Math.max(0,at+q)),Y=b.useRef(null);b.useEffect(()=>{Y.current?.focus()},[]);const Ae=`${m}:${n.id}`,[lt]=b.useState(()=>Rl.getState().ensureDetail(Ae,{feedback:Qo(`${Ae}:feedback`,""),answers:Qo(`${Ae}:answers`,{}),view:"overview"})),{feedback:Se,answers:ye,view:_e}=Rl(q=>q.details[Ae]??lt),je=Tm(Ae,"feedback"),re=Tm(Ae,"answers"),Oe=Tm(Ae,"view");b.useEffect(()=>{pe.current&&(pe.current.scrollTop=0)},[_e]),b.useEffect(()=>Oa(`${m}:${n.id}:answers`,ye),[m,n.id,ye]),b.useEffect(()=>Oa(`${m}:${n.id}:feedback`,Se),[m,n.id,Se]);const Ce=n.attempts.find(q=>q.id===n.activeAttemptId),Ee=n.status==="open",Be=z6(n,a),Ne=n.artifacts.filter(q=>q.kind==="result"&&q.attemptId===n.activeAttemptId).at(-1);b.useEffect(()=>{F?.state==="saved"&&Ne?.id!==F.resultId&&U(null)},[Ne?.id,F]);const le=n.artifacts.filter(q=>q.kind==="plan"&&q.attemptId===n.activeAttemptId).at(-1),He=n.events.filter(q=>q.kind==="revise"&&q.source==="user"&&q.attemptId===n.activeAttemptId).at(-1),rt=Ne&&n.events.some(q=>q.kind==="revise"&&q.attemptId===n.activeAttemptId&&q.createdAt>=Ne.createdAt),mt=e&&Ee&&!!rt,ue=F?.state==="saved"&&F.kind==="revise"&&F.resultId===Ne?.id,Ye=n.decisions.filter(q=>q.status==="pending"&&q.attemptId===n.activeAttemptId),st=n.dependsOn.some(q=>a.find(at=>at.id===q)?.status!=="accepted"),Ie=!n.workflow||n.artifacts.filter(q=>q.kind==="review"&&q.reviewsArtifactId===Ne?.id).at(-1)?.verdict==="pass",We=n.children??[],Te=n.workflow?.kind==="goal"&&We.some(q=>!["accepted","closed"].includes(q.status)),H=`任务:${n.title}
|
|
141
141
|
任务 ID:${n.id}
|
|
142
142
|
${n.spec}
|
|
@@ -159,7 +159,7 @@ ${Ye.map(q=>`待回答:${q.question}`).join(`
|
|
|
159
159
|
`))},Vr,ge)},[w,e,n,y,dt?.id,ge,Vr,Y,vt]),b.useEffect(()=>{const K=Lr.current;if(!w||!K)return;const Ue=Et=>pe(String(Et.detail));return K.addEventListener("termdock:file-drop-error",Ue),()=>K.removeEventListener("termdock:file-drop-error",Ue)},[w,dt?.id,pe]);const Ot=async K=>{const Ue=dt?.id;pe(null),an(Et=>Et+1);try{const Et=await L0("/tmp",K);if(Et.files.length!==K.length||Et.files.some(tr=>!tr.path))throw new Error("文件路径准备失败,请重试");const kt=Et.files.map(tr=>Dc(tr.path)).join(" ")+" ";if(wt.current===Ue)St(tr=>tr+(tr&&!/\s$/.test(tr)?`
|
|
160
160
|
`:"")+kt);else if(Ue){const tr=Me.current.get(Ue)??{content:"",targets:null},Qr={...tr,content:tr.content+`
|
|
161
161
|
`+kt};Me.current.set(Ue,Qr),Ht({drafts:{[Ue]:Qr}})}}catch(Et){pe(Et instanceof Error?Et.message:"文件上传失败")}finally{an(Et=>Et-1)}},Tr=new Set(L.filter(Sm).map(K=>K.sessionId)),mr=Oe.size,Hr=[...Oe].filter(K=>!Tr.has(K)),_n=QO(dt,L),dr=Ee.trim().toLocaleLowerCase(),bn=L.filter(K=>!dr||[ku(K,L),K.name,K.serviceLabel??"",K.cwd,_m(K.currentTask)].some(Ue=>Ue.toLocaleLowerCase().includes(dr))),hn=Lb(bn),Tn=Lb(_n),ir=K=>!dr&&Ne.has(K),pn=K=>le(Ue=>{const Et=new Set(Ue);return Et.has(K)?Et.delete(K):Et.add(K),Et});b.useEffect(()=>{jt(!1),zt.current!==dt?.id&&Zt(!1),zt.current=null,Se(!1),et(!1),rt(!1),De({}),q(new Set(dt?.sessionIds??[])),bt(dt?.defaultLaunchProfileId??"")},[dt?.id]),b.useEffect(()=>{!Ct&&E[0]&&Nt(E[0].slug)},[E,Ct]),b.useEffect(()=>{st([]),H(null)},[dt?.id]),b.useEffect(()=>{if(!B||!n||w&&!y||!dt){We(!1);return}We(!0);let K=!1,Ue=0,Et=!1;const kt=()=>{if(K||Et||document.hidden||navigator.onLine===!1)return;Et=!0;const Qr=++Ue;i2(dt.id).then(cr=>{!K&&Qr===Ue&&(st(cr.messages),H(null))}).catch(cr=>{!K&&Qr===Ue&&H(cr instanceof Error?cr.message:"消息加载失败")}).finally(()=>{Et=!1,!K&&Qr===Ue&&We(!1)})};kt();const tr=window.setInterval(kt,3e3);return document.addEventListener("visibilitychange",kt),window.addEventListener(nf,kt),window.addEventListener("pageshow",kt),()=>{K=!0,window.clearInterval(tr),document.removeEventListener("visibilitychange",kt),window.removeEventListener(nf,kt),window.removeEventListener("pageshow",kt)}},[dt?.id,n,w,y]),b.useEffect(()=>{!B||dt?.id!==B||it.current||(it.current=!0,Y==="messages"&&Lr.current?.scrollIntoView?.({block:"nearest"}))},[B,dt?.id]);const Pr=async()=>{xe("create-group"),pe(null),te(null);try{if(Hr.length)throw new Error("所选会话已变化,请先清除不可用选择");const K=await ac({name:je,sessionIds:[...Oe]});re(""),Be(""),x(K.group.id),await ke(),te(`“${K.group.name}”已创建。`),r?await r(K.group.id,"messages"):U&&await U(K.group.id)}catch(K){pe(K instanceof Error?K.message:"创建失败")}finally{xe(null)}},qr=dt?.sessionIds.filter(K=>be===null||be.includes(K))??[],Wr=async()=>{if(!dt||ce||xn||!Je.trim()||!qr.length)return;const K=Je,Ue=dt.id;xe("send-message"),pe(null),te(null);try{const Et=await Pw(dt.id,{fromSessionId:null,toSessionIds:be===null?void 0:qr,kind:"message",content:Je});if(wt.current===Ue){const cr=Ir.current,Sn=cr===K?"":cr.startsWith(K)?cr.slice(K.length).replace(/^\n/,""):cr;St(Sn),Ht({drafts:{[Ue]:{content:Sn,targets:rn.current}}})}else{const cr=Me.current.get(Ue);if(cr){const Sn={...cr,content:cr.content===K?"":cr.content.startsWith(K)?cr.content.slice(K.length).replace(/^\n/,""):cr.content};Me.current.set(Ue,Sn),Ht({drafts:{[Ue]:Sn}})}}const kt=await i2(Ue).catch(()=>null);kt&&wt.current===Ue&&st(kt.messages);const tr=Et.deliveries?.filter(cr=>cr.serviceUnavailable).length??0,Qr=Et.deliveries?.filter(cr=>cr.pending>0).length??0;te(tr>0?`已保存消息;${tr} 个接收成员的服务不可达,尚未送达,等待重连`:Qr>0?`已保存消息;${Qr} 个成员等待投递确认`:`消息已送达 ${Et.messages.length} 个会话`)}catch(Et){pe(Et instanceof Error?Et.message:"发送失败")}finally{xe(null)}},fs=async()=>{if(!dt)return;xe(`delete:${dt.id}`),pe(null),te(null);const K=dt.name;try{await Ow(dt.id,mt),x(null),rt(!1),await ke(),te(`“${K}”已删除`)}catch(Ue){pe(Ue instanceof Error?Ue.message:"删除失败")}finally{xe(null)}},Br=async()=>{if(!dt)return;const K=[...pt];xe("save-members"),pe(null),te(null);try{const Ue=await ac({id:dt.id,name:dt.name,sessionIds:K,expectedUpdatedAt:at});x(Ue.group.id),jt(!1),await ke(),te(`“${dt.name}”成员已更新,共 ${K.length} 个会话`)}catch(Ue){pe(Ue instanceof Error?Ue.message:"成员更新失败")}finally{xe(null)}},Mn=async K=>{if(!dt||!dt.sessionIds.includes(K)){Ge(null);return}const Ue=L.find(kt=>kt.sessionId===K)?.name??K,Et=dt.name;xe(`remove-member:${K}`),pe(null),te(null);try{await ac({id:dt.id,name:Et,sessionIds:dt.sessionIds.filter(kt=>kt!==K),expectedUpdatedAt:dt.updatedAt}),Ge(null),q(kt=>new Set([...kt].filter(tr=>tr!==K))),De(kt=>Object.fromEntries(Object.entries(kt).filter(([tr])=>tr!==K))),await ke(),te(`已把“${Ue}”移出“${Et}”`)}catch(kt){pe(kt instanceof Error?kt.message:"移出成员失败")}finally{xe(null)}},Sr=async K=>{if(!dt)return;const Ue=Ve[K]??"";xe(`role:${K}`),pe(null),te(null);try{await zw(dt.id,K,Ue.trim()||null),await ke(),te(Ue.trim()?"定位已保存,该成员每次收到消息都会看到":"定位已清除")}catch(Et){pe(Et instanceof Error?Et.message:"定位保存失败")}finally{xe(null)}},Kr=()=>{bt(dt?.defaultLaunchProfileId??"");const K=L.find(Ue=>Ue.sessionId===R)?.cwd??L.find(Ue=>dt?.sessionIds.includes(Ue.sessionId))?.cwd??"";nr(K),yt(""),cn(""),et(!0),jt(!1)},nn=async()=>{if(!(!dt||!Ct||gt&&!dt.launchProfiles?.some(K=>K.id===gt))){xe("spawn-agent"),pe(null),te(null);try{const K=await Fw(dt.id,{agentSlug:dt.launchProfiles?.find(Ue=>Ue.id===gt)?.agentSlug??Ct,...gt||dt.launchProfiles?.length?{launchProfileId:gt}:{},name:It.trim()||void 0,cwd:pr.trim()||void 0,task:Cr.trim()||void 0,mode:Z});et(!1),await ke(),te(`“${K.session.name}”已创建并加入“${K.group.name}”`)}catch(K){pe(K instanceof Error?K.message:"Agent Session 创建失败")}finally{xe(null)}}},Fr=UO(Ye,L),ks=K=>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:!Sm(K),checked:Oe.has(K.sessionId),onChange:()=>Ce(Ue=>{const Et=new Set(Ue);return Et.has(K.sessionId)?Et.delete(K.sessionId):Et.add(K.sessionId),Et})}),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:ku(K,L)}),s.jsx(Cm,{session:K}),s.jsx("span",{className:"shrink-0 text-[9px] text-muted-foreground",children:tf(K)})]}),s.jsx("span",{className:"mt-0.5 block truncate text-[10px] text-muted-foreground",children:K.currentTask?`${_m(K.currentTask)} · ${K.cwd}`:K.cwd||K.capability||"终端会话"})]})]},K.sessionId),Or=K=>{const Ue=Ve[K.sessionId]??"",Et=dt?.roles?.[K.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:!dt?.sessionIds.includes(K.sessionId)&&!Sm(K),checked:pt.has(K.sessionId),onChange:()=>q(kt=>{const tr=new Set(kt);return tr.has(K.sessionId)?tr.delete(K.sessionId):tr.add(K.sessionId),tr})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block truncate text-[11px] text-foreground",children:K.name}),s.jsx(Cm,{session:K}),s.jsxs("span",{className:"block truncate text-[9px] text-muted-foreground",children:[tf(K)," · ",K.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":`${K.name} 的定位`,className:`${Fs} min-h-8 py-1 text-[10px]`,value:Ue,maxLength:200,placeholder:"成员收到的定位;清空后保存可移除",onChange:kt=>De(tr=>({...tr,[K.sessionId]:kt.target.value}))}),s.jsx("button",{"aria-label":`保存 ${K.name} 的定位`,title:Ue.trim()===Et?"定位未变化":"保存此成员的定位",disabled:ce!==null||Ue.trim()===Et,className:`${wr} min-h-8 shrink-0 px-2 text-muted-foreground`,onClick:()=>{Sr(K.sessionId)},children:ce===`role:${K.sessionId}`?s.jsx(gn,{size:12,className:"animate-spin"}):s.jsx(hi,{size:12})})]})]},K.sessionId)},Xr=s.jsx("nav",{"aria-label":"协作工作区",className:"flex shrink-0 items-center gap-1",children:[["tasks",e||$e?"看板":"目标"],["messages","成员与消息"]].map(([K,Ue])=>s.jsxs("button",{type:"button","aria-label":Ue,"aria-pressed":Y===K,className:`${wr} min-h-11 ${Y===K?"bg-surface-2 text-foreground":"text-muted-foreground hover:bg-surface-2"}`,onClick:Et=>{if($e&&K==="tasks"){U?.(dt.id).catch(Qr=>pe(Qr instanceof Error?Qr.message:"无法打开看板"));return}const kt=Et.currentTarget.closest("[data-collaboration-views]"),tr=Et.currentTarget;Ae(K),requestAnimationFrame(()=>{const Qr=document.activeElement;Qr!==tr&&Qr!==document.body&&Qr?.isConnected&&!Qr.closest("[hidden]")||Array.from(kt?.querySelectorAll('nav[aria-label="协作工作区"] button')??[]).find(cr=>cr.getAttribute("aria-pressed")==="true"&&!cr.closest("[hidden]"))?.focus()})},children:[e&&K==="messages"?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"sm:hidden",children:"成员"}),s.jsx("span",{className:"hidden sm:inline",children:Ue})]}):Ue,!e&&K==="tasks"&&ye>0&&s.jsxs("span",{className:"rounded bg-primary/15 px-1.5 text-[11px] text-primary",children:[ye," 待处理"]})]},K))}),fn=s.jsxs("button",{type:"button","aria-label":"组设置",title:"组设置","aria-expanded":vt,className:`${wr} min-h-11 shrink-0 text-muted-foreground hover:bg-surface-2`,onClick:K=>{Xt.current=K.currentTarget,Zt(Ue=>!Ue),pe(null),te(null)},children:[s.jsx(e0,{size:14}),e&&s.jsx("span",{className:"sm:sr-only",children:"组设置"})]});return s.jsxs("div",{ref:Pt,className:e?"flex min-h-0 flex-1 flex-col gap-3":$e?void 0:"space-y-3",children:[Te&&oe==="ready"&&!sf(Te)&&s.jsxs("p",{role:"alert",className:"rounded-lg bg-destructive/10 px-3 py-2 text-[11px] text-destructive",children:["消息同步暂时失败,正在自动重试:",Te]}),Te&&sf(Te)&&!e&&s.jsx("p",{role:"status",className:"text-[11px] text-muted-foreground",children:"正在恢复消息同步,现有记录已保留"}),s.jsxs("div",{className:e?vt?"min-h-0 flex-1 overflow-auto":"contents":void 0,children:[!B&&m!=="new"&&S.length>0&&s.jsx("div",{hidden:vt,children:s.jsx(pO,{groups:S,sessions:L,busy:ce!==null,onOpen:(K,Ue)=>{r?.(K,Ue)},onSettings:(K,Ue)=>{zt.current=K,x(K),Xt.current=Ue,Zt(!0),pe(null),te(null)},onCreate:()=>{x("new"),rt(!1),te(null)}})}),!B&&(m==="new"||vt)&&S.length>0&&s.jsx("button",{type:"button",className:`${wr} min-h-11 text-muted-foreground hover:bg-surface-2`,onClick:()=>{vt?Lt():x(S[0].id)},children:"返回协作组"}),vt&&dt&&s.jsx(MO,{group:dt,agents:E,activeSessionId:R,sessions:L,busy:ce,setBusy:xe,setError:pe,setNotice:te,refresh:ke,onClose:Lt},dt.id),!B&&v!=="loaded"&&!S.length&&s.jsx("p",{role:"status",className:"py-5 text-xs text-muted-foreground",children:v==="loading"?"正在加载协作组与会话…":"会话加载失败,请重试"}),!dt&&(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] ${mr>=2?"text-primary":"text-muted-foreground"}`,children:["已选 ",mr," 个"]})]}),s.jsxs("label",{className:"mt-4 block space-y-1 text-[10px] text-muted-foreground",children:["协作组名称",s.jsx("input",{className:Fs,value:je,onChange:K=>re(K.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:["复用已有会话(选填) · 已选 ",mr," 个"]}),L.length>5&&s.jsxs("label",{className:"relative mt-3 block",children:[s.jsx("span",{className:"sr-only",children:"筛选会话"}),s.jsx(Ml,{size:13,className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),s.jsx("input",{className:`${Fs} pl-8`,value:Ee,onChange:K=>Be(K.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:[hn.length<=1?bn.map(ks):hn.map(K=>{const Ue=ir(K.key);return s.jsxs("div",{children:[s.jsx(Ib,{label:K.label,count:K.sessions.length,collapsed:Ue,onToggle:()=>pn(K.key)}),!Ue&&s.jsx("div",{className:"divide-y divide-border/10",children:K.sessions.map(ks)})]},K.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&&bn.length===0&&s.jsx("p",{className:"px-3 py-6 text-center text-[11px] text-muted-foreground",children:"没有符合筛选条件的会话"})]})]}),Hr.length>0&&s.jsxs("div",{role:"alert",className:"mt-2 text-[11px] text-destructive",children:["有 ",Hr.length," 个所选会话暂不可用。",s.jsx("button",{className:wr,onClick:()=>Ce(K=>new Set([...K].filter(Ue=>Tr.has(Ue)))),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] ${mr<2?"text-muted-foreground":"text-primary"}`,children:je.trim()?"创建后进入成员消息,看板可随时使用":"请填写协作组名称"}),s.jsxs("div",{className:"flex justify-end gap-2",children:[S.length>0&&s.jsx("button",{className:`${wr} bg-surface-2 text-foreground`,onClick:()=>x(S[0]?.id??null),children:"取消"}),s.jsxs("button",{disabled:ce!==null||!je.trim()||Hr.length>0,className:`${wr} bg-primary text-primary-foreground`,onClick:()=>{Pr()},children:[ce==="create-group"?s.jsx(gn,{size:13,className:"animate-spin"}):s.jsx(Us,{size:13}),"创建协作组"]})]})]})]})]}),dt&&B&&s.jsxs("div",{"data-collaboration-views":!0,hidden:vt,className:e?`${vt?"hidden":"flex"} min-h-0 flex-1 flex-col gap-3`:$e?void 0:"space-y-3",children:[!$e&&(!e||Y==="messages")&&s.jsxs("div",{className:"flex shrink-0 items-center gap-1 border-b border-border/15 pb-2",children:[Xr,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||ce!==null,className:`${wr} min-h-11 text-muted-foreground hover:bg-surface-2`,onClick:()=>{xe("dock-messages"),pe(null),V?.().catch(K=>pe(K instanceof Error?K.message:"消息面板打开失败,草稿已保留")).finally(()=>xe(null))},children:[s.jsx(Fc,{size:14}),s.jsx("span",{className:"hidden sm:inline",children:"放到终端旁"})]}),fn]})]}),!$e&&Y==="messages"&&s.jsx("div",{className:"flex gap-1 overflow-x-auto","aria-label":"工作组终端",children:sr.map(K=>s.jsx("button",{type:"button","aria-pressed":K.sessionId===R,title:`${K.name} · ${K.cwd||"终端会话"}`,className:`${wr} min-h-9 shrink-0 ${K.sessionId===R?"bg-primary/15 text-primary":"text-muted-foreground hover:bg-surface-2"}`,onClick:()=>{F(K).catch(Ue=>pe(Ue instanceof Error?Ue.message:"无法打开终端"))},children:ku(K,sr)},K.sessionId))}),!$e&&s.jsx("div",{hidden:Y!=="tasks",className:e?`${Y==="tasks"?"flex":"hidden"} min-h-0 flex-1 flex-col`:void 0,children:s.jsx(CO,{paneKey:d?Vr:void 0,boardNavigation:e?Xr:void 0,boardSettings:e?fn:void 0,board:e,group:dt,sessions:L,agents:E,defaultCwd:L.find(K=>K.sessionId===R)?.cwd??void 0,onTeamReady:ke,active:n&&!vt&&Y==="tasks"&&(!w||y),onAttentionChange:_e,onManageMembers:()=>Ae("messages"),onOpenSession:F},dt.id)}),s.jsxs("div",{hidden:Y!=="messages",className:e?"min-h-0 flex-1 overflow-auto":void 0,children:[s.jsxs("section",{onFocusCapture:()=>t0(Vr),onPointerDownCapture:()=>t0(Vr),"data-termdock-terminal-dropzone":w?R??"collaboration-composer":void 0,onDragOver:K=>{w&&K.preventDefault()},onDrop:K=>{if(!w)return;const Ue=Array.from(K.dataTransfer.files);if(!(Ue.length&&xo()))if(K.preventDefault(),K.stopPropagation(),Ue.length)Ot(Ue);else{const Et=K.dataTransfer.getData("text/plain")||K.dataTransfer.getData("text/uri-list");Et&&St(kt=>kt+(kt?`
|
|
162
|
-
`:"")+Et)}},ref:Lr,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:[dt.name," · 发送给成员"]}),s.jsxs("div",{className:w?"space-y-2":"mt-2 space-y-2",children:[$e&&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:K=>{K.key==="Escape"&&(K.currentTarget.removeAttribute("open"),K.currentTarget.querySelector("summary")?.focus(),K.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($o,{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:`${wr} min-h-11 w-full justify-start text-foreground hover:bg-surface-elevated`,onClick:K=>{K.currentTarget.closest("details")?.removeAttribute("open"),U?.(dt.id).catch(Ue=>pe(Ue instanceof Error?Ue.message:"无法打开看板"))},children:[s.jsx(Fc,{size:14}),"看板"]}),s.jsx("button",{type:"button","aria-expanded":lt,className:`${wr} min-h-11 w-full justify-start text-foreground hover:bg-surface-elevated`,onClick:K=>{K.currentTarget.closest("details")?.removeAttribute("open"),Se(Ue=>!Ue)},children:"成员管理"}),s.jsxs("button",{type:"button","aria-label":"组设置","aria-expanded":vt,className:`${wr} min-h-11 w-full justify-start text-foreground hover:bg-surface-elevated`,onClick:K=>{K.currentTarget.closest("details")?.removeAttribute("open"),Xt.current=K.currentTarget,Zt(!0),pe(null),te(null)},children:[s.jsx(e0,{size:14}),"组设置"]})]})]})]}),s.jsxs("fieldset",{className:"min-w-0",children:[s.jsx("legend",{className:$e?"sr-only":"mb-1 text-[10px] text-muted-foreground",children:"接收人(可多选)"}),s.jsx("div",{className:"flex flex-wrap gap-1",children:[{id:"*",label:"全组成员"},...dt.sessionIds.map(K=>({id:K,label:(()=>{const Ue=sr.find(Et=>Et.sessionId===K);return Ue?ku(Ue,sr):void 0})()??`${K.slice(0,8)}(离线)`}))].map(({id:K,label:Ue})=>{const Et=K==="*"?be===null:be?.includes(K)??!1,kt=L.find(tr=>tr.sessionId===K);return s.jsxs("span",{className:"inline-flex max-w-full items-center gap-0.5",children:[s.jsxs("button",{type:"button","aria-pressed":Et,onClick:()=>Ze(tr=>K==="*"?null:tr?.includes(K)?tr.filter(Qr=>Qr!==K):[...tr??[],K]),className:`${E1} min-h-9 min-w-0 gap-1 sm:min-h-7 ${Et?"border-primary/40 bg-primary/15 text-primary":"border-border/20 bg-surface-2 text-muted-foreground hover:text-foreground"}`,children:[Et&&s.jsx(hi,{size:12,"aria-hidden":"true",className:"shrink-0"}),s.jsx("span",{className:"break-words text-left",children:Ue})]}),kt&&s.jsx("button",{type:"button","aria-label":`打开 ${Ue} 的终端`,title:`打开 ${Ue} 的终端`,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:()=>{W(kt).catch(tr=>pe(tr instanceof Error?tr.message:"无法打开会话"))},children:s.jsx(Fc,{size:12})})]},K)})})]})]}),s.jsxs("label",{className:"mt-2 block space-y-1 text-[9px] text-muted-foreground",children:[s.jsx("span",{className:$e?"sr-only":void 0,children:"内容"}),s.jsx("textarea",{onKeyDown:K=>{K.key==="Enter"&&(K.metaKey||K.ctrlKey)&&!K.nativeEvent.isComposing&&K.keyCode!==229&&(K.preventDefault(),Wr())},onPaste:K=>{const Ue=Array.from(K.clipboardData.files);Ue.length&&(K.preventDefault(),Ot(Ue))},className:`${Fs} min-h-16 max-h-48 resize-y`,value:Je,onChange:K=>St(K.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:xn>0?"正在准备文件路径…":w&&a?a:dt.federated?"消息由服务端后台投递,可查看送达结果;无需保持客户端在线。":"在线成员立即入队;离线成员上线后送达。"}),s.jsxs("button",{disabled:ce!==null||xn>0||!Je.trim()||!qr.length,className:`${wr} shrink-0 bg-primary text-primary-foreground`,title:"发送(⌘ / Ctrl + Enter)",onClick:()=>{Wr()},children:[ce==="send-message"?s.jsx(gn,{size:13,className:"animate-spin"}):null,"发送"]})]})]}),s.jsxs("div",{children:[s.jsxs("details",{hidden:$e&&!lt,open:$e?lt:void 0,onToggle:K=>{$e&&Se(K.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:["管理成员、角色与删除 · ",dt.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:dt.name}),s.jsxs("p",{className:"mt-1 text-[10px] text-muted-foreground",children:[dt.sessionIds.length," 个成员 · 组 ID:",s.jsx("span",{className:"break-all font-mono",children:W6(dt.id)})]})]}),He?s.jsxs("div",{className:"flex flex-wrap items-center gap-1 sm:justify-end",children:[s.jsx("button",{className:`${wr} bg-surface-2 px-2 text-foreground`,onClick:()=>rt(!1),children:"取消"}),s.jsxs("button",{disabled:ce!==null,className:`${wr} bg-destructive px-2 text-destructive-foreground`,onClick:()=>{fs()},children:[ce===`delete:${dt.id}`?s.jsx(gn,{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:`${wr} px-2 text-muted-foreground hover:bg-surface-2 hover:text-foreground`,onClick:()=>{q(new Set(dt.sessionIds)),qt(dt.updatedAt);const K=!Vt;jt(K),K&&De(Object.fromEntries(dt.sessionIds.map(Ue=>[Ue,dt.roles?.[Ue]??""]))),et(!1)},children:[s.jsx(e0,{size:13}),"管理成员"]}),s.jsxs("button",{className:`${wr} px-2 text-primary hover:bg-primary/10`,onClick:Kr,children:[s.jsx(Us,{size:13}),"新建 Agent"]}),s.jsx("button",{"aria-label":`删除协作组 ${dt.name}`,title:"删除协作组",disabled:ce!==null,className:"rounded-lg p-2 text-muted-foreground transition hover:bg-destructive/10 hover:text-destructive",onClick:()=>{ue(dt.updatedAt),rt(!0)},children:s.jsx(zs,{size:14})})]})]}),He&&s.jsxs("p",{role:"alert",className:"mt-2 rounded-lg bg-destructive/10 px-3 py-2 text-[10px] leading-relaxed text-destructive",children:["将删除“",dt.name,"”协作组及其协作记录,",dt.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:dt.sessionIds.map(K=>{const Ue=L.find(tr=>tr.sessionId===K),Et=dt.roles?.[K],kt=Ue?.name??K;return s.jsxs("div",{className:`flex min-w-0 items-stretch transition ${me===K?"bg-destructive/5":"hover:bg-surface-2"}`,children:[s.jsxs("button",{disabled:!Ue,onClick:()=>Ue&&void W(Ue).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 ${Ue&&["ready","shell","terminal-connected","service-reachable","working","idle","done"].includes(Ue.status)&&Ue.serviceConnected!==!1?"bg-[var(--success)]":"bg-muted-foreground"}`}),s.jsx("span",{className:"truncate text-[11px] text-foreground",children:kt}),Ue&&s.jsx(Cm,{session:Ue}),s.jsx("span",{className:"ml-auto shrink-0 text-[9px] text-muted-foreground",children:Ue?tf(Ue):"已离线"})]}),s.jsxs("span",{className:"mt-1 flex min-w-0 items-center gap-1 text-[9px] text-muted-foreground",children:[Et?s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"min-w-0 truncate font-medium text-primary/80",children:["定位:",Et]}),s.jsx("span",{className:"shrink-0 text-muted-foreground/50",children:"·"})]}):null,Ue?s.jsx("span",{className:"min-w-0 truncate",children:_m(Ue.currentTask)}):s.jsx("span",{className:"shrink-0",children:"重新上线后可继续接收消息"})]})]}),s.jsx("button",{"aria-label":`把 ${kt} 移出协作组`,"aria-expanded":me===K,title:"移出协作组",disabled:ce!==null,className:`mr-1 shrink-0 self-center rounded-lg p-2 transition ${me===K?"text-destructive":"text-muted-foreground hover:bg-destructive/10 hover:text-destructive"}`,onClick:()=>Ge(me===K?null:K),children:s.jsx(zs,{size:13})})]},K)})}),me&&dt.sessionIds.includes(me)&&(()=>{const K=L.find(Et=>Et.sessionId===me)?.name??me,Ue=ce===`remove-member:${me}`;return s.jsxs("div",{role:"group","aria-label":`确认移除成员 ${K}`,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:`把“${K}”移出“${dt.name}”?移出后它不再收到这个组的消息,可以随时重新加入`}),s.jsxs("div",{className:"flex shrink-0 gap-2",children:[s.jsx("button",{className:`${wr} min-h-8 bg-surface-2 px-2 text-[10px] text-foreground`,onClick:()=>Ge(null),children:"取消"}),s.jsxs("button",{disabled:ce!==null,className:`${wr} min-h-8 px-2 text-[10px] bg-destructive text-destructive-foreground`,onClick:()=>{Mn(me)},children:[Ue?s.jsx(gn,{size:12,className:"animate-spin"}):s.jsx(zs,{size:12}),"移出"]})]})]})})(),Vt&&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:["已选 ",pt.size]})]}),s.jsx("div",{className:"mt-3 max-h-72 divide-y divide-border/10 overflow-y-auto border-y border-border/10",children:Tn.length<=1?_n.map(Or):Tn.map(K=>{const Ue=ir(K.key);return s.jsxs("div",{children:[s.jsx(Ib,{label:K.label,count:K.sessions.length,collapsed:Ue,onToggle:()=>pn(K.key)}),!Ue&&s.jsx("div",{className:"divide-y divide-border/10",children:K.sessions.map(Or)})]},K.key)})}),s.jsxs("div",{className:"mt-3 flex justify-end gap-2",children:[s.jsx("button",{className:`${wr} bg-surface-2 text-foreground`,onClick:()=>{jt(!1),De({})},children:"取消"}),s.jsxs("button",{disabled:ce!==null||v!=="loaded",className:`${wr} bg-primary text-primary-foreground`,onClick:()=>{Br()},children:[ce==="save-members"?s.jsx(gn,{size:13,className:"animate-spin"}):s.jsx(hi,{size:13}),"保存成员"]})]})]}),er&&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(mO,{group:dt,value:gt,onChange:bt,disabled:ce!==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:Fs,disabled:!!gt,value:dt.launchProfiles?.find(K=>K.id===gt)?.agentSlug??Ct,onChange:K=>Nt(K.target.value),children:E.map(K=>s.jsxs("option",{value:K.slug,children:[K.displayName,K.isPlugin?" · Plugin":""]},K.slug))})]}),s.jsxs("label",{className:"space-y-1 text-[9px] text-muted-foreground",children:["会话名称",s.jsx("input",{"aria-label":"新 Agent 会话名称",className:Fs,value:It,onChange:K=>yt(K.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:Fs,value:pr,onChange:K=>nr(K.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:`${Fs} min-h-16 resize-y`,value:Cr,onChange:K=>cn(K.target.value),placeholder:"说明它加入后要先完成什么"})]}),s.jsxs("div",{className:"mt-3 flex justify-end gap-2",children:[s.jsx("button",{className:`${wr} bg-surface-2 text-foreground`,onClick:()=>et(!1),children:"取消"}),s.jsxs("button",{disabled:ce!==null||!Ct||!!gt&&!dt.launchProfiles?.some(K=>K.id===gt),className:`${wr} bg-primary text-primary-foreground`,onClick:()=>{nn()},children:[ce==="spawn-agent"?s.jsx(gn,{size:13,className:"animate-spin"}):s.jsx(E0,{size:13}),"创建并加入"]})]})]})]})]},dt.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:[Fr.length," 条"]})]}),s.jsxs("div",{className:"divide-y divide-border/10 border-y border-border/10 [overflow-wrap:anywhere]",children:[Fr.map(K=>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:K.responseKind==="ack"?"收到确认":K.responseKind==="progress"?"进展":K.responseKind==="result"?"结果":$O(K.kind)}),s.jsx("span",{children:K.fromName}),s.jsx("span",{children:"→"}),s.jsx("span",{className:"truncate",children:K.toNames.join("、")}),s.jsx("span",{className:"ml-auto shrink-0",children:new Date(K.createdAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),s.jsx("p",{className:"mt-1 whitespace-pre-wrap text-[11px] leading-relaxed text-foreground",children:K.content}),s.jsx("p",{className:"mt-1 text-[9px] text-muted-foreground",children:K.status==="pending"?"已入队 · 等待投递":K.status==="failed"?"投递失败":K.status==="expired"?"消息已过期,未继续投递":K.status==="stored"?"答复已持久保存 · 供后台接收":"已写入接收方终端 · 等待接手确认"}),(K.task||K.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(K.task??{failure_reason:K.failureReason},null,2)})]})]},K.key)),Fr.length===0&&s.jsx(ZO,{text:Ie?"正在加载协作记录…":"还没有消息。可以直接给成员发送说明或问题。"})]})]})]})]})]})]})}function MO({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)&&!Pu(Y.sessionId)),[y,w]=b.useState(()=>kO(e,r&&x.some(Y=>Y.sessionId===r)?r:"")),v=b.useRef(y),[S,L]=b.useState(null),E=Y=>{const Ae={...v.current,...Y};v.current=Ae,LO(e.id,Ae),w(Ae)},{name:R,rules:B,savedName:W,savedRules:F,rulesVersion:U,rulesMemberId:V}=y,Z=Bf(y),ce=new TextEncoder().encode(B).length,xe=x.some(Y=>Y.sessionId===V),pe=async()=>{if(!(a||!R.trim())){c("group-name"),l(null),d(null);try{const Y=await ac({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===F?{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 Jd&&Y.status===409?"组设置已被其他人修改。请查看最新状态并确认,名称与群规草稿仍保留。":Y instanceof Error?Y.message:"改名失败")}finally{c(null)}}},te=async()=>{if(!(a||!xe||ce>8192)){c("group-rules"),l(null),d(null);try{const Y=await Uw(e.id,{sessionId:V,text:B,expectedVersion:U});L(null),E({savedName:Y.group.name,...R===W?{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 Jd&&Y.status===409?"群规已被其他人修改。请查看最新状态并确认,名称与群规草稿仍保留。":Y instanceof Error?Y.message:"群规保存失败")}finally{c(null)}}},ke=()=>{E(Lg(e,V)),L(null),l(null)},$e=async()=>{if(!a){c("group-latest"),l(null),d(null),L(null);try{const Ae=(await B1()).groups.find(lt=>lt.id===e.id);if(!Ae)throw new Error("协作组已删除;草稿仍保留,请返回看板查看。");L(Ae)}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(Rn,{size:14})})]}),s.jsxs("label",{className:"block space-y-1 text-[10px] text-muted-foreground",children:["协作组名称",s.jsx("input",{autoFocus:!0,className:Fs,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()===W,className:`${wr} min-h-9 bg-primary text-primary-foreground`,onClick:()=>{pe()},children:a==="group-name"?"保存中…":"保存名称"})}),s.jsx(gO,{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:Fs,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:`${Fs} min-h-24 resize-y`,value:B,maxLength:8192,disabled:!!a,onChange:Y=>E({rules:Y.target.value}),placeholder:"例如:说明分工、交接要求和结果格式。清空后保存可移除群规。"})]})]}),!xe&&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] ${ce>8192?"text-destructive":"text-muted-foreground"}`,children:ce>8192?"内容过长,请缩短群规":"保存或清空群规会通知本组其他成员"}),s.jsx("button",{type:"button",disabled:!!a||!!S||!xe||ce>8192||B===F,className:`${wr} min-h-9 shrink-0 bg-primary text-primary-foreground`,onClick:()=>{te()},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:`${wr} mt-2 min-h-11 text-primary hover:bg-surface-elevated`,onClick:()=>{$e()},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(Ae=>Ae.sessionId===Y)?.name??W6(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:`${wr} min-h-11 bg-primary text-primary-foreground`,onClick:()=>{E(_O(v.current,S)),L(null),l(null),d("已确认最新状态,草稿仍保留;请分别保存名称与群规。")},children:"确认最新状态,保留草稿"}),s.jsx("button",{type:"button",className:`${wr} 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:`${wr} min-h-9 text-muted-foreground hover:bg-surface-elevated`,onClick:ke,children:[s.jsx(gn,{size:12}),"重新载入",Z&&"(放弃草稿)"]}),s.jsx("button",{type:"button",disabled:!!a,className:`${wr} min-h-9 bg-surface text-foreground`,onClick:m,children:Z?"关闭并保留草稿":"关闭"})]})]})}function jO({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 qw(E):await Yw(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(DO,{service:E})]}),E.serviceId&&s.jsxs("button",{type:"button",disabled:!!r,"aria-label":`移除协作连接 ${E.origin}`,className:`${wr} 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(zs,{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:zO(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:`${wr} min-h-9 text-muted-foreground`,onClick:()=>p(null),children:"取消"}),s.jsx("button",{type:"button",disabled:!!r||!!E.groups?.length,className:`${wr} 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:`${wr} mt-1 min-h-9 text-primary hover:bg-primary/10`,onClick:Vw,children:[s.jsx(gn,{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:`${wr} 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:`${wr} 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 DO({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 Sm(e){return!Pu(e.sessionId)||e.serviceConnected!==!1}function BO(e){return e.serviceOrigin?e.serviceOrigin===window.location.origin?"":e.serviceOrigin:Pu(e.sessionId)?.origin??""}function Lb(e){const t=new Map;for(const r of e){const n=BO(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 Ib({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 QO(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,...Pu(n)?{serviceConnected:!1}:{}})}return[...r.values()]}function Cm({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 tf(e){return e.serviceConnected===!1?"服务不可达":e.status==="recovering"&&e.route_error==="ROUTE_NOT_CHECKED"?"投递目标未检查":FO(e.status)}function PO(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 OO(e){e.sessionId.startsWith("remote:")?await b6(e.sessionId):window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:e.sessionId}))}function FO(e){return{ready:"终端可达",shell:"Shell 终端",recovering:"正在检查投递目标",unchecked:"投递目标未检查","terminal-connected":"终端已连接",detached:"终端未连接","agent-exited":"Agent 已退出",offline:"已离线",ambiguous:"需确认目标终端","identity-mismatch":"终端身份已变化",unavailable:"终端暂不可达","service-reachable":"服务可达","service-unreachable":"服务不可达"}[e]??"在线"}function _m(e){if(!e)return"暂无任务摘要";try{const t=JSON.parse(e);if(typeof t.prompt=="string")return Qf(t.prompt)||"暂无任务摘要"}catch{}return Qf(e)||"暂无任务摘要"}function $O(e){return{message:"消息",ask:"问题",reply:"回复",task:"任务",handoff:"交接",done:"完成"}[e]}function UO(e,t){const r=new Map(t.map(a=>[a.sessionId,PO(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 zO(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 km({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 HO({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,W]=b.useState(null),[F,U]=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,te=new AbortController;let ke;W(null),R(!0);const $e=async()=>{try{const Y=await Zw(a.trim(),w,te.signal);if(pe!==Z.current)return;d(Y.results),m(Y.total??Y.results.length),y(Y.index),Y.index?.building&&(ke=window.setTimeout(()=>{$e()},2500))}catch(Y){pe===Z.current&&!te.signal.aborted&&W(Y instanceof Error?Y.message:"搜索失败")}finally{pe===Z.current&&R(!1)}};return ke=window.setTimeout(()=>{$e()},a.trim()?250:0),()=>{window.clearTimeout(ke),te.abort(),++Z.current}},[e,a,w,S]);const ce=pe=>{n(null),c(pe),d([]),m(0),v(50)},xe=async pe=>{if(!F){if(pe.live){window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:pe.sessionId})),t();return}if(!(!pe.nativeKey&&!pe.resumeHistoryId)){U(pe.sessionId),n(null);try{const te=pe.nativeKey?await Kw(pe.nativeKey):await ky(pe.resumeHistoryId);if("sessionId"in te&&te.sessionId)window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:te.sessionId}));else if(te.command)r({mode:"shell",cwd:te.cwd,command:te.command});else throw new Error("这条会话暂时无法恢复,请重新搜索");t()}catch(te){n(te instanceof Error?te.message:"恢复失败")}finally{U(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(Ml,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),s.jsx("input",{ref:V,maxLength:512,className:`${Fs} pl-9 pr-9`,value:a,onChange:pe=>ce(pe.target.value),placeholder:"搜索会话名称、对话关键词、目录或 session ID"}),E?s.jsx(gn,{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:()=>ce(""),children:s.jsx(Rn,{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:`${wr} text-muted-foreground hover:bg-surface-2 hover:text-foreground`,onClick:()=>L(pe=>pe+1),children:[s.jsx(gn,{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 te=pe.live||!!(pe.nativeKey||pe.resumeHistoryId),ke=F===pe.sessionId?"正在恢复…":pe.live?"打开会话":te?"恢复会话":"仅供查阅",$e=pe.source==="codex"||pe.source==="claude"?pe.snippet:WO(pe),Y=pe.source==="codex"?"Codex 历史":pe.source==="claude"?"Claude 历史":"终端记录",Ae=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(km,{value:pe.title,query:a})}),s.jsx("p",{className:"mt-0.5 break-all text-[9px] text-muted-foreground",children:s.jsx(km,{value:pe.cwd||"项目目录待索引",query:a})})]}),s.jsx("span",{className:`shrink-0 text-[10px] ${pe.live?"text-[var(--success)]":te?"text-primary":"text-muted-foreground"}`,children:ke})]}),$e&&s.jsx("p",{className:"mt-2 line-clamp-3 break-words text-[10px] leading-relaxed text-foreground/75",children:s.jsx(km,{value:$e,query:a})}),s.jsxs("p",{className:"mt-2 text-[9px] text-muted-foreground",children:[Y," · ",Pf(pe.updatedAt),a.trim()?` · ${pe.matchCount>=999?"999+":pe.matchCount} 处匹配`:"",te?"":" · 没有可恢复记录"]}),pe.agentNativeSessionId&&s.jsx("p",{className:"mt-1 select-text break-all text-[9px] text-muted-foreground",children:pe.agentNativeSessionId})]});return te?s.jsx("button",{disabled:!!F,onClick:()=>{xe(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:Ae},pe.nativeKey||pe.sessionId):s.jsx("article",{className:"px-2 py-3",children:Ae},pe.sessionId)})}),p>l.length&&w<5e3&&s.jsx("button",{type:"button",disabled:E,className:`${wr} 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:`${wr} 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:`${wr} mt-3 bg-surface-2 text-foreground`,onClick:()=>ce(""),children:"查看最近会话"})]})]})}function Qf(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 WO(e){let t=Qf(e.snippet);for(const r of[e.title,e.cwd,e.agentSlug])r&&(t=t.split(r).join(" "));return Qf(t)}function GO(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 VO(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 Pf(e){return new Intl.DateTimeFormat("zh-CN",{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(e)}function qO(e){return e==="running"?"投递中":e==="success"?"已投递":e==="failed"?"投递失败":""}function YO(e){return e==="running"?"text-[var(--warning)]":e==="success"?"text-[var(--success)]":e==="failed"?"text-destructive":"text-muted-foreground"}function ZO({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 KO({onOpenSettings:e,serverAttention:t,actions:r}){const{t:n}=zr(),[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,W=(w?.offsetTop??0)+(w?.height??window.innerHeight)-8,F=Math.max(0,Math.min(256,B)),U=Math.max(0,L.top-R-4),V=Math.max(0,W-L.bottom-4),Z=U>=180||U>=V;Object.assign(y.style,{width:`${F}px`,left:`${Math.max(E,Math.min(L.right-F,E+B-F))}px`,top:`${Z?L.top-4:L.bottom+4}px`,maxHeight:`${Z?U: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(mS,{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($o,{size:15}),s.jsx("span",{children:n("sidebar.moreActions")})]}),a&&Ii.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 Qd=64,Eb=10,XO=120;function JO({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?Qd: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?Qd:0,offset:t?Qd: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>=XO||Math.abs(E)>Eb){p.current=null;return}if(Math.abs(L)<=Eb)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(Qd,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>=Qd/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(zs,{size:14}),a]})}),e]})}const Nb="recoverable-tmux";function eF({sessions:e,loading:t,attachingName:r,onRefresh:n,onRestore:a,onClose:c}){const{t:l}=zr(),d=Gt(R=>R.collapsedGroups.has(Nb)),p=Gt(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(Nb),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(fi,{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(gn,{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,W=Yu(R.cwd??null),F=r===R.name,U=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||U,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:F?s.jsx(Cn,{size:12,className:"animate-spin"}):s.jsx(Uu,{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,W].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(F?"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(Rn,{size:12})})]}),U&&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)})})]})}function tF(e,t){return zy(e,t)}function Pd(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 Od(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 Rb(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 rF({status:e,detail:t,needsReview:r,inCopyMode:n}){return s.jsx(OP,{status:e,detail:t,needsReview:r,inCopyMode:n})}function Mb({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:W,onOpenQuota:F,updateState:U,updateActionPending:V=!1,onConfirmUpdateRestart:Z,onRetryUpdate:ce,serverHealthState:xe,tmuxAvailable:pe=!0,defaultSessionMode:te="shell",push:ke,pinned:$e,onTogglePinned:Y,recoverableTmuxSessions:Ae=[],recoverableTmuxSessionsLoading:lt=!1,onRefreshRecoverableTmuxSessions:Se,onCloseRecoverableTmuxSession:ye}){const{t:_e}=zr(),[,je]=b.useState(0),[re,Oe]=b.useState(null),[Ce,Ee]=b.useState(!1),[Be,Ne]=b.useState(!1),[le,He]=b.useState(null),rt=b.useRef(!1),mt=b.useRef(0),ue=b.useCallback(G=>{G||(mt.current+=1),Ee(G)},[]),[Ye,st]=b.useState(!1),Ie=la(G=>G.groupId),[We,Te]=b.useState({}),H=Ye||Object.keys(We).length>0,oe=b.useRef(!1),be=b.useRef(!1),[Ze,Je]=b.useState(null);b.useEffect(()=>{let G=!1;return fc().then(Le=>{G||oe.current||Te(Object.fromEntries(Ky(Le.collaborationPanels?.[$f()]).map(Ke=>[Ke,!0])))}).catch(()=>{}),()=>{G=!0}},[]);const St=async(G,Le)=>{oe.current=!0,await bo({floatingGroupId:Le},G),Te(Ke=>({...Ke,[G]:Le!==null}))},[Vt,jt]=b.useState([]),[vt,Zt]=b.useState(!1),[Pt,Xt]=b.useState(null),[zt,Lt]=b.useState(null),[me,Ge]=b.useState(null),[pt,q]=b.useState(null),at=_u(G=>G.tasks),qt=_u(G=>G.allTasks),[Ve,De]=b.useState(0),[er,et]=b.useState(null),Ct=b.useRef(!1),[Nt,gt]=b.useState({}),bt=_u(G=>G.error),[It,yt]=b.useState(!1);b.useEffect(()=>{const G=()=>{document.hidden||_u.getState().refresh()};G();const Le=window.setInterval(G,5e3);return document.addEventListener("visibilitychange",G),()=>{clearInterval(Le),document.removeEventListener("visibilitychange",G)}},[]);const pr=async G=>(ue(!1),oe.current=!0,G?(la.getState().open(G),Fr(),!0):(st(!0),Fr(),!0)),nr=uf(G=>G.collaborationGroups),Cr=uf(G=>G.setCollaborationGroups),[cn,Lr]=b.useState({mode:te}),{preference:ge,agents:Vr,detecting:it,refresh:dt,selectAgent:sr}=fO(),xn=b.useRef(null),an=!!(U?.latestVersion&&["installing","ready","restarting","error"].includes(U.status)),Me=!!xe?.attention,nt=[_e("sidebar.moreActions"),Me?_e("sidebar.serverAttention"):null,an&&U?.latestVersion?_e("sidebar.updateAvailable",{version:U.latestVersion}):null].filter(Boolean).join(": "),wt=Gt(G=>G.groupByFolder),Rr=Gt(G=>G.collapsedGroups),rn=Gt(G=>G.toggleGroupCollapsed),Ir=b.useRef(null),ne=b.useRef(null),ht=b.useRef(null),Ht=b.useRef(0),Ot=b.useRef(!1),Tr=b.useRef(null),mr=b.useRef(null),[Hr,_n]=b.useState(!1),dr=b.useRef([]),bn=b.useRef(null),hn=b.useRef(null),Tn=b.useRef(new Set),ir=b.useRef(null),pn=b.useMemo(()=>new Set(v.flatMap(G=>G.sessionIds)),[v]),Pr=b.useMemo(()=>new Map(a.map(G=>[G.id,G])),[a]),qr=b.useMemo(()=>tF(nr,new Set(Pr.keys())),[nr,Pr]),Wr=b.useCallback(async()=>{const G=++Ht.current;try{const Le=await B1();if(G!==Ht.current)return;Cr(Array.isArray(Le.groups)?Le.groups:[])}catch{}},[]);b.useEffect(()=>_y(G=>Cr(G.groups)),[]),b.useEffect(()=>{Wr();const G=window.setInterval(()=>{Wr()},1e4),Le=()=>{Wr()};return window.addEventListener("focus",Le),()=>{Ht.current+=1,window.clearInterval(G),window.removeEventListener("focus",Le)}},[Wr]),b.useEffect(()=>{(e||!H)&&Wr()},[H,e,Wr]);const fs=b.useCallback(()=>{dr.current=Array.from(document.querySelectorAll("[data-collaboration-member], [data-collaboration-background]")).flatMap(G=>{const Le=G.dataset.collaborationMember??"",Ke=G.hasAttribute("data-collaboration-background"),ct=G.closest("[data-collaboration-group]")?.dataset.collaborationGroup;if(!Le&&!Ke||!ct)return[];const qe=[];for(let At=G.parentElement;At;At=At.parentElement)qe.push({element:At,top:At.scrollTop,left:At.scrollLeft});return[{element:G,sessionId:Le,groupId:ct,background:Ke,rect:G.getBoundingClientRect(),scrollParents:qe}]})},[]),Br=b.useCallback((G,Le)=>{if(!Ot.current)return;document.querySelectorAll("[data-split-exit-drop-index]").forEach(N=>N.removeAttribute("data-active")),document.querySelectorAll("[data-drop-active]").forEach(N=>N.removeAttribute("data-drop-active"));const ct=document.elementsFromPoint(G,Le).map(N=>N.closest("[data-collaboration-background]")).find(Boolean)?.closest("[data-collaboration-group]");if(ct?.dataset.collaborationGroup){ct.dataset.dropActive="true",hn.current={kind:"collaboration",groupId:ct.dataset.collaborationGroup,background:!0};return}const qe=dr.current.find(N=>{if(N.sessionId===mr.current||!N.element.isConnected)return!1;const $=N.scrollParents.reduce((ie,Qe)=>ie+Qe.element.scrollLeft-Qe.left,0),ee=N.scrollParents.reduce((ie,Qe)=>ie+Qe.element.scrollTop-Qe.top,0);return G>=N.rect.left-$&&G<=N.rect.right-$&&Le>=N.rect.top-ee+N.rect.height*.25&&Le<=N.rect.bottom-ee-N.rect.height*.25});if(qe?.background){qe.element.closest("[data-collaboration-group]")?.setAttribute("data-drop-active","true"),hn.current={kind:"collaboration",groupId:qe.groupId,background:!0};return}if(qe&&!v.find($=>$.sessionIds.includes(qe.sessionId))?.sessionIds.includes(mr.current??"")){qe.element.dataset.dropActive="true",hn.current={kind:"split",sessionId:qe.sessionId,groupId:qe.groupId};return}const At=document.elementsFromPoint(G,Le).filter(N=>{const $=N.closest("[data-rfd-draggable-id]");return!$||!["session:","split-member:","collaboration-member:"].some(ee=>$.dataset.rfdDraggableId===`${ee}${mr.current}`)}),Rt=At.map(N=>N.closest("[data-collaboration-group]")).find(N=>N?.dataset.collaborationGroup);if(Rt?.dataset.collaborationGroup){const N=Rt.dataset.collaborationGroup,$=At.map(ze=>ze.closest("[data-collaboration-split]")).find(Boolean),ee=At.map(ze=>ze.closest("[data-collaboration-member]")).find(Boolean),ie=ee?.dataset.collaborationMember??$?.dataset.splitAnchor,Qe=N===Tr.current&&v.some(ze=>ze.sessionIds.includes(ie??"")&&ze.sessionIds.includes(mr.current??""));if(ie&&!Qe&&(N!==Tr.current||!ee&&$)){Rt.dataset.dropActive="true";const ze=ee??$;ze&&(ze.dataset.dropActive="true"),hn.current={kind:"split",sessionId:ie,groupId:N}}else{const ze=At.some(xt=>xt.closest("[data-collaboration-background]"));(N!==Tr.current||ze)&&(Rt.dataset.dropActive="true"),hn.current={kind:"collaboration",groupId:N,background:ze}}return}const ot=Array.from(document.querySelectorAll("[data-sidebar-entity-list-id]")).filter(N=>N.dataset.sidebarEntityListId===bn.current).find(N=>{const $=N.getBoundingClientRect();return G>=$.left&&G<=$.right&&Le>=$.top-8&&Le<=$.bottom+8});if(!ot){hn.current=null;return}const Ft=Array.from(ot.children).filter(N=>N instanceof HTMLElement&&N.hasAttribute("data-sidebar-entity-index")),hr=Ft.findIndex(N=>{const $=N.getBoundingClientRect();return Le<$.top+$.height/2}),Kt=hr<0?Ft.length:hr;hn.current={kind:"list",listId:ot.dataset.sidebarEntityListId??"",index:Kt};const z=Array.from(ot.querySelectorAll(":scope > [data-sidebar-entity-index] > [data-split-exit-drop-index]")).find(N=>N.dataset.splitExitDropIndex===String(Kt));z instanceof HTMLElement&&(z.dataset.active="true")},[v]);b.useEffect(()=>{const G=Ke=>Br(Ke.clientX,Ke.clientY),Le=Ke=>{const ct=Ke.touches[0];ct&&Br(ct.clientX,ct.clientY)};return window.addEventListener("pointermove",G),window.addEventListener("touchmove",Le,{passive:!0}),()=>{window.removeEventListener("pointermove",G),window.removeEventListener("touchmove",Le)}},[Br]);const Mn=b.useCallback((G,Le)=>{try{G(Le)}finally{document.querySelectorAll("[data-sidebar-dragging]").forEach(Ke=>{delete Ke.dataset.sidebarDragging}),Ot.current=!1,dr.current=[],_n(!1),Tr.current=null,mr.current=null,bn.current=null,hn.current=null,document.querySelectorAll("[data-split-exit-drop-index]").forEach(Ke=>Ke.removeAttribute("data-active")),document.querySelectorAll("[data-drop-active]").forEach(Ke=>Ke.removeAttribute("data-drop-active"))}},[]),Sr=b.useMemo(()=>a.filter(G=>!pn.has(G.id)),[a,pn]),Kr=b.useMemo(()=>{let G=0;for(const Le of a)l.get(Le.id)?.agentStatus==="working"&&(G+=1);return G},[a,l]);b.useLayoutEffect(()=>{const G=Ir.current,Le=ne.current;if(!e||!G||!Le){ht.current=null;return}const Ke=Le.getBoundingClientRect(),ct=G.getBoundingClientRect(),qe={item:G,top:Math.round(ct.top-Ke.top+Le.scrollTop),height:Math.round(ct.height),viewportHeight:Le.clientHeight},At=ht.current;if(ht.current=qe,At?.item===qe.item&&At.top===qe.top&&At.height===qe.height&&At.viewportHeight===qe.viewportHeight||Ot.current||Le.clientHeight===0)return;const Rt=8,Bt=ct.top-Ke.top,ot=ct.bottom-Ke.top;Bt<Rt?Le.scrollTop+=Bt-Rt:ot>Le.clientHeight-Rt&&(Le.scrollTop+=ot-Le.clientHeight+Rt)});const nn=b.useMemo(()=>{if(!wt||!c)return null;const G=l.get(c)?.cwd??null;return $S(G)},[wt,c,l]);b.useEffect(()=>{if(!wt){ir.current=null,Tn.current.clear();return}if(!c){ir.current=null;return}const G=Gt.getState(),Le=Tn.current,Ke=ir.current,ct=nn;Ke!==null&&Ke!==ct&&Le.has(Ke)&&(G.collapsedGroups.has(Ke)||G.toggleGroupCollapsed(Ke),Le.delete(Ke)),ct!==null&&ct!==""&&G.collapsedGroups.has(ct)&&(G.toggleGroupCollapsed(ct),Le.add(ct)),ir.current=ct},[wt,c,nn]),b.useEffect(()=>{e||ue(!1)},[e]),b.useEffect(()=>{Lr(G=>({...G,command:ge?.command}))},[ge]),b.useEffect(()=>{if(!Ce)return;let G=!1;return Zt(!0),Lt(null),a2().then(Le=>{G||jt(Le)}).catch(()=>{G||Lt(_e("sidebar.resumeHistoryLoadFailed"))}).finally(()=>{G||Zt(!1)}),()=>{G=!0}},[Ce,_e]),b.useEffect(()=>{if(!re)return;const G=Le=>{Le instanceof KeyboardEvent&&Le.key!=="Escape"||Le instanceof PointerEvent&&Le.target instanceof Node&&xn.current?.contains(Le.target)||Oe(null)};return window.addEventListener("pointerdown",G),window.addEventListener("keydown",G),()=>{window.removeEventListener("pointerdown",G),window.removeEventListener("keydown",G)}},[re]);const Fr=()=>{!ke&&!$e&&r()};b.useEffect(()=>{const G=Le=>{ue(!1);const{groupId:Ke,dock:ct}=Le.detail;oe.current=!0,es.getState().setDock(Ke,{...ct,preferredWidth:360}),Te(qe=>({...qe,[Ke]:!0})),la.getState().terminal(),Fr()};return window.addEventListener("termdock:open-collaboration-messages",G),()=>window.removeEventListener("termdock:open-collaboration-messages",G)},[Fr]);const ks=te==="tmux"&&!pe?"shell":te,Or=(G,Le=!1)=>{if(rt.current)return;rt.current=!0,Ne(!0),He(null);const Ke=mt.current;p({...G,shouldActivate:()=>Ke===mt.current&&(G.shouldActivate?.()??!0),onResult:ct=>{if(rt.current=!1,Ne(!1),!ct.ok){He(ct.error);return}Ke===mt.current&&(Le&&ue(!1),Fr())}})},Xr=()=>{Or({mode:ks})},fn=()=>{ge&&Or({mode:ks,command:ge.command})},K=G=>{ue(!1),Ge(G.name),p({mode:"tmux",tmuxSessionName:G.name,cwd:G.cwd??void 0}),Fr()};b.useEffect(()=>{me&&(Ae.some(G=>G.name===me)||Ge(null))},[me,Ae]);const Ue=(G,Le)=>{Or({...cn,cwd:cn.cwd?.trim()||void 0,command:Le??G?.command},!0)},Et=async G=>{Xt(G.id),Lt(null);try{const Le=await ky(G.id);Or({mode:"shell",cwd:Le.cwd,command:Le.command},!0)}catch(Le){const Ke=Le&&typeof Le=="object"&&"code"in Le?String(Le.code??""):"";Lt(_e(Ke==="AGENT_SESSION_ACTIVE_ELSEWHERE"?"tab.resumeAgentConflict":"sidebar.resumeHistoryFailed"))}finally{Xt(null)}},kt=async G=>{jt(Le=>Le.filter(Ke=>Ke.id!==G));try{await o9(G)}catch{Lt(_e("sidebar.resumeHistoryRemoveFailed")),a2().then(jt).catch(()=>{})}},tr=()=>{if(Ce){ue(!1);return}rt.current||(mt.current+=1,rt.current||He(null),Lr({mode:te==="tmux"&&!pe?"shell":te,cwd:c?l.get(c)?.cwd??void 0:void 0,command:ge?.command}),ue(!0))},Qr=b.useCallback(G=>{const Le=l.get(G);return Le?.agentStatus==="waiting"||Le?.agentNeedsReview?"bg-[rgb(var(--warning-rgb)_/_0.10)] text-foreground":Le?.agentStatus==="working"?"bg-[rgb(var(--success-rgb)_/_0.08)] text-foreground":Le?.inCopyMode?"bg-[rgb(var(--tmux-rgb)_/_0.08)] text-foreground":null},[l]),cr=g6(),[Sn,Ls]=b.useState(null);b.useEffect(()=>{e||Ls(null)},[e]);const Zn=b.useCallback((G,Le,Ke,ct,qe)=>{const At=!Ie&&G.id===c,Rt=pn.has(G.id),Bt=!!(Ke&&Rt),ot=l.get(G.id),Ft=Yu(ot?.cwd??null),hr=ot?.shellTitle??Jw(G.id),Kt=hr===ot?.cwd||hr===Ft?null:hr,z=e9(G,ot?.activeProgram??null,null,t9,Kt,ot?.promptState??null),N=!!(ot?.tuiProgress&&ot.tuiProgress.state!=="remove"),ee=ot?.promptState==="running"||ot?.agentStatus==="working"||N?"bg-[var(--success)]":ot?.agentStatus==="waiting"||ot?.agentNeedsReview?"bg-[var(--warning)]":ot?.inCopyMode?"bg-[var(--tmux)]":"bg-primary";return s.jsxs(JO,{open:Sn===G.id,onOpenChange:ie=>Ls(Qe=>ie?G.id:Qe===G.id?null:Qe),onClose:ie=>m(G.id,ie,{skipConfirmation:!0}),closeLabel:_e("common.close"),closeTitle:_e("sidebar.closeSession",{name:z}),compact:Ke,children:[s.jsxs("button",{ref:At?Ir:null,type:"button",...Le??{},onContextMenu:ie=>{B&&(ie.preventDefault(),B(G.id,{x:ie.clientX,y:ie.clientY}))},onClick:()=>{ue(!1),la.getState().terminal(),window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:G.id})),Fr()},className:`sidebar-session-primary relative min-w-0 flex flex-1 items-center overflow-hidden text-left ${Le?"cursor-grab active:cursor-grabbing ":""}${Ke?"gap-1.5 py-0.5 pl-1.5 pr-0.5":"gap-1.5 py-1 pl-2 pr-1"}`,title:ot?.cwd??G.name,children:[At&&s.jsx("span",{className:`absolute inset-y-2 left-0 w-0.5 rounded-full ${ee}`}),s.jsxs("span",{className:`relative inline-flex shrink-0 items-center justify-center rounded-md ${Ke?"h-5 w-[22px]":"h-[22px] w-[22px]"} ${At?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:[ot?.isConnecting||N&&!ot?.agentStatus?s.jsx(Cn,{size:Ke?10:11,className:"animate-spin"}):ot?.agent??o2(G.id)?s.jsx(Wc,{agent:ot?.agent??o2(G.id),size:Ke?13:15}):G.mode==="tmux"?s.jsx(Uu,{size:Ke?10:11}):s.jsx(Fo,{size:Ke?10:11}),s.jsx(rF,{status:ot?.agentStatus??null,detail:ot?.agentStatusDetail,needsReview:ot?.agentNeedsReview,inCopyMode:ot?.inCopyMode})]}),s.jsx("span",{className:`min-w-0 flex-1 truncate leading-tight ${Ke?"text-[11px]":"text-[12px]"} ${At?"font-medium text-foreground":""} ${ot?.inCopyMode?"text-[color:var(--tmux)]":""}`,children:z}),s.jsx(O5,{sessionIds:[G.id]})]}),ct,s.jsx("button",{type:"button",onClick:ie=>{ie.stopPropagation(),Bt?w(G.id):Rt?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 ${Ke?"h-6 w-6":"h-[26px] w-[26px]"} ${Rt?"bg-primary/15 text-primary":"text-muted-foreground/70"}`,"aria-label":`${_e(Bt?"tab.splitRemovePane":Rt?"tab.splitClose":"tab.split")} ${z}`,title:_e(Bt?"tab.splitRemovePane":Rt?"tab.splitClose":"tab.split"),children:Bt?s.jsx(ES,{size:11}):s.jsx(Il,{size:12})}),qe??s.jsx("button",{type:"button",onClick:ie=>{ie.stopPropagation(),m(G.id,ie)},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 ${Ke?"h-6 w-6":"h-[26px] w-[26px]"}`,"aria-label":_e("sidebar.closeSession",{name:z}),title:_e("common.close"),children:s.jsx(Rn,{size:Ke?11:12})})]})},[c,pn,l,m,x,y,w,B,_e,Sn]),sn=b.useMemo(()=>lf(a,G=>l.get(G.id)?.cwd??null,wt,_e("sidebar.ungrouped"),v,qr).groups,[qr,wt,a,l,v,_e]),on=b.useMemo(()=>Od(a,v,Pr,qr),[qr,a,Pr,v]),_r=b.useCallback(G=>{_n(G.draggableId.startsWith("collaboration:")||G.draggableId.startsWith("workspace:"));const Le=G.draggableId.replace(/^split-member:/,"");mr.current=G.draggableId.replace(/^(?:session|split-member|collaboration-member):/,"");const Ke=G.type==="split-member"?v.find(Bt=>Bt.sessionIds.includes(Le)):null,ct=G.type==="collaboration-member"?G.source.droppableId.replace(/^collaboration-members:/,""):null,qe=ct?qr.find(Bt=>Bt.id===ct):null;Ot.current=!!(Ke||qe||G.type==="session"&&G.draggableId.startsWith("session:")),Ot.current&&document.querySelectorAll("[data-collaboration-group]").forEach(Bt=>{Bt.dataset.sidebarDragging="true"}),Tr.current=qe?.id??null;const At=Ke?.sessionIds??qe?.sessionIds??[],Rt=At.length>0?sn.find(Bt=>At.every(ot=>Bt.sessions.some(Ft=>Ft.id===ot))):null;bn.current=wt?Rt?`group-sessions:${Rt.key}`:null:At.length>0?"sidebar-entities":null,hn.current=null},[qr,sn,wt,v]),$r=b.useCallback((G,Le,Ke)=>{if(Le===Ke)return;const ct=Le?nr.find(ot=>ot.id===Le):null,qe=Ke?nr.find(ot=>ot.id===Ke):null;if(Ke&&!qe)return;if(qe){const ot=a.map(hr=>hr.id).filter(hr=>hr!==G);let Ft=-1;ot.forEach((hr,Kt)=>{qe.sessionIds.includes(hr)&&(Ft=Kt)}),Ft>=0&&(ot.splice(Ft+1,0,G),R(ot))}const At=ct?.sessionIds.filter(ot=>ot!==G)??[],Rt=qe?[...qe.sessionIds.filter(ot=>ot!==G),G]:[];Cr(ot=>ot.flatMap(Ft=>Ft.id===Le?[{...Ft,sessionIds:At}]:Ft.id===Ke?[{...Ft,sessionIds:Rt}]:[Ft])),q(null),(ct&&qe?r9({sourceGroupId:ct.id,targetGroupId:qe.id,sessionId:G,expectedSourceUpdatedAt:ct.updatedAt,expectedTargetUpdatedAt:qe.updatedAt}):ct?ac({id:ct.id,name:ct.name,sessionIds:At,expectedUpdatedAt:ct.updatedAt}):qe?ac({id:qe.id,name:qe.name,sessionIds:Rt,expectedUpdatedAt:qe.updatedAt}):Promise.resolve()).then(()=>Wr(),ot=>(q(ot instanceof Error?ot.message:"协作成员移动失败"),Wr()))},[nr,Wr,a,R]),Wn=b.useCallback((G,Le,Ke,ct=!1)=>{const qe=nr.find($=>$.id===G);if(!qe||Le===Ke)return;const At=qe.sessionIds.filter($=>!$.startsWith("remote:")),Rt=Pd(At,v).flatMap($=>$.sessionIds),Bt=Q5(qt,qe.id),ot=ct&&!Nt[qe.id]?Rt.filter($=>!Bt.has($)||$===c||pn.has($)):Rt.slice(),Ft=new Set(ot),[hr]=ot.splice(Le,1);if(!hr)return;ot.splice(Ke,0,hr);let Kt=0;const z=Rt.map($=>Ft.has($)?ot[Kt++]:$),N=v.find($=>$.sessionIds.includes(hr));if(N&&N.sessionIds.every($=>qe.sessionIds.includes($))){const $=z.filter(ee=>N.sessionIds.includes(ee));L(N.id,$)}z.push(...qe.sessionIds.filter($=>$.startsWith("remote:"))),Cr($=>$.map(ee=>ee.id===G?{...ee,sessionIds:z}:ee)),q(null),ac({id:qe.id,name:qe.name,sessionIds:z,expectedUpdatedAt:qe.updatedAt}).then(()=>Wr(),$=>(q($ instanceof Error?$.message:"成员排序失败"),Wr()))},[nr,Wr,v,L,qt,Nt,c,pn]);b.useEffect(()=>{const G=Le=>{const{sourceId:Ke,targetId:ct}=Le.detail;if(!Ke||!ct||Ke===ct)return;const qe=lf(a,ie=>l.get(ie.id)?.cwd??null,wt,"",v,qr).arranged.map(ie=>ie.id),At=qe.indexOf(Ke),Rt=qe.indexOf(ct);if(At<0||Rt<0)return;const Bt=qr.find(ie=>ie.sessionIds.includes(Ke));if(Bt?.sessionIds.includes(ct)){const ie=Pd(Bt.sessionIds,v).flatMap(Qe=>Qe.sessionIds);Wn(Bt.id,ie.indexOf(Ke),ie.indexOf(ct));return}const ot=v.filter(ie=>ie.sessionIds.length>=2&&ie.sessionIds.every(Qe=>Pr.has(Qe))&&!qr.some(Qe=>ie.sessionIds.some(ze=>Qe.sessionIds.includes(ze)))),Ft=ot.find(ie=>ie.sessionIds.includes(Ke));if(Ft?.sessionIds.includes(ct)){const ie=[...Ft.sessionIds];ie.splice(ie.indexOf(Ke),1),ie.splice(Ft.sessionIds.indexOf(ct),0,Ke),L(Ft.id,ie);return}const hr=ie=>qr.find(Qe=>Qe.sessionIds.includes(ie))?.sessionIds??ot.find(Qe=>Qe.sessionIds.includes(ie))?.sessionIds??[ie],Kt=new Set(hr(Ke)),z=new Set(hr(ct)),N=qe.filter(ie=>!Kt.has(ie)),$=N.flatMap((ie,Qe)=>z.has(ie)?[Qe]:[]),ee=At<Rt?Math.max(...$)+1:Math.min(...$);N.splice(ee,0,...qe.filter(ie=>Kt.has(ie))),R(N)};return window.addEventListener("reorder-navigation-session",G),()=>window.removeEventListener("reorder-navigation-session",G)},[a,l,wt,v,qr,Pr,Wn,L,R]);const Gn=b.useCallback(G=>{if(G.type!=="collaboration-member")return!1;if(G.reason==="CANCEL")return!0;const Le=G.source.droppableId.replace(/^collaboration-members:/,""),Ke=G.draggableId.replace(/^collaboration-member:/,""),ct=hn.current;if(ct?.kind==="split")return $r(Ke,Le,ct.groupId),E(ct.sessionId,Ke),!0;if(ct?.kind==="collaboration"&&ct.groupId!==Le)return $r(Ke,Le,ct.groupId),!0;if(ct?.kind==="collaboration"&&ct.background)return pn.has(Ke)&&w(Ke),!0;if(G.destination&&G.destination.droppableId!==G.source.droppableId){const qe=G.destination.droppableId.replace(/^collaboration-members:/,"");if(qr.some(At=>At.id===qe))return $r(Ke,Le,qe),!0}if(G.combine){const qe=G.combine.droppableId.replace(/^collaboration-members:/,"");qe!==Le&&$r(Ke,Le,qe);const At=G.combine.draggableId.replace(/^collaboration-member:/,"");if(v.find(Bt=>Bt.sessionIds.includes(Ke))?.sessionIds.includes(At)){const Bt=qr.find(Ft=>Ft.id===Le),ot=Bt?Pd(Bt.sessionIds,v).flatMap(Ft=>Ft.sessionIds).indexOf(At):-1;ot>=0&&Bt&&Wn(Le,Pd(Bt.sessionIds,v).flatMap(Ft=>Ft.sessionIds).indexOf(Ke),ot)}else Pr.has(At)&&E(At,Ke);return!0}if(G.destination?.droppableId===G.source.droppableId)return Wn(Le,G.source.index,G.destination.index,!0),!0;if(ct?.kind!=="list")return!0;if(ct?.kind==="list"){const qe=sn.find(Rt=>`group-sessions:${Rt.key}`===ct.listId),At=ct.listId==="sidebar-entities"?on:qe?Od(qe.sessions,v,Pr,qr):null;if(At){const Rt=Rb(At,Ke,ct.index);ct.listId==="sidebar-entities"?R(Rt):qe&&R(sn.flatMap(Bt=>Bt.key===qe.key?Rt:Bt.sessions.map(ot=>ot.id)))}}return $r(Ke,Le,null),!0},[qr,on,sn,$r,R,Wn,Pr,v,pn,w,E]),un=b.useCallback(G=>{if(G.type!=="split-member")return!1;if(G.reason==="CANCEL")return!0;const Le=G.draggableId.replace(/^split-member:/,""),Ke=v.find(ot=>ot.sessionIds.includes(Le));if(!Ke?.sessionIds.includes(Le))return!0;const ct=Ke.id,qe=hn.current;if(qe?.kind==="split")return $r(Le,null,qe.groupId),E(qe.sessionId,Le),!0;if(qe?.kind==="collaboration")return $r(Le,null,qe.groupId),!0;if(!G.destination&&qe?.kind==="list"){const ot=sn.find(Kt=>`group-sessions:${Kt.key}`===qe.listId),Ft=qe.listId==="sidebar-entities"?on:ot?Od(ot.sessions,v,Pr,qr):null;if(!Ft)return!0;const hr=Rb(Ft,Le,qe.index);return w(Le),qe.listId==="sidebar-entities"?R(hr):ot&&R(sn.flatMap(Kt=>Kt.key===ot.key?hr:Kt.sessions.map(z=>z.id))),!0}if(!G.destination)return!0;const At=G.destination.droppableId.replace(/^split-members:/,"");if(At!==ct){const Ft=v.find(hr=>hr.id===At)?.sessionIds[0];return Ft&&E(Ft,Le),!0}if(G.source.index===G.destination.index)return!0;const Rt=[...Ke.sessionIds],[Bt]=Rt.splice(G.source.index,1);return Bt&&(Rt.splice(G.destination.index,0,Bt),L(ct,Rt)),!0},[qr,on,sn,$r,E,w,R,L,Pr,v]),Kn=(G,Le="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 ${Le==="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,Le,Ke)=>{if(Gn(G)||un(G)||G.reason==="CANCEL")return;const ct=Le.find(ot=>ot.id===G.draggableId);if(!ct)return;const qe=hn.current;if(qe?.kind==="split"&&ct.kind==="session"){$r(ct.session.id,null,qe.groupId),E(qe.sessionId,ct.session.id);return}if(qe?.kind==="collaboration"&&ct.kind==="session"){$r(ct.session.id,null,qe.groupId);return}if(G.combine&&ct.kind!=="session"){const ot=Le.findIndex(Ft=>Ft.id===G.combine?.draggableId);if(ot<0)return;G={...G,combine:null,destination:{...G.source,index:ot}}}if(G.combine){const ot=Le.find(N=>N.id===G.combine?.draggableId);if(!ot)return;const Ft=ot.kind==="workspace"?ot:ct.kind==="workspace"?ct:ot,hr=Ft===ct?ot:ct,Kt=Ft.sessionIds[0],z=hr.sessionIds[0];Kt&&z&&Kt!==z&&E(Kt,z);return}if(!G.destination||G.source.index===G.destination.index)return;const At=[...Le],[Rt]=At.splice(G.source.index,1);if(!Rt)return;At.splice(G.destination.index,0,Rt);const Bt=At.flatMap(ot=>ot.sessionIds);if(Ke===void 0){R(Bt);return}R(sn.flatMap(ot=>ot.key===Ke?Bt:ot.sessions.map(Ft=>Ft.id)))},[sn,Gn,un,$r,E,R]),Er=b.useCallback(G=>{if(G.reason==="CANCEL"||Gn(G)||un(G))return;if(G.type==="group"){if(!G.destination||G.source.index===G.destination.index)return;R(Uy(sn,G.source.index,G.destination.index));return}const Le=G.source.droppableId.replace(/^group-sessions:/,""),Ke=sn.find(qe=>qe.key===Le);if(!Ke)return;const ct=Od(Ke.sessions,v,Pr,qr);if(G.combine||hn.current?.kind==="collaboration"||hn.current?.kind==="split"){kr(G,ct,Le);return}!G.destination||G.destination.droppableId!==G.source.droppableId||kr(G,ct,Le)},[qr,sn,Pr,v,Gn,kr,un,R]),gr=G=>{const Le=re===G.id,Ke=[{layout:"horizontal",label:_e("tab.splitHorizontal"),icon:Il},{layout:"vertical",label:_e("tab.splitVertical"),icon:h2},...G.sessionIds.length>=3||G.layout==="grid"?[{layout:"grid",label:_e("tab.splitGrid"),icon:d2}]:[]],ct=G.layout==="vertical"?h2:G.layout==="grid"?d2:Il,qe=Ke.find(At=>At.layout===G.layout)?.label??_e("tab.splitHorizontal");return s.jsxs("div",{ref:Le?xn:void 0,className:"relative shrink-0",onPointerDown:At=>At.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 ${Le?"bg-primary/15 text-primary":"text-muted-foreground/70 hover:bg-surface-2 hover:text-foreground"}`,"aria-label":`${_e("tab.splitLayout")}: ${qe}`,"aria-haspopup":"menu","aria-expanded":Le,title:_e("tab.splitLayout"),onClick:At=>{At.stopPropagation(),Oe(Rt=>Rt===G.id?null:G.id)},children:s.jsx(ct,{size:12})}),Le&&s.jsx("div",{role:"menu","aria-label":_e("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:Ke.map(At=>{const Rt=At.icon,Bt=At.layout===G.layout;return s.jsx("button",{type:"button",role:"menuitemradio","aria-checked":Bt,"aria-label":At.label,title:At.label,className:`sidebar-session-action inline-flex h-7 w-7 items-center justify-center rounded-sm transition active:scale-95 ${Bt?"bg-primary/15 text-primary":"text-muted-foreground hover:bg-surface-2 hover:text-foreground"}`,onClick:ot=>{ot.stopPropagation(),S(G.sessionIds[0],At.layout),Oe(null)},children:s.jsx(Rt,{size:13})},At.layout)})})]})},rs=(G,Le)=>Le&&s.jsx("button",{type:"button",...Le,"aria-label":G,title:G,onClick:Ke=>Ke.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(Ff,{size:10})}),$n=(G,Le,Ke=!1,ct=!1,qe)=>{if(Le.length<2)return null;const At=Le.some(Kt=>Kt.id===c),Rt=[],Bt=[],ot=[];for(const Kt of Le){const z=l.get(Kt.id);z?.agentStatus==="waiting"||z?.agentNeedsReview?Rt.push(Kt):z?.agentStatus==="working"?Bt.push(Kt):z?.inCopyMode&&ot.push(Kt)}const Ft=G.name?.trim()||`${_e("tab.splitWorkspace")} ${v.findIndex(Kt=>Kt.id===G.id)+1}`,hr=re===G.id;return s.jsxs("section",{"data-split-workspace":G.id,"aria-label":Ft,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 ${ct?"bg-primary/15 ring-1 ring-primary/40":Ke?"bg-surface-elevated opacity-90 shadow-lg":Rt.length>0?"bg-[rgb(var(--warning-rgb)_/_0.08)] hover:bg-[rgb(var(--warning-rgb)_/_0.12)]":Bt.length>0?"bg-[rgb(var(--success-rgb)_/_0.06)] hover:bg-[rgb(var(--success-rgb)_/_0.10)]":ot.length>0?"bg-[rgb(var(--tmux-rgb)_/_0.07)] hover:bg-[rgb(var(--tmux-rgb)_/_0.11)]":At?"bg-primary/[0.07]":"hover:bg-surface-2"}`,children:[rs(`移动分屏组 ${Ft}`,qe),s.jsx(Ll,{droppableId:`split-members:${G.id}`,type:"split-member",direction:"vertical",children:(Kt,z)=>s.jsxs("div",{ref:Kt.innerRef,...Kt.droppableProps,"data-split-members":!0,className:z.isDraggingOver?"rounded-sm bg-primary/10 ring-1 ring-primary/40":"",children:[Le.map((N,$)=>s.jsx(kl,{draggableId:`split-member:${N.id}`,index:$,disableInteractiveElementBlocking:!0,children:(ee,ie)=>s.jsx("div",{ref:ee.innerRef,...ee.draggableProps,...B?cr(()=>B(N.id)):{},className:`${$===0&&hr?"relative z-20 ":"relative "}flex items-center rounded-sm pr-0.5 transition-colors ${ie.isDragging?"bg-surface-elevated opacity-90 shadow-lg ":""}${Qr(N.id)??(N.id===c?"bg-surface-elevated/80 text-foreground":"text-muted-foreground hover:bg-surface-2")}`,children:Zn(N,ee.dragHandleProps,!0,$===0?gr(G):void 0)})},N.id)),Kt.placeholder]})})]})},kn=(G,Le,Ke,ct=!1,qe=!1)=>{const At=`collaboration:${G.id}`,Rt=Rr.has(At),Bt=`collaboration-members-${G.id}`,ot=Ie===G.id||!Ie&&Le.some(ie=>ie.id===c),Ft=Q5(qt,G.id),hr=G.sessionIds.filter(ie=>Ft.has(ie)&&ie!==c&&!pn.has(ie)),Kt=Nt[G.id]===!0,z=Kt?G.sessionIds:G.sessionIds.filter(ie=>!hr.includes(ie)),N=Pd(z,v),$=N.flatMap(ie=>ie.sessionIds),ee=N.length===1?N[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 ${Rt?"":"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 ${qe?"bg-primary/15 ring-1 ring-primary/40":ct?"bg-surface-elevated opacity-90 shadow-lg":ot?"bg-primary/[0.07]":"hover:bg-surface-2"}`,children:[rs(`移动工作组 ${G.name}`,Ke),s.jsxs("div",{className:"flex items-center",children:[s.jsx("button",{type:"button","aria-label":`${Rt?"展开":"收起"} ${G.name} 的成员会话`,"aria-expanded":!Rt,"aria-controls":Bt,title:`${Rt?"展开":"收起"}成员会话`,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:ie=>{ie.stopPropagation(),rn(At)},children:s.jsx(fi,{size:14,className:Rt?"":"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:ie=>{ie.stopPropagation(),pr(G.id)},children:[s.jsx(rh,{size:14,className:"shrink-0 text-primary"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:G.name}),at.some(ie=>ie.groupId===G.id)&&s.jsxs("span",{className:"shrink-0 text-[10px] font-normal text-primary",children:[at.filter(ie=>ie.groupId===G.id).length," 待处理"]})]}),s.jsx("button",{type:"button","aria-label":`成员与消息:${G.name}`,title:"在终端旁打开成员与消息",disabled:Ze!==null||!c&&!Le.length,"aria-busy":Ze===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:ie=>{ie.stopPropagation(),!be.current&&(ue(!1),be.current=!0,Je(G.id),q(null),lC(G.id,c??Le[0].id).catch(Qe=>q(Qe instanceof Error?Qe.message:"消息面板打开失败,请重试")).finally(()=>{be.current=!1,Je(null)}))},children:Ze===G.id?s.jsx(gn,{size:14,className:"animate-spin"}):s.jsx(N0,{size:14})})]}),s.jsx("div",{id:Bt,children:!Rt&&s.jsxs(s.Fragment,{children:[hr.length>0&&s.jsxs("button",{type:"button","aria-expanded":Kt,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:()=>gt(ie=>({...ie,[G.id]:!Kt})),children:[s.jsx(fi,{size:12,className:Kt?"rotate-90":""}),"已完成的执行会话 · ",hr.length]}),s.jsx(Ll,{droppableId:`collaboration-members:${G.id}`,type:"collaboration-member",direction:"vertical",isCombineEnabled:!0,children:(ie,Qe)=>s.jsxs("div",{ref:ie.innerRef,...ie.droppableProps,"data-collaboration-members":!0,className:`${Qe.isDraggingOver?"rounded-sm bg-primary/10":""}`,children:[N.map(ze=>s.jsx("div",{"data-collaboration-split":ze.workspace?.id,"data-split-anchor":ze.workspace?.sessionIds[0],role:ze.workspace?"region":void 0,"aria-label":ze.workspace?`${_e("tab.splitWorkspace")} · ${ze.sessionIds.length}`:void 0,className:ze.workspace&&!ee?`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 ${ze.sessionIds.includes(c??"")?"bg-primary/[0.07]":"bg-surface/35"}`:void 0,children:ze.sessionIds.map(xt=>{const _t=Pr.get(xt);return _t?s.jsx(kl,{draggableId:`collaboration-member:${_t.id}`,index:$.indexOf(_t.id),disableInteractiveElementBlocking:!0,children:(Mr,Dt)=>s.jsxs("div",{ref:Mr.innerRef,...Mr.draggableProps,"data-collaboration-member":_t.id,"data-split-member":pn.has(_t.id)?"true":void 0,...B?cr(()=>B(_t.id)):{},className:`${ze.workspace&&xt===ze.sessionIds[0]&&re===ze.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 ${Dt.combineTargetFor?"bg-primary/15 ring-1 ring-primary/40 ":Dt.isDragging?"bg-surface-elevated opacity-90 shadow-lg ":""}${Qr(_t.id)??(_t.id===c?"bg-surface-elevated/80 text-foreground":pn.has(_t.id)?"bg-primary/[0.05] text-muted-foreground hover:bg-primary/[0.09]":"text-muted-foreground hover:bg-surface-2")}`,children:[Zn(_t,Mr.dragHandleProps,!0,ze.workspace&&xt===ze.sessionIds[0]?gr(ze.workspace):void 0,Ft.has(xt)?s.jsxs("button",{type:"button","aria-label":`归档 ${_t.name}`,title:"保存 Agent 会话 ID 并停止终端;只回收干净的执行目录,结果和分支保留",disabled:er!==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:Gr=>{Gr.stopPropagation(),!Ct.current&&(Ct.current=!0,et(xt),q(null),a9(xt).then(async()=>{De(dn=>dn+1),await Wr()}).catch(dn=>q(dn instanceof Error?dn.message:"归档失败,终端已保留")).finally(()=>{Ct.current=!1,et(null)}))},children:[er===xt?s.jsx(gn,{size:13,className:"animate-spin"}):s.jsx(Ly,{size:13}),s.jsx("span",{className:"text-[10px] md:sr-only",children:"归档"})]}):void 0),!ze.workspace&&pn.has(_t.id)&&s.jsx("button",{type:"button",className:"shrink-0 px-1 text-[10px] text-primary",title:`与 ${v.find(Gr=>Gr.sessionIds.includes(_t.id))?.sessionIds.filter(Gr=>Gr!==_t.id).map(Gr=>Pr.get(Gr)?.name??Gr).join("、")} 分屏`,"aria-label":`查看 ${_t.name} 的跨组分屏`,onClick:()=>{ue(!1),la.getState().terminal(),window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:_t.id})),Fr()},children:s.jsx(Il,{size:10})})]})},_t.id):null})},ze.workspace?.id??ze.sessionIds[0])),ie.placeholder]})}),s.jsx(XB,{groupId:G.id,version:Ve,onRestore:async ie=>{ue(!1),window.dispatchEvent(new CustomEvent("new-terminal-session",{detail:{mode:"tmux",cwd:ie.cwd,preferredFrontendSessionId:ie.sessionId,requireExisting:!0}})),await Wr(),la.getState().terminal(),Fr()}}),G.remoteSessions?.map(ie=>s.jsxs("button",{type:"button",title:`${uc(ie)} · ${ie.serviceConnected===!1?"服务不可达,消息尚未送达":ie.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),b6(ie.sessionId).catch(()=>{pr(G.id)})},children:[s.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${ie.serviceConnected===!1?"bg-muted-foreground":"bg-primary"}`}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:ie.name}),s.jsx("span",{className:"max-w-20 truncate rounded border border-border/20 px-1 text-[9px]",children:uc(ie)}),ie.serviceConnected===!1&&s.jsx("span",{className:"shrink-0 text-[9px]",children:"不可达"})]},ie.sessionId))]})}),s.jsx("div",{"data-collaboration-background":!0,className:Rt?"absolute inset-0 pointer-events-none":"h-1.5"})]})},Ln=(G,Le,Ke)=>s.jsx(c0,{onBeforeCapture:fs,onDragStart:_r,onDragEnd:ct=>Mn(qe=>kr(qe,G,Ke),ct),children:s.jsx(Ll,{droppableId:Le,direction:"vertical",isCombineEnabled:!Hr,children:ct=>s.jsxs("div",{ref:ct.innerRef,...ct.droppableProps,"data-sidebar-entity-list-id":Le,className:"flex-1 space-y-0.5",children:[G.map((qe,At)=>s.jsx(kl,{draggableId:qe.id,index:At,disableInteractiveElementBlocking:!0,children:(Rt,Bt)=>s.jsxs("div",{ref:Rt.innerRef,...Rt.draggableProps,"data-sidebar-gesture-ignore":!0,"data-sidebar-entity-index":At,className:"relative",children:[Kn(At),At===G.length-1&&Kn(G.length,"bottom"),qe.kind==="workspace"?$n(qe.workspace,qe.members,Bt.isDragging,!!Bt.combineTargetFor,Rt.dragHandleProps):qe.kind==="collaboration"?kn(qe.group,qe.members,Rt.dragHandleProps,Bt.isDragging,!!Bt.combineTargetFor):s.jsx("div",{...B?cr(()=>B(qe.session.id)):{},className:`group relative flex items-center gap-1 rounded-md pr-1 transition-colors ${Bt.combineTargetFor?"bg-primary/15 text-foreground ring-1 ring-primary/40":Bt.isDragging?"bg-surface-elevated text-foreground opacity-90 shadow-lg":Qr(qe.session.id)??(!Ie&&qe.session.id===c?"bg-surface-elevated text-foreground":"text-muted-foreground hover:bg-surface-2")} cursor-grab active:cursor-grabbing`,children:Zn(qe.session,Rt.dragHandleProps)})]})},qe.id)),ct.placeholder]})})}),ps=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:_e("sidebar.sessions")}),s.jsx("span",{className:"text-[11px] text-muted-foreground",children:a.length}),Kr>0&&s.jsx("span",{className:"ml-0.5 flex items-center",children:s.jsx(j6,{count:Kr,tone:"running",title:_e("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),pr(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(rh,{size:16})}),(!ke||$e)&&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":_e("common.close"),children:s.jsx(Rn,{size:16})})]})]})]}),pt&&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:pt}),s.jsx("button",{type:"button","aria-label":"关闭协作错误提示",className:"shrink-0",onClick:()=>q(null),children:s.jsx(Rn,{size:14})})]}),s.jsxs("div",{ref:ne,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:[(at.length>0||bt)&&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":It,onClick:()=>yt(G=>!G),children:[s.jsx(rh,{size:14}),s.jsx("span",{className:"min-w-0 flex-1",children:"需要你处理"}),s.jsx("span",{children:at.length}),s.jsx(fi,{size:12,className:It?"rotate-90":""})]}),It&&s.jsxs("div",{className:"space-y-1 p-1 pt-0",children:[bt&&s.jsxs("p",{role:"alert",className:"px-2 py-2 text-[11px] text-destructive",children:[bt,s.jsx("button",{type:"button",className:"ml-2 text-primary",onClick:()=>{_u.getState().refresh()},children:"重试"})]}),at.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:()=>{P5(G.groupId,G.id),pr(G.groupId).then(Le=>{Le&&P5(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:[nr.find(Le=>Le.id===G.groupId)?.name??"协作组"," · ",Yc(G)]})]},G.id))]})]}),s.jsx(eF,{sessions:Ae,loading:lt,attachingName:me,onRefresh:Se,onRestore:K,onClose:ye}),qr.filter(G=>!G.sessionIds.length).map(G=>s.jsx(c0,{onDragEnd:()=>{},children:kn(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(Fo,{size:26,className:"mx-auto mb-2 text-muted-foreground"}),s.jsx("p",{className:"text-[12px] text-muted-foreground",children:_e("sidebar.noSessions")})]}):Sr.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:_e("sidebar.noMatchingSessions")})}):wt?s.jsx("div",{className:"flex flex-1 flex-col",children:s.jsx(c0,{onBeforeCapture:fs,onDragStart:_r,onDragEnd:G=>Mn(Er,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:[sn.map((Le,Ke)=>{const ct=Rr.has(Le.key),qe=!ct&&Ke===sn.length-1,At=Od(Le.sessions,v,Pr,qr);let Rt=0,Bt=0;for(const Ft of Le.sessions){const hr=l.get(Ft.id);hr?.agentStatus==="working"&&(Rt+=1),(hr?.agentStatus==="waiting"||hr?.agentNeedsReview)&&(Bt+=1)}const ot=Le.key==="";return s.jsx(kl,{draggableId:`sidebar-group:${Le.key||"__ungrouped__"}`,index:Ke,isDragDisabled:ot,disableInteractiveElementBlocking:!0,children:(Ft,hr)=>s.jsxs("div",{ref:Ft.innerRef,...Ft.draggableProps,className:`shrink-0 rounded-md transition-colors ${qe?"flex flex-1 flex-col ":""}${hr.isDragging?"bg-surface-elevated shadow-lg opacity-90":""}`,children:[s.jsxs("button",{type:"button",...ot?{}:Ft.dragHandleProps,onClick:()=>{rn(Le.key),Tn.current.delete(Le.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 ${ot?"":"cursor-grab active:cursor-grabbing"}`,title:Le.key||Le.label,children:[s.jsx(fi,{size:13,className:`shrink-0 transition-transform ${ct?"":"rotate-90"}`}),s.jsx("span",{className:"min-w-0 flex-1 truncate text-[11.5px] font-semibold uppercase tracking-wide",children:Le.label}),Rt>0&&s.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--success)] animate-pulse"}),Bt>0&&s.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--warning)] animate-pulse"}),s.jsx(O5,{sessionIds:Le.sessions.map(Kt=>Kt.id)}),s.jsx("span",{className:"shrink-0 text-[10.5px] text-muted-foreground/70",children:Le.sessions.length})]}),!ct&&s.jsx("div",{className:`mt-0.5 pl-2 ${qe?"flex flex-1 flex-col":""}`,children:s.jsx(Ll,{droppableId:`group-sessions:${Le.key}`,type:"session",direction:"vertical",isCombineEnabled:!Hr,children:Kt=>s.jsxs("div",{ref:Kt.innerRef,...Kt.droppableProps,"data-sidebar-entity-list-id":`group-sessions:${Le.key}`,className:`${qe?"flex-1 ":""}space-y-0.5`,children:[At.map((z,N)=>s.jsx(kl,{draggableId:z.id,index:N,disableInteractiveElementBlocking:!0,children:($,ee)=>s.jsxs("div",{ref:$.innerRef,...$.draggableProps,"data-sidebar-gesture-ignore":!0,"data-sidebar-entity-index":N,className:"relative",children:[Kn(N),N===At.length-1&&Kn(At.length,"bottom"),z.kind==="workspace"?$n(z.workspace,z.members,ee.isDragging,!!ee.combineTargetFor,$.dragHandleProps):z.kind==="collaboration"?kn(z.group,z.members,$.dragHandleProps,ee.isDragging,!!ee.combineTargetFor):s.jsx("div",{...B?cr(()=>B(z.session.id)):{},className:`group relative flex items-center gap-1 rounded-md pr-1 transition-colors ${ee.combineTargetFor?"bg-primary/15 text-foreground ring-1 ring-primary/40":ee.isDragging?"bg-surface-elevated text-foreground opacity-90 shadow-lg":Qr(z.session.id)??(!Ie&&z.session.id===c?"bg-surface-elevated text-foreground":"text-muted-foreground hover:bg-surface-2")} cursor-grab active:cursor-grabbing`,children:Zn(z.session,$.dragHandleProps)})]})},z.id)),Kt.placeholder]})})})]})},Le.key||"__ungrouped__")}),G.placeholder]})})})}):Ln(on,"sidebar-entities")]}),s.jsx(n9,{onReselect:()=>{d&&(ht.current=null,je(G=>G+1),d())}}),Ce&&s.jsx(uO,{directories:a.flatMap(G=>{const Le=l.get(G.id)?.cwd;return Le?[Le]:[]}),tmuxAvailable:pe,options:cn,launchPending:Be,launchError:le?_e(Um(le)):null,agents:Vr,selectedAgent:ge,detecting:it,resumeHistory:Vt,resumeHistoryLoading:vt,resumeHistoryPendingId:Pt,resumeHistoryError:zt,onRefreshAgents:()=>{dt().catch(()=>{})},onSelectAgent:G=>{sr(G).catch(()=>{})},onLaunchAgent:Ue,onResumeHistory:G=>{Et(G)},onRemoveResumeHistory:G=>{kt(G)},onClose:()=>ue(!1),onOptionsChange:Lr,additionalContent:an&&U?.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(gn,{size:13,className:U.status==="installing"||U.status==="restarting"?"animate-spin":""})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block font-semibold",children:_e("sidebar.updateAvailable",{version:U.latestVersion})}),s.jsx("span",{className:"mt-0.5 block text-[10.5px] leading-relaxed text-muted-foreground",children:U.status==="installing"?_e("sidebar.updateInstalling"):U.status==="ready"?_e("sidebar.updateReady"):U.status==="restarting"?_e("sidebar.updateRestarting"):_e("sidebar.updateFailed")})]})]}),U.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:_e("sidebar.updateRestart")}),U.status==="error"&&ce&&s.jsx("button",{type:"button",disabled:V,onClick:ce,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:_e("sidebar.updateRetry")})]}),footerActions:s.jsx(KO,{serverAttention:Me,onOpenSettings:()=>{ue(!1),W()},actions:[...F?[{label:_e("sidebar.subscriptionQuota"),icon:FA,onSelect:()=>{ue(!1),F()}}]:[],{label:"Agent 工作台",icon:rh,onSelect:()=>{ue(!1),pr(null)}},{label:"服务与设备",icon:s9,onSelect:()=>{ue(!1),i9()}},...Y?[{label:_e($e?"sidebar.unpinSidebar":"sidebar.pinSidebar"),icon:$e?m0:p0,separated:!0,onSelect:()=>{ue(!1),Y()}}]:[]]})}),Ye&&s.jsx(Cb,{onEnterGroup:async G=>{if(!await pr(G))throw new Error("协作组已保存,打开工作区失败,请重试");st(!1)},onFloatingChange:async G=>{if(G){if(!await pr(G))throw new Error("打开协作工作区失败");st(!1)}},activeSessionId:c,defaultSessionMode:te,onClose:()=>st(!1),onNewSession:G=>p(G)}),Object.entries(We).map(([G,Le])=>s.jsx(Cb,{activeSessionId:c,initialCollaborationGroupId:G,initialFloating:Le,visible:!Ie,onEnterGroup:async Ke=>{if(Ke===G){await pr(Ke);return}if(!await pr(Ke))throw new Error("协作组已保存,打开工作区失败,请重试");await bo({floatingGroupId:null},G),Te(ct=>{const qe={...ct};return delete qe[G],qe})},onFloatingChange:Ke=>St(G,Ke),defaultSessionMode:te,onClose:()=>{oe.current=!0,Te(Ke=>{const ct={...Ke};return delete ct[G],ct})},onNewSession:Ke=>p(Ke)},G)),!Ce&&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:[le&&s.jsx("p",{role:"alert",className:"mb-2 text-[11px] leading-relaxed text-destructive",children:_e(Um(le))}),s.jsxs("div",{className:`grid gap-1.5 [&>button]:min-h-11 [&>button]:shadow-none [&>button]:ring-0 md:[&>button]:min-h-0 ${ge?"grid-cols-[minmax(0,1fr)_minmax(0,1fr)_2.5rem]":"grid-cols-[minmax(0,1fr)_2.5rem]"}`,children:[s.jsxs("button",{type:"button",onClick:Xr,disabled:Be,"aria-busy":Be,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] ${ge?"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:_e("sidebar.newSession"),"aria-label":_e("sidebar.newSession"),children:[s.jsx(Fo,{size:15,className:"shrink-0"}),s.jsx("span",{className:"truncate",children:Be?_e("sidebar.sessionCreating"):"Terminal"})]}),ge&&s.jsxs("button",{type:"button",onClick:fn,disabled:Be,"aria-busy":Be,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:_e("sidebar.newSessionWithAgent",{agent:ge.displayName}),"aria-label":_e("sidebar.newSessionWithAgent",{agent:ge.displayName}),children:[s.jsx(Wc,{agent:ge,size:15}),s.jsx("span",{className:"truncate",children:ge.displayName})]}),s.jsxs("button",{type:"button",onClick:tr,disabled:Be,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:nt,"aria-label":nt,"aria-expanded":Ce,"aria-controls":"sidebar-launch-options",children:[s.jsx($o,{size:15}),Me&&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"}),an&&s.jsx("span",{className:`absolute top-0.5 h-2 w-2 rounded-full bg-[var(--warning)] ring-2 ring-[var(--chrome-bg)] ${Me?"right-3.5":"right-0.5"}`,"aria-hidden":"true"})]})]})]})]});return $e?s.jsx("div",{"data-session-sidebar-pinned":!0,className:"h-full flex flex-col app-chrome-bg border-r border-border",children:ps}):s.jsx(N6,{side:"left",isOpen:e,drawerWidthPx:t,onClose:r,onOpen:n,push:ke,children:ps})}function nF(){const{t:e}=zr();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 sF({slow:e=!1}){const{t}=zr();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 G6=()=>Oc(()=>import("./RightSidebar-DKA0jXPW.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})),iF=b.lazy(G6);function jb(e){const t=b.useRef(!1);b.useEffect(()=>{const p=navigator.connection;if(!(p?.saveData||/2g|3g/.test(p?.effectiveType??"")))return $1(()=>{G6().catch(()=>{})},3e3)},[]);const{t:r}=zr(),n=Gt(p=>p.rootPath),a=Gt(p=>p.rightTab),c=Gt(p=>p.setRightTab),l=n?.replace(/\/+$/,"").split("/").pop()||r("rightSidebar.workspace");(e.isOpen||e.pinned)&&(t.current=!0);const d=s.jsx(N6,{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:[Ml,JT,$o].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(Rn,{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",vA,"rightSidebar.tabGit"],["diff",AA,"rightSidebar.tabChanges"],["files",Gc,"rightSidebar.tabFiles"],["architecture",PT,"architecture.tab"],["computer",l9,"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(sF,{}):s.jsx(nF,{})})]})});return t.current?s.jsx(b.Suspense,{fallback:d,children:s.jsx(iF,{...e})}):d}const Db=hc(e=>({overlay:"off",setOverlay:t=>e({overlay:t})}));function aF(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 oF=hc((e,t)=>({sessions:new Map,activeSessionId:null,nextSessionNumber:1,createSession:r=>{const n=Xy(),a=Date.now(),c=t().sessions,l=aF(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})}})),lF=[7e5,1e6,14e5,18e5,24e5,32e5,4e6,5e6,6e6,8e6,1e7,12e6].map(e=>({id:"auto",maxSize:1600,bitRate:e,maxFps:30}));class cF{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 lF[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 Xc(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 uF(){return Xc("/api/android/devices")}async function dF(e){return Xc("/api/android/connect",{method:"POST",body:JSON.stringify({address:e})})}const Of=[{id:"low",maxSize:720,bitRate:12e5,maxFps:30},{id:"medium",maxSize:1080,bitRate:4e6,maxFps:30},{id:"high",maxSize:1600,bitRate:8e6,maxFps:60}],k0=Of[1];function N1(e){if(!e||typeof e!="object")return k0;const t=e;if(t.id==="auto")return{id:"auto",maxSize:1600,bitRate:4e6,maxFps:30};const r=Of.find(l=>l.id===t.id);if(r)return r;if(t.id!=="custom")return k0;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 hF(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 Bb(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 fF(e){return Xc(`/api/android/recordings?serial=${encodeURIComponent(e)}`)}function pF(e){return Xc("/api/android/recordings",{method:"POST",body:JSON.stringify({serial:e})})}function mF(e){return Xc(`/api/android/recordings/${encodeURIComponent(e)}/stop`,{method:"POST"})}function gF(e,t){return Xc(`/api/android/recordings/${encodeURIComponent(e)}/save`,{method:"POST",body:JSON.stringify({directory:t})})}function xF(e){return Xc(`/api/android/recordings/${encodeURIComponent(e)}`,{method:"DELETE"})}const bF=0,yF=1,vF=2,wF=3,AF=4,TF=5,SF=7,CF=10,_F=11,kF=16,Qb=17,Pb=0,Lm=1,LF=2,Ob=3,Im=0,Fb=1,$b=1,wu=0xffffffffffffffffn,Eh=0xfffffffffffffffen,Fd={HOME:3,APP_SWITCH:187,POWER:26,VOLUME_UP:24,VOLUME_DOWN:25};function V6(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 IF(e,t,r,n,a,c){const l=new Uint8Array(32),d=new DataView(l.buffer);return d.setUint8(0,vF),d.setUint8(1,e),d.setBigUint64(2,t),V6(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 Em(e,t,r=0,n=0){const a=new Uint8Array(14),c=new DataView(a.buffer);return c.setUint8(0,bF),c.setUint8(1,e),c.setUint32(2,t>>>0),c.setUint32(6,r>>>0),c.setUint32(10,n>>>0),a}function EF(e,t,r,n=0){const a=new Uint8Array(21),c=new DataView(a.buffer);c.setUint8(0,wF),V6(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 NF(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,yF),a.setUint32(1,r.length),n.set(r,5),n}function RF(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]=kF,r[1]=t.length,r.set(t,2),r}function $d(e){return new Uint8Array([e])}function Ub(e){return new Uint8Array([AF,e])}function MF(e){return new Uint8Array([CF,e?1:0])}function jF(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}function DF(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 Nm(e){return e.toString(16).padStart(2,"0")}function q6(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 BF(e){const t=e?q6(e,7,!1):null;return t&&t.length>=4?`avc1.${Nm(t[1])}${Nm(t[2])}${Nm(t[3])}`:"avc1.42e01e"}function QF(e){const t=e?q6(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 PF{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=c9(hF(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($d(Qb)))},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:jF(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=DF(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($d(Qb))}})}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=[BF(this.configData),"avc1.42e01e","avc1.4d401e","avc1.64001f"].filter((l,d,p)=>p.indexOf(l)===d),r.avc={format:"annexb"}):t==="h265"?(n=[QF(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===Lm||t===Ob,l=c?0:1,d=a===wu&&!c?$b:0,p=(t===Pb||t===Lm)&&a===wu?$b:0;this.sendControl(IF(t,a,this.pointerPoint(r,n),l,p,d))}pointerDown(t,r,n){this.touch(Pb,t,r,n==="mouse"?wu:Eh)}pointerMove(t,r,n){this.touch(LF,t,r,n==="mouse"?wu:Eh)}pointerUp(t,r,n){this.touch(Lm,t,r,n==="mouse"?wu:Eh)}pointerCancel(t,r,n){this.touch(Ob,t,r,n==="mouse"?wu:Eh)}scroll(t,r,n,a){this.sendControl(EF(this.pointerPoint(t,r),n,a))}key(t,r=Im){this.sendControl(Em(r,t))}tapKey(t){this.sendControl(Em(Im,t)),this.sendControl(Em(Fb,t))}back(){this.sendControl(Ub(Im)),this.sendControl(Ub(Fb))}home(){this.tapKey(Fd.HOME)}recents(){this.tapKey(Fd.APP_SWITCH)}power(){this.tapKey(Fd.POWER)}volumeUp(){this.tapKey(Fd.VOLUME_UP)}volumeDown(){this.tapKey(Fd.VOLUME_DOWN)}rotate(){this.sendControl($d(_F))}expandNotifications(){this.sendControl($d(TF))}collapsePanels(){this.sendControl($d(SF))}setDisplayPower(t){this.sendControl(MF(t))}sendText(t){this.sendControl(NF(t))}startApp(t){this.sendControl(RF(t))}}function OF(){try{return crypto.randomUUID().slice(0,8)}catch{return Math.random().toString(36).slice(2,10)}}function FF(){return`termdock-mirror-shot-${new Date().toISOString().replace(/[-:T]/g,"").slice(0,14)}-${OF()}.png`}function zb(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 $F(e,t=FF()){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 Y6(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 Hb(e,t,r,n,a){const c=Math.max(1,Math.min(8,e.zoom*a)),l=c/e.zoom;return{zoom:c,pan:Y6({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 Z6(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 Wb(e,t){return Z6(l1(e,null),t)}const Rm=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 UF({file:e,initialPath:t,onInsert:r,onDone:n}){const{t:a}=zr(),[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 xF(e.id),n()}catch(W){S(W instanceof Error?W.message:String(W))}finally{L.current=!1,p(!1),w(!1)}}};b.useEffect(()=>{if(c)return;E.current?.focus();const W=F=>{if(F.stopPropagation(),F.key==="Escape"&&F.preventDefault(),F.key!=="Tab")return;const U=Array.from(E.current?.querySelectorAll("button:not(:disabled)")??[]),V=U[0],Z=U.at(-1);F.shiftKey&&(document.activeElement===V||document.activeElement===E.current)?(F.preventDefault(),Z?.focus()):!F.shiftKey&&document.activeElement===Z&&(F.preventDefault(),V?.focus())};return document.addEventListener("keydown",W,!0),()=>document.removeEventListener("keydown",W,!0)},[c]);const B=async W=>{if(!L.current){L.current=!0,p(!0),x(W!==void 0),l(!1),S(null);try{const F=await gF(e.id,W);W===void 0&&await r(F.path),n()}catch(F){S(F instanceof Error?F.message:String(F))}finally{L.current=!1,p(!1)}}};return c?s.jsx(tp,{open:!0,initialPath:t||"/",title:a("android.recordingSave"),onCancel:()=>l(!1),onConfirm:W=>{B(W)}}):Ii.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(Cn,{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 Xd="android-mirror",Ud=Xd,K6="termdock:android:quality:v1",Mm=176,zF=204,_l=1,rf=8,Gb=[1,1.25,1.5,2,2.5,3,4,6,8],HF=e=>Math.max(_l,Math.min(rf,e));function WF(e){return`${Number.isInteger(e)?e:e.toFixed(1)}×`}function Nh(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 GF(e,t){try{e.setPointerCapture?.(t)}catch{}}function Vb(e,t){try{e.releasePointerCapture?.(t)}catch{}}const qb=e=>typeof requestAnimationFrame=="function"?requestAnimationFrame(e):window.setTimeout(e,16),Rh=e=>{typeof cancelAnimationFrame=="function"?cancelAnimationFrame(e):window.clearTimeout(e)},jm={auto:"android.qualityAuto",low:"android.qualityLow",medium:"android.qualityMedium",high:"android.qualityHigh",custom:"android.qualityCustom"},VF=()=>{try{const e=localStorage.getItem(K6);return e?N1(JSON.parse(e)):k0}catch{return k0}},zd=e=>{try{localStorage.setItem(K6,JSON.stringify(e))}catch{}};function qF({sessionId:e,dockOnly:t=!1,onInsertPrompt:r,onInsertFile:n,onRecordingComplete:a,onCloseTab:c}){const{t:l}=zr(),d=Db(N=>N.overlay),p=Db(N=>N.setOverlay),m=b.useRef(null),x=b.useRef(null),y=b.useRef(null),w=b.useMemo(VF,[]),v=b.useRef(w),S=b.useRef(null),L=b.useRef(null),[E,R]=b.useState(4e6),B=b.useRef(null),W=b.useRef(new Map),F=b.useRef(null),U=b.useRef(!1),[V,Z]=b.useState(_l),ce=b.useRef(V),xe=b.useRef({x:0,y:0}),pe=b.useRef(null),te=b.useRef(0),ke=b.useRef(0),$e=b.useRef(null),Y=b.useRef(0),[Ae,lt]=b.useState(null),[Se,ye]=b.useState(null),[_e,je]=b.useState(!0),[re,Oe]=b.useState(""),[Ce,Ee]=b.useState(w.id),[Be,Ne]=b.useState([]),[le,He]=b.useState(null),[rt,mt]=b.useState(""),[ue,Ye]=b.useState(!0),[st,Ie]=b.useState({maxSize:w.maxSize,bitRate:w.bitRate,maxFps:w.maxFps}),[We,Te]=b.useState("idle"),[H,oe]=b.useState(null),[be,Ze]=b.useState(null),[Je,St]=b.useState({fps:0,kbps:0,width:0,height:0,received:0,decoded:0,controls:0,last:""}),[Vt,jt]=b.useState(null),[vt,Zt]=b.useState(null),[Pt,Xt]=b.useState(!1),[zt,Lt]=b.useState([]),[me,Ge]=b.useState(null),[pt,q]=b.useState([]),[at,qt]=b.useState(!1),Ve=b.useRef(null),De=b.useRef(0),er=b.useRef([]),[et,Ct]=b.useState(!1),[Nt,gt]=b.useState(""),[bt,It]=b.useState(!1),[yt,pr]=b.useState(!1),[nr,Cr]=b.useState(""),[cn,Lr]=b.useState(null),[ge,Vr]=b.useState(null),[it,dt]=b.useState(!1),[sr,xn]=b.useState(0),an=b.useRef(null),[Me,nt]=b.useState(!1),wt=b.useRef(!1),Rr=b.useRef(new Set),rn=b.useRef(null),Ir=b.useRef(null),ne=b.useRef(!1),[ht,Ht]=b.useState(!1),Ot=b.useRef(a);Ot.current=a;const[Tr,mr]=b.useState(!1),[Hr,_n]=b.useState(null),dr=b.useRef(null),bn=b.useRef(null),hn=oF(N=>N.activeSessionId??N.sessions.keys().next().value??null),Tn=e??hn,ir=es(N=>!!N.docks[Ud]),pn=es(N=>N.hosts[Ud]),Pr=es(N=>N.setDock),qr=b.useCallback(async()=>{je(!0);try{const N=await uF();lt(N),ye(null)}catch(N){ye(N instanceof Error?N.message:"ADB_UNAVAILABLE")}finally{je(!1)}},[]);b.useEffect(()=>{qr()},[qr]);const Wr=Ae?.devices??[],fs=Wr.find(N=>N.serial===re)??null,Br=!!(Se&&/ADB_NOT_FOUND|ADB_UNAVAILABLE/i.test(Se)),Mn=!!(Ae?.adbAvailable&&!Ae.scrcpyVersion),Sr=b.useCallback(()=>{const N=B.current,$=[...W.current.keys()];B.current=null,W.current.clear(),F.current=null,U.current=!1,Ve.current=null,Rh(te.current),te.current=0,N&&x.current?.pointerCancel(N.x,N.y,N.type);const ee=m.current;if(ee)for(const ie of $)Vb(ee,ie);Ge(null),qt(!1),q([]),Z(ce.current)},[]);b.useEffect(()=>{const N=ie=>{W.current.has(ie.pointerId)&&(ie.type==="pointercancel"||ie.target!==m.current)&&Sr()},$=()=>Sr(),ee=()=>{document.hidden&&Sr()};return window.addEventListener("pointerup",N,!0),window.addEventListener("pointercancel",N,!0),window.addEventListener("blur",$),document.addEventListener("visibilitychange",ee),()=>{window.removeEventListener("pointerup",N,!0),window.removeEventListener("pointercancel",N,!0),window.removeEventListener("blur",$),document.removeEventListener("visibilitychange",ee),Sr()}},[Sr]);const Kr=b.useCallback(()=>{Sr(),x.current?.disconnect(),x.current=null,Te("idle"),oe(null),Ze(null)},[Sr]),nn=b.useCallback((N,$=!1)=>{const ee=m.current;if(!ee||!N)return;Sr(),x.current?.disconnect(),oe(null),!$&&y.current!==N&&Ze(null),y.current=N,Zt(null),jt(null);const ie=new PF(ee,{onBitrateSupport:(ze,xt)=>{x.current!==ie||v.current.id!=="auto"||jt(ze?null:xt??"BITRATE_REASON_UNAVAILABLE")},onState:(ze,xt)=>{x.current===ie&&(Te(ze),oe(xt??null))},onHeader:ze=>{x.current===ie&&Ze(ze)},onStats:ze=>{x.current===ie&&St(ze)},onWarning:ze=>{x.current===ie&&Zt(ze)}});x.current=ie;let Qe=v.current;Qe.id==="auto"?(S.current?.serial!==N&&(S.current={serial:N,policy:new cF}),S.current.policy.connected(performance.now()),Qe=S.current.policy.quality,R(Qe.bitRate)):S.current=null,L.current=Qe,ie.connect(N,Qe)},[Sr]);b.useEffect(()=>{if(Ce!=="auto"||v.current.id!=="auto"||We!=="streaming"||!Je.adaptation||document.hidden)return;const N=S.current,$=x.current;if(!N||N.serial!==re||!$?.canSetBitrate)return;const ee=m.current,ie=ee?Math.max(ee.clientWidth,ee.clientHeight)*(window.devicePixelRatio||1)*ce.current:1600,Qe=N.policy.sample(Je.adaptation,performance.now(),ie||1600);Qe&&$.setBitrate(Qe.bitRate).then(ze=>{ze&&x.current===$&&(L.current=Qe,R(Qe.bitRate))})},[Je,Ce,We,re,nn]);const Fr=b.useCallback(N=>{const $={...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}:{}};ka({androidPanel:$}).catch(()=>{})},[]);b.useEffect(()=>{let N=!1;return fc().then($=>{if(N)return;const ee=$.androidPanel;if(ee?.quality){const ie=N1(ee.quality);v.current=ie,Ee(ie.id),Ie({maxSize:ie.maxSize,bitRate:ie.bitRate,maxFps:ie.maxFps}),zd(ie)}Ne(ee?.presets??[]),He(ee?.activePresetId??null),ee?.deviceSerial&&($e.current=ee.deviceSerial,Oe(ee.deviceSerial))}).catch(()=>{}),()=>{N=!0}},[]);const ks=b.useCallback(N=>{const $=++De.current;Lt(ie=>[...ie,{id:$,left:N.left,top:N.top}]);const ee=window.setTimeout(()=>{Lt(ie=>ie.filter(Qe=>Qe.id!==$)),er.current=er.current.filter(ie=>ie!==ee)},300);er.current.push(ee)},[]),Or=b.useCallback((N,$)=>{const ee=x.current,ie=L.current;ee?.supportsLiveBitrate&&y.current===N&&ie&&ie.maxSize===$.maxSize&&ie.maxFps===$.maxFps?ee.setBitrate($.bitRate).then(Qe=>{x.current===ee&&(Qe?(L.current=$,jt(null)):jt(ee.lastBitrateFailure??"BITRATE_REASON_UNAVAILABLE"))}):nn(N)},[nn,l]),Xr=b.useCallback(N=>{if(S.current=null,N.startsWith("user:")){const ee=Be.find(Qe=>Qe.id===N.slice(5));if(!ee)return;const ie={id:"custom",maxSize:ee.maxSize,bitRate:ee.bitRate,maxFps:ee.maxFps};v.current=ie,Ee("custom"),He(ee.id),Ie({maxSize:ee.maxSize,bitRate:ee.bitRate,maxFps:ee.maxFps}),Ye(!0),zd(ie),Fr({quality:ie,activePresetId:ee.id}),re&&nn(re);return}if(N==="custom"){const ee=v.current;Ee("custom"),He(null),Ie({maxSize:ee.maxSize,bitRate:ee.bitRate,maxFps:ee.maxFps}),Ye(!0);return}const $=N==="auto"?N1({id:"auto"}):Of.find(ee=>ee.id===N)??k0;v.current=$,Ee($.id),He(null),zd($),Fr({quality:$,activePresetId:null}),re&&nn(re)},[nn,re,Be,Fr]),fn=b.useCallback(()=>{const N={id:"custom",maxSize:st.maxSize,bitRate:st.bitRate,maxFps:st.maxFps};v.current=N,zd(N),Fr({quality:N,activePresetId:null}),Ee("custom"),He(null),re&&Or(re,N)},[Or,re,st,Fr]),K=b.useCallback(()=>{const N=rt.trim();if(!N)return;const $=`p${Date.now().toString(36)}${Math.random().toString(36).slice(2,6)}`,ee={id:$,name:N,maxSize:st.maxSize,bitRate:st.bitRate,maxFps:st.maxFps},ie=[...Be.filter(ze=>ze.name!==N),ee].slice(-12),Qe={id:"custom",maxSize:st.maxSize,bitRate:st.bitRate,maxFps:st.maxFps};Ne(ie),mt(""),He($),Ee("custom"),v.current=Qe,zd(Qe),Fr({quality:Qe,activePresetId:$,presets:ie}),re&&Or(re,Qe)},[rt,st,Be,re,Or,Fr]),Ue=b.useCallback(()=>{if(!le)return;const N=Be.filter($=>$.id!==le);Ne(N),He(null),Fr({activePresetId:null,presets:N})},[le,Be,Fr]);b.useEffect(()=>()=>{x.current?.disconnect(),x.current=null;for(const N of er.current)window.clearTimeout(N);er.current=[]},[]),b.useEffect(()=>{if(d==="off")return;const N=$=>{$.key==="Escape"&&p("off")};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[d,p]),b.useEffect(()=>{const N=Wr.filter(ee=>ee.state==="device");if(re||N.length!==1)return;const $=N[0].serial;$e.current!==$&&($e.current=$,Oe($))},[Wr,re]),b.useEffect(()=>{re&&nn(re)},[re,nn]),b.useEffect(()=>{if(We==="streaming"){Y.current=0,Xt(!1);return}if(We!=="error"||!re||!ZF(H??""))return;const N=Math.min(8e3,700*2**Y.current);Y.current+=1,Xt(!0);const $=window.setTimeout(()=>{Xt(!1),nn(re)},N);return()=>window.clearTimeout($)},[We,H,re,nn]);const Et=b.useCallback((N,$,ee)=>{const ie=m.current,Qe=ee??(ie?Nh(ie):null);return!ie||!Qe?{x:0,y:0}:Y6(N,$,Qe)},[]),kt=b.useCallback(()=>{const N=m.current;if(!N)return;const{x:$,y:ee}=xe.current,ie=ce.current,Qe=ie===_l&&$===0&&ee===0?"":`translate3d(${$}px, ${ee}px, 0) scale(${ie})`;N.style.transform!==Qe&&(N.style.transform=Qe);const ze=pe.current;ze&&(ze.textContent=ie>_l?WF(ie):"")},[]),tr=b.useCallback((N,$,ee=!0)=>{const ie=m.current,Qe=ce.current,ze=HF(N);if(!ie||ze===Qe)return;const xt=Nh(ie);if(!xt)return;const _t=$??{x:xt.cx,y:xt.cy},Mr=Hb({zoom:Qe,pan:xe.current},xt,_t,_t,ze/Qe);ce.current=Mr.zoom,xe.current=Mr.pan,ee&&kt()},[kt]),Qr=b.useCallback(()=>{const N=ce.current;Z($=>$<=_l+.01==N<=_l+.01&&$>=rf-.01==N>=rf-.01?$:N)},[]);b.useEffect(()=>()=>{Rh(te.current),Rh(ke.current)},[]);const cr=()=>{let N=0,$=0;for(const ie of W.current.values())N+=ie.x,$+=ie.y;const ee=W.current.size;return ee?{x:N/ee,y:$/ee}:null},Sn=()=>{const[N,$]=Array.from(W.current.values());return N&&$?Math.hypot(N.x-$.x,N.y-$.y):0},Ls=()=>{const N=cr(),$=m.current?Nh(m.current):null;!N||!$||(F.current={startCentroid:N,startDistance:Sn(),box:$})},Zn=b.useCallback(()=>{const N=F.current,$=cr();if(!N||!$)return;const ee=Sn(),ie=N.startDistance>0&&ee>0?ee/N.startDistance:1,Qe=Hb({zoom:ce.current,pan:xe.current},N.box,N.startCentroid,$,ie);ce.current=Qe.zoom,xe.current=Qe.pan,N.startCentroid=$,N.startDistance=ee},[]),sn=b.useCallback(()=>{te.current||(te.current=qb(()=>{te.current=0,Zn(),kt()}))},[Zn,kt]),on=b.useCallback(()=>{te.current&&(Rh(te.current),te.current=0,Zn(),kt())},[Zn,kt]);b.useEffect(()=>{const N=m.current;if(!N)return;const $=N.parentElement;if(!$)return;const ee=Qe=>{if(Qe.ctrlKey||Qe.metaKey){if(Qe.preventDefault(),!Qe.deltaY||F.current)return;const _t=Qe.deltaMode===1?16:Qe.deltaMode===2?N.parentElement?.clientHeight||600:1,Mr=Math.max(-600,Math.min(600,Qe.deltaY*_t));tr(ce.current*Math.exp(-Mr*.002),{x:Qe.clientX,y:Qe.clientY},!1),ke.current||(ke.current=qb(()=>{ke.current=0,kt(),Qr()}));return}const ze=x.current;if(!ze||Qe.target!==N)return;Qe.preventDefault();const xt=jh(N,Qe.clientX,Qe.clientY);ze.scroll(xt.x,xt.y,Qe.deltaX,Qe.deltaY)},ie=Qe=>Qe.preventDefault();return $.addEventListener("wheel",ee,{passive:!1}),$.addEventListener("gesturestart",ie,{passive:!1}),$.addEventListener("gesturechange",ie,{passive:!1}),()=>{$.removeEventListener("wheel",ee),$.removeEventListener("gesturestart",ie),$.removeEventListener("gesturechange",ie)}},[tr,kt,Qr]),b.useEffect(()=>{const N=m.current,$=N?.parentElement;if(!N||!$||typeof ResizeObserver>"u")return;const ee=new ResizeObserver(()=>{F.current&&(F.current.box=Nh(N));const ie=Et(xe.current,ce.current);ie.x===xe.current.x&&ie.y===xe.current.y||(xe.current=ie,kt())});return ee.observe(N),ee.observe($),()=>ee.disconnect()},[Et,kt]),b.useLayoutEffect(()=>{kt()});const _r=N=>{const $=x.current,ee=m.current;if(!$||!ee)return;if(N.pointerType==="mouse"&&N.button!==0){N.preventDefault(),N.button===2?$.back():N.button===1&&$.home();return}N.preventDefault(),ee.closest(".android-mirror-panel")?.focus({preventScroll:!0}),kt(),Qr(),on(),GF(ee,N.pointerId),W.current.set(N.pointerId,{x:N.clientX,y:N.clientY});const ie=N.pointerType==="mouse"&&N.altKey;if(W.current.size>=2||ie){const xt=B.current;xt&&($.pointerCancel(xt.x,xt.y,xt.type),B.current=null,Ve.current=null,Ge(null),qt(!1),q([])),U.current=!0,Ls();return}if(U.current)return;const Qe=jh(ee,N.clientX,N.clientY);B.current={id:N.pointerId,type:N.pointerType,x:Qe.x,y:Qe.y},$.pointerDown(Qe.x,Qe.y,N.pointerType);const ze=Jb(ee,N.clientX,N.clientY);ze&&(Ve.current={left:ze.left,top:ze.top},q([]),qt(!1),Ge(ze))},$r=N=>{const $=x.current,ee=m.current;if(!ee||!W.current.has(N.pointerId))return;if(N.pointerType==="mouse"){const _t=ee.getBoundingClientRect(),Mr=ee.parentElement?.getBoundingClientRect()??_t;if(!(N.buttons&1)||N.clientX<Math.max(_t.left,Mr.left)||N.clientX>=Math.min(_t.right,Mr.right)||N.clientY<Math.max(_t.top,Mr.top)||N.clientY>=Math.min(_t.bottom,Mr.bottom)){Sr();return}}if(N.preventDefault(),W.current.set(N.pointerId,{x:N.clientX,y:N.clientY}),F.current){sn();return}const ie=B.current;if(!$||!ie||ie.id!==N.pointerId)return;const Qe=jh(ee,N.clientX,N.clientY);ie.x=Qe.x,ie.y=Qe.y,$.pointerMove(Qe.x,Qe.y,ie.type);const ze=Jb(ee,N.clientX,N.clientY),xt=Ve.current;!ze||!xt||(Ge(ze),Math.hypot(ze.left-xt.left,ze.top-xt.top)>=6&&(qt(!0),q(_t=>{const Mr=_t[_t.length-1];if(Mr&&Math.hypot(ze.left-Mr.x,ze.top-Mr.y)<4)return _t;const Dt=[..._t,{x:ze.left,y:ze.top}];return Dt.length>12?Dt.slice(Dt.length-12):Dt})))},Wn=N=>{const $=x.current,ee=m.current;if(!ee||!W.current.has(N.pointerId))return;if(on(),W.current.delete(N.pointerId),Vb(ee,N.pointerId),W.current.size===0&&(U.current=!1),F.current){W.current.size===0?(F.current=null,Z(ce.current)):Ls();return}const ie=B.current;if(!ie||ie.id!==N.pointerId)return;const Qe=jh(ee,N.clientX,N.clientY);$?.pointerUp(Qe.x,Qe.y,ie.type),me&&ks(me),Ge(null),qt(!1),window.setTimeout(()=>q([]),200),B.current=null,Ve.current=null},Gn=N=>{if(Tr||et||yt)return;const $=x.current;$&&(N.key==="Backspace"?(N.preventDefault(),$.key(67)):N.key==="Escape"?(N.preventDefault(),$.back()):N.key==="Enter"&&(N.preventDefault(),$.key(66)))},un=async()=>{const N=Nt.trim();if(N){It(!0);try{const $=await dF(N);gt(""),Ct(!1),await qr(),Oe($.serial)}catch($){ye($ instanceof Error?$.message:"ADB_CONNECT_FAILED")}finally{It(!1)}}},Kn=()=>{const N=x.current,$=nr;!N||!$||(N.sendText($),Cr(""))},kr=b.useCallback(N=>{Lr(N),Ir.current!==null&&window.clearTimeout(Ir.current),Ir.current=window.setTimeout(()=>{Ir.current=null,Lr(null)},2500)},[]),Er=b.useCallback(N=>{const $=ce.current,ee=N==="in"?Gb.find(ie=>ie>$+.01):[...Gb].reverse().find(ie=>ie<$-.01);ee!==void 0&&($<=_l&&ee>_l&&kr(l("android.zoomPanHint")),on(),tr(ee),Z(ee))},[tr,on,kr,l]),gr=N=>{Promise.resolve().then(()=>r?.(N)).catch($=>{Vr($ instanceof Error?$.message:String($))})},rs=b.useCallback(async(N,$)=>{try{if(!n)throw new Error(l("android.captureUnavailable"));await n(N),kr($)}catch(ee){Vr(l("android.captureFailed")+(ee instanceof Error?`:${ee.message}`:""))}},[n,kr,l]),$n=async()=>{const N=m.current;if(!(!N||ne.current)){ne.current=!0,Ht(!0),Vr(null);try{const $=await $F(N);await rs($,l("android.captureInserted"))}catch($){Vr($ instanceof Error?$.message:String($))}finally{ne.current=!1,Ht(!1)}}},kn=b.useCallback(N=>{(N.status==="ready"||N.status==="error")&&Ot.current&&!Rr.current.has(N.id)&&(Rr.current.add(N.id),Ot.current?.(N))},[]),Ln=b.useCallback(async N=>{const $=an.current;if(!(!$||wt.current)){wt.current=!0,nt(!0),Vr(null);try{const ee=await mF($.id);an.current=null,dt(!1),kn(ee)}catch(ee){Vr(ee instanceof Error?ee.message:String(ee))}finally{wt.current=!1,nt(!1)}}},[kn]),ps=async()=>{if(!(!re||wt.current||an.current)){wt.current=!0,nt(!0),Vr(null);try{const N=await pF(re);N.status==="recording"||N.status==="starting"||N.status==="stopping"?(an.current=N,dt(!0),xn(Math.max(0,Date.now()-N.startedAt))):kn(N)}catch(N){Vr(N instanceof Error?N.message:String(N))}finally{wt.current=!1,nt(!1)}}};b.useEffect(()=>{let N=!1,$=!1;an.current=null,dt(!1);const ee=async()=>{if(!(!re||$||wt.current)){$=!0;try{const{recordings:Qe}=await fF(re);if(N||wt.current)return;const ze=Qe.find(xt=>["starting","recording","stopping"].includes(xt.status));an.current=ze??null,dt(!!ze);for(const xt of Qe)kn(xt)}catch{}finally{$=!1}}};ee();const ie=window.setInterval(()=>{ee()},2e3);return rn.current=window.setInterval(()=>{an.current&&xn(Math.max(0,Date.now()-an.current.startedAt))},500),()=>{N=!0,window.clearInterval(ie),rn.current!==null&&window.clearInterval(rn.current)}},[re,kn]),b.useEffect(()=>{if(!Tr)return;const N=()=>mr(!1),$=ie=>{const Qe=ie.target;Qe instanceof Node&&(dr.current?.contains(Qe)||bn.current?.contains(Qe)||N())},ee=ie=>{ie.key==="Escape"&&(ie.preventDefault(),ie.stopPropagation(),N())};return document.addEventListener("pointerdown",$,!0),document.addEventListener("keydown",ee,!0),window.addEventListener("resize",N),()=>{document.removeEventListener("pointerdown",$,!0),document.removeEventListener("keydown",ee,!0),window.removeEventListener("resize",N)}},[Tr]),b.useEffect(()=>()=>{Ir.current!==null&&window.clearTimeout(Ir.current)},[]);const G=We==="streaming",Le=ir,Ke=Le?"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",ct=fs?(fs.model||fs.serial)+ey(fs,l):Wr.length?l("android.selectDevice"):l("android.noDevices"),At=(le?Be.find(N=>N.id===le):null)?.name??(Ce==="auto"?`${l("android.qualityAuto")} · ${E/1e6} Mbps`:l(jm[Ce])),Rt=Le?"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",Bt=Le?"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",ot="absolute inset-0 h-full w-full cursor-pointer opacity-0",Ft=()=>{const N=dr.current?.getBoundingClientRect();N&&_n({left:Math.max(8,Math.min(N.right-Mm,window.innerWidth-Mm-8)),top:Math.min(N.bottom+4,Math.max(8,window.innerHeight-zF-8))}),mr(!0)},hr=()=>{if(ir){Pr(Ud,null),Fr({docked:null});return}if(!Tn)return;const N={sessionId:Tn,side:"right"};Pr(Ud,N),Fr({docked:N})},Kt=et||ir||d!=="off",z=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:Gn,tabIndex:-1,children:[s.jsxs("div",{"data-panel-drag-title":ir?"true":void 0,className:Le?"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:[ir&&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(Ff,{size:12})}),s.jsx(u9,{size:Le?12:14,className:"shrink-0 text-muted-foreground"}),s.jsxs("div",{className:`${Rt} flex-1`,children:[s.jsx("span",{"aria-hidden":"true",className:`${Bt} w-full`,children:ct}),s.jsxs("select",{value:re,onChange:N=>{const $=N.target.value;Oe($),$e.current=$,$&&Fr({deviceSerial:$})},className:ot,"aria-label":l("android.device"),children:[s.jsx("option",{value:"",children:Wr.length?l("android.selectDevice"):l("android.noDevices")}),Wr.map(N=>s.jsx("option",{value:N.serial,children:(N.model||N.serial)+ey(N,l)},N.serial))]})]}),s.jsxs("div",{className:`${Rt} max-w-[45%] shrink-0`,children:[s.jsx("span",{"aria-hidden":"true",className:Bt,children:At}),s.jsxs("select",{value:le?`user:${le}`:Ce,onChange:N=>Xr(N.target.value),className:ot,title:l(Ce==="auto"?"android.qualityAutoHint":"android.quality"),"aria-label":l("android.quality"),children:[s.jsxs("option",{value:"auto",children:[l("android.qualityAuto"),Ce==="auto"?` · ${E/1e6} Mbps`:""]}),Of.map(N=>s.jsx("option",{value:N.id,children:l(jm[N.id])},N.id)),Be.map(N=>s.jsx("option",{value:`user:${N.id}`,children:N.name},N.id)),s.jsx("option",{value:"custom",children:l(jm.custom)})]})]}),s.jsx("button",{type:"button",onClick:()=>{qr()},className:`${Ke} text-muted-foreground`,title:l("android.refresh"),children:_e?s.jsx(Cn,{size:13,className:"animate-spin"}):s.jsx(gn,{size:13})}),G?s.jsx("button",{type:"button",onClick:Kr,className:`${Ke} text-destructive`,title:l("android.disconnect"),children:s.jsx(Oy,{size:13})}):s.jsx("button",{type:"button",onClick:()=>re&&nn(re),disabled:!re,className:`${Ke} text-primary`,title:l("android.connect"),children:s.jsx(sS,{size:13})}),(G||it)&&s.jsx("button",{type:"button",onClick:()=>{$n()},disabled:!n||ht,className:`${Ke} text-muted-foreground`,title:l(n?"android.screenshot":"android.captureUnavailable"),"aria-label":l("android.screenshot"),children:ht?s.jsx(Cn,{size:Le?12:13,className:"animate-spin"}):s.jsx(PA,{size:Le?12:13})}),(G||it)&&s.jsx("button",{type:"button",onClick:()=>{it?Ln("manual"):ps()},disabled:Me||!it&&!a,className:`${Ke} ${it?"text-destructive":"text-muted-foreground"}`,title:l(it?"android.recordingStop":a?"android.recordingStart":"android.captureUnavailable"),"aria-label":l(it?"android.recordingStop":"android.recordingStart"),children:Me?s.jsx(Cn,{className:"animate-spin",size:13}):it?s.jsx(Py,{size:Le?10:11,fill:"currentColor"}):s.jsx(Fy,{size:Le?12:13})}),s.jsx("button",{ref:dr,type:"button",onClick:()=>Tr?mr(!1):Ft(),"aria-haspopup":"menu","aria-expanded":Tr,className:`${Ke} ${Kt?"text-primary":"text-muted-foreground"}`,title:l("android.more"),"aria-label":l("android.more"),children:s.jsx($o,{size:Le?13:14})}),c&&!t&&s.jsx("button",{type:"button",onClick:()=>{mr(!1),p("off"),c()},className:`${Ke} text-muted-foreground hover:bg-destructive/20 hover:text-destructive`,title:l("android.closeTab"),"aria-label":l("android.closeTab"),children:s.jsx(Rn,{size:14})})]}),Tr&&Hr&&Ii.createPortal(s.jsxs("div",{ref:bn,role:"menu","aria-label":l("android.more"),style:{left:Hr.left,top:Hr.top,width:Mm},className:"fixed z-popover overflow-hidden rounded-md border border-border bg-surface-elevated py-1 text-[11px] shadow-lg",children:[s.jsx(Mh,{icon:s.jsx(ul,{size:13}),label:l("android.addDevice"),active:et,onSelect:()=>{Ct(N=>!N),mr(!1)}}),s.jsx(Mh,{icon:ir?s.jsx(Rn,{size:13}):s.jsx(Il,{size:13}),label:l(ir?"android.splitClose":"android.splitOpen"),active:ir,disabled:!ir&&!Tn,onSelect:()=>{hr(),mr(!1)}}),s.jsx(Mh,{icon:d==="window"?s.jsx(ET,{size:13}):s.jsx(_T,{size:13}),label:l(d==="window"?"android.exitFullscreen":"android.fullscreen"),active:d==="window",onSelect:()=>{p(d==="window"?"off":"window"),mr(!1)}}),!t&&s.jsx(Mh,{icon:d==="sidebar"?s.jsx(FT,{size:13}):s.jsx(HT,{size:13}),label:l(d==="sidebar"?"android.exitFullscreen":"android.fillSidebar"),active:d==="sidebar",onSelect:()=>{p(d==="sidebar"?"off":"sidebar"),mr(!1)}}),be&&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:`${Je.fps} fps · ${Je.kbps} kbps`}),s.jsx("div",{className:"truncate",children:`${Je.width}×${Je.height}`})]})]}),document.body),(Ce==="custom"||le)&&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:()=>Ye(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"),le?` · ${Be.find(N=>N.id===le)?.name??""}`:""]})]}),ue&&s.jsxs("div",{className:"mt-2 grid gap-2",children:[s.jsx(Xb,{label:l("android.qualityResolution"),display:`${st.maxSize}px`,min:360,max:2160,step:8,value:st.maxSize,onChange:N=>Ie($=>({...$,maxSize:N}))}),s.jsx(Xb,{label:l("android.qualityBitRate"),display:`${(st.bitRate/1e6).toFixed(1)} Mbps`,min:.5,max:20,step:.5,value:st.bitRate/1e6,onChange:N=>Ie($=>({...$,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($=>({...$,maxFps:N})),className:`rounded px-2 py-0.5 ${st.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 ${st.maxFps===0?"bg-surface-elevated text-primary":"text-muted-foreground hover:bg-surface-2"}`,children:l("android.qualityAuto")})]}),s.jsx("button",{type:"button",onClick:fn,disabled:!re,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:rt,onChange:N=>mt(N.target.value),onKeyDown:N=>{N.key==="Enter"&&!N.nativeEvent.isComposing&&K()},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:K,disabled:!rt.trim(),className:"shrink-0 rounded bg-surface-2 px-2 py-1 text-primary disabled:opacity-40",children:l("android.presetSave")}),le&&s.jsx("button",{type:"button",onClick:Ue,className:"shrink-0 rounded px-2 py-1 text-destructive hover:bg-surface-2",children:l("android.presetDelete")})]})]})]}),et&&s.jsxs("div",{className:"flex items-center gap-1.5 border-b border-border px-2 py-2",children:[s.jsx("input",{value:Nt,onChange:N=>gt(N.target.value),onKeyDown:N=>{N.key==="Enter"&&un()},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:()=>{un()},disabled:bt,className:"rounded bg-surface-2 px-2 py-1 text-[11px] text-primary disabled:opacity-40",children:bt?s.jsx(Cn,{size:12,className:"animate-spin"}):l("android.connect")})]}),Br&&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(Zb,{label:l("android.insertFixPrompt"),onClick:()=>gr(Kb("adb",Se??"")),enabled:!!r})]}),!Br&&Mn&&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(Zb,{label:l("android.insertFixPrompt"),onClick:()=>gr(Kb("scrcpy","")),enabled:!!r})]}),fs&&fs.state!=="device"&&s.jsx("div",{className:"border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-warning",children:KF(fs,l)}),Se&&!Br&&s.jsx("div",{className:"border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-destructive",children:Bb(Se)}),Vt&&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(Vt.startsWith("SCRCPY_VERSION")?"android.qualityAutoVersionError":Vt.startsWith("SCRCPY_BUILD")?"android.qualityAutoBuildError":/EXTENSION|SERVER_READ|PUSH/.test(Vt.split(":")[0])?"android.qualityAutoExtensionError":/TIMEOUT/.test(Vt.split(":")[0])?"android.qualityAutoTimeoutError":/ENCODER_REJECTED/.test(Vt.split(":")[0])?"android.qualityAutoEncoderError":/CHANNEL|TUNNEL|LISTEN|PROTOCOL|CONNECTION/.test(Vt.split(":")[0])?"android.qualityAutoChannelError":"android.qualityAutoUnknownError")]}),s.jsx("pre",{className:"mt-1 select-text whitespace-pre-wrap break-all text-[10px]",children:Vt})]}),vt&&s.jsx("div",{className:"border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-warning",children:vt}),ge&&s.jsx("div",{role:"alert",className:"border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-destructive",children:ge}),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:G||be?"block":"none",transformOrigin:"center",transition:"none"},onPointerDown:_r,onPointerMove:$r,onPointerUp:Wn,onPointerCancel:()=>Sr(),onLostPointerCapture:N=>{W.current.has(N.pointerId)&&Sr()},onPointerLeave:N=>{W.current.has(N.pointerId)&&!N.currentTarget.hasPointerCapture?.(N.pointerId)&&Sr()},onContextMenu:N=>N.preventDefault()}),me&&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:me.left,top:me.top}}),pt.length>1&&s.jsx("svg",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0 h-full w-full",style:{opacity:at?1:0,transition:"opacity 160ms linear"},children:pt.slice(1).map((N,$)=>{const ee=pt[$],ie=($+1)/(pt.length-1);return s.jsx("line",{x1:ee.x,y1:ee.y,x2:N.x,y2:N.y,stroke:"var(--primary)",strokeWidth:1+1.6*ie,strokeLinecap:"round",opacity:.06+.45*ie},$)})}),zt.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)),!G&&s.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-2 text-center text-[11px] text-muted-foreground",children:[We==="connecting"&&s.jsxs(s.Fragment,{children:[s.jsx(Cn,{size:18,className:"animate-spin"}),s.jsx("span",{children:l("android.connecting")})]}),We==="error"&&s.jsxs(s.Fragment,{children:[s.jsx($u,{size:14,className:"text-destructive"}),s.jsx("span",{className:"max-w-[80%] text-destructive",children:Pt?l("android.reconnecting"):Bb(H||"")}),re&&s.jsx("button",{type:"button",onClick:()=>{Y.current=0,nn(re)},className:"rounded bg-surface-2 px-2 py-1 text-foreground",children:l("android.retry")})]}),We==="idle"&&!Br&&!Mn&&s.jsxs(s.Fragment,{children:[s.jsx(RT,{size:22,className:"opacity-60"}),s.jsx("span",{children:Wr.length?l("android.idleHint"):l("android.noDevicesHint")})]})]})]}),s.jsxs("div",{className:`flex flex-wrap items-center gap-1 border-t border-border ${Le?"px-1.5 py-0.5":"px-2 py-1.5"}`,children:[s.jsx(Mo,{compact:Le,label:l("android.back"),onClick:()=>x.current?.back(),disabled:!G,children:s.jsx(Cy,{size:14})}),s.jsx(Mo,{compact:Le,label:l("android.home"),onClick:()=>x.current?.home(),disabled:!G,children:s.jsx(yT,{size:14})}),s.jsx(Mo,{compact:Le,label:l("android.recents"),onClick:()=>x.current?.recents(),disabled:!G,children:s.jsx(jy,{size:14})}),s.jsx(Mo,{compact:Le,label:l("android.notifications"),onClick:()=>x.current?.expandNotifications(),disabled:!G,children:s.jsx(Ey,{size:14})}),s.jsx(Mo,{compact:Le,label:l("android.rotate"),onClick:()=>x.current?.rotate(),disabled:!G,children:s.jsx(uS,{size:14})}),s.jsx(Mo,{compact:Le,label:l("android.volumeDown"),onClick:()=>x.current?.volumeDown(),disabled:!G,children:s.jsx(jS,{size:14})}),s.jsx(Mo,{compact:Le,label:l("android.volumeUp"),onClick:()=>x.current?.volumeUp(),disabled:!G,children:s.jsx(BS,{size:14})}),s.jsx(Mo,{compact:Le,label:l("android.power"),onClick:()=>x.current?.power(),disabled:!G,children:s.jsx(aS,{size:14})}),s.jsx(Mo,{compact:Le,label:l("android.inputText"),active:yt,onClick:()=>pr(N=>!N),disabled:!G,children:s.jsx(My,{size:14})}),s.jsx(Mo,{compact:Le,label:l("android.zoomIn"),onClick:()=>Er("in"),disabled:!G||V>=rf-.01,children:s.jsx(Us,{size:14})}),s.jsx(Mo,{compact:Le,label:l("android.zoomOut"),onClick:()=>Er("out"),disabled:!G||V<=_l+.01,children:s.jsx(Dy,{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":it||!!cn||ht,className:`block truncate text-right text-[10px] leading-5 tabular-nums text-muted-foreground ${it||cn||ht?"invisible":""}`,children:be?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(YF,{recording:it,elapsed:sr,status:ht?l("android.captureInserting"):cn,stopLabel:l("android.recordingStop"),onStop:()=>{Ln("manual")}})})]})]}),yt&&s.jsxs("div",{className:"flex items-center gap-1.5 border-t border-border px-2 py-1.5",children:[s.jsx("input",{value:nr,onChange:N=>Cr(N.target.value),onKeyDown:N=>{N.key==="Enter"&&!N.nativeEvent.isComposing&&(N.preventDefault(),Kn())},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:Kn,disabled:!nr,className:"rounded bg-surface-2 p-1.5 text-primary disabled:opacity-40",title:l("android.send"),children:s.jsx(r0,{size:13})})]})]});return d==="window"?Ii.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:z}),document.body):t?ir&&pn?Ii.createPortal(z,pn):null:ir&&pn?s.jsxs(s.Fragment,{children:[Ii.createPortal(z,pn),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:()=>{Pr(Ud,null),Fr({docked:null})},className:"rounded bg-surface-2 px-2 py-1 text-foreground",children:l("android.splitClose")})]})]}):z}function Mh({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(hi,{size:12,className:"shrink-0"})]})}function YF({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"}),zb(t),s.jsx("button",{type:"button",onClick:a,title:n,"aria-label":`${n} · ${zb(t)}`,className:"ml-0.5 inline-flex h-4 w-4 items-center justify-center rounded hover:bg-destructive/25",children:s.jsx(Py,{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 Yb({sessionId:e}){const t=es(x=>x.docks[Xd]),r=!!t,n=t?.sessionId??e??null,c=Rm(x=>x.pending)[0],l=b.useCallback(async x=>{if(!n)throw new Error("没有可接收截图的终端");const w=(await L0("/tmp",[x])).files[0]?.path;if(!w)throw new Error("截图上传未返回文件路径");await Wb(w,n)},[n]),d=b.useCallback(x=>{Rm.getState().enqueue(x,n)},[n]),p=es(x=>!!x.hosts[Xd]),m=b.useRef(!1);return b.useEffect(()=>{m.current||(m.current=!0,fc().then(x=>{const y=x.androidPanel?.docked;y&&(es.getState().docks[Xd]||es.getState().setDock(Xd,y))}).catch(()=>{}))},[]),s.jsxs(s.Fragment,{children:[r&&p&&s.jsx(qF,{sessionId:n,dockOnly:!0,onInsertFile:n?l:void 0,onInsertPrompt:n?x=>Z6(x,n):void 0,onRecordingComplete:d}),c&&s.jsx(UF,{file:c.file,initialPath:c.initialPath,onInsert:x=>c.insert?c.insert(x):Wb(x,c.sessionId),onDone:()=>Rm.getState().remove(c.file.id)},c.file.id)]})}function Zb({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 Kb(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
|
+
`:"")+Et)}},ref:Lr,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:[dt.name," · 发送给成员"]}),s.jsxs("div",{className:w?"space-y-2":"mt-2 space-y-2",children:[$e&&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:K=>{K.key==="Escape"&&(K.currentTarget.removeAttribute("open"),K.currentTarget.querySelector("summary")?.focus(),K.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($o,{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:`${wr} min-h-11 w-full justify-start text-foreground hover:bg-surface-elevated`,onClick:K=>{K.currentTarget.closest("details")?.removeAttribute("open"),U?.(dt.id).catch(Ue=>pe(Ue instanceof Error?Ue.message:"无法打开看板"))},children:[s.jsx(Fc,{size:14}),"看板"]}),s.jsx("button",{type:"button","aria-expanded":lt,className:`${wr} min-h-11 w-full justify-start text-foreground hover:bg-surface-elevated`,onClick:K=>{K.currentTarget.closest("details")?.removeAttribute("open"),Se(Ue=>!Ue)},children:"成员管理"}),s.jsxs("button",{type:"button","aria-label":"组设置","aria-expanded":vt,className:`${wr} min-h-11 w-full justify-start text-foreground hover:bg-surface-elevated`,onClick:K=>{K.currentTarget.closest("details")?.removeAttribute("open"),Xt.current=K.currentTarget,Zt(!0),pe(null),te(null)},children:[s.jsx(e0,{size:14}),"组设置"]})]})]})]}),s.jsxs("fieldset",{className:"min-w-0",children:[s.jsx("legend",{className:$e?"sr-only":"mb-1 text-[10px] text-muted-foreground",children:"接收人(可多选)"}),s.jsx("div",{className:"flex flex-wrap gap-1",children:[{id:"*",label:"全组成员"},...dt.sessionIds.map(K=>({id:K,label:(()=>{const Ue=sr.find(Et=>Et.sessionId===K);return Ue?ku(Ue,sr):void 0})()??`${K.slice(0,8)}(离线)`}))].map(({id:K,label:Ue})=>{const Et=K==="*"?be===null:be?.includes(K)??!1,kt=L.find(tr=>tr.sessionId===K);return s.jsxs("span",{className:"inline-flex max-w-full items-center gap-0.5",children:[s.jsxs("button",{type:"button","aria-pressed":Et,onClick:()=>Ze(tr=>K==="*"?null:tr?.includes(K)?tr.filter(Qr=>Qr!==K):[...tr??[],K]),className:`${E1} min-h-9 min-w-0 gap-1 sm:min-h-7 ${Et?"border-primary/40 bg-primary/15 text-primary":"border-border/20 bg-surface-2 text-muted-foreground hover:text-foreground"}`,children:[Et&&s.jsx(hi,{size:12,"aria-hidden":"true",className:"shrink-0"}),s.jsx("span",{className:"break-words text-left",children:Ue})]}),kt&&s.jsx("button",{type:"button","aria-label":`打开 ${Ue} 的终端`,title:`打开 ${Ue} 的终端`,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:()=>{W(kt).catch(tr=>pe(tr instanceof Error?tr.message:"无法打开会话"))},children:s.jsx(Fc,{size:12})})]},K)})})]})]}),s.jsxs("label",{className:"mt-2 block space-y-1 text-[9px] text-muted-foreground",children:[s.jsx("span",{className:$e?"sr-only":void 0,children:"内容"}),s.jsx("textarea",{onKeyDown:K=>{K.key==="Enter"&&(K.metaKey||K.ctrlKey)&&!K.nativeEvent.isComposing&&K.keyCode!==229&&(K.preventDefault(),Wr())},onPaste:K=>{const Ue=Array.from(K.clipboardData.files);Ue.length&&(K.preventDefault(),Ot(Ue))},className:`${Fs} min-h-16 max-h-48 resize-y`,value:Je,onChange:K=>St(K.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:xn>0?"正在准备文件路径…":w&&a?a:dt.federated?"消息由服务端后台投递,可查看送达结果;无需保持客户端在线。":"在线成员立即入队;离线成员上线后送达。"}),s.jsxs("button",{disabled:ce!==null||xn>0||!Je.trim()||!qr.length,className:`${wr} shrink-0 bg-primary text-primary-foreground`,title:"发送(⌘ / Ctrl + Enter)",onClick:()=>{Wr()},children:[ce==="send-message"?s.jsx(gn,{size:13,className:"animate-spin"}):null,"发送"]})]})]}),s.jsxs("div",{children:[s.jsxs("details",{hidden:$e&&!lt,open:$e?lt:void 0,onToggle:K=>{$e&&Se(K.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:["管理成员、角色与删除 · ",dt.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:dt.name}),s.jsxs("p",{className:"mt-1 text-[10px] text-muted-foreground",children:[dt.sessionIds.length," 个成员 · 组 ID:",s.jsx("span",{className:"break-all font-mono",children:W6(dt.id)})]})]}),He?s.jsxs("div",{className:"flex flex-wrap items-center gap-1 sm:justify-end",children:[s.jsx("button",{className:`${wr} bg-surface-2 px-2 text-foreground`,onClick:()=>rt(!1),children:"取消"}),s.jsxs("button",{disabled:ce!==null,className:`${wr} bg-destructive px-2 text-destructive-foreground`,onClick:()=>{fs()},children:[ce===`delete:${dt.id}`?s.jsx(gn,{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:`${wr} px-2 text-muted-foreground hover:bg-surface-2 hover:text-foreground`,onClick:()=>{q(new Set(dt.sessionIds)),qt(dt.updatedAt);const K=!Vt;jt(K),K&&De(Object.fromEntries(dt.sessionIds.map(Ue=>[Ue,dt.roles?.[Ue]??""]))),et(!1)},children:[s.jsx(e0,{size:13}),"管理成员"]}),s.jsxs("button",{className:`${wr} px-2 text-primary hover:bg-primary/10`,onClick:Kr,children:[s.jsx(Us,{size:13}),"新建 Agent"]}),s.jsx("button",{"aria-label":`删除协作组 ${dt.name}`,title:"删除协作组",disabled:ce!==null,className:"rounded-lg p-2 text-muted-foreground transition hover:bg-destructive/10 hover:text-destructive",onClick:()=>{ue(dt.updatedAt),rt(!0)},children:s.jsx(zs,{size:14})})]})]}),He&&s.jsxs("p",{role:"alert",className:"mt-2 rounded-lg bg-destructive/10 px-3 py-2 text-[10px] leading-relaxed text-destructive",children:["将删除“",dt.name,"”协作组及其协作记录,",dt.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:dt.sessionIds.map(K=>{const Ue=L.find(tr=>tr.sessionId===K),Et=dt.roles?.[K],kt=Ue?.name??K;return s.jsxs("div",{className:`flex min-w-0 items-stretch transition ${me===K?"bg-destructive/5":"hover:bg-surface-2"}`,children:[s.jsxs("button",{disabled:!Ue,onClick:()=>Ue&&void W(Ue).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 ${Ue&&["ready","shell","terminal-connected","service-reachable","working","idle","done"].includes(Ue.status)&&Ue.serviceConnected!==!1?"bg-[var(--success)]":"bg-muted-foreground"}`}),s.jsx("span",{className:"truncate text-[11px] text-foreground",children:kt}),Ue&&s.jsx(Cm,{session:Ue}),s.jsx("span",{className:"ml-auto shrink-0 text-[9px] text-muted-foreground",children:Ue?tf(Ue):"已离线"})]}),s.jsxs("span",{className:"mt-1 flex min-w-0 items-center gap-1 text-[9px] text-muted-foreground",children:[Et?s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"min-w-0 truncate font-medium text-primary/80",children:["定位:",Et]}),s.jsx("span",{className:"shrink-0 text-muted-foreground/50",children:"·"})]}):null,Ue?s.jsx("span",{className:"min-w-0 truncate",children:_m(Ue.currentTask)}):s.jsx("span",{className:"shrink-0",children:"重新上线后可继续接收消息"})]})]}),s.jsx("button",{"aria-label":`把 ${kt} 移出协作组`,"aria-expanded":me===K,title:"移出协作组",disabled:ce!==null,className:`mr-1 shrink-0 self-center rounded-lg p-2 transition ${me===K?"text-destructive":"text-muted-foreground hover:bg-destructive/10 hover:text-destructive"}`,onClick:()=>Ge(me===K?null:K),children:s.jsx(zs,{size:13})})]},K)})}),me&&dt.sessionIds.includes(me)&&(()=>{const K=L.find(Et=>Et.sessionId===me)?.name??me,Ue=ce===`remove-member:${me}`;return s.jsxs("div",{role:"group","aria-label":`确认移除成员 ${K}`,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:`把“${K}”移出“${dt.name}”?移出后它不再收到这个组的消息,可以随时重新加入`}),s.jsxs("div",{className:"flex shrink-0 gap-2",children:[s.jsx("button",{className:`${wr} min-h-8 bg-surface-2 px-2 text-[10px] text-foreground`,onClick:()=>Ge(null),children:"取消"}),s.jsxs("button",{disabled:ce!==null,className:`${wr} min-h-8 px-2 text-[10px] bg-destructive text-destructive-foreground`,onClick:()=>{Mn(me)},children:[Ue?s.jsx(gn,{size:12,className:"animate-spin"}):s.jsx(zs,{size:12}),"移出"]})]})]})})(),Vt&&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:["已选 ",pt.size]})]}),s.jsx("div",{className:"mt-3 max-h-72 divide-y divide-border/10 overflow-y-auto border-y border-border/10",children:Tn.length<=1?_n.map(Or):Tn.map(K=>{const Ue=ir(K.key);return s.jsxs("div",{children:[s.jsx(Ib,{label:K.label,count:K.sessions.length,collapsed:Ue,onToggle:()=>pn(K.key)}),!Ue&&s.jsx("div",{className:"divide-y divide-border/10",children:K.sessions.map(Or)})]},K.key)})}),s.jsxs("div",{className:"mt-3 flex justify-end gap-2",children:[s.jsx("button",{className:`${wr} bg-surface-2 text-foreground`,onClick:()=>{jt(!1),De({})},children:"取消"}),s.jsxs("button",{disabled:ce!==null||v!=="loaded",className:`${wr} bg-primary text-primary-foreground`,onClick:()=>{Br()},children:[ce==="save-members"?s.jsx(gn,{size:13,className:"animate-spin"}):s.jsx(hi,{size:13}),"保存成员"]})]})]}),er&&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(mO,{group:dt,value:gt,onChange:bt,disabled:ce!==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:Fs,disabled:!!gt,value:dt.launchProfiles?.find(K=>K.id===gt)?.agentSlug??Ct,onChange:K=>Nt(K.target.value),children:E.map(K=>s.jsxs("option",{value:K.slug,children:[K.displayName,K.isPlugin?" · Plugin":""]},K.slug))})]}),s.jsxs("label",{className:"space-y-1 text-[9px] text-muted-foreground",children:["会话名称",s.jsx("input",{"aria-label":"新 Agent 会话名称",className:Fs,value:It,onChange:K=>yt(K.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:Fs,value:pr,onChange:K=>nr(K.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:`${Fs} min-h-16 resize-y`,value:Cr,onChange:K=>cn(K.target.value),placeholder:"说明它加入后要先完成什么"})]}),s.jsxs("div",{className:"mt-3 flex justify-end gap-2",children:[s.jsx("button",{className:`${wr} bg-surface-2 text-foreground`,onClick:()=>et(!1),children:"取消"}),s.jsxs("button",{disabled:ce!==null||!Ct||!!gt&&!dt.launchProfiles?.some(K=>K.id===gt),className:`${wr} bg-primary text-primary-foreground`,onClick:()=>{nn()},children:[ce==="spawn-agent"?s.jsx(gn,{size:13,className:"animate-spin"}):s.jsx(E0,{size:13}),"创建并加入"]})]})]})]})]},dt.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:[Fr.length," 条"]})]}),s.jsxs("div",{className:"divide-y divide-border/10 border-y border-border/10 [overflow-wrap:anywhere]",children:[Fr.map(K=>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:K.responseKind==="ack"?"收到确认":K.responseKind==="progress"?"进展":K.responseKind==="result"?"结果":$O(K.kind)}),s.jsx("span",{children:K.fromName}),s.jsx("span",{children:"→"}),s.jsx("span",{className:"truncate",children:K.toNames.join("、")}),s.jsx("span",{className:"ml-auto shrink-0",children:new Date(K.createdAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),s.jsx("p",{className:"mt-1 whitespace-pre-wrap text-[11px] leading-relaxed text-foreground",children:K.content}),s.jsx("p",{className:"mt-1 text-[9px] text-muted-foreground",children:K.status==="pending"?"已入队 · 等待投递":K.status==="failed"?"投递失败":K.status==="expired"?"消息已过期,未继续投递":K.status==="stored"?"答复已持久保存 · 供后台接收":"已写入接收方终端 · 等待接手确认"}),(K.task||K.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(K.task??{failure_reason:K.failureReason},null,2)})]})]},K.key)),Fr.length===0&&s.jsx(ZO,{text:Ie?"正在加载协作记录…":"还没有消息。可以直接给成员发送说明或问题。"})]})]})]})]})]})]})}function MO({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)&&!Pu(Y.sessionId)),[y,w]=b.useState(()=>kO(e,r&&x.some(Y=>Y.sessionId===r)?r:"")),v=b.useRef(y),[S,L]=b.useState(null),E=Y=>{const Ae={...v.current,...Y};v.current=Ae,LO(e.id,Ae),w(Ae)},{name:R,rules:B,savedName:W,savedRules:F,rulesVersion:U,rulesMemberId:V}=y,Z=Bf(y),ce=new TextEncoder().encode(B).length,xe=x.some(Y=>Y.sessionId===V),pe=async()=>{if(!(a||!R.trim())){c("group-name"),l(null),d(null);try{const Y=await ac({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===F?{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 Jd&&Y.status===409?"组设置已被其他人修改。请查看最新状态并确认,名称与群规草稿仍保留。":Y instanceof Error?Y.message:"改名失败")}finally{c(null)}}},te=async()=>{if(!(a||!xe||ce>8192)){c("group-rules"),l(null),d(null);try{const Y=await Uw(e.id,{sessionId:V,text:B,expectedVersion:U});L(null),E({savedName:Y.group.name,...R===W?{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 Jd&&Y.status===409?"群规已被其他人修改。请查看最新状态并确认,名称与群规草稿仍保留。":Y instanceof Error?Y.message:"群规保存失败")}finally{c(null)}}},ke=()=>{E(Lg(e,V)),L(null),l(null)},$e=async()=>{if(!a){c("group-latest"),l(null),d(null),L(null);try{const Ae=(await B1()).groups.find(lt=>lt.id===e.id);if(!Ae)throw new Error("协作组已删除;草稿仍保留,请返回看板查看。");L(Ae)}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(Rn,{size:14})})]}),s.jsxs("label",{className:"block space-y-1 text-[10px] text-muted-foreground",children:["协作组名称",s.jsx("input",{autoFocus:!0,className:Fs,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()===W,className:`${wr} min-h-9 bg-primary text-primary-foreground`,onClick:()=>{pe()},children:a==="group-name"?"保存中…":"保存名称"})}),s.jsx(gO,{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:Fs,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:`${Fs} min-h-24 resize-y`,value:B,maxLength:8192,disabled:!!a,onChange:Y=>E({rules:Y.target.value}),placeholder:"例如:说明分工、交接要求和结果格式。清空后保存可移除群规。"})]})]}),!xe&&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] ${ce>8192?"text-destructive":"text-muted-foreground"}`,children:ce>8192?"内容过长,请缩短群规":"保存或清空群规会通知本组其他成员"}),s.jsx("button",{type:"button",disabled:!!a||!!S||!xe||ce>8192||B===F,className:`${wr} min-h-9 shrink-0 bg-primary text-primary-foreground`,onClick:()=>{te()},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:`${wr} mt-2 min-h-11 text-primary hover:bg-surface-elevated`,onClick:()=>{$e()},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(Ae=>Ae.sessionId===Y)?.name??W6(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:`${wr} min-h-11 bg-primary text-primary-foreground`,onClick:()=>{E(_O(v.current,S)),L(null),l(null),d("已确认最新状态,草稿仍保留;请分别保存名称与群规。")},children:"确认最新状态,保留草稿"}),s.jsx("button",{type:"button",className:`${wr} 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:`${wr} min-h-9 text-muted-foreground hover:bg-surface-elevated`,onClick:ke,children:[s.jsx(gn,{size:12}),"重新载入",Z&&"(放弃草稿)"]}),s.jsx("button",{type:"button",disabled:!!a,className:`${wr} min-h-9 bg-surface text-foreground`,onClick:m,children:Z?"关闭并保留草稿":"关闭"})]})]})}function jO({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 qw(E):await Yw(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(DO,{service:E})]}),E.serviceId&&s.jsxs("button",{type:"button",disabled:!!r,"aria-label":`移除协作连接 ${E.origin}`,className:`${wr} 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(zs,{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:zO(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:`${wr} min-h-9 text-muted-foreground`,onClick:()=>p(null),children:"取消"}),s.jsx("button",{type:"button",disabled:!!r||!!E.groups?.length,className:`${wr} 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:`${wr} mt-1 min-h-9 text-primary hover:bg-primary/10`,onClick:Vw,children:[s.jsx(gn,{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:`${wr} 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:`${wr} 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 DO({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 Sm(e){return!Pu(e.sessionId)||e.serviceConnected!==!1}function BO(e){return e.serviceOrigin?e.serviceOrigin===window.location.origin?"":e.serviceOrigin:Pu(e.sessionId)?.origin??""}function Lb(e){const t=new Map;for(const r of e){const n=BO(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 Ib({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 QO(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,...Pu(n)?{serviceConnected:!1}:{}})}return[...r.values()]}function Cm({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 tf(e){return e.serviceConnected===!1?"服务不可达":e.status==="recovering"&&e.route_error==="ROUTE_NOT_CHECKED"?"投递目标未检查":FO(e.status)}function PO(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 OO(e){e.sessionId.startsWith("remote:")?await b6(e.sessionId):window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:e.sessionId}))}function FO(e){return{ready:"终端可达",shell:"Shell 终端",recovering:"正在检查投递目标",unchecked:"投递目标未检查","terminal-connected":"终端已连接",detached:"终端未连接","agent-exited":"Agent 已退出",offline:"已离线",ambiguous:"需确认目标终端","identity-mismatch":"终端身份已变化",unavailable:"终端暂不可达","service-reachable":"服务可达","service-unreachable":"服务不可达"}[e]??"在线"}function _m(e){if(!e)return"暂无任务摘要";try{const t=JSON.parse(e);if(typeof t.prompt=="string")return Qf(t.prompt)||"暂无任务摘要"}catch{}return Qf(e)||"暂无任务摘要"}function $O(e){return{message:"消息",ask:"问题",reply:"回复",task:"任务",handoff:"交接",done:"完成"}[e]}function UO(e,t){const r=new Map(t.map(a=>[a.sessionId,PO(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 zO(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 km({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 HO({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,W]=b.useState(null),[F,U]=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,te=new AbortController;let ke;W(null),R(!0);const $e=async()=>{try{const Y=await Zw(a.trim(),w,te.signal);if(pe!==Z.current)return;d(Y.results),m(Y.total??Y.results.length),y(Y.index),Y.index?.building&&(ke=window.setTimeout(()=>{$e()},2500))}catch(Y){pe===Z.current&&!te.signal.aborted&&W(Y instanceof Error?Y.message:"搜索失败")}finally{pe===Z.current&&R(!1)}};return ke=window.setTimeout(()=>{$e()},a.trim()?250:0),()=>{window.clearTimeout(ke),te.abort(),++Z.current}},[e,a,w,S]);const ce=pe=>{n(null),c(pe),d([]),m(0),v(50)},xe=async pe=>{if(!F){if(pe.live){window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:pe.sessionId})),t();return}if(!(!pe.nativeKey&&!pe.resumeHistoryId)){U(pe.sessionId),n(null);try{const te=pe.nativeKey?await Kw(pe.nativeKey):await ky(pe.resumeHistoryId);if("sessionId"in te&&te.sessionId)window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:te.sessionId}));else if(te.command)r({mode:"shell",cwd:te.cwd,command:te.command});else throw new Error("这条会话暂时无法恢复,请重新搜索");t()}catch(te){n(te instanceof Error?te.message:"恢复失败")}finally{U(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(Ml,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),s.jsx("input",{ref:V,maxLength:512,className:`${Fs} pl-9 pr-9`,value:a,onChange:pe=>ce(pe.target.value),placeholder:"搜索会话名称、对话关键词、目录或 session ID"}),E?s.jsx(gn,{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:()=>ce(""),children:s.jsx(Rn,{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:`${wr} text-muted-foreground hover:bg-surface-2 hover:text-foreground`,onClick:()=>L(pe=>pe+1),children:[s.jsx(gn,{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 te=pe.live||!!(pe.nativeKey||pe.resumeHistoryId),ke=F===pe.sessionId?"正在恢复…":pe.live?"打开会话":te?"恢复会话":"仅供查阅",$e=pe.source==="codex"||pe.source==="claude"?pe.snippet:WO(pe),Y=pe.source==="codex"?"Codex 历史":pe.source==="claude"?"Claude 历史":"终端记录",Ae=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(km,{value:pe.title,query:a})}),s.jsx("p",{className:"mt-0.5 break-all text-[9px] text-muted-foreground",children:s.jsx(km,{value:pe.cwd||"项目目录待索引",query:a})})]}),s.jsx("span",{className:`shrink-0 text-[10px] ${pe.live?"text-[var(--success)]":te?"text-primary":"text-muted-foreground"}`,children:ke})]}),$e&&s.jsx("p",{className:"mt-2 line-clamp-3 break-words text-[10px] leading-relaxed text-foreground/75",children:s.jsx(km,{value:$e,query:a})}),s.jsxs("p",{className:"mt-2 text-[9px] text-muted-foreground",children:[Y," · ",Pf(pe.updatedAt),a.trim()?` · ${pe.matchCount>=999?"999+":pe.matchCount} 处匹配`:"",te?"":" · 没有可恢复记录"]}),pe.agentNativeSessionId&&s.jsx("p",{className:"mt-1 select-text break-all text-[9px] text-muted-foreground",children:pe.agentNativeSessionId})]});return te?s.jsx("button",{disabled:!!F,onClick:()=>{xe(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:Ae},pe.nativeKey||pe.sessionId):s.jsx("article",{className:"px-2 py-3",children:Ae},pe.sessionId)})}),p>l.length&&w<5e3&&s.jsx("button",{type:"button",disabled:E,className:`${wr} 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:`${wr} 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:`${wr} mt-3 bg-surface-2 text-foreground`,onClick:()=>ce(""),children:"查看最近会话"})]})]})}function Qf(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 WO(e){let t=Qf(e.snippet);for(const r of[e.title,e.cwd,e.agentSlug])r&&(t=t.split(r).join(" "));return Qf(t)}function GO(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 VO(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 Pf(e){return new Intl.DateTimeFormat("zh-CN",{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(e)}function qO(e){return e==="running"?"投递中":e==="success"?"已投递":e==="failed"?"投递失败":""}function YO(e){return e==="running"?"text-[var(--warning)]":e==="success"?"text-[var(--success)]":e==="failed"?"text-destructive":"text-muted-foreground"}function ZO({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 KO({onOpenSettings:e,serverAttention:t,actions:r}){const{t:n}=zr(),[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,W=(w?.offsetTop??0)+(w?.height??window.innerHeight)-8,F=Math.max(0,Math.min(256,B)),U=Math.max(0,L.top-R-4),V=Math.max(0,W-L.bottom-4),Z=U>=180||U>=V;Object.assign(y.style,{width:`${F}px`,left:`${Math.max(E,Math.min(L.right-F,E+B-F))}px`,top:`${Z?L.top-4:L.bottom+4}px`,maxHeight:`${Z?U: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(mS,{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($o,{size:15}),s.jsx("span",{children:n("sidebar.moreActions")})]}),a&&Ii.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 Qd=64,Eb=10,XO=120;function JO({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?Qd: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?Qd:0,offset:t?Qd: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>=XO||Math.abs(E)>Eb){p.current=null;return}if(Math.abs(L)<=Eb)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(Qd,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>=Qd/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(zs,{size:14}),a]})}),e]})}const Nb="recoverable-tmux";function eF({sessions:e,loading:t,attachingName:r,onRefresh:n,onRestore:a,onClose:c}){const{t:l}=zr(),d=Gt(R=>R.collapsedGroups.has(Nb)),p=Gt(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(Nb),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(fi,{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(gn,{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,W=Yu(R.cwd??null),F=r===R.name,U=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||U,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:F?s.jsx(Cn,{size:12,className:"animate-spin"}):s.jsx(Uu,{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,W].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(F?"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(Rn,{size:12})})]}),U&&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)})})]})}function tF(e,t){return zy(e,t)}function Pd(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 Od(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 Rb(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 rF({status:e,detail:t,needsReview:r,inCopyMode:n}){return s.jsx(OP,{status:e,detail:t,needsReview:r,inCopyMode:n})}function Mb({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:W,onOpenQuota:F,updateState:U,updateActionPending:V=!1,onConfirmUpdateRestart:Z,onRetryUpdate:ce,serverHealthState:xe,tmuxAvailable:pe=!0,defaultSessionMode:te="shell",push:ke,pinned:$e,onTogglePinned:Y,recoverableTmuxSessions:Ae=[],recoverableTmuxSessionsLoading:lt=!1,onRefreshRecoverableTmuxSessions:Se,onCloseRecoverableTmuxSession:ye}){const{t:_e}=zr(),[,je]=b.useState(0),[re,Oe]=b.useState(null),[Ce,Ee]=b.useState(!1),[Be,Ne]=b.useState(!1),[le,He]=b.useState(null),rt=b.useRef(!1),mt=b.useRef(0),ue=b.useCallback(G=>{G||(mt.current+=1),Ee(G)},[]),[Ye,st]=b.useState(!1),Ie=la(G=>G.groupId),[We,Te]=b.useState({}),H=Ye||Object.keys(We).length>0,oe=b.useRef(!1),be=b.useRef(!1),[Ze,Je]=b.useState(null);b.useEffect(()=>{let G=!1;return fc().then(Le=>{G||oe.current||Te(Object.fromEntries(Ky(Le.collaborationPanels?.[$f()]).map(Ke=>[Ke,!0])))}).catch(()=>{}),()=>{G=!0}},[]);const St=async(G,Le)=>{oe.current=!0,await bo({floatingGroupId:Le},G),Te(Ke=>({...Ke,[G]:Le!==null}))},[Vt,jt]=b.useState([]),[vt,Zt]=b.useState(!1),[Pt,Xt]=b.useState(null),[zt,Lt]=b.useState(null),[me,Ge]=b.useState(null),[pt,q]=b.useState(null),at=_u(G=>G.tasks),qt=_u(G=>G.allTasks),[Ve,De]=b.useState(0),[er,et]=b.useState(null),Ct=b.useRef(!1),[Nt,gt]=b.useState({}),bt=_u(G=>G.error),[It,yt]=b.useState(!1);b.useEffect(()=>{const G=()=>{document.hidden||_u.getState().refresh()};G();const Le=window.setInterval(G,5e3);return document.addEventListener("visibilitychange",G),()=>{clearInterval(Le),document.removeEventListener("visibilitychange",G)}},[]);const pr=async G=>(ue(!1),oe.current=!0,G?(la.getState().open(G),Fr(),!0):(st(!0),Fr(),!0)),nr=uf(G=>G.collaborationGroups),Cr=uf(G=>G.setCollaborationGroups),[cn,Lr]=b.useState({mode:te}),{preference:ge,agents:Vr,detecting:it,refresh:dt,selectAgent:sr}=fO(),xn=b.useRef(null),an=!!(U?.latestVersion&&["installing","ready","restarting","error"].includes(U.status)),Me=!!xe?.attention,nt=[_e("sidebar.moreActions"),Me?_e("sidebar.serverAttention"):null,an&&U?.latestVersion?_e("sidebar.updateAvailable",{version:U.latestVersion}):null].filter(Boolean).join(": "),wt=Gt(G=>G.groupByFolder),Rr=Gt(G=>G.collapsedGroups),rn=Gt(G=>G.toggleGroupCollapsed),Ir=b.useRef(null),ne=b.useRef(null),ht=b.useRef(null),Ht=b.useRef(0),Ot=b.useRef(!1),Tr=b.useRef(null),mr=b.useRef(null),[Hr,_n]=b.useState(!1),dr=b.useRef([]),bn=b.useRef(null),hn=b.useRef(null),Tn=b.useRef(new Set),ir=b.useRef(null),pn=b.useMemo(()=>new Set(v.flatMap(G=>G.sessionIds)),[v]),Pr=b.useMemo(()=>new Map(a.map(G=>[G.id,G])),[a]),qr=b.useMemo(()=>tF(nr,new Set(Pr.keys())),[nr,Pr]),Wr=b.useCallback(async()=>{const G=++Ht.current;try{const Le=await B1();if(G!==Ht.current)return;Cr(Array.isArray(Le.groups)?Le.groups:[])}catch{}},[]);b.useEffect(()=>_y(G=>Cr(G.groups)),[]),b.useEffect(()=>{Wr();const G=window.setInterval(()=>{Wr()},1e4),Le=()=>{Wr()};return window.addEventListener("focus",Le),()=>{Ht.current+=1,window.clearInterval(G),window.removeEventListener("focus",Le)}},[Wr]),b.useEffect(()=>{(e||!H)&&Wr()},[H,e,Wr]);const fs=b.useCallback(()=>{dr.current=Array.from(document.querySelectorAll("[data-collaboration-member], [data-collaboration-background]")).flatMap(G=>{const Le=G.dataset.collaborationMember??"",Ke=G.hasAttribute("data-collaboration-background"),ct=G.closest("[data-collaboration-group]")?.dataset.collaborationGroup;if(!Le&&!Ke||!ct)return[];const qe=[];for(let At=G.parentElement;At;At=At.parentElement)qe.push({element:At,top:At.scrollTop,left:At.scrollLeft});return[{element:G,sessionId:Le,groupId:ct,background:Ke,rect:G.getBoundingClientRect(),scrollParents:qe}]})},[]),Br=b.useCallback((G,Le)=>{if(!Ot.current)return;document.querySelectorAll("[data-split-exit-drop-index]").forEach(N=>N.removeAttribute("data-active")),document.querySelectorAll("[data-drop-active]").forEach(N=>N.removeAttribute("data-drop-active"));const ct=document.elementsFromPoint(G,Le).map(N=>N.closest("[data-collaboration-background]")).find(Boolean)?.closest("[data-collaboration-group]");if(ct?.dataset.collaborationGroup){ct.dataset.dropActive="true",hn.current={kind:"collaboration",groupId:ct.dataset.collaborationGroup,background:!0};return}const qe=dr.current.find(N=>{if(N.sessionId===mr.current||!N.element.isConnected)return!1;const $=N.scrollParents.reduce((ie,Qe)=>ie+Qe.element.scrollLeft-Qe.left,0),ee=N.scrollParents.reduce((ie,Qe)=>ie+Qe.element.scrollTop-Qe.top,0);return G>=N.rect.left-$&&G<=N.rect.right-$&&Le>=N.rect.top-ee+N.rect.height*.25&&Le<=N.rect.bottom-ee-N.rect.height*.25});if(qe?.background){qe.element.closest("[data-collaboration-group]")?.setAttribute("data-drop-active","true"),hn.current={kind:"collaboration",groupId:qe.groupId,background:!0};return}if(qe&&!v.find($=>$.sessionIds.includes(qe.sessionId))?.sessionIds.includes(mr.current??"")){qe.element.dataset.dropActive="true",hn.current={kind:"split",sessionId:qe.sessionId,groupId:qe.groupId};return}const At=document.elementsFromPoint(G,Le).filter(N=>{const $=N.closest("[data-rfd-draggable-id]");return!$||!["session:","split-member:","collaboration-member:"].some(ee=>$.dataset.rfdDraggableId===`${ee}${mr.current}`)}),Rt=At.map(N=>N.closest("[data-collaboration-group]")).find(N=>N?.dataset.collaborationGroup);if(Rt?.dataset.collaborationGroup){const N=Rt.dataset.collaborationGroup,$=At.map(ze=>ze.closest("[data-collaboration-split]")).find(Boolean),ee=At.map(ze=>ze.closest("[data-collaboration-member]")).find(Boolean),ie=ee?.dataset.collaborationMember??$?.dataset.splitAnchor,Qe=N===Tr.current&&v.some(ze=>ze.sessionIds.includes(ie??"")&&ze.sessionIds.includes(mr.current??""));if(ie&&!Qe&&(N!==Tr.current||!ee&&$)){Rt.dataset.dropActive="true";const ze=ee??$;ze&&(ze.dataset.dropActive="true"),hn.current={kind:"split",sessionId:ie,groupId:N}}else{const ze=At.some(xt=>xt.closest("[data-collaboration-background]"));(N!==Tr.current||ze)&&(Rt.dataset.dropActive="true"),hn.current={kind:"collaboration",groupId:N,background:ze}}return}const ot=Array.from(document.querySelectorAll("[data-sidebar-entity-list-id]")).filter(N=>N.dataset.sidebarEntityListId===bn.current).find(N=>{const $=N.getBoundingClientRect();return G>=$.left&&G<=$.right&&Le>=$.top-8&&Le<=$.bottom+8});if(!ot){hn.current=null;return}const Ft=Array.from(ot.children).filter(N=>N instanceof HTMLElement&&N.hasAttribute("data-sidebar-entity-index")),hr=Ft.findIndex(N=>{const $=N.getBoundingClientRect();return Le<$.top+$.height/2}),Kt=hr<0?Ft.length:hr;hn.current={kind:"list",listId:ot.dataset.sidebarEntityListId??"",index:Kt};const z=Array.from(ot.querySelectorAll(":scope > [data-sidebar-entity-index] > [data-split-exit-drop-index]")).find(N=>N.dataset.splitExitDropIndex===String(Kt));z instanceof HTMLElement&&(z.dataset.active="true")},[v]);b.useEffect(()=>{const G=Ke=>Br(Ke.clientX,Ke.clientY),Le=Ke=>{const ct=Ke.touches[0];ct&&Br(ct.clientX,ct.clientY)};return window.addEventListener("pointermove",G),window.addEventListener("touchmove",Le,{passive:!0}),()=>{window.removeEventListener("pointermove",G),window.removeEventListener("touchmove",Le)}},[Br]);const Mn=b.useCallback((G,Le)=>{try{G(Le)}finally{document.querySelectorAll("[data-sidebar-dragging]").forEach(Ke=>{delete Ke.dataset.sidebarDragging}),Ot.current=!1,dr.current=[],_n(!1),Tr.current=null,mr.current=null,bn.current=null,hn.current=null,document.querySelectorAll("[data-split-exit-drop-index]").forEach(Ke=>Ke.removeAttribute("data-active")),document.querySelectorAll("[data-drop-active]").forEach(Ke=>Ke.removeAttribute("data-drop-active"))}},[]),Sr=b.useMemo(()=>a.filter(G=>!pn.has(G.id)),[a,pn]),Kr=b.useMemo(()=>{let G=0;for(const Le of a)l.get(Le.id)?.agentStatus==="working"&&(G+=1);return G},[a,l]);b.useLayoutEffect(()=>{const G=Ir.current,Le=ne.current;if(!e||!G||!Le){ht.current=null;return}const Ke=Le.getBoundingClientRect(),ct=G.getBoundingClientRect(),qe={item:G,top:Math.round(ct.top-Ke.top+Le.scrollTop),height:Math.round(ct.height),viewportHeight:Le.clientHeight},At=ht.current;if(ht.current=qe,At?.item===qe.item&&At.top===qe.top&&At.height===qe.height&&At.viewportHeight===qe.viewportHeight||Ot.current||Le.clientHeight===0)return;const Rt=8,Bt=ct.top-Ke.top,ot=ct.bottom-Ke.top;Bt<Rt?Le.scrollTop+=Bt-Rt:ot>Le.clientHeight-Rt&&(Le.scrollTop+=ot-Le.clientHeight+Rt)});const nn=b.useMemo(()=>{if(!wt||!c)return null;const G=l.get(c)?.cwd??null;return $S(G)},[wt,c,l]);b.useEffect(()=>{if(!wt){ir.current=null,Tn.current.clear();return}if(!c){ir.current=null;return}const G=Gt.getState(),Le=Tn.current,Ke=ir.current,ct=nn;Ke!==null&&Ke!==ct&&Le.has(Ke)&&(G.collapsedGroups.has(Ke)||G.toggleGroupCollapsed(Ke),Le.delete(Ke)),ct!==null&&ct!==""&&G.collapsedGroups.has(ct)&&(G.toggleGroupCollapsed(ct),Le.add(ct)),ir.current=ct},[wt,c,nn]),b.useEffect(()=>{e||ue(!1)},[e]),b.useEffect(()=>{Lr(G=>({...G,command:ge?.command}))},[ge]),b.useEffect(()=>{if(!Ce)return;let G=!1;return Zt(!0),Lt(null),a2().then(Le=>{G||jt(Le)}).catch(()=>{G||Lt(_e("sidebar.resumeHistoryLoadFailed"))}).finally(()=>{G||Zt(!1)}),()=>{G=!0}},[Ce,_e]),b.useEffect(()=>{if(!re)return;const G=Le=>{Le instanceof KeyboardEvent&&Le.key!=="Escape"||Le instanceof PointerEvent&&Le.target instanceof Node&&xn.current?.contains(Le.target)||Oe(null)};return window.addEventListener("pointerdown",G),window.addEventListener("keydown",G),()=>{window.removeEventListener("pointerdown",G),window.removeEventListener("keydown",G)}},[re]);const Fr=()=>{!ke&&!$e&&r()};b.useEffect(()=>{const G=Le=>{ue(!1);const{groupId:Ke,dock:ct}=Le.detail;oe.current=!0,es.getState().setDock(Ke,{...ct,preferredWidth:360}),Te(qe=>({...qe,[Ke]:!0})),la.getState().terminal(),Fr()};return window.addEventListener("termdock:open-collaboration-messages",G),()=>window.removeEventListener("termdock:open-collaboration-messages",G)},[Fr]);const ks=te==="tmux"&&!pe?"shell":te,Or=(G,Le=!1)=>{if(rt.current)return;rt.current=!0,Ne(!0),He(null);const Ke=mt.current;p({...G,shouldActivate:()=>Ke===mt.current&&(G.shouldActivate?.()??!0),onResult:ct=>{if(rt.current=!1,Ne(!1),!ct.ok){He(ct.error);return}Ke===mt.current&&(Le&&ue(!1),Fr())}})},Xr=()=>{Or({mode:ks})},fn=()=>{ge&&Or({mode:ks,command:ge.command})},K=G=>{ue(!1),Ge(G.name),p({mode:"tmux",tmuxSessionName:G.name,cwd:G.cwd??void 0}),Fr()};b.useEffect(()=>{me&&(Ae.some(G=>G.name===me)||Ge(null))},[me,Ae]);const Ue=(G,Le)=>{Or({...cn,cwd:cn.cwd?.trim()||void 0,command:Le??G?.command},!0)},Et=async G=>{Xt(G.id),Lt(null);try{const Le=await ky(G.id);Or({mode:"shell",cwd:Le.cwd,command:Le.command},!0)}catch(Le){const Ke=Le&&typeof Le=="object"&&"code"in Le?String(Le.code??""):"";Lt(_e(Ke==="AGENT_SESSION_ACTIVE_ELSEWHERE"?"tab.resumeAgentConflict":"sidebar.resumeHistoryFailed"))}finally{Xt(null)}},kt=async G=>{jt(Le=>Le.filter(Ke=>Ke.id!==G));try{await o9(G)}catch{Lt(_e("sidebar.resumeHistoryRemoveFailed")),a2().then(jt).catch(()=>{})}},tr=()=>{if(Ce){ue(!1);return}rt.current||(mt.current+=1,rt.current||He(null),Lr({mode:te==="tmux"&&!pe?"shell":te,cwd:c?l.get(c)?.cwd??void 0:void 0,command:ge?.command}),ue(!0))},Qr=b.useCallback(G=>{const Le=l.get(G);return Le?.agentStatus==="waiting"||Le?.agentNeedsReview?"bg-[rgb(var(--warning-rgb)_/_0.10)] text-foreground":Le?.agentStatus==="working"?"bg-[rgb(var(--success-rgb)_/_0.08)] text-foreground":Le?.inCopyMode?"bg-[rgb(var(--tmux-rgb)_/_0.08)] text-foreground":null},[l]),cr=g6(),[Sn,Ls]=b.useState(null);b.useEffect(()=>{e||Ls(null)},[e]);const Zn=b.useCallback((G,Le,Ke,ct,qe)=>{const At=!Ie&&G.id===c,Rt=pn.has(G.id),Bt=!!(Ke&&Rt),ot=l.get(G.id),Ft=Yu(ot?.cwd??null),hr=ot?.shellTitle??Jw(G.id),Kt=hr===ot?.cwd||hr===Ft?null:hr,z=e9(G,ot?.activeProgram??null,null,t9,Kt,ot?.promptState??null),N=!!(ot?.tuiProgress&&ot.tuiProgress.state!=="remove"),ee=ot?.promptState==="running"||ot?.agentStatus==="working"||N?"bg-[var(--success)]":ot?.agentStatus==="waiting"||ot?.agentNeedsReview?"bg-[var(--warning)]":ot?.inCopyMode?"bg-[var(--tmux)]":"bg-primary";return s.jsxs(JO,{open:Sn===G.id,onOpenChange:ie=>Ls(Qe=>ie?G.id:Qe===G.id?null:Qe),onClose:ie=>m(G.id,ie,{skipConfirmation:!0}),closeLabel:_e("common.close"),closeTitle:_e("sidebar.closeSession",{name:z}),compact:Ke,children:[s.jsxs("button",{ref:At?Ir:null,type:"button",...Le??{},onContextMenu:ie=>{B&&(ie.preventDefault(),B(G.id,{x:ie.clientX,y:ie.clientY}))},onClick:()=>{ue(!1),la.getState().terminal(),window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:G.id})),Fr()},className:`sidebar-session-primary relative min-w-0 flex flex-1 items-center overflow-hidden text-left ${Le?"cursor-grab active:cursor-grabbing ":""}${Ke?"gap-1.5 py-0.5 pl-1.5 pr-0.5":"gap-1.5 py-1 pl-2 pr-1"}`,title:ot?.cwd??G.name,children:[At&&s.jsx("span",{className:`absolute inset-y-2 left-0 w-0.5 rounded-full ${ee}`}),s.jsxs("span",{className:`relative inline-flex shrink-0 items-center justify-center rounded-md ${Ke?"h-5 w-[22px]":"h-[22px] w-[22px]"} ${At?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:[ot?.isConnecting||N&&!ot?.agentStatus?s.jsx(Cn,{size:Ke?10:11,className:"animate-spin"}):ot?.agent??o2(G.id)?s.jsx(Wc,{agent:ot?.agent??o2(G.id),size:Ke?13:15}):G.mode==="tmux"?s.jsx(Uu,{size:Ke?10:11}):s.jsx(Fo,{size:Ke?10:11}),s.jsx(rF,{status:ot?.agentStatus??null,detail:ot?.agentStatusDetail,needsReview:ot?.agentNeedsReview,inCopyMode:ot?.inCopyMode})]}),s.jsx("span",{className:`min-w-0 flex-1 truncate leading-tight ${Ke?"text-[11px]":"text-[12px]"} ${At?"font-medium text-foreground":""} ${ot?.inCopyMode?"text-[color:var(--tmux)]":""}`,children:z}),s.jsx(O5,{sessionIds:[G.id]})]}),ct,s.jsx("button",{type:"button",onClick:ie=>{ie.stopPropagation(),Bt?w(G.id):Rt?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 ${Ke?"h-6 w-6":"h-[26px] w-[26px]"} ${Rt?"bg-primary/15 text-primary":"text-muted-foreground/70"}`,"aria-label":`${_e(Bt?"tab.splitRemovePane":Rt?"tab.splitClose":"tab.split")} ${z}`,title:_e(Bt?"tab.splitRemovePane":Rt?"tab.splitClose":"tab.split"),children:Bt?s.jsx(ES,{size:11}):s.jsx(Il,{size:12})}),qe??s.jsx("button",{type:"button",onClick:ie=>{ie.stopPropagation(),m(G.id,ie)},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 ${Ke?"h-6 w-6":"h-[26px] w-[26px]"}`,"aria-label":_e("sidebar.closeSession",{name:z}),title:_e("common.close"),children:s.jsx(Rn,{size:Ke?11:12})})]})},[c,pn,l,m,x,y,w,B,_e,Sn]),sn=b.useMemo(()=>lf(a,G=>l.get(G.id)?.cwd??null,wt,_e("sidebar.ungrouped"),v,qr).groups,[qr,wt,a,l,v,_e]),on=b.useMemo(()=>Od(a,v,Pr,qr),[qr,a,Pr,v]),_r=b.useCallback(G=>{_n(G.draggableId.startsWith("collaboration:")||G.draggableId.startsWith("workspace:"));const Le=G.draggableId.replace(/^split-member:/,"");mr.current=G.draggableId.replace(/^(?:session|split-member|collaboration-member):/,"");const Ke=G.type==="split-member"?v.find(Bt=>Bt.sessionIds.includes(Le)):null,ct=G.type==="collaboration-member"?G.source.droppableId.replace(/^collaboration-members:/,""):null,qe=ct?qr.find(Bt=>Bt.id===ct):null;Ot.current=!!(Ke||qe||G.type==="session"&&G.draggableId.startsWith("session:")),Ot.current&&document.querySelectorAll("[data-collaboration-group]").forEach(Bt=>{Bt.dataset.sidebarDragging="true"}),Tr.current=qe?.id??null;const At=Ke?.sessionIds??qe?.sessionIds??[],Rt=At.length>0?sn.find(Bt=>At.every(ot=>Bt.sessions.some(Ft=>Ft.id===ot))):null;bn.current=wt?Rt?`group-sessions:${Rt.key}`:null:At.length>0?"sidebar-entities":null,hn.current=null},[qr,sn,wt,v]),$r=b.useCallback((G,Le,Ke)=>{if(Le===Ke)return;const ct=Le?nr.find(ot=>ot.id===Le):null,qe=Ke?nr.find(ot=>ot.id===Ke):null;if(Ke&&!qe)return;if(qe){const ot=a.map(hr=>hr.id).filter(hr=>hr!==G);let Ft=-1;ot.forEach((hr,Kt)=>{qe.sessionIds.includes(hr)&&(Ft=Kt)}),Ft>=0&&(ot.splice(Ft+1,0,G),R(ot))}const At=ct?.sessionIds.filter(ot=>ot!==G)??[],Rt=qe?[...qe.sessionIds.filter(ot=>ot!==G),G]:[];Cr(ot=>ot.flatMap(Ft=>Ft.id===Le?[{...Ft,sessionIds:At}]:Ft.id===Ke?[{...Ft,sessionIds:Rt}]:[Ft])),q(null),(ct&&qe?r9({sourceGroupId:ct.id,targetGroupId:qe.id,sessionId:G,expectedSourceUpdatedAt:ct.updatedAt,expectedTargetUpdatedAt:qe.updatedAt}):ct?ac({id:ct.id,name:ct.name,sessionIds:At,expectedUpdatedAt:ct.updatedAt}):qe?ac({id:qe.id,name:qe.name,sessionIds:Rt,expectedUpdatedAt:qe.updatedAt}):Promise.resolve()).then(()=>Wr(),ot=>(q(ot instanceof Error?ot.message:"协作成员移动失败"),Wr()))},[nr,Wr,a,R]),Wn=b.useCallback((G,Le,Ke,ct=!1)=>{const qe=nr.find($=>$.id===G);if(!qe||Le===Ke)return;const At=qe.sessionIds.filter($=>!$.startsWith("remote:")),Rt=Pd(At,v).flatMap($=>$.sessionIds),Bt=Q5(qt,qe.id),ot=ct&&!Nt[qe.id]?Rt.filter($=>!Bt.has($)||$===c||pn.has($)):Rt.slice(),Ft=new Set(ot),[hr]=ot.splice(Le,1);if(!hr)return;ot.splice(Ke,0,hr);let Kt=0;const z=Rt.map($=>Ft.has($)?ot[Kt++]:$),N=v.find($=>$.sessionIds.includes(hr));if(N&&N.sessionIds.every($=>qe.sessionIds.includes($))){const $=z.filter(ee=>N.sessionIds.includes(ee));L(N.id,$)}z.push(...qe.sessionIds.filter($=>$.startsWith("remote:"))),Cr($=>$.map(ee=>ee.id===G?{...ee,sessionIds:z}:ee)),q(null),ac({id:qe.id,name:qe.name,sessionIds:z,expectedUpdatedAt:qe.updatedAt}).then(()=>Wr(),$=>(q($ instanceof Error?$.message:"成员排序失败"),Wr()))},[nr,Wr,v,L,qt,Nt,c,pn]);b.useEffect(()=>{const G=Le=>{const{sourceId:Ke,targetId:ct}=Le.detail;if(!Ke||!ct||Ke===ct)return;const qe=lf(a,ie=>l.get(ie.id)?.cwd??null,wt,"",v,qr).arranged.map(ie=>ie.id),At=qe.indexOf(Ke),Rt=qe.indexOf(ct);if(At<0||Rt<0)return;const Bt=qr.find(ie=>ie.sessionIds.includes(Ke));if(Bt?.sessionIds.includes(ct)){const ie=Pd(Bt.sessionIds,v).flatMap(Qe=>Qe.sessionIds);Wn(Bt.id,ie.indexOf(Ke),ie.indexOf(ct));return}const ot=v.filter(ie=>ie.sessionIds.length>=2&&ie.sessionIds.every(Qe=>Pr.has(Qe))&&!qr.some(Qe=>ie.sessionIds.some(ze=>Qe.sessionIds.includes(ze)))),Ft=ot.find(ie=>ie.sessionIds.includes(Ke));if(Ft?.sessionIds.includes(ct)){const ie=[...Ft.sessionIds];ie.splice(ie.indexOf(Ke),1),ie.splice(Ft.sessionIds.indexOf(ct),0,Ke),L(Ft.id,ie);return}const hr=ie=>qr.find(Qe=>Qe.sessionIds.includes(ie))?.sessionIds??ot.find(Qe=>Qe.sessionIds.includes(ie))?.sessionIds??[ie],Kt=new Set(hr(Ke)),z=new Set(hr(ct)),N=qe.filter(ie=>!Kt.has(ie)),$=N.flatMap((ie,Qe)=>z.has(ie)?[Qe]:[]),ee=At<Rt?Math.max(...$)+1:Math.min(...$);N.splice(ee,0,...qe.filter(ie=>Kt.has(ie))),R(N)};return window.addEventListener("reorder-navigation-session",G),()=>window.removeEventListener("reorder-navigation-session",G)},[a,l,wt,v,qr,Pr,Wn,L,R]);const Gn=b.useCallback(G=>{if(G.type!=="collaboration-member")return!1;if(G.reason==="CANCEL")return!0;const Le=G.source.droppableId.replace(/^collaboration-members:/,""),Ke=G.draggableId.replace(/^collaboration-member:/,""),ct=hn.current;if(ct?.kind==="split")return $r(Ke,Le,ct.groupId),E(ct.sessionId,Ke),!0;if(ct?.kind==="collaboration"&&ct.groupId!==Le)return $r(Ke,Le,ct.groupId),!0;if(ct?.kind==="collaboration"&&ct.background)return pn.has(Ke)&&w(Ke),!0;if(G.destination&&G.destination.droppableId!==G.source.droppableId){const qe=G.destination.droppableId.replace(/^collaboration-members:/,"");if(qr.some(At=>At.id===qe))return $r(Ke,Le,qe),!0}if(G.combine){const qe=G.combine.droppableId.replace(/^collaboration-members:/,"");qe!==Le&&$r(Ke,Le,qe);const At=G.combine.draggableId.replace(/^collaboration-member:/,"");if(v.find(Bt=>Bt.sessionIds.includes(Ke))?.sessionIds.includes(At)){const Bt=qr.find(Ft=>Ft.id===Le),ot=Bt?Pd(Bt.sessionIds,v).flatMap(Ft=>Ft.sessionIds).indexOf(At):-1;ot>=0&&Bt&&Wn(Le,Pd(Bt.sessionIds,v).flatMap(Ft=>Ft.sessionIds).indexOf(Ke),ot)}else Pr.has(At)&&E(At,Ke);return!0}if(G.destination?.droppableId===G.source.droppableId)return Wn(Le,G.source.index,G.destination.index,!0),!0;if(ct?.kind!=="list")return!0;if(ct?.kind==="list"){const qe=sn.find(Rt=>`group-sessions:${Rt.key}`===ct.listId),At=ct.listId==="sidebar-entities"?on:qe?Od(qe.sessions,v,Pr,qr):null;if(At){const Rt=Rb(At,Ke,ct.index);ct.listId==="sidebar-entities"?R(Rt):qe&&R(sn.flatMap(Bt=>Bt.key===qe.key?Rt:Bt.sessions.map(ot=>ot.id)))}}return $r(Ke,Le,null),!0},[qr,on,sn,$r,R,Wn,Pr,v,pn,w,E]),un=b.useCallback(G=>{if(G.type!=="split-member")return!1;if(G.reason==="CANCEL")return!0;const Le=G.draggableId.replace(/^split-member:/,""),Ke=v.find(ot=>ot.sessionIds.includes(Le));if(!Ke?.sessionIds.includes(Le))return!0;const ct=Ke.id,qe=hn.current;if(qe?.kind==="split")return $r(Le,null,qe.groupId),E(qe.sessionId,Le),!0;if(qe?.kind==="collaboration")return $r(Le,null,qe.groupId),!0;if(!G.destination&&qe?.kind==="list"){const ot=sn.find(Kt=>`group-sessions:${Kt.key}`===qe.listId),Ft=qe.listId==="sidebar-entities"?on:ot?Od(ot.sessions,v,Pr,qr):null;if(!Ft)return!0;const hr=Rb(Ft,Le,qe.index);return w(Le),qe.listId==="sidebar-entities"?R(hr):ot&&R(sn.flatMap(Kt=>Kt.key===ot.key?hr:Kt.sessions.map(z=>z.id))),!0}if(!G.destination)return!0;const At=G.destination.droppableId.replace(/^split-members:/,"");if(At!==ct){const Ft=v.find(hr=>hr.id===At)?.sessionIds[0];return Ft&&E(Ft,Le),!0}if(G.source.index===G.destination.index)return!0;const Rt=[...Ke.sessionIds],[Bt]=Rt.splice(G.source.index,1);return Bt&&(Rt.splice(G.destination.index,0,Bt),L(ct,Rt)),!0},[qr,on,sn,$r,E,w,R,L,Pr,v]),Kn=(G,Le="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 ${Le==="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,Le,Ke)=>{if(Gn(G)||un(G)||G.reason==="CANCEL")return;const ct=Le.find(ot=>ot.id===G.draggableId);if(!ct)return;const qe=hn.current;if(qe?.kind==="split"&&ct.kind==="session"){$r(ct.session.id,null,qe.groupId),E(qe.sessionId,ct.session.id);return}if(qe?.kind==="collaboration"&&ct.kind==="session"){$r(ct.session.id,null,qe.groupId);return}if(G.combine&&ct.kind!=="session"){const ot=Le.findIndex(Ft=>Ft.id===G.combine?.draggableId);if(ot<0)return;G={...G,combine:null,destination:{...G.source,index:ot}}}if(G.combine){const ot=Le.find(N=>N.id===G.combine?.draggableId);if(!ot)return;const Ft=ot.kind==="workspace"?ot:ct.kind==="workspace"?ct:ot,hr=Ft===ct?ot:ct,Kt=Ft.sessionIds[0],z=hr.sessionIds[0];Kt&&z&&Kt!==z&&E(Kt,z);return}if(!G.destination||G.source.index===G.destination.index)return;const At=[...Le],[Rt]=At.splice(G.source.index,1);if(!Rt)return;At.splice(G.destination.index,0,Rt);const Bt=At.flatMap(ot=>ot.sessionIds);if(Ke===void 0){R(Bt);return}R(sn.flatMap(ot=>ot.key===Ke?Bt:ot.sessions.map(Ft=>Ft.id)))},[sn,Gn,un,$r,E,R]),Er=b.useCallback(G=>{if(G.reason==="CANCEL"||Gn(G)||un(G))return;if(G.type==="group"){if(!G.destination||G.source.index===G.destination.index)return;R(Uy(sn,G.source.index,G.destination.index));return}const Le=G.source.droppableId.replace(/^group-sessions:/,""),Ke=sn.find(qe=>qe.key===Le);if(!Ke)return;const ct=Od(Ke.sessions,v,Pr,qr);if(G.combine||hn.current?.kind==="collaboration"||hn.current?.kind==="split"){kr(G,ct,Le);return}!G.destination||G.destination.droppableId!==G.source.droppableId||kr(G,ct,Le)},[qr,sn,Pr,v,Gn,kr,un,R]),gr=G=>{const Le=re===G.id,Ke=[{layout:"horizontal",label:_e("tab.splitHorizontal"),icon:Il},{layout:"vertical",label:_e("tab.splitVertical"),icon:h2},...G.sessionIds.length>=3||G.layout==="grid"?[{layout:"grid",label:_e("tab.splitGrid"),icon:d2}]:[]],ct=G.layout==="vertical"?h2:G.layout==="grid"?d2:Il,qe=Ke.find(At=>At.layout===G.layout)?.label??_e("tab.splitHorizontal");return s.jsxs("div",{ref:Le?xn:void 0,className:"relative shrink-0",onPointerDown:At=>At.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 ${Le?"bg-primary/15 text-primary":"text-muted-foreground/70 hover:bg-surface-2 hover:text-foreground"}`,"aria-label":`${_e("tab.splitLayout")}: ${qe}`,"aria-haspopup":"menu","aria-expanded":Le,title:_e("tab.splitLayout"),onClick:At=>{At.stopPropagation(),Oe(Rt=>Rt===G.id?null:G.id)},children:s.jsx(ct,{size:12})}),Le&&s.jsx("div",{role:"menu","aria-label":_e("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:Ke.map(At=>{const Rt=At.icon,Bt=At.layout===G.layout;return s.jsx("button",{type:"button",role:"menuitemradio","aria-checked":Bt,"aria-label":At.label,title:At.label,className:`sidebar-session-action inline-flex h-7 w-7 items-center justify-center rounded-sm transition active:scale-95 ${Bt?"bg-primary/15 text-primary":"text-muted-foreground hover:bg-surface-2 hover:text-foreground"}`,onClick:ot=>{ot.stopPropagation(),S(G.sessionIds[0],At.layout),Oe(null)},children:s.jsx(Rt,{size:13})},At.layout)})})]})},rs=(G,Le)=>Le&&s.jsx("button",{type:"button",...Le,"aria-label":G,title:G,onClick:Ke=>Ke.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(Ff,{size:10})}),$n=(G,Le,Ke=!1,ct=!1,qe)=>{if(Le.length<2)return null;const At=Le.some(Kt=>Kt.id===c),Rt=[],Bt=[],ot=[];for(const Kt of Le){const z=l.get(Kt.id);z?.agentStatus==="waiting"||z?.agentNeedsReview?Rt.push(Kt):z?.agentStatus==="working"?Bt.push(Kt):z?.inCopyMode&&ot.push(Kt)}const Ft=G.name?.trim()||`${_e("tab.splitWorkspace")} ${v.findIndex(Kt=>Kt.id===G.id)+1}`,hr=re===G.id;return s.jsxs("section",{"data-split-workspace":G.id,"aria-label":Ft,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 ${ct?"bg-primary/15 ring-1 ring-primary/40":Ke?"bg-surface-elevated opacity-90 shadow-lg":Rt.length>0?"bg-[rgb(var(--warning-rgb)_/_0.08)] hover:bg-[rgb(var(--warning-rgb)_/_0.12)]":Bt.length>0?"bg-[rgb(var(--success-rgb)_/_0.06)] hover:bg-[rgb(var(--success-rgb)_/_0.10)]":ot.length>0?"bg-[rgb(var(--tmux-rgb)_/_0.07)] hover:bg-[rgb(var(--tmux-rgb)_/_0.11)]":At?"bg-primary/[0.07]":"hover:bg-surface-2"}`,children:[rs(`移动分屏组 ${Ft}`,qe),s.jsx(Ll,{droppableId:`split-members:${G.id}`,type:"split-member",direction:"vertical",children:(Kt,z)=>s.jsxs("div",{ref:Kt.innerRef,...Kt.droppableProps,"data-split-members":!0,className:z.isDraggingOver?"rounded-sm bg-primary/10 ring-1 ring-primary/40":"",children:[Le.map((N,$)=>s.jsx(kl,{draggableId:`split-member:${N.id}`,index:$,disableInteractiveElementBlocking:!0,children:(ee,ie)=>s.jsx("div",{ref:ee.innerRef,...ee.draggableProps,...B?cr(()=>B(N.id)):{},className:`${$===0&&hr?"relative z-20 ":"relative "}flex items-center rounded-sm pr-0.5 transition-colors ${ie.isDragging?"bg-surface-elevated opacity-90 shadow-lg ":""}${Qr(N.id)??(N.id===c?"bg-surface-elevated/80 text-foreground":"text-muted-foreground hover:bg-surface-2")}`,children:Zn(N,ee.dragHandleProps,!0,$===0?gr(G):void 0)})},N.id)),Kt.placeholder]})})]})},kn=(G,Le,Ke,ct=!1,qe=!1)=>{const At=`collaboration:${G.id}`,Rt=Rr.has(At),Bt=`collaboration-members-${G.id}`,ot=Ie===G.id||!Ie&&Le.some(ie=>ie.id===c),Ft=Q5(qt,G.id),hr=G.sessionIds.filter(ie=>Ft.has(ie)&&ie!==c&&!pn.has(ie)),Kt=Nt[G.id]===!0,z=Kt?G.sessionIds:G.sessionIds.filter(ie=>!hr.includes(ie)),N=Pd(z,v),$=N.flatMap(ie=>ie.sessionIds),ee=N.length===1?N[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 ${Rt?"":"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 ${qe?"bg-primary/15 ring-1 ring-primary/40":ct?"bg-surface-elevated opacity-90 shadow-lg":ot?"bg-primary/[0.07]":"hover:bg-surface-2"}`,children:[rs(`移动工作组 ${G.name}`,Ke),s.jsxs("div",{className:"flex items-center",children:[s.jsx("button",{type:"button","aria-label":`${Rt?"展开":"收起"} ${G.name} 的成员会话`,"aria-expanded":!Rt,"aria-controls":Bt,title:`${Rt?"展开":"收起"}成员会话`,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:ie=>{ie.stopPropagation(),rn(At)},children:s.jsx(fi,{size:14,className:Rt?"":"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:ie=>{ie.stopPropagation(),pr(G.id)},children:[s.jsx(rh,{size:14,className:"shrink-0 text-primary"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:G.name}),at.some(ie=>ie.groupId===G.id)&&s.jsxs("span",{className:"shrink-0 text-[10px] font-normal text-primary",children:[at.filter(ie=>ie.groupId===G.id).length," 待处理"]})]}),s.jsx("button",{type:"button","aria-label":`成员与消息:${G.name}`,title:"在终端旁打开成员与消息",disabled:Ze!==null||!c&&!Le.length,"aria-busy":Ze===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:ie=>{ie.stopPropagation(),!be.current&&(ue(!1),be.current=!0,Je(G.id),q(null),lC(G.id,c??Le[0].id).catch(Qe=>q(Qe instanceof Error?Qe.message:"消息面板打开失败,请重试")).finally(()=>{be.current=!1,Je(null)}))},children:Ze===G.id?s.jsx(gn,{size:14,className:"animate-spin"}):s.jsx(N0,{size:14})})]}),s.jsx("div",{id:Bt,children:!Rt&&s.jsxs(s.Fragment,{children:[hr.length>0&&s.jsxs("button",{type:"button","aria-expanded":Kt,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:()=>gt(ie=>({...ie,[G.id]:!Kt})),children:[s.jsx(fi,{size:12,className:Kt?"rotate-90":""}),"已完成的执行会话 · ",hr.length]}),s.jsx(Ll,{droppableId:`collaboration-members:${G.id}`,type:"collaboration-member",direction:"vertical",isCombineEnabled:!0,children:(ie,Qe)=>s.jsxs("div",{ref:ie.innerRef,...ie.droppableProps,"data-collaboration-members":!0,className:`${Qe.isDraggingOver?"rounded-sm bg-primary/10":""}`,children:[N.map(ze=>s.jsx("div",{"data-collaboration-split":ze.workspace?.id,"data-split-anchor":ze.workspace?.sessionIds[0],role:ze.workspace?"region":void 0,"aria-label":ze.workspace?`${_e("tab.splitWorkspace")} · ${ze.sessionIds.length}`:void 0,className:ze.workspace&&!ee?`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 ${ze.sessionIds.includes(c??"")?"bg-primary/[0.07]":"bg-surface/35"}`:void 0,children:ze.sessionIds.map(xt=>{const _t=Pr.get(xt);return _t?s.jsx(kl,{draggableId:`collaboration-member:${_t.id}`,index:$.indexOf(_t.id),disableInteractiveElementBlocking:!0,children:(Mr,Dt)=>s.jsxs("div",{ref:Mr.innerRef,...Mr.draggableProps,"data-collaboration-member":_t.id,"data-split-member":pn.has(_t.id)?"true":void 0,...B?cr(()=>B(_t.id)):{},className:`${ze.workspace&&xt===ze.sessionIds[0]&&re===ze.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 ${Dt.combineTargetFor?"bg-primary/15 ring-1 ring-primary/40 ":Dt.isDragging?"bg-surface-elevated opacity-90 shadow-lg ":""}${Qr(_t.id)??(_t.id===c?"bg-surface-elevated/80 text-foreground":pn.has(_t.id)?"bg-primary/[0.05] text-muted-foreground hover:bg-primary/[0.09]":"text-muted-foreground hover:bg-surface-2")}`,children:[Zn(_t,Mr.dragHandleProps,!0,ze.workspace&&xt===ze.sessionIds[0]?gr(ze.workspace):void 0,Ft.has(xt)?s.jsxs("button",{type:"button","aria-label":`归档 ${_t.name}`,title:"保存 Agent 会话 ID 并停止终端;只回收干净的执行目录,结果和分支保留",disabled:er!==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:Gr=>{Gr.stopPropagation(),!Ct.current&&(Ct.current=!0,et(xt),q(null),a9(xt).then(async()=>{De(dn=>dn+1),await Wr()}).catch(dn=>q(dn instanceof Error?dn.message:"归档失败,终端已保留")).finally(()=>{Ct.current=!1,et(null)}))},children:[er===xt?s.jsx(gn,{size:13,className:"animate-spin"}):s.jsx(Ly,{size:13}),s.jsx("span",{className:"text-[10px] md:sr-only",children:"归档"})]}):void 0),!ze.workspace&&pn.has(_t.id)&&s.jsx("button",{type:"button",className:"shrink-0 px-1 text-[10px] text-primary",title:`与 ${v.find(Gr=>Gr.sessionIds.includes(_t.id))?.sessionIds.filter(Gr=>Gr!==_t.id).map(Gr=>Pr.get(Gr)?.name??Gr).join("、")} 分屏`,"aria-label":`查看 ${_t.name} 的跨组分屏`,onClick:()=>{ue(!1),la.getState().terminal(),window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:_t.id})),Fr()},children:s.jsx(Il,{size:10})})]})},_t.id):null})},ze.workspace?.id??ze.sessionIds[0])),ie.placeholder]})}),s.jsx(XB,{groupId:G.id,version:Ve,onRestore:async ie=>{ue(!1),window.dispatchEvent(new CustomEvent("new-terminal-session",{detail:{mode:"tmux",cwd:ie.cwd,preferredFrontendSessionId:ie.sessionId,requireExisting:!0}})),await Wr(),la.getState().terminal(),Fr()}}),G.remoteSessions?.map(ie=>s.jsxs("button",{type:"button",title:`${uc(ie)} · ${ie.serviceConnected===!1?"服务不可达,消息尚未送达":ie.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),b6(ie.sessionId).catch(()=>{pr(G.id)})},children:[s.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${ie.serviceConnected===!1?"bg-muted-foreground":"bg-primary"}`}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:ie.name}),s.jsx("span",{className:"max-w-20 truncate rounded border border-border/20 px-1 text-[9px]",children:uc(ie)}),ie.serviceConnected===!1&&s.jsx("span",{className:"shrink-0 text-[9px]",children:"不可达"})]},ie.sessionId))]})}),s.jsx("div",{"data-collaboration-background":!0,className:Rt?"absolute inset-0 pointer-events-none":"h-1.5"})]})},Ln=(G,Le,Ke)=>s.jsx(c0,{onBeforeCapture:fs,onDragStart:_r,onDragEnd:ct=>Mn(qe=>kr(qe,G,Ke),ct),children:s.jsx(Ll,{droppableId:Le,direction:"vertical",isCombineEnabled:!Hr,children:ct=>s.jsxs("div",{ref:ct.innerRef,...ct.droppableProps,"data-sidebar-entity-list-id":Le,className:"flex-1 space-y-0.5",children:[G.map((qe,At)=>s.jsx(kl,{draggableId:qe.id,index:At,disableInteractiveElementBlocking:!0,children:(Rt,Bt)=>s.jsxs("div",{ref:Rt.innerRef,...Rt.draggableProps,"data-sidebar-gesture-ignore":!0,"data-sidebar-entity-index":At,className:"relative",children:[Kn(At),At===G.length-1&&Kn(G.length,"bottom"),qe.kind==="workspace"?$n(qe.workspace,qe.members,Bt.isDragging,!!Bt.combineTargetFor,Rt.dragHandleProps):qe.kind==="collaboration"?kn(qe.group,qe.members,Rt.dragHandleProps,Bt.isDragging,!!Bt.combineTargetFor):s.jsx("div",{...B?cr(()=>B(qe.session.id)):{},className:`group relative flex items-center gap-1 rounded-md pr-1 transition-colors ${Bt.combineTargetFor?"bg-primary/15 text-foreground ring-1 ring-primary/40":Bt.isDragging?"bg-surface-elevated text-foreground opacity-90 shadow-lg":Qr(qe.session.id)??(!Ie&&qe.session.id===c?"bg-surface-elevated text-foreground":"text-muted-foreground hover:bg-surface-2")} cursor-grab active:cursor-grabbing`,children:Zn(qe.session,Rt.dragHandleProps)})]})},qe.id)),ct.placeholder]})})}),ps=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:_e("sidebar.sessions")}),s.jsx("span",{className:"text-[11px] text-muted-foreground",children:a.length}),Kr>0&&s.jsx("span",{className:"ml-0.5 flex items-center",children:s.jsx(j6,{count:Kr,tone:"running",title:_e("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),pr(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(rh,{size:16})}),(!ke||$e)&&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":_e("common.close"),children:s.jsx(Rn,{size:16})})]})]})]}),pt&&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:pt}),s.jsx("button",{type:"button","aria-label":"关闭协作错误提示",className:"shrink-0",onClick:()=>q(null),children:s.jsx(Rn,{size:14})})]}),s.jsxs("div",{ref:ne,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:[(at.length>0||bt)&&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":It,onClick:()=>yt(G=>!G),children:[s.jsx(rh,{size:14}),s.jsx("span",{className:"min-w-0 flex-1",children:"需要你处理"}),s.jsx("span",{children:at.length}),s.jsx(fi,{size:12,className:It?"rotate-90":""})]}),It&&s.jsxs("div",{className:"space-y-1 p-1 pt-0",children:[bt&&s.jsxs("p",{role:"alert",className:"px-2 py-2 text-[11px] text-destructive",children:[bt,s.jsx("button",{type:"button",className:"ml-2 text-primary",onClick:()=>{_u.getState().refresh()},children:"重试"})]}),at.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:()=>{P5(G.groupId,G.id),pr(G.groupId).then(Le=>{Le&&P5(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:[nr.find(Le=>Le.id===G.groupId)?.name??"协作组"," · ",Yc(G)]})]},G.id))]})]}),s.jsx(eF,{sessions:Ae,loading:lt,attachingName:me,onRefresh:Se,onRestore:K,onClose:ye}),qr.filter(G=>!G.sessionIds.length).map(G=>s.jsx(c0,{onDragEnd:()=>{},children:kn(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(Fo,{size:26,className:"mx-auto mb-2 text-muted-foreground"}),s.jsx("p",{className:"text-[12px] text-muted-foreground",children:_e("sidebar.noSessions")})]}):Sr.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:_e("sidebar.noMatchingSessions")})}):wt?s.jsx("div",{className:"flex flex-1 flex-col",children:s.jsx(c0,{onBeforeCapture:fs,onDragStart:_r,onDragEnd:G=>Mn(Er,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:[sn.map((Le,Ke)=>{const ct=Rr.has(Le.key),qe=!ct&&Ke===sn.length-1,At=Od(Le.sessions,v,Pr,qr);let Rt=0,Bt=0;for(const Ft of Le.sessions){const hr=l.get(Ft.id);hr?.agentStatus==="working"&&(Rt+=1),(hr?.agentStatus==="waiting"||hr?.agentNeedsReview)&&(Bt+=1)}const ot=Le.key==="";return s.jsx(kl,{draggableId:`sidebar-group:${Le.key||"__ungrouped__"}`,index:Ke,isDragDisabled:ot,disableInteractiveElementBlocking:!0,children:(Ft,hr)=>s.jsxs("div",{ref:Ft.innerRef,...Ft.draggableProps,className:`shrink-0 rounded-md transition-colors ${qe?"flex flex-1 flex-col ":""}${hr.isDragging?"bg-surface-elevated shadow-lg opacity-90":""}`,children:[s.jsxs("button",{type:"button",...ot?{}:Ft.dragHandleProps,onClick:()=>{rn(Le.key),Tn.current.delete(Le.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 ${ot?"":"cursor-grab active:cursor-grabbing"}`,title:Le.key||Le.label,children:[s.jsx(fi,{size:13,className:`shrink-0 transition-transform ${ct?"":"rotate-90"}`}),s.jsx("span",{className:"min-w-0 flex-1 truncate text-[11.5px] font-semibold uppercase tracking-wide",children:Le.label}),Rt>0&&s.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--success)] animate-pulse"}),Bt>0&&s.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--warning)] animate-pulse"}),s.jsx(O5,{sessionIds:Le.sessions.map(Kt=>Kt.id)}),s.jsx("span",{className:"shrink-0 text-[10.5px] text-muted-foreground/70",children:Le.sessions.length})]}),!ct&&s.jsx("div",{className:`mt-0.5 pl-2 ${qe?"flex flex-1 flex-col":""}`,children:s.jsx(Ll,{droppableId:`group-sessions:${Le.key}`,type:"session",direction:"vertical",isCombineEnabled:!Hr,children:Kt=>s.jsxs("div",{ref:Kt.innerRef,...Kt.droppableProps,"data-sidebar-entity-list-id":`group-sessions:${Le.key}`,className:`${qe?"flex-1 ":""}space-y-0.5`,children:[At.map((z,N)=>s.jsx(kl,{draggableId:z.id,index:N,disableInteractiveElementBlocking:!0,children:($,ee)=>s.jsxs("div",{ref:$.innerRef,...$.draggableProps,"data-sidebar-gesture-ignore":!0,"data-sidebar-entity-index":N,className:"relative",children:[Kn(N),N===At.length-1&&Kn(At.length,"bottom"),z.kind==="workspace"?$n(z.workspace,z.members,ee.isDragging,!!ee.combineTargetFor,$.dragHandleProps):z.kind==="collaboration"?kn(z.group,z.members,$.dragHandleProps,ee.isDragging,!!ee.combineTargetFor):s.jsx("div",{...B?cr(()=>B(z.session.id)):{},className:`group relative flex items-center gap-1 rounded-md pr-1 transition-colors ${ee.combineTargetFor?"bg-primary/15 text-foreground ring-1 ring-primary/40":ee.isDragging?"bg-surface-elevated text-foreground opacity-90 shadow-lg":Qr(z.session.id)??(!Ie&&z.session.id===c?"bg-surface-elevated text-foreground":"text-muted-foreground hover:bg-surface-2")} cursor-grab active:cursor-grabbing`,children:Zn(z.session,$.dragHandleProps)})]})},z.id)),Kt.placeholder]})})})]})},Le.key||"__ungrouped__")}),G.placeholder]})})})}):Ln(on,"sidebar-entities")]}),s.jsx(n9,{onReselect:()=>{d&&(ht.current=null,je(G=>G+1),d())}}),Ce&&s.jsx(uO,{directories:a.flatMap(G=>{const Le=l.get(G.id)?.cwd;return Le?[Le]:[]}),tmuxAvailable:pe,options:cn,launchPending:Be,launchError:le?_e(Um(le)):null,agents:Vr,selectedAgent:ge,detecting:it,resumeHistory:Vt,resumeHistoryLoading:vt,resumeHistoryPendingId:Pt,resumeHistoryError:zt,onRefreshAgents:()=>{dt().catch(()=>{})},onSelectAgent:G=>{sr(G).catch(()=>{})},onLaunchAgent:Ue,onResumeHistory:G=>{Et(G)},onRemoveResumeHistory:G=>{kt(G)},onClose:()=>ue(!1),onOptionsChange:Lr,additionalContent:an&&U?.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(gn,{size:13,className:U.status==="installing"||U.status==="restarting"?"animate-spin":""})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block font-semibold",children:_e("sidebar.updateAvailable",{version:U.latestVersion})}),s.jsx("span",{className:"mt-0.5 block text-[10.5px] leading-relaxed text-muted-foreground",children:U.status==="installing"?_e("sidebar.updateInstalling"):U.status==="ready"?_e("sidebar.updateReady"):U.status==="restarting"?_e("sidebar.updateRestarting"):_e("sidebar.updateFailed")})]})]}),U.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:_e("sidebar.updateRestart")}),U.status==="error"&&ce&&s.jsx("button",{type:"button",disabled:V,onClick:ce,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:_e("sidebar.updateRetry")})]}),footerActions:s.jsx(KO,{serverAttention:Me,onOpenSettings:()=>{ue(!1),W()},actions:[...F?[{label:_e("sidebar.subscriptionQuota"),icon:FA,onSelect:()=>{ue(!1),F()}}]:[],{label:"Agent 工作台",icon:rh,onSelect:()=>{ue(!1),pr(null)}},{label:"服务与设备",icon:s9,onSelect:()=>{ue(!1),i9()}},...Y?[{label:_e($e?"sidebar.unpinSidebar":"sidebar.pinSidebar"),icon:$e?m0:p0,separated:!0,onSelect:()=>{ue(!1),Y()}}]:[]]})}),Ye&&s.jsx(Cb,{onEnterGroup:async G=>{if(!await pr(G))throw new Error("协作组已保存,打开工作区失败,请重试");st(!1)},onFloatingChange:async G=>{if(G){if(!await pr(G))throw new Error("打开协作工作区失败");st(!1)}},activeSessionId:c,defaultSessionMode:te,onClose:()=>st(!1),onNewSession:G=>p(G)}),Object.entries(We).map(([G,Le])=>s.jsx(Cb,{activeSessionId:c,initialCollaborationGroupId:G,initialFloating:Le,visible:!Ie,onEnterGroup:async Ke=>{if(Ke===G){await pr(Ke);return}if(!await pr(Ke))throw new Error("协作组已保存,打开工作区失败,请重试");await bo({floatingGroupId:null},G),Te(ct=>{const qe={...ct};return delete qe[G],qe})},onFloatingChange:Ke=>St(G,Ke),defaultSessionMode:te,onClose:()=>{oe.current=!0,Te(Ke=>{const ct={...Ke};return delete ct[G],ct})},onNewSession:Ke=>p(Ke)},G)),!Ce&&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:[le&&s.jsx("p",{role:"alert",className:"mb-2 text-[11px] leading-relaxed text-destructive",children:_e(Um(le))}),s.jsxs("div",{className:`grid gap-1.5 [&>button]:min-h-11 [&>button]:shadow-none [&>button]:ring-0 md:[&>button]:min-h-0 ${ge?"grid-cols-[minmax(0,1fr)_minmax(0,1fr)_2.5rem]":"grid-cols-[minmax(0,1fr)_2.5rem]"}`,children:[s.jsxs("button",{type:"button",onClick:Xr,disabled:Be,"aria-busy":Be,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] ${ge?"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:_e("sidebar.newSession"),"aria-label":_e("sidebar.newSession"),children:[s.jsx(Fo,{size:15,className:"shrink-0"}),s.jsx("span",{className:"truncate",children:Be?_e("sidebar.sessionCreating"):"Terminal"})]}),ge&&s.jsxs("button",{type:"button",onClick:fn,disabled:Be,"aria-busy":Be,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:_e("sidebar.newSessionWithAgent",{agent:ge.displayName}),"aria-label":_e("sidebar.newSessionWithAgent",{agent:ge.displayName}),children:[s.jsx(Wc,{agent:ge,size:15}),s.jsx("span",{className:"truncate",children:ge.displayName})]}),s.jsxs("button",{type:"button",onClick:tr,disabled:Be,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:nt,"aria-label":nt,"aria-expanded":Ce,"aria-controls":"sidebar-launch-options",children:[s.jsx($o,{size:15}),Me&&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"}),an&&s.jsx("span",{className:`absolute top-0.5 h-2 w-2 rounded-full bg-[var(--warning)] ring-2 ring-[var(--chrome-bg)] ${Me?"right-3.5":"right-0.5"}`,"aria-hidden":"true"})]})]})]})]});return $e?s.jsx("div",{"data-session-sidebar-pinned":!0,className:"h-full flex flex-col app-chrome-bg border-r border-border",children:ps}):s.jsx(N6,{side:"left",isOpen:e,drawerWidthPx:t,onClose:r,onOpen:n,push:ke,children:ps})}function nF(){const{t:e}=zr();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 sF({slow:e=!1}){const{t}=zr();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 G6=()=>Oc(()=>import("./RightSidebar-DaRdlJzn.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})),iF=b.lazy(G6);function jb(e){const t=b.useRef(!1);b.useEffect(()=>{const p=navigator.connection;if(!(p?.saveData||/2g|3g/.test(p?.effectiveType??"")))return $1(()=>{G6().catch(()=>{})},3e3)},[]);const{t:r}=zr(),n=Gt(p=>p.rootPath),a=Gt(p=>p.rightTab),c=Gt(p=>p.setRightTab),l=n?.replace(/\/+$/,"").split("/").pop()||r("rightSidebar.workspace");(e.isOpen||e.pinned)&&(t.current=!0);const d=s.jsx(N6,{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:[Ml,JT,$o].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(Rn,{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",vA,"rightSidebar.tabGit"],["diff",AA,"rightSidebar.tabChanges"],["files",Gc,"rightSidebar.tabFiles"],["architecture",PT,"architecture.tab"],["computer",l9,"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(sF,{}):s.jsx(nF,{})})]})});return t.current?s.jsx(b.Suspense,{fallback:d,children:s.jsx(iF,{...e})}):d}const Db=hc(e=>({overlay:"off",setOverlay:t=>e({overlay:t})}));function aF(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 oF=hc((e,t)=>({sessions:new Map,activeSessionId:null,nextSessionNumber:1,createSession:r=>{const n=Xy(),a=Date.now(),c=t().sessions,l=aF(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})}})),lF=[7e5,1e6,14e5,18e5,24e5,32e5,4e6,5e6,6e6,8e6,1e7,12e6].map(e=>({id:"auto",maxSize:1600,bitRate:e,maxFps:30}));class cF{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 lF[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 Xc(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 uF(){return Xc("/api/android/devices")}async function dF(e){return Xc("/api/android/connect",{method:"POST",body:JSON.stringify({address:e})})}const Of=[{id:"low",maxSize:720,bitRate:12e5,maxFps:30},{id:"medium",maxSize:1080,bitRate:4e6,maxFps:30},{id:"high",maxSize:1600,bitRate:8e6,maxFps:60}],k0=Of[1];function N1(e){if(!e||typeof e!="object")return k0;const t=e;if(t.id==="auto")return{id:"auto",maxSize:1600,bitRate:4e6,maxFps:30};const r=Of.find(l=>l.id===t.id);if(r)return r;if(t.id!=="custom")return k0;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 hF(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 Bb(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 fF(e){return Xc(`/api/android/recordings?serial=${encodeURIComponent(e)}`)}function pF(e){return Xc("/api/android/recordings",{method:"POST",body:JSON.stringify({serial:e})})}function mF(e){return Xc(`/api/android/recordings/${encodeURIComponent(e)}/stop`,{method:"POST"})}function gF(e,t){return Xc(`/api/android/recordings/${encodeURIComponent(e)}/save`,{method:"POST",body:JSON.stringify({directory:t})})}function xF(e){return Xc(`/api/android/recordings/${encodeURIComponent(e)}`,{method:"DELETE"})}const bF=0,yF=1,vF=2,wF=3,AF=4,TF=5,SF=7,CF=10,_F=11,kF=16,Qb=17,Pb=0,Lm=1,LF=2,Ob=3,Im=0,Fb=1,$b=1,wu=0xffffffffffffffffn,Eh=0xfffffffffffffffen,Fd={HOME:3,APP_SWITCH:187,POWER:26,VOLUME_UP:24,VOLUME_DOWN:25};function V6(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 IF(e,t,r,n,a,c){const l=new Uint8Array(32),d=new DataView(l.buffer);return d.setUint8(0,vF),d.setUint8(1,e),d.setBigUint64(2,t),V6(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 Em(e,t,r=0,n=0){const a=new Uint8Array(14),c=new DataView(a.buffer);return c.setUint8(0,bF),c.setUint8(1,e),c.setUint32(2,t>>>0),c.setUint32(6,r>>>0),c.setUint32(10,n>>>0),a}function EF(e,t,r,n=0){const a=new Uint8Array(21),c=new DataView(a.buffer);c.setUint8(0,wF),V6(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 NF(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,yF),a.setUint32(1,r.length),n.set(r,5),n}function RF(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]=kF,r[1]=t.length,r.set(t,2),r}function $d(e){return new Uint8Array([e])}function Ub(e){return new Uint8Array([AF,e])}function MF(e){return new Uint8Array([CF,e?1:0])}function jF(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}function DF(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 Nm(e){return e.toString(16).padStart(2,"0")}function q6(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 BF(e){const t=e?q6(e,7,!1):null;return t&&t.length>=4?`avc1.${Nm(t[1])}${Nm(t[2])}${Nm(t[3])}`:"avc1.42e01e"}function QF(e){const t=e?q6(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 PF{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=c9(hF(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($d(Qb)))},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:jF(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=DF(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($d(Qb))}})}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=[BF(this.configData),"avc1.42e01e","avc1.4d401e","avc1.64001f"].filter((l,d,p)=>p.indexOf(l)===d),r.avc={format:"annexb"}):t==="h265"?(n=[QF(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===Lm||t===Ob,l=c?0:1,d=a===wu&&!c?$b:0,p=(t===Pb||t===Lm)&&a===wu?$b:0;this.sendControl(IF(t,a,this.pointerPoint(r,n),l,p,d))}pointerDown(t,r,n){this.touch(Pb,t,r,n==="mouse"?wu:Eh)}pointerMove(t,r,n){this.touch(LF,t,r,n==="mouse"?wu:Eh)}pointerUp(t,r,n){this.touch(Lm,t,r,n==="mouse"?wu:Eh)}pointerCancel(t,r,n){this.touch(Ob,t,r,n==="mouse"?wu:Eh)}scroll(t,r,n,a){this.sendControl(EF(this.pointerPoint(t,r),n,a))}key(t,r=Im){this.sendControl(Em(r,t))}tapKey(t){this.sendControl(Em(Im,t)),this.sendControl(Em(Fb,t))}back(){this.sendControl(Ub(Im)),this.sendControl(Ub(Fb))}home(){this.tapKey(Fd.HOME)}recents(){this.tapKey(Fd.APP_SWITCH)}power(){this.tapKey(Fd.POWER)}volumeUp(){this.tapKey(Fd.VOLUME_UP)}volumeDown(){this.tapKey(Fd.VOLUME_DOWN)}rotate(){this.sendControl($d(_F))}expandNotifications(){this.sendControl($d(TF))}collapsePanels(){this.sendControl($d(SF))}setDisplayPower(t){this.sendControl(MF(t))}sendText(t){this.sendControl(NF(t))}startApp(t){this.sendControl(RF(t))}}function OF(){try{return crypto.randomUUID().slice(0,8)}catch{return Math.random().toString(36).slice(2,10)}}function FF(){return`termdock-mirror-shot-${new Date().toISOString().replace(/[-:T]/g,"").slice(0,14)}-${OF()}.png`}function zb(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 $F(e,t=FF()){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 Y6(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 Hb(e,t,r,n,a){const c=Math.max(1,Math.min(8,e.zoom*a)),l=c/e.zoom;return{zoom:c,pan:Y6({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 Z6(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 Wb(e,t){return Z6(l1(e,null),t)}const Rm=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 UF({file:e,initialPath:t,onInsert:r,onDone:n}){const{t:a}=zr(),[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 xF(e.id),n()}catch(W){S(W instanceof Error?W.message:String(W))}finally{L.current=!1,p(!1),w(!1)}}};b.useEffect(()=>{if(c)return;E.current?.focus();const W=F=>{if(F.stopPropagation(),F.key==="Escape"&&F.preventDefault(),F.key!=="Tab")return;const U=Array.from(E.current?.querySelectorAll("button:not(:disabled)")??[]),V=U[0],Z=U.at(-1);F.shiftKey&&(document.activeElement===V||document.activeElement===E.current)?(F.preventDefault(),Z?.focus()):!F.shiftKey&&document.activeElement===Z&&(F.preventDefault(),V?.focus())};return document.addEventListener("keydown",W,!0),()=>document.removeEventListener("keydown",W,!0)},[c]);const B=async W=>{if(!L.current){L.current=!0,p(!0),x(W!==void 0),l(!1),S(null);try{const F=await gF(e.id,W);W===void 0&&await r(F.path),n()}catch(F){S(F instanceof Error?F.message:String(F))}finally{L.current=!1,p(!1)}}};return c?s.jsx(tp,{open:!0,initialPath:t||"/",title:a("android.recordingSave"),onCancel:()=>l(!1),onConfirm:W=>{B(W)}}):Ii.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(Cn,{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 Xd="android-mirror",Ud=Xd,K6="termdock:android:quality:v1",Mm=176,zF=204,_l=1,rf=8,Gb=[1,1.25,1.5,2,2.5,3,4,6,8],HF=e=>Math.max(_l,Math.min(rf,e));function WF(e){return`${Number.isInteger(e)?e:e.toFixed(1)}×`}function Nh(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 GF(e,t){try{e.setPointerCapture?.(t)}catch{}}function Vb(e,t){try{e.releasePointerCapture?.(t)}catch{}}const qb=e=>typeof requestAnimationFrame=="function"?requestAnimationFrame(e):window.setTimeout(e,16),Rh=e=>{typeof cancelAnimationFrame=="function"?cancelAnimationFrame(e):window.clearTimeout(e)},jm={auto:"android.qualityAuto",low:"android.qualityLow",medium:"android.qualityMedium",high:"android.qualityHigh",custom:"android.qualityCustom"},VF=()=>{try{const e=localStorage.getItem(K6);return e?N1(JSON.parse(e)):k0}catch{return k0}},zd=e=>{try{localStorage.setItem(K6,JSON.stringify(e))}catch{}};function qF({sessionId:e,dockOnly:t=!1,onInsertPrompt:r,onInsertFile:n,onRecordingComplete:a,onCloseTab:c}){const{t:l}=zr(),d=Db(N=>N.overlay),p=Db(N=>N.setOverlay),m=b.useRef(null),x=b.useRef(null),y=b.useRef(null),w=b.useMemo(VF,[]),v=b.useRef(w),S=b.useRef(null),L=b.useRef(null),[E,R]=b.useState(4e6),B=b.useRef(null),W=b.useRef(new Map),F=b.useRef(null),U=b.useRef(!1),[V,Z]=b.useState(_l),ce=b.useRef(V),xe=b.useRef({x:0,y:0}),pe=b.useRef(null),te=b.useRef(0),ke=b.useRef(0),$e=b.useRef(null),Y=b.useRef(0),[Ae,lt]=b.useState(null),[Se,ye]=b.useState(null),[_e,je]=b.useState(!0),[re,Oe]=b.useState(""),[Ce,Ee]=b.useState(w.id),[Be,Ne]=b.useState([]),[le,He]=b.useState(null),[rt,mt]=b.useState(""),[ue,Ye]=b.useState(!0),[st,Ie]=b.useState({maxSize:w.maxSize,bitRate:w.bitRate,maxFps:w.maxFps}),[We,Te]=b.useState("idle"),[H,oe]=b.useState(null),[be,Ze]=b.useState(null),[Je,St]=b.useState({fps:0,kbps:0,width:0,height:0,received:0,decoded:0,controls:0,last:""}),[Vt,jt]=b.useState(null),[vt,Zt]=b.useState(null),[Pt,Xt]=b.useState(!1),[zt,Lt]=b.useState([]),[me,Ge]=b.useState(null),[pt,q]=b.useState([]),[at,qt]=b.useState(!1),Ve=b.useRef(null),De=b.useRef(0),er=b.useRef([]),[et,Ct]=b.useState(!1),[Nt,gt]=b.useState(""),[bt,It]=b.useState(!1),[yt,pr]=b.useState(!1),[nr,Cr]=b.useState(""),[cn,Lr]=b.useState(null),[ge,Vr]=b.useState(null),[it,dt]=b.useState(!1),[sr,xn]=b.useState(0),an=b.useRef(null),[Me,nt]=b.useState(!1),wt=b.useRef(!1),Rr=b.useRef(new Set),rn=b.useRef(null),Ir=b.useRef(null),ne=b.useRef(!1),[ht,Ht]=b.useState(!1),Ot=b.useRef(a);Ot.current=a;const[Tr,mr]=b.useState(!1),[Hr,_n]=b.useState(null),dr=b.useRef(null),bn=b.useRef(null),hn=oF(N=>N.activeSessionId??N.sessions.keys().next().value??null),Tn=e??hn,ir=es(N=>!!N.docks[Ud]),pn=es(N=>N.hosts[Ud]),Pr=es(N=>N.setDock),qr=b.useCallback(async()=>{je(!0);try{const N=await uF();lt(N),ye(null)}catch(N){ye(N instanceof Error?N.message:"ADB_UNAVAILABLE")}finally{je(!1)}},[]);b.useEffect(()=>{qr()},[qr]);const Wr=Ae?.devices??[],fs=Wr.find(N=>N.serial===re)??null,Br=!!(Se&&/ADB_NOT_FOUND|ADB_UNAVAILABLE/i.test(Se)),Mn=!!(Ae?.adbAvailable&&!Ae.scrcpyVersion),Sr=b.useCallback(()=>{const N=B.current,$=[...W.current.keys()];B.current=null,W.current.clear(),F.current=null,U.current=!1,Ve.current=null,Rh(te.current),te.current=0,N&&x.current?.pointerCancel(N.x,N.y,N.type);const ee=m.current;if(ee)for(const ie of $)Vb(ee,ie);Ge(null),qt(!1),q([]),Z(ce.current)},[]);b.useEffect(()=>{const N=ie=>{W.current.has(ie.pointerId)&&(ie.type==="pointercancel"||ie.target!==m.current)&&Sr()},$=()=>Sr(),ee=()=>{document.hidden&&Sr()};return window.addEventListener("pointerup",N,!0),window.addEventListener("pointercancel",N,!0),window.addEventListener("blur",$),document.addEventListener("visibilitychange",ee),()=>{window.removeEventListener("pointerup",N,!0),window.removeEventListener("pointercancel",N,!0),window.removeEventListener("blur",$),document.removeEventListener("visibilitychange",ee),Sr()}},[Sr]);const Kr=b.useCallback(()=>{Sr(),x.current?.disconnect(),x.current=null,Te("idle"),oe(null),Ze(null)},[Sr]),nn=b.useCallback((N,$=!1)=>{const ee=m.current;if(!ee||!N)return;Sr(),x.current?.disconnect(),oe(null),!$&&y.current!==N&&Ze(null),y.current=N,Zt(null),jt(null);const ie=new PF(ee,{onBitrateSupport:(ze,xt)=>{x.current!==ie||v.current.id!=="auto"||jt(ze?null:xt??"BITRATE_REASON_UNAVAILABLE")},onState:(ze,xt)=>{x.current===ie&&(Te(ze),oe(xt??null))},onHeader:ze=>{x.current===ie&&Ze(ze)},onStats:ze=>{x.current===ie&&St(ze)},onWarning:ze=>{x.current===ie&&Zt(ze)}});x.current=ie;let Qe=v.current;Qe.id==="auto"?(S.current?.serial!==N&&(S.current={serial:N,policy:new cF}),S.current.policy.connected(performance.now()),Qe=S.current.policy.quality,R(Qe.bitRate)):S.current=null,L.current=Qe,ie.connect(N,Qe)},[Sr]);b.useEffect(()=>{if(Ce!=="auto"||v.current.id!=="auto"||We!=="streaming"||!Je.adaptation||document.hidden)return;const N=S.current,$=x.current;if(!N||N.serial!==re||!$?.canSetBitrate)return;const ee=m.current,ie=ee?Math.max(ee.clientWidth,ee.clientHeight)*(window.devicePixelRatio||1)*ce.current:1600,Qe=N.policy.sample(Je.adaptation,performance.now(),ie||1600);Qe&&$.setBitrate(Qe.bitRate).then(ze=>{ze&&x.current===$&&(L.current=Qe,R(Qe.bitRate))})},[Je,Ce,We,re,nn]);const Fr=b.useCallback(N=>{const $={...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}:{}};ka({androidPanel:$}).catch(()=>{})},[]);b.useEffect(()=>{let N=!1;return fc().then($=>{if(N)return;const ee=$.androidPanel;if(ee?.quality){const ie=N1(ee.quality);v.current=ie,Ee(ie.id),Ie({maxSize:ie.maxSize,bitRate:ie.bitRate,maxFps:ie.maxFps}),zd(ie)}Ne(ee?.presets??[]),He(ee?.activePresetId??null),ee?.deviceSerial&&($e.current=ee.deviceSerial,Oe(ee.deviceSerial))}).catch(()=>{}),()=>{N=!0}},[]);const ks=b.useCallback(N=>{const $=++De.current;Lt(ie=>[...ie,{id:$,left:N.left,top:N.top}]);const ee=window.setTimeout(()=>{Lt(ie=>ie.filter(Qe=>Qe.id!==$)),er.current=er.current.filter(ie=>ie!==ee)},300);er.current.push(ee)},[]),Or=b.useCallback((N,$)=>{const ee=x.current,ie=L.current;ee?.supportsLiveBitrate&&y.current===N&&ie&&ie.maxSize===$.maxSize&&ie.maxFps===$.maxFps?ee.setBitrate($.bitRate).then(Qe=>{x.current===ee&&(Qe?(L.current=$,jt(null)):jt(ee.lastBitrateFailure??"BITRATE_REASON_UNAVAILABLE"))}):nn(N)},[nn,l]),Xr=b.useCallback(N=>{if(S.current=null,N.startsWith("user:")){const ee=Be.find(Qe=>Qe.id===N.slice(5));if(!ee)return;const ie={id:"custom",maxSize:ee.maxSize,bitRate:ee.bitRate,maxFps:ee.maxFps};v.current=ie,Ee("custom"),He(ee.id),Ie({maxSize:ee.maxSize,bitRate:ee.bitRate,maxFps:ee.maxFps}),Ye(!0),zd(ie),Fr({quality:ie,activePresetId:ee.id}),re&&nn(re);return}if(N==="custom"){const ee=v.current;Ee("custom"),He(null),Ie({maxSize:ee.maxSize,bitRate:ee.bitRate,maxFps:ee.maxFps}),Ye(!0);return}const $=N==="auto"?N1({id:"auto"}):Of.find(ee=>ee.id===N)??k0;v.current=$,Ee($.id),He(null),zd($),Fr({quality:$,activePresetId:null}),re&&nn(re)},[nn,re,Be,Fr]),fn=b.useCallback(()=>{const N={id:"custom",maxSize:st.maxSize,bitRate:st.bitRate,maxFps:st.maxFps};v.current=N,zd(N),Fr({quality:N,activePresetId:null}),Ee("custom"),He(null),re&&Or(re,N)},[Or,re,st,Fr]),K=b.useCallback(()=>{const N=rt.trim();if(!N)return;const $=`p${Date.now().toString(36)}${Math.random().toString(36).slice(2,6)}`,ee={id:$,name:N,maxSize:st.maxSize,bitRate:st.bitRate,maxFps:st.maxFps},ie=[...Be.filter(ze=>ze.name!==N),ee].slice(-12),Qe={id:"custom",maxSize:st.maxSize,bitRate:st.bitRate,maxFps:st.maxFps};Ne(ie),mt(""),He($),Ee("custom"),v.current=Qe,zd(Qe),Fr({quality:Qe,activePresetId:$,presets:ie}),re&&Or(re,Qe)},[rt,st,Be,re,Or,Fr]),Ue=b.useCallback(()=>{if(!le)return;const N=Be.filter($=>$.id!==le);Ne(N),He(null),Fr({activePresetId:null,presets:N})},[le,Be,Fr]);b.useEffect(()=>()=>{x.current?.disconnect(),x.current=null;for(const N of er.current)window.clearTimeout(N);er.current=[]},[]),b.useEffect(()=>{if(d==="off")return;const N=$=>{$.key==="Escape"&&p("off")};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[d,p]),b.useEffect(()=>{const N=Wr.filter(ee=>ee.state==="device");if(re||N.length!==1)return;const $=N[0].serial;$e.current!==$&&($e.current=$,Oe($))},[Wr,re]),b.useEffect(()=>{re&&nn(re)},[re,nn]),b.useEffect(()=>{if(We==="streaming"){Y.current=0,Xt(!1);return}if(We!=="error"||!re||!ZF(H??""))return;const N=Math.min(8e3,700*2**Y.current);Y.current+=1,Xt(!0);const $=window.setTimeout(()=>{Xt(!1),nn(re)},N);return()=>window.clearTimeout($)},[We,H,re,nn]);const Et=b.useCallback((N,$,ee)=>{const ie=m.current,Qe=ee??(ie?Nh(ie):null);return!ie||!Qe?{x:0,y:0}:Y6(N,$,Qe)},[]),kt=b.useCallback(()=>{const N=m.current;if(!N)return;const{x:$,y:ee}=xe.current,ie=ce.current,Qe=ie===_l&&$===0&&ee===0?"":`translate3d(${$}px, ${ee}px, 0) scale(${ie})`;N.style.transform!==Qe&&(N.style.transform=Qe);const ze=pe.current;ze&&(ze.textContent=ie>_l?WF(ie):"")},[]),tr=b.useCallback((N,$,ee=!0)=>{const ie=m.current,Qe=ce.current,ze=HF(N);if(!ie||ze===Qe)return;const xt=Nh(ie);if(!xt)return;const _t=$??{x:xt.cx,y:xt.cy},Mr=Hb({zoom:Qe,pan:xe.current},xt,_t,_t,ze/Qe);ce.current=Mr.zoom,xe.current=Mr.pan,ee&&kt()},[kt]),Qr=b.useCallback(()=>{const N=ce.current;Z($=>$<=_l+.01==N<=_l+.01&&$>=rf-.01==N>=rf-.01?$:N)},[]);b.useEffect(()=>()=>{Rh(te.current),Rh(ke.current)},[]);const cr=()=>{let N=0,$=0;for(const ie of W.current.values())N+=ie.x,$+=ie.y;const ee=W.current.size;return ee?{x:N/ee,y:$/ee}:null},Sn=()=>{const[N,$]=Array.from(W.current.values());return N&&$?Math.hypot(N.x-$.x,N.y-$.y):0},Ls=()=>{const N=cr(),$=m.current?Nh(m.current):null;!N||!$||(F.current={startCentroid:N,startDistance:Sn(),box:$})},Zn=b.useCallback(()=>{const N=F.current,$=cr();if(!N||!$)return;const ee=Sn(),ie=N.startDistance>0&&ee>0?ee/N.startDistance:1,Qe=Hb({zoom:ce.current,pan:xe.current},N.box,N.startCentroid,$,ie);ce.current=Qe.zoom,xe.current=Qe.pan,N.startCentroid=$,N.startDistance=ee},[]),sn=b.useCallback(()=>{te.current||(te.current=qb(()=>{te.current=0,Zn(),kt()}))},[Zn,kt]),on=b.useCallback(()=>{te.current&&(Rh(te.current),te.current=0,Zn(),kt())},[Zn,kt]);b.useEffect(()=>{const N=m.current;if(!N)return;const $=N.parentElement;if(!$)return;const ee=Qe=>{if(Qe.ctrlKey||Qe.metaKey){if(Qe.preventDefault(),!Qe.deltaY||F.current)return;const _t=Qe.deltaMode===1?16:Qe.deltaMode===2?N.parentElement?.clientHeight||600:1,Mr=Math.max(-600,Math.min(600,Qe.deltaY*_t));tr(ce.current*Math.exp(-Mr*.002),{x:Qe.clientX,y:Qe.clientY},!1),ke.current||(ke.current=qb(()=>{ke.current=0,kt(),Qr()}));return}const ze=x.current;if(!ze||Qe.target!==N)return;Qe.preventDefault();const xt=jh(N,Qe.clientX,Qe.clientY);ze.scroll(xt.x,xt.y,Qe.deltaX,Qe.deltaY)},ie=Qe=>Qe.preventDefault();return $.addEventListener("wheel",ee,{passive:!1}),$.addEventListener("gesturestart",ie,{passive:!1}),$.addEventListener("gesturechange",ie,{passive:!1}),()=>{$.removeEventListener("wheel",ee),$.removeEventListener("gesturestart",ie),$.removeEventListener("gesturechange",ie)}},[tr,kt,Qr]),b.useEffect(()=>{const N=m.current,$=N?.parentElement;if(!N||!$||typeof ResizeObserver>"u")return;const ee=new ResizeObserver(()=>{F.current&&(F.current.box=Nh(N));const ie=Et(xe.current,ce.current);ie.x===xe.current.x&&ie.y===xe.current.y||(xe.current=ie,kt())});return ee.observe(N),ee.observe($),()=>ee.disconnect()},[Et,kt]),b.useLayoutEffect(()=>{kt()});const _r=N=>{const $=x.current,ee=m.current;if(!$||!ee)return;if(N.pointerType==="mouse"&&N.button!==0){N.preventDefault(),N.button===2?$.back():N.button===1&&$.home();return}N.preventDefault(),ee.closest(".android-mirror-panel")?.focus({preventScroll:!0}),kt(),Qr(),on(),GF(ee,N.pointerId),W.current.set(N.pointerId,{x:N.clientX,y:N.clientY});const ie=N.pointerType==="mouse"&&N.altKey;if(W.current.size>=2||ie){const xt=B.current;xt&&($.pointerCancel(xt.x,xt.y,xt.type),B.current=null,Ve.current=null,Ge(null),qt(!1),q([])),U.current=!0,Ls();return}if(U.current)return;const Qe=jh(ee,N.clientX,N.clientY);B.current={id:N.pointerId,type:N.pointerType,x:Qe.x,y:Qe.y},$.pointerDown(Qe.x,Qe.y,N.pointerType);const ze=Jb(ee,N.clientX,N.clientY);ze&&(Ve.current={left:ze.left,top:ze.top},q([]),qt(!1),Ge(ze))},$r=N=>{const $=x.current,ee=m.current;if(!ee||!W.current.has(N.pointerId))return;if(N.pointerType==="mouse"){const _t=ee.getBoundingClientRect(),Mr=ee.parentElement?.getBoundingClientRect()??_t;if(!(N.buttons&1)||N.clientX<Math.max(_t.left,Mr.left)||N.clientX>=Math.min(_t.right,Mr.right)||N.clientY<Math.max(_t.top,Mr.top)||N.clientY>=Math.min(_t.bottom,Mr.bottom)){Sr();return}}if(N.preventDefault(),W.current.set(N.pointerId,{x:N.clientX,y:N.clientY}),F.current){sn();return}const ie=B.current;if(!$||!ie||ie.id!==N.pointerId)return;const Qe=jh(ee,N.clientX,N.clientY);ie.x=Qe.x,ie.y=Qe.y,$.pointerMove(Qe.x,Qe.y,ie.type);const ze=Jb(ee,N.clientX,N.clientY),xt=Ve.current;!ze||!xt||(Ge(ze),Math.hypot(ze.left-xt.left,ze.top-xt.top)>=6&&(qt(!0),q(_t=>{const Mr=_t[_t.length-1];if(Mr&&Math.hypot(ze.left-Mr.x,ze.top-Mr.y)<4)return _t;const Dt=[..._t,{x:ze.left,y:ze.top}];return Dt.length>12?Dt.slice(Dt.length-12):Dt})))},Wn=N=>{const $=x.current,ee=m.current;if(!ee||!W.current.has(N.pointerId))return;if(on(),W.current.delete(N.pointerId),Vb(ee,N.pointerId),W.current.size===0&&(U.current=!1),F.current){W.current.size===0?(F.current=null,Z(ce.current)):Ls();return}const ie=B.current;if(!ie||ie.id!==N.pointerId)return;const Qe=jh(ee,N.clientX,N.clientY);$?.pointerUp(Qe.x,Qe.y,ie.type),me&&ks(me),Ge(null),qt(!1),window.setTimeout(()=>q([]),200),B.current=null,Ve.current=null},Gn=N=>{if(Tr||et||yt)return;const $=x.current;$&&(N.key==="Backspace"?(N.preventDefault(),$.key(67)):N.key==="Escape"?(N.preventDefault(),$.back()):N.key==="Enter"&&(N.preventDefault(),$.key(66)))},un=async()=>{const N=Nt.trim();if(N){It(!0);try{const $=await dF(N);gt(""),Ct(!1),await qr(),Oe($.serial)}catch($){ye($ instanceof Error?$.message:"ADB_CONNECT_FAILED")}finally{It(!1)}}},Kn=()=>{const N=x.current,$=nr;!N||!$||(N.sendText($),Cr(""))},kr=b.useCallback(N=>{Lr(N),Ir.current!==null&&window.clearTimeout(Ir.current),Ir.current=window.setTimeout(()=>{Ir.current=null,Lr(null)},2500)},[]),Er=b.useCallback(N=>{const $=ce.current,ee=N==="in"?Gb.find(ie=>ie>$+.01):[...Gb].reverse().find(ie=>ie<$-.01);ee!==void 0&&($<=_l&&ee>_l&&kr(l("android.zoomPanHint")),on(),tr(ee),Z(ee))},[tr,on,kr,l]),gr=N=>{Promise.resolve().then(()=>r?.(N)).catch($=>{Vr($ instanceof Error?$.message:String($))})},rs=b.useCallback(async(N,$)=>{try{if(!n)throw new Error(l("android.captureUnavailable"));await n(N),kr($)}catch(ee){Vr(l("android.captureFailed")+(ee instanceof Error?`:${ee.message}`:""))}},[n,kr,l]),$n=async()=>{const N=m.current;if(!(!N||ne.current)){ne.current=!0,Ht(!0),Vr(null);try{const $=await $F(N);await rs($,l("android.captureInserted"))}catch($){Vr($ instanceof Error?$.message:String($))}finally{ne.current=!1,Ht(!1)}}},kn=b.useCallback(N=>{(N.status==="ready"||N.status==="error")&&Ot.current&&!Rr.current.has(N.id)&&(Rr.current.add(N.id),Ot.current?.(N))},[]),Ln=b.useCallback(async N=>{const $=an.current;if(!(!$||wt.current)){wt.current=!0,nt(!0),Vr(null);try{const ee=await mF($.id);an.current=null,dt(!1),kn(ee)}catch(ee){Vr(ee instanceof Error?ee.message:String(ee))}finally{wt.current=!1,nt(!1)}}},[kn]),ps=async()=>{if(!(!re||wt.current||an.current)){wt.current=!0,nt(!0),Vr(null);try{const N=await pF(re);N.status==="recording"||N.status==="starting"||N.status==="stopping"?(an.current=N,dt(!0),xn(Math.max(0,Date.now()-N.startedAt))):kn(N)}catch(N){Vr(N instanceof Error?N.message:String(N))}finally{wt.current=!1,nt(!1)}}};b.useEffect(()=>{let N=!1,$=!1;an.current=null,dt(!1);const ee=async()=>{if(!(!re||$||wt.current)){$=!0;try{const{recordings:Qe}=await fF(re);if(N||wt.current)return;const ze=Qe.find(xt=>["starting","recording","stopping"].includes(xt.status));an.current=ze??null,dt(!!ze);for(const xt of Qe)kn(xt)}catch{}finally{$=!1}}};ee();const ie=window.setInterval(()=>{ee()},2e3);return rn.current=window.setInterval(()=>{an.current&&xn(Math.max(0,Date.now()-an.current.startedAt))},500),()=>{N=!0,window.clearInterval(ie),rn.current!==null&&window.clearInterval(rn.current)}},[re,kn]),b.useEffect(()=>{if(!Tr)return;const N=()=>mr(!1),$=ie=>{const Qe=ie.target;Qe instanceof Node&&(dr.current?.contains(Qe)||bn.current?.contains(Qe)||N())},ee=ie=>{ie.key==="Escape"&&(ie.preventDefault(),ie.stopPropagation(),N())};return document.addEventListener("pointerdown",$,!0),document.addEventListener("keydown",ee,!0),window.addEventListener("resize",N),()=>{document.removeEventListener("pointerdown",$,!0),document.removeEventListener("keydown",ee,!0),window.removeEventListener("resize",N)}},[Tr]),b.useEffect(()=>()=>{Ir.current!==null&&window.clearTimeout(Ir.current)},[]);const G=We==="streaming",Le=ir,Ke=Le?"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",ct=fs?(fs.model||fs.serial)+ey(fs,l):Wr.length?l("android.selectDevice"):l("android.noDevices"),At=(le?Be.find(N=>N.id===le):null)?.name??(Ce==="auto"?`${l("android.qualityAuto")} · ${E/1e6} Mbps`:l(jm[Ce])),Rt=Le?"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",Bt=Le?"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",ot="absolute inset-0 h-full w-full cursor-pointer opacity-0",Ft=()=>{const N=dr.current?.getBoundingClientRect();N&&_n({left:Math.max(8,Math.min(N.right-Mm,window.innerWidth-Mm-8)),top:Math.min(N.bottom+4,Math.max(8,window.innerHeight-zF-8))}),mr(!0)},hr=()=>{if(ir){Pr(Ud,null),Fr({docked:null});return}if(!Tn)return;const N={sessionId:Tn,side:"right"};Pr(Ud,N),Fr({docked:N})},Kt=et||ir||d!=="off",z=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:Gn,tabIndex:-1,children:[s.jsxs("div",{"data-panel-drag-title":ir?"true":void 0,className:Le?"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:[ir&&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(Ff,{size:12})}),s.jsx(u9,{size:Le?12:14,className:"shrink-0 text-muted-foreground"}),s.jsxs("div",{className:`${Rt} flex-1`,children:[s.jsx("span",{"aria-hidden":"true",className:`${Bt} w-full`,children:ct}),s.jsxs("select",{value:re,onChange:N=>{const $=N.target.value;Oe($),$e.current=$,$&&Fr({deviceSerial:$})},className:ot,"aria-label":l("android.device"),children:[s.jsx("option",{value:"",children:Wr.length?l("android.selectDevice"):l("android.noDevices")}),Wr.map(N=>s.jsx("option",{value:N.serial,children:(N.model||N.serial)+ey(N,l)},N.serial))]})]}),s.jsxs("div",{className:`${Rt} max-w-[45%] shrink-0`,children:[s.jsx("span",{"aria-hidden":"true",className:Bt,children:At}),s.jsxs("select",{value:le?`user:${le}`:Ce,onChange:N=>Xr(N.target.value),className:ot,title:l(Ce==="auto"?"android.qualityAutoHint":"android.quality"),"aria-label":l("android.quality"),children:[s.jsxs("option",{value:"auto",children:[l("android.qualityAuto"),Ce==="auto"?` · ${E/1e6} Mbps`:""]}),Of.map(N=>s.jsx("option",{value:N.id,children:l(jm[N.id])},N.id)),Be.map(N=>s.jsx("option",{value:`user:${N.id}`,children:N.name},N.id)),s.jsx("option",{value:"custom",children:l(jm.custom)})]})]}),s.jsx("button",{type:"button",onClick:()=>{qr()},className:`${Ke} text-muted-foreground`,title:l("android.refresh"),children:_e?s.jsx(Cn,{size:13,className:"animate-spin"}):s.jsx(gn,{size:13})}),G?s.jsx("button",{type:"button",onClick:Kr,className:`${Ke} text-destructive`,title:l("android.disconnect"),children:s.jsx(Oy,{size:13})}):s.jsx("button",{type:"button",onClick:()=>re&&nn(re),disabled:!re,className:`${Ke} text-primary`,title:l("android.connect"),children:s.jsx(sS,{size:13})}),(G||it)&&s.jsx("button",{type:"button",onClick:()=>{$n()},disabled:!n||ht,className:`${Ke} text-muted-foreground`,title:l(n?"android.screenshot":"android.captureUnavailable"),"aria-label":l("android.screenshot"),children:ht?s.jsx(Cn,{size:Le?12:13,className:"animate-spin"}):s.jsx(PA,{size:Le?12:13})}),(G||it)&&s.jsx("button",{type:"button",onClick:()=>{it?Ln("manual"):ps()},disabled:Me||!it&&!a,className:`${Ke} ${it?"text-destructive":"text-muted-foreground"}`,title:l(it?"android.recordingStop":a?"android.recordingStart":"android.captureUnavailable"),"aria-label":l(it?"android.recordingStop":"android.recordingStart"),children:Me?s.jsx(Cn,{className:"animate-spin",size:13}):it?s.jsx(Py,{size:Le?10:11,fill:"currentColor"}):s.jsx(Fy,{size:Le?12:13})}),s.jsx("button",{ref:dr,type:"button",onClick:()=>Tr?mr(!1):Ft(),"aria-haspopup":"menu","aria-expanded":Tr,className:`${Ke} ${Kt?"text-primary":"text-muted-foreground"}`,title:l("android.more"),"aria-label":l("android.more"),children:s.jsx($o,{size:Le?13:14})}),c&&!t&&s.jsx("button",{type:"button",onClick:()=>{mr(!1),p("off"),c()},className:`${Ke} text-muted-foreground hover:bg-destructive/20 hover:text-destructive`,title:l("android.closeTab"),"aria-label":l("android.closeTab"),children:s.jsx(Rn,{size:14})})]}),Tr&&Hr&&Ii.createPortal(s.jsxs("div",{ref:bn,role:"menu","aria-label":l("android.more"),style:{left:Hr.left,top:Hr.top,width:Mm},className:"fixed z-popover overflow-hidden rounded-md border border-border bg-surface-elevated py-1 text-[11px] shadow-lg",children:[s.jsx(Mh,{icon:s.jsx(ul,{size:13}),label:l("android.addDevice"),active:et,onSelect:()=>{Ct(N=>!N),mr(!1)}}),s.jsx(Mh,{icon:ir?s.jsx(Rn,{size:13}):s.jsx(Il,{size:13}),label:l(ir?"android.splitClose":"android.splitOpen"),active:ir,disabled:!ir&&!Tn,onSelect:()=>{hr(),mr(!1)}}),s.jsx(Mh,{icon:d==="window"?s.jsx(ET,{size:13}):s.jsx(_T,{size:13}),label:l(d==="window"?"android.exitFullscreen":"android.fullscreen"),active:d==="window",onSelect:()=>{p(d==="window"?"off":"window"),mr(!1)}}),!t&&s.jsx(Mh,{icon:d==="sidebar"?s.jsx(FT,{size:13}):s.jsx(HT,{size:13}),label:l(d==="sidebar"?"android.exitFullscreen":"android.fillSidebar"),active:d==="sidebar",onSelect:()=>{p(d==="sidebar"?"off":"sidebar"),mr(!1)}}),be&&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:`${Je.fps} fps · ${Je.kbps} kbps`}),s.jsx("div",{className:"truncate",children:`${Je.width}×${Je.height}`})]})]}),document.body),(Ce==="custom"||le)&&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:()=>Ye(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"),le?` · ${Be.find(N=>N.id===le)?.name??""}`:""]})]}),ue&&s.jsxs("div",{className:"mt-2 grid gap-2",children:[s.jsx(Xb,{label:l("android.qualityResolution"),display:`${st.maxSize}px`,min:360,max:2160,step:8,value:st.maxSize,onChange:N=>Ie($=>({...$,maxSize:N}))}),s.jsx(Xb,{label:l("android.qualityBitRate"),display:`${(st.bitRate/1e6).toFixed(1)} Mbps`,min:.5,max:20,step:.5,value:st.bitRate/1e6,onChange:N=>Ie($=>({...$,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($=>({...$,maxFps:N})),className:`rounded px-2 py-0.5 ${st.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 ${st.maxFps===0?"bg-surface-elevated text-primary":"text-muted-foreground hover:bg-surface-2"}`,children:l("android.qualityAuto")})]}),s.jsx("button",{type:"button",onClick:fn,disabled:!re,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:rt,onChange:N=>mt(N.target.value),onKeyDown:N=>{N.key==="Enter"&&!N.nativeEvent.isComposing&&K()},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:K,disabled:!rt.trim(),className:"shrink-0 rounded bg-surface-2 px-2 py-1 text-primary disabled:opacity-40",children:l("android.presetSave")}),le&&s.jsx("button",{type:"button",onClick:Ue,className:"shrink-0 rounded px-2 py-1 text-destructive hover:bg-surface-2",children:l("android.presetDelete")})]})]})]}),et&&s.jsxs("div",{className:"flex items-center gap-1.5 border-b border-border px-2 py-2",children:[s.jsx("input",{value:Nt,onChange:N=>gt(N.target.value),onKeyDown:N=>{N.key==="Enter"&&un()},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:()=>{un()},disabled:bt,className:"rounded bg-surface-2 px-2 py-1 text-[11px] text-primary disabled:opacity-40",children:bt?s.jsx(Cn,{size:12,className:"animate-spin"}):l("android.connect")})]}),Br&&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(Zb,{label:l("android.insertFixPrompt"),onClick:()=>gr(Kb("adb",Se??"")),enabled:!!r})]}),!Br&&Mn&&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(Zb,{label:l("android.insertFixPrompt"),onClick:()=>gr(Kb("scrcpy","")),enabled:!!r})]}),fs&&fs.state!=="device"&&s.jsx("div",{className:"border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-warning",children:KF(fs,l)}),Se&&!Br&&s.jsx("div",{className:"border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-destructive",children:Bb(Se)}),Vt&&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(Vt.startsWith("SCRCPY_VERSION")?"android.qualityAutoVersionError":Vt.startsWith("SCRCPY_BUILD")?"android.qualityAutoBuildError":/EXTENSION|SERVER_READ|PUSH/.test(Vt.split(":")[0])?"android.qualityAutoExtensionError":/TIMEOUT/.test(Vt.split(":")[0])?"android.qualityAutoTimeoutError":/ENCODER_REJECTED/.test(Vt.split(":")[0])?"android.qualityAutoEncoderError":/CHANNEL|TUNNEL|LISTEN|PROTOCOL|CONNECTION/.test(Vt.split(":")[0])?"android.qualityAutoChannelError":"android.qualityAutoUnknownError")]}),s.jsx("pre",{className:"mt-1 select-text whitespace-pre-wrap break-all text-[10px]",children:Vt})]}),vt&&s.jsx("div",{className:"border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-warning",children:vt}),ge&&s.jsx("div",{role:"alert",className:"border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-destructive",children:ge}),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:G||be?"block":"none",transformOrigin:"center",transition:"none"},onPointerDown:_r,onPointerMove:$r,onPointerUp:Wn,onPointerCancel:()=>Sr(),onLostPointerCapture:N=>{W.current.has(N.pointerId)&&Sr()},onPointerLeave:N=>{W.current.has(N.pointerId)&&!N.currentTarget.hasPointerCapture?.(N.pointerId)&&Sr()},onContextMenu:N=>N.preventDefault()}),me&&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:me.left,top:me.top}}),pt.length>1&&s.jsx("svg",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0 h-full w-full",style:{opacity:at?1:0,transition:"opacity 160ms linear"},children:pt.slice(1).map((N,$)=>{const ee=pt[$],ie=($+1)/(pt.length-1);return s.jsx("line",{x1:ee.x,y1:ee.y,x2:N.x,y2:N.y,stroke:"var(--primary)",strokeWidth:1+1.6*ie,strokeLinecap:"round",opacity:.06+.45*ie},$)})}),zt.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)),!G&&s.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-2 text-center text-[11px] text-muted-foreground",children:[We==="connecting"&&s.jsxs(s.Fragment,{children:[s.jsx(Cn,{size:18,className:"animate-spin"}),s.jsx("span",{children:l("android.connecting")})]}),We==="error"&&s.jsxs(s.Fragment,{children:[s.jsx($u,{size:14,className:"text-destructive"}),s.jsx("span",{className:"max-w-[80%] text-destructive",children:Pt?l("android.reconnecting"):Bb(H||"")}),re&&s.jsx("button",{type:"button",onClick:()=>{Y.current=0,nn(re)},className:"rounded bg-surface-2 px-2 py-1 text-foreground",children:l("android.retry")})]}),We==="idle"&&!Br&&!Mn&&s.jsxs(s.Fragment,{children:[s.jsx(RT,{size:22,className:"opacity-60"}),s.jsx("span",{children:Wr.length?l("android.idleHint"):l("android.noDevicesHint")})]})]})]}),s.jsxs("div",{className:`flex flex-wrap items-center gap-1 border-t border-border ${Le?"px-1.5 py-0.5":"px-2 py-1.5"}`,children:[s.jsx(Mo,{compact:Le,label:l("android.back"),onClick:()=>x.current?.back(),disabled:!G,children:s.jsx(Cy,{size:14})}),s.jsx(Mo,{compact:Le,label:l("android.home"),onClick:()=>x.current?.home(),disabled:!G,children:s.jsx(yT,{size:14})}),s.jsx(Mo,{compact:Le,label:l("android.recents"),onClick:()=>x.current?.recents(),disabled:!G,children:s.jsx(jy,{size:14})}),s.jsx(Mo,{compact:Le,label:l("android.notifications"),onClick:()=>x.current?.expandNotifications(),disabled:!G,children:s.jsx(Ey,{size:14})}),s.jsx(Mo,{compact:Le,label:l("android.rotate"),onClick:()=>x.current?.rotate(),disabled:!G,children:s.jsx(uS,{size:14})}),s.jsx(Mo,{compact:Le,label:l("android.volumeDown"),onClick:()=>x.current?.volumeDown(),disabled:!G,children:s.jsx(jS,{size:14})}),s.jsx(Mo,{compact:Le,label:l("android.volumeUp"),onClick:()=>x.current?.volumeUp(),disabled:!G,children:s.jsx(BS,{size:14})}),s.jsx(Mo,{compact:Le,label:l("android.power"),onClick:()=>x.current?.power(),disabled:!G,children:s.jsx(aS,{size:14})}),s.jsx(Mo,{compact:Le,label:l("android.inputText"),active:yt,onClick:()=>pr(N=>!N),disabled:!G,children:s.jsx(My,{size:14})}),s.jsx(Mo,{compact:Le,label:l("android.zoomIn"),onClick:()=>Er("in"),disabled:!G||V>=rf-.01,children:s.jsx(Us,{size:14})}),s.jsx(Mo,{compact:Le,label:l("android.zoomOut"),onClick:()=>Er("out"),disabled:!G||V<=_l+.01,children:s.jsx(Dy,{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":it||!!cn||ht,className:`block truncate text-right text-[10px] leading-5 tabular-nums text-muted-foreground ${it||cn||ht?"invisible":""}`,children:be?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(YF,{recording:it,elapsed:sr,status:ht?l("android.captureInserting"):cn,stopLabel:l("android.recordingStop"),onStop:()=>{Ln("manual")}})})]})]}),yt&&s.jsxs("div",{className:"flex items-center gap-1.5 border-t border-border px-2 py-1.5",children:[s.jsx("input",{value:nr,onChange:N=>Cr(N.target.value),onKeyDown:N=>{N.key==="Enter"&&!N.nativeEvent.isComposing&&(N.preventDefault(),Kn())},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:Kn,disabled:!nr,className:"rounded bg-surface-2 p-1.5 text-primary disabled:opacity-40",title:l("android.send"),children:s.jsx(r0,{size:13})})]})]});return d==="window"?Ii.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:z}),document.body):t?ir&&pn?Ii.createPortal(z,pn):null:ir&&pn?s.jsxs(s.Fragment,{children:[Ii.createPortal(z,pn),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:()=>{Pr(Ud,null),Fr({docked:null})},className:"rounded bg-surface-2 px-2 py-1 text-foreground",children:l("android.splitClose")})]})]}):z}function Mh({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(hi,{size:12,className:"shrink-0"})]})}function YF({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"}),zb(t),s.jsx("button",{type:"button",onClick:a,title:n,"aria-label":`${n} · ${zb(t)}`,className:"ml-0.5 inline-flex h-4 w-4 items-center justify-center rounded hover:bg-destructive/25",children:s.jsx(Py,{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 Yb({sessionId:e}){const t=es(x=>x.docks[Xd]),r=!!t,n=t?.sessionId??e??null,c=Rm(x=>x.pending)[0],l=b.useCallback(async x=>{if(!n)throw new Error("没有可接收截图的终端");const w=(await L0("/tmp",[x])).files[0]?.path;if(!w)throw new Error("截图上传未返回文件路径");await Wb(w,n)},[n]),d=b.useCallback(x=>{Rm.getState().enqueue(x,n)},[n]),p=es(x=>!!x.hosts[Xd]),m=b.useRef(!1);return b.useEffect(()=>{m.current||(m.current=!0,fc().then(x=>{const y=x.androidPanel?.docked;y&&(es.getState().docks[Xd]||es.getState().setDock(Xd,y))}).catch(()=>{}))},[]),s.jsxs(s.Fragment,{children:[r&&p&&s.jsx(qF,{sessionId:n,dockOnly:!0,onInsertFile:n?l:void 0,onInsertPrompt:n?x=>Z6(x,n):void 0,onRecordingComplete:d}),c&&s.jsx(UF,{file:c.file,initialPath:c.initialPath,onInsert:x=>c.insert?c.insert(x):Wb(x,c.sessionId),onDone:()=>Rm.getState().remove(c.file.id)},c.file.id)]})}function Zb({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 Kb(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 Xb({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 Mo({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 Jb(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 jh(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 ZF(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 ey(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 KF(e,t){return e.state==="unauthorized"?t("android.unauthorizedHint"):e.state==="offline"?t("android.offlineHint"):t("android.stateUnknown")}function XF(e){return e>=90?"var(--destructive)":e>=70?"var(--warning)":"var(--success)"}function JF(e){return e>=90?"var(--destructive)/0.15":e>=70?"var(--warning)/0.15":"var(--success)/0.12"}function e$(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 t$(e){return{claude:"🧠",codex:"✨",kimi:"🌙",copilot:"🐙",grok:"🚀",gemini:"💎"}[e]||"📊"}function r$({result:e}){const{t}=zr(),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:t$(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:JF(d.percent)},children:s.jsx("div",{className:"h-full rounded-full transition-all duration-500",style:{width:`${p}%`,background:XF(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:e$(d.resetAt)})]},d.label)})}):c?s.jsx("p",{className:"mt-2 text-[11px] text-muted-foreground",children:e.error}):null]})}function n$({isOpen:e,onClose:t}){const{t:r}=zr(),[n,a]=b.useState([]),[c,l]=b.useState(!1),d=async(x=!1)=>{l(!0);try{const y=x?await d9():await h9();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(gn,{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(Rn,{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(d0,{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(r$,{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 ty=[{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~"}],s$=2,i$=20;function a$({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 o$({value:e,onChange:t,placeholder:r}){const{t:n}=zr(),[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=V3(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&&Rx(p),x=m&&!bf(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=Rx(y),v=w&&!bf(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(Rn,{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 l$({value:e,min:t,max:r,onChange:n}){const{t:a}=zr();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(Dy,{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(Us,{size:14})})]})}const c$=({presets:e,selectedPresetId:t,onSelectPreset:r,onUpdatePreset:n,onAddPreset:a,onRemovePreset:c,onResetDefaults:l})=>{const{t:d}=zr(),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:a1(R,B)})):["Enter","Home","End","Ctrl-C","Ctrl-D"].map(R=>({id:R,label:R}))],v=q3(w,p.rowLayout),S=(R,B)=>{n(p.id,W=>{const F=W.actions.findIndex(Z=>Z.id===R);if(F===-1)return W;const U=F+B;if(U<0||U>=W.actions.length)return W;const V=[...W.actions];return[V[F],V[U]]=[V[U],V[F]],{...W,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 W=R.items[0]?.kind==="preset",F=Math.max(2,R.columns),U=W?`${Y3}px repeat(${Math.max(1,F-1)}, minmax(0, 1fr))`:`repeat(${F}, minmax(0, 1fr))`;return s.jsx("div",{className:"grid gap-1",style:{gridTemplateColumns:U},children:R.items.map(V=>V.kind==="preset"?s.jsx(Z3,{mode:"auto",presetLabel:V.label,title:`Auto preset · ${V.label}`,disabled:!0},V.id):s.jsx(a$,{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(Us,{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(gn,{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(zs,{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(o$,{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:[...X1(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(Us,{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(l$,{value:R,min:s$,max:i$,onChange:W=>n(p.id,F=>({...F,rowLayout:F.rowLayout.map((U,V)=>V===B?W:U)}))}),p.rowLayout.length>1&&s.jsx("button",{type:"button",onClick:()=>n(p.id,W=>({...W,rowLayout:W.rowLayout.filter((F,U)=>U!==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(Us,{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 W=m===R.id;return s.jsxs("div",{className:`rounded-2xl bg-surface-2 transition ${W?"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(Iy,{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(kA,{size:12})})]}),s.jsxs("button",{type:"button",onClick:()=>x(W?null:R.id),className:"min-w-0 flex-1 text-left",children:[s.jsx("div",{className:"truncate text-sm font-medium text-foreground",children:a1(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,F=>({...F,actions:F.actions.filter(U=>U.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(zs,{size:14})})]}),W&&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:F=>n(p.id,U=>({...U,actions:U.actions.map(V=>V.id===R.id?{...V,label:F.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:F=>n(p.id,U=>({...U,actions:U.actions.map(V=>V.id===R.id?{...V,sequence:F.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:ty.map(F=>s.jsx("button",{type:"button",onClick:()=>n(p.id,U=>({...U,actions:U.actions.map(V=>V.id===R.id?{...V,sequence:F.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:F.label},F.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,F=>({...F,actions:F.actions.map(U=>U.id===R.id?{...U,doubleTapSequence:""}:U)})),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:F=>n(p.id,U=>({...U,actions:U.actions.map(V=>V.id===R.id?{...V,doubleTapSequence:F.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:[ty.map(F=>s.jsx("button",{type:"button",onClick:()=>n(p.id,U=>({...U,actions:U.actions.map(V=>V.id===R.id?{...V,doubleTapSequence:(V.doubleTapSequence??"")+F.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:F.label},F.label)),s.jsx("button",{type:"button",onClick:()=>n(p.id,F=>({...F,actions:F.actions.map(U=>{if(U.id!==R.id)return U;const{doubleTapSequence:V,...Z}=U;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)})]})]})]})},u$={installed:"text-[color:var(--success)]",outdated:"text-[color:var(--warning)]","needs-approval":"text-[color:var(--warning)]","not-installed":"text-muted-foreground"};function d$(){const{t:e}=zr(),[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),[W,F]=k.useState([]),[U,V]=k.useState([]),[Z,ce]=k.useState(null),[xe,pe]=k.useState(new Set),[te,ke]=k.useState(null),[$e,Y]=k.useState("auto"),[Ae,lt]=k.useState({}),[Se,ye]=k.useState(null),[_e,je]=k.useState(null),[re,Oe]=k.useState(10),[Ce,Ee]=k.useState(""),[Be,Ne]=k.useState(""),[le,He]=k.useState(12e3),[rt,mt]=k.useState(null),[ue,Ye]=k.useState(null),st=k.useCallback(async()=>{const[me,Ge,pt,q]=await Promise.allSettled([f9(),p9(),fc(),ud()]);if(r(me.status==="fulfilled"?me.value:[]),Ge.status==="fulfilled"){const at=Ge.value;F(at.plugins??[]),V(at.errors??[])}else F([]),V([]);if(pt.status==="fulfilled"){const at=pt.value;pe(new Set(at.autoRenameAgents??[])),Y(at.autoRenameNamer??"auto"),lt(at.autoRenameModels??{}),Oe(at.autoRenameIntervalMinutes??10),Ee(at.autoRenamePromptPreference??""),Ne(at.autoRenamePromptPreference??""),He(at.autoRenamePromptPayloadChars??12e3)}else pe(new Set);ye(q.status==="fulfilled"?q.value:[])},[]);k.useEffect(()=>{st()},[st]);const Ie=async(me,Ge)=>{a(me),l(null);try{Ge==="install"?(await m9(me)).devMode&&p(me):(await g9(me),d===me&&p(null)),await st()}catch(pt){l(pt instanceof Error?pt.message:String(pt))}finally{a(null)}},We=me=>e(me==="installed"?"settings.agentHooksInstalled":me==="outdated"?"settings.agentHooksOutdated":me==="needs-approval"?"settings.agentHooksNeedsApproval":"settings.agentHooksNotInstalled"),Te=async()=>{B(null);let me;try{me=JSON.parse(L)}catch{B("Invalid JSON");return}try{await A9(me),E(""),x(!1),await st()}catch(Ge){if(Ge instanceof T9&&Ge.migration){V(pt=>[{slug:typeof me.slug=="string"?me.slug:"manifest.json",errors:Ge.message.split(`
|
|
164
164
|
`),code:Ge.code,migration:Ge.migration},...pt.filter(q=>q.slug!==me.slug)]);return}B(Ge instanceof Error?Ge.message:String(Ge))}},H=async()=>{const me=v.trim();if(me){mt("install"),B(null);try{await x9(me),S(""),w(!1),await st()}catch(Ge){B(Ge instanceof Error?Ge.message:String(Ge))}finally{mt(null)}}},oe=async me=>{mt(`remove:${me}`);try{await w9(me),Ye(Ge=>Ge?.slug===me?null:Ge),await st()}catch(Ge){l(Ge instanceof Error?Ge.message:String(Ge))}finally{mt(null)}},be=async me=>{mt(`check:${me}`),l(null);try{await v9(me),await st()}catch(Ge){l(Ge instanceof Error?Ge.message:String(Ge))}finally{mt(null)}},Ze=async me=>{mt(`update:${me}`),l(null);try{const Ge=await y9(me),pt=[Ge.hookWarning,Ge.titleWarning].filter(Boolean).join(" ");pt&&l(pt),Ye(q=>q?.slug===me?null:q),await st()}catch(Ge){l(Ge instanceof Error?Ge.message:String(Ge))}finally{mt(null)}},Je=async me=>{mt(`doctor:${me}`),l(null),Ye(null);try{const Ge=await b9(me);Ye(Ge),ye(await ud())}catch(Ge){l(Ge instanceof Error?Ge.message:String(Ge))}finally{mt(null)}},St=async me=>{const Ge=me.migration?.aiPrompt??me.errors.join(`
|
|
165
165
|
`);try{await navigator.clipboard.writeText(Ge),ce(me.slug),window.setTimeout(()=>ce(pt=>pt===me.slug?null:pt),1800)}catch{B(Ge)}},Vt=async me=>{if(te)return;const Ge=xe,pt=new Set(Ge);pt.has(me)?pt.delete(me):pt.add(me),pe(pt),ke(me),l(null);try{const q=await ka({autoRenameAgents:[...pt]});pe(new Set(q.autoRenameAgents??[])),ye(await ud(!0))}catch(q){pe(Ge),l(q instanceof Error?q.message:String(q))}finally{ke(null)}},jt=async me=>{const Ge=$e;Y(me),je("namer"),l(null);try{const pt=await ka({autoRenameNamer:me});Y(pt.autoRenameNamer??"auto"),ye(await ud(!0))}catch(pt){Y(Ge),l(pt instanceof Error?pt.message:String(pt))}finally{je(null)}},vt=async(me,Ge)=>{const pt=Ae,q={...pt};Ge?q[me]=Ge:delete q[me],lt(q),je(me),l(null);try{const at=await ka({autoRenameModels:q});lt(at.autoRenameModels??{})}catch(at){lt(pt),l(at instanceof Error?at.message:String(at))}finally{je(null)}},Zt=async me=>{const Ge=re;Oe(me),je("interval"),l(null);try{const pt=await ka({autoRenameIntervalMinutes:me});Oe(pt.autoRenameIntervalMinutes??10)}catch(pt){Oe(Ge),l(pt instanceof Error?pt.message:String(pt))}finally{je(null)}},Pt=async()=>{const me=Ce.trim();if(me!==Be){je("preference"),l(null);try{const pt=(await ka({autoRenamePromptPreference:me})).autoRenamePromptPreference??"";Ee(pt),Ne(pt)}catch(Ge){Ee(Be),l(Ge instanceof Error?Ge.message:String(Ge))}finally{je(null)}}},Xt=async me=>{const Ge=Math.max(1e3,Math.min(64e3,Math.round(me||12e3))),pt=le;He(Ge),je("payload-limit"),l(null);try{const q=await ka({autoRenamePromptPayloadChars:Ge});He(q.autoRenamePromptPayloadChars??12e3)}catch(q){He(pt),l(q instanceof Error?q.message:String(q))}finally{je(null)}},zt=new Set(W.map(me=>me.slug)),Lt=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:$e,disabled:_e!==null,onChange:me=>{jt(me.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")}),Se?.filter(me=>me.available).map(me=>s.jsx("option",{value:me.slug,children:me.displayName},me.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:re,disabled:_e!==null,onChange:me=>{Zt(Number(me.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(me=>s.jsxs("option",{value:me,children:[me," ",e("settings.agentAutoRenameMinutes")]},me))})]}),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:Ce,maxLength:2e3,rows:3,disabled:_e!==null,placeholder:e("settings.agentAutoRenamePreferencePlaceholder"),onChange:me=>Ee(me.target.value),onBlur:()=>{Pt()},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:_e==="preference"?e("settings.saving"):`${Ce.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:le,disabled:_e!==null,onChange:me=>He(Number(me.target.value)),onBlur:me=>{Xt(Number(me.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 ud(!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(gn,{size:11,className:Se===null?"animate-spin":""})})]}),Se?.filter(me=>me.available).map(me=>{const Ge=me.models.find(pt=>pt.id===me.recommendedModel);return s.jsxs("label",{className:"flex items-center justify-between gap-3",children:[s.jsx("span",{className:"text-[11px] text-muted-foreground",children:me.displayName}),s.jsxs("select",{value:Ae[me.slug]??"",disabled:_e!==null,onChange:pt=>{vt(me.slug,pt.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:Ge?`${e("settings.agentAutoRenameAutomatic")} · ${Ge.displayName}`:e("settings.agentAutoRenameCliDefault")}),me.models.map(pt=>s.jsx("option",{value:pt.id,children:pt.displayName},pt.id))]})]},me.slug)}),Se?.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(Cn,{size:12,className:"animate-spin"})," …"]}),t?.map(me=>{const Ge=n===me.slug,pt=me.state!=="not-installed",q=zt.has(me.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:me.slug,displayName:me.displayName,accentColor:me.accentColor??"#878580",icon:me.icon,isPlugin:q,iconMode:me.iconMode,iconVersion:me.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:me.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] ${u$[me.state]}`,children:[me.state==="installed"&&s.jsx(Fu,{size:10,className:"mr-0.5 inline"}),(me.state==="outdated"||me.state==="needs-approval")&&s.jsx(Q1,{size:10,className:"mr-0.5 inline"}),We(me.state)]})]}),s.jsxs("div",{className:"truncate text-[10px] text-muted-foreground",title:me.targetDisplay,children:[e("settings.agentHooksTarget")," ",me.targetDisplay]}),d===me.slug&&s.jsx("div",{className:"mt-0.5 text-[10px] text-[color:var(--warning)]",children:e("settings.agentHooksDevMode")}),me.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:te!==null,onClick:()=>{Vt(me.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":xe.has(me.slug),title:e("settings.agentAutoRenameToggle"),children:[s.jsx("span",{children:e("settings.agentAutoRenameShort")}),s.jsx(ll,{checked:xe.has(me.slug),disabled:te!==null,size:"sm"})]}),s.jsxs("button",{type:"button",disabled:Ge,onClick:()=>{Ie(me.slug,pt?"uninstall":"install")},className:`flex shrink-0 items-center gap-1 rounded-full px-2.5 py-1 text-[11px] font-medium transition ${pt?"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:[Ge?s.jsx(Cn,{size:11,className:"animate-spin"}):pt?s.jsx(zs,{size:11}):me.state==="outdated"?s.jsx(gn,{size:11}):s.jsx(f0,{size:11}),Ge?"…":pt?e("settings.agentHooksUninstall"):me.state==="outdated"?e("settings.agentHooksReinstall"):e("settings.agentHooksInstall")]})]})]},me.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(Us,{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:me=>S(me.target.value),onKeyDown:me=>{me.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()||rt!==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:[rt==="install"?s.jsx(Cn,{size:11,className:"animate-spin"}):s.jsx(f0,{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")})]}),W.map(me=>{const Ge=me.revision?.slice(0,8),pt=rt?.endsWith(`:${me.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:me.displayName}),me.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:me.source??void 0,children:[me.source??e("settings.agentPluginManualSource"),Ge?` · ${Ge}`:""]})]}),s.jsxs("button",{type:"button",disabled:rt!==null,onClick:()=>{Je(me.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:[rt===`doctor:${me.slug}`?s.jsx(Cn,{size:10,className:"animate-spin"}):s.jsx(TS,{size:10}),e("settings.agentPluginDoctor")]}),me.updateSupported&&s.jsxs("button",{type:"button",disabled:rt!==null,onClick:()=>{me.updateAvailable?Ze(me.slug):be(me.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:[pt?s.jsx(Cn,{size:10,className:"animate-spin"}):s.jsx(gn,{size:10}),me.updateAvailable?e("settings.agentPluginUpdate"):e("settings.agentPluginCheck")]}),s.jsx("button",{type:"button",disabled:rt!==null,onClick:()=>{oe(me.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(zs,{size:11})})]},me.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,": ",Lt]}),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(me=>s.jsxs("div",{children:["• ",me]},me))}),ue.nextSteps.length>0&&s.jsx("div",{className:"mt-1 space-y-0.5 text-muted-foreground",children:ue.nextSteps.map(me=>s.jsxs("div",{children:["→ ",me]},me))})]}),U.map(me=>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:[me.slug,": ",me.code??e("settings.agentPluginInvalid")]}),s.jsxs("button",{type:"button",onClick:()=>{St(me)},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===me.slug?s.jsx(Fu,{size:10}):s.jsx(Ny,{size:10}),Z===me.slug?e("settings.agentPluginCopied"):e("settings.agentPluginCopyAiPrompt")]})]}),s.jsx("div",{className:"mt-1 whitespace-pre-wrap break-words text-muted-foreground",children:me.errors.join(`
|
|
@@ -182,5 +182,5 @@ ${Ye.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:()=>{Te()},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(XA,{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 h$({state:e,pending:t,onCheck:r,onConfirmRestart:n,desktopState:a,desktopPending:c=!1,desktopSnapshot:l,desktopActions:d,onCheckDesktop:p,onInstallDesktop:m}){const{t:x}=zr(),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",W=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(gn,{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(gn,{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?W: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 f$({quality:e}){const{locale:t}=zr(),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 p$({backendSessionId:e}){const{locale:t}=zr(),r=t==="zh",[n,a]=k.useState(null),[c,l]=k.useState(!1);k.useEffect(()=>{if(a(null),!c||!e)return;const y=()=>a(S9(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(f$,{quality:n})]})]})]})}const ry={"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 m$(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 g$({state:e,onDismiss:t}){const{t:r}=zr(),[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 W=window.setTimeout(()=>{d.current=!1,a(!1),l(!0)},45e3);return()=>window.clearTimeout(W)},[n]);const m=async()=>{if(!d.current){d.current=!0,l(!1),a(!0);try{await C9()}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(ry[x.event]??"settings.serverHealthUnknownEvent"):"",R=x?.causeEvent?r(ry[x.causeEvent]??"settings.serverHealthUnknownEvent"):"",B=x?[new Date(x.at).toLocaleString(),x.uptimeMs!==null?r("settings.serverHealthUptime",{duration:m$(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(xS,{size:15}):s.jsx(yS,{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 x$=()=>()=>{},b$=()=>1/0;function y$(){const{t:e}=zr(),t=b.useId(),r=Bo(),n=b.useSyncExternalStore(r?.subscribe??x$,r?.retentionLimit??b$);if(!r)return null;const a=_9+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 R1="mobile-session-destroy";function v$(e,t){return t&&e.type==="session"&&e.destination?.droppableId===R1}const Sa="termdock-program-rules-cache",Dh="termdock-toolbar-presets-cache",Hd="termdock-settings-cache",ny="termdock-color-theme",sy="termdock:right-sidebar:file-preview-open-by-session:v2",Wd="termdock:running-session-button-enabled:v1",Gd="termdock:attention-button-enabled:v1",w$=60,iy=320,ay=420,jo=8;function oy(e,t,r){return Math.min(Math.max(e,t),r)}function ly(e){if(typeof window>"u")return{left:jo,top:jo};const t=window.innerWidth/2,r=Math.min(64,window.innerHeight/4),n=e?.x??t,a=e?.y??r,c=Math.max(jo,window.innerWidth-iy-jo),l=Math.max(jo,window.innerHeight-ay-jo);return{left:oy(n+jo,jo,c),top:oy(a+jo,jo,l),width:iy,maxHeight:`min(${ay}px, calc(100vh - ${jo*2}px))`}}function A$(e){return e==="dark"||e==="light"}function T$(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 Dm(e){const t=Object.entries(e).filter(([r,n])=>r&&Number.isFinite(n.updatedAt)).sort(([,r],[,n])=>n.updatedAt-r.updatedAt).slice(0,w$);return Object.fromEntries(t)}function S$(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 C$(e){return typeof e=="object"&&e!==null&&typeof e.version=="number"&&Array.isArray(e.presets)}function _$(e,t){const r=b0(),n=new Set(pE()),a=Array.isArray(e)?e:[],c=Eu(a),l=t<Zd;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 k$(e){return typeof e=="object"&&e!==null&&typeof e.preventSleep=="boolean"&&typeof e.networkAvailable=="boolean"}const L$={name:"",source:"auto",hostname:"",fallbackHostname:"",url:"",fallbackUrl:"",onboardingUrl:null,status:"disabled",reason:null,httpsEnabled:!1,caAvailable:!1,lanAddresses:[],interfaces:[]},rp="__termdockOverlay",np="__termdockBaseAnchor",sp="__termdockBaseGuard",I$=3,cy=250,E$="termdock-notification-target-v1",uy="/__termdock-notification-target",dy=3e4;function N$(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 Au(e){if(!e||typeof e!="object")return null;const t=e[rp];return N$(t)?t:null}function Ig(e){return e&&typeof e=="object"?{...e}:{}}function X6(e){const t=Ig(e);return delete t[rp],t}function R$(e){const t=X6(e);return delete t[sp],{...t,[np]:!0}}function M$(){typeof window>"u"||window.history.pushState({...X6(window.history.state),[np]:!0,[sp]:!0},"",window.location.href)}function J6(){for(let e=0;e<I$;e+=1)M$()}function Bh(){typeof window>"u"||(window.history.replaceState(R$(window.history.state),"",window.location.href),J6())}function Vd(e){typeof window>"u"||window.history.pushState({...Ig(window.history.state),[np]:!0,[rp]:e,[sp]:!1},"",window.location.href)}function j$(e){typeof window>"u"||window.history.replaceState({...Ig(window.history.state),[np]:!0,[rp]:e,[sp]:!1},"",window.location.href)}const e4=["bash","zsh","fish","sh","dash","ksh","tcsh","csh","nu"];let Ca=new Set(e4);function hy(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 D$(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 fy(e,t){return s.jsx(PP,{sessionMode:e,state:t})}function B$(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 Q$=k.lazy(()=>Oc(()=>import("./CollaborationMainWorkspace-D5WKV3rA.js"),__vite__mapDeps([18,1,2,3,4,5,8,9,15,13])));function P$(){const{t:e,locale:t,setLocale:r}=zr(),n="env(safe-area-inset-top, 0px)",a="env(safe-area-inset-bottom, 0px)";k9();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(ny,A$)??"dark"),x=k.useRef(Tc(Hd,k$)).current,[y,w]=k.useState(x?.preventSleep??!1),[v,S]=k.useState(x?.networkAvailable??!0),[L,E]=k.useState(L9),[R,B]=k.useState(I9),[W,F]=k.useState(E9),[U,V]=k.useState(N9),[Z,ce]=k.useState(Ap),[xe,pe]=k.useState(x?.localAccess??L$),[te,ke]=k.useState(x?.localAccess?.name??""),[$e,Y]=k.useState(!1),[Ae,lt]=k.useState(null),[Se,ye]=k.useState(null),[_e,je]=k.useState(null),[re,Oe]=k.useState(!1),[Ce,Ee]=k.useState(null),Be=k.useMemo(()=>xo(),[]),Ne=!!(Be?.desktopUpdateState&&Be.checkDesktopUpdate&&Be.installDesktopUpdate),[le,He]=k.useState(null),[rt,mt]=k.useState(null),[ue,Ye]=k.useState(!1),[st,Ie]=k.useState(null),[We,Te]=k.useState(!1),[H,oe]=k.useState(()=>Dm(Tc(sy,T$)??{})),[be,Ze]=k.useState(0),[Je,St]=k.useState(!1),[Vt,jt]=k.useState(0),[vt,Zt]=k.useState(!1),[Pt,Xt]=k.useState(0),[zt,Lt]=k.useState(!1),[me,Ge]=k.useState(0),pt=k.useRef(null),[q,at]=k.useState({}),{terminalSettings:qt,updateTerminalSettings:Ve}=WB(),De=qt.fontSize,er=qt.rendererMode,[et,Ct]=k.useState(!1),Nt=k.useRef(R9()).current,[gt,bt]=b.useState(()=>Nt.sessions.map(C=>({id:C.sessionId,name:C.name,customName:C.customName,mode:C.mode,tmuxSessionName:C.tmuxSessionName}))),It=la(C=>C.groupId);k.useEffect(()=>{const C=()=>la.getState().terminal();return window.addEventListener("switch-terminal-session",C),()=>window.removeEventListener("switch-terminal-session",C)},[]);const[yt,pr]=k.useState(Nt.activeSessionId),[nr,Cr]=k.useState(!1);k.useEffect(()=>{nr&&M9({rendered:!0})},[nr]);const[cn,Lr]=k.useState(null),[ge,Vr]=k.useState(null),[it,dt]=k.useState([]),[sr,xn]=b.useState(()=>{const C=Yr.getState();return Nt.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)}),Nu("session-chrome-hydrated"),hy(Yr.getState().sessions)});b.useEffect(()=>{!Be||!et||Promise.all([Be.snapshot(),Be.desktopUpdateState?.()??Promise.resolve(null)]).then(([C,P])=>{He(C),mt(P)}).catch(C=>Ie(C instanceof Error?C.message:String(C)))},[Be,et]),b.useEffect(()=>{Be?.onDesktopUpdateState&&Be.onDesktopUpdateState(mt)},[Be]),b.useEffect(()=>Yr.subscribe(C=>{const P=hy(C.sessions);xn(de=>D$(de,P)?de:P)}),[]);const an=b.useCallback(async(C,P)=>{Vr(null),Lr({sessionId:C,status:"submitting",error:null});try{await j9(P),Lr(de=>de?.sessionId===C?{...de,status:"waiting",error:null}:de)}catch(de){const Tt=(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");Lr(Yt=>Yt?.sessionId===C?{...Yt,error:Tt}:Yt),Vr({tone:"error",message:Tt})}},[e]);b.useEffect(()=>{if(!cn||cn.status!=="waiting")return;const C=sr.get(cn.sessionId);if(!C||C.agentResumeRecovered||C.agentStatus===null&&!C.agent)return;const P=C.agent?.displayName??"Agent";Lr(null),Vr({tone:"success",message:e("tab.resumeAgentSuccess",{agent:P})})},[cn,sr,e]),b.useEffect(()=>{if(!cn||cn.status!=="waiting"||cn.error)return;const C=cn.sessionId,P=window.setTimeout(()=>{const de=e("tab.resumeAgentTimeout");Lr(tt=>tt?.sessionId===C&&tt.status==="waiting"?{...tt,error:de}:tt),Vr({tone:"error",message:de})},15e3);return()=>window.clearTimeout(P)},[cn,e]),b.useEffect(()=>{if(ge?.tone!=="success")return;const C=window.setTimeout(()=>Vr(null),3200);return()=>window.clearTimeout(C)},[ge]),b.useEffect(()=>{let C=!1;D9().then(de=>{C||je(de)}).catch(()=>{}),B9().then(de=>{C||Ee(de)}).catch(()=>{});const P=l2(de=>{C||(de.type==="update-state"?je(de.state):de.type==="server-health"&&Ee(de.state))});return()=>{C=!0,P()}},[]);const Me=b.useCallback(async()=>{try{Ee(await Q9())}catch(C){window.alert(C instanceof Error?C.message:String(C))}},[]),nt=b.useCallback(async()=>{const C=_e?.latestVersion;if(!(!C||re)&&window.confirm(e("sidebar.updateRestartConfirm",{version:C}))){Oe(!0);try{je(await P9())}catch(P){window.alert(P instanceof Error?P.message:String(P))}finally{Oe(!1)}}},[_e?.latestVersion,e,re]),wt=b.useCallback(async()=>{if(!re){Oe(!0);try{je(await O9())}catch(C){window.alert(C instanceof Error?C.message:String(C))}finally{Oe(!1)}}},[re]),Rr=b.useCallback(async()=>{if(!(!Be?.checkDesktopUpdate||ue)){Ye(!0);try{mt(await Be.checkDesktopUpdate())}catch(C){Ie(C instanceof Error?C.message:String(C))}finally{Ye(!1)}}},[Be,ue]),rn=b.useCallback(async()=>{if(!(!Be?.installDesktopUpdate||ue||rt?.status!=="ready")&&window.confirm(e("settings.desktopUpdateRestartConfirm"))){Ye(!0);try{mt(await Be.installDesktopUpdate())}catch(C){Ie(C instanceof Error?C.message:String(C))}finally{Ye(!1)}}},[Be,ue,rt?.status,e]);b.useEffect(()=>{document.documentElement.dataset.theme=p,F9(p),On(ny,p)},[p]),b.useEffect(()=>{On(sy,Dm(H))},[H]);const Ir=Gt(C=>C.leftOpen),ne=Gt(C=>C.rightOpen),ht=Gt(C=>C.leftPinned),Ht=Gt(C=>C.leftSidebarWidth),Ot=Gt(C=>C.rightPinned),Tr=Gt(C=>C.rightSidebarWidth),mr=Gt(C=>C.rootPath),Hr=Gt(C=>C.contextKey),_n=Gt(C=>C.selectedFilePath),dr=Gt(C=>C.groupByFolder),bn=uf(C=>C.collaborationGroups),hn=Gt(C=>C.collapsedGroups),Tn=Gt(C=>C.toggleGroupCollapsed),[ir,pn]=b.useState(()=>typeof window>"u"?!0:window.matchMedia("(min-width: 1024px)").matches),[Pr,qr]=b.useState(()=>typeof window>"u"?1024:window.innerWidth),[Wr,fs]=b.useState(()=>typeof window>"u"?!1:window.matchMedia("(orientation: landscape)").matches),[Br,Mn]=b.useState([]),[Sr,Kr]=b.useState({available:!0,version:null,reason:null}),[nn,Fr]=b.useState(!1),[ks,Or]=b.useState(null),[Xr,fn]=b.useState(null),[K,Ue]=b.useState(null),[Et,kt]=b.useState(null),[tr,Qr]=b.useState(null),[cr,Sn]=b.useState(null),[Ls,Zn]=b.useState(null),[,sn]=b.useState(0),[on,_r]=b.useState(null),[$r,Wn]=b.useState(null),[Gn,un]=b.useState(null),[Kn,kr]=b.useState(!1),[Er,gr]=b.useState(()=>Tc(Wd,C=>typeof C=="boolean")??!1),rs=b.useCallback(async C=>{const P=Er;gr(C),On(Wd,C);try{const de=await ka({runningSessionButtonEnabled:C});gr(de.runningSessionButtonEnabled),On(Wd,de.runningSessionButtonEnabled)}catch{gr(P),On(Wd,P)}},[Er]),[$n,kn]=b.useState(()=>Tc(Gd,C=>typeof C=="boolean")??!0),Ln=b.useCallback(async C=>{const P=$n;kn(C),On(Gd,C);try{const de=await ka({attentionButtonEnabled:C});kn(de.attentionButtonEnabled),On(Gd,de.attentionButtonEnabled)}catch{kn(P),On(Gd,P)}},[$n]),[ps,G]=b.useState(null),Le=b.useCallback(C=>{G(C)},[]),Ke=b.useRef(!1),[ct,qe]=b.useState(null),[At,Rt]=b.useState(null),Bt=k.useRef(null),ot=k.useRef(!1),Ft=k.useRef(null),hr=k.useRef(!1),Kt=b.useCallback(()=>{Sn(null),Zn(null)},[]),z=k.useRef(typeof window>"u"?null:new URLSearchParams(window.location.search).get("session")),[N,$]=k.useState(z.current),[ee,ie]=k.useState(!0),Qe=k.useRef(z.current),ze=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=()=>{pn(C.matches),qr(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=()=>fs(C.matches);return P(),C.addEventListener("change",P),()=>C.removeEventListener("change",P)},[]);const xt=k.useMemo(()=>yt?it.find(C=>C.sessionIds.includes(yt))??null:null,[yt,it]),_t=xt?.id??null,Mr=xt?.sessionIds[0]??yt,Dt=k.useRef([]);k.useLayoutEffect(()=>{const C=Dt.current;if(Dt.current=it,C.length===0)return;const P=new Set(it.flatMap(de=>de.sessionIds));for(const de of C){const tt=de.sessionIds.filter(Tt=>!P.has(Tt)).map(Tt=>({sessionId:Tt,rootPath:Yr.getState().sessions.get(Tt)?.cwd??null}));tt.length>0&&Gt.getState().inheritRightSidebarStateFromSplitWorkspace(de.id,tt)}},[it]),k.useLayoutEffect(()=>((()=>{const P=Mr?Yr.getState().sessions.get(Mr)?.cwd??null:null;Gt.getState().setRootPath(P,Mr,_t)})(),Yr.subscribe((P,de)=>{const tt=Mr?P.sessions.get(Mr)?.cwd??null:null,Tt=Mr?de.sessions.get(Mr)?.cwd??null:null;tt!==Tt&&Gt.getState().setRootPath(tt,Mr,_t)})),[_t,Mr]);const Gr=k.useRef(Vy(window.location.search)??JS(Sc()?.targetPeerId)),[dn,jn]=k.useState("");k.useEffect(()=>{const C=Gr.current;if(!C)return;if(C.peerId&&C.peerId!==Sc()?.targetPeerId){const tt=$9().find(Tt=>Tt.targetPeerId===C.peerId);if(tt&&Bo()){try{XS(C)}catch{jn(t==="zh"?"无法在此浏览器打开架构链接。":"Cannot open this architecture link in this browser.");return}if(U9(tt)){Gr.current=null;const Tt=new URL(window.location.href);Tt.searchParams.delete("architecture"),window.history.replaceState(window.history.state,"",Tt);return}}jn(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}jn("");try{sessionStorage.setItem(`termdock.architecture.selection:${C.root}`,C.file)}catch{}const P=Gt.getState();P.setRootPath(C.root,Mr,_t),P.setRightTab("architecture"),P.openRight();const de=new URL(window.location.href);de.searchParams.delete("architecture"),window.history.replaceState(window.history.state,"",de),Mr&&(Gr.current=null)},[Mr,_t,t]);const ns=ir||Wr,Un=Pr*.95,fr=ns?Math.min(Math.max(Pr*.22,280),340):Math.min(Pr*.86,380),Mt=yt&&mr?`${yt}\0${mr}`:"",Dn=!!(Mt&&_n&&H[Mt]),Vn=b.useCallback(C=>{Mt&&(C&&!Gt.getState().selectedFilePath||oe(P=>{if(!!P[Mt]===C)return P;if(C)return Dm({...P,[Mt]:{updatedAt:Date.now()}});const tt={...P};return delete tt[Mt],tt}))},[Mt]);b.useEffect(()=>{KB(Mt,Hr,_n)&&oe(C=>{if(!C[Mt])return C;const P={...C};return delete P[Mt],P})},[Mt,Hr,_n]);const Bn=zt?"markdown-image-lightbox":vt?"markdown-outline":Je?"right-sidebar-repo-picker":ne&&Dn?"right-sidebar-file-preview":et?"settings":ne&&!(Ot&&ir)?"right-sidebar":Ir&&!(ht&&ir)?"left-sidebar":null,ss=k.useRef(Bn),$i=k.useRef(Bn),ua=k.useRef(!1),bs=k.useRef(!1),Wa=b.useCallback(()=>{if(typeof window>"u")return;const C=window.matchMedia("(hover: hover) and (pointer: fine)").matches;!ir||!C||navigator.maxTouchPoints>0||window.setTimeout(()=>{window.dispatchEvent(new CustomEvent("focus-active-terminal-session"))},0)},[ir]),wo=b.useCallback(C=>{if(C==="markdown-image-lightbox"){Lt(!1),Ge(P=>P+1);return}if(C==="markdown-outline"){Zt(!1),Xt(P=>P+1);return}if(C==="right-sidebar-file-preview"){Zt(!1),Xt(P=>P+1),Vn(!1),Ze(P=>P+1);return}if(C==="right-sidebar-repo-picker"){St(!1),jt(P=>P+1);return}if(C==="settings"){Ct(!1),ws(!1),ti(!1),ls(!1);return}if(C==="left-sidebar"){Gt.getState().closeLeft();return}Zt(!1),Xt(P=>P+1),St(!1),jt(P=>P+1),Lt(!1),Ge(P=>P+1),Gt.getState().closeRight()},[Vn]),zn=b.useCallback(C=>{if(!c&&typeof window<"u"&&ss.current===C&&Au(window.history.state)===C){window.history.back();return}wo(C)},[wo,c]),da=b.useCallback(()=>{Ct(!1);const C=Gt.getState();C.closeRight(),C.openLeft()},[]),ms=b.useCallback(()=>{Ct(!1);const C=Gt.getState();C.closeLeft(),C.openRight()},[]),La=b.useCallback(()=>{Ct(!1);const C=Gt.getState();C.closeLeft(),C.openRight(),C.setRightTab("files"),C.openRightSearch()},[]),is=b.useCallback(()=>{const C=Gt.getState();if(C.leftPinned){C.setLeftPinned(!1),C.closeLeft();return}if(Ir){zn("left-sidebar");return}da()},[da,zn,Ir]),Ga=b.useCallback(()=>{const C=Gt.getState();C.leftPinned?(C.setLeftPinned(!1),C.openLeft()):(C.setLeftPinned(!0),C.openLeft())},[]),Ks=b.useCallback(()=>{const C=Gt.getState();C.setLeftPinned(!1),C.closeLeft()},[]),Xs=b.useCallback(()=>{const C=Gt.getState();C.rightPinned?(C.setRightPinned(!1),C.openRight()):(C.setRightPinned(!0),C.openRight())},[]),Hs=b.useCallback(()=>{const C=Gt.getState();C.setRightPinned(!1),C.closeRight()},[]),Va=b.useRef(0),Is=b.useRef(0),ha=b.useRef(null),dl=b.useCallback(C=>{C.preventDefault(),Va.current=C.clientX,Is.current=Gt.getState().leftSidebarWidth;const P=tt=>{ha.current===null&&(ha.current=requestAnimationFrame(()=>{ha.current=null;const Tt=tt.clientX-Va.current;Gt.getState().setLeftSidebarWidth(Is.current+Tt)}))},de=()=>{window.removeEventListener("mousemove",P),window.removeEventListener("mouseup",de),ha.current!==null&&(cancelAnimationFrame(ha.current),ha.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)},[]),qa=b.useRef(0),as=b.useRef(0),Rs=b.useRef(null),Ui=b.useCallback(C=>{C.preventDefault(),qa.current=C.clientX;const P=Gt.getState(),de=P.leftPinned?P.leftSidebarWidth:0;as.current=Ph(P.rightSidebarWidth,window.innerWidth,de);const tt=Yt=>{Rs.current===null&&(Rs.current=requestAnimationFrame(()=>{Rs.current=null;const jr=qa.current-Yt.clientX,vn=Gt.getState(),En=vn.leftPinned?vn.leftSidebarWidth:0;vn.setRightSidebarWidth(Ph(as.current+jr,window.innerWidth,En))}))},Tt=()=>{window.removeEventListener("mousemove",tt),window.removeEventListener("mouseup",Tt),Rs.current!==null&&(cancelAnimationFrame(Rs.current),Rs.current=null),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",window.addEventListener("mousemove",tt),window.addEventListener("mouseup",Tt)},[]),gi=b.useCallback(()=>{const C=Gt.getState();if(C.rightPinned){C.setRightPinned(!1),C.closeRight();return}if(ne){zn("right-sidebar");return}ms()},[ms,zn,ne]),xi=b.useCallback(()=>{!Dn&&!c&&typeof window<"u"&&ss.current==="right-sidebar"&&Au(window.history.state)==="right-sidebar"&&(Vd("right-sidebar-file-preview"),$i.current="right-sidebar-file-preview"),Vn(!0)},[Dn,c,Vn]),hl=b.useCallback(()=>{zn("right-sidebar-file-preview")},[zn]),Js=b.useCallback(()=>{!Je&&!c&&typeof window<"u"&&ss.current==="right-sidebar"&&Au(window.history.state)==="right-sidebar"&&(Vd("right-sidebar-repo-picker"),$i.current="right-sidebar-repo-picker"),St(!0)},[Je,c]),Uo=b.useCallback(()=>{zn("right-sidebar-repo-picker")},[zn]),fa=b.useCallback(()=>{!vt&&!c&&typeof window<"u"&&ss.current&&Au(window.history.state)===ss.current&&(Vd("markdown-outline"),$i.current="markdown-outline"),Zt(!0)},[vt,c]),fl=b.useCallback(()=>{zn("markdown-outline")},[zn]),pl=b.useCallback(()=>{!c&&typeof window<"u"&&ss.current&&Au(window.history.state)===ss.current&&(Vd("markdown-image-lightbox"),$i.current="markdown-image-lightbox"),Lt(!0)},[c]),os=b.useCallback(()=>{zn("markdown-image-lightbox")},[zn]),Ms=b.useCallback(()=>{!c&&typeof window<"u"&&ss.current&&Au(window.history.state)===ss.current&&(j$("settings"),$i.current="settings"),Gt.getState().closeAll(),Ct(!0)},[c]),Ni=b.useCallback(()=>{zn("settings")},[zn]);b.useEffect(()=>{if(!Be)return;const C=()=>Ms();return window.addEventListener("termdock:open-settings",C),()=>window.removeEventListener("termdock:open-settings",C)},[Be,Ms]);const zo=b.useCallback(()=>{Te(!0),pt.current!==null&&(window.clearTimeout(pt.current),pt.current=null)},[]),jl=b.useCallback(()=>{pt.current!==null&&(window.clearTimeout(pt.current),pt.current=null),Te(!1),bs.current=!0,Bh(),bs.current},[]);b.useEffect(()=>()=>{pt.current!==null&&window.clearTimeout(pt.current)},[]),b.useEffect(()=>{c||Bh()},[c]),b.useEffect(()=>{if(typeof window>"u"||c)return;let C=null;const P=()=>{C!==null&&(window.clearTimeout(C),C=null)},de=vn=>{if(ss.current,bs.current,ss.current){ss.current;return}!vn?.force&&bs.current||(vn?.userActivated&&(bs.current=!0),Bh(),bs.current,void 0)},tt=()=>{P(),C=window.setTimeout(()=>{C=null,de({force:!0})},cy)},Tt=()=>{de({userActivated:!0})},Yt=()=>{tt()},jr=()=>{document.visibilityState==="visible"&&tt()};return window.addEventListener("pointerdown",Tt,{capture:!0,passive:!0}),window.addEventListener("touchstart",Tt,{capture:!0,passive:!0}),window.addEventListener("keydown",Tt,{capture:!0}),window.addEventListener("pageshow",Yt),document.addEventListener("visibilitychange",jr),()=>{P(),window.removeEventListener("pointerdown",Tt,{capture:!0}),window.removeEventListener("touchstart",Tt,{capture:!0}),window.removeEventListener("keydown",Tt,{capture:!0}),window.removeEventListener("pageshow",Yt),document.removeEventListener("visibilitychange",jr)}},[c]),b.useEffect(()=>{ss.current=Bn},[Bn]),b.useEffect(()=>{if(typeof window>"u"||Bn||c)return;const C=window.setTimeout(()=>{ss.current?(ss.current,void 0):Bh()},cy);return()=>window.clearTimeout(C)},[Bn,c]),b.useEffect(()=>{if(typeof window>"u"||c)return;const C=$i.current;ua.current,Bn&&Bn!==C&&!ua.current&&Vd(Bn),!Bn&&C&&Wa(),$i.current=Bn,!Bn&&ua.current&&window.setTimeout(()=>{ua.current=!1},0)},[Bn,c,Wa]),b.useEffect(()=>{if(typeof window>"u"||c)return;const C=()=>{const P=ss.current;if(bs.current,!P){bs.current=!1,bs.current,zo(),J6();return}ua.current=!0,wo(P)};return window.addEventListener("popstate",C),()=>window.removeEventListener("popstate",C)},[wo,zo,c]),b.useEffect(()=>{const C=P=>{const de=P.metaKey||P.ctrlKey;if(de&&P.key==="b"&&!P.shiftKey&&(P.preventDefault(),is()),de&&P.shiftKey&&P.key==="E"&&(P.preventDefault(),gi()),de&&P.shiftKey&&P.key==="P"&&(P.preventDefault(),La()),de&&!P.shiftKey&&P.altKey&&(P.key==="ArrowLeft"||P.key==="ArrowRight")){P.preventDefault();const tt=P.key==="ArrowRight"?"next":"prev";window.dispatchEvent(new CustomEvent("cycle-terminal-session",{detail:{direction:tt}}));return}if(de&&P.shiftKey&&!P.altKey&&(P.code==="BracketLeft"||P.code==="BracketRight")){P.preventDefault();const tt=P.code==="BracketRight"?"next":"prev";window.dispatchEvent(new CustomEvent("cycle-terminal-session",{detail:{direction:tt}}));return}};return document.addEventListener("keydown",C),()=>{document.removeEventListener("keydown",C)}},[is,gi,La]);const Es=b.useCallback(async()=>{Y(!0),lt(null);try{const C=await ka({localAccess:{name:te}});pe(C.localAccess),ke(C.localAccess.name),On(Hd,{preventSleep:C.preventSleep,networkAvailable:C.networkAvailable,localAccess:C.localAccess})}catch(C){lt(C instanceof Error?C.message:"Failed to save local access name")}finally{Y(!1)}},[te]),Ia=b.useCallback(async()=>{Y(!0),lt(null);try{const C=await ka({localAccess:{reset:!0}});pe(C.localAccess),ke(C.localAccess.name),On(Hd,{preventSleep:C.preventSleep,networkAvailable:C.networkAvailable,localAccess:C.localAccess})}catch(C){lt(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)}},[]),Xn=b.useCallback(C=>{const P=B$(gt,C);P.map(de=>de.id).join("\0")!==gt.map(de=>de.id).join("\0")&&(bt(P),window.dispatchEvent(new CustomEvent("reorder-terminal-session",{detail:{sessionIds:P.map(de=>de.id)}})))},[gt]),zi=b.useCallback(C=>{ir||C.type!=="session"||(Ke.current=!1,kr(!1),un(C.draggableId))},[ir]),Ri=b.useCallback(C=>{if(ir||C.type!=="session")return;const P=C.destination?.droppableId===R1;P!==Ke.current&&(Ke.current=P,kr(P),P&&navigator.vibrate?.(20))},[ir]),Hi=b.useCallback(C=>{const P=v$(C,!ir);if(Ke.current=!1,kr(!1),un(null),!P)return!1;const de=gt.find(Tt=>Tt.id===C.draggableId),tt=de?sr.get(de.id):null;return de&&B5({mode:de.mode,activeProgram:tt?.activeProgram??null,promptState:tt?.promptState??null,shellNames:Ca})?(Rt(null),qe(de.id),Ue(null)):de&&window.dispatchEvent(new CustomEvent("close-terminal-session",{detail:{sessionId:de.id,source:"other",closeMode:de.mode==="tmux"?"destroy":"auto"}})),!0},[ir,gt,sr]),{groups:gs,arranged:Ws}=k.useMemo(()=>lf(gt,C=>sr.get(C.id)?.cwd??null,dr,e("sidebar.ungrouped"),it,bn),[gt,sr,dr,e,it,bn]),Dl=b.useCallback(C=>{Hi(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}}))},[Hi,Ws]),Wi=b.useCallback((C,P)=>{const de=P.trim();de&&window.dispatchEvent(new CustomEvent("rename-terminal-session",{detail:{sessionId:C,name:de}}))},[]),Gi=b.useCallback(C=>{window.dispatchEvent(new CustomEvent("reset-terminal-session-name",{detail:{sessionId:C}}))},[]),{newSessionMode:ln,newSessionTmuxName:pa,userSelectedNewSessionMode:Vi,setNewSessionMode:Ea}=qB(),[Mi,ji]=b.useState(null),[ei,ws]=k.useState(!1),[Gs,Di]=k.useState(!1),[Na,ti]=k.useState(!1),[ys,Ya]=k.useState("idle"),Za=k.useRef(Tc(Dh,C$)).current,[As,Ka]=k.useState(()=>{const C=Za?.presets;if(C&&C.length>0){const P=Eu(C);if(P.length>0)return P}return b0()}),[Bl,Ho]=k.useState(!1),[Ao,ma]=k.useState("default"),Ra=k.useRef(typeof Za?.updatedAt=="number"?Za.updatedAt:null),Wo=k.useRef(!1),[ga,ls]=k.useState(!1),[Go,qi]=k.useState(!1),gl=k.useRef(Tc(Sa,S$)).current,[se,T]=k.useState(gl??[]),[j,Q]=k.useState(gl!==null),[O,fe]=k.useState(!1),we=!It&&!Bn&&!Gs&&!Na&&!ei&&!ga&&!Go&&!cr&&!ct&&!Mi,Pe=k.useCallback(C=>{const P=typeof C.version=="number"?C.version:0,de=_$(Array.isArray(C.presets)?C.presets:[],P);Ra.current=typeof C.updatedAt=="number"?C.updatedAt:null,Ka(tt=>z9(tt,de)?tt:(Wo.current=!0,de)),On(Dh,{version:Zd,presets:de,updatedAt:Ra.current??void 0})},[]);b.useEffect(()=>{const C=P=>{if(P.key!=="Escape"||P.defaultPrevented||P.isComposing||D1())return;if(Gs){P.preventDefault(),Di(!1);return}if(Na){P.preventDefault(),ti(!1);return}if(ei){P.preventDefault(),ws(!1);return}if(ga){P.preventDefault(),ls(!1);return}if(Go){P.preventDefault(),qi(!1);return}if(cr){P.preventDefault(),Kt();return}if(on){P.preventDefault(),Qr(null),_r(null);return}if(et){P.preventDefault(),Ni();return}if(ne&&!(Ot&&ir)){P.preventDefault(),zn("right-sidebar");return}Ir&&!(ht&&ir)&&(P.preventDefault(),zn("left-sidebar"))};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[Gs,Na,ei,ga,cr,Kt,et,ne,Ot,Ir,ht,ir,Ni,zn]),b.useEffect(()=>{Q(!0)},[]);const[Xe,ft]=k.useState({genericProgramNames:[],wrapperScriptNames:[],shellNames:e4}),[,Jt]=k.useState(!1),or=k.useCallback(()=>H9().then(C=>{ft(C),Ca=new Set(C.shellNames),Jt(!0)}).catch(()=>{}),[]);b.useEffect(()=>{or()},[or]),b.useEffect(()=>l2(C=>{if(C.type==="config-updated"){if(C.key==="toolbar-presets"){c2().then(P=>Pe(P)).catch(P=>{console.warn("[toolbar-presets] Failed to refresh after remote update:",P)});return}C.key==="program-detection"&&or()}}),[Pe,or]),b.useEffect(()=>{let C=!1;return(async()=>{try{const P=await c2();if(C)return;Pe(P)}catch(P){console.warn("[toolbar-presets] Failed to load from server:",P)}finally{C||Ho(!0)}})(),()=>{C=!0}},[Pe]),b.useEffect(()=>{if(Bl){if(Wo.current){Wo.current=!1;return}On(Dh,{version:Zd,presets:As,updatedAt:Ra.current??void 0}),W9({version:Zd,presets:As,baseUpdatedAt:Ra.current??void 0}).then(C=>{Ra.current=typeof C.updatedAt=="number"?C.updatedAt:null,On(Dh,{version:Zd,presets:As,updatedAt:Ra.current??void 0})}).catch(C=>{const P=C instanceof Error&&"current"in C?C.current:null;P&&typeof P=="object"&&Pe(P),console.warn("[toolbar-presets] Failed to save to server:",C)})}},[Pe,As,Bl]),b.useEffect(()=>{fc().then(C=>{w(P=>P===C.preventSleep?P:C.preventSleep),S(P=>P===C.networkAvailable?P:C.networkAvailable),pe(C.localAccess),ke(C.localAccess.name),gr(C.runningSessionButtonEnabled),On(Wd,C.runningSessionButtonEnabled),kn(C.attentionButtonEnabled),On(Gd,C.attentionButtonEnabled),On(Hd,{preventSleep:C.preventSleep,networkAvailable:C.networkAvailable,localAccess:C.localAccess})}).catch(()=>{})},[]),b.useEffect(()=>{if(!L)return;const C=Ap();ce(C),C!=="granted"&&(E(!1),eh(!1))},[L]),b.useEffect(()=>{if(!L)return;dd();const C=()=>{document.visibilityState==="visible"&&(dd(),sA())},P=window.setInterval(()=>{dd()},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 Ur=b.useCallback(async()=>{if(L){E(!1),eh(!1),G9(),ce(Ap());return}const C=await V9();if(ce(C),C!=="granted"){E(!1),eh(!1);return}E(!0),eh(!0),await dd(!0,!0),Ya("idle")},[L]),Jr=b.useCallback(async()=>{Ya("checking"),await xo()?.prepareNotificationTest?.();const C=await q9({title:"Termdock",body:e("settings.notificationsTestBody"),tag:"termdock-notification-test",requireHidden:!1,data:{url:"/"}});Ya(C?"delivered":"failed")},[e]),Qn=b.useCallback(C=>{B(C),Y9(C),Tp()},[]),vr=b.useCallback(C=>{F(C),Z9(C),Tp()},[]),yn=b.useCallback(C=>{V(C),K9(C),Tp()},[]);b.useEffect(()=>{As.some(C=>C.id===Ao)||ma(As[0]?.id??"default")},[Ao,As]),b.useEffect(()=>{if(!Sr.available&&ln==="tmux"){Ea("shell",{userInitiated:!1});return}Sr.available&&Vi!=="shell"&&ln!=="tmux"&&Ea("tmux",{userInitiated:!1})},[ln,Sr.available,Vi,Ea]),b.useEffect(()=>{ji(null)},[et,ln,Sr.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),at(C)},[]);const cs=b.useCallback(C=>{if(Hi(C)||!C.destination)return;if(C.type==="group"){if(C.source.index===C.destination.index)return;Xn(Uy(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(tt=>tt.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,Xn,Hi]),js=k.useMemo(()=>Ws.flatMap(C=>{const P=sr.get(C.id);if(P?.agentStatus!=="working")return[];const{primary:de,secondary:tt}=il(C,P?.activeProgram??null,P?.cwd??null,Ca,P?.shellTitle??null,P?.promptState??null);return[{id:C.id,label:de,detail:tt}]}),[Ws,sr]),pc=yt?Ws.findIndex(C=>C.id===yt):-1,Vs=Ws.length>0&&pc>=0?`${pc+1}/${Ws.length}`:`${Ws.length}`,Yi=k.useMemo(()=>{let C=0;for(const P of gt){const de=sr.get(P.id);(de?.agentStatus==="waiting"||de?.agentNeedsReview)&&(C+=1)}return{running:js.length,review:C}},[js.length,gt,sr]),To=k.useMemo(()=>Ws.flatMap(C=>{const P=sr.get(C.id);if(P?.agentStatus!=="waiting"&&!P?.agentNeedsReview)return[];const{primary:de}=il(C,P.activeProgram,P.cwd,Ca,P.shellTitle,P.promptState);return[{id:P.terminalSessionId??C.id,label:de,waiting:P.agentStatus==="waiting"}]}),[Ws,sr]);X9(Yi.running,Yi.review,To);const bi=yt?gt.find(C=>C.id===yt)??null:null,So=bi?sr.get(bi.id):void 0,Jc=!!(bi&&So?.agentResumeRecovered&&So.agentNativeSessionId&&So.terminalSessionId),yi=bi&&cn?.sessionId===bi.id?cn:null;k.useLayoutEffect(()=>{if(!ee)return;const C=Ft.current;if(!C)return;const P=!hr.current;C.scrollIntoView({inline:"nearest",block:"nearest",behavior:P?"auto":"smooth"}),hr.current=!0,P&&Nu("active-tab-positioned")},[yt,ee]),b.useEffect(()=>{tr&&Bt.current&&(Bt.current.scrollIntoView({block:"nearest",inline:"nearest"}),Bt.current.focus(),Bt.current.select()),tr||(ot.current=!1)},[tr]);const O0=b.useCallback(C=>{window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:C}))},[]),vi=b.useCallback((C,P)=>{Zn(P??null),Sn(C)},[]),td=g6(),Xa=b.useCallback(C=>{if(!C)return;$(C),ze.current&&_a("info","PWA_NOTIFICATION_CLICK app-focus-request",{traceId:ze.current,requestedSessionId:C,activeSessionId:yt,sessions:gt.map(de=>({id:de.id,terminalSessionId:sr.get(de.id)?.terminalSessionId??null}))}),J9(C);const P=gt.find(de=>de.id===C||sr.get(de.id)?.terminalSessionId===C);P?(Qe.current=null,ze.current&&_a("info","PWA_NOTIFICATION_CLICK app-focus-dispatch",{traceId:ze.current,requestedSessionId:C,targetSessionId:P.id}),window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:P.id}))):(Qe.current=C,ze.current&&_a("info","PWA_NOTIFICATION_CLICK app-focus-pending",{traceId:ze.current,requestedSessionId:C}))},[yt,gt,sr]);b.useEffect(()=>{if(typeof window>"u"||typeof caches>"u")return;let C=!1;const P=async()=>{if(window.parent!==window&&Bo()){ie(!0);return}try{const tt=await caches.open(E$),Tt=await tt.match(uy);if(!Tt)return;await tt.delete(uy);const Yt=await Tt.json();if(C)return;const jr=typeof Yt.sessionId=="string"?Yt.sessionId:null,vn=typeof Yt.traceId=="string"?Yt.traceId:null,En=typeof Yt.clickedAt=="number"?Yt.clickedAt:0,In=Date.now()-En;_a("info","PWA_NOTIFICATION_CLICK app-cache-consumed",{traceId:vn,sessionId:jr,ageMs:In,valid:!!(jr&&In>=0&&In<=dy),visibilityState:document.visibilityState}),jr&&In>=0&&In<=dy&&(ze.current=vn,typeof Yt.targetPeerId=="string"&&Yt.targetPeerId!==Sc()?.targetPeerId?Bo()?.focusSession(Yt.targetPeerId,jr):Xa(jr))}catch(tt){_a("warn","PWA_NOTIFICATION_CLICK app-cache-failed",{error:tt instanceof Error?tt.message:String(tt)})}finally{C||ie(!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)}},[Xa]),b.useEffect(()=>{if(typeof window>"u")return;const C=new URLSearchParams(window.location.search),P=C.get("session");if(!P)return;_a("info","PWA_NOTIFICATION_CLICK app-url-received",{traceId:ze.current,targetSessionId:P,href:window.location.href,visibilityState:document.visibilityState});const de=C.get("service");de&&de!==Sc()?.targetPeerId?Bo()?.focusSession(de,P):Qe.current=P,C.delete("service"),C.delete("session"),C.delete("_notifTrace");const tt=C.toString(),Tt=`${window.location.pathname}${tt?`?${tt}`:""}${window.location.hash}`;window.history.replaceState(window.history.state,"",Tt)},[]),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(),tt=`${window.location.pathname}${de?`?${de}`:""}${window.location.hash}`;if(window.history.replaceState(window.history.state,"",tt),window.parent!==window&&Bo())return;const Tt=new BroadcastChannel("termdock:notif");let Yt=!1;const jr=En=>{En.data?.type==="termdock:notif-pong"&&!Yt&&(Yt=!0,Tt.close(),window.close())};Tt.addEventListener("message",jr),Tt.postMessage({type:"termdock:notif-ping",sessionId:P,targetPeerId:C.get("service")});const vn=setTimeout(()=>{Yt||Tt.close()},500);return()=>{clearTimeout(vn),Yt||Tt.close()}},[]),b.useEffect(()=>{if(typeof window>"u"||window.parent!==window&&Bo())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?Bo()?.focusSession(de.data.targetPeerId,de.data.sessionId):Xa(de.data.sessionId)))};return C.addEventListener("message",P),()=>C.close()},[Xa]),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){Bo()?.focusSession(de.targetPeerId,de.sessionId)&&P.ports[0]?.postMessage({type:"termdock:focus-session-ack"});return}P.ports[0]?.postMessage({type:"termdock:focus-session-ack"}),Xa(de.sessionId)}else de?.type==="termdock:push-subscription-changed"?dd(!0):de?.type};return navigator.serviceWorker.addEventListener("message",C),()=>navigator.serviceWorker.removeEventListener("message",C)},[Xa]),b.useEffect(()=>{const C=P=>{const de=P.detail;typeof de=="string"&&Xa(de)};return window.addEventListener("termdock:focus-session",C),()=>window.removeEventListener("termdock:focus-session",C)},[Xa]),b.useEffect(()=>{const C=()=>{const P=iA(Sc()?.targetPeerId);P&&Xa(P)};return C(),window.addEventListener("termdock:workspace-session",C),()=>window.removeEventListener("termdock:workspace-session",C)},[Xa]),b.useEffect(()=>{const C=Qe.current;if(!C)return;const P=gt.find(de=>de.id===C||sr.get(de.id)?.terminalSessionId===C);P?(Qe.current=null,ze.current&&_a("info","PWA_NOTIFICATION_CLICK app-pending-dispatch",{traceId:ze.current,requestedSessionId:C,targetSessionId:P.id,activeSessionId:yt}),window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:P.id}))):ze.current&&_a("info","PWA_NOTIFICATION_CLICK app-pending-unmatched",{traceId:ze.current,requestedSessionId:C,activeSessionId:yt,sessions:gt.map(de=>({id:de.id,terminalSessionId:sr.get(de.id)?.terminalSessionId??null}))})},[yt,gt,sr]);const xa=k.useMemo(()=>{const C=[];for(const P of gt){const de=sr.get(P.id);(de?.agentStatus==="waiting"||de?.agentNeedsReview)&&C.push(P.id)}return C},[gt,sr]),Ql=b.useCallback(()=>{if(xa.length===0)return;yt&&Yr.getState().clearAgentNeedsReview(yt);const C=yt?gt.findIndex(de=>de.id===yt):-1,P=xa.find(de=>gt.findIndex(tt=>tt.id===de)>C)??xa[0];P&&window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:P}))},[xa,gt,yt]),eu=b.useCallback(()=>{if(xa.length===0)return;yt&&Yr.getState().clearAgentNeedsReview(yt);const C=yt?gt.findIndex(de=>de.id===yt):gt.length,P=[...xa].reverse().find(de=>gt.findIndex(tt=>tt.id===de)<C)??xa[xa.length-1];P&&window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:P}))},[xa,gt,yt]);b.useEffect(()=>{const C=P=>{!P.altKey||!P.shiftKey||P.metaKey||P.ctrlKey||P.key!=="ArrowUp"&&P.key!=="ArrowDown"||(P.preventDefault(),P.key==="ArrowUp"?eu():Ql())};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[Ql,eu]);const ip=b.useCallback(async C=>{const de=Yr.getState().sessions.get(C)?.cwd;if(de)try{await navigator.clipboard?.writeText(de),Wn(de),window.setTimeout(()=>{Wn(tt=>tt===de?null:tt)},1400)}catch{}},[]),ap=b.useCallback(C=>{bt(C.sessions),pr(C.activeSessionId),dt(C.splitWorkspaces),Yr.getState().setActiveSessionId(C.activeSessionId)},[]),op=b.useCallback(()=>{Cr(!0)},[]),lp=b.useCallback(()=>{Cr(!0),window.requestAnimationFrame(()=>{window.dispatchEvent(new Event("termdock:initial-viewport-presented"))})},[]);b.useEffect(()=>{if(!N||!yt)return;gt.find(P=>P.id===N||sr.get(P.id)?.terminalSessionId===N)?.id===yt&&$(null)},[yt,N,gt,sr]);const rd=b.useRef(!1),[tu,F0]=b.useState(!1),Ma=b.useCallback(C=>{const P=!C?.onResult;if(P&&rd.current)return;P&&(rd.current=!0,F0(!0));const de=C?.mode??ln,tt=de==="tmux"&&(C?.tmuxSessionName?.trim()||pa.trim())||void 0,Tt=C?.cwd||(yt?Yr.getState().sessions.get(yt)?.cwd:void 0);window.dispatchEvent(new CustomEvent("new-terminal-session",{detail:{mode:de,tmuxSessionName:tt,cwd:Tt,command:C?.command,shouldActivate:C?.shouldActivate,onResult:C?.onResult??(Yt=>{rd.current=!1,F0(!1),Yt.ok||Vr({tone:"error",message:e(Um(Yt.error))})})}}))},[ln,pa,yt,e]),Vo=b.useCallback(async()=>{Fr(!0);try{const C=await Bm();if(Kr(C),!C.available){Mn([]);return}const P=await Qm();Mn(P)}catch{Kr({available:!1,version:null,reason:"tmux integration is unavailable with the current server build."}),Mn([])}finally{Fr(!1)}},[]),mc=b.useCallback(async C=>{const{cleanedSessions:P}=await yy(C);for(const de of P)window.dispatchEvent(new CustomEvent("close-terminal-session-by-backend",{detail:de}));await Vo()},[Vo]),ru=b.useCallback(async C=>{fn(C),Ue(null);try{await mc(C),Or(null)}catch(P){Ue(P instanceof Error?P.message:"Failed to kill tmux session")}finally{fn(null)}},[mc]);b.useEffect(()=>{if(!Et)return;if(Br.find(de=>de.name===Et&&(de.connected||de.boundFrontendSessionId))){kt(null);return}const P=setTimeout(()=>kt(null),1e4);return()=>clearTimeout(P)},[Et,Br]);const gc=b.useCallback(C=>{window.dispatchEvent(new CustomEvent("close-terminal-session",{detail:C}))},[]),nu=b.useCallback(C=>{const P=C??yt;P&&window.dispatchEvent(new CustomEvent("open-terminal-split-chooser",{detail:P}))},[yt]),nd=b.useCallback((C,P)=>{window.dispatchEvent(new CustomEvent("set-terminal-split-direction",{detail:{sessionId:C,layout:P}}))},[]),$0=b.useCallback((C,P)=>{window.dispatchEvent(new CustomEvent("reorder-terminal-split-workspace",{detail:{workspaceId:C,sessionIds:P}}))},[]),U0=b.useCallback((C,P)=>{window.dispatchEvent(new CustomEvent("rename-terminal-split-workspace",{detail:{workspaceId:C,name:P}}))},[]),z0=b.useCallback((C,P)=>{window.dispatchEvent(new CustomEvent("combine-terminal-split-sessions",{detail:{primaryId:C,secondaryId:P}}))},[]),Pl=b.useCallback((C,P,de)=>{const tt=gt.find(Yt=>Yt.id===C);if(!tt)return;const Tt=sr.get(C);if(de?.skipConfirmation||!B5({mode:tt.mode,activeProgram:Tt?.activeProgram??null,promptState:Tt?.promptState??null,shellNames:Ca})){gc({sessionId:C,source:"sidebar",closeMode:tt.mode==="tmux"?"destroy":"auto"});return}Rt(P?{x:P.clientX,y:P.clientY}:null),qe(C),Ue(null)},[gt,sr,gc]);b.useEffect(()=>{if(!Be)return;const C=P=>{const de=P.detail;de==="new-session"?Ma():de==="close-session"?yt&&Pl(yt):de==="previous-session"||de==="next-session"?window.dispatchEvent(new CustomEvent("cycle-terminal-session",{detail:{direction:de==="next-session"?"next":"prev"}})):de==="toggle-left-sidebar"?is():de==="toggle-right-sidebar"?gi():de==="previous-attention"?eu():de==="next-attention"&&Ql()};return window.addEventListener("termdock:native-command",C),()=>window.removeEventListener("termdock:native-command",C)},[yt,Be,Ma,Pl,is,gi,Ql,eu]);const Ja=k.useMemo(()=>gt.find(C=>C.id===ct)??null,[gt,ct]),sd=b.useCallback(()=>{Ja&&(gc({sessionId:Ja.id,source:"sidebar",closeMode:"destroy"}),qe(null),Rt(null))},[Ja,gc]);b.useEffect(()=>{if(!Ja)return;const C=P=>{if(P.key==="Escape"){P.preventDefault(),P.stopImmediatePropagation(),qe(null),Rt(null),Ue(null);return}P.key!=="Enter"||P.isComposing||P.keyCode===229||P.altKey||P.ctrlKey||P.metaKey||P.shiftKey||(P.preventDefault(),P.stopImmediatePropagation(),P.repeat||sd())};return window.addEventListener("keydown",C,!0),()=>window.removeEventListener("keydown",C,!0)},[Ja,sd]);const H0=k.useMemo(()=>{if(!Ja)return"";const C=sr.get(Ja.id);return il(Ja,C?.activeProgram??null,C?.cwd??null,Ca,C?.shellTitle??null,C?.promptState??null).primary},[Ja,sr]);b.useEffect(()=>{if(!et)return;let C=!1,P=!1;const de=async()=>{if(!P)try{const Tt=await Bm();if(C||Kr(Tt),!Tt.available){C||Mn([]);return}const Yt=await Qm();C||Mn(Yt)}catch{P=!0,C||(Kr({available:!1,version:null,reason:"tmux integration is unavailable with the current server build."}),Mn([]))}};de();const tt=setInterval(()=>{de()},4e3);return()=>{C=!0,clearInterval(tt)}},[et]);const xc=Mi??ln,Ol=xc==="shell",su=xc==="tmux"&&Sr.available,xl=k.useMemo(()=>$y(Br.map(C=>({...C,id:C.name})),C=>C.cwd??null,e("sidebar.ungrouped")),[Br,e]),id=k.useMemo(()=>Br.filter(C=>C.recoveryCandidate===!0&&!C.connected&&!C.boundFrontendSessionId).sort((C,P)=>(P.lastActiveAt??P.createdAt??0)-(C.lastActiveAt??C.createdAt??0)),[Br]);b.useEffect(()=>{!Ir&&!(ht&&ir)||Vo()},[Ir,ht,ir,gt.length,Vo]);const bc=(C,P,de,tt=!1)=>{const Tt=C.id===yt,Yt=C.id===tr,jr=sr.get(C.id),{primary:vn,secondary:En}=il(C,jr?.activeProgram??null,jr?.cwd??null,Ca,jr?.shellTitle??null,jr?.promptState??null),In=Yu(jr?.cwd??null),wi=P?En??(In&&In!==vn?In:null):null,wn=jr?.gitStatus,Zi=`${jr?.cwd||C.name}${wn?`
|
|
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:()=>{Te()},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(XA,{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 h$({state:e,pending:t,onCheck:r,onConfirmRestart:n,desktopState:a,desktopPending:c=!1,desktopSnapshot:l,desktopActions:d,onCheckDesktop:p,onInstallDesktop:m}){const{t:x}=zr(),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",W=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(gn,{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(gn,{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?W: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 f$({quality:e}){const{locale:t}=zr(),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 p$({backendSessionId:e}){const{locale:t}=zr(),r=t==="zh",[n,a]=k.useState(null),[c,l]=k.useState(!1);k.useEffect(()=>{if(a(null),!c||!e)return;const y=()=>a(S9(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(f$,{quality:n})]})]})]})}const ry={"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 m$(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 g$({state:e,onDismiss:t}){const{t:r}=zr(),[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 W=window.setTimeout(()=>{d.current=!1,a(!1),l(!0)},45e3);return()=>window.clearTimeout(W)},[n]);const m=async()=>{if(!d.current){d.current=!0,l(!1),a(!0);try{await C9()}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(ry[x.event]??"settings.serverHealthUnknownEvent"):"",R=x?.causeEvent?r(ry[x.causeEvent]??"settings.serverHealthUnknownEvent"):"",B=x?[new Date(x.at).toLocaleString(),x.uptimeMs!==null?r("settings.serverHealthUptime",{duration:m$(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(xS,{size:15}):s.jsx(yS,{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 x$=()=>()=>{},b$=()=>1/0;function y$(){const{t:e}=zr(),t=b.useId(),r=Bo(),n=b.useSyncExternalStore(r?.subscribe??x$,r?.retentionLimit??b$);if(!r)return null;const a=_9+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 R1="mobile-session-destroy";function v$(e,t){return t&&e.type==="session"&&e.destination?.droppableId===R1}const Sa="termdock-program-rules-cache",Dh="termdock-toolbar-presets-cache",Hd="termdock-settings-cache",ny="termdock-color-theme",sy="termdock:right-sidebar:file-preview-open-by-session:v2",Wd="termdock:running-session-button-enabled:v1",Gd="termdock:attention-button-enabled:v1",w$=60,iy=320,ay=420,jo=8;function oy(e,t,r){return Math.min(Math.max(e,t),r)}function ly(e){if(typeof window>"u")return{left:jo,top:jo};const t=window.innerWidth/2,r=Math.min(64,window.innerHeight/4),n=e?.x??t,a=e?.y??r,c=Math.max(jo,window.innerWidth-iy-jo),l=Math.max(jo,window.innerHeight-ay-jo);return{left:oy(n+jo,jo,c),top:oy(a+jo,jo,l),width:iy,maxHeight:`min(${ay}px, calc(100vh - ${jo*2}px))`}}function A$(e){return e==="dark"||e==="light"}function T$(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 Dm(e){const t=Object.entries(e).filter(([r,n])=>r&&Number.isFinite(n.updatedAt)).sort(([,r],[,n])=>n.updatedAt-r.updatedAt).slice(0,w$);return Object.fromEntries(t)}function S$(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 C$(e){return typeof e=="object"&&e!==null&&typeof e.version=="number"&&Array.isArray(e.presets)}function _$(e,t){const r=b0(),n=new Set(pE()),a=Array.isArray(e)?e:[],c=Eu(a),l=t<Zd;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 k$(e){return typeof e=="object"&&e!==null&&typeof e.preventSleep=="boolean"&&typeof e.networkAvailable=="boolean"}const L$={name:"",source:"auto",hostname:"",fallbackHostname:"",url:"",fallbackUrl:"",onboardingUrl:null,status:"disabled",reason:null,httpsEnabled:!1,caAvailable:!1,lanAddresses:[],interfaces:[]},rp="__termdockOverlay",np="__termdockBaseAnchor",sp="__termdockBaseGuard",I$=3,cy=250,E$="termdock-notification-target-v1",uy="/__termdock-notification-target",dy=3e4;function N$(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 Au(e){if(!e||typeof e!="object")return null;const t=e[rp];return N$(t)?t:null}function Ig(e){return e&&typeof e=="object"?{...e}:{}}function X6(e){const t=Ig(e);return delete t[rp],t}function R$(e){const t=X6(e);return delete t[sp],{...t,[np]:!0}}function M$(){typeof window>"u"||window.history.pushState({...X6(window.history.state),[np]:!0,[sp]:!0},"",window.location.href)}function J6(){for(let e=0;e<I$;e+=1)M$()}function Bh(){typeof window>"u"||(window.history.replaceState(R$(window.history.state),"",window.location.href),J6())}function Vd(e){typeof window>"u"||window.history.pushState({...Ig(window.history.state),[np]:!0,[rp]:e,[sp]:!1},"",window.location.href)}function j$(e){typeof window>"u"||window.history.replaceState({...Ig(window.history.state),[np]:!0,[rp]:e,[sp]:!1},"",window.location.href)}const e4=["bash","zsh","fish","sh","dash","ksh","tcsh","csh","nu"];let Ca=new Set(e4);function hy(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 D$(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 fy(e,t){return s.jsx(PP,{sessionMode:e,state:t})}function B$(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 Q$=k.lazy(()=>Oc(()=>import("./CollaborationMainWorkspace-P_jXjsT-.js"),__vite__mapDeps([18,1,2,3,4,5,8,9,15,13])));function P$(){const{t:e,locale:t,setLocale:r}=zr(),n="env(safe-area-inset-top, 0px)",a="env(safe-area-inset-bottom, 0px)";k9();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(ny,A$)??"dark"),x=k.useRef(Tc(Hd,k$)).current,[y,w]=k.useState(x?.preventSleep??!1),[v,S]=k.useState(x?.networkAvailable??!0),[L,E]=k.useState(L9),[R,B]=k.useState(I9),[W,F]=k.useState(E9),[U,V]=k.useState(N9),[Z,ce]=k.useState(Ap),[xe,pe]=k.useState(x?.localAccess??L$),[te,ke]=k.useState(x?.localAccess?.name??""),[$e,Y]=k.useState(!1),[Ae,lt]=k.useState(null),[Se,ye]=k.useState(null),[_e,je]=k.useState(null),[re,Oe]=k.useState(!1),[Ce,Ee]=k.useState(null),Be=k.useMemo(()=>xo(),[]),Ne=!!(Be?.desktopUpdateState&&Be.checkDesktopUpdate&&Be.installDesktopUpdate),[le,He]=k.useState(null),[rt,mt]=k.useState(null),[ue,Ye]=k.useState(!1),[st,Ie]=k.useState(null),[We,Te]=k.useState(!1),[H,oe]=k.useState(()=>Dm(Tc(sy,T$)??{})),[be,Ze]=k.useState(0),[Je,St]=k.useState(!1),[Vt,jt]=k.useState(0),[vt,Zt]=k.useState(!1),[Pt,Xt]=k.useState(0),[zt,Lt]=k.useState(!1),[me,Ge]=k.useState(0),pt=k.useRef(null),[q,at]=k.useState({}),{terminalSettings:qt,updateTerminalSettings:Ve}=WB(),De=qt.fontSize,er=qt.rendererMode,[et,Ct]=k.useState(!1),Nt=k.useRef(R9()).current,[gt,bt]=b.useState(()=>Nt.sessions.map(C=>({id:C.sessionId,name:C.name,customName:C.customName,mode:C.mode,tmuxSessionName:C.tmuxSessionName}))),It=la(C=>C.groupId);k.useEffect(()=>{const C=()=>la.getState().terminal();return window.addEventListener("switch-terminal-session",C),()=>window.removeEventListener("switch-terminal-session",C)},[]);const[yt,pr]=k.useState(Nt.activeSessionId),[nr,Cr]=k.useState(!1);k.useEffect(()=>{nr&&M9({rendered:!0})},[nr]);const[cn,Lr]=k.useState(null),[ge,Vr]=k.useState(null),[it,dt]=k.useState([]),[sr,xn]=b.useState(()=>{const C=Yr.getState();return Nt.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)}),Nu("session-chrome-hydrated"),hy(Yr.getState().sessions)});b.useEffect(()=>{!Be||!et||Promise.all([Be.snapshot(),Be.desktopUpdateState?.()??Promise.resolve(null)]).then(([C,P])=>{He(C),mt(P)}).catch(C=>Ie(C instanceof Error?C.message:String(C)))},[Be,et]),b.useEffect(()=>{Be?.onDesktopUpdateState&&Be.onDesktopUpdateState(mt)},[Be]),b.useEffect(()=>Yr.subscribe(C=>{const P=hy(C.sessions);xn(de=>D$(de,P)?de:P)}),[]);const an=b.useCallback(async(C,P)=>{Vr(null),Lr({sessionId:C,status:"submitting",error:null});try{await j9(P),Lr(de=>de?.sessionId===C?{...de,status:"waiting",error:null}:de)}catch(de){const Tt=(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");Lr(Yt=>Yt?.sessionId===C?{...Yt,error:Tt}:Yt),Vr({tone:"error",message:Tt})}},[e]);b.useEffect(()=>{if(!cn||cn.status!=="waiting")return;const C=sr.get(cn.sessionId);if(!C||C.agentResumeRecovered||C.agentStatus===null&&!C.agent)return;const P=C.agent?.displayName??"Agent";Lr(null),Vr({tone:"success",message:e("tab.resumeAgentSuccess",{agent:P})})},[cn,sr,e]),b.useEffect(()=>{if(!cn||cn.status!=="waiting"||cn.error)return;const C=cn.sessionId,P=window.setTimeout(()=>{const de=e("tab.resumeAgentTimeout");Lr(tt=>tt?.sessionId===C&&tt.status==="waiting"?{...tt,error:de}:tt),Vr({tone:"error",message:de})},15e3);return()=>window.clearTimeout(P)},[cn,e]),b.useEffect(()=>{if(ge?.tone!=="success")return;const C=window.setTimeout(()=>Vr(null),3200);return()=>window.clearTimeout(C)},[ge]),b.useEffect(()=>{let C=!1;D9().then(de=>{C||je(de)}).catch(()=>{}),B9().then(de=>{C||Ee(de)}).catch(()=>{});const P=l2(de=>{C||(de.type==="update-state"?je(de.state):de.type==="server-health"&&Ee(de.state))});return()=>{C=!0,P()}},[]);const Me=b.useCallback(async()=>{try{Ee(await Q9())}catch(C){window.alert(C instanceof Error?C.message:String(C))}},[]),nt=b.useCallback(async()=>{const C=_e?.latestVersion;if(!(!C||re)&&window.confirm(e("sidebar.updateRestartConfirm",{version:C}))){Oe(!0);try{je(await P9())}catch(P){window.alert(P instanceof Error?P.message:String(P))}finally{Oe(!1)}}},[_e?.latestVersion,e,re]),wt=b.useCallback(async()=>{if(!re){Oe(!0);try{je(await O9())}catch(C){window.alert(C instanceof Error?C.message:String(C))}finally{Oe(!1)}}},[re]),Rr=b.useCallback(async()=>{if(!(!Be?.checkDesktopUpdate||ue)){Ye(!0);try{mt(await Be.checkDesktopUpdate())}catch(C){Ie(C instanceof Error?C.message:String(C))}finally{Ye(!1)}}},[Be,ue]),rn=b.useCallback(async()=>{if(!(!Be?.installDesktopUpdate||ue||rt?.status!=="ready")&&window.confirm(e("settings.desktopUpdateRestartConfirm"))){Ye(!0);try{mt(await Be.installDesktopUpdate())}catch(C){Ie(C instanceof Error?C.message:String(C))}finally{Ye(!1)}}},[Be,ue,rt?.status,e]);b.useEffect(()=>{document.documentElement.dataset.theme=p,F9(p),On(ny,p)},[p]),b.useEffect(()=>{On(sy,Dm(H))},[H]);const Ir=Gt(C=>C.leftOpen),ne=Gt(C=>C.rightOpen),ht=Gt(C=>C.leftPinned),Ht=Gt(C=>C.leftSidebarWidth),Ot=Gt(C=>C.rightPinned),Tr=Gt(C=>C.rightSidebarWidth),mr=Gt(C=>C.rootPath),Hr=Gt(C=>C.contextKey),_n=Gt(C=>C.selectedFilePath),dr=Gt(C=>C.groupByFolder),bn=uf(C=>C.collaborationGroups),hn=Gt(C=>C.collapsedGroups),Tn=Gt(C=>C.toggleGroupCollapsed),[ir,pn]=b.useState(()=>typeof window>"u"?!0:window.matchMedia("(min-width: 1024px)").matches),[Pr,qr]=b.useState(()=>typeof window>"u"?1024:window.innerWidth),[Wr,fs]=b.useState(()=>typeof window>"u"?!1:window.matchMedia("(orientation: landscape)").matches),[Br,Mn]=b.useState([]),[Sr,Kr]=b.useState({available:!0,version:null,reason:null}),[nn,Fr]=b.useState(!1),[ks,Or]=b.useState(null),[Xr,fn]=b.useState(null),[K,Ue]=b.useState(null),[Et,kt]=b.useState(null),[tr,Qr]=b.useState(null),[cr,Sn]=b.useState(null),[Ls,Zn]=b.useState(null),[,sn]=b.useState(0),[on,_r]=b.useState(null),[$r,Wn]=b.useState(null),[Gn,un]=b.useState(null),[Kn,kr]=b.useState(!1),[Er,gr]=b.useState(()=>Tc(Wd,C=>typeof C=="boolean")??!1),rs=b.useCallback(async C=>{const P=Er;gr(C),On(Wd,C);try{const de=await ka({runningSessionButtonEnabled:C});gr(de.runningSessionButtonEnabled),On(Wd,de.runningSessionButtonEnabled)}catch{gr(P),On(Wd,P)}},[Er]),[$n,kn]=b.useState(()=>Tc(Gd,C=>typeof C=="boolean")??!0),Ln=b.useCallback(async C=>{const P=$n;kn(C),On(Gd,C);try{const de=await ka({attentionButtonEnabled:C});kn(de.attentionButtonEnabled),On(Gd,de.attentionButtonEnabled)}catch{kn(P),On(Gd,P)}},[$n]),[ps,G]=b.useState(null),Le=b.useCallback(C=>{G(C)},[]),Ke=b.useRef(!1),[ct,qe]=b.useState(null),[At,Rt]=b.useState(null),Bt=k.useRef(null),ot=k.useRef(!1),Ft=k.useRef(null),hr=k.useRef(!1),Kt=b.useCallback(()=>{Sn(null),Zn(null)},[]),z=k.useRef(typeof window>"u"?null:new URLSearchParams(window.location.search).get("session")),[N,$]=k.useState(z.current),[ee,ie]=k.useState(!0),Qe=k.useRef(z.current),ze=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=()=>{pn(C.matches),qr(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=()=>fs(C.matches);return P(),C.addEventListener("change",P),()=>C.removeEventListener("change",P)},[]);const xt=k.useMemo(()=>yt?it.find(C=>C.sessionIds.includes(yt))??null:null,[yt,it]),_t=xt?.id??null,Mr=xt?.sessionIds[0]??yt,Dt=k.useRef([]);k.useLayoutEffect(()=>{const C=Dt.current;if(Dt.current=it,C.length===0)return;const P=new Set(it.flatMap(de=>de.sessionIds));for(const de of C){const tt=de.sessionIds.filter(Tt=>!P.has(Tt)).map(Tt=>({sessionId:Tt,rootPath:Yr.getState().sessions.get(Tt)?.cwd??null}));tt.length>0&&Gt.getState().inheritRightSidebarStateFromSplitWorkspace(de.id,tt)}},[it]),k.useLayoutEffect(()=>((()=>{const P=Mr?Yr.getState().sessions.get(Mr)?.cwd??null:null;Gt.getState().setRootPath(P,Mr,_t)})(),Yr.subscribe((P,de)=>{const tt=Mr?P.sessions.get(Mr)?.cwd??null:null,Tt=Mr?de.sessions.get(Mr)?.cwd??null:null;tt!==Tt&&Gt.getState().setRootPath(tt,Mr,_t)})),[_t,Mr]);const Gr=k.useRef(Vy(window.location.search)??JS(Sc()?.targetPeerId)),[dn,jn]=k.useState("");k.useEffect(()=>{const C=Gr.current;if(!C)return;if(C.peerId&&C.peerId!==Sc()?.targetPeerId){const tt=$9().find(Tt=>Tt.targetPeerId===C.peerId);if(tt&&Bo()){try{XS(C)}catch{jn(t==="zh"?"无法在此浏览器打开架构链接。":"Cannot open this architecture link in this browser.");return}if(U9(tt)){Gr.current=null;const Tt=new URL(window.location.href);Tt.searchParams.delete("architecture"),window.history.replaceState(window.history.state,"",Tt);return}}jn(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}jn("");try{sessionStorage.setItem(`termdock.architecture.selection:${C.root}`,C.file)}catch{}const P=Gt.getState();P.setRootPath(C.root,Mr,_t),P.setRightTab("architecture"),P.openRight();const de=new URL(window.location.href);de.searchParams.delete("architecture"),window.history.replaceState(window.history.state,"",de),Mr&&(Gr.current=null)},[Mr,_t,t]);const ns=ir||Wr,Un=Pr*.95,fr=ns?Math.min(Math.max(Pr*.22,280),340):Math.min(Pr*.86,380),Mt=yt&&mr?`${yt}\0${mr}`:"",Dn=!!(Mt&&_n&&H[Mt]),Vn=b.useCallback(C=>{Mt&&(C&&!Gt.getState().selectedFilePath||oe(P=>{if(!!P[Mt]===C)return P;if(C)return Dm({...P,[Mt]:{updatedAt:Date.now()}});const tt={...P};return delete tt[Mt],tt}))},[Mt]);b.useEffect(()=>{KB(Mt,Hr,_n)&&oe(C=>{if(!C[Mt])return C;const P={...C};return delete P[Mt],P})},[Mt,Hr,_n]);const Bn=zt?"markdown-image-lightbox":vt?"markdown-outline":Je?"right-sidebar-repo-picker":ne&&Dn?"right-sidebar-file-preview":et?"settings":ne&&!(Ot&&ir)?"right-sidebar":Ir&&!(ht&&ir)?"left-sidebar":null,ss=k.useRef(Bn),$i=k.useRef(Bn),ua=k.useRef(!1),bs=k.useRef(!1),Wa=b.useCallback(()=>{if(typeof window>"u")return;const C=window.matchMedia("(hover: hover) and (pointer: fine)").matches;!ir||!C||navigator.maxTouchPoints>0||window.setTimeout(()=>{window.dispatchEvent(new CustomEvent("focus-active-terminal-session"))},0)},[ir]),wo=b.useCallback(C=>{if(C==="markdown-image-lightbox"){Lt(!1),Ge(P=>P+1);return}if(C==="markdown-outline"){Zt(!1),Xt(P=>P+1);return}if(C==="right-sidebar-file-preview"){Zt(!1),Xt(P=>P+1),Vn(!1),Ze(P=>P+1);return}if(C==="right-sidebar-repo-picker"){St(!1),jt(P=>P+1);return}if(C==="settings"){Ct(!1),ws(!1),ti(!1),ls(!1);return}if(C==="left-sidebar"){Gt.getState().closeLeft();return}Zt(!1),Xt(P=>P+1),St(!1),jt(P=>P+1),Lt(!1),Ge(P=>P+1),Gt.getState().closeRight()},[Vn]),zn=b.useCallback(C=>{if(!c&&typeof window<"u"&&ss.current===C&&Au(window.history.state)===C){window.history.back();return}wo(C)},[wo,c]),da=b.useCallback(()=>{Ct(!1);const C=Gt.getState();C.closeRight(),C.openLeft()},[]),ms=b.useCallback(()=>{Ct(!1);const C=Gt.getState();C.closeLeft(),C.openRight()},[]),La=b.useCallback(()=>{Ct(!1);const C=Gt.getState();C.closeLeft(),C.openRight(),C.setRightTab("files"),C.openRightSearch()},[]),is=b.useCallback(()=>{const C=Gt.getState();if(C.leftPinned){C.setLeftPinned(!1),C.closeLeft();return}if(Ir){zn("left-sidebar");return}da()},[da,zn,Ir]),Ga=b.useCallback(()=>{const C=Gt.getState();C.leftPinned?(C.setLeftPinned(!1),C.openLeft()):(C.setLeftPinned(!0),C.openLeft())},[]),Ks=b.useCallback(()=>{const C=Gt.getState();C.setLeftPinned(!1),C.closeLeft()},[]),Xs=b.useCallback(()=>{const C=Gt.getState();C.rightPinned?(C.setRightPinned(!1),C.openRight()):(C.setRightPinned(!0),C.openRight())},[]),Hs=b.useCallback(()=>{const C=Gt.getState();C.setRightPinned(!1),C.closeRight()},[]),Va=b.useRef(0),Is=b.useRef(0),ha=b.useRef(null),dl=b.useCallback(C=>{C.preventDefault(),Va.current=C.clientX,Is.current=Gt.getState().leftSidebarWidth;const P=tt=>{ha.current===null&&(ha.current=requestAnimationFrame(()=>{ha.current=null;const Tt=tt.clientX-Va.current;Gt.getState().setLeftSidebarWidth(Is.current+Tt)}))},de=()=>{window.removeEventListener("mousemove",P),window.removeEventListener("mouseup",de),ha.current!==null&&(cancelAnimationFrame(ha.current),ha.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)},[]),qa=b.useRef(0),as=b.useRef(0),Rs=b.useRef(null),Ui=b.useCallback(C=>{C.preventDefault(),qa.current=C.clientX;const P=Gt.getState(),de=P.leftPinned?P.leftSidebarWidth:0;as.current=Ph(P.rightSidebarWidth,window.innerWidth,de);const tt=Yt=>{Rs.current===null&&(Rs.current=requestAnimationFrame(()=>{Rs.current=null;const jr=qa.current-Yt.clientX,vn=Gt.getState(),En=vn.leftPinned?vn.leftSidebarWidth:0;vn.setRightSidebarWidth(Ph(as.current+jr,window.innerWidth,En))}))},Tt=()=>{window.removeEventListener("mousemove",tt),window.removeEventListener("mouseup",Tt),Rs.current!==null&&(cancelAnimationFrame(Rs.current),Rs.current=null),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",window.addEventListener("mousemove",tt),window.addEventListener("mouseup",Tt)},[]),gi=b.useCallback(()=>{const C=Gt.getState();if(C.rightPinned){C.setRightPinned(!1),C.closeRight();return}if(ne){zn("right-sidebar");return}ms()},[ms,zn,ne]),xi=b.useCallback(()=>{!Dn&&!c&&typeof window<"u"&&ss.current==="right-sidebar"&&Au(window.history.state)==="right-sidebar"&&(Vd("right-sidebar-file-preview"),$i.current="right-sidebar-file-preview"),Vn(!0)},[Dn,c,Vn]),hl=b.useCallback(()=>{zn("right-sidebar-file-preview")},[zn]),Js=b.useCallback(()=>{!Je&&!c&&typeof window<"u"&&ss.current==="right-sidebar"&&Au(window.history.state)==="right-sidebar"&&(Vd("right-sidebar-repo-picker"),$i.current="right-sidebar-repo-picker"),St(!0)},[Je,c]),Uo=b.useCallback(()=>{zn("right-sidebar-repo-picker")},[zn]),fa=b.useCallback(()=>{!vt&&!c&&typeof window<"u"&&ss.current&&Au(window.history.state)===ss.current&&(Vd("markdown-outline"),$i.current="markdown-outline"),Zt(!0)},[vt,c]),fl=b.useCallback(()=>{zn("markdown-outline")},[zn]),pl=b.useCallback(()=>{!c&&typeof window<"u"&&ss.current&&Au(window.history.state)===ss.current&&(Vd("markdown-image-lightbox"),$i.current="markdown-image-lightbox"),Lt(!0)},[c]),os=b.useCallback(()=>{zn("markdown-image-lightbox")},[zn]),Ms=b.useCallback(()=>{!c&&typeof window<"u"&&ss.current&&Au(window.history.state)===ss.current&&(j$("settings"),$i.current="settings"),Gt.getState().closeAll(),Ct(!0)},[c]),Ni=b.useCallback(()=>{zn("settings")},[zn]);b.useEffect(()=>{if(!Be)return;const C=()=>Ms();return window.addEventListener("termdock:open-settings",C),()=>window.removeEventListener("termdock:open-settings",C)},[Be,Ms]);const zo=b.useCallback(()=>{Te(!0),pt.current!==null&&(window.clearTimeout(pt.current),pt.current=null)},[]),jl=b.useCallback(()=>{pt.current!==null&&(window.clearTimeout(pt.current),pt.current=null),Te(!1),bs.current=!0,Bh(),bs.current},[]);b.useEffect(()=>()=>{pt.current!==null&&window.clearTimeout(pt.current)},[]),b.useEffect(()=>{c||Bh()},[c]),b.useEffect(()=>{if(typeof window>"u"||c)return;let C=null;const P=()=>{C!==null&&(window.clearTimeout(C),C=null)},de=vn=>{if(ss.current,bs.current,ss.current){ss.current;return}!vn?.force&&bs.current||(vn?.userActivated&&(bs.current=!0),Bh(),bs.current,void 0)},tt=()=>{P(),C=window.setTimeout(()=>{C=null,de({force:!0})},cy)},Tt=()=>{de({userActivated:!0})},Yt=()=>{tt()},jr=()=>{document.visibilityState==="visible"&&tt()};return window.addEventListener("pointerdown",Tt,{capture:!0,passive:!0}),window.addEventListener("touchstart",Tt,{capture:!0,passive:!0}),window.addEventListener("keydown",Tt,{capture:!0}),window.addEventListener("pageshow",Yt),document.addEventListener("visibilitychange",jr),()=>{P(),window.removeEventListener("pointerdown",Tt,{capture:!0}),window.removeEventListener("touchstart",Tt,{capture:!0}),window.removeEventListener("keydown",Tt,{capture:!0}),window.removeEventListener("pageshow",Yt),document.removeEventListener("visibilitychange",jr)}},[c]),b.useEffect(()=>{ss.current=Bn},[Bn]),b.useEffect(()=>{if(typeof window>"u"||Bn||c)return;const C=window.setTimeout(()=>{ss.current?(ss.current,void 0):Bh()},cy);return()=>window.clearTimeout(C)},[Bn,c]),b.useEffect(()=>{if(typeof window>"u"||c)return;const C=$i.current;ua.current,Bn&&Bn!==C&&!ua.current&&Vd(Bn),!Bn&&C&&Wa(),$i.current=Bn,!Bn&&ua.current&&window.setTimeout(()=>{ua.current=!1},0)},[Bn,c,Wa]),b.useEffect(()=>{if(typeof window>"u"||c)return;const C=()=>{const P=ss.current;if(bs.current,!P){bs.current=!1,bs.current,zo(),J6();return}ua.current=!0,wo(P)};return window.addEventListener("popstate",C),()=>window.removeEventListener("popstate",C)},[wo,zo,c]),b.useEffect(()=>{const C=P=>{const de=P.metaKey||P.ctrlKey;if(de&&P.key==="b"&&!P.shiftKey&&(P.preventDefault(),is()),de&&P.shiftKey&&P.key==="E"&&(P.preventDefault(),gi()),de&&P.shiftKey&&P.key==="P"&&(P.preventDefault(),La()),de&&!P.shiftKey&&P.altKey&&(P.key==="ArrowLeft"||P.key==="ArrowRight")){P.preventDefault();const tt=P.key==="ArrowRight"?"next":"prev";window.dispatchEvent(new CustomEvent("cycle-terminal-session",{detail:{direction:tt}}));return}if(de&&P.shiftKey&&!P.altKey&&(P.code==="BracketLeft"||P.code==="BracketRight")){P.preventDefault();const tt=P.code==="BracketRight"?"next":"prev";window.dispatchEvent(new CustomEvent("cycle-terminal-session",{detail:{direction:tt}}));return}};return document.addEventListener("keydown",C),()=>{document.removeEventListener("keydown",C)}},[is,gi,La]);const Es=b.useCallback(async()=>{Y(!0),lt(null);try{const C=await ka({localAccess:{name:te}});pe(C.localAccess),ke(C.localAccess.name),On(Hd,{preventSleep:C.preventSleep,networkAvailable:C.networkAvailable,localAccess:C.localAccess})}catch(C){lt(C instanceof Error?C.message:"Failed to save local access name")}finally{Y(!1)}},[te]),Ia=b.useCallback(async()=>{Y(!0),lt(null);try{const C=await ka({localAccess:{reset:!0}});pe(C.localAccess),ke(C.localAccess.name),On(Hd,{preventSleep:C.preventSleep,networkAvailable:C.networkAvailable,localAccess:C.localAccess})}catch(C){lt(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)}},[]),Xn=b.useCallback(C=>{const P=B$(gt,C);P.map(de=>de.id).join("\0")!==gt.map(de=>de.id).join("\0")&&(bt(P),window.dispatchEvent(new CustomEvent("reorder-terminal-session",{detail:{sessionIds:P.map(de=>de.id)}})))},[gt]),zi=b.useCallback(C=>{ir||C.type!=="session"||(Ke.current=!1,kr(!1),un(C.draggableId))},[ir]),Ri=b.useCallback(C=>{if(ir||C.type!=="session")return;const P=C.destination?.droppableId===R1;P!==Ke.current&&(Ke.current=P,kr(P),P&&navigator.vibrate?.(20))},[ir]),Hi=b.useCallback(C=>{const P=v$(C,!ir);if(Ke.current=!1,kr(!1),un(null),!P)return!1;const de=gt.find(Tt=>Tt.id===C.draggableId),tt=de?sr.get(de.id):null;return de&&B5({mode:de.mode,activeProgram:tt?.activeProgram??null,promptState:tt?.promptState??null,shellNames:Ca})?(Rt(null),qe(de.id),Ue(null)):de&&window.dispatchEvent(new CustomEvent("close-terminal-session",{detail:{sessionId:de.id,source:"other",closeMode:de.mode==="tmux"?"destroy":"auto"}})),!0},[ir,gt,sr]),{groups:gs,arranged:Ws}=k.useMemo(()=>lf(gt,C=>sr.get(C.id)?.cwd??null,dr,e("sidebar.ungrouped"),it,bn),[gt,sr,dr,e,it,bn]),Dl=b.useCallback(C=>{Hi(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}}))},[Hi,Ws]),Wi=b.useCallback((C,P)=>{const de=P.trim();de&&window.dispatchEvent(new CustomEvent("rename-terminal-session",{detail:{sessionId:C,name:de}}))},[]),Gi=b.useCallback(C=>{window.dispatchEvent(new CustomEvent("reset-terminal-session-name",{detail:{sessionId:C}}))},[]),{newSessionMode:ln,newSessionTmuxName:pa,userSelectedNewSessionMode:Vi,setNewSessionMode:Ea}=qB(),[Mi,ji]=b.useState(null),[ei,ws]=k.useState(!1),[Gs,Di]=k.useState(!1),[Na,ti]=k.useState(!1),[ys,Ya]=k.useState("idle"),Za=k.useRef(Tc(Dh,C$)).current,[As,Ka]=k.useState(()=>{const C=Za?.presets;if(C&&C.length>0){const P=Eu(C);if(P.length>0)return P}return b0()}),[Bl,Ho]=k.useState(!1),[Ao,ma]=k.useState("default"),Ra=k.useRef(typeof Za?.updatedAt=="number"?Za.updatedAt:null),Wo=k.useRef(!1),[ga,ls]=k.useState(!1),[Go,qi]=k.useState(!1),gl=k.useRef(Tc(Sa,S$)).current,[se,T]=k.useState(gl??[]),[j,Q]=k.useState(gl!==null),[O,fe]=k.useState(!1),we=!It&&!Bn&&!Gs&&!Na&&!ei&&!ga&&!Go&&!cr&&!ct&&!Mi,Pe=k.useCallback(C=>{const P=typeof C.version=="number"?C.version:0,de=_$(Array.isArray(C.presets)?C.presets:[],P);Ra.current=typeof C.updatedAt=="number"?C.updatedAt:null,Ka(tt=>z9(tt,de)?tt:(Wo.current=!0,de)),On(Dh,{version:Zd,presets:de,updatedAt:Ra.current??void 0})},[]);b.useEffect(()=>{const C=P=>{if(P.key!=="Escape"||P.defaultPrevented||P.isComposing||D1())return;if(Gs){P.preventDefault(),Di(!1);return}if(Na){P.preventDefault(),ti(!1);return}if(ei){P.preventDefault(),ws(!1);return}if(ga){P.preventDefault(),ls(!1);return}if(Go){P.preventDefault(),qi(!1);return}if(cr){P.preventDefault(),Kt();return}if(on){P.preventDefault(),Qr(null),_r(null);return}if(et){P.preventDefault(),Ni();return}if(ne&&!(Ot&&ir)){P.preventDefault(),zn("right-sidebar");return}Ir&&!(ht&&ir)&&(P.preventDefault(),zn("left-sidebar"))};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[Gs,Na,ei,ga,cr,Kt,et,ne,Ot,Ir,ht,ir,Ni,zn]),b.useEffect(()=>{Q(!0)},[]);const[Xe,ft]=k.useState({genericProgramNames:[],wrapperScriptNames:[],shellNames:e4}),[,Jt]=k.useState(!1),or=k.useCallback(()=>H9().then(C=>{ft(C),Ca=new Set(C.shellNames),Jt(!0)}).catch(()=>{}),[]);b.useEffect(()=>{or()},[or]),b.useEffect(()=>l2(C=>{if(C.type==="config-updated"){if(C.key==="toolbar-presets"){c2().then(P=>Pe(P)).catch(P=>{console.warn("[toolbar-presets] Failed to refresh after remote update:",P)});return}C.key==="program-detection"&&or()}}),[Pe,or]),b.useEffect(()=>{let C=!1;return(async()=>{try{const P=await c2();if(C)return;Pe(P)}catch(P){console.warn("[toolbar-presets] Failed to load from server:",P)}finally{C||Ho(!0)}})(),()=>{C=!0}},[Pe]),b.useEffect(()=>{if(Bl){if(Wo.current){Wo.current=!1;return}On(Dh,{version:Zd,presets:As,updatedAt:Ra.current??void 0}),W9({version:Zd,presets:As,baseUpdatedAt:Ra.current??void 0}).then(C=>{Ra.current=typeof C.updatedAt=="number"?C.updatedAt:null,On(Dh,{version:Zd,presets:As,updatedAt:Ra.current??void 0})}).catch(C=>{const P=C instanceof Error&&"current"in C?C.current:null;P&&typeof P=="object"&&Pe(P),console.warn("[toolbar-presets] Failed to save to server:",C)})}},[Pe,As,Bl]),b.useEffect(()=>{fc().then(C=>{w(P=>P===C.preventSleep?P:C.preventSleep),S(P=>P===C.networkAvailable?P:C.networkAvailable),pe(C.localAccess),ke(C.localAccess.name),gr(C.runningSessionButtonEnabled),On(Wd,C.runningSessionButtonEnabled),kn(C.attentionButtonEnabled),On(Gd,C.attentionButtonEnabled),On(Hd,{preventSleep:C.preventSleep,networkAvailable:C.networkAvailable,localAccess:C.localAccess})}).catch(()=>{})},[]),b.useEffect(()=>{if(!L)return;const C=Ap();ce(C),C!=="granted"&&(E(!1),eh(!1))},[L]),b.useEffect(()=>{if(!L)return;dd();const C=()=>{document.visibilityState==="visible"&&(dd(),sA())},P=window.setInterval(()=>{dd()},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 Ur=b.useCallback(async()=>{if(L){E(!1),eh(!1),G9(),ce(Ap());return}const C=await V9();if(ce(C),C!=="granted"){E(!1),eh(!1);return}E(!0),eh(!0),await dd(!0,!0),Ya("idle")},[L]),Jr=b.useCallback(async()=>{Ya("checking"),await xo()?.prepareNotificationTest?.();const C=await q9({title:"Termdock",body:e("settings.notificationsTestBody"),tag:"termdock-notification-test",requireHidden:!1,data:{url:"/"}});Ya(C?"delivered":"failed")},[e]),Qn=b.useCallback(C=>{B(C),Y9(C),Tp()},[]),vr=b.useCallback(C=>{F(C),Z9(C),Tp()},[]),yn=b.useCallback(C=>{V(C),K9(C),Tp()},[]);b.useEffect(()=>{As.some(C=>C.id===Ao)||ma(As[0]?.id??"default")},[Ao,As]),b.useEffect(()=>{if(!Sr.available&&ln==="tmux"){Ea("shell",{userInitiated:!1});return}Sr.available&&Vi!=="shell"&&ln!=="tmux"&&Ea("tmux",{userInitiated:!1})},[ln,Sr.available,Vi,Ea]),b.useEffect(()=>{ji(null)},[et,ln,Sr.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),at(C)},[]);const cs=b.useCallback(C=>{if(Hi(C)||!C.destination)return;if(C.type==="group"){if(C.source.index===C.destination.index)return;Xn(Uy(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(tt=>tt.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,Xn,Hi]),js=k.useMemo(()=>Ws.flatMap(C=>{const P=sr.get(C.id);if(P?.agentStatus!=="working")return[];const{primary:de,secondary:tt}=il(C,P?.activeProgram??null,P?.cwd??null,Ca,P?.shellTitle??null,P?.promptState??null);return[{id:C.id,label:de,detail:tt}]}),[Ws,sr]),pc=yt?Ws.findIndex(C=>C.id===yt):-1,Vs=Ws.length>0&&pc>=0?`${pc+1}/${Ws.length}`:`${Ws.length}`,Yi=k.useMemo(()=>{let C=0;for(const P of gt){const de=sr.get(P.id);(de?.agentStatus==="waiting"||de?.agentNeedsReview)&&(C+=1)}return{running:js.length,review:C}},[js.length,gt,sr]),To=k.useMemo(()=>Ws.flatMap(C=>{const P=sr.get(C.id);if(P?.agentStatus!=="waiting"&&!P?.agentNeedsReview)return[];const{primary:de}=il(C,P.activeProgram,P.cwd,Ca,P.shellTitle,P.promptState);return[{id:P.terminalSessionId??C.id,label:de,waiting:P.agentStatus==="waiting"}]}),[Ws,sr]);X9(Yi.running,Yi.review,To);const bi=yt?gt.find(C=>C.id===yt)??null:null,So=bi?sr.get(bi.id):void 0,Jc=!!(bi&&So?.agentResumeRecovered&&So.agentNativeSessionId&&So.terminalSessionId),yi=bi&&cn?.sessionId===bi.id?cn:null;k.useLayoutEffect(()=>{if(!ee)return;const C=Ft.current;if(!C)return;const P=!hr.current;C.scrollIntoView({inline:"nearest",block:"nearest",behavior:P?"auto":"smooth"}),hr.current=!0,P&&Nu("active-tab-positioned")},[yt,ee]),b.useEffect(()=>{tr&&Bt.current&&(Bt.current.scrollIntoView({block:"nearest",inline:"nearest"}),Bt.current.focus(),Bt.current.select()),tr||(ot.current=!1)},[tr]);const O0=b.useCallback(C=>{window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:C}))},[]),vi=b.useCallback((C,P)=>{Zn(P??null),Sn(C)},[]),td=g6(),Xa=b.useCallback(C=>{if(!C)return;$(C),ze.current&&_a("info","PWA_NOTIFICATION_CLICK app-focus-request",{traceId:ze.current,requestedSessionId:C,activeSessionId:yt,sessions:gt.map(de=>({id:de.id,terminalSessionId:sr.get(de.id)?.terminalSessionId??null}))}),J9(C);const P=gt.find(de=>de.id===C||sr.get(de.id)?.terminalSessionId===C);P?(Qe.current=null,ze.current&&_a("info","PWA_NOTIFICATION_CLICK app-focus-dispatch",{traceId:ze.current,requestedSessionId:C,targetSessionId:P.id}),window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:P.id}))):(Qe.current=C,ze.current&&_a("info","PWA_NOTIFICATION_CLICK app-focus-pending",{traceId:ze.current,requestedSessionId:C}))},[yt,gt,sr]);b.useEffect(()=>{if(typeof window>"u"||typeof caches>"u")return;let C=!1;const P=async()=>{if(window.parent!==window&&Bo()){ie(!0);return}try{const tt=await caches.open(E$),Tt=await tt.match(uy);if(!Tt)return;await tt.delete(uy);const Yt=await Tt.json();if(C)return;const jr=typeof Yt.sessionId=="string"?Yt.sessionId:null,vn=typeof Yt.traceId=="string"?Yt.traceId:null,En=typeof Yt.clickedAt=="number"?Yt.clickedAt:0,In=Date.now()-En;_a("info","PWA_NOTIFICATION_CLICK app-cache-consumed",{traceId:vn,sessionId:jr,ageMs:In,valid:!!(jr&&In>=0&&In<=dy),visibilityState:document.visibilityState}),jr&&In>=0&&In<=dy&&(ze.current=vn,typeof Yt.targetPeerId=="string"&&Yt.targetPeerId!==Sc()?.targetPeerId?Bo()?.focusSession(Yt.targetPeerId,jr):Xa(jr))}catch(tt){_a("warn","PWA_NOTIFICATION_CLICK app-cache-failed",{error:tt instanceof Error?tt.message:String(tt)})}finally{C||ie(!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)}},[Xa]),b.useEffect(()=>{if(typeof window>"u")return;const C=new URLSearchParams(window.location.search),P=C.get("session");if(!P)return;_a("info","PWA_NOTIFICATION_CLICK app-url-received",{traceId:ze.current,targetSessionId:P,href:window.location.href,visibilityState:document.visibilityState});const de=C.get("service");de&&de!==Sc()?.targetPeerId?Bo()?.focusSession(de,P):Qe.current=P,C.delete("service"),C.delete("session"),C.delete("_notifTrace");const tt=C.toString(),Tt=`${window.location.pathname}${tt?`?${tt}`:""}${window.location.hash}`;window.history.replaceState(window.history.state,"",Tt)},[]),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(),tt=`${window.location.pathname}${de?`?${de}`:""}${window.location.hash}`;if(window.history.replaceState(window.history.state,"",tt),window.parent!==window&&Bo())return;const Tt=new BroadcastChannel("termdock:notif");let Yt=!1;const jr=En=>{En.data?.type==="termdock:notif-pong"&&!Yt&&(Yt=!0,Tt.close(),window.close())};Tt.addEventListener("message",jr),Tt.postMessage({type:"termdock:notif-ping",sessionId:P,targetPeerId:C.get("service")});const vn=setTimeout(()=>{Yt||Tt.close()},500);return()=>{clearTimeout(vn),Yt||Tt.close()}},[]),b.useEffect(()=>{if(typeof window>"u"||window.parent!==window&&Bo())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?Bo()?.focusSession(de.data.targetPeerId,de.data.sessionId):Xa(de.data.sessionId)))};return C.addEventListener("message",P),()=>C.close()},[Xa]),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){Bo()?.focusSession(de.targetPeerId,de.sessionId)&&P.ports[0]?.postMessage({type:"termdock:focus-session-ack"});return}P.ports[0]?.postMessage({type:"termdock:focus-session-ack"}),Xa(de.sessionId)}else de?.type==="termdock:push-subscription-changed"?dd(!0):de?.type};return navigator.serviceWorker.addEventListener("message",C),()=>navigator.serviceWorker.removeEventListener("message",C)},[Xa]),b.useEffect(()=>{const C=P=>{const de=P.detail;typeof de=="string"&&Xa(de)};return window.addEventListener("termdock:focus-session",C),()=>window.removeEventListener("termdock:focus-session",C)},[Xa]),b.useEffect(()=>{const C=()=>{const P=iA(Sc()?.targetPeerId);P&&Xa(P)};return C(),window.addEventListener("termdock:workspace-session",C),()=>window.removeEventListener("termdock:workspace-session",C)},[Xa]),b.useEffect(()=>{const C=Qe.current;if(!C)return;const P=gt.find(de=>de.id===C||sr.get(de.id)?.terminalSessionId===C);P?(Qe.current=null,ze.current&&_a("info","PWA_NOTIFICATION_CLICK app-pending-dispatch",{traceId:ze.current,requestedSessionId:C,targetSessionId:P.id,activeSessionId:yt}),window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:P.id}))):ze.current&&_a("info","PWA_NOTIFICATION_CLICK app-pending-unmatched",{traceId:ze.current,requestedSessionId:C,activeSessionId:yt,sessions:gt.map(de=>({id:de.id,terminalSessionId:sr.get(de.id)?.terminalSessionId??null}))})},[yt,gt,sr]);const xa=k.useMemo(()=>{const C=[];for(const P of gt){const de=sr.get(P.id);(de?.agentStatus==="waiting"||de?.agentNeedsReview)&&C.push(P.id)}return C},[gt,sr]),Ql=b.useCallback(()=>{if(xa.length===0)return;yt&&Yr.getState().clearAgentNeedsReview(yt);const C=yt?gt.findIndex(de=>de.id===yt):-1,P=xa.find(de=>gt.findIndex(tt=>tt.id===de)>C)??xa[0];P&&window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:P}))},[xa,gt,yt]),eu=b.useCallback(()=>{if(xa.length===0)return;yt&&Yr.getState().clearAgentNeedsReview(yt);const C=yt?gt.findIndex(de=>de.id===yt):gt.length,P=[...xa].reverse().find(de=>gt.findIndex(tt=>tt.id===de)<C)??xa[xa.length-1];P&&window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:P}))},[xa,gt,yt]);b.useEffect(()=>{const C=P=>{!P.altKey||!P.shiftKey||P.metaKey||P.ctrlKey||P.key!=="ArrowUp"&&P.key!=="ArrowDown"||(P.preventDefault(),P.key==="ArrowUp"?eu():Ql())};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[Ql,eu]);const ip=b.useCallback(async C=>{const de=Yr.getState().sessions.get(C)?.cwd;if(de)try{await navigator.clipboard?.writeText(de),Wn(de),window.setTimeout(()=>{Wn(tt=>tt===de?null:tt)},1400)}catch{}},[]),ap=b.useCallback(C=>{bt(C.sessions),pr(C.activeSessionId),dt(C.splitWorkspaces),Yr.getState().setActiveSessionId(C.activeSessionId)},[]),op=b.useCallback(()=>{Cr(!0)},[]),lp=b.useCallback(()=>{Cr(!0),window.requestAnimationFrame(()=>{window.dispatchEvent(new Event("termdock:initial-viewport-presented"))})},[]);b.useEffect(()=>{if(!N||!yt)return;gt.find(P=>P.id===N||sr.get(P.id)?.terminalSessionId===N)?.id===yt&&$(null)},[yt,N,gt,sr]);const rd=b.useRef(!1),[tu,F0]=b.useState(!1),Ma=b.useCallback(C=>{const P=!C?.onResult;if(P&&rd.current)return;P&&(rd.current=!0,F0(!0));const de=C?.mode??ln,tt=de==="tmux"&&(C?.tmuxSessionName?.trim()||pa.trim())||void 0,Tt=C?.cwd||(yt?Yr.getState().sessions.get(yt)?.cwd:void 0);window.dispatchEvent(new CustomEvent("new-terminal-session",{detail:{mode:de,tmuxSessionName:tt,cwd:Tt,command:C?.command,shouldActivate:C?.shouldActivate,onResult:C?.onResult??(Yt=>{rd.current=!1,F0(!1),Yt.ok||Vr({tone:"error",message:e(Um(Yt.error))})})}}))},[ln,pa,yt,e]),Vo=b.useCallback(async()=>{Fr(!0);try{const C=await Bm();if(Kr(C),!C.available){Mn([]);return}const P=await Qm();Mn(P)}catch{Kr({available:!1,version:null,reason:"tmux integration is unavailable with the current server build."}),Mn([])}finally{Fr(!1)}},[]),mc=b.useCallback(async C=>{const{cleanedSessions:P}=await yy(C);for(const de of P)window.dispatchEvent(new CustomEvent("close-terminal-session-by-backend",{detail:de}));await Vo()},[Vo]),ru=b.useCallback(async C=>{fn(C),Ue(null);try{await mc(C),Or(null)}catch(P){Ue(P instanceof Error?P.message:"Failed to kill tmux session")}finally{fn(null)}},[mc]);b.useEffect(()=>{if(!Et)return;if(Br.find(de=>de.name===Et&&(de.connected||de.boundFrontendSessionId))){kt(null);return}const P=setTimeout(()=>kt(null),1e4);return()=>clearTimeout(P)},[Et,Br]);const gc=b.useCallback(C=>{window.dispatchEvent(new CustomEvent("close-terminal-session",{detail:C}))},[]),nu=b.useCallback(C=>{const P=C??yt;P&&window.dispatchEvent(new CustomEvent("open-terminal-split-chooser",{detail:P}))},[yt]),nd=b.useCallback((C,P)=>{window.dispatchEvent(new CustomEvent("set-terminal-split-direction",{detail:{sessionId:C,layout:P}}))},[]),$0=b.useCallback((C,P)=>{window.dispatchEvent(new CustomEvent("reorder-terminal-split-workspace",{detail:{workspaceId:C,sessionIds:P}}))},[]),U0=b.useCallback((C,P)=>{window.dispatchEvent(new CustomEvent("rename-terminal-split-workspace",{detail:{workspaceId:C,name:P}}))},[]),z0=b.useCallback((C,P)=>{window.dispatchEvent(new CustomEvent("combine-terminal-split-sessions",{detail:{primaryId:C,secondaryId:P}}))},[]),Pl=b.useCallback((C,P,de)=>{const tt=gt.find(Yt=>Yt.id===C);if(!tt)return;const Tt=sr.get(C);if(de?.skipConfirmation||!B5({mode:tt.mode,activeProgram:Tt?.activeProgram??null,promptState:Tt?.promptState??null,shellNames:Ca})){gc({sessionId:C,source:"sidebar",closeMode:tt.mode==="tmux"?"destroy":"auto"});return}Rt(P?{x:P.clientX,y:P.clientY}:null),qe(C),Ue(null)},[gt,sr,gc]);b.useEffect(()=>{if(!Be)return;const C=P=>{const de=P.detail;de==="new-session"?Ma():de==="close-session"?yt&&Pl(yt):de==="previous-session"||de==="next-session"?window.dispatchEvent(new CustomEvent("cycle-terminal-session",{detail:{direction:de==="next-session"?"next":"prev"}})):de==="toggle-left-sidebar"?is():de==="toggle-right-sidebar"?gi():de==="previous-attention"?eu():de==="next-attention"&&Ql()};return window.addEventListener("termdock:native-command",C),()=>window.removeEventListener("termdock:native-command",C)},[yt,Be,Ma,Pl,is,gi,Ql,eu]);const Ja=k.useMemo(()=>gt.find(C=>C.id===ct)??null,[gt,ct]),sd=b.useCallback(()=>{Ja&&(gc({sessionId:Ja.id,source:"sidebar",closeMode:"destroy"}),qe(null),Rt(null))},[Ja,gc]);b.useEffect(()=>{if(!Ja)return;const C=P=>{if(P.key==="Escape"){P.preventDefault(),P.stopImmediatePropagation(),qe(null),Rt(null),Ue(null);return}P.key!=="Enter"||P.isComposing||P.keyCode===229||P.altKey||P.ctrlKey||P.metaKey||P.shiftKey||(P.preventDefault(),P.stopImmediatePropagation(),P.repeat||sd())};return window.addEventListener("keydown",C,!0),()=>window.removeEventListener("keydown",C,!0)},[Ja,sd]);const H0=k.useMemo(()=>{if(!Ja)return"";const C=sr.get(Ja.id);return il(Ja,C?.activeProgram??null,C?.cwd??null,Ca,C?.shellTitle??null,C?.promptState??null).primary},[Ja,sr]);b.useEffect(()=>{if(!et)return;let C=!1,P=!1;const de=async()=>{if(!P)try{const Tt=await Bm();if(C||Kr(Tt),!Tt.available){C||Mn([]);return}const Yt=await Qm();C||Mn(Yt)}catch{P=!0,C||(Kr({available:!1,version:null,reason:"tmux integration is unavailable with the current server build."}),Mn([]))}};de();const tt=setInterval(()=>{de()},4e3);return()=>{C=!0,clearInterval(tt)}},[et]);const xc=Mi??ln,Ol=xc==="shell",su=xc==="tmux"&&Sr.available,xl=k.useMemo(()=>$y(Br.map(C=>({...C,id:C.name})),C=>C.cwd??null,e("sidebar.ungrouped")),[Br,e]),id=k.useMemo(()=>Br.filter(C=>C.recoveryCandidate===!0&&!C.connected&&!C.boundFrontendSessionId).sort((C,P)=>(P.lastActiveAt??P.createdAt??0)-(C.lastActiveAt??C.createdAt??0)),[Br]);b.useEffect(()=>{!Ir&&!(ht&&ir)||Vo()},[Ir,ht,ir,gt.length,Vo]);const bc=(C,P,de,tt=!1)=>{const Tt=C.id===yt,Yt=C.id===tr,jr=sr.get(C.id),{primary:vn,secondary:En}=il(C,jr?.activeProgram??null,jr?.cwd??null,Ca,jr?.shellTitle??null,jr?.promptState??null),In=Yu(jr?.cwd??null),wi=P?En??(In&&In!==vn?In:null):null,wn=jr?.gitStatus,Zi=`${jr?.cwd||C.name}${wn?`
|
|
186
186
|
⎇ ${wn.branch} +${wn.added} −${wn.removed}`:""}`,_o=!!(jr?.tuiProgress&&jr.tuiProgress.state!=="remove"),ko=jr?.agentStatus==="working"||_o?"var(--success)":jr?.agentStatus==="waiting"||jr?.agentNeedsReview?"var(--warning)":jr?.inCopyMode?"var(--tmux)":null;if(Yt&&ir&&!on){const Da=C.customName?C.name:vn,Bi=(eo,cp)=>{const ld=cp.trim();ld?ld!==Da&&Wi(eo,ld):Gi(eo),Qr(null)};return s.jsx("input",{ref:eo=>{Bt.current=eo},type:"text",defaultValue:Da,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(Da.length,5)}ch`},onKeyDown:eo=>{eo.key==="Enter"?Bi(C.id,eo.target.value):eo.key==="Escape"&&Qr(null)},onBlur:eo=>Bi(C.id,eo.target.value)})}return s.jsx("div",{ref:Tt?Ft:null,onContextMenu:Da=>{Da.preventDefault(),Zn({x:Da.clientX,y:Da.clientY}),Sn(C.id)},...td(()=>vi(C.id)),className:tt?`group relative inline-flex h-5 shrink-0 items-center rounded-sm text-[11px] leading-none transition ${Tt?"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 ${Tt?"bg-surface-elevated text-foreground shadow-sm":"text-muted-foreground hover:bg-surface-elevated/50 hover:text-foreground"}`,style:!tt&&Tt&&ko?{boxShadow:`inset 2px 0 0 0 ${ko}`}:!tt&&Tt?{boxShadow:"inset 2px 0 0 0 rgb(var(--primary-rgb, 99 102 241))"}:void 0,title:Zi,children:s.jsx("button",{type:"button",...de??{},onClick:()=>O0(C.id),className:`inline-flex min-w-0 flex-1 items-center gap-1 overflow-hidden text-left ${tt?"px-1":"py-1 pl-1 pr-1.5 sm:pl-1.5 sm:pr-2"} ${de?"cursor-grab active:cursor-grabbing":""}`,title:Zi,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:[fy(C.mode,jr),jr?.agentResumeRecovered&&s.jsx(Qc,{size:tt?9:10,className:"-ml-0.5 shrink-0 text-[color:var(--warning)]","aria-label":e("tab.resumeAgentAvailable")}),_o&&!jr?.agentStatus&&s.jsx(Cn,{size:tt?9:10,className:"-ml-0.5 shrink-0 animate-spin text-[color:var(--success)]"})]}),wi?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] ${jr?.inCopyMode?"text-[color:var(--tmux)]":""}`,children:vn}),s.jsx("span",{className:"truncate text-[9px] text-muted-foreground/80 sm:text-[9.5px]",children:wi})]}):s.jsx("span",{className:`whitespace-nowrap text-[11px] sm:text-[12px] ${jr?.inCopyMode?"text-[color:var(--tmux)]":""}`,children:vn})]})})})},ad=()=>s.jsx(Ll,{droppableId:R1,type:"session",isDropDisabled:ir,children:(C,P)=>{const de=Kn||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":!Gn,"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 ${Gn?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(zs,{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]})}}),ba=ht&&ir,Fl=Ot&&ir,od=Ph(Tr,Pr,ba?Ht:0),yc=Fl?od+by:0,$l=ba?gt.find(C=>C.id===yt):null,Ds=$l?sr.get($l.id):void 0,W0=$l?il($l,Ds?.activeProgram??null,Ds?.cwd??null,Ca,Ds?.shellTitle??null,Ds?.promptState??null).primary:"",ja=ir?xt:null,Co=ba&&!ja&&Ds?Ds.agentStatus==="working"?"bg-gradient-to-r from-[rgb(var(--success-rgb)_/_0.08)] to-transparent":Ds.agentStatus==="waiting"?"bg-gradient-to-r from-[rgb(var(--warning-rgb)_/_0.14)] to-transparent":Ds.agentNeedsReview?"bg-gradient-to-r from-[rgb(var(--warning-rgb)_/_0.08)] to-transparent":Ds.inCopyMode?"bg-gradient-to-r from-[rgb(var(--tmux-rgb)_/_0.07)] to-transparent":"":"",Ul=s.jsxs("div",{className:"w-full h-full flex flex-col app-chrome-bg text-foreground",children:[dn&&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:dn}),s.jsx("button",{type:"button",className:"min-h-11 px-2 text-primary",onClick:()=>jn(""),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(tC,{rightInset:yc,workspace:It&&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(Q$,{groupId:It,activeSessionId:yt,defaultSessionMode:ln,onOpenSidebar:is,leftSidebarVisible:Ir||ba,onToggleRightSidebar:gi,rightSidebarOpen:ne||Fl},It)}),children:[s.jsxs("div",{className:`${ir?"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 ${ba?"flex justify-end":"flex justify-between"} ${dr?"h-10 sm:h-10":"h-9 sm:h-10"} ${Co}`,style:{position:ir?"absolute":void 0,marginRight:yc||void 0,display:ja?"none":void 0},children:[!ba&&s.jsxs("button",{type:"button",onClick:is,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")}: ${Yi.running} · ${e("agent.needsReview")}: ${Yi.review}`,children:[s.jsx(UT,{size:14}),s.jsx(FP,{runningCount:Yi.running,reviewCount:Yi.review,className:"sm:hidden"})]}),ba?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:$l?s.jsxs(s.Fragment,{children:[fy($l.mode,Ds),s.jsx("span",{className:`truncate text-[12px] font-medium ${Ds?.inCopyMode?"text-[color:var(--tmux)]":"text-foreground"}`,children:W0}),Ds?.agentStatus==="working"&&s.jsx("span",{title:Ds?.agentMessage??void 0,children:s.jsx(Cn,{size:12,className:"shrink-0 animate-spin text-[color:var(--success)]"})}),Ds?.agentStatus==="waiting"&&s.jsx("span",{title:Ds?.agentMessage??void 0,children:s.jsx(af,{size:12,className:"shrink-0 animate-bounce-y text-[color:var(--warning)]"})}),!Ds?.agentStatus&&Ds?.agentNeedsReview&&s.jsx("span",{title:Ds?.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")})}):dr?s.jsxs(c0,{onDragStart:zi,onDragUpdate:Ri,onDragEnd:cs,children:[ad(),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 tt=0,Tt=0;for(const En of P.sessions){const In=sr.get(En.id);In?.agentStatus==="working"&&(tt+=1),(In?.agentStatus==="waiting"||In?.agentNeedsReview)&&(Tt+=1)}const Yt=P.sessions.some(En=>En.id===yt),jr=hn.has(P.key),vn=P.key==="";return s.jsx(kl,{draggableId:`group-${P.key||"__ungrouped__"}`,index:de,isDragDisabled:vn,disableInteractiveElementBlocking:!0,children:(En,In)=>s.jsxs("div",{ref:En.innerRef,...En.draggableProps,className:`flex w-fit shrink-0 flex-col justify-center gap-px rounded-md py-0.5 px-1 ring-1 transition-colors ${In.isDragging?"bg-surface-elevated ring-primary/30 shadow-lg opacity-90":Yt?"bg-primary/[0.06] ring-primary/20":"bg-surface-2/40 ring-border/10"}`,children:[s.jsxs("button",{type:"button",...vn?{}:En.dragHandleProps,onClick:()=>Tn(P.key),className:`flex ${jr?"":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 ${vn?"":"cursor-grab active:cursor-grabbing"} ${Yt?"text-primary/80":"text-muted-foreground/55"}`,title:P.key||P.label,children:[s.jsx(fi,{size:9,className:`shrink-0 opacity-70 transition-transform ${jr?"":"rotate-90"}`}),s.jsx("span",{className:"min-w-0 truncate",children:P.label}),tt>0&&s.jsx("span",{className:"ml-auto h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--success)]"}),Tt>0&&s.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--warning)] ${tt>0?"":"ml-auto"}`})]}),jr?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:wi=>s.jsxs("div",{ref:wi.innerRef,...wi.droppableProps,className:"flex items-center gap-px",children:[P.sessions.map((wn,Zi)=>s.jsx(kl,{draggableId:wn.id,index:Zi,disableInteractiveElementBlocking:!0,children:(_o,ko)=>s.jsx("div",{ref:_o.innerRef,..._o.draggableProps,className:`flex shrink-0 items-center ${ko.isDragging?"opacity-70":""}`,children:bc(wn,!1,_o.dragHandleProps,!0)})},wn.id)),wi.placeholder]})})]})},P.key||"__ungrouped__")}),C.placeholder,s.jsx("button",{type:"button",onClick:()=>Ma(),disabled:tu,"aria-busy":tu,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(Us,{size:14})})]})})]}):s.jsxs(c0,{onDragStart:zi,onDragUpdate:Ri,onDragEnd:Dl,children:[ad(),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:Tt=>s.jsx("div",{ref:Tt.innerRef,...Tt.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:(Tt,Yt)=>s.jsx("div",{ref:Tt.innerRef,...Tt.draggableProps,className:`flex h-full shrink-0 items-center ${Yt.isDragging?"opacity-70":""}`,children:bc(P,!0,Tt.dragHandleProps)})})},P.id)),s.jsx("button",{type:"button",onClick:()=>Ma(),disabled:tu,"aria-busy":tu,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(Us,{size:14})}),C.placeholder]})})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[!ba&&Yi.running>0&&s.jsx("span",{className:"hidden items-center gap-1 sm:inline-flex",children:s.jsx(j6,{count:Yi.running,tone:"running",title:e("agent.aiRunning")})}),!ba&>.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 ${gt.length}`,children:Vs}),!Fl&&s.jsx("button",{type:"button",onClick:gi,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(By,{size:14})})]})]}),Jc&&bi&&So?.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:!yi?.error&&(yi?.status==="submitting"||yi?.status==="waiting")?s.jsx(Cn,{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:So.agent?.displayName??"Agent"})}),s.jsx("div",{className:`truncate text-[10px] sm:text-[11px] ${yi?.error?"text-destructive":"text-muted-foreground"}`,children:yi?.error??(yi?.status==="submitting"?e("tab.resumeAgentSubmitting"):yi?.status==="waiting"?e("tab.resumeAgentWaiting"):e("tab.resumeAgentRecoveredHint"))})]}),s.jsx("button",{type:"button",disabled:!yi?.error&&(yi?.status==="submitting"||yi?.status==="waiting"),onClick:()=>{an(bi.id,So.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:yi?.error?e("common.retry"):e("tab.resumeAgentNow")}),s.jsx("button",{type:"button",onClick:()=>{Yr.getState().setAgentResumeRecovered(bi.id,!1),Lr(C=>C?.sessionId===bi.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(Rn,{size:13})})]}),s.jsx("div",{ref:Le,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(CN,{terminalSettings:qt,colorTheme:p,toolbarPresets:As,showDebug:l&&ir,terminalFocusAvailable:we,defaultSessionMode:ln,defaultTmuxSessionName:pa,connectionPrioritySessionId:N,connectionPriorityReady:ee,desktopRightSidebarEnabled:ir,onToggleRightSidebar:gi,desktopFloatingTitle:ir,desktopPinnedLeftSidebarWidth:ba?Ht:0,desktopViewportWidth:Pr,onSessionDataUpdate:ap,onInitialViewportReady:lp,onInitialRecoveryRequired:op})})})]})}),!It&&s.jsx(WP,{reviewCount:Yi.review,runningSessions:js,activeSessionId:yt,runningButtonEnabled:Er,attentionButtonEnabled:$n,isDesktopLayout:ir,containerElement:ps,occlusionInsets:{right:yc}}),et&&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:Ni,"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($m,{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:Ni,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(Rn,{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:()=>Ve({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=>Ve({fontSize:parseInt(C.target.value,10)}),className:"min-w-0 flex-1","aria-label":e("settings.font")}),s.jsx("button",{type:"button",onClick:()=>Ve({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(y$,{}),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=er===C;return s.jsx("button",{type:"button",onClick:()=>Ve({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",jT,e("settings.darkTheme")],["light",CS,e("settings.lightTheme")]].map(([C,P,de])=>{const tt=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 ${tt?"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=ln===C,de=C==="tmux"&&!Sr.available;return s.jsx("button",{type:"button",disabled:de,onClick:()=>Ea(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?Sr.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 ka({preventSleep:C});w(P.preventSleep),S(P.networkAvailable),pe(P.localAccess),On(Hd,{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":Er,"aria-label":e("sidebar.runningSessionButton"),onClick:()=>{rs(!Er)},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(of,{size:14,className:Er?"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:Er,size:"sm"})]}),s.jsxs("button",{type:"button",role:"switch","aria-checked":$n,"aria-label":e("sidebar.attentionButton"),onClick:()=>{Ln(!$n)},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:$n?"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:$n,size:"sm"})]})]}),s.jsxs("button",{type:"button",onClick:()=>ti(!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(Ey,{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&&W?"settings.notificationsBothOnSummary":R?"settings.notificationsAiOnSummary":W?"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:()=>Di(!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(fi,{size:16,className:"shrink-0 text-muted-foreground"})]}),s.jsx(h$,{state:_e,pending:re,onCheck:()=>{wt()},onConfirmRestart:()=>{nt()},desktopState:Ne?rt:void 0,desktopPending:ue,onCheckDesktop:Ne?()=>{Rr()}:void 0,onInstallDesktop:()=>{rn()},desktopSnapshot:le,desktopActions:Be?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:()=>{Be.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(jA,{size:13,className:"shrink-0 text-primary"}),e("settings.desktopSwitchService")]}),s.jsxs("button",{type:"button",onClick:()=>{Ie(null),Be.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(Ru,{size:13,className:"shrink-0 text-primary"}),e("settings.desktopOpenDataDirectory")]})]}),st&&s.jsx("div",{className:"border-t border-border/10 px-3 py-2 text-[10px] text-muted-foreground",children:st})]}):void 0}),s.jsx(p$,{backendSessionId:yt?sr.get(yt)?.terminalSessionId??null:null}),s.jsx(g$,{state:Ce,onDismiss:()=>{Me()}}),s.jsxs("div",{className:"mt-3 flex gap-2",children:[s.jsxs("button",{type:"button",onClick:()=>{ji(null),Ma({mode:"shell"}),Ni()},className:`flex min-w-0 items-center justify-center gap-1.5 rounded-xl text-[13px] font-semibold transition active:scale-[0.98] ${Ol?"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(Mi==="shell"?"sidebar.confirmNewShell":"settings.shell"),children:[s.jsx(Us,{size:14,className:Ol?"shrink-0":"hidden"}),s.jsx(Fo,{size:12}),s.jsx("span",{className:Ol?"whitespace-nowrap":"hidden",children:e(Mi==="shell"?"sidebar.confirmNewShell":"settings.shell")})]}),s.jsxs("button",{type:"button",disabled:!Sr.available,onClick:()=>{Sr.available&&(ji(null),Ma({mode:"tmux"}),Ni())},className:`flex min-w-0 items-center justify-center gap-1.5 rounded-xl text-[13px] font-semibold transition active:scale-[0.98] ${Sr.available?su?"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:Sr.available?e(Mi==="tmux"?"sidebar.confirmNewTmux":"settings.tmux"):Sr.reason||e("settings.installTmuxHint"),children:[s.jsx(Us,{size:14,className:su?"shrink-0":"hidden"}),s.jsx(Uu,{size:12}),s.jsx("span",{className:su?"whitespace-nowrap":"hidden",children:e(Mi==="tmux"?"sidebar.confirmNewTmux":"settings.tmux")})]})]}),(Sr.available||Br.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 ${Sr.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:Sr.available?e("settings.sessions",{n:Br.length}):e("settings.tmuxUnavailable")})]}),s.jsx("button",{type:"button",onClick:C=>{C.preventDefault(),Vo()},disabled:nn,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(gn,{size:12,className:nn?"animate-spin":""})})]}),s.jsx("div",{className:"px-2 pb-2",children:Sr.available?Br.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(Gc,{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,tt=!!(P.connected||de),Tt=de?gt.find(Bi=>Bi.id===de)??null:null,Yt=P.friendlyName?.trim()||null,jr=P.label&&P.label!==P.name?P.label:null,vn=Yt||jr||P.name,En=Yt||jr?`tmux:${P.name}`:null,In=P.clientCount&&P.clientCount>0?t==="zh"?`网页连接 ${P.clientCount}`:`Web clients ${P.clientCount}`:null,wi=P.attached>0?t==="zh"?`原生 tmux ${P.attached}`:`Native tmux ${P.attached}`:null,wn=[En,tt?P.restorable?e("settings.restorable"):e("settings.attached"):null,In,wi].filter(Bi=>!!Bi),Zi=[e("settings.windows",{n:P.windows}),P.createdAt?new Date(P.createdAt).toLocaleDateString():null].filter(Bi=>!!Bi),_o=ks===P.name,ko=Xr===P.name,Da=Et===P.name;return s.jsxs("div",{className:`flex items-start gap-2 rounded-lg px-2.5 py-2 ${_o?"bg-destructive/10 ring-1 ring-destructive/40":"bg-surface"}`,children:[s.jsx(Uu,{size:13,className:tt?"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:vn}),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"})]}),wn.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:wn.map(Bi=>s.jsx("span",{className:"max-w-full truncate",children:Bi},Bi))}),(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(gT,{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(Gc,{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:Zi.map(Bi=>s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(ZA,{size:10,className:"shrink-0 text-muted-foreground/60"}),Bi]},Bi))})]}),_o?s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",disabled:ko,onClick:()=>{ru(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:ko?"…":e("settings.destroy")}),s.jsx("button",{type:"button",disabled:ko,onClick:()=>{Or(null),Ue(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:()=>{Tt?O0(Tt.id):(kt(P.name),Ma({mode:"tmux",tmuxSessionName:P.name}))},disabled:Da,className:`shrink-0 inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-[11px] font-medium transition disabled:opacity-50 ${tt?"bg-surface text-foreground hover:bg-surface-elevated":Da?"bg-primary/10 text-primary":"bg-primary/15 text-primary hover:bg-primary/25"}`,children:Da?s.jsxs(s.Fragment,{children:[s.jsx(Cn,{size:10,className:"animate-spin"}),e("settings.attaching")]}):e(tt?"settings.attached":"settings.attach")}),s.jsx("button",{type:"button",disabled:ko,onClick:()=>{Ue(null),Or(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(zs,{size:12})})]})]},P.name)})]},C.key||"__ungrouped_tmux__")),K&&s.jsx("p",{className:"px-2 text-[11px] text-destructive",children:K})]}):s.jsx("p",{className:"px-2 py-1.5 text-[11px] text-muted-foreground",children:Sr.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(My,{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:()=>ls(!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(E0,{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 eA()}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(Oy,{size:14}),e("settings.signOut")]})]})]})})]}),Ja&&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:()=>{qe(null),Rt(null),Ue(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 ${At&&ir?"":"inset-x-3 bottom-6 mx-auto max-w-sm sm:bottom-auto sm:top-[15%]"}`,style:At&&ir?{...ly(At),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:H0}),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:sd,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(zs,{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")})]})]}),K&&s.jsx("p",{className:"px-4 py-2 text-[11px] text-destructive",children:K})]}),s.jsx("div",{className:"border-t border-border/15 px-3 py-2",children:s.jsx("button",{type:"button",onClick:()=>{qe(null),Rt(null),Ue(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=gt.find(In=>In.id===cr);if(!C)return null;const P=sr.get(C.id),{primary:de}=il(C,P?.activeProgram??null,P?.cwd??null,Ca),tt=ir,Tt=tt?ly(Ls):{paddingBottom:a},Yt=tt?"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%]",jr=tt?"border-b border-border/15 px-3 py-2":"border-b border-border/15 px-4 py-3",vn=tt?"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",En=tt?"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 ${tt?"bg-transparent":"bg-[var(--app-backdrop-soft)] backdrop-blur-sm"}`,onClick:Kt,"aria-label":"Close menu"}),s.jsxs("div",{className:Yt,style:Tt,children:[s.jsxs("div",{className:jr,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 In=Ls;Kt(),_r(In),Qr(C.id)},className:`${vn} text-foreground hover:bg-surface-2`,children:[s.jsx("span",{className:`${En} bg-primary/15 text-primary`,children:s.jsx(KT,{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:()=>{ip(C.id),Kt()},className:`${vn} ${P?.cwd?"text-foreground hover:bg-surface-2":"text-muted-foreground/50 cursor-not-allowed"}`,children:[s.jsx("span",{className:`${En} bg-surface-2 text-muted-foreground`,children:s.jsx(jy,{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")})]}),$r&&$r===P?.cwd&&s.jsx("span",{className:"ml-auto text-[11px] text-primary",children:e("tab.copied")})]}),(()=>{const In=Pm(C.id),wi=In??De;return s.jsxs("div",{className:`${vn} text-foreground`,children:[s.jsx("span",{className:`${En} bg-surface-2 text-muted-foreground`,children:s.jsx(LS,{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:()=>{Qh(C.id,wi-1),sn(wn=>wn+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:[wi,"px"]}),s.jsx("button",{type:"button",onClick:()=>{Qh(C.id,wi+1),sn(wn=>wn+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:"+"}),In!==null&&s.jsx("button",{type:"button",onClick:()=>{Qh(C.id,null),sn(wn=>wn+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 In=P.terminalSessionId;In&&(Kt(),an(C.id,In))},className:`${vn} text-foreground hover:bg-surface-2`,children:[s.jsx("span",{className:`${En} 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:()=>{Kt(),Pl(C.id)},className:`${vn} text-destructive hover:bg-destructive/10`,children:[s.jsx("span",{className:`${En} bg-destructive/15 text-destructive`,children:s.jsx(zs,{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:()=>{Kt(),gc({sessionId:C.id,source:"tab-menu",closeMode:"auto"})},className:`${vn} text-destructive hover:bg-destructive/10`,children:[s.jsx("span",{className:`${En} bg-destructive/15 text-destructive`,children:s.jsx(Rn,{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")})]})]}),!tt&&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:()=>{Kt()},children:e("tab.longPressTip")})]}),!tt&&s.jsx("div",{className:"border-t border-border/15 px-3 py-2",children:s.jsx("button",{type:"button",onClick:Kt,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&&on&&ir&&(()=>{const C=gt.find(wn=>wn.id===tr);if(!C)return null;const P=sr.get(C.id),{primary:de}=il(C,P?.activeProgram??null,P?.cwd??null,Ca,P?.shellTitle??null,P?.promptState??null),tt=C.customName?C.name:de,Tt=wn=>{const Zi=wn.trim();Zi?Zi!==tt&&Wi(C.id,Zi):Gi(C.id),Qr(null),_r(null)},Yt=300,jr=160,vn=on.x,En=on.y,In=Math.min(Math.max(vn-Yt/2,12),window.innerWidth-Yt-12),wi=En+jr+20>window.innerHeight?Math.max(En-jr-12,12):En+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:()=>{Qr(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:`${In}px`,top:`${wi}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:wn=>{wn.preventDefault();const Zi=new FormData(wn.currentTarget).get("session-name");Tt(typeof Zi=="string"?Zi:"")},children:[s.jsx("input",{ref:wn=>{Bt.current=wn,wn&&!ot.current&&(ot.current=!0,wn.focus({preventScroll:!0}),wn.select())},type:"text",name:"session-name",defaultValue:tt,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:wn=>{wn.key==="Escape"&&(wn.stopPropagation(),Qr(null),_r(null))}}),s.jsxs("div",{className:"mt-2.5 flex gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{Qr(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&&!ir&&(()=>{const C=gt.find(Yt=>Yt.id===tr);if(!C)return null;const P=sr.get(C.id),{primary:de}=il(C,P?.activeProgram??null,P?.cwd??null,Ca,P?.shellTitle??null,P?.promptState??null),tt=C.customName?C.name:de,Tt=Yt=>{const jr=Yt.trim();jr?jr!==tt&&Wi(C.id,jr):Gi(C.id),Qr(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:()=>Qr(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:Yt=>{Yt.preventDefault();const jr=new FormData(Yt.currentTarget).get("session-name");Tt(typeof jr=="string"?jr:"")},children:[s.jsx("input",{ref:Yt=>{Bt.current=Yt,Yt&&!ot.current&&(ot.current=!0,Yt.focus({preventScroll:!0}),Yt.select())},type:"text",name:"session-name",defaultValue:tt,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:Yt=>{Yt.key==="Escape"&&(Yt.stopPropagation(),Qr(null))}}),s.jsxs("div",{className:"mt-3 flex gap-2",children:[s.jsx("button",{type:"button",onClick:()=>Qr(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:()=>Di(!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:()=>Di(!1),className:"rounded-full bg-surface-2 p-2 text-muted-foreground",children:s.jsx(Rn,{size:18})})]}),s.jsxs("div",{className:"overflow-y-auto overscroll-contain p-4",children:[s.jsx(rC,{state:xe,onCopy:C=>{ml(C,"setup")},copied:Se==="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:te,onChange:C=>ke(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:$e,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($e?"settings.saving":"common.save")}),s.jsx("button",{type:"button",disabled:$e,onClick:()=>{Ia()},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:[xe.url&&s.jsxs("button",{type:"button",onClick:()=>{ml(xe.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: ",xe.url]}),s.jsx("span",{className:"shrink-0 rounded-full bg-primary/10 px-2 py-0.5 text-[10px] font-medium",children:Se==="lan"?"Copied":e("common.copy")})]}),xe.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:xe.interfaces.map(C=>{const P=C.url??`${xe.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:Se===`ip-${C.address}`?"Copied":e("common.copy")})]})]},`${C.name}-${C.address}`)})})]}),s.jsxs("div",{className:"text-muted-foreground",children:[xe.httpsEnabled?e("settings.httpsActive"):e("settings.httpsInactive"),!xe.caAvailable&&` · ${e("settings.caMissing")}`]}),xe.reason&&s.jsx("div",{className:"text-[color:var(--warning)]",children:xe.reason}),Ae&&s.jsx("div",{className:"text-destructive",children:Ae})]})]})]})]}),Na&&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:()=>ti(!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:()=>ti(!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(Rn,{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"):th()?e("settings.notificationsMasterHint"):e("settings.notificationsUnsupported")}),th()&&!tA()&&s.jsx("div",{className:"mt-1.5 text-[11px] leading-relaxed text-[var(--warning)]",children:e("settings.notificationsIOSInstallHint")})]}),s.jsx("button",{type:"button",onClick:()=>{Ur()},disabled:!th()||Z==="denied",className:"shrink-0 transition disabled:cursor-not-allowed","aria-pressed":L,children:s.jsx(ll,{checked:L,disabled:!th()||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"),": ",xo()?e("settings.notificationsPermissionSystem"):Z]}),s.jsx("button",{type:"button",disabled:!L||Z!=="granted"||ys==="checking",onClick:()=>{Jr()},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")}),xo()?.openNotificationSettings&&s.jsx("button",{type:"button",onClick:()=>{xo()?.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 tt=U===C;return s.jsxs("button",{type:"button",disabled:!L,onClick:()=>yn(C),className:`min-w-0 rounded-lg px-2 py-2 text-left transition ${tt&&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:()=>Qn(!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:()=>vr(!W),className:"shrink-0 transition disabled:cursor-not-allowed","aria-pressed":W&&L,children:s.jsx(ll,{checked:W&&L,disabled:!L})})]})]}),s.jsx("p",{className:"mt-2 text-[10px] text-muted-foreground",children:e("settings.notificationsFutureHint")})]})]})]})]}),ei&&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(Rn,{size:18})})]}),s.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto p-4 sm:p-6",children:s.jsx(c$,{presets:As,selectedPresetId:Ao,onSelectPreset:ma,onUpdatePreset:(C,P)=>{Ka(de=>Eu(de.map(tt=>tt.id===C?P(tt):tt)))},onAddPreset:()=>{const C=`preset-${Date.now()}`;Ka(P=>Eu([...P,{id:C,label:`Preset ${P.length}`,programs:[],includeAlt:!1,rowLayout:[3,3],actions:[],showOnDesktop:!1}])),ma(C)},onRemovePreset:C=>{Ka(P=>Eu(P.filter(de=>de.id!==C)))},onResetDefaults:()=>{Ka(b0()),ma("default")}})})]})]}),ga&&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:()=>ls(!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:()=>ls(!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(Rn,{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(d$,{}),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:gt.map(C=>{const P=sr.get(C.id),de=P?.activeProgramRaw??null,tt=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:"})," ",tt||"—"]}),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(tt=>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:[tt,s.jsx("button",{type:"button",onClick:()=>{const Tt={...Xe,[C]:Xe[C].filter(Yt=>Yt!==tt)};ft(Tt),C==="shellNames"&&(Ca=new Set(Tt.shellNames)),u2(Tt).catch(()=>{})},className:"ml-0.5 text-muted-foreground hover:text-destructive",children:"×"})]},tt)),s.jsx("input",{placeholder:e("settings.addTag"),className:"w-16 rounded bg-surface px-1.5 py-0.5 text-[11px] font-mono",onKeyDown:tt=>{if(tt.key!=="Enter")return;const Tt=tt.target.value.trim().toLowerCase();if(!Tt||Xe[C].includes(Tt))return;const Yt={...Xe,[C]:[...Xe[C],Tt]};ft(Yt),C==="shellNames"&&(Ca=new Set(Yt.shellNames)),tt.target.value="",u2(Yt).catch(()=>{})}})]})]},C)),s.jsx("button",{type:"button",onClick:()=>{rA().then(C=>{ft(C),Ca=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 tt=se.map((Tt,Yt)=>Yt===P?{...Tt,enabled:de.target.checked}:Tt);T(tt),On(Sa,tt),fe(!0),lu(tt).then(Tt=>{T(Tt),On(Sa,Tt)}).catch(()=>{}).finally(()=>fe(!1))}}),s.jsxs("select",{value:C.matchType,onChange:de=>{const tt=se.map((Tt,Yt)=>Yt===P?{...Tt,matchType:de.target.value}:Tt);T(tt),On(Sa,tt),fe(!0),lu(tt).then(Tt=>{T(Tt),On(Sa,Tt)}).catch(()=>{}).finally(()=>fe(!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 tt=se.map((Tt,Yt)=>Yt===P?{...Tt,pattern:de.target.value}:Tt);T(tt),On(Sa,tt)},onBlur:()=>{fe(!0),lu(se).then(de=>{T(de),On(Sa,de)}).catch(()=>{}).finally(()=>fe(!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 tt=se.map((Tt,Yt)=>Yt===P?{...Tt,output:de.target.value}:Tt);T(tt),On(Sa,tt)},onBlur:()=>{fe(!0),lu(se).then(de=>{T(de),On(Sa,de)}).catch(()=>{}).finally(()=>fe(!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((tt,Tt)=>Tt!==P);T(de),On(Sa,de),fe(!0),lu(de).then(tt=>{T(tt),On(Sa,tt)}).catch(()=>{}).finally(()=>fe(!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),On(Sa,C),fe(!0),lu(C).then(P=>{T(P),On(Sa,P)}).catch(()=>{}).finally(()=>fe(!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:()=>{fe(!0),nA().then(C=>{T(C),On(Sa,C)}).catch(()=>{}).finally(()=>fe(!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:O?e("settings.saving"):j?`${se.length} rules`:"…"})]})]})]})]})]})]}),Go&&s.jsx(n$,{isOpen:Go,onClose:()=>qi(!1)}),!ba&&s.jsx(Mb,{isOpen:Ir,drawerWidthPx:fr,onClose:()=>zn("left-sidebar"),onOpen:da,sessions:gt,activeSessionId:yt,sessionStates:sr,onNewSession:C=>Ma(C),recoverableTmuxSessions:id,recoverableTmuxSessionsLoading:nn,onRefreshRecoverableTmuxSessions:()=>{Vo()},onCloseRecoverableTmuxSession:mc,onCloseSession:Pl,onSplitSession:nu,onCloseSplit:C=>window.dispatchEvent(new CustomEvent("close-terminal-split",{detail:C})),onRemoveFromSplit:C=>window.dispatchEvent(new CustomEvent("remove-terminal-split-pane",{detail:C})),splitWorkspaces:it,onSetSplitLayout:nd,onReorderSplitWorkspace:$0,onRenameSplitWorkspace:U0,onCombineSplitSessions:z0,onReorderSessions:Xn,onSessionMenu:vi,onOpenSettings:Ms,onJumpToNextAttention:xa.length>0?Ql:void 0,onOpenQuota:()=>qi(!0),updateState:_e,updateActionPending:re,onConfirmUpdateRestart:nt,onRetryUpdate:wt,serverHealthState:Ce,tmuxAvailable:Sr.available,defaultSessionMode:ln,onTogglePinned:ir?Ga:void 0}),!Fl&&s.jsx(jb,{isOpen:ne,sessionId:yt,drawerWidthPx:Un,onClose:()=>zn("right-sidebar"),onOpen:ms,rightSidebarFilePreviewOpen:Dn,rightSidebarFilePreviewCloseSignal:be,onOpenRightSidebarFilePreview:xi,onCloseRightSidebarFilePreview:hl,rightSidebarRepoPickerOpen:Je,rightSidebarRepoPickerCloseSignal:Vt,onOpenRightSidebarRepoPicker:Js,onCloseRightSidebarRepoPicker:Uo,markdownOutlineOpen:vt,markdownOutlineCloseSignal:Pt,onOpenMarkdownOutline:fa,onCloseMarkdownOutline:fl,markdownImageLightboxOpen:zt,markdownImageLightboxCloseSignal:me,onOpenMarkdownImageLightbox:pl,onCloseMarkdownImageLightbox:os,onTogglePinned:ir?Xs:void 0}),We&&!c&&s.jsx("button",{type:"button",onClick:jl,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"})]})}),ge&&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 ${ge.tone==="success"?"border-[rgb(var(--success-rgb)_/_0.24)] bg-surface-elevated text-foreground":"border-destructive/30 bg-surface-elevated text-destructive"}`,role:ge.tone==="error"?"alert":"status",children:[ge.tone==="success"?s.jsx(Qc,{size:14,className:"shrink-0 text-[color:var(--success)]"}):s.jsx(af,{size:14,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1",children:ge.message}),s.jsx("button",{type:"button",onClick:()=>Vr(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(Rn,{size:12})})]}),l&&s.jsxs(s.Fragment,{children:[!ir&&s.jsx(nC,{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)})]})]})]}),zl=nr?null:s.jsx(aA,{className:"z-modal-panel",status:"正在恢复终端…"});return ir?s.jsxs("div",{className:"w-screen h-full flex flex-row",children:[ba&&s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{width:Ht,flexShrink:0,height:"100%"},children:s.jsx(Mb,{isOpen:Ir,drawerWidthPx:Ht,onClose:Ks,onOpen:da,sessions:gt,activeSessionId:yt,sessionStates:sr,onNewSession:C=>Ma(C),recoverableTmuxSessions:id,recoverableTmuxSessionsLoading:nn,onRefreshRecoverableTmuxSessions:()=>{Vo()},onCloseRecoverableTmuxSession:mc,onCloseSession:Pl,onSplitSession:nu,onCloseSplit:C=>window.dispatchEvent(new CustomEvent("close-terminal-split",{detail:C})),onRemoveFromSplit:C=>window.dispatchEvent(new CustomEvent("remove-terminal-split-pane",{detail:C})),splitWorkspaces:it,onSetSplitLayout:nd,onReorderSplitWorkspace:$0,onRenameSplitWorkspace:U0,onCombineSplitSessions:z0,onReorderSessions:Xn,onSessionMenu:vi,onOpenSettings:Ms,onJumpToNextAttention:xa.length>0?Ql:void 0,onOpenQuota:()=>qi(!0),updateState:_e,updateActionPending:re,onConfirmUpdateRestart:nt,onRetryUpdate:wt,serverHealthState:Ce,tmuxAvailable:Sr.available,defaultSessionMode:ln,pinned:!0,onTogglePinned:Ga})}),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:[Ul,Fl&&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:Ui}),s.jsx("div",{style:{width:od,flexShrink:0,height:"100%"},children:s.jsx(jb,{isOpen:!0,sessionId:yt,drawerWidthPx:od,onClose:Hs,onOpen:ms,pinned:!0,onTogglePinned:Xs,rightSidebarFilePreviewOpen:Dn,rightSidebarFilePreviewCloseSignal:be,onOpenRightSidebarFilePreview:xi,onCloseRightSidebarFilePreview:hl,rightSidebarRepoPickerOpen:Je,rightSidebarRepoPickerCloseSignal:Vt,onOpenRightSidebarRepoPicker:Js,onCloseRightSidebarRepoPicker:Uo,markdownOutlineOpen:vt,markdownOutlineCloseSignal:Pt,onOpenMarkdownOutline:fa,onCloseMarkdownOutline:fl,markdownImageLightboxOpen:zt,markdownImageLightboxCloseSignal:me,onOpenMarkdownImageLightbox:pl,onCloseMarkdownImageLightbox:os})})]})]}),s.jsx(Yb,{sessionId:yt}),zl]}):s.jsxs(s.Fragment,{children:[Ul,s.jsx(Yb,{sessionId:yt}),zl]})}const RU=Object.freeze(Object.defineProperty({__proto__:null,default:P$},Symbol.toStringTag,{value:"Module"}));export{q$ as $,Xd as A,m0 as B,nF as C,GS as D,of as E,Ry as F,sF as G,Qc as H,Qy as I,uS as J,My as K,jy as L,_T as M,PT as N,r0 as O,UT as P,N6 as Q,gn as R,Ml as S,$m as T,CS as U,TI as V,zs as W,Oy as X,BS as Y,rh as Z,ZS as _,VS as a,G$ as a0,Gy as a1,Z$ as a2,K$ as a3,Y$ as a4,X3 as a5,EU as a6,Px as a7,l1 as a8,$f as a9,Wb as aa,Wy as ab,Oh as ac,F1 as ad,lC as ae,OO as af,V$ as ag,Ox as ah,qE as ai,Db as aj,Rm as ak,la as al,NU as am,Xy as an,cf as b,qF as c,RU as d,YS as e,Ly as f,kA as g,CA as h,Iy as i,Ny as j,h0 as k,RO as l,tT as m,f0 as n,oO as o,Ru as p,O1 as q,yT as r,ET as s,Dy as t,jT as u,By as v,YT as w,KT as x,JT as y,p0 as z};
|