termdock 1.4.330 → 1.4.331
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-JL8Fd8uO.js → App-xBkso5In.js} +6 -6
- package/dist/client/assets/App-xBkso5In.js.br +0 -0
- package/dist/client/assets/App-xBkso5In.js.gz +0 -0
- package/dist/client/assets/{ArchitecturePanel-CwvZXpvS.js → ArchitecturePanel-DNY0prqs.js} +2 -2
- package/dist/client/assets/ArchitecturePanel-DNY0prqs.js.br +0 -0
- package/dist/client/assets/ArchitecturePanel-DNY0prqs.js.gz +0 -0
- package/dist/client/assets/{ChangeWalkthroughPanel-BF3p_M6Y.js → ChangeWalkthroughPanel-xvUzbgKh.js} +1 -1
- package/dist/client/assets/ChangeWalkthroughPanel-xvUzbgKh.js.br +0 -0
- package/dist/client/assets/ChangeWalkthroughPanel-xvUzbgKh.js.gz +0 -0
- package/dist/client/assets/{CollaborationMainWorkspace-CYpn4j_x.js → CollaborationMainWorkspace-DsIWXeh0.js} +1 -1
- package/dist/client/assets/CollaborationMainWorkspace-DsIWXeh0.js.br +0 -0
- package/dist/client/assets/CollaborationMainWorkspace-DsIWXeh0.js.gz +0 -0
- package/dist/client/assets/CollaborationTaskContent-DatXl2k_.js +2 -0
- package/dist/client/assets/{ComputerControlView-DWlZmlCH.js → ComputerControlView-D-1UEmtr.js} +3 -3
- package/dist/client/assets/ComputerControlView-D-1UEmtr.js.br +0 -0
- package/dist/client/assets/ComputerControlView-D-1UEmtr.js.gz +0 -0
- package/dist/client/assets/{DagPlayground-IbzlcDVX.js → DagPlayground-1KaifMRo.js} +1 -1
- package/dist/client/assets/DagPlayground-1KaifMRo.js.br +0 -0
- package/dist/client/assets/DagPlayground-1KaifMRo.js.gz +0 -0
- package/dist/client/assets/{DiffLab-DEAYEwfY.js → DiffLab-Dh7lMk1W.js} +1 -1
- package/dist/client/assets/DiffLab-Dh7lMk1W.js.br +0 -0
- package/dist/client/assets/DiffLab-Dh7lMk1W.js.gz +0 -0
- package/dist/client/assets/{DiffReview-BPHfC8nZ.js → DiffReview-Bxe6OacV.js} +1 -1
- package/dist/client/assets/DiffReview-Bxe6OacV.js.br +0 -0
- package/dist/client/assets/DiffReview-Bxe6OacV.js.gz +0 -0
- package/dist/client/assets/{DiffReviewLab-2iKu20Ik.js → DiffReviewLab-CwdLf6kM.js} +1 -1
- package/dist/client/assets/DiffReviewLab-CwdLf6kM.js.br +0 -0
- package/dist/client/assets/DiffReviewLab-CwdLf6kM.js.gz +0 -0
- package/dist/client/assets/{DiffViewer-C4S3oEQV.js → DiffViewer-oGb-V3AK.js} +1 -1
- package/dist/client/assets/DiffViewer-oGb-V3AK.js.br +0 -0
- package/dist/client/assets/DiffViewer-oGb-V3AK.js.gz +0 -0
- package/dist/client/assets/{ModelPreview-D_KABt7i.js → ModelPreview-BTunplWr.js} +1 -1
- package/dist/client/assets/{ModelPreview-D_KABt7i.js.br → ModelPreview-BTunplWr.js.br} +0 -0
- package/dist/client/assets/ModelPreview-BTunplWr.js.gz +0 -0
- package/dist/client/assets/{RightSidebar-scaBEaFJ.js → RightSidebar-DvYmab8z.js} +3 -3
- package/dist/client/assets/RightSidebar-DvYmab8z.js.br +0 -0
- package/dist/client/assets/RightSidebar-DvYmab8z.js.gz +0 -0
- package/dist/client/assets/{abnfDiagram-VCTEODGH-OAQJcJ5a.js → abnfDiagram-VCTEODGH-D4LxQjpJ.js} +1 -1
- package/dist/client/assets/abnfDiagram-VCTEODGH-D4LxQjpJ.js.br +0 -0
- package/dist/client/assets/abnfDiagram-VCTEODGH-D4LxQjpJ.js.gz +0 -0
- package/dist/client/assets/app-A96wp9Xv.js +35 -0
- package/dist/client/assets/app-A96wp9Xv.js.br +0 -0
- package/dist/client/assets/app-A96wp9Xv.js.gz +0 -0
- package/dist/client/assets/{arc-B29HLhod.js → arc-BcCf73Fm.js} +1 -1
- package/dist/client/assets/arc-BcCf73Fm.js.br +0 -0
- package/dist/client/assets/arc-BcCf73Fm.js.gz +0 -0
- package/dist/client/assets/{architectureDiagram-5GKGNRK7-CQeKeLzl.js → architectureDiagram-5GKGNRK7-Dfg95GK6.js} +1 -1
- package/dist/client/assets/architectureDiagram-5GKGNRK7-Dfg95GK6.js.br +0 -0
- package/dist/client/assets/architectureDiagram-5GKGNRK7-Dfg95GK6.js.gz +0 -0
- package/dist/client/assets/{blockDiagram-I7D4REHJ-CgQQGQN_.js → blockDiagram-I7D4REHJ-BwXSp0xK.js} +1 -1
- package/dist/client/assets/blockDiagram-I7D4REHJ-BwXSp0xK.js.br +0 -0
- package/dist/client/assets/blockDiagram-I7D4REHJ-BwXSp0xK.js.gz +0 -0
- package/dist/client/assets/{c4Diagram-7LVT6UL2-BTeUIAS9.js → c4Diagram-7LVT6UL2-D4GfUedH.js} +1 -1
- package/dist/client/assets/c4Diagram-7LVT6UL2-D4GfUedH.js.br +0 -0
- package/dist/client/assets/c4Diagram-7LVT6UL2-D4GfUedH.js.gz +0 -0
- package/dist/client/assets/channel-k5dcS0_z.js +1 -0
- package/dist/client/assets/{chunk-2Q5K7J3B-Bao8D59Y.js → chunk-2Q5K7J3B-BqcmDKjo.js} +1 -1
- package/dist/client/assets/{chunk-5VM5RSS4-RIpn4ucJ.js → chunk-5VM5RSS4-BBV3_wnk.js} +1 -1
- package/dist/client/assets/{chunk-F27PBJKO-Cu3ypVNN.js → chunk-F27PBJKO-B-r7e040.js} +1 -1
- package/dist/client/assets/chunk-F27PBJKO-B-r7e040.js.br +0 -0
- package/dist/client/assets/chunk-F27PBJKO-B-r7e040.js.gz +0 -0
- package/dist/client/assets/{chunk-IMKFNOWR-BioTa0jG.js → chunk-IMKFNOWR-B83oWEy_.js} +1 -1
- package/dist/client/assets/chunk-IMKFNOWR-B83oWEy_.js.br +0 -0
- package/dist/client/assets/chunk-IMKFNOWR-B83oWEy_.js.gz +0 -0
- package/dist/client/assets/{chunk-JWPE2WC7-BPE5l-1s.js → chunk-JWPE2WC7-C2FW583q.js} +1 -1
- package/dist/client/assets/{chunk-POPQ4Y6H-DUF-0HB1.js → chunk-POPQ4Y6H-BWU7oLd-.js} +1 -1
- package/dist/client/assets/{chunk-SVP7TREG-BHaV6_ki.js → chunk-SVP7TREG-C5OgXymb.js} +1 -1
- package/dist/client/assets/chunk-SVP7TREG-C5OgXymb.js.br +0 -0
- package/dist/client/assets/chunk-SVP7TREG-C5OgXymb.js.gz +0 -0
- package/dist/client/assets/{chunk-TICWLB2K-SU15adqY.js → chunk-TICWLB2K-B1LlRwu4.js} +1 -1
- package/dist/client/assets/chunk-TICWLB2K-B1LlRwu4.js.br +0 -0
- package/dist/client/assets/chunk-TICWLB2K-B1LlRwu4.js.gz +0 -0
- package/dist/client/assets/{chunk-XXDRQBXY-oLy1dZJs.js → chunk-XXDRQBXY-7l9gcG6S.js} +1 -1
- package/dist/client/assets/classDiagram-ZZMXUADV-DQzBzWJL.js +1 -0
- package/dist/client/assets/classDiagram-v2-VYDZK3BY-DQzBzWJL.js +1 -0
- package/dist/client/assets/{cose-bilkent-JH36ORCC-EE27IbbX.js → cose-bilkent-JH36ORCC-DNBCyqkI.js} +1 -1
- package/dist/client/assets/{cose-bilkent-JH36ORCC-EE27IbbX.js.br → cose-bilkent-JH36ORCC-DNBCyqkI.js.br} +0 -0
- package/dist/client/assets/cose-bilkent-JH36ORCC-DNBCyqkI.js.gz +0 -0
- package/dist/client/assets/{cynefin-OW5HDTMX-CpY9J9iu.js → cynefin-OW5HDTMX-BiCAbJSv.js} +1 -1
- package/dist/client/assets/cynefin-OW5HDTMX-BiCAbJSv.js.br +0 -0
- package/dist/client/assets/cynefin-OW5HDTMX-BiCAbJSv.js.gz +0 -0
- package/dist/client/assets/{cynefinDiagram-5FMLGOSQ-mJxcQnkp.js → cynefinDiagram-5FMLGOSQ-CaRucQy9.js} +1 -1
- package/dist/client/assets/cynefinDiagram-5FMLGOSQ-CaRucQy9.js.br +0 -0
- package/dist/client/assets/cynefinDiagram-5FMLGOSQ-CaRucQy9.js.gz +0 -0
- package/dist/client/assets/{dagre-GXQ25YYZ-DAUZrxwq.js → dagre-GXQ25YYZ-kU4wdq9U.js} +1 -1
- package/dist/client/assets/dagre-GXQ25YYZ-kU4wdq9U.js.br +0 -0
- package/dist/client/assets/dagre-GXQ25YYZ-kU4wdq9U.js.gz +0 -0
- package/dist/client/assets/{diagram-S7CK7UJ4-3rquuCu6.js → diagram-S7CK7UJ4-BvDFZeQg.js} +1 -1
- package/dist/client/assets/diagram-S7CK7UJ4-BvDFZeQg.js.br +0 -0
- package/dist/client/assets/diagram-S7CK7UJ4-BvDFZeQg.js.gz +0 -0
- package/dist/client/assets/{diagram-UQ7AKVKN-CZWjaDbi.js → diagram-UQ7AKVKN-DYTly1n3.js} +1 -1
- package/dist/client/assets/diagram-UQ7AKVKN-DYTly1n3.js.br +0 -0
- package/dist/client/assets/diagram-UQ7AKVKN-DYTly1n3.js.gz +0 -0
- package/dist/client/assets/{diagram-VSXAHHWV-CNQEg3jR.js → diagram-VSXAHHWV-C0bMSg7N.js} +1 -1
- package/dist/client/assets/diagram-VSXAHHWV-C0bMSg7N.js.br +0 -0
- package/dist/client/assets/diagram-VSXAHHWV-C0bMSg7N.js.gz +0 -0
- package/dist/client/assets/{diagram-VX7I27RA-DYorDR1n.js → diagram-VX7I27RA-C9_Uoa7n.js} +1 -1
- package/dist/client/assets/diagram-VX7I27RA-C9_Uoa7n.js.br +0 -0
- package/dist/client/assets/diagram-VX7I27RA-C9_Uoa7n.js.gz +0 -0
- package/dist/client/assets/{diagram-Z3DM3KII-BPgvVftJ.js → diagram-Z3DM3KII-CLsF0k3J.js} +1 -1
- package/dist/client/assets/diagram-Z3DM3KII-CLsF0k3J.js.br +0 -0
- package/dist/client/assets/diagram-Z3DM3KII-CLsF0k3J.js.gz +0 -0
- package/dist/client/assets/{ebnfDiagram-PWID7BFC-KqpJv-fX.js → ebnfDiagram-PWID7BFC-Bt6b2Ygi.js} +1 -1
- package/dist/client/assets/ebnfDiagram-PWID7BFC-Bt6b2Ygi.js.br +0 -0
- package/dist/client/assets/ebnfDiagram-PWID7BFC-Bt6b2Ygi.js.gz +0 -0
- package/dist/client/assets/{erDiagram-RLTQ6QDP-Bwj_TPoi.js → erDiagram-RLTQ6QDP-Bs5jB7E2.js} +1 -1
- package/dist/client/assets/erDiagram-RLTQ6QDP-Bs5jB7E2.js.br +0 -0
- package/dist/client/assets/erDiagram-RLTQ6QDP-Bs5jB7E2.js.gz +0 -0
- package/dist/client/assets/{flowDiagram-HODETNUW-BYALZ5I6.js → flowDiagram-HODETNUW-BCSeo8DJ.js} +1 -1
- package/dist/client/assets/flowDiagram-HODETNUW-BCSeo8DJ.js.br +0 -0
- package/dist/client/assets/flowDiagram-HODETNUW-BCSeo8DJ.js.gz +0 -0
- package/dist/client/assets/{ganttDiagram-EL5Y4UJY-DwrR8yW_.js → ganttDiagram-EL5Y4UJY-BnCBe-Ue.js} +1 -1
- package/dist/client/assets/ganttDiagram-EL5Y4UJY-BnCBe-Ue.js.br +0 -0
- package/dist/client/assets/ganttDiagram-EL5Y4UJY-BnCBe-Ue.js.gz +0 -0
- package/dist/client/assets/{gestureArbiter-4NWfZprH.js → gestureArbiter-W1Lo4NZw.js} +1 -1
- package/dist/client/assets/gestureArbiter-W1Lo4NZw.js.br +0 -0
- package/dist/client/assets/gestureArbiter-W1Lo4NZw.js.gz +0 -0
- package/dist/client/assets/{gitGraphDiagram-WWUBYQGX-C3pH5ZGR.js → gitGraphDiagram-WWUBYQGX-C7BJXlkD.js} +1 -1
- package/dist/client/assets/gitGraphDiagram-WWUBYQGX-C7BJXlkD.js.br +0 -0
- package/dist/client/assets/gitGraphDiagram-WWUBYQGX-C7BJXlkD.js.gz +0 -0
- package/dist/client/assets/{infoDiagram-27XIBGKW-DpnbClE9.js → infoDiagram-27XIBGKW-CJXzvnav.js} +1 -1
- package/dist/client/assets/{ishikawaDiagram-5VMMS53U-BFhiY6uy.js → ishikawaDiagram-5VMMS53U-BoBCZ1Wa.js} +1 -1
- package/dist/client/assets/ishikawaDiagram-5VMMS53U-BoBCZ1Wa.js.br +0 -0
- package/dist/client/assets/ishikawaDiagram-5VMMS53U-BoBCZ1Wa.js.gz +0 -0
- package/dist/client/assets/{journeyDiagram-3NMN7TZE-Beg2Cmg4.js → journeyDiagram-3NMN7TZE-C5bywqIt.js} +1 -1
- package/dist/client/assets/journeyDiagram-3NMN7TZE-C5bywqIt.js.br +0 -0
- package/dist/client/assets/journeyDiagram-3NMN7TZE-C5bywqIt.js.gz +0 -0
- package/dist/client/assets/{kanban-definition-UXKFOSKX-CNb51-_F.js → kanban-definition-UXKFOSKX-ChHpoQyu.js} +1 -1
- package/dist/client/assets/kanban-definition-UXKFOSKX-ChHpoQyu.js.br +0 -0
- package/dist/client/assets/kanban-definition-UXKFOSKX-ChHpoQyu.js.gz +0 -0
- package/dist/client/assets/{layout-B07GM-uc.js → layout-e7M-xuok.js} +1 -1
- package/dist/client/assets/layout-e7M-xuok.js.br +0 -0
- package/dist/client/assets/layout-e7M-xuok.js.gz +0 -0
- package/dist/client/assets/{linear-DRJlaLbJ.js → linear-A5CrihlL.js} +1 -1
- package/dist/client/assets/linear-A5CrihlL.js.br +0 -0
- package/dist/client/assets/linear-A5CrihlL.js.gz +0 -0
- package/dist/client/assets/{mermaid.core-BySznxI_.js → mermaid.core-BNac_Y3z.js} +5 -5
- package/dist/client/assets/mermaid.core-BNac_Y3z.js.br +0 -0
- package/dist/client/assets/{mermaid.core-BySznxI_.js.gz → mermaid.core-BNac_Y3z.js.gz} +0 -0
- package/dist/client/assets/{mindmap-definition-YA3MSWOX-BtStMFHK.js → mindmap-definition-YA3MSWOX-fQoEGcCr.js} +1 -1
- package/dist/client/assets/mindmap-definition-YA3MSWOX-fQoEGcCr.js.br +0 -0
- package/dist/client/assets/mindmap-definition-YA3MSWOX-fQoEGcCr.js.gz +0 -0
- package/dist/client/assets/{passwordBootstrap-B-T8YSfQ.js → passwordBootstrap--0YoOXsx.js} +1 -1
- package/dist/client/assets/passwordBootstrap--0YoOXsx.js.br +0 -0
- package/dist/client/assets/passwordBootstrap--0YoOXsx.js.gz +0 -0
- package/dist/client/assets/{pegDiagram-XKGWAZYB-BNJzxFGK.js → pegDiagram-XKGWAZYB-CYbfla8A.js} +1 -1
- package/dist/client/assets/pegDiagram-XKGWAZYB-CYbfla8A.js.br +0 -0
- package/dist/client/assets/pegDiagram-XKGWAZYB-CYbfla8A.js.gz +0 -0
- package/dist/client/assets/{pieDiagram-E7YTZNPT-Df1Y6zou.js → pieDiagram-E7YTZNPT-B6--ZKXC.js} +1 -1
- package/dist/client/assets/pieDiagram-E7YTZNPT-B6--ZKXC.js.br +0 -0
- package/dist/client/assets/pieDiagram-E7YTZNPT-B6--ZKXC.js.gz +0 -0
- package/dist/client/assets/{quadrantDiagram-AXDQQJYC-Q3jN6--F.js → quadrantDiagram-AXDQQJYC-Bau_h7Jl.js} +1 -1
- package/dist/client/assets/quadrantDiagram-AXDQQJYC-Bau_h7Jl.js.br +0 -0
- package/dist/client/assets/quadrantDiagram-AXDQQJYC-Bau_h7Jl.js.gz +0 -0
- package/dist/client/assets/{railroadDiagram-O6MQD6OU-c-1SN7pC.js → railroadDiagram-O6MQD6OU-CApEuiEL.js} +1 -1
- package/dist/client/assets/railroadDiagram-O6MQD6OU-CApEuiEL.js.br +0 -0
- package/dist/client/assets/railroadDiagram-O6MQD6OU-CApEuiEL.js.gz +0 -0
- package/dist/client/assets/{rdpSession-B6j6_C4D.js → rdpSession-CydBq1bk.js} +1 -1
- package/dist/client/assets/rdpSession-CydBq1bk.js.br +0 -0
- package/dist/client/assets/rdpSession-CydBq1bk.js.gz +0 -0
- package/dist/client/assets/{referenceLongPress-Bln9X6SW.js → referenceLongPress-8ExgTbB3.js} +1 -1
- package/dist/client/assets/referenceLongPress-8ExgTbB3.js.br +0 -0
- package/dist/client/assets/referenceLongPress-8ExgTbB3.js.gz +0 -0
- package/dist/client/assets/{requirementDiagram-BXWQKSXE-wcsUZu82.js → requirementDiagram-BXWQKSXE-Rxe80d7j.js} +1 -1
- package/dist/client/assets/requirementDiagram-BXWQKSXE-Rxe80d7j.js.br +0 -0
- package/dist/client/assets/requirementDiagram-BXWQKSXE-Rxe80d7j.js.gz +0 -0
- package/dist/client/assets/{sankeyDiagram-P5KCCOFB-CfXyROPC.js → sankeyDiagram-P5KCCOFB-BaPl8d6E.js} +1 -1
- package/dist/client/assets/sankeyDiagram-P5KCCOFB-BaPl8d6E.js.br +0 -0
- package/dist/client/assets/sankeyDiagram-P5KCCOFB-BaPl8d6E.js.gz +0 -0
- package/dist/client/assets/{sequenceDiagram-WJ2MYXX4-D-IasKbj.js → sequenceDiagram-WJ2MYXX4-Asyx5gWK.js} +1 -1
- package/dist/client/assets/sequenceDiagram-WJ2MYXX4-Asyx5gWK.js.br +0 -0
- package/dist/client/assets/sequenceDiagram-WJ2MYXX4-Asyx5gWK.js.gz +0 -0
- package/dist/client/assets/{sizeCapture-INFHLROL-Cyoh7jyx.js → sizeCapture-INFHLROL-BQaSglof.js} +1 -1
- package/dist/client/assets/sizeCapture-INFHLROL-BQaSglof.js.br +0 -0
- package/dist/client/assets/sizeCapture-INFHLROL-BQaSglof.js.gz +0 -0
- package/dist/client/assets/{sparkles-kooHQYLJ.js → sparkles-BMR6NziM.js} +1 -1
- package/dist/client/assets/{stateDiagram-D77RDMKH-BFeLYGOW.js → stateDiagram-D77RDMKH-DycNNggj.js} +1 -1
- package/dist/client/assets/stateDiagram-D77RDMKH-DycNNggj.js.br +0 -0
- package/dist/client/assets/stateDiagram-D77RDMKH-DycNNggj.js.gz +0 -0
- package/dist/client/assets/stateDiagram-v2-MP3YSRHH-CS1AgP_n.js +1 -0
- package/dist/client/assets/{swimlanes-42K2YHIH-BtMhgPB2.js → swimlanes-42K2YHIH-2Z5Zd5j6.js} +1 -1
- package/dist/client/assets/swimlanes-42K2YHIH-2Z5Zd5j6.js.br +0 -0
- package/dist/client/assets/swimlanes-42K2YHIH-2Z5Zd5j6.js.gz +0 -0
- package/dist/client/assets/swimlanesDiagram-VR7AAH4N-Cxqp7K9j.js +8 -0
- package/dist/client/assets/{timeline-definition-24CTP7MA-BccUO5W0.js → timeline-definition-24CTP7MA-BHiRARcP.js} +1 -1
- package/dist/client/assets/timeline-definition-24CTP7MA-BHiRARcP.js.br +0 -0
- package/dist/client/assets/timeline-definition-24CTP7MA-BHiRARcP.js.gz +0 -0
- package/dist/client/assets/{triangle-alert-rgLWcpfP.js → triangle-alert-TsfoVQJR.js} +1 -1
- package/dist/client/assets/{vennDiagram-4TSXK5OY-hNN_O594.js → vennDiagram-4TSXK5OY-JgKZ8N2y.js} +1 -1
- package/dist/client/assets/vennDiagram-4TSXK5OY-JgKZ8N2y.js.br +0 -0
- package/dist/client/assets/vennDiagram-4TSXK5OY-JgKZ8N2y.js.gz +0 -0
- package/dist/client/assets/{videoCompression-DS0r00L6.js → videoCompression-DGfMcwdq.js} +1 -1
- package/dist/client/assets/videoCompression-DGfMcwdq.js.br +0 -0
- package/dist/client/assets/videoCompression-DGfMcwdq.js.gz +0 -0
- package/dist/client/assets/{wardleyDiagram-VM6X3IG4-C6h02bPv.js → wardleyDiagram-VM6X3IG4-DNmP9dmD.js} +1 -1
- package/dist/client/assets/wardleyDiagram-VM6X3IG4-DNmP9dmD.js.br +0 -0
- package/dist/client/assets/wardleyDiagram-VM6X3IG4-DNmP9dmD.js.gz +0 -0
- package/dist/client/assets/{xychartDiagram-S5SC5T6Z-DvNnLmXs.js → xychartDiagram-S5SC5T6Z-BBFR9gmo.js} +1 -1
- package/dist/client/assets/xychartDiagram-S5SC5T6Z-BBFR9gmo.js.br +0 -0
- package/dist/client/assets/xychartDiagram-S5SC5T6Z-BBFR9gmo.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-encrypted-background.js +1 -1
- package/dist/client/sw-encrypted-background.js.br +0 -0
- package/dist/client/sw-encrypted-background.js.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/collaborationPeerTransport.js +2 -1
- package/dist/server/federation/relay.js +121 -37
- package/dist/server/federation/streamLimits.js +5 -0
- package/package.json +1 -1
- package/runtime-manifest.json +3 -3
- package/dist/client/assets/App-JL8Fd8uO.js.br +0 -0
- package/dist/client/assets/App-JL8Fd8uO.js.gz +0 -0
- package/dist/client/assets/ArchitecturePanel-CwvZXpvS.js.br +0 -0
- package/dist/client/assets/ArchitecturePanel-CwvZXpvS.js.gz +0 -0
- package/dist/client/assets/ChangeWalkthroughPanel-BF3p_M6Y.js.br +0 -0
- package/dist/client/assets/ChangeWalkthroughPanel-BF3p_M6Y.js.gz +0 -0
- package/dist/client/assets/CollaborationMainWorkspace-CYpn4j_x.js.br +0 -0
- package/dist/client/assets/CollaborationMainWorkspace-CYpn4j_x.js.gz +0 -0
- package/dist/client/assets/CollaborationTaskContent-BjjX05Cv.js +0 -2
- package/dist/client/assets/ComputerControlView-DWlZmlCH.js.br +0 -0
- package/dist/client/assets/ComputerControlView-DWlZmlCH.js.gz +0 -0
- package/dist/client/assets/DagPlayground-IbzlcDVX.js.br +0 -0
- package/dist/client/assets/DagPlayground-IbzlcDVX.js.gz +0 -0
- package/dist/client/assets/DiffLab-DEAYEwfY.js.br +0 -0
- package/dist/client/assets/DiffLab-DEAYEwfY.js.gz +0 -0
- package/dist/client/assets/DiffReview-BPHfC8nZ.js.br +0 -0
- package/dist/client/assets/DiffReview-BPHfC8nZ.js.gz +0 -0
- package/dist/client/assets/DiffReviewLab-2iKu20Ik.js.br +0 -0
- package/dist/client/assets/DiffReviewLab-2iKu20Ik.js.gz +0 -0
- package/dist/client/assets/DiffViewer-C4S3oEQV.js.br +0 -0
- package/dist/client/assets/DiffViewer-C4S3oEQV.js.gz +0 -0
- package/dist/client/assets/ModelPreview-D_KABt7i.js.gz +0 -0
- package/dist/client/assets/RightSidebar-scaBEaFJ.js.br +0 -0
- package/dist/client/assets/RightSidebar-scaBEaFJ.js.gz +0 -0
- package/dist/client/assets/abnfDiagram-VCTEODGH-OAQJcJ5a.js.br +0 -0
- package/dist/client/assets/abnfDiagram-VCTEODGH-OAQJcJ5a.js.gz +0 -0
- package/dist/client/assets/app-aNkllBsm.js +0 -35
- package/dist/client/assets/app-aNkllBsm.js.br +0 -0
- package/dist/client/assets/app-aNkllBsm.js.gz +0 -0
- package/dist/client/assets/arc-B29HLhod.js.br +0 -0
- package/dist/client/assets/arc-B29HLhod.js.gz +0 -0
- package/dist/client/assets/architectureDiagram-5GKGNRK7-CQeKeLzl.js.br +0 -0
- package/dist/client/assets/architectureDiagram-5GKGNRK7-CQeKeLzl.js.gz +0 -0
- package/dist/client/assets/blockDiagram-I7D4REHJ-CgQQGQN_.js.br +0 -0
- package/dist/client/assets/blockDiagram-I7D4REHJ-CgQQGQN_.js.gz +0 -0
- package/dist/client/assets/c4Diagram-7LVT6UL2-BTeUIAS9.js.br +0 -0
- package/dist/client/assets/c4Diagram-7LVT6UL2-BTeUIAS9.js.gz +0 -0
- package/dist/client/assets/channel-DPAqeRss.js +0 -1
- package/dist/client/assets/chunk-F27PBJKO-Cu3ypVNN.js.br +0 -0
- package/dist/client/assets/chunk-F27PBJKO-Cu3ypVNN.js.gz +0 -0
- package/dist/client/assets/chunk-IMKFNOWR-BioTa0jG.js.br +0 -0
- package/dist/client/assets/chunk-IMKFNOWR-BioTa0jG.js.gz +0 -0
- package/dist/client/assets/chunk-SVP7TREG-BHaV6_ki.js.br +0 -0
- package/dist/client/assets/chunk-SVP7TREG-BHaV6_ki.js.gz +0 -0
- package/dist/client/assets/chunk-TICWLB2K-SU15adqY.js.br +0 -0
- package/dist/client/assets/chunk-TICWLB2K-SU15adqY.js.gz +0 -0
- package/dist/client/assets/classDiagram-ZZMXUADV-kQeU2Z7d.js +0 -1
- package/dist/client/assets/classDiagram-v2-VYDZK3BY-kQeU2Z7d.js +0 -1
- package/dist/client/assets/cose-bilkent-JH36ORCC-EE27IbbX.js.gz +0 -0
- package/dist/client/assets/cynefin-OW5HDTMX-CpY9J9iu.js.br +0 -0
- package/dist/client/assets/cynefin-OW5HDTMX-CpY9J9iu.js.gz +0 -0
- package/dist/client/assets/cynefinDiagram-5FMLGOSQ-mJxcQnkp.js.br +0 -0
- package/dist/client/assets/cynefinDiagram-5FMLGOSQ-mJxcQnkp.js.gz +0 -0
- package/dist/client/assets/dagre-GXQ25YYZ-DAUZrxwq.js.br +0 -0
- package/dist/client/assets/dagre-GXQ25YYZ-DAUZrxwq.js.gz +0 -0
- package/dist/client/assets/diagram-S7CK7UJ4-3rquuCu6.js.br +0 -0
- package/dist/client/assets/diagram-S7CK7UJ4-3rquuCu6.js.gz +0 -0
- package/dist/client/assets/diagram-UQ7AKVKN-CZWjaDbi.js.br +0 -0
- package/dist/client/assets/diagram-UQ7AKVKN-CZWjaDbi.js.gz +0 -0
- package/dist/client/assets/diagram-VSXAHHWV-CNQEg3jR.js.br +0 -0
- package/dist/client/assets/diagram-VSXAHHWV-CNQEg3jR.js.gz +0 -0
- package/dist/client/assets/diagram-VX7I27RA-DYorDR1n.js.br +0 -0
- package/dist/client/assets/diagram-VX7I27RA-DYorDR1n.js.gz +0 -0
- package/dist/client/assets/diagram-Z3DM3KII-BPgvVftJ.js.br +0 -0
- package/dist/client/assets/diagram-Z3DM3KII-BPgvVftJ.js.gz +0 -0
- package/dist/client/assets/ebnfDiagram-PWID7BFC-KqpJv-fX.js.br +0 -0
- package/dist/client/assets/ebnfDiagram-PWID7BFC-KqpJv-fX.js.gz +0 -0
- package/dist/client/assets/erDiagram-RLTQ6QDP-Bwj_TPoi.js.br +0 -0
- package/dist/client/assets/erDiagram-RLTQ6QDP-Bwj_TPoi.js.gz +0 -0
- package/dist/client/assets/flowDiagram-HODETNUW-BYALZ5I6.js.br +0 -0
- package/dist/client/assets/flowDiagram-HODETNUW-BYALZ5I6.js.gz +0 -0
- package/dist/client/assets/ganttDiagram-EL5Y4UJY-DwrR8yW_.js.br +0 -0
- package/dist/client/assets/ganttDiagram-EL5Y4UJY-DwrR8yW_.js.gz +0 -0
- package/dist/client/assets/gestureArbiter-4NWfZprH.js.br +0 -0
- package/dist/client/assets/gestureArbiter-4NWfZprH.js.gz +0 -0
- package/dist/client/assets/gitGraphDiagram-WWUBYQGX-C3pH5ZGR.js.br +0 -0
- package/dist/client/assets/gitGraphDiagram-WWUBYQGX-C3pH5ZGR.js.gz +0 -0
- package/dist/client/assets/ishikawaDiagram-5VMMS53U-BFhiY6uy.js.br +0 -0
- package/dist/client/assets/ishikawaDiagram-5VMMS53U-BFhiY6uy.js.gz +0 -0
- package/dist/client/assets/journeyDiagram-3NMN7TZE-Beg2Cmg4.js.br +0 -0
- package/dist/client/assets/journeyDiagram-3NMN7TZE-Beg2Cmg4.js.gz +0 -0
- package/dist/client/assets/kanban-definition-UXKFOSKX-CNb51-_F.js.br +0 -0
- package/dist/client/assets/kanban-definition-UXKFOSKX-CNb51-_F.js.gz +0 -0
- package/dist/client/assets/layout-B07GM-uc.js.br +0 -0
- package/dist/client/assets/layout-B07GM-uc.js.gz +0 -0
- package/dist/client/assets/linear-DRJlaLbJ.js.br +0 -0
- package/dist/client/assets/linear-DRJlaLbJ.js.gz +0 -0
- package/dist/client/assets/mermaid.core-BySznxI_.js.br +0 -0
- package/dist/client/assets/mindmap-definition-YA3MSWOX-BtStMFHK.js.br +0 -0
- package/dist/client/assets/mindmap-definition-YA3MSWOX-BtStMFHK.js.gz +0 -0
- package/dist/client/assets/passwordBootstrap-B-T8YSfQ.js.br +0 -0
- package/dist/client/assets/passwordBootstrap-B-T8YSfQ.js.gz +0 -0
- package/dist/client/assets/pegDiagram-XKGWAZYB-BNJzxFGK.js.br +0 -0
- package/dist/client/assets/pegDiagram-XKGWAZYB-BNJzxFGK.js.gz +0 -0
- package/dist/client/assets/pieDiagram-E7YTZNPT-Df1Y6zou.js.br +0 -0
- package/dist/client/assets/pieDiagram-E7YTZNPT-Df1Y6zou.js.gz +0 -0
- package/dist/client/assets/quadrantDiagram-AXDQQJYC-Q3jN6--F.js.br +0 -0
- package/dist/client/assets/quadrantDiagram-AXDQQJYC-Q3jN6--F.js.gz +0 -0
- package/dist/client/assets/railroadDiagram-O6MQD6OU-c-1SN7pC.js.br +0 -0
- package/dist/client/assets/railroadDiagram-O6MQD6OU-c-1SN7pC.js.gz +0 -0
- package/dist/client/assets/rdpSession-B6j6_C4D.js.br +0 -0
- package/dist/client/assets/rdpSession-B6j6_C4D.js.gz +0 -0
- package/dist/client/assets/referenceLongPress-Bln9X6SW.js.br +0 -0
- package/dist/client/assets/referenceLongPress-Bln9X6SW.js.gz +0 -0
- package/dist/client/assets/requirementDiagram-BXWQKSXE-wcsUZu82.js.br +0 -0
- package/dist/client/assets/requirementDiagram-BXWQKSXE-wcsUZu82.js.gz +0 -0
- package/dist/client/assets/sankeyDiagram-P5KCCOFB-CfXyROPC.js.br +0 -0
- package/dist/client/assets/sankeyDiagram-P5KCCOFB-CfXyROPC.js.gz +0 -0
- package/dist/client/assets/sequenceDiagram-WJ2MYXX4-D-IasKbj.js.br +0 -0
- package/dist/client/assets/sequenceDiagram-WJ2MYXX4-D-IasKbj.js.gz +0 -0
- package/dist/client/assets/sizeCapture-INFHLROL-Cyoh7jyx.js.br +0 -0
- package/dist/client/assets/sizeCapture-INFHLROL-Cyoh7jyx.js.gz +0 -0
- package/dist/client/assets/stateDiagram-D77RDMKH-BFeLYGOW.js.br +0 -0
- package/dist/client/assets/stateDiagram-D77RDMKH-BFeLYGOW.js.gz +0 -0
- package/dist/client/assets/stateDiagram-v2-MP3YSRHH-Cn5inEsZ.js +0 -1
- package/dist/client/assets/swimlanes-42K2YHIH-BtMhgPB2.js.br +0 -0
- package/dist/client/assets/swimlanes-42K2YHIH-BtMhgPB2.js.gz +0 -0
- package/dist/client/assets/swimlanesDiagram-VR7AAH4N-Di2Vfydj.js +0 -8
- package/dist/client/assets/timeline-definition-24CTP7MA-BccUO5W0.js.br +0 -0
- package/dist/client/assets/timeline-definition-24CTP7MA-BccUO5W0.js.gz +0 -0
- package/dist/client/assets/vennDiagram-4TSXK5OY-hNN_O594.js.br +0 -0
- package/dist/client/assets/vennDiagram-4TSXK5OY-hNN_O594.js.gz +0 -0
- package/dist/client/assets/videoCompression-DS0r00L6.js.br +0 -0
- package/dist/client/assets/videoCompression-DS0r00L6.js.gz +0 -0
- package/dist/client/assets/wardleyDiagram-VM6X3IG4-C6h02bPv.js.br +0 -0
- package/dist/client/assets/wardleyDiagram-VM6X3IG4-C6h02bPv.js.gz +0 -0
- package/dist/client/assets/xychartDiagram-S5SC5T6Z-DvNnLmXs.js.br +0 -0
- package/dist/client/assets/xychartDiagram-S5SC5T6Z-DvNnLmXs.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{ah as Ht,aP as cd,b8 as ea,bA as s,ad as vc,df as Hr,H as p8,dq as ml,db as ja,dd as ns,b3 as wc,a7 as mh,aB as Uy,br as eg,cQ as m8,C as ai,X as Mn,cG as zy,dc as W0,cA as Hc,j as _0,ag as ed,cq as Pp,cZ as g8,au as Fu,bz as Bu,g as x8,ak as wl,cL as Xh,Z as b8,bd as r1,bK as n1,az as y8,cj as v8,a5 as Hy,ch as w8,cE as Wy,ab as A8,ai as T8,L as jn,f as S8,d as Al,bi as C8,b2 as s1,dh as _8,dm as Vr,bI as tg,dl as Vt,aF as k8,dv as L8,v as I8,bP as E8,c2 as N8,a4 as Ma,bT as R8,cC as Tx,cD as Sx,cF as Cx,W as _x,c1 as M8,cR as j8,t as x0,bq as rg,da as D8,_ as Vc,bb as B8,i as Q8,dp as Gy,b0 as gl,T as Zo,dg as eu,dk as P8,ck as O8,cS as F8,ap as $8,a_ as U8,b$ as z8,c0 as H8,P as Vy,V as kx,bQ as Lx,bC as qy,n as Zs,$ as Jh,c$ as Op,bJ as W8,cm as G8,bH as Yy,cw as Ki,dj as V8,bh as Vo,ds as q8,B as xc,e as Ys,u as Y8,o as $u,am as Z8,N as i1,cx as K8,h as Io,bv as X8,bw as J8,ar as Zy,aD as Ky,a6 as Uu,m as qu,cu as Hl,c4 as Xy,ay as b0,c as ef,de as Jy,aL as e9,S as k0,bo as wf,a as e3,at as t9,af as r9,d8 as n9,c5 as td,a9 as bc,bG as Ix,cB as s9,c9 as t3,cW as i9,cY as r3,bD as a9,bF as ng,cJ as o9,cK as l9,c6 as c9,cH as u9,cr as d9,co as h9,cl as f9,c8 as p9,cy as m9,bS as g9,bR as n3,ct as x9,cI as b9,bE as Ex,aJ as y9,b1 as v9,D as w9,aI as Nx,bM as A9,p as T9,bO as S9,q as C9,F as _9,a8 as k9,c7 as L9,l as I9,cz as E9,r as N9,c3 as R9,aw as M9,aC as j9,aE as D9,bc as Ld,bm as B9,d5 as Q9,bn as P9,aq as O9,d7 as F9,Q as $9,al as U9,ae as z9,A as H9,ba as W9,as as G9,M as V9,dn as q9,bV as Rc,b7 as Y9,b4 as Z9,b5 as K9,b6 as X9,aY as Fp,bW as J9,cd as eA,cn as tA,b9 as rA,a$ as nA,cX as Rx,ao as sA,Y as iA,d3 as aA,dt as qn,bU as oA,w as lA,cU as cA,aX as uA,be as Mx,cc as dA,cP as gh,d2 as Id,d6 as hA,ce as fA,cV as pA,cM as mA,d1 as $p,cN as gA,cO as xA,di as bA,an as yA,bL as vA,by as xh,bx as wA,ca as jx,cf as AA,cb as vu,cg as TA,a3 as SA,ac as CA,s as _A,aa as kA}from"./app-aNkllBsm.js";import{b,R as _,r as Ks,a as LA}from"./dnd-BCFAPC0L.js";import{b as IA,c as EA,F as tu,S as NA,e as RA,h as MA,r as jA,y as DA,d as BA,u as QA}from"./gestureArbiter-4NWfZprH.js";import{L as PA,l as OA}from"./terminal-C7X98Amf.js";import{T as sg,L as rd,C as L0,M as FA,G as $A}from"./triangle-alert-rgLWcpfP.js";import{r as UA}from"./react-XDCjal2T.js";import{u as ig,G as zA}from"./referenceLongPress-Bln9X6SW.js";const HA=[["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"}]],Af=Ht("archive",HA);const WA=[["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"}]],GA=Ht("arrow-down-a-z",WA);const VA=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],qA=Ht("arrow-down",VA);const YA=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],s3=Ht("arrow-up",YA);const ZA=[["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"}]],i3=Ht("bell",ZA);const KA=[["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"}]],G0=Ht("bot",KA);const XA=[["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"}]],JA=Ht("box",XA);const eT=[["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"}]],tT=Ht("cable",eT);const rT=[["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"}]],nT=Ht("calendar-clock",rT);const sT=[["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"}]],iT=Ht("camera",sT);const aT=[["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"}]],oT=Ht("chart-bar",aT);const lT=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],cT=Ht("circle-dot",lT);const uT=[["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"}]],Tf=Ht("circle-question-mark",uT);const dT=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],V0=Ht("circle",dT);const hT=[["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"}]],fT=Ht("clipboard-paste",hT);const pT=[["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"}]],a3=Ht("clipboard",pT);const mT=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6h4",key:"135r8i"}]],I0=Ht("clock-3",mT);const gT=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],xT=Ht("clock",gT);const bT=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],yT=Ht("code",bT);const vT=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 3v18",key:"108xh3"}]],Fl=Ht("columns-2",vT);const wT=[["path",{d:"M20 4v7a4 4 0 0 1-4 4H4",key:"6o5b7l"}],["path",{d:"m9 10-5 5 5 5",key:"1kshq7"}]],AT=Ht("corner-down-left",wT);const TT=[["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"}]],E0=Ht("download",TT);const ST=[["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"}]],qc=Ht("external-link",ST);const CT=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}]],_T=Ht("file-code",CT);const kT=[["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"}]],LT=Ht("file-up",kT);const IT=[["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"}]],o3=Ht("file",IT);const ET=[["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"}]],Yu=Ht("folder-open",ET);const NT=[["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"}]],ag=Ht("folder-search",NT);const RT=[["path",{d:"M20 10a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1h-2.5a1 1 0 0 1-.8-.4l-.9-1.2A1 1 0 0 0 15 3h-2a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",key:"hod4my"}],["path",{d:"M20 21a1 1 0 0 0 1-1v-3a1 1 0 0 0-1-1h-2.9a1 1 0 0 1-.88-.55l-.42-.85a1 1 0 0 0-.92-.6H13a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",key:"w4yl2u"}],["path",{d:"M3 5a2 2 0 0 0 2 2h3",key:"f2jnh7"}],["path",{d:"M3 3v13a2 2 0 0 0 2 2h3",key:"k8epm1"}]],MT=Ht("folder-tree",RT);const jT=[["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"}]],Dx=Ht("grid-2x2",jT);const DT=[["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"}]],sp=Ht("grip-vertical",DT);const BT=[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]],QT=Ht("hash",BT);const PT=[["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"}]],Wc=Ht("history",PT);const OT=[["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"}]],FT=Ht("house",OT);const $T=[["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"}]],l3=Ht("keyboard",$T);const UT=[["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"}]],c3=Ht("layers",UT);const zT=[["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"}]],HT=Ht("layout-dashboard",zT);const WT=[["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"}]],ru=Ht("layout-grid",WT);const GT=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],VT=Ht("loader-circle",GT);const qT=[["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"}]],YT=Ht("maximize",qT);const ZT=[["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"}]],ud=Ht("message-circle",ZT);const KT=[["path",{d:"M5 12h14",key:"1ays0h"}]],u3=Ht("minus",KT);const XT=[["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"}]],JT=Ht("minimize",XT);const eS=[["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"}]],tS=Ht("monitor-smartphone",eS);const rS=[["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"}]],nS=Ht("moon",rS);const sS=[["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"}]],iS=Ht("move",sS);const aS=[["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"}]],oS=Ht("network",aS);const lS=[["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"}]],cS=Ht("panel-right-close",lS);const uS=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],dS=Ht("panel-left",uS);const hS=[["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"}]],fS=Ht("panel-right-open",hS);const pS=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],d3=Ht("panel-right",pS);const mS=[["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"}]],gS=Ht("paperclip",mS);const xS=[["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"}]],bS=Ht("pause",xS);const yS=[["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"}]],vS=Ht("pen-line",yS);const wS=[["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"}]],AS=Ht("pencil-line",wS);const TS=[["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"}]],N0=Ht("pin",TS);const SS=[["path",{d:"M12 17v5",key:"bb1du9"}],["path",{d:"M15 9.34V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H7.89",key:"znwnzq"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M9 9v1.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h11",key:"c9qhm2"}]],R0=Ht("pin-off",SS);const CS=[["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"}]],Sf=Ht("play",CS);const _S=[["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"}]],kS=Ht("plug",_S);const LS=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],IS=Ht("power",LS);const ES=[["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"}]],wn=Ht("refresh-cw",ES);const NS=[["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"}]],h3=Ht("rotate-ccw",NS);const RS=[["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"}]],MS=Ht("rotate-cw",RS);const jS=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 12h18",key:"1i2n21"}]],Bx=Ht("rows-2",jS);const DS=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Wl=Ht("search",DS);const BS=[["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"}]],y0=Ht("send",BS);const QS=[["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"}]],f3=Ht("settings",QS);const PS=[["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"}]],OS=Ht("shield-alert",PS);const FS=[["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"}]],$S=Ht("shield-check",FS);const US=[["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"}]],a1=Ht("sliders-horizontal",US);const zS=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],p3=Ht("square",zS);const HS=[["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"}]],WS=Ht("stethoscope",HS);const GS=[["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"}]],VS=Ht("sun",GS);const qS=[["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"}]],Ds=Ht("trash-2",qS);const YS=[["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"}]],ZS=Ht("type",YS);const KS=[["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"}]],XS=Ht("unlink",KS);const JS=[["path",{d:"m19 5 3-3",key:"yk6iyv"}],["path",{d:"m2 22 3-3",key:"19mgm9"}],["path",{d:"M6.3 20.3a2.4 2.4 0 0 0 3.4 0L12 18l-6-6-2.3 2.3a2.4 2.4 0 0 0 0 3.4Z",key:"goz73y"}],["path",{d:"M7.5 13.5 10 11",key:"7xgeeb"}],["path",{d:"M10.5 16.5 13 14",key:"10btkg"}],["path",{d:"m12 6 6 6 2.3-2.3a2.4 2.4 0 0 0 0-3.4l-2.6-2.6a2.4 2.4 0 0 0-3.4 0Z",key:"1snsnr"}]],m3=Ht("unplug",JS);const eC=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],tC=Ht("upload",eC);const rC=[["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"}]],g3=Ht("video",rC);const nC=[["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"}]],sC=Ht("volume-1",nC);const iC=[["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"}]],aC=Ht("volume-2",iC);const oC=[["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"}]],lC=Ht("wand-sparkles",oC);const cC=[["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"}]],Up=Ht("workflow",cC);function uC(e,t){return e==="webgl"&&t}function x3(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 f=a.get(d);f||(f={key:d,label:d?cd(d)??d:r,sessions:[]},a.set(d,f),n.push(f)),f.sessions.push(c)}return n.sort((c,l)=>(c.key===""?1:0)-(l.key===""?1:0))}function dC(e){return e&&e.trim().length>0?e:""}function b3(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 og(e,t){const r=new Set;return e.flatMap(n=>{const a=[...new Set(n.sessionIds)].filter(c=>t.has(c)&&!r.has(c));return!n.federated&&n.sessionIds.length>0&&a.length===0?[]:(a.forEach(c=>r.add(c)),[{...n,sessionIds:a}])})}function Cf(e,t,r,n,a=[],c=[]){const l=new Map(e.map(T=>[T.id,T])),d=og(c,new Set(l.keys())),f=new Map,m=new Map,x=a.filter(T=>T.sessionIds.length>=2&&T.sessionIds.every(S=>l.has(S))),y=(T,S)=>{const I=l.get(S);T.forEach(N=>{f.set(N,T),m.set(N,I)})};for(const T of d){const S=new Set(T.sessionIds),I=new Map;for(const F of x)F.sessionIds.every(P=>S.has(P))&&F.sessionIds.forEach(P=>I.set(P,F.sessionIds));const N=new Set,B=T.sessionIds.flatMap(F=>{if(N.has(F))return[];const P=I.get(F)??[F];return P.forEach($=>N.add($)),P});y(B,T.sessionIds[0])}for(const T of x)T.sessionIds.some(S=>f.has(S))||y(T.sessionIds,T.sessionIds[0]);const w=T=>{const S=new Set;return T.flatMap(I=>{if(S.has(I.id))return[];const N=f.get(I.id)??[I.id];return N.forEach(B=>S.add(B)),N.map(B=>l.get(B))})};if(!r)return{arranged:w(e),groups:[]};const v=x3(e,T=>t(m.get(T.id)??T),n).map(T=>({...T,sessions:w(T.sessions)}));return{arranged:v.flatMap(T=>T.sessions),groups:v}}function hC(e){return e.isActive&&e.viewportFocused&&e.documentVisible&&e.windowFocused&&e.streamReady}function fC(e){return e.isActive&&e.documentVisible&&e.streamReady&&(!e.isDesktop||e.windowFocused)}function pC(e){return e.isActive&&!e.isMobile&&e.documentVisible&&!e.activeElementIsEditable}function mC(e,t){return!e&&t}async function y3(e){const t=ea();return t?.confirmationUI==="page-v1"&&t.confirm?await t.confirm(e):window.confirm(e.message)}function o1(e){const t=ea();t?.confirmationUI==="page-v1"&&t.alert?t.alert(e):window.alert(e)}async function lg(e,t){if(!e.busy){e.busy=!0,t.pending(!0);try{if(!await t.confirm())return;if(!t.current())throw new Error(t.expiredMessage);const r=await t.submit(t.current);t.current()&&t.apply(r)}catch(r){t.current()&&t.failure(r instanceof Error?r.message:String(r))}finally{e.busy=!1,t.pending(!1)}}}const _f=".termdock/architecture.json",v3=".termdock/architectures",gC={kind:"project",target:"",paths:[],depth:"boundary",focus:""},xC=["description","diagram","context","constraint","concern","todo","note"],bC=/^[a-zA-Z][a-zA-Z0-9_-]{0,79}$/;class yC extends Error{}function xs(){throw new yC("Invalid architecture document")}function Bl(e){return(!e||typeof e!="object"||Array.isArray(e))&&xs(),e}function bi(e,t=8e3){return(typeof e!="string"||e.length>t)&&xs(),e}function Mc(e){const t=bi(e,80);return bC.test(t)||xs(),t}function uc(e,t){return(!Array.isArray(e)||e.length>t)&&xs(),e}function Qx(e){return Object.fromEntries(xC.filter(t=>e[t]!==void 0).map(t=>[t,bi(e[t],1e5)]))}function wu(e){if(e===void 0)return;const t=Bl(e),r={};for(const n of["created","updated","gitCommit","gitBranch","previousDiagram"])t[n]!==void 0&&(r[n]=bi(t[n],n==="previousDiagram"?1e5:200));return t.updateCount!==void 0&&((!Number.isSafeInteger(t.updateCount)||t.updateCount<0)&&xs(),r.updateCount=t.updateCount),r}function tf(e){return!!e&&!/[:\\\x00-\x1f]/.test(e)&&!e.startsWith("/")&&e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function cg(e){(!["project","module","feature"].includes(e.kind)||!["boundary","dependencies"].includes(e.depth))&&xs();const t=e.kind==="project"?[]:[...new Set(uc(e.paths,20).map(a=>bi(a,1024).trim()))].sort();t.some(a=>!tf(a))&&xs();const r=bi(e.target,1e3).trim(),n=bi(e.focus,2e3).trim();return(e.kind==="module"&&!t.length||e.kind==="feature"&&!r)&&xs(),{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-DGfMcwdq.js","assets/app-A96wp9Xv.js","assets/react-XDCjal2T.js","assets/dnd-BCFAPC0L.js","assets/terminal-C7X98Amf.js","assets/index-e1PkqIqN.css","assets/CollaborationTaskContent-DatXl2k_.js","assets/RightSidebar-DvYmab8z.js","assets/gestureArbiter-W1Lo4NZw.js","assets/gestureArbiter-C2J0D0kV.css","assets/DiffReview-Bxe6OacV.js","assets/sparkles-BMR6NziM.js","assets/DiffViewer-oGb-V3AK.js","assets/referenceLongPress-8ExgTbB3.js","assets/DiffViewer-T3uj2-aP.css","assets/triangle-alert-TsfoVQJR.js","assets/ChangeWalkthroughPanel-xvUzbgKh.js","assets/RightSidebar-DW-JEgm2.css","assets/CollaborationMainWorkspace-DsIWXeh0.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{ah as Ht,aP as cd,b8 as ea,bA as s,ad as vc,df as Hr,H as p8,dq as ml,db as ja,dd as ns,b3 as wc,a7 as mh,aB as Uy,br as eg,cQ as m8,C as ai,X as Mn,cG as zy,dc as W0,cA as Hc,j as _0,ag as ed,cq as Pp,cZ as g8,au as Fu,bz as Bu,g as x8,ak as wl,cL as Xh,Z as b8,bd as r1,bK as n1,az as y8,cj as v8,a5 as Hy,ch as w8,cE as Wy,ab as A8,ai as T8,L as jn,f as S8,d as Al,bi as C8,b2 as s1,dh as _8,dm as Vr,bI as tg,dl as Vt,aF as k8,dv as L8,v as I8,bP as E8,c2 as N8,a4 as Ma,bT as R8,cC as Tx,cD as Sx,cF as Cx,W as _x,c1 as M8,cR as j8,t as x0,bq as rg,da as D8,_ as Vc,bb as B8,i as Q8,dp as Gy,b0 as gl,T as Zo,dg as eu,dk as P8,ck as O8,cS as F8,ap as $8,a_ as U8,b$ as z8,c0 as H8,P as Vy,V as kx,bQ as Lx,bC as qy,n as Zs,$ as Jh,c$ as Op,bJ as W8,cm as G8,bH as Yy,cw as Ki,dj as V8,bh as Vo,ds as q8,B as xc,e as Ys,u as Y8,o as $u,am as Z8,N as i1,cx as K8,h as Io,bv as X8,bw as J8,ar as Zy,aD as Ky,a6 as Uu,m as qu,cu as Hl,c4 as Xy,ay as b0,c as ef,de as Jy,aL as e9,S as k0,bo as wf,a as e3,at as t9,af as r9,d8 as n9,c5 as td,a9 as bc,bG as Ix,cB as s9,c9 as t3,cW as i9,cY as r3,bD as a9,bF as ng,cJ as o9,cK as l9,c6 as c9,cH as u9,cr as d9,co as h9,cl as f9,c8 as p9,cy as m9,bS as g9,bR as n3,ct as x9,cI as b9,bE as Ex,aJ as y9,b1 as v9,D as w9,aI as Nx,bM as A9,p as T9,bO as S9,q as C9,F as _9,a8 as k9,c7 as L9,l as I9,cz as E9,r as N9,c3 as R9,aw as M9,aC as j9,aE as D9,bc as Ld,bm as B9,d5 as Q9,bn as P9,aq as O9,d7 as F9,Q as $9,al as U9,ae as z9,A as H9,ba as W9,as as G9,M as V9,dn as q9,bV as Rc,b7 as Y9,b4 as Z9,b5 as K9,b6 as X9,aY as Fp,bW as J9,cd as eA,cn as tA,b9 as rA,a$ as nA,cX as Rx,ao as sA,Y as iA,d3 as aA,dt as qn,bU as oA,w as lA,cU as cA,aX as uA,be as Mx,cc as dA,cP as gh,d2 as Id,d6 as hA,ce as fA,cV as pA,cM as mA,d1 as $p,cN as gA,cO as xA,di as bA,an as yA,bL as vA,by as xh,bx as wA,ca as jx,cf as AA,cb as vu,cg as TA,a3 as SA,ac as CA,s as _A,aa as kA}from"./app-A96wp9Xv.js";import{b,R as _,r as Ks,a as LA}from"./dnd-BCFAPC0L.js";import{b as IA,c as EA,F as tu,S as NA,e as RA,h as MA,r as jA,y as DA,d as BA,u as QA}from"./gestureArbiter-W1Lo4NZw.js";import{L as PA,l as OA}from"./terminal-C7X98Amf.js";import{T as sg,L as rd,C as L0,M as FA,G as $A}from"./triangle-alert-TsfoVQJR.js";import{r as UA}from"./react-XDCjal2T.js";import{u as ig,G as zA}from"./referenceLongPress-8ExgTbB3.js";const HA=[["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"}]],Af=Ht("archive",HA);const WA=[["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"}]],GA=Ht("arrow-down-a-z",WA);const VA=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],qA=Ht("arrow-down",VA);const YA=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],s3=Ht("arrow-up",YA);const ZA=[["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"}]],i3=Ht("bell",ZA);const KA=[["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"}]],G0=Ht("bot",KA);const XA=[["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"}]],JA=Ht("box",XA);const eT=[["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"}]],tT=Ht("cable",eT);const rT=[["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"}]],nT=Ht("calendar-clock",rT);const sT=[["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"}]],iT=Ht("camera",sT);const aT=[["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"}]],oT=Ht("chart-bar",aT);const lT=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],cT=Ht("circle-dot",lT);const uT=[["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"}]],Tf=Ht("circle-question-mark",uT);const dT=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],V0=Ht("circle",dT);const hT=[["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"}]],fT=Ht("clipboard-paste",hT);const pT=[["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"}]],a3=Ht("clipboard",pT);const mT=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6h4",key:"135r8i"}]],I0=Ht("clock-3",mT);const gT=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],xT=Ht("clock",gT);const bT=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],yT=Ht("code",bT);const vT=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 3v18",key:"108xh3"}]],Fl=Ht("columns-2",vT);const wT=[["path",{d:"M20 4v7a4 4 0 0 1-4 4H4",key:"6o5b7l"}],["path",{d:"m9 10-5 5 5 5",key:"1kshq7"}]],AT=Ht("corner-down-left",wT);const TT=[["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"}]],E0=Ht("download",TT);const ST=[["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"}]],qc=Ht("external-link",ST);const CT=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}]],_T=Ht("file-code",CT);const kT=[["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"}]],LT=Ht("file-up",kT);const IT=[["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"}]],o3=Ht("file",IT);const ET=[["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"}]],Yu=Ht("folder-open",ET);const NT=[["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"}]],ag=Ht("folder-search",NT);const RT=[["path",{d:"M20 10a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1h-2.5a1 1 0 0 1-.8-.4l-.9-1.2A1 1 0 0 0 15 3h-2a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",key:"hod4my"}],["path",{d:"M20 21a1 1 0 0 0 1-1v-3a1 1 0 0 0-1-1h-2.9a1 1 0 0 1-.88-.55l-.42-.85a1 1 0 0 0-.92-.6H13a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",key:"w4yl2u"}],["path",{d:"M3 5a2 2 0 0 0 2 2h3",key:"f2jnh7"}],["path",{d:"M3 3v13a2 2 0 0 0 2 2h3",key:"k8epm1"}]],MT=Ht("folder-tree",RT);const jT=[["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"}]],Dx=Ht("grid-2x2",jT);const DT=[["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"}]],sp=Ht("grip-vertical",DT);const BT=[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]],QT=Ht("hash",BT);const PT=[["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"}]],Wc=Ht("history",PT);const OT=[["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"}]],FT=Ht("house",OT);const $T=[["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"}]],l3=Ht("keyboard",$T);const UT=[["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"}]],c3=Ht("layers",UT);const zT=[["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"}]],HT=Ht("layout-dashboard",zT);const WT=[["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"}]],ru=Ht("layout-grid",WT);const GT=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],VT=Ht("loader-circle",GT);const qT=[["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"}]],YT=Ht("maximize",qT);const ZT=[["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"}]],ud=Ht("message-circle",ZT);const KT=[["path",{d:"M5 12h14",key:"1ays0h"}]],u3=Ht("minus",KT);const XT=[["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"}]],JT=Ht("minimize",XT);const eS=[["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"}]],tS=Ht("monitor-smartphone",eS);const rS=[["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"}]],nS=Ht("moon",rS);const sS=[["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"}]],iS=Ht("move",sS);const aS=[["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"}]],oS=Ht("network",aS);const lS=[["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"}]],cS=Ht("panel-right-close",lS);const uS=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],dS=Ht("panel-left",uS);const hS=[["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"}]],fS=Ht("panel-right-open",hS);const pS=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],d3=Ht("panel-right",pS);const mS=[["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"}]],gS=Ht("paperclip",mS);const xS=[["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"}]],bS=Ht("pause",xS);const yS=[["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"}]],vS=Ht("pen-line",yS);const wS=[["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"}]],AS=Ht("pencil-line",wS);const TS=[["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"}]],N0=Ht("pin",TS);const SS=[["path",{d:"M12 17v5",key:"bb1du9"}],["path",{d:"M15 9.34V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H7.89",key:"znwnzq"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M9 9v1.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h11",key:"c9qhm2"}]],R0=Ht("pin-off",SS);const CS=[["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"}]],Sf=Ht("play",CS);const _S=[["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"}]],kS=Ht("plug",_S);const LS=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],IS=Ht("power",LS);const ES=[["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"}]],wn=Ht("refresh-cw",ES);const NS=[["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"}]],h3=Ht("rotate-ccw",NS);const RS=[["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"}]],MS=Ht("rotate-cw",RS);const jS=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 12h18",key:"1i2n21"}]],Bx=Ht("rows-2",jS);const DS=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Wl=Ht("search",DS);const BS=[["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"}]],y0=Ht("send",BS);const QS=[["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"}]],f3=Ht("settings",QS);const PS=[["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"}]],OS=Ht("shield-alert",PS);const FS=[["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"}]],$S=Ht("shield-check",FS);const US=[["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"}]],a1=Ht("sliders-horizontal",US);const zS=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],p3=Ht("square",zS);const HS=[["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"}]],WS=Ht("stethoscope",HS);const GS=[["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"}]],VS=Ht("sun",GS);const qS=[["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"}]],Ds=Ht("trash-2",qS);const YS=[["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"}]],ZS=Ht("type",YS);const KS=[["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"}]],XS=Ht("unlink",KS);const JS=[["path",{d:"m19 5 3-3",key:"yk6iyv"}],["path",{d:"m2 22 3-3",key:"19mgm9"}],["path",{d:"M6.3 20.3a2.4 2.4 0 0 0 3.4 0L12 18l-6-6-2.3 2.3a2.4 2.4 0 0 0 0 3.4Z",key:"goz73y"}],["path",{d:"M7.5 13.5 10 11",key:"7xgeeb"}],["path",{d:"M10.5 16.5 13 14",key:"10btkg"}],["path",{d:"m12 6 6 6 2.3-2.3a2.4 2.4 0 0 0 0-3.4l-2.6-2.6a2.4 2.4 0 0 0-3.4 0Z",key:"1snsnr"}]],m3=Ht("unplug",JS);const eC=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],tC=Ht("upload",eC);const rC=[["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"}]],g3=Ht("video",rC);const nC=[["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"}]],sC=Ht("volume-1",nC);const iC=[["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"}]],aC=Ht("volume-2",iC);const oC=[["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"}]],lC=Ht("wand-sparkles",oC);const cC=[["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"}]],Up=Ht("workflow",cC);function uC(e,t){return e==="webgl"&&t}function x3(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 f=a.get(d);f||(f={key:d,label:d?cd(d)??d:r,sessions:[]},a.set(d,f),n.push(f)),f.sessions.push(c)}return n.sort((c,l)=>(c.key===""?1:0)-(l.key===""?1:0))}function dC(e){return e&&e.trim().length>0?e:""}function b3(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 og(e,t){const r=new Set;return e.flatMap(n=>{const a=[...new Set(n.sessionIds)].filter(c=>t.has(c)&&!r.has(c));return!n.federated&&n.sessionIds.length>0&&a.length===0?[]:(a.forEach(c=>r.add(c)),[{...n,sessionIds:a}])})}function Cf(e,t,r,n,a=[],c=[]){const l=new Map(e.map(T=>[T.id,T])),d=og(c,new Set(l.keys())),f=new Map,m=new Map,x=a.filter(T=>T.sessionIds.length>=2&&T.sessionIds.every(S=>l.has(S))),y=(T,S)=>{const I=l.get(S);T.forEach(N=>{f.set(N,T),m.set(N,I)})};for(const T of d){const S=new Set(T.sessionIds),I=new Map;for(const F of x)F.sessionIds.every(P=>S.has(P))&&F.sessionIds.forEach(P=>I.set(P,F.sessionIds));const N=new Set,B=T.sessionIds.flatMap(F=>{if(N.has(F))return[];const P=I.get(F)??[F];return P.forEach($=>N.add($)),P});y(B,T.sessionIds[0])}for(const T of x)T.sessionIds.some(S=>f.has(S))||y(T.sessionIds,T.sessionIds[0]);const w=T=>{const S=new Set;return T.flatMap(I=>{if(S.has(I.id))return[];const N=f.get(I.id)??[I.id];return N.forEach(B=>S.add(B)),N.map(B=>l.get(B))})};if(!r)return{arranged:w(e),groups:[]};const v=x3(e,T=>t(m.get(T.id)??T),n).map(T=>({...T,sessions:w(T.sessions)}));return{arranged:v.flatMap(T=>T.sessions),groups:v}}function hC(e){return e.isActive&&e.viewportFocused&&e.documentVisible&&e.windowFocused&&e.streamReady}function fC(e){return e.isActive&&e.documentVisible&&e.streamReady&&(!e.isDesktop||e.windowFocused)}function pC(e){return e.isActive&&!e.isMobile&&e.documentVisible&&!e.activeElementIsEditable}function mC(e,t){return!e&&t}async function y3(e){const t=ea();return t?.confirmationUI==="page-v1"&&t.confirm?await t.confirm(e):window.confirm(e.message)}function o1(e){const t=ea();t?.confirmationUI==="page-v1"&&t.alert?t.alert(e):window.alert(e)}async function lg(e,t){if(!e.busy){e.busy=!0,t.pending(!0);try{if(!await t.confirm())return;if(!t.current())throw new Error(t.expiredMessage);const r=await t.submit(t.current);t.current()&&t.apply(r)}catch(r){t.current()&&t.failure(r instanceof Error?r.message:String(r))}finally{e.busy=!1,t.pending(!1)}}}const _f=".termdock/architecture.json",v3=".termdock/architectures",gC={kind:"project",target:"",paths:[],depth:"boundary",focus:""},xC=["description","diagram","context","constraint","concern","todo","note"],bC=/^[a-zA-Z][a-zA-Z0-9_-]{0,79}$/;class yC extends Error{}function xs(){throw new yC("Invalid architecture document")}function Bl(e){return(!e||typeof e!="object"||Array.isArray(e))&&xs(),e}function bi(e,t=8e3){return(typeof e!="string"||e.length>t)&&xs(),e}function Mc(e){const t=bi(e,80);return bC.test(t)||xs(),t}function uc(e,t){return(!Array.isArray(e)||e.length>t)&&xs(),e}function Qx(e){return Object.fromEntries(xC.filter(t=>e[t]!==void 0).map(t=>[t,bi(e[t],1e5)]))}function wu(e){if(e===void 0)return;const t=Bl(e),r={};for(const n of["created","updated","gitCommit","gitBranch","previousDiagram"])t[n]!==void 0&&(r[n]=bi(t[n],n==="previousDiagram"?1e5:200));return t.updateCount!==void 0&&((!Number.isSafeInteger(t.updateCount)||t.updateCount<0)&&xs(),r.updateCount=t.updateCount),r}function tf(e){return!!e&&!/[:\\\x00-\x1f]/.test(e)&&!e.startsWith("/")&&e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function cg(e){(!["project","module","feature"].includes(e.kind)||!["boundary","dependencies"].includes(e.depth))&&xs();const t=e.kind==="project"?[]:[...new Set(uc(e.paths,20).map(a=>bi(a,1024).trim()))].sort();t.some(a=>!tf(a))&&xs();const r=bi(e.target,1e3).trim(),n=bi(e.focus,2e3).trim();return(e.kind==="module"&&!t.length||e.kind==="feature"&&!r)&&xs(),{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 vC(e){const t=cg(e);if(t.kind==="project")return _f;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`${v3}/${t.kind}-${a}-${(n>>>0).toString(16).padStart(8,"0")}.json`}function w3(e){return e===".omm"||e===_f||new RegExp(`^${v3.replace(".","\\.")}/(?:module|feature)-[\\p{L}\\p{N}_-]{1,48}-[a-f0-9]{8}\\.json$`,"u").test(e)}function _U(e){return e.split("/").pop()?.replace(/^(module|feature)-/,"").replace(/-[a-f0-9]{8}\.json$/,"").replace(/-/g," ")??e}function kU(e){new TextEncoder().encode(e).byteLength>5e6&&xs();let t;try{t=JSON.parse(e)}catch{xs()}const r=Bl(t);r.version!==1&&xs();const n=bi(r.generatedAt,80);Number.isFinite(Date.parse(n))||xs();const a=uc(r.perspectives,12).map(d=>{const f=Bl(d),m=uc(f.nodes,200).map(w=>{const v=Bl(w),T=uc(v.files,40).map(I=>{const N=Bl(I),B=bi(N.path,1024);return tf(B)||xs(),N.line!==void 0&&(!Number.isSafeInteger(N.line)||N.line<1)&&xs(),{path:B,...N.line!==void 0?{line:N.line}:{}}}),S=v.references===void 0?void 0:uc(v.references,100).map(I=>{const N=Bl(I);return{perspective:Mc(N.perspective),...N.node!==void 0?{node:Mc(N.node)}:{}}});return v.documentPath!==void 0&&!tf(bi(v.documentPath,1024))&&xs(),v.role!==void 0&&!["external","concern","entry","store"].includes(v.role)&&xs(),{id:Mc(v.id),title:bi(v.title,160),summary:bi(v.summary),files:T,...Qx(v),...v.parentId!==void 0?{parentId:Mc(v.parentId)}:{},...v.documentPath!==void 0?{documentPath:bi(v.documentPath,1024)}:{},...wu(v.meta)?{meta:wu(v.meta)}:{},...S?{references:S}:{},...v.role!==void 0?{role:v.role}:{}}});m.length||xs();const x=new Map(m.map(w=>[w.id,w]));x.size!==m.length&&xs();for(const w of m){const v=new Set([w.id]);let T=w.parentId;for(;T;)(v.has(T)||!x.has(T))&&xs(),v.add(T),T=x.get(T)?.parentId}const y=uc(f.edges,600).map(w=>{const v=Bl(w),T=Mc(v.from),S=Mc(v.to);return(!x.has(T)||!x.has(S))&&xs(),{from:T,to:S,label:bi(v.label,200)}});return{id:Mc(f.id),title:bi(f.title,160),summary:bi(f.summary),nodes:m,edges:y,...Qx(f),...wu(f.meta)?{meta:wu(f.meta)}:{}}});(!a.length||new Set(a.map(d=>d.id)).size!==a.length)&&xs();for(const d of a)for(const f of d.nodes)for(const m of f.references??[]){const x=a.find(y=>y.id===m.perspective);(!x||m.node&&!x.nodes.some(y=>y.id===m.node))&&xs()}const c=r.analysis===void 0?void 0:cg(Bl(r.analysis));let l;if(r.details!==void 0){const d=Bl(r.details),f=uc(d.analyzedPaths,200).map(x=>{const y=bi(x,1024);return tf(y)||xs(),y}),m=uc(d.limitations,30).map(x=>bi(x,2e3));l={analyzedPaths:f,limitations:m}}return r.origin!==void 0&&!["termdock","omm"].includes(r.origin)&&xs(),{version:1,generatedAt:n,summary:bi(r.summary),perspectives:a,...c?{analysis:c}:{},...l?{details:l}:{},...r.origin?{origin:r.origin}:{},...wu(r.meta)?{meta:wu(r.meta)}:{}}}function A3(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 f=n.get(d);for(;f&&!a.has(f.id);)f=f.parentId?n.get(f.parentId):void 0;return f?.id},l=new Map;for(const d of e.edges){const f=c(d.from),m=c(d.to);f&&m&&f!==m&&!l.has(`${f}:${m}`)&&l.set(`${f}:${m}`,{from:f,to:m,label:d.label})}return{nodes:r,edges:[...l.values()]}}function zp(e){return e.slice(0,100).replace(/[&<>"\[\]{}|`#;\\\r\n]/g," ").trim()||"…"}function LU(e,t,r=0){const n=A3(e,t),a=[],c=(w,v)=>{for(const T of e.nodes.filter(S=>S.parentId===w))a.push(T),v<r&&c(T.id,v+1)};c(t,0);const l=new Map(a.map((w,v)=>[w.id,`n${v}`])),d=[],f=new Set,m=(w,v)=>{for(const T of e.nodes.filter(S=>S.parentId===w)){const S=l.get(T.id);v<r&&e.nodes.some(I=>I.parentId===T.id)?(f.add(T.id),d.push(`subgraph ${S}["${zp(T.title)}"]`),m(T.id,v+1),d.push("end")):d.push(`${S}["${zp(T.title)}"]`)}};m(t,0);const x=w=>{let v=e.nodes.find(T=>T.id===w);for(;v&&!l.has(v.id);)v=e.nodes.find(T=>T.id===v.parentId);return v?.id},y=new Map;for(const w of r?e.edges:n.edges){const v=x(w.from),T=x(w.to),S=(I,N)=>{let B=e.nodes.find(F=>F.id===N);for(;B?.parentId;){if(B.parentId===I)return!0;B=e.nodes.find(F=>F.id===B.parentId)}return!1};v&&T&&v!==T&&!S(v,T)&&!S(T,v)&&y.set(`${v}:${T}:${w.label}`,{from:v,to:T,label:w.label})}return{nodes:a,groups:f,code:["---","config:"," htmlLabels: false","---","flowchart TD",...d,...y.values()].map(w=>typeof w=="string"?w:`${l.get(w.from)} -->|"${zp(w.label)}"| ${l.get(w.to)}`).join(`
|
|
4
4
|
`)}}function IU(e,t,r=gC,n){const a=cg(r),c=n??vC(a);if(c===".omm")return wC(e,t);(!w3(c)||a.kind!=="project"&&c===_f||a.kind==="project"&&c!==_f)&&xs();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 s5="||",$E=120;function UE(e){return e.includes(s5)?e.split(s5).filter(t=>t.length>0):[e]}function Wu(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(f=>Tv(f)).filter(f=>!!f):[],includeAlt:typeof a.includeAlt=="boolean"?!!a.includeAlt:!1,rowLayout:wg(a.rowLayout),showOnDesktop:typeof a.showOnDesktop=="boolean"?!!a.showOnDesktop:!1,actions:Array.isArray(a.actions)?a.actions.map((f,m)=>{const x={id:typeof f.id=="string"&&f.id.trim().length>0?f.id:`${d}-action-${m+1}`,label:typeof f.label=="string"?f.label:`Key ${m+1}`,sequence:typeof f.sequence=="string"?f.sequence:""};return typeof f.doubleTapSequence=="string"&&(x.doubleTapSequence=f.doubleTapSequence),x}):[]}}).filter(a=>a.id!=="auto"),n=D0()[0];return n&&!r.some(a=>a.id==="default")&&r.unshift(n),r}function zE(e,t){const r=Av(e);if(!r)return"default";for(const n of t)if(n.id!=="default")for(const a of n.programs){const c=Df(a);if(c){if(c.test(r))return n.id}else if(r.includes(a))return n.id}return"default"}function i5(e,t){return e.find(r=>r.id===t)??e.find(r=>r.id==="default")??D0()[0]}function HE(e){return[{id:"auto",label:"Auto"},...e.map(t=>({id:t.id,label:t.label}))]}function WE(e){return[{id:"auto",label:"Auto"},...e.filter(t=>t.id==="default"||t.showOnDesktop===!0).map(t=>({id:t.id,label:t.label}))]}function Sv(e,t){const r=wg(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 Cv=28,_v=({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(lC,{size:14}):(t.charAt(0)||"?").toUpperCase()}),GE={esc:"\x1B",enter:"\r",home:"\x1B[H",end:"\x1B[F","ctrl-c":"","ctrl-d":"","ctrl-w":"","ctrl-u":""},Vd=8;function VE(e,t){return GE[e]??null}const qE=({visible:e,interactive:t=!0,presentation:r="mobile",activeModifier:n,lockedModifier:a,disabled:c,defaultShowExtended:l=!1,presetLabel:d,presetModeLabel:f,presetMode:m,presetOptions:x,includeAlt:y,presetRowLayout:w,extraActions:v,onKeyPress:T,onTextPress:S,onPastePress:I,onFilePress:N,onFileLongPress:B,fileUploadState:F="idle",fileUploadProgress:P=0,longPressMode:$="arrows",copyFeedback:ee="idle",onLongPressModeToggle:Z,onModifierToggle:V,onPresetSelect:de,onExpandedChange:pe})=>{const{t:J}=Hr(),[Re,Xe]=_.useState(l),[q,ve]=_.useState(!1),qe=_.useRef(null),ce=r==="desktop-actions",ye=ce||Re,[Te,Fe]=_.useState(!1),[se,De]=_.useState(null),_e=c||!e||!t,Me=c||!e,Je=_.useRef(null),Ne=_.useRef(null),ae=_.useRef(null),ze=_.useRef(null),at=_.useRef(null),ut=_.useRef(ee),me=_.useRef(null),dt=_.useRef(0),ft=_.useRef(null),Se=_.useRef(!1),We=_.useCallback(Ce=>{if(_e)return;const St=Ce.target;if(!(St instanceof Element))return;const Ot=St.closest("button"),tr=Ot?.hasAttribute("data-mobile-native-action")===!0;Ot&&!tr?(Ce.preventDefault(),So(Vd)):Ot&&So(Vd)},[_e]),Le=_.useCallback(Ce=>{Ce.preventDefault()},[]),z=_.useCallback(Ce=>{const St=Ce.target;_e||St instanceof HTMLElement&&St.closest("button")&&St.blur()},[_e]);_.useEffect(()=>{Xe(l)},[l]),_.useEffect(()=>{ce||pe?.(Re)},[ce,pe,Re]),_.useEffect(()=>{_e&&(me.current!==null&&(window.clearTimeout(me.current.timer),me.current=null),Fe(!1),De(null))},[_e]),_.useEffect(()=>{e||(Fe(!1),De(null))},[e]),_.useEffect(()=>{if(!Te)return;const Ce=()=>{const St=Je.current?.getBoundingClientRect();St&&De({left:Math.max(8,St.left),top:Math.max(8,St.top-8)})};return Ce(),window.addEventListener("resize",Ce),window.addEventListener("scroll",Ce,!0),()=>{window.removeEventListener("resize",Ce),window.removeEventListener("scroll",Ce,!0)}},[Te]),_.useEffect(()=>{const Ce=ut.current;if(ut.current=ee,ee==="idle"||ee===Ce)return;if(at.current!==null&&window.clearTimeout(at.current),!(typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches))if(ee==="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 Ot=[{opacity:0,transform:"scale(0.65)"},{opacity:.75,transform:"scale(0.9)",offset:.18},{opacity:0,transform:"scale(1.65)"}];ae.current?.animate?.(Ot,{duration:760,easing:"ease-out"}),ze.current?.animate?.(Ot,{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"});So(Vd),ee==="copied"&&(at.current=window.setTimeout(()=>{So(Vd),at.current=null},90),$==="copy"&&Z?.())},[ee,$,Z]),_.useEffect(()=>()=>{at.current!==null&&window.clearTimeout(at.current)},[]);const ie=_.useCallback((Ce,St)=>{_e||(Ce.preventDefault(),T(St))},[T,_e]),ge=_.useCallback((Ce,St)=>{_e||(Ce.preventDefault(),V(St))},[V,_e]),Ge=_.useCallback(Ce=>{_e||(Ce.preventDefault(),Xe(St=>{const Ot=!St;return Ot&&(ve(!0),qe.current!==null&&window.clearTimeout(qe.current),qe.current=window.setTimeout(()=>{ve(!1),qe.current=null},350)),Ot}))},[_e]),rt=_.useCallback(()=>{const Ce=typeof performance<"u"?performance.now():Date.now();Ce-dt.current<350||(dt.current=Ce,I?.())},[I]),vt=_.useCallback(Ce=>{_e||(Ce.stopPropagation(),Ce.pointerType!=="touch"&&(Ce.preventDefault(),rt()))},[_e,rt]),Yt=_.useCallback(Ce=>{_e||(Ce.preventDefault(),Ce.stopPropagation(),rt())},[_e,rt]),Ut=_.useCallback(Ce=>{_e||F==="uploading"||!N||(Ce.preventDefault(),Ce.stopPropagation(),Se.current||N(),Se.current=!1)},[F,N,_e]),Nt=_.useCallback(()=>{ft.current!==null&&window.clearTimeout(ft.current),ft.current=null},[]),ir=_.useCallback(Ce=>{Ce.stopPropagation(),!(_e||F==="uploading"||!B)&&(Se.current=!1,ft.current=window.setTimeout(()=>{ft.current=null,Se.current=!0,So(Vd),B()},500))},[F,B,_e]);_.useEffect(()=>()=>Nt(),[Nt]);const Mt=_.useCallback(Ce=>{_e||Ce.stopPropagation()},[_e]),Xt=250,Bt=_.useCallback(()=>{me.current!==null&&(window.clearTimeout(me.current.timer),me.current=null)},[]);_.useEffect(()=>()=>{Bt(),qe.current!==null&&(window.clearTimeout(qe.current),qe.current=null)},[Bt]);const Wt=_.useCallback((Ce,St)=>{if(_e)return;if(Ce.preventDefault(),!St.doubleTapSequence){S(St.sequence);return}const Ot=me.current;if(Ot!==null&&Ot.actionId===St.id){window.clearTimeout(Ot.timer),me.current=null,S(St.doubleTapSequence);return}Bt();const tr=window.setTimeout(()=>{me.current=null,S(St.sequence)},Xt);me.current={actionId:St.id,timer:tr}},[Bt,S,_e]),xe=_.useCallback(Ce=>{_e||(Ce.preventDefault(),Ce.stopPropagation(),Z?.())},[Z,_e]),et=_.useCallback(Ce=>{_e||Ce.stopPropagation()},[_e]),ot=_.useCallback(Ce=>{if(_e)return;Ce.preventDefault();const St=Ce.currentTarget.getBoundingClientRect();De({left:Math.max(8,St.left),top:Math.max(8,St.top-8)}),Fe(Ot=>!Ot)},[_e]),Et=_.useCallback((Ce,St)=>{_e||(Ce.preventDefault(),Fe(!1),De(null),de(St))},[de,_e]),K=v.length>0,xt=_.useMemo(()=>{const Ce=[{id:"preset",kind:"preset"}];if(!ce&&y&&Ce.push({id:"alt",kind:"alt"}),K){const St=v.map(Ot=>({id:Ot.id,kind:"text",action:Ot}));return Ce.concat(St)}return ce?Ce.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"}]):Ce.concat([{id:"home",kind:"key",keyName:"home"},{id:"end",kind:"key",keyName:"end"},{id:"ctrl-d",kind:"key",keyName:"ctrl-d"}])},[v,K,y,ce]),rr=_.useMemo(()=>Sv(xt,ce&&!K?[6]:w),[xt,K,ce,w]),$e=`${ce?"space-y-1":"mt-1 space-y-1"}${q?" pointer-events-none":""}`,Dr=Te&&se?Ks.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:se.left,top:se.top},children:s.jsx("div",{className:"grid gap-1",children:x.map(Ce=>s.jsx("button",{type:"button",onPointerDown:St=>Et(St,Ce.id),tabIndex:-1,disabled:Me,className:`h-7 rounded-full px-3 text-left text-xs font-medium transition-colors disabled:opacity-50 ${Ce.id===m?"bg-primary text-primary-foreground":"bg-surface-2 hover:bg-surface-elevated text-muted-foreground hover:text-foreground"}`,children:Ce.label},Ce.id))})}),document.body):null;return s.jsxs(s.Fragment,{children:[Dr,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?ce?"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:Le,onFocusCapture:z,children:s.jsxs("div",{className:"rounded-2xl bg-surface-elevated p-0.5 space-y-0.5",children:[!ce&&s.jsxs("div",{"data-mobile-keyboard-primary-row":"true",className:"grid grid-cols-10 gap-1",children:[s.jsx("button",{type:"button",onPointerDown:Ce=>ie(Ce,"esc"),tabIndex:-1,disabled:Me,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:Ce=>ge(Ce,"ctrl"),tabIndex:-1,disabled:Me,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:Ce=>ie(Ce,"ctrl-c"),tabIndex:-1,disabled:Me,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:Ce=>ie(Ce,"ctrl-u"),tabIndex:-1,disabled:Me,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:ir,onPointerUp:Nt,onPointerCancel:Nt,onClick:Ut,tabIndex:-1,disabled:Me||!N||F==="uploading",title:F==="uploading"?`${J("rightSidebar.uploading")} ${Math.round(P)}%`:J(F==="inserted"?"rightSidebar.inserted":F==="failed"?"rightSidebar.uploadFailed":"rightSidebar.insertLocalFile"),"aria-label":J("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 ${F==="inserted"?"bg-primary/15 text-primary":F==="failed"?"bg-destructive/15 text-destructive":"bg-surface-2"}`,children:[F==="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,P))}%`}}),s.jsx("span",{className:"relative z-10 flex items-center justify-center",children:F==="uploading"?s.jsx(jn,{size:15,className:"animate-spin"}):F==="inserted"?s.jsx(ai,{size:15}):F==="failed"?s.jsx(Mn,{size:15}):s.jsx(LT,{size:15})}),F!=="idle"&&s.jsx("span",{className:"sr-only",role:"status","aria-live":"polite",children:F==="uploading"?`${J("rightSidebar.uploading")} ${Math.round(P)}%`:J(F==="inserted"?"rightSidebar.inserted":"rightSidebar.uploadFailed")})]}),s.jsx("button",{type:"button",onPointerDown:()=>S("/"),tabIndex:-1,disabled:Me,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:Ce=>ie(Ce,"enter"),tabIndex:-1,disabled:Me,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(AT,{size:16})}),s.jsxs("button",{ref:Ne,type:"button","data-mobile-copy-button":"true","data-mobile-native-action":"true",onPointerDown:et,onTouchStart:et,onClick:xe,tabIndex:-1,disabled:Me,title:J(ee==="copied"?"terminal.copied":ee==="failed"?"terminal.copyFailed":$==="copy"?"terminal.longPressSelectsText":"terminal.longPressSendsArrows"),"aria-label":J($==="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 ${ee==="copied"?"bg-primary/15 text-primary":ee==="failed"?"bg-destructive/15 text-destructive":$==="copy"?"bg-primary/15 text-primary":"bg-surface-2"}`,children:[s.jsx("span",{ref:ae,"aria-hidden":"true",className:"pointer-events-none absolute inset-0 z-0 rounded-full border border-primary/70 opacity-0"}),s.jsx("span",{ref:ze,"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(ai,{size:16,className:`absolute inset-0 transition-[opacity,transform] duration-300 ease-out motion-reduce:transition-none ${ee==="copied"?"scale-100 rotate-0 opacity-100":"scale-50 -rotate-45 opacity-0"}`}),s.jsx(Mn,{size:16,className:`absolute inset-0 transition-[opacity,transform] duration-200 ease-out motion-reduce:transition-none ${ee==="failed"?"scale-100 opacity-100":"scale-50 opacity-0"}`}),s.jsx(a3,{size:15,className:`absolute inset-0 transition-[opacity,transform] duration-300 ease-out motion-reduce:transition-none ${ee==="idle"&&$==="copy"?"scale-100 opacity-100":"scale-50 opacity-0"}`}),s.jsx(iS,{size:15,className:`absolute inset-0 transition-[opacity,transform] duration-300 ease-out motion-reduce:transition-none ${ee==="idle"&&$==="arrows"?"scale-100 rotate-0 opacity-100":"scale-50 rotate-45 opacity-0"}`})]}),ee!=="idle"&&s.jsx("span",{className:"sr-only",role:"status","aria-live":"polite",children:ee==="copied"?`${J("terminal.copied")} · ${J("terminal.longPressSendsArrows")}`:`${J("terminal.copyFailed")} · ${J("terminal.longPressSelectsText")}`})]}),s.jsx("button",{type:"button","data-mobile-copy-button":"true","data-mobile-native-action":"true",onPointerDown:vt,onPointerUp:Mt,onTouchStart:Mt,onTouchEnd:Mt,onClick:Yt,tabIndex:-1,disabled:Me,title:J("terminal.paste"),"aria-label":J("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(fT,{size:15})}),s.jsx("button",{type:"button",onPointerDown:Ge,tabIndex:-1,disabled:Me,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:Re?s.jsx(S8,{size:16}):s.jsx(Al,{size:16})})]}),ye&&s.jsx("div",{className:$e,children:rr.map((Ce,St)=>{const Ot=Ce.items[0]?.kind==="preset",tr=Math.max(2,Ce.columns),ct=Ot?`${Cv}px repeat(${Math.max(1,tr-1)}, minmax(0, 1fr))`:`repeat(${tr}, minmax(0, 1fr))`;return s.jsx("div",{className:"relative grid gap-1",style:{gridTemplateColumns:ct},children:Ce.items.map(Ct=>Ct.kind==="preset"?s.jsx(_v,{buttonRef:Ct.id==="preset"?Je:void 0,mode:m,presetLabel:d,title:f,disabled:Me,onPointerDown:ot},Ct.id):Ct.kind==="alt"?s.jsx("button",{type:"button",onPointerDown:or=>ge(or,"alt"),tabIndex:-1,disabled:Me,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"})},Ct.id):Ct.kind==="text"?s.jsxs("button",{type:"button",onPointerDown:or=>Wt(or,Ct.action),tabIndex:-1,disabled:Me,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:[Ct.action.label,Ct.action.doubleTapSequence&&s.jsx("span",{className:"absolute top-0.5 right-1.5 h-1 w-1 rounded-full bg-accent/60"})]},Ct.id):s.jsx("button",{type:"button",onPointerDown:or=>ie(or,Ct.keyName),tabIndex:-1,disabled:Me,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:Ct.keyName==="esc"?"Esc":Ct.keyName==="ctrl-c"?"Ctrl-C":Ct.keyName==="ctrl-d"?"Ctrl-D":Ct.keyName==="home"?"Home":"End"},Ct.id))},`row-${St}`)})})]})})]})},YE=({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"})})]})},ZE=/^Reconnecting/i,KE=({connectionError:e,isFatalError:t,isRestarting:r,isConnecting:n,onHardRestart:a})=>{const{t:c}=Hr(),l=!!e&&ZE.test(e),d=!!(n&&!e||l),[f,m]=_.useState(!1);return _.useEffect(()=>{if(!d){m(!1);return}const x=setTimeout(()=>m(!0),1500);return()=>clearTimeout(x)},[d]),d?f?s.jsx("div",{className:"absolute inset-x-0 bottom-0 flex items-end justify-center pb-2 pointer-events-none",children:s.jsx(_0,{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},XE=120,JE=80,eN=400;function a5(){if(typeof window>"u"||document.visibilityState!=="visible"||!C8())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=ml().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 kv(e){const{enabled:t,openThresholdPx:r=XE,closeThresholdPx:n=JE,settleDelayMs:a=eN}=e,c=_.useMemo(()=>ed("keyboard"),[]),l=_.useRef(!1),d=_.useRef(null),f=_.useRef(0),[m,x]=_.useState({isOpen:!1,isSettled:!1,keyboardHeight:0});return _.useEffect(()=>{if(typeof window>"u"||!t){l.current=!1,d.current!==null&&(clearTimeout(d.current),d.current=null),x(ee=>!ee.isOpen&&!ee.isSettled&&ee.keyboardHeight===0?ee:{isOpen:!1,isSettled:!1,keyboardHeight:0});return}let y=null;const w=()=>{y=null;const ee=a5();let Z=l.current;if(ee>=r?Z=!0:ee<=n&&(Z=!1),l.current=Z,Z){const V=Math.abs(ee-f.current);f.current=ee,V>10&&(d.current!==null&&clearTimeout(d.current),d.current=setTimeout(()=>{d.current=null,x(de=>de.isSettled?de:{...de,isSettled:!0})},a))}else d.current!==null&&(clearTimeout(d.current),d.current=null);x(V=>{const de=Z?V.isSettled:!1;return V.isOpen===Z&&V.keyboardHeight===ee&&V.isSettled===de?V:(c("sync",{keyboardHeight:ee,isOpen:Z,isSettled:de,visualViewport:ml().visualViewport?{width:Math.round(ml().visualViewport.width),height:Math.round(ml().visualViewport.height),offsetTop:Math.round(ml().visualViewport.offsetTop)}:null}),{isOpen:Z,isSettled:de,keyboardHeight:ee})})},v=(ee="event")=>{(ee.includes("visibilitychange")||ee.includes("pageshow"))&&c("schedule",{source:ee}),y===null&&(y=window.requestAnimationFrame(w))};v("mount");const T=()=>v("resize"),S=()=>v("orientationchange"),I=()=>v("visualViewport.resize"),N=()=>v("visualViewport.scroll"),B=()=>v("viewport-keyboard-change");window.addEventListener("resize",T),window.addEventListener("orientationchange",S),ml().visualViewport?.addEventListener("resize",I),ml().visualViewport?.addEventListener("scroll",N),document.addEventListener("termdock:viewport-keyboard-change",B);const F=ee=>{c("resume",{source:ee,keyboardHeight:a5(),hidden:document.hidden}),v(`${ee}:now`),window.setTimeout(()=>v(`${ee}:50ms`),50),window.setTimeout(()=>v(`${ee}:200ms`),200)},P=()=>{document.hidden||F("visibilitychange")},$=()=>F("pageshow");return document.addEventListener("visibilitychange",P),window.addEventListener("pageshow",$),()=>{window.removeEventListener("resize",T),window.removeEventListener("orientationchange",S),ml().visualViewport?.removeEventListener("resize",I),ml().visualViewport?.removeEventListener("scroll",N),document.removeEventListener("termdock:viewport-keyboard-change",B),document.removeEventListener("visibilitychange",P),window.removeEventListener("pageshow",$),y!==null&&window.cancelAnimationFrame(y),d.current!==null&&(clearTimeout(d.current),d.current=null)}},[c,t,r,n,a]),m}const df=300,tN=120,rN=2e3,nN=250,sN=6e4;function iN(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 bm(e,t){return t?e.find(r=>r.id===t||r.backendSessionId===t)?.id??null:null}function Mh(e){return e.prioritySessionId??e.activeSessionId??e.persistedActiveSessionId??e.firstSessionId}function aN(e){return e.foregroundSessionId===null||e.isVisible===!0||e.sessionId===e.foregroundSessionId||e.foregroundReady}function oN(e){return e.sessionId===e.foregroundSessionId||e.visibleSessionIds.has(e.sessionId)||e.deferredViewportSessionIds.has(e.sessionId)}function lN(e){return e.isMobile&&(!e.viewportReady||!e.streamReady||!e.contentReady)}function cN(e){return e.writtenChunkId!==null&&e.initialTargetChunkId!==null&&e.writtenChunkId>=e.initialTargetChunkId}function uN(e){return!e.initialConnectionPending}function dN(e){return!e}function hN(e){return e.requestToken===0||e.isVisible===!0||e.foregroundSessionId===null||e.isVisible===void 0&&e.sessionId===e.foregroundSessionId||e.foregroundCompletedToken===e.requestToken}function fN(e,t){return[...e].every(r=>t.has(r))}function pN(e,t){return e===null||t-e>=nN}function mN(e){return!1}function gN(e){return!e.isActive||e.isStreamReady||e.reconnectStartedAt===null?null:Math.max(0,sN-(e.now-e.reconnectStartedAt))}function xN(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,df+n*tN),n+=1}return r}const bN="Session not found on server",hf="Terminal session not found",yN="STALE_SESSION_RESTORE_REJECTED";function o5(e){return k1(e)?!1:e?.message===bN||e?.status===404&&e.message===hf}function k1(e){return e?.code===yN}function vN(e,t){if(!e||e.startsWith("/"))return e;const r=e.replace(/^\.\//,"");return t?`${t.replace(/\/+$/,"")}/${r}`:r}function Lv(e,t){return vN(e,t).replace(/ /g,"\\ ")}function L1(e,t){return`${Lv(e,t)} `}function l5(e,t){return Lv(e,t)}function uz(e,t,r){if(!r)return l5(e,t);const n=r.start===r.end?`${r.start}`:`${r.start}-${r.end}`;return`${l5(e,t)}:${n}`}const wN="/tmp";async function AN(e,t,r){const a=(await t(wN,[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 Bf(a)}if(!c)throw new Bf(a);return a}class Bf extends Error{constructor(t){super("File uploaded, but its reference was not accepted"),this.uploaded=t,this.name="UploadedReferenceRejectedError"}uploaded}function c5(e,t,r,n,a){if(!e||!t||!r())return Promise.resolve(!1);const c=n?OC(n,t,e):null;if(n&&!c)return Promise.resolve(!1);const l=c?.nonce??`reference-${crypto.randomUUID()}`;return new Promise(d=>{let f=!1;const m=w=>{f||(f=!0,window.clearTimeout(y),window.removeEventListener("termdock-insert-reference-ack",x),c&&FC(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 Iv=[640,960,1280,1600,2048,2560,3072,4096],Ev=[240,360,480,540,720,1080,1440,2160],A0={min:.1,max:1,step:.01},T0={min:25e4,max:2e7,step:25e4},Tg="termdock:mobile-media-compression-v1",Eu={showResultToast:!0,imageEnabled:!1,imageMaxDimension:2048,imageQuality:.8,videoEnabled:!1,videoMaxHeight:720,videoBitrate:25e5};function Nv(){try{const e=JSON.parse(localStorage.getItem(Tg)||"null");return!e||typeof e!="object"?Eu:{showResultToast:e.showResultToast!==!1,imageEnabled:e.imageEnabled===!0,imageMaxDimension:Iv.includes(e.imageMaxDimension)?e.imageMaxDimension:Eu.imageMaxDimension,imageQuality:typeof e.imageQuality=="number"&&e.imageQuality>=A0.min&&e.imageQuality<=A0.max?e.imageQuality:Eu.imageQuality,videoEnabled:e.videoEnabled===!0,videoMaxHeight:Ev.includes(e.videoMaxHeight)?e.videoMaxHeight:Eu.videoMaxHeight,videoBitrate:typeof e.videoBitrate=="number"&&e.videoBitrate>=T0.min&&e.videoBitrate<=T0.max?e.videoBitrate:Eu.videoBitrate}}catch{return Eu}}const Sg=vc((e,t)=>({preferences:Nv(),saveFailed:!1,update:r=>{const n={...t().preferences,...r};let a=!1;try{localStorage.setItem(Tg,JSON.stringify(n))}catch{a=!0}e({preferences:n,saveFailed:a})}}));typeof window<"u"&&window.addEventListener("storage",e=>{(e.key===Tg||e.key===null)&&Sg.setState({preferences:Nv(),saveFailed:!1})});function jh(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 TN({result:e,message:t,onClose:r}){const{locale:n}=Hr(),a=n==="zh",c=b.useRef(null),[l,d]=b.useState(null),[f,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(Mn,{size:18})})]}),s.jsx("div",{className:"min-h-0 overflow-auto p-2",children:f?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 SN({result:e,onDismiss:t}){const{locale:r}=Hr(),n=r==="zh",a=Sg(I=>I.preferences.showResultToast),c=a?e:null,[l,d]=b.useState(null);b.useEffect(()=>{if(!e)return;if(!a){t();return}const I=window.setTimeout(t,2e3);return()=>window.clearTimeout(I)},[e,a,t]);const f=c??l?.result;if(!f)return null;const m=f.originalSize-f.uploadedSize,x=f.originalSize>0?Math.abs(m)/f.originalSize*100:0,y=x<1?"<1%":`${Math.floor(x)}%`,w=f.kind==="image"?n?"图片":"Image":n?"视频":"Video",v=m>0?n?"已压缩上传":"Compressed upload":n?"已处理上传":"Processed upload",T=m>0?n?`省 ${y}`:`${y} saved`:m<0?`+${y}`:n?"体积未变":"Size unchanged",S=f.originalRetained?n?`已尝试压缩 · 保留原图 ${jh(f.uploadedSize)},已上传`:`Compression tried · original ${jh(f.uploadedSize)} uploaded`:`${v} · ${jh(f.originalSize)} → ${jh(f.uploadedSize)} · ${T}`;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}:${S} · ${n?"点击预览":"Preview"}`,onClick:()=>{d({result:c,message:S}),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(ai,{size:13,strokeWidth:2.5,className:"shrink-0 text-primary","aria-hidden":"true"}),s.jsx("span",{className:"truncate tabular-nums",children:S}),s.jsx("span",{className:"shrink-0 text-muted-foreground",children:n?"预览 ›":"Preview ›"})]})}),l&&Ks.createPortal(s.jsx(TN,{result:l.result,message:l.message,onClose:()=>d(null)}),document.body)]})}const CN=320,u5="termdock:mobile-keyboard-expanded",d5="termdock:mobile-keyboard-preset-mode",h5="termdock:mobile-long-press-mode",_N=80;function kN(e){return/\.(?:jpe?g|png|heic|heif)$/i.test(e.name)||/^(?:image\/jpeg|image\/png|image\/heic|image\/heif)$/i.test(e.type)}function f5(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 LN(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 ym(){return Gy()}const IN={retry:{maxRetries:60,initialDelayMs:1e3,maxDelayMs:2e4},connectionTimeoutMs:15e3},EN=({sessionId:e,mode:t,tmuxSessionName:r=null,terminalSettings:n=vg(),colorTheme:a="dark",toolbarPresets:c=[],isActive:l=!0,focusSuspended:d=!1,deferCursorUntilPositioned:f=!1,isLayoutVisible:m=!0,focusRequestToken:x=0,resumeRequestToken:y=0,resumeRequestReason:w="visibility",resumeRequestDelayMs:v=0,forceResumeReconnect:T=!1,initialConnectDelayMs:S=0,initialConnectEnabled:I=!0,resumeRequestEnabled:N=!0,onStreamReadyChange:B,onStreamConnected:F,onViewportReadyChange:P,onContentReadyChange:$,onKeyboardVisibilityChange:ee,suppressKeyboard:Z=!1,keyboardPortalTarget:V=null,sharedMobileKeyboardLayout:de=!1,suppressPageFlipRefresh:pe=!1,showDebug:J,onStatusChange:Re})=>{const{t:Xe}=Hr(),[q]=_.useState(e||L3()),[ve,qe]=_.useState(()=>(e?s1(e):null)??n.fontSize),ce=_.useMemo(()=>ME(),[]),ye=_.useMemo(()=>ed("session"),[]),Te=_.useMemo(()=>ed("keyboard"),[]),Fe=_.useRef(null),se=_.useRef(null);_.useEffect(()=>{s1(q)===null&&qe(n.fontSize)},[n.fontSize,q]);const De=_.useMemo(()=>({...n,fontSize:ve}),[n,ve]),_e=_8(),Me=d||_e,[Je,Ne]=_.useState(ym),[ae,ze]=_.useState(!1),[at,ut]=_.useState(!1),[me,dt]=_.useState(!1),[ft,Se]=_.useState(()=>typeof document>"u"?!0:!document.hidden&&Bu()),[We,Le]=_.useState(()=>typeof document>"u"?!0:document.hasFocus()),[z,ie]=_.useState(!1),ge=_.useRef(z);ge.current=z;const[Ge,rt]=_.useState(!1),[vt,Yt]=_.useState(!1),[Ut,Nt]=_.useState(!1),[ir,Mt]=_.useState(!0),{isOpen:Xt,keyboardHeight:Bt}=kv({enabled:Je&&l}),[Wt,xe]=_.useState(null),[et,ot]=_.useState(null),[Et,K]=_.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(u5)==="true"),[xt,rr]=_.useState(()=>{if(typeof window>"u")return"auto";const oe=window.localStorage.getItem(d5);return oe&&oe.length>0?oe:"auto"}),[$e,Dr]=_.useState(()=>typeof window>"u"?"arrows":window.localStorage.getItem(h5)==="copy"?"copy":"arrows"),[Ce,St]=_.useState("idle"),[Ot,tr]=_.useState("idle"),[ct,Ct]=_.useState(0),[or,Cr]=_.useState(null),[Ir,$r]=_.useState(null),[Tt,Ft]=_.useState(null),we=_.useCallback(()=>Ft(null),[]),{preferences:wt,update:it,saveFailed:bt}=Sg(),{videoEnabled:An,videoMaxHeight:xn,videoBitrate:rn,imageEnabled:Oe,imageMaxDimension:_t,imageQuality:mt}=wt,[Zt,$t]=_.useState(!1),[wr,Tn]=_.useState(null),[Dn,yn]=_.useState(null),un=Vr(oe=>oe.sessions.get(q)),{setTerminalSession:Cn,setConnecting:Ur,appendToBuffer:ne,replaceBuffer:Ze,clearTerminalSession:Dt,removeTerminalSession:ur,clearBuffer:Pr,setSessionActiveProgram:qr,setSessionCwd:sn,setSessionCopyMode:Nr,setSessionAgentStatus:Wr,setSessionShellTitle:_n,setSessionPromptState:en,clearAgentNeedsReview:Fr}=Vr.getState(),Kr=_.useMemo(()=>`wt-${q.replace(/[^a-zA-Z0-9_-]/g,"").slice(0,12)}`,[q]),gr=un?.terminalSessionId??null,an=un?.mode??"shell",Xr=un?.activeProgram??null,dn=_.useMemo(()=>Wu(c),[c]),Rr=an==="tmux",zn=un?.bufferChunks??[],pn=un?.isConnecting??!1,Gr=gr,zr=_.useCallback(async(oe,He)=>{const At=tE(oe,un?.cwd||un?.directory);if(!At)return;let jt=At,tt="directory";try{jt=(await tg(At)).path}catch(Rt){if(!(Rt instanceof Error)||Rt.message!=="Path is not a directory")return;tt="file"}try{const Rt=Vt.getState();Rt.setRightTab("files"),Rt.openRight(),window.dispatchEvent(new CustomEvent(YI,{detail:{path:jt,kind:tt,line:He}}))}catch{}},[un?.cwd,un?.directory]),Y=t??un?.mode??"shell",Be=Y==="tmux"?r??un?.tmuxSessionName??null:null,[Qt,er]=_.useState(null),nr=_.useRef(!1),[Or,kr]=_.useState(!1),[Zn,ys]=_.useState(!1),[ss,Hn]=_.useState(null),[hn,Qn]=_.useState(0),[Xn,fn]=_.useState(null),cr=J!==void 0?J:!1,is=_.useRef(null),tn=_.useRef(null),xr=_.useRef(null),vr=_.useRef(null),br=_.useRef(null),us=_.useRef(!1),Bn=_.useRef(null),vs=_.useRef([]),Bs=_.useRef(0),Ls=_.useRef(!1),Qr=_.useRef(Promise.resolve()),yr=_.useRef(null),Pn=_.useRef(null),Jn=_.useRef(-1),es=_.useRef(null),oi=_.useRef(0),W=_.useRef(null),Ie=_.useRef(null),Ye=_.useRef(0),nt=_.useRef(0),st=_.useRef(!1),yt=_.useRef(null),Pt=_.useRef(null),H=_.useRef(!1),ue=_.useRef(0),R=_.useRef(!1),U=_.useRef(!1),X=_.useRef(!1),be=_.useRef(null),Ee=_.useRef(null),Ve=_.useRef(null),ht=_.useRef(l);ht.current=l;const Qe=_.useRef(Me);Qe.current=Me;const ar=_.useRef(d);ar.current=d;const sr=_.useRef(Je),It=_.useRef(null),_r=_.useRef(null),on=_.useRef(null),bn=_.useRef(null),Jr=_.useRef(null),mn=_.useRef(null),dr=_.useRef(null),pr=_.useCallback(()=>{const oe=++ue.current,He=()=>{oe===ue.current&&rt(!0)};if(typeof window>"u"){He();return}window.requestAnimationFrame(()=>window.requestAnimationFrame(He))},[]),fs=_.useCallback(oe=>{if(R.current){if(Ee.current!==null&&(window.clearTimeout(Ee.current),Ee.current=null),oe.x===0&&oe.y>=oe.rows-1){Mt(!1);return}Ee.current=window.setTimeout(()=>{Ee.current=null,Mt(!0)},_N)}},[]),ws=_.useRef(null);_.useEffect(()=>()=>{ws.current?.()},[]);const Ss=_.useCallback(()=>{ws.current||(ws.current=ug(()=>{ws.current=null;const oe=Vr.getState(),He=xr.current,At=oe.getTerminalSession(q);if(!He||At?.mode!=="shell"||oe.hasPendingBufferWrites(q))return;const jt=k8(He),tt=br.current?.getDimensions();if(!jt||!tt)return;const L=br.current?.serializeSnapshot();L&&L8({id:He,version:1,...jt,...tt,data:L,savedAt:Date.now()})},2e3))},[q]),Fi=_.useCallback(oe=>{const He=Vr.getState(),At=He.getTerminalSession(q)?.bufferChunks.at(-1)?.id;if(xr.current&&At!==void 0&&At<=oe&&!He.hasPendingBufferWrites(q)&&(I8(xr.current),Ss()),!st.current||!cN({writtenChunkId:oe,initialTargetChunkId:yt.current}))return;const jt=Pt.current;Pt.current=null,jt!==null&&br.current?.notifyScreenSynchronized(jt),st.current=!1,yt.current=null,pr()},[pr,Ss,q]),Gl=_.useCallback(oe=>{if(!R.current)return;const He=be.current;He&&He.x===oe.x&&He.y===oe.y&&He.rows===oe.rows||(be.current=oe,Ee.current!==null&&(window.clearTimeout(Ee.current),Ee.current=null),oe.x===0&&oe.y>=oe.rows-1&&Mt(!1))},[]);_.useEffect(()=>{if(!f){U.current=!1;return}U.current||(U.current=!0,X.current=!1,R.current=!0,be.current=null,Mt(!1),Ee.current!==null&&(window.clearTimeout(Ee.current),Ee.current=null),Ve.current!==null&&window.clearTimeout(Ve.current),Ve.current=window.setTimeout(()=>{Ve.current=null,Ee.current!==null&&typeof window<"u"&&window.clearTimeout(Ee.current),Ee.current=null,R.current=!1,Mt(!0)},15e3))},[f]);const As=_.useCallback(()=>{bn.current=null;const oe=on.current;on.current=null,oe&&_n(oe.sessionId,oe.title)},[_n]),Is=_.useCallback((oe,He)=>{if(on.current={sessionId:oe,title:He},bn.current===null){if(typeof window>"u"){As();return}bn.current=window.requestAnimationFrame(As)}},[As]),li=_.useCallback(()=>{bn.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(bn.current),bn.current=null,on.current=null},[]),Aa=_.useCallback(async()=>{const oe=Y;return(await E8({preferredFrontendSessionId:q,mode:oe,tmuxSessionName:oe==="tmux"?Be||Kr:void 0,termType:"xterm-256color",requireExisting:!0})).terminalSession},[Y,Be,Kr,q]),Vl=_.useRef(l);_.useEffect(()=>{if(!l){br.current?.blur(),Vl.current=!1;return}if(Vl.current)return;Vl.current=!0;const oe=gI(Je,pe);if(oe==="single"){br.current?.requestRefresh("focus",{skipResizePush:!0,skipScrollToBottom:!0});return}oe!=="none"&&br.current?.requestRefresh("page-flip",{reconcileServerSize:!0,skipScrollToBottom:!0})},[l,Je,pe,Gr]),_.useEffect(()=>{sr.current=Je},[Je]);const Wn=_.useCallback(()=>{!ht.current||Qe.current||br.current?.focus()},[]);_.useLayoutEffect(()=>{Me&&br.current?.blur()},[Me]),_.useEffect(()=>{if(!l||Me||ir||X.current)return;X.current=!0;const oe=window.requestAnimationFrame(()=>{br.current?.requestPtyRedraw()});return()=>window.cancelAnimationFrame(oe)},[Me,l,ir]);const as=_.useCallback(oe=>{typeof window>"u"||typeof document>"u"||!ht.current||Qe.current||sr.current||document.hidden||!Bu()||(It.current!==null&&window.clearTimeout(It.current),It.current=window.setTimeout(()=>{if(It.current=null,!ht.current||Qe.current||sr.current||document.hidden||!Bu())return;const He=document.activeElement,At=He?.getAttribute("data-terminal-input-anchor")==="true";if((He instanceof HTMLInputElement||He instanceof HTMLTextAreaElement||He instanceof HTMLSelectElement||He?.isContentEditable===!0)&&!At){Te("desktop resume focus skipped: editable active",{reason:oe});return}Te("desktop resume focus",{reason:oe}),br.current?.requestRefresh("focus",{force:!0,forceRedraw:!0,skipResizePush:!0,skipScrollToBottom:!0}),br.current?.focus()},50))},[Te]);_.useEffect(()=>()=>{It.current!==null&&typeof window<"u"&&window.clearTimeout(It.current),It.current=null,_r.current!==null&&typeof window<"u"&&window.clearTimeout(_r.current),_r.current=null,Jr.current!==null&&typeof window<"u"&&window.clearTimeout(Jr.current),Jr.current=null,mn.current!==null&&typeof window<"u"&&window.clearTimeout(mn.current),mn.current=null,Ve.current!==null&&typeof window<"u"&&window.clearTimeout(Ve.current),Ve.current=null,Ee.current!==null&&typeof window<"u"&&window.clearTimeout(Ee.current),Ee.current=null},[]),_.useEffect(()=>{if(typeof document>"u"||typeof window>"u")return;const oe=()=>{_r.current!==null&&window.clearTimeout(_r.current),_r.current=window.setTimeout(()=>{_r.current=null;const He=document.activeElement,jt=!(He?.getAttribute("data-terminal-input-anchor")==="true")&&!!(He&&(He instanceof HTMLInputElement||He instanceof HTMLTextAreaElement||He instanceof HTMLSelectElement||He.isContentEditable));pC({isActive:ht.current&&!Qe.current,isMobile:sr.current,documentVisible:!document.hidden,activeElementIsEditable:jt})&&Wn()},0)};return document.addEventListener("pointerup",oe),()=>{document.removeEventListener("pointerup",oe),_r.current!==null&&(window.clearTimeout(_r.current),_r.current=null)}},[Wn]);const Es=_.useCallback(()=>{os.current=!1,Qn(oe=>oe+1)},[]),eo=_.useCallback((oe,He,At)=>{const jt=xr.current,tt=Date.now();if(jt&&He&&N8(jt)){se.current={startedAt:tt,strategy:"reconnect",reason:oe},Ma("info","PWA_RESUME terminal-start",{frontendSessionId:q,backendSessionId:jt,strategy:"reconnect",reason:oe,active:ht.current});return}if(jt&&R8(jt,()=>{const Rt=se.current;Ma("info","PWA_RESUME terminal-responsive",{frontendSessionId:q,backendSessionId:jt,durationMs:Rt?Date.now()-Rt.startedAt:null,strategy:Rt?.strategy??"probe",reason:Rt?.reason??oe}),se.current=null,F?.(q)},{visible:At})){se.current={startedAt:tt,strategy:"probe",reason:oe},Ma("info","PWA_RESUME terminal-start",{frontendSessionId:q,backendSessionId:jt,strategy:"probe",reason:oe,active:ht.current}),ye("[Terminal] resume probe sent",{reason:oe,backendSessionId:jt,active:ht.current});return}if(ye("[Terminal] resume probe missing connection, restarting ensureSession",{reason:oe,backendSessionId:jt,active:ht.current}),!uN({initialConnectionPending:H.current})){ye("[Terminal] resume probe deferred during initial websocket handshake",{reason:oe,backendSessionId:jt});return}Es()},[ye,F,Es,q]),zs=_.useCallback((oe,He)=>{const At=xr.current;At&&Bn.current!==oe&&(Bn.current=oe,Tx(At,oe,He),ye("[Terminal] flow-control state sent",{backendSessionId:At,paused:oe,reason:He}))},[ye]),Tl=_.useCallback((oe,He)=>{const At=xr.current;At&&W.current!==oe&&(W.current=oe,Sx(At,oe,He),ye("[Terminal] focus state sent",{backendSessionId:At,focused:oe,reason:He}))},[ye]),Da=_.useCallback((oe,He)=>{const At=xr.current;At&&Ie.current!==oe&&(Ie.current=oe,Cx(At,oe,He),ye("[Terminal] viewing state sent",{backendSessionId:At,viewing:oe,reason:He}))},[ye]),On=hC({isActive:l&&!Me,viewportFocused:me,documentVisible:ft,windowFocused:We,streamReady:z}),ki=fC({isActive:l,documentVisible:ft,windowFocused:We,streamReady:z,isDesktop:ea()!==null}),Ba=_.useRef(On),Eo=_.useRef(ki);_.useEffect(()=>{Ba.current=On,Tl(On,"logical-focus-change")},[On,Tl,Gr]),_.useEffect(()=>{Eo.current=ki,Da(ki,"logical-viewing-change")},[ki,Da,Gr]),HC(Gr,ft,z),_.useEffect(()=>{const oe=He=>{const At=He.detail;!At||At.sessionId!==q||qe(At.fontSize??n.fontSize)};return window.addEventListener("termfontchange",oe),()=>window.removeEventListener("termfontchange",oe)},[q,n.fontSize]),_.useEffect(()=>{const oe=()=>{const tt=!document.hidden&&Bu();Se(tt),tt&&l&&as("visibility")},He=tt=>{l&&as(tt.persisted?"bfcache":"pageshow")},At=()=>{Le(!0),as("window-focus")},jt=()=>Le(!1);return document.addEventListener("visibilitychange",oe),window.addEventListener(_x,oe),window.addEventListener("pageshow",He),window.addEventListener("focus",At),window.addEventListener("blur",jt),()=>{document.removeEventListener("visibilitychange",oe),window.removeEventListener(_x,oe),window.removeEventListener("pageshow",He),window.removeEventListener("focus",At),window.removeEventListener("blur",jt)}},[l,as]),_.useEffect(()=>{if(!y||!N||!Qa.current)return;const oe=v,He=oe<=0,At=Fe.current;if(At?.token===y&&(At.visible||!He))return;const jt=()=>{Fe.current={token:y,visible:He},br.current?.requestRefresh(w,{skipScrollToBottom:!0}),eo(oe>0?"global-resume-background":"global-resume-visible",oe<=0&&T,He)};if(oe<=0){jt();return}const tt=window.setTimeout(jt,oe);return()=>window.clearTimeout(tt)},[y,w,N,v,T,eo]);const ci=_.useRef(0);_.useEffect(()=>{if(z){ci.current=0;return}if(!Or||Qt==="Authentication required"||Qt===hf)return;const oe=ci.current,He=Math.min(2e3*Math.pow(2,Math.min(oe,4)),3e4),At=setTimeout(()=>{ci.current+=1,ye("[Terminal] fatal self-heal: auto restarting ensureSession",{attempt:ci.current,backendSessionId:xr.current}),er("Reconnecting..."),kr(!1),Es()},He);return()=>clearTimeout(At)},[Qt,Or,z,hn,ye,Es]),_.useEffect(()=>{if(typeof window>"u"){ze(!1);return}const oe=/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1;ze(oe)},[]),_.useEffect(()=>{(!l||!Je)&&ut(!1),l||dt(!1)},[l,Je]),_.useEffect(()=>{xr.current=Gr,Jn.current=-1,Pt.current=null,W.current=null,Ie.current=null,Bn.current=null},[Gr]),_.useEffect(()=>{B?.(q,z)},[z,B,q]),_.useEffect(()=>{$?.(q,z&&Ge&&vt)},[Ge,vt,z,$,q]),_.useEffect(()=>{Rr||(Ls.current=!1,yr.current=null,Pn.current&&(clearTimeout(Pn.current),Pn.current=null))},[Rr]),_.useEffect(()=>{Gr&&br.current?.requestRefresh("session-key-change",{force:!0})},[Gr]),_.useEffect(()=>{const oe=l&&Je&&Xt;Te("visibility signal",{sessionId:q,isActive:l,isMobile:Je,isInputFocused:at,isViewportKeyboardOpen:Xt,viewportKeyboardHeight:Bt,visible:oe}),ee?.(q,oe)},[ee,q,l,Je,Xt,Bt,Te]),_.useEffect(()=>{l&&x&&x!==oi.current&&(oi.current=x,Wn())},[x,Wn,l]),_.useEffect(()=>{vr.current=q},[q]),_.useEffect(()=>{!Je&&(Wt!==null||et!==null)&&(xe(null),ot(null),es.current=null)},[Je,Wt,et]),_.useEffect(()=>{!Gr&&(Wt!==null||et!==null)&&(xe(null),ot(null),es.current=null)},[Gr,Wt,et]),_.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(u5,Et?"true":"false")},[Et]),_.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(d5,xt)},[xt]),_.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(h5,$e)},[$e]),_.useEffect(()=>{Ne(ym());const oe=()=>{Ne(ym())};return window.addEventListener("resize",oe),()=>window.removeEventListener("resize",oe)},[]);const Fn=_.useCallback(()=>{Ye.current+=1,nt.current+=1,Qr.current=Promise.resolve(),As(),li();const oe=is.current;is.current=null,tn.current=null,H.current=!1,ge.current=!1,ie(!1),br.current?.setSessionReady(!1);const He=xr.current;He&&Tx(He,!1,"stream-disconnect"),us.current=!1,Bn.current=null,vs.current=[],oe?.()},[li,As]),Xs=_.useCallback(async oe=>{if(tn.current===oe){ye(`[startStream] Skipping - already connected to ${oe}`);return}ye(`[startStream] Starting stream for frontendSessionId=${q} backendSessionId=${oe}`),Hn(null),ue.current+=1,st.current=!1,yt.current=null,rt(!1),Yt(!1),Fn();const He=Ye.current+1;Ye.current=He,H.current=!0;const At=Vr.getState().getTerminalSession(q);if(At?.mode==="shell"&&!At.bufferChunks.length){const tt=await Promise.race([M8(oe),new Promise(Rt=>window.setTimeout(()=>Rt(null),75))]);if(Ye.current!==He||vr.current!==q)return;if(tt&&!Vr.getState().getTerminalSession(q)?.bufferChunks.length){Vr.getState().replaceBuffer(q,[tt.data]);const Rt=br.current?.getDimensions();Rt?.cols===tt.cols&&Rt.rows===tt.rows&&j8(oe,tt.seq,tt.epoch)}}const jt=ce.connect(oe,{onEvent:tt=>{if(Ye.current!==He)return;const Rt=q;if(Rt)switch(tt.type){case"connected":{nt.current+=1,Qr.current=Promise.resolve(),H.current=!1;const L=se.current;L&&(Ma("info","PWA_RESUME terminal-connected",{frontendSessionId:Rt,backendSessionId:xr.current,durationMs:Date.now()-L.startedAt,strategy:L.strategy,reason:L.reason}),se.current=null),F?.(Rt),(tt.runtime||tt.ptyBackend)&&ye(`[Terminal] connected frontendSessionId=${Rt} backendSessionId=${xr.current} runtime=${tt.runtime??"unknown"} pty=${tt.ptyBackend??"unknown"} cwd=${tt.cwd??"unknown"}`),Ur(Rt,!1),er(null),kr(!1),Hn(null),ge.current=!0,ie(!0),xr.current&&(Sx(xr.current,Ba.current,"stream-connected"),Cx(xr.current,Eo.current,"stream-connected")),br.current?.setSessionReady(!0),Bn.current=null,zs(us.current,"stream-connected"),tt.tuiProgress!==void 0&&Vr.getState().setSessionTuiProgress(Rt,tt.tuiProgress??null),tt.shellTitle!==void 0&&Vr.getState().setSessionShellTitle(Rt,tt.shellTitle??null),tt.promptState!==void 0&&tt.promptState!==null&&Vr.getState().setSessionPromptState(Rt,tt.promptState);const D=Vr.getState().getTerminalSession(Rt);if(D?.terminalSessionId&&tt.mode&&Vr.getState().setTerminalSession(Rt,{sessionId:D.terminalSessionId,cols:80,rows:24,mode:tt.mode,tmuxSessionName:tt.tmuxSessionName??null,cwd:tt.cwd??null}),tt.activeProgram!==void 0&&qr(Rt,tt.activeProgram??null,tt.activeProgramSource??null,tt.activeProgramRaw??null),br.current?.requestRefresh("connected",{force:!0,reconcileServerSize:ht.current}),tt.mode!=="tmux"&&(fn(null),Nr(Rt,!1)),ye("[Terminal] Connected event received:",{frontendSessionId:Rt,backendSessionId:xr.current,storeHasState:!!D,storeTerminalId:D?.terminalSessionId,hasHistoryInStore:!!D?.history?.length,historyLength:D?.history?.length??0}),D?.history&&D.history.length>0){ye(`[Terminal] Restoring ${D.history.length} history chunks to frontend session ${Rt}`);const Pe=D.history.reduce((Ke,gt)=>Ke+gt.length,0),ke=Math.max(300,Math.min(2e3,Math.ceil(Pe/200)));Bs.current=Date.now()+ke,D.history.forEach(Ke=>{ne(Rt,Ke,{markActivity:!1})}),Vr.getState().setSessionHistory(Rt,[]),ye(`[Terminal] History restoration complete for ${Rt}`)}else ye(`[Terminal] No history to restore for ${Rt}`);const O=tt.replayChunks,G=!!D?.history?.length||!!O?.length;if(G?st.current=!0:pr(),O&&O.length>0){let Pe=null;if(tt.replayOutOfWindow)br.current?.prepareScreenReplacement(),ye(`[Terminal] Replay out-of-window, atomically replacing buffer (${O.length} chunks)`),Pe=Ze(Rt,XC(O));else{ye(`[Terminal] Replay incremental: ${O.length} chunks`);for(const gt of O)ne(Rt,gt)}const ke=O.reduce((gt,Lt)=>gt+Lt.length,0),Ke=Math.max(200,Math.min(1500,Math.ceil(ke/200)));Bs.current=Math.max(Bs.current,Date.now()+Ke),yt.current=Pe}G&&yt.current===null&&(yt.current=Vr.getState().flushPendingBufferWrites(Rt),yt.current===null&&(st.current=!1,pr()));break}case"reconnecting":{ge.current=!1,ie(!1),Hn(L=>L??Date.now()),er("Reconnecting..."),kr(!1);break}case"data":{tt.data&&(us.current?vs.current.push(tt.data):ne(Rt,tt.data));break}case"tmux-layout":{fn(tt.layout??null),tt.layout&&Nr(Rt,tt.layout.inCopyMode);break}case"tmux-screen-sync":{const L=tt.generation??0;if(L<Jn.current)break;Jn.current=L,ue.current+=1,st.current=!0,rt(!1),vs.current=[],br.current?.prepareScreenReplacement(),Pt.current=L,yt.current=Ze(Rt,JC(tt.chunks??[])),yt.current===null&&(Pt.current=null,br.current?.notifyScreenSynchronized(L),st.current=!1,pr()),typeof tt.cols=="number"&&typeof tt.rows=="number"&&br.current?.notifyServerSize(tt.cols,tt.rows,"tmux-screen-sync");break}case"active-program":{qr(Rt,tt.activeProgram??null,tt.activeProgramSource??null,tt.activeProgramRaw??null);break}case"cwd":{sn(Rt,tt.cwd??null);break}case"agent-status":{Wr(Rt,{agentStatus:tt.agentStatus??null,agentIndicator:tt.agentIndicator??null,agentStatusDetail:tt.agentStatusDetail??null,agent:tt.agent??null,agentMessage:tt.agentMessage??null,agentNativeSessionId:tt.agentNativeSessionId??null,agentResumeRecovered:tt.agentResumeRecovered===!0,agentRich:tt.agentRich===!0,agentActivity:tt.agentActivity??0,agentCwd:tt.agentCwd??null,reviewed:tt.reviewed??null});break}case"git-status":{Vr.getState().setSessionGitStatus(Rt,tt.gitStatus??null);break}case"focus-mode":{ye("[Terminal] focus tracking mode",{backendSessionId:xr.current,requested:tt.focusTrackingRequested===!0});break}case"resize-ack":{br.current?.acknowledgeResize({seq:tt.seq,ok:tt.ok!==!1,cols:tt.cols,rows:tt.rows,screenSyncPending:tt.screenSyncPending,screenSyncGeneration:tt.screenSyncGeneration});break}case"pty-size":{typeof tt.cols=="number"&&typeof tt.rows=="number"&&br.current?.notifyServerSize(tt.cols,tt.rows,tt.source);break}case"shell-title":{Is(Rt,tt.title??null);break}case"prompt-state":{en(Rt,tt.state??"idle",tt.exitCode??null);break}case"tui-progress":{Vr.getState().setSessionTuiProgress(Rt,tt.tuiProgress??null);break}case"exit":{const L=typeof tt.exitCode=="number"?tt.exitCode:null,D=typeof tt.signal=="number"?tt.signal:null;ne(Rt,`\r
|
|
76
76
|
[Process exited${L!==null?` with code ${L}`:""}${D!==null?` (signal ${D})`:""}]\r
|
|
77
|
-
`),Dt(Rt),Ur(Rt,!1),er("Terminal session ended"),ie(!1),kr(!1),Hn(null),fn(null),Nr(Rt,!1),Fn();break}}},onError:(tt,Rt)=>{if(Ye.current!==He)return;const L=q;if(!L)return;H.current=!1,ge.current=!1,ie(!1);const D=tt.name==="TerminalInputError"&&"code"in tt&&tt.code==="TERMINAL_INPUT_REJECTED",O=Rt&&tt.message==="Authentication required",G=!D&&o5(tt),Pe=D||O?tt.message:G||Rt?"Reconnecting...":tt.message||"Terminal stream connection error";console.error(`[Terminal] Stream error (fatal=${Rt}):`,Pe),G&&console.warn("[Terminal] SESSION_NOT_FOUND_DETECTED",{terminalIdAtError:xr.current,frontendSessionId:L,isActive:l,isMobile:Je,fatal:Rt,stack:new Error().stack}),er(Pe),kr(!!Rt),Rt&&(Hn(null),Ur(L,!1),Fn(),G&&(ye("[onError] Session lost, auto-recreating"),er("Reconnecting..."),kr(!1),Dt(L),Pr(L),xr.current=null,os.current=!1,Es()))}},{...IN,getDimensions:()=>br.current?.getDimensions()??null});is.current=()=>{jt.close(),Ye.current===He&&(tn.current=null)},tn.current=oe},[ne,Pr,Dt,ye,Fn,pr,F,zs,Es,Is,Ur,qr,Wr,Nr,sn,en,ce,q]);_.useEffect(()=>{const oe=gN({isActive:l,isStreamReady:z,reconnectStartedAt:ss,now:Date.now()});if(oe===null)return;const He=window.setTimeout(()=>{ye("[Terminal] visible reconnect watchdog expired",{backendSessionId:xr.current,reconnectStartedAt:ss}),Fn(),Ur(q,!1),er("Reconnecting..."),kr(!1),Hn(Date.now()),Es()},oe);return()=>window.clearTimeout(He)},[ye,Fn,l,z,ss,Es,q,Ur]);const os=_.useRef(!1),Qa=_.useRef(!1),ds=_.useRef(0);_.useEffect(()=>()=>{ds.current+=1,os.current=!1,Fn()},[Fn]);const No=_.useRef(Y),Ko=_.useRef(Be);_.useEffect(()=>{const oe=No.current,He=Ko.current;No.current=Y,Ko.current=Be,vr.current===q&&(oe===Y&&He===Be||(os.current=!1,Fn(),Qn(At=>At+1)))},[Y,Be,Fn,q]),_.useEffect(()=>{if(vr.current!==q&&(ye(`[useEffect] sessionId changed from ${vr.current} to ${q}, allowing reinitialization`),os.current=!1,Qa.current=!1),os.current&&vr.current===q){ye(`[useEffect] Already initialized for sessionId=${q}, skipping`);return}if(!Ut)return;const oe=async Rt=>{if(ye(`[ensureSession] Starting for sessionId=${q}, runId=${Rt}`),!vr.current||vr.current!==q){ye(`[ensureSession] SessionId mismatch or stale run (current=${vr.current}, target=${q}), skipping`);return}if(Rt!==ds.current){ye(`[ensureSession] Stale run detected (runId=${Rt}, currentRunId=${ds.current}), skipping`);return}const L=Vr.getState(),D=L.getTerminalSession(q),O=D?.mode??Y;ye("[ensureSession] Current state from store:",{terminalSessionId:D?.terminalSessionId,mode:D?.mode,tmuxSessionName:D?.tmuxSessionName,isConnecting:D?.isConnecting});let G=D?.terminalSessionId??null,Pe=!G;if(G&&O!==Y?(ye(`[ensureSession] Store mode mismatch for ${G}: current=${O} desired=${Y}, will create new session`),Pe=!0,L.clearTerminalSession(q),G=null):G&&Y==="tmux"&&Be&&D?.tmuxSessionName!==Be&&(ye(`[ensureSession] Store tmux name mismatch for ${G}: current=${D?.tmuxSessionName} desired=${Be}, will create new session`),Pe=!0,L.clearTerminalSession(q),G=null),G&&ce.checkHealth&&!ht.current){ye(`[ensureSession] Checking health of existing session ${G}`);try{const ke=await ce.checkHealth(G);if(ye("[ensureSession] Health check result:",ke),!ke.healthy)ye(`[ensureSession] Session ${G} is NOT healthy (healthy=${ke.healthy}), will create new session`),ye("[ensureSession] Health check details:",ke),Pe=!0,ke.mode&&D?.terminalSessionId&&L.setTerminalSession(q,{sessionId:D.terminalSessionId,cols:80,rows:24,mode:ke.mode,tmuxSessionName:ke.tmuxSessionName??null}),L.clearTerminalSession(q),ye("[ensureSession] Cleared unhealthy session from store");else{ye(`[ensureSession] Session ${G} is healthy, reusing it, cwd=${ke.cwd}, clients=${ke.clients}, lastActivity=${Date.now()-(ke.lastActivity||0)}ms ago`),ke.mode&&D?.terminalSessionId&&L.setTerminalSession(q,{sessionId:D.terminalSessionId,cols:80,rows:24,mode:ke.mode,tmuxSessionName:ke.tmuxSessionName??null}),ye(`[ensureSession] Setting terminalIdRef to ${G} and starting stream`),xr.current=G,Xs(G),ye(`[ensureSession] Successfully reused healthy session ${G}, returning early`);return}}catch(ke){ye(`[ensureSession] Failed to check health of session ${G}:`,ke),ye("[ensureSession] Health check API call failed, proceeding as if session might be unhealthy")}}if(ye(`[ensureSession] Decision: shouldCreateNewSession=${Pe}, terminalId=${G}`),Pe){ye(`[ensureSession] Creating new session, shouldCreateNewSession=${Pe}, runId=${Rt}`),er(null),kr(!1),L.setConnecting(q,!0);const Ke=Vr.getState().getTerminalSession(q),Lt=(Ke?.mode??Y)===Y&&(Y!=="tmux"||!Be||Ke?.tmuxSessionName===Be);if(Ke?.terminalSessionId&&Lt)ye(`[ensureSession] Race condition avoided: another instance already created session ${Ke.terminalSessionId}`),L.setConnecting(q,!1),G=Ke.terminalSessionId,Pe=!1;else try{const Jt=await Aa();if(ye(`[ensureSession] Opened managed backend session ${Jt.sessionId}`),Rt!==ds.current){ye(`[ensureSession] Stale run after session creation (runId=${Rt}, currentRunId=${ds.current}), leaving ${Jt.sessionId} for sibling`);return}L.setTerminalSession(q,Jt),ye(`[ensureSession] Updated store with new session ${Jt.sessionId}`),G=Jt.sessionId}catch(Jt){if(Rt!==ds.current){ye("[ensureSession] Stale run after session creation failed, skipping error handling");return}if(Jt instanceof x0&&k1(Jt)){ye("[ensureSession] Confirmed missing persisted session:",{sessionId:q,error:Jt.message}),L.clearTerminalSession(q),er(hf),kr(!0),L.setConnecting(q,!1);return}er("Reconnecting..."),kr(!0),L.setConnecting(q,!1);return}}if(Rt!==ds.current){ye(`[ensureSession] Stale run before starting stream (runId=${Rt}, currentRunId=${ds.current}), skipping`);return}if(!G){ye(`[ensureSession] No terminalId, terminalId=${G}`);return}ye(`[ensureSession] Starting stream for session ${G}`),xr.current=G,Xs(G),ye(`[ensureSession] ensureSession completed for sessionId=${q}, terminalId=${G}`)};let He=null,At=null;const jt=()=>{At=null,!(os.current&&vr.current===q)&&(ye(`[useEffect] Running ensureSession for sessionId=${q}, hasInitialized=${os.current}`),os.current=!0,Qa.current=!0,He=++ds.current,oe(He))};if(!I&&!Qa.current){ye(`[useEffect] Holding background connection until the selected session is ready: ${q}`);return}const tt=Qa.current?0:Math.max(0,S);return tt>0?(ye(`[useEffect] Delaying initial connection for sessionId=${q} by ${tt}ms`),At=window.setTimeout(jt,tt)):jt(),()=>{At!==null&&window.clearTimeout(At),ye(`[useEffect] Cleanup for sessionId=${q}, runId=${He??"pending"}`)}},[q,hn,Xs,Fn,ce,ye,Y,Be,Kr,S,I,Ut]);const Ro=_.useCallback(async()=>{if(q&&!Zn){ys(!0),er(null),kr(!1),Hn(null),Fn();try{ce.forceKill&&await ce.forceKill({sessionId:q})}catch{}ur(q),Pr(q),br.current?.clear(),await new Promise(oe=>setTimeout(oe,100));try{Ur(q,!0);const oe=await Aa();Cn(q,oe),xr.current=oe.sessionId,Xs(oe.sessionId)}catch(oe){er(oe instanceof x0&&k1(oe)?hf:"Reconnecting..."),kr(!0),Ur(q,!1)}finally{ys(!1)}}},[q,Zn,Fn,ce,ur,Pr,Ur,Cn,Xs,Aa]),Ta=_.useCallback((oe,He,At,jt)=>{if(!(xr.current!==He||nt.current!==At)){if(oe instanceof x0&&o5(oe)){ye("[Terminal] operation backend missing, recovering",{terminalId:He,sessionId:q}),er("Reconnecting..."),kr(!1),Fn(),Dt(q),xr.current=null,Ur(q,!0),Es();return}er(oe instanceof Error?oe.message:jt)}},[Dt,ye,Fn,Es,q,Ur]),ra=_.useCallback((oe,He)=>{const At=He?.ownedPaste?UC(He.ownedPaste,q,oe):!1;if(He?.ownedPaste&&!At||ar.current||(Qe.current||rg())&&!At)return Promise.resolve(!1);const jt=()=>!!He?.ownedPaste&&zC(He.ownedPaste,q)&&ht.current&&!ar.current&&ge.current&&!nr.current&&!document.hidden&&navigator.onLine!==!1&&Bu();if(At&&!jt())return Promise.resolve(!1);if(!ht.current&&!He?.targeted||!oe)return;const tt=PE(oe),Rt=/^(\x1b\[<6[45];[0-9]+;[0-9]+M)+$/.test(oe);if(Date.now()<Bs.current)return Promise.resolve(!1);let L=oe,D=He?.consumeModifier??!1;if(!He?.skipModifierTransform&&Wt&&oe.length>0){const Ke=oe[0];if(Ke.length===1&&/[a-zA-Z]/.test(Ke)){const gt=Ke.toUpperCase();Wt==="ctrl"?(L=String.fromCharCode(gt.charCodeAt(0)&31),D=!0):Wt==="alt"&&(L=`\x1B${oe}`,D=!0)}D||(Wt==="alt"&&(L=`\x1B${oe}`),D=!0)}const O=xr.current;if(!O)return;const G=nt.current,Pe=async()=>{if(xr.current!==O||nt.current!==G)return!1;try{if(Rr&&Rt&&(Ls.current=!0),Rr&&!tt&&Ls.current&&ce.tmuxAction){Ls.current=!1;try{await ce.tmuxAction(O,{action:"copy-mode",enabled:!1})}catch{}if(xr.current!==O||nt.current!==G)return!1;if(OE(L))return!0}return At&&(!jt()||xr.current!==O||nt.current!==G)||(await ce.sendInput(O,L),At&&(!jt()||xr.current!==O||nt.current!==G))?!1:(Fr(q),!0)}catch(Ke){return Ta(Ke,O,G,"Failed to send input"),!1}},ke=Qr.current.then(Pe);return Qr.current=ke.then(()=>{},()=>{}),D&&(et||xe(null),Wn()),ke},[Wt,Fr,Wn,Ta,Rr,et,q,ce]);_.useEffect(()=>{const oe=He=>{const At=He,jt=At.detail?.sessionId;if(jt?jt!==q:!ht.current)return;const tt=At.detail?.text;if(!tt)return;const Rt=At.detail?.nonce;if(nr.current||!br.current){Rt&&window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:Rt,ok:!1}}));return}const L=$C(At.detail,q),D=At.detail?.ownedPaste&&!L?Promise.resolve(!1):br.current.sendSequence(tt,{paste:At.detail?.paste,submitAfterPaste:At.detail?.submitAfterPaste,targeted:!!jt,ownedPaste:L??void 0});Rt&&Promise.resolve(D).then(O=>{window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:Rt,ok:O===!0}}))},()=>{window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:Rt,ok:!1}}))}),mC(sr.current,At.detail?.focus!==!1)&&Wn()};return window.addEventListener("termdock-insert-reference",oe),()=>window.removeEventListener("termdock-insert-reference",oe)},[Wn,q]);const Ac=_.useCallback((oe,He,At)=>{const jt=xr.current;if(!jt){Te("xterm resize push skipped: no terminalId",{cols:oe,rows:He});return}Te("xterm resize push",{cols:oe,rows:He}),ce.resize({sessionId:jt,cols:oe,rows:He,seq:At}).catch(tt=>{br.current?.acknowledgeResize({seq:At,ok:!1}),tt&&/session not found/i.test(String(tt.message||tt))&&console.warn("[Terminal] resize 404 session not found",{sessionId:jt,cols:oe,rows:He,stack:new Error().stack})})},[ce,Te]),Li=_.useCallback(async oe=>{const He=xr.current;if(!He||!ce.tmuxAction)return;const At=nt.current;try{const jt=await ce.tmuxAction(He,oe);if(xr.current!==He||nt.current!==At)return;jt.layout&&(fn(jt.layout),oe.action==="switch-session"&&(Cn(q,{sessionId:He,cols:80,rows:24,mode:"tmux",tmuxSessionName:jt.layout.sessionName}),D8(q,{tmuxSessionName:jt.layout.sessionName}).catch(tt=>{console.warn("[Terminal] failed to update inventory after tmux switch",tt)})))}catch(jt){Ta(jt,He,At,"Failed to execute tmux action")}},[Ta,q,Cn,ce]);_.useEffect(()=>{if(!Xn||!Gr)return;const He=Xn.windows.find(At=>At.id===Xn.activeWindowId)?.panes.find(At=>At.id===Xn.activePaneId);He&&br.current?.requestRefresh("tmux-layout",{skipResizePush:!0,skipScrollToBottom:!0,dedupeKey:`${Gr}:${Xn.sessionId}:${He.id}:${He.width}x${He.height}`})},[Xn,Gr]);const Sl=_.useCallback((oe,He=5)=>{const At=Math.max(1,Math.min(Math.floor(He)||1,40));Ls.current=!0;const jt=yr.current;if(jt&&jt.direction===oe){jt.lines+=At;return}jt&&Li({action:"scroll",direction:jt.direction,lines:jt.lines}).finally(()=>{Wn()}),yr.current={direction:oe,lines:At},Pn.current&&clearTimeout(Pn.current),Pn.current=setTimeout(()=>{const tt=yr.current;tt&&(yr.current=null,Li({action:"scroll",direction:tt.direction,lines:tt.lines}).finally(()=>{Wn()}))},0)},[Wn,Li]),ql=_.useCallback(oe=>{const He=Date.now(),At=es.current,jt=At!==null&&At.modifier===oe&&He-At.timestamp<=CN;if(es.current={modifier:oe,timestamp:He},et===oe){ot(null),xe(null);return}if(jt){ot(oe),xe(oe);return}et!==null&&et!==oe&&ot(null),xe(tt=>tt===oe?null:oe)},[et]),ui=_.useCallback(oe=>{if(dt(oe&&ht.current),Te("input focus changed",{focused:oe,isActive:ht.current,isMobile:sr.current}),!sr.current||!ht.current){ut(!1);return}ut(He=>He===oe?He:oe)},[Te]),Js=_.useCallback(oe=>{if(us.current=oe,zs(oe,"viewport-watermark"),!oe&&vs.current.length>0){const He=q;if(He){const At=vs.current;vs.current=[];for(const jt of At)ne(He,jt)}}},[ne,zs,q]),di=_.useCallback(oe=>{ht.current&&br.current?.ensureSizeMatches(oe)},[]),Xo=_.useRef(null);_.useEffect(()=>{if(!l)return;const oe=Xo.current;if(!oe)return;const He=()=>di("pointerdown"),At=()=>di("keydown"),jt=()=>di("touchstart"),tt=()=>di("wheel");return oe.addEventListener("pointerdown",He),oe.addEventListener("keydown",At),oe.addEventListener("touchstart",jt,{passive:!0}),oe.addEventListener("wheel",tt,{passive:!0}),()=>{oe.removeEventListener("pointerdown",He),oe.removeEventListener("keydown",At),oe.removeEventListener("touchstart",jt),oe.removeEventListener("wheel",tt)}},[l,di]);const na=_.useCallback(oe=>{br.current=oe},[]),Cs=_.useCallback(oe=>{Nt(oe),P?.(q,oe)},[P,q]),hi=_.useCallback(oe=>{const He=VE(oe);if(!He)return;const At=Wt!==null;br.current?.sendSequence(He,{consumeModifier:At})},[Wt]),$i=_.useCallback(oe=>{const He=UE(oe);if(He.length===0)return;const At=Wt!==null;br.current?.sendSequence(n5(He[0]),{consumeModifier:At});for(let jt=1;jt<He.length;jt+=1){const tt=He[jt];window.setTimeout(()=>{br.current?.sendSequence(n5(tt))},$E*jt)}},[Wt]),Jo=_.useCallback(()=>{br.current?.pasteClipboardText()},[]),Ii=_.useCallback(oe=>{mn.current!==null&&(window.clearTimeout(mn.current),mn.current=null),tr(oe),(oe==="inserted"||oe==="failed")&&(mn.current=window.setTimeout(()=>{mn.current=null,tr("idle")},1400))},[]),Tc=_.useCallback(()=>{Ii("idle"),Ct(0),dr.current?.click()},[Ii]),Sc=_.useCallback(()=>{$t(!0)},[]),el=_.useCallback(oe=>{const He=oe.currentTarget.files?.[0];if(oe.currentTarget.value="",!He)return;const At=q;$r(null),Cr(null),Ft(null),Ct(0),Ii("uploading");const jt=An&&He.type.startsWith("video/")?{maxHeight:xn,videoBitrate:rn,onProgress:Ct}:null,tt=Oe&&kN(He)?{maxDimension:_t,quality:mt}:null;let Rt=jt?"视频压缩":tt?"图片压缩":"文件上传";(async()=>{const L=jt?await(await Vc(async()=>{const{compressVideoLocally:D}=await import("./videoCompression-DS0r00L6.js");return{compressVideoLocally:D}},__vite__mapDeps([0,1,2,3,4,5]))).compressVideoLocally(He,jt):tt?await(await Vc(async()=>{const{compressImageLocally:D}=await import("./imageCompression-DaUBNTq-.js");return{compressImageLocally:D}},[])).compressImageLocally(He,tt):He;Rt="文件上传",await AN(L,(D,O)=>W0(D,O,void 0,Ct),D=>(Rt="插入终端",c5(L1(D,null),At,()=>ht.current&&!nr.current&&vr.current===At&&Vr.getState().activeSessionId===At))),(jt||tt)&&Ft({file:L,kind:jt?"video":"image",originalSize:He.size,uploadedSize:L.size,originalRetained:L===He})})().then(()=>Ii("inserted"),L=>{L instanceof Bf&&$r({path:L.uploaded.path,sessionId:At});const D=L instanceof Bf?L.uploaded.path:f5(L);Cr({stage:Rt,detail:D}),$t(!0),Ii("failed"),Ma("warn","MOBILE_MEDIA_UPLOAD failed",{stage:Rt,detail:D})})},[rn,An,xn,Oe,_t,mt,q,Ii]),Qs=_.useCallback(async()=>{const oe=Ir;if(!oe||oe.sessionId!==q)return;$t(!1),await new Promise(At=>window.requestAnimationFrame(()=>At())),Ii("uploading"),await c5(L1(oe.path,null),oe.sessionId,()=>ht.current&&!nr.current&&vr.current===oe.sessionId&&Vr.getState().activeSessionId===oe.sessionId)?($r(null),Cr(null),Ii("inserted")):($t(!0),Ii("failed"))},[Ir,q,Ii]);_.useEffect(()=>{if(!Zt||!An)return;let oe=!0;return yn(null),Tn({phase:"checking-cache"}),Vc(async()=>{const{prepareLocalVideoCompression:He}=await import("./videoCompression-DS0r00L6.js");return{prepareLocalVideoCompression:He}},__vite__mapDeps([0,1,2,3,4,5])).then(({prepareLocalVideoCompression:He})=>{if(oe)return He(At=>{oe&&Tn(At)})}).catch(He=>{oe&&yn(f5(He))}),()=>{oe=!1}},[Zt,An]);const Ei=pn||Qt!==null;nr.current=Ei;const Ui=_.useRef(Xr);Ei||(Ui.current=Xr);const zi=Ei?Ui.current:Xr,sa=_.useMemo(()=>zE(zi,dn),[zi,dn]),ei=_.useMemo(()=>i5(dn,xt),[xt,dn]),Pa=!Je&&xt!=="auto"&&ei.id!=="default"&&ei.showOnDesktop!==!0?"auto":xt,Hi=Pa==="auto"?sa:Pa,ls=_.useMemo(()=>i5(dn,Hi),[Hi,dn]),gn=_.useMemo(()=>ls.actions.filter(oe=>oe.sequence.trim().length>0).map((oe,He)=>({...oe,label:_1(oe,He)})),[ls.actions]),ia=_.useMemo(()=>Av(Xr),[Xr]),fi=ls.label,Oa=_.useMemo(()=>Pa!=="auto"?`Manual preset: ${ls.label}`:ia?`Auto preset · ${ls.label} (${ia})`:"Auto preset",[ia,Pa,ls.label]),aa=_.useCallback(oe=>{rr(oe)},[]),to=_.useCallback(()=>{Dr(oe=>oe==="copy"?"arrows":"copy"),St("idle")},[]),pi=_.useCallback(()=>{typeof window>"u"||(Jr.current!==null&&window.clearTimeout(Jr.current),Jr.current=window.setTimeout(()=>{Jr.current=null,St("idle")},1200))},[]),Fa=_.useCallback(oe=>{Jr.current!==null&&typeof window<"u"&&(window.clearTimeout(Jr.current),Jr.current=null),St(oe?"copied":"failed"),pi()},[pi]),oa=_.useCallback(oe=>{K(oe)},[]),Sa=_.useMemo(()=>Je?HE(dn):WE(dn),[Je,dn]),mi=_.useMemo(()=>B8(a),[a]);_.useEffect(()=>{if(!Rr||!z||!Ut||!Gr)return;const oe=e_(mi);oe&&ce.sendInput(Gr,oe).catch(He=>{console.warn("[Terminal] Failed to synchronize tmux default colors:",He)})},[Rr,z,Ut,Gr,ce,mi]);const Wi=_.useMemo(()=>`terminal::${q}`,[q]),ps=_.useCallback(()=>`${xr.current??"pending"}:${nt.current}`,[]);_.useEffect(()=>{Re?.({isConnecting:pn,isRestarting:Zn,hasError:!!Qt,sessionId:Gr})},[pn,Zn,Qt,Gr,Re]);const Ca=!Gr||pn||Zn,ro=_.useCallback((oe,He)=>{if(Ca)return;const At=Math.max(1,Math.min(Math.floor(He)||1,40));Sl(oe,At)},[Sl,Ca]);_.useEffect(()=>{if(!l||!Je)return;br.current?.requestRefresh("resize",{skipScrollToBottom:!Xt,force:!0})},[l,Je,Xt,Bt,q]),_.useEffect(()=>{if(!l||!Je)return;const oe=He=>{const At=He.detail;br.current?.requestRefresh("resize",{skipScrollToBottom:At?.isOpen!==!0,force:!0})};return document.addEventListener("termdock:viewport-keyboard-change",oe),()=>{document.removeEventListener("termdock:viewport-keyboard-change",oe)}},[l,Je,q]);const Ps=!Z&&(Je||ls.id==="default"||ls.showOnDesktop===!0),no=l,Cl=Je&&!de?{transform:"translateY(var(--kb-translate-y, 0px))",transition:"none"}:void 0,Yl=Je&&!de?{marginTop:"var(--kb-margin-top, 0px)",transition:"none"}:void 0,Mo=s.jsx(qE,{visible:Ps,interactive:no,presentation:Je?"mobile":"desktop-actions",activeModifier:Wt,lockedModifier:et,disabled:Ca,defaultShowExtended:Et,presetLabel:fi,presetModeLabel:Oa,presetMode:Pa,presetOptions:Sa,includeAlt:ls.includeAlt,presetRowLayout:ls.rowLayout,extraActions:gn,onKeyPress:hi,onTextPress:$i,onPastePress:Je?Jo:void 0,onFilePress:Je?Tc:void 0,onFileLongPress:Je?Sc:void 0,fileUploadState:Ot,fileUploadProgress:ct,longPressMode:$e,copyFeedback:Ce,onLongPressModeToggle:to,onModifierToggle:ql,onPresetSelect:aa,onExpandedChange:oa}),so=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:Cl,"data-owned-terminal-startup":window.__TD_NATIVE_GATE_STATE?JSON.stringify({active:l,viewportReady:Ut,streamReady:z,contentReady:Ge,sizeReady:vt}):void 0,children:[s.jsx("input",{ref:dr,type:"file",className:"hidden",onChange:el}),Zt&&Ks.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:()=>$t(!1),"aria-label":Xe("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:()=>$t(!1),children:Xe("common.close")})]}),or&&s.jsxs("div",{role:"alert",className:"mt-3 rounded-lg bg-destructive/10 p-3 text-xs text-destructive",children:[s.jsxs("p",{children:[or.stage,"失败。",or.stage.endsWith("压缩")?"原文件未上传。":or.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:or.detail})]}),Ir&&s.jsx("button",{type:"button",onClick:()=>{Qs()},disabled:Ot==="uploading"||Ir.sessionId!==q,className:"mt-2 rounded-lg bg-surface-2 px-3 py-2 text-foreground disabled:opacity-50",children:Xe("common.retry")})]}),bt&&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:wt.showResultToast,onChange:oe=>it({showResultToast:oe.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:Oe,onChange:oe=>it({imageEnabled:oe.target.checked}),className:"h-4 w-4 accent-primary"})]}),Oe&&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:_t,onChange:oe=>it({imageMaxDimension:Number(oe.target.value)}),className:"mt-1 block min-h-10 w-full rounded-lg bg-surface-2 px-3 text-sm text-foreground",children:Iv.map(oe=>s.jsxs("option",{value:oe,children:[oe," px",oe===640?" · 最省流量":oe===2048?" · 推荐":oe===4096?" · 保留更多细节":""]},oe))})]}),s.jsxs("label",{className:"block text-xs text-muted-foreground",children:["图片画质:",Math.round(mt*100),"%",s.jsx("input",{type:"range",min:A0.min,max:A0.max,step:A0.step,value:mt,onChange:oe=>it({imageQuality:Number(oe.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:An,onChange:oe=>it({videoEnabled:oe.target.checked}),className:"h-4 w-4 accent-primary"})]}),An&&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:oe=>it({videoMaxHeight:Number(oe.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(oe=>s.jsxs("option",{value:oe,children:[oe," px",oe===240?" · 最省流量":oe===720?" · 推荐":oe>=1440?" · 手机处理较慢":""]},oe))})]}),s.jsxs("label",{className:"block text-xs text-muted-foreground",children:["目标视频码率:",rn/1e6," Mbps",s.jsx("input",{type:"range",min:T0.min,max:T0.max,step:T0.step,value:rn,onChange:oe=>it({videoBitrate:Number(oe.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:Dn?"本地转码器准备失败,请关闭开关后重试。":LN(wr)}),wr?.saved===!1&&s.jsx("p",{className:"text-[11px] text-destructive",children:"本机未能保存转码器,重新打开后可能需要重新下载。"}),Dn&&s.jsx("p",{className:"text-[11px] text-destructive",children:Dn})]})]})]}),document.body),cr&&s.jsx(YE,{isMobile:Je,isInputFocused:at,isIOS:ae,isConnecting:pn,connectionError:Qt,terminalSessionId:Gr}),s.jsxs("div",{className:"relative min-h-0 flex-1 overflow-hidden",style:{backgroundColor:mi.background,...Yl},children:[s.jsx("div",{ref:Xo,className:"h-full w-full box-border",children:s.jsx(Q8,{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:Xe("terminal.componentFailed")})]})}),children:s.jsx(NE,{ref:na,sessionKey:Wi,sessionId:q,getPasteOwnerKey:ps,backendSessionId:Gr,isLayoutVisible:m,chunks:zn,onInput:ra,onResize:Ac,onFlowControl:Js,onTmuxScroll:Rr?ro:void 0,tmuxScrollSensitivity:.38,onDoubleTap:Je?()=>{br.current?.sendSequence(" ")}:void 0,onInputFocusChange:ui,onMobileLongPressCopyResult:Fa,onReadyChange:Cs,onSizeSynchronizedChange:Yt,onWritesSettled:fs,onWriteProgress:Fi,onCursorPositionChange:Gl,onDirectoryLinkActivate:zr,terminalSettings:De,theme:mi,enableTouchScroll:Je,mobileLongPressMode:$e,autoFocus:l&&!Me&&!Je&&!so,inputActive:l&&!Me,cursorVisible:!Me&&ir,suppressSmoothScroll:!Ge||!vt,className:Me||!ir?"terminal-focus-suspended":void 0},Wi)})}),s.jsx(SN,{result:Tt,onDismiss:we}),s.jsx(KE,{connectionError:Qt,isFatalError:Or,isRestarting:Zn,isConnecting:pn,onHardRestart:Ro})]}),V?Z?null:Ks.createPortal(Mo,V):Mo]})};function NN({session:e,active:t,onActivate:r,onToggleRightSidebar:n}){const{t:a}=Hr(),c=Vr(l=>{const d=l.sessions.get(e.id);return gl(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(Zo,{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(sp,{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(d3,{size:14})})]})}const RN="termdock:startup:";function Gu(e){if(typeof performance>"u"||typeof performance.mark!="function")return;const t=`${RN}${e}`;performance.getEntriesByName(t,"mark").length>0||performance.mark(t)}function p5(e,t){e||Ks.flushSync(t)}const I1="horizontal";function Xu(e){return e<=0?[]:Array.from({length:e},()=>1/e)}function ff(e,t){if(!Array.isArray(e)||e.length!==t)return Xu(t);const r=e.map(Number);if(r.some(a=>!Number.isFinite(a)||a<=0))return Xu(t);const n=r.reduce((a,c)=>a+c,0);return n<=0?Xu(t):r.map(a=>a/n)}function MN(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 jN(e){return e==="horizontal"||e==="vertical"||e==="grid"}function DN(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 f=MN(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:jN(c.layout)?c.layout:I1,ratios:ff(c.ratios,d.length),...c.gridColumnRatios!==void 0?{gridColumnRatios:ff(c.gridColumnRatios,f.columns)}:{},...c.gridRowRatios!==void 0?{gridRowRatios:ff(c.gridRowRatios,f.rows)}:{}})}return n}function BN(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?ff(n.ratios,a.length):Xu(a.length)}]})}function B0(e,t){if(t)return e.find(r=>r.sessionIds.includes(t))}function vm(e,t,r){if(!t||!r||t===r)return e;const n=B0(e,t),a=B0(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===I1)?"grid":n?.layout??I1,ratios:Xu(l.length)},f=new Set([n?.id,a?.id].filter(Boolean)),m=e.filter(y=>!f.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 QN(e,t){const r=B0(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:Xu(n.length)}:a)}function PN(e,t){const r=B0(e,t);return r?e.filter(n=>n.id!==r.id):e}function ON(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 FN(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 E1=320,Rv=1,$N=E1+120,N1="termdock:split-workspaces:v2",Mv="termdock:split-workspace:v1",UN=.1,zN=.9;function wm(){if(typeof window>"u")return{mobile:!1,landscape:!1};const e=Gy();return{mobile:e,landscape:e&&window.innerWidth>window.innerHeight}}function HN(){if(typeof window>"u")return[];try{const e=window.localStorage.getItem(N1);if(e)return DN(JSON.parse(e));const t=JSON.parse(window.localStorage.getItem(Mv)||"null");if(t&&typeof t.primaryId=="string"&&typeof t.secondaryId=="string"&&t.primaryId!==t.secondaryId){const r=Math.min(zN,Math.max(UN,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 WN(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 f=d.sessionIds.flatMap(m=>{const x=r.get(m);return x?[x]:[]});f.length>=2&&c.push({key:d.id,sessions:f,workspace:d})}return c}function m5(e){const t=e.wrapperEl;if(t)try{t.getAnimations().forEach(r=>r.cancel())}catch{}}function Dh(e,t){const r=Qf(e,t);if(r===null)return;const n=e.wrapperEl;m5(e),n&&(n.style.transitionDuration="0ms");try{const a=e;a.setTransition?.(0),a.setTranslate?.(r),m5(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 R1(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 Qf(e,t){const r=e.snapGrid,n=Array.isArray(r)?r[t]:void 0;return typeof n!="number"||!Number.isFinite(n)?null:-n}function GN(e,t){const r=R1(e),n=Qf(e,t);return r!==null&&n!==null&&Math.abs(r-n)<=Rv}function VN(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 jv(e){const t=new Map;for(const r of e)t.set(r.id,r);return Array.from(t.values())}function Dv(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 qN(e,t){const r=jv(e),n=r.findIndex(a=>a.id===t.id);if(n>=0){const a=[...r];return a[n]=t,a}return[...r,t]}function g5(e,t){const r=new Map(e.map(n=>[n.id,n]));return t.map(n=>{const a=r.get(n.sessionId);return{...Dv(n),history:a?.history}})}function x5(e,t){return e.length===0?null:t&&e.some(r=>r.sessionId===t)?t:e[0]?.sessionId??null}function b5(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 y5(e){const t=new Map;for(const[r,n]of e)t.set(r,n.cwd??null);return t}function YN(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 ZN(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 KN=({terminalSettings:e=vg(),colorTheme:t="dark",toolbarPresets:r=[],showDebug:n,terminalFocusAvailable:a=!0,defaultSessionMode:c="shell",defaultTmuxSessionName:l="",connectionPrioritySessionId:d=null,connectionPriorityReady:f=!0,desktopRightSidebarEnabled:m=!1,onToggleRightSidebar:x,desktopFloatingTitle:y=!1,desktopLeftSidebarPinned:w=!1,desktopPinnedLeftSidebarWidth:v=0,desktopViewportWidth:T=0,onStatusChange:S,onSessionDataUpdate:I,onInitialViewportReady:N,onInitialRecoveryRequired:B})=>{const{t:F}=Hr(),P=y&&!w&&ea()?.platform==="darwin"&&document.documentElement.dataset.termdockPreview==="true",$=b.useMemo(()=>ed("session"),[]),ee=b.useMemo(()=>ed("terminal"),[]),[Z,V]=b.useState([]),[de,pe]=b.useState(null),J=b.useRef(0),Re=b.useRef(0),Xe=ns(R=>R.activePaneId);b.useEffect(()=>{ns.getState().setActivePane(de)},[de]);const[q,ve]=b.useState(null),[qe,ce]=b.useState(!0),[ye,Te]=b.useState({token:0,reason:"visibility",forceForegroundReconnect:!1}),[Fe,se]=b.useState(()=>new Set),[De,_e]=b.useState(()=>({token:0,completed:new Set})),[Me,Je]=b.useState(0),[Ne,ae]=b.useState(()=>new Set),[ze,at]=b.useState(()=>new Set),ut=b.useRef(new Map),[me,dt]=b.useState(()=>new Set),ft=b.useRef(!1),Se=b.useRef(null),We=b.useRef({}),[Le,z]=b.useState(null),[ie,ge]=b.useState(()=>HN()),[Ge,rt]=b.useState(!1),vt=b.useCallback(R=>{J.current+=1,rt(R)},[]),Yt=b.useRef(null),Ut=b.useRef(Ge);Ut.current=Ge,eu(Yt,Ge&&!!de,()=>vt(!1));const[Nt,ir]=b.useState(null),[Mt,Xt]=b.useState(null),Bt=b.useRef(new Set),[Wt,xe]=b.useState(null),[et,ot]=b.useState(null),[Et,K]=b.useState(!1),[xt,rr]=b.useState(()=>wm().mobile),[$e,Dr]=b.useState(()=>wm().landscape),[Ce,St]=b.useState(null),[Ot,tr]=b.useState(null),ct=b.useRef(a),Ct=b.useRef(!1),or=b.useRef(!1),Cr=b.useRef(null),Ir=b.useRef(null),$r=b.useRef(xt),Tt=b.useRef(null),Ft=b.useCallback(R=>{R!==Tt.current&&(J.current+=1),Tt.current=R,pe(R)},[]);b.useEffect(()=>Vt.subscribe((R,U)=>{(R.rightOpen!==U.rightOpen||R.rightTab!==U.rightTab)&&(J.current+=1)}),[]);const we=b.useRef(0),wt=b.useRef([]),it=b.useRef(0),bt=b.useRef(null),An=b.useRef(!1),xn=b.useRef(!0),rn=b.useRef(null),Oe=b.useRef(""),_t=b.useRef(0);b.useEffect(()=>{if(typeof window>"u")return;const R=()=>{const U=wm();$r.current=U.mobile,rr(U.mobile),Dr(U.landscape)};return R(),window.addEventListener("resize",R),()=>window.removeEventListener("resize",R)},[]);const{sessions:mt,inventory:Zt,activeSessionId:$t,isLoading:wr,openSession:Tn,setActiveSession:Dn,removeSession:yn,renameSession:un,resetSessionCustomName:Cn,reorderSessions:Ur,restoreSessions:ne}=P8(),Ze=Zt?.tmuxRecovery??null;b.useEffect(()=>{Ze&&B?.()},[Ze,B]),b.useEffect(()=>{ot(null),xe(null)},[Ze?.id]);const Dt=b.useCallback(async()=>{xe("restore"),ot(null);try{const R=await O8(Ze?.id);await ne(),R.accepted||ot(F("tab.tmuxRecoveryFailed"))}catch{ot(F("tab.tmuxRecoveryFailed"))}finally{xe(null)}},[ne,F,Ze?.id]),ur=b.useCallback(async()=>{const R=Ze?.operation;if(R)try{await F8(R.id,!R.paused),await ne()}catch{ot(F("tab.tmuxRecoveryFailed"))}},[ne,F,Ze?.operation]),Pr=b.useCallback(async()=>{xe("dismiss"),ot(null);try{await $8(),await ne()}catch{ot(F("tab.tmuxRecoveryDismissFailed"))}finally{xe(null)}},[ne,F]),qr=Vt(R=>R.groupByFolder),sn=kf(R=>R.collaborationGroups),Nr=Vt(R=>R.leftOpen||R.rightOpen),Wr=Vt(R=>R.rightSidebarWidthContextKey),_n=Vt(R=>R.rightSidebarWidth),en=Vt(R=>R.rightPinned),[Fr,Kr]=b.useState(()=>y5(Vr.getState().sessions));b.useEffect(()=>Vr.subscribe(R=>{const U=y5(R.sessions);Kr(X=>YN(X,U)?X:U)}),[]);const{arranged:gr}=b.useMemo(()=>Cf(Z,R=>Fr.get(R.id)??null,qr,"",ie,sn),[Z,Fr,qr,ie,sn]),an=b.useRef(gr);an.current=gr;const Xr=b.useMemo(()=>WN(gr,ie),[gr,ie]),dn=b.useRef(Xr);dn.current=Xr;const Rr=b.useMemo(()=>B0(ie,de),[de,ie]),zn=b.useMemo(()=>{const R=Xr.find(U=>U.sessions.some(X=>X.id===de));return new Set(R?.sessions.map(U=>U.id)??[])},[de,Xr]),pn=b.useMemo(()=>{const R=new Map;if(!m||T<=0)return R;for(const U of Xr){const X=U.sessions[0];if(!X)continue;const be=U8(X.id,Fr.get(X.id)??null,U.workspace?.id??null);if(!(be===Wr?en:z8(X.id,Fr.get(X.id)??null,U.workspace?.id??null)))continue;const Ve=be===Wr?_n:H8(X.id,Fr.get(X.id)??null,U.workspace?.id??null),ht=Jh(Ve,T,v);R.set(U.key,ht+Vy)}return R},[Fr,v,m,en,Wr,_n,T,Xr]),Gr=b.useMemo(()=>bm(Z.map(R=>({id:R.id,backendSessionId:R.sessionId})),d),[d,Z]),zr=b.useMemo(()=>x5(mt,$t),[$t,mt]),Y=Mh({prioritySessionId:Gr,activeSessionId:q??de,persistedActiveSessionId:zr,firstSessionId:Z[0]?.id??null}),Be=b.useMemo(()=>xN(Xr.flatMap(R=>R.sessions.map(U=>U.id)),zn),[zn,Xr]),Qt=Y!==null&&Fe.has(Y),er=b.useMemo(()=>{const R=new Set(zn);return q&&R.add(q),!R.size&&Y&&R.add(Y),R},[zn,q,Y]),nr=De.token===ye.token&&fN(er,De.completed),Or=nr||Me===ye.token?ye.token:-1;b.useEffect(()=>{if(!ye.token||nr)return;const R=window.setTimeout(()=>Je(ye.token),rN);return()=>window.clearTimeout(R)},[ye.token,nr]);const kr=b.useCallback((R,U)=>{se(X=>{if(X.has(R)===U)return X;const Ee=new Set(X);return U?Ee.add(R):Ee.delete(R),Ee})},[]),Zn=b.useCallback(R=>{const U=we.current;_e(be=>{if(be.token===U&&be.completed.has(R))return be;const Ee=new Set(be.token===U?be.completed:[]);return Ee.add(R),{token:U,completed:Ee}});const X=Gr??q??Tt.current;R===X&&Gu("foreground-stream-connected")},[q,Gr]),ys=b.useCallback((R,U)=>{ae(X=>{if(X.has(R)===U)return X;const be=new Set(X);return U?be.add(R):be.delete(R),be})},[]),ss=b.useCallback((R,U)=>{at(X=>{if(X.has(R)===U)return X;const be=new Set(X);return U?be.add(R):be.delete(R),be})},[]);b.useEffect(()=>{for(const[R,U]of ut.current){const X=Z.find(be=>be.id===R);if(!X||X.sessionId!==U.backendSessionId){ut.current.delete(R);continue}!Fe.has(R)||!Ne.has(R)||!ze.has(R)||(ut.current.delete(R),Wy(U.backendSessionId,`${U.command}\r`).catch(be=>{console.error("[Session] Failed to send startup command:",be)}))}},[Z,Fe,Ne,ze]);const Hn=Y!==null&&Ne.has(Y),hn=Y!==null&&ze.has(Y);b.useEffect(()=>{Hn&&Gu("foreground-viewport-ready")},[Hn]),b.useEffect(()=>{hn&&Gu("foreground-content-ready")},[hn]),b.useEffect(()=>{if(!N)return;if(!qe&&Z.length===0){N();return}if(!Hn||!Qt||!hn)return;const R=[...zn].every(Ve=>Ne.has(Ve)&&Fe.has(Ve)&&ze.has(Ve));let U=0,X=0;const be=()=>{U=requestAnimationFrame(()=>{X=requestAnimationFrame(()=>{Gu("initial-viewport-presented"),N()})})};R&&be();const Ee=R?void 0:window.setTimeout(be,8e3);return()=>{cancelAnimationFrame(U),cancelAnimationFrame(X),clearTimeout(Ee)}},[Qt,hn,Hn,qe,N,Z.length,zn,Ne,Fe,ze]);const Qn=b.useMemo(()=>xt?iN({slides:Xr.map(R=>R.sessions.map(U=>U.id)),visibleSessionIds:zn,foregroundSessionId:Y}):me,[xt,Xr,zn,Y,me]);b.useEffect(()=>{if(xt||zn.size===0)return;const R=new Set(zn),U=Xr.findIndex(X=>X.sessions.some(be=>zn.has(be.id)));for(let X=-2;X<=2;X+=1)X!==0&&Xr[U+X]?.sessions.forEach(be=>R.add(be.id));dt(X=>{let be=!1;const Ee=new Set(X);for(const Ve of R)Ee.has(Ve)||(Ee.add(Ve),be=!0);return be?Ee:X})},[xt,zn,Xr]);const Xn=BC(Qn);b.useEffect(()=>{if(!q)return;if(!Z.some(U=>U.id===q)){ve(null);return}if(!Ne.has(q)||!Fe.has(q)||!ze.has(q))return;const R=window.setTimeout(()=>{ve(U=>U===q?null:U),ct.current&&!$r.current&&z({sessionId:q,token:Date.now()})},80);return()=>window.clearTimeout(R)},[ze,q,Fe,Z,Ne]),b.useEffect(()=>{typeof window>"u"||(ie.length>0?(window.localStorage.setItem(N1,JSON.stringify(ie)),window.localStorage.removeItem(Mv)):window.localStorage.removeItem(N1))},[ie]),b.useEffect(()=>{wr||qe||ie.length===0||ge(R=>BN(R,Z.map(U=>U.id)))},[wr,qe,Z,ie.length]),b.useEffect(()=>{if(!Nt)return;const R=window.setTimeout(()=>ir(null),3200);return()=>window.clearTimeout(R)},[Nt]),Tt.current=de,we.current=ye.token,wt.current=Z,bt.current=$t,An.current=wr,xn.current=qe,ct.current=a;const fn=b.useCallback((R=Se.current)=>{const U=it.current,X=typeof window<"u"?window.visualViewport:null,be=R?R1(R):null,Ee=R?Qf(R,U):null;return{sessionsLength:wt.current.length,workspaceSlidesLength:dn.current.length,sessionIds:wt.current.map(Ve=>Ve.id),activeSessionId:Tt.current,activeSessionIndex:U,persistedActiveId:bt.current,isLoading:An.current,isRestoring:xn.current,activeIndex:R?.activeIndex??null,previousIndex:R?.previousIndex??null,animating:R?.animating??null,allowTouchMove:R?.allowTouchMove??null,width:R?.width??null,translate:be,targetTranslate:Ee,translateDelta:be!==null&&Ee!==null?be-Ee:null,snapGridLength:R?.snapGrid?.length??null,targetSnap:R?.snapGrid?.[U]??null,visualViewport:X?{width:Math.round(X.width),height:Math.round(X.height),offsetTop:Math.round(X.offsetTop)}:null}},[]),cr=b.useCallback((R,U)=>{$(R,{...fn(),...U})},[$,fn]);b.useEffect(()=>{wr||qe||de!==$t&&Dn(de)},[de,wr,qe,$t,Dn]);const is=b.useMemo(()=>{if(gr.length===0||!de)return 0;const R=Xr.findIndex(U=>U.sessions.some(X=>X.id===de));return R>=0?R:0},[Xr,de]);it.current=is;const tn=b.useCallback(()=>{Cr.current&&(clearTimeout(Cr.current),Cr.current=null)},[]),xr=b.useCallback(R=>{tn(),Cr.current=setTimeout(()=>{Cr.current=null,Ct.current=!1,cr("[swiper:touch-guard-clear]",{reason:R})},$N)},[tn,cr]),vr=b.useCallback((R,U={})=>{const X=Se.current,be=it.current,Ee=dn.current;if(!X||Ee.length===0||be<0||be>=Ee.length)return;if(Ct.current){cr("[swiper:sync-skip-touch]",{reason:R});return}if(X.animating){cr("[swiper:sync-skip-animating]",{reason:R});return}const Ve=R1(X),ht=Qf(X,be),Qe=Ve!==null&&ht!==null&&Math.abs(Ve-ht)<=Rv,ar=X.activeIndex===be;if(cr("[swiper:sync-check]",{reason:R,activeIndexAligned:ar,translateAligned:Qe,immediate:U.immediate===!0}),!(ar&&Qe)){if(ar){Dh(X,be),cr("[swiper:sync-forced-active]",{reason:R,translateAligned:Qe,immediate:U.immediate===!0});return}U.immediate?(Dh(X,be),X.slideTo(be,0,!1),Dh(X,be)):X.slideTo(be,E1,!1),cr("[swiper:sync-applied]",{reason:R,activeIndexAligned:ar,translateAligned:Qe,immediate:U.immediate===!0})}},[cr]);b.useEffect(()=>{const R=U=>{const X=U;Se.current&&(Se.current.allowTouchMove=!X.detail.locked),cr("[swiper:gesture-lock]",{locked:X.detail.locked})};return document.addEventListener("termdock:gesture-lock",R),()=>document.removeEventListener("termdock:gesture-lock",R)},[cr]),b.useEffect(()=>{if(Z.length===0){de!==null&&Ft(null);return}if(!de){if(!f)return;Ft(Mh({prioritySessionId:Gr,activeSessionId:null,persistedActiveSessionId:zr,firstSessionId:Z[0]?.id??null}));return}Z.some(U=>U.id===de)||Ft(Z[0].id)},[Z,de,f,Gr,zr]);const br=b.useCallback((R,U)=>{if(U&&Date.now()<_t.current){We.current[R]=!1;return}We.current[R]=U,tr(X=>U?R:X===R?null:X)},[]),us=b.useCallback(R=>{if(!Ct.current&&R.activeIndex!==it.current){cr("[swiper:slide-change-ignored-layout]",{instanceActiveIndex:R.activeIndex,expectedActiveIndex:it.current}),requestAnimationFrame(()=>vr("ignored-layout-slide-change",{immediate:!0}));return}const U=dn.current[R.activeIndex],X=U?.sessions.some(Ve=>Ve.id===de)?de:U?.sessions[0]?.id;if(cr("[swiper:slide-change]",{nextSessionId:X??null,instanceActiveIndex:R.activeIndex}),!X||X===de)return;const be=!!de&&We.current[de]===!0,Ee=ct.current&&(!$r.current||be);if(Ir.current=X,Ft(X),Ee){z({sessionId:X,token:Date.now()});return}z(null)},[Z,de,cr,vr]);b.useLayoutEffect(()=>{if(Ir.current===de){cr("[swiper:sync-skip-swiper-driven]",{activeSessionId:de}),Ir.current=null;return}vr("active-session-index",{immediate:!0})},[de,is,Z.length,vr,cr]),b.useEffect(()=>{const R=Se.current;if(!R)return;const U=Xr.length>1&&!Nr&&!Ge;R.allowTouchMove!==U&&(R.allowTouchMove=U,cr("[swiper:allow-touch-sync]",{nextAllow:U,sidebarOverlayOpen:Nr}))},[Xr.length,cr,Nr,Ge]);const Bn=b.useCallback(R=>{const U=Se.current;if(!U)return;const X=U.el;if(cr("[swiper:layout-before]",{reason:R,scrollLeft:X?.scrollLeft??null}),X&&(X.scrollLeft=0),U.updateSize(),U.updateSlides(),U.updateProgress(),U.updateSlidesClasses(),X&&(X.scrollLeft=0),cr("[swiper:layout-after]",{reason:R,scrollLeft:X?.scrollLeft??null}),Ct.current||U.animating){cr("[swiper:layout-skip-sync-motion]",{reason:R});return}vr(`layout:${R}`,{immediate:!0}),requestAnimationFrame(()=>{const be=Se.current;be&&(Ct.current||be.animating||Dh(be,it.current))})},[cr,vr]);b.useEffect(()=>()=>tn(),[tn]);const vs=Xr.map(R=>R.key).join("\0");b.useEffect(()=>{requestAnimationFrame(()=>Bn("group-change"))},[qr,vs,Bn]),b.useEffect(()=>{let R=null,U="mount";const X=Qe=>{U=Qe,R===null&&(R=requestAnimationFrame(()=>{R=null,Bn(`viewport-change:${U}`)}))},be=()=>X("window-resize"),Ee=()=>X("visual-viewport-resize"),Ve=()=>X("visual-viewport-scroll"),ht=Qe=>{X(`measured:${Qe.detail?.source??"unknown"}`)};return window.addEventListener("resize",be),window.visualViewport?.addEventListener("resize",Ee),window.visualViewport?.addEventListener("scroll",Ve),document.addEventListener(kx,ht),X("mount"),()=>{window.removeEventListener("resize",be),window.visualViewport?.removeEventListener("resize",Ee),window.visualViewport?.removeEventListener("scroll",Ve),document.removeEventListener(kx,ht),R!==null&&cancelAnimationFrame(R)}},[Bn]),b.useEffect(()=>{if(typeof document>"u")return;let R=null,U=null;const X=ar=>{if(ar!=="online"&&document.hidden)return;const sr=performance.now();if(!pN(U,sr))return;U=sr;const It=ar==="bfcache"||ar==="online"?ar:"visibility",_r=mN();Op(),Ma("info","PWA_RESUME scheduled",{source:ar,forceForegroundReconnect:_r,activeSessionId:Tt.current}),Te(on=>({token:on.token+1,reason:It,forceForegroundReconnect:_r})),requestAnimationFrame(()=>Bn(`resume:${ar}:raf`)),R&&clearTimeout(R),R=setTimeout(()=>{R=null,Bn(`resume:${ar}:settled`)},320)},be=()=>{if(document.hidden){Op();return}X("visibility")},Ee=()=>{Op()},Ve=ar=>{X(ar.persisted?"bfcache":"pageshow")},ht=()=>X("online"),Qe=()=>X("focus");return document.addEventListener("visibilitychange",be),window.addEventListener("pagehide",Ee),window.addEventListener("pageshow",Ve),window.addEventListener("online",ht),window.addEventListener("focus",Qe),()=>{document.removeEventListener("visibilitychange",be),window.removeEventListener("pagehide",Ee),window.removeEventListener("pageshow",Ve),window.removeEventListener("online",ht),window.removeEventListener("focus",Qe),R&&clearTimeout(R)}},[Bn]),b.useLayoutEffect(()=>{if(!dN(qe))return;const R=VN(Z),U=JSON.stringify(R);R.length>0&&U!==Oe.current?(Oe.current=U,console.warn("[session-invariant] duplicate mapping detected",R)):R.length===0&&Oe.current&&(Oe.current=""),I?.({sessions:Z.map(X=>({id:X.id,name:X.name,customName:X.customName,mode:X.mode,tmuxSessionName:X.tmuxSessionName})),activeSessionId:de,splitWorkspaces:ie.map(({id:X,name:be,sessionIds:Ee,layout:Ve})=>({id:X,...be?{name:be}:{},sessionIds:Ee,layout:Ve}))})},[Z,de,ie,I,qe]),b.useEffect(()=>{if(wr||ft.current)return;ft.current=!0;const R=bm(mt.map(Ve=>({id:Ve.sessionId,backendSessionId:Ve.backendSessionId??null})),d),U=x5(mt,$t),X=Mh({prioritySessionId:f?R:null,activeSessionId:null,persistedActiveSessionId:U,firstSessionId:mt[0]?.sessionId??null}),be=jv(mt.map(Dv));if($("[Session] Restoring",be.length,"persisted sessions (one-shot)"),cr("[swiper:restore-start]",{persistedSessionIds:mt.map(Ve=>Ve.sessionId),nextActiveSessionId:X}),be.length>0){const Ve=Vr.getState();be.forEach(Qe=>{Qe.sessionId&&Ve.setTerminalSession(Qe.id,{sessionId:Qe.sessionId,cols:80,rows:24,mode:Qe.mode,tmuxSessionName:Qe.tmuxSessionName,history:Qe.history})}),mt.forEach(Qe=>{Qe.agent!==void 0&&Ve.setSessionAgentIdentity(Qe.sessionId,Qe.agent),Qe.activeProgram!=null&&Ve.setSessionActiveProgram(Qe.sessionId,Qe.activeProgram),Qe.cwd!=null&&Ve.setSessionCwd(Qe.sessionId,Qe.cwd),Qe.shellTitle!=null&&Ve.setSessionShellTitle(Qe.sessionId,Qe.shellTitle)}),V(be);const ht=X||be[0]?.id||null;Ft(ht),cr("[swiper:restore-complete]",{restoredSessionIds:be.map(Qe=>Qe.id),nextActiveSessionId:ht})}(async()=>(be.length===0&&await rn.current?.({createIfEmpty:!0}),ce(!1),requestAnimationFrame(()=>vr("restore-finished",{immediate:!0}))))()},[wr,mt,$t,$,cr,vr,f,d]),b.useEffect(()=>{if(!f||qe||Z.length===0)return;const R=bm(Z.map(X=>({id:X.id,backendSessionId:X.sessionId})),d),U=Mh({prioritySessionId:R,activeSessionId:Tt.current,persistedActiveSessionId:zr,firstSessionId:Z[0]?.id??null});U&&U!==Tt.current&&Ft(U)},[f,d,qe,zr,Z]);const Bs=b.useRef([]),Ls=b.useRef(!1);Tt.current=de,b.useEffect(()=>{if(qe)return;const R=Bs.current,U=mt,X=new Map(R.map(It=>[It.sessionId,It])),be=Vr.getState();for(const It of U){const _r=X.get(It.sessionId),on=Vr.getState().sessions.get(It.sessionId);It.agent!==void 0&&JSON.stringify(It.agent)!==JSON.stringify(on?.agent)&&(on?.agent==null||JSON.stringify(It.agent)!==JSON.stringify(_r?.agent))&&be.setSessionAgentIdentity(It.sessionId,It.agent),It.activeProgram!=null&&It.activeProgram!==on?.activeProgram&&(on?.activeProgram==null||It.activeProgram!==_r?.activeProgram)&&be.setSessionActiveProgram(It.sessionId,It.activeProgram),It.cwd!=null&&It.cwd!==on?.cwd&&(on?.cwd==null||It.cwd!==_r?.cwd)&&be.setSessionCwd(It.sessionId,It.cwd),It.shellTitle!=null&&It.shellTitle!==on?.shellTitle&&(on?.shellTitle==null||It.shellTitle!==_r?.shellTitle)&&be.setSessionShellTitle(It.sessionId,It.shellTitle)}if(!Ls.current){V(It=>g5(It,U)),Bs.current=U,Ls.current=!0;return}const Ee=new Set(R.map(It=>It.sessionId)),Ve=new Set(U.map(It=>It.sessionId)),ht=new Map(R.map(It=>[It.sessionId,It.name]));Bs.current=U,V(It=>{const _r=g5(It,U);return(!Tt.current||!_r.some(on=>on.id===Tt.current))&&Ft(_r[0]?.id??null),_r});const Qe=U.filter(It=>!Ee.has(It.sessionId)),ar=[...Ee].filter(It=>!Ve.has(It)),sr=U.filter(It=>Ee.has(It.sessionId)&&ht.get(It.sessionId)!==It.name);(Qe.length>0||ar.length>0||sr.length>0)&&$("[Session] Synced persisted sessions:",{newSessionIds:Qe.map(It=>It.sessionId),removedSessionIds:ar,renamedSessionIds:sr.map(It=>It.sessionId),currentSessionIds:U.map(It=>It.sessionId)});for(const It of U){if(!It.backendSessionId)continue;Vr.getState().setTerminalSession(It.sessionId,{sessionId:It.backendSessionId,cols:80,rows:24,mode:It.mode,tmuxSessionName:It.tmuxSessionName})}},[mt,qe,$]);const Qr=b.useCallback(async R=>{const U=++Re.current,X=J.current,be=()=>U===Re.current&&X===J.current&&(R?.shouldActivate?.()??!0);try{const Ee=Vt.getState(),Ve=de?{rightOpen:Ee.rightOpen,rightPinned:Ee.rightPinned,rightSidebarWidth:Ee.rightSidebarWidth,rightTab:Ee.rightTab}:null,ht=R?.mode==="tmux"||R?.mode==="shell"?R.mode:c,Qe=(R?.tmuxSessionName||"").trim(),ar=l.trim(),sr=ht==="tmux"?Qe||ar||ZN():null,It=typeof R?.cwd=="string"?R.cwd:null,_r=de?Vr.getState().sessions.get(de)?.cwd??null:null,on=typeof It=="string"&&It.trim().length>0?It:typeof _r=="string"&&_r.trim().length>0?_r:void 0,bn=await Tn({preferredFrontendSessionId:R?.preferredFrontendSessionId,requireExisting:R?.requireExisting===!0,mode:ht,tmuxSessionName:sr,cwd:on,termType:"xterm-256color",createIfEmpty:R?.createIfEmpty===!0},{shouldActivate:be});if(bn.discarded)return R?.onResult?.({ok:!1,error:"unknown"}),null;const Jr=bn.session,mn=bn.terminalSession;!bn.reused&&Ve&&Vt.getState().initializeRightSidebarForSession(Jr.sessionId,mn.cwd??on??null,Ve);const dr={id:Jr.sessionId,name:Jr.name,customName:Jr.customName===!0,sessionId:mn.sessionId,mode:mn.mode??Jr.mode,tmuxSessionName:mn.tmuxSessionName??Jr.tmuxSessionName},pr=R?.command?.trim();return pr&&ut.current.set(dr.id,{backendSessionId:mn.sessionId,command:pr}),V(ws=>qN(ws,dr)),be()&&Ft(dr.id),Vr.getState().setTerminalSession(dr.id,{sessionId:mn.sessionId,cols:80,rows:24,mode:dr.mode,tmuxSessionName:dr.tmuxSessionName,activeProgram:mn.activeProgram,activeProgramRaw:mn.activeProgramRaw,activeProgramSource:mn.activeProgramSource,cwd:mn.cwd}),$("[Session] Inventory opened session:",{frontendSessionId:dr.id,backendSessionId:mn.sessionId,reused:bn.reused,mode:dr.mode,tmuxSessionName:dr.tmuxSessionName}),R?.onResult?.({ok:!0,sessionId:dr.id}),dr.id}catch(Ee){return console.error("[Session] Failed to create new session:",Ee),R?.onResult?.({ok:!1,error:SC(Ee)}),null}},[c,l,de,Tn,$]);rn.current=Qr;const yr=b.useCallback((R,U={})=>{J.current+=1,ns.getState().setActivePane(R);const X=Tt.current,be=!!X&&We.current[X]===!0;if(Ft(R),$r.current&&U.preserveMobileKeyboard===!1){_t.current=Date.now()+600,X&&(We.current[X]=!1),tr(null),z(null);const Ee=document.activeElement;Ee instanceof HTMLTextAreaElement&&Ee.closest(".terminal-viewport-container")&&Ee.blur();return}be&&$r.current&&tr(R),ct.current&&(!$r.current||be)&&z({sessionId:R,token:Date.now()})},[]),Pn=b.useCallback(R=>{Ft(R),vt(!0),ir(null)},[]),Jn=b.useCallback(R=>{const U=Tt.current;!U||U===R||(ge(X=>vm(X,U,R)),vt(!1),yr(U,{preserveMobileKeyboard:!1}))},[yr]),es=b.useCallback(async()=>{const R=Tt.current;if(!R||Et)return;const U=J.current;K(!0);const X=Vr.getState().sessions.get(R)?.cwd??void 0,be=await Qr({cwd:X||void 0,mode:c,shouldActivate:()=>!1});if(K(!1),!be){ir(F("common.error"));return}!Ut.current||U!==J.current||!wt.current.some(Ee=>Ee.id===R)||(ge(Ee=>vm(Ee,R,be)),vt(!1),yr(R,{preserveMobileKeyboard:!1}))},[yr,c,Qr,Et,F]),oi=b.useCallback(R=>{ge(U=>PN(U,R)),R&&yr(R,{preserveMobileKeyboard:!1})},[yr]),W=b.useCallback(R=>{ge(U=>QN(U,R)),yr(R,{preserveMobileKeyboard:!1})},[yr]),Ie=b.useCallback(R=>{if(Z.find(X=>X.id===R)){if(J.current+=1,ns.getState().setActivePane(R),R===Tt.current)return;if(Ft(R),!lN({isMobile:$r.current,viewportReady:Ne.has(R),streamReady:Fe.has(R),contentReady:ze.has(R)})){ve(null),ct.current&&z({sessionId:R,token:Date.now()}),$("[Session] Switched to session:",R);return}dt(be=>{if(be.has(R))return be;const Ee=new Set(be);return Ee.add(R),Ee}),ve(R),$("[Session] Switched to session:",R)}},[ze,$,Fe,Z,Ne]),Ye=b.useCallback((R,U)=>{U.trim()&&(V(X=>X.map(be=>be.id===R?{...be,name:U.trim(),customName:!0}:be)),un(R,U.trim()))},[un]),nt=b.useCallback(R=>{V(U=>U.map(X=>X.id===R?{...X,customName:!1}:X)),Cn(R)},[Cn]),st=b.useCallback(R=>{V(U=>{const X=new Map(U.map(ht=>[ht.id,ht])),be=R.map(ht=>X.get(ht)).filter(ht=>ht!==void 0),Ee=new Set(R),Ve=U.filter(ht=>!Ee.has(ht.id));return[...be,...Ve]}),Ur(R),$("[Session] Reordered sessions:",R),requestAnimationFrame(()=>{Se.current?.update()})},[Ur,$]),yt=b.useCallback(async R=>{const U=typeof R=="string"?R:R.sessionId,X=typeof R=="string"?"auto":R.closeMode??"auto",be=Z.find(Qe=>Qe.id===U);if(!be||Bt.current.has(U))return;Bt.current.add(U),J.current+=1;const Ee=Lx(gr,U,Qe=>Qe.id);try{X==="destroy"&&be.mode==="tmux"&&be.tmuxSessionName?(await qy(be.tmuxSessionName),$("[Session] Destroyed tmux session:",{frontendSessionId:be.id,tmuxSessionName:be.tmuxSessionName})):be.sessionId&&(await Hy(be.sessionId),$("[Session] Closed backend terminal:",be.sessionId))}catch(Qe){console.error("[Session] Failed to close backend terminal:",Qe),Xt({sessionId:U,closeMode:X});return}finally{Bt.current.delete(U)}Xt(Qe=>Qe?.sessionId===U?null:Qe);const ht=wt.current.filter(Qe=>Qe.id!==U).some(Qe=>Qe.id===Ee)?Ee:Lx(wt.current,U,Qe=>Qe.id);Tt.current===U&&Ft(ht),V(Qe=>Qe.filter(ar=>ar.id!==U)),yn(U,ht),delete We.current[U],$("[Session] Closed session:",{sessionId:U,closeMode:X})},[Z,gr,yn,$]),Pt=b.useCallback(R=>{if(!R)return;const U=Z.filter(X=>X.sessionId===R);if(U.length!==0){U.length>1&&console.warn("[session-invariant] backend matched multiple frontend sessions during cleanup",{backendSessionId:R,frontendSessionIds:U.map(X=>X.id)}),V(X=>{const be=X.filter(Ee=>Ee.sessionId!==R);return be.length!==X.length&&!be.some(Ve=>Ve.id===de)&&Ft(be.length>0?be[0].id:null),be});for(const X of U)yn(X.id),delete We.current[X.id];$("[Session] Backend gone, dropped local session(s):",U.map(X=>X.id))}},[Z,de,yn,$]);b.useEffect(()=>{const R=dr=>{Qr(dr.detail)},U=dr=>{Ie(dr.detail)},X=()=>{const dr=Tt.current;!dr||$r.current||z({sessionId:dr,token:Date.now()})},be=dr=>{const pr=dr;pr.detail&&Pn(pr.detail)},Ee=dr=>{const pr=dr.detail;oi(pr??Tt.current??void 0)},Ve=dr=>{const pr=dr.detail;pr&&W(pr)},ht=dr=>{const pr=dr.detail,fs=typeof pr=="string"?pr:pr?.layout,ws=typeof pr=="string"?Tt.current:pr?.sessionId;fs!=="horizontal"&&fs!=="vertical"&&fs!=="grid"||ge(Ss=>Ss.map(Fi=>Fi.sessionIds.includes(ws??"")?{...Fi,layout:fs}:Fi))},Qe=dr=>{const fs=dr.detail?.direction;if(fs!=="prev"&&fs!=="next")return;const ws=an.current;if(ws.length<=1)return;const Ss=Tt.current,Fi=Ss?ws.findIndex(Aa=>Aa.id===Ss):-1,Is=((Fi>=0?Fi:0)+(fs==="next"?1:-1)+ws.length)%ws.length,li=ws[Is]?.id;li&&li!==Ss&&Ie(li)},ar=dr=>{yt(dr.detail)},sr=dr=>{Pt(dr.detail)},It=dr=>{const pr=dr;!pr.detail?.sessionId||!pr.detail?.name||Ye(pr.detail.sessionId,pr.detail.name)},_r=dr=>{const pr=dr;pr.detail?.sessionId&&nt(pr.detail.sessionId)},on=dr=>{const pr=dr;pr.detail?.sessionIds&&st(pr.detail.sessionIds)},bn=dr=>{const pr=dr.detail;!pr?.workspaceId||!Array.isArray(pr.sessionIds)||ge(fs=>ON(fs,pr.workspaceId,pr.sessionIds))},Jr=dr=>{const pr=dr.detail;!pr?.workspaceId||typeof pr.name!="string"||ge(fs=>FN(fs,pr.workspaceId,pr.name))},mn=dr=>{const pr=dr.detail;!pr?.primaryId||!pr.secondaryId||pr.primaryId===pr.secondaryId||(ge(fs=>vm(fs,pr.primaryId,pr.secondaryId)),yr(pr.primaryId,{preserveMobileKeyboard:!1}))};return window.addEventListener("new-terminal-session",R),window.addEventListener("switch-terminal-session",U),window.addEventListener("focus-active-terminal-session",X),window.addEventListener("open-terminal-split-chooser",be),window.addEventListener("close-terminal-split",Ee),window.addEventListener("remove-terminal-split-pane",Ve),window.addEventListener("set-terminal-split-direction",ht),window.addEventListener("cycle-terminal-session",Qe),window.addEventListener("close-terminal-session",ar),window.addEventListener("close-terminal-session-by-backend",sr),window.addEventListener("rename-terminal-session",It),window.addEventListener("reset-terminal-session-name",_r),window.addEventListener("reorder-terminal-session",on),window.addEventListener("reorder-terminal-split-workspace",bn),window.addEventListener("rename-terminal-split-workspace",Jr),window.addEventListener("combine-terminal-split-sessions",mn),()=>{window.removeEventListener("new-terminal-session",R),window.removeEventListener("switch-terminal-session",U),window.removeEventListener("focus-active-terminal-session",X),window.removeEventListener("open-terminal-split-chooser",be),window.removeEventListener("close-terminal-split",Ee),window.removeEventListener("remove-terminal-split-pane",Ve),window.removeEventListener("set-terminal-split-direction",ht),window.removeEventListener("cycle-terminal-session",Qe),window.removeEventListener("close-terminal-session",ar),window.removeEventListener("close-terminal-session-by-backend",sr),window.removeEventListener("rename-terminal-session",It),window.removeEventListener("reset-terminal-session-name",_r),window.removeEventListener("reorder-terminal-session",on),window.removeEventListener("reorder-terminal-split-workspace",bn),window.removeEventListener("rename-terminal-split-workspace",Jr),window.removeEventListener("combine-terminal-split-sessions",mn)}},[yr,Qr,Ie,Pn,oi,W,yt,Pt,Ye,nt,st]),b.useEffect(()=>{if(!Rr||xt)return;const R=U=>{if(!QC(U,rg())||!(U.ctrlKey||U.metaKey)||!U.shiftKey)return;if(Rr.layout==="horizontal"?U.key==="ArrowLeft"||U.key==="ArrowRight":Rr.layout==="vertical"?U.key==="ArrowUp"||U.key==="ArrowDown":U.key.startsWith("Arrow")){U.preventDefault(),U.stopPropagation();const be=Rr.sessionIds.indexOf(Tt.current??""),Ee=U.key==="ArrowLeft"||U.key==="ArrowUp"?-1:1,Ve=(Math.max(0,be)+Ee+Rr.sessionIds.length)%Rr.sessionIds.length,ht=Rr.sessionIds[Ve];if(!ht)return;yr(ht);return}U.key==="Backspace"&&(U.preventDefault(),U.stopPropagation(),oi(Tt.current??void 0))};return window.addEventListener("keydown",R,!0),()=>window.removeEventListener("keydown",R,!0)},[yr,Rr,oi,xt]);const H=R=>{const U=Vr.getState().sessions.get(R.id);return gl(R,U?.activeProgram??null,U?.cwd??null,void 0,U?.shellTitle??null,U?.promptState??null)},ue=(R,U={})=>{const X=R.id===de&&!Xe?.startsWith("@collaboration:"),be=zn.has(R.id)&&!U.hidden,Ee=f&&oN({sessionId:R.id,foregroundSessionId:Y,visibleSessionIds:zn,deferredViewportSessionIds:xt?Xn:Qn}),Ve=aN({sessionId:R.id,foregroundSessionId:Y,foregroundReady:Qt,isVisible:be})&&f,ht=hN({sessionId:R.id,foregroundSessionId:Y,requestToken:ye.token,foregroundCompletedToken:Or,isVisible:er.has(R.id)})&&f,Qe=be||R.id===Y||Qn.has(R.id)?0:Be.get(R.id)??df;return s.jsxs("div",{className:`relative flex h-full min-h-0 min-w-0 flex-col overflow-hidden ${U.hidden?"invisible pointer-events-none":""}`,style:U.containerStyle,"aria-hidden":U.hidden||void 0,onPointerDownCapture:()=>{be&&p5(X,()=>yr(R.id))},onWheelCapture:()=>{p5(X,()=>yr(R.id))},children:[U.showPaneTitle&&s.jsx(NN,{session:R,active:X,onActivate:()=>yr(R.id),onToggleRightSidebar:X?x:void 0}),s.jsx("div",{className:"min-h-0 flex-1 app-chrome-bg",children:Ee&&s.jsx(EN,{sessionId:R.id,mode:R.mode,tmuxSessionName:R.tmuxSessionName,terminalSettings:e,colorTheme:t,toolbarPresets:r,isActive:X,focusSuspended:!a||q!==null,deferCursorUntilPositioned:q===R.id||R.mode==="tmux"&&!ze.has(R.id),isLayoutVisible:be,initialConnectEnabled:Ve&&ht,resumeRequestEnabled:ht,suppressKeyboard:U.suppressKeyboard,keyboardPortalTarget:U.keyboardPortalTarget,sharedMobileKeyboardLayout:U.sharedMobileKeyboardLayout,suppressPageFlipRefresh:U.suppressPageFlipRefresh,focusRequestToken:Le?.sessionId===R.id?Le.token:0,resumeRequestToken:ye.token,resumeRequestReason:ye.reason,forceResumeReconnect:ye.forceForegroundReconnect&&er.has(R.id),resumeRequestDelayMs:er.has(R.id)?0:U.hidden?df:Be.get(R.id)??df,initialConnectDelayMs:Qe,onStreamReadyChange:kr,onStreamConnected:Zn,onViewportReadyChange:ys,onContentReadyChange:ss,onKeyboardVisibilityChange:br,showDebug:n,onStatusChange:X?S:void 0})})]},R.id)};return s.jsxs("div",{className:"relative h-full flex flex-col",children:[Mt&&Z.some(R=>R.id===Mt.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:F("tab.closeFailed",{name:Z.find(R=>R.id===Mt.sessionId).name})}),s.jsx("button",{type:"button",className:"shrink-0 rounded-lg px-2 py-1 text-primary hover:bg-surface-2",onClick:()=>{yt(Mt)},children:F("common.retry")}),s.jsx("button",{type:"button",className:"shrink-0 rounded-lg p-1 hover:bg-surface-2","aria-label":F("common.close"),onClick:()=>Xt(null),children:s.jsx(Mn,{size:16})})]}),Ze&&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(sg,{size:18})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("h2",{className:"text-[13px] font-semibold text-foreground",children:F("tab.tmuxRecoveryTitle",{count:Ze.sessions.length})}),s.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-muted-foreground",children:F("tab.tmuxRecoveryHint")}),s.jsx("p",{className:"mt-1.5 truncate text-[10px] text-foreground/70",children:Ze.sessions.map(R=>R.name).join(" · ")}),Ze.operation&&s.jsxs("div",{className:"mt-2 rounded-lg bg-surface-2 px-2.5 py-2 text-[10px] text-muted-foreground","aria-live":"polite",children:[s.jsx("p",{children:F("tab.tmuxRecoveryProgress",{total:Ze.operation.total,queued:Ze.operation.queued,paused:Ze.operation.paused_count,resourceWait:Ze.operation.resource_wait,running:Ze.operation.running,succeeded:Ze.operation.succeeded,failed:Ze.operation.failed})}),Ze.operation.pauseReason==="resources"&&s.jsx("p",{className:"mt-1",children:F("tab.tmuxRecoveryPausedForResources")}),s.jsx("div",{className:"mt-1 max-h-24 overflow-y-auto",children:Ze.operation.items.map(R=>s.jsxs("p",{className:`mt-1 ${R.errorCode?"text-destructive":""}`,children:[R.sessionId,": ",R.errorCode??R.resourceWaitReason??R.phase,R.memAvailableBytes!==void 0?` · 可用内存 ${(R.memAvailableBytes/1024**3).toFixed(1)} GiB`:"",R.actualRssBytes!==void 0?` · 实际 RSS ${(R.actualRssBytes/1024**2).toFixed(0)} MiB`:"",R.estimatedRssBytes!==void 0&&R.actualRssBytes===void 0?` · 预估 RSS ${(R.estimatedRssBytes/1024**2).toFixed(0)} MiB`:""]},R.sessionId))})]}),et&&s.jsx("p",{className:"mt-2 text-[10px] text-destructive",children:et}),s.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[s.jsxs("button",{type:"button",disabled:Wt!==null||!!(Ze.operation&&!["succeeded","partial_failure"].includes(Ze.operation.state)),onClick:()=>{Dt()},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(h3,{size:13,className:Wt==="restore"?"animate-spin":""}),Wt==="restore"?F("tab.tmuxRecoveryRestoring"):Ze.operation&&!["succeeded","partial_failure"].includes(Ze.operation.state)?F("tab.tmuxRecoveryInProgress"):F("tab.tmuxRecoveryRestoreAll")]}),Ze.operation&&["queued","resource_wait","running","paused"].includes(Ze.operation.state)&&s.jsx("button",{type:"button",disabled:Wt!==null,onClick:()=>{ur()},className:"inline-flex min-h-9 items-center rounded-lg px-3 text-[11px] text-muted-foreground transition hover:bg-surface-2 disabled:opacity-50",children:Ze.operation.paused?F("tab.tmuxRecoveryResume"):F("tab.tmuxRecoveryPause")}),s.jsx("button",{type:"button",disabled:Wt!==null||!!(Ze.operation&&!["succeeded","partial_failure"].includes(Ze.operation.state)),onClick:()=>{Pr()},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:F("tab.tmuxRecoveryDismiss")})]})]})]})}),s.jsx("div",{className:"flex-1 overflow-hidden",children:s.jsx(IA,{onSwiper:R=>{Se.current=R,R.allowTouchMove=Xr.length>1&&!Nr&&!Ge,cr("[swiper:on-swiper]",{allowTouchMove:R.allowTouchMove}),requestAnimationFrame(()=>Bn("on-swiper"))},onSlideChange:us,onTouchStart:(R,U)=>{const X=b5(U),be=X==="touch"||X==="pen"||X==="unknown";ee("[swipe:touch-start]",{pointerType:X,allowed:be}),cr("[swiper:touch-start]",{pointerType:X,allowed:be}),be&&(tn(),or.current=!0,Ct.current=!0)},onTouchEnd:(R,U)=>{const X=b5(U),be=X==="touch"||X==="pen"||X==="unknown";ee("[swipe:touch-end]",{pointerType:X,allowed:be}),cr("[swiper:touch-end]",{pointerType:X,allowed:be}),be&&(or.current=!1,xr("touch-end"))},onTransitionEnd:()=>{const R=Se.current;if(or.current){cr("[swiper:transition-end-during-touch]");return}if(Ct.current&&R&&!GN(R,it.current)){cr("[swiper:transition-end-deferred]");return}tn(),Ct.current=!1,cr("[swiper:transition-end]")},initialSlide:Math.max(0,is),speed:E1,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:Xr.map(R=>{const U=R.workspace,X=!!U&&R.sessions.length>=2,be=xt?$e?"horizontal":"vertical":U?.layout??"horizontal",Ee=xt&&Ot?R.sessions.some(ht=>ht.id===Ot):!1,Ve=R.sessions.some(ht=>ht.id===de)?de:R.sessions[0]?.id;return s.jsx(EA,{className:"h-full",children:s.jsx("div",{className:"h-full min-w-0","data-pinned-right-sidebar-inset":pn.get(R.key)??0,style:{paddingRight:pn.get(R.key)??0,paddingTop:y&&!X?"2.5rem":void 0},children:X?s.jsxs("div",{className:"flex h-full min-h-0 min-w-0 flex-col bg-[var(--chrome-bg)]",style:xt?{transform:"translateY(var(--kb-translate-y, 0px))",transition:"none"}:void 0,children:[P&&!xt&&s.jsx("header",{"data-termdock-window-header":"true","data-split-window-header":"true",className:"flex h-[46px] min-h-[46px] shrink-0 items-center app-chrome-bg pl-[88px] pr-3 text-[12px] text-muted-foreground",children:s.jsx("span",{className:"min-w-0 truncate",children:U?.name||F("tab.splitWorkspace")})}),s.jsx(Ux,{layoutId:R.key,preset:U?.layout??"horizontal",initialTree:EC(R.sessions.map(ht=>ht.id),be,U?.ratios,U?.gridColumnRatios,U?.gridRowRatios),mobile:xt,focusId:Ee?Ot:null,panes:R.sessions.map(ht=>({id:ht.id,content:ue(ht,{showPaneTitle:!xt,suppressKeyboard:xt&&ht.id!==Ve,keyboardPortalTarget:xt?Ce:null,sharedMobileKeyboardLayout:xt,suppressPageFlipRefresh:!0})}))}),xt&&s.jsx("div",{ref:St,className:"relative shrink-0 app-chrome-bg","data-split-keyboard-host":"true"})]}):s.jsx(Ux,{layoutId:R.key,preset:U?.layout??"horizontal",mobile:xt,panes:[{id:R.sessions[0].id,content:ue(R.sessions[0])}]})})},R.key)})})}),Ge&&de&&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:()=>vt(!1),"aria-label":F("common.close")}),s.jsxs("section",{ref:Yt,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":F("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(Fl,{size:17})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("h2",{className:"text-[14px] font-semibold text-foreground",children:F("tab.splitTitle")}),s.jsx("p",{className:"mt-0.5 text-[11px] leading-relaxed text-muted-foreground",children:F("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:()=>vt(!1),"aria-label":F("common.close"),children:s.jsx(Mn,{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:Et,onClick:()=>{es()},className:"flex w-full items-center gap-3 rounded-xl px-3 py-3 text-left transition hover:bg-surface-2 active:bg-surface-elevated disabled:opacity-60",children:[s.jsx("span",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-primary/15 text-primary",children:s.jsx(Zs,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-[13px] font-medium text-foreground",children:F("tab.splitNew")}),s.jsx("span",{className:"mt-0.5 block text-[11px] text-muted-foreground",children:F("tab.splitNewHint")})]})]}),ie.filter(R=>R.id!==Rr?.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:F("tab.splitExistingGroups")}),ie.filter(R=>R.id!==Rr?.id).map((R,U)=>{const X=R.sessionIds.flatMap(Ve=>{const ht=Z.find(Qe=>Qe.id===Ve);return ht?[ht]:[]});if(X.length<2)return null;const be=R.name||`${F("tab.splitWorkspace")} ${U+1}`,Ee=X.map(Ve=>H(Ve).primary).join(" · ");return s.jsxs("button",{type:"button",onClick:()=>Jn(X[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(Fl,{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:be}),s.jsx("span",{className:"shrink-0 rounded-full bg-primary/10 px-1.5 py-0.5 text-[9px] font-medium text-primary",children:F("tab.splitOccupied")})]}),s.jsxs("span",{className:"mt-0.5 block truncate text-[10px] text-muted-foreground",children:[F("tab.sessionCount",{count:X.length})," · ",Ee]})]}),s.jsx(ai,{size:14,className:"text-primary opacity-0 transition group-hover:opacity-100"})]},R.id)})]}),s.jsx("div",{className:"px-3 pb-1 pt-3 text-[10px] font-medium uppercase tracking-[0.12em] text-muted-foreground",children:F("tab.splitAvailableSessions")}),Z.filter(R=>!ie.some(U=>U.sessionIds.includes(R.id))&&R.id!==de).length===0&&ie.filter(R=>R.id!==Rr?.id).length===0?s.jsx("p",{className:"px-3 py-4 text-[12px] text-muted-foreground",children:F("tab.splitNoOtherSessions")}):Z.filter(R=>!ie.some(U=>U.sessionIds.includes(R.id))&&R.id!==de).map(R=>{const U=Fr.get(R.id)??null,X=H(R);return s.jsxs("button",{type:"button",onClick:()=>Jn(R.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:U?s.jsx(tu,{size:15}):s.jsx(Fl,{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:X.primary}),s.jsx("span",{className:"mt-0.5 block truncate text-[10px] text-muted-foreground",children:U?cd(U)??U:R.name})]}),s.jsx(ai,{size:14,className:"text-primary opacity-0 transition group-hover:opacity-100"})]},R.id)})]})]})]}),Nt&&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:Nt})]})},XN={sm:"h-4 w-7",md:"h-6 w-10"},JN={sm:"h-3 w-3",md:"h-5 w-5"},eR={sm:"translate-x-3",md:"translate-x-4"};function yl({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 ${XN[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 ${JN[r]} ${e?eR[r]:""}`})})}function ya(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 tR=typeof Symbol=="function"&&Symbol.observable||"@@observable",v5=tR,w5=()=>Math.random().toString(36).substring(7).split("").join("."),rR={INIT:`@@redux/INIT${w5()}`,REPLACE:`@@redux/REPLACE${w5()}`},A5=rR;function nR(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 Bv(e,t,r){if(typeof e!="function")throw new Error(ya(2));if(typeof t=="function"&&typeof r=="function"||typeof r=="function"&&typeof arguments[3]=="function")throw new Error(ya(0));if(typeof t=="function"&&typeof r>"u"&&(r=t,t=void 0),typeof r<"u"){if(typeof r!="function")throw new Error(ya(1));return r(Bv)(e,t)}let n=e,a=t,c=new Map,l=c,d=0,f=!1;function m(){l===c&&(l=new Map,c.forEach((I,N)=>{l.set(N,I)}))}function x(){if(f)throw new Error(ya(3));return a}function y(I){if(typeof I!="function")throw new Error(ya(4));if(f)throw new Error(ya(5));let N=!0;m();const B=d++;return l.set(B,I),function(){if(N){if(f)throw new Error(ya(6));N=!1,m(),l.delete(B),c=null}}}function w(I){if(!nR(I))throw new Error(ya(7));if(typeof I.type>"u")throw new Error(ya(8));if(typeof I.type!="string")throw new Error(ya(17));if(f)throw new Error(ya(9));try{f=!0,a=n(a,I)}finally{f=!1}return(c=l).forEach(B=>{B()}),I}function v(I){if(typeof I!="function")throw new Error(ya(10));n=I,w({type:A5.REPLACE})}function T(){const I=y;return{subscribe(N){if(typeof N!="object"||N===null)throw new Error(ya(11));function B(){const P=N;P.next&&P.next(x())}return B(),{unsubscribe:I(B)}},[v5](){return this}}}return w({type:A5.INIT}),{dispatch:w,subscribe:y,getState:x,replaceReducer:v,[v5]:T}}function T5(e,t){return function(...r){return t(e.apply(this,r))}}function S5(e,t){if(typeof e=="function")return T5(e,t);if(typeof e!="object"||e===null)throw new Error(ya(16));const r={};for(const n in e){const a=e[n];typeof a=="function"&&(r[n]=T5(a,t))}return r}function Qv(...e){return e.length===0?t=>t:e.length===1?e[0]:e.reduce((t,r)=>(...n)=>t(r(...n)))}function sR(...e){return t=>(r,n)=>{const a=t(r,n);let c=()=>{throw new Error(ya(15))};const l={getState:a.getState,dispatch:(f,...m)=>c(f,...m)},d=e.map(f=>f(l));return c=Qv(...d)(a.dispatch),{...a,dispatch:c}}}var Am={exports:{}},Tm={};var C5;function iR(){if(C5)return Tm;C5=1;var e=UA();function t(f,m){return f===m&&(f!==0||1/f===1/m)||f!==f&&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 Tm.useSyncExternalStoreWithSelector=function(f,m,x,y,w){var v=a(null);if(v.current===null){var T={hasValue:!1,value:null};v.current=T}else T=v.current;v=l(function(){function I($){if(!N){if(N=!0,B=$,$=y($),w!==void 0&&T.hasValue){var ee=T.value;if(w(ee,$))return F=ee}return F=$}if(ee=F,r(B,$))return ee;var Z=y($);return w!==void 0&&w(ee,Z)?(B=$,ee):(B=$,F=Z)}var N=!1,B,F,P=x===void 0?null:x;return[function(){return I(m())},P===null?void 0:function(){return I(P())}]},[m,x,y,w]);var S=n(f,v[0],v[1]);return c(function(){T.hasValue=!0,T.value=S},[S]),d(S),S},Tm}var _5;function aR(){return _5||(_5=1,Am.exports=iR()),Am.exports}aR();var oR=b.version.startsWith("19"),lR=Symbol.for(oR?"react.transitional.element":"react.element"),cR=Symbol.for("react.portal"),uR=Symbol.for("react.fragment"),dR=Symbol.for("react.strict_mode"),hR=Symbol.for("react.profiler"),fR=Symbol.for("react.consumer"),pR=Symbol.for("react.context"),Pv=Symbol.for("react.forward_ref"),mR=Symbol.for("react.suspense"),gR=Symbol.for("react.suspense_list"),Cg=Symbol.for("react.memo"),xR=Symbol.for("react.lazy"),bR=Pv,yR=Cg;function vR(e){if(typeof e=="object"&&e!==null){const{$$typeof:t}=e;switch(t){case lR:switch(e=e.type,e){case uR:case hR:case dR:case mR:case gR:return e;default:switch(e=e&&e.$$typeof,e){case pR:case Pv:case xR:case Cg:return e;case fR:return e;default:return t}}case cR:return t}}}function wR(e){return vR(e)===Cg}function AR(e,t,r,n,{areStatesEqual:a,areOwnPropsEqual:c,areStatePropsEqual:l}){let d=!1,f,m,x,y,w;function v(B,F){return f=B,m=F,x=e(f,m),y=t(n,m),w=r(x,y,m),d=!0,w}function T(){return x=e(f,m),t.dependsOnOwnProps&&(y=t(n,m)),w=r(x,y,m),w}function S(){return e.dependsOnOwnProps&&(x=e(f,m)),t.dependsOnOwnProps&&(y=t(n,m)),w=r(x,y,m),w}function I(){const B=e(f,m),F=!l(B,x);return x=B,F&&(w=r(x,y,m)),w}function N(B,F){const P=!c(F,m),$=!a(B,f,F,m);return f=B,m=F,P&&$?T():P?S():$?I():w}return function(F,P){return d?N(F,P):v(F,P)}}function TR(e,{initMapStateToProps:t,initMapDispatchToProps:r,initMergeProps:n,...a}){const c=t(e,a),l=r(e,a),d=n(e,a);return AR(c,l,d,e,a)}function SR(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 M1(e){return function(r){const n=e(r);function a(){return n}return a.dependsOnOwnProps=!1,a}}function k5(e){return e.dependsOnOwnProps?!!e.dependsOnOwnProps:e.length!==1}function Ov(e,t){return function(n,{displayName:a}){const c=function(d,f){return c.dependsOnOwnProps?c.mapToProps(d,f):c.mapToProps(d,void 0)};return c.dependsOnOwnProps=!0,c.mapToProps=function(d,f){c.mapToProps=e,c.dependsOnOwnProps=k5(e);let m=c(d,f);return typeof m=="function"&&(c.mapToProps=m,c.dependsOnOwnProps=k5(m),m=c(d,f)),m},c}}function _g(e,t){return(r,n)=>{throw new Error(`Invalid value of type ${typeof e} for ${t} argument when connecting component ${n.wrappedComponentName}.`)}}function CR(e){return e&&typeof e=="object"?M1(t=>SR(e,t)):e?typeof e=="function"?Ov(e):_g(e,"mapDispatchToProps"):M1(t=>({dispatch:t}))}function _R(e){return e?typeof e=="function"?Ov(e):_g(e,"mapStateToProps"):M1(()=>({}))}function kR(e,t,r){return{...r,...e,...t}}function LR(e){return function(r,{displayName:n,areMergedPropsEqual:a}){let c=!1,l;return function(f,m,x){const y=e(f,m,x);return c?a(y,l)||(l=y):(c=!0,l=y),l}}}function IR(e){return e?typeof e=="function"?LR(e):_g(e,"mergeProps"):()=>kR}function ER(e){e()}function NR(){let e=null,t=null;return{clear(){e=null,t=null},notify(){ER(()=>{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 L5={notify(){},get:()=>[]};function Fv(e,t){let r,n=L5,a=0,c=!1;function l(S){x();const I=n.subscribe(S);let N=!1;return()=>{N||(N=!0,I(),y())}}function d(){n.notify()}function f(){T.onStateChange&&T.onStateChange()}function m(){return c}function x(){a++,r||(r=t?t.addNestedSub(f):e.subscribe(f),n=NR())}function y(){a--,r&&a===0&&(r(),r=void 0,n.clear(),n=L5)}function w(){c||(c=!0,x())}function v(){c&&(c=!1,y())}const T={addNestedSub:l,notifyNestedSubs:d,handleChangeWrapper:f,isSubscribed:m,trySubscribe:w,tryUnsubscribe:v,getListeners:()=>n};return T}var RR=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",MR=RR(),jR=()=>typeof navigator<"u"&&navigator.product==="ReactNative",DR=jR(),BR=()=>MR||DR?b.useLayoutEffect:b.useEffect,Pf=BR();function I5(e,t){return e===t?e!==0||t!==0||1/e===1/t:e!==e&&t!==t}function Sm(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 QR={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},PR={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},OR={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},$v={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},FR={[bR]:OR,[yR]:$v};function E5(e){return wR(e)?$v:FR[e.$$typeof]||QR}var $R=Object.defineProperty,UR=Object.getOwnPropertyNames,N5=Object.getOwnPropertySymbols,zR=Object.getOwnPropertyDescriptor,HR=Object.getPrototypeOf,R5=Object.prototype;function j1(e,t){if(typeof t!="string"){if(R5){const c=HR(t);c&&c!==R5&&j1(e,c)}let r=UR(t);N5&&(r=r.concat(N5(t)));const n=E5(e),a=E5(t);for(let c=0;c<r.length;++c){const l=r[c];if(!PR[l]&&!(a&&a[l])&&!(n&&n[l])){const d=zR(t,l);try{$R(e,l,d)}catch{}}}}return e}var WR=Symbol.for("react-redux-context"),GR=typeof globalThis<"u"?globalThis:{};function VR(){if(!b.createContext)return{};const e=GR[WR]??=new Map;let t=e.get(b.createContext);return t||(t=b.createContext(null),e.set(b.createContext,t)),t}var Uv=VR(),qR=[null,null];function YR(e,t,r){Pf(()=>e(...t),r)}function ZR(e,t,r,n,a,c){e.current=n,r.current=!1,a.current&&(a.current=null,c())}function KR(e,t,r,n,a,c,l,d,f,m,x){if(!e)return()=>{};let y=!1,w=null;const v=()=>{if(y||!d.current)return;const S=t.getState();let I,N;try{I=n(S,a.current)}catch(B){N=B,w=B}N||(w=null),I===c.current?l.current||m():(c.current=I,f.current=I,l.current=!0,x())};return r.onStateChange=v,r.trySubscribe(),v(),()=>{if(y=!0,r.tryUnsubscribe(),r.onStateChange=null,w)throw w}}function XR(e,t){return e===t}function JR(e,t,r,{pure:n,areStatesEqual:a=XR,areOwnPropsEqual:c=Sm,areStatePropsEqual:l=Sm,areMergedPropsEqual:d=Sm,forwardRef:f=!1,context:m=Uv}={}){const x=m,y=_R(e),w=CR(t),v=IR(r),T=!!e;return I=>{const N=I.displayName||I.name||"Component",B=`Connect(${N})`,F={shouldHandleStateChanges:T,displayName:B,wrappedComponentName:N,WrappedComponent:I,initMapStateToProps:y,initMapDispatchToProps:w,initMergeProps:v,areStatesEqual:a,areStatePropsEqual:l,areOwnPropsEqual:c,areMergedPropsEqual:d};function P(Z){const[V,de,pe]=b.useMemo(()=>{const{reactReduxForwardedRef:dt,...ft}=Z;return[Z.context,dt,ft]},[Z]),J=b.useMemo(()=>{let dt=x;return V?.Consumer,dt},[V,x]),Re=b.useContext(J),Xe=!!Z.store&&!!Z.store.getState&&!!Z.store.dispatch,q=!!Re&&!!Re.store,ve=Xe?Z.store:Re.store,qe=q?Re.getServerState:ve.getState,ce=b.useMemo(()=>TR(ve.dispatch,F),[ve]),[ye,Te]=b.useMemo(()=>{if(!T)return qR;const dt=Fv(ve,Xe?void 0:Re.subscription),ft=dt.notifyNestedSubs.bind(dt);return[dt,ft]},[ve,Xe,Re]),Fe=b.useMemo(()=>Xe?Re:{...Re,subscription:ye},[Xe,Re,ye]),se=b.useRef(void 0),De=b.useRef(pe),_e=b.useRef(void 0),Me=b.useRef(!1),Je=b.useRef(!1),Ne=b.useRef(void 0);Pf(()=>(Je.current=!0,()=>{Je.current=!1}),[]);const ae=b.useMemo(()=>()=>_e.current&&pe===De.current?_e.current:ce(ve.getState(),pe),[ve,pe]),ze=b.useMemo(()=>ft=>ye?KR(T,ve,ye,ce,De,se,Me,Je,_e,Te,ft):()=>{},[ye]);YR(ZR,[De,se,Me,pe,_e,Te]);let at;try{at=b.useSyncExternalStore(ze,ae,qe?()=>ce(qe(),pe):ae)}catch(dt){throw Ne.current&&(dt.message+=`
|
|
77
|
+
`),Dt(Rt),Ur(Rt,!1),er("Terminal session ended"),ie(!1),kr(!1),Hn(null),fn(null),Nr(Rt,!1),Fn();break}}},onError:(tt,Rt)=>{if(Ye.current!==He)return;const L=q;if(!L)return;H.current=!1,ge.current=!1,ie(!1);const D=tt.name==="TerminalInputError"&&"code"in tt&&tt.code==="TERMINAL_INPUT_REJECTED",O=Rt&&tt.message==="Authentication required",G=!D&&o5(tt),Pe=D||O?tt.message:G||Rt?"Reconnecting...":tt.message||"Terminal stream connection error";console.error(`[Terminal] Stream error (fatal=${Rt}):`,Pe),G&&console.warn("[Terminal] SESSION_NOT_FOUND_DETECTED",{terminalIdAtError:xr.current,frontendSessionId:L,isActive:l,isMobile:Je,fatal:Rt,stack:new Error().stack}),er(Pe),kr(!!Rt),Rt&&(Hn(null),Ur(L,!1),Fn(),G&&(ye("[onError] Session lost, auto-recreating"),er("Reconnecting..."),kr(!1),Dt(L),Pr(L),xr.current=null,os.current=!1,Es()))}},{...IN,getDimensions:()=>br.current?.getDimensions()??null});is.current=()=>{jt.close(),Ye.current===He&&(tn.current=null)},tn.current=oe},[ne,Pr,Dt,ye,Fn,pr,F,zs,Es,Is,Ur,qr,Wr,Nr,sn,en,ce,q]);_.useEffect(()=>{const oe=gN({isActive:l,isStreamReady:z,reconnectStartedAt:ss,now:Date.now()});if(oe===null)return;const He=window.setTimeout(()=>{ye("[Terminal] visible reconnect watchdog expired",{backendSessionId:xr.current,reconnectStartedAt:ss}),Fn(),Ur(q,!1),er("Reconnecting..."),kr(!1),Hn(Date.now()),Es()},oe);return()=>window.clearTimeout(He)},[ye,Fn,l,z,ss,Es,q,Ur]);const os=_.useRef(!1),Qa=_.useRef(!1),ds=_.useRef(0);_.useEffect(()=>()=>{ds.current+=1,os.current=!1,Fn()},[Fn]);const No=_.useRef(Y),Ko=_.useRef(Be);_.useEffect(()=>{const oe=No.current,He=Ko.current;No.current=Y,Ko.current=Be,vr.current===q&&(oe===Y&&He===Be||(os.current=!1,Fn(),Qn(At=>At+1)))},[Y,Be,Fn,q]),_.useEffect(()=>{if(vr.current!==q&&(ye(`[useEffect] sessionId changed from ${vr.current} to ${q}, allowing reinitialization`),os.current=!1,Qa.current=!1),os.current&&vr.current===q){ye(`[useEffect] Already initialized for sessionId=${q}, skipping`);return}if(!Ut)return;const oe=async Rt=>{if(ye(`[ensureSession] Starting for sessionId=${q}, runId=${Rt}`),!vr.current||vr.current!==q){ye(`[ensureSession] SessionId mismatch or stale run (current=${vr.current}, target=${q}), skipping`);return}if(Rt!==ds.current){ye(`[ensureSession] Stale run detected (runId=${Rt}, currentRunId=${ds.current}), skipping`);return}const L=Vr.getState(),D=L.getTerminalSession(q),O=D?.mode??Y;ye("[ensureSession] Current state from store:",{terminalSessionId:D?.terminalSessionId,mode:D?.mode,tmuxSessionName:D?.tmuxSessionName,isConnecting:D?.isConnecting});let G=D?.terminalSessionId??null,Pe=!G;if(G&&O!==Y?(ye(`[ensureSession] Store mode mismatch for ${G}: current=${O} desired=${Y}, will create new session`),Pe=!0,L.clearTerminalSession(q),G=null):G&&Y==="tmux"&&Be&&D?.tmuxSessionName!==Be&&(ye(`[ensureSession] Store tmux name mismatch for ${G}: current=${D?.tmuxSessionName} desired=${Be}, will create new session`),Pe=!0,L.clearTerminalSession(q),G=null),G&&ce.checkHealth&&!ht.current){ye(`[ensureSession] Checking health of existing session ${G}`);try{const ke=await ce.checkHealth(G);if(ye("[ensureSession] Health check result:",ke),!ke.healthy)ye(`[ensureSession] Session ${G} is NOT healthy (healthy=${ke.healthy}), will create new session`),ye("[ensureSession] Health check details:",ke),Pe=!0,ke.mode&&D?.terminalSessionId&&L.setTerminalSession(q,{sessionId:D.terminalSessionId,cols:80,rows:24,mode:ke.mode,tmuxSessionName:ke.tmuxSessionName??null}),L.clearTerminalSession(q),ye("[ensureSession] Cleared unhealthy session from store");else{ye(`[ensureSession] Session ${G} is healthy, reusing it, cwd=${ke.cwd}, clients=${ke.clients}, lastActivity=${Date.now()-(ke.lastActivity||0)}ms ago`),ke.mode&&D?.terminalSessionId&&L.setTerminalSession(q,{sessionId:D.terminalSessionId,cols:80,rows:24,mode:ke.mode,tmuxSessionName:ke.tmuxSessionName??null}),ye(`[ensureSession] Setting terminalIdRef to ${G} and starting stream`),xr.current=G,Xs(G),ye(`[ensureSession] Successfully reused healthy session ${G}, returning early`);return}}catch(ke){ye(`[ensureSession] Failed to check health of session ${G}:`,ke),ye("[ensureSession] Health check API call failed, proceeding as if session might be unhealthy")}}if(ye(`[ensureSession] Decision: shouldCreateNewSession=${Pe}, terminalId=${G}`),Pe){ye(`[ensureSession] Creating new session, shouldCreateNewSession=${Pe}, runId=${Rt}`),er(null),kr(!1),L.setConnecting(q,!0);const Ke=Vr.getState().getTerminalSession(q),Lt=(Ke?.mode??Y)===Y&&(Y!=="tmux"||!Be||Ke?.tmuxSessionName===Be);if(Ke?.terminalSessionId&&Lt)ye(`[ensureSession] Race condition avoided: another instance already created session ${Ke.terminalSessionId}`),L.setConnecting(q,!1),G=Ke.terminalSessionId,Pe=!1;else try{const Jt=await Aa();if(ye(`[ensureSession] Opened managed backend session ${Jt.sessionId}`),Rt!==ds.current){ye(`[ensureSession] Stale run after session creation (runId=${Rt}, currentRunId=${ds.current}), leaving ${Jt.sessionId} for sibling`);return}L.setTerminalSession(q,Jt),ye(`[ensureSession] Updated store with new session ${Jt.sessionId}`),G=Jt.sessionId}catch(Jt){if(Rt!==ds.current){ye("[ensureSession] Stale run after session creation failed, skipping error handling");return}if(Jt instanceof x0&&k1(Jt)){ye("[ensureSession] Confirmed missing persisted session:",{sessionId:q,error:Jt.message}),L.clearTerminalSession(q),er(hf),kr(!0),L.setConnecting(q,!1);return}er("Reconnecting..."),kr(!0),L.setConnecting(q,!1);return}}if(Rt!==ds.current){ye(`[ensureSession] Stale run before starting stream (runId=${Rt}, currentRunId=${ds.current}), skipping`);return}if(!G){ye(`[ensureSession] No terminalId, terminalId=${G}`);return}ye(`[ensureSession] Starting stream for session ${G}`),xr.current=G,Xs(G),ye(`[ensureSession] ensureSession completed for sessionId=${q}, terminalId=${G}`)};let He=null,At=null;const jt=()=>{At=null,!(os.current&&vr.current===q)&&(ye(`[useEffect] Running ensureSession for sessionId=${q}, hasInitialized=${os.current}`),os.current=!0,Qa.current=!0,He=++ds.current,oe(He))};if(!I&&!Qa.current){ye(`[useEffect] Holding background connection until the selected session is ready: ${q}`);return}const tt=Qa.current?0:Math.max(0,S);return tt>0?(ye(`[useEffect] Delaying initial connection for sessionId=${q} by ${tt}ms`),At=window.setTimeout(jt,tt)):jt(),()=>{At!==null&&window.clearTimeout(At),ye(`[useEffect] Cleanup for sessionId=${q}, runId=${He??"pending"}`)}},[q,hn,Xs,Fn,ce,ye,Y,Be,Kr,S,I,Ut]);const Ro=_.useCallback(async()=>{if(q&&!Zn){ys(!0),er(null),kr(!1),Hn(null),Fn();try{ce.forceKill&&await ce.forceKill({sessionId:q})}catch{}ur(q),Pr(q),br.current?.clear(),await new Promise(oe=>setTimeout(oe,100));try{Ur(q,!0);const oe=await Aa();Cn(q,oe),xr.current=oe.sessionId,Xs(oe.sessionId)}catch(oe){er(oe instanceof x0&&k1(oe)?hf:"Reconnecting..."),kr(!0),Ur(q,!1)}finally{ys(!1)}}},[q,Zn,Fn,ce,ur,Pr,Ur,Cn,Xs,Aa]),Ta=_.useCallback((oe,He,At,jt)=>{if(!(xr.current!==He||nt.current!==At)){if(oe instanceof x0&&o5(oe)){ye("[Terminal] operation backend missing, recovering",{terminalId:He,sessionId:q}),er("Reconnecting..."),kr(!1),Fn(),Dt(q),xr.current=null,Ur(q,!0),Es();return}er(oe instanceof Error?oe.message:jt)}},[Dt,ye,Fn,Es,q,Ur]),ra=_.useCallback((oe,He)=>{const At=He?.ownedPaste?UC(He.ownedPaste,q,oe):!1;if(He?.ownedPaste&&!At||ar.current||(Qe.current||rg())&&!At)return Promise.resolve(!1);const jt=()=>!!He?.ownedPaste&&zC(He.ownedPaste,q)&&ht.current&&!ar.current&&ge.current&&!nr.current&&!document.hidden&&navigator.onLine!==!1&&Bu();if(At&&!jt())return Promise.resolve(!1);if(!ht.current&&!He?.targeted||!oe)return;const tt=PE(oe),Rt=/^(\x1b\[<6[45];[0-9]+;[0-9]+M)+$/.test(oe);if(Date.now()<Bs.current)return Promise.resolve(!1);let L=oe,D=He?.consumeModifier??!1;if(!He?.skipModifierTransform&&Wt&&oe.length>0){const Ke=oe[0];if(Ke.length===1&&/[a-zA-Z]/.test(Ke)){const gt=Ke.toUpperCase();Wt==="ctrl"?(L=String.fromCharCode(gt.charCodeAt(0)&31),D=!0):Wt==="alt"&&(L=`\x1B${oe}`,D=!0)}D||(Wt==="alt"&&(L=`\x1B${oe}`),D=!0)}const O=xr.current;if(!O)return;const G=nt.current,Pe=async()=>{if(xr.current!==O||nt.current!==G)return!1;try{if(Rr&&Rt&&(Ls.current=!0),Rr&&!tt&&Ls.current&&ce.tmuxAction){Ls.current=!1;try{await ce.tmuxAction(O,{action:"copy-mode",enabled:!1})}catch{}if(xr.current!==O||nt.current!==G)return!1;if(OE(L))return!0}return At&&(!jt()||xr.current!==O||nt.current!==G)||(await ce.sendInput(O,L),At&&(!jt()||xr.current!==O||nt.current!==G))?!1:(Fr(q),!0)}catch(Ke){return Ta(Ke,O,G,"Failed to send input"),!1}},ke=Qr.current.then(Pe);return Qr.current=ke.then(()=>{},()=>{}),D&&(et||xe(null),Wn()),ke},[Wt,Fr,Wn,Ta,Rr,et,q,ce]);_.useEffect(()=>{const oe=He=>{const At=He,jt=At.detail?.sessionId;if(jt?jt!==q:!ht.current)return;const tt=At.detail?.text;if(!tt)return;const Rt=At.detail?.nonce;if(nr.current||!br.current){Rt&&window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:Rt,ok:!1}}));return}const L=$C(At.detail,q),D=At.detail?.ownedPaste&&!L?Promise.resolve(!1):br.current.sendSequence(tt,{paste:At.detail?.paste,submitAfterPaste:At.detail?.submitAfterPaste,targeted:!!jt,ownedPaste:L??void 0});Rt&&Promise.resolve(D).then(O=>{window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:Rt,ok:O===!0}}))},()=>{window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:Rt,ok:!1}}))}),mC(sr.current,At.detail?.focus!==!1)&&Wn()};return window.addEventListener("termdock-insert-reference",oe),()=>window.removeEventListener("termdock-insert-reference",oe)},[Wn,q]);const Ac=_.useCallback((oe,He,At)=>{const jt=xr.current;if(!jt){Te("xterm resize push skipped: no terminalId",{cols:oe,rows:He});return}Te("xterm resize push",{cols:oe,rows:He}),ce.resize({sessionId:jt,cols:oe,rows:He,seq:At}).catch(tt=>{br.current?.acknowledgeResize({seq:At,ok:!1}),tt&&/session not found/i.test(String(tt.message||tt))&&console.warn("[Terminal] resize 404 session not found",{sessionId:jt,cols:oe,rows:He,stack:new Error().stack})})},[ce,Te]),Li=_.useCallback(async oe=>{const He=xr.current;if(!He||!ce.tmuxAction)return;const At=nt.current;try{const jt=await ce.tmuxAction(He,oe);if(xr.current!==He||nt.current!==At)return;jt.layout&&(fn(jt.layout),oe.action==="switch-session"&&(Cn(q,{sessionId:He,cols:80,rows:24,mode:"tmux",tmuxSessionName:jt.layout.sessionName}),D8(q,{tmuxSessionName:jt.layout.sessionName}).catch(tt=>{console.warn("[Terminal] failed to update inventory after tmux switch",tt)})))}catch(jt){Ta(jt,He,At,"Failed to execute tmux action")}},[Ta,q,Cn,ce]);_.useEffect(()=>{if(!Xn||!Gr)return;const He=Xn.windows.find(At=>At.id===Xn.activeWindowId)?.panes.find(At=>At.id===Xn.activePaneId);He&&br.current?.requestRefresh("tmux-layout",{skipResizePush:!0,skipScrollToBottom:!0,dedupeKey:`${Gr}:${Xn.sessionId}:${He.id}:${He.width}x${He.height}`})},[Xn,Gr]);const Sl=_.useCallback((oe,He=5)=>{const At=Math.max(1,Math.min(Math.floor(He)||1,40));Ls.current=!0;const jt=yr.current;if(jt&&jt.direction===oe){jt.lines+=At;return}jt&&Li({action:"scroll",direction:jt.direction,lines:jt.lines}).finally(()=>{Wn()}),yr.current={direction:oe,lines:At},Pn.current&&clearTimeout(Pn.current),Pn.current=setTimeout(()=>{const tt=yr.current;tt&&(yr.current=null,Li({action:"scroll",direction:tt.direction,lines:tt.lines}).finally(()=>{Wn()}))},0)},[Wn,Li]),ql=_.useCallback(oe=>{const He=Date.now(),At=es.current,jt=At!==null&&At.modifier===oe&&He-At.timestamp<=CN;if(es.current={modifier:oe,timestamp:He},et===oe){ot(null),xe(null);return}if(jt){ot(oe),xe(oe);return}et!==null&&et!==oe&&ot(null),xe(tt=>tt===oe?null:oe)},[et]),ui=_.useCallback(oe=>{if(dt(oe&&ht.current),Te("input focus changed",{focused:oe,isActive:ht.current,isMobile:sr.current}),!sr.current||!ht.current){ut(!1);return}ut(He=>He===oe?He:oe)},[Te]),Js=_.useCallback(oe=>{if(us.current=oe,zs(oe,"viewport-watermark"),!oe&&vs.current.length>0){const He=q;if(He){const At=vs.current;vs.current=[];for(const jt of At)ne(He,jt)}}},[ne,zs,q]),di=_.useCallback(oe=>{ht.current&&br.current?.ensureSizeMatches(oe)},[]),Xo=_.useRef(null);_.useEffect(()=>{if(!l)return;const oe=Xo.current;if(!oe)return;const He=()=>di("pointerdown"),At=()=>di("keydown"),jt=()=>di("touchstart"),tt=()=>di("wheel");return oe.addEventListener("pointerdown",He),oe.addEventListener("keydown",At),oe.addEventListener("touchstart",jt,{passive:!0}),oe.addEventListener("wheel",tt,{passive:!0}),()=>{oe.removeEventListener("pointerdown",He),oe.removeEventListener("keydown",At),oe.removeEventListener("touchstart",jt),oe.removeEventListener("wheel",tt)}},[l,di]);const na=_.useCallback(oe=>{br.current=oe},[]),Cs=_.useCallback(oe=>{Nt(oe),P?.(q,oe)},[P,q]),hi=_.useCallback(oe=>{const He=VE(oe);if(!He)return;const At=Wt!==null;br.current?.sendSequence(He,{consumeModifier:At})},[Wt]),$i=_.useCallback(oe=>{const He=UE(oe);if(He.length===0)return;const At=Wt!==null;br.current?.sendSequence(n5(He[0]),{consumeModifier:At});for(let jt=1;jt<He.length;jt+=1){const tt=He[jt];window.setTimeout(()=>{br.current?.sendSequence(n5(tt))},$E*jt)}},[Wt]),Jo=_.useCallback(()=>{br.current?.pasteClipboardText()},[]),Ii=_.useCallback(oe=>{mn.current!==null&&(window.clearTimeout(mn.current),mn.current=null),tr(oe),(oe==="inserted"||oe==="failed")&&(mn.current=window.setTimeout(()=>{mn.current=null,tr("idle")},1400))},[]),Tc=_.useCallback(()=>{Ii("idle"),Ct(0),dr.current?.click()},[Ii]),Sc=_.useCallback(()=>{$t(!0)},[]),el=_.useCallback(oe=>{const He=oe.currentTarget.files?.[0];if(oe.currentTarget.value="",!He)return;const At=q;$r(null),Cr(null),Ft(null),Ct(0),Ii("uploading");const jt=An&&He.type.startsWith("video/")?{maxHeight:xn,videoBitrate:rn,onProgress:Ct}:null,tt=Oe&&kN(He)?{maxDimension:_t,quality:mt}:null;let Rt=jt?"视频压缩":tt?"图片压缩":"文件上传";(async()=>{const L=jt?await(await Vc(async()=>{const{compressVideoLocally:D}=await import("./videoCompression-DGfMcwdq.js");return{compressVideoLocally:D}},__vite__mapDeps([0,1,2,3,4,5]))).compressVideoLocally(He,jt):tt?await(await Vc(async()=>{const{compressImageLocally:D}=await import("./imageCompression-DaUBNTq-.js");return{compressImageLocally:D}},[])).compressImageLocally(He,tt):He;Rt="文件上传",await AN(L,(D,O)=>W0(D,O,void 0,Ct),D=>(Rt="插入终端",c5(L1(D,null),At,()=>ht.current&&!nr.current&&vr.current===At&&Vr.getState().activeSessionId===At))),(jt||tt)&&Ft({file:L,kind:jt?"video":"image",originalSize:He.size,uploadedSize:L.size,originalRetained:L===He})})().then(()=>Ii("inserted"),L=>{L instanceof Bf&&$r({path:L.uploaded.path,sessionId:At});const D=L instanceof Bf?L.uploaded.path:f5(L);Cr({stage:Rt,detail:D}),$t(!0),Ii("failed"),Ma("warn","MOBILE_MEDIA_UPLOAD failed",{stage:Rt,detail:D})})},[rn,An,xn,Oe,_t,mt,q,Ii]),Qs=_.useCallback(async()=>{const oe=Ir;if(!oe||oe.sessionId!==q)return;$t(!1),await new Promise(At=>window.requestAnimationFrame(()=>At())),Ii("uploading"),await c5(L1(oe.path,null),oe.sessionId,()=>ht.current&&!nr.current&&vr.current===oe.sessionId&&Vr.getState().activeSessionId===oe.sessionId)?($r(null),Cr(null),Ii("inserted")):($t(!0),Ii("failed"))},[Ir,q,Ii]);_.useEffect(()=>{if(!Zt||!An)return;let oe=!0;return yn(null),Tn({phase:"checking-cache"}),Vc(async()=>{const{prepareLocalVideoCompression:He}=await import("./videoCompression-DGfMcwdq.js");return{prepareLocalVideoCompression:He}},__vite__mapDeps([0,1,2,3,4,5])).then(({prepareLocalVideoCompression:He})=>{if(oe)return He(At=>{oe&&Tn(At)})}).catch(He=>{oe&&yn(f5(He))}),()=>{oe=!1}},[Zt,An]);const Ei=pn||Qt!==null;nr.current=Ei;const Ui=_.useRef(Xr);Ei||(Ui.current=Xr);const zi=Ei?Ui.current:Xr,sa=_.useMemo(()=>zE(zi,dn),[zi,dn]),ei=_.useMemo(()=>i5(dn,xt),[xt,dn]),Pa=!Je&&xt!=="auto"&&ei.id!=="default"&&ei.showOnDesktop!==!0?"auto":xt,Hi=Pa==="auto"?sa:Pa,ls=_.useMemo(()=>i5(dn,Hi),[Hi,dn]),gn=_.useMemo(()=>ls.actions.filter(oe=>oe.sequence.trim().length>0).map((oe,He)=>({...oe,label:_1(oe,He)})),[ls.actions]),ia=_.useMemo(()=>Av(Xr),[Xr]),fi=ls.label,Oa=_.useMemo(()=>Pa!=="auto"?`Manual preset: ${ls.label}`:ia?`Auto preset · ${ls.label} (${ia})`:"Auto preset",[ia,Pa,ls.label]),aa=_.useCallback(oe=>{rr(oe)},[]),to=_.useCallback(()=>{Dr(oe=>oe==="copy"?"arrows":"copy"),St("idle")},[]),pi=_.useCallback(()=>{typeof window>"u"||(Jr.current!==null&&window.clearTimeout(Jr.current),Jr.current=window.setTimeout(()=>{Jr.current=null,St("idle")},1200))},[]),Fa=_.useCallback(oe=>{Jr.current!==null&&typeof window<"u"&&(window.clearTimeout(Jr.current),Jr.current=null),St(oe?"copied":"failed"),pi()},[pi]),oa=_.useCallback(oe=>{K(oe)},[]),Sa=_.useMemo(()=>Je?HE(dn):WE(dn),[Je,dn]),mi=_.useMemo(()=>B8(a),[a]);_.useEffect(()=>{if(!Rr||!z||!Ut||!Gr)return;const oe=e_(mi);oe&&ce.sendInput(Gr,oe).catch(He=>{console.warn("[Terminal] Failed to synchronize tmux default colors:",He)})},[Rr,z,Ut,Gr,ce,mi]);const Wi=_.useMemo(()=>`terminal::${q}`,[q]),ps=_.useCallback(()=>`${xr.current??"pending"}:${nt.current}`,[]);_.useEffect(()=>{Re?.({isConnecting:pn,isRestarting:Zn,hasError:!!Qt,sessionId:Gr})},[pn,Zn,Qt,Gr,Re]);const Ca=!Gr||pn||Zn,ro=_.useCallback((oe,He)=>{if(Ca)return;const At=Math.max(1,Math.min(Math.floor(He)||1,40));Sl(oe,At)},[Sl,Ca]);_.useEffect(()=>{if(!l||!Je)return;br.current?.requestRefresh("resize",{skipScrollToBottom:!Xt,force:!0})},[l,Je,Xt,Bt,q]),_.useEffect(()=>{if(!l||!Je)return;const oe=He=>{const At=He.detail;br.current?.requestRefresh("resize",{skipScrollToBottom:At?.isOpen!==!0,force:!0})};return document.addEventListener("termdock:viewport-keyboard-change",oe),()=>{document.removeEventListener("termdock:viewport-keyboard-change",oe)}},[l,Je,q]);const Ps=!Z&&(Je||ls.id==="default"||ls.showOnDesktop===!0),no=l,Cl=Je&&!de?{transform:"translateY(var(--kb-translate-y, 0px))",transition:"none"}:void 0,Yl=Je&&!de?{marginTop:"var(--kb-margin-top, 0px)",transition:"none"}:void 0,Mo=s.jsx(qE,{visible:Ps,interactive:no,presentation:Je?"mobile":"desktop-actions",activeModifier:Wt,lockedModifier:et,disabled:Ca,defaultShowExtended:Et,presetLabel:fi,presetModeLabel:Oa,presetMode:Pa,presetOptions:Sa,includeAlt:ls.includeAlt,presetRowLayout:ls.rowLayout,extraActions:gn,onKeyPress:hi,onTextPress:$i,onPastePress:Je?Jo:void 0,onFilePress:Je?Tc:void 0,onFileLongPress:Je?Sc:void 0,fileUploadState:Ot,fileUploadProgress:ct,longPressMode:$e,copyFeedback:Ce,onLongPressModeToggle:to,onModifierToggle:ql,onPresetSelect:aa,onExpandedChange:oa}),so=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:Cl,"data-owned-terminal-startup":window.__TD_NATIVE_GATE_STATE?JSON.stringify({active:l,viewportReady:Ut,streamReady:z,contentReady:Ge,sizeReady:vt}):void 0,children:[s.jsx("input",{ref:dr,type:"file",className:"hidden",onChange:el}),Zt&&Ks.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:()=>$t(!1),"aria-label":Xe("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:()=>$t(!1),children:Xe("common.close")})]}),or&&s.jsxs("div",{role:"alert",className:"mt-3 rounded-lg bg-destructive/10 p-3 text-xs text-destructive",children:[s.jsxs("p",{children:[or.stage,"失败。",or.stage.endsWith("压缩")?"原文件未上传。":or.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:or.detail})]}),Ir&&s.jsx("button",{type:"button",onClick:()=>{Qs()},disabled:Ot==="uploading"||Ir.sessionId!==q,className:"mt-2 rounded-lg bg-surface-2 px-3 py-2 text-foreground disabled:opacity-50",children:Xe("common.retry")})]}),bt&&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:wt.showResultToast,onChange:oe=>it({showResultToast:oe.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:Oe,onChange:oe=>it({imageEnabled:oe.target.checked}),className:"h-4 w-4 accent-primary"})]}),Oe&&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:_t,onChange:oe=>it({imageMaxDimension:Number(oe.target.value)}),className:"mt-1 block min-h-10 w-full rounded-lg bg-surface-2 px-3 text-sm text-foreground",children:Iv.map(oe=>s.jsxs("option",{value:oe,children:[oe," px",oe===640?" · 最省流量":oe===2048?" · 推荐":oe===4096?" · 保留更多细节":""]},oe))})]}),s.jsxs("label",{className:"block text-xs text-muted-foreground",children:["图片画质:",Math.round(mt*100),"%",s.jsx("input",{type:"range",min:A0.min,max:A0.max,step:A0.step,value:mt,onChange:oe=>it({imageQuality:Number(oe.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:An,onChange:oe=>it({videoEnabled:oe.target.checked}),className:"h-4 w-4 accent-primary"})]}),An&&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:oe=>it({videoMaxHeight:Number(oe.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(oe=>s.jsxs("option",{value:oe,children:[oe," px",oe===240?" · 最省流量":oe===720?" · 推荐":oe>=1440?" · 手机处理较慢":""]},oe))})]}),s.jsxs("label",{className:"block text-xs text-muted-foreground",children:["目标视频码率:",rn/1e6," Mbps",s.jsx("input",{type:"range",min:T0.min,max:T0.max,step:T0.step,value:rn,onChange:oe=>it({videoBitrate:Number(oe.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:Dn?"本地转码器准备失败,请关闭开关后重试。":LN(wr)}),wr?.saved===!1&&s.jsx("p",{className:"text-[11px] text-destructive",children:"本机未能保存转码器,重新打开后可能需要重新下载。"}),Dn&&s.jsx("p",{className:"text-[11px] text-destructive",children:Dn})]})]})]}),document.body),cr&&s.jsx(YE,{isMobile:Je,isInputFocused:at,isIOS:ae,isConnecting:pn,connectionError:Qt,terminalSessionId:Gr}),s.jsxs("div",{className:"relative min-h-0 flex-1 overflow-hidden",style:{backgroundColor:mi.background,...Yl},children:[s.jsx("div",{ref:Xo,className:"h-full w-full box-border",children:s.jsx(Q8,{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:Xe("terminal.componentFailed")})]})}),children:s.jsx(NE,{ref:na,sessionKey:Wi,sessionId:q,getPasteOwnerKey:ps,backendSessionId:Gr,isLayoutVisible:m,chunks:zn,onInput:ra,onResize:Ac,onFlowControl:Js,onTmuxScroll:Rr?ro:void 0,tmuxScrollSensitivity:.38,onDoubleTap:Je?()=>{br.current?.sendSequence(" ")}:void 0,onInputFocusChange:ui,onMobileLongPressCopyResult:Fa,onReadyChange:Cs,onSizeSynchronizedChange:Yt,onWritesSettled:fs,onWriteProgress:Fi,onCursorPositionChange:Gl,onDirectoryLinkActivate:zr,terminalSettings:De,theme:mi,enableTouchScroll:Je,mobileLongPressMode:$e,autoFocus:l&&!Me&&!Je&&!so,inputActive:l&&!Me,cursorVisible:!Me&&ir,suppressSmoothScroll:!Ge||!vt,className:Me||!ir?"terminal-focus-suspended":void 0},Wi)})}),s.jsx(SN,{result:Tt,onDismiss:we}),s.jsx(KE,{connectionError:Qt,isFatalError:Or,isRestarting:Zn,isConnecting:pn,onHardRestart:Ro})]}),V?Z?null:Ks.createPortal(Mo,V):Mo]})};function NN({session:e,active:t,onActivate:r,onToggleRightSidebar:n}){const{t:a}=Hr(),c=Vr(l=>{const d=l.sessions.get(e.id);return gl(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(Zo,{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(sp,{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(d3,{size:14})})]})}const RN="termdock:startup:";function Gu(e){if(typeof performance>"u"||typeof performance.mark!="function")return;const t=`${RN}${e}`;performance.getEntriesByName(t,"mark").length>0||performance.mark(t)}function p5(e,t){e||Ks.flushSync(t)}const I1="horizontal";function Xu(e){return e<=0?[]:Array.from({length:e},()=>1/e)}function ff(e,t){if(!Array.isArray(e)||e.length!==t)return Xu(t);const r=e.map(Number);if(r.some(a=>!Number.isFinite(a)||a<=0))return Xu(t);const n=r.reduce((a,c)=>a+c,0);return n<=0?Xu(t):r.map(a=>a/n)}function MN(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 jN(e){return e==="horizontal"||e==="vertical"||e==="grid"}function DN(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 f=MN(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:jN(c.layout)?c.layout:I1,ratios:ff(c.ratios,d.length),...c.gridColumnRatios!==void 0?{gridColumnRatios:ff(c.gridColumnRatios,f.columns)}:{},...c.gridRowRatios!==void 0?{gridRowRatios:ff(c.gridRowRatios,f.rows)}:{}})}return n}function BN(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?ff(n.ratios,a.length):Xu(a.length)}]})}function B0(e,t){if(t)return e.find(r=>r.sessionIds.includes(t))}function vm(e,t,r){if(!t||!r||t===r)return e;const n=B0(e,t),a=B0(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===I1)?"grid":n?.layout??I1,ratios:Xu(l.length)},f=new Set([n?.id,a?.id].filter(Boolean)),m=e.filter(y=>!f.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 QN(e,t){const r=B0(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:Xu(n.length)}:a)}function PN(e,t){const r=B0(e,t);return r?e.filter(n=>n.id!==r.id):e}function ON(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 FN(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 E1=320,Rv=1,$N=E1+120,N1="termdock:split-workspaces:v2",Mv="termdock:split-workspace:v1",UN=.1,zN=.9;function wm(){if(typeof window>"u")return{mobile:!1,landscape:!1};const e=Gy();return{mobile:e,landscape:e&&window.innerWidth>window.innerHeight}}function HN(){if(typeof window>"u")return[];try{const e=window.localStorage.getItem(N1);if(e)return DN(JSON.parse(e));const t=JSON.parse(window.localStorage.getItem(Mv)||"null");if(t&&typeof t.primaryId=="string"&&typeof t.secondaryId=="string"&&t.primaryId!==t.secondaryId){const r=Math.min(zN,Math.max(UN,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 WN(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 f=d.sessionIds.flatMap(m=>{const x=r.get(m);return x?[x]:[]});f.length>=2&&c.push({key:d.id,sessions:f,workspace:d})}return c}function m5(e){const t=e.wrapperEl;if(t)try{t.getAnimations().forEach(r=>r.cancel())}catch{}}function Dh(e,t){const r=Qf(e,t);if(r===null)return;const n=e.wrapperEl;m5(e),n&&(n.style.transitionDuration="0ms");try{const a=e;a.setTransition?.(0),a.setTranslate?.(r),m5(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 R1(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 Qf(e,t){const r=e.snapGrid,n=Array.isArray(r)?r[t]:void 0;return typeof n!="number"||!Number.isFinite(n)?null:-n}function GN(e,t){const r=R1(e),n=Qf(e,t);return r!==null&&n!==null&&Math.abs(r-n)<=Rv}function VN(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 jv(e){const t=new Map;for(const r of e)t.set(r.id,r);return Array.from(t.values())}function Dv(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 qN(e,t){const r=jv(e),n=r.findIndex(a=>a.id===t.id);if(n>=0){const a=[...r];return a[n]=t,a}return[...r,t]}function g5(e,t){const r=new Map(e.map(n=>[n.id,n]));return t.map(n=>{const a=r.get(n.sessionId);return{...Dv(n),history:a?.history}})}function x5(e,t){return e.length===0?null:t&&e.some(r=>r.sessionId===t)?t:e[0]?.sessionId??null}function b5(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 y5(e){const t=new Map;for(const[r,n]of e)t.set(r,n.cwd??null);return t}function YN(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 ZN(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 KN=({terminalSettings:e=vg(),colorTheme:t="dark",toolbarPresets:r=[],showDebug:n,terminalFocusAvailable:a=!0,defaultSessionMode:c="shell",defaultTmuxSessionName:l="",connectionPrioritySessionId:d=null,connectionPriorityReady:f=!0,desktopRightSidebarEnabled:m=!1,onToggleRightSidebar:x,desktopFloatingTitle:y=!1,desktopLeftSidebarPinned:w=!1,desktopPinnedLeftSidebarWidth:v=0,desktopViewportWidth:T=0,onStatusChange:S,onSessionDataUpdate:I,onInitialViewportReady:N,onInitialRecoveryRequired:B})=>{const{t:F}=Hr(),P=y&&!w&&ea()?.platform==="darwin"&&document.documentElement.dataset.termdockPreview==="true",$=b.useMemo(()=>ed("session"),[]),ee=b.useMemo(()=>ed("terminal"),[]),[Z,V]=b.useState([]),[de,pe]=b.useState(null),J=b.useRef(0),Re=b.useRef(0),Xe=ns(R=>R.activePaneId);b.useEffect(()=>{ns.getState().setActivePane(de)},[de]);const[q,ve]=b.useState(null),[qe,ce]=b.useState(!0),[ye,Te]=b.useState({token:0,reason:"visibility",forceForegroundReconnect:!1}),[Fe,se]=b.useState(()=>new Set),[De,_e]=b.useState(()=>({token:0,completed:new Set})),[Me,Je]=b.useState(0),[Ne,ae]=b.useState(()=>new Set),[ze,at]=b.useState(()=>new Set),ut=b.useRef(new Map),[me,dt]=b.useState(()=>new Set),ft=b.useRef(!1),Se=b.useRef(null),We=b.useRef({}),[Le,z]=b.useState(null),[ie,ge]=b.useState(()=>HN()),[Ge,rt]=b.useState(!1),vt=b.useCallback(R=>{J.current+=1,rt(R)},[]),Yt=b.useRef(null),Ut=b.useRef(Ge);Ut.current=Ge,eu(Yt,Ge&&!!de,()=>vt(!1));const[Nt,ir]=b.useState(null),[Mt,Xt]=b.useState(null),Bt=b.useRef(new Set),[Wt,xe]=b.useState(null),[et,ot]=b.useState(null),[Et,K]=b.useState(!1),[xt,rr]=b.useState(()=>wm().mobile),[$e,Dr]=b.useState(()=>wm().landscape),[Ce,St]=b.useState(null),[Ot,tr]=b.useState(null),ct=b.useRef(a),Ct=b.useRef(!1),or=b.useRef(!1),Cr=b.useRef(null),Ir=b.useRef(null),$r=b.useRef(xt),Tt=b.useRef(null),Ft=b.useCallback(R=>{R!==Tt.current&&(J.current+=1),Tt.current=R,pe(R)},[]);b.useEffect(()=>Vt.subscribe((R,U)=>{(R.rightOpen!==U.rightOpen||R.rightTab!==U.rightTab)&&(J.current+=1)}),[]);const we=b.useRef(0),wt=b.useRef([]),it=b.useRef(0),bt=b.useRef(null),An=b.useRef(!1),xn=b.useRef(!0),rn=b.useRef(null),Oe=b.useRef(""),_t=b.useRef(0);b.useEffect(()=>{if(typeof window>"u")return;const R=()=>{const U=wm();$r.current=U.mobile,rr(U.mobile),Dr(U.landscape)};return R(),window.addEventListener("resize",R),()=>window.removeEventListener("resize",R)},[]);const{sessions:mt,inventory:Zt,activeSessionId:$t,isLoading:wr,openSession:Tn,setActiveSession:Dn,removeSession:yn,renameSession:un,resetSessionCustomName:Cn,reorderSessions:Ur,restoreSessions:ne}=P8(),Ze=Zt?.tmuxRecovery??null;b.useEffect(()=>{Ze&&B?.()},[Ze,B]),b.useEffect(()=>{ot(null),xe(null)},[Ze?.id]);const Dt=b.useCallback(async()=>{xe("restore"),ot(null);try{const R=await O8(Ze?.id);await ne(),R.accepted||ot(F("tab.tmuxRecoveryFailed"))}catch{ot(F("tab.tmuxRecoveryFailed"))}finally{xe(null)}},[ne,F,Ze?.id]),ur=b.useCallback(async()=>{const R=Ze?.operation;if(R)try{await F8(R.id,!R.paused),await ne()}catch{ot(F("tab.tmuxRecoveryFailed"))}},[ne,F,Ze?.operation]),Pr=b.useCallback(async()=>{xe("dismiss"),ot(null);try{await $8(),await ne()}catch{ot(F("tab.tmuxRecoveryDismissFailed"))}finally{xe(null)}},[ne,F]),qr=Vt(R=>R.groupByFolder),sn=kf(R=>R.collaborationGroups),Nr=Vt(R=>R.leftOpen||R.rightOpen),Wr=Vt(R=>R.rightSidebarWidthContextKey),_n=Vt(R=>R.rightSidebarWidth),en=Vt(R=>R.rightPinned),[Fr,Kr]=b.useState(()=>y5(Vr.getState().sessions));b.useEffect(()=>Vr.subscribe(R=>{const U=y5(R.sessions);Kr(X=>YN(X,U)?X:U)}),[]);const{arranged:gr}=b.useMemo(()=>Cf(Z,R=>Fr.get(R.id)??null,qr,"",ie,sn),[Z,Fr,qr,ie,sn]),an=b.useRef(gr);an.current=gr;const Xr=b.useMemo(()=>WN(gr,ie),[gr,ie]),dn=b.useRef(Xr);dn.current=Xr;const Rr=b.useMemo(()=>B0(ie,de),[de,ie]),zn=b.useMemo(()=>{const R=Xr.find(U=>U.sessions.some(X=>X.id===de));return new Set(R?.sessions.map(U=>U.id)??[])},[de,Xr]),pn=b.useMemo(()=>{const R=new Map;if(!m||T<=0)return R;for(const U of Xr){const X=U.sessions[0];if(!X)continue;const be=U8(X.id,Fr.get(X.id)??null,U.workspace?.id??null);if(!(be===Wr?en:z8(X.id,Fr.get(X.id)??null,U.workspace?.id??null)))continue;const Ve=be===Wr?_n:H8(X.id,Fr.get(X.id)??null,U.workspace?.id??null),ht=Jh(Ve,T,v);R.set(U.key,ht+Vy)}return R},[Fr,v,m,en,Wr,_n,T,Xr]),Gr=b.useMemo(()=>bm(Z.map(R=>({id:R.id,backendSessionId:R.sessionId})),d),[d,Z]),zr=b.useMemo(()=>x5(mt,$t),[$t,mt]),Y=Mh({prioritySessionId:Gr,activeSessionId:q??de,persistedActiveSessionId:zr,firstSessionId:Z[0]?.id??null}),Be=b.useMemo(()=>xN(Xr.flatMap(R=>R.sessions.map(U=>U.id)),zn),[zn,Xr]),Qt=Y!==null&&Fe.has(Y),er=b.useMemo(()=>{const R=new Set(zn);return q&&R.add(q),!R.size&&Y&&R.add(Y),R},[zn,q,Y]),nr=De.token===ye.token&&fN(er,De.completed),Or=nr||Me===ye.token?ye.token:-1;b.useEffect(()=>{if(!ye.token||nr)return;const R=window.setTimeout(()=>Je(ye.token),rN);return()=>window.clearTimeout(R)},[ye.token,nr]);const kr=b.useCallback((R,U)=>{se(X=>{if(X.has(R)===U)return X;const Ee=new Set(X);return U?Ee.add(R):Ee.delete(R),Ee})},[]),Zn=b.useCallback(R=>{const U=we.current;_e(be=>{if(be.token===U&&be.completed.has(R))return be;const Ee=new Set(be.token===U?be.completed:[]);return Ee.add(R),{token:U,completed:Ee}});const X=Gr??q??Tt.current;R===X&&Gu("foreground-stream-connected")},[q,Gr]),ys=b.useCallback((R,U)=>{ae(X=>{if(X.has(R)===U)return X;const be=new Set(X);return U?be.add(R):be.delete(R),be})},[]),ss=b.useCallback((R,U)=>{at(X=>{if(X.has(R)===U)return X;const be=new Set(X);return U?be.add(R):be.delete(R),be})},[]);b.useEffect(()=>{for(const[R,U]of ut.current){const X=Z.find(be=>be.id===R);if(!X||X.sessionId!==U.backendSessionId){ut.current.delete(R);continue}!Fe.has(R)||!Ne.has(R)||!ze.has(R)||(ut.current.delete(R),Wy(U.backendSessionId,`${U.command}\r`).catch(be=>{console.error("[Session] Failed to send startup command:",be)}))}},[Z,Fe,Ne,ze]);const Hn=Y!==null&&Ne.has(Y),hn=Y!==null&&ze.has(Y);b.useEffect(()=>{Hn&&Gu("foreground-viewport-ready")},[Hn]),b.useEffect(()=>{hn&&Gu("foreground-content-ready")},[hn]),b.useEffect(()=>{if(!N)return;if(!qe&&Z.length===0){N();return}if(!Hn||!Qt||!hn)return;const R=[...zn].every(Ve=>Ne.has(Ve)&&Fe.has(Ve)&&ze.has(Ve));let U=0,X=0;const be=()=>{U=requestAnimationFrame(()=>{X=requestAnimationFrame(()=>{Gu("initial-viewport-presented"),N()})})};R&&be();const Ee=R?void 0:window.setTimeout(be,8e3);return()=>{cancelAnimationFrame(U),cancelAnimationFrame(X),clearTimeout(Ee)}},[Qt,hn,Hn,qe,N,Z.length,zn,Ne,Fe,ze]);const Qn=b.useMemo(()=>xt?iN({slides:Xr.map(R=>R.sessions.map(U=>U.id)),visibleSessionIds:zn,foregroundSessionId:Y}):me,[xt,Xr,zn,Y,me]);b.useEffect(()=>{if(xt||zn.size===0)return;const R=new Set(zn),U=Xr.findIndex(X=>X.sessions.some(be=>zn.has(be.id)));for(let X=-2;X<=2;X+=1)X!==0&&Xr[U+X]?.sessions.forEach(be=>R.add(be.id));dt(X=>{let be=!1;const Ee=new Set(X);for(const Ve of R)Ee.has(Ve)||(Ee.add(Ve),be=!0);return be?Ee:X})},[xt,zn,Xr]);const Xn=BC(Qn);b.useEffect(()=>{if(!q)return;if(!Z.some(U=>U.id===q)){ve(null);return}if(!Ne.has(q)||!Fe.has(q)||!ze.has(q))return;const R=window.setTimeout(()=>{ve(U=>U===q?null:U),ct.current&&!$r.current&&z({sessionId:q,token:Date.now()})},80);return()=>window.clearTimeout(R)},[ze,q,Fe,Z,Ne]),b.useEffect(()=>{typeof window>"u"||(ie.length>0?(window.localStorage.setItem(N1,JSON.stringify(ie)),window.localStorage.removeItem(Mv)):window.localStorage.removeItem(N1))},[ie]),b.useEffect(()=>{wr||qe||ie.length===0||ge(R=>BN(R,Z.map(U=>U.id)))},[wr,qe,Z,ie.length]),b.useEffect(()=>{if(!Nt)return;const R=window.setTimeout(()=>ir(null),3200);return()=>window.clearTimeout(R)},[Nt]),Tt.current=de,we.current=ye.token,wt.current=Z,bt.current=$t,An.current=wr,xn.current=qe,ct.current=a;const fn=b.useCallback((R=Se.current)=>{const U=it.current,X=typeof window<"u"?window.visualViewport:null,be=R?R1(R):null,Ee=R?Qf(R,U):null;return{sessionsLength:wt.current.length,workspaceSlidesLength:dn.current.length,sessionIds:wt.current.map(Ve=>Ve.id),activeSessionId:Tt.current,activeSessionIndex:U,persistedActiveId:bt.current,isLoading:An.current,isRestoring:xn.current,activeIndex:R?.activeIndex??null,previousIndex:R?.previousIndex??null,animating:R?.animating??null,allowTouchMove:R?.allowTouchMove??null,width:R?.width??null,translate:be,targetTranslate:Ee,translateDelta:be!==null&&Ee!==null?be-Ee:null,snapGridLength:R?.snapGrid?.length??null,targetSnap:R?.snapGrid?.[U]??null,visualViewport:X?{width:Math.round(X.width),height:Math.round(X.height),offsetTop:Math.round(X.offsetTop)}:null}},[]),cr=b.useCallback((R,U)=>{$(R,{...fn(),...U})},[$,fn]);b.useEffect(()=>{wr||qe||de!==$t&&Dn(de)},[de,wr,qe,$t,Dn]);const is=b.useMemo(()=>{if(gr.length===0||!de)return 0;const R=Xr.findIndex(U=>U.sessions.some(X=>X.id===de));return R>=0?R:0},[Xr,de]);it.current=is;const tn=b.useCallback(()=>{Cr.current&&(clearTimeout(Cr.current),Cr.current=null)},[]),xr=b.useCallback(R=>{tn(),Cr.current=setTimeout(()=>{Cr.current=null,Ct.current=!1,cr("[swiper:touch-guard-clear]",{reason:R})},$N)},[tn,cr]),vr=b.useCallback((R,U={})=>{const X=Se.current,be=it.current,Ee=dn.current;if(!X||Ee.length===0||be<0||be>=Ee.length)return;if(Ct.current){cr("[swiper:sync-skip-touch]",{reason:R});return}if(X.animating){cr("[swiper:sync-skip-animating]",{reason:R});return}const Ve=R1(X),ht=Qf(X,be),Qe=Ve!==null&&ht!==null&&Math.abs(Ve-ht)<=Rv,ar=X.activeIndex===be;if(cr("[swiper:sync-check]",{reason:R,activeIndexAligned:ar,translateAligned:Qe,immediate:U.immediate===!0}),!(ar&&Qe)){if(ar){Dh(X,be),cr("[swiper:sync-forced-active]",{reason:R,translateAligned:Qe,immediate:U.immediate===!0});return}U.immediate?(Dh(X,be),X.slideTo(be,0,!1),Dh(X,be)):X.slideTo(be,E1,!1),cr("[swiper:sync-applied]",{reason:R,activeIndexAligned:ar,translateAligned:Qe,immediate:U.immediate===!0})}},[cr]);b.useEffect(()=>{const R=U=>{const X=U;Se.current&&(Se.current.allowTouchMove=!X.detail.locked),cr("[swiper:gesture-lock]",{locked:X.detail.locked})};return document.addEventListener("termdock:gesture-lock",R),()=>document.removeEventListener("termdock:gesture-lock",R)},[cr]),b.useEffect(()=>{if(Z.length===0){de!==null&&Ft(null);return}if(!de){if(!f)return;Ft(Mh({prioritySessionId:Gr,activeSessionId:null,persistedActiveSessionId:zr,firstSessionId:Z[0]?.id??null}));return}Z.some(U=>U.id===de)||Ft(Z[0].id)},[Z,de,f,Gr,zr]);const br=b.useCallback((R,U)=>{if(U&&Date.now()<_t.current){We.current[R]=!1;return}We.current[R]=U,tr(X=>U?R:X===R?null:X)},[]),us=b.useCallback(R=>{if(!Ct.current&&R.activeIndex!==it.current){cr("[swiper:slide-change-ignored-layout]",{instanceActiveIndex:R.activeIndex,expectedActiveIndex:it.current}),requestAnimationFrame(()=>vr("ignored-layout-slide-change",{immediate:!0}));return}const U=dn.current[R.activeIndex],X=U?.sessions.some(Ve=>Ve.id===de)?de:U?.sessions[0]?.id;if(cr("[swiper:slide-change]",{nextSessionId:X??null,instanceActiveIndex:R.activeIndex}),!X||X===de)return;const be=!!de&&We.current[de]===!0,Ee=ct.current&&(!$r.current||be);if(Ir.current=X,Ft(X),Ee){z({sessionId:X,token:Date.now()});return}z(null)},[Z,de,cr,vr]);b.useLayoutEffect(()=>{if(Ir.current===de){cr("[swiper:sync-skip-swiper-driven]",{activeSessionId:de}),Ir.current=null;return}vr("active-session-index",{immediate:!0})},[de,is,Z.length,vr,cr]),b.useEffect(()=>{const R=Se.current;if(!R)return;const U=Xr.length>1&&!Nr&&!Ge;R.allowTouchMove!==U&&(R.allowTouchMove=U,cr("[swiper:allow-touch-sync]",{nextAllow:U,sidebarOverlayOpen:Nr}))},[Xr.length,cr,Nr,Ge]);const Bn=b.useCallback(R=>{const U=Se.current;if(!U)return;const X=U.el;if(cr("[swiper:layout-before]",{reason:R,scrollLeft:X?.scrollLeft??null}),X&&(X.scrollLeft=0),U.updateSize(),U.updateSlides(),U.updateProgress(),U.updateSlidesClasses(),X&&(X.scrollLeft=0),cr("[swiper:layout-after]",{reason:R,scrollLeft:X?.scrollLeft??null}),Ct.current||U.animating){cr("[swiper:layout-skip-sync-motion]",{reason:R});return}vr(`layout:${R}`,{immediate:!0}),requestAnimationFrame(()=>{const be=Se.current;be&&(Ct.current||be.animating||Dh(be,it.current))})},[cr,vr]);b.useEffect(()=>()=>tn(),[tn]);const vs=Xr.map(R=>R.key).join("\0");b.useEffect(()=>{requestAnimationFrame(()=>Bn("group-change"))},[qr,vs,Bn]),b.useEffect(()=>{let R=null,U="mount";const X=Qe=>{U=Qe,R===null&&(R=requestAnimationFrame(()=>{R=null,Bn(`viewport-change:${U}`)}))},be=()=>X("window-resize"),Ee=()=>X("visual-viewport-resize"),Ve=()=>X("visual-viewport-scroll"),ht=Qe=>{X(`measured:${Qe.detail?.source??"unknown"}`)};return window.addEventListener("resize",be),window.visualViewport?.addEventListener("resize",Ee),window.visualViewport?.addEventListener("scroll",Ve),document.addEventListener(kx,ht),X("mount"),()=>{window.removeEventListener("resize",be),window.visualViewport?.removeEventListener("resize",Ee),window.visualViewport?.removeEventListener("scroll",Ve),document.removeEventListener(kx,ht),R!==null&&cancelAnimationFrame(R)}},[Bn]),b.useEffect(()=>{if(typeof document>"u")return;let R=null,U=null;const X=ar=>{if(ar!=="online"&&document.hidden)return;const sr=performance.now();if(!pN(U,sr))return;U=sr;const It=ar==="bfcache"||ar==="online"?ar:"visibility",_r=mN();Op(),Ma("info","PWA_RESUME scheduled",{source:ar,forceForegroundReconnect:_r,activeSessionId:Tt.current}),Te(on=>({token:on.token+1,reason:It,forceForegroundReconnect:_r})),requestAnimationFrame(()=>Bn(`resume:${ar}:raf`)),R&&clearTimeout(R),R=setTimeout(()=>{R=null,Bn(`resume:${ar}:settled`)},320)},be=()=>{if(document.hidden){Op();return}X("visibility")},Ee=()=>{Op()},Ve=ar=>{X(ar.persisted?"bfcache":"pageshow")},ht=()=>X("online"),Qe=()=>X("focus");return document.addEventListener("visibilitychange",be),window.addEventListener("pagehide",Ee),window.addEventListener("pageshow",Ve),window.addEventListener("online",ht),window.addEventListener("focus",Qe),()=>{document.removeEventListener("visibilitychange",be),window.removeEventListener("pagehide",Ee),window.removeEventListener("pageshow",Ve),window.removeEventListener("online",ht),window.removeEventListener("focus",Qe),R&&clearTimeout(R)}},[Bn]),b.useLayoutEffect(()=>{if(!dN(qe))return;const R=VN(Z),U=JSON.stringify(R);R.length>0&&U!==Oe.current?(Oe.current=U,console.warn("[session-invariant] duplicate mapping detected",R)):R.length===0&&Oe.current&&(Oe.current=""),I?.({sessions:Z.map(X=>({id:X.id,name:X.name,customName:X.customName,mode:X.mode,tmuxSessionName:X.tmuxSessionName})),activeSessionId:de,splitWorkspaces:ie.map(({id:X,name:be,sessionIds:Ee,layout:Ve})=>({id:X,...be?{name:be}:{},sessionIds:Ee,layout:Ve}))})},[Z,de,ie,I,qe]),b.useEffect(()=>{if(wr||ft.current)return;ft.current=!0;const R=bm(mt.map(Ve=>({id:Ve.sessionId,backendSessionId:Ve.backendSessionId??null})),d),U=x5(mt,$t),X=Mh({prioritySessionId:f?R:null,activeSessionId:null,persistedActiveSessionId:U,firstSessionId:mt[0]?.sessionId??null}),be=jv(mt.map(Dv));if($("[Session] Restoring",be.length,"persisted sessions (one-shot)"),cr("[swiper:restore-start]",{persistedSessionIds:mt.map(Ve=>Ve.sessionId),nextActiveSessionId:X}),be.length>0){const Ve=Vr.getState();be.forEach(Qe=>{Qe.sessionId&&Ve.setTerminalSession(Qe.id,{sessionId:Qe.sessionId,cols:80,rows:24,mode:Qe.mode,tmuxSessionName:Qe.tmuxSessionName,history:Qe.history})}),mt.forEach(Qe=>{Qe.agent!==void 0&&Ve.setSessionAgentIdentity(Qe.sessionId,Qe.agent),Qe.activeProgram!=null&&Ve.setSessionActiveProgram(Qe.sessionId,Qe.activeProgram),Qe.cwd!=null&&Ve.setSessionCwd(Qe.sessionId,Qe.cwd),Qe.shellTitle!=null&&Ve.setSessionShellTitle(Qe.sessionId,Qe.shellTitle)}),V(be);const ht=X||be[0]?.id||null;Ft(ht),cr("[swiper:restore-complete]",{restoredSessionIds:be.map(Qe=>Qe.id),nextActiveSessionId:ht})}(async()=>(be.length===0&&await rn.current?.({createIfEmpty:!0}),ce(!1),requestAnimationFrame(()=>vr("restore-finished",{immediate:!0}))))()},[wr,mt,$t,$,cr,vr,f,d]),b.useEffect(()=>{if(!f||qe||Z.length===0)return;const R=bm(Z.map(X=>({id:X.id,backendSessionId:X.sessionId})),d),U=Mh({prioritySessionId:R,activeSessionId:Tt.current,persistedActiveSessionId:zr,firstSessionId:Z[0]?.id??null});U&&U!==Tt.current&&Ft(U)},[f,d,qe,zr,Z]);const Bs=b.useRef([]),Ls=b.useRef(!1);Tt.current=de,b.useEffect(()=>{if(qe)return;const R=Bs.current,U=mt,X=new Map(R.map(It=>[It.sessionId,It])),be=Vr.getState();for(const It of U){const _r=X.get(It.sessionId),on=Vr.getState().sessions.get(It.sessionId);It.agent!==void 0&&JSON.stringify(It.agent)!==JSON.stringify(on?.agent)&&(on?.agent==null||JSON.stringify(It.agent)!==JSON.stringify(_r?.agent))&&be.setSessionAgentIdentity(It.sessionId,It.agent),It.activeProgram!=null&&It.activeProgram!==on?.activeProgram&&(on?.activeProgram==null||It.activeProgram!==_r?.activeProgram)&&be.setSessionActiveProgram(It.sessionId,It.activeProgram),It.cwd!=null&&It.cwd!==on?.cwd&&(on?.cwd==null||It.cwd!==_r?.cwd)&&be.setSessionCwd(It.sessionId,It.cwd),It.shellTitle!=null&&It.shellTitle!==on?.shellTitle&&(on?.shellTitle==null||It.shellTitle!==_r?.shellTitle)&&be.setSessionShellTitle(It.sessionId,It.shellTitle)}if(!Ls.current){V(It=>g5(It,U)),Bs.current=U,Ls.current=!0;return}const Ee=new Set(R.map(It=>It.sessionId)),Ve=new Set(U.map(It=>It.sessionId)),ht=new Map(R.map(It=>[It.sessionId,It.name]));Bs.current=U,V(It=>{const _r=g5(It,U);return(!Tt.current||!_r.some(on=>on.id===Tt.current))&&Ft(_r[0]?.id??null),_r});const Qe=U.filter(It=>!Ee.has(It.sessionId)),ar=[...Ee].filter(It=>!Ve.has(It)),sr=U.filter(It=>Ee.has(It.sessionId)&&ht.get(It.sessionId)!==It.name);(Qe.length>0||ar.length>0||sr.length>0)&&$("[Session] Synced persisted sessions:",{newSessionIds:Qe.map(It=>It.sessionId),removedSessionIds:ar,renamedSessionIds:sr.map(It=>It.sessionId),currentSessionIds:U.map(It=>It.sessionId)});for(const It of U){if(!It.backendSessionId)continue;Vr.getState().setTerminalSession(It.sessionId,{sessionId:It.backendSessionId,cols:80,rows:24,mode:It.mode,tmuxSessionName:It.tmuxSessionName})}},[mt,qe,$]);const Qr=b.useCallback(async R=>{const U=++Re.current,X=J.current,be=()=>U===Re.current&&X===J.current&&(R?.shouldActivate?.()??!0);try{const Ee=Vt.getState(),Ve=de?{rightOpen:Ee.rightOpen,rightPinned:Ee.rightPinned,rightSidebarWidth:Ee.rightSidebarWidth,rightTab:Ee.rightTab}:null,ht=R?.mode==="tmux"||R?.mode==="shell"?R.mode:c,Qe=(R?.tmuxSessionName||"").trim(),ar=l.trim(),sr=ht==="tmux"?Qe||ar||ZN():null,It=typeof R?.cwd=="string"?R.cwd:null,_r=de?Vr.getState().sessions.get(de)?.cwd??null:null,on=typeof It=="string"&&It.trim().length>0?It:typeof _r=="string"&&_r.trim().length>0?_r:void 0,bn=await Tn({preferredFrontendSessionId:R?.preferredFrontendSessionId,requireExisting:R?.requireExisting===!0,mode:ht,tmuxSessionName:sr,cwd:on,termType:"xterm-256color",createIfEmpty:R?.createIfEmpty===!0},{shouldActivate:be});if(bn.discarded)return R?.onResult?.({ok:!1,error:"unknown"}),null;const Jr=bn.session,mn=bn.terminalSession;!bn.reused&&Ve&&Vt.getState().initializeRightSidebarForSession(Jr.sessionId,mn.cwd??on??null,Ve);const dr={id:Jr.sessionId,name:Jr.name,customName:Jr.customName===!0,sessionId:mn.sessionId,mode:mn.mode??Jr.mode,tmuxSessionName:mn.tmuxSessionName??Jr.tmuxSessionName},pr=R?.command?.trim();return pr&&ut.current.set(dr.id,{backendSessionId:mn.sessionId,command:pr}),V(ws=>qN(ws,dr)),be()&&Ft(dr.id),Vr.getState().setTerminalSession(dr.id,{sessionId:mn.sessionId,cols:80,rows:24,mode:dr.mode,tmuxSessionName:dr.tmuxSessionName,activeProgram:mn.activeProgram,activeProgramRaw:mn.activeProgramRaw,activeProgramSource:mn.activeProgramSource,cwd:mn.cwd}),$("[Session] Inventory opened session:",{frontendSessionId:dr.id,backendSessionId:mn.sessionId,reused:bn.reused,mode:dr.mode,tmuxSessionName:dr.tmuxSessionName}),R?.onResult?.({ok:!0,sessionId:dr.id}),dr.id}catch(Ee){return console.error("[Session] Failed to create new session:",Ee),R?.onResult?.({ok:!1,error:SC(Ee)}),null}},[c,l,de,Tn,$]);rn.current=Qr;const yr=b.useCallback((R,U={})=>{J.current+=1,ns.getState().setActivePane(R);const X=Tt.current,be=!!X&&We.current[X]===!0;if(Ft(R),$r.current&&U.preserveMobileKeyboard===!1){_t.current=Date.now()+600,X&&(We.current[X]=!1),tr(null),z(null);const Ee=document.activeElement;Ee instanceof HTMLTextAreaElement&&Ee.closest(".terminal-viewport-container")&&Ee.blur();return}be&&$r.current&&tr(R),ct.current&&(!$r.current||be)&&z({sessionId:R,token:Date.now()})},[]),Pn=b.useCallback(R=>{Ft(R),vt(!0),ir(null)},[]),Jn=b.useCallback(R=>{const U=Tt.current;!U||U===R||(ge(X=>vm(X,U,R)),vt(!1),yr(U,{preserveMobileKeyboard:!1}))},[yr]),es=b.useCallback(async()=>{const R=Tt.current;if(!R||Et)return;const U=J.current;K(!0);const X=Vr.getState().sessions.get(R)?.cwd??void 0,be=await Qr({cwd:X||void 0,mode:c,shouldActivate:()=>!1});if(K(!1),!be){ir(F("common.error"));return}!Ut.current||U!==J.current||!wt.current.some(Ee=>Ee.id===R)||(ge(Ee=>vm(Ee,R,be)),vt(!1),yr(R,{preserveMobileKeyboard:!1}))},[yr,c,Qr,Et,F]),oi=b.useCallback(R=>{ge(U=>PN(U,R)),R&&yr(R,{preserveMobileKeyboard:!1})},[yr]),W=b.useCallback(R=>{ge(U=>QN(U,R)),yr(R,{preserveMobileKeyboard:!1})},[yr]),Ie=b.useCallback(R=>{if(Z.find(X=>X.id===R)){if(J.current+=1,ns.getState().setActivePane(R),R===Tt.current)return;if(Ft(R),!lN({isMobile:$r.current,viewportReady:Ne.has(R),streamReady:Fe.has(R),contentReady:ze.has(R)})){ve(null),ct.current&&z({sessionId:R,token:Date.now()}),$("[Session] Switched to session:",R);return}dt(be=>{if(be.has(R))return be;const Ee=new Set(be);return Ee.add(R),Ee}),ve(R),$("[Session] Switched to session:",R)}},[ze,$,Fe,Z,Ne]),Ye=b.useCallback((R,U)=>{U.trim()&&(V(X=>X.map(be=>be.id===R?{...be,name:U.trim(),customName:!0}:be)),un(R,U.trim()))},[un]),nt=b.useCallback(R=>{V(U=>U.map(X=>X.id===R?{...X,customName:!1}:X)),Cn(R)},[Cn]),st=b.useCallback(R=>{V(U=>{const X=new Map(U.map(ht=>[ht.id,ht])),be=R.map(ht=>X.get(ht)).filter(ht=>ht!==void 0),Ee=new Set(R),Ve=U.filter(ht=>!Ee.has(ht.id));return[...be,...Ve]}),Ur(R),$("[Session] Reordered sessions:",R),requestAnimationFrame(()=>{Se.current?.update()})},[Ur,$]),yt=b.useCallback(async R=>{const U=typeof R=="string"?R:R.sessionId,X=typeof R=="string"?"auto":R.closeMode??"auto",be=Z.find(Qe=>Qe.id===U);if(!be||Bt.current.has(U))return;Bt.current.add(U),J.current+=1;const Ee=Lx(gr,U,Qe=>Qe.id);try{X==="destroy"&&be.mode==="tmux"&&be.tmuxSessionName?(await qy(be.tmuxSessionName),$("[Session] Destroyed tmux session:",{frontendSessionId:be.id,tmuxSessionName:be.tmuxSessionName})):be.sessionId&&(await Hy(be.sessionId),$("[Session] Closed backend terminal:",be.sessionId))}catch(Qe){console.error("[Session] Failed to close backend terminal:",Qe),Xt({sessionId:U,closeMode:X});return}finally{Bt.current.delete(U)}Xt(Qe=>Qe?.sessionId===U?null:Qe);const ht=wt.current.filter(Qe=>Qe.id!==U).some(Qe=>Qe.id===Ee)?Ee:Lx(wt.current,U,Qe=>Qe.id);Tt.current===U&&Ft(ht),V(Qe=>Qe.filter(ar=>ar.id!==U)),yn(U,ht),delete We.current[U],$("[Session] Closed session:",{sessionId:U,closeMode:X})},[Z,gr,yn,$]),Pt=b.useCallback(R=>{if(!R)return;const U=Z.filter(X=>X.sessionId===R);if(U.length!==0){U.length>1&&console.warn("[session-invariant] backend matched multiple frontend sessions during cleanup",{backendSessionId:R,frontendSessionIds:U.map(X=>X.id)}),V(X=>{const be=X.filter(Ee=>Ee.sessionId!==R);return be.length!==X.length&&!be.some(Ve=>Ve.id===de)&&Ft(be.length>0?be[0].id:null),be});for(const X of U)yn(X.id),delete We.current[X.id];$("[Session] Backend gone, dropped local session(s):",U.map(X=>X.id))}},[Z,de,yn,$]);b.useEffect(()=>{const R=dr=>{Qr(dr.detail)},U=dr=>{Ie(dr.detail)},X=()=>{const dr=Tt.current;!dr||$r.current||z({sessionId:dr,token:Date.now()})},be=dr=>{const pr=dr;pr.detail&&Pn(pr.detail)},Ee=dr=>{const pr=dr.detail;oi(pr??Tt.current??void 0)},Ve=dr=>{const pr=dr.detail;pr&&W(pr)},ht=dr=>{const pr=dr.detail,fs=typeof pr=="string"?pr:pr?.layout,ws=typeof pr=="string"?Tt.current:pr?.sessionId;fs!=="horizontal"&&fs!=="vertical"&&fs!=="grid"||ge(Ss=>Ss.map(Fi=>Fi.sessionIds.includes(ws??"")?{...Fi,layout:fs}:Fi))},Qe=dr=>{const fs=dr.detail?.direction;if(fs!=="prev"&&fs!=="next")return;const ws=an.current;if(ws.length<=1)return;const Ss=Tt.current,Fi=Ss?ws.findIndex(Aa=>Aa.id===Ss):-1,Is=((Fi>=0?Fi:0)+(fs==="next"?1:-1)+ws.length)%ws.length,li=ws[Is]?.id;li&&li!==Ss&&Ie(li)},ar=dr=>{yt(dr.detail)},sr=dr=>{Pt(dr.detail)},It=dr=>{const pr=dr;!pr.detail?.sessionId||!pr.detail?.name||Ye(pr.detail.sessionId,pr.detail.name)},_r=dr=>{const pr=dr;pr.detail?.sessionId&&nt(pr.detail.sessionId)},on=dr=>{const pr=dr;pr.detail?.sessionIds&&st(pr.detail.sessionIds)},bn=dr=>{const pr=dr.detail;!pr?.workspaceId||!Array.isArray(pr.sessionIds)||ge(fs=>ON(fs,pr.workspaceId,pr.sessionIds))},Jr=dr=>{const pr=dr.detail;!pr?.workspaceId||typeof pr.name!="string"||ge(fs=>FN(fs,pr.workspaceId,pr.name))},mn=dr=>{const pr=dr.detail;!pr?.primaryId||!pr.secondaryId||pr.primaryId===pr.secondaryId||(ge(fs=>vm(fs,pr.primaryId,pr.secondaryId)),yr(pr.primaryId,{preserveMobileKeyboard:!1}))};return window.addEventListener("new-terminal-session",R),window.addEventListener("switch-terminal-session",U),window.addEventListener("focus-active-terminal-session",X),window.addEventListener("open-terminal-split-chooser",be),window.addEventListener("close-terminal-split",Ee),window.addEventListener("remove-terminal-split-pane",Ve),window.addEventListener("set-terminal-split-direction",ht),window.addEventListener("cycle-terminal-session",Qe),window.addEventListener("close-terminal-session",ar),window.addEventListener("close-terminal-session-by-backend",sr),window.addEventListener("rename-terminal-session",It),window.addEventListener("reset-terminal-session-name",_r),window.addEventListener("reorder-terminal-session",on),window.addEventListener("reorder-terminal-split-workspace",bn),window.addEventListener("rename-terminal-split-workspace",Jr),window.addEventListener("combine-terminal-split-sessions",mn),()=>{window.removeEventListener("new-terminal-session",R),window.removeEventListener("switch-terminal-session",U),window.removeEventListener("focus-active-terminal-session",X),window.removeEventListener("open-terminal-split-chooser",be),window.removeEventListener("close-terminal-split",Ee),window.removeEventListener("remove-terminal-split-pane",Ve),window.removeEventListener("set-terminal-split-direction",ht),window.removeEventListener("cycle-terminal-session",Qe),window.removeEventListener("close-terminal-session",ar),window.removeEventListener("close-terminal-session-by-backend",sr),window.removeEventListener("rename-terminal-session",It),window.removeEventListener("reset-terminal-session-name",_r),window.removeEventListener("reorder-terminal-session",on),window.removeEventListener("reorder-terminal-split-workspace",bn),window.removeEventListener("rename-terminal-split-workspace",Jr),window.removeEventListener("combine-terminal-split-sessions",mn)}},[yr,Qr,Ie,Pn,oi,W,yt,Pt,Ye,nt,st]),b.useEffect(()=>{if(!Rr||xt)return;const R=U=>{if(!QC(U,rg())||!(U.ctrlKey||U.metaKey)||!U.shiftKey)return;if(Rr.layout==="horizontal"?U.key==="ArrowLeft"||U.key==="ArrowRight":Rr.layout==="vertical"?U.key==="ArrowUp"||U.key==="ArrowDown":U.key.startsWith("Arrow")){U.preventDefault(),U.stopPropagation();const be=Rr.sessionIds.indexOf(Tt.current??""),Ee=U.key==="ArrowLeft"||U.key==="ArrowUp"?-1:1,Ve=(Math.max(0,be)+Ee+Rr.sessionIds.length)%Rr.sessionIds.length,ht=Rr.sessionIds[Ve];if(!ht)return;yr(ht);return}U.key==="Backspace"&&(U.preventDefault(),U.stopPropagation(),oi(Tt.current??void 0))};return window.addEventListener("keydown",R,!0),()=>window.removeEventListener("keydown",R,!0)},[yr,Rr,oi,xt]);const H=R=>{const U=Vr.getState().sessions.get(R.id);return gl(R,U?.activeProgram??null,U?.cwd??null,void 0,U?.shellTitle??null,U?.promptState??null)},ue=(R,U={})=>{const X=R.id===de&&!Xe?.startsWith("@collaboration:"),be=zn.has(R.id)&&!U.hidden,Ee=f&&oN({sessionId:R.id,foregroundSessionId:Y,visibleSessionIds:zn,deferredViewportSessionIds:xt?Xn:Qn}),Ve=aN({sessionId:R.id,foregroundSessionId:Y,foregroundReady:Qt,isVisible:be})&&f,ht=hN({sessionId:R.id,foregroundSessionId:Y,requestToken:ye.token,foregroundCompletedToken:Or,isVisible:er.has(R.id)})&&f,Qe=be||R.id===Y||Qn.has(R.id)?0:Be.get(R.id)??df;return s.jsxs("div",{className:`relative flex h-full min-h-0 min-w-0 flex-col overflow-hidden ${U.hidden?"invisible pointer-events-none":""}`,style:U.containerStyle,"aria-hidden":U.hidden||void 0,onPointerDownCapture:()=>{be&&p5(X,()=>yr(R.id))},onWheelCapture:()=>{p5(X,()=>yr(R.id))},children:[U.showPaneTitle&&s.jsx(NN,{session:R,active:X,onActivate:()=>yr(R.id),onToggleRightSidebar:X?x:void 0}),s.jsx("div",{className:"min-h-0 flex-1 app-chrome-bg",children:Ee&&s.jsx(EN,{sessionId:R.id,mode:R.mode,tmuxSessionName:R.tmuxSessionName,terminalSettings:e,colorTheme:t,toolbarPresets:r,isActive:X,focusSuspended:!a||q!==null,deferCursorUntilPositioned:q===R.id||R.mode==="tmux"&&!ze.has(R.id),isLayoutVisible:be,initialConnectEnabled:Ve&&ht,resumeRequestEnabled:ht,suppressKeyboard:U.suppressKeyboard,keyboardPortalTarget:U.keyboardPortalTarget,sharedMobileKeyboardLayout:U.sharedMobileKeyboardLayout,suppressPageFlipRefresh:U.suppressPageFlipRefresh,focusRequestToken:Le?.sessionId===R.id?Le.token:0,resumeRequestToken:ye.token,resumeRequestReason:ye.reason,forceResumeReconnect:ye.forceForegroundReconnect&&er.has(R.id),resumeRequestDelayMs:er.has(R.id)?0:U.hidden?df:Be.get(R.id)??df,initialConnectDelayMs:Qe,onStreamReadyChange:kr,onStreamConnected:Zn,onViewportReadyChange:ys,onContentReadyChange:ss,onKeyboardVisibilityChange:br,showDebug:n,onStatusChange:X?S:void 0})})]},R.id)};return s.jsxs("div",{className:"relative h-full flex flex-col",children:[Mt&&Z.some(R=>R.id===Mt.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:F("tab.closeFailed",{name:Z.find(R=>R.id===Mt.sessionId).name})}),s.jsx("button",{type:"button",className:"shrink-0 rounded-lg px-2 py-1 text-primary hover:bg-surface-2",onClick:()=>{yt(Mt)},children:F("common.retry")}),s.jsx("button",{type:"button",className:"shrink-0 rounded-lg p-1 hover:bg-surface-2","aria-label":F("common.close"),onClick:()=>Xt(null),children:s.jsx(Mn,{size:16})})]}),Ze&&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(sg,{size:18})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("h2",{className:"text-[13px] font-semibold text-foreground",children:F("tab.tmuxRecoveryTitle",{count:Ze.sessions.length})}),s.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-muted-foreground",children:F("tab.tmuxRecoveryHint")}),s.jsx("p",{className:"mt-1.5 truncate text-[10px] text-foreground/70",children:Ze.sessions.map(R=>R.name).join(" · ")}),Ze.operation&&s.jsxs("div",{className:"mt-2 rounded-lg bg-surface-2 px-2.5 py-2 text-[10px] text-muted-foreground","aria-live":"polite",children:[s.jsx("p",{children:F("tab.tmuxRecoveryProgress",{total:Ze.operation.total,queued:Ze.operation.queued,paused:Ze.operation.paused_count,resourceWait:Ze.operation.resource_wait,running:Ze.operation.running,succeeded:Ze.operation.succeeded,failed:Ze.operation.failed})}),Ze.operation.pauseReason==="resources"&&s.jsx("p",{className:"mt-1",children:F("tab.tmuxRecoveryPausedForResources")}),s.jsx("div",{className:"mt-1 max-h-24 overflow-y-auto",children:Ze.operation.items.map(R=>s.jsxs("p",{className:`mt-1 ${R.errorCode?"text-destructive":""}`,children:[R.sessionId,": ",R.errorCode??R.resourceWaitReason??R.phase,R.memAvailableBytes!==void 0?` · 可用内存 ${(R.memAvailableBytes/1024**3).toFixed(1)} GiB`:"",R.actualRssBytes!==void 0?` · 实际 RSS ${(R.actualRssBytes/1024**2).toFixed(0)} MiB`:"",R.estimatedRssBytes!==void 0&&R.actualRssBytes===void 0?` · 预估 RSS ${(R.estimatedRssBytes/1024**2).toFixed(0)} MiB`:""]},R.sessionId))})]}),et&&s.jsx("p",{className:"mt-2 text-[10px] text-destructive",children:et}),s.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[s.jsxs("button",{type:"button",disabled:Wt!==null||!!(Ze.operation&&!["succeeded","partial_failure"].includes(Ze.operation.state)),onClick:()=>{Dt()},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(h3,{size:13,className:Wt==="restore"?"animate-spin":""}),Wt==="restore"?F("tab.tmuxRecoveryRestoring"):Ze.operation&&!["succeeded","partial_failure"].includes(Ze.operation.state)?F("tab.tmuxRecoveryInProgress"):F("tab.tmuxRecoveryRestoreAll")]}),Ze.operation&&["queued","resource_wait","running","paused"].includes(Ze.operation.state)&&s.jsx("button",{type:"button",disabled:Wt!==null,onClick:()=>{ur()},className:"inline-flex min-h-9 items-center rounded-lg px-3 text-[11px] text-muted-foreground transition hover:bg-surface-2 disabled:opacity-50",children:Ze.operation.paused?F("tab.tmuxRecoveryResume"):F("tab.tmuxRecoveryPause")}),s.jsx("button",{type:"button",disabled:Wt!==null||!!(Ze.operation&&!["succeeded","partial_failure"].includes(Ze.operation.state)),onClick:()=>{Pr()},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:F("tab.tmuxRecoveryDismiss")})]})]})]})}),s.jsx("div",{className:"flex-1 overflow-hidden",children:s.jsx(IA,{onSwiper:R=>{Se.current=R,R.allowTouchMove=Xr.length>1&&!Nr&&!Ge,cr("[swiper:on-swiper]",{allowTouchMove:R.allowTouchMove}),requestAnimationFrame(()=>Bn("on-swiper"))},onSlideChange:us,onTouchStart:(R,U)=>{const X=b5(U),be=X==="touch"||X==="pen"||X==="unknown";ee("[swipe:touch-start]",{pointerType:X,allowed:be}),cr("[swiper:touch-start]",{pointerType:X,allowed:be}),be&&(tn(),or.current=!0,Ct.current=!0)},onTouchEnd:(R,U)=>{const X=b5(U),be=X==="touch"||X==="pen"||X==="unknown";ee("[swipe:touch-end]",{pointerType:X,allowed:be}),cr("[swiper:touch-end]",{pointerType:X,allowed:be}),be&&(or.current=!1,xr("touch-end"))},onTransitionEnd:()=>{const R=Se.current;if(or.current){cr("[swiper:transition-end-during-touch]");return}if(Ct.current&&R&&!GN(R,it.current)){cr("[swiper:transition-end-deferred]");return}tn(),Ct.current=!1,cr("[swiper:transition-end]")},initialSlide:Math.max(0,is),speed:E1,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:Xr.map(R=>{const U=R.workspace,X=!!U&&R.sessions.length>=2,be=xt?$e?"horizontal":"vertical":U?.layout??"horizontal",Ee=xt&&Ot?R.sessions.some(ht=>ht.id===Ot):!1,Ve=R.sessions.some(ht=>ht.id===de)?de:R.sessions[0]?.id;return s.jsx(EA,{className:"h-full",children:s.jsx("div",{className:"h-full min-w-0","data-pinned-right-sidebar-inset":pn.get(R.key)??0,style:{paddingRight:pn.get(R.key)??0,paddingTop:y&&!X?"2.5rem":void 0},children:X?s.jsxs("div",{className:"flex h-full min-h-0 min-w-0 flex-col bg-[var(--chrome-bg)]",style:xt?{transform:"translateY(var(--kb-translate-y, 0px))",transition:"none"}:void 0,children:[P&&!xt&&s.jsx("header",{"data-termdock-window-header":"true","data-split-window-header":"true",className:"flex h-[46px] min-h-[46px] shrink-0 items-center app-chrome-bg pl-[88px] pr-3 text-[12px] text-muted-foreground",children:s.jsx("span",{className:"min-w-0 truncate",children:U?.name||F("tab.splitWorkspace")})}),s.jsx(Ux,{layoutId:R.key,preset:U?.layout??"horizontal",initialTree:EC(R.sessions.map(ht=>ht.id),be,U?.ratios,U?.gridColumnRatios,U?.gridRowRatios),mobile:xt,focusId:Ee?Ot:null,panes:R.sessions.map(ht=>({id:ht.id,content:ue(ht,{showPaneTitle:!xt,suppressKeyboard:xt&&ht.id!==Ve,keyboardPortalTarget:xt?Ce:null,sharedMobileKeyboardLayout:xt,suppressPageFlipRefresh:!0})}))}),xt&&s.jsx("div",{ref:St,className:"relative shrink-0 app-chrome-bg","data-split-keyboard-host":"true"})]}):s.jsx(Ux,{layoutId:R.key,preset:U?.layout??"horizontal",mobile:xt,panes:[{id:R.sessions[0].id,content:ue(R.sessions[0])}]})})},R.key)})})}),Ge&&de&&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:()=>vt(!1),"aria-label":F("common.close")}),s.jsxs("section",{ref:Yt,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":F("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(Fl,{size:17})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("h2",{className:"text-[14px] font-semibold text-foreground",children:F("tab.splitTitle")}),s.jsx("p",{className:"mt-0.5 text-[11px] leading-relaxed text-muted-foreground",children:F("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:()=>vt(!1),"aria-label":F("common.close"),children:s.jsx(Mn,{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:Et,onClick:()=>{es()},className:"flex w-full items-center gap-3 rounded-xl px-3 py-3 text-left transition hover:bg-surface-2 active:bg-surface-elevated disabled:opacity-60",children:[s.jsx("span",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-primary/15 text-primary",children:s.jsx(Zs,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-[13px] font-medium text-foreground",children:F("tab.splitNew")}),s.jsx("span",{className:"mt-0.5 block text-[11px] text-muted-foreground",children:F("tab.splitNewHint")})]})]}),ie.filter(R=>R.id!==Rr?.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:F("tab.splitExistingGroups")}),ie.filter(R=>R.id!==Rr?.id).map((R,U)=>{const X=R.sessionIds.flatMap(Ve=>{const ht=Z.find(Qe=>Qe.id===Ve);return ht?[ht]:[]});if(X.length<2)return null;const be=R.name||`${F("tab.splitWorkspace")} ${U+1}`,Ee=X.map(Ve=>H(Ve).primary).join(" · ");return s.jsxs("button",{type:"button",onClick:()=>Jn(X[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(Fl,{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:be}),s.jsx("span",{className:"shrink-0 rounded-full bg-primary/10 px-1.5 py-0.5 text-[9px] font-medium text-primary",children:F("tab.splitOccupied")})]}),s.jsxs("span",{className:"mt-0.5 block truncate text-[10px] text-muted-foreground",children:[F("tab.sessionCount",{count:X.length})," · ",Ee]})]}),s.jsx(ai,{size:14,className:"text-primary opacity-0 transition group-hover:opacity-100"})]},R.id)})]}),s.jsx("div",{className:"px-3 pb-1 pt-3 text-[10px] font-medium uppercase tracking-[0.12em] text-muted-foreground",children:F("tab.splitAvailableSessions")}),Z.filter(R=>!ie.some(U=>U.sessionIds.includes(R.id))&&R.id!==de).length===0&&ie.filter(R=>R.id!==Rr?.id).length===0?s.jsx("p",{className:"px-3 py-4 text-[12px] text-muted-foreground",children:F("tab.splitNoOtherSessions")}):Z.filter(R=>!ie.some(U=>U.sessionIds.includes(R.id))&&R.id!==de).map(R=>{const U=Fr.get(R.id)??null,X=H(R);return s.jsxs("button",{type:"button",onClick:()=>Jn(R.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:U?s.jsx(tu,{size:15}):s.jsx(Fl,{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:X.primary}),s.jsx("span",{className:"mt-0.5 block truncate text-[10px] text-muted-foreground",children:U?cd(U)??U:R.name})]}),s.jsx(ai,{size:14,className:"text-primary opacity-0 transition group-hover:opacity-100"})]},R.id)})]})]})]}),Nt&&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:Nt})]})},XN={sm:"h-4 w-7",md:"h-6 w-10"},JN={sm:"h-3 w-3",md:"h-5 w-5"},eR={sm:"translate-x-3",md:"translate-x-4"};function yl({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 ${XN[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 ${JN[r]} ${e?eR[r]:""}`})})}function ya(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 tR=typeof Symbol=="function"&&Symbol.observable||"@@observable",v5=tR,w5=()=>Math.random().toString(36).substring(7).split("").join("."),rR={INIT:`@@redux/INIT${w5()}`,REPLACE:`@@redux/REPLACE${w5()}`},A5=rR;function nR(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 Bv(e,t,r){if(typeof e!="function")throw new Error(ya(2));if(typeof t=="function"&&typeof r=="function"||typeof r=="function"&&typeof arguments[3]=="function")throw new Error(ya(0));if(typeof t=="function"&&typeof r>"u"&&(r=t,t=void 0),typeof r<"u"){if(typeof r!="function")throw new Error(ya(1));return r(Bv)(e,t)}let n=e,a=t,c=new Map,l=c,d=0,f=!1;function m(){l===c&&(l=new Map,c.forEach((I,N)=>{l.set(N,I)}))}function x(){if(f)throw new Error(ya(3));return a}function y(I){if(typeof I!="function")throw new Error(ya(4));if(f)throw new Error(ya(5));let N=!0;m();const B=d++;return l.set(B,I),function(){if(N){if(f)throw new Error(ya(6));N=!1,m(),l.delete(B),c=null}}}function w(I){if(!nR(I))throw new Error(ya(7));if(typeof I.type>"u")throw new Error(ya(8));if(typeof I.type!="string")throw new Error(ya(17));if(f)throw new Error(ya(9));try{f=!0,a=n(a,I)}finally{f=!1}return(c=l).forEach(B=>{B()}),I}function v(I){if(typeof I!="function")throw new Error(ya(10));n=I,w({type:A5.REPLACE})}function T(){const I=y;return{subscribe(N){if(typeof N!="object"||N===null)throw new Error(ya(11));function B(){const P=N;P.next&&P.next(x())}return B(),{unsubscribe:I(B)}},[v5](){return this}}}return w({type:A5.INIT}),{dispatch:w,subscribe:y,getState:x,replaceReducer:v,[v5]:T}}function T5(e,t){return function(...r){return t(e.apply(this,r))}}function S5(e,t){if(typeof e=="function")return T5(e,t);if(typeof e!="object"||e===null)throw new Error(ya(16));const r={};for(const n in e){const a=e[n];typeof a=="function"&&(r[n]=T5(a,t))}return r}function Qv(...e){return e.length===0?t=>t:e.length===1?e[0]:e.reduce((t,r)=>(...n)=>t(r(...n)))}function sR(...e){return t=>(r,n)=>{const a=t(r,n);let c=()=>{throw new Error(ya(15))};const l={getState:a.getState,dispatch:(f,...m)=>c(f,...m)},d=e.map(f=>f(l));return c=Qv(...d)(a.dispatch),{...a,dispatch:c}}}var Am={exports:{}},Tm={};var C5;function iR(){if(C5)return Tm;C5=1;var e=UA();function t(f,m){return f===m&&(f!==0||1/f===1/m)||f!==f&&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 Tm.useSyncExternalStoreWithSelector=function(f,m,x,y,w){var v=a(null);if(v.current===null){var T={hasValue:!1,value:null};v.current=T}else T=v.current;v=l(function(){function I($){if(!N){if(N=!0,B=$,$=y($),w!==void 0&&T.hasValue){var ee=T.value;if(w(ee,$))return F=ee}return F=$}if(ee=F,r(B,$))return ee;var Z=y($);return w!==void 0&&w(ee,Z)?(B=$,ee):(B=$,F=Z)}var N=!1,B,F,P=x===void 0?null:x;return[function(){return I(m())},P===null?void 0:function(){return I(P())}]},[m,x,y,w]);var S=n(f,v[0],v[1]);return c(function(){T.hasValue=!0,T.value=S},[S]),d(S),S},Tm}var _5;function aR(){return _5||(_5=1,Am.exports=iR()),Am.exports}aR();var oR=b.version.startsWith("19"),lR=Symbol.for(oR?"react.transitional.element":"react.element"),cR=Symbol.for("react.portal"),uR=Symbol.for("react.fragment"),dR=Symbol.for("react.strict_mode"),hR=Symbol.for("react.profiler"),fR=Symbol.for("react.consumer"),pR=Symbol.for("react.context"),Pv=Symbol.for("react.forward_ref"),mR=Symbol.for("react.suspense"),gR=Symbol.for("react.suspense_list"),Cg=Symbol.for("react.memo"),xR=Symbol.for("react.lazy"),bR=Pv,yR=Cg;function vR(e){if(typeof e=="object"&&e!==null){const{$$typeof:t}=e;switch(t){case lR:switch(e=e.type,e){case uR:case hR:case dR:case mR:case gR:return e;default:switch(e=e&&e.$$typeof,e){case pR:case Pv:case xR:case Cg:return e;case fR:return e;default:return t}}case cR:return t}}}function wR(e){return vR(e)===Cg}function AR(e,t,r,n,{areStatesEqual:a,areOwnPropsEqual:c,areStatePropsEqual:l}){let d=!1,f,m,x,y,w;function v(B,F){return f=B,m=F,x=e(f,m),y=t(n,m),w=r(x,y,m),d=!0,w}function T(){return x=e(f,m),t.dependsOnOwnProps&&(y=t(n,m)),w=r(x,y,m),w}function S(){return e.dependsOnOwnProps&&(x=e(f,m)),t.dependsOnOwnProps&&(y=t(n,m)),w=r(x,y,m),w}function I(){const B=e(f,m),F=!l(B,x);return x=B,F&&(w=r(x,y,m)),w}function N(B,F){const P=!c(F,m),$=!a(B,f,F,m);return f=B,m=F,P&&$?T():P?S():$?I():w}return function(F,P){return d?N(F,P):v(F,P)}}function TR(e,{initMapStateToProps:t,initMapDispatchToProps:r,initMergeProps:n,...a}){const c=t(e,a),l=r(e,a),d=n(e,a);return AR(c,l,d,e,a)}function SR(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 M1(e){return function(r){const n=e(r);function a(){return n}return a.dependsOnOwnProps=!1,a}}function k5(e){return e.dependsOnOwnProps?!!e.dependsOnOwnProps:e.length!==1}function Ov(e,t){return function(n,{displayName:a}){const c=function(d,f){return c.dependsOnOwnProps?c.mapToProps(d,f):c.mapToProps(d,void 0)};return c.dependsOnOwnProps=!0,c.mapToProps=function(d,f){c.mapToProps=e,c.dependsOnOwnProps=k5(e);let m=c(d,f);return typeof m=="function"&&(c.mapToProps=m,c.dependsOnOwnProps=k5(m),m=c(d,f)),m},c}}function _g(e,t){return(r,n)=>{throw new Error(`Invalid value of type ${typeof e} for ${t} argument when connecting component ${n.wrappedComponentName}.`)}}function CR(e){return e&&typeof e=="object"?M1(t=>SR(e,t)):e?typeof e=="function"?Ov(e):_g(e,"mapDispatchToProps"):M1(t=>({dispatch:t}))}function _R(e){return e?typeof e=="function"?Ov(e):_g(e,"mapStateToProps"):M1(()=>({}))}function kR(e,t,r){return{...r,...e,...t}}function LR(e){return function(r,{displayName:n,areMergedPropsEqual:a}){let c=!1,l;return function(f,m,x){const y=e(f,m,x);return c?a(y,l)||(l=y):(c=!0,l=y),l}}}function IR(e){return e?typeof e=="function"?LR(e):_g(e,"mergeProps"):()=>kR}function ER(e){e()}function NR(){let e=null,t=null;return{clear(){e=null,t=null},notify(){ER(()=>{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 L5={notify(){},get:()=>[]};function Fv(e,t){let r,n=L5,a=0,c=!1;function l(S){x();const I=n.subscribe(S);let N=!1;return()=>{N||(N=!0,I(),y())}}function d(){n.notify()}function f(){T.onStateChange&&T.onStateChange()}function m(){return c}function x(){a++,r||(r=t?t.addNestedSub(f):e.subscribe(f),n=NR())}function y(){a--,r&&a===0&&(r(),r=void 0,n.clear(),n=L5)}function w(){c||(c=!0,x())}function v(){c&&(c=!1,y())}const T={addNestedSub:l,notifyNestedSubs:d,handleChangeWrapper:f,isSubscribed:m,trySubscribe:w,tryUnsubscribe:v,getListeners:()=>n};return T}var RR=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",MR=RR(),jR=()=>typeof navigator<"u"&&navigator.product==="ReactNative",DR=jR(),BR=()=>MR||DR?b.useLayoutEffect:b.useEffect,Pf=BR();function I5(e,t){return e===t?e!==0||t!==0||1/e===1/t:e!==e&&t!==t}function Sm(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 QR={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},PR={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},OR={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},$v={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},FR={[bR]:OR,[yR]:$v};function E5(e){return wR(e)?$v:FR[e.$$typeof]||QR}var $R=Object.defineProperty,UR=Object.getOwnPropertyNames,N5=Object.getOwnPropertySymbols,zR=Object.getOwnPropertyDescriptor,HR=Object.getPrototypeOf,R5=Object.prototype;function j1(e,t){if(typeof t!="string"){if(R5){const c=HR(t);c&&c!==R5&&j1(e,c)}let r=UR(t);N5&&(r=r.concat(N5(t)));const n=E5(e),a=E5(t);for(let c=0;c<r.length;++c){const l=r[c];if(!PR[l]&&!(a&&a[l])&&!(n&&n[l])){const d=zR(t,l);try{$R(e,l,d)}catch{}}}}return e}var WR=Symbol.for("react-redux-context"),GR=typeof globalThis<"u"?globalThis:{};function VR(){if(!b.createContext)return{};const e=GR[WR]??=new Map;let t=e.get(b.createContext);return t||(t=b.createContext(null),e.set(b.createContext,t)),t}var Uv=VR(),qR=[null,null];function YR(e,t,r){Pf(()=>e(...t),r)}function ZR(e,t,r,n,a,c){e.current=n,r.current=!1,a.current&&(a.current=null,c())}function KR(e,t,r,n,a,c,l,d,f,m,x){if(!e)return()=>{};let y=!1,w=null;const v=()=>{if(y||!d.current)return;const S=t.getState();let I,N;try{I=n(S,a.current)}catch(B){N=B,w=B}N||(w=null),I===c.current?l.current||m():(c.current=I,f.current=I,l.current=!0,x())};return r.onStateChange=v,r.trySubscribe(),v(),()=>{if(y=!0,r.tryUnsubscribe(),r.onStateChange=null,w)throw w}}function XR(e,t){return e===t}function JR(e,t,r,{pure:n,areStatesEqual:a=XR,areOwnPropsEqual:c=Sm,areStatePropsEqual:l=Sm,areMergedPropsEqual:d=Sm,forwardRef:f=!1,context:m=Uv}={}){const x=m,y=_R(e),w=CR(t),v=IR(r),T=!!e;return I=>{const N=I.displayName||I.name||"Component",B=`Connect(${N})`,F={shouldHandleStateChanges:T,displayName:B,wrappedComponentName:N,WrappedComponent:I,initMapStateToProps:y,initMapDispatchToProps:w,initMergeProps:v,areStatesEqual:a,areStatePropsEqual:l,areOwnPropsEqual:c,areMergedPropsEqual:d};function P(Z){const[V,de,pe]=b.useMemo(()=>{const{reactReduxForwardedRef:dt,...ft}=Z;return[Z.context,dt,ft]},[Z]),J=b.useMemo(()=>{let dt=x;return V?.Consumer,dt},[V,x]),Re=b.useContext(J),Xe=!!Z.store&&!!Z.store.getState&&!!Z.store.dispatch,q=!!Re&&!!Re.store,ve=Xe?Z.store:Re.store,qe=q?Re.getServerState:ve.getState,ce=b.useMemo(()=>TR(ve.dispatch,F),[ve]),[ye,Te]=b.useMemo(()=>{if(!T)return qR;const dt=Fv(ve,Xe?void 0:Re.subscription),ft=dt.notifyNestedSubs.bind(dt);return[dt,ft]},[ve,Xe,Re]),Fe=b.useMemo(()=>Xe?Re:{...Re,subscription:ye},[Xe,Re,ye]),se=b.useRef(void 0),De=b.useRef(pe),_e=b.useRef(void 0),Me=b.useRef(!1),Je=b.useRef(!1),Ne=b.useRef(void 0);Pf(()=>(Je.current=!0,()=>{Je.current=!1}),[]);const ae=b.useMemo(()=>()=>_e.current&&pe===De.current?_e.current:ce(ve.getState(),pe),[ve,pe]),ze=b.useMemo(()=>ft=>ye?KR(T,ve,ye,ce,De,se,Me,Je,_e,Te,ft):()=>{},[ye]);YR(ZR,[De,se,Me,pe,_e,Te]);let at;try{at=b.useSyncExternalStore(ze,ae,qe?()=>ce(qe(),pe):ae)}catch(dt){throw Ne.current&&(dt.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:Vf[t.status]??"成员明确报告",createdAt:l?t.createdAt:null,content:r,summary:c?c.slice(0,512):"报告摘要未提供,请查看详情中的原始报告"}}function gp(e){if(e.status!=="open")return[];const t=qf(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 kQ(e){return gp(e)[0]??null}function ou(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=kQ(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?Vf[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 ta(e){return e.purpose!=="automation"&&e.status==="open"&&["需要你回答","需要你确认方案","等待你验收","执行准备受阻","自动安排受阻","成员报告受阻","成员报告失败","投递未成功","投递需要关注","投递需要处理"].includes(ou(e))}function lb(){return JSON.stringify(Ki())}function LQ(e){const t=e instanceof Error?e.message:String(e);return(e&&typeof e=="object"&&"name"in e?String(e.name):"")==="UnexpectedEOFError"&&/^Unexpected EOF - stream closed while reading \d+\/\d+ bytes$/.test(t)||t==="Secure response ended unexpectedly"?"连接中断,待处理事项暂时无法加载;恢复后会自动重试。":t||"协作待处理事项加载失败"}const Ou=vc(e=>{let t=0,r,n=null,a;return{tasks:[],allTasks:[],error:null,refresh:async()=>{const c=lb();if(a?.target===c)return a.promise;a?.controller.abort(),r!==c&&(r=c,n=null,e({tasks:[],allTasks:[],error:null}));const l=++t,d=new AbortController,f={owner:l,target:c,controller:d,promise:Promise.resolve()};a=f;const m=()=>a?.owner===l&&lb()===c;return f.promise=(async()=>{try{const{tasks:x}=await Yy(void 0,d.signal);m()&&(n=null,e({tasks:x.filter(ta),allTasks:x,error:null}))}catch(x){if(!m()||d.signal.aborted||x instanceof Error&&x.name==="AbortError")return;const y=x instanceof Error?x.message:String(x);n!==y&&(console.error("[CollaborationTaskInbox] refresh failed",x),n=y),e({error:LQ(x)})}finally{a?.owner===l&&(a=void 0)}})(),f.promise}}});function cb(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 ub(e){const t=e.trim().match(/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/);return t?{numbers:[Number(t[1]),Number(t[2]),Number(t[3])],prerelease:t[4]??null}:null}function IQ(e,t){const r=ub(e),n=ub(t);if(!r||!n)throw new Error(`Invalid version comparison: ${e} / ${t}`);for(let a=0;a<3;a+=1)if(r.numbers[a]!==n.numbers[a])return r.numbers[a]-n.numbers[a];return r.prerelease===n.prerelease?0:r.prerelease===null?1:n.prerelease===null?-1:r.prerelease.localeCompare(n.prerelease,"en",{numeric:!0})}function db({sessionIds:e}){const t=V8(a=>e.reduce((c,l)=>c+(a.unread[l]?.length??0),0)),{locale:r}=Hr();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 G6(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 NQ(e,t,r){return Math.max(t,Math.min(e,r))}const bs={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 hb(e,t,r){return t===0||Math.abs(t)===1/0?Math.pow(e,r*5):e*t*r/(t+r*e)}function fb(e,t,r,n=.15){return n===0?NQ(e,t,r):e<t?-hb(t-e,r-t,n)+t:e>r?+hb(e-r,r-t,n)+r:e}function RQ(e,[t,r],[n,a]){const[[c,l],[d,f]]=e;return[fb(t,c,l,n),fb(r,d,f,a)]}function MQ(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 jQ(e){var t=MQ(e,"string");return typeof t=="symbol"?t:String(t)}function Ws(e,t,r){return t=jQ(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function pb(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 ks(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?pb(Object(r),!0).forEach(function(n){Ws(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):pb(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}const V6={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 mb(e){return e?e[0].toUpperCase()+e.slice(1):""}const DQ=["enter","leave"];function BQ(e=!1,t){return e&&!DQ.includes(t)}function QQ(e,t="",r=!1){const n=V6[e],a=n&&n[t]||t;return"on"+mb(e)+mb(a)+(BQ(r,a)?"Capture":"")}const PQ=["gotpointercapture","lostpointercapture"];function OQ(e){let t=e.substring(2).toLowerCase();const r=!!~t.indexOf("passive");r&&(t=t.replace("passive",""));const n=PQ.includes(t)?"capturecapture":"capture",a=!!~t.indexOf(n);return a&&(t=t.replace("capture","")),{device:t,capture:a,passive:r}}function FQ(e,t=""){const r=V6[e],n=r&&r[t]||t;return e+n}function xp(e){return"touches"in e}function q6(e){return xp(e)?"touch":"pointerType"in e?e.pointerType:"mouse"}function $Q(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 UQ(e){return e.type==="touchend"||e.type==="touchcancel"?e.changedTouches:e.targetTouches}function Y6(e){return xp(e)?UQ(e)[0]:e}function U1(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 zQ(e){return $Q(e).map(t=>t.identifier)}function gb(e,t){const[r,n]=Array.from(e.touches).filter(a=>t.includes(a.identifier));return U1(r,n)}function Dm(e){const t=Y6(e);return xp(e)?t.identifier:t.pointerId}function od(e){const t=Y6(e);return[t.clientX,t.clientY]}const xb=40,bb=800;function Z6(e){let{deltaX:t,deltaY:r,deltaMode:n}=e;return n===1?(t*=xb,r*=xb):n===2&&(t*=bb,r*=bb),[t,r]}function HQ(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 WQ(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 Yf(e,...t){return typeof e=="function"?e(...t):e}function GQ(){}function VQ(...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 yb(e,t){return Object.assign({},t,e||{})}const qQ=32;class K6{constructor(t,r,n){this.ctrl=t,this.args=r,this.key=n,this.state||(this.state={},this.computeValues([0,0]),this.computeInitial(),this.init&&this.init(),this.reset())}get state(){return this.ctrl.state[this.key]}set state(t){this.ctrl.state[this.key]=t}get shared(){return this.ctrl.state.shared}get eventStore(){return this.ctrl.gestureEventStores[this.key]}get timeoutStore(){return this.ctrl.gestureTimeoutStores[this.key]}get config(){return this.ctrl.config[this.key]}get sharedConfig(){return this.ctrl.config.shared}get handler(){return this.ctrl.handlers[this.key]}reset(){const{state:t,shared:r,ingKey:n,args:a}=this;r[n]=t._active=t.active=t._blocked=t._force=!1,t._step=[!1,!1],t.intentional=!1,t._movement=[0,0],t._distance=[0,0],t._direction=[0,0],t._delta=[0,0],t._bounds=[[-1/0,1/0],[-1/0,1/0]],t.args=a,t.axis=void 0,t.memo=void 0,t.elapsedTime=t.timeDelta=0,t.direction=[0,0],t.distance=[0,0],t.overflow=[0,0],t._movementBound=[!1,!1],t.velocity=[0,0],t.movement=[0,0],t.delta=[0,0],t.timeStamp=0}start(t){const r=this.state,n=this.config;r._active||(this.reset(),this.computeInitial(),r._active=!0,r.target=t.target,r.currentTarget=t.currentTarget,r.lastOffset=n.from?Yf(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,WQ(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 ee=r._delta.map(Math.abs);bs.addTo(r._distance,ee)}this.axisIntent&&this.axisIntent(t);const[l,d]=r._movement,[f,m]=n.threshold,{_step:x,values:y}=r;if(n.hasCustomTransform?(x[0]===!1&&(x[0]=Math.abs(l)>=f&&y[0]),x[1]===!1&&(x[1]=Math.abs(d)>=m&&y[1])):(x[0]===!1&&(x[0]=Math.abs(l)>=f&&Math.sign(l)*f),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[ee,Z]=y;w[0]=x[0]!==!1?ee-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,T=r._active&&!r._blocked||r.active;T&&(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=Yf(n.bounds,r)),this.setup&&this.setup()),r.movement=w,this.computeOffset()));const[S,I]=r.offset,[[N,B],[F,P]]=r._bounds;r.overflow=[S<N?-1:S>B?1:0,I<F?-1:I>P?1:0],r._movementBound[0]=r.overflow[0]?r._movementBound[0]===!1?r._movement[0]:r._movementBound[0]:!1,r._movementBound[1]=r.overflow[1]?r._movementBound[1]===!1?r._movement[1]:r._movementBound[1]:!1;const $=r._active?n.rubberband||[0,0]:[0,0];if(r.offset=RQ(r._bounds,r.offset,$),r.delta=bs.sub(r.offset,v),this.computeMovement(),T&&(!r.last||c>qQ)){r.delta=bs.sub(r.offset,v);const ee=r.delta.map(Math.abs);bs.addTo(r.distance,ee),r.direction=r.delta.map(Math.sign),r._direction=r._delta.map(Math.sign),!r.first&&c>0&&(r.velocity=[ee[0]/c,ee[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(ks(ks(ks({},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 J0 extends K6{constructor(...t){super(...t),Ws(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=bs.add(this.state.lastOffset,this.state.movement)}computeMovement(){this.state.movement=bs.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[q6(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 ZQ=e=>e,vb=.15,X6={enabled(e=!0){return e},eventOptions(e,t,r){return ks(ks({},r.shared.eventOptions),e)},preventDefault(e=!1){return e},triggerAllEvents(e=!1){return e},rubberband(e=0){switch(e){case!0:return[vb,vb];case!1:return[0,0];default:return bs.toVector(e)}},from(e){if(typeof e=="function")return e;if(e!=null)return bs.toVector(e)},transform(e,t,r){const n=e||r.shared.transform;return this.hasCustomTransform=!!n,n||ZQ},threshold(e){return bs.toVector(e,0)}},KQ=0,lu=ks(ks({},X6),{},{axis(e,t,{axis:r}){if(this.lockDirection=r==="lock",!this.lockDirection)return r},axisThreshold(e=KQ){return e},bounds(e={}){if(typeof e=="function")return c=>lu.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]]}}),wb={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 XQ extends J0{constructor(...t){super(...t),Ws(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=lu.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=Dm(t),n._pointerActive=!0,this.computeValues(od(t)),this.computeInitial(),r.preventScrollAxis&&q6(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=Dm(t);if(r._pointerId!==void 0&&a!==r._pointerId)return;const c=od(t);if(document.pointerLockElement===t.target?r._delta=[t.movementX,t.movementY]:(r._delta=bs.sub(c,r._values),this.computeValues(c)),bs.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=Dm(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,f]=r._delta,[m,x]=r._movement,[y,w]=n.swipe.velocity,[v,T]=n.swipe.distance,S=n.swipe.duration;if(r.elapsedTime<S){const I=Math.abs(d/r.timeDelta),N=Math.abs(f/r.timeDelta);I>y&&Math.abs(m)>v&&(r.swipe[0]=Math.sign(d)),N>w&&Math.abs(x)>T&&(r.swipe[1]=Math.sign(f))}}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,JQ(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=wb[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,bs.addTo(n._movement,n._delta),this.compute(t),this.emit()}}keyUp(t){t.key in wb&&(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 JQ(e){"persist"in e&&typeof e.persist=="function"&&e.persist()}const eh=typeof window<"u"&&window.document&&window.document.createElement;function J6(){return eh&&"ontouchstart"in window}function eP(){return J6()||eh&&window.navigator.maxTouchPoints>1}function tP(){return eh&&"onpointerdown"in window}function rP(){return eh&&"exitPointerLock"in window.document}function nP(){try{return"constructor"in GestureEvent}catch{return!1}}const _o={isBrowser:eh,gesture:nP(),touch:J6(),touchscreen:eP(),pointer:tP(),pointerLock:rP()},sP=250,iP=180,aP=.5,oP=50,lP=250,cP=10,Ab={mouse:0,touch:0,pen:8},uP=ks(ks({},lu),{},{device(e,t,{pointer:{touch:r=!1,lock:n=!1,mouse:a=!1}={}}){return this.pointerLock=n&&_o.pointerLock,_o.touch&&r?"touch":this.pointerLock?"mouse":_o.pointer&&!a?"pointer":_o.touch?"touch":"mouse"},preventScrollAxis(e,t,{preventScroll:r}){if(this.preventScrollDelay=typeof r=="number"?r:r||r===void 0&&e?sP:void 0,!(!_o.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=bs.toVector(e,r?n:a?1:0);return this.filterTaps=r,this.tapsThreshold=n,c},swipe({velocity:e=aP,distance:t=oP,duration:r=lP}={}){return{velocity:this.transform(bs.toVector(e)),distance:this.transform(bs.toVector(t)),duration:r}},delay(e=0){switch(e){case!0:return iP;case!1:return 0;default:return e}},axisThreshold(e){return e?ks(ks({},Ab),e):Ab},keyboardDisplacement(e=cP){return e}});function e4(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 dP=30,hP=100;class fP extends K6{constructor(...t){super(...t),Ws(this,"ingKey","pinching"),Ws(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=bs.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)*dP-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=gb(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=U1(...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=gb(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=U1(...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=bs.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=[-Z6(t)[1]/hP*n.offset[0],0],bs.addTo(n._movement,n._delta),e4(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 pP=ks(ks({},X6),{},{device(e,t,{shared:r,pointer:{touch:n=!1}={}}){if(r.target&&!_o.touch&&_o.gesture)return"gesture";if(_o.touch&&n)return"touch";if(_o.touchscreen){if(_o.pointer)return"pointer";if(_o.touch)return"touch"}},bounds(e,t,{scaleBounds:r={},angleBounds:n={}}){const a=l=>{const d=yb(Yf(r,l),{min:-1/0,max:1/0});return[d.min,d.max]},c=l=>{const d=yb(Yf(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",bs.toVector(e,this.lockDirection?[.1,3]:0)},modifierKey(e){return e===void 0?"ctrlKey":e},pinchOnWheel(e=!0){return e}});class mP extends J0{constructor(...t){super(...t),Ws(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(od(t)),this.compute(t),this.computeInitial(),this.emit()}moveChange(t){if(!this.state._active)return;const r=od(t),n=this.state;n._delta=bs.sub(r,n._values),bs.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 gP=ks(ks({},lu),{},{mouseOnly:(e=!0)=>e});class xP extends J0{constructor(...t){super(...t),Ws(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=HQ(t);r._delta=bs.sub(n,r._values),bs.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 bP=lu;class yP extends J0{constructor(...t){super(...t),Ws(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=Z6(t),bs.addTo(r._movement,r._delta),e4(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 vP=lu;class wP extends J0{constructor(...t){super(...t),Ws(this,"ingKey","hovering")}enter(t){this.config.mouseOnly&&t.pointerType!=="mouse"||(this.start(t),this.computeValues(od(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=od(t);r._movement=r._delta=bs.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 AP=ks(ks({},lu),{},{mouseOnly:(e=!0)=>e}),qg=new Map,z1=new Map;function t4(e){qg.set(e.key,e.engine),z1.set(e.key,e.resolver)}const r4={key:"drag",engine:XQ,resolver:uP},TP={key:"hover",engine:wP,resolver:AP},SP={key:"move",engine:mP,resolver:gP},CP={key:"pinch",engine:fP,resolver:pP},_P={key:"scroll",engine:xP,resolver:bP},kP={key:"wheel",engine:yP,resolver:vP};function LP(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 IP(e,t){if(e==null)return{};var r=LP(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=_o.isBrowser?window:void 0){return e},eventOptions({passive:e=!0,capture:t=!1}={}){return{passive:e,capture:t}},transform(e){return e}},NP=["target","eventOptions","window","enabled","transform"];function mf(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]=mf(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:f}=n,m=IP(n,NP);if(r.shared=mf({target:a,eventOptions:c,window:l,enabled:d,transform:f},EP),t){const x=z1.get(t);r[t]=mf(ks({shared:r.shared},m),x)}else for(const x in m){const y=z1.get(x);y&&(r[x]=mf(ks({shared:r.shared},m[x]),y))}return r}class n4{constructor(t,r){Ws(this,"_listeners",new Set),this._ctrl=t,this._gestureKey=r}add(t,r,n,a,c){const l=this._listeners,d=FQ(r,n),f=this._gestureKey?this._ctrl.config[this._gestureKey].eventOptions:{},m=ks(ks({},f),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 MP{constructor(){Ws(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 jP{constructor(t){Ws(this,"gestures",new Set),Ws(this,"_targetEventStore",new n4(this)),Ws(this,"gestureEventStores",{}),Ws(this,"gestureTimeoutStores",{}),Ws(this,"handlers",{}),Ws(this,"config",{}),Ws(this,"pointerIds",new Set),Ws(this,"touchIds",new Set),Ws(this,"state",{shared:{shiftKey:!1,metaKey:!1,ctrlKey:!1,altKey:!1}}),DP(this,t)}setEventIds(t){if(xp(t))return this.touchIds=new Set(zQ(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],f=Tb(n,d.eventOptions,!!a);if(d.enabled){const m=qg.get(l);new m(this,t,l).bind(f)}}const c=Tb(n,r.eventOptions,!!a);for(const l in this.nativeHandlers)c(l,"",d=>this.nativeHandlers[l](ks(ks({},this.state.shared),{},{event:d,args:t})),void 0,!0)}for(const c in n)n[c]=VQ(...n[c]);if(!a)return n;for(const c in n){const{device:l,capture:d,passive:f}=OQ(c);this._targetEventStore.add(a,l,"",n[c],{capture:d,passive:f})}}}}function Nu(e,t){e.gestures.add(t),e.gestureEventStores[t]=new n4(e,t),e.gestureTimeoutStores[t]=new MP}function DP(e,t){t.drag&&Nu(e,"drag"),t.wheel&&Nu(e,"wheel"),t.scroll&&Nu(e,"scroll"),t.move&&Nu(e,"move"),t.pinch&&Nu(e,"pinch"),t.hover&&Nu(e,"hover")}const Tb=(e,t,r)=>(n,a,c,l={},d=!1)=>{var f,m;const x=(f=l.capture)!==null&&f!==void 0?f:t.capture,y=(m=l.passive)!==null&&m!==void 0?m:t.passive;let w=d?n:QQ(n,a,x);r&&y&&(w+="Passive"),e[w]=e[w]||[],e[w].push(c)},BP=/^on(Drag|Wheel|Scroll|Move|Pinch|Hover)/;function QP(e){const t={},r={},n=new Set;for(let a in e)BP.test(a)?(n.add(RegExp.lastMatch),r[a]=e[a]):t[a]=e[a];return[r,t,n]}function Ru(e,t,r,n,a,c){if(!e.has(r)||!qg.has(n))return;const l=r+"Start",d=r+"End",f=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]=f,c[n]=c[n]||{}}function PP(e,t){const[r,n,a]=QP(e),c={};return Ru(a,r,"onDrag","drag",c,t),Ru(a,r,"onWheel","wheel",c,t),Ru(a,r,"onScroll","scroll",c,t),Ru(a,r,"onPinch","pinch",c,t),Ru(a,r,"onMove","move",c,t),Ru(a,r,"onHover","hover",c,t),{handlers:c,config:t,nativeHandlers:n}}function s4(e,t={},r,n){const a=_.useMemo(()=>new jP(e),[]);if(a.applyHandlers(e,n),a.applyConfig(t,r),_.useEffect(a.effect.bind(a)),_.useEffect(()=>a.clean.bind(a),[]),t.target===void 0)return a.bind.bind(a)}function Sb(e,t){return t4(r4),s4({drag:e},t||{},"drag")}function OP(e){return e.forEach(t4),function(r,n){const{handlers:a,nativeHandlers:c,config:l}=PP(r,n||{});return s4(a,l,void 0,c)}}function dz(e,t){return OP([r4,CP,_P,kP,SP,TP])(e,t||{})}const Cb={dampingRatio:.8,response:.3},FP=.998;function $P(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,T=l+a*c;return{value:S=>n+(v+T*S)*Math.exp(-a*S),velocity:S=>(T-a*(v+T*S))*Math.exp(-a*S)}}if(d<1){const v=a*Math.sqrt(1-d*d),T=c,S=(l+d*a*c)/v;return{value:I=>n+Math.exp(-d*a*I)*(T*Math.cos(v*I)+S*Math.sin(v*I)),velocity:I=>Math.exp(-d*a*I)*((S*v-d*a*T)*Math.cos(v*I)-(T*v+d*a*S)*Math.sin(v*I))}}const f=a*Math.sqrt(d*d-1),m=-d*a+f,x=-d*a-f,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 UP(e,t=FP){return e/1e3*(t/(1-t))}function _b(e,t,r=.55){return e*t*r/(t+r*Math.abs(e))}function zP(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}const HP=.1,WP=5;function GP(e,t,r,n,a){const c=$P(e,t,r,n),l=1e3/60,d=240,f=[];for(let m=0;m<d;m++){const x=m*l/1e3,y=c.value(x),w=c.velocity(x);if(f.push(a?a(y):y),m>0&&Math.abs(y-n)<HP&&Math.abs(w)<WP)break}return f.push(a?a(n):n),{frames:f,durationMs:(f.length-1)*l,solver:c}}const VP='input:not([type="hidden"]), textarea, select, [contenteditable]:not([contenteditable="false"])';function qP(){if(typeof document>"u")return;const e=document.activeElement;e instanceof HTMLElement&&e.matches(VP)&&e.blur()}const YP=18,kb=8,Lb={touch:kb,pen:kb},ZP=500,Bm=200,Ib=50,KP=`[${NA}]`;function Qm(e,t,r){return Math.min(r,Math.max(t,e))}function Eb(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 Nb(e){if(!e||typeof e!="object")return!1;const t=e.target;return t instanceof Element&&!!t.closest(KP)}function Kd(...e){typeof window<"u"&&window.__SIDEBAR_DEBUG__&&console.log("[Sidebar]",...e)}const i4=_.forwardRef(function({side:t,isOpen:r,drawerWidthPx:n,onClose:a,onOpen:c,children:l,pinned:d=!1},f){const{t:m}=Hr(),x=t==="left",y=x?-n:n,w=b.useRef(null),v=b.useRef(null),T=b.useRef(r?0:y),S=b.useRef(null),I=b.useRef(null),N=b.useRef(0),B=b.useRef(null),F=b.useRef(null),P=b.useRef(!1),$=b.useRef(null),ee=b.useRef(!1),Z=b.useRef([]),V=b.useRef(null),de=b.useRef(T.current),pe=b.useRef(r?1:0),J=b.useRef(r);J.current=r;const Re=b.useRef(y);Re.current=y;const Xe=b.useRef(n);Xe.current=n;const q=b.useRef(x);q.current=x;const ve=b.useRef(a);ve.current=a;const qe=b.useRef(c);qe.current=c;const ce=b.useCallback(ie=>{w.current=ie,typeof f=="function"?f(ie):f&&(f.current=ie)},[f]),ye=b.useCallback(()=>{I.current!==null&&(window.cancelAnimationFrame(I.current),I.current=null),S.current=null},[]),Te=b.useCallback(ie=>{const ge=Xe.current;return q.current?(ie+ge)/ge:(ge-ie)/ge},[]),Fe=b.useCallback(ie=>{const ge=v.current;ge&&(ge.style.opacity=String(Qm(Te(ie),0,1)))},[Te]),se=b.useCallback(ie=>{T.current=ie;const ge=w.current;ge&&(ge.style.transform=`translateX(${ie}px)`,Fe(ie))},[Fe]),De=b.useCallback(ie=>{S.current=ie,I.current===null&&(I.current=window.requestAnimationFrame(()=>{I.current=null;const ge=S.current;S.current=null,ge!==null&&se(ge)}))},[se]),_e=b.useCallback(()=>{I.current!==null&&(window.cancelAnimationFrame(I.current),I.current=null);const ie=S.current;S.current=null,ie!==null&&se(ie)},[se]),Me=b.useCallback(ie=>{const ge=Re.current;return Qm(ie,Math.min(0,ge),Math.max(0,ge))},[]),Je=b.useCallback(()=>{const ie=B.current;if(!ie)return null;B.current=null;const ge=(performance.now()-ie.startTime)/1e3,Ge={value:ie.solver.value(ge),velocity:ie.solver.velocity(ge)};return ie.animations.forEach(rt=>rt.cancel()),Ge},[]),Ne=b.useCallback(()=>{F.current!==null&&(window.clearTimeout(F.current),F.current=null)},[]),ae=b.useCallback(()=>{V.current?.(),V.current=null},[]),ze=b.useCallback(()=>{_e(),Ne();const ie=Je();ie&&se(Me(ie.value));const ge=w.current,Ge=v.current;ge?.getAnimations().forEach(rt=>rt.cancel()),ge&&(ge.style.transition="none",ge.style.opacity="1"),Ge?.getAnimations().forEach(rt=>rt.cancel()),Ge&&(Ge.style.transition="none")},[se,Ne,Me,_e,Je]),at=b.useCallback((ie,ge)=>{_e(),Ne();const Ge=w.current,rt=v.current,vt=ie?0:Re.current;rt&&(rt.style.pointerEvents=ie?"auto":"none");const Yt=Je(),Ut=Yt?Me(Yt.value):T.current,Nt=ge?.velocity??Yt?.velocity??0;if(zP())return T.current=vt,Ge&&(Ge.style.transition=`opacity ${Bm}ms ease`,Ge.style.opacity=ie?"1":"0",Ge.style.transform=`translateX(${vt}px)`),rt&&(rt.style.transition=`opacity ${Bm}ms ease`,rt.style.opacity=ie?"1":"0"),Bm;Ge&&(Ge.style.transition="none",Ge.style.opacity="1"),rt&&(rt.style.transition="none");const ir=Math.abs(ge?.velocity??0)>ZP,{frames:Mt,durationMs:Xt,solver:Bt}=GP({dampingRatio:ir?Cb.dampingRatio:1,response:Cb.response},Ut,Nt,vt,Me);if(!Ge||Math.abs(Ut-vt)<.5&&Math.abs(Nt)<5)return se(vt),0;const Wt=Ge.animate(Mt.map(et=>({transform:`translateX(${et}px)`})),{duration:Xt,easing:"linear",fill:"forwards"}),xe=[Wt];return rt&&xe.push(rt.animate(Mt.map(et=>({opacity:String(Qm(Te(et),0,1))})),{duration:Xt,easing:"linear",fill:"forwards"})),B.current={solver:Bt,startTime:performance.now(),target:vt,animations:xe},Kd("spring start",{startX:Ut,startVelocity:Nt,targetX:vt,frames:Mt.length,durationMs:Xt}),Wt.onfinish=()=>{const et=B.current;!et||!et.animations.includes(Wt)||(B.current=null,se(vt),et.animations.forEach(ot=>ot.cancel()),Kd("spring finish",{targetX:vt}))},Xt},[se,Ne,Me,_e,Te,Je]),ut=b.useCallback(ie=>{_e();const ge=ie,Ge=0,rt=Re.current,vt=T.current+UP(ge),Yt=Math.abs(vt-Ge)<=Math.abs(vt-rt);Kd("decideSnap",{velocity:ge,currentX:T.current,projected:vt,shouldOpen:Yt});const Ut=at(Yt,{velocity:ge});return Yt&&!J.current?F.current=window.setTimeout(()=>{F.current=null,qe.current?.()},Ut+Ib):!Yt&&J.current&&(F.current=window.setTimeout(()=>{F.current=null,ve.current()},Ut+Ib)),Yt},[at,_e]),me=b.useCallback(ie=>{const ge=Re.current,Ge=Math.min(0,ge),rt=Math.max(0,ge),vt=Xe.current;return ie<Ge?Ge-_b(Ge-ie,vt):ie>rt?rt+_b(ie-rt,vt):ie},[]),dt=b.useCallback(ie=>{const ge=Z.current,Ge=performance.now();ge.push({t:Ge,x:ie});const rt=Ge-120;for(;ge.length>0&&ge[0].t<rt;)ge.shift()},[]),ft=b.useCallback(()=>{const ie=Z.current;if(ie.length<2)return 0;const ge=ie[ie.length-1];if(performance.now()-ge.t>60)return 0;const Ge=ie[0],rt=(ge.t-Ge.t)/1e3;return rt<.016?0:(ge.x-Ge.x)/rt},[]);b.useEffect(()=>{Ne();const ie=B.current,ge=r?0:Re.current;ie&&ie.target===ge||at(r)},[r,at,Ne]),b.useEffect(()=>{ze(),De(J.current?0:y)},[y,ze,De]),b.useEffect(()=>()=>{ye(),Ne(),Je(),ae()},[Ne,ye,ae,Je]);const Se=Sb(({active:ie,cancel:ge,first:Ge,last:rt,movement:[vt],event:Yt})=>{if(Kd("bindPanel",{active:ie,first:Ge,last:rt,mx:vt}),!Eb(Yt)){ge();return}if(Ge){if(ae(),P.current=!1,$.current=null,Z.current=[],Nb(Yt)){ge();return}const Ut=w.current,Nt=Ut?RA(Yt.target,Ut):null;if(!Nt||MA()){ge();return}const ir=jA(Nt,vt,q.current?-1:1);if(Kd("arbitrate",{owner:ir.kind,mx:vt}),ir.kind==="swiper"){V.current=DA(ir.instance),ge();return}if(ir.kind==="scroller"){const Mt=BA(ir.element);if(Mt)$.current=Mt;else{ge();return}}$.current||(P.current=!0,ze(),N.current=T.current)}if(!ie){$.current=null,P.current&&(P.current=!1,ut(ft()));return}if($.current){QA($.current,vt);return}if(P.current){const Ut=me(N.current+vt);dt(Ut),De(Ut)}},{axis:"x",axisThreshold:Lb,filterTaps:!0,pointer:{touch:!0}}),We=Sb(({active:ie,cancel:ge,first:Ge,movement:[rt],event:vt})=>{if(!Eb(vt)){ge();return}if(J.current){ge();return}if(Ge&&(ee.current=!0,Z.current=[],ze(),N.current=T.current),!ie){ee.current&&(ee.current=!1,ut(ft())&&qP());return}if(ee.current){const Yt=me(N.current+rt);dt(Yt),De(Yt)}},{axis:"x",axisThreshold:Lb,filterTaps:!0,pointer:{touch:!0}}),Le=b.useCallback(ie=>{ie.preventDefault(),ie.stopPropagation(),J.current||qe.current?.()},[]);if(d)return s.jsx("aside",{ref:ce,"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 z=Se();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:Le,"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",{...z,onClickCapture:ie=>{Nb(ie)||z.onClickCapture?.(ie)},ref:ce,"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(${de.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})]})}),XP={activeKey:"root",items:[]},JP=()=>()=>{},eO=()=>XP;function tO(e){const t=Vo(),r=b.useSyncExternalStore(t?.subscribe??JP,t?.snapshot??eO),n=q8(),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 rO({groups:e,currentKey:t,onClose:r}){const{t:n}=Hr(),a=b.useId(),c=b.useRef(null),l=b.useRef(null),d=b.useRef(r);d.current=r;const f=b.useRef(!0),[m,x]=b.useState(""),y=e.reduce((T,S)=>T+S.reviewCount,0);b.useEffect(()=>{const T=document.activeElement;l.current?.focus({preventScroll:!0});const S=I=>{if(I.key==="Escape"&&(I.preventDefault(),I.stopImmediatePropagation(),d.current()),I.key!=="Tab")return;const N=Array.from(c.current?.querySelectorAll("button:not(:disabled)")??[]),B=N[0],F=N[N.length-1],P=!c.current?.contains(document.activeElement);I.shiftKey&&(document.activeElement===B||P)?(I.preventDefault(),F?.focus()):!I.shiftKey&&(document.activeElement===F||P)&&(I.preventDefault(),B?.focus())};return document.addEventListener("keydown",S,!0),()=>{document.removeEventListener("keydown",S,!0),f.current&&T?.isConnected&&!T.closest("[inert]")&&T.focus({preventScroll:!0})}},[]);const w=(T,S)=>{const I=Vo(),N=I?.snapshot().items.find(F=>F.key===T.key);if(!N?.reviewCount||S&&!N.attentionSessions?.some(F=>F.id===S)){x(n("serviceAttention.changed"));return}f.current=!1;let B=!1;S&&T.key===t?(window.dispatchEvent(new CustomEvent("termdock:focus-session",{detail:S})),B=!0):S&&N.service?.targetPeerId?B=I?.focusSession(N.service.targetPeerId,S)??!1:N.service&&(B=I?.activate(N.service,!0)??!1),B?r():(f.current=!0,x(n("serviceAttention.unavailable")))},v=T=>T.phase==="offline"?n("serviceAttention.offline"):T.phase==="login"?n("serviceAttention.login"):T.phase==="connecting"||T.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:T=>T.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(xc,{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(Mn,{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(T=>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:T.service?.label,children:T.service?.label||n("serviceAttention.currentService")}),T.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:T.reviewCount})]}),v(T)&&s.jsx("p",{className:"px-3 pb-1 text-xs text-[color:var(--warning)]",children:v(T)}),T.attentionSessions?.length?T.attentionSessions.map(S=>s.jsxs("button",{type:"button",onClick:()=>w(T,S.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:S.label,children:S.label}),s.jsx("span",{className:"mt-0.5 block text-xs text-muted-foreground",children:S.waiting?n("serviceAttention.waiting"):n("agent.needsReview")})]}),s.jsx(Ys,{size:16,className:"shrink-0 text-muted-foreground","aria-hidden":"true"})]},S.id)):s.jsx("button",{type:"button",onClick:()=>w(T),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")})]},T.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 nO(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 sO(e){return e.agentStatus==="waiting"||e.agentNeedsReview===!0}function iO(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,f=e[d];if(f&&r(f))return f.sessionId}return null}function aO(e,t,r="next"){return iO(e,t,sO,r)}const Ka=42,Zf=20,oO=10;function H1(e,t,r){return Math.min(r,Math.max(t,e))}function bp(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+Zf,d=Math.max(l,e.width-r-Zf-Ka),f=Math.max(t+12,52),m=Math.max(f,e.height-n-c-Ka);return{minX:l,maxX:d,minY:f,maxY:m}}function Rb(e,t){const r=bp(e),n=H1(t.yRatio,0,1);return{x:t.side==="left"?r.minX:r.maxX,y:r.minY+(r.maxY-r.minY)*n}}function Xc(e,t){const r=bp(e);return{x:H1(t.x,r.minX,r.maxX),y:H1(t.y,r.minY,r.maxY)}}function Mb(e,t){const r=bp(e),n=Xc(e,t),a=(r.minX+r.maxX+Ka)/2,c=n.x+Ka/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 jb(e,t,r){const n=Xc(e,t),a=Ka+oO,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=>Xc(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=bp(e);return[{...n,x:d.minX},{...n,x:d.maxX}].map(m=>Xc(e,m)).filter(m=>!c(m)).sort((m,x)=>Math.abs(m.x-n.x)-Math.abs(x.x-n.x))[0]??n}const Pm="var(--warning)",lO="var(--success)",Db="var(--tmux)",Bb="termdock:mobile-attention-position:v1",Qb="termdock:running-session-position:v1",cO={side:"right",yRatio:.68},uO={side:"right",yRatio:.54};function Pb(e,t){if(typeof window>"u")return t;try{const r=JSON.parse(window.localStorage.getItem(e)??"null");if(r&&(r.side==="left"||r.side==="right")&&typeof r.yRatio=="number"&&Number.isFinite(r.yRatio))return{side:r.side,yRatio:Math.min(1,Math.max(0,r.yRatio))}}catch{}return t}function dO(e,t){try{window.localStorage.setItem(e,JSON.stringify(t))}catch{}}function Oh(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 hO(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(Oh("--safe-top-inset"),(d?Math.max(0,l.top):0)+Math.max(0,r.top??0)),safeRight:Math.max(Oh("--safe-right-inset"),(d?Math.max(0,a-l.right):0)+Math.max(0,r.right??0)),safeBottom:Math.max(Oh("--safe-bottom-inset"),(d?Math.max(0,c-l.bottom):0)+Math.max(0,r.bottom??0)),safeLeft:Math.max(Oh("--safe-left-inset"),(d?Math.max(0,l.left):0)+Math.max(0,r.left??0)),bottomClearance:e?Zf:72}}function a4(){const e=Vr.getState(),t=Array.from(e.sessions.values()),r=aO(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 Ob(e){window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:e}))}function o4(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 fO({indicator:e,tone:t,size:r}){const n=o4(t);switch(e){case"spinner":return s.jsx(jn,{size:r,className:"shrink-0 animate-spin",style:{color:n}});case"question":return s.jsx(Tf,{size:r,className:"shrink-0 animate-bounce-y",style:{color:n}});case"badge":return s.jsx(xc,{size:r+1,className:"shrink-0 animate-pulse",style:{color:n}});case"terminal":return s.jsx(Zo,{size:r,className:"shrink-0",style:{color:n}});case"pulse":return s.jsx(cT,{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 Jc({agent:e,size:t=12}){const r=t-4,n=nO(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(G0,{size:r,className:"text-white"})})}function pO({sessionMode:e,state:t,size:r=11}){const n=t?.agent?s.jsx(Jc,{agent:t.agent,size:r+1}):e==="tmux"?s.jsx(ru,{size:r,className:"shrink-0"}):s.jsx(Zo,{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(fO,{indicator:t.agentIndicator,tone:t.agentStatusDetail.tone,size:r})}):t?.agentStatus==="working"?s.jsx("span",{title:t.agentMessage??t.agent?.displayName,children:s.jsx(jn,{size:r,className:"shrink-0 animate-spin",style:{color:lO}})}):t?.agentStatus==="waiting"?s.jsx("span",{title:t.agentMessage??void 0,children:s.jsx(Tf,{size:r,className:"shrink-0 animate-bounce-y",style:{color:Pm}})}):t?.agentStatus==="done"&&t.agentNeedsReview?s.jsx("span",{title:t.agentMessage??void 0,children:s.jsx(xc,{size:r+1,className:"shrink-0 animate-pulse",style:{color:Pm}})}):t?.agentNeedsReview?s.jsx("span",{title:t.agentMessage??void 0,children:s.jsx(xc,{size:r+1,className:"shrink-0 animate-pulse",style:{color:Pm}})}):t?.inCopyMode?e==="tmux"?s.jsx(ru,{size:r,className:"shrink-0 animate-pulse",style:{color:Db}}):s.jsx(Zo,{size:r,className:"shrink-0 animate-pulse",style:{color:Db}}):n}function mO({status:e,detail:t,needsReview:r,inCopyMode:n}){const{t:a}=Hr();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:o4(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 l4({count:e,tone:t,title:r}){const{t:n}=Hr();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:a4,children:[s.jsx(xc,{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 gO({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 xO=380,Fb=10,Fh=10,Om=52,bO=104;function yO(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=Zf,f=e.x+Ka/2>=n+(a-n)/2,m=f?e.x-Fh-n-d:a-d-e.x-Ka-Fh,x=Math.max(1,Math.min(Math.max(0,m),Math.max(168,r*bO))),y=f?e.x-Fh-x:e.x+Ka+Fh,w=Math.min(Math.max(y,n+d),Math.max(n+d,a-d-x)),v=e.y+Ka/2-Om/2,T=Math.min(Math.max(v,c+d),Math.max(c+d,l-d-Om));return{left:w,top:T,width:x,height:Om,itemWidth:x/Math.max(1,r),side:f?"left":"right"}}function $b(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 vO(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 wO({reviewCount:e,runningSessions:t,activeSessionId:r,runningButtonEnabled:n,attentionButtonEnabled:a=!0,isDesktopLayout:c,containerElement:l,occlusionInsets:d}){const{t:f}=Hr(),m=Vt(Se=>Se.leftOpen),x=Vt(Se=>Se.rightOpen),{isOpen:y}=kv({enabled:!c}),w=c||!m&&!x&&!y,v=tO(e),[T,S]=_.useState(!1);_.useEffect(()=>{(!v.active||!w)&&S(!1)},[v.active,w]);const I=a&&v.total>0&&w,N=t.length>1||t.length===1&&t[0]?.id!==r,B=n&&t.length>0&&N&&w,F=Math.max(0,d?.top??0),P=Math.max(0,d?.right??0),$=Math.max(0,d?.bottom??0),ee=Math.max(0,d?.left??0),Z=_.useCallback(()=>hO(c,l,{top:F,right:P,bottom:$,left:ee}),[l,c,$,ee,P,F]),V=_.useRef({attention:Pb(Bb,cO),running:Pb(Qb,uO)}),de=_.useCallback(()=>{const Se=Z(),We=Rb(Se,V.current.attention),Le=Rb(Se,V.current.running);return{attention:We,running:I&&B?jb(Se,Le,We):Le}},[I,Z,B]),[pe,J]=_.useState(()=>de()),Re=_.useRef(pe);Re.current=pe;const[Xe,q]=_.useState(null),ve=_.useRef(null),[qe,ce]=_.useState("idle"),[ye,Te]=_.useState(null),Fe=_.useRef(null),se=_.useRef({attention:!1,running:!1});_.useEffect(()=>()=>{const Se=Fe.current?.longPressTimer;Se!=null&&window.clearTimeout(Se)},[]),_.useEffect(()=>{if(B)return;const Se=Fe.current?.longPressTimer;Se!=null&&window.clearTimeout(Se),Fe.current=null,ce("idle"),Te(null)},[B]),_.useLayoutEffect(()=>{const Se=()=>{const Le=de();Re.current=Le,J(Le)};Se(),window.addEventListener("resize",Se),window.addEventListener("orientationchange",Se),window.visualViewport?.addEventListener("resize",Se);const We=typeof ResizeObserver>"u"?null:new ResizeObserver(Se);return l&&We?.observe(l),()=>{window.removeEventListener("resize",Se),window.removeEventListener("orientationchange",Se),window.visualViewport?.removeEventListener("resize",Se),We?.disconnect()}},[l,de]);const De=_.useCallback(Se=>Se==="attention"?B:I,[I,B]),_e=_.useCallback((Se,We)=>{if(!De(Se))return We;const Le=Se==="attention"?"running":"attention";return jb(Z(),We,Re.current[Le])},[Z,De]),Me=_.useCallback((Se,We,Le,z)=>{const ie=Z(),ge=We.moved?Xc(ie,{x:We.startX+(Le-We.originX),y:We.startY+(z-We.originY)}):Re.current[Se],Ge=Mb(ie,ge),rt=_e(Se,Ge.position),vt=Mb(ie,rt);V.current[Se]=vt.preference,dO(Se==="attention"?Bb:Qb,vt.preference);const Yt={...Re.current,[Se]:vt.position};Re.current=Yt,J(Yt)},[_e,Z]),Je=_.useCallback(Se=>{se.current[Se]=!0,window.setTimeout(()=>{se.current[Se]=!1},0)},[]),Ne=_.useCallback(Se=>{const We=ve.current;!We||We.kind!=="attention"||We.pointerId!==Se.pointerId||(ve.current=null,q(null),Me("attention",We,Se.clientX,Se.clientY),We.moved&&Je("attention"))},[Me,Je]),ae={onPointerDown:Se=>{Se.stopPropagation(),Se.currentTarget.setPointerCapture(Se.pointerId),ve.current={kind:"attention",pointerId:Se.pointerId,originX:Se.clientX,originY:Se.clientY,startX:pe.attention.x,startY:pe.attention.y,moved:!1}},onPointerMove:Se=>{const We=ve.current;if(!We||We.kind!=="attention"||We.pointerId!==Se.pointerId)return;const Le=Se.clientX-We.originX,z=Se.clientY-We.originY;if(!We.moved&&Math.hypot(Le,z)<5)return;We.moved=!0,q("attention");const ie=Z(),ge=_e("attention",Xc(ie,{x:We.startX+Le,y:We.startY+z})),Ge={...Re.current,attention:ge};Re.current=Ge,J(Ge)},onPointerUp:Ne,onPointerCancel:Ne},ze=l?yO(pe.running,Z(),t.length):null,at=Se=>{Se.longPressTimer!==null&&(window.clearTimeout(Se.longPressTimer),Se.longPressTimer=null)},ut={onPointerDown:Se=>{Se.stopPropagation(),Se.currentTarget.setPointerCapture(Se.pointerId);const We=Se.pointerId,Le={pointerId:We,originX:Se.clientX,originY:Se.clientY,startX:pe.running.x,startY:pe.running.y,mode:"pressing",moved:!1,selectedIndex:null,longPressTimer:null};Le.longPressTimer=window.setTimeout(()=>{const z=Fe.current;!z||z.pointerId!==We||z.mode!=="pressing"||(z.longPressTimer=null,z.mode="dragging",se.current.running=!0,ce("dragging"))},xO),Fe.current=Le,ce("pressing"),Te(null)},onPointerMove:Se=>{const We=Fe.current;if(!We||We.pointerId!==Se.pointerId)return;const Le=Se.clientX-We.originX,z=Se.clientY-We.originY;if(We.mode==="pressing")if(Math.abs(Le)>=Fb&&Math.abs(Le)>=Math.abs(z))at(We),We.mode="selecting",se.current.running=!0,ce("selecting");else if(Math.hypot(Le,z)>=Fb){at(We),We.mode="cancelled",se.current.running=!0,ce("idle");return}else return;if(We.mode==="selecting"){const rt=ze?$b(ze,Se.clientX,Se.clientY,t.length):null;We.selectedIndex=rt,Te(rt);return}if(We.mode!=="dragging"||!We.moved&&Math.hypot(Le,z)<5)return;We.moved=!0;const ie=Z(),ge=_e("running",Xc(ie,{x:We.startX+Le,y:We.startY+z})),Ge={...Re.current,running:ge};Re.current=Ge,J(Ge)},onPointerUp:Se=>{const We=Fe.current;if(!We||We.pointerId!==Se.pointerId)return;at(We);const Le=We.mode;if(Le==="selecting"){const z=ze?$b(ze,Se.clientX,Se.clientY,t.length):We.selectedIndex,ie=z===null?null:t[z]?.id;ie&&Ob(ie)}else Le==="dragging"&&Me("running",We,Se.clientX,Se.clientY);Fe.current=null,ce("idle"),Te(null),Le!=="pressing"&&Je("running")},onPointerCancel:Se=>{const We=Fe.current;!We||We.pointerId!==Se.pointerId||(at(We),Fe.current=null,ce("idle"),Te(null),Je("running"))}},me=(Se,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:Se>9?"9+":Se}),dt=()=>{const Se=v.hasOtherAttention?f("serviceAttention.title"):f("agent.jumpToNext"),We=pe.attention,Le=Xe==="attention";return s.jsxs("button",{type:"button","data-attention-button":!0,"data-mobile-attention-button":!0,...ae,onClick:z=>{z.stopPropagation(),!se.current.attention&&(v.hasOtherAttention?S(!0):a4())},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 ${Le?"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:T?"none":void 0,left:We.x,top:We.y,width:Ka,height:Ka,touchAction:"none"},"aria-label":`${Se}: ${v.total}`,"aria-haspopup":v.hasOtherAttention?"dialog":void 0,title:Se,children:[s.jsx(xc,{size:17,className:"shrink-0"}),me(v.total,"attention")]},"attention")},ft=()=>{const Se=t.length,We=pe.running,Le=qe==="selecting",z=qe==="dragging";return s.jsxs(_.Fragment,{children:[s.jsxs("button",{type:"button","data-running-session-button":!0,"data-running-session-gesture":qe,...ut,onClick:ie=>{if(ie.stopPropagation(),se.current.running)return;const ge=vO(t,r);ge&&Ob(ge)},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 ${z?"cursor-grabbing scale-[1.04] shadow-[0_12px_30px_var(--app-shadow-strong)]":Le?"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:Ka,height:Ka,touchAction:"none"},"aria-label":`${f("agent.jumpToNextRunning")}: ${Se}`,title:f("agent.runningSessionGestureHint"),children:[s.jsx(jn,{size:18,className:"shrink-0 animate-spin"}),me(Se,"running")]}),Le&&ze&&s.jsx("div",{role:"listbox","data-running-session-rail":!0,"data-side":ze.side,"aria-label":f("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:ze.left,top:ze.top,width:ze.width,height:ze.height},children:t.map((ie,ge)=>{const Ge=ge===ye,rt=ie.id===r,vt=`${ie.label}${ie.detail?` · ${ie.detail}`:""}${rt?` · ${f("agent.currentSession")}`:""}`;return s.jsxs("div",{role:"option","aria-selected":Ge,"data-running-session-option":ie.id,"data-selected":Ge?"true":"false",title:vt,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 ${Ge?"scale-[1.02] bg-[var(--success)] text-[color:var(--success-foreground)]":rt?"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 ${Ge?"bg-surface/25":"bg-surface-2 text-muted-foreground"}`,children:ge+1}),s.jsx("span",{className:"truncate text-[10px] font-medium",children:ie.label})]},ie.id)})})]},"running")};return!I&&!B&&!T||l===null||typeof document>"u"?null:s.jsxs(Y8,{children:[I&&dt(),B&&!T&&ft(),T&&v.active&&w&&s.jsx(rO,{groups:v.groups,currentKey:v.currentKey,onClose:()=>S(!1)})]})}function AO(){const{t:e}=Hr();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 TO=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"]),Ub=120,zb=120,SO=new Set,CO=[],_O={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 Yg(e,t){if(t==="directory")return null;if(X8(e))return s.jsx(JA,{size:14});if(J8(e))return s.jsx(g3,{size:14});const r=e.lastIndexOf(".")>=0?e.slice(e.lastIndexOf(".")):"";return TO.has(r)?s.jsx(_T,{size:14}):s.jsx(o3,{size:14})}function c4({path:e}){const r=Vt(a=>a.changedFiles.get(e))?.status;if(!r)return null;const n=_O[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 ld(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 Zg(e){return ld(e)}const kO=b.memo(function({path:t}){const{t:r}=Hr(),[n,a]=b.useState("idle"),[c,l]=b.useState(null),d=b.useCallback(async f=>{if(f.stopPropagation(),n!=="pending"){a("pending"),l(null);try{await Zy(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:f=>{d(f)},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 ${ld(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(jn,{size:12,className:"animate-spin"}):s.jsx(E0,{size:12})})});function u4(){const{t:e}=Hr(),[t,r]=b.useState({status:"idle"}),n=b.useCallback(async a=>{r({status:"pending"});try{await Zy(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 W1(e){return e instanceof DOMException&&e.name==="AbortError"}function Kf(){if(typeof window>"u")return!1;const e=window.getSelection();return!!(e&&!e.isCollapsed&&e.toString().trim())}function d4(e){return e.button===2||e.ctrlKey}const LO=176,IO=160,Xd=8;function Hb(e,t,r,n){const a=window.visualViewport,c=a?.offsetLeft??0,l=a?.offsetTop??0,d=c+(a?.width??window.innerWidth),f=l+(a?.height??window.innerHeight),m=c+Xd,x=l+Xd,y=Math.max(m,d-r-Xd),w=Math.max(x,f-n-Xd),v=t+n<=f-Xd?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 h4(e){const[t,r]=b.useState(null),n=b.useRef(null),a=b.useCallback((c,l)=>{r(Hb(c,l,LO,IO))},[]);return b.useLayoutEffect(()=>{if(!e||!t||!n.current)return;const c=n.current.getBoundingClientRect();if(c.width<=0||c.height<=0)return;const l=Hb(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 f4(e,t){return t&&typeof document<"u"?Ks.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 G1(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 V1(e,t){return!e||!t.startsWith(e)?t:t.slice(e.length).replace(/^\/+/,"")||t}const NO=b.memo(function e({node:t,depth:r,onFileSelect:n,directoriesOnly:a=!1,onPathReference:c,referenceSelection:l,getReferenceText:d,onReferenceCopied:f,insertedReferenceKey:m,copiedReferenceKey:x,onDirectoryRoot:y,onSearchFromDirectory:w,onDirectoryPinToggle:v,onFilePinToggle:T,onOpenInFileBrowser:S,canOpenInFileBrowser:I,pinnedPaths:N,selectedFilePath:B,queryLower:F,onDirectoryDropFiles:P,onFileDeleteRequest:$,deletingFilePath:ee,revealedDirectoryPath:Z,gitIgnoreRoot:V}){const{t:de}=Hr(),pe=Vt(ct=>ct.expandedPaths.has(t.path)),J=Vt(ct=>ct.directoryCache.get(t.path)),Re=Vt(ct=>ct.showHiddenFiles),Xe=Vt(ct=>ct.toggleExpanded),q=Vt(ct=>ct.setDirectoryCache),ve=Vt(ct=>ct.fileSortModes[t.path]??"name"),qe=Vt(ct=>ct.setDirectorySortMode),[ce,ye]=b.useState(!1),[Te,Fe]=b.useState(!1),{position:se,menuRef:De,openAt:_e,clearPosition:Me}=h4(Te),[Je,Ne]=b.useState(!1),ae=b.useRef(0),ze=b.useRef(null),at=`file-tree-reference:${b.useId()}:${t.path}`;eu(De,Te&&!!l,()=>Fe(!1));const ut=b.useRef(null),me=t.path===B||t.path===Z,dt=t.type==="directory"&&(pe||!!F),ft=t.type==="directory",Se=N.has(t.path),We=!ft&&!!T,Le=!!(I&&S),z=`path:${t.path}`,ie=m===z||!!l?.paths.has(t.path),ge=x===z,Ge=d?.(t.path)??t.path,rt=ig(f,!!l),{state:vt,run:Yt}=u4(),Ut=ee===t.path,Nt=ft&&!a&&!!(y||w||v||Le),ir=b.useMemo(()=>{if(!J)return;if(!F)return J;const ct=Vt.getState().directoryCache;return J.filter(Ct=>(!a||Ct.type==="directory")&&Kg(Ct,F,ct))},[J,a,F]),Mt=b.useCallback(async()=>{if(!Vt.getState().directoryCache.has(t.path)&&!ce){const Ct=l?at:`file-tree:${t.path}`;ze.current?.abort(),i1(Ct);const or=new AbortController;ze.current=or,ye(!0);try{const Cr=await tg(t.path,or.signal,Re,"expand_directory",Ct,ve,V);if(or.signal.aborted)return;const Ir=G1(Cr.entries);q(t.path,Ir)}catch(Cr){W1(Cr)}finally{ze.current===or&&(ze.current=null),ye(!1)}}},[t.path,ce,q,Re,ve,V,!!l,at]),Xt=b.useCallback(async()=>{if(t.type!=="directory"){n(t.path);return}if(a&&y){y(t.path);return}const ct=!Vt.getState().expandedPaths.has(t.path);Xe(t.path),ct&&await Mt()},[a,t.path,t.type,Mt,y,Xe,n]);b.useEffect(()=>{t.type==="directory"&&pe&&!J&&!ce&&Mt()},[J,pe,Mt,ce,t.type]);const Bt=b.useCallback(ct=>{ct.stopPropagation(),c?.(t.path,z)},[c,t.path,z]),Wt=b.useCallback(ct=>{ct.stopPropagation(),y?.(t.path),Fe(!1)},[t.path,y]),xe=b.useCallback(ct=>{ct.stopPropagation(),w?.(t.path),Fe(!1)},[t.path,w]),et=b.useCallback(ct=>{ct.stopPropagation(),v?.(t.path),Fe(!1)},[t.path,v]),ot=b.useCallback(ct=>{ct.stopPropagation(),qe(t.path,ve==="modified"?"name":"modified"),Fe(!1)},[t.path,qe,ve]),Et=b.useCallback(ct=>{ct.stopPropagation(),T?.(t.path),Fe(!1)},[t.path,T]),K=b.useCallback(ct=>{ct.stopPropagation(),Fe(!1),Yt(t.path)},[t.path,Yt]),xt=b.useCallback(ct=>{ct.stopPropagation(),Fe(!1),$(t)},[t,$]),rr=b.useCallback(ct=>{ct.stopPropagation(),S?.(t.path),Fe(!1)},[t.path,S]),$e=b.useCallback(ct=>{!ft||!P||!ct.dataTransfer.types.includes("Files")||(ct.preventDefault(),ct.stopPropagation(),ae.current+=1,Ne(!0))},[ft,P]),Dr=b.useCallback(ct=>{!ft||!P||!ct.dataTransfer.types.includes("Files")||(ct.preventDefault(),ct.stopPropagation(),ct.dataTransfer.dropEffect="copy",Ne(!0))},[ft,P]),Ce=b.useCallback(ct=>{!ft||!P||(ct.preventDefault(),ct.stopPropagation(),ae.current-=1,ae.current<=0&&(ae.current=0,Ne(!1)))},[ft,P]),St=b.useCallback(ct=>{if(!ft||!P)return;ct.preventDefault(),ct.stopPropagation(),ae.current=0,Ne(!1);const Ct=Array.from(ct.dataTransfer.files);Ct.length>0&&P(t.path,Ct)},[ft,t.path,P]),Ot=b.useCallback(ct=>{ct.stopPropagation(),l?_e(ct.clientX,ct.clientY):Me(),Fe(Ct=>!Ct)},[Me,_e,!!l]),tr=b.useCallback(ct=>{!Nt||!d4(ct)||(ct.preventDefault(),ct.stopPropagation(),_e(ct.clientX,ct.clientY),Fe(!0))},[Nt,_e]);return b.useEffect(()=>{if(!Te)return;const ct=or=>{const Cr=or.target;Cr instanceof Node&&(ut.current?.contains(Cr)||De.current?.contains(Cr))||Fe(!1)},Ct=or=>{or.key==="Escape"&&Fe(!1)};return document.addEventListener("pointerdown",ct),document.addEventListener("keydown",Ct),()=>{document.removeEventListener("pointerdown",ct),document.removeEventListener("keydown",Ct)}},[Te,De]),b.useEffect(()=>()=>{ze.current?.abort()},[]),s.jsxs("div",{style:!dt&&!Te?{contentVisibility:"auto",containIntrinsicSize:"auto 32px"}:void 0,children:[s.jsxs("div",{ref:ut,className:"relative",children:[rt.popoverNode,s.jsxs("div",{"data-file-tree-path":t.path,"data-sort-mode":ve,role:"button",tabIndex:0,onClick:()=>{Kf()||Xt()},onContextMenu:tr,onKeyDown:ct=>{ct.target!==ct.currentTarget||ct.key!=="Enter"&&ct.key!==" "||(ct.preventDefault(),Xt())},onDragEnter:$e,onDragOver:Dr,onDragLeave:Ce,onDrop:St,className:`group relative flex w-full cursor-pointer items-center gap-1 rounded px-2 py-1 text-[13px] transition ${Je?"scale-[1.015] bg-primary/15 text-foreground shadow-[0_0_0_1px_rgb(var(--primary-rgb)_/_0.45)]":me?"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`}}),Je&&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:de("fileTree.dropToUploadHere")}),t.type==="directory"?s.jsxs(s.Fragment,{children:[dt?s.jsx(Al,{size:14,className:"shrink-0 text-muted-foreground/80"}):s.jsx(Ys,{size:14,className:"shrink-0 text-muted-foreground/80"}),dt?s.jsx(Yu,{size:14,className:"shrink-0 text-[color:var(--folder)]"}):s.jsx(tu,{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:me?"text-primary":"text-muted-foreground/80",children:Yg(t.name,t.type)})]}),s.jsxs("span",{className:`flex-1 select-text whitespace-nowrap text-left leading-snug ${me?"font-medium":""}`,children:[t.name,ve==="modified"&&s.jsx("span",{className:"ml-1 inline-flex align-middle text-primary",title:de("fileTree.sortedByModified"),"aria-label":de("fileTree.sortedByModified"),children:s.jsx(I0,{size:11})}),t.isSymlink&&s.jsx("span",{className:"ml-1 inline-flex align-middle text-muted-foreground/70",title:de("fileTree.symbolicLink"),children:s.jsx(rd,{size:11})})]}),s.jsxs("div",{className:`sticky right-0 z-20 flex shrink-0 items-center rounded pl-1 ${me?"bg-surface-elevated":"bg-surface group-hover:bg-surface-2"}`,onClick:ct=>ct.stopPropagation(),children:[ce&&s.jsx(jn,{size:12,className:"shrink-0 animate-spin text-muted-foreground"}),s.jsx(c4,{path:t.path}),Nt&&s.jsx("button",{type:"button",onClick:Ot,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 ${ld(Te)} ${Te?"bg-surface-elevated text-foreground":"bg-surface-2 hover:bg-surface-elevated hover:text-foreground"}`,"aria-label":de("fileTree.moreDirActions"),"aria-expanded":Te,title:de("fileTree.moreDirActions"),children:s.jsx(Io,{size:13})}),!ft&&!l&&s.jsx("button",{type:"button",onClick:Ot,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 ${ld(Te||vt.status==="pending"||Ut||Se)} ${Te?"bg-surface-elevated text-foreground":Se?"bg-primary/15 text-primary":"bg-surface-2 hover:bg-surface-elevated hover:text-foreground"}`,"aria-label":de("fileTree.moreFileActions"),"aria-expanded":Te,title:vt.status==="error"?vt.message??de("rightSidebar.downloadFailed"):de("fileTree.moreFileActions"),children:vt.status==="pending"||Ut?s.jsx(jn,{size:13,className:"animate-spin"}):s.jsx(Io,{size:13})}),c&&s.jsx("button",{type:"button",onClick:Bt,...rt(Ge,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 ${l?"ml-1 min-h-11 min-w-11":Zg(ie||ge)} ${ie||ge?"bg-surface-elevated text-foreground":"bg-primary/10 text-primary"}`,"aria-label":l?`${l.label}: ${t.name}`:de(ge?"rightSidebar.copied":ie?"rightSidebar.inserted":"fileTree.insertRefTitle"),"aria-pressed":l?ie:void 0,disabled:!!l?.disabled&&!ie,title:l?`${l.label}: ${t.name}`:de(ge?"rightSidebar.copied":ie?"rightSidebar.inserted":"fileTree.insertRefTitle"),children:ge||ie?s.jsx(ai,{size:12}):s.jsx(rd,{size:12})}),Nt&&Te&&f4(s.jsxs("div",{ref:De,className:`${se?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:se?{left:se.left,top:se.top}:void 0,children:[Le&&s.jsxs("button",{type:"button",onClick:rr,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:de("fileTree.openInFileBrowserTitle"),children:[s.jsx(Yu,{size:13,className:"shrink-0 text-[color:var(--folder)]"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:de("fileTree.openInFileBrowser")})]}),y&&s.jsxs("button",{type:"button",onClick:Wt,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:de("fileTree.openDirRootTitle"),children:[s.jsx(Yu,{size:13,className:"shrink-0 text-[color:var(--folder)]"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:de("fileTree.openDirRoot")})]}),w&&s.jsxs("button",{type:"button",onClick:xe,className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left font-medium text-foreground transition hover:bg-surface-2 active:scale-[0.99]",title:de("fileTree.searchFromDirTitle"),children:[s.jsx(ag,{size:13,className:"shrink-0 text-primary"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:de("fileTree.searchFromDir")})]}),v&&s.jsxs("button",{type:"button",onClick:et,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] ${Se?"text-primary hover:bg-primary/10":"text-foreground hover:bg-surface-2"}`,title:de(Se?"fileTree.unpinDirTitle":"fileTree.pinDirTitle"),children:[Se?s.jsx(R0,{size:13,className:"shrink-0"}):s.jsx(N0,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:de(Se?"fileTree.unpinDir":"fileTree.pinDir")})]}),s.jsxs("button",{type:"button",onClick:ot,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:[ve==="modified"?s.jsx(GA,{size:13,className:"shrink-0"}):s.jsx(I0,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:de(ve==="modified"?"fileTree.sortByName":"fileTree.sortByModified")})]})]}),!!se),!ft&&!l&&Te&&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:[Le&&s.jsxs("button",{type:"button",onClick:rr,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:de("fileTree.openInFileBrowserTitle"),children:[s.jsx(o3,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:de("fileTree.openInFileBrowser")})]}),s.jsxs("button",{type:"button",onClick:K,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:de("rightSidebar.downloadFile"),children:[s.jsx(E0,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:de("rightSidebar.downloadFile")})]}),We&&s.jsxs("button",{type:"button",onClick:Et,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] ${Se?"text-primary hover:bg-primary/10":"text-foreground hover:bg-surface-2"}`,title:de(Se?"fileTree.unpinFileTitle":"fileTree.pinFileTitle"),children:[Se?s.jsx(R0,{size:13,className:"shrink-0"}):s.jsx(N0,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:de(Se?"fileTree.unpinFile":"fileTree.pinFile")})]}),s.jsxs("button",{type:"button",onClick:xt,disabled:Ut,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:de("fileTree.deleteFile"),children:[Ut?s.jsx(jn,{size:13,className:"shrink-0 animate-spin"}):s.jsx(Ds,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:de("fileTree.deleteFile")})]})]})]})]})]}),dt&&ir&&ir.length>0&&s.jsx("div",{className:r===0?"mt-0.5":"",children:ir.map(ct=>s.jsx(e,{node:ct,depth:r+1,onFileSelect:n,directoriesOnly:a,onPathReference:c,referenceSelection:l,getReferenceText:d,onReferenceCopied:f,onDirectoryRoot:y,onSearchFromDirectory:w,onDirectoryPinToggle:v,onFilePinToggle:T,onOpenInFileBrowser:S,canOpenInFileBrowser:I,pinnedPaths:N,selectedFilePath:B,queryLower:F,insertedReferenceKey:m,copiedReferenceKey:x,onDirectoryDropFiles:P,onFileDeleteRequest:$,deletingFilePath:ee,gitIgnoreRoot:V,revealedDirectoryPath:Z},ct.path))})]})}),RO=b.memo(function({node:t,rootPath:r,onFileSelect:n,onPathReference:a,referenceSelection:c,getReferenceText:l,onReferenceCopied:d,insertedReferenceKey:f,copiedReferenceKey:m,onDirectoryRoot:x,onSearchFromDirectory:y,onDirectoryPinToggle:w,onFilePinToggle:v,pinnedPaths:T,selectedFilePath:S,onFileDeleteRequest:I,deletingFilePath:N}){const{t:B}=Hr(),F=t.path===S,P=t.type==="directory",$=T.has(t.path),ee=!P&&!!v,Z=`path:${t.path}`,V=f===Z||!!c?.paths.has(t.path),de=m===Z,pe=l?.(t.path)??t.path,J=ig(d,!!c),{state:Re,run:Xe}=u4(),[q,ve]=b.useState(!1),{position:qe,menuRef:ce,openAt:ye,clearPosition:Te}=h4(q);eu(ce,q&&!!c,()=>ve(!1));const Fe=b.useRef(null),se=N===t.path,De=P&&!!(x||y||w),_e=b.useCallback(()=>{Kf()||(t.type==="directory"?x?.(t.path):n(t.path))},[t.path,t.type,x,n]),Me=b.useCallback(me=>{me.stopPropagation(),a?.(t.path,Z)},[a,t.path,Z]),Je=b.useCallback(me=>{me.stopPropagation(),w?.(t.path),ve(!1)},[t.path,w]),Ne=b.useCallback(me=>{me.stopPropagation(),v?.(t.path),ve(!1)},[t.path,v]),ae=b.useCallback(me=>{me.stopPropagation(),ve(!1),Xe(t.path)},[t.path,Xe]),ze=b.useCallback(me=>{me.stopPropagation(),ve(!1),I(t)},[t,I]),at=b.useCallback(me=>{me.stopPropagation(),c?ye(me.clientX,me.clientY):Te(),ve(dt=>!dt)},[Te,ye,!!c]),ut=b.useCallback(me=>{!De||!d4(me)||(me.preventDefault(),me.stopPropagation(),ye(me.clientX,me.clientY),ve(!0))},[De,ye]);return b.useEffect(()=>{if(!q)return;const me=ft=>{const Se=ft.target;Se instanceof Node&&(Fe.current?.contains(Se)||ce.current?.contains(Se))||ve(!1)},dt=ft=>{ft.key==="Escape"&&ve(!1)};return document.addEventListener("pointerdown",me),document.addEventListener("keydown",dt),()=>{document.removeEventListener("pointerdown",me),document.removeEventListener("keydown",dt)}},[q,ce]),s.jsxs("div",{ref:Fe,className:"relative border-b border-border/10 last:border-b-0",children:[J.popoverNode,s.jsxs("div",{role:"button",tabIndex:0,onClick:_e,onContextMenu:ut,onKeyDown:me=>{me.target!==me.currentTarget||me.key!=="Enter"&&me.key!==" "||(me.preventDefault(),_e())},className:`group flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-2 text-left text-[13px] transition ${F?"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(tu,{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:F?"text-primary":"text-muted-foreground/80",children:Yg(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 ${F?"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(rd,{size:11})})]}),s.jsx("span",{className:"mt-0.5 block truncate font-mono text-[10px] text-muted-foreground/80",children:V1(r,t.path)})]}),s.jsx(c4,{path:t.path}),t.type==="directory"&&(w||y)&&s.jsx("button",{type:"button",onClick:at,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 ${ld(q)} ${q?"bg-surface-elevated text-foreground":"bg-surface-2 hover:bg-surface-elevated hover:text-foreground"}`,"aria-label":B("fileTree.moreDirActions"),"aria-expanded":q,title:B("fileTree.moreDirActions"),children:s.jsx(Io,{size:13})}),!P&&!c&&s.jsx("button",{type:"button",onClick:at,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 ${ld(q||Re.status==="pending"||se||$)} ${q?"bg-surface-elevated text-foreground":$?"bg-primary/15 text-primary":"bg-surface-2 hover:bg-surface-elevated hover:text-foreground"}`,"aria-label":B("fileTree.moreFileActions"),"aria-expanded":q,title:Re.status==="error"?Re.message??B("rightSidebar.downloadFailed"):B("fileTree.moreFileActions"),children:Re.status==="pending"||se?s.jsx(jn,{size:13,className:"animate-spin"}):s.jsx(Io,{size:13})}),a&&s.jsx("button",{type:"button",onClick:Me,...J(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":Zg(V||de)} ${V||de?"bg-surface-elevated text-foreground":"bg-primary/10 text-primary"}`,"aria-label":c?`${c.label}: ${t.name}`:B(de?"rightSidebar.copied":V?"rightSidebar.inserted":"fileTree.insertRefTitle"),"aria-pressed":c?V:void 0,disabled:!!c?.disabled&&!V,title:c?`${c.label}: ${t.name}`:B(de?"rightSidebar.copied":V?"rightSidebar.inserted":"fileTree.insertRefTitle"),children:de||V?s.jsx(ai,{size:12}):s.jsx(rd,{size:12})})]}),De&&q&&f4(s.jsxs("div",{ref:ce,className:`${qe?c?"fixed z-popover":"fixed z-menu-panel":"absolute right-2 top-[calc(100%+2px)] z-30"} w-44 overflow-hidden rounded-xl border border-border/15 bg-surface/98 p-1 text-[12px] shadow-xl shadow-[0_18px_48px_var(--app-shadow-soft)] backdrop-blur animate-fade-in`,style:qe?{left:qe.left,top:qe.top}:void 0,children:[x&&s.jsxs("button",{type:"button",onClick:me=>{me.stopPropagation(),x(t.path),ve(!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(Yu,{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:me=>{me.stopPropagation(),y(t.path),ve(!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(ag,{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:Je,className:`flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left font-medium transition active:scale-[0.99] ${$?"text-primary hover:bg-primary/10":"text-foreground hover:bg-surface-2"}`,title:B($?"fileTree.unpinDirTitle":"fileTree.pinDirTitle"),children:[$?s.jsx(R0,{size:13,className:"shrink-0"}):s.jsx(N0,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:B($?"fileTree.unpinDir":"fileTree.pinDir")})]})]}),!!qe),!P&&!c&&q&&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:ae,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(E0,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:B("rightSidebar.downloadFile")})]}),ee&&s.jsxs("button",{type:"button",onClick:Ne,className:`flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left font-medium transition active:scale-[0.99] ${$?"text-primary hover:bg-primary/10":"text-foreground hover:bg-surface-2"}`,title:B($?"fileTree.unpinFileTitle":"fileTree.pinFileTitle"),children:[$?s.jsx(R0,{size:13,className:"shrink-0"}):s.jsx(N0,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:B($?"fileTree.unpinFile":"fileTree.pinFile")})]}),s.jsxs("button",{type:"button",onClick:ze,disabled:se,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:[se?s.jsx(jn,{size:13,className:"shrink-0 animate-spin"}):s.jsx(Ds,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:B("fileTree.deleteFile")})]})]})]})}),MO=60,Wb=60,jO=20;function Gb({count:e,loading:t,engine:r,limited:n,scope:a,content:c}){const{t:l}=Hr();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(ag,{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(jn,{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 DO(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 BO=b.memo(function({entry:t,rootPath:r,selectedFilePath:n,query:a,onContentMatchSelect:c,onPathReference:l,referenceSelection:d,getReferenceText:f,onReferenceCopied:m,insertedReferenceKey:x,copiedReferenceKey:y}){const{t:w}=Hr(),[v,T]=b.useState(!0),S=t.path===n,I=v?t.matches.slice(0,jO):[],N=t.matches.length-I.length,B=`path:${t.path}`,F=x===B||!!d?.paths.has(t.path),P=y===B,$=f?.(t.path)??t.path,ee=ig(m,!!d);return s.jsxs("div",{className:"border-b border-border/10 last:border-b-0",children:[ee.popoverNode,s.jsxs("div",{role:"button",tabIndex:0,onClick:()=>{Kf()||T(Z=>!Z)},onKeyDown:Z=>{Z.target!==Z.currentTarget||Z.key!=="Enter"&&Z.key!==" "||(Z.preventDefault(),T(V=>!V))},className:`group flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-2 text-left text-[13px] transition ${S?"bg-surface-elevated text-foreground":"text-muted-foreground hover:bg-surface-2 hover:text-foreground"}`,title:t.path,children:[v?s.jsx(Al,{size:14,className:"shrink-0 text-muted-foreground/80"}):s.jsx(Ys,{size:14,className:"shrink-0 text-muted-foreground/80"}),s.jsx("span",{className:S?"text-primary":"text-muted-foreground/80",children:Yg(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:V1(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(kO,{path:t.path}),l&&s.jsx("button",{type:"button",onClick:Z=>{Z.stopPropagation(),l(t.path,B)},...ee($,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":Zg(F||P)} ${F||P?"bg-surface-elevated text-foreground":"bg-primary/10 text-primary"}`,"aria-label":d?`${d.label}: ${t.name}`:w(P?"rightSidebar.copied":F?"rightSidebar.inserted":"fileTree.insertRefTitle"),"aria-pressed":d?F:void 0,disabled:!!d?.disabled&&!F,title:d?`${d.label}: ${t.name}`:w(P?"rightSidebar.copied":F?"rightSidebar.inserted":"fileTree.insertRefTitle"),children:P||F?s.jsx(ai,{size:12}):s.jsx(rd,{size:12})})]}),v&&s.jsxs("div",{className:"mb-1 ml-3 border-l border-border/20 pl-1",children:[I.map((Z,V)=>s.jsxs("div",{role:"button",tabIndex:0,onClick:()=>{Kf()||c?.(t.path,Z.line)},onKeyDown:de=>{de.target!==de.currentTarget||de.key!=="Enter"&&de.key!==" "||(de.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:`${V1(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:DO(Z.text,a)})]},`${Z.line}-${V}`)),N>0&&s.jsx("div",{className:"px-2 py-1 text-[10px] text-muted-foreground/70",children:w("fileTree.moreMatches",{count:N})})]})]})});function QO({rootPath:e,onFileSelect:t,directoriesOnly:r=!1,onPathReference:n,referenceSelection:a,getReferenceText:c,onReferenceCopied:l,insertedReferenceKey:d,copiedReferenceKey:f,onDirectoryRoot:m,onSearchFromDirectory:x,onDirectoryPinToggle:y,onFilePinToggle:w,onOpenInFileBrowser:v,canOpenInFileBrowser:T=!1,pinnedPaths:S=SO,selectedFilePath:I,query:N="",searchRootPath:B,searchOptions:F={},searchMode:P="name",onContentMatchSelect:$,onDirectoryDropFiles:ee,revealDirectory:Z}){const{t:V}=Hr(),de=b.useId(),pe=a?`file-tree-reference-root:${de}:${e}`:`file-tree-root:${e}`,J=Vt(Ce=>e?Ce.directoryCache.get(e):void 0),Re=Vt(Ce=>Ce.setDirectoryCache),Xe=Vt(Ce=>Ce.showHiddenFiles),q=Vt(Ce=>Ce.fileSortModesHydrated),ve=Vt(Ce=>Ce.fileSortModes[e]??"name"),qe=Vt(Ce=>Ce.hydrateFileSortModes),ce=Vt(Ce=>Ce.hydrateHideGitIgnoredRoots),ye=Vt(Ce=>!!Ce.hideGitIgnoredRoots[e]),Te=Vt(Ce=>Ce.hideGitIgnoredRootsHydrated),Fe=Vt(Ce=>JSON.stringify(Ce.gitIgnoreExceptions[e]??[])),se=Vt(Ce=>Ce.invalidateDirectoryCache),De=`${e}:${ye}:${Fe}`,[_e,Me]=b.useState("");b.useLayoutEffect(()=>{e&&se(e,!0),Me(De)},[e,ye,Fe,se,De]);const[Je,Ne]=b.useState(!1),[ae,ze]=b.useState(null),[at,ut]=b.useState(!1),[me,dt]=b.useState(!1),[ft,Se]=b.useState(null),[We,Le]=b.useState(q&&Te),z=q&&Te||We;b.useEffect(()=>{let Ce=!1;return Promise.all([qe(),ce()]).catch(()=>{}).finally(()=>{Ce||Le(!0)}),()=>{Ce=!0}},[qe,ce]);const[ie,ge]=b.useState([]),[Ge,rt]=b.useState(null),[vt,Yt]=b.useState(Ub),[Ut,Nt]=b.useState([]),[ir,Mt]=b.useState(null),Xt=b.useRef({busy:!1}),Bt=b.useRef(0),Wt=b.useRef(e);Wt.current=e,b.useEffect(()=>{const Ce=()=>{Bt.current++};for(const St of["pagehide","auth:unauthorized",$u])window.addEventListener(St,Ce);return()=>{Ce();for(const St of["pagehide","auth:unauthorized",$u])window.removeEventListener(St,Ce)}},[]);const xe=b.useRef(null),et=b.useRef(0),ot=N.trim().toLowerCase(),Et=P==="content",K=B||e,xt=F.excludePatterns??CO,rr=xt.join(`
|
|
137
137
|
`);b.useEffect(()=>{const Ce=Z?.path;if(!Ce||!Ce.startsWith(`${e}/`)&&Ce!==e)return;const St=Ce.slice(e.length).replace(/^\/+/,""),Ot=St?St.split("/"):[],tr=Ot.map((Tt,Ft)=>`${e}/${Ot.slice(0,Ft+1).join("/")}`),ct=Vt.getState(),Ct=tr.filter(Tt=>!ct.expandedPaths.has(Tt));Ct.length>0&&Vt.setState(Tt=>({expandedPaths:new Set([...Tt.expandedPaths,...Ct])}));let or=!1,Cr=0;const Ir=()=>{if(or)return;const Tt=Array.from(document.querySelectorAll("[data-file-tree-path]")).find(Ft=>Ft.dataset.fileTreePath===Ce);if(Tt){Tt.scrollIntoView({block:"center",behavior:"smooth"});return}Cr+=1,Cr<80&&window.setTimeout(Ir,50)},$r=window.requestAnimationFrame(Ir);return()=>{or=!0,window.cancelAnimationFrame($r)}},[Z?.nonce,Z?.path,e]);const $e=b.useCallback(async Ce=>{if(Xt.current.busy||Ce.type==="directory")return;const St=Bt.current,Ot=Ki(),tr=wl(),ct=e,Ct=Ce.path.slice(0,Ce.path.lastIndexOf("/"))||"/",or=()=>Vt.getState().directoryCache.get(Ct)?.find(wt=>wt.path===Ce.path),Cr=wt=>JSON.stringify([wt.path,wt.name,wt.type,wt.isSymlink,wt.modified]),Ir=Cr(Ce),$r=or(),Tt=$r?Cr($r):null;let Ft=!1;const we=()=>{const wt=or();return St===Bt.current&&ct===Wt.current&&Ot===Ki()&&tr===wl()&&!tr?.closed&&Cr(Ce)===Ir&&(wt?Cr(wt)===(Tt??Ir):Tt===null||Ft)};await lg(Xt.current,{current:we,confirm:()=>y3({title:V("fileTree.deleteFile"),message:V("fileTree.deleteFileConfirm",{name:Ce.name}),confirmLabel:V("fileTree.deleteFile"),cancelLabel:V("common.cancel")}),submit:async wt=>{await Z8(Ce.path,wt),Ft=!0},apply:()=>{Vt.getState().applyFileWatchEvents([{type:"deleted",path:Ce.path}]),ge(wt=>wt.filter(it=>it.path!==Ce.path)),Nt(wt=>wt.filter(it=>it.path!==Ce.path)),S.has(Ce.path)&&w?.(Ce.path)},pending:wt=>{St===Bt.current&&Mt(wt?Ce.path:null)},failure:wt=>o1(V("fileTree.deleteFileFailed",{message:wt})),expiredMessage:"File deletion context changed"})},[e,w,S,V]);b.useEffect(()=>{if(!e||!z||_e!==De)return;if(ot){Ne(!1);return}if(Vt.getState().directoryCache.has(e)){Ne(!1);return}let Ce=!1;const St=new AbortController;return Ne(!0),ze(null),tg(e,St.signal,Xe,"load_file_tree_root",pe,ve,e).then(Ot=>{if(Ce)return;const tr=G1(Ot.entries);ut(!!Ot.truncated),Re(e,tr)}).catch(Ot=>{Ce||W1(Ot)||ze(Ot instanceof Error?Ot.message:"Failed to load directory")}).finally(()=>{Ce||Ne(!1)}),()=>{Ce=!0,St.abort(),i1(pe)}},[ot,J,e,ve,Re,Xe,z,ye,Fe,pe,_e,De]),b.useEffect(()=>{if(!K||!ot){dt(!1),Se(null),ge([]),Nt([]),rt(null);return}let Ce=!1;const St=new AbortController,Ot=new Set;dt(!0),Se(null),ge([]),Nt([]),Yt(Et?MO:Ub),rt({truncated:!1,total:0,engine:"rg",limited:!1,done:!1});const tr=`file-search:${a?de+":":""}${K}:${++et.current}`;return K8(K,N.trim(),ct=>{if(!Ce){if(ct.engine&&rt(Ct=>({truncated:Ct?.truncated??!1,total:Ct?.total??0,engine:ct.engine,limited:ct.limited??Ct?.limited??!1,done:Ct?.done??!1})),ct.entries?.length){const Ct=ct.entries.filter(or=>Ot.has(or.path)?!1:(Ot.add(or.path),!0));Ct.length>0&&(ge(or=>[...or,...G1(Ct)]),rt(or=>or?{...or,total:Ot.size}:{truncated:!1,total:Ot.size,engine:"rg",limited:!1,done:!1}))}if(ct.contentEntries?.length){const Ct=ct.contentEntries.filter(or=>Ot.has(or.path)?!1:(Ot.add(or.path),!0));Ct.length>0&&(Nt(or=>[...or,...Ct]),rt(or=>or?{...or,total:Ot.size}:{truncated:!1,total:Ot.size,engine:"rg",limited:!1,done:!1}))}ct.done&&rt(Ct=>({truncated:!!ct.truncated,total:typeof ct.total=="number"?ct.total:Ot.size,engine:ct.engine??Ct?.engine??"rg",limited:!!ct.limited,done:!0}))}},St.signal,Xe,P,tr,{excludePatterns:xt,caseSensitive:F.caseSensitive,wholeWord:F.wholeWord,regex:F.regex}).catch(ct=>{Ce||W1(ct)||(Se(ct instanceof Error?ct.message:"Failed to search files"),ge([]),Nt([]),rt(null))}).finally(()=>{Ce||dt(!1)}),()=>{Ce=!0,St.abort(),i1(tr)}},[K,rr,Et,N,ot,P,F.caseSensitive,F.regex,F.wholeWord,Xe,!!a,de]),b.useEffect(()=>{if(!ot)return;const Ce=xe.current;if(!Ce)return;const St=Et?Ut.length:ie.length,Ot=Et?Wb:zb,tr=new IntersectionObserver(ct=>{ct.some(Ct=>Ct.isIntersecting)&&Yt(Ct=>Math.min(Ct+Ot,St))},{rootMargin:"160px 0px"});return tr.observe(Ce),()=>tr.disconnect()},[ot,ie.length,Ut.length,Et]);const Dr=b.useMemo(()=>{if(!J)return;if(!ot)return r?J.filter(St=>St.type==="directory"):J;const Ce=Vt.getState().directoryCache;return J.filter(St=>(!r||St.type==="directory")&&Kg(St,ot,Ce))},[r,ot,J]);if(!e)return s.jsx("div",{className:"px-4 py-8 text-center text-sm text-muted-foreground",children:V("fileTree.noWorkingDir")});if(Je||!z)return s.jsx(AO,{});if(ot&&Et){const Ce=Ge?.total??Ut.length,St=Ut.slice(0,vt),Ot=vt<Ut.length;return s.jsxs("div",{className:"termdock-native-select min-h-full space-y-px bg-surface px-2 py-2",children:[s.jsx(Gb,{count:Ce,loading:me,engine:Ge?.engine,limited:Ge?.limited,scope:K,content:!0}),ft?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:[V("fileTree.contentSearchNeedsRipgrep"),s.jsx("div",{className:"mt-1 break-words text-[11px] text-muted-foreground/70",children:ft})]}):me&&Ut.length===0?s.jsx(_0,{label:V("fileTree.searching"),className:"py-8"}):Ut.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:V("fileTree.noContentMatches")}):s.jsxs(s.Fragment,{children:[Ge?.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:V("fileTree.searchTruncatedHint",{count:Ge.total})}),St.map(tr=>s.jsx(BO,{entry:tr,rootPath:K,selectedFilePath:I,query:N.trim(),onContentMatchSelect:$,onPathReference:n,referenceSelection:a,getReferenceText:c,onReferenceCopied:l,insertedReferenceKey:d,copiedReferenceKey:f},tr.path)),s.jsx("div",{ref:xe,className:"py-2 text-center text-[11px] text-muted-foreground",children:Ot?s.jsx("button",{type:"button",onClick:()=>Yt(tr=>Math.min(tr+Wb,Ut.length)),className:"rounded-full bg-surface-2 px-3 py-1 hover:bg-surface-elevated hover:text-foreground",children:V("fileTree.loadMoreSearchResults",{shown:St.length,total:Ut.length})}):me?s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(jn,{size:10,className:"animate-spin"}),V("fileTree.searchStillRunning")]}):St.length>0?s.jsx("span",{children:V("fileTree.showingSearchResults",{shown:St.length,total:Ce})}):null})]})]})}if(ot){const Ce=Ge?.total??ie.length,St=ie.slice(0,vt),Ot=vt<ie.length;return s.jsxs("div",{className:"termdock-native-select min-h-full space-y-px bg-surface px-2 py-2",children:[s.jsx(Gb,{count:Ce,loading:me,engine:Ge?.engine,limited:Ge?.limited,scope:K,content:!1}),me&&ie.length===0?s.jsx(_0,{label:V("fileTree.searching"),className:"py-8"}):ft?s.jsx("div",{className:"px-4 py-4 text-sm text-destructive",children:ft}):ie.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:V("fileTree.noMatchingFiles")}):s.jsxs(s.Fragment,{children:[Ge?.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:V("fileTree.searchTruncatedHint",{count:Ge.total})}),St.map(tr=>s.jsx(RO,{node:tr,rootPath:K,onFileSelect:t,onPathReference:n,referenceSelection:a,getReferenceText:c,onReferenceCopied:l,onDirectoryRoot:m,onSearchFromDirectory:x,onDirectoryPinToggle:y,onFilePinToggle:w,pinnedPaths:S,selectedFilePath:I,insertedReferenceKey:d,copiedReferenceKey:f,onFileDeleteRequest:$e,deletingFilePath:ir},tr.path)),s.jsx("div",{ref:xe,className:"py-2 text-center text-[11px] text-muted-foreground",children:Ot?s.jsx("button",{type:"button",onClick:()=>Yt(tr=>Math.min(tr+zb,ie.length)),className:"rounded-full bg-surface-2 px-3 py-1 hover:bg-surface-elevated hover:text-foreground",children:V("fileTree.loadMoreSearchResults",{shown:St.length,total:ie.length})}):me?s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(jn,{size:10,className:"animate-spin"}),V("fileTree.searchStillRunning")]}):St.length>0?s.jsx("span",{children:V("fileTree.showingSearchResults",{shown:St.length,total:Ce})}):null})]})]})}return ae?s.jsx("div",{role:a?"alert":void 0,className:"px-4 py-4 text-sm text-destructive",children:ae}):!J||J.length===0?s.jsx("div",{className:"px-4 py-8 text-center text-sm text-muted-foreground",children:V("fileTree.emptyDir")}):!Dr||Dr.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:V("fileTree.noMatchingFiles")}):s.jsxs("div",{className:"termdock-native-select w-max min-w-full space-y-px px-2 py-2",children:[at&&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:V("fileTree.truncatedHint")}),Dr.map(Ce=>s.jsx(NO,{node:Ce,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:T,pinnedPaths:S,selectedFilePath:I,queryLower:ot,insertedReferenceKey:d,copiedReferenceKey:f,onDirectoryDropFiles:ee,onFileDeleteRequest:$e,deletingFilePath:ir,revealedDirectoryPath:Z?.path},Ce.path))]})}function q1(e){return e.trim().replace(/\/+$/,"")||"/"}function PO(e){const t=q1(e);if(t==="/")return"/";const r=t.lastIndexOf("/");return r<=0?"/":t.slice(0,r)}function yp({open:e,initialPath:t,title:r,labels:n,onCancel:a,onConfirm:c}){const{t:l}=Hr(),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")},f=b.useRef(null);eu(f,e,a);const[m,x]=b.useState(()=>q1(t));return b.useEffect(()=>{e&&x(q1(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?Ks.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:f,tabIndex:-1,role:"dialog","aria-modal":"true","aria-labelledby":"directory-picker-title",className:"fixed bottom-[max(0.75rem,env(safe-area-inset-bottom,0px))] left-[max(0.75rem,env(safe-area-inset-left,0px))] right-[max(0.75rem,env(safe-area-inset-right,0px))] top-[max(0.75rem,env(safe-area-inset-top,0px))] z-modal-panel flex flex-col overflow-hidden rounded-2xl border border-border/15 bg-surface shadow-[0_28px_70px_var(--app-shadow-strong),0_14px_32px_var(--app-shadow-soft)] sm:bottom-auto sm:left-1/2 sm:right-auto sm:top-1/2 sm:h-[min(72svh,36rem)] sm:w-[min(36rem,calc(100vw-2rem))] sm:-translate-x-1/2 sm:-translate-y-1/2",children:[s.jsxs("header",{className:"flex shrink-0 items-center gap-3 border-b border-border/15 px-4 py-3",children:[s.jsx("span",{className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/15 text-primary",children:s.jsx(MT,{size:15})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("h2",{id:"directory-picker-title",className:"text-[13px] font-semibold text-foreground",children:r}),s.jsx("p",{className:"mt-0.5 text-[10px] text-muted-foreground",children:d.hint})]}),s.jsx("button",{type:"button",onClick:a,className:"inline-flex h-9 w-9 items-center justify-center rounded-lg text-muted-foreground transition hover:bg-surface-2 hover:text-foreground","aria-label":d.close,children:s.jsx(Mn,{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(PO(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(s3,{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(QO,{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(ai,{size:13}),d.confirm]})]})]})]}),document.body):null}const OO=Object.freeze(Object.defineProperty({__proto__:null,DirectoryPickerDialog:yp},Symbol.toStringTag,{value:"Module"})),Y1="termdock:new-session-commands:v1",pc="__saved_command__:";function $h(e){return[...new Set(Object.entries(e).filter(([t])=>t.startsWith(pc)||t==="__custom__"||t==="__terminal__").map(([,t])=>t.trim()).filter(Boolean))]}function Jd(){try{const e=JSON.parse(localStorage.getItem(Y1)||"{}");return!e||typeof e!="object"||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(t=>typeof t[1]=="string"))}catch{return{}}}function FO({directories:e,tmuxAvailable:t,options:r,agents:n,selectedAgent:a,detecting:c,resumeHistory:l,resumeHistoryLoading:d,resumeHistoryPendingId:f,resumeHistoryError:m,onRefreshAgents:x,onSelectAgent:y,onLaunchAgent:w,onResumeHistory:v,onRemoveResumeHistory:T,onClose:S,onOptionsChange:I,additionalContent:N,footerActions:B,launchPending:F=!1,launchError:P}){const{t:$,locale:ee}=Hr(),Z=b.useRef(null);eu(Z,!0,S,()=>document.querySelector('[aria-controls="sidebar-launch-options"]'));const[V,de]=b.useState(a),[pe,J]=b.useState(!1),[Re,Xe]=b.useState(!1),[q,ve]=b.useState(Jd),[qe,ce]=b.useState(()=>$h(Jd())),[ye,Te]=b.useState(null),[Fe,se]=b.useState("idle"),De=Re?"__custom__":V?.slug??"__terminal__",_e=V?.command??"",Me=Re?q.__custom__??q.__terminal__??"":V?q[De]??_e:"",Je=()=>{const Le=Me.trim()||_e;if(!(Re&&!Le))try{const z={...Jd(),[De]:Le};if(Re){for(const ie of $h(Jd()))z[pc+ie]=ie;z[pc+Le]=Le}localStorage.setItem(Y1,JSON.stringify(z)),ce($h(z)),Re&&Te(Le),se("saved")}catch{se("error")}},Ne=()=>{if(ye)try{const Le=Jd();for(const[z,ie]of Object.entries(Le))(z.startsWith(pc)||z==="__custom__"||z==="__terminal__")&&ie.trim()===ye&&delete Le[z];localStorage.setItem(Y1,JSON.stringify(Le)),ce($h(Le)),ve(z=>({...z,__custom__:""})),Te(null),se("idle")}catch{se("error")}},ae=()=>{const Le=Me.trim()||_e;F||Re&&!Le||(Je(),w(V,Le))},ze=b.useMemo(()=>[...new Set(e.filter(Boolean))].slice(0,5),[e]),at=Re?ye?pc+ye:"__custom__":V?.slug??"__terminal__",ut=Le=>{se("idle");const z=Le.startsWith(pc)?Le.slice(pc.length):null;Te(z),Xe(Le==="__custom__"||z!==null),(z!==null||Le==="__custom__")&&ve(ie=>({...ie,__custom__:z??""})),de(n.find(ie=>ie.slug===Le)??null)},me=Re?ye??$("sidebar.customStartupCommand"):V?.displayName??"Terminal",dt=a?.displayName??"Terminal",ft=!Re&&(V===null?a===null:a?.slug===V.slug);b.useEffect(()=>{if(pe)return;const Le=z=>{z.target instanceof Node&&(Z.current?.contains(z.target)||z.target instanceof Element&&z.target.closest("[data-sidebar-composer-popover]")?.getAttribute("data-sidebar-composer-popover")===Z.current?.id||z.target instanceof Element&&z.target.closest('[aria-controls="sidebar-launch-options"]')||S())};return document.addEventListener("pointerdown",Le,!0),()=>document.removeEventListener("pointerdown",Le,!0)},[pe,S]);const Se=Le=>{I({...r,cwd:Le}),J(!1)},We=Le=>new Intl.DateTimeFormat(ee==="zh"?"zh-CN":"en",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}).format(new Date(Le));return s.jsxs("section",{ref:Z,tabIndex:-1,"aria-busy":F,id:"sidebar-launch-options",className:`absolute inset-x-3 bottom-3 z-30 flex flex-col overflow-hidden rounded-2xl border border-border bg-surface shadow-[0_18px_50px_var(--app-shadow-strong),0_4px_14px_var(--app-shadow-soft)] animate-slide-down ${B?"max-h-[min(70svh,42rem,calc(100%_-_4.5rem))]":"max-h-[min(56svh,36rem,calc(100%_-_4.5rem))]"}`,"aria-label":$("sidebar.newSessionComposerTitle"),children:[s.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-3 px-3 py-1.5",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-2.5",children:[s.jsx("span",{className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg text-muted-foreground",children:s.jsx(Zo,{size:14})}),s.jsx("div",{className:"min-w-0",children:s.jsx("div",{className:"text-[12px] font-semibold text-foreground",children:$("sidebar.newSessionComposerTitle")})})]}),s.jsx("button",{type:"button",onClick:S,className:"inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition hover:bg-surface-2 hover:text-foreground","aria-label":$("common.close"),children:s.jsx(Mn,{size:14})})]}),s.jsxs("fieldset",{disabled:F,className:"min-h-0 min-w-0 flex-1 overflow-y-auto overscroll-contain border-0 px-3 pb-1",children:[s.jsxs("div",{className:"flex min-h-11 items-center justify-between gap-3",children:[s.jsx("span",{className:"shrink-0 text-[11px] text-muted-foreground",children:$("sidebar.sessionMode")}),s.jsx("div",{className:"grid grid-cols-2 gap-1 rounded-lg bg-surface p-0.5",children:["shell","tmux"].map(Le=>s.jsx("button",{type:"button",disabled:Le==="tmux"&&!t,onClick:()=>I({...r,mode:Le}),"aria-pressed":r.mode===Le,title:Le==="tmux"?$(t?"sidebar.tmuxKeepsRunning":"sidebar.newTmuxDisabled"):void 0,className:`min-h-9 rounded-md px-4 text-[11px] font-medium transition ${r.mode===Le?"bg-surface-2 text-foreground":"text-muted-foreground hover:text-foreground"} disabled:cursor-not-allowed disabled:opacity-40`,children:$(Le==="shell"?"sidebar.newShell":"sidebar.newTmux")},Le))})]}),s.jsxs("div",{className:"mt-1 flex items-center justify-between",children:[s.jsx("span",{className:"text-[11px] text-muted-foreground",children:$("sidebar.startupCommand")}),s.jsx("button",{type:"button",onClick:x,disabled:c,className:"inline-flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground transition hover:bg-surface hover:text-foreground disabled:opacity-50",title:$("sidebar.detectAgents"),"aria-label":$("sidebar.detectAgents"),children:s.jsx(wn,{size:12,className:c?"animate-spin":""})})]}),s.jsxs("div",{role:"radiogroup","aria-label":$("sidebar.startupCommand"),className:"flex flex-wrap gap-1",children:[n.map(Le=>{const z=!Re&&V?.slug===Le.slug;return s.jsxs("button",{type:"button",role:"radio","aria-checked":z,onClick:()=>ut(Le.slug),className:`inline-flex min-h-7 items-center gap-1 rounded-md px-2 text-[10.5px] font-medium transition ${z?"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(Jc,{agent:Le,size:12}),s.jsx("span",{className:"max-w-[9rem] truncate",children:Le.displayName}),a?.slug===Le.slug&&s.jsx("span",{className:"ml-0.5 text-[9px] text-muted-foreground",children:$("sidebar.defaultAgent")})]},Le.slug)}),qe.map(Le=>{const z=Re&&ye===Le;return s.jsxs("button",{type:"button",role:"radio","aria-checked":z,onClick:()=>ut(pc+Le),title:Le,className:`inline-flex min-h-7 items-center gap-1 rounded-md px-2 transition ${z?"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,{size:10,className:"shrink-0"}),s.jsx("span",{className:"max-w-[9rem] truncate font-mono text-[10px]",children:Le})]},Le)}),s.jsxs("button",{type:"button",role:"radio","aria-checked":at==="__terminal__",onClick:()=>ut("__terminal__"),className:`inline-flex min-h-7 items-center gap-1 rounded-md px-2 text-[10.5px] font-medium transition ${at==="__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(Zo,{size:11,className:"shrink-0"}),s.jsx("span",{children:"Terminal"}),a===null&&s.jsx("span",{className:"ml-0.5 text-[9px] font-normal text-muted-foreground",children:$("sidebar.defaultAgent")})]}),s.jsxs("button",{type:"button",role:"radio","aria-checked":at==="__custom__",onClick:()=>ut("__custom__"),className:`inline-flex min-h-7 items-center gap-0.5 rounded-md px-2 text-[10.5px] font-medium transition ${at==="__custom__"?"bg-surface-2 text-foreground ring-1 ring-inset ring-primary/50":"bg-surface text-muted-foreground hover:bg-surface-2 hover:text-foreground"}`,children:[s.jsx(Zs,{size:10,className:"shrink-0"}),s.jsx("span",{children:$("sidebar.addStartupCommand")})]})]}),!ft&&!Re&&s.jsxs("div",{className:"mt-1 flex min-h-8 items-center justify-between gap-2 px-0.5 text-[10px]",children:[s.jsx("span",{className:"truncate text-muted-foreground",children:$("sidebar.currentDefaultAgent",{name:dt})}),s.jsx("button",{type:"button",onClick:()=>y(V),className:"relative z-10 shrink-0 rounded-md px-2 py-1.5 font-medium text-primary transition hover:bg-primary/10",children:$("sidebar.makeDefault")})]}),Fe==="error"&&s.jsx("p",{role:"alert",className:"text-[10px] text-destructive",children:$("sidebar.saveStartupCommandFailed")}),(V||Re)&&s.jsxs("details",{open:Re&&!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:[$(Re&&!ye?"sidebar.customStartupCommand":"sidebar.changeStartupCommand"),s.jsx(Al,{size:11,className:"transition-transform group-open/command:rotate-180"})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2",children:[s.jsx("label",{htmlFor:"new-session-command",className:"sr-only",children:$("sidebar.startupCommand")}),V&&Me!==_e&&s.jsx("button",{type:"button",onClick:()=>{ve(Le=>({...Le,[De]:_e})),se("idle")},className:"min-h-8 rounded-md px-2 text-[10px] text-primary transition hover:bg-primary/10",children:$("sidebar.resetStartupCommand")})]}),s.jsx("input",{id:"new-session-command",value:Me,onChange:Le=>{ve(z=>({...z,[De]:Le.target.value})),se("idle")},placeholder:_e||$("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:[Re&&ye&&s.jsxs("button",{type:"button",onClick:Ne,className:"mr-auto inline-flex min-h-9 items-center gap-1 rounded-md px-2 text-[10px] text-muted-foreground transition hover:text-destructive","aria-label":$("sidebar.deleteStartupCommand"),children:[s.jsx(Ds,{size:11}),$("sidebar.deleteStartupCommand")]}),s.jsx("button",{type:"button",onClick:Je,disabled:Fe==="saved"||Re&&!Me.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:$(Fe==="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:$(V?"sidebar.agentStartupCommandHint":"sidebar.terminalStartupCommandHint")})]},ye??De),s.jsx("label",{htmlFor:"new-session-directory",className:"mt-2 block text-[11px] text-muted-foreground",children:$("sidebar.workingDirectory")}),s.jsxs("button",{id:"new-session-directory",type:"button","aria-haspopup":"dialog",onClick:()=>J(!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(tu,{size:12,className:"shrink-0 text-muted-foreground"}),s.jsx("span",{className:`min-w-0 flex-1 truncate text-left ${r.cwd?"":"text-muted-foreground"}`,children:r.cwd||$("sidebar.directoryPlaceholder")})]}),ze.length>0&&s.jsx("div",{className:"mt-1.5 flex gap-1 overflow-x-auto pb-0.5","aria-label":$("sidebar.recentDirectories"),children:ze.map(Le=>s.jsx("button",{type:"button",onClick:()=>Se(Le),title:Le,className:"min-h-8 shrink-0 rounded-md px-2 text-[10px] text-muted-foreground transition hover:bg-surface hover:text-foreground",children:cd(Le)||Le},Le))}),(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(Wc,{size:11}),s.jsx("span",{className:"flex-1",children:$("sidebar.resumeHistory")}),d&&s.jsx(jn,{size:10,className:"animate-spin"}),l.length>0&&s.jsx("span",{className:"normal-case tracking-normal",children:$("sidebar.resumeHistoryCount",{n:l.length})}),s.jsx(Al,{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(Le=>{const z=f===Le.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:f!==null,onClick:()=>v(Le),className:"flex min-h-11 min-w-0 flex-1 items-center gap-2.5 px-2.5 py-2 text-left disabled:cursor-wait disabled:opacity-60","aria-label":$("sidebar.resumeHistoryAction",{title:Le.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:z?s.jsx(jn,{size:13,className:"animate-spin"}):s.jsx(Jc,{agent:Le.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:Le.title}),s.jsxs("span",{className:"block truncate text-[9.5px] text-muted-foreground",children:[Le.agent.displayName," · ",We(Le.closedAt)]})]}),s.jsx(h3,{size:12,className:"shrink-0 text-muted-foreground transition group-hover:text-primary"})]}),s.jsxs("button",{type:"button",disabled:f!==null,onClick:()=>T(Le.id),className:"relative inline-flex w-11 shrink-0 items-center justify-center text-muted-foreground transition hover:text-destructive disabled:opacity-40","aria-label":$("sidebar.resumeHistoryRemove",{title:Le.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(Ds,{size:12})]})]},Le.id)})}),m&&s.jsx("div",{role:"alert",className:"mt-1.5 px-1 text-[10px] text-destructive",children:m})]}),N]}),s.jsxs("div",{className:"shrink-0 bg-surface px-3 pb-3 pt-2",children:[P&&s.jsx("p",{role:"alert",className:"mb-2 text-[11px] leading-relaxed text-destructive",children:P}),s.jsxs("button",{type:"button",onClick:ae,disabled:F||Re&&!Me.trim(),className:"flex min-h-11 w-full items-center justify-center gap-2 rounded-lg bg-primary px-3 text-[12px] font-semibold text-primary-foreground transition hover:brightness-110 active:scale-[0.99] disabled:cursor-not-allowed disabled:opacity-40","aria-label":$("sidebar.launchSessionWith",{name:me}),children:[F?s.jsx(jn,{size:14}):V?s.jsx(Jc,{agent:V,size:15}):s.jsx(Zo,{size:14}),s.jsx("span",{className:"truncate",children:F?$("sidebar.sessionCreating"):$("sidebar.launchSessionWith",{name:me})})]}),B]}),s.jsx(yp,{open:pe,initialPath:r.cwd?.trim()||ze[0]||"/",title:$("sidebar.chooseDirectory"),onCancel:()=>J(!1),onConfirm:Se})]})}function $O({onOpenSettings:e,serverAttention:t,actions:r,compact:n=!1}){const{t:a}=Hr(),[c,l]=b.useState(!1),d=b.useRef(null),f=b.useRef(null),m=b.useRef(null),x=b.useId();return b.useLayoutEffect(()=>{if(!c)return;const y=d.current,w=m.current;if(!y||!w)return;const v=window.visualViewport,T=()=>{const I=y.getBoundingClientRect(),N=(v?.offsetLeft??0)+8,B=(v?.offsetTop??0)+8,F=(v?.width??window.innerWidth)-16,P=(v?.offsetTop??0)+(v?.height??window.innerHeight)-8,$=Math.max(0,Math.min(256,F)),ee=Math.max(0,I.top-B-4),Z=Math.max(0,P-I.bottom-4),V=ee>=180||ee>=Z;Object.assign(w.style,{width:`${$}px`,left:`${Math.max(N,Math.min(I.right-$,N+F-$))}px`,top:`${V?I.top-4:I.bottom+4}px`,maxHeight:`${V?ee:Z}px`,transform:V?"translateY(-100%)":"none"})};T();const S=typeof ResizeObserver>"u"?null:new ResizeObserver(T);return S?.observe(y),window.addEventListener("resize",T),window.addEventListener("scroll",T,!0),v?.addEventListener("resize",T),v?.addEventListener("scroll",T),()=>{S?.disconnect(),window.removeEventListener("resize",T),window.removeEventListener("scroll",T,!0),v?.removeEventListener("resize",T),v?.removeEventListener("scroll",T)}},[c]),b.useEffect(()=>{if(!c)return;m.current?.querySelector('[role="menuitem"]')?.focus({preventScroll:!0});const y=w=>{w.target instanceof Node&&!d.current?.contains(w.target)&&!m.current?.contains(w.target)&&l(!1)};return document.addEventListener("pointerdown",y),()=>document.removeEventListener("pointerdown",y)},[c]),s.jsxs("div",{ref:d,role:"group","data-sidebar-gesture-ignore":!0,"aria-label":a("sidebar.moreActions"),className:n?"relative z-20 flex shrink-0 items-center":"relative z-20 mt-2 flex items-center justify-between gap-2",onKeyDown:y=>{c&&y.key==="Escape"&&(y.preventDefault(),y.stopPropagation(),l(!1),f.current?.focus({preventScroll:!0}))},children:[!n&&s.jsxs("button",{type:"button",onClick:e,title:t?a("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(f3,{size:14,className:t?"text-destructive":void 0}),s.jsx("span",{children:a("sidebar.settings")})]}),s.jsxs("button",{ref:f,"data-session-sidebar-header-action":n?"":void 0,title:a("sidebar.moreActions"),"aria-label":a("sidebar.moreActions"),type:"button","aria-haspopup":"menu","aria-expanded":c,"aria-controls":c?x:void 0,onClick:()=>l(y=>!y),onKeyDown:y=>{(y.key==="ArrowDown"||y.key==="ArrowUp")&&(y.preventDefault(),l(!0))},className:`relative inline-flex items-center justify-center gap-1.5 whitespace-nowrap rounded-lg text-[11px] transition focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary ${n?"h-9 w-9 shrink-0":"min-h-9 px-2"} ${c?"bg-surface-2 text-foreground":"text-muted-foreground hover:bg-surface-2 hover:text-foreground"}`,children:[s.jsx(Io,{size:15}),!n&&s.jsx("span",{children:a("sidebar.moreActions")}),n&&t&&s.jsx("span",{"aria-hidden":"true",className:"absolute right-0 top-0 h-1.5 w-1.5 rounded-full bg-destructive"})]}),c&&Ks.createPortal(s.jsx("div",{ref:m,id:x,role:"menu","data-sidebar-gesture-ignore":!0,"data-sidebar-composer-popover":"sidebar-launch-options","aria-label":a("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:y=>{const w=[...y.currentTarget.querySelectorAll('[role="menuitem"]')],v=w.indexOf(document.activeElement);let T;if(y.key==="ArrowDown")T=(v+1)%w.length;else if(y.key==="ArrowUp")T=(v-1+w.length)%w.length;else if(y.key==="Home")T=0;else if(y.key==="End")T=w.length-1;else if(y.key==="Tab"){l(!1);return}else return;y.preventDefault(),w[T]?.focus({preventScroll:!0})},children:r.map(({label:y,icon:w,onSelect:v,separated:T})=>s.jsxs("div",{role:"none",children:[T&&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:()=>{l(!1),v()},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(w,{size:15,className:"shrink-0 text-muted-foreground"}),s.jsx("span",{children:y})]})]},y))}),document.body)]})}const Fm="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";function UO({label:e,count:t,badge:r,actions:n,pinned:a,onTogglePinned:c,onClose:l,onOpenSettings:d,serverAttention:f}){const{t:m}=Hr(),x=b.useRef(null),y=b.useRef(null),[w,v]=b.useState(!0);return b.useLayoutEffect(()=>{const T=x.current;if(!T)return;const S=()=>{const N=getComputedStyle(T),B=T.clientWidth-parseFloat(N.paddingLeft)-parseFloat(N.paddingRight),F=T.querySelector("button"),P=F?F.getBoundingClientRect().width:36,$=[...y.current?.children??[]],ee=$.reduce((de,pe)=>de+pe.scrollWidth,0)+Math.max(0,$.length-1)*6,Z=n.length+(c?1:0)+(a?0:1),V=ee+Z*P+Math.max(0,Z-1)*4+6;v(B<V+8)};S();const I=typeof ResizeObserver>"u"?null:new ResizeObserver(S);return I?.observe(T),window.addEventListener("resize",S),()=>{I?.disconnect(),window.removeEventListener("resize",S)}}),s.jsxs("div",{ref:x,"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 min-w-0 w-full items-center gap-1.5",children:[s.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:s.jsxs("div",{ref:y,className:"flex min-w-0 items-center gap-1.5 whitespace-nowrap",children:[s.jsx("span",{className:"min-w-0 truncate text-[12px] font-medium text-muted-foreground",children:e}),s.jsx("span",{className:"shrink-0 text-[11px] text-muted-foreground",children:t}),r&&s.jsx("span",{className:"flex shrink-0 items-center",children:r})]})}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[w?s.jsx($O,{compact:!0,actions:n,serverAttention:f,onOpenSettings:d}):n.map(({label:T,icon:S,onSelect:I})=>s.jsx("button",{"data-session-sidebar-header-action":!0,type:"button",className:Fm,"aria-label":T,title:T,onClick:I,children:s.jsx(S,{size:16})},T)),c&&s.jsx("button",{"data-session-sidebar-header-action":!0,type:"button",className:Fm,onClick:c,"aria-label":m(a?"sidebar.unpinSidebar":"sidebar.pinSidebar"),title:m(a?"sidebar.unpinSidebar":"sidebar.pinSidebar"),"aria-pressed":a,children:a?s.jsx(R0,{size:16}):s.jsx(N0,{size:16})}),!a&&s.jsx("button",{"data-session-sidebar-header-action":!0,type:"button",className:Fm,onClick:l,"aria-label":m("common.close"),children:s.jsx(Mn,{size:16})})]})]})]})}const p4="termdock:new-session-agent:v1";function zO(){if(typeof window>"u")return null;try{const e=JSON.parse(window.localStorage.getItem(p4)||"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 $m(e){if(!(typeof window>"u"))try{window.localStorage.setItem(p4,JSON.stringify(e))}catch{}}function HO(e,t){return e?t.find(r=>r.slug===e)??null:null}function WO(){const[e,t]=b.useState(zO),[r,n]=b.useState([]),[a,c]=b.useState(!0),l=b.useCallback(async()=>{c(!0);try{const[f,m]=await Promise.all([wc(),Ky()]),x=HO(f.newSessionAgentSlug,m);n(m),t(x),$m(x)}finally{c(!1)}},[]);b.useEffect(()=>{const f=()=>{l().catch(()=>{})};if(performance.getEntriesByName("termdock:startup:initial-viewport-presented").length>0){f();return}return window.addEventListener("termdock:initial-viewport-presented",f,{once:!0}),()=>window.removeEventListener("termdock:initial-viewport-presented",f)},[l]);const d=b.useCallback(async f=>{const m=e;t(f),$m(f);try{await ja({newSessionAgentSlug:f?.slug??null})}catch(x){throw t(m),$m(m),x}},[e]);return{preference:e,agents:r,detecting:a,refresh:l,selectAgent:d}}function GO({label:e,disabled:t,onRemove:r,children:n}){const[a,c]=b.useState(null),l=b.useRef(null),d=b.useRef(null),f=(m=!1)=>{c(null),m&&l.current?.querySelector("button")?.focus({preventScroll:!0})};return b.useEffect(()=>{t&&c(null)},[t]),b.useLayoutEffect(()=>{if(!a||!d.current)return;const m=d.current.getBoundingClientRect();d.current.style.left=`${Math.max(8,Math.min(a.x,window.innerWidth-m.width-8))}px`,d.current.style.top=`${Math.max(8,Math.min(a.y,window.innerHeight-m.height-8))}px`,d.current.querySelector("button")?.focus({preventScroll:!0})},[a]),b.useEffect(()=>{if(!a)return;const m=w=>{d.current?.contains(w.target)||f()},x=w=>{w.key==="Escape"?(w.preventDefault(),w.stopPropagation(),f(!0)):w.key==="Tab"&&f()},y=()=>f();return window.addEventListener("pointerdown",m,!0),window.addEventListener("keydown",x,!0),window.addEventListener("resize",y),window.addEventListener("scroll",y,!0),()=>{window.removeEventListener("pointerdown",m,!0),window.removeEventListener("keydown",x,!0),window.removeEventListener("resize",y),window.removeEventListener("scroll",y,!0)}},[a]),s.jsxs("span",{ref:l,className:"inline-flex max-w-full items-center gap-0.5",onContextMenu:m=>{t||(m.preventDefault(),m.stopPropagation(),c({x:m.clientX,y:m.clientY}))},onKeyDown:m=>{if(!t&&(m.key==="ContextMenu"||m.shiftKey&&m.key==="F10")){m.preventDefault(),m.stopPropagation();const x=l.current.getBoundingClientRect();c({x:x.left,y:x.bottom})}},children:[n,a&&Ks.createPortal(s.jsx("div",{ref:d,role:"menu","aria-label":`${e} 的成员操作`,style:{left:a.x,top:a.y},className:"fixed z-popover min-w-44 rounded-lg border border-border/30 bg-surface-2 p-1 shadow-xl",children:s.jsxs("button",{type:"button",role:"menuitem",className:"flex min-h-9 w-full items-center gap-2 rounded-md px-3 py-2 text-left text-xs text-destructive hover:bg-destructive/10 focus:bg-destructive/10 focus:outline-none",onClick:()=>{f(!0),r()},children:[s.jsx(Ds,{size:14}),"从协作组移除"]})}),document.body)]})}function VO({groups:e,sessions:t,busy:r,onOpen:n,onSettings:a,onCreate:c}){const[l,d]=b.useState(""),f=e.filter(m=>!l.trim()||`${m.name} ${m.sessionIds.map(x=>t.find(y=>y.sessionId===x)?.name??"").join(" ")}`.toLowerCase().includes(l.trim().toLowerCase()));return s.jsxs("section",{"aria-label":"协作组列表",className:"space-y-3",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsx("p",{className:"text-xs leading-6 text-muted-foreground",children:"成员消息用于日常交流;看板用于目标、交付与验收。"}),s.jsxs("button",{type:"button",disabled:r,className:"inline-flex min-h-11 shrink-0 items-center gap-1.5 rounded-lg bg-primary px-3 text-xs font-medium text-primary-foreground disabled:opacity-40",onClick:c,children:[s.jsx(Zs,{size:14}),"新建协作组"]})]}),(e.length>5||l)&&s.jsxs("label",{className:"relative block",children:[s.jsx("span",{className:"sr-only",children:"搜索协作组"}),s.jsx(Wl,{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:[f.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=>Uu(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(ud,{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(HT,{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(qu,{size:14})})]})]},m.id)}),!f.length&&s.jsx("p",{className:"px-3 py-6 text-xs text-muted-foreground",children:"没有匹配的协作组,试试其他名称。"})]})]})}const Uc="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",Uh="inline-flex min-h-11 items-center justify-center gap-2 rounded-lg px-3 text-xs disabled:opacity-40",zh=e=>({profiles:e.launchProfiles??[],defaultId:e.defaultLaunchProfileId??"",group:e}),Um=new Map,e0=e=>JSON.stringify(e.profiles)!==JSON.stringify(e.group.launchProfiles??[])||e.defaultId!==(e.group.defaultLaunchProfileId??"");function qO({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:Uc,value:t,disabled:n,onChange:c=>r(c.target.value),children:[s.jsx("option",{value:"",children:"Agent 默认命令"}),e.launchProfiles?.map(c=>s.jsx("option",{value:c.id,children:c.name},c.id))]})]}),a&&s.jsxs("p",{className:"whitespace-pre-wrap break-words text-xs leading-5 text-muted-foreground",children:[a.notes||"未填写使用备注",s.jsx("code",{className:"block break-all",children:a.command})]}),t&&!a&&s.jsx("p",{role:"alert",className:"text-xs text-destructive",children:"原方案已删除,请重新选择。"})]})}function YO({group:e,agents:t,busy:r,setBusy:n,refresh:a}){const c=`${window.location.origin}:${e.id}`,[l,d]=b.useState(()=>Um.get(c)??zh(e)),f=b.useRef(l);f.current=l;const[m,x]=b.useState(l.profiles[0]?.id??""),[y,w]=b.useState(null),[v,T]=b.useState(""),S=($,ee=!0)=>{f.current=$,d($),e0($)?Um.set(c,$):Um.delete(c),ee&&T("")};b.useEffect(()=>{!e0(f.current)&&e.updatedAt>=f.current.group.updatedAt&&S(zh(e),!1)},[e.updatedAt]);const I=l.profiles.find($=>$.id===m),N=$=>S({...l,profiles:l.profiles.map(ee=>ee.id===m?{...ee,...$}:ee)}),B=l.profiles.every($=>$.name.trim()&&$.agentSlug&&$.command.trim()&&!/[\x00-\x1f\x7f]/.test($.command)),F=()=>{const $=t[0],ee={id:`profile-${crypto.randomUUID()}`,name:"",agentSlug:$?.slug??"",command:$?.command??"",notes:""};S({...l,profiles:[...l.profiles,ee]}),x(ee.id)},P=async()=>{if(!(r||!B||!e0(l))){n("launch-profiles"),w(null),T("");try{const{group:$}=await Hl({id:e.id,name:l.group.name,sessionIds:l.group.sessionIds,expectedUpdatedAt:l.group.updatedAt,launchProfiles:l.profiles,defaultLaunchProfileId:l.defaultId||null});S(zh($)),T("启动方案已保存。新会话使用所选方案,正在运行的成员保持原配置。"),await a()}catch($){w($ instanceof Error?$.message:"保存失败")}finally{n(null)}}};return s.jsxs("details",{className:"mt-3 border-t border-border/15 pt-2",children:[s.jsxs("summary",{className:"min-h-11 cursor-pointer py-3 text-xs font-medium text-foreground",children:["Agent 启动方案 · ",l.profiles.length," 个",e0(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:Uc,value:l.defaultId,onChange:$=>S({...l,defaultId:$.target.value}),children:[s.jsx("option",{value:"",children:"使用 Agent 默认命令"}),l.profiles.map($=>s.jsx("option",{value:$.id,children:$.name||"未命名方案"},$.id))]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("label",{className:"min-w-0 flex-1 text-xs text-muted-foreground",children:["编辑方案",s.jsxs("select",{"aria-label":"编辑方案",className:`${Uc} mt-1`,value:m,onChange:$=>x($.target.value),children:[s.jsx("option",{value:"",children:"选择方案"}),l.profiles.map($=>s.jsx("option",{value:$.id,children:$.name||"未命名方案"},$.id))]})]}),s.jsxs("button",{type:"button",className:`${Uh} self-end bg-surface text-foreground`,disabled:l.profiles.length>=20,onClick:F,children:[s.jsx(Zs,{size:14}),"新增方案"]})]}),I?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:Uc,value:I.name,maxLength:100,onChange:$=>N({name:$.target.value}),placeholder:"例如:快速排查、深度实现"})]}),s.jsxs("label",{className:"block space-y-1 text-xs text-muted-foreground",children:["Agent 类型",s.jsxs("select",{"aria-label":"Agent 类型",className:Uc,value:I.agentSlug,onChange:$=>N({agentSlug:$.target.value,command:t.find(ee=>ee.slug===$.target.value)?.command??""}),children:[!t.some($=>$.slug===I.agentSlug)&&s.jsxs("option",{value:I.agentSlug,children:[I.agentSlug||"选择 Agent","(当前不可用)"]}),t.map($=>s.jsx("option",{value:$.slug,children:$.displayName},$.slug))]})]}),s.jsxs("label",{className:"block space-y-1 text-xs text-muted-foreground",children:["启动命令",s.jsx("input",{className:`${Uc} font-mono`,value:I.command,maxLength:4096,onChange:$=>N({command:$.target.value}),placeholder:"填写完整命令,包括模型和启动参数"})]}),s.jsxs("label",{className:"block space-y-1 text-xs text-muted-foreground",children:["使用备注",s.jsx("textarea",{"aria-label":"使用备注",className:`${Uc} min-h-24 resize-y`,value:I.notes,maxLength:2e3,onChange:$=>N({notes:$.target.value}),placeholder:"适合哪些任务、何时不要使用;协调者会读取这些备注。"})]}),s.jsxs("details",{className:"text-[11px] text-muted-foreground",children:[s.jsx("summary",{className:"min-h-11 cursor-pointer py-3",children:"CLI 方案标识"}),s.jsx("code",{className:"break-all",children:I.id})]}),s.jsxs("button",{type:"button",className:`${Uh} text-destructive hover:bg-destructive/10`,onClick:()=>{const $=l.profiles.filter(ee=>ee.id!==m);S({...l,profiles:$,defaultId:l.defaultId===m?"":l.defaultId}),x($[0]?.id??"")},children:[s.jsx(Ds,{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:`${Uh} bg-surface text-muted-foreground`,disabled:!!r,onClick:()=>{S(zh(e)),x(e.launchProfiles?.[0]?.id??""),w(null)},children:"重新载入(放弃方案草稿)"}),s.jsx("button",{type:"button",disabled:!!r||!B||!e0(l),className:`${Uh} bg-primary text-primary-foreground`,onClick:()=>{P()},children:r==="launch-profiles"?"保存中…":"保存启动方案"})]})]})]})}function m4(e,t=[]){const r=(t.length?t:e.children??[]).filter(S=>S.status!=="closed"),n=r.filter(S=>S.status==="accepted").length,a=ou(e),c=e.events.filter(S=>S.kind==="revise"&&S.attemptId===e.activeAttemptId).at(-1),l=e.artifacts.filter(S=>S.kind==="result"&&S.attemptId===e.activeAttemptId).at(-1),d=!!c&&(!l||c.createdAt>=l.createdAt),f=qf(e),m=e.attempts.find(S=>S.id===e.activeAttemptId)?.report,x=S=>S?.summarySource==="explicit"||S?.summarySource!=="excerpt"&&!!S?.summary?.trim(),y=e.events.filter(S=>S.kind==="coordinate"&&S.attemptId===e.activeAttemptId&&(!c||S.sequence>c.sequence)).at(-1),w=[...f?.createdAt&&(!c||f.createdAt>c.createdAt)?[{summary:f.summary,createdAt:f.createdAt,source:"成员报告",explicit:x(m),taskId:e.id,title:e.title}]:[],...y?[{summary:y.summary||y.content,createdAt:y.createdAt,source:"协调说明",explicit:!!y.summary?.trim(),taskId:e.id,title:e.title}]:[],...d?[]:t.filter(S=>S.status!=="closed").flatMap(S=>{const I=qf(S);return I?.createdAt?[{summary:I.summary,createdAt:I.createdAt,source:"执行报告",explicit:x(S.attempts.find(N=>N.id===S.activeAttemptId)?.report),taskId:S.id,title:S.title}]:[]})].filter(S=>S.summary.trim()&&Number.isFinite(S.createdAt)&&Number.isFinite(new Date(S.createdAt).getTime())).sort((S,I)=>I.createdAt-S.createdAt);let v=a,T="分派和报告会保存在这里;终端输出不能代替明确的任务报告。";return e.workflow?.kind==="goal"&&(e.status==="accepted"?(v="已完成 · 你已验收",T="结果与执行记录已保留;追加要求可以继续跟进。"):e.status==="closed"?T="此目标已关闭,已有报告仍保留。":ta(e)||e.workflow.paused||l?T=a==="等待你验收"?"总结果已交付;查看结论后验收,或提出继续跟进。":a==="等待独立评审"?"总结果已提交,独立评审通过后交给你验收。":a==="需要你回答"?"回答当前问题后,成员可以继续原来的工作。":a==="需要你确认方案"?"确认这项必要决定后再继续;普通拆分不需要逐项批准。":d?"沿用原目标推进追加要求;上一版结果不代表本轮完成。":e.workflow.paused?"自动安排已暂停,恢复后才能继续安排后续工作。":"查看记录的阻塞原因,补充条件或重试;已有交付保留。":d?(v="已提出跟进 · 等待新报告",T="沿用原目标推进追加要求;旧报告保留为历史,等待本轮明确更新。"):r.length?(v=n===r.length?"执行交付已评审 · 等待总结果":"工作已拆分 · 执行与评审",T=n===r.length?"执行事项已交付评审,下一步由协调者汇总总结果,再交给你验收。":`已记录 ${r.length} 项工作,${n} 项交付已评审,${r.length-n} 项尚待交付或评审。`):f?(v=f.status==="ack"?"协调者已接手 · 等待拆分记录":a,T="尚未记录执行事项;协调者需说明工作划分、交付内容和下一步。"):T=a==="已写入终端 · 等待回复"?"目标已写入协调者终端,等待明确接手和拆分说明。":"目标已保存,等待分派、投递和协调者明确回复。"),{label:v,next:T,latest:w[0]??null,total:r.length,done:n}}function ZO(e,t){const r=e.dependsOn.filter(n=>t.find(a=>a.id===n)?.status!=="accepted");return r.length?`等待依赖:${r.map(n=>t.find(a=>a.id===n)?.title??"记录尚未同步").join("、")}`:e.dependsOn.length?"依赖交付已评审,可以接续":""}function g4(e){return e.explicit?e.summary:e.source==="协调说明"?"协调者已更新工作安排。此记录未提供简短摘要,详情保留原始说明。":`「${e.title}」有新的明确报告。此记录未提供简短摘要,详情保留原文。`}function Vb(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 f=[];let m=d;for(;;){const x=f.findIndex(w=>w.id===m.id);if(x!==-1)return f.slice(x).sort((w,v)=>w.id.localeCompare(v.id))[0];f.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 f=t||r.trim()?[]:e.filter(y=>y.id!==d.id&&l.get(y.id)===d.id&&y.status!=="closed"),m=d.status==="open"&&!ta(d)?f.find(y=>y.decisions.some(w=>w.status==="pending"))??f.find(y=>ta(y)||y.workflow?.paused):void 0,x=f.filter(y=>ta(y)||y.workflow?.paused).length;return{task:d,children:f,attention:m,attentionCount:x,rootId:l.get(d.id)}})}function Z1(e,t=[]){const r=ou(e),n={已验收:"已完成 · 你已验收",独立评审通过:"执行交付已评审",需要你回答:"请回答成员的问题",需要你确认方案:"请确认方案",等待你验收:"请查看结果并验收",成员报告受阻:"需要补充条件",成员报告失败:"成员报告执行失败",成员确认接手:"已接手 · 等待后续报告",成员报告进行中:"成员报告:进行中",等待独立评审:"结果已提交 · 等待评审","评审通过 · 等待接续":"交付已评审 · 等待接续","已要求跟进 · 等待新结果":"已提出跟进 · 等待新结果"};return e.status==="open"&&t.length&&!ta(e)&&!e.artifacts.some(a=>a.kind==="result"&&a.attemptId===e.activeAttemptId)?t.every(a=>a.status==="accepted")?"执行交付已评审 · 等待总结果":"目标未完成 · 执行交付待齐":n[r]??r}function x4({task:e,children:t,onSelect:r,detail:n=!1,tasks:a=t,name:c}){const l=new Map(t.map(w=>[w.id,w])),d=(t.length?t:e.children??[]).filter(w=>w.status!=="closed");if(!d.length)return null;const f=(w,v)=>{const T=l.get(w);return T&&(ta(T)||T.workflow?.paused)?0:v?2:1},m=[...d].sort((w,v)=>f(w.id,w.status==="accepted")-f(v.id,v.status==="accepted")||(l.get(v.id)?.updatedAt??0)-(l.get(w.id)?.updatedAt??0)),x=d.filter(w=>w.status==="accepted").length,y=w=>{const v=l.get(w.id),T=w.status==="accepted",S=v&&(ta(v)||v.workflow?.paused),I=v?.status==="open"?ZO(v,a):"",N=v?.attempts.find(P=>P.id===v.activeAttemptId)?.assignee??v?.scheduledAssignee??null,B=v?Z1(v):T?w.completionMode==="reviewed"?"执行交付已评审":"已验收":"等待报告",F=T?L0:V0;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(w.id),children:[s.jsx(F,{size:14,className:`mt-0.5 shrink-0 ${T||S?"text-primary":"text-muted-foreground"}`}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{title:w.title,className:"line-clamp-2 break-words text-xs leading-5 text-foreground",children:w.title}),s.jsx("span",{className:`block text-[11px] leading-5 ${S?"text-primary":"text-muted-foreground"}`,children:B}),n&&v?.parentTaskId&&v.parentTaskId!==e.id&&s.jsxs("span",{className:"block text-[11px] leading-5 text-muted-foreground",children:["所属事项:",a.find(P=>P.id===v.parentTaskId)?.title??"父任务记录尚未同步"]}),n&&v?.acceptance&&s.jsxs("span",{className:"mt-1 line-clamp-2 text-xs leading-5 text-muted-foreground",children:["交付标准:",v.acceptance]}),I&&s.jsx("span",{className:"line-clamp-2 text-[11px] leading-5 text-muted-foreground",children:I}),n&&c&&s.jsxs("span",{className:"block text-[11px] leading-5 text-muted-foreground",children:["负责人:",N?c(v,N):"尚未分派"]})]}),s.jsx(Ys,{size:12,className:"mt-1 shrink-0 text-muted-foreground"})]},w.id)};return s.jsxs("section",{"aria-label":"执行事项",className:n?"border-t border-border/15 py-2":"mx-4 border-t border-border/15 py-2",children:[!n&&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:[x,"/",d.length," 项已完成"]})]}),(n?m.filter(w=>x===d.length||w.status!=="accepted"):m.slice(0,3)).map(y),n&&x>0&&x<d.length&&s.jsxs("details",{children:[s.jsxs("summary",{className:"min-h-11 cursor-pointer py-3 text-xs text-muted-foreground",children:["查看 ",x," 项已完成的执行交付"]}),m.filter(w=>w.status==="accepted").map(y)]}),!n&&m.length>3&&s.jsxs("details",{children:[s.jsxs("summary",{className:"min-h-11 cursor-pointer py-3 text-[11px] text-muted-foreground",children:["展开其余 ",m.length-3," 项"]}),m.slice(3).map(y)]})]})}function KO(e,t){const r=t.events.filter(f=>f.kind==="retry"&&!e.events.some(m=>m.id===f.id)).at(-1),n=new Set(e.deliveries.filter(f=>f.status==="delivered").map(f=>f.id)),a=new Set(e.outbox.filter(f=>!n.has(f.id)).map(f=>f.id)),c=r&&t.deliveries.some(f=>a.has(f.id)&&f.status==="delivered"&&f.deliveredAt!==null&&f.deliveredAt>=r.createdAt);let l=c?"重试请求已保存,匹配本次请求的投递已写入终端。":"重试请求已保存,服务将重新检查现有投递与协调条件。";!t.outbox.length&&!c&&(l+=" 当前没有待重试的投递记录。"),t.workflow?.paused&&(l+=" 后续自动安排仍已暂停。");const d=t.attempts.find(f=>f.id===t.activeAttemptId)?.report;return d&&["blocked","failed"].includes(d.status)&&(l+=" 成员原报告仍保留;请补齐条件并通知成员,收到新的明确回复后更新报告。"),l}function XO(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 qb(e){return new Date(e).toLocaleString([],{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1})}function Xf({task:e,now:t,compact:r=!1}){const n=qf(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:qb(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():XO(e.updatedAt,t),children:qb(e.updatedAt)})]}):"记录更新时间未提供"})]})}function b4(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 gf({inputKey:e,paneKey:t,label:r,value:n,onChange:a,active:c=!0,disabled:l=!1,required:d,autoFocus:f,placeholder:m,className:x,onUploadChange:y}){const w=b.useId(),v=b.useRef(null),T=b.useRef(null),S=b.useRef({value:n,onChange:a,onUploadChange:y});S.current={value:n,onChange:a,onUploadChange:y};const[I,N]=b.useState(0),[B,F]=b.useState(""),P=b.useRef(Promise.resolve());b.useEffect(()=>{const J=v.current;J&&J.setSelectionRange(J.value.length,J.value.length)},[e]);const $=()=>({value:S.current.value,start:v.current?.selectionStart??n.length,end:v.current?.selectionEnd??n.length}),ee=(J,Re=$())=>{S.current.onChange(Xe=>Xe!==Re.value?Xe+(Xe&&!/\s$/.test(Xe)?`
|
|
138
138
|
`:"")+J:Xe.slice(0,Re.start)+J+Xe.slice(Re.end))};b.useEffect(()=>{if(!c)return;const J=Xy(Re=>ee(Re.replace(/\r\n?/g,`
|
|
139
|
-
`)),e,!!t,t);return t||b0(e),J},[c,e,t]);const Z=()=>{const J=Hc();return`${location.origin}:${J?.targetPeerId??""}:${J?.serviceOrigin??""}`},V=J=>{const Re=$(),Xe=Z(),q=S.current.onUploadChange;F(""),N(ve=>ve+1),q?.(1),P.current=P.current.then(async()=>{try{if(Xe!==Z())throw new Error("目标服务已切换,请重新添加附件");const ve=await J();if(Xe!==Z())throw new Error("目标服务已切换,请重新添加附件");Array.isArray(ve)?ee(ve.map(Fu).join(" ")+" ",Re):ve&&ee(ve,Re)}catch(ve){const qe=ve instanceof Error?ve.message:"附件准备失败,请重试";F(qe.includes("Upload did not return")?"附件上传未返回完整路径,请重试":qe)}finally{N(ve=>ve-1),q?.(-1)}})},de=async J=>J.length===1&&J[0].type.startsWith("image/")?[await N3(J[0])]:j3(J),pe=J=>{const Re=J.clipboardData.files.length?Array.from(J.clipboardData.files):Array.from(J.clipboardData.items??[]).filter(ve=>ve.kind==="file").map(ve=>ve.getAsFile()).filter(ve=>ve!==null),Xe=J.clipboardData.getData("text/plain"),q=ea();!q?.readClipboardFiles&&!Re.length&&Xe||!q&&!Re.length&&typeof navigator.clipboard?.read!="function"||(J.preventDefault(),V(async()=>{const ve=Z();let qe;if(q?.readClipboardFiles)try{const ce=await M3();if(ce.paths.length||ce.files.length)return[...ce.paths,...await de(ce.files)]}catch(ce){if(ce instanceof w0)throw ce;qe=ce}if(ve!==Z())throw new Error("目标服务已切换,请重新粘贴");if(Re.length)return de(Re);if(Xe)return Xe;if(typeof navigator.clipboard?.read=="function"){const ce=await navigator.clipboard.read(),ye={read:async()=>ce},Te=await R3(ye);if(Te.length)return de(Te);const Fe=await If(ye);if(Fe)return de([Fe]);for(const se of ce)if(se.types.includes("text/plain"))return(await se.getType("text/plain")).text()}else{const ce=await If();if(ce)return de([ce])}if(qe)throw qe;return null}))};return s.jsxs("div",{className:"space-y-1.5",onFocusCapture:()=>b0(e),onPointerDownCapture:()=>b0(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:f,"aria-describedby":I||B?`${w}-status`:void 0,placeholder:m,className:x,onChange:J=>a(J.target.value),onPaste:pe,onDragOver:J=>{!l&&J.dataTransfer.types.includes("Files")&&J.preventDefault()},onDrop:J=>{const Re=Array.from(J.dataTransfer.files);!Re.length||l||(J.preventDefault(),J.stopPropagation(),V(()=>de(Re)))}}),s.jsxs("div",{className:"flex min-h-9 items-center gap-2",children:[s.jsx("input",{ref:T,type:"file",multiple:!0,hidden:!0,"aria-label":`选择附件:${r}`,onChange:J=>{const Re=Array.from(J.target.files??[]);J.target.value="",Re.length&&V(()=>de(Re))}}),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:()=>T.current?.click(),children:[s.jsx(gS,{size:14}),"附件"]}),I>0?s.jsxs("span",{id:`${w}-status`,role:"status",className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[s.jsx(wn,{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 Yb(e){return e.status!=="open"?"done":ta(e)||e.workflow?.paused?"attention":e.activeAttemptId?"running":"backlog"}const Dl=[{id:"backlog",label:"待开始",icon:V0,hint:"等待分派或依赖完成"},{id:"running",label:"执行中",icon:Sf,hint:"分派后的任务会出现在这里"},{id:"attention",label:"需要你",icon:ud,hint:"问题、方案与验收都在这里"},{id:"done",label:"已完成",icon:L0,hint:"验收后的结果会保留在这里"}];function JO({tasks:e,selectedId:t,onSelect:r,name:n,storage:a,action:c,navigation:l,settings:d}){const f=b.useRef(null),m=b.useRef(null),x=b.useRef("backlog"),y=b.useRef(0),w=b.useRef(null),[v,T]=b.useState(Date.now);b.useEffect(()=>iu(()=>T(Date.now()),3e4),[]);const[S,I]=b.useState(!1);b.useEffect(()=>{const z=new ResizeObserver(ie=>{const ge=ie[0].contentRect.width;I(ge>=760),ge!==y.current&&ge<760&&m.current&&(m.current.scrollLeft=Dl.findIndex(Ge=>Ge.id===x.current)*m.current.clientWidth),y.current=ge});return f.current&&z.observe(f.current),()=>z.disconnect()},[]);const[N]=b.useState(()=>{try{return JSON.parse(localStorage.getItem(`${a}:board`)??"null")}catch{return null}}),[B,F]=b.useState(()=>{if(Dl.some(ge=>ge.id===N?.lane))return N.lane;const ie=Vb(e,N?.showSteps===!0,N?.query??"").map(ge=>ge.attention?"attention":Yb(ge.task));return ie.includes("attention")?"attention":ie.includes("running")?"running":ie.includes("backlog")?"backlog":"done"});x.current=B;function P(z,ie=!0){F(z);const ge=m.current;if(!ge||!ge.clientWidth)return;w.current=z;const Ge=Dl.findIndex(vt=>vt.id===z)*ge.clientWidth,rt=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;ge.scrollTo?ge.scrollTo({left:Ge,behavior:ie&&!rt?"smooth":"auto"}):ge.scrollLeft=Ge}b.useEffect(()=>{S||P(x.current,!1)},[S]);const[$,ee]=b.useState(typeof N?.scope=="string"?N.scope:"all"),[Z,V]=b.useState(typeof N?.query=="string"?N.query:""),[de,pe]=b.useState(N?.closed===!0),[J,Re]=b.useState(N?.showSteps===!0),[Xe,q]=b.useState(!!N?.query),[ve,qe]=b.useState(!1),[ce,ye]=b.useState(!1),Te=b.useRef(null),Fe=b.useRef(null);b.useEffect(()=>{if(!ce)return;Te.current?.querySelector('[aria-label="看板更多操作"] button')?.focus();const z=ge=>{Te.current?.contains(ge.target)||ye(!1)},ie=ge=>{ge.key==="Escape"&&(ge.preventDefault(),ge.stopPropagation(),ye(!1),Fe.current?.focus())};return document.addEventListener("pointerdown",z),document.addEventListener("keydown",ie),()=>{document.removeEventListener("pointerdown",z),document.removeEventListener("keydown",ie)}},[ce]);const se=b.useRef(null),De=b.useRef(null),_e=b.useRef(null),Me=b.useRef(null);b.useEffect(()=>{Xe&&se.current?.focus()},[Xe]),b.useEffect(()=>{if(!ve)return;_e.current?.querySelector("select")?.focus();const z=ge=>{_e.current?.contains(ge.target)||qe(!1)},ie=ge=>{ge.key==="Escape"&&(ge.preventDefault(),ge.stopPropagation(),qe(!1),(S?Me:Fe).current?.focus())};return document.addEventListener("pointerdown",z),document.addEventListener("keydown",ie),()=>{document.removeEventListener("pointerdown",z),document.removeEventListener("keydown",ie)}},[ve]),b.useEffect(()=>{try{localStorage.setItem(`${a}:board`,JSON.stringify({lane:B,scope:$,query:Z,closed:de,showSteps:J}))}catch{}},[a,B,$,Z,de,J]);const Je=e.filter(z=>z.workflow?.kind==="goal"),Ne=Vb(e,J,Z),ae=new Map(Ne.map(z=>[z.task.id,z])),ze=z=>ae.get(z.id)?.attention?"attention":Yb(z),at=t?Ne.find(z=>z.task.id===t||z.children.some(ie=>ie.id===t)):void 0,ut=at?ze(at.task):void 0;b.useEffect(()=>{ut&&P(ut,!1)},[t,ut]);const me=Ne.map(z=>z.task).filter(z=>(de||z.status!=="closed")&&($==="all"||z.id===$||ae.get(z.id)?.rootId===$)&&(!Z.trim()||`${z.title} ${z.spec} ${z.attempts.map(ie=>n(z,ie.assignee)).join(" ")}`.toLocaleLowerCase().includes(Z.trim().toLocaleLowerCase()))),dt=+($!=="all")+Number(de)+Number(J),ft="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",Se="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 ${S?"flex-1 max-w-[240px]":"w-full"}`,children:[s.jsx("span",{className:"sr-only",children:"搜索任务"}),s.jsx(Wl,{"aria-hidden":"true",size:15,className:"pointer-events-none absolute left-3 text-muted-foreground"}),s.jsx("input",{ref:se,"aria-label":"搜索任务",type:"search",value:Z,onChange:z=>V(z.target.value),onKeyDown:z=>{z.key==="Escape"&&(z.preventDefault(),z.stopPropagation(),Z?V(""):(q(!1),requestAnimationFrame(()=>(S?De:Fe).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:()=>{V(""),q(!1),requestAnimationFrame(()=>(S?De:Fe).current?.focus())},children:s.jsx(Mn,{size:14})})]}),Le=s.jsxs("div",{"aria-label":"任务筛选",className:"absolute right-0 top-full z-30 mt-1 w-64 space-y-3 rounded-xl border border-border/30 bg-surface p-3 shadow-xl",children:[s.jsxs("label",{className:"block space-y-1 text-xs text-muted-foreground",children:[s.jsx("span",{children:"目标范围"}),s.jsxs("select",{"aria-label":"按目标查看",value:$,onChange:z=>ee(z.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:"所有目标"}),Je.map(z=>s.jsx("option",{value:z.id,children:z.title},z.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:de,onChange:z=>pe(z.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:J,onChange:z=>Re(z.target.checked)}),"显示执行子任务"]}),dt>0&&s.jsx("button",{type:"button",className:"min-h-11 w-full rounded-lg text-xs text-primary hover:bg-surface-2",onClick:()=>{ee("all"),pe(!1),Re(!1)},children:"清除筛选"})]});return s.jsxs("div",{ref:f,className:"flex min-h-0 min-w-0 flex-1 flex-col gap-2",children:[s.jsx("div",{ref:S?void 0:_e,"aria-label":"看板工具栏",className:"relative z-20 flex shrink-0 flex-wrap items-center gap-1.5 border-b border-border/15 pb-2",children:S?s.jsxs(s.Fragment,{children:[l&&s.jsx("div",{className:"flex min-w-0 items-center mr-auto",children:l}),Xe?We:s.jsx("button",{ref:De,type:"button","aria-label":"搜索任务",title:"搜索任务",className:`${ft} ${l?"":"ml-auto"}`,onClick:()=>q(!0),children:s.jsx(Wl,{size:16})}),s.jsxs("div",{ref:_e,className:"relative shrink-0",children:[s.jsxs("button",{ref:Me,type:"button","aria-label":dt?`筛选任务,${dt} 项已启用`:"筛选任务","aria-expanded":ve,className:`${ft} ${dt?"text-primary":""}`,onClick:()=>qe(z=>!z),children:[s.jsx(a1,{size:15}),s.jsx("span",{children:"筛选"}),dt>0&&s.jsx("span",{className:"tabular-nums text-primary",children:dt})]}),ve&&Le]}),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:Te,className:"relative shrink-0",children:[s.jsxs("button",{ref:Fe,type:"button","aria-label":"更多看板操作","aria-expanded":ce,className:`${ft} ${ce?"bg-surface-2 text-foreground":dt||Z.trim()?"text-primary":""}`,onClick:()=>{ye(z=>!z),qe(!1)},children:[s.jsx(Io,{size:18}),dt>0&&s.jsx("span",{className:"text-[10px]",children:dt})]}),ce&&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:De,type:"button","aria-label":"搜索任务",className:Se,onClick:()=>q(!0),children:[s.jsx(Wl,{size:18,className:"shrink-0 text-muted-foreground"}),"搜索任务"]}),s.jsxs("button",{ref:Me,type:"button","aria-label":dt?`筛选任务,${dt} 项已启用`:"筛选任务",className:Se,onClick:()=>qe(!0),children:[s.jsx(a1,{size:18,className:"shrink-0 text-muted-foreground"}),"筛选任务",dt>0&&s.jsx("span",{className:"ml-auto rounded bg-primary/10 px-1.5 text-xs tabular-nums text-primary",children:dt})]}),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})]})]}),Xe&&We,ve&&Le]})}),s.jsx("p",{className:"px-1 text-[11px] leading-5 text-muted-foreground",children:J?"包含执行子任务,可在筛选中切回目标视图。":"每张卡片对应一个目标,待完成事项和最近交付直接显示在卡片中。"}),s.jsx("nav",{hidden:S,"aria-label":"看板阶段",className:`${S?"hidden":"grid"} shrink-0 grid-cols-4 gap-1`,children:Dl.map(z=>s.jsxs("button",{type:"button","aria-pressed":B===z.id,className:`min-h-11 rounded-lg px-1 text-xs ${B===z.id?"bg-surface-2 text-foreground":"text-muted-foreground"}`,onClick:()=>P(z.id),children:[z.label,s.jsx("span",{className:"ml-1 tabular-nums",children:me.filter(ie=>ze(ie)===z.id).length})]},z.id))}),s.jsxs("div",{ref:S?void 0:m,"data-kanban-scroll":!0,onPointerDown:()=>{w.current=null},onWheel:()=>{w.current=null},"aria-label":S?void 0:"可左右滑动的任务看板",onScroll:S?void 0:z=>{if(z.target!==z.currentTarget||!z.currentTarget.clientWidth)return;const ie=w.current;if(ie){const Ge=Dl.findIndex(rt=>rt.id===ie)*z.currentTarget.clientWidth;if(Math.abs(z.currentTarget.scrollLeft-Ge)>2)return;w.current=null}const ge=Math.max(0,Math.min(Dl.length-1,Math.round(z.currentTarget.scrollLeft/z.currentTarget.clientWidth)));F(Dl[ge].id)},className:S?"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:[S&&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:Dl.map(z=>{const ie=z.icon;return s.jsxs("h4",{className:`flex items-center gap-2 px-3 py-2 text-[13px] font-medium ${z.id==="attention"?"text-primary":"text-muted-foreground"}`,children:[s.jsx(ie,{size:15}),z.label,s.jsx("span",{className:"ml-auto tabular-nums text-xs",children:me.filter(ge=>ze(ge)===z.id).length})]},z.id)})}),s.jsx("div",{className:S?"grid min-h-full min-w-[1000px] grid-cols-4 items-start gap-4 pt-2":"flex h-full",children:Dl.map(z=>{const ie=me.filter(ge=>ze(ge)===z.id).sort((ge,Ge)=>Ge.updatedAt-ge.updatedAt);return s.jsx("section",{"aria-label":`${z.label}任务`,"aria-hidden":!S&&B!==z.id?!0:void 0,ref:ge=>{ge&&(ge.inert=!S&&B!==z.id)},style:S?void 0:{width:"100%"},className:S?"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:[ie.map(ge=>{const Ge=ae.get(ge.id),rt=Ge.attention??ge,vt=rt.attempts.find($e=>$e.id===rt.activeAttemptId),Yt=rt.decisions.find($e=>$e.status==="pending"),Ut=ou(rt),Nt=m4(ge,Ge.children),ir=Ge.attention?Z1(rt):ge.workflow?.kind==="goal"?Nt.label:Z1(rt,Ge.children),Mt=gp(rt),Xt=Mt[0],Bt=Mt.find($e=>$e.source==="system"),Wt=Mt.find($e=>$e.source==="unknown"),xe=Bt?.content,et=z.id==="attention",ot=Yt?"回答问题":Wt?"查看详情核对记录":Xt?.source==="member"&&Bt?"查看条件与异常处理":Xt?.source==="member"?"查看阻塞并补充条件":xe?"查看原因与处理":Ut==="等待你验收"?"查看结果并验收":Ut==="需要你确认方案"?"查看并确认方案":"查看任务并处理",Et=rt.artifacts.filter($e=>$e.kind==="result"&&$e.attemptId===rt.activeAttemptId).at(-1),K=rt.events.filter($e=>$e.kind==="revise"&&$e.source==="user"&&$e.attemptId===rt.activeAttemptId&&(!Et||$e.createdAt>=Et.createdAt)).at(-1),xt=Yt?Yt.question||"成员提出了一个问题,打开后可查看并回答。":Xt?.summary||K?.content||(ge.workflow?.kind==="goal"&&!Ge.attention&&Nt.latest?Et?.summary||g4(Nt.latest):Et?.summary||(vt?.report?.content?b4(vt.report.content).summary:vt?.report?.summary||"")),rr=e.find($e=>$e.id===ge.parentTaskId);return s.jsxs("article",{"aria-label":ge.title,className:`overflow-hidden rounded-xl border bg-surface text-left shadow-sm ${t===ge.id?"border-primary/60":xe?"border-destructive/35":"border-border/20"}`,children:[s.jsxs("button",{type:"button","data-task-id":ge.id,"aria-pressed":t===ge.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(rt.id),children:[rr&&s.jsx("span",{className:"mb-2 block truncate text-[10px] text-muted-foreground",children:rr.title}),s.jsx("span",{title:ge.title,className:"block line-clamp-3 break-words text-sm font-medium leading-6 text-foreground",children:ge.title}),s.jsxs("span",{className:`mt-3 flex items-center gap-1.5 text-xs ${xe&&Xt?.source!=="member"?"text-destructive":et?"text-primary":"text-muted-foreground"}`,children:[xe&&Xt?.source!=="member"&&s.jsx(sg,{size:13,className:"shrink-0"}),ir]}),Ge.attention&&s.jsxs("span",{className:"mt-2 block truncate text-[11px] text-muted-foreground",children:["来自执行任务:",Ge.attention.title]}),Ge.attention&&Ge.attentionCount>1&&s.jsxs("span",{className:"mt-1 block text-[11px] text-primary",children:["共 ",Ge.attentionCount," 项执行需要你处理"]}),ge.workflow?.kind==="goal"&&!Ge.attention&&s.jsx("span",{className:"mt-2 block text-xs leading-5 text-muted-foreground",children:Nt.next}),xt&&s.jsx("span",{className:"mt-2 line-clamp-3 break-words text-xs leading-5 text-foreground/80",children:xt}),Bt&&Xt?.source==="member"&&s.jsxs("span",{className:"mt-2 block line-clamp-2 break-words text-xs leading-5 text-destructive",children:[Bt.label,":",Bt.summary]}),Wt&&s.jsxs("span",{className:"mt-2 block line-clamp-2 break-words text-xs leading-5 text-muted-foreground",children:[Wt.label,":",Wt.summary]}),et&&s.jsxs("span",{className:`mt-4 flex min-h-9 items-center justify-between rounded-lg px-2.5 text-xs font-medium ${xe?"bg-destructive/10 text-destructive":"bg-primary/10 text-primary"}`,children:[ot,s.jsx(ef,{size:14})]}),!et&&(ge.status==="accepted"||ge.artifacts.some($e=>$e.kind==="result"&&$e.attemptId===ge.activeAttemptId))&&s.jsxs("span",{className:"mt-3 flex min-h-9 items-center justify-between text-xs font-medium text-primary",children:[K?"查看跟进":"查看结果",s.jsx(ef,{size:14})]}),!et&&ge.workflow?.kind==="goal"&&!Et&&s.jsxs("span",{className:"mt-3 flex min-h-9 items-center justify-between text-xs font-medium text-primary",children:["查看拆分与进展",s.jsx(ef,{size:14})]})]}),s.jsx(x4,{task:ge,children:Ge.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:[Ge.attention?"待处理任务负责人:":ge.workflow?.kind==="goal"?"协调者:":"负责人:",vt?n(rt,vt.assignee):rt.scheduledAssignee?n(rt,rt.scheduledAssignee):"未分派"]}),ge.workflow?.kind==="goal"&&!et&&!Ge.attention&&Nt.latest?s.jsxs("time",{className:"mt-1 block text-[11px]",dateTime:new Date(Nt.latest.createdAt).toISOString(),children:[Nt.latest.source," · ",new Date(Nt.latest.createdAt).toLocaleString([],{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1})]}):s.jsx(Xf,{task:rt,now:v,compact:!0})]})]},ge.id)}),!ie.length&&s.jsx("p",{className:"px-2 py-3 text-xs leading-6 text-muted-foreground/70",children:Z||$!=="all"?"没有匹配的任务":e.length?"暂无任务":z.hint})]})},z.id)})})]})]})}const zl=vc((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 Hh(e,t){return r=>zl.getState().update(e,t,r)}function zm(e,t){return r=>zl.getState().updateDetail(e,t,r)}const eF=b.lazy(()=>Vc(()=>Promise.resolve().then(()=>OO),void 0).then(e=>({default:e.DirectoryPickerDialog}))),tF=b.lazy(()=>Vc(()=>import("./CollaborationTaskContent-BjjX05Cv.js"),__vite__mapDeps([6,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17]))),va="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",Us="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",vl=`${va} bg-primary text-primary-foreground`,si=`${va} bg-surface-2 text-foreground hover:bg-surface-2/80`,rF={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:"请求重新检查"},Ju=e=>`${e.serviceId}:${e.sessionId}`,ga=e=>new Date(e).toLocaleString([],{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit"});function To(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 Xi(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch{}}const m0={mode:"goal",isolated:!0,title:"",spec:"",constraints:"",acceptance:"",assignee:"",coordinator:"",parent:"",dependencies:[]},Zb="__new_coordinator__";function nF(e){const t={...m0,...To(e,m0)};return!t||!Array.isArray(t.dependencies)||t.dependencies.some(r=>typeof r!="string")||Object.keys(m0).some(r=>!["dependencies","isolated"].includes(r)&&typeof t[r]!="string")?m0:{...t,mode:t.mode==="task"?"task":"goal",isolated:t.isolated!==!1}}function y4(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 sF({group:e,sessions:t,active:r,onOpenSession:n,onAttentionChange:a,onManageMembers:c,board:l=!1,boardNavigation:d,boardSettings:f,paneKey:m,agents:x=[],defaultCwd:y,onTeamReady:w}){const v=`termdock:tasks:${location.origin}:${e.id}`,[T,S]=b.useState([]),I=b.useRef(T);I.current=T;const[N,B]=b.useState(null),[F]=b.useState(()=>zl.getState().ensure(v,{draft:nF(`${v}:draft`),selectedId:To(`${v}:selected`,null),creating:!1,mobileDetail:!1})),{selectedId:P,mobileDetail:$,creating:ee,draft:Z}=zl(ne=>ne.views[v]??F),V=Hh(v,"selectedId"),de=Hh(v,"mobileDetail"),pe=Hh(v,"creating"),J=Hh(v,"draft"),[Re,Xe]=b.useState(!1),[q,ve]=b.useState(!1),qe=b.useRef(null),ce=b.useRef(null),ye=b.useRef(!1),Te=b.useCallback(ne=>{!ne&&ce.current===document.activeElement&&(ye.current=!0),ce.current=ne,ne&&ye.current&&(ye.current=!1,ne.focus())},[]);b.useEffect(()=>{const ne=qe.current;if(!ne)return;const Ze=new ResizeObserver(Dt=>Xe(Dt[0].contentRect.width>=(l?1100:760)));return Ze.observe(ne),()=>Ze.disconnect()},[l]);const[Fe,se]=b.useState(!1),[De,_e]=b.useState(null),Me=Jy(),[Je,Ne]=b.useState(0),[ae,ze]=b.useState(null),[at,ut]=b.useState(!1),[me,dt]=b.useState(0),ft=ne=>dt(Ze=>Math.max(0,Ze+ne)),[Se,We]=b.useState("");b.useEffect(()=>{if(!Se)return;const ne=setTimeout(()=>We(""),5e3);return()=>clearTimeout(ne)},[Se]);const[Le,z]=b.useState("open"),[ie,ge]=b.useState(""),Ge=b.useRef(!1),rt=b.useRef(!0),vt=b.useRef(new Map),Yt=b.useRef(!1),Ut=e.sessionIds.flatMap(ne=>{const Ze=t.find(Dt=>Dt.sessionId===ne);return Ze?[Ze]:[]}),Nt=Ut.map(ne=>({...ne,name:Uu(ne,Ut)})),ir=Z.coordinator===Zb,Mt=Z.coordinator||To(`${v}:lead`,""),Xt=Nt.find(ne=>ne.sessionId===Z.coordinator&&ne.agent),Bt=!!Z.coordinator&&!ir&&!Xt,Wt=ir||Bt?"":Xt?.sessionId||Nt.find(ne=>ne.sessionId===Mt&&ne.agent)?.sessionId||Nt.find(ne=>ne.agent)?.sessionId||"",xe=Nt.filter(ne=>ne.sessionId!==Wt&&ne.agent).map(ne=>ne.sessionId),[et,ot]=b.useState(!1),[Et,K]=b.useState(!1),[xt,rr]=b.useState(()=>To(`${v}:agent`,"")),[$e,Dr]=b.useState(()=>To(`${v}:launch-profile`,e.defaultLaunchProfileId??"")),Ce=e.launchProfiles?.find(ne=>ne.id===$e),St=Nt.flatMap(ne=>ne.agent&&x.some(Ze=>Ze.slug===ne.agent.slug)?[ne.agent.slug]:[]),Ot=[...new Set(St)].sort((ne,Ze)=>St.filter(Dt=>Dt===Ze).length-St.filter(Dt=>Dt===ne).length)[0],tr=x.find(ne=>ne.slug===Xt?.agent?.slug)?.slug??Ot??x[0]?.slug??"",ct=Ce?.agentSlug??(xt||tr),[Ct,or]=b.useState(()=>To(`${v}:cwd`,Nt[0]?.cwd??y??"")),Cr=!Nt.find(ne=>ne.sessionId===Wt)?.agent||!xe.length,[Ir,$r]=b.useState(null),Tt=!!Z.spec.trim()&&(!!Ir||!Bt&&(!Cr||!e.federated&&(!$e||!!Ce)&&!!x.find(ne=>ne.slug===ct)&&!!Ct.trim())),Ft=T.find(ne=>ne.id===P)??null,we=N?.id===P?N:null;b.useEffect(()=>(rt.current=!0,()=>{rt.current=!1}),[]),b.useEffect(()=>{Xi(`${v}:draft`,Z)},[v,Z]),b.useEffect(()=>{Xi(`${v}:selected`,P)},[v,P]),b.useEffect(()=>{const ne=Dt=>{const ur=Dt.detail;ur?.groupId===e.id&&(Xi(`${v}:open-task`,null),V(ur.taskId),de(!0),pe(!1),z("all"),wt())};window.addEventListener("open-collaboration-task",ne);const Ze=To(`${v}:open-task`,null);return Ze&&(V(Ze),de(!0),z("all"),Xi(`${v}:open-task`,null)),()=>window.removeEventListener("open-collaboration-task",ne)},[e.id]),b.useEffect(()=>{if(!r||!Ft||N?.id===Ft.id&&N.revision===Ft.revision)return;let ne=!1;return e9(Ft.id).then(Ze=>{ne||(B(Ze.task),_e(null))}).catch(Ze=>{ne||_e(Ze instanceof Error?Ze.message:"任务详情加载失败")}),()=>{ne=!0}},[r,Ft?.id,Ft?.revision,N?.id,N?.revision,Je]);const wt=async()=>{if(!Yt.current){Yt.current=!0;try{const ne=await Yy(e.id);rt.current&&(S(ne.tasks),se(!0),_e(null),Ne(Ze=>Ze+1))}catch(ne){rt.current&&_e(ne instanceof Error?ne.message:"任务加载失败")}finally{Yt.current=!1}}};b.useEffect(()=>{if(r)return iu(()=>{navigator.onLine!==!1&&wt()},2500,[k0,"pageshow"])},[r,e.id]);const it=ne=>{const Ze=JSON.stringify(ne),Dt=To(`${v}:request`,null);let ur=vt.current.get(Ze)??(Dt?.fingerprint===Ze?Dt.key:void 0);return ur||(ur=crypto.randomUUID(),vt.current.set(Ze,ur)),Xi(`${v}:request`,{fingerprint:Ze,key:ur}),ur},bt=ne=>{vt.current.delete(JSON.stringify(ne)),Xi(`${v}:request`,null)},An=async(ne,Ze)=>{if(at||Ge.current)return{ok:!1,error:"已有操作正在提交,请稍候。"};Ge.current=!0,ut(!0),ze(null),We("");let Dt={...Ze,expectedRevision:ne.revision};if(["comment","revise"].includes(Ze.kind)){const ur=To(`${v}:request`,null);try{const[Pr,qr]=JSON.parse(ur?.fingerprint??"null"),{expectedRevision:sn,...Nr}=qr;Pr===ne.id&&JSON.stringify(Nr)===JSON.stringify(Ze)&&(Dt=qr)}catch{}}try{const ur=await n9(ne.id,{...Dt,idempotencyKey:it([ne.id,Dt])});if(bt([ne.id,Dt]),Ou.getState().refresh(),rt.current){const Pr=I.current.find(Wr=>Wr.id===ur.task.id),qr=Pr&&Pr.revision>ur.task.revision?Pr:ur.task;S(Wr=>Wr.map(_n=>_n.id===ur.task.id&&_n.revision<=ur.task.revision?ur.task:_n)),B(Wr=>Wr?.id===ur.task.id&&Wr.revision>ur.task.revision?Wr:ur.task);const sn=y4(qr,I.current),Nr=`${Ze.kind==="answer"?"回答已保存":"方案确认已保存"},${sn?sn.workflow?.kind==="goal"?"目标仍暂停;恢复目标后才能投递。":"任务仍暂停;继续安排后才能投递。":"投递状态请查看任务记录。"}`;We(["comment","revise"].includes(Ze.kind)?"":Ze.kind==="retry"?KO(ne,ur.task):["answer","approve-plan"].includes(Ze.kind)?Nr:Ze.kind==="accept"?"已验收此版本结果。":"记录已保存。")}return{ok:!0}}catch(ur){const Pr=ur instanceof Error?ur.message:"操作失败";return Pr.includes("任务已更新")&&bt([ne.id,Dt]),rt.current&&(ze(["comment","revise"].includes(Ze.kind)?null:Pr),wt()),{ok:!1,error:Pr}}finally{Ge.current=!1,rt.current&&ut(!1)}},xn=async ne=>{if(ne.preventDefault(),at||me>0||(Z.mode==="goal"?!Tt:!Z.title.trim()||!Z.spec.trim())||Ge.current)return;Ge.current=!0,ut(!0),ze(null);const Ze=Z.mode==="goal",Dt={groupId:e.id,title:Z.title.trim()||Z.spec.trim().split(`
|
|
139
|
+
`)),e,!!t,t);return t||b0(e),J},[c,e,t]);const Z=()=>{const J=Hc();return`${location.origin}:${J?.targetPeerId??""}:${J?.serviceOrigin??""}`},V=J=>{const Re=$(),Xe=Z(),q=S.current.onUploadChange;F(""),N(ve=>ve+1),q?.(1),P.current=P.current.then(async()=>{try{if(Xe!==Z())throw new Error("目标服务已切换,请重新添加附件");const ve=await J();if(Xe!==Z())throw new Error("目标服务已切换,请重新添加附件");Array.isArray(ve)?ee(ve.map(Fu).join(" ")+" ",Re):ve&&ee(ve,Re)}catch(ve){const qe=ve instanceof Error?ve.message:"附件准备失败,请重试";F(qe.includes("Upload did not return")?"附件上传未返回完整路径,请重试":qe)}finally{N(ve=>ve-1),q?.(-1)}})},de=async J=>J.length===1&&J[0].type.startsWith("image/")?[await N3(J[0])]:j3(J),pe=J=>{const Re=J.clipboardData.files.length?Array.from(J.clipboardData.files):Array.from(J.clipboardData.items??[]).filter(ve=>ve.kind==="file").map(ve=>ve.getAsFile()).filter(ve=>ve!==null),Xe=J.clipboardData.getData("text/plain"),q=ea();!q?.readClipboardFiles&&!Re.length&&Xe||!q&&!Re.length&&typeof navigator.clipboard?.read!="function"||(J.preventDefault(),V(async()=>{const ve=Z();let qe;if(q?.readClipboardFiles)try{const ce=await M3();if(ce.paths.length||ce.files.length)return[...ce.paths,...await de(ce.files)]}catch(ce){if(ce instanceof w0)throw ce;qe=ce}if(ve!==Z())throw new Error("目标服务已切换,请重新粘贴");if(Re.length)return de(Re);if(Xe)return Xe;if(typeof navigator.clipboard?.read=="function"){const ce=await navigator.clipboard.read(),ye={read:async()=>ce},Te=await R3(ye);if(Te.length)return de(Te);const Fe=await If(ye);if(Fe)return de([Fe]);for(const se of ce)if(se.types.includes("text/plain"))return(await se.getType("text/plain")).text()}else{const ce=await If();if(ce)return de([ce])}if(qe)throw qe;return null}))};return s.jsxs("div",{className:"space-y-1.5",onFocusCapture:()=>b0(e),onPointerDownCapture:()=>b0(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:f,"aria-describedby":I||B?`${w}-status`:void 0,placeholder:m,className:x,onChange:J=>a(J.target.value),onPaste:pe,onDragOver:J=>{!l&&J.dataTransfer.types.includes("Files")&&J.preventDefault()},onDrop:J=>{const Re=Array.from(J.dataTransfer.files);!Re.length||l||(J.preventDefault(),J.stopPropagation(),V(()=>de(Re)))}}),s.jsxs("div",{className:"flex min-h-9 items-center gap-2",children:[s.jsx("input",{ref:T,type:"file",multiple:!0,hidden:!0,"aria-label":`选择附件:${r}`,onChange:J=>{const Re=Array.from(J.target.files??[]);J.target.value="",Re.length&&V(()=>de(Re))}}),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:()=>T.current?.click(),children:[s.jsx(gS,{size:14}),"附件"]}),I>0?s.jsxs("span",{id:`${w}-status`,role:"status",className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[s.jsx(wn,{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 Yb(e){return e.status!=="open"?"done":ta(e)||e.workflow?.paused?"attention":e.activeAttemptId?"running":"backlog"}const Dl=[{id:"backlog",label:"待开始",icon:V0,hint:"等待分派或依赖完成"},{id:"running",label:"执行中",icon:Sf,hint:"分派后的任务会出现在这里"},{id:"attention",label:"需要你",icon:ud,hint:"问题、方案与验收都在这里"},{id:"done",label:"已完成",icon:L0,hint:"验收后的结果会保留在这里"}];function JO({tasks:e,selectedId:t,onSelect:r,name:n,storage:a,action:c,navigation:l,settings:d}){const f=b.useRef(null),m=b.useRef(null),x=b.useRef("backlog"),y=b.useRef(0),w=b.useRef(null),[v,T]=b.useState(Date.now);b.useEffect(()=>iu(()=>T(Date.now()),3e4),[]);const[S,I]=b.useState(!1);b.useEffect(()=>{const z=new ResizeObserver(ie=>{const ge=ie[0].contentRect.width;I(ge>=760),ge!==y.current&&ge<760&&m.current&&(m.current.scrollLeft=Dl.findIndex(Ge=>Ge.id===x.current)*m.current.clientWidth),y.current=ge});return f.current&&z.observe(f.current),()=>z.disconnect()},[]);const[N]=b.useState(()=>{try{return JSON.parse(localStorage.getItem(`${a}:board`)??"null")}catch{return null}}),[B,F]=b.useState(()=>{if(Dl.some(ge=>ge.id===N?.lane))return N.lane;const ie=Vb(e,N?.showSteps===!0,N?.query??"").map(ge=>ge.attention?"attention":Yb(ge.task));return ie.includes("attention")?"attention":ie.includes("running")?"running":ie.includes("backlog")?"backlog":"done"});x.current=B;function P(z,ie=!0){F(z);const ge=m.current;if(!ge||!ge.clientWidth)return;w.current=z;const Ge=Dl.findIndex(vt=>vt.id===z)*ge.clientWidth,rt=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;ge.scrollTo?ge.scrollTo({left:Ge,behavior:ie&&!rt?"smooth":"auto"}):ge.scrollLeft=Ge}b.useEffect(()=>{S||P(x.current,!1)},[S]);const[$,ee]=b.useState(typeof N?.scope=="string"?N.scope:"all"),[Z,V]=b.useState(typeof N?.query=="string"?N.query:""),[de,pe]=b.useState(N?.closed===!0),[J,Re]=b.useState(N?.showSteps===!0),[Xe,q]=b.useState(!!N?.query),[ve,qe]=b.useState(!1),[ce,ye]=b.useState(!1),Te=b.useRef(null),Fe=b.useRef(null);b.useEffect(()=>{if(!ce)return;Te.current?.querySelector('[aria-label="看板更多操作"] button')?.focus();const z=ge=>{Te.current?.contains(ge.target)||ye(!1)},ie=ge=>{ge.key==="Escape"&&(ge.preventDefault(),ge.stopPropagation(),ye(!1),Fe.current?.focus())};return document.addEventListener("pointerdown",z),document.addEventListener("keydown",ie),()=>{document.removeEventListener("pointerdown",z),document.removeEventListener("keydown",ie)}},[ce]);const se=b.useRef(null),De=b.useRef(null),_e=b.useRef(null),Me=b.useRef(null);b.useEffect(()=>{Xe&&se.current?.focus()},[Xe]),b.useEffect(()=>{if(!ve)return;_e.current?.querySelector("select")?.focus();const z=ge=>{_e.current?.contains(ge.target)||qe(!1)},ie=ge=>{ge.key==="Escape"&&(ge.preventDefault(),ge.stopPropagation(),qe(!1),(S?Me:Fe).current?.focus())};return document.addEventListener("pointerdown",z),document.addEventListener("keydown",ie),()=>{document.removeEventListener("pointerdown",z),document.removeEventListener("keydown",ie)}},[ve]),b.useEffect(()=>{try{localStorage.setItem(`${a}:board`,JSON.stringify({lane:B,scope:$,query:Z,closed:de,showSteps:J}))}catch{}},[a,B,$,Z,de,J]);const Je=e.filter(z=>z.workflow?.kind==="goal"),Ne=Vb(e,J,Z),ae=new Map(Ne.map(z=>[z.task.id,z])),ze=z=>ae.get(z.id)?.attention?"attention":Yb(z),at=t?Ne.find(z=>z.task.id===t||z.children.some(ie=>ie.id===t)):void 0,ut=at?ze(at.task):void 0;b.useEffect(()=>{ut&&P(ut,!1)},[t,ut]);const me=Ne.map(z=>z.task).filter(z=>(de||z.status!=="closed")&&($==="all"||z.id===$||ae.get(z.id)?.rootId===$)&&(!Z.trim()||`${z.title} ${z.spec} ${z.attempts.map(ie=>n(z,ie.assignee)).join(" ")}`.toLocaleLowerCase().includes(Z.trim().toLocaleLowerCase()))),dt=+($!=="all")+Number(de)+Number(J),ft="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",Se="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 ${S?"flex-1 max-w-[240px]":"w-full"}`,children:[s.jsx("span",{className:"sr-only",children:"搜索任务"}),s.jsx(Wl,{"aria-hidden":"true",size:15,className:"pointer-events-none absolute left-3 text-muted-foreground"}),s.jsx("input",{ref:se,"aria-label":"搜索任务",type:"search",value:Z,onChange:z=>V(z.target.value),onKeyDown:z=>{z.key==="Escape"&&(z.preventDefault(),z.stopPropagation(),Z?V(""):(q(!1),requestAnimationFrame(()=>(S?De:Fe).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:()=>{V(""),q(!1),requestAnimationFrame(()=>(S?De:Fe).current?.focus())},children:s.jsx(Mn,{size:14})})]}),Le=s.jsxs("div",{"aria-label":"任务筛选",className:"absolute right-0 top-full z-30 mt-1 w-64 space-y-3 rounded-xl border border-border/30 bg-surface p-3 shadow-xl",children:[s.jsxs("label",{className:"block space-y-1 text-xs text-muted-foreground",children:[s.jsx("span",{children:"目标范围"}),s.jsxs("select",{"aria-label":"按目标查看",value:$,onChange:z=>ee(z.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:"所有目标"}),Je.map(z=>s.jsx("option",{value:z.id,children:z.title},z.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:de,onChange:z=>pe(z.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:J,onChange:z=>Re(z.target.checked)}),"显示执行子任务"]}),dt>0&&s.jsx("button",{type:"button",className:"min-h-11 w-full rounded-lg text-xs text-primary hover:bg-surface-2",onClick:()=>{ee("all"),pe(!1),Re(!1)},children:"清除筛选"})]});return s.jsxs("div",{ref:f,className:"flex min-h-0 min-w-0 flex-1 flex-col gap-2",children:[s.jsx("div",{ref:S?void 0:_e,"aria-label":"看板工具栏",className:"relative z-20 flex shrink-0 flex-wrap items-center gap-1.5 border-b border-border/15 pb-2",children:S?s.jsxs(s.Fragment,{children:[l&&s.jsx("div",{className:"flex min-w-0 items-center mr-auto",children:l}),Xe?We:s.jsx("button",{ref:De,type:"button","aria-label":"搜索任务",title:"搜索任务",className:`${ft} ${l?"":"ml-auto"}`,onClick:()=>q(!0),children:s.jsx(Wl,{size:16})}),s.jsxs("div",{ref:_e,className:"relative shrink-0",children:[s.jsxs("button",{ref:Me,type:"button","aria-label":dt?`筛选任务,${dt} 项已启用`:"筛选任务","aria-expanded":ve,className:`${ft} ${dt?"text-primary":""}`,onClick:()=>qe(z=>!z),children:[s.jsx(a1,{size:15}),s.jsx("span",{children:"筛选"}),dt>0&&s.jsx("span",{className:"tabular-nums text-primary",children:dt})]}),ve&&Le]}),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:Te,className:"relative shrink-0",children:[s.jsxs("button",{ref:Fe,type:"button","aria-label":"更多看板操作","aria-expanded":ce,className:`${ft} ${ce?"bg-surface-2 text-foreground":dt||Z.trim()?"text-primary":""}`,onClick:()=>{ye(z=>!z),qe(!1)},children:[s.jsx(Io,{size:18}),dt>0&&s.jsx("span",{className:"text-[10px]",children:dt})]}),ce&&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:De,type:"button","aria-label":"搜索任务",className:Se,onClick:()=>q(!0),children:[s.jsx(Wl,{size:18,className:"shrink-0 text-muted-foreground"}),"搜索任务"]}),s.jsxs("button",{ref:Me,type:"button","aria-label":dt?`筛选任务,${dt} 项已启用`:"筛选任务",className:Se,onClick:()=>qe(!0),children:[s.jsx(a1,{size:18,className:"shrink-0 text-muted-foreground"}),"筛选任务",dt>0&&s.jsx("span",{className:"ml-auto rounded bg-primary/10 px-1.5 text-xs tabular-nums text-primary",children:dt})]}),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})]})]}),Xe&&We,ve&&Le]})}),s.jsx("p",{className:"px-1 text-[11px] leading-5 text-muted-foreground",children:J?"包含执行子任务,可在筛选中切回目标视图。":"每张卡片对应一个目标,待完成事项和最近交付直接显示在卡片中。"}),s.jsx("nav",{hidden:S,"aria-label":"看板阶段",className:`${S?"hidden":"grid"} shrink-0 grid-cols-4 gap-1`,children:Dl.map(z=>s.jsxs("button",{type:"button","aria-pressed":B===z.id,className:`min-h-11 rounded-lg px-1 text-xs ${B===z.id?"bg-surface-2 text-foreground":"text-muted-foreground"}`,onClick:()=>P(z.id),children:[z.label,s.jsx("span",{className:"ml-1 tabular-nums",children:me.filter(ie=>ze(ie)===z.id).length})]},z.id))}),s.jsxs("div",{ref:S?void 0:m,"data-kanban-scroll":!0,onPointerDown:()=>{w.current=null},onWheel:()=>{w.current=null},"aria-label":S?void 0:"可左右滑动的任务看板",onScroll:S?void 0:z=>{if(z.target!==z.currentTarget||!z.currentTarget.clientWidth)return;const ie=w.current;if(ie){const Ge=Dl.findIndex(rt=>rt.id===ie)*z.currentTarget.clientWidth;if(Math.abs(z.currentTarget.scrollLeft-Ge)>2)return;w.current=null}const ge=Math.max(0,Math.min(Dl.length-1,Math.round(z.currentTarget.scrollLeft/z.currentTarget.clientWidth)));F(Dl[ge].id)},className:S?"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:[S&&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:Dl.map(z=>{const ie=z.icon;return s.jsxs("h4",{className:`flex items-center gap-2 px-3 py-2 text-[13px] font-medium ${z.id==="attention"?"text-primary":"text-muted-foreground"}`,children:[s.jsx(ie,{size:15}),z.label,s.jsx("span",{className:"ml-auto tabular-nums text-xs",children:me.filter(ge=>ze(ge)===z.id).length})]},z.id)})}),s.jsx("div",{className:S?"grid min-h-full min-w-[1000px] grid-cols-4 items-start gap-4 pt-2":"flex h-full",children:Dl.map(z=>{const ie=me.filter(ge=>ze(ge)===z.id).sort((ge,Ge)=>Ge.updatedAt-ge.updatedAt);return s.jsx("section",{"aria-label":`${z.label}任务`,"aria-hidden":!S&&B!==z.id?!0:void 0,ref:ge=>{ge&&(ge.inert=!S&&B!==z.id)},style:S?void 0:{width:"100%"},className:S?"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:[ie.map(ge=>{const Ge=ae.get(ge.id),rt=Ge.attention??ge,vt=rt.attempts.find($e=>$e.id===rt.activeAttemptId),Yt=rt.decisions.find($e=>$e.status==="pending"),Ut=ou(rt),Nt=m4(ge,Ge.children),ir=Ge.attention?Z1(rt):ge.workflow?.kind==="goal"?Nt.label:Z1(rt,Ge.children),Mt=gp(rt),Xt=Mt[0],Bt=Mt.find($e=>$e.source==="system"),Wt=Mt.find($e=>$e.source==="unknown"),xe=Bt?.content,et=z.id==="attention",ot=Yt?"回答问题":Wt?"查看详情核对记录":Xt?.source==="member"&&Bt?"查看条件与异常处理":Xt?.source==="member"?"查看阻塞并补充条件":xe?"查看原因与处理":Ut==="等待你验收"?"查看结果并验收":Ut==="需要你确认方案"?"查看并确认方案":"查看任务并处理",Et=rt.artifacts.filter($e=>$e.kind==="result"&&$e.attemptId===rt.activeAttemptId).at(-1),K=rt.events.filter($e=>$e.kind==="revise"&&$e.source==="user"&&$e.attemptId===rt.activeAttemptId&&(!Et||$e.createdAt>=Et.createdAt)).at(-1),xt=Yt?Yt.question||"成员提出了一个问题,打开后可查看并回答。":Xt?.summary||K?.content||(ge.workflow?.kind==="goal"&&!Ge.attention&&Nt.latest?Et?.summary||g4(Nt.latest):Et?.summary||(vt?.report?.content?b4(vt.report.content).summary:vt?.report?.summary||"")),rr=e.find($e=>$e.id===ge.parentTaskId);return s.jsxs("article",{"aria-label":ge.title,className:`overflow-hidden rounded-xl border bg-surface text-left shadow-sm ${t===ge.id?"border-primary/60":xe?"border-destructive/35":"border-border/20"}`,children:[s.jsxs("button",{type:"button","data-task-id":ge.id,"aria-pressed":t===ge.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(rt.id),children:[rr&&s.jsx("span",{className:"mb-2 block truncate text-[10px] text-muted-foreground",children:rr.title}),s.jsx("span",{title:ge.title,className:"block line-clamp-3 break-words text-sm font-medium leading-6 text-foreground",children:ge.title}),s.jsxs("span",{className:`mt-3 flex items-center gap-1.5 text-xs ${xe&&Xt?.source!=="member"?"text-destructive":et?"text-primary":"text-muted-foreground"}`,children:[xe&&Xt?.source!=="member"&&s.jsx(sg,{size:13,className:"shrink-0"}),ir]}),Ge.attention&&s.jsxs("span",{className:"mt-2 block truncate text-[11px] text-muted-foreground",children:["来自执行任务:",Ge.attention.title]}),Ge.attention&&Ge.attentionCount>1&&s.jsxs("span",{className:"mt-1 block text-[11px] text-primary",children:["共 ",Ge.attentionCount," 项执行需要你处理"]}),ge.workflow?.kind==="goal"&&!Ge.attention&&s.jsx("span",{className:"mt-2 block text-xs leading-5 text-muted-foreground",children:Nt.next}),xt&&s.jsx("span",{className:"mt-2 line-clamp-3 break-words text-xs leading-5 text-foreground/80",children:xt}),Bt&&Xt?.source==="member"&&s.jsxs("span",{className:"mt-2 block line-clamp-2 break-words text-xs leading-5 text-destructive",children:[Bt.label,":",Bt.summary]}),Wt&&s.jsxs("span",{className:"mt-2 block line-clamp-2 break-words text-xs leading-5 text-muted-foreground",children:[Wt.label,":",Wt.summary]}),et&&s.jsxs("span",{className:`mt-4 flex min-h-9 items-center justify-between rounded-lg px-2.5 text-xs font-medium ${xe?"bg-destructive/10 text-destructive":"bg-primary/10 text-primary"}`,children:[ot,s.jsx(ef,{size:14})]}),!et&&(ge.status==="accepted"||ge.artifacts.some($e=>$e.kind==="result"&&$e.attemptId===ge.activeAttemptId))&&s.jsxs("span",{className:"mt-3 flex min-h-9 items-center justify-between text-xs font-medium text-primary",children:[K?"查看跟进":"查看结果",s.jsx(ef,{size:14})]}),!et&&ge.workflow?.kind==="goal"&&!Et&&s.jsxs("span",{className:"mt-3 flex min-h-9 items-center justify-between text-xs font-medium text-primary",children:["查看拆分与进展",s.jsx(ef,{size:14})]})]}),s.jsx(x4,{task:ge,children:Ge.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:[Ge.attention?"待处理任务负责人:":ge.workflow?.kind==="goal"?"协调者:":"负责人:",vt?n(rt,vt.assignee):rt.scheduledAssignee?n(rt,rt.scheduledAssignee):"未分派"]}),ge.workflow?.kind==="goal"&&!et&&!Ge.attention&&Nt.latest?s.jsxs("time",{className:"mt-1 block text-[11px]",dateTime:new Date(Nt.latest.createdAt).toISOString(),children:[Nt.latest.source," · ",new Date(Nt.latest.createdAt).toLocaleString([],{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1})]}):s.jsx(Xf,{task:rt,now:v,compact:!0})]})]},ge.id)}),!ie.length&&s.jsx("p",{className:"px-2 py-3 text-xs leading-6 text-muted-foreground/70",children:Z||$!=="all"?"没有匹配的任务":e.length?"暂无任务":z.hint})]})},z.id)})})]})]})}const zl=vc((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 Hh(e,t){return r=>zl.getState().update(e,t,r)}function zm(e,t){return r=>zl.getState().updateDetail(e,t,r)}const eF=b.lazy(()=>Vc(()=>Promise.resolve().then(()=>OO),void 0).then(e=>({default:e.DirectoryPickerDialog}))),tF=b.lazy(()=>Vc(()=>import("./CollaborationTaskContent-DatXl2k_.js"),__vite__mapDeps([6,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17]))),va="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",Us="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",vl=`${va} bg-primary text-primary-foreground`,si=`${va} bg-surface-2 text-foreground hover:bg-surface-2/80`,rF={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:"请求重新检查"},Ju=e=>`${e.serviceId}:${e.sessionId}`,ga=e=>new Date(e).toLocaleString([],{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit"});function To(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 Xi(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch{}}const m0={mode:"goal",isolated:!0,title:"",spec:"",constraints:"",acceptance:"",assignee:"",coordinator:"",parent:"",dependencies:[]},Zb="__new_coordinator__";function nF(e){const t={...m0,...To(e,m0)};return!t||!Array.isArray(t.dependencies)||t.dependencies.some(r=>typeof r!="string")||Object.keys(m0).some(r=>!["dependencies","isolated"].includes(r)&&typeof t[r]!="string")?m0:{...t,mode:t.mode==="task"?"task":"goal",isolated:t.isolated!==!1}}function y4(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 sF({group:e,sessions:t,active:r,onOpenSession:n,onAttentionChange:a,onManageMembers:c,board:l=!1,boardNavigation:d,boardSettings:f,paneKey:m,agents:x=[],defaultCwd:y,onTeamReady:w}){const v=`termdock:tasks:${location.origin}:${e.id}`,[T,S]=b.useState([]),I=b.useRef(T);I.current=T;const[N,B]=b.useState(null),[F]=b.useState(()=>zl.getState().ensure(v,{draft:nF(`${v}:draft`),selectedId:To(`${v}:selected`,null),creating:!1,mobileDetail:!1})),{selectedId:P,mobileDetail:$,creating:ee,draft:Z}=zl(ne=>ne.views[v]??F),V=Hh(v,"selectedId"),de=Hh(v,"mobileDetail"),pe=Hh(v,"creating"),J=Hh(v,"draft"),[Re,Xe]=b.useState(!1),[q,ve]=b.useState(!1),qe=b.useRef(null),ce=b.useRef(null),ye=b.useRef(!1),Te=b.useCallback(ne=>{!ne&&ce.current===document.activeElement&&(ye.current=!0),ce.current=ne,ne&&ye.current&&(ye.current=!1,ne.focus())},[]);b.useEffect(()=>{const ne=qe.current;if(!ne)return;const Ze=new ResizeObserver(Dt=>Xe(Dt[0].contentRect.width>=(l?1100:760)));return Ze.observe(ne),()=>Ze.disconnect()},[l]);const[Fe,se]=b.useState(!1),[De,_e]=b.useState(null),Me=Jy(),[Je,Ne]=b.useState(0),[ae,ze]=b.useState(null),[at,ut]=b.useState(!1),[me,dt]=b.useState(0),ft=ne=>dt(Ze=>Math.max(0,Ze+ne)),[Se,We]=b.useState("");b.useEffect(()=>{if(!Se)return;const ne=setTimeout(()=>We(""),5e3);return()=>clearTimeout(ne)},[Se]);const[Le,z]=b.useState("open"),[ie,ge]=b.useState(""),Ge=b.useRef(!1),rt=b.useRef(!0),vt=b.useRef(new Map),Yt=b.useRef(!1),Ut=e.sessionIds.flatMap(ne=>{const Ze=t.find(Dt=>Dt.sessionId===ne);return Ze?[Ze]:[]}),Nt=Ut.map(ne=>({...ne,name:Uu(ne,Ut)})),ir=Z.coordinator===Zb,Mt=Z.coordinator||To(`${v}:lead`,""),Xt=Nt.find(ne=>ne.sessionId===Z.coordinator&&ne.agent),Bt=!!Z.coordinator&&!ir&&!Xt,Wt=ir||Bt?"":Xt?.sessionId||Nt.find(ne=>ne.sessionId===Mt&&ne.agent)?.sessionId||Nt.find(ne=>ne.agent)?.sessionId||"",xe=Nt.filter(ne=>ne.sessionId!==Wt&&ne.agent).map(ne=>ne.sessionId),[et,ot]=b.useState(!1),[Et,K]=b.useState(!1),[xt,rr]=b.useState(()=>To(`${v}:agent`,"")),[$e,Dr]=b.useState(()=>To(`${v}:launch-profile`,e.defaultLaunchProfileId??"")),Ce=e.launchProfiles?.find(ne=>ne.id===$e),St=Nt.flatMap(ne=>ne.agent&&x.some(Ze=>Ze.slug===ne.agent.slug)?[ne.agent.slug]:[]),Ot=[...new Set(St)].sort((ne,Ze)=>St.filter(Dt=>Dt===Ze).length-St.filter(Dt=>Dt===ne).length)[0],tr=x.find(ne=>ne.slug===Xt?.agent?.slug)?.slug??Ot??x[0]?.slug??"",ct=Ce?.agentSlug??(xt||tr),[Ct,or]=b.useState(()=>To(`${v}:cwd`,Nt[0]?.cwd??y??"")),Cr=!Nt.find(ne=>ne.sessionId===Wt)?.agent||!xe.length,[Ir,$r]=b.useState(null),Tt=!!Z.spec.trim()&&(!!Ir||!Bt&&(!Cr||!e.federated&&(!$e||!!Ce)&&!!x.find(ne=>ne.slug===ct)&&!!Ct.trim())),Ft=T.find(ne=>ne.id===P)??null,we=N?.id===P?N:null;b.useEffect(()=>(rt.current=!0,()=>{rt.current=!1}),[]),b.useEffect(()=>{Xi(`${v}:draft`,Z)},[v,Z]),b.useEffect(()=>{Xi(`${v}:selected`,P)},[v,P]),b.useEffect(()=>{const ne=Dt=>{const ur=Dt.detail;ur?.groupId===e.id&&(Xi(`${v}:open-task`,null),V(ur.taskId),de(!0),pe(!1),z("all"),wt())};window.addEventListener("open-collaboration-task",ne);const Ze=To(`${v}:open-task`,null);return Ze&&(V(Ze),de(!0),z("all"),Xi(`${v}:open-task`,null)),()=>window.removeEventListener("open-collaboration-task",ne)},[e.id]),b.useEffect(()=>{if(!r||!Ft||N?.id===Ft.id&&N.revision===Ft.revision)return;let ne=!1;return e9(Ft.id).then(Ze=>{ne||(B(Ze.task),_e(null))}).catch(Ze=>{ne||_e(Ze instanceof Error?Ze.message:"任务详情加载失败")}),()=>{ne=!0}},[r,Ft?.id,Ft?.revision,N?.id,N?.revision,Je]);const wt=async()=>{if(!Yt.current){Yt.current=!0;try{const ne=await Yy(e.id);rt.current&&(S(ne.tasks),se(!0),_e(null),Ne(Ze=>Ze+1))}catch(ne){rt.current&&_e(ne instanceof Error?ne.message:"任务加载失败")}finally{Yt.current=!1}}};b.useEffect(()=>{if(r)return iu(()=>{navigator.onLine!==!1&&wt()},2500,[k0,"pageshow"])},[r,e.id]);const it=ne=>{const Ze=JSON.stringify(ne),Dt=To(`${v}:request`,null);let ur=vt.current.get(Ze)??(Dt?.fingerprint===Ze?Dt.key:void 0);return ur||(ur=crypto.randomUUID(),vt.current.set(Ze,ur)),Xi(`${v}:request`,{fingerprint:Ze,key:ur}),ur},bt=ne=>{vt.current.delete(JSON.stringify(ne)),Xi(`${v}:request`,null)},An=async(ne,Ze)=>{if(at||Ge.current)return{ok:!1,error:"已有操作正在提交,请稍候。"};Ge.current=!0,ut(!0),ze(null),We("");let Dt={...Ze,expectedRevision:ne.revision};if(["comment","revise"].includes(Ze.kind)){const ur=To(`${v}:request`,null);try{const[Pr,qr]=JSON.parse(ur?.fingerprint??"null"),{expectedRevision:sn,...Nr}=qr;Pr===ne.id&&JSON.stringify(Nr)===JSON.stringify(Ze)&&(Dt=qr)}catch{}}try{const ur=await n9(ne.id,{...Dt,idempotencyKey:it([ne.id,Dt])});if(bt([ne.id,Dt]),Ou.getState().refresh(),rt.current){const Pr=I.current.find(Wr=>Wr.id===ur.task.id),qr=Pr&&Pr.revision>ur.task.revision?Pr:ur.task;S(Wr=>Wr.map(_n=>_n.id===ur.task.id&&_n.revision<=ur.task.revision?ur.task:_n)),B(Wr=>Wr?.id===ur.task.id&&Wr.revision>ur.task.revision?Wr:ur.task);const sn=y4(qr,I.current),Nr=`${Ze.kind==="answer"?"回答已保存":"方案确认已保存"},${sn?sn.workflow?.kind==="goal"?"目标仍暂停;恢复目标后才能投递。":"任务仍暂停;继续安排后才能投递。":"投递状态请查看任务记录。"}`;We(["comment","revise"].includes(Ze.kind)?"":Ze.kind==="retry"?KO(ne,ur.task):["answer","approve-plan"].includes(Ze.kind)?Nr:Ze.kind==="accept"?"已验收此版本结果。":"记录已保存。")}return{ok:!0}}catch(ur){const Pr=ur instanceof Error?ur.message:"操作失败";return Pr.includes("任务已更新")&&bt([ne.id,Dt]),rt.current&&(ze(["comment","revise"].includes(Ze.kind)?null:Pr),wt()),{ok:!1,error:Pr}}finally{Ge.current=!1,rt.current&&ut(!1)}},xn=async ne=>{if(ne.preventDefault(),at||me>0||(Z.mode==="goal"?!Tt:!Z.title.trim()||!Z.spec.trim())||Ge.current)return;Ge.current=!0,ut(!0),ze(null);const Ze=Z.mode==="goal",Dt={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:Ze?void 0:Z.assignee||void 0,coordinatorSessionId:Ze?Wt:Z.coordinator||void 0,parentTaskId:Ze?void 0:Z.parent||void 0,dependsOn:Ze?[]:Z.dependencies,managed:Ze,isolated:Z.isolated,reviewerSessionIds:Ze?xe:void 0};try{if(Ze&&(Cr||Ir)){K(!0);const Pr=ir?To(`${v}:team-request`,"")||crypto.randomUUID():void 0;Pr&&Xi(`${v}:team-request`,Pr);const qr=Ir??await t9(e.id,{agentSlug:ct,...$e?{launchProfileId:$e}:e.launchProfiles?.length?{launchProfileId:""}:{},cwd:Ct.trim(),...ir?{coordinatorSessionId:null,coordinatorCreationKey:Pr}:Wt?{coordinatorSessionId:Wt}:{}});K(!1),$r(qr),Dt.coordinatorSessionId=qr.coordinatorSessionId,Dt.reviewerSessionIds=qr.reviewerSessionIds,Xi(`${v}:agent`,xt),Xi(`${v}:cwd`,Ct.trim()),Xi(`${v}:launch-profile`,$e)}const{task:ur}=await r9({...Dt,idempotencyKey:it(Dt)});bt(Dt),rt.current&&(S(Pr=>[ur,...Pr.filter(qr=>qr.id!==ur.id)]),V(ur.id),de(!0),B(ur),Ze&&Xi(`${v}:lead`,Dt.coordinatorSessionId),Xi(`${v}:team-request`,null),$r(null),w?.(),J(m0),pe(!1),z("open"),ge(""),We(Ze?"目标已提交,协调者收到后开始拆分与分派。后续评审和依赖由服务接续。":"任务已保存。分派后由服务端持续投递。"))}catch(ur){rt.current&&ze(ur instanceof Error?ur.message:"创建失败")}finally{Ge.current=!1,rt.current&&(ut(!1),K(!1))}},rn=(ne,Ze)=>{if(!Ze)return"用户";const Dt=ne.memberSessions[Ju(Ze)];return Nt.find(ur=>ur.sessionId===Dt)?.name??t.find(ur=>ur.sessionId===Dt)?.name??"暂不可用的成员"},Oe=T.filter(ne=>(Le==="all"?!0:Le==="archive"?ne.status!=="open":ne.status==="open")&&(Le==="all"||Le==="attention"||ne.workflow?.kind!=="step")&&(Le!=="attention"||ta(ne))&&(!ie.trim()||`${ne.title} ${ne.spec} ${ne.attempts.map(Ze=>rn(ne,Ze.assignee)).join(" ")}`.toLowerCase().includes(ie.trim().toLowerCase()))),_t=T.filter(ta).length;b.useEffect(()=>{a?.(_t)},[_t,a]);const mt=!!Ft&&(l?$:Re||$),Zt=()=>{pe(!1),requestAnimationFrame(()=>ce.current?.focus())},$t=ne=>{zl.getState().updateDetail(`${v}:${ne}`,"view","overview"),V(ne),de(!0),We("")},wr=T.filter(ta).filter(ne=>!ie.trim()||`${ne.title} ${ne.spec} ${ne.attempts.map(Ze=>rn(ne,Ze.assignee)).join(" ")}`.toLowerCase().includes(ie.trim().toLowerCase())),Tn=(ne,Ze=!1)=>{const Dt=ne.attempts.find(Wr=>Wr.id===ne.activeAttemptId),ur=ne.children?.filter(Wr=>Wr.status==="accepted").length??0,Pr=ne.children?.filter(Wr=>Wr.status!=="closed").length??0,qr=gp(ne),sn=qr.length>1?qr.find(Wr=>Wr.source!=="member"):null,Nr=(Ze?ne.decisions.find(Wr=>Wr.status==="pending")?.question:"")||qr[0]?.summary||Dt?.report?.summary||Dt?.report?.content;return s.jsxs("button",{type:"button","aria-pressed":P===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 ${P===ne.id?"bg-surface-2":"hover:bg-surface-2/70"}`,onClick:()=>$t(ne.id),children:[s.jsx("span",{className:`mt-0.5 shrink-0 ${Ze||ne.status==="accepted"?"text-primary":"text-muted-foreground"}`,children:Ze?s.jsx(ud,{size:16}):ne.status==="accepted"?s.jsx(L0,{size:16}):s.jsx(V0,{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 ${Ze?"text-primary":"text-muted-foreground"}`,children:ou(ne)}),Nr&&s.jsx("span",{className:"mt-1 block line-clamp-2 break-words text-xs leading-5 text-muted-foreground",children:Nr}),sn&&s.jsxs("span",{className:`mt-1 block line-clamp-2 break-words text-xs leading-5 ${sn.source==="system"?"text-destructive":"text-muted-foreground"}`,children:[sn.label,":",sn.summary]}),Pr>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(Wr=>Wr.status!=="closed").slice(0,8).map(Wr=>s.jsx("span",{className:`h-1.5 w-3 rounded-full ${Wr.status==="accepted"?"bg-primary":"bg-border/30"}`},Wr.id))}),ur,"/",Pr," 子任务已验收"]}),s.jsxs("span",{className:"mt-2 block text-[11px] text-muted-foreground",children:[s.jsx("span",{className:"block truncate",children:Dt?rn(ne,Dt.assignee):"尚未分派"}),s.jsx(Xf,{task:ne})]})]}),s.jsx(Ys,{size:14,className:"mt-1 shrink-0 text-muted-foreground/60"})]},ne.id)},Dn=[],yn=new Set([P]);let un=Ft?.parentTaskId;for(;un&&!yn.has(un);){yn.add(un);const ne=T.find(Ze=>Ze.id===un);if(!ne)break;Dn.unshift(ne),un=ne.parentTaskId}const Cn=()=>{const ne=Array.from(qe.current?.querySelectorAll("button[data-task-id]")??[]).find(Ze=>Ze.dataset.taskId===P);de(!1),requestAnimationFrame(()=>{ne&&!ne.closest("[hidden]")?ne.focus():ce.current?.focus()})},Ur=ee||!l&&Fe&&T.length===0;return s.jsxs("section",{ref:qe,"aria-label":"协作任务",className:l?"relative flex h-full min-h-0 min-w-0 flex-col gap-2":"space-y-5",children:[l&&(Ur||!Fe)&&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:f})]}),(ae||De&&Me==="ready"&&!wf(De))&&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:[ae||De,!ae&&Fe?" · 显示最近保存的记录":""]}),s.jsxs("button",{type:"button",className:va,onClick:()=>ae?ze(null):void wt(),children:[s.jsx(wn,{size:14}),ae?"关闭提示":"重试"]})]}),De&&wf(De)&&!l&&s.jsx("p",{role:"status",className:"text-xs text-muted-foreground",children:"正在恢复任务同步,现有记录和草稿已保留"}),Se&&s.jsx("p",{role:"status",className:"rounded-lg bg-primary/10 px-3 py-2 text-xs leading-5 text-primary",children:Se}),Ur?s.jsxs("form",{onSubmit:ne=>{xn(ne)},className:`mx-auto w-full max-w-xl space-y-4 ${l?"overflow-auto px-1 py-5":""}`,onKeyDown:ne=>{ne.key==="Escape"&&ee&&!ne.defaultPrevented&&!ne.nativeEvent.isComposing&&eg(ne.currentTarget)&&(ne.preventDefault(),ne.stopPropagation(),at||Zt())},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"?"交给协调者拆分,你在这里看交付、回答问题。":"选择负责人,保留分派和验收记录。"})]}),(T.length>0||l)&&s.jsx("button",{type:"button","aria-label":"取消创建,保留草稿",className:`${va} shrink-0 px-2 text-muted-foreground hover:bg-surface-2`,disabled:at,onClick:Zt,children:s.jsx(Mn,{size:16})})]}),Z.mode==="task"&&s.jsx(qa,{label:"任务标题",children:s.jsx("input",{className:Us,required:!0,maxLength:200,value:Z.title,onChange:ne=>J(Ze=>({...Ze,title:ne.target.value})),placeholder:"要完成什么?"})}),s.jsx(gf,{paneKey:m,inputKey:`${v}:spec`,active:r&&Ur,label:Z.mode==="goal"?"协作目标":"目标与交付要求",className:`${Us} ${Cr&&Z.mode==="goal"?"min-h-24":"min-h-32"} resize-y text-sm leading-6`,autoFocus:ee,required:!0,disabled:at,value:Z.spec,onUploadChange:ft,onChange:ne=>J(Ze=>({...Ze,spec:typeof ne=="function"?ne(Ze.spec):ne})),placeholder:"例如:完善附件预览体验,交付实现和评审结果,保留现有快捷键。"}),Z.mode==="goal"&&Ir&&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:at,onClick:()=>{w?.(),c()},children:"查看已准备的成员"})]}),Z.mode==="goal"&&s.jsxs(qa,{label:"协调者",children:[s.jsxs("select",{"aria-label":"协调者",className:Us,disabled:at||!!Ir,value:Z.coordinator,onChange:ne=>{Xi(`${v}:team-request`,null),J(Ze=>({...Ze,coordinator:ne.target.value}))},children:[s.jsx("option",{value:"",children:"自动选择(优先复用组内 Agent)"}),s.jsx("option",{value:Zb,disabled:!!e.federated,children:"新建协调者"}),Bt&&s.jsx("option",{value:Z.coordinator,disabled:!0,children:"原协调者已不可用,请重新选择"}),Nt.map(ne=>s.jsxs("option",{value:ne.sessionId,disabled:!ne.agent,children:[ne.name,ne.agent?` · ${ne.agent.displayName}`:"(需要启动 Agent)"]},ne.sessionId))]}),Bt&&!Ir&&s.jsx("p",{role:"alert",className:"text-xs text-destructive",children:"所选协调者已离组或未运行 Agent,请重新选择。"})]}),Z.mode==="goal"&&(Cr||Ir)?s.jsxs("fieldset",{disabled:at||!!Ir,className:"space-y-3",children:[s.jsx("legend",{className:"mb-2 text-xs text-muted-foreground",children:Ir?"已用于准备成员的配置":"首次开始时配置 Agent"}),(!!e.launchProfiles?.length||!!$e)&&s.jsxs(qa,{label:"启动方案",children:[s.jsxs("select",{"aria-label":"协作启动方案",className:Us,value:$e,onChange:ne=>Dr(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(Ze=>Ze.slug===ne.agentSlug)?.displayName??ne.agentSlug]},ne.id))]}),Ce&&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:Ce.notes||"查看启动命令与使用备注"})}),s.jsx("p",{"aria-label":"完整使用备注",className:"whitespace-pre-wrap break-words",children:Ce.notes}),s.jsx("code",{className:"mt-1 block break-all",children:Ce.command})]}),$e&&!Ce&&s.jsx("p",{role:"alert",className:"text-xs text-destructive",children:"原方案已删除,请重新选择。"})]}),!Ce&&s.jsx(qa,{label:"Agent",children:s.jsxs("select",{"aria-label":"协作 Agent",className:Us,disabled:!!Ce,value:ct,onChange:ne=>rr(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(qa,{label:"工作目录",children:[s.jsxs("div",{className:"flex gap-2",children:[s.jsx("input",{"aria-label":"工作目录",className:`${Us} min-w-0 flex-1`,value:Ct,onChange:ne=>or(ne.target.value),placeholder:"选择项目所在的目录"}),s.jsx("button",{type:"button",className:si,onClick:()=>ot(!0),children:"浏览目录"})]}),et&&s.jsx(b.Suspense,{fallback:s.jsx("p",{className:"text-xs",children:"正在打开目录…"}),children:s.jsx(eF,{open:!0,initialPath:Ct.trim()||y||"/",title:"选择协作项目目录",onCancel:()=>ot(!1),onConfirm:ne=>{or(ne),ot(!1)}})})]}),!Ir&&s.jsx("p",{className:"text-xs leading-5 text-muted-foreground",children:ir?"开始时新建协调者,并补齐执行/评审成员。":"保留所选协调者,开始时补齐执行/评审成员;自动选择会优先复用组内 Agent。"}),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==="task"&&s.jsx(qa,{label:"分派给",children:s.jsxs("select",{className:Us,value:Z.assignee,onChange:ne=>J(Ze=>({...Ze,assignee:ne.target.value})),children:[s.jsx("option",{value:"",children:"先保存,稍后分派"}),Nt.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:[Z.mode==="goal"&&s.jsxs(qa,{label:"目标名称(选填)",children:[s.jsx("input",{"aria-label":"目标名称",className:Us,maxLength:100,value:Z.title,onChange:ne=>J(Ze=>({...Ze,title:ne.target.value})),placeholder:"用成果命名,例如:交付可安装的 Preview 客户端"}),s.jsx("p",{className:"text-xs leading-5 text-muted-foreground",children:"看板用这个名称辨认目标;未填写时使用正文第一行。"})]}),s.jsx(qa,{label:"验收标准(选填)",children:s.jsx("textarea",{className:`${Us} min-h-20 resize-y`,value:Z.acceptance,onChange:ne=>J(Ze=>({...Ze,acceptance:ne.target.value})),placeholder:"什么结果满足要求?"})}),s.jsx(qa,{label:"约束(选填)",children:s.jsx("textarea",{className:`${Us} min-h-20 resize-y`,value:Z.constraints,onChange:ne=>J(Ze=>({...Ze,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=>J(Ze=>({...Ze,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(qa,{label:"协调者",children:s.jsxs("select",{className:Us,value:Z.coordinator,onChange:ne=>J(Ze=>({...Ze,coordinator:ne.target.value})),children:[s.jsx("option",{value:"",children:"由用户协调"}),Nt.map(ne=>s.jsx("option",{value:ne.sessionId,children:ne.name},ne.sessionId))]})}),s.jsx(qa,{label:"父任务",children:s.jsxs("select",{className:Us,value:Z.parent,onChange:ne=>J(Ze=>({...Ze,parent:ne.target.value})),children:[s.jsx("option",{value:"",children:"独立任务"}),T.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:"需先验收的依赖任务"}),T.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:Ze=>J(Dt=>({...Dt,dependencies:Ze.target.checked?[...Dt.dependencies,ne.id]:Dt.dependencies.filter(ur=>ur!==ne.id)}))}),ne.title]},ne.id))]})]}),s.jsx("button",{type:"button",className:`${va} text-muted-foreground hover:bg-surface-2`,onClick:()=>J(ne=>({...ne,mode:ne.mode==="goal"?"task":"goal"})),children:Z.mode==="goal"?"改为手动分派任务":"改为自动协作目标"})]})]}),s.jsxs("button",{className:`${vl} w-full`,disabled:at||me>0||(Z.mode==="goal"?!Tt:!Z.title.trim()||!Z.spec.trim()),children:[at?s.jsx(wn,{size:14,className:"animate-spin"}):s.jsx(y0,{size:14}),at?Et?"正在准备成员…":"提交中…":Z.mode==="goal"?Ir?"重试提交目标":"开始协作":Z.assignee?"创建并分派":"保存任务"]}),s.jsx("p",{className:"text-center text-[11px] leading-5 text-muted-foreground",children:Z.mode==="goal"?"拆分任务 → 执行与独立评审 → 你验收结果":"草稿自动保存,分派后保留投递与回复记录。"})]}):l&&Fe?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:mt,className:`${mt?"hidden":"flex"} min-h-0 min-w-0 flex-1`,children:s.jsx(JO,{navigation:d,settings:f,action:s.jsxs("button",{ref:Te,type:"button",className:vl,disabled:at,onClick:()=>pe(!0),children:[s.jsx(Zs,{size:14}),"新目标"]}),storage:v,tasks:T,selectedId:mt?P:null,name:rn,onSelect:$t})}),mt&&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:`${va} px-2 hover:bg-surface-2`,onClick:Cn,children:"看板"})}),Dn.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(Ys,{"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:`${va} min-w-0 px-2 hover:bg-surface-2`,onClick:()=>$t(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(Ys,{"aria-hidden":"true",size:12}),s.jsx("span",{className:"px-2",children:Ft?.parentTaskId?"子任务详情":Ft?.workflow?.kind==="goal"?"目标详情":"任务详情"})]})]})}),s.jsx("div",{className:"min-h-0 flex-1",children:we?s.jsx(Kb,{reader:!0,paneKey:m,active:r,task:we,tasks:T,members:Nt,busy:at,name:ne=>rn(we,ne),act:ne=>An(we,ne),storage:v,onSelectTask:$t,onOpenSession:async ne=>{const Ze=t.find(Dt=>Dt.sessionId===we.memberSessions[Ju(ne)]);if(!Ze){ze("成员会话暂不可用,任务历史已保留。");return}try{await n(Ze)}catch(Dt){ze(Dt instanceof Error?Dt.message:"无法打开终端")}}},we.id):s.jsx("p",{role:"status",className:"py-8 text-center text-xs text-muted-foreground",children:"正在加载任务详情…"})})]})]})]}):!Fe&&!T.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:De?"任务暂时无法加载,请重试。":"正在加载目标…"}),!De&&[0,1,2].map(ne=>s.jsx("div",{className:"h-14 animate-pulse rounded-lg bg-surface-2"},ne))]}):s.jsxs(s.Fragment,{children:[(!mt||Re)&&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:[T.filter(ne=>ne.status==="open"&&ne.workflow?.kind!=="step").length," 个进行中 · ",T.filter(ne=>ne.status==="accepted"&&ne.workflow?.kind!=="step").length," 个已验收"]})]}),s.jsxs("button",{ref:Te,type:"button",className:vl,disabled:at,onClick:()=>pe(!0),children:[s.jsx(Zs,{size:14}),"新目标"]})]}),s.jsxs("div",{className:Re&&mt?"grid items-start gap-6 grid-cols-[260px_minmax(0,1fr)]":"",children:[(!mt||Re)&&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:`${Us} min-w-0 flex-1 border-transparent bg-transparent`,value:Le,onChange:ne=>z(ne.target.value),children:[s.jsx("option",{value:"open",children:"进行中的目标"}),s.jsxs("option",{value:"attention",children:["需要你处理(",_t,")"]}),s.jsx("option",{value:"archive",children:"已归档"}),s.jsx("option",{value:"all",children:"全部任务"})]}),s.jsx("button",{type:"button","aria-label":"搜索任务","aria-expanded":q,className:`${va} shrink-0 px-3 text-muted-foreground hover:bg-surface-2`,onClick:()=>{ve(ne=>!ne),ge("")},children:s.jsx(Wl,{size:16})})]}),q&&s.jsx("input",{"aria-label":"搜索任务或负责人",autoFocus:!0,className:Us,value:ie,onChange:ne=>ge(ne.target.value),placeholder:"搜索目标、内容或负责人"}),Le==="open"&&wr.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:wr.length})]}),wr.map(ne=>Tn(ne,!0))]}),(Le!=="open"||Oe.some(ne=>!ta(ne))||Oe.length===0)&&s.jsxs("section",{className:"space-y-1",children:[s.jsx("h4",{className:"px-3 text-[11px] font-medium text-muted-foreground",children:Le==="attention"?"需要你处理":Le==="archive"?"已归档":Le==="all"?"全部任务":"当前目标"}),Oe.filter(ne=>Le!=="open"||!ta(ne)).map(ne=>Tn(ne,Le==="attention")),!Oe.length&&s.jsxs("div",{className:"px-3 py-6 text-center text-xs leading-5 text-muted-foreground",children:[ie.trim()?"没有匹配的任务。":Le==="attention"?"目前没有需要你处理的任务。":Le==="archive"?"还没有归档任务。":"当前没有进行中的目标。",(Le!=="all"||ie)&&s.jsx("button",{type:"button",className:`${va} mt-2 text-primary`,onClick:()=>{z("all"),ge("")},children:"查看全部任务"})]})]})]}),mt&&s.jsxs("div",{className:"min-w-0",children:[!Re&&s.jsxs("button",{type:"button",className:`${va} mb-4 -ml-2 text-muted-foreground hover:bg-surface-2`,onClick:()=>de(!1),children:[s.jsx(e3,{size:14}),"全部目标"]}),we?s.jsx(Kb,{paneKey:m,active:r,task:we,tasks:T,members:Nt,busy:at,name:ne=>rn(we,ne),act:ne=>An(we,ne),storage:v,onSelectTask:$t,onOpenSession:async ne=>{const Ze=t.find(Dt=>Dt.sessionId===we.memberSessions[Ju(ne)]);if(!Ze){ze("成员会话暂不可用,任务历史已保留。");return}try{await n(Ze)}catch(Dt){ze(Dt instanceof Error?Dt.message:"无法打开终端")}}},we.id):s.jsx("p",{role:"status",className:"py-8 text-center text-xs text-muted-foreground",children:"正在加载任务详情…"})]})]})]})]})}function qa({label:e,children:t}){return s.jsxs("label",{className:"block space-y-1.5",children:[s.jsx("span",{className:"text-xs text-muted-foreground",children:e}),t]})}function Kb({reader:e=!1,active:t,paneKey:r,task:n,tasks:a,members:c,name:l,busy:d,act:f,storage:m,onOpenSession:x,onSelectTask:y}){const[w,v]=b.useState(""),[T,S]=b.useState(""),[I,N]=b.useState(""),[B,F]=b.useState(!1),[P,$]=b.useState(null),ee=b.useRef(!1),Z=b.useRef(!0);b.useEffect(()=>(Z.current=!0,()=>{Z.current=!1}),[]);const V=b.useRef(null),de=b.useRef(null);b.useEffect(()=>{!e&&P&&P.state!=="pending"&&t&&requestAnimationFrame(()=>de.current?.scrollIntoView({block:"nearest"}))},[P]);const pe=b.useRef(null),[J,Re]=b.useState(0),Xe=K=>Re(xt=>Math.max(0,xt+K)),q=b.useRef(null);b.useEffect(()=>{q.current?.focus()},[]);const ve=`${m}:${n.id}`,[qe]=b.useState(()=>zl.getState().ensureDetail(ve,{feedback:To(`${ve}:feedback`,""),answers:To(`${ve}:answers`,{}),view:"overview"})),{feedback:ce,answers:ye,view:Te}=zl(K=>K.details[ve]??qe),Fe=zm(ve,"feedback"),se=zm(ve,"answers"),De=zm(ve,"view");b.useEffect(()=>{pe.current&&(pe.current.scrollTop=0)},[Te]),b.useEffect(()=>Xi(`${m}:${n.id}:answers`,ye),[m,n.id,ye]),b.useEffect(()=>Xi(`${m}:${n.id}:feedback`,ce),[m,n.id,ce]);const _e=n.attempts.find(K=>K.id===n.activeAttemptId),Me=n.status==="open",Je=y4(n,a),Ne=n.artifacts.filter(K=>K.kind==="result"&&K.attemptId===n.activeAttemptId).at(-1);b.useEffect(()=>{P?.state==="saved"&&Ne?.id!==P.resultId&&$(null)},[Ne?.id,P]);const ae=n.artifacts.filter(K=>K.kind==="plan"&&K.attemptId===n.activeAttemptId).at(-1),ze=n.events.filter(K=>K.kind==="revise"&&K.source==="user"&&K.attemptId===n.activeAttemptId).at(-1),at=Ne&&n.events.some(K=>K.kind==="revise"&&K.attemptId===n.activeAttemptId&&K.createdAt>=Ne.createdAt),ut=e&&Me&&!!at,me=P?.state==="saved"&&P.kind==="revise"&&P.resultId===Ne?.id,dt=n.decisions.filter(K=>K.status==="pending"&&K.attemptId===n.activeAttemptId),ft=n.dependsOn.some(K=>a.find(xt=>xt.id===K)?.status!=="accepted"),Se=!n.workflow||n.artifacts.filter(K=>K.kind==="review"&&K.reviewsArtifactId===Ne?.id).at(-1)?.verdict==="pass",We=n.children??[],Le=n.workflow?.kind==="goal"&&We.some(K=>!["accepted","closed"].includes(K.status)),z=`任务:${n.title}
|
|
141
141
|
任务 ID:${n.id}
|
|
142
142
|
${n.spec}
|
|
@@ -159,7 +159,7 @@ ${dt.map(K=>`待回答:${K.question}`).join(`
|
|
|
159
159
|
`))},wt,we)},[w,e,n,y,bt?.id,we,wt,q,Nt]),b.useEffect(()=>{const Y=Ft.current;if(!w||!Y)return;const Be=Qt=>pe(String(Qt.detail));return Y.addEventListener("termdock:file-drop-error",Be),()=>Y.removeEventListener("termdock:file-drop-error",Be)},[w,bt?.id,pe]);const un=async Y=>{const Be=bt?.id;pe(null),rn(Qt=>Qt+1);try{const Qt=await W0("/tmp",Y);if(Qt.files.length!==Y.length||Qt.files.some(nr=>!nr.path))throw new Error("文件路径准备失败,请重试");const er=Qt.files.map(nr=>Fu(nr.path)).join(" ")+" ";if(mt.current===Be)vt(nr=>nr+(nr&&!/\s$/.test(nr)?`
|
|
160
160
|
`:"")+er);else if(Be){const nr=Oe.current.get(Be)??{content:"",targets:null},Or={...nr,content:nr.content+`
|
|
161
161
|
`+er};Oe.current.set(Be,Or),yn({drafts:{[Be]:Or}})}}catch(Qt){pe(Qt instanceof Error?Qt.message:"文件上传失败")}finally{rn(Qt=>Qt-1)}},Cn=new Set(S.filter(Hm).map(Y=>Y.sessionId)),Ur=De.size,ne=[...De].filter(Y=>!Cn.has(Y)),Ze=gF(bt,S),Dt=Me.trim().toLocaleLowerCase(),ur=S.filter(Y=>!Dt||[Uu(Y,S),Y.name,Y.serviceLabel??"",Y.cwd,Gm(Y.currentTask)].some(Be=>Be.toLocaleLowerCase().includes(Dt))),Pr=ty(ur),qr=ty(Ze),sn=Y=>!Dt&&Ne.has(Y),Nr=Y=>ae(Be=>{const Qt=new Set(Be);return Qt.has(Y)?Qt.delete(Y):Qt.add(Y),Qt});b.useEffect(()=>{Ut(!1),Bt.current!==bt?.id&&ir(!1),Bt.current=null,ce(!1),Ce(!1),at(!1),$e({}),Et(new Set(bt?.sessionIds??[])),ct(bt?.defaultLaunchProfileId??"")},[bt?.id]),b.useEffect(()=>{!St&&I[0]&&Ot(I[0].slug)},[I,St]),b.useEffect(()=>{ft([]),z(null)},[bt?.id]),b.useEffect(()=>{if(!B||!n||w&&!y||!bt){We(!1);return}We(!0);let Y=!1,Be=0,Qt=!1;const nr=iu(()=>{if(Y||Qt||document.hidden||navigator.onLine===!1)return;Qt=!0;const Or=++Be;Ix(bt.id).then(kr=>{!Y&&Or===Be&&(ft(kr.messages),z(null))}).catch(kr=>{!Y&&Or===Be&&z(kr instanceof Error?kr.message:"消息加载失败")}).finally(()=>{Qt=!1,!Y&&Or===Be&&We(!1)})},3e3,[k0,"pageshow"]);return()=>{Y=!0,nr()}},[bt?.id,n,w,y]),b.useEffect(()=>{!B||bt?.id!==B||it.current||(it.current=!0,q==="messages"&&Ft.current?.scrollIntoView?.({block:"nearest"}))},[B,bt?.id]);const Wr=async()=>{de("create-group"),pe(null),J(null);try{if(ne.length)throw new Error("所选会话已变化,请先清除不可用选择");const Y=await Hl({name:Fe,sessionIds:[...De]});se(""),Je(""),x(Y.group.id),await Re(),J(`“${Y.group.name}”已创建。`),r?await r(Y.group.id,"messages"):$&&await $(Y.group.id)}catch(Y){pe(Y instanceof Error?Y.message:"创建失败")}finally{de(null)}},_n=bt?.sessionIds.filter(Y=>ge===null||ge.includes(Y))??[],en=async()=>{if(!bt||V||xn||!rt.trim()||!_n.length)return;const Y=rt,Be=bt.id;de("send-message"),pe(null),J(null);try{const Qt=await s9(bt.id,{fromSessionId:null,toSessionIds:ge===null?void 0:_n,kind:"message",content:rt});if(mt.current===Be){const kr=wr.current,Zn=kr===Y?"":kr.startsWith(Y)?kr.slice(Y.length).replace(/^\n/,""):kr;vt(Zn),yn({drafts:{[Be]:{content:Zn,targets:$t.current}}})}else{const kr=Oe.current.get(Be);if(kr){const Zn={...kr,content:kr.content===Y?"":kr.content.startsWith(Y)?kr.content.slice(Y.length).replace(/^\n/,""):kr.content};Oe.current.set(Be,Zn),yn({drafts:{[Be]:Zn}})}}const er=await Ix(Be).catch(()=>null);er&&mt.current===Be&&ft(er.messages);const nr=Qt.deliveries?.filter(kr=>kr.serviceUnavailable).length??0,Or=Qt.deliveries?.filter(kr=>kr.pending>0).length??0;J(nr>0?`已保存消息;${nr} 个接收成员的服务不可达,尚未送达,等待重连`:Or>0?`已保存消息;${Or} 个成员等待投递确认`:`消息已送达 ${Qt.messages.length} 个会话`)}catch(Qt){pe(Qt instanceof Error?Qt.message:"发送失败")}finally{de(null)}},Fr=async()=>{if(!bt)return;de(`delete:${bt.id}`),pe(null),J(null);const Y=bt.name;try{await t3(bt.id,ut),x(null),at(!1),await Re(),J(`“${Y}”已删除`)}catch(Be){pe(Be instanceof Error?Be.message:"删除失败")}finally{de(null)}},Kr=async()=>{if(!bt)return;const Y=[...ot];de("save-members"),pe(null),J(null);try{const Be=await Hl({id:bt.id,name:bt.name,sessionIds:Y,expectedUpdatedAt:K});x(Be.group.id),Ut(!1),await Re(),J(`“${bt.name}”成员已更新,共 ${Y.length} 个会话`)}catch(Be){pe(Be instanceof Error?Be.message:"成员更新失败")}finally{de(null)}},gr=async Y=>{if(!bt||!bt.sessionIds.includes(Y)){et(null);return}const Be=S.find(er=>er.sessionId===Y)?.name??Y,Qt=bt.name;de(`remove-member:${Y}`),pe(null),J(null);try{await Hl({id:bt.id,name:Qt,sessionIds:bt.sessionIds.filter(er=>er!==Y),expectedUpdatedAt:bt.updatedAt}),et(null),Ge(er=>er?.filter(nr=>nr!==Y)??null),Et(er=>new Set([...er].filter(nr=>nr!==Y))),$e(er=>Object.fromEntries(Object.entries(er).filter(([nr])=>nr!==Y))),await Re(),J(`已把“${Be}”移出“${Qt}”`)}catch(er){pe(er instanceof Error?er.message:"移出成员失败")}finally{de(null)}},an=async Y=>{if(!bt)return;const Be=rr[Y]??"";de(`role:${Y}`),pe(null),J(null);try{await l9(bt.id,Y,Be.trim()||null),await Re(),J(Be.trim()?"定位已保存,该成员每次收到消息都会看到":"定位已清除")}catch(Qt){pe(Qt instanceof Error?Qt.message:"定位保存失败")}finally{de(null)}},Xr=()=>{ct(bt?.defaultLaunchProfileId??"");const Y=S.find(Be=>Be.sessionId===N)?.cwd??S.find(Be=>bt?.sessionIds.includes(Be.sessionId))?.cwd??"";Ir(Y),or(""),Tt(""),Ce(!0),Ut(!1)},dn=async()=>{if(!(!bt||!St||tr&&!bt.launchProfiles?.some(Y=>Y.id===tr))){de("spawn-agent"),pe(null),J(null);try{const Y=await i9(bt.id,{agentSlug:bt.launchProfiles?.find(Be=>Be.id===tr)?.agentSlug??St,...tr||bt.launchProfiles?.length?{launchProfileId:tr}:{},name:Ct.trim()||void 0,cwd:Cr.trim()||void 0,task:$r.trim()||void 0,mode:Z});Ce(!1),await Re(),J(`“${Y.session.name}”已创建并加入“${Y.group.name}”`)}catch(Y){pe(Y instanceof Error?Y.message:"Agent Session 创建失败")}finally{de(null)}}},Rr=wF(dt,S),zn=Y=>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:!Hm(Y),checked:De.has(Y.sessionId),onChange:()=>_e(Be=>{const Qt=new Set(Be);return Qt.has(Y.sessionId)?Qt.delete(Y.sessionId):Qt.add(Y.sessionId),Qt})}),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:Uu(Y,S)}),s.jsx(Wm,{session:Y}),s.jsx("span",{className:"shrink-0 text-[9px] text-muted-foreground",children:yf(Y)})]}),s.jsx("span",{className:"mt-0.5 block truncate text-[10px] text-muted-foreground",children:Y.currentTask?`${Gm(Y.currentTask)} · ${Y.cwd}`:Y.cwd||Y.capability||"终端会话"})]})]},Y.sessionId),pn=Y=>{const Be=rr[Y.sessionId]??"",Qt=bt?.roles?.[Y.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:!bt?.sessionIds.includes(Y.sessionId)&&!Hm(Y),checked:ot.has(Y.sessionId),onChange:()=>Et(er=>{const nr=new Set(er);return nr.has(Y.sessionId)?nr.delete(Y.sessionId):nr.add(Y.sessionId),nr})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block truncate text-[11px] text-foreground",children:Y.name}),s.jsx(Wm,{session:Y}),s.jsxs("span",{className:"block truncate text-[9px] text-muted-foreground",children:[yf(Y)," · ",Y.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":`${Y.name} 的定位`,className:`${Vs} min-h-8 py-1 text-[10px]`,value:Be,maxLength:200,placeholder:"成员收到的定位;清空后保存可移除",onChange:er=>$e(nr=>({...nr,[Y.sessionId]:er.target.value}))}),s.jsx("button",{"aria-label":`保存 ${Y.name} 的定位`,title:Be.trim()===Qt?"定位未变化":"保存此成员的定位",disabled:V!==null||Be.trim()===Qt,className:`${Lr} min-h-8 shrink-0 px-2 text-muted-foreground`,onClick:()=>{an(Y.sessionId)},children:V===`role:${Y.sessionId}`?s.jsx(wn,{size:12,className:"animate-spin"}):s.jsx(ai,{size:12})})]})]},Y.sessionId)},Gr=s.jsx("nav",{"aria-label":"协作工作区",className:"flex shrink-0 items-center gap-1",children:[["tasks",e||Xe?"看板":"目标"],["messages","成员与消息"]].map(([Y,Be])=>s.jsxs("button",{type:"button","aria-label":Be,"aria-pressed":q===Y,className:`${Lr} min-h-11 ${q===Y?"bg-surface-2 text-foreground":"text-muted-foreground hover:bg-surface-2"}`,onClick:Qt=>{if(Xe&&Y==="tasks"){$?.(bt.id).catch(Or=>pe(Or instanceof Error?Or.message:"无法打开看板"));return}const er=Qt.currentTarget.closest("[data-collaboration-views]"),nr=Qt.currentTarget;ve(Y),requestAnimationFrame(()=>{const Or=document.activeElement;Or!==nr&&Or!==document.body&&Or?.isConnected&&!Or.closest("[hidden]")||Array.from(er?.querySelectorAll('nav[aria-label="协作工作区"] button')??[]).find(kr=>kr.getAttribute("aria-pressed")==="true"&&!kr.closest("[hidden]"))?.focus()})},children:[e&&Y==="messages"?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"sm:hidden",children:"成员"}),s.jsx("span",{className:"hidden sm:inline",children:Be})]}):Be,!e&&Y==="tasks"&&ye>0&&s.jsxs("span",{className:"rounded bg-primary/15 px-1.5 text-[11px] text-primary",children:[ye," 待处理"]})]},Y))}),zr=s.jsxs("button",{type:"button","aria-label":"组设置",title:"组设置","aria-expanded":Nt,className:`${Lr} min-h-11 shrink-0 text-muted-foreground hover:bg-surface-2`,onClick:Y=>{Xt.current=Y.currentTarget,ir(Be=>!Be),pe(null),J(null)},children:[s.jsx(qu,{size:14}),e&&s.jsx("span",{className:"sm:sr-only",children:"组设置"})]});return s.jsxs("div",{ref:Mt,className:e?"flex min-h-0 flex-1 flex-col gap-3":Xe?void 0:"space-y-3",children:[Le&&ie==="ready"&&!wf(Le)&&s.jsxs("p",{role:"alert",className:"rounded-lg bg-destructive/10 px-3 py-2 text-[11px] text-destructive",children:["消息同步暂时失败,正在自动重试:",Le]}),Le&&wf(Le)&&!e&&s.jsx("p",{role:"status",className:"text-[11px] text-muted-foreground",children:"正在恢复消息同步,现有记录已保留"}),s.jsxs("div",{className:e?Nt?"min-h-0 flex-1 overflow-auto":"contents":void 0,children:[!B&&m!=="new"&&T.length>0&&s.jsx("div",{hidden:Nt,children:s.jsx(VO,{groups:T,sessions:S,busy:V!==null,onOpen:(Y,Be)=>{r?.(Y,Be)},onSettings:(Y,Be)=>{Bt.current=Y,x(Y),Xt.current=Be,ir(!0),pe(null),J(null)},onCreate:()=>{x("new"),at(!1),J(null)}})}),!B&&(m==="new"||Nt)&&T.length>0&&s.jsx("button",{type:"button",className:`${Lr} min-h-11 text-muted-foreground hover:bg-surface-2`,onClick:()=>{Nt?Wt():x(T[0].id)},children:"返回协作组"}),Nt&&bt&&s.jsx(hF,{group:bt,agents:I,activeSessionId:N,sessions:S,busy:V,setBusy:de,setError:pe,setNotice:J,refresh:Re,onClose:Wt},bt.id),!B&&v!=="loaded"&&!T.length&&s.jsx("p",{role:"status",className:"py-5 text-xs text-muted-foreground",children:v==="loading"?"正在加载协作组与会话…":"会话加载失败,请重试"}),!bt&&(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] ${Ur>=2?"text-primary":"text-muted-foreground"}`,children:["已选 ",Ur," 个"]})]}),s.jsxs("label",{className:"mt-4 block space-y-1 text-[10px] text-muted-foreground",children:["协作组名称",s.jsx("input",{className:Vs,value:Fe,onChange:Y=>se(Y.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:["复用已有会话(选填) · 已选 ",Ur," 个"]}),S.length>5&&s.jsxs("label",{className:"relative mt-3 block",children:[s.jsx("span",{className:"sr-only",children:"筛选会话"}),s.jsx(Wl,{size:13,className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),s.jsx("input",{className:`${Vs} pl-8`,value:Me,onChange:Y=>Je(Y.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:[Pr.length<=1?ur.map(zn):Pr.map(Y=>{const Be=sn(Y.key);return s.jsxs("div",{children:[s.jsx(ry,{label:Y.label,count:Y.sessions.length,collapsed:Be,onToggle:()=>Nr(Y.key)}),!Be&&s.jsx("div",{className:"divide-y divide-border/10",children:Y.sessions.map(zn)})]},Y.key)}),S.length===0&&s.jsx("p",{className:"px-3 py-6 text-center text-[11px] text-muted-foreground",children:v==="loading"?"正在加载会话…":v==="error"?"会话加载失败,请重试":"没有现有会话也可以创建,开始目标时会启动 Agent"}),S.length>0&&ur.length===0&&s.jsx("p",{className:"px-3 py-6 text-center text-[11px] text-muted-foreground",children:"没有符合筛选条件的会话"})]})]}),ne.length>0&&s.jsxs("div",{role:"alert",className:"mt-2 text-[11px] text-destructive",children:["有 ",ne.length," 个所选会话暂不可用。",s.jsx("button",{className:Lr,onClick:()=>_e(Y=>new Set([...Y].filter(Be=>Cn.has(Be)))),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] ${Ur<2?"text-muted-foreground":"text-primary"}`,children:Fe.trim()?"创建后进入成员消息,看板可随时使用":"请填写协作组名称"}),s.jsxs("div",{className:"flex justify-end gap-2",children:[T.length>0&&s.jsx("button",{className:`${Lr} bg-surface-2 text-foreground`,onClick:()=>x(T[0]?.id??null),children:"取消"}),s.jsxs("button",{disabled:V!==null||!Fe.trim()||ne.length>0,className:`${Lr} bg-primary text-primary-foreground`,onClick:()=>{Wr()},children:[V==="create-group"?s.jsx(wn,{size:13,className:"animate-spin"}):s.jsx(Zs,{size:13}),"创建协作组"]})]})]})]})]}),bt&&B&&s.jsxs("div",{"data-collaboration-views":!0,hidden:Nt,className:e?`${Nt?"hidden":"flex"} min-h-0 flex-1 flex-col gap-3`:Xe?void 0:"space-y-3",children:[!Xe&&(!e||q==="messages")&&s.jsxs("div",{className:"flex shrink-0 items-center gap-1 border-b border-border/15 pb-2",children:[Gr,s.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[e&&q==="messages"&&s.jsxs("button",{type:"button","aria-label":"放到终端旁",title:ee?"在当前终端分屏中使用成员与消息":"先打开一个终端,再嵌入消息面板",disabled:!ee||V!==null,className:`${Lr} min-h-11 text-muted-foreground hover:bg-surface-2`,onClick:()=>{de("dock-messages"),pe(null),ee?.().catch(Y=>pe(Y instanceof Error?Y.message:"消息面板打开失败,草稿已保留")).finally(()=>de(null))},children:[s.jsx(qc,{size:14}),s.jsx("span",{className:"hidden sm:inline",children:"放到终端旁"})]}),zr]})]}),!Xe&&q==="messages"&&s.jsx("div",{className:"flex gap-1 overflow-x-auto","aria-label":"工作组终端",children:An.map(Y=>s.jsx("button",{type:"button","aria-pressed":Y.sessionId===N,title:`${Y.name} · ${Y.cwd||"终端会话"}`,className:`${Lr} min-h-9 shrink-0 ${Y.sessionId===N?"bg-primary/15 text-primary":"text-muted-foreground hover:bg-surface-2"}`,onClick:()=>{P(Y).catch(Be=>pe(Be instanceof Error?Be.message:"无法打开终端"))},children:Uu(Y,An)},Y.sessionId))}),!Xe&&s.jsx("div",{hidden:q!=="tasks",className:e?`${q==="tasks"?"flex":"hidden"} min-h-0 flex-1 flex-col`:void 0,children:s.jsx(sF,{paneKey:d?wt:void 0,boardNavigation:e?Gr:void 0,boardSettings:e?zr:void 0,board:e,group:bt,sessions:S,agents:I,defaultCwd:S.find(Y=>Y.sessionId===N)?.cwd??void 0,onTeamReady:Re,active:n&&!Nt&&q==="tasks"&&(!w||y),onAttentionChange:Te,onManageMembers:()=>ve("messages"),onOpenSession:P},bt.id)}),s.jsxs("div",{hidden:q!=="messages",className:e?"min-h-0 flex-1 overflow-auto":void 0,children:[s.jsxs("section",{onFocusCapture:()=>b0(wt),onPointerDownCapture:()=>b0(wt),"data-termdock-terminal-dropzone":w?N??"collaboration-composer":void 0,onDragOver:Y=>{w&&Y.preventDefault()},onDrop:Y=>{if(!w)return;const Be=Array.from(Y.dataTransfer.files);if(!(Be.length&&ea()))if(Y.preventDefault(),Y.stopPropagation(),Be.length)un(Be);else{const Qt=Y.dataTransfer.getData("text/plain")||Y.dataTransfer.getData("text/uri-list");Qt&&vt(er=>er+(er?`
|
|
162
|
-
`:"")+Qt)}},ref:Ft,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:[bt.name," · 发送给成员"]}),s.jsxs("div",{className:w?"space-y-2":"mt-2 space-y-2",children:[Xe&&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:Y=>{Y.key==="Escape"&&(Y.currentTarget.removeAttribute("open"),Y.currentTarget.querySelector("summary")?.focus(),Y.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(Io,{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:`${Lr} min-h-11 w-full justify-start text-foreground hover:bg-surface-elevated`,onClick:Y=>{Y.currentTarget.closest("details")?.removeAttribute("open"),$?.(bt.id).catch(Be=>pe(Be instanceof Error?Be.message:"无法打开看板"))},children:[s.jsx(qc,{size:14}),"看板"]}),s.jsx("button",{type:"button","aria-expanded":qe,className:`${Lr} min-h-11 w-full justify-start text-foreground hover:bg-surface-elevated`,onClick:Y=>{Y.currentTarget.closest("details")?.removeAttribute("open"),ce(Be=>!Be)},children:"成员管理"}),s.jsxs("button",{type:"button","aria-label":"组设置","aria-expanded":Nt,className:`${Lr} min-h-11 w-full justify-start text-foreground hover:bg-surface-elevated`,onClick:Y=>{Y.currentTarget.closest("details")?.removeAttribute("open"),Xt.current=Y.currentTarget,ir(!0),pe(null),J(null)},children:[s.jsx(qu,{size:14}),"组设置"]})]})]})]}),s.jsxs("fieldset",{className:"min-w-0",children:[s.jsx("legend",{className:Xe?"sr-only":"mb-1 text-[10px] text-muted-foreground",children:"接收人(可多选)"}),s.jsx("div",{className:"flex flex-wrap gap-1",children:[{id:"*",label:"全组成员"},...bt.sessionIds.map(Y=>({id:Y,label:(()=>{const Be=An.find(Qt=>Qt.sessionId===Y);return Be?Uu(Be,An):void 0})()??`${Y.slice(0,8)}(离线)`}))].map(({id:Y,label:Be})=>{const Qt=Y==="*"?ge===null:ge?.includes(Y)??!1,er=S.find(nr=>nr.sessionId===Y);return s.jsxs(GO,{label:Be,disabled:Y==="*"||V!==null,onRemove:()=>{gr(Y)},children:[s.jsxs("button",{type:"button","aria-pressed":Qt,onClick:()=>Ge(nr=>Y==="*"?null:nr?.includes(Y)?nr.filter(Or=>Or!==Y):[...nr??[],Y]),className:`${K1} min-h-9 min-w-0 gap-1 sm:min-h-7 ${Qt?"border-primary/40 bg-primary/15 text-primary":"border-border/20 bg-surface-2 text-muted-foreground hover:text-foreground"}`,children:[Qt&&s.jsx(ai,{size:12,"aria-hidden":"true",className:"shrink-0"}),s.jsx("span",{className:"break-words text-left",children:Be})]}),er&&s.jsx("button",{type:"button","aria-label":`打开 ${Be} 的终端`,title:`打开 ${Be} 的终端`,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:()=>{F(er).catch(nr=>pe(nr instanceof Error?nr.message:"无法打开会话"))},children:s.jsx(qc,{size:12})})]},`${bt.id}:${Y}`)})})]})]}),s.jsxs("label",{className:"mt-2 block space-y-1 text-[9px] text-muted-foreground",children:[s.jsx("span",{className:Xe?"sr-only":void 0,children:"内容"}),s.jsx("textarea",{onKeyDown:Y=>{Y.key==="Enter"&&(Y.metaKey||Y.ctrlKey)&&!Y.nativeEvent.isComposing&&Y.keyCode!==229&&(Y.preventDefault(),en())},onPaste:Y=>{const Be=Array.from(Y.clipboardData.files);Be.length&&(Y.preventDefault(),un(Be))},className:`${Vs} min-h-16 max-h-48 resize-y`,value:rt,onChange:Y=>vt(Y.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:bt.federated?"消息由服务端后台投递,可查看送达结果;无需保持客户端在线。":"在线成员立即入队;离线成员上线后送达。"}),s.jsxs("button",{disabled:V!==null||xn>0||!rt.trim()||!_n.length,className:`${Lr} shrink-0 bg-primary text-primary-foreground`,title:"发送(⌘ / Ctrl + Enter)",onClick:()=>{en()},children:[V==="send-message"?s.jsx(wn,{size:13,className:"animate-spin"}):null,"发送"]})]})]}),s.jsxs("div",{children:[s.jsxs("details",{hidden:Xe&&!qe,open:Xe?qe:void 0,onToggle:Y=>{Xe&&ce(Y.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:["管理成员、角色与删除 · ",bt.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:bt.name}),s.jsxs("p",{className:"mt-1 text-[10px] text-muted-foreground",children:[bt.sessionIds.length," 个成员 · 组 ID:",s.jsx("span",{className:"break-all font-mono",children:w4(bt.id)})]})]}),ze?s.jsxs("div",{className:"flex flex-wrap items-center gap-1 sm:justify-end",children:[s.jsx("button",{className:`${Lr} bg-surface-2 px-2 text-foreground`,onClick:()=>at(!1),children:"取消"}),s.jsxs("button",{disabled:V!==null,className:`${Lr} bg-destructive px-2 text-destructive-foreground`,onClick:()=>{Fr()},children:[V===`delete:${bt.id}`?s.jsx(wn,{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:`${Lr} px-2 text-muted-foreground hover:bg-surface-2 hover:text-foreground`,onClick:()=>{Et(new Set(bt.sessionIds)),xt(bt.updatedAt);const Y=!Yt;Ut(Y),Y&&$e(Object.fromEntries(bt.sessionIds.map(Be=>[Be,bt.roles?.[Be]??""]))),Ce(!1)},children:[s.jsx(qu,{size:13}),"管理成员"]}),s.jsxs("button",{className:`${Lr} px-2 text-primary hover:bg-primary/10`,onClick:Xr,children:[s.jsx(Zs,{size:13}),"新建 Agent"]}),s.jsx("button",{"aria-label":`删除协作组 ${bt.name}`,title:"删除协作组",disabled:V!==null,className:"rounded-lg p-2 text-muted-foreground transition hover:bg-destructive/10 hover:text-destructive",onClick:()=>{me(bt.updatedAt),at(!0)},children:s.jsx(Ds,{size:14})})]})]}),ze&&s.jsxs("p",{role:"alert",className:"mt-2 rounded-lg bg-destructive/10 px-3 py-2 text-[10px] leading-relaxed text-destructive",children:["将删除“",bt.name,"”协作组及其协作记录,",bt.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:bt.sessionIds.map(Y=>{const Be=S.find(nr=>nr.sessionId===Y),Qt=bt.roles?.[Y],er=Be?.name??Y;return s.jsxs("div",{className:`flex min-w-0 items-stretch transition ${xe===Y?"bg-destructive/5":"hover:bg-surface-2"}`,children:[s.jsxs("button",{disabled:!Be,onClick:()=>Be&&void F(Be).catch(nr=>pe(nr instanceof Error?nr.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 ${Be&&["ready","shell","terminal-connected","service-reachable","working","idle","done"].includes(Be.status)&&Be.serviceConnected!==!1?"bg-[var(--success)]":"bg-muted-foreground"}`}),s.jsx("span",{className:"truncate text-[11px] text-foreground",children:er}),Be&&s.jsx(Wm,{session:Be}),s.jsx("span",{className:"ml-auto shrink-0 text-[9px] text-muted-foreground",children:Be?yf(Be):"已离线"})]}),s.jsxs("span",{className:"mt-1 flex min-w-0 items-center gap-1 text-[9px] text-muted-foreground",children:[Qt?s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"min-w-0 truncate font-medium text-primary/80",children:["定位:",Qt]}),s.jsx("span",{className:"shrink-0 text-muted-foreground/50",children:"·"})]}):null,Be?s.jsx("span",{className:"min-w-0 truncate",children:Gm(Be.currentTask)}):s.jsx("span",{className:"shrink-0",children:"重新上线后可继续接收消息"})]})]}),s.jsx("button",{"aria-label":`把 ${er} 移出协作组`,"aria-expanded":xe===Y,title:"移出协作组",disabled:V!==null,className:`mr-1 shrink-0 self-center rounded-lg p-2 transition ${xe===Y?"text-destructive":"text-muted-foreground hover:bg-destructive/10 hover:text-destructive"}`,onClick:()=>et(xe===Y?null:Y),children:s.jsx(Ds,{size:13})})]},Y)})}),xe&&bt.sessionIds.includes(xe)&&(()=>{const Y=S.find(Qt=>Qt.sessionId===xe)?.name??xe,Be=V===`remove-member:${xe}`;return s.jsxs("div",{role:"group","aria-label":`确认移除成员 ${Y}`,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:`把“${Y}”移出“${bt.name}”?移出后它不再收到这个组的消息,可以随时重新加入`}),s.jsxs("div",{className:"flex shrink-0 gap-2",children:[s.jsx("button",{className:`${Lr} min-h-8 bg-surface-2 px-2 text-[10px] text-foreground`,onClick:()=>et(null),children:"取消"}),s.jsxs("button",{disabled:V!==null,className:`${Lr} min-h-8 px-2 text-[10px] bg-destructive text-destructive-foreground`,onClick:()=>{gr(xe)},children:[Be?s.jsx(wn,{size:12,className:"animate-spin"}):s.jsx(Ds,{size:12}),"移出"]})]})]})})(),Yt&&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:["已选 ",ot.size]})]}),s.jsx("div",{className:"mt-3 max-h-72 divide-y divide-border/10 overflow-y-auto border-y border-border/10",children:qr.length<=1?Ze.map(pn):qr.map(Y=>{const Be=sn(Y.key);return s.jsxs("div",{children:[s.jsx(ry,{label:Y.label,count:Y.sessions.length,collapsed:Be,onToggle:()=>Nr(Y.key)}),!Be&&s.jsx("div",{className:"divide-y divide-border/10",children:Y.sessions.map(pn)})]},Y.key)})}),s.jsxs("div",{className:"mt-3 flex justify-end gap-2",children:[s.jsx("button",{className:`${Lr} bg-surface-2 text-foreground`,onClick:()=>{Ut(!1),$e({})},children:"取消"}),s.jsxs("button",{disabled:V!==null||v!=="loaded",className:`${Lr} bg-primary text-primary-foreground`,onClick:()=>{Kr()},children:[V==="save-members"?s.jsx(wn,{size:13,className:"animate-spin"}):s.jsx(ai,{size:13}),"保存成员"]})]})]}),Dr&&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(qO,{group:bt,value:tr,onChange:ct,disabled:V!==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:Vs,disabled:!!tr,value:bt.launchProfiles?.find(Y=>Y.id===tr)?.agentSlug??St,onChange:Y=>Ot(Y.target.value),children:I.map(Y=>s.jsxs("option",{value:Y.slug,children:[Y.displayName,Y.isPlugin?" · Plugin":""]},Y.slug))})]}),s.jsxs("label",{className:"space-y-1 text-[9px] text-muted-foreground",children:["会话名称",s.jsx("input",{"aria-label":"新 Agent 会话名称",className:Vs,value:Ct,onChange:Y=>or(Y.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:Vs,value:Cr,onChange:Y=>Ir(Y.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:`${Vs} min-h-16 resize-y`,value:$r,onChange:Y=>Tt(Y.target.value),placeholder:"说明它加入后要先完成什么"})]}),s.jsxs("div",{className:"mt-3 flex justify-end gap-2",children:[s.jsx("button",{className:`${Lr} bg-surface-2 text-foreground`,onClick:()=>Ce(!1),children:"取消"}),s.jsxs("button",{disabled:V!==null||!St||!!tr&&!bt.launchProfiles?.some(Y=>Y.id===tr),className:`${Lr} bg-primary text-primary-foreground`,onClick:()=>{dn()},children:[V==="spawn-agent"?s.jsx(wn,{size:13,className:"animate-spin"}):s.jsx(G0,{size:13}),"创建并加入"]})]})]})]})]},bt.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:[Rr.length," 条"]})]}),s.jsxs("div",{className:"divide-y divide-border/10 border-y border-border/10 [overflow-wrap:anywhere]",children:[Rr.map(Y=>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:Y.responseKind==="ack"?"收到确认":Y.responseKind==="progress"?"进展":Y.responseKind==="result"?"结果":vF(Y.kind)}),s.jsx("span",{children:Y.fromName}),s.jsx("span",{children:"→"}),s.jsx("span",{className:"truncate",children:Y.toNames.join("、")}),s.jsx("span",{className:"ml-auto shrink-0",children:new Date(Y.createdAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),s.jsx("p",{className:"mt-1 whitespace-pre-wrap text-[11px] leading-relaxed text-foreground",children:Y.content}),s.jsx("p",{className:"mt-1 text-[9px] text-muted-foreground",children:Y.status==="pending"?"已入队 · 等待投递":Y.status==="failed"?"投递失败":Y.status==="expired"?"消息已过期,未继续投递":Y.status==="stored"?"答复已持久保存 · 供后台接收":"已写入接收方终端 · 等待接手确认"}),Y.deliveryErrors.map(Be=>s.jsx("p",{role:"status",className:"mt-1 text-[10px] text-destructive",children:Be==="TMUX_PANE_CHANGED"?"目标会话绑定已变化,投递暂停。原消息已保留,请确认目标会话后继续。":`投递暂停:${Be}。原消息已保留,请检查目标会话。`},Be)),(Y.task||Y.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(Y.task??{failure_reason:Y.failureReason},null,2)})]})]},Y.key)),Rr.length===0&&s.jsx(IF,{text:Se?"正在加载协作记录…":"还没有消息。可以直接给成员发送说明或问题。"})]})]})]})]})]})]})}function hF({group:e,agents:t,activeSessionId:r,sessions:n,busy:a,setBusy:c,setError:l,setNotice:d,refresh:f,onClose:m}){const x=n.filter(q=>e.sessionIds.includes(q.sessionId)&&!td(q.sessionId)),[y,w]=b.useState(()=>aF(e,r&&x.some(q=>q.sessionId===r)?r:"")),v=b.useRef(y),[T,S]=b.useState(null),I=q=>{const ve={...v.current,...q};v.current=ve,oF(e.id,ve),w(ve)},{name:N,rules:B,savedName:F,savedRules:P,rulesVersion:$,rulesMemberId:ee}=y,Z=ep(y),V=new TextEncoder().encode(B).length,de=x.some(q=>q.sessionId===ee),pe=async()=>{if(!(a||!N.trim())){c("group-name"),l(null),d(null);try{const q=await Hl({id:e.id,name:N.trim(),sessionIds:y.sessionIds??e.sessionIds,expectedUpdatedAt:y.updatedAt});S(null),I({savedName:q.group.name,name:q.group.name,updatedAt:q.group.updatedAt,sessionIds:q.group.sessionIds,...B===P?{rules:q.group.instructions?.text??"",savedRules:q.group.instructions?.text??"",rulesVersion:q.group.instructions?.version??""}:{}}),await f(),d("协作组名称已更新")}catch(q){S(null),l(q instanceof x0&&q.status===409?"组设置已被其他人修改。请查看最新状态并确认,名称与群规草稿仍保留。":q instanceof Error?q.message:"改名失败")}finally{c(null)}}},J=async()=>{if(!(a||!de||V>8192)){c("group-rules"),l(null),d(null);try{const q=await o9(e.id,{sessionId:ee,text:B,expectedVersion:$});S(null),I({savedName:q.group.name,...N===F?{name:q.group.name}:{},updatedAt:q.group.updatedAt,sessionIds:q.group.sessionIds,rules:q.group.instructions?.text??"",savedRules:q.group.instructions?.text??"",rulesVersion:q.group.instructions?.version??""}),await f(),d(B.trim()?"群规已保存,变更通知已入队":"群规已清空,变更通知已入队")}catch(q){S(null),l(q instanceof x0&&q.status===409?"群规已被其他人修改。请查看最新状态并确认,名称与群规草稿仍保留。":q instanceof Error?q.message:"群规保存失败")}finally{c(null)}}},Re=()=>{I(Xg(e,ee)),S(null),l(null)},Xe=async()=>{if(!a){c("group-latest"),l(null),d(null),S(null);try{const ve=(await ng()).groups.find(qe=>qe.id===e.id);if(!ve)throw new Error("协作组已删除;草稿仍保留,请返回看板查看。");S(ve)}catch(q){l(q instanceof Error?q.message:"最新状态读取失败;草稿仍保留,请重试。")}finally{c(null)}}};return s.jsxs("section",{"aria-label":"协作组设置",onKeyDown:q=>{q.key!=="Escape"||q.defaultPrevented||q.nativeEvent.isComposing||(q.preventDefault(),q.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(Mn,{size:14})})]}),s.jsxs("label",{className:"block space-y-1 text-[10px] text-muted-foreground",children:["协作组名称",s.jsx("input",{autoFocus:!0,className:Vs,value:N,maxLength:240,disabled:!!a,onChange:q=>I({name:q.target.value})})]}),s.jsx("div",{className:"mt-2 flex justify-end",children:s.jsx("button",{type:"button",disabled:!!a||!!T||!N.trim()||N.trim()===F,className:`${Lr} min-h-9 bg-primary text-primary-foreground`,onClick:()=>{pe()},children:a==="group-name"?"保存中…":"保存名称"})}),s.jsx(YO,{group:e,agents:t,busy:a,setBusy:c,refresh:f}),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:Vs,value:ee,disabled:!!a||!x.length,onChange:q=>I({rulesMemberId:q.target.value}),children:[s.jsx("option",{value:"",children:"选择当前服务的一个成员"}),!x.some(q=>q.sessionId===ee)&&ee&&s.jsx("option",{value:ee,children:"原成员已不在组内,请重新选择"}),x.map(q=>s.jsx("option",{value:q.sessionId,children:q.name},q.sessionId))]})]}),s.jsxs("label",{className:"block space-y-1 text-[10px] text-muted-foreground",children:["群规与协作约定",s.jsx("textarea",{className:`${Vs} min-h-24 resize-y`,value:B,maxLength:8192,disabled:!!a,onChange:q=>I({rules:q.target.value}),placeholder:"例如:说明分工、交接要求和结果格式。清空后保存可移除群规。"})]})]}),!de&&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] ${V>8192?"text-destructive":"text-muted-foreground"}`,children:V>8192?"内容过长,请缩短群规":"保存或清空群规会通知本组其他成员"}),s.jsx("button",{type:"button",disabled:!!a||!!T||!de||V>8192||B===P,className:`${Lr} min-h-9 shrink-0 bg-primary text-primary-foreground`,onClick:()=>{J()},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:`${Lr} mt-2 min-h-11 text-primary hover:bg-surface-elevated`,onClick:()=>{Xe()},children:a==="group-latest"?"读取中…":"查看最新状态并保留草稿"}),T&&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:["当前名称:",T.name]}),s.jsxs("p",{className:"whitespace-pre-wrap break-words text-muted-foreground",children:["当前群规:",T.instructions?.text||"未设置"]}),s.jsxs("p",{className:"break-words text-muted-foreground",children:["当前成员(",T.sessionIds.length,"):",T.sessionIds.map(q=>n.find(ve=>ve.sessionId===q)?.name??w4(q)).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:`${Lr} min-h-11 bg-primary text-primary-foreground`,onClick:()=>{I(iF(v.current,T)),S(null),l(null),d("已确认最新状态,草稿仍保留;请分别保存名称与群规。")},children:"确认最新状态,保留草稿"}),s.jsx("button",{type:"button",className:`${Lr} min-h-11 text-muted-foreground`,onClick:()=>S(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:`${Lr} min-h-9 text-muted-foreground hover:bg-surface-elevated`,onClick:Re,children:[s.jsx(wn,{size:12}),"重新载入",Z&&"(放弃草稿)"]}),s.jsx("button",{type:"button",disabled:!!a,className:`${Lr} min-h-9 bg-surface text-foreground`,onClick:m,children:Z?"关闭并保留草稿":"关闭"})]})]})}function fF({peers:e,currentGroupId:t,busy:r,setBusy:n,setError:a,setNotice:c,onSelectGroup:l}){const[d,f]=b.useState(null),[m,x]=b.useState(!1),y=e.services??[],w=e.removedServices??[],v=y.filter(I=>!I.connected),T=v.some(I=>I.groups?.some(N=>N.id===t)),S=async(I,N)=>{if(!r){n(`peer:${I}`),a(null),c(null);try{N?await f9(I):await p9(I),f(null),x(!1),c(N?"协作连接已恢复,正在连接服务":"协作连接已移除,不会再自动重连;已有会话和消息保留")}catch(B){a(B instanceof Error?B.message:N?"重新连接失败":"移除连接失败")}finally{n(null)}}};return s.jsxs("details",{className:"mt-4 shrink-0 rounded-lg border border-border/15",open:T||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:T?"当前协作组的部分服务不可达,消息会保留并等待重连。":"其他服务暂时离线;当前服务内的协作可以继续。不再使用的连接可移除。"}),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(I=>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:[bc({serviceLabel:I.label,serviceOrigin:I.origin}),s.jsx("span",{className:`ml-2 text-[9px] ${I.connected?"text-[var(--success)]":"text-muted-foreground"}`,children:I.connected?"已连接":I.error==="CONNECTING"?"连接中":"暂时离线"})]}),s.jsx(pF,{service:I})]}),I.serviceId&&s.jsxs("button",{type:"button",disabled:!!r,"aria-label":`移除协作连接 ${I.origin}`,className:`${Lr} min-h-9 shrink-0 text-muted-foreground hover:bg-destructive/10 hover:text-destructive`,onClick:()=>f(d===I.serviceId?null:I.serviceId),children:[s.jsx(Ds,{size:12}),"移除"]})]}),!!I.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:"用于"}),I.groups.map(N=>s.jsx("button",{type:"button",className:"rounded px-1.5 py-1 text-primary hover:bg-primary/10",onClick:()=>l(N.id),children:N.name},N.id))]}),!I.connected&&I.error&&I.error!=="CONNECTING"&&s.jsxs("details",{className:"mt-1 text-[9px] text-muted-foreground",children:[s.jsx("summary",{className:"cursor-pointer",children:AF(I.error)}),s.jsx("p",{className:"mt-1 select-text break-words",children:I.error})]}),d===I.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:I.groups?.length?"请先处理上方协作组的成员,再移除这条连接。":"移除后停止与该服务协作,保留已有会话和消息;以后可重新连接。"}),s.jsxs("div",{className:"mt-2 flex justify-end gap-2",children:[s.jsx("button",{type:"button",disabled:!!r,className:`${Lr} min-h-9 text-muted-foreground`,onClick:()=>f(null),children:"取消"}),s.jsx("button",{type:"button",disabled:!!r||!!I.groups?.length,className:`${Lr} min-h-9 bg-destructive text-destructive-foreground`,onClick:()=>{S(I.serviceId,!1)},children:r===`peer:${I.serviceId}`?"正在移除…":"确认移除"})]})]})]},I.serviceId||I.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:`${Lr} mt-1 min-h-9 text-primary hover:bg-primary/10`,onClick:h9,children:[s.jsx(wn,{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:`${Lr} min-h-9 text-muted-foreground hover:bg-surface-2`,onClick:()=>x(I=>!I),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(I=>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:[bc({serviceLabel:I.label,serviceOrigin:I.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:I.accessUrl||I.origin})]}),s.jsx("button",{type:"button",disabled:!!r||!I.serviceId,className:`${Lr} min-h-9 shrink-0 text-primary hover:bg-primary/10`,onClick:()=>{S(I.serviceId,!0)},children:r===`peer:${I.serviceId}`?"恢复中…":"恢复连接"})]},I.serviceId||I.origin))})]})]})]})]},T?"affected":"other")}function pF({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 Hm(e){return!td(e.sessionId)||e.serviceConnected!==!1}function mF(e){return e.serviceOrigin?e.serviceOrigin===window.location.origin?"":e.serviceOrigin:td(e.sessionId)?.origin??""}function ty(e){const t=new Map;for(const r of e){const n=mF(r),a=t.get(n)??{key:n,label:n?bc(r):"本机服务",sessions:[]};n&&a.label==="远端服务"&&(a.label=bc(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 ry({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(Al,{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 gF(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,...td(n)?{serviceConnected:!1}:{}})}return[...r.values()]}function Wm({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(qc,{size:9}),s.jsx("span",{className:"truncate",children:bc(e)})]})}function yf(e){return e.serviceConnected===!1?"服务不可达":e.status==="recovering"&&e.route_error==="ROUTE_NOT_CHECKED"?"投递目标未检查":yF(e.status)}function xF(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:")?bc(e):"本机服务";return r?`${e.name} · ${n}`:e.name}async function bF(e){e.sessionId.startsWith("remote:")?await G6(e.sessionId):window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:e.sessionId}))}function yF(e){return{ready:"终端可达",shell:"Shell 终端",recovering:"正在检查投递目标",unchecked:"投递目标未检查","terminal-connected":"终端已连接",detached:"终端未连接","agent-exited":"Agent 已退出",offline:"已离线",ambiguous:"需确认目标终端","identity-mismatch":"终端身份已变化",unavailable:"终端暂不可达","service-reachable":"服务可达","service-unreachable":"服务不可达"}[e]??"在线"}function Gm(e){if(!e)return"暂无任务摘要";try{const t=JSON.parse(e);if(typeof t.prompt=="string")return tp(t.prompt)||"暂无任务摘要"}catch{}return tp(e)||"暂无任务摘要"}function vF(e){return{message:"消息",ask:"问题",reply:"回复",task:"任务",handoff:"交接",done:"完成"}[e]}function wF(e,t){const r=new Map(t.map(a=>[a.sessionId,xF(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),a.delivery?.stage==="blocked"&&a.delivery.error&&!l.deliveryErrors.includes(a.delivery.error)&&l.deliveryErrors.push(a.delivery.error);const f={failed:-2,expired:-1,pending:0,delivered:1,read:2,stored:3};f[a.status]<f[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,deliveryErrors:a.delivery?.stage==="blocked"&&a.delivery.error?[a.delivery.error]:[]})}return[...n.values()].sort((a,c)=>c.createdAt-a.createdAt)}function AF(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 Vm({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 TF({active:e,onClose:t,onNewSession:r,setError:n}){const[a,c]=b.useState(""),[l,d]=b.useState([]),[f,m]=b.useState(0),[x,y]=b.useState(),[w,v]=b.useState(50),[T,S]=b.useState(0),[I,N]=b.useState(!1),[B,F]=b.useState(null),[P,$]=b.useState(null),ee=b.useRef(null),Z=b.useRef(0);b.useEffect(()=>{e&&ee.current?.focus({preventScroll:!0})},[e]),b.useEffect(()=>{if(!e)return;const pe=++Z.current,J=new AbortController;let Re;F(null),N(!0);const Xe=async()=>{try{const q=await m9(a.trim(),w,J.signal);if(pe!==Z.current)return;d(q.results),m(q.total??q.results.length),y(q.index),q.index?.building&&(Re=window.setTimeout(()=>{Xe()},2500))}catch(q){pe===Z.current&&!J.signal.aborted&&F(q instanceof Error?q.message:"搜索失败")}finally{pe===Z.current&&N(!1)}};return Re=window.setTimeout(()=>{Xe()},a.trim()?250:0),()=>{window.clearTimeout(Re),J.abort(),++Z.current}},[e,a,w,T]);const V=pe=>{n(null),c(pe),d([]),m(0),v(50)},de=async pe=>{if(!P){if(pe.live){window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:pe.sessionId})),t();return}if(!(!pe.nativeKey&&!pe.resumeHistoryId)){$(pe.sessionId),n(null);try{const J=pe.nativeKey?await g9(pe.nativeKey):await n3(pe.resumeHistoryId);if("sessionId"in J&&J.sessionId)window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:J.sessionId}));else if(J.command)r({mode:"shell",cwd:J.cwd,command:J.command});else throw new Error("这条会话暂时无法恢复,请重新搜索");t()}catch(J){n(J instanceof Error?J.message:"恢复失败")}finally{$(null)}}}};return s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"sticky -top-4 z-20 -mx-4 -mt-4 border-b border-border/15 bg-surface px-4 py-3",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-[13px] font-medium text-foreground",children:"历史会话搜索"}),s.jsx("p",{className:"mt-1 text-[10px] leading-relaxed text-muted-foreground",children:"搜索当前服务的 Codex、Claude 历史对话和 Termdock 终端记录,未启动的会话也能找到并恢复。"})]}),s.jsxs("label",{className:"relative mt-3 block",children:[s.jsx("span",{className:"sr-only",children:"搜索历史会话"}),s.jsx(Wl,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),s.jsx("input",{ref:ee,maxLength:512,className:`${Vs} pl-9 pr-9`,value:a,onChange:pe=>V(pe.target.value),placeholder:"搜索会话名称、对话关键词、目录或 session ID"}),I?s.jsx(wn,{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:()=>V(""),children:s.jsx(Mn,{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()?`找到 ${f} 个会话`:"最近的会话",f>l.length?` · 显示 ${l.length} 个`:""]}),s.jsxs("button",{type:"button",disabled:I,className:`${Lr} text-muted-foreground hover:bg-surface-2 hover:text-foreground`,onClick:()=>S(pe=>pe+1),children:[s.jsx(wn,{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 J=pe.live||!!(pe.nativeKey||pe.resumeHistoryId),Re=P===pe.sessionId?"正在恢复…":pe.live?"打开会话":J?"恢复会话":"仅供查阅",Xe=pe.source==="codex"||pe.source==="claude"?pe.snippet:SF(pe),q=pe.source==="codex"?"Codex 历史":pe.source==="claude"?"Claude 历史":"终端记录",ve=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(Vm,{value:pe.title,query:a})}),s.jsx("p",{className:"mt-0.5 break-all text-[9px] text-muted-foreground",children:s.jsx(Vm,{value:pe.cwd||"项目目录待索引",query:a})})]}),s.jsx("span",{className:`shrink-0 text-[10px] ${pe.live?"text-[var(--success)]":J?"text-primary":"text-muted-foreground"}`,children:Re})]}),Xe&&s.jsx("p",{className:"mt-2 line-clamp-3 break-words text-[10px] leading-relaxed text-foreground/75",children:s.jsx(Vm,{value:Xe,query:a})}),s.jsxs("p",{className:"mt-2 text-[9px] text-muted-foreground",children:[q," · ",rp(pe.updatedAt),a.trim()?` · ${pe.matchCount>=999?"999+":pe.matchCount} 处匹配`:"",J?"":" · 没有可恢复记录"]}),pe.agentNativeSessionId&&s.jsx("p",{className:"mt-1 select-text break-all text-[9px] text-muted-foreground",children:pe.agentNativeSessionId})]});return J?s.jsx("button",{disabled:!!P,onClick:()=>{de(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:ve},pe.nativeKey||pe.sessionId):s.jsx("article",{className:"px-2 py-3",children:ve},pe.sessionId)})}),f>l.length&&w<5e3&&s.jsx("button",{type:"button",disabled:I,className:`${Lr} w-full bg-surface-2 text-foreground`,onClick:()=>v(pe=>pe+50),children:I?"正在加载…":"加载更多会话"}),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:`${Lr} ml-2`,onClick:()=>S(pe=>pe+1),children:"重试"})]}),!I&&!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:`${Lr} mt-3 bg-surface-2 text-foreground`,onClick:()=>V(""),children:"查看最近会话"})]})]})}function tp(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 SF(e){let t=tp(e.snippet);for(const r of[e.title,e.cwd,e.agentSlug])r&&(t=t.split(r).join(" "));return tp(t)}function CF(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 _F(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 rp(e){return new Intl.DateTimeFormat("zh-CN",{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(e)}function kF(e){return e==="running"?"投递中":e==="success"?"已投递":e==="failed"?"投递失败":""}function LF(e){return e==="running"?"text-[var(--warning)]":e==="success"?"text-[var(--success)]":e==="failed"?"text-destructive":"text-muted-foreground"}function IF({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})}const t0=64,ny=10,EF=120;function NF({children:e,open:t,onOpenChange:r,onClose:n,closeLabel:a,closeTitle:c,compact:l}){const d=b.useRef(null),f=b.useRef(null),m=b.useRef(0),[x,y]=b.useState(null),w=x??(t?t0:0);return b.useEffect(()=>{if(!t)return;const v=T=>{T.target instanceof Node&&!d.current?.contains(T.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){f.current=null,y(null);return}!(v.target instanceof Element)||!v.target.closest(".sidebar-session-primary")||(f.current={pointerId:v.pointerId,x:v.clientX,y:v.clientY,startedAt:Date.now(),initialOffset:t?t0:0,offset:t?t0:0,horizontal:!1})}},onPointerMove:v=>{const T=f.current;if(!T||T.pointerId!==v.pointerId)return;const S=v.clientX-T.x,I=v.clientY-T.y;if(!T.horizontal){if(v.defaultPrevented||Date.now()-T.startedAt>=EF||Math.abs(I)>ny){f.current=null;return}if(Math.abs(S)<=ny)return;if(Math.abs(S)<Math.abs(I)*1.5||!t&&S<0){f.current=null;return}T.horizontal=!0,v.currentTarget.setPointerCapture?.(v.pointerId)}v.preventDefault(),T.offset=Math.max(0,Math.min(t0,T.initialOffset+S)),y(T.offset)},onPointerUp:v=>{const T=f.current;!T||T.pointerId!==v.pointerId||(f.current=null,T.horizontal&&(m.current=Date.now()+600,r(T.offset>=t0/2),y(null)))},onPointerCancel:()=>{f.current?.horizontal&&(m.current=Date.now()+600),f.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(Ds,{size:14}),a]})}),e]})}const sy="recoverable-tmux";function RF({sessions:e,loading:t,attachingName:r,onRefresh:n,onRestore:a,onClose:c}){const{t:l}=Hr(),d=Vt(N=>N.collapsedGroups.has(sy)),f=Vt(N=>N.toggleGroupCollapsed),[m,x]=b.useState(null),[y,w]=b.useState(null),[v,T]=b.useState(null),S=b.useRef(!1),I=async N=>{if(!(!c||S.current)){S.current=!0,w(N),T(null);try{await c(N),x(null)}catch(B){T(B instanceof Error?B.message:l("sidebar.closeRecoverableSessionFailed"))}finally{S.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:()=>f(sy),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(Ys,{size:12,className:`shrink-0 ${d?"":"rotate-90"}`}),s.jsx(Wc,{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(wn,{size:11,className:t?"animate-spin":""})})]}),!d&&s.jsx("div",{className:"space-y-0.5",children:e.map(N=>{const B=N.friendlyName?.trim()||N.label?.trim()||N.name,F=cd(N.cwd??null),P=r===N.name,$=m===N.name;return s.jsxs("div",{children:[s.jsxs("div",{className:"flex min-w-0 items-center",children:[s.jsxs("button",{type:"button",disabled:r!==null||y!==null||$,onClick:()=>a(N),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:N.cwd||N.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:P?s.jsx(jn,{size:12,className:"animate-spin"}):s.jsx(ru,{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:[N.program,F].filter(Boolean).join(" · ")||`tmux:${N.name}`})]}),s.jsx("span",{className:"shrink-0 text-[10px] font-medium text-[color:var(--tmux)] group-hover:text-foreground",children:l(P?"sidebar.restoringRecoverableSession":"sidebar.restore")})]}),c&&s.jsx("button",{type:"button",disabled:r!==null||y!==null,onClick:()=>{x(N.name),T(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(Mn,{size:12})})]}),$&&s.jsxs("div",{role:"group","aria-label":l("sidebar.closeSession",{name:B}),className:"space-y-2 rounded-md bg-surface px-2 py-2",children:[s.jsx("p",{className:"text-[11px] text-foreground",children:l("sidebar.confirmCloseRecoverableSession",{name:B})}),v&&s.jsx("p",{role:"alert",className:"text-[11px] text-destructive",children:v}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{type:"button",disabled:y!==null,onClick:()=>{x(null),T(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:()=>{I(N.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===N.name?l("common.loading"):l("sidebar.endRecoverableSession")})]})]})]},N.name)})})]})}const Mu="flex min-h-11 w-full items-center gap-2.5 rounded-lg px-3 text-left text-xs transition hover:bg-surface-2 focus:bg-surface-2 focus:outline-none",iy="min-h-11 rounded-lg px-4 text-xs transition disabled:opacity-40 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary";function MF({group:e,collapsed:t,onOpen:r,onMessages:n,onToggleCollapsed:a,onChanged:c,children:l}){const[d,f]=b.useState(null),[m,x]=b.useState(null),[y,w]=b.useState(""),[v,T]=b.useState(!1),S=b.useRef(!1),[I,N]=b.useState(""),B=b.useRef(null),F=b.useRef(null),P=b.useRef(null),$=b.useRef(null),ee=b.useRef(null),Z=b.useId(),V=Vg(),de=()=>ee.current?.isConnected?ee.current:F.current,pe=()=>{S.current||(x(null),N(""))};eu(P,!!d,()=>f(null),de),eu($,!!m,pe,de);const J=ve=>{ee.current=document.activeElement instanceof HTMLElement&&B.current?.contains(document.activeElement)?document.activeElement:F.current;const qe=F.current?.getBoundingClientRect();f(ve??{x:qe?.left??8,y:qe?.bottom??8})};b.useEffect(()=>{d&&P.current?.querySelector('[role="menuitem"]')?.focus({preventScroll:!0})},[d]),b.useEffect(()=>{if(!d)return;const ve=ce=>{ce.target instanceof Node&&!P.current?.contains(ce.target)&&!B.current?.contains(ce.target)&&f(null)},qe=ce=>{ce.target instanceof Node&&P.current?.contains(ce.target)||f(null)};return document.addEventListener("pointerdown",ve),window.addEventListener("resize",qe),window.addEventListener("scroll",qe,!0),()=>{document.removeEventListener("pointerdown",ve),window.removeEventListener("resize",qe),window.removeEventListener("scroll",qe,!0)}},[d]),b.useLayoutEffect(()=>{if(!d||!P.current)return;const ve=window.visualViewport,qe=(ve?.offsetLeft??0)+8,ce=(ve?.offsetTop??0)+8,ye=Math.min(240,(ve?.width??innerWidth)-16),Te=ce+(ve?.height??innerHeight)-16;Object.assign(P.current.style,{width:`${ye}px`,maxHeight:`${Te-ce}px`,left:`${Math.max(qe,Math.min(d.x,qe+(ve?.width??innerWidth)-16-ye))}px`,top:`${Math.max(ce,Math.min(d.y,Te-P.current.offsetHeight))}px`})},[d]);const Re=ve=>{f(null),ve()},Xe=ve=>{N(""),w(e.name),x({kind:ve,group:e})},q=async()=>{if(!(!m||S.current||m.kind==="rename"&&!y.trim())){S.current=!0,T(!0),N("");try{const ve=m.group,qe=m.kind==="delete"?(await t3(ve.id,ve.updatedAt),null):m.kind==="archive"||m.kind==="unarchive"?await b9(ve,m.kind==="archive"):(await Hl({id:ve.id,name:y.trim(),sessionIds:ve.sessionIds,expectedUpdatedAt:ve.updatedAt})).group;x(null),c(qe)}catch(ve){const qe=ve instanceof Error?ve.message:"操作失败,请重试";N(qe.includes("协作组已变化")?"协作组刚刚发生变化,请取消后重新打开操作。":qe)}finally{S.current=!1,T(!1)}}};return s.jsxs("div",{ref:B,className:"flex min-w-0 items-center","data-sidebar-gesture-ignore":!0,...V(()=>J()),onContextMenu:ve=>{ve.preventDefault(),ve.stopPropagation(),J({x:ve.clientX,y:ve.clientY})},onKeyDown:ve=>{(ve.key==="ContextMenu"||ve.shiftKey&&ve.key==="F10")&&(ve.preventDefault(),ve.stopPropagation(),J())},children:[l,s.jsx("button",{ref:F,type:"button","aria-label":`协作组操作:${e.name}`,title:"协作组操作","aria-haspopup":"menu","aria-expanded":!!d,"aria-controls":d?`${Z}-menu`:void 0,className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-surface-elevated hover:text-foreground focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary md:h-[30px] md:w-7",onClick:ve=>{ve.stopPropagation(),d?f(null):J()},children:s.jsx(Io,{size:14})}),d&&Ks.createPortal(s.jsxs("div",{ref:P,id:`${Z}-menu`,role:"menu",tabIndex:-1,"aria-label":`协作组操作:${e.name}`,"data-sidebar-gesture-ignore":!0,className:"fixed z-popover overflow-y-auto overscroll-contain rounded-xl border border-border/15 bg-surface p-1 shadow-[0_12px_32px_var(--app-shadow-soft)]",onKeyDown:ve=>{const qe=Array.from(ve.currentTarget.querySelectorAll('[role="menuitem"]:not(:disabled)')),ce=qe.indexOf(document.activeElement),ye=ve.key==="ArrowDown"?(ce+1)%qe.length:ve.key==="ArrowUp"?(ce-1+qe.length)%qe.length:ve.key==="Home"?0:ve.key==="End"?qe.length-1:null;ye!==null&&(ve.preventDefault(),ve.stopPropagation(),qe[ye]?.focus({preventScroll:!0})),ve.key==="Tab"&&(ve.preventDefault(),f(null))},children:[s.jsxs("button",{role:"menuitem",tabIndex:-1,className:Mu,onClick:()=>Re(r),children:[s.jsx(ru,{size:15}),"打开看板"]}),s.jsxs("button",{role:"menuitem",tabIndex:-1,disabled:!n,className:`${Mu} disabled:opacity-40`,onClick:()=>Re(()=>n?.()),children:[s.jsx(ud,{size:15}),"成员与消息"]}),s.jsxs("button",{role:"menuitem",tabIndex:-1,className:Mu,onClick:()=>Re(a),children:[s.jsx(Ys,{size:15,className:t?"":"rotate-90"}),t?"展开成员会话":"收起成员会话"]}),s.jsxs("button",{role:"menuitem",tabIndex:-1,className:Mu,onClick:()=>Re(()=>Xe("rename")),children:[s.jsx(qu,{size:15}),"重命名协作组"]}),!e.federated&&s.jsxs("button",{role:"menuitem",tabIndex:-1,className:Mu,onClick:()=>Re(()=>Xe(e.archivedAt===void 0?"archive":"unarchive")),children:[s.jsx(Af,{size:15}),e.archivedAt===void 0?"归档协作组":"恢复显示"]}),s.jsx("div",{role:"separator",className:"mx-2 my-1 h-px bg-border/30"}),s.jsxs("button",{role:"menuitem",tabIndex:-1,className:`${Mu} text-destructive`,onClick:()=>Re(()=>Xe("delete")),children:[s.jsx(Ds,{size:15}),"删除协作组"]})]}),document.body),m&&Ks.createPortal(s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-modal-backdrop bg-black/50 backdrop-blur-sm",onClick:pe}),s.jsxs("section",{ref:$,role:"dialog","aria-modal":"true","aria-labelledby":`${Z}-title`,"aria-describedby":`${Z}-description`,tabIndex:-1,className:"fixed left-1/2 top-1/2 z-modal-panel max-h-[calc(100dvh-2rem)] w-[min(24rem,calc(100vw-2rem))] -translate-x-1/2 -translate-y-1/2 overflow-y-auto rounded-2xl border border-border/15 bg-surface p-4 text-foreground shadow-[0_28px_70px_var(--app-shadow-strong)]",children:[s.jsxs("header",{className:"flex items-center gap-2",children:[s.jsx("h2",{id:`${Z}-title`,className:"min-w-0 flex-1 text-sm font-semibold",children:m.kind==="delete"?"删除协作组":m.kind==="archive"?"归档协作组":m.kind==="unarchive"?"恢复协作组显示":"重命名协作组"}),s.jsx("button",{type:"button","aria-label":"关闭协作组操作",disabled:v,className:"flex h-11 w-11 items-center justify-center rounded-lg hover:bg-surface-2",onClick:pe,children:s.jsx(Mn,{size:16})})]}),s.jsx("p",{id:`${Z}-description`,className:"my-3 break-words text-xs leading-6 text-muted-foreground",children:m.kind==="delete"?s.jsxs(s.Fragment,{children:["确定删除“",m.group.name,"”?协作组及组内消息会被移除,成员终端会保留。此操作无法撤销。",m.group.federated&&"删除会同步到其他服务。"]}):m.kind==="archive"?s.jsxs(s.Fragment,{children:["归档“",m.group.name,"”后,它会从默认侧栏隐藏。组、成员、消息和历史都会保留,之后可以恢复显示。"]}):m.kind==="unarchive"?s.jsxs(s.Fragment,{children:["恢复“",m.group.name,"”的显示后,它会重新出现在侧栏;不会自动恢复已关闭的会话。"]}):"修改协作组的名称。"}),s.jsxs("form",{onSubmit:ve=>{ve.preventDefault(),q()},children:[m.kind==="rename"&&s.jsxs("label",{className:"block text-xs text-muted-foreground",children:["协作组名称",s.jsx("input",{autoFocus:!0,required:!0,maxLength:256,disabled:v,className:"mt-2 min-h-11 w-full rounded-lg border border-border/30 bg-surface-2 px-3 text-sm text-foreground outline-none focus:border-primary",value:y,onChange:ve=>w(ve.target.value)})]}),I&&s.jsx("p",{role:"alert",className:"mt-3 break-words text-xs leading-5 text-destructive",children:I}),s.jsxs("footer",{className:"mt-4 flex justify-end gap-2",children:[s.jsx("button",{type:"button",disabled:v,className:`${iy} bg-surface-2`,onClick:pe,children:"取消"}),s.jsxs("button",{type:"submit",disabled:v||m.kind==="rename"&&!y.trim(),className:`${iy} inline-flex items-center gap-2 ${m.kind==="delete"?"bg-destructive text-destructive-foreground":"bg-primary text-primary-foreground"}`,children:[v&&s.jsx(wn,{size:14,className:"animate-spin"}),v?m.kind==="delete"?"正在删除…":"正在保存…":m.kind==="delete"?"确认删除":m.kind==="archive"?"归档并隐藏":m.kind==="unarchive"?"恢复显示":"保存名称"]})]})]})]})]}),document.body)]})}function jF(e,t){return og(e.filter(r=>r.archivedAt===void 0),t)}function r0(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 n0(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,f=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 T=y.sessionIds.flatMap(S=>{const I=r.get(S);return I?[I]:[]});m.push({kind:"collaboration",id:`collaboration:${y.id}`,group:y,members:T,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(f.has(w.id))continue;f.add(w.id);const v=w.sessionIds.flatMap(T=>{const S=r.get(T);return S?[S]:[]});m.push({kind:"workspace",id:`workspace:${w.id}`,workspace:w,members:v,sessionIds:w.sessionIds})}return m}function ay(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 DF({status:e,detail:t,needsReview:r,inCopyMode:n}){return s.jsx(mO,{status:e,detail:t,needsReview:r,inCopyMode:n})}function oy({isOpen:e,drawerWidthPx:t,onClose:r,onOpen:n,sessions:a,activeSessionId:c,sessionStates:l,onJumpToNextAttention:d,onNewSession:f,onCloseSession:m,onSplitSession:x,onCloseSplit:y,onRemoveFromSplit:w,splitWorkspaces:v,onSetSplitLayout:T,onReorderSplitWorkspace:S,onCombineSplitSessions:I,onReorderSessions:N,onSessionMenu:B,onOpenSettings:F,onOpenQuota:P,updateState:$,updateActionPending:ee=!1,onConfirmUpdateRestart:Z,onRetryUpdate:V,serverHealthState:de,tmuxAvailable:pe=!0,defaultSessionMode:J="shell",push:Re,pinned:Xe,onTogglePinned:q,recoverableTmuxSessions:ve=[],recoverableTmuxSessionsLoading:qe=!1,onRefreshRecoverableTmuxSessions:ce,onCloseRecoverableTmuxSession:ye}){const{t:Te}=Hr(),[,Fe]=b.useState(0),[se,De]=b.useState(null),[_e,Me]=b.useState(!1),[Je,Ne]=b.useState(!1),[ae,ze]=b.useState(null),at=b.useRef(!1),ut=b.useRef(0),me=b.useCallback(W=>{W||(ut.current+=1),Me(W)},[]),[dt,ft]=b.useState(!1),Se=Pi(W=>W.groupId),[We,Le]=b.useState({}),z=dt||Object.keys(We).length>0,ie=b.useRef(!1),ge=b.useRef(!1),[Ge,rt]=b.useState(null);b.useEffect(()=>{let W=!1;return wc().then(Ie=>{W||ie.current||Le(Object.fromEntries(k3(Ie.collaborationPanels?.[ip()]).map(Ye=>[Ye,!0])))}).catch(()=>{}),()=>{W=!0}},[]);const vt=async(W,Ie)=>{ie.current=!0,await Ya({floatingGroupId:Ie},W),Le(Ye=>({...Ye,[W]:Ie!==null}))},[Yt,Ut]=b.useState([]),[Nt,ir]=b.useState(!1),[Mt,Xt]=b.useState(null),[Bt,Wt]=b.useState(null),[xe,et]=b.useState(null),[ot,Et]=b.useState(null),K=Ou(W=>W.tasks),xt=Ou(W=>W.allTasks),[rr,$e]=b.useState(0),[Dr,Ce]=b.useState(null),St=b.useRef(!1),[Ot,tr]=b.useState({}),ct=Ou(W=>W.error),[Ct,or]=b.useState(!1),[Cr,Ir]=b.useState(!1);b.useEffect(()=>iu(()=>{Ou.getState().refresh()},5e3,[k0]),[]);const $r=async W=>(me(!1),ie.current=!0,W?(Pi.getState().open(W),zr(),!0):(ft(!0),zr(),!0)),Tt=kf(W=>W.collaborationGroups),Ft=kf(W=>W.setCollaborationGroups),[we,wt]=b.useState({mode:J}),{preference:it,agents:bt,detecting:An,refresh:xn,selectAgent:rn}=WO(),Oe=b.useRef(null);let _t=!1;if($?.latestVersion)try{_t=IQ($.latestVersion,$.currentVersion)>0}catch{}const mt=!!(_t&&$&&["checking","installing","ready","restarting","error"].includes($.status)),Zt=!!de?.attention,$t=[Te("sidebar.moreActions"),mt&&$?.latestVersion?Te("sidebar.updateAvailable",{version:$.latestVersion}):null].filter(Boolean).join(": "),wr=Vt(W=>W.groupByFolder),Tn=Vt(W=>W.collapsedGroups),Dn=Vt(W=>W.toggleGroupCollapsed),yn=b.useRef(null),un=b.useRef(null),Cn=b.useRef(null),Ur=b.useRef(0),ne=b.useRef(!1),Ze=b.useRef(null),Dt=b.useRef(null),[ur,Pr]=b.useState(!1),qr=b.useRef([]),sn=b.useRef(null),Nr=b.useRef(null),Wr=b.useRef(new Set),_n=b.useRef(null),en=b.useMemo(()=>new Set(v.flatMap(W=>W.sessionIds)),[v]),Fr=b.useMemo(()=>new Map(a.map(W=>[W.id,W])),[a]),Kr=b.useMemo(()=>jF(Tt,new Set(Fr.keys())),[Tt,Fr]),gr=b.useMemo(()=>og(Tt.filter(W=>W.archivedAt!==void 0),new Set(Fr.keys())),[Tt,Fr]),an=b.useCallback(async()=>{const W=++Ur.current;try{const Ie=await ng();if(W!==Ur.current)return;Ft(Array.isArray(Ie.groups)?Ie.groups:[])}catch{if(W!==Ur.current)return;Ft(Ie=>Ie.map(Ye=>({...Ye,remoteSessions:Ye.remoteSessions?.map(nt=>({...nt,status:"offline",serviceConnected:!1}))})))}},[]);b.useEffect(()=>r3(W=>Ft(W.groups)),[]),b.useEffect(()=>{const W=iu(()=>{an()},1e4,["focus",k0]);return()=>{Ur.current+=1,W()}},[an]),b.useEffect(()=>{(e||!z)&&an()},[z,e,an]);const Xr=b.useCallback(()=>{qr.current=Array.from(document.querySelectorAll("[data-collaboration-member], [data-collaboration-background]")).flatMap(W=>{const Ie=W.dataset.collaborationMember??"",Ye=W.hasAttribute("data-collaboration-background"),nt=W.closest("[data-collaboration-group]")?.dataset.collaborationGroup;if(!Ie&&!Ye||!nt)return[];const st=[];for(let yt=W.parentElement;yt;yt=yt.parentElement)st.push({element:yt,top:yt.scrollTop,left:yt.scrollLeft});return[{element:W,sessionId:Ie,groupId:nt,background:Ye,rect:W.getBoundingClientRect(),scrollParents:st}]})},[]),dn=b.useCallback((W,Ie)=>{if(!ne.current)return;document.querySelectorAll("[data-split-exit-drop-index]").forEach(Ee=>Ee.removeAttribute("data-active")),document.querySelectorAll("[data-drop-active]").forEach(Ee=>Ee.removeAttribute("data-drop-active"));const nt=document.elementsFromPoint(W,Ie).map(Ee=>Ee.closest("[data-collaboration-background]")).find(Boolean)?.closest("[data-collaboration-group]");if(nt?.dataset.collaborationGroup){nt.dataset.dropActive="true",Nr.current={kind:"collaboration",groupId:nt.dataset.collaborationGroup,background:!0};return}const st=qr.current.find(Ee=>{if(Ee.sessionId===Dt.current||!Ee.element.isConnected)return!1;const Ve=Ee.scrollParents.reduce((Qe,ar)=>Qe+ar.element.scrollLeft-ar.left,0),ht=Ee.scrollParents.reduce((Qe,ar)=>Qe+ar.element.scrollTop-ar.top,0);return W>=Ee.rect.left-Ve&&W<=Ee.rect.right-Ve&&Ie>=Ee.rect.top-ht+Ee.rect.height*.25&&Ie<=Ee.rect.bottom-ht-Ee.rect.height*.25});if(st?.background){st.element.closest("[data-collaboration-group]")?.setAttribute("data-drop-active","true"),Nr.current={kind:"collaboration",groupId:st.groupId,background:!0};return}if(st&&!v.find(Ve=>Ve.sessionIds.includes(st.sessionId))?.sessionIds.includes(Dt.current??"")){st.element.dataset.dropActive="true",Nr.current={kind:"split",sessionId:st.sessionId,groupId:st.groupId};return}const yt=document.elementsFromPoint(W,Ie).filter(Ee=>{const Ve=Ee.closest("[data-rfd-draggable-id]");return!Ve||!["session:","split-member:","collaboration-member:"].some(ht=>Ve.dataset.rfdDraggableId===`${ht}${Dt.current}`)}),Pt=yt.map(Ee=>Ee.closest("[data-collaboration-group]")).find(Ee=>Ee?.dataset.collaborationGroup);if(Pt?.dataset.collaborationGroup){const Ee=Pt.dataset.collaborationGroup,Ve=yt.map(sr=>sr.closest("[data-collaboration-split]")).find(Boolean),ht=yt.map(sr=>sr.closest("[data-collaboration-member]")).find(Boolean),Qe=ht?.dataset.collaborationMember??Ve?.dataset.splitAnchor,ar=Ee===Ze.current&&v.some(sr=>sr.sessionIds.includes(Qe??"")&&sr.sessionIds.includes(Dt.current??""));if(Qe&&!ar&&(Ee!==Ze.current||!ht&&Ve)){Pt.dataset.dropActive="true";const sr=ht??Ve;sr&&(sr.dataset.dropActive="true"),Nr.current={kind:"split",sessionId:Qe,groupId:Ee}}else{const sr=yt.some(It=>It.closest("[data-collaboration-background]"));(Ee!==Ze.current||sr)&&(Pt.dataset.dropActive="true"),Nr.current={kind:"collaboration",groupId:Ee,background:sr}}return}const ue=Array.from(document.querySelectorAll("[data-sidebar-entity-list-id]")).filter(Ee=>Ee.dataset.sidebarEntityListId===sn.current).find(Ee=>{const Ve=Ee.getBoundingClientRect();return W>=Ve.left&&W<=Ve.right&&Ie>=Ve.top-8&&Ie<=Ve.bottom+8});if(!ue){Nr.current=null;return}const R=Array.from(ue.children).filter(Ee=>Ee instanceof HTMLElement&&Ee.hasAttribute("data-sidebar-entity-index")),U=R.findIndex(Ee=>{const Ve=Ee.getBoundingClientRect();return Ie<Ve.top+Ve.height/2}),X=U<0?R.length:U;Nr.current={kind:"list",listId:ue.dataset.sidebarEntityListId??"",index:X};const be=Array.from(ue.querySelectorAll(":scope > [data-sidebar-entity-index] > [data-split-exit-drop-index]")).find(Ee=>Ee.dataset.splitExitDropIndex===String(X));be instanceof HTMLElement&&(be.dataset.active="true")},[v]);b.useEffect(()=>{const W=Ye=>dn(Ye.clientX,Ye.clientY),Ie=Ye=>{const nt=Ye.touches[0];nt&&dn(nt.clientX,nt.clientY)};return window.addEventListener("pointermove",W),window.addEventListener("touchmove",Ie,{passive:!0}),()=>{window.removeEventListener("pointermove",W),window.removeEventListener("touchmove",Ie)}},[dn]);const Rr=b.useCallback((W,Ie)=>{try{W(Ie)}finally{document.querySelectorAll("[data-sidebar-dragging]").forEach(Ye=>{delete Ye.dataset.sidebarDragging}),ne.current=!1,qr.current=[],Pr(!1),Ze.current=null,Dt.current=null,sn.current=null,Nr.current=null,document.querySelectorAll("[data-split-exit-drop-index]").forEach(Ye=>Ye.removeAttribute("data-active")),document.querySelectorAll("[data-drop-active]").forEach(Ye=>Ye.removeAttribute("data-drop-active"))}},[]),zn=b.useMemo(()=>a.filter(W=>!en.has(W.id)),[a,en]),pn=b.useMemo(()=>{let W=0;for(const Ie of a)l.get(Ie.id)?.agentStatus==="working"&&(W+=1);return W},[a,l]);b.useLayoutEffect(()=>{const W=yn.current,Ie=un.current;if(!e||!W||!Ie){Cn.current=null;return}const Ye=Ie.getBoundingClientRect(),nt=W.getBoundingClientRect(),st={item:W,top:Math.round(nt.top-Ye.top+Ie.scrollTop),height:Math.round(nt.height),viewportHeight:Ie.clientHeight},yt=Cn.current;if(Cn.current=st,yt?.item===st.item&&yt.top===st.top&&yt.height===st.height&&yt.viewportHeight===st.viewportHeight||ne.current||Ie.clientHeight===0)return;const Pt=8,H=nt.top-Ye.top,ue=nt.bottom-Ye.top;H<Pt?Ie.scrollTop+=H-Pt:ue>Ie.clientHeight-Pt&&(Ie.scrollTop+=ue-Ie.clientHeight+Pt)});const Gr=b.useMemo(()=>{if(!wr||!c)return null;const W=l.get(c)?.cwd??null;return dC(W)},[wr,c,l]);b.useEffect(()=>{if(!wr){_n.current=null,Wr.current.clear();return}if(!c){_n.current=null;return}const W=Vt.getState(),Ie=Wr.current,Ye=_n.current,nt=Gr;Ye!==null&&Ye!==nt&&Ie.has(Ye)&&(W.collapsedGroups.has(Ye)||W.toggleGroupCollapsed(Ye),Ie.delete(Ye)),nt!==null&&nt!==""&&W.collapsedGroups.has(nt)&&(W.toggleGroupCollapsed(nt),Ie.add(nt)),_n.current=nt},[wr,c,Gr]),b.useEffect(()=>{e||me(!1)},[e]),b.useEffect(()=>{wt(W=>({...W,command:it?.command}))},[it]),b.useEffect(()=>{if(!_e)return;let W=!1;return ir(!0),Wt(null),Ex().then(Ie=>{W||Ut(Ie)}).catch(()=>{W||Wt(Te("sidebar.resumeHistoryLoadFailed"))}).finally(()=>{W||ir(!1)}),()=>{W=!0}},[_e,Te]),b.useEffect(()=>{if(!se)return;const W=Ie=>{Ie instanceof KeyboardEvent&&Ie.key!=="Escape"||Ie instanceof PointerEvent&&Ie.target instanceof Node&&Oe.current?.contains(Ie.target)||De(null)};return window.addEventListener("pointerdown",W),window.addEventListener("keydown",W),()=>{window.removeEventListener("pointerdown",W),window.removeEventListener("keydown",W)}},[se]);const zr=()=>{!Re&&!Xe&&r()};b.useEffect(()=>{const W=Ie=>{me(!1);const{groupId:Ye,dock:nt}=Ie.detail;ie.current=!0,ns.getState().setDock(Ye,{...nt,preferredWidth:360}),Le(st=>({...st,[Ye]:!0})),Pi.getState().terminal(),zr()};return window.addEventListener("termdock:open-collaboration-messages",W),()=>window.removeEventListener("termdock:open-collaboration-messages",W)},[zr]);const Y=J==="tmux"&&!pe?"shell":J,Be=(W,Ie=!1)=>{if(at.current)return;at.current=!0,Ne(!0),ze(null);const Ye=ut.current;f({...W,shouldActivate:()=>Ye===ut.current&&(W.shouldActivate?.()??!0),onResult:nt=>{if(at.current=!1,Ne(!1),!nt.ok){ze(nt.error);return}Ye===ut.current&&(Ie&&me(!1),zr())}})},Qt=()=>{Be({mode:Y})},er=()=>{it&&Be({mode:Y,command:it.command})},nr=W=>{me(!1),et(W.name),f({mode:"tmux",tmuxSessionName:W.name,cwd:W.cwd??void 0}),zr()};b.useEffect(()=>{xe&&(ve.some(W=>W.name===xe)||et(null))},[xe,ve]);const Or=(W,Ie)=>{Be({...we,cwd:we.cwd?.trim()||void 0,command:Ie??W?.command},!0)},kr=async W=>{Xt(W.id),Wt(null);try{const Ie=await n3(W.id);Be({mode:"shell",cwd:Ie.cwd,command:Ie.command},!0)}catch(Ie){const Ye=Ie&&typeof Ie=="object"&&"code"in Ie?String(Ie.code??""):"";Wt(Te(Ye==="AGENT_SESSION_ACTIVE_ELSEWHERE"?"tab.resumeAgentConflict":"sidebar.resumeHistoryFailed"))}finally{Xt(null)}},Zn=async W=>{Ut(Ie=>Ie.filter(Ye=>Ye.id!==W));try{await L9(W)}catch{Wt(Te("sidebar.resumeHistoryRemoveFailed")),Ex().then(Ut).catch(()=>{})}},ys=()=>{if(_e){me(!1);return}at.current||(ut.current+=1,at.current||ze(null),wt({mode:J==="tmux"&&!pe?"shell":J,cwd:c?l.get(c)?.cwd??void 0:void 0,command:it?.command}),me(!0))},ss=b.useCallback(W=>{const Ie=l.get(W);return Ie?.agentStatus==="waiting"||Ie?.agentNeedsReview?"bg-[rgb(var(--warning-rgb)_/_0.10)] text-foreground":Ie?.agentStatus==="working"?"bg-[rgb(var(--success-rgb)_/_0.08)] text-foreground":Ie?.inCopyMode?"bg-[rgb(var(--tmux-rgb)_/_0.08)] text-foreground":null},[l]),Hn=Vg(),[hn,Qn]=b.useState(null);b.useEffect(()=>{e||Qn(null)},[e]);const Xn=b.useCallback((W,Ie,Ye,nt,st)=>{const yt=!Se&&W.id===c,Pt=en.has(W.id),H=!!(Ye&&Pt),ue=l.get(W.id),R=cd(ue?.cwd??null),U=ue?.shellTitle??y9(W.id),X=U===ue?.cwd||U===R?null:U,be=v9(W,ue?.activeProgram??null,null,w9,X,ue?.promptState??null),Ee=!!(ue?.tuiProgress&&ue.tuiProgress.state!=="remove"),ht=ue?.promptState==="running"||ue?.agentStatus==="working"||Ee?"bg-[var(--success)]":ue?.agentStatus==="waiting"||ue?.agentNeedsReview?"bg-[var(--warning)]":ue?.inCopyMode?"bg-[var(--tmux)]":"bg-primary";return s.jsxs(NF,{open:hn===W.id,onOpenChange:Qe=>Qn(ar=>Qe?W.id:ar===W.id?null:ar),onClose:Qe=>m(W.id,Qe,{skipConfirmation:!0}),closeLabel:Te("common.close"),closeTitle:Te("sidebar.closeSession",{name:be}),compact:Ye,children:[s.jsxs("button",{ref:yt?yn:null,type:"button",...Ie??{},onContextMenu:Qe=>{B&&(Qe.preventDefault(),B(W.id,{x:Qe.clientX,y:Qe.clientY}))},onClick:()=>{me(!1),Pi.getState().terminal(),window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:W.id})),zr()},className:`sidebar-session-primary relative min-w-0 flex flex-1 items-center overflow-hidden text-left ${Ie?"cursor-grab active:cursor-grabbing ":""}${Ye?"gap-1.5 py-0.5 pl-1.5 pr-0.5":"gap-1.5 py-1 pl-2 pr-1"}`,title:ue?.cwd??W.name,children:[yt&&s.jsx("span",{className:`absolute inset-y-2 left-0 w-0.5 rounded-full ${ht}`}),s.jsxs("span",{className:`relative inline-flex shrink-0 items-center justify-center rounded-md ${Ye?"h-5 w-[22px]":"h-[22px] w-[22px]"} ${yt?W.mode==="tmux"?"bg-[rgb(var(--tmux-rgb)_/_0.15)] text-[color:var(--tmux)]":"bg-primary/15 text-primary":W.mode==="tmux"?"bg-surface text-[rgb(var(--tmux-rgb)_/_0.80)]":"bg-surface text-muted-foreground"}`,children:[ue?.isConnecting||Ee&&!ue?.agentStatus?s.jsx(jn,{size:Ye?10:11,className:"animate-spin"}):ue?.agent??Nx(W.id)?s.jsx(Jc,{agent:ue?.agent??Nx(W.id),size:Ye?13:15}):W.mode==="tmux"?s.jsx(ru,{size:Ye?10:11}):s.jsx(Zo,{size:Ye?10:11}),s.jsx(DF,{status:ue?.agentStatus??null,detail:ue?.agentStatusDetail,needsReview:ue?.agentNeedsReview,inCopyMode:ue?.inCopyMode})]}),s.jsx("span",{className:`min-w-0 flex-1 truncate leading-tight ${Ye?"text-[11px]":"text-[12px]"} ${yt?"font-medium text-foreground":""} ${ue?.inCopyMode?"text-[color:var(--tmux)]":""}`,children:be}),s.jsx(db,{sessionIds:[W.id]})]}),nt,s.jsx("button",{type:"button",onClick:Qe=>{Qe.stopPropagation(),H?w(W.id):Pt?y(W.id):x(W.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 ${Ye?"h-6 w-6":"h-[26px] w-[26px]"} ${Pt?"bg-primary/15 text-primary":"text-muted-foreground/70"}`,"aria-label":`${Te(H?"tab.splitRemovePane":Pt?"tab.splitClose":"tab.split")} ${be}`,title:Te(H?"tab.splitRemovePane":Pt?"tab.splitClose":"tab.split"),children:H?s.jsx(XS,{size:11}):s.jsx(Fl,{size:12})}),st??s.jsx("button",{type:"button",onClick:Qe=>{Qe.stopPropagation(),m(W.id,Qe)},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 ${Ye?"h-6 w-6":"h-[26px] w-[26px]"}`,"aria-label":Te("sidebar.closeSession",{name:be}),title:Te("common.close"),children:s.jsx(Mn,{size:Ye?11:12})})]})},[c,en,l,m,x,y,w,B,Te,hn]),fn=b.useMemo(()=>Cf(a,W=>l.get(W.id)?.cwd??null,wr,Te("sidebar.ungrouped"),v,Kr).groups,[Kr,wr,a,l,v,Te]),cr=b.useMemo(()=>n0(a,v,Fr,Kr),[Kr,a,Fr,v]),is=b.useCallback(W=>{Pr(W.draggableId.startsWith("collaboration:")||W.draggableId.startsWith("workspace:"));const Ie=W.draggableId.replace(/^split-member:/,"");Dt.current=W.draggableId.replace(/^(?:session|split-member|collaboration-member):/,"");const Ye=W.type==="split-member"?v.find(H=>H.sessionIds.includes(Ie)):null,nt=W.type==="collaboration-member"?W.source.droppableId.replace(/^collaboration-members:/,""):null,st=nt?Kr.find(H=>H.id===nt):null;ne.current=!!(Ye||st||W.type==="session"&&W.draggableId.startsWith("session:")),ne.current&&document.querySelectorAll("[data-collaboration-group]").forEach(H=>{H.dataset.sidebarDragging="true"}),Ze.current=st?.id??null;const yt=Ye?.sessionIds??st?.sessionIds??[],Pt=yt.length>0?fn.find(H=>yt.every(ue=>H.sessions.some(R=>R.id===ue))):null;sn.current=wr?Pt?`group-sessions:${Pt.key}`:null:yt.length>0?"sidebar-entities":null,Nr.current=null},[Kr,fn,wr,v]),tn=b.useCallback((W,Ie,Ye)=>{if(Ie===Ye)return;const nt=Ie?Tt.find(ue=>ue.id===Ie):null,st=Ye?Tt.find(ue=>ue.id===Ye):null;if(Ye&&!st)return;if(st){const ue=a.map(U=>U.id).filter(U=>U!==W);let R=-1;ue.forEach((U,X)=>{st.sessionIds.includes(U)&&(R=X)}),R>=0&&(ue.splice(R+1,0,W),N(ue))}const yt=nt?.sessionIds.filter(ue=>ue!==W)??[],Pt=st?[...st.sessionIds.filter(ue=>ue!==W),W]:[];Ft(ue=>ue.flatMap(R=>R.id===Ie?[{...R,sessionIds:yt}]:R.id===Ye?[{...R,sessionIds:Pt}]:[R])),Et(null),(nt&&st?A9({sourceGroupId:nt.id,targetGroupId:st.id,sessionId:W,expectedSourceUpdatedAt:nt.updatedAt,expectedTargetUpdatedAt:st.updatedAt}):nt?Hl({id:nt.id,name:nt.name,sessionIds:yt,expectedUpdatedAt:nt.updatedAt}):st?Hl({id:st.id,name:st.name,sessionIds:Pt,expectedUpdatedAt:st.updatedAt}):Promise.resolve()).then(()=>an(),ue=>(Et(ue instanceof Error?ue.message:"协作成员移动失败"),an()))},[Tt,an,a,N]),xr=b.useCallback((W,Ie,Ye,nt=!1)=>{const st=Tt.find(Ve=>Ve.id===W);if(!st||Ie===Ye)return;const yt=st.sessionIds.filter(Ve=>!Ve.startsWith("remote:")),Pt=r0(yt,v).flatMap(Ve=>Ve.sessionIds),H=ob(xt,st.id),ue=nt&&!Ot[st.id]?Pt.filter(Ve=>!H.has(Ve)||Ve===c||en.has(Ve)):Pt.slice(),R=new Set(ue),[U]=ue.splice(Ie,1);if(!U)return;ue.splice(Ye,0,U);let X=0;const be=Pt.map(Ve=>R.has(Ve)?ue[X++]:Ve),Ee=v.find(Ve=>Ve.sessionIds.includes(U));if(Ee&&Ee.sessionIds.every(Ve=>st.sessionIds.includes(Ve))){const Ve=be.filter(ht=>Ee.sessionIds.includes(ht));S(Ee.id,Ve)}be.push(...st.sessionIds.filter(Ve=>Ve.startsWith("remote:"))),Ft(Ve=>Ve.map(ht=>ht.id===W?{...ht,sessionIds:be}:ht)),Et(null),Hl({id:st.id,name:st.name,sessionIds:be,expectedUpdatedAt:st.updatedAt}).then(()=>an(),Ve=>(Et(Ve instanceof Error?Ve.message:"成员排序失败"),an()))},[Tt,an,v,S,xt,Ot,c,en]);b.useEffect(()=>{const W=Ie=>{const{sourceId:Ye,targetId:nt}=Ie.detail;if(!Ye||!nt||Ye===nt)return;const st=Cf(a,Qe=>l.get(Qe.id)?.cwd??null,wr,"",v,Kr).arranged.map(Qe=>Qe.id),yt=st.indexOf(Ye),Pt=st.indexOf(nt);if(yt<0||Pt<0)return;const H=Kr.find(Qe=>Qe.sessionIds.includes(Ye));if(H?.sessionIds.includes(nt)){const Qe=r0(H.sessionIds,v).flatMap(ar=>ar.sessionIds);xr(H.id,Qe.indexOf(Ye),Qe.indexOf(nt));return}const ue=v.filter(Qe=>Qe.sessionIds.length>=2&&Qe.sessionIds.every(ar=>Fr.has(ar))&&!Kr.some(ar=>Qe.sessionIds.some(sr=>ar.sessionIds.includes(sr)))),R=ue.find(Qe=>Qe.sessionIds.includes(Ye));if(R?.sessionIds.includes(nt)){const Qe=[...R.sessionIds];Qe.splice(Qe.indexOf(Ye),1),Qe.splice(R.sessionIds.indexOf(nt),0,Ye),S(R.id,Qe);return}const U=Qe=>Kr.find(ar=>ar.sessionIds.includes(Qe))?.sessionIds??ue.find(ar=>ar.sessionIds.includes(Qe))?.sessionIds??[Qe],X=new Set(U(Ye)),be=new Set(U(nt)),Ee=st.filter(Qe=>!X.has(Qe)),Ve=Ee.flatMap((Qe,ar)=>be.has(Qe)?[ar]:[]),ht=yt<Pt?Math.max(...Ve)+1:Math.min(...Ve);Ee.splice(ht,0,...st.filter(Qe=>X.has(Qe))),N(Ee)};return window.addEventListener("reorder-navigation-session",W),()=>window.removeEventListener("reorder-navigation-session",W)},[a,l,wr,v,Kr,Fr,xr,S,N]);const vr=b.useCallback(W=>{if(W.type!=="collaboration-member")return!1;if(W.reason==="CANCEL")return!0;const Ie=W.source.droppableId.replace(/^collaboration-members:/,""),Ye=W.draggableId.replace(/^collaboration-member:/,""),nt=Nr.current;if(nt?.kind==="split")return tn(Ye,Ie,nt.groupId),I(nt.sessionId,Ye),!0;if(nt?.kind==="collaboration"&&nt.groupId!==Ie)return tn(Ye,Ie,nt.groupId),!0;if(nt?.kind==="collaboration"&&nt.background)return en.has(Ye)&&w(Ye),!0;if(W.destination&&W.destination.droppableId!==W.source.droppableId){const st=W.destination.droppableId.replace(/^collaboration-members:/,"");if(Kr.some(yt=>yt.id===st))return tn(Ye,Ie,st),!0}if(W.combine){const st=W.combine.droppableId.replace(/^collaboration-members:/,"");st!==Ie&&tn(Ye,Ie,st);const yt=W.combine.draggableId.replace(/^collaboration-member:/,"");if(v.find(H=>H.sessionIds.includes(Ye))?.sessionIds.includes(yt)){const H=Kr.find(R=>R.id===Ie),ue=H?r0(H.sessionIds,v).flatMap(R=>R.sessionIds).indexOf(yt):-1;ue>=0&&H&&xr(Ie,r0(H.sessionIds,v).flatMap(R=>R.sessionIds).indexOf(Ye),ue)}else Fr.has(yt)&&I(yt,Ye);return!0}if(W.destination?.droppableId===W.source.droppableId)return xr(Ie,W.source.index,W.destination.index,!0),!0;if(nt?.kind!=="list")return!0;if(nt?.kind==="list"){const st=fn.find(Pt=>`group-sessions:${Pt.key}`===nt.listId),yt=nt.listId==="sidebar-entities"?cr:st?n0(st.sessions,v,Fr,Kr):null;if(yt){const Pt=ay(yt,Ye,nt.index);nt.listId==="sidebar-entities"?N(Pt):st&&N(fn.flatMap(H=>H.key===st.key?Pt:H.sessions.map(ue=>ue.id)))}}return tn(Ye,Ie,null),!0},[Kr,cr,fn,tn,N,xr,Fr,v,en,w,I]),br=b.useCallback(W=>{if(W.type!=="split-member")return!1;if(W.reason==="CANCEL")return!0;const Ie=W.draggableId.replace(/^split-member:/,""),Ye=v.find(ue=>ue.sessionIds.includes(Ie));if(!Ye?.sessionIds.includes(Ie))return!0;const nt=Ye.id,st=Nr.current;if(st?.kind==="split")return tn(Ie,null,st.groupId),I(st.sessionId,Ie),!0;if(st?.kind==="collaboration")return tn(Ie,null,st.groupId),!0;if(!W.destination&&st?.kind==="list"){const ue=fn.find(X=>`group-sessions:${X.key}`===st.listId),R=st.listId==="sidebar-entities"?cr:ue?n0(ue.sessions,v,Fr,Kr):null;if(!R)return!0;const U=ay(R,Ie,st.index);return w(Ie),st.listId==="sidebar-entities"?N(U):ue&&N(fn.flatMap(X=>X.key===ue.key?U:X.sessions.map(be=>be.id))),!0}if(!W.destination)return!0;const yt=W.destination.droppableId.replace(/^split-members:/,"");if(yt!==nt){const R=v.find(U=>U.id===yt)?.sessionIds[0];return R&&I(R,Ie),!0}if(W.source.index===W.destination.index)return!0;const Pt=[...Ye.sessionIds],[H]=Pt.splice(W.source.index,1);return H&&(Pt.splice(W.destination.index,0,H),S(nt,Pt)),!0},[Kr,cr,fn,tn,I,w,N,S,Fr,v]),us=(W,Ie="top")=>s.jsx("div",{"data-split-exit-drop-index":W,className:`group/split-exit pointer-events-none absolute inset-x-0 z-10 h-2 ${Ie==="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"})}),Bn=b.useCallback((W,Ie,Ye)=>{if(vr(W)||br(W)||W.reason==="CANCEL")return;const nt=Ie.find(ue=>ue.id===W.draggableId);if(!nt)return;const st=Nr.current;if(st?.kind==="split"&&nt.kind==="session"){tn(nt.session.id,null,st.groupId),I(st.sessionId,nt.session.id);return}if(st?.kind==="collaboration"&&nt.kind==="session"){tn(nt.session.id,null,st.groupId);return}if(W.combine&&nt.kind!=="session"){const ue=Ie.findIndex(R=>R.id===W.combine?.draggableId);if(ue<0)return;W={...W,combine:null,destination:{...W.source,index:ue}}}if(W.combine){const ue=Ie.find(Ee=>Ee.id===W.combine?.draggableId);if(!ue)return;const R=ue.kind==="workspace"?ue:nt.kind==="workspace"?nt:ue,U=R===nt?ue:nt,X=R.sessionIds[0],be=U.sessionIds[0];X&&be&&X!==be&&I(X,be);return}if(!W.destination||W.source.index===W.destination.index)return;const yt=[...Ie],[Pt]=yt.splice(W.source.index,1);if(!Pt)return;yt.splice(W.destination.index,0,Pt);const H=yt.flatMap(ue=>ue.sessionIds);if(Ye===void 0){N(H);return}N(fn.flatMap(ue=>ue.key===Ye?H:ue.sessions.map(R=>R.id)))},[fn,vr,br,tn,I,N]),vs=b.useCallback(W=>{if(W.reason==="CANCEL"||vr(W)||br(W))return;if(W.type==="group"){if(!W.destination||W.source.index===W.destination.index)return;N(b3(fn,W.source.index,W.destination.index));return}const Ie=W.source.droppableId.replace(/^group-sessions:/,""),Ye=fn.find(st=>st.key===Ie);if(!Ye)return;const nt=n0(Ye.sessions,v,Fr,Kr);if(W.combine||Nr.current?.kind==="collaboration"||Nr.current?.kind==="split"){Bn(W,nt,Ie);return}!W.destination||W.destination.droppableId!==W.source.droppableId||Bn(W,nt,Ie)},[Kr,fn,Fr,v,vr,Bn,br,N]),Bs=W=>{const Ie=se===W.id,Ye=[{layout:"horizontal",label:Te("tab.splitHorizontal"),icon:Fl},{layout:"vertical",label:Te("tab.splitVertical"),icon:Bx},...W.sessionIds.length>=3||W.layout==="grid"?[{layout:"grid",label:Te("tab.splitGrid"),icon:Dx}]:[]],nt=W.layout==="vertical"?Bx:W.layout==="grid"?Dx:Fl,st=Ye.find(yt=>yt.layout===W.layout)?.label??Te("tab.splitHorizontal");return s.jsxs("div",{ref:Ie?Oe:void 0,className:"relative shrink-0",onPointerDown:yt=>yt.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 ${Ie?"bg-primary/15 text-primary":"text-muted-foreground/70 hover:bg-surface-2 hover:text-foreground"}`,"aria-label":`${Te("tab.splitLayout")}: ${st}`,"aria-haspopup":"menu","aria-expanded":Ie,title:Te("tab.splitLayout"),onClick:yt=>{yt.stopPropagation(),De(Pt=>Pt===W.id?null:W.id)},children:s.jsx(nt,{size:12})}),Ie&&s.jsx("div",{role:"menu","aria-label":Te("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:Ye.map(yt=>{const Pt=yt.icon,H=yt.layout===W.layout;return s.jsx("button",{type:"button",role:"menuitemradio","aria-checked":H,"aria-label":yt.label,title:yt.label,className:`sidebar-session-action inline-flex h-7 w-7 items-center justify-center rounded-sm transition active:scale-95 ${H?"bg-primary/15 text-primary":"text-muted-foreground hover:bg-surface-2 hover:text-foreground"}`,onClick:ue=>{ue.stopPropagation(),T(W.sessionIds[0],yt.layout),De(null)},children:s.jsx(Pt,{size:13})},yt.layout)})})]})},Ls=(W,Ie)=>Ie&&s.jsx("button",{type:"button",...Ie,"aria-label":W,title:W,onClick:Ye=>Ye.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(sp,{size:10})}),Qr=(W,Ie,Ye=!1,nt=!1,st)=>{if(Ie.length<2)return null;const yt=Ie.some(X=>X.id===c),Pt=[],H=[],ue=[];for(const X of Ie){const be=l.get(X.id);be?.agentStatus==="waiting"||be?.agentNeedsReview?Pt.push(X):be?.agentStatus==="working"?H.push(X):be?.inCopyMode&&ue.push(X)}const R=W.name?.trim()||`${Te("tab.splitWorkspace")} ${v.findIndex(X=>X.id===W.id)+1}`,U=se===W.id;return s.jsxs("section",{"data-split-workspace":W.id,"aria-label":R,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 ${nt?"bg-primary/15 ring-1 ring-primary/40":Ye?"bg-surface-elevated opacity-90 shadow-lg":Pt.length>0?"bg-[rgb(var(--warning-rgb)_/_0.08)] hover:bg-[rgb(var(--warning-rgb)_/_0.12)]":H.length>0?"bg-[rgb(var(--success-rgb)_/_0.06)] hover:bg-[rgb(var(--success-rgb)_/_0.10)]":ue.length>0?"bg-[rgb(var(--tmux-rgb)_/_0.07)] hover:bg-[rgb(var(--tmux-rgb)_/_0.11)]":yt?"bg-primary/[0.07]":"hover:bg-surface-2"}`,children:[Ls(`移动分屏组 ${R}`,st),s.jsx(Ol,{droppableId:`split-members:${W.id}`,type:"split-member",direction:"vertical",children:(X,be)=>s.jsxs("div",{ref:X.innerRef,...X.droppableProps,"data-split-members":!0,className:be.isDraggingOver?"rounded-sm bg-primary/10 ring-1 ring-primary/40":"",children:[Ie.map((Ee,Ve)=>s.jsx(Pl,{draggableId:`split-member:${Ee.id}`,index:Ve,disableInteractiveElementBlocking:!0,children:(ht,Qe)=>s.jsx("div",{ref:ht.innerRef,...ht.draggableProps,...B?Hn(()=>B(Ee.id)):{},className:`${Ve===0&&U?"relative z-20 ":"relative "}flex items-center rounded-sm pr-0.5 transition-colors ${Qe.isDragging?"bg-surface-elevated opacity-90 shadow-lg ":""}${ss(Ee.id)??(Ee.id===c?"bg-surface-elevated/80 text-foreground":"text-muted-foreground hover:bg-surface-2")}`,children:Xn(Ee,ht.dragHandleProps,!0,Ve===0?Bs(W):void 0)})},Ee.id)),X.placeholder]})})]})},yr=(W,Ie)=>{const Ye=c??Ie;ge.current||!Ye||(me(!1),ge.current=!0,rt(W),Et(null),RC(W,Ye).catch(nt=>Et(nt instanceof Error?nt.message:"消息面板打开失败,请重试")).finally(()=>{ge.current=!1,rt(null)}))},Pn=(W,Ie)=>{Ur.current+=1,Ft(Ye=>Ie?Ye.map(nt=>nt.id===W?Ie:nt):Ye.filter(nt=>nt.id!==W)),Ie||(Pi.getState().groupId===W&&Pi.getState().terminal(),ns.getState().setDock(W,null),Le(Ye=>{const nt={...Ye};return delete nt[W],nt}),requestAnimationFrame(()=>yn.current?.focus({preventScroll:!0})),Ya({floatingGroupId:null},W).catch(()=>Et("协作组已删除,面板布局保存失败,请刷新后检查。"))),an()},Jn=(W,Ie,Ye,nt=!1,st=!1)=>{const yt=`collaboration:${W.id}`,Pt=Tn.has(yt),H=`collaboration-members-${W.id}`,ue=Se===W.id||!Se&&Ie.some(Qe=>Qe.id===c),R=ob(xt,W.id),U=W.sessionIds.filter(Qe=>R.has(Qe)&&Qe!==c&&!en.has(Qe)),X=Ot[W.id]===!0,be=X?W.sessionIds:W.sessionIds.filter(Qe=>!U.includes(Qe)),Ee=r0(be,v),Ve=Ee.flatMap(Qe=>Qe.sessionIds),ht=Ee.length===1?Ee[0]?.workspace:void 0;return s.jsxs("section",{"data-collaboration-group":W.id,"data-collaboration-group-name":W.name,"aria-label":`Agent 工作组:${W.name}`,className:`group/collaboration relative rounded-md ${Pt?"":"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 ${st?"bg-primary/15 ring-1 ring-primary/40":nt?"bg-surface-elevated opacity-90 shadow-lg":ue?"bg-primary/[0.07]":"hover:bg-surface-2"}`,children:[Ls(`移动工作组 ${W.name}`,Ye),s.jsxs(MF,{group:Tt.find(Qe=>Qe.id===W.id)??W,collapsed:Pt,onOpen:()=>{$r(W.id)},onMessages:Ge===null&&(c||Ie.length)?()=>yr(W.id,Ie[0]?.id):void 0,onToggleCollapsed:()=>Dn(yt),onChanged:Qe=>Pn(W.id,Qe),children:[s.jsx("button",{type:"button","aria-label":`${Pt?"展开":"收起"} ${W.name} 的成员会话`,"aria-expanded":!Pt,"aria-controls":H,title:`${Pt?"展开":"收起"}成员会话`,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:Qe=>{Qe.stopPropagation(),Dn(yt)},children:s.jsx(Ys,{size:14,className:Pt?"":"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:`打开 ${W.name} 的协作工作区`,"aria-label":`打开协作工作区:${W.name}`,"aria-current":Se===W.id?"page":void 0,onClick:Qe=>{Qe.stopPropagation(),$r(W.id)},children:[s.jsx(Up,{size:14,className:"shrink-0 text-primary"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:W.name}),K.some(Qe=>Qe.groupId===W.id)&&s.jsxs("span",{className:"shrink-0 text-[10px] font-normal text-primary",children:[K.filter(Qe=>Qe.groupId===W.id).length," 待处理"]})]}),s.jsx("button",{type:"button","aria-label":`成员与消息:${W.name}`,title:"在终端旁打开成员与消息",disabled:Ge!==null||!c&&!Ie.length,"aria-busy":Ge===W.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:Qe=>{Qe.stopPropagation(),yr(W.id,Ie[0]?.id)},children:Ge===W.id?s.jsx(wn,{size:14,className:"animate-spin"}):s.jsx(ud,{size:14})})]}),s.jsx("div",{id:H,children:!Pt&&s.jsxs(s.Fragment,{children:[U.length>0&&s.jsxs("button",{type:"button","aria-expanded":X,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:()=>tr(Qe=>({...Qe,[W.id]:!X})),children:[s.jsx(Ys,{size:12,className:X?"rotate-90":""}),"已完成的执行会话 · ",U.length]}),s.jsx(Ol,{droppableId:`collaboration-members:${W.id}`,type:"collaboration-member",direction:"vertical",isCombineEnabled:!0,children:(Qe,ar)=>s.jsxs("div",{ref:Qe.innerRef,...Qe.droppableProps,"data-collaboration-members":!0,className:`${ar.isDraggingOver?"rounded-sm bg-primary/10":""}`,children:[Ee.map(sr=>s.jsx("div",{"data-collaboration-split":sr.workspace?.id,"data-split-anchor":sr.workspace?.sessionIds[0],role:sr.workspace?"region":void 0,"aria-label":sr.workspace?`${Te("tab.splitWorkspace")} · ${sr.sessionIds.length}`:void 0,className:sr.workspace&&!ht?`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 ${sr.sessionIds.includes(c??"")?"bg-primary/[0.07]":"bg-surface/35"}`:void 0,children:sr.sessionIds.map(It=>{const _r=Fr.get(It);return _r?s.jsx(Pl,{draggableId:`collaboration-member:${_r.id}`,index:Ve.indexOf(_r.id),disableInteractiveElementBlocking:!0,children:(on,bn)=>s.jsxs("div",{ref:on.innerRef,...on.draggableProps,"data-collaboration-member":_r.id,"data-split-member":en.has(_r.id)?"true":void 0,...B?Hn(()=>B(_r.id)):{},className:`${sr.workspace&&It===sr.sessionIds[0]&&se===sr.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 ${bn.combineTargetFor?"bg-primary/15 ring-1 ring-primary/40 ":bn.isDragging?"bg-surface-elevated opacity-90 shadow-lg ":""}${ss(_r.id)??(_r.id===c?"bg-surface-elevated/80 text-foreground":en.has(_r.id)?"bg-primary/[0.05] text-muted-foreground hover:bg-primary/[0.09]":"text-muted-foreground hover:bg-surface-2")}`,children:[Xn(_r,on.dragHandleProps,!0,sr.workspace&&It===sr.sessionIds[0]?Bs(sr.workspace):void 0,R.has(It)?s.jsxs("button",{type:"button","aria-label":`归档 ${_r.name}`,title:"保存 Agent 会话 ID 并停止终端;只回收干净的执行目录,结果和分支保留",disabled:Dr!==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:Jr=>{Jr.stopPropagation(),!St.current&&(St.current=!0,Ce(It),Et(null),_9(It).then(async()=>{$e(mn=>mn+1),await an()}).catch(mn=>Et(mn instanceof Error?mn.message:"归档失败,终端已保留")).finally(()=>{St.current=!1,Ce(null)}))},children:[Dr===It?s.jsx(wn,{size:13,className:"animate-spin"}):s.jsx(Af,{size:13}),s.jsx("span",{className:"text-[10px] md:sr-only",children:"归档"})]}):void 0),!sr.workspace&&en.has(_r.id)&&s.jsx("button",{type:"button",className:"shrink-0 px-1 text-[10px] text-primary",title:`与 ${v.find(Jr=>Jr.sessionIds.includes(_r.id))?.sessionIds.filter(Jr=>Jr!==_r.id).map(Jr=>Fr.get(Jr)?.name??Jr).join("、")} 分屏`,"aria-label":`查看 ${_r.name} 的跨组分屏`,onClick:()=>{me(!1),Pi.getState().terminal(),window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:_r.id})),zr()},children:s.jsx(Fl,{size:10})})]})},_r.id):null})},sr.workspace?.id??sr.sessionIds[0])),Qe.placeholder]})}),s.jsx(_Q,{groupId:W.id,version:rr,onRestore:async Qe=>{me(!1),window.dispatchEvent(new CustomEvent("new-terminal-session",{detail:{mode:"tmux",cwd:Qe.cwd,preferredFrontendSessionId:Qe.sessionId,requireExisting:!0}})),await an(),Pi.getState().terminal(),zr()}}),W.remoteSessions?.map(Qe=>{const ar=k9(Qe),sr=ar==="connected",It=ar==="unknown"?"连接状态未知":"连接已断开";return s.jsxs("button",{type:"button",title:`${bc(Qe)} · ${sr?"服务已连接":It}`,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:()=>{me(!1),G6(Qe.sessionId).catch(()=>{$r(W.id)})},children:[s.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${sr?"bg-primary":"bg-muted-foreground"}`}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:Qe.name}),s.jsx("span",{className:"max-w-20 truncate rounded border border-border/20 px-1 text-[9px]",children:bc(Qe)}),!sr&&s.jsx("span",{className:"shrink-0 text-[9px]",children:It})]},Qe.sessionId)})]})}),s.jsx("div",{"data-collaboration-background":!0,className:Pt?"absolute inset-0 pointer-events-none":"h-1.5"})]})},es=(W,Ie,Ye)=>s.jsx(Vu,{onBeforeCapture:Xr,onDragStart:is,onDragEnd:nt=>Rr(st=>Bn(st,W,Ye),nt),children:s.jsx(Ol,{droppableId:Ie,direction:"vertical",isCombineEnabled:!ur,children:nt=>s.jsxs("div",{ref:nt.innerRef,...nt.droppableProps,"data-sidebar-entity-list-id":Ie,className:"flex-1 space-y-0.5",children:[W.map((st,yt)=>s.jsx(Pl,{draggableId:st.id,index:yt,disableInteractiveElementBlocking:!0,children:(Pt,H)=>s.jsxs("div",{ref:Pt.innerRef,...Pt.draggableProps,"data-sidebar-gesture-ignore":!0,"data-sidebar-entity-index":yt,className:"relative",children:[us(yt),yt===W.length-1&&us(W.length,"bottom"),st.kind==="workspace"?Qr(st.workspace,st.members,H.isDragging,!!H.combineTargetFor,Pt.dragHandleProps):st.kind==="collaboration"?Jn(st.group,st.members,Pt.dragHandleProps,H.isDragging,!!H.combineTargetFor):s.jsx("div",{...B?Hn(()=>B(st.session.id)):{},className:`group relative flex items-center gap-1 rounded-md pr-1 transition-colors ${H.combineTargetFor?"bg-primary/15 text-foreground ring-1 ring-primary/40":H.isDragging?"bg-surface-elevated text-foreground opacity-90 shadow-lg":ss(st.session.id)??(!Se&&st.session.id===c?"bg-surface-elevated text-foreground":"text-muted-foreground hover:bg-surface-2")} cursor-grab active:cursor-grabbing`,children:Xn(st.session,Pt.dragHandleProps)})]})},st.id)),nt.placeholder]})})}),oi=s.jsxs("div",{className:"relative flex min-h-0 flex-1 flex-col",children:[s.jsx(UO,{label:Te("sidebar.sessions"),count:a.length,badge:pn>0?s.jsx(l4,{count:pn,tone:"running",title:Te("agent.aiRunning")}):null,pinned:!!Xe,onClose:r,onTogglePinned:q?()=>{me(!1),q()}:void 0,serverAttention:Zt,onOpenSettings:()=>{me(!1),F()},actions:[...P?[{label:Te("sidebar.subscriptionQuota"),icon:oT,onSelect:()=>{me(!1),P()}}]:[],{label:"Agent 工作台",icon:Up,onSelect:()=>{me(!1),$r(null)}},{label:"服务与设备",icon:T9,onSelect:()=>{me(!1),S9()}},{label:Te("sidebar.settings"),icon:f3,onSelect:()=>{me(!1),F()}}]}),ot&&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:ot}),s.jsx("button",{type:"button","aria-label":"关闭协作错误提示",className:"shrink-0",onClick:()=>Et(null),children:s.jsx(Mn,{size:14})})]}),s.jsxs("div",{ref:un,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:[K.length>0&&s.jsxs("section",{className:"mb-2 rounded-lg border border-primary/20 bg-primary/5","aria-label":"协作待处理事项",children:[K.length>0&&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":Ct,onClick:()=>or(W=>!W),children:[s.jsx(Up,{size:14}),s.jsx("span",{className:"min-w-0 flex-1",children:"需要你处理"}),s.jsx("span",{children:K.length}),s.jsx(Ys,{size:12,className:Ct?"rotate-90":""})]}),(Ct||K.length===0)&&s.jsxs("div",{className:"space-y-1 p-1 pt-0",children:[ct&&s.jsxs("p",{role:"alert",className:"px-2 py-2 text-[11px] text-destructive",children:[ct,s.jsx("button",{type:"button",className:"ml-2 text-primary",onClick:()=>{Ou.getState().refresh()},children:"重试"})]}),K.map(W=>s.jsxs("button",{type:"button",className:"min-h-11 w-full rounded-md px-2 py-2 text-left hover:bg-surface-2",onClick:()=>{cb(W.groupId,W.id),$r(W.groupId).then(Ie=>{Ie&&cb(W.groupId,W.id)})},children:[s.jsx("span",{className:"block truncate text-xs text-foreground",children:W.title}),s.jsxs("span",{className:"mt-1 block truncate text-[10px] text-muted-foreground",children:[Tt.find(Ie=>Ie.id===W.groupId)?.name??"协作组"," · ",ou(W)]})]},W.id))]})]}),s.jsx(RF,{sessions:ve,loading:qe,attachingName:xe,onRefresh:ce,onRestore:nr,onClose:ye}),gr.length>0&&s.jsxs("section",{className:"mb-1","aria-label":"已归档协作组",children:[s.jsxs("button",{type:"button",className:"flex min-h-10 w-full items-center gap-2 rounded-md px-2 text-left text-[11px] text-muted-foreground hover:bg-surface-2","aria-expanded":Cr,onClick:()=>Ir(W=>!W),children:[s.jsx(Af,{size:13}),s.jsx("span",{className:"flex-1",children:"已归档协作组"}),s.jsx("span",{children:gr.length}),s.jsx(Ys,{size:12,className:Cr?"rotate-90":""})]}),Cr&&s.jsx("div",{className:"space-y-1",children:gr.map(W=>s.jsx(Vu,{onDragEnd:()=>{},children:Jn(W,W.sessionIds.flatMap(Ie=>Fr.get(Ie)??[]))},W.id))})]}),Kr.filter(W=>!W.sessionIds.length).map(W=>s.jsx(Vu,{onDragEnd:()=>{},children:Jn(W,[])},W.id)),a.length===0?s.jsxs("div",{className:"rounded-xl bg-surface-2/60 px-4 py-8 text-center",children:[s.jsx(Zo,{size:26,className:"mx-auto mb-2 text-muted-foreground"}),s.jsx("p",{className:"text-[12px] text-muted-foreground",children:Te("sidebar.noSessions")})]}):zn.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:Te("sidebar.noMatchingSessions")})}):wr?s.jsx("div",{className:"flex flex-1 flex-col",children:s.jsx(Vu,{onBeforeCapture:Xr,onDragStart:is,onDragEnd:W=>Rr(vs,W),children:s.jsx(Ol,{droppableId:"sidebar-groups",type:"group",direction:"vertical",children:W=>s.jsxs("div",{ref:W.innerRef,...W.droppableProps,className:"flex flex-1 flex-col space-y-1.5",children:[fn.map((Ie,Ye)=>{const nt=Tn.has(Ie.key),st=!nt&&Ye===fn.length-1,yt=n0(Ie.sessions,v,Fr,Kr);let Pt=0,H=0;for(const R of Ie.sessions){const U=l.get(R.id);U?.agentStatus==="working"&&(Pt+=1),(U?.agentStatus==="waiting"||U?.agentNeedsReview)&&(H+=1)}const ue=Ie.key==="";return s.jsx(Pl,{draggableId:`sidebar-group:${Ie.key||"__ungrouped__"}`,index:Ye,isDragDisabled:ue,disableInteractiveElementBlocking:!0,children:(R,U)=>s.jsxs("div",{ref:R.innerRef,...R.draggableProps,className:`shrink-0 rounded-md transition-colors ${st?"flex flex-1 flex-col ":""}${U.isDragging?"bg-surface-elevated shadow-lg opacity-90":""}`,children:[s.jsxs("button",{type:"button",...ue?{}:R.dragHandleProps,onClick:()=>{Dn(Ie.key),Wr.current.delete(Ie.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 ${ue?"":"cursor-grab active:cursor-grabbing"}`,title:Ie.key||Ie.label,children:[s.jsx(Ys,{size:13,className:`shrink-0 transition-transform ${nt?"":"rotate-90"}`}),s.jsx("span",{className:"min-w-0 flex-1 truncate text-[11.5px] font-semibold uppercase tracking-wide",children:Ie.label}),Pt>0&&s.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--success)] animate-pulse"}),H>0&&s.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--warning)] animate-pulse"}),s.jsx(db,{sessionIds:Ie.sessions.map(X=>X.id)}),s.jsx("span",{className:"shrink-0 text-[10.5px] text-muted-foreground/70",children:Ie.sessions.length})]}),!nt&&s.jsx("div",{className:`mt-0.5 pl-2 ${st?"flex flex-1 flex-col":""}`,children:s.jsx(Ol,{droppableId:`group-sessions:${Ie.key}`,type:"session",direction:"vertical",isCombineEnabled:!ur,children:X=>s.jsxs("div",{ref:X.innerRef,...X.droppableProps,"data-sidebar-entity-list-id":`group-sessions:${Ie.key}`,className:`${st?"flex-1 ":""}space-y-0.5`,children:[yt.map((be,Ee)=>s.jsx(Pl,{draggableId:be.id,index:Ee,disableInteractiveElementBlocking:!0,children:(Ve,ht)=>s.jsxs("div",{ref:Ve.innerRef,...Ve.draggableProps,"data-sidebar-gesture-ignore":!0,"data-sidebar-entity-index":Ee,className:"relative",children:[us(Ee),Ee===yt.length-1&&us(yt.length,"bottom"),be.kind==="workspace"?Qr(be.workspace,be.members,ht.isDragging,!!ht.combineTargetFor,Ve.dragHandleProps):be.kind==="collaboration"?Jn(be.group,be.members,Ve.dragHandleProps,ht.isDragging,!!ht.combineTargetFor):s.jsx("div",{...B?Hn(()=>B(be.session.id)):{},className:`group relative flex items-center gap-1 rounded-md pr-1 transition-colors ${ht.combineTargetFor?"bg-primary/15 text-foreground ring-1 ring-primary/40":ht.isDragging?"bg-surface-elevated text-foreground opacity-90 shadow-lg":ss(be.session.id)??(!Se&&be.session.id===c?"bg-surface-elevated text-foreground":"text-muted-foreground hover:bg-surface-2")} cursor-grab active:cursor-grabbing`,children:Xn(be.session,Ve.dragHandleProps)})]})},be.id)),X.placeholder]})})})]})},Ie.key||"__ungrouped__")}),W.placeholder]})})})}):es(cr,"sidebar-entities")]}),s.jsx(C9,{onReselect:()=>{d&&(Cn.current=null,Fe(W=>W+1),d())}}),_e&&s.jsx(FO,{directories:a.flatMap(W=>{const Ie=l.get(W.id)?.cwd;return Ie?[Ie]:[]}),tmuxAvailable:pe,options:we,launchPending:Je,launchError:ae?Te(l1(ae)):null,agents:bt,selectedAgent:it,detecting:An,resumeHistory:Yt,resumeHistoryLoading:Nt,resumeHistoryPendingId:Mt,resumeHistoryError:Bt,onRefreshAgents:()=>{xn().catch(()=>{})},onSelectAgent:W=>{rn(W).catch(()=>{})},onLaunchAgent:Or,onResumeHistory:W=>{kr(W)},onRemoveResumeHistory:W=>{Zn(W)},onClose:()=>me(!1),onOptionsChange:wt,additionalContent:mt&&$?.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(wn,{size:13,className:$.status==="checking"||$.status==="installing"||$.status==="restarting"?"animate-spin":""})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block font-semibold",children:Te("sidebar.updateAvailable",{version:$.latestVersion})}),s.jsx("span",{className:"mt-0.5 block text-[10.5px] leading-relaxed text-muted-foreground",children:$.status==="checking"?Te("settings.updateChecking"):$.status==="installing"?Te("sidebar.updateInstalling"):$.status==="ready"?Te("sidebar.updateReady"):$.status==="restarting"?Te("sidebar.updateRestarting"):$.error||Te("sidebar.updateFailed")})]})]}),$.status==="ready"&&Z&&s.jsx("button",{type:"button",disabled:ee,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:Te("sidebar.updateRestart")}),$.status==="error"&&V&&s.jsx("button",{type:"button",disabled:ee,onClick:V,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:Te("sidebar.updateRetry")})]})}),dt&&s.jsx(Xb,{onEnterGroup:async W=>{if(!await $r(W))throw new Error("协作组已保存,打开工作区失败,请重试");ft(!1)},onFloatingChange:async W=>{if(W){if(!await $r(W))throw new Error("打开协作工作区失败");ft(!1)}},activeSessionId:c,defaultSessionMode:J,onClose:()=>ft(!1),onNewSession:W=>f(W)}),Object.entries(We).map(([W,Ie])=>s.jsx(Xb,{activeSessionId:c,initialCollaborationGroupId:W,initialFloating:Ie,visible:!Se,onEnterGroup:async Ye=>{if(Ye===W){await $r(Ye);return}if(!await $r(Ye))throw new Error("协作组已保存,打开工作区失败,请重试");await Ya({floatingGroupId:null},W),Le(nt=>{const st={...nt};return delete st[W],st})},onFloatingChange:Ye=>vt(W,Ye),defaultSessionMode:J,onClose:()=>{ie.current=!0,Le(Ye=>{const nt={...Ye};return delete nt[W],nt})},onNewSession:Ye=>f(Ye)},W)),!_e&&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:[ae&&s.jsx("p",{role:"alert",className:"mb-2 text-[11px] leading-relaxed text-destructive",children:Te(l1(ae))}),s.jsxs("div",{className:`grid gap-1.5 [&>button]:min-h-11 [&>button]:shadow-none [&>button]:ring-0 md:[&>button]:min-h-0 ${it?"grid-cols-[minmax(0,1fr)_minmax(0,1fr)_2.5rem]":"grid-cols-[minmax(0,1fr)_2.5rem]"}`,children:[s.jsxs("button",{type:"button",onClick:Qt,disabled:Je,"aria-busy":Je,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] ${it?"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:Te("sidebar.newSession"),"aria-label":Te("sidebar.newSession"),children:[s.jsx(Zo,{size:15,className:"shrink-0"}),s.jsx("span",{className:"truncate",children:Je?Te("sidebar.sessionCreating"):"Terminal"})]}),it&&s.jsxs("button",{type:"button",onClick:er,disabled:Je,"aria-busy":Je,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:Te("sidebar.newSessionWithAgent",{agent:it.displayName}),"aria-label":Te("sidebar.newSessionWithAgent",{agent:it.displayName}),children:[s.jsx(Jc,{agent:it,size:15}),s.jsx("span",{className:"truncate",children:it.displayName})]}),s.jsxs("button",{type:"button",onClick:ys,disabled:Je,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:$t,"aria-label":$t,"aria-expanded":_e,"aria-controls":"sidebar-launch-options",children:[s.jsx(Io,{size:15}),mt&&s.jsx("span",{className:"absolute right-0.5 top-0.5 h-2 w-2 rounded-full bg-[var(--warning)] ring-2 ring-[var(--chrome-bg)]","aria-hidden":"true"})]})]})]})]});return Xe?s.jsx("div",{"data-session-sidebar-pinned":!0,className:"h-full flex flex-col app-chrome-bg border-r border-border",children:oi}):s.jsx(i4,{side:"left",isOpen:e,drawerWidthPx:t,onClose:r,onOpen:n,push:Re,children:oi})}function BF(e,t,r,n,a){let c=t,l=null,d=!1;const f=e.style.width,m=document.body.style.cursor,x=document.body.style.userSelect,y=()=>n(r+c-t),w=()=>{l=null,e.style.width=`${y()}px`},v=N=>{c=N.clientX,l===null&&(l=requestAnimationFrame(w))},T=N=>{d||(d=!0,window.removeEventListener("mousemove",v),window.removeEventListener("mouseup",S),window.removeEventListener("blur",I),l!==null&&cancelAnimationFrame(l),l=null,document.body.style.cursor=m,document.body.style.userSelect=x,N?(w(),y()!==r&&a(y())):e.style.width=f)},S=N=>{c=N.clientX,T(!0)},I=()=>T(!0);return document.body.style.cursor="col-resize",document.body.style.userSelect="none",window.addEventListener("mousemove",v),window.addEventListener("mouseup",S),window.addEventListener("blur",I),()=>T(!1)}function QF(){const{t:e}=Hr();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 PF({slow:e=!1}){const{t}=Hr();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 A4=()=>Vc(()=>import("./RightSidebar-scaBEaFJ.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})),OF=b.lazy(A4);function ly(e){const t=b.useRef(!1);b.useEffect(()=>{const f=navigator.connection;if(!(f?.saveData||/2g|3g/.test(f?.effectiveType??"")))return ug(()=>{A4().catch(()=>{})},3e3)},[]);const{t:r}=Hr(),n=Vt(f=>f.rootPath),a=Vt(f=>f.rightTab),c=Vt(f=>f.setRightTab),l=n?.replace(/\/+$/,"").split("/").pop()||r("rightSidebar.workspace");(e.isOpen||e.pinned)&&(t.current=!0);const d=s.jsx(i4,{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:[Wl,AS,Io].map((f,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(f,{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(Mn,{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",$A,"rightSidebar.tabGit"],["diff",zA,"rightSidebar.tabChanges"],["files",tu,"rightSidebar.tabFiles"],["architecture",oS,"architecture.tab"],["computer",I9,"rightSidebar.tabComputer"]].map(([f,m,x])=>s.jsxs("button",{type:"button",onClick:()=>c(f),className:`flex items-center justify-center gap-1 rounded px-2 py-1.5 text-[11px] font-medium ${a===f?"bg-surface-elevated text-foreground":"text-muted-foreground"}`,children:[s.jsx(m,{size:12}),r(x)]},f))}),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(PF,{}):s.jsx(QF,{})})]})});return t.current?s.jsx(b.Suspense,{fallback:d,children:s.jsx(OF,{...e})}):d}const cy=vc(e=>({overlay:"off",setOverlay:t=>e({overlay:t})}));function FF(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 $F=vc((e,t)=>({sessions:new Map,activeSessionId:null,nextSessionNumber:1,createSession:r=>{const n=L3(),a=Date.now(),c=t().sessions,l=FF(c),d={id:n,cwd:r,sessionId:null,name:l,customName:!1,createdAt:a,lastActivity:a};return e(f=>{const m=new Map(f.sessions);return m.set(n,d),{sessions:m,activeSessionId:f.activeSessionId??n,nextSessionNumber:f.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})}})),UF=[7e5,1e6,14e5,18e5,24e5,32e5,4e6,5e6,6e6,8e6,1e7,12e6].map(e=>({id:"auto",maxSize:1600,bitRate:e,maxFps:30}));class zF{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 UF[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 f=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<f)this.level++,this.lastUpgrade=r;else return null;return this.lastChange=r,this.badSince=this.goodSince=null,this.quality}}async function cu(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 HF(){return cu("/api/android/devices")}async function WF(e){return cu("/api/android/connect",{method:"POST",body:JSON.stringify({address:e})})}const np=[{id:"low",maxSize:720,bitRate:12e5,maxFps:30},{id:"medium",maxSize:1080,bitRate:4e6,maxFps:30},{id:"high",maxSize:1600,bitRate:8e6,maxFps:60}],H0=np[1];function X1(e){if(!e||typeof e!="object")return H0;const t=e;if(t.id==="auto")return{id:"auto",maxSize:1600,bitRate:4e6,maxFps:30};const r=np.find(l=>l.id===t.id);if(r)return r;if(t.id!=="custom")return H0;const n=typeof t.maxSize=="number"?Math.max(360,Math.min(2160,Math.round(t.maxSize))):1080,a=typeof t.bitRate=="number"?Math.max(3e5,Math.min(3e7,Math.round(t.bitRate))):4e6,c=typeof t.maxFps=="number"?Math.max(0,Math.min(60,Math.round(t.maxFps))):30;return{id:"custom",maxSize:n,bitRate:a,maxFps:c}}function GF(e,t){if(!/^[0-9a-zA-Z_.:\-]{1,128}$/.test(e))throw new Error("INVALID_SERIAL");const r=new URLSearchParams;t&&(r.set("max_size",String(t.maxSize)),r.set("bit_rate",String(t.bitRate)),t.maxFps>0&&r.set("max_fps",String(t.maxFps)));const n=r.toString();return`/api/android/${e}/ws${n?`?${n}`:""}`}function uy(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 VF(e){return cu(`/api/android/recordings?serial=${encodeURIComponent(e)}`)}function qF(e){return cu("/api/android/recordings",{method:"POST",body:JSON.stringify({serial:e})})}function YF(e){return cu(`/api/android/recordings/${encodeURIComponent(e)}/stop`,{method:"POST"})}function ZF(e,t){return cu(`/api/android/recordings/${encodeURIComponent(e)}/save`,{method:"POST",body:JSON.stringify({directory:t})})}function KF(e){return cu(`/api/android/recordings/${encodeURIComponent(e)}`,{method:"DELETE"})}const XF=0,JF=1,e$=2,t$=3,r$=4,n$=5,s$=7,i$=10,a$=11,o$=16,dy=17,hy=0,qm=1,l$=2,fy=3,Ym=0,py=1,my=1,ju=0xffffffffffffffffn,Wh=0xfffffffffffffffen,s0={HOME:3,APP_SWITCH:187,POWER:26,VOLUME_UP:24,VOLUME_DOWN:25};function T4(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 c$(e,t,r,n,a,c){const l=new Uint8Array(32),d=new DataView(l.buffer);return d.setUint8(0,e$),d.setUint8(1,e),d.setBigUint64(2,t),T4(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 Zm(e,t,r=0,n=0){const a=new Uint8Array(14),c=new DataView(a.buffer);return c.setUint8(0,XF),c.setUint8(1,e),c.setUint32(2,t>>>0),c.setUint32(6,r>>>0),c.setUint32(10,n>>>0),a}function u$(e,t,r,n=0){const a=new Uint8Array(21),c=new DataView(a.buffer);c.setUint8(0,t$),T4(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 d$(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,JF),a.setUint32(1,r.length),n.set(r,5),n}function h$(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]=o$,r[1]=t.length,r.set(t,2),r}function i0(e){return new Uint8Array([e])}function gy(e){return new Uint8Array([r$,e])}function f$(e){return new Uint8Array([i$,e?1:0])}function p$(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}function m$(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 Km(e){return e.toString(16).padStart(2,"0")}function S4(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 f=l+1;for(;f+2<e.length&&!(e[f]===0&&e[f+1]===0&&(e[f+2]===1||e[f+2]===0&&e[f+3]===1));)f++;return e.subarray(l,Math.min(e.length,f))}return null}function g$(e){const t=e?S4(e,7,!1):null;return t&&t.length>=4?`avc1.${Km(t[1])}${Km(t[2])}${Km(t[3])}`:"avc1.42e01e"}function x$(e){const t=e?S4(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 b${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=E9(GF(t,r))}catch(a){this.callbacks.onState("error",a instanceof Error?a.message:"ANDROID_STREAM_FAILED");return}this.socket=n,n.onopen=()=>{this.lastMessageAt=Date.now()},n.onmessage=a=>{this.closedByUser||this.handleMessage(a.data)},n.onerror=()=>{this.closedByUser||this.callbacks.onState("error","SCRCPY_CONNECTION_LOST")},n.onclose=()=>{this.finishBitrate(!1,"BITRATE_CONNECTION_CLOSED: preview connection closed"),this.liveBitrate=!1,this.teardownTimers(),this.closedByUser?this.callbacks.onState("idle"):this.callbacks.onState("error","SCRCPY_CONNECTION_CLOSED")},this.startTimers()}disconnect(){this.closedByUser=!0,this.finishBitrate(!1),this.liveBitrate=!1,this.teardownTimers();try{this.decoder?.close()}catch{}this.decoder=null,this.configured=!1;try{this.socket?.close()}catch{}this.socket=null,this.callbacks.onState("idle")}teardownTimers(){this.heartbeat&&clearInterval(this.heartbeat),this.statsTimer&&clearInterval(this.statsTimer),this.stallTimer&&clearInterval(this.stallTimer),this.heartbeat=null,this.statsTimer=null,this.stallTimer=null}startTimers(){this.lastSampleAt=Date.now(),this.heartbeat=setInterval(()=>{if(!(!this.socket||this.socket.readyState!==1)){if(Date.now()-this.lastMessageAt>45e3){try{this.socket.close()}catch{}return}this.pingAt===null&&(this.pingAt=performance.now(),this.send({type:"ping"}))}},this.autoQuality?2e3:15e3),this.stallTimer=setInterval(()=>{if(!this.header||this.closedByUser)return;const t=Date.now();t-this.lastFrameAt>8e3&&t-this.lastResetAt>8e3&&(this.lastResetAt=t,console.warn("[android] no frames for 8s; requesting keyframe reset"),this.sendControl(i0(dy)))},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:p$(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=m$(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(i0(dy))}})}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=[g$(this.configData),"avc1.42e01e","avc1.4d401e","avc1.64001f"].filter((l,d,f)=>f.indexOf(l)===d),r.avc={format:"annexb"}):t==="h265"?(n=[x$(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===qm||t===fy,l=c?0:1,d=a===ju&&!c?my:0,f=(t===hy||t===qm)&&a===ju?my:0;this.sendControl(c$(t,a,this.pointerPoint(r,n),l,f,d))}pointerDown(t,r,n){this.touch(hy,t,r,n==="mouse"?ju:Wh)}pointerMove(t,r,n){this.touch(l$,t,r,n==="mouse"?ju:Wh)}pointerUp(t,r,n){this.touch(qm,t,r,n==="mouse"?ju:Wh)}pointerCancel(t,r,n){this.touch(fy,t,r,n==="mouse"?ju:Wh)}scroll(t,r,n,a){this.sendControl(u$(this.pointerPoint(t,r),n,a))}key(t,r=Ym){this.sendControl(Zm(r,t))}tapKey(t){this.sendControl(Zm(Ym,t)),this.sendControl(Zm(py,t))}back(){this.sendControl(gy(Ym)),this.sendControl(gy(py))}home(){this.tapKey(s0.HOME)}recents(){this.tapKey(s0.APP_SWITCH)}power(){this.tapKey(s0.POWER)}volumeUp(){this.tapKey(s0.VOLUME_UP)}volumeDown(){this.tapKey(s0.VOLUME_DOWN)}rotate(){this.sendControl(i0(a$))}expandNotifications(){this.sendControl(i0(n$))}collapsePanels(){this.sendControl(i0(s$))}setDisplayPower(t){this.sendControl(f$(t))}sendText(t){this.sendControl(d$(t))}startApp(t){this.sendControl(h$(t))}}function y$(){try{return crypto.randomUUID().slice(0,8)}catch{return Math.random().toString(36).slice(2,10)}}function v$(){return`termdock-mirror-shot-${new Date().toISOString().replace(/[-:T]/g,"").slice(0,14)}-${y$()}.png`}function xy(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 w$(e,t=v$()){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 C4(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 by(e,t,r,n,a){const c=Math.max(1,Math.min(8,e.zoom*a)),l=c/e.zoom;return{zoom:c,pan:C4({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 _4(e,t){return t?new Promise((r,n)=>{const a=crypto.randomUUID(),c=f=>{window.clearTimeout(d),window.removeEventListener("termdock-insert-reference-ack",l),f?r():n(new Error("目标终端不可用,内容尚未插入,请连接终端后重试"))},l=f=>{const m=f.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 yy(e,t){return _4(L1(e,null),t)}const Xm=vc(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 A$({file:e,initialPath:t,onInsert:r,onDone:n}){const{t:a}=Hr(),[c,l]=b.useState(!1),[d,f]=b.useState(!1),[m,x]=b.useState(!1),[y,w]=b.useState(!1),[v,T]=b.useState(null),S=b.useRef(!1),I=b.useRef(null),N=async()=>{if(!S.current){S.current=!0,f(!0),w(!0);try{await KF(e.id),n()}catch(F){T(F instanceof Error?F.message:String(F))}finally{S.current=!1,f(!1),w(!1)}}};b.useEffect(()=>{if(c)return;I.current?.focus();const F=P=>{if(P.stopPropagation(),P.key==="Escape"&&P.preventDefault(),P.key!=="Tab")return;const $=Array.from(I.current?.querySelectorAll("button:not(:disabled)")??[]),ee=$[0],Z=$.at(-1);P.shiftKey&&(document.activeElement===ee||document.activeElement===I.current)?(P.preventDefault(),Z?.focus()):!P.shiftKey&&document.activeElement===Z&&(P.preventDefault(),ee?.focus())};return document.addEventListener("keydown",F,!0),()=>document.removeEventListener("keydown",F,!0)},[c]);const B=async F=>{if(!S.current){S.current=!0,f(!0),x(F!==void 0),l(!1),T(null);try{const P=await ZF(e.id,F);F===void 0&&await r(P.path),n()}catch(P){T(P instanceof Error?P.message:String(P))}finally{S.current=!1,f(!1)}}};return c?s.jsx(yp,{open:!0,initialPath:t||"/",title:a("android.recordingSave"),onCancel:()=>l(!1),onConfirm:F=>{B(F)}}):Ks.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:I,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(jn,{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:()=>{N()},className:"min-h-10 rounded-lg px-3 text-sm text-muted-foreground disabled:opacity-40",children:a("android.recordingDiscard")})]})]})}),document.body)}const g0="android-mirror",a0=g0,k4="termdock:android:quality:v1",Jm=176,T$=204,Ql=1,vf=8,vy=[1,1.25,1.5,2,2.5,3,4,6,8],S$=e=>Math.max(Ql,Math.min(vf,e));function C$(e){return`${Number.isInteger(e)?e:e.toFixed(1)}×`}function Gh(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 _$(e,t){try{e.setPointerCapture?.(t)}catch{}}function wy(e,t){try{e.releasePointerCapture?.(t)}catch{}}const Ay=e=>typeof requestAnimationFrame=="function"?requestAnimationFrame(e):window.setTimeout(e,16),Vh=e=>{typeof cancelAnimationFrame=="function"?cancelAnimationFrame(e):window.clearTimeout(e)},e1={auto:"android.qualityAuto",low:"android.qualityLow",medium:"android.qualityMedium",high:"android.qualityHigh",custom:"android.qualityCustom"},k$=()=>{try{const e=localStorage.getItem(k4);return e?X1(JSON.parse(e)):H0}catch{return H0}},o0=e=>{try{localStorage.setItem(k4,JSON.stringify(e))}catch{}};function L$({sessionId:e,dockOnly:t=!1,onInsertPrompt:r,onInsertFile:n,onRecordingComplete:a,onCloseTab:c}){const{t:l}=Hr(),d=cy(H=>H.overlay),f=cy(H=>H.setOverlay),m=b.useRef(null),x=b.useRef(null),y=b.useRef(null),w=b.useMemo(k$,[]),v=b.useRef(w),T=b.useRef(null),S=b.useRef(null),[I,N]=b.useState(4e6),B=b.useRef(null),F=b.useRef(new Map),P=b.useRef(null),$=b.useRef(!1),[ee,Z]=b.useState(Ql),V=b.useRef(ee),de=b.useRef({x:0,y:0}),pe=b.useRef(null),J=b.useRef(0),Re=b.useRef(0),Xe=b.useRef(null),q=b.useRef(0),[ve,qe]=b.useState(null),[ce,ye]=b.useState(null),[Te,Fe]=b.useState(!0),[se,De]=b.useState(""),[_e,Me]=b.useState(w.id),[Je,Ne]=b.useState([]),[ae,ze]=b.useState(null),[at,ut]=b.useState(""),[me,dt]=b.useState(!0),[ft,Se]=b.useState({maxSize:w.maxSize,bitRate:w.bitRate,maxFps:w.maxFps}),[We,Le]=b.useState("idle"),[z,ie]=b.useState(null),[ge,Ge]=b.useState(null),[rt,vt]=b.useState({fps:0,kbps:0,width:0,height:0,received:0,decoded:0,controls:0,last:""}),[Yt,Ut]=b.useState(null),[Nt,ir]=b.useState(null),[Mt,Xt]=b.useState(!1),[Bt,Wt]=b.useState([]),[xe,et]=b.useState(null),[ot,Et]=b.useState([]),[K,xt]=b.useState(!1),rr=b.useRef(null),$e=b.useRef(0),Dr=b.useRef([]),[Ce,St]=b.useState(!1),[Ot,tr]=b.useState(""),[ct,Ct]=b.useState(!1),[or,Cr]=b.useState(!1),[Ir,$r]=b.useState(""),[Tt,Ft]=b.useState(null),[we,wt]=b.useState(null),[it,bt]=b.useState(!1),[An,xn]=b.useState(0),rn=b.useRef(null),[Oe,_t]=b.useState(!1),mt=b.useRef(!1),Zt=b.useRef(new Set),$t=b.useRef(null),wr=b.useRef(null),Tn=b.useRef(!1),[Dn,yn]=b.useState(!1),un=b.useRef(a);un.current=a;const[Cn,Ur]=b.useState(!1),[ne,Ze]=b.useState(null),Dt=b.useRef(null),ur=b.useRef(null),Pr=$F(H=>H.activeSessionId??H.sessions.keys().next().value??null),qr=e??Pr,sn=ns(H=>!!H.docks[a0]),Nr=ns(H=>H.hosts[a0]),Wr=ns(H=>H.setDock),_n=b.useCallback(async()=>{Fe(!0);try{const H=await HF();qe(H),ye(null)}catch(H){ye(H instanceof Error?H.message:"ADB_UNAVAILABLE")}finally{Fe(!1)}},[]);b.useEffect(()=>{_n()},[_n]);const en=ve?.devices??[],Fr=en.find(H=>H.serial===se)??null,Kr=!!(ce&&/ADB_NOT_FOUND|ADB_UNAVAILABLE/i.test(ce)),gr=!!(ve?.adbAvailable&&!ve.scrcpyVersion),an=b.useCallback(()=>{const H=B.current,ue=[...F.current.keys()];B.current=null,F.current.clear(),P.current=null,$.current=!1,rr.current=null,Vh(J.current),J.current=0,H&&x.current?.pointerCancel(H.x,H.y,H.type);const R=m.current;if(R)for(const U of ue)wy(R,U);et(null),xt(!1),Et([]),Z(V.current)},[]);b.useEffect(()=>{const H=U=>{F.current.has(U.pointerId)&&(U.type==="pointercancel"||U.target!==m.current)&&an()},ue=()=>an(),R=()=>{document.hidden&&an()};return window.addEventListener("pointerup",H,!0),window.addEventListener("pointercancel",H,!0),window.addEventListener("blur",ue),document.addEventListener("visibilitychange",R),()=>{window.removeEventListener("pointerup",H,!0),window.removeEventListener("pointercancel",H,!0),window.removeEventListener("blur",ue),document.removeEventListener("visibilitychange",R),an()}},[an]);const Xr=b.useCallback(()=>{an(),x.current?.disconnect(),x.current=null,Le("idle"),ie(null),Ge(null)},[an]),dn=b.useCallback((H,ue=!1)=>{const R=m.current;if(!R||!H)return;an(),x.current?.disconnect(),ie(null),!ue&&y.current!==H&&Ge(null),y.current=H,ir(null),Ut(null);const U=new b$(R,{onBitrateSupport:(be,Ee)=>{x.current!==U||v.current.id!=="auto"||Ut(be?null:Ee??"BITRATE_REASON_UNAVAILABLE")},onState:(be,Ee)=>{x.current===U&&(Le(be),ie(Ee??null))},onHeader:be=>{x.current===U&&Ge(be)},onStats:be=>{x.current===U&&vt(be)},onWarning:be=>{x.current===U&&ir(be)}});x.current=U;let X=v.current;X.id==="auto"?(T.current?.serial!==H&&(T.current={serial:H,policy:new zF}),T.current.policy.connected(performance.now()),X=T.current.policy.quality,N(X.bitRate)):T.current=null,S.current=X,U.connect(H,X)},[an]);b.useEffect(()=>{if(_e!=="auto"||v.current.id!=="auto"||We!=="streaming"||!rt.adaptation||document.hidden)return;const H=T.current,ue=x.current;if(!H||H.serial!==se||!ue?.canSetBitrate)return;const R=m.current,U=R?Math.max(R.clientWidth,R.clientHeight)*(window.devicePixelRatio||1)*V.current:1600,X=H.policy.sample(rt.adaptation,performance.now(),U||1600);X&&ue.setBitrate(X.bitRate).then(be=>{be&&x.current===ue&&(S.current=X,N(X.bitRate))})},[rt,_e,We,se,dn]);const Rr=b.useCallback(H=>{const ue={...H.quality?{quality:{id:H.quality.id,maxSize:H.quality.maxSize,bitRate:H.quality.bitRate,maxFps:H.quality.maxFps}}:{},...H.activePresetId!==void 0?{activePresetId:H.activePresetId}:{},...H.presets!==void 0?{presets:H.presets}:{},...H.docked!==void 0?{docked:H.docked}:{},...H.deviceSerial!==void 0?{deviceSerial:H.deviceSerial}:{}};ja({androidPanel:ue}).catch(()=>{})},[]);b.useEffect(()=>{let H=!1;return wc().then(ue=>{if(H)return;const R=ue.androidPanel;if(R?.quality){const U=X1(R.quality);v.current=U,Me(U.id),Se({maxSize:U.maxSize,bitRate:U.bitRate,maxFps:U.maxFps}),o0(U)}Ne(R?.presets??[]),ze(R?.activePresetId??null),R?.deviceSerial&&(Xe.current=R.deviceSerial,De(R.deviceSerial))}).catch(()=>{}),()=>{H=!0}},[]);const zn=b.useCallback(H=>{const ue=++$e.current;Wt(U=>[...U,{id:ue,left:H.left,top:H.top}]);const R=window.setTimeout(()=>{Wt(U=>U.filter(X=>X.id!==ue)),Dr.current=Dr.current.filter(U=>U!==R)},300);Dr.current.push(R)},[]),pn=b.useCallback((H,ue)=>{const R=x.current,U=S.current;R?.supportsLiveBitrate&&y.current===H&&U&&U.maxSize===ue.maxSize&&U.maxFps===ue.maxFps?R.setBitrate(ue.bitRate).then(X=>{x.current===R&&(X?(S.current=ue,Ut(null)):Ut(R.lastBitrateFailure??"BITRATE_REASON_UNAVAILABLE"))}):dn(H)},[dn,l]),Gr=b.useCallback(H=>{if(T.current=null,H.startsWith("user:")){const R=Je.find(X=>X.id===H.slice(5));if(!R)return;const U={id:"custom",maxSize:R.maxSize,bitRate:R.bitRate,maxFps:R.maxFps};v.current=U,Me("custom"),ze(R.id),Se({maxSize:R.maxSize,bitRate:R.bitRate,maxFps:R.maxFps}),dt(!0),o0(U),Rr({quality:U,activePresetId:R.id}),se&&dn(se);return}if(H==="custom"){const R=v.current;Me("custom"),ze(null),Se({maxSize:R.maxSize,bitRate:R.bitRate,maxFps:R.maxFps}),dt(!0);return}const ue=H==="auto"?X1({id:"auto"}):np.find(R=>R.id===H)??H0;v.current=ue,Me(ue.id),ze(null),o0(ue),Rr({quality:ue,activePresetId:null}),se&&dn(se)},[dn,se,Je,Rr]),zr=b.useCallback(()=>{const H={id:"custom",maxSize:ft.maxSize,bitRate:ft.bitRate,maxFps:ft.maxFps};v.current=H,o0(H),Rr({quality:H,activePresetId:null}),Me("custom"),ze(null),se&&pn(se,H)},[pn,se,ft,Rr]),Y=b.useCallback(()=>{const H=at.trim();if(!H)return;const ue=`p${Date.now().toString(36)}${Math.random().toString(36).slice(2,6)}`,R={id:ue,name:H,maxSize:ft.maxSize,bitRate:ft.bitRate,maxFps:ft.maxFps},U=[...Je.filter(be=>be.name!==H),R].slice(-12),X={id:"custom",maxSize:ft.maxSize,bitRate:ft.bitRate,maxFps:ft.maxFps};Ne(U),ut(""),ze(ue),Me("custom"),v.current=X,o0(X),Rr({quality:X,activePresetId:ue,presets:U}),se&&pn(se,X)},[at,ft,Je,se,pn,Rr]),Be=b.useCallback(()=>{if(!ae)return;const H=Je.filter(ue=>ue.id!==ae);Ne(H),ze(null),Rr({activePresetId:null,presets:H})},[ae,Je,Rr]);b.useEffect(()=>()=>{x.current?.disconnect(),x.current=null;for(const H of Dr.current)window.clearTimeout(H);Dr.current=[]},[]),b.useEffect(()=>{if(d==="off")return;const H=ue=>{ue.key==="Escape"&&f("off")};return window.addEventListener("keydown",H),()=>window.removeEventListener("keydown",H)},[d,f]),b.useEffect(()=>{const H=en.filter(R=>R.state==="device");if(se||H.length!==1)return;const ue=H[0].serial;Xe.current!==ue&&(Xe.current=ue,De(ue))},[en,se]),b.useEffect(()=>{se&&dn(se)},[se,dn]),b.useEffect(()=>{if(We==="streaming"){q.current=0,Xt(!1);return}if(We!=="error"||!se||!E$(z??""))return;const H=Math.min(8e3,700*2**q.current);q.current+=1,Xt(!0);const ue=window.setTimeout(()=>{Xt(!1),dn(se)},H);return()=>window.clearTimeout(ue)},[We,z,se,dn]);const Qt=b.useCallback((H,ue,R)=>{const U=m.current,X=R??(U?Gh(U):null);return!U||!X?{x:0,y:0}:C4(H,ue,X)},[]),er=b.useCallback(()=>{const H=m.current;if(!H)return;const{x:ue,y:R}=de.current,U=V.current,X=U===Ql&&ue===0&&R===0?"":`translate3d(${ue}px, ${R}px, 0) scale(${U})`;H.style.transform!==X&&(H.style.transform=X);const be=pe.current;be&&(be.textContent=U>Ql?C$(U):"")},[]),nr=b.useCallback((H,ue,R=!0)=>{const U=m.current,X=V.current,be=S$(H);if(!U||be===X)return;const Ee=Gh(U);if(!Ee)return;const Ve=ue??{x:Ee.cx,y:Ee.cy},ht=by({zoom:X,pan:de.current},Ee,Ve,Ve,be/X);V.current=ht.zoom,de.current=ht.pan,R&&er()},[er]),Or=b.useCallback(()=>{const H=V.current;Z(ue=>ue<=Ql+.01==H<=Ql+.01&&ue>=vf-.01==H>=vf-.01?ue:H)},[]);b.useEffect(()=>()=>{Vh(J.current),Vh(Re.current)},[]);const kr=()=>{let H=0,ue=0;for(const U of F.current.values())H+=U.x,ue+=U.y;const R=F.current.size;return R?{x:H/R,y:ue/R}:null},Zn=()=>{const[H,ue]=Array.from(F.current.values());return H&&ue?Math.hypot(H.x-ue.x,H.y-ue.y):0},ys=()=>{const H=kr(),ue=m.current?Gh(m.current):null;!H||!ue||(P.current={startCentroid:H,startDistance:Zn(),box:ue})},ss=b.useCallback(()=>{const H=P.current,ue=kr();if(!H||!ue)return;const R=Zn(),U=H.startDistance>0&&R>0?R/H.startDistance:1,X=by({zoom:V.current,pan:de.current},H.box,H.startCentroid,ue,U);V.current=X.zoom,de.current=X.pan,H.startCentroid=ue,H.startDistance=R},[]),Hn=b.useCallback(()=>{J.current||(J.current=Ay(()=>{J.current=0,ss(),er()}))},[ss,er]),hn=b.useCallback(()=>{J.current&&(Vh(J.current),J.current=0,ss(),er())},[ss,er]);b.useEffect(()=>{const H=m.current;if(!H)return;const ue=H.parentElement;if(!ue)return;const R=X=>{if(X.ctrlKey||X.metaKey){if(X.preventDefault(),!X.deltaY||P.current)return;const Ve=X.deltaMode===1?16:X.deltaMode===2?H.parentElement?.clientHeight||600:1,ht=Math.max(-600,Math.min(600,X.deltaY*Ve));nr(V.current*Math.exp(-ht*.002),{x:X.clientX,y:X.clientY},!1),Re.current||(Re.current=Ay(()=>{Re.current=0,er(),Or()}));return}const be=x.current;if(!be||X.target!==H)return;X.preventDefault();const Ee=Yh(H,X.clientX,X.clientY);be.scroll(Ee.x,Ee.y,X.deltaX,X.deltaY)},U=X=>X.preventDefault();return ue.addEventListener("wheel",R,{passive:!1}),ue.addEventListener("gesturestart",U,{passive:!1}),ue.addEventListener("gesturechange",U,{passive:!1}),()=>{ue.removeEventListener("wheel",R),ue.removeEventListener("gesturestart",U),ue.removeEventListener("gesturechange",U)}},[nr,er,Or]),b.useEffect(()=>{const H=m.current,ue=H?.parentElement;if(!H||!ue||typeof ResizeObserver>"u")return;const R=new ResizeObserver(()=>{P.current&&(P.current.box=Gh(H));const U=Qt(de.current,V.current);U.x===de.current.x&&U.y===de.current.y||(de.current=U,er())});return R.observe(H),R.observe(ue),()=>R.disconnect()},[Qt,er]),b.useLayoutEffect(()=>{er()});const Qn=H=>{const ue=x.current,R=m.current;if(!ue||!R)return;if(H.pointerType==="mouse"&&H.button!==0){H.preventDefault(),H.button===2?ue.back():H.button===1&&ue.home();return}H.preventDefault(),R.closest(".android-mirror-panel")?.focus({preventScroll:!0}),er(),Or(),hn(),_$(R,H.pointerId),F.current.set(H.pointerId,{x:H.clientX,y:H.clientY});const U=H.pointerType==="mouse"&&H.altKey;if(F.current.size>=2||U){const Ee=B.current;Ee&&(ue.pointerCancel(Ee.x,Ee.y,Ee.type),B.current=null,rr.current=null,et(null),xt(!1),Et([])),$.current=!0,ys();return}if($.current)return;const X=Yh(R,H.clientX,H.clientY);B.current={id:H.pointerId,type:H.pointerType,x:X.x,y:X.y},ue.pointerDown(X.x,X.y,H.pointerType);const be=ky(R,H.clientX,H.clientY);be&&(rr.current={left:be.left,top:be.top},Et([]),xt(!1),et(be))},Xn=H=>{const ue=x.current,R=m.current;if(!R||!F.current.has(H.pointerId))return;if(H.pointerType==="mouse"){const Ve=R.getBoundingClientRect(),ht=R.parentElement?.getBoundingClientRect()??Ve;if(!(H.buttons&1)||H.clientX<Math.max(Ve.left,ht.left)||H.clientX>=Math.min(Ve.right,ht.right)||H.clientY<Math.max(Ve.top,ht.top)||H.clientY>=Math.min(Ve.bottom,ht.bottom)){an();return}}if(H.preventDefault(),F.current.set(H.pointerId,{x:H.clientX,y:H.clientY}),P.current){Hn();return}const U=B.current;if(!ue||!U||U.id!==H.pointerId)return;const X=Yh(R,H.clientX,H.clientY);U.x=X.x,U.y=X.y,ue.pointerMove(X.x,X.y,U.type);const be=ky(R,H.clientX,H.clientY),Ee=rr.current;!be||!Ee||(et(be),Math.hypot(be.left-Ee.left,be.top-Ee.top)>=6&&(xt(!0),Et(Ve=>{const ht=Ve[Ve.length-1];if(ht&&Math.hypot(be.left-ht.x,be.top-ht.y)<4)return Ve;const Qe=[...Ve,{x:be.left,y:be.top}];return Qe.length>12?Qe.slice(Qe.length-12):Qe})))},fn=H=>{const ue=x.current,R=m.current;if(!R||!F.current.has(H.pointerId))return;if(hn(),F.current.delete(H.pointerId),wy(R,H.pointerId),F.current.size===0&&($.current=!1),P.current){F.current.size===0?(P.current=null,Z(V.current)):ys();return}const U=B.current;if(!U||U.id!==H.pointerId)return;const X=Yh(R,H.clientX,H.clientY);ue?.pointerUp(X.x,X.y,U.type),xe&&zn(xe),et(null),xt(!1),window.setTimeout(()=>Et([]),200),B.current=null,rr.current=null},cr=H=>{if(Cn||Ce||or)return;const ue=x.current;ue&&(H.key==="Backspace"?(H.preventDefault(),ue.key(67)):H.key==="Escape"?(H.preventDefault(),ue.back()):H.key==="Enter"&&(H.preventDefault(),ue.key(66)))},is=async()=>{const H=Ot.trim();if(H){Ct(!0);try{const ue=await WF(H);tr(""),St(!1),await _n(),De(ue.serial)}catch(ue){ye(ue instanceof Error?ue.message:"ADB_CONNECT_FAILED")}finally{Ct(!1)}}},tn=()=>{const H=x.current,ue=Ir;!H||!ue||(H.sendText(ue),$r(""))},xr=b.useCallback(H=>{Ft(H),wr.current!==null&&window.clearTimeout(wr.current),wr.current=window.setTimeout(()=>{wr.current=null,Ft(null)},2500)},[]),vr=b.useCallback(H=>{const ue=V.current,R=H==="in"?vy.find(U=>U>ue+.01):[...vy].reverse().find(U=>U<ue-.01);R!==void 0&&(ue<=Ql&&R>Ql&&xr(l("android.zoomPanHint")),hn(),nr(R),Z(R))},[nr,hn,xr,l]),br=H=>{Promise.resolve().then(()=>r?.(H)).catch(ue=>{wt(ue instanceof Error?ue.message:String(ue))})},us=b.useCallback(async(H,ue)=>{try{if(!n)throw new Error(l("android.captureUnavailable"));await n(H),xr(ue)}catch(R){wt(l("android.captureFailed")+(R instanceof Error?`:${R.message}`:""))}},[n,xr,l]),Bn=async()=>{const H=m.current;if(!(!H||Tn.current)){Tn.current=!0,yn(!0),wt(null);try{const ue=await w$(H);await us(ue,l("android.captureInserted"))}catch(ue){wt(ue instanceof Error?ue.message:String(ue))}finally{Tn.current=!1,yn(!1)}}},vs=b.useCallback(H=>{(H.status==="ready"||H.status==="error")&&un.current&&!Zt.current.has(H.id)&&(Zt.current.add(H.id),un.current?.(H))},[]),Bs=b.useCallback(async H=>{const ue=rn.current;if(!(!ue||mt.current)){mt.current=!0,_t(!0),wt(null);try{const R=await YF(ue.id);rn.current=null,bt(!1),vs(R)}catch(R){wt(R instanceof Error?R.message:String(R))}finally{mt.current=!1,_t(!1)}}},[vs]),Ls=async()=>{if(!(!se||mt.current||rn.current)){mt.current=!0,_t(!0),wt(null);try{const H=await qF(se);H.status==="recording"||H.status==="starting"||H.status==="stopping"?(rn.current=H,bt(!0),xn(Math.max(0,Date.now()-H.startedAt))):vs(H)}catch(H){wt(H instanceof Error?H.message:String(H))}finally{mt.current=!1,_t(!1)}}};b.useEffect(()=>{let H=!1,ue=!1;rn.current=null,bt(!1);const R=async()=>{if(!(!se||ue||mt.current)){ue=!0;try{const{recordings:X}=await VF(se);if(H||mt.current)return;const be=X.find(Ee=>["starting","recording","stopping"].includes(Ee.status));rn.current=be??null,bt(!!be);for(const Ee of X)vs(Ee)}catch{}finally{ue=!1}}};R();const U=window.setInterval(()=>{R()},2e3);return $t.current=window.setInterval(()=>{rn.current&&xn(Math.max(0,Date.now()-rn.current.startedAt))},500),()=>{H=!0,window.clearInterval(U),$t.current!==null&&window.clearInterval($t.current)}},[se,vs]),b.useEffect(()=>{if(!Cn)return;const H=()=>Ur(!1),ue=U=>{const X=U.target;X instanceof Node&&(Dt.current?.contains(X)||ur.current?.contains(X)||H())},R=U=>{U.key==="Escape"&&(U.preventDefault(),U.stopPropagation(),H())};return document.addEventListener("pointerdown",ue,!0),document.addEventListener("keydown",R,!0),window.addEventListener("resize",H),()=>{document.removeEventListener("pointerdown",ue,!0),document.removeEventListener("keydown",R,!0),window.removeEventListener("resize",H)}},[Cn]),b.useEffect(()=>()=>{wr.current!==null&&window.clearTimeout(wr.current)},[]);const Qr=We==="streaming",yr=sn,Pn=yr?"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",Jn=Fr?(Fr.model||Fr.serial)+Ly(Fr,l):en.length?l("android.selectDevice"):l("android.noDevices"),oi=(ae?Je.find(H=>H.id===ae):null)?.name??(_e==="auto"?`${l("android.qualityAuto")} · ${I/1e6} Mbps`:l(e1[_e])),W=yr?"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",Ie=yr?"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",Ye="absolute inset-0 h-full w-full cursor-pointer opacity-0",nt=()=>{const H=Dt.current?.getBoundingClientRect();H&&Ze({left:Math.max(8,Math.min(H.right-Jm,window.innerWidth-Jm-8)),top:Math.min(H.bottom+4,Math.max(8,window.innerHeight-T$-8))}),Ur(!0)},st=()=>{if(sn){Wr(a0,null),Rr({docked:null});return}if(!qr)return;const H={sessionId:qr,side:"right"};Wr(a0,H),Rr({docked:H})},yt=Ce||sn||d!=="off",Pt=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:cr,tabIndex:-1,children:[s.jsxs("div",{"data-panel-drag-title":sn?"true":void 0,className:yr?"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:[sn&&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(sp,{size:12})}),s.jsx(N9,{size:yr?12:14,className:"shrink-0 text-muted-foreground"}),s.jsxs("div",{className:`${W} flex-1`,children:[s.jsx("span",{"aria-hidden":"true",className:`${Ie} w-full`,children:Jn}),s.jsxs("select",{value:se,onChange:H=>{const ue=H.target.value;De(ue),Xe.current=ue,ue&&Rr({deviceSerial:ue})},className:Ye,"aria-label":l("android.device"),children:[s.jsx("option",{value:"",children:en.length?l("android.selectDevice"):l("android.noDevices")}),en.map(H=>s.jsx("option",{value:H.serial,children:(H.model||H.serial)+Ly(H,l)},H.serial))]})]}),s.jsxs("div",{className:`${W} max-w-[45%] shrink-0`,children:[s.jsx("span",{"aria-hidden":"true",className:Ie,children:oi}),s.jsxs("select",{value:ae?`user:${ae}`:_e,onChange:H=>Gr(H.target.value),className:Ye,title:l(_e==="auto"?"android.qualityAutoHint":"android.quality"),"aria-label":l("android.quality"),children:[s.jsxs("option",{value:"auto",children:[l("android.qualityAuto"),_e==="auto"?` · ${I/1e6} Mbps`:""]}),np.map(H=>s.jsx("option",{value:H.id,children:l(e1[H.id])},H.id)),Je.map(H=>s.jsx("option",{value:`user:${H.id}`,children:H.name},H.id)),s.jsx("option",{value:"custom",children:l(e1.custom)})]})]}),s.jsx("button",{type:"button",onClick:()=>{_n()},className:`${Pn} text-muted-foreground`,title:l("android.refresh"),children:Te?s.jsx(jn,{size:13,className:"animate-spin"}):s.jsx(wn,{size:13})}),Qr?s.jsx("button",{type:"button",onClick:Xr,className:`${Pn} text-destructive`,title:l("android.disconnect"),children:s.jsx(m3,{size:13})}):s.jsx("button",{type:"button",onClick:()=>se&&dn(se),disabled:!se,className:`${Pn} text-primary`,title:l("android.connect"),children:s.jsx(kS,{size:13})}),(Qr||it)&&s.jsx("button",{type:"button",onClick:()=>{Bn()},disabled:!n||Dn,className:`${Pn} text-muted-foreground`,title:l(n?"android.screenshot":"android.captureUnavailable"),"aria-label":l("android.screenshot"),children:Dn?s.jsx(jn,{size:yr?12:13,className:"animate-spin"}):s.jsx(iT,{size:yr?12:13})}),(Qr||it)&&s.jsx("button",{type:"button",onClick:()=>{it?Bs("manual"):Ls()},disabled:Oe||!it&&!a,className:`${Pn} ${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:Oe?s.jsx(jn,{className:"animate-spin",size:13}):it?s.jsx(p3,{size:yr?10:11,fill:"currentColor"}):s.jsx(g3,{size:yr?12:13})}),s.jsx("button",{ref:Dt,type:"button",onClick:()=>Cn?Ur(!1):nt(),"aria-haspopup":"menu","aria-expanded":Cn,className:`${Pn} ${yt?"text-primary":"text-muted-foreground"}`,title:l("android.more"),"aria-label":l("android.more"),children:s.jsx(Io,{size:yr?13:14})}),c&&!t&&s.jsx("button",{type:"button",onClick:()=>{Ur(!1),f("off"),c()},className:`${Pn} text-muted-foreground hover:bg-destructive/20 hover:text-destructive`,title:l("android.closeTab"),"aria-label":l("android.closeTab"),children:s.jsx(Mn,{size:14})})]}),Cn&&ne&&Ks.createPortal(s.jsxs("div",{ref:ur,role:"menu","aria-label":l("android.more"),style:{left:ne.left,top:ne.top,width:Jm},className:"fixed z-popover overflow-hidden rounded-md border border-border bg-surface-elevated py-1 text-[11px] shadow-lg",children:[s.jsx(qh,{icon:s.jsx(Al,{size:13}),label:l("android.addDevice"),active:Ce,onSelect:()=>{St(H=>!H),Ur(!1)}}),s.jsx(qh,{icon:sn?s.jsx(Mn,{size:13}):s.jsx(Fl,{size:13}),label:l(sn?"android.splitClose":"android.splitOpen"),active:sn,disabled:!sn&&!qr,onSelect:()=>{st(),Ur(!1)}}),s.jsx(qh,{icon:d==="window"?s.jsx(JT,{size:13}):s.jsx(YT,{size:13}),label:l(d==="window"?"android.exitFullscreen":"android.fullscreen"),active:d==="window",onSelect:()=>{f(d==="window"?"off":"window"),Ur(!1)}}),!t&&s.jsx(qh,{icon:d==="sidebar"?s.jsx(cS,{size:13}):s.jsx(fS,{size:13}),label:l(d==="sidebar"?"android.exitFullscreen":"android.fillSidebar"),active:d==="sidebar",onSelect:()=>{f(d==="sidebar"?"off":"sidebar"),Ur(!1)}}),ge&&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:`${rt.fps} fps · ${rt.kbps} kbps`}),s.jsx("div",{className:"truncate",children:`${rt.width}×${rt.height}`})]})]}),document.body),(_e==="custom"||ae)&&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:()=>dt(H=>!H),"aria-expanded":me,className:"flex w-full items-center gap-1 rounded text-muted-foreground hover:text-foreground",children:[s.jsx(Al,{size:12,className:`transition-transform ${me?"":"-rotate-90"}`}),s.jsxs("span",{children:[l("android.quality"),ae?` · ${Je.find(H=>H.id===ae)?.name??""}`:""]})]}),me&&s.jsxs("div",{className:"mt-2 grid gap-2",children:[s.jsx(_y,{label:l("android.qualityResolution"),display:`${ft.maxSize}px`,min:360,max:2160,step:8,value:ft.maxSize,onChange:H=>Se(ue=>({...ue,maxSize:H}))}),s.jsx(_y,{label:l("android.qualityBitRate"),display:`${(ft.bitRate/1e6).toFixed(1)} Mbps`,min:.5,max:20,step:.5,value:ft.bitRate/1e6,onChange:H=>Se(ue=>({...ue,bitRate:Math.round(H*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(H=>s.jsx("button",{type:"button",onClick:()=>Se(ue=>({...ue,maxFps:H})),className:`rounded px-2 py-0.5 ${ft.maxFps===H?"bg-surface-elevated text-primary":"text-muted-foreground hover:bg-surface-2"}`,children:H},H)),s.jsx("button",{type:"button",onClick:()=>Se(H=>({...H,maxFps:0})),className:`rounded px-2 py-0.5 ${ft.maxFps===0?"bg-surface-elevated text-primary":"text-muted-foreground hover:bg-surface-2"}`,children:l("android.qualityAuto")})]}),s.jsx("button",{type:"button",onClick:zr,disabled:!se,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:at,onChange:H=>ut(H.target.value),onKeyDown:H=>{H.key==="Enter"&&!H.nativeEvent.isComposing&&Y()},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:Y,disabled:!at.trim(),className:"shrink-0 rounded bg-surface-2 px-2 py-1 text-primary disabled:opacity-40",children:l("android.presetSave")}),ae&&s.jsx("button",{type:"button",onClick:Be,className:"shrink-0 rounded px-2 py-1 text-destructive hover:bg-surface-2",children:l("android.presetDelete")})]})]})]}),Ce&&s.jsxs("div",{className:"flex items-center gap-1.5 border-b border-border px-2 py-2",children:[s.jsx("input",{value:Ot,onChange:H=>tr(H.target.value),onKeyDown:H=>{H.key==="Enter"&&is()},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:()=>{is()},disabled:ct,className:"rounded bg-surface-2 px-2 py-1 text-[11px] text-primary disabled:opacity-40",children:ct?s.jsx(jn,{size:12,className:"animate-spin"}):l("android.connect")})]}),Kr&&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(Sy,{label:l("android.insertFixPrompt"),onClick:()=>br(Cy("adb",ce??"")),enabled:!!r})]}),!Kr&&gr&&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(Sy,{label:l("android.insertFixPrompt"),onClick:()=>br(Cy("scrcpy","")),enabled:!!r})]}),Fr&&Fr.state!=="device"&&s.jsx("div",{className:"border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-warning",children:N$(Fr,l)}),ce&&!Kr&&s.jsx("div",{className:"border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-destructive",children:uy(ce)}),Yt&&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(Yt.startsWith("SCRCPY_VERSION")?"android.qualityAutoVersionError":Yt.startsWith("SCRCPY_BUILD")?"android.qualityAutoBuildError":/EXTENSION|SERVER_READ|PUSH/.test(Yt.split(":")[0])?"android.qualityAutoExtensionError":/TIMEOUT/.test(Yt.split(":")[0])?"android.qualityAutoTimeoutError":/ENCODER_REJECTED/.test(Yt.split(":")[0])?"android.qualityAutoEncoderError":/CHANNEL|TUNNEL|LISTEN|PROTOCOL|CONNECTION/.test(Yt.split(":")[0])?"android.qualityAutoChannelError":"android.qualityAutoUnknownError")]}),s.jsx("pre",{className:"mt-1 select-text whitespace-pre-wrap break-all text-[10px]",children:Yt})]}),Nt&&s.jsx("div",{className:"border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-warning",children:Nt}),we&&s.jsx("div",{role:"alert",className:"border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-destructive",children:we}),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:Qr||ge?"block":"none",transformOrigin:"center",transition:"none"},onPointerDown:Qn,onPointerMove:Xn,onPointerUp:fn,onPointerCancel:()=>an(),onLostPointerCapture:H=>{F.current.has(H.pointerId)&&an()},onPointerLeave:H=>{F.current.has(H.pointerId)&&!H.currentTarget.hasPointerCapture?.(H.pointerId)&&an()},onContextMenu:H=>H.preventDefault()}),xe&&s.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute h-3.5 w-3.5 -translate-x-1/2 -translate-y-1/2 rounded-full border border-primary/80 bg-primary/35",style:{left:xe.left,top:xe.top}}),ot.length>1&&s.jsx("svg",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0 h-full w-full",style:{opacity:K?1:0,transition:"opacity 160ms linear"},children:ot.slice(1).map((H,ue)=>{const R=ot[ue],U=(ue+1)/(ot.length-1);return s.jsx("line",{x1:R.x,y1:R.y,x2:H.x,y2:H.y,stroke:"var(--primary)",strokeWidth:1+1.6*U,strokeLinecap:"round",opacity:.06+.45*U},ue)})}),Bt.map(H=>s.jsx("span",{"aria-hidden":"true",className:"termdock-tap-fade pointer-events-none absolute h-4 w-4 rounded-full bg-primary",style:{left:H.left,top:H.top}},H.id)),!Qr&&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(jn,{size:18,className:"animate-spin"}),s.jsx("span",{children:l("android.connecting")})]}),We==="error"&&s.jsxs(s.Fragment,{children:[s.jsx(V0,{size:14,className:"text-destructive"}),s.jsx("span",{className:"max-w-[80%] text-destructive",children:Mt?l("android.reconnecting"):uy(z||"")}),se&&s.jsx("button",{type:"button",onClick:()=>{q.current=0,dn(se)},className:"rounded bg-surface-2 px-2 py-1 text-foreground",children:l("android.retry")})]}),We==="idle"&&!Kr&&!gr&&s.jsxs(s.Fragment,{children:[s.jsx(tS,{size:22,className:"opacity-60"}),s.jsx("span",{children:en.length?l("android.idleHint"):l("android.noDevicesHint")})]})]})]}),s.jsxs("div",{className:`flex flex-wrap items-center gap-1 border-t border-border ${yr?"px-1.5 py-0.5":"px-2 py-1.5"}`,children:[s.jsx(Wo,{compact:yr,label:l("android.back"),onClick:()=>x.current?.back(),disabled:!Qr,children:s.jsx(e3,{size:14})}),s.jsx(Wo,{compact:yr,label:l("android.home"),onClick:()=>x.current?.home(),disabled:!Qr,children:s.jsx(FT,{size:14})}),s.jsx(Wo,{compact:yr,label:l("android.recents"),onClick:()=>x.current?.recents(),disabled:!Qr,children:s.jsx(c3,{size:14})}),s.jsx(Wo,{compact:yr,label:l("android.notifications"),onClick:()=>x.current?.expandNotifications(),disabled:!Qr,children:s.jsx(i3,{size:14})}),s.jsx(Wo,{compact:yr,label:l("android.rotate"),onClick:()=>x.current?.rotate(),disabled:!Qr,children:s.jsx(MS,{size:14})}),s.jsx(Wo,{compact:yr,label:l("android.volumeDown"),onClick:()=>x.current?.volumeDown(),disabled:!Qr,children:s.jsx(sC,{size:14})}),s.jsx(Wo,{compact:yr,label:l("android.volumeUp"),onClick:()=>x.current?.volumeUp(),disabled:!Qr,children:s.jsx(aC,{size:14})}),s.jsx(Wo,{compact:yr,label:l("android.power"),onClick:()=>x.current?.power(),disabled:!Qr,children:s.jsx(IS,{size:14})}),s.jsx(Wo,{compact:yr,label:l("android.inputText"),active:or,onClick:()=>Cr(H=>!H),disabled:!Qr,children:s.jsx(l3,{size:14})}),s.jsx(Wo,{compact:yr,label:l("android.zoomIn"),onClick:()=>vr("in"),disabled:!Qr||ee>=vf-.01,children:s.jsx(Zs,{size:14})}),s.jsx(Wo,{compact:yr,label:l("android.zoomOut"),onClick:()=>vr("out"),disabled:!Qr||ee<=Ql+.01,children:s.jsx(u3,{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||!!Tt||Dn,className:`block truncate text-right text-[10px] leading-5 tabular-nums text-muted-foreground ${it||Tt||Dn?"invisible":""}`,children:ge?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(I$,{recording:it,elapsed:An,status:Dn?l("android.captureInserting"):Tt,stopLabel:l("android.recordingStop"),onStop:()=>{Bs("manual")}})})]})]}),or&&s.jsxs("div",{className:"flex items-center gap-1.5 border-t border-border px-2 py-1.5",children:[s.jsx("input",{value:Ir,onChange:H=>$r(H.target.value),onKeyDown:H=>{H.key==="Enter"&&!H.nativeEvent.isComposing&&(H.preventDefault(),tn())},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:tn,disabled:!Ir,className:"rounded bg-surface-2 p-1.5 text-primary disabled:opacity-40",title:l("android.send"),children:s.jsx(y0,{size:13})})]})]});return d==="window"?Ks.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:Pt}),document.body):t?sn&&Nr?Ks.createPortal(Pt,Nr):null:sn&&Nr?s.jsxs(s.Fragment,{children:[Ks.createPortal(Pt,Nr),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(Fl,{size:18,className:"opacity-60"}),s.jsx("span",{children:l("android.splitDockedHint")}),s.jsx("button",{type:"button",onClick:()=>{Wr(a0,null),Rr({docked:null})},className:"rounded bg-surface-2 px-2 py-1 text-foreground",children:l("android.splitClose")})]})]}):Pt}function qh({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(ai,{size:12,className:"shrink-0"})]})}function I$({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"}),xy(t),s.jsx("button",{type:"button",onClick:a,title:n,"aria-label":`${n} · ${xy(t)}`,className:"ml-0.5 inline-flex h-4 w-4 items-center justify-center rounded hover:bg-destructive/25",children:s.jsx(p3,{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 Ty({sessionId:e}){const t=ns(x=>x.docks[g0]),r=!!t,n=t?.sessionId??e??null,c=Xm(x=>x.pending)[0],l=b.useCallback(async x=>{if(!n)throw new Error("没有可接收截图的终端");const w=(await W0("/tmp",[x])).files[0]?.path;if(!w)throw new Error("截图上传未返回文件路径");await yy(w,n)},[n]),d=b.useCallback(x=>{Xm.getState().enqueue(x,n)},[n]),f=ns(x=>!!x.hosts[g0]),m=b.useRef(!1);return b.useEffect(()=>{m.current||(m.current=!0,wc().then(x=>{const y=x.androidPanel?.docked;y&&(ns.getState().docks[g0]||ns.getState().setDock(g0,y))}).catch(()=>{}))},[]),s.jsxs(s.Fragment,{children:[r&&f&&s.jsx(L$,{sessionId:n,dockOnly:!0,onInsertFile:n?l:void 0,onInsertPrompt:n?x=>_4(x,n):void 0,onRecordingComplete:d}),c&&s.jsx(A$,{file:c.file,initialPath:c.initialPath,onInsert:x=>c.insert?c.insert(x):yy(x,c.sessionId),onDone:()=>Xm.getState().remove(c.file.id)},c.file.id)]})}function Sy({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 Cy(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
|
+
`:"")+Qt)}},ref:Ft,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:[bt.name," · 发送给成员"]}),s.jsxs("div",{className:w?"space-y-2":"mt-2 space-y-2",children:[Xe&&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:Y=>{Y.key==="Escape"&&(Y.currentTarget.removeAttribute("open"),Y.currentTarget.querySelector("summary")?.focus(),Y.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(Io,{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:`${Lr} min-h-11 w-full justify-start text-foreground hover:bg-surface-elevated`,onClick:Y=>{Y.currentTarget.closest("details")?.removeAttribute("open"),$?.(bt.id).catch(Be=>pe(Be instanceof Error?Be.message:"无法打开看板"))},children:[s.jsx(qc,{size:14}),"看板"]}),s.jsx("button",{type:"button","aria-expanded":qe,className:`${Lr} min-h-11 w-full justify-start text-foreground hover:bg-surface-elevated`,onClick:Y=>{Y.currentTarget.closest("details")?.removeAttribute("open"),ce(Be=>!Be)},children:"成员管理"}),s.jsxs("button",{type:"button","aria-label":"组设置","aria-expanded":Nt,className:`${Lr} min-h-11 w-full justify-start text-foreground hover:bg-surface-elevated`,onClick:Y=>{Y.currentTarget.closest("details")?.removeAttribute("open"),Xt.current=Y.currentTarget,ir(!0),pe(null),J(null)},children:[s.jsx(qu,{size:14}),"组设置"]})]})]})]}),s.jsxs("fieldset",{className:"min-w-0",children:[s.jsx("legend",{className:Xe?"sr-only":"mb-1 text-[10px] text-muted-foreground",children:"接收人(可多选)"}),s.jsx("div",{className:"flex flex-wrap gap-1",children:[{id:"*",label:"全组成员"},...bt.sessionIds.map(Y=>({id:Y,label:(()=>{const Be=An.find(Qt=>Qt.sessionId===Y);return Be?Uu(Be,An):void 0})()??`${Y.slice(0,8)}(离线)`}))].map(({id:Y,label:Be})=>{const Qt=Y==="*"?ge===null:ge?.includes(Y)??!1,er=S.find(nr=>nr.sessionId===Y);return s.jsxs(GO,{label:Be,disabled:Y==="*"||V!==null,onRemove:()=>{gr(Y)},children:[s.jsxs("button",{type:"button","aria-pressed":Qt,onClick:()=>Ge(nr=>Y==="*"?null:nr?.includes(Y)?nr.filter(Or=>Or!==Y):[...nr??[],Y]),className:`${K1} min-h-9 min-w-0 gap-1 sm:min-h-7 ${Qt?"border-primary/40 bg-primary/15 text-primary":"border-border/20 bg-surface-2 text-muted-foreground hover:text-foreground"}`,children:[Qt&&s.jsx(ai,{size:12,"aria-hidden":"true",className:"shrink-0"}),s.jsx("span",{className:"break-words text-left",children:Be})]}),er&&s.jsx("button",{type:"button","aria-label":`打开 ${Be} 的终端`,title:`打开 ${Be} 的终端`,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:()=>{F(er).catch(nr=>pe(nr instanceof Error?nr.message:"无法打开会话"))},children:s.jsx(qc,{size:12})})]},`${bt.id}:${Y}`)})})]})]}),s.jsxs("label",{className:"mt-2 block space-y-1 text-[9px] text-muted-foreground",children:[s.jsx("span",{className:Xe?"sr-only":void 0,children:"内容"}),s.jsx("textarea",{onKeyDown:Y=>{Y.key==="Enter"&&(Y.metaKey||Y.ctrlKey)&&!Y.nativeEvent.isComposing&&Y.keyCode!==229&&(Y.preventDefault(),en())},onPaste:Y=>{const Be=Array.from(Y.clipboardData.files);Be.length&&(Y.preventDefault(),un(Be))},className:`${Vs} min-h-16 max-h-48 resize-y`,value:rt,onChange:Y=>vt(Y.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:bt.federated?"消息由服务端后台投递,可查看送达结果;无需保持客户端在线。":"在线成员立即入队;离线成员上线后送达。"}),s.jsxs("button",{disabled:V!==null||xn>0||!rt.trim()||!_n.length,className:`${Lr} shrink-0 bg-primary text-primary-foreground`,title:"发送(⌘ / Ctrl + Enter)",onClick:()=>{en()},children:[V==="send-message"?s.jsx(wn,{size:13,className:"animate-spin"}):null,"发送"]})]})]}),s.jsxs("div",{children:[s.jsxs("details",{hidden:Xe&&!qe,open:Xe?qe:void 0,onToggle:Y=>{Xe&&ce(Y.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:["管理成员、角色与删除 · ",bt.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:bt.name}),s.jsxs("p",{className:"mt-1 text-[10px] text-muted-foreground",children:[bt.sessionIds.length," 个成员 · 组 ID:",s.jsx("span",{className:"break-all font-mono",children:w4(bt.id)})]})]}),ze?s.jsxs("div",{className:"flex flex-wrap items-center gap-1 sm:justify-end",children:[s.jsx("button",{className:`${Lr} bg-surface-2 px-2 text-foreground`,onClick:()=>at(!1),children:"取消"}),s.jsxs("button",{disabled:V!==null,className:`${Lr} bg-destructive px-2 text-destructive-foreground`,onClick:()=>{Fr()},children:[V===`delete:${bt.id}`?s.jsx(wn,{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:`${Lr} px-2 text-muted-foreground hover:bg-surface-2 hover:text-foreground`,onClick:()=>{Et(new Set(bt.sessionIds)),xt(bt.updatedAt);const Y=!Yt;Ut(Y),Y&&$e(Object.fromEntries(bt.sessionIds.map(Be=>[Be,bt.roles?.[Be]??""]))),Ce(!1)},children:[s.jsx(qu,{size:13}),"管理成员"]}),s.jsxs("button",{className:`${Lr} px-2 text-primary hover:bg-primary/10`,onClick:Xr,children:[s.jsx(Zs,{size:13}),"新建 Agent"]}),s.jsx("button",{"aria-label":`删除协作组 ${bt.name}`,title:"删除协作组",disabled:V!==null,className:"rounded-lg p-2 text-muted-foreground transition hover:bg-destructive/10 hover:text-destructive",onClick:()=>{me(bt.updatedAt),at(!0)},children:s.jsx(Ds,{size:14})})]})]}),ze&&s.jsxs("p",{role:"alert",className:"mt-2 rounded-lg bg-destructive/10 px-3 py-2 text-[10px] leading-relaxed text-destructive",children:["将删除“",bt.name,"”协作组及其协作记录,",bt.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:bt.sessionIds.map(Y=>{const Be=S.find(nr=>nr.sessionId===Y),Qt=bt.roles?.[Y],er=Be?.name??Y;return s.jsxs("div",{className:`flex min-w-0 items-stretch transition ${xe===Y?"bg-destructive/5":"hover:bg-surface-2"}`,children:[s.jsxs("button",{disabled:!Be,onClick:()=>Be&&void F(Be).catch(nr=>pe(nr instanceof Error?nr.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 ${Be&&["ready","shell","terminal-connected","service-reachable","working","idle","done"].includes(Be.status)&&Be.serviceConnected!==!1?"bg-[var(--success)]":"bg-muted-foreground"}`}),s.jsx("span",{className:"truncate text-[11px] text-foreground",children:er}),Be&&s.jsx(Wm,{session:Be}),s.jsx("span",{className:"ml-auto shrink-0 text-[9px] text-muted-foreground",children:Be?yf(Be):"已离线"})]}),s.jsxs("span",{className:"mt-1 flex min-w-0 items-center gap-1 text-[9px] text-muted-foreground",children:[Qt?s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"min-w-0 truncate font-medium text-primary/80",children:["定位:",Qt]}),s.jsx("span",{className:"shrink-0 text-muted-foreground/50",children:"·"})]}):null,Be?s.jsx("span",{className:"min-w-0 truncate",children:Gm(Be.currentTask)}):s.jsx("span",{className:"shrink-0",children:"重新上线后可继续接收消息"})]})]}),s.jsx("button",{"aria-label":`把 ${er} 移出协作组`,"aria-expanded":xe===Y,title:"移出协作组",disabled:V!==null,className:`mr-1 shrink-0 self-center rounded-lg p-2 transition ${xe===Y?"text-destructive":"text-muted-foreground hover:bg-destructive/10 hover:text-destructive"}`,onClick:()=>et(xe===Y?null:Y),children:s.jsx(Ds,{size:13})})]},Y)})}),xe&&bt.sessionIds.includes(xe)&&(()=>{const Y=S.find(Qt=>Qt.sessionId===xe)?.name??xe,Be=V===`remove-member:${xe}`;return s.jsxs("div",{role:"group","aria-label":`确认移除成员 ${Y}`,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:`把“${Y}”移出“${bt.name}”?移出后它不再收到这个组的消息,可以随时重新加入`}),s.jsxs("div",{className:"flex shrink-0 gap-2",children:[s.jsx("button",{className:`${Lr} min-h-8 bg-surface-2 px-2 text-[10px] text-foreground`,onClick:()=>et(null),children:"取消"}),s.jsxs("button",{disabled:V!==null,className:`${Lr} min-h-8 px-2 text-[10px] bg-destructive text-destructive-foreground`,onClick:()=>{gr(xe)},children:[Be?s.jsx(wn,{size:12,className:"animate-spin"}):s.jsx(Ds,{size:12}),"移出"]})]})]})})(),Yt&&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:["已选 ",ot.size]})]}),s.jsx("div",{className:"mt-3 max-h-72 divide-y divide-border/10 overflow-y-auto border-y border-border/10",children:qr.length<=1?Ze.map(pn):qr.map(Y=>{const Be=sn(Y.key);return s.jsxs("div",{children:[s.jsx(ry,{label:Y.label,count:Y.sessions.length,collapsed:Be,onToggle:()=>Nr(Y.key)}),!Be&&s.jsx("div",{className:"divide-y divide-border/10",children:Y.sessions.map(pn)})]},Y.key)})}),s.jsxs("div",{className:"mt-3 flex justify-end gap-2",children:[s.jsx("button",{className:`${Lr} bg-surface-2 text-foreground`,onClick:()=>{Ut(!1),$e({})},children:"取消"}),s.jsxs("button",{disabled:V!==null||v!=="loaded",className:`${Lr} bg-primary text-primary-foreground`,onClick:()=>{Kr()},children:[V==="save-members"?s.jsx(wn,{size:13,className:"animate-spin"}):s.jsx(ai,{size:13}),"保存成员"]})]})]}),Dr&&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(qO,{group:bt,value:tr,onChange:ct,disabled:V!==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:Vs,disabled:!!tr,value:bt.launchProfiles?.find(Y=>Y.id===tr)?.agentSlug??St,onChange:Y=>Ot(Y.target.value),children:I.map(Y=>s.jsxs("option",{value:Y.slug,children:[Y.displayName,Y.isPlugin?" · Plugin":""]},Y.slug))})]}),s.jsxs("label",{className:"space-y-1 text-[9px] text-muted-foreground",children:["会话名称",s.jsx("input",{"aria-label":"新 Agent 会话名称",className:Vs,value:Ct,onChange:Y=>or(Y.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:Vs,value:Cr,onChange:Y=>Ir(Y.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:`${Vs} min-h-16 resize-y`,value:$r,onChange:Y=>Tt(Y.target.value),placeholder:"说明它加入后要先完成什么"})]}),s.jsxs("div",{className:"mt-3 flex justify-end gap-2",children:[s.jsx("button",{className:`${Lr} bg-surface-2 text-foreground`,onClick:()=>Ce(!1),children:"取消"}),s.jsxs("button",{disabled:V!==null||!St||!!tr&&!bt.launchProfiles?.some(Y=>Y.id===tr),className:`${Lr} bg-primary text-primary-foreground`,onClick:()=>{dn()},children:[V==="spawn-agent"?s.jsx(wn,{size:13,className:"animate-spin"}):s.jsx(G0,{size:13}),"创建并加入"]})]})]})]})]},bt.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:[Rr.length," 条"]})]}),s.jsxs("div",{className:"divide-y divide-border/10 border-y border-border/10 [overflow-wrap:anywhere]",children:[Rr.map(Y=>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:Y.responseKind==="ack"?"收到确认":Y.responseKind==="progress"?"进展":Y.responseKind==="result"?"结果":vF(Y.kind)}),s.jsx("span",{children:Y.fromName}),s.jsx("span",{children:"→"}),s.jsx("span",{className:"truncate",children:Y.toNames.join("、")}),s.jsx("span",{className:"ml-auto shrink-0",children:new Date(Y.createdAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),s.jsx("p",{className:"mt-1 whitespace-pre-wrap text-[11px] leading-relaxed text-foreground",children:Y.content}),s.jsx("p",{className:"mt-1 text-[9px] text-muted-foreground",children:Y.status==="pending"?"已入队 · 等待投递":Y.status==="failed"?"投递失败":Y.status==="expired"?"消息已过期,未继续投递":Y.status==="stored"?"答复已持久保存 · 供后台接收":"已写入接收方终端 · 等待接手确认"}),Y.deliveryErrors.map(Be=>s.jsx("p",{role:"status",className:"mt-1 text-[10px] text-destructive",children:Be==="TMUX_PANE_CHANGED"?"目标会话绑定已变化,投递暂停。原消息已保留,请确认目标会话后继续。":`投递暂停:${Be}。原消息已保留,请检查目标会话。`},Be)),(Y.task||Y.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(Y.task??{failure_reason:Y.failureReason},null,2)})]})]},Y.key)),Rr.length===0&&s.jsx(IF,{text:Se?"正在加载协作记录…":"还没有消息。可以直接给成员发送说明或问题。"})]})]})]})]})]})]})}function hF({group:e,agents:t,activeSessionId:r,sessions:n,busy:a,setBusy:c,setError:l,setNotice:d,refresh:f,onClose:m}){const x=n.filter(q=>e.sessionIds.includes(q.sessionId)&&!td(q.sessionId)),[y,w]=b.useState(()=>aF(e,r&&x.some(q=>q.sessionId===r)?r:"")),v=b.useRef(y),[T,S]=b.useState(null),I=q=>{const ve={...v.current,...q};v.current=ve,oF(e.id,ve),w(ve)},{name:N,rules:B,savedName:F,savedRules:P,rulesVersion:$,rulesMemberId:ee}=y,Z=ep(y),V=new TextEncoder().encode(B).length,de=x.some(q=>q.sessionId===ee),pe=async()=>{if(!(a||!N.trim())){c("group-name"),l(null),d(null);try{const q=await Hl({id:e.id,name:N.trim(),sessionIds:y.sessionIds??e.sessionIds,expectedUpdatedAt:y.updatedAt});S(null),I({savedName:q.group.name,name:q.group.name,updatedAt:q.group.updatedAt,sessionIds:q.group.sessionIds,...B===P?{rules:q.group.instructions?.text??"",savedRules:q.group.instructions?.text??"",rulesVersion:q.group.instructions?.version??""}:{}}),await f(),d("协作组名称已更新")}catch(q){S(null),l(q instanceof x0&&q.status===409?"组设置已被其他人修改。请查看最新状态并确认,名称与群规草稿仍保留。":q instanceof Error?q.message:"改名失败")}finally{c(null)}}},J=async()=>{if(!(a||!de||V>8192)){c("group-rules"),l(null),d(null);try{const q=await o9(e.id,{sessionId:ee,text:B,expectedVersion:$});S(null),I({savedName:q.group.name,...N===F?{name:q.group.name}:{},updatedAt:q.group.updatedAt,sessionIds:q.group.sessionIds,rules:q.group.instructions?.text??"",savedRules:q.group.instructions?.text??"",rulesVersion:q.group.instructions?.version??""}),await f(),d(B.trim()?"群规已保存,变更通知已入队":"群规已清空,变更通知已入队")}catch(q){S(null),l(q instanceof x0&&q.status===409?"群规已被其他人修改。请查看最新状态并确认,名称与群规草稿仍保留。":q instanceof Error?q.message:"群规保存失败")}finally{c(null)}}},Re=()=>{I(Xg(e,ee)),S(null),l(null)},Xe=async()=>{if(!a){c("group-latest"),l(null),d(null),S(null);try{const ve=(await ng()).groups.find(qe=>qe.id===e.id);if(!ve)throw new Error("协作组已删除;草稿仍保留,请返回看板查看。");S(ve)}catch(q){l(q instanceof Error?q.message:"最新状态读取失败;草稿仍保留,请重试。")}finally{c(null)}}};return s.jsxs("section",{"aria-label":"协作组设置",onKeyDown:q=>{q.key!=="Escape"||q.defaultPrevented||q.nativeEvent.isComposing||(q.preventDefault(),q.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(Mn,{size:14})})]}),s.jsxs("label",{className:"block space-y-1 text-[10px] text-muted-foreground",children:["协作组名称",s.jsx("input",{autoFocus:!0,className:Vs,value:N,maxLength:240,disabled:!!a,onChange:q=>I({name:q.target.value})})]}),s.jsx("div",{className:"mt-2 flex justify-end",children:s.jsx("button",{type:"button",disabled:!!a||!!T||!N.trim()||N.trim()===F,className:`${Lr} min-h-9 bg-primary text-primary-foreground`,onClick:()=>{pe()},children:a==="group-name"?"保存中…":"保存名称"})}),s.jsx(YO,{group:e,agents:t,busy:a,setBusy:c,refresh:f}),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:Vs,value:ee,disabled:!!a||!x.length,onChange:q=>I({rulesMemberId:q.target.value}),children:[s.jsx("option",{value:"",children:"选择当前服务的一个成员"}),!x.some(q=>q.sessionId===ee)&&ee&&s.jsx("option",{value:ee,children:"原成员已不在组内,请重新选择"}),x.map(q=>s.jsx("option",{value:q.sessionId,children:q.name},q.sessionId))]})]}),s.jsxs("label",{className:"block space-y-1 text-[10px] text-muted-foreground",children:["群规与协作约定",s.jsx("textarea",{className:`${Vs} min-h-24 resize-y`,value:B,maxLength:8192,disabled:!!a,onChange:q=>I({rules:q.target.value}),placeholder:"例如:说明分工、交接要求和结果格式。清空后保存可移除群规。"})]})]}),!de&&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] ${V>8192?"text-destructive":"text-muted-foreground"}`,children:V>8192?"内容过长,请缩短群规":"保存或清空群规会通知本组其他成员"}),s.jsx("button",{type:"button",disabled:!!a||!!T||!de||V>8192||B===P,className:`${Lr} min-h-9 shrink-0 bg-primary text-primary-foreground`,onClick:()=>{J()},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:`${Lr} mt-2 min-h-11 text-primary hover:bg-surface-elevated`,onClick:()=>{Xe()},children:a==="group-latest"?"读取中…":"查看最新状态并保留草稿"}),T&&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:["当前名称:",T.name]}),s.jsxs("p",{className:"whitespace-pre-wrap break-words text-muted-foreground",children:["当前群规:",T.instructions?.text||"未设置"]}),s.jsxs("p",{className:"break-words text-muted-foreground",children:["当前成员(",T.sessionIds.length,"):",T.sessionIds.map(q=>n.find(ve=>ve.sessionId===q)?.name??w4(q)).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:`${Lr} min-h-11 bg-primary text-primary-foreground`,onClick:()=>{I(iF(v.current,T)),S(null),l(null),d("已确认最新状态,草稿仍保留;请分别保存名称与群规。")},children:"确认最新状态,保留草稿"}),s.jsx("button",{type:"button",className:`${Lr} min-h-11 text-muted-foreground`,onClick:()=>S(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:`${Lr} min-h-9 text-muted-foreground hover:bg-surface-elevated`,onClick:Re,children:[s.jsx(wn,{size:12}),"重新载入",Z&&"(放弃草稿)"]}),s.jsx("button",{type:"button",disabled:!!a,className:`${Lr} min-h-9 bg-surface text-foreground`,onClick:m,children:Z?"关闭并保留草稿":"关闭"})]})]})}function fF({peers:e,currentGroupId:t,busy:r,setBusy:n,setError:a,setNotice:c,onSelectGroup:l}){const[d,f]=b.useState(null),[m,x]=b.useState(!1),y=e.services??[],w=e.removedServices??[],v=y.filter(I=>!I.connected),T=v.some(I=>I.groups?.some(N=>N.id===t)),S=async(I,N)=>{if(!r){n(`peer:${I}`),a(null),c(null);try{N?await f9(I):await p9(I),f(null),x(!1),c(N?"协作连接已恢复,正在连接服务":"协作连接已移除,不会再自动重连;已有会话和消息保留")}catch(B){a(B instanceof Error?B.message:N?"重新连接失败":"移除连接失败")}finally{n(null)}}};return s.jsxs("details",{className:"mt-4 shrink-0 rounded-lg border border-border/15",open:T||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:T?"当前协作组的部分服务不可达,消息会保留并等待重连。":"其他服务暂时离线;当前服务内的协作可以继续。不再使用的连接可移除。"}),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(I=>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:[bc({serviceLabel:I.label,serviceOrigin:I.origin}),s.jsx("span",{className:`ml-2 text-[9px] ${I.connected?"text-[var(--success)]":"text-muted-foreground"}`,children:I.connected?"已连接":I.error==="CONNECTING"?"连接中":"暂时离线"})]}),s.jsx(pF,{service:I})]}),I.serviceId&&s.jsxs("button",{type:"button",disabled:!!r,"aria-label":`移除协作连接 ${I.origin}`,className:`${Lr} min-h-9 shrink-0 text-muted-foreground hover:bg-destructive/10 hover:text-destructive`,onClick:()=>f(d===I.serviceId?null:I.serviceId),children:[s.jsx(Ds,{size:12}),"移除"]})]}),!!I.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:"用于"}),I.groups.map(N=>s.jsx("button",{type:"button",className:"rounded px-1.5 py-1 text-primary hover:bg-primary/10",onClick:()=>l(N.id),children:N.name},N.id))]}),!I.connected&&I.error&&I.error!=="CONNECTING"&&s.jsxs("details",{className:"mt-1 text-[9px] text-muted-foreground",children:[s.jsx("summary",{className:"cursor-pointer",children:AF(I.error)}),s.jsx("p",{className:"mt-1 select-text break-words",children:I.error})]}),d===I.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:I.groups?.length?"请先处理上方协作组的成员,再移除这条连接。":"移除后停止与该服务协作,保留已有会话和消息;以后可重新连接。"}),s.jsxs("div",{className:"mt-2 flex justify-end gap-2",children:[s.jsx("button",{type:"button",disabled:!!r,className:`${Lr} min-h-9 text-muted-foreground`,onClick:()=>f(null),children:"取消"}),s.jsx("button",{type:"button",disabled:!!r||!!I.groups?.length,className:`${Lr} min-h-9 bg-destructive text-destructive-foreground`,onClick:()=>{S(I.serviceId,!1)},children:r===`peer:${I.serviceId}`?"正在移除…":"确认移除"})]})]})]},I.serviceId||I.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:`${Lr} mt-1 min-h-9 text-primary hover:bg-primary/10`,onClick:h9,children:[s.jsx(wn,{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:`${Lr} min-h-9 text-muted-foreground hover:bg-surface-2`,onClick:()=>x(I=>!I),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(I=>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:[bc({serviceLabel:I.label,serviceOrigin:I.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:I.accessUrl||I.origin})]}),s.jsx("button",{type:"button",disabled:!!r||!I.serviceId,className:`${Lr} min-h-9 shrink-0 text-primary hover:bg-primary/10`,onClick:()=>{S(I.serviceId,!0)},children:r===`peer:${I.serviceId}`?"恢复中…":"恢复连接"})]},I.serviceId||I.origin))})]})]})]})]},T?"affected":"other")}function pF({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 Hm(e){return!td(e.sessionId)||e.serviceConnected!==!1}function mF(e){return e.serviceOrigin?e.serviceOrigin===window.location.origin?"":e.serviceOrigin:td(e.sessionId)?.origin??""}function ty(e){const t=new Map;for(const r of e){const n=mF(r),a=t.get(n)??{key:n,label:n?bc(r):"本机服务",sessions:[]};n&&a.label==="远端服务"&&(a.label=bc(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 ry({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(Al,{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 gF(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,...td(n)?{serviceConnected:!1}:{}})}return[...r.values()]}function Wm({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(qc,{size:9}),s.jsx("span",{className:"truncate",children:bc(e)})]})}function yf(e){return e.serviceConnected===!1?"服务不可达":e.status==="recovering"&&e.route_error==="ROUTE_NOT_CHECKED"?"投递目标未检查":yF(e.status)}function xF(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:")?bc(e):"本机服务";return r?`${e.name} · ${n}`:e.name}async function bF(e){e.sessionId.startsWith("remote:")?await G6(e.sessionId):window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:e.sessionId}))}function yF(e){return{ready:"终端可达",shell:"Shell 终端",recovering:"正在检查投递目标",unchecked:"投递目标未检查","terminal-connected":"终端已连接",detached:"终端未连接","agent-exited":"Agent 已退出",offline:"已离线",ambiguous:"需确认目标终端","identity-mismatch":"终端身份已变化",unavailable:"终端暂不可达","service-reachable":"服务可达","service-unreachable":"服务不可达"}[e]??"在线"}function Gm(e){if(!e)return"暂无任务摘要";try{const t=JSON.parse(e);if(typeof t.prompt=="string")return tp(t.prompt)||"暂无任务摘要"}catch{}return tp(e)||"暂无任务摘要"}function vF(e){return{message:"消息",ask:"问题",reply:"回复",task:"任务",handoff:"交接",done:"完成"}[e]}function wF(e,t){const r=new Map(t.map(a=>[a.sessionId,xF(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),a.delivery?.stage==="blocked"&&a.delivery.error&&!l.deliveryErrors.includes(a.delivery.error)&&l.deliveryErrors.push(a.delivery.error);const f={failed:-2,expired:-1,pending:0,delivered:1,read:2,stored:3};f[a.status]<f[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,deliveryErrors:a.delivery?.stage==="blocked"&&a.delivery.error?[a.delivery.error]:[]})}return[...n.values()].sort((a,c)=>c.createdAt-a.createdAt)}function AF(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 Vm({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 TF({active:e,onClose:t,onNewSession:r,setError:n}){const[a,c]=b.useState(""),[l,d]=b.useState([]),[f,m]=b.useState(0),[x,y]=b.useState(),[w,v]=b.useState(50),[T,S]=b.useState(0),[I,N]=b.useState(!1),[B,F]=b.useState(null),[P,$]=b.useState(null),ee=b.useRef(null),Z=b.useRef(0);b.useEffect(()=>{e&&ee.current?.focus({preventScroll:!0})},[e]),b.useEffect(()=>{if(!e)return;const pe=++Z.current,J=new AbortController;let Re;F(null),N(!0);const Xe=async()=>{try{const q=await m9(a.trim(),w,J.signal);if(pe!==Z.current)return;d(q.results),m(q.total??q.results.length),y(q.index),q.index?.building&&(Re=window.setTimeout(()=>{Xe()},2500))}catch(q){pe===Z.current&&!J.signal.aborted&&F(q instanceof Error?q.message:"搜索失败")}finally{pe===Z.current&&N(!1)}};return Re=window.setTimeout(()=>{Xe()},a.trim()?250:0),()=>{window.clearTimeout(Re),J.abort(),++Z.current}},[e,a,w,T]);const V=pe=>{n(null),c(pe),d([]),m(0),v(50)},de=async pe=>{if(!P){if(pe.live){window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:pe.sessionId})),t();return}if(!(!pe.nativeKey&&!pe.resumeHistoryId)){$(pe.sessionId),n(null);try{const J=pe.nativeKey?await g9(pe.nativeKey):await n3(pe.resumeHistoryId);if("sessionId"in J&&J.sessionId)window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:J.sessionId}));else if(J.command)r({mode:"shell",cwd:J.cwd,command:J.command});else throw new Error("这条会话暂时无法恢复,请重新搜索");t()}catch(J){n(J instanceof Error?J.message:"恢复失败")}finally{$(null)}}}};return s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"sticky -top-4 z-20 -mx-4 -mt-4 border-b border-border/15 bg-surface px-4 py-3",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-[13px] font-medium text-foreground",children:"历史会话搜索"}),s.jsx("p",{className:"mt-1 text-[10px] leading-relaxed text-muted-foreground",children:"搜索当前服务的 Codex、Claude 历史对话和 Termdock 终端记录,未启动的会话也能找到并恢复。"})]}),s.jsxs("label",{className:"relative mt-3 block",children:[s.jsx("span",{className:"sr-only",children:"搜索历史会话"}),s.jsx(Wl,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),s.jsx("input",{ref:ee,maxLength:512,className:`${Vs} pl-9 pr-9`,value:a,onChange:pe=>V(pe.target.value),placeholder:"搜索会话名称、对话关键词、目录或 session ID"}),I?s.jsx(wn,{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:()=>V(""),children:s.jsx(Mn,{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()?`找到 ${f} 个会话`:"最近的会话",f>l.length?` · 显示 ${l.length} 个`:""]}),s.jsxs("button",{type:"button",disabled:I,className:`${Lr} text-muted-foreground hover:bg-surface-2 hover:text-foreground`,onClick:()=>S(pe=>pe+1),children:[s.jsx(wn,{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 J=pe.live||!!(pe.nativeKey||pe.resumeHistoryId),Re=P===pe.sessionId?"正在恢复…":pe.live?"打开会话":J?"恢复会话":"仅供查阅",Xe=pe.source==="codex"||pe.source==="claude"?pe.snippet:SF(pe),q=pe.source==="codex"?"Codex 历史":pe.source==="claude"?"Claude 历史":"终端记录",ve=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(Vm,{value:pe.title,query:a})}),s.jsx("p",{className:"mt-0.5 break-all text-[9px] text-muted-foreground",children:s.jsx(Vm,{value:pe.cwd||"项目目录待索引",query:a})})]}),s.jsx("span",{className:`shrink-0 text-[10px] ${pe.live?"text-[var(--success)]":J?"text-primary":"text-muted-foreground"}`,children:Re})]}),Xe&&s.jsx("p",{className:"mt-2 line-clamp-3 break-words text-[10px] leading-relaxed text-foreground/75",children:s.jsx(Vm,{value:Xe,query:a})}),s.jsxs("p",{className:"mt-2 text-[9px] text-muted-foreground",children:[q," · ",rp(pe.updatedAt),a.trim()?` · ${pe.matchCount>=999?"999+":pe.matchCount} 处匹配`:"",J?"":" · 没有可恢复记录"]}),pe.agentNativeSessionId&&s.jsx("p",{className:"mt-1 select-text break-all text-[9px] text-muted-foreground",children:pe.agentNativeSessionId})]});return J?s.jsx("button",{disabled:!!P,onClick:()=>{de(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:ve},pe.nativeKey||pe.sessionId):s.jsx("article",{className:"px-2 py-3",children:ve},pe.sessionId)})}),f>l.length&&w<5e3&&s.jsx("button",{type:"button",disabled:I,className:`${Lr} w-full bg-surface-2 text-foreground`,onClick:()=>v(pe=>pe+50),children:I?"正在加载…":"加载更多会话"}),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:`${Lr} ml-2`,onClick:()=>S(pe=>pe+1),children:"重试"})]}),!I&&!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:`${Lr} mt-3 bg-surface-2 text-foreground`,onClick:()=>V(""),children:"查看最近会话"})]})]})}function tp(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 SF(e){let t=tp(e.snippet);for(const r of[e.title,e.cwd,e.agentSlug])r&&(t=t.split(r).join(" "));return tp(t)}function CF(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 _F(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 rp(e){return new Intl.DateTimeFormat("zh-CN",{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(e)}function kF(e){return e==="running"?"投递中":e==="success"?"已投递":e==="failed"?"投递失败":""}function LF(e){return e==="running"?"text-[var(--warning)]":e==="success"?"text-[var(--success)]":e==="failed"?"text-destructive":"text-muted-foreground"}function IF({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})}const t0=64,ny=10,EF=120;function NF({children:e,open:t,onOpenChange:r,onClose:n,closeLabel:a,closeTitle:c,compact:l}){const d=b.useRef(null),f=b.useRef(null),m=b.useRef(0),[x,y]=b.useState(null),w=x??(t?t0:0);return b.useEffect(()=>{if(!t)return;const v=T=>{T.target instanceof Node&&!d.current?.contains(T.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){f.current=null,y(null);return}!(v.target instanceof Element)||!v.target.closest(".sidebar-session-primary")||(f.current={pointerId:v.pointerId,x:v.clientX,y:v.clientY,startedAt:Date.now(),initialOffset:t?t0:0,offset:t?t0:0,horizontal:!1})}},onPointerMove:v=>{const T=f.current;if(!T||T.pointerId!==v.pointerId)return;const S=v.clientX-T.x,I=v.clientY-T.y;if(!T.horizontal){if(v.defaultPrevented||Date.now()-T.startedAt>=EF||Math.abs(I)>ny){f.current=null;return}if(Math.abs(S)<=ny)return;if(Math.abs(S)<Math.abs(I)*1.5||!t&&S<0){f.current=null;return}T.horizontal=!0,v.currentTarget.setPointerCapture?.(v.pointerId)}v.preventDefault(),T.offset=Math.max(0,Math.min(t0,T.initialOffset+S)),y(T.offset)},onPointerUp:v=>{const T=f.current;!T||T.pointerId!==v.pointerId||(f.current=null,T.horizontal&&(m.current=Date.now()+600,r(T.offset>=t0/2),y(null)))},onPointerCancel:()=>{f.current?.horizontal&&(m.current=Date.now()+600),f.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(Ds,{size:14}),a]})}),e]})}const sy="recoverable-tmux";function RF({sessions:e,loading:t,attachingName:r,onRefresh:n,onRestore:a,onClose:c}){const{t:l}=Hr(),d=Vt(N=>N.collapsedGroups.has(sy)),f=Vt(N=>N.toggleGroupCollapsed),[m,x]=b.useState(null),[y,w]=b.useState(null),[v,T]=b.useState(null),S=b.useRef(!1),I=async N=>{if(!(!c||S.current)){S.current=!0,w(N),T(null);try{await c(N),x(null)}catch(B){T(B instanceof Error?B.message:l("sidebar.closeRecoverableSessionFailed"))}finally{S.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:()=>f(sy),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(Ys,{size:12,className:`shrink-0 ${d?"":"rotate-90"}`}),s.jsx(Wc,{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(wn,{size:11,className:t?"animate-spin":""})})]}),!d&&s.jsx("div",{className:"space-y-0.5",children:e.map(N=>{const B=N.friendlyName?.trim()||N.label?.trim()||N.name,F=cd(N.cwd??null),P=r===N.name,$=m===N.name;return s.jsxs("div",{children:[s.jsxs("div",{className:"flex min-w-0 items-center",children:[s.jsxs("button",{type:"button",disabled:r!==null||y!==null||$,onClick:()=>a(N),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:N.cwd||N.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:P?s.jsx(jn,{size:12,className:"animate-spin"}):s.jsx(ru,{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:[N.program,F].filter(Boolean).join(" · ")||`tmux:${N.name}`})]}),s.jsx("span",{className:"shrink-0 text-[10px] font-medium text-[color:var(--tmux)] group-hover:text-foreground",children:l(P?"sidebar.restoringRecoverableSession":"sidebar.restore")})]}),c&&s.jsx("button",{type:"button",disabled:r!==null||y!==null,onClick:()=>{x(N.name),T(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(Mn,{size:12})})]}),$&&s.jsxs("div",{role:"group","aria-label":l("sidebar.closeSession",{name:B}),className:"space-y-2 rounded-md bg-surface px-2 py-2",children:[s.jsx("p",{className:"text-[11px] text-foreground",children:l("sidebar.confirmCloseRecoverableSession",{name:B})}),v&&s.jsx("p",{role:"alert",className:"text-[11px] text-destructive",children:v}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{type:"button",disabled:y!==null,onClick:()=>{x(null),T(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:()=>{I(N.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===N.name?l("common.loading"):l("sidebar.endRecoverableSession")})]})]})]},N.name)})})]})}const Mu="flex min-h-11 w-full items-center gap-2.5 rounded-lg px-3 text-left text-xs transition hover:bg-surface-2 focus:bg-surface-2 focus:outline-none",iy="min-h-11 rounded-lg px-4 text-xs transition disabled:opacity-40 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary";function MF({group:e,collapsed:t,onOpen:r,onMessages:n,onToggleCollapsed:a,onChanged:c,children:l}){const[d,f]=b.useState(null),[m,x]=b.useState(null),[y,w]=b.useState(""),[v,T]=b.useState(!1),S=b.useRef(!1),[I,N]=b.useState(""),B=b.useRef(null),F=b.useRef(null),P=b.useRef(null),$=b.useRef(null),ee=b.useRef(null),Z=b.useId(),V=Vg(),de=()=>ee.current?.isConnected?ee.current:F.current,pe=()=>{S.current||(x(null),N(""))};eu(P,!!d,()=>f(null),de),eu($,!!m,pe,de);const J=ve=>{ee.current=document.activeElement instanceof HTMLElement&&B.current?.contains(document.activeElement)?document.activeElement:F.current;const qe=F.current?.getBoundingClientRect();f(ve??{x:qe?.left??8,y:qe?.bottom??8})};b.useEffect(()=>{d&&P.current?.querySelector('[role="menuitem"]')?.focus({preventScroll:!0})},[d]),b.useEffect(()=>{if(!d)return;const ve=ce=>{ce.target instanceof Node&&!P.current?.contains(ce.target)&&!B.current?.contains(ce.target)&&f(null)},qe=ce=>{ce.target instanceof Node&&P.current?.contains(ce.target)||f(null)};return document.addEventListener("pointerdown",ve),window.addEventListener("resize",qe),window.addEventListener("scroll",qe,!0),()=>{document.removeEventListener("pointerdown",ve),window.removeEventListener("resize",qe),window.removeEventListener("scroll",qe,!0)}},[d]),b.useLayoutEffect(()=>{if(!d||!P.current)return;const ve=window.visualViewport,qe=(ve?.offsetLeft??0)+8,ce=(ve?.offsetTop??0)+8,ye=Math.min(240,(ve?.width??innerWidth)-16),Te=ce+(ve?.height??innerHeight)-16;Object.assign(P.current.style,{width:`${ye}px`,maxHeight:`${Te-ce}px`,left:`${Math.max(qe,Math.min(d.x,qe+(ve?.width??innerWidth)-16-ye))}px`,top:`${Math.max(ce,Math.min(d.y,Te-P.current.offsetHeight))}px`})},[d]);const Re=ve=>{f(null),ve()},Xe=ve=>{N(""),w(e.name),x({kind:ve,group:e})},q=async()=>{if(!(!m||S.current||m.kind==="rename"&&!y.trim())){S.current=!0,T(!0),N("");try{const ve=m.group,qe=m.kind==="delete"?(await t3(ve.id,ve.updatedAt),null):m.kind==="archive"||m.kind==="unarchive"?await b9(ve,m.kind==="archive"):(await Hl({id:ve.id,name:y.trim(),sessionIds:ve.sessionIds,expectedUpdatedAt:ve.updatedAt})).group;x(null),c(qe)}catch(ve){const qe=ve instanceof Error?ve.message:"操作失败,请重试";N(qe.includes("协作组已变化")?"协作组刚刚发生变化,请取消后重新打开操作。":qe)}finally{S.current=!1,T(!1)}}};return s.jsxs("div",{ref:B,className:"flex min-w-0 items-center","data-sidebar-gesture-ignore":!0,...V(()=>J()),onContextMenu:ve=>{ve.preventDefault(),ve.stopPropagation(),J({x:ve.clientX,y:ve.clientY})},onKeyDown:ve=>{(ve.key==="ContextMenu"||ve.shiftKey&&ve.key==="F10")&&(ve.preventDefault(),ve.stopPropagation(),J())},children:[l,s.jsx("button",{ref:F,type:"button","aria-label":`协作组操作:${e.name}`,title:"协作组操作","aria-haspopup":"menu","aria-expanded":!!d,"aria-controls":d?`${Z}-menu`:void 0,className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-surface-elevated hover:text-foreground focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary md:h-[30px] md:w-7",onClick:ve=>{ve.stopPropagation(),d?f(null):J()},children:s.jsx(Io,{size:14})}),d&&Ks.createPortal(s.jsxs("div",{ref:P,id:`${Z}-menu`,role:"menu",tabIndex:-1,"aria-label":`协作组操作:${e.name}`,"data-sidebar-gesture-ignore":!0,className:"fixed z-popover overflow-y-auto overscroll-contain rounded-xl border border-border/15 bg-surface p-1 shadow-[0_12px_32px_var(--app-shadow-soft)]",onKeyDown:ve=>{const qe=Array.from(ve.currentTarget.querySelectorAll('[role="menuitem"]:not(:disabled)')),ce=qe.indexOf(document.activeElement),ye=ve.key==="ArrowDown"?(ce+1)%qe.length:ve.key==="ArrowUp"?(ce-1+qe.length)%qe.length:ve.key==="Home"?0:ve.key==="End"?qe.length-1:null;ye!==null&&(ve.preventDefault(),ve.stopPropagation(),qe[ye]?.focus({preventScroll:!0})),ve.key==="Tab"&&(ve.preventDefault(),f(null))},children:[s.jsxs("button",{role:"menuitem",tabIndex:-1,className:Mu,onClick:()=>Re(r),children:[s.jsx(ru,{size:15}),"打开看板"]}),s.jsxs("button",{role:"menuitem",tabIndex:-1,disabled:!n,className:`${Mu} disabled:opacity-40`,onClick:()=>Re(()=>n?.()),children:[s.jsx(ud,{size:15}),"成员与消息"]}),s.jsxs("button",{role:"menuitem",tabIndex:-1,className:Mu,onClick:()=>Re(a),children:[s.jsx(Ys,{size:15,className:t?"":"rotate-90"}),t?"展开成员会话":"收起成员会话"]}),s.jsxs("button",{role:"menuitem",tabIndex:-1,className:Mu,onClick:()=>Re(()=>Xe("rename")),children:[s.jsx(qu,{size:15}),"重命名协作组"]}),!e.federated&&s.jsxs("button",{role:"menuitem",tabIndex:-1,className:Mu,onClick:()=>Re(()=>Xe(e.archivedAt===void 0?"archive":"unarchive")),children:[s.jsx(Af,{size:15}),e.archivedAt===void 0?"归档协作组":"恢复显示"]}),s.jsx("div",{role:"separator",className:"mx-2 my-1 h-px bg-border/30"}),s.jsxs("button",{role:"menuitem",tabIndex:-1,className:`${Mu} text-destructive`,onClick:()=>Re(()=>Xe("delete")),children:[s.jsx(Ds,{size:15}),"删除协作组"]})]}),document.body),m&&Ks.createPortal(s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-modal-backdrop bg-black/50 backdrop-blur-sm",onClick:pe}),s.jsxs("section",{ref:$,role:"dialog","aria-modal":"true","aria-labelledby":`${Z}-title`,"aria-describedby":`${Z}-description`,tabIndex:-1,className:"fixed left-1/2 top-1/2 z-modal-panel max-h-[calc(100dvh-2rem)] w-[min(24rem,calc(100vw-2rem))] -translate-x-1/2 -translate-y-1/2 overflow-y-auto rounded-2xl border border-border/15 bg-surface p-4 text-foreground shadow-[0_28px_70px_var(--app-shadow-strong)]",children:[s.jsxs("header",{className:"flex items-center gap-2",children:[s.jsx("h2",{id:`${Z}-title`,className:"min-w-0 flex-1 text-sm font-semibold",children:m.kind==="delete"?"删除协作组":m.kind==="archive"?"归档协作组":m.kind==="unarchive"?"恢复协作组显示":"重命名协作组"}),s.jsx("button",{type:"button","aria-label":"关闭协作组操作",disabled:v,className:"flex h-11 w-11 items-center justify-center rounded-lg hover:bg-surface-2",onClick:pe,children:s.jsx(Mn,{size:16})})]}),s.jsx("p",{id:`${Z}-description`,className:"my-3 break-words text-xs leading-6 text-muted-foreground",children:m.kind==="delete"?s.jsxs(s.Fragment,{children:["确定删除“",m.group.name,"”?协作组及组内消息会被移除,成员终端会保留。此操作无法撤销。",m.group.federated&&"删除会同步到其他服务。"]}):m.kind==="archive"?s.jsxs(s.Fragment,{children:["归档“",m.group.name,"”后,它会从默认侧栏隐藏。组、成员、消息和历史都会保留,之后可以恢复显示。"]}):m.kind==="unarchive"?s.jsxs(s.Fragment,{children:["恢复“",m.group.name,"”的显示后,它会重新出现在侧栏;不会自动恢复已关闭的会话。"]}):"修改协作组的名称。"}),s.jsxs("form",{onSubmit:ve=>{ve.preventDefault(),q()},children:[m.kind==="rename"&&s.jsxs("label",{className:"block text-xs text-muted-foreground",children:["协作组名称",s.jsx("input",{autoFocus:!0,required:!0,maxLength:256,disabled:v,className:"mt-2 min-h-11 w-full rounded-lg border border-border/30 bg-surface-2 px-3 text-sm text-foreground outline-none focus:border-primary",value:y,onChange:ve=>w(ve.target.value)})]}),I&&s.jsx("p",{role:"alert",className:"mt-3 break-words text-xs leading-5 text-destructive",children:I}),s.jsxs("footer",{className:"mt-4 flex justify-end gap-2",children:[s.jsx("button",{type:"button",disabled:v,className:`${iy} bg-surface-2`,onClick:pe,children:"取消"}),s.jsxs("button",{type:"submit",disabled:v||m.kind==="rename"&&!y.trim(),className:`${iy} inline-flex items-center gap-2 ${m.kind==="delete"?"bg-destructive text-destructive-foreground":"bg-primary text-primary-foreground"}`,children:[v&&s.jsx(wn,{size:14,className:"animate-spin"}),v?m.kind==="delete"?"正在删除…":"正在保存…":m.kind==="delete"?"确认删除":m.kind==="archive"?"归档并隐藏":m.kind==="unarchive"?"恢复显示":"保存名称"]})]})]})]})]}),document.body)]})}function jF(e,t){return og(e.filter(r=>r.archivedAt===void 0),t)}function r0(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 n0(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,f=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 T=y.sessionIds.flatMap(S=>{const I=r.get(S);return I?[I]:[]});m.push({kind:"collaboration",id:`collaboration:${y.id}`,group:y,members:T,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(f.has(w.id))continue;f.add(w.id);const v=w.sessionIds.flatMap(T=>{const S=r.get(T);return S?[S]:[]});m.push({kind:"workspace",id:`workspace:${w.id}`,workspace:w,members:v,sessionIds:w.sessionIds})}return m}function ay(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 DF({status:e,detail:t,needsReview:r,inCopyMode:n}){return s.jsx(mO,{status:e,detail:t,needsReview:r,inCopyMode:n})}function oy({isOpen:e,drawerWidthPx:t,onClose:r,onOpen:n,sessions:a,activeSessionId:c,sessionStates:l,onJumpToNextAttention:d,onNewSession:f,onCloseSession:m,onSplitSession:x,onCloseSplit:y,onRemoveFromSplit:w,splitWorkspaces:v,onSetSplitLayout:T,onReorderSplitWorkspace:S,onCombineSplitSessions:I,onReorderSessions:N,onSessionMenu:B,onOpenSettings:F,onOpenQuota:P,updateState:$,updateActionPending:ee=!1,onConfirmUpdateRestart:Z,onRetryUpdate:V,serverHealthState:de,tmuxAvailable:pe=!0,defaultSessionMode:J="shell",push:Re,pinned:Xe,onTogglePinned:q,recoverableTmuxSessions:ve=[],recoverableTmuxSessionsLoading:qe=!1,onRefreshRecoverableTmuxSessions:ce,onCloseRecoverableTmuxSession:ye}){const{t:Te}=Hr(),[,Fe]=b.useState(0),[se,De]=b.useState(null),[_e,Me]=b.useState(!1),[Je,Ne]=b.useState(!1),[ae,ze]=b.useState(null),at=b.useRef(!1),ut=b.useRef(0),me=b.useCallback(W=>{W||(ut.current+=1),Me(W)},[]),[dt,ft]=b.useState(!1),Se=Pi(W=>W.groupId),[We,Le]=b.useState({}),z=dt||Object.keys(We).length>0,ie=b.useRef(!1),ge=b.useRef(!1),[Ge,rt]=b.useState(null);b.useEffect(()=>{let W=!1;return wc().then(Ie=>{W||ie.current||Le(Object.fromEntries(k3(Ie.collaborationPanels?.[ip()]).map(Ye=>[Ye,!0])))}).catch(()=>{}),()=>{W=!0}},[]);const vt=async(W,Ie)=>{ie.current=!0,await Ya({floatingGroupId:Ie},W),Le(Ye=>({...Ye,[W]:Ie!==null}))},[Yt,Ut]=b.useState([]),[Nt,ir]=b.useState(!1),[Mt,Xt]=b.useState(null),[Bt,Wt]=b.useState(null),[xe,et]=b.useState(null),[ot,Et]=b.useState(null),K=Ou(W=>W.tasks),xt=Ou(W=>W.allTasks),[rr,$e]=b.useState(0),[Dr,Ce]=b.useState(null),St=b.useRef(!1),[Ot,tr]=b.useState({}),ct=Ou(W=>W.error),[Ct,or]=b.useState(!1),[Cr,Ir]=b.useState(!1);b.useEffect(()=>iu(()=>{Ou.getState().refresh()},5e3,[k0]),[]);const $r=async W=>(me(!1),ie.current=!0,W?(Pi.getState().open(W),zr(),!0):(ft(!0),zr(),!0)),Tt=kf(W=>W.collaborationGroups),Ft=kf(W=>W.setCollaborationGroups),[we,wt]=b.useState({mode:J}),{preference:it,agents:bt,detecting:An,refresh:xn,selectAgent:rn}=WO(),Oe=b.useRef(null);let _t=!1;if($?.latestVersion)try{_t=IQ($.latestVersion,$.currentVersion)>0}catch{}const mt=!!(_t&&$&&["checking","installing","ready","restarting","error"].includes($.status)),Zt=!!de?.attention,$t=[Te("sidebar.moreActions"),mt&&$?.latestVersion?Te("sidebar.updateAvailable",{version:$.latestVersion}):null].filter(Boolean).join(": "),wr=Vt(W=>W.groupByFolder),Tn=Vt(W=>W.collapsedGroups),Dn=Vt(W=>W.toggleGroupCollapsed),yn=b.useRef(null),un=b.useRef(null),Cn=b.useRef(null),Ur=b.useRef(0),ne=b.useRef(!1),Ze=b.useRef(null),Dt=b.useRef(null),[ur,Pr]=b.useState(!1),qr=b.useRef([]),sn=b.useRef(null),Nr=b.useRef(null),Wr=b.useRef(new Set),_n=b.useRef(null),en=b.useMemo(()=>new Set(v.flatMap(W=>W.sessionIds)),[v]),Fr=b.useMemo(()=>new Map(a.map(W=>[W.id,W])),[a]),Kr=b.useMemo(()=>jF(Tt,new Set(Fr.keys())),[Tt,Fr]),gr=b.useMemo(()=>og(Tt.filter(W=>W.archivedAt!==void 0),new Set(Fr.keys())),[Tt,Fr]),an=b.useCallback(async()=>{const W=++Ur.current;try{const Ie=await ng();if(W!==Ur.current)return;Ft(Array.isArray(Ie.groups)?Ie.groups:[])}catch{if(W!==Ur.current)return;Ft(Ie=>Ie.map(Ye=>({...Ye,remoteSessions:Ye.remoteSessions?.map(nt=>({...nt,status:"offline",serviceConnected:!1}))})))}},[]);b.useEffect(()=>r3(W=>Ft(W.groups)),[]),b.useEffect(()=>{const W=iu(()=>{an()},1e4,["focus",k0]);return()=>{Ur.current+=1,W()}},[an]),b.useEffect(()=>{(e||!z)&&an()},[z,e,an]);const Xr=b.useCallback(()=>{qr.current=Array.from(document.querySelectorAll("[data-collaboration-member], [data-collaboration-background]")).flatMap(W=>{const Ie=W.dataset.collaborationMember??"",Ye=W.hasAttribute("data-collaboration-background"),nt=W.closest("[data-collaboration-group]")?.dataset.collaborationGroup;if(!Ie&&!Ye||!nt)return[];const st=[];for(let yt=W.parentElement;yt;yt=yt.parentElement)st.push({element:yt,top:yt.scrollTop,left:yt.scrollLeft});return[{element:W,sessionId:Ie,groupId:nt,background:Ye,rect:W.getBoundingClientRect(),scrollParents:st}]})},[]),dn=b.useCallback((W,Ie)=>{if(!ne.current)return;document.querySelectorAll("[data-split-exit-drop-index]").forEach(Ee=>Ee.removeAttribute("data-active")),document.querySelectorAll("[data-drop-active]").forEach(Ee=>Ee.removeAttribute("data-drop-active"));const nt=document.elementsFromPoint(W,Ie).map(Ee=>Ee.closest("[data-collaboration-background]")).find(Boolean)?.closest("[data-collaboration-group]");if(nt?.dataset.collaborationGroup){nt.dataset.dropActive="true",Nr.current={kind:"collaboration",groupId:nt.dataset.collaborationGroup,background:!0};return}const st=qr.current.find(Ee=>{if(Ee.sessionId===Dt.current||!Ee.element.isConnected)return!1;const Ve=Ee.scrollParents.reduce((Qe,ar)=>Qe+ar.element.scrollLeft-ar.left,0),ht=Ee.scrollParents.reduce((Qe,ar)=>Qe+ar.element.scrollTop-ar.top,0);return W>=Ee.rect.left-Ve&&W<=Ee.rect.right-Ve&&Ie>=Ee.rect.top-ht+Ee.rect.height*.25&&Ie<=Ee.rect.bottom-ht-Ee.rect.height*.25});if(st?.background){st.element.closest("[data-collaboration-group]")?.setAttribute("data-drop-active","true"),Nr.current={kind:"collaboration",groupId:st.groupId,background:!0};return}if(st&&!v.find(Ve=>Ve.sessionIds.includes(st.sessionId))?.sessionIds.includes(Dt.current??"")){st.element.dataset.dropActive="true",Nr.current={kind:"split",sessionId:st.sessionId,groupId:st.groupId};return}const yt=document.elementsFromPoint(W,Ie).filter(Ee=>{const Ve=Ee.closest("[data-rfd-draggable-id]");return!Ve||!["session:","split-member:","collaboration-member:"].some(ht=>Ve.dataset.rfdDraggableId===`${ht}${Dt.current}`)}),Pt=yt.map(Ee=>Ee.closest("[data-collaboration-group]")).find(Ee=>Ee?.dataset.collaborationGroup);if(Pt?.dataset.collaborationGroup){const Ee=Pt.dataset.collaborationGroup,Ve=yt.map(sr=>sr.closest("[data-collaboration-split]")).find(Boolean),ht=yt.map(sr=>sr.closest("[data-collaboration-member]")).find(Boolean),Qe=ht?.dataset.collaborationMember??Ve?.dataset.splitAnchor,ar=Ee===Ze.current&&v.some(sr=>sr.sessionIds.includes(Qe??"")&&sr.sessionIds.includes(Dt.current??""));if(Qe&&!ar&&(Ee!==Ze.current||!ht&&Ve)){Pt.dataset.dropActive="true";const sr=ht??Ve;sr&&(sr.dataset.dropActive="true"),Nr.current={kind:"split",sessionId:Qe,groupId:Ee}}else{const sr=yt.some(It=>It.closest("[data-collaboration-background]"));(Ee!==Ze.current||sr)&&(Pt.dataset.dropActive="true"),Nr.current={kind:"collaboration",groupId:Ee,background:sr}}return}const ue=Array.from(document.querySelectorAll("[data-sidebar-entity-list-id]")).filter(Ee=>Ee.dataset.sidebarEntityListId===sn.current).find(Ee=>{const Ve=Ee.getBoundingClientRect();return W>=Ve.left&&W<=Ve.right&&Ie>=Ve.top-8&&Ie<=Ve.bottom+8});if(!ue){Nr.current=null;return}const R=Array.from(ue.children).filter(Ee=>Ee instanceof HTMLElement&&Ee.hasAttribute("data-sidebar-entity-index")),U=R.findIndex(Ee=>{const Ve=Ee.getBoundingClientRect();return Ie<Ve.top+Ve.height/2}),X=U<0?R.length:U;Nr.current={kind:"list",listId:ue.dataset.sidebarEntityListId??"",index:X};const be=Array.from(ue.querySelectorAll(":scope > [data-sidebar-entity-index] > [data-split-exit-drop-index]")).find(Ee=>Ee.dataset.splitExitDropIndex===String(X));be instanceof HTMLElement&&(be.dataset.active="true")},[v]);b.useEffect(()=>{const W=Ye=>dn(Ye.clientX,Ye.clientY),Ie=Ye=>{const nt=Ye.touches[0];nt&&dn(nt.clientX,nt.clientY)};return window.addEventListener("pointermove",W),window.addEventListener("touchmove",Ie,{passive:!0}),()=>{window.removeEventListener("pointermove",W),window.removeEventListener("touchmove",Ie)}},[dn]);const Rr=b.useCallback((W,Ie)=>{try{W(Ie)}finally{document.querySelectorAll("[data-sidebar-dragging]").forEach(Ye=>{delete Ye.dataset.sidebarDragging}),ne.current=!1,qr.current=[],Pr(!1),Ze.current=null,Dt.current=null,sn.current=null,Nr.current=null,document.querySelectorAll("[data-split-exit-drop-index]").forEach(Ye=>Ye.removeAttribute("data-active")),document.querySelectorAll("[data-drop-active]").forEach(Ye=>Ye.removeAttribute("data-drop-active"))}},[]),zn=b.useMemo(()=>a.filter(W=>!en.has(W.id)),[a,en]),pn=b.useMemo(()=>{let W=0;for(const Ie of a)l.get(Ie.id)?.agentStatus==="working"&&(W+=1);return W},[a,l]);b.useLayoutEffect(()=>{const W=yn.current,Ie=un.current;if(!e||!W||!Ie){Cn.current=null;return}const Ye=Ie.getBoundingClientRect(),nt=W.getBoundingClientRect(),st={item:W,top:Math.round(nt.top-Ye.top+Ie.scrollTop),height:Math.round(nt.height),viewportHeight:Ie.clientHeight},yt=Cn.current;if(Cn.current=st,yt?.item===st.item&&yt.top===st.top&&yt.height===st.height&&yt.viewportHeight===st.viewportHeight||ne.current||Ie.clientHeight===0)return;const Pt=8,H=nt.top-Ye.top,ue=nt.bottom-Ye.top;H<Pt?Ie.scrollTop+=H-Pt:ue>Ie.clientHeight-Pt&&(Ie.scrollTop+=ue-Ie.clientHeight+Pt)});const Gr=b.useMemo(()=>{if(!wr||!c)return null;const W=l.get(c)?.cwd??null;return dC(W)},[wr,c,l]);b.useEffect(()=>{if(!wr){_n.current=null,Wr.current.clear();return}if(!c){_n.current=null;return}const W=Vt.getState(),Ie=Wr.current,Ye=_n.current,nt=Gr;Ye!==null&&Ye!==nt&&Ie.has(Ye)&&(W.collapsedGroups.has(Ye)||W.toggleGroupCollapsed(Ye),Ie.delete(Ye)),nt!==null&&nt!==""&&W.collapsedGroups.has(nt)&&(W.toggleGroupCollapsed(nt),Ie.add(nt)),_n.current=nt},[wr,c,Gr]),b.useEffect(()=>{e||me(!1)},[e]),b.useEffect(()=>{wt(W=>({...W,command:it?.command}))},[it]),b.useEffect(()=>{if(!_e)return;let W=!1;return ir(!0),Wt(null),Ex().then(Ie=>{W||Ut(Ie)}).catch(()=>{W||Wt(Te("sidebar.resumeHistoryLoadFailed"))}).finally(()=>{W||ir(!1)}),()=>{W=!0}},[_e,Te]),b.useEffect(()=>{if(!se)return;const W=Ie=>{Ie instanceof KeyboardEvent&&Ie.key!=="Escape"||Ie instanceof PointerEvent&&Ie.target instanceof Node&&Oe.current?.contains(Ie.target)||De(null)};return window.addEventListener("pointerdown",W),window.addEventListener("keydown",W),()=>{window.removeEventListener("pointerdown",W),window.removeEventListener("keydown",W)}},[se]);const zr=()=>{!Re&&!Xe&&r()};b.useEffect(()=>{const W=Ie=>{me(!1);const{groupId:Ye,dock:nt}=Ie.detail;ie.current=!0,ns.getState().setDock(Ye,{...nt,preferredWidth:360}),Le(st=>({...st,[Ye]:!0})),Pi.getState().terminal(),zr()};return window.addEventListener("termdock:open-collaboration-messages",W),()=>window.removeEventListener("termdock:open-collaboration-messages",W)},[zr]);const Y=J==="tmux"&&!pe?"shell":J,Be=(W,Ie=!1)=>{if(at.current)return;at.current=!0,Ne(!0),ze(null);const Ye=ut.current;f({...W,shouldActivate:()=>Ye===ut.current&&(W.shouldActivate?.()??!0),onResult:nt=>{if(at.current=!1,Ne(!1),!nt.ok){ze(nt.error);return}Ye===ut.current&&(Ie&&me(!1),zr())}})},Qt=()=>{Be({mode:Y})},er=()=>{it&&Be({mode:Y,command:it.command})},nr=W=>{me(!1),et(W.name),f({mode:"tmux",tmuxSessionName:W.name,cwd:W.cwd??void 0}),zr()};b.useEffect(()=>{xe&&(ve.some(W=>W.name===xe)||et(null))},[xe,ve]);const Or=(W,Ie)=>{Be({...we,cwd:we.cwd?.trim()||void 0,command:Ie??W?.command},!0)},kr=async W=>{Xt(W.id),Wt(null);try{const Ie=await n3(W.id);Be({mode:"shell",cwd:Ie.cwd,command:Ie.command},!0)}catch(Ie){const Ye=Ie&&typeof Ie=="object"&&"code"in Ie?String(Ie.code??""):"";Wt(Te(Ye==="AGENT_SESSION_ACTIVE_ELSEWHERE"?"tab.resumeAgentConflict":"sidebar.resumeHistoryFailed"))}finally{Xt(null)}},Zn=async W=>{Ut(Ie=>Ie.filter(Ye=>Ye.id!==W));try{await L9(W)}catch{Wt(Te("sidebar.resumeHistoryRemoveFailed")),Ex().then(Ut).catch(()=>{})}},ys=()=>{if(_e){me(!1);return}at.current||(ut.current+=1,at.current||ze(null),wt({mode:J==="tmux"&&!pe?"shell":J,cwd:c?l.get(c)?.cwd??void 0:void 0,command:it?.command}),me(!0))},ss=b.useCallback(W=>{const Ie=l.get(W);return Ie?.agentStatus==="waiting"||Ie?.agentNeedsReview?"bg-[rgb(var(--warning-rgb)_/_0.10)] text-foreground":Ie?.agentStatus==="working"?"bg-[rgb(var(--success-rgb)_/_0.08)] text-foreground":Ie?.inCopyMode?"bg-[rgb(var(--tmux-rgb)_/_0.08)] text-foreground":null},[l]),Hn=Vg(),[hn,Qn]=b.useState(null);b.useEffect(()=>{e||Qn(null)},[e]);const Xn=b.useCallback((W,Ie,Ye,nt,st)=>{const yt=!Se&&W.id===c,Pt=en.has(W.id),H=!!(Ye&&Pt),ue=l.get(W.id),R=cd(ue?.cwd??null),U=ue?.shellTitle??y9(W.id),X=U===ue?.cwd||U===R?null:U,be=v9(W,ue?.activeProgram??null,null,w9,X,ue?.promptState??null),Ee=!!(ue?.tuiProgress&&ue.tuiProgress.state!=="remove"),ht=ue?.promptState==="running"||ue?.agentStatus==="working"||Ee?"bg-[var(--success)]":ue?.agentStatus==="waiting"||ue?.agentNeedsReview?"bg-[var(--warning)]":ue?.inCopyMode?"bg-[var(--tmux)]":"bg-primary";return s.jsxs(NF,{open:hn===W.id,onOpenChange:Qe=>Qn(ar=>Qe?W.id:ar===W.id?null:ar),onClose:Qe=>m(W.id,Qe,{skipConfirmation:!0}),closeLabel:Te("common.close"),closeTitle:Te("sidebar.closeSession",{name:be}),compact:Ye,children:[s.jsxs("button",{ref:yt?yn:null,type:"button",...Ie??{},onContextMenu:Qe=>{B&&(Qe.preventDefault(),B(W.id,{x:Qe.clientX,y:Qe.clientY}))},onClick:()=>{me(!1),Pi.getState().terminal(),window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:W.id})),zr()},className:`sidebar-session-primary relative min-w-0 flex flex-1 items-center overflow-hidden text-left ${Ie?"cursor-grab active:cursor-grabbing ":""}${Ye?"gap-1.5 py-0.5 pl-1.5 pr-0.5":"gap-1.5 py-1 pl-2 pr-1"}`,title:ue?.cwd??W.name,children:[yt&&s.jsx("span",{className:`absolute inset-y-2 left-0 w-0.5 rounded-full ${ht}`}),s.jsxs("span",{className:`relative inline-flex shrink-0 items-center justify-center rounded-md ${Ye?"h-5 w-[22px]":"h-[22px] w-[22px]"} ${yt?W.mode==="tmux"?"bg-[rgb(var(--tmux-rgb)_/_0.15)] text-[color:var(--tmux)]":"bg-primary/15 text-primary":W.mode==="tmux"?"bg-surface text-[rgb(var(--tmux-rgb)_/_0.80)]":"bg-surface text-muted-foreground"}`,children:[ue?.isConnecting||Ee&&!ue?.agentStatus?s.jsx(jn,{size:Ye?10:11,className:"animate-spin"}):ue?.agent??Nx(W.id)?s.jsx(Jc,{agent:ue?.agent??Nx(W.id),size:Ye?13:15}):W.mode==="tmux"?s.jsx(ru,{size:Ye?10:11}):s.jsx(Zo,{size:Ye?10:11}),s.jsx(DF,{status:ue?.agentStatus??null,detail:ue?.agentStatusDetail,needsReview:ue?.agentNeedsReview,inCopyMode:ue?.inCopyMode})]}),s.jsx("span",{className:`min-w-0 flex-1 truncate leading-tight ${Ye?"text-[11px]":"text-[12px]"} ${yt?"font-medium text-foreground":""} ${ue?.inCopyMode?"text-[color:var(--tmux)]":""}`,children:be}),s.jsx(db,{sessionIds:[W.id]})]}),nt,s.jsx("button",{type:"button",onClick:Qe=>{Qe.stopPropagation(),H?w(W.id):Pt?y(W.id):x(W.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 ${Ye?"h-6 w-6":"h-[26px] w-[26px]"} ${Pt?"bg-primary/15 text-primary":"text-muted-foreground/70"}`,"aria-label":`${Te(H?"tab.splitRemovePane":Pt?"tab.splitClose":"tab.split")} ${be}`,title:Te(H?"tab.splitRemovePane":Pt?"tab.splitClose":"tab.split"),children:H?s.jsx(XS,{size:11}):s.jsx(Fl,{size:12})}),st??s.jsx("button",{type:"button",onClick:Qe=>{Qe.stopPropagation(),m(W.id,Qe)},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 ${Ye?"h-6 w-6":"h-[26px] w-[26px]"}`,"aria-label":Te("sidebar.closeSession",{name:be}),title:Te("common.close"),children:s.jsx(Mn,{size:Ye?11:12})})]})},[c,en,l,m,x,y,w,B,Te,hn]),fn=b.useMemo(()=>Cf(a,W=>l.get(W.id)?.cwd??null,wr,Te("sidebar.ungrouped"),v,Kr).groups,[Kr,wr,a,l,v,Te]),cr=b.useMemo(()=>n0(a,v,Fr,Kr),[Kr,a,Fr,v]),is=b.useCallback(W=>{Pr(W.draggableId.startsWith("collaboration:")||W.draggableId.startsWith("workspace:"));const Ie=W.draggableId.replace(/^split-member:/,"");Dt.current=W.draggableId.replace(/^(?:session|split-member|collaboration-member):/,"");const Ye=W.type==="split-member"?v.find(H=>H.sessionIds.includes(Ie)):null,nt=W.type==="collaboration-member"?W.source.droppableId.replace(/^collaboration-members:/,""):null,st=nt?Kr.find(H=>H.id===nt):null;ne.current=!!(Ye||st||W.type==="session"&&W.draggableId.startsWith("session:")),ne.current&&document.querySelectorAll("[data-collaboration-group]").forEach(H=>{H.dataset.sidebarDragging="true"}),Ze.current=st?.id??null;const yt=Ye?.sessionIds??st?.sessionIds??[],Pt=yt.length>0?fn.find(H=>yt.every(ue=>H.sessions.some(R=>R.id===ue))):null;sn.current=wr?Pt?`group-sessions:${Pt.key}`:null:yt.length>0?"sidebar-entities":null,Nr.current=null},[Kr,fn,wr,v]),tn=b.useCallback((W,Ie,Ye)=>{if(Ie===Ye)return;const nt=Ie?Tt.find(ue=>ue.id===Ie):null,st=Ye?Tt.find(ue=>ue.id===Ye):null;if(Ye&&!st)return;if(st){const ue=a.map(U=>U.id).filter(U=>U!==W);let R=-1;ue.forEach((U,X)=>{st.sessionIds.includes(U)&&(R=X)}),R>=0&&(ue.splice(R+1,0,W),N(ue))}const yt=nt?.sessionIds.filter(ue=>ue!==W)??[],Pt=st?[...st.sessionIds.filter(ue=>ue!==W),W]:[];Ft(ue=>ue.flatMap(R=>R.id===Ie?[{...R,sessionIds:yt}]:R.id===Ye?[{...R,sessionIds:Pt}]:[R])),Et(null),(nt&&st?A9({sourceGroupId:nt.id,targetGroupId:st.id,sessionId:W,expectedSourceUpdatedAt:nt.updatedAt,expectedTargetUpdatedAt:st.updatedAt}):nt?Hl({id:nt.id,name:nt.name,sessionIds:yt,expectedUpdatedAt:nt.updatedAt}):st?Hl({id:st.id,name:st.name,sessionIds:Pt,expectedUpdatedAt:st.updatedAt}):Promise.resolve()).then(()=>an(),ue=>(Et(ue instanceof Error?ue.message:"协作成员移动失败"),an()))},[Tt,an,a,N]),xr=b.useCallback((W,Ie,Ye,nt=!1)=>{const st=Tt.find(Ve=>Ve.id===W);if(!st||Ie===Ye)return;const yt=st.sessionIds.filter(Ve=>!Ve.startsWith("remote:")),Pt=r0(yt,v).flatMap(Ve=>Ve.sessionIds),H=ob(xt,st.id),ue=nt&&!Ot[st.id]?Pt.filter(Ve=>!H.has(Ve)||Ve===c||en.has(Ve)):Pt.slice(),R=new Set(ue),[U]=ue.splice(Ie,1);if(!U)return;ue.splice(Ye,0,U);let X=0;const be=Pt.map(Ve=>R.has(Ve)?ue[X++]:Ve),Ee=v.find(Ve=>Ve.sessionIds.includes(U));if(Ee&&Ee.sessionIds.every(Ve=>st.sessionIds.includes(Ve))){const Ve=be.filter(ht=>Ee.sessionIds.includes(ht));S(Ee.id,Ve)}be.push(...st.sessionIds.filter(Ve=>Ve.startsWith("remote:"))),Ft(Ve=>Ve.map(ht=>ht.id===W?{...ht,sessionIds:be}:ht)),Et(null),Hl({id:st.id,name:st.name,sessionIds:be,expectedUpdatedAt:st.updatedAt}).then(()=>an(),Ve=>(Et(Ve instanceof Error?Ve.message:"成员排序失败"),an()))},[Tt,an,v,S,xt,Ot,c,en]);b.useEffect(()=>{const W=Ie=>{const{sourceId:Ye,targetId:nt}=Ie.detail;if(!Ye||!nt||Ye===nt)return;const st=Cf(a,Qe=>l.get(Qe.id)?.cwd??null,wr,"",v,Kr).arranged.map(Qe=>Qe.id),yt=st.indexOf(Ye),Pt=st.indexOf(nt);if(yt<0||Pt<0)return;const H=Kr.find(Qe=>Qe.sessionIds.includes(Ye));if(H?.sessionIds.includes(nt)){const Qe=r0(H.sessionIds,v).flatMap(ar=>ar.sessionIds);xr(H.id,Qe.indexOf(Ye),Qe.indexOf(nt));return}const ue=v.filter(Qe=>Qe.sessionIds.length>=2&&Qe.sessionIds.every(ar=>Fr.has(ar))&&!Kr.some(ar=>Qe.sessionIds.some(sr=>ar.sessionIds.includes(sr)))),R=ue.find(Qe=>Qe.sessionIds.includes(Ye));if(R?.sessionIds.includes(nt)){const Qe=[...R.sessionIds];Qe.splice(Qe.indexOf(Ye),1),Qe.splice(R.sessionIds.indexOf(nt),0,Ye),S(R.id,Qe);return}const U=Qe=>Kr.find(ar=>ar.sessionIds.includes(Qe))?.sessionIds??ue.find(ar=>ar.sessionIds.includes(Qe))?.sessionIds??[Qe],X=new Set(U(Ye)),be=new Set(U(nt)),Ee=st.filter(Qe=>!X.has(Qe)),Ve=Ee.flatMap((Qe,ar)=>be.has(Qe)?[ar]:[]),ht=yt<Pt?Math.max(...Ve)+1:Math.min(...Ve);Ee.splice(ht,0,...st.filter(Qe=>X.has(Qe))),N(Ee)};return window.addEventListener("reorder-navigation-session",W),()=>window.removeEventListener("reorder-navigation-session",W)},[a,l,wr,v,Kr,Fr,xr,S,N]);const vr=b.useCallback(W=>{if(W.type!=="collaboration-member")return!1;if(W.reason==="CANCEL")return!0;const Ie=W.source.droppableId.replace(/^collaboration-members:/,""),Ye=W.draggableId.replace(/^collaboration-member:/,""),nt=Nr.current;if(nt?.kind==="split")return tn(Ye,Ie,nt.groupId),I(nt.sessionId,Ye),!0;if(nt?.kind==="collaboration"&&nt.groupId!==Ie)return tn(Ye,Ie,nt.groupId),!0;if(nt?.kind==="collaboration"&&nt.background)return en.has(Ye)&&w(Ye),!0;if(W.destination&&W.destination.droppableId!==W.source.droppableId){const st=W.destination.droppableId.replace(/^collaboration-members:/,"");if(Kr.some(yt=>yt.id===st))return tn(Ye,Ie,st),!0}if(W.combine){const st=W.combine.droppableId.replace(/^collaboration-members:/,"");st!==Ie&&tn(Ye,Ie,st);const yt=W.combine.draggableId.replace(/^collaboration-member:/,"");if(v.find(H=>H.sessionIds.includes(Ye))?.sessionIds.includes(yt)){const H=Kr.find(R=>R.id===Ie),ue=H?r0(H.sessionIds,v).flatMap(R=>R.sessionIds).indexOf(yt):-1;ue>=0&&H&&xr(Ie,r0(H.sessionIds,v).flatMap(R=>R.sessionIds).indexOf(Ye),ue)}else Fr.has(yt)&&I(yt,Ye);return!0}if(W.destination?.droppableId===W.source.droppableId)return xr(Ie,W.source.index,W.destination.index,!0),!0;if(nt?.kind!=="list")return!0;if(nt?.kind==="list"){const st=fn.find(Pt=>`group-sessions:${Pt.key}`===nt.listId),yt=nt.listId==="sidebar-entities"?cr:st?n0(st.sessions,v,Fr,Kr):null;if(yt){const Pt=ay(yt,Ye,nt.index);nt.listId==="sidebar-entities"?N(Pt):st&&N(fn.flatMap(H=>H.key===st.key?Pt:H.sessions.map(ue=>ue.id)))}}return tn(Ye,Ie,null),!0},[Kr,cr,fn,tn,N,xr,Fr,v,en,w,I]),br=b.useCallback(W=>{if(W.type!=="split-member")return!1;if(W.reason==="CANCEL")return!0;const Ie=W.draggableId.replace(/^split-member:/,""),Ye=v.find(ue=>ue.sessionIds.includes(Ie));if(!Ye?.sessionIds.includes(Ie))return!0;const nt=Ye.id,st=Nr.current;if(st?.kind==="split")return tn(Ie,null,st.groupId),I(st.sessionId,Ie),!0;if(st?.kind==="collaboration")return tn(Ie,null,st.groupId),!0;if(!W.destination&&st?.kind==="list"){const ue=fn.find(X=>`group-sessions:${X.key}`===st.listId),R=st.listId==="sidebar-entities"?cr:ue?n0(ue.sessions,v,Fr,Kr):null;if(!R)return!0;const U=ay(R,Ie,st.index);return w(Ie),st.listId==="sidebar-entities"?N(U):ue&&N(fn.flatMap(X=>X.key===ue.key?U:X.sessions.map(be=>be.id))),!0}if(!W.destination)return!0;const yt=W.destination.droppableId.replace(/^split-members:/,"");if(yt!==nt){const R=v.find(U=>U.id===yt)?.sessionIds[0];return R&&I(R,Ie),!0}if(W.source.index===W.destination.index)return!0;const Pt=[...Ye.sessionIds],[H]=Pt.splice(W.source.index,1);return H&&(Pt.splice(W.destination.index,0,H),S(nt,Pt)),!0},[Kr,cr,fn,tn,I,w,N,S,Fr,v]),us=(W,Ie="top")=>s.jsx("div",{"data-split-exit-drop-index":W,className:`group/split-exit pointer-events-none absolute inset-x-0 z-10 h-2 ${Ie==="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"})}),Bn=b.useCallback((W,Ie,Ye)=>{if(vr(W)||br(W)||W.reason==="CANCEL")return;const nt=Ie.find(ue=>ue.id===W.draggableId);if(!nt)return;const st=Nr.current;if(st?.kind==="split"&&nt.kind==="session"){tn(nt.session.id,null,st.groupId),I(st.sessionId,nt.session.id);return}if(st?.kind==="collaboration"&&nt.kind==="session"){tn(nt.session.id,null,st.groupId);return}if(W.combine&&nt.kind!=="session"){const ue=Ie.findIndex(R=>R.id===W.combine?.draggableId);if(ue<0)return;W={...W,combine:null,destination:{...W.source,index:ue}}}if(W.combine){const ue=Ie.find(Ee=>Ee.id===W.combine?.draggableId);if(!ue)return;const R=ue.kind==="workspace"?ue:nt.kind==="workspace"?nt:ue,U=R===nt?ue:nt,X=R.sessionIds[0],be=U.sessionIds[0];X&&be&&X!==be&&I(X,be);return}if(!W.destination||W.source.index===W.destination.index)return;const yt=[...Ie],[Pt]=yt.splice(W.source.index,1);if(!Pt)return;yt.splice(W.destination.index,0,Pt);const H=yt.flatMap(ue=>ue.sessionIds);if(Ye===void 0){N(H);return}N(fn.flatMap(ue=>ue.key===Ye?H:ue.sessions.map(R=>R.id)))},[fn,vr,br,tn,I,N]),vs=b.useCallback(W=>{if(W.reason==="CANCEL"||vr(W)||br(W))return;if(W.type==="group"){if(!W.destination||W.source.index===W.destination.index)return;N(b3(fn,W.source.index,W.destination.index));return}const Ie=W.source.droppableId.replace(/^group-sessions:/,""),Ye=fn.find(st=>st.key===Ie);if(!Ye)return;const nt=n0(Ye.sessions,v,Fr,Kr);if(W.combine||Nr.current?.kind==="collaboration"||Nr.current?.kind==="split"){Bn(W,nt,Ie);return}!W.destination||W.destination.droppableId!==W.source.droppableId||Bn(W,nt,Ie)},[Kr,fn,Fr,v,vr,Bn,br,N]),Bs=W=>{const Ie=se===W.id,Ye=[{layout:"horizontal",label:Te("tab.splitHorizontal"),icon:Fl},{layout:"vertical",label:Te("tab.splitVertical"),icon:Bx},...W.sessionIds.length>=3||W.layout==="grid"?[{layout:"grid",label:Te("tab.splitGrid"),icon:Dx}]:[]],nt=W.layout==="vertical"?Bx:W.layout==="grid"?Dx:Fl,st=Ye.find(yt=>yt.layout===W.layout)?.label??Te("tab.splitHorizontal");return s.jsxs("div",{ref:Ie?Oe:void 0,className:"relative shrink-0",onPointerDown:yt=>yt.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 ${Ie?"bg-primary/15 text-primary":"text-muted-foreground/70 hover:bg-surface-2 hover:text-foreground"}`,"aria-label":`${Te("tab.splitLayout")}: ${st}`,"aria-haspopup":"menu","aria-expanded":Ie,title:Te("tab.splitLayout"),onClick:yt=>{yt.stopPropagation(),De(Pt=>Pt===W.id?null:W.id)},children:s.jsx(nt,{size:12})}),Ie&&s.jsx("div",{role:"menu","aria-label":Te("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:Ye.map(yt=>{const Pt=yt.icon,H=yt.layout===W.layout;return s.jsx("button",{type:"button",role:"menuitemradio","aria-checked":H,"aria-label":yt.label,title:yt.label,className:`sidebar-session-action inline-flex h-7 w-7 items-center justify-center rounded-sm transition active:scale-95 ${H?"bg-primary/15 text-primary":"text-muted-foreground hover:bg-surface-2 hover:text-foreground"}`,onClick:ue=>{ue.stopPropagation(),T(W.sessionIds[0],yt.layout),De(null)},children:s.jsx(Pt,{size:13})},yt.layout)})})]})},Ls=(W,Ie)=>Ie&&s.jsx("button",{type:"button",...Ie,"aria-label":W,title:W,onClick:Ye=>Ye.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(sp,{size:10})}),Qr=(W,Ie,Ye=!1,nt=!1,st)=>{if(Ie.length<2)return null;const yt=Ie.some(X=>X.id===c),Pt=[],H=[],ue=[];for(const X of Ie){const be=l.get(X.id);be?.agentStatus==="waiting"||be?.agentNeedsReview?Pt.push(X):be?.agentStatus==="working"?H.push(X):be?.inCopyMode&&ue.push(X)}const R=W.name?.trim()||`${Te("tab.splitWorkspace")} ${v.findIndex(X=>X.id===W.id)+1}`,U=se===W.id;return s.jsxs("section",{"data-split-workspace":W.id,"aria-label":R,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 ${nt?"bg-primary/15 ring-1 ring-primary/40":Ye?"bg-surface-elevated opacity-90 shadow-lg":Pt.length>0?"bg-[rgb(var(--warning-rgb)_/_0.08)] hover:bg-[rgb(var(--warning-rgb)_/_0.12)]":H.length>0?"bg-[rgb(var(--success-rgb)_/_0.06)] hover:bg-[rgb(var(--success-rgb)_/_0.10)]":ue.length>0?"bg-[rgb(var(--tmux-rgb)_/_0.07)] hover:bg-[rgb(var(--tmux-rgb)_/_0.11)]":yt?"bg-primary/[0.07]":"hover:bg-surface-2"}`,children:[Ls(`移动分屏组 ${R}`,st),s.jsx(Ol,{droppableId:`split-members:${W.id}`,type:"split-member",direction:"vertical",children:(X,be)=>s.jsxs("div",{ref:X.innerRef,...X.droppableProps,"data-split-members":!0,className:be.isDraggingOver?"rounded-sm bg-primary/10 ring-1 ring-primary/40":"",children:[Ie.map((Ee,Ve)=>s.jsx(Pl,{draggableId:`split-member:${Ee.id}`,index:Ve,disableInteractiveElementBlocking:!0,children:(ht,Qe)=>s.jsx("div",{ref:ht.innerRef,...ht.draggableProps,...B?Hn(()=>B(Ee.id)):{},className:`${Ve===0&&U?"relative z-20 ":"relative "}flex items-center rounded-sm pr-0.5 transition-colors ${Qe.isDragging?"bg-surface-elevated opacity-90 shadow-lg ":""}${ss(Ee.id)??(Ee.id===c?"bg-surface-elevated/80 text-foreground":"text-muted-foreground hover:bg-surface-2")}`,children:Xn(Ee,ht.dragHandleProps,!0,Ve===0?Bs(W):void 0)})},Ee.id)),X.placeholder]})})]})},yr=(W,Ie)=>{const Ye=c??Ie;ge.current||!Ye||(me(!1),ge.current=!0,rt(W),Et(null),RC(W,Ye).catch(nt=>Et(nt instanceof Error?nt.message:"消息面板打开失败,请重试")).finally(()=>{ge.current=!1,rt(null)}))},Pn=(W,Ie)=>{Ur.current+=1,Ft(Ye=>Ie?Ye.map(nt=>nt.id===W?Ie:nt):Ye.filter(nt=>nt.id!==W)),Ie||(Pi.getState().groupId===W&&Pi.getState().terminal(),ns.getState().setDock(W,null),Le(Ye=>{const nt={...Ye};return delete nt[W],nt}),requestAnimationFrame(()=>yn.current?.focus({preventScroll:!0})),Ya({floatingGroupId:null},W).catch(()=>Et("协作组已删除,面板布局保存失败,请刷新后检查。"))),an()},Jn=(W,Ie,Ye,nt=!1,st=!1)=>{const yt=`collaboration:${W.id}`,Pt=Tn.has(yt),H=`collaboration-members-${W.id}`,ue=Se===W.id||!Se&&Ie.some(Qe=>Qe.id===c),R=ob(xt,W.id),U=W.sessionIds.filter(Qe=>R.has(Qe)&&Qe!==c&&!en.has(Qe)),X=Ot[W.id]===!0,be=X?W.sessionIds:W.sessionIds.filter(Qe=>!U.includes(Qe)),Ee=r0(be,v),Ve=Ee.flatMap(Qe=>Qe.sessionIds),ht=Ee.length===1?Ee[0]?.workspace:void 0;return s.jsxs("section",{"data-collaboration-group":W.id,"data-collaboration-group-name":W.name,"aria-label":`Agent 工作组:${W.name}`,className:`group/collaboration relative rounded-md ${Pt?"":"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 ${st?"bg-primary/15 ring-1 ring-primary/40":nt?"bg-surface-elevated opacity-90 shadow-lg":ue?"bg-primary/[0.07]":"hover:bg-surface-2"}`,children:[Ls(`移动工作组 ${W.name}`,Ye),s.jsxs(MF,{group:Tt.find(Qe=>Qe.id===W.id)??W,collapsed:Pt,onOpen:()=>{$r(W.id)},onMessages:Ge===null&&(c||Ie.length)?()=>yr(W.id,Ie[0]?.id):void 0,onToggleCollapsed:()=>Dn(yt),onChanged:Qe=>Pn(W.id,Qe),children:[s.jsx("button",{type:"button","aria-label":`${Pt?"展开":"收起"} ${W.name} 的成员会话`,"aria-expanded":!Pt,"aria-controls":H,title:`${Pt?"展开":"收起"}成员会话`,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:Qe=>{Qe.stopPropagation(),Dn(yt)},children:s.jsx(Ys,{size:14,className:Pt?"":"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:`打开 ${W.name} 的协作工作区`,"aria-label":`打开协作工作区:${W.name}`,"aria-current":Se===W.id?"page":void 0,onClick:Qe=>{Qe.stopPropagation(),$r(W.id)},children:[s.jsx(Up,{size:14,className:"shrink-0 text-primary"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:W.name}),K.some(Qe=>Qe.groupId===W.id)&&s.jsxs("span",{className:"shrink-0 text-[10px] font-normal text-primary",children:[K.filter(Qe=>Qe.groupId===W.id).length," 待处理"]})]}),s.jsx("button",{type:"button","aria-label":`成员与消息:${W.name}`,title:"在终端旁打开成员与消息",disabled:Ge!==null||!c&&!Ie.length,"aria-busy":Ge===W.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:Qe=>{Qe.stopPropagation(),yr(W.id,Ie[0]?.id)},children:Ge===W.id?s.jsx(wn,{size:14,className:"animate-spin"}):s.jsx(ud,{size:14})})]}),s.jsx("div",{id:H,children:!Pt&&s.jsxs(s.Fragment,{children:[U.length>0&&s.jsxs("button",{type:"button","aria-expanded":X,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:()=>tr(Qe=>({...Qe,[W.id]:!X})),children:[s.jsx(Ys,{size:12,className:X?"rotate-90":""}),"已完成的执行会话 · ",U.length]}),s.jsx(Ol,{droppableId:`collaboration-members:${W.id}`,type:"collaboration-member",direction:"vertical",isCombineEnabled:!0,children:(Qe,ar)=>s.jsxs("div",{ref:Qe.innerRef,...Qe.droppableProps,"data-collaboration-members":!0,className:`${ar.isDraggingOver?"rounded-sm bg-primary/10":""}`,children:[Ee.map(sr=>s.jsx("div",{"data-collaboration-split":sr.workspace?.id,"data-split-anchor":sr.workspace?.sessionIds[0],role:sr.workspace?"region":void 0,"aria-label":sr.workspace?`${Te("tab.splitWorkspace")} · ${sr.sessionIds.length}`:void 0,className:sr.workspace&&!ht?`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 ${sr.sessionIds.includes(c??"")?"bg-primary/[0.07]":"bg-surface/35"}`:void 0,children:sr.sessionIds.map(It=>{const _r=Fr.get(It);return _r?s.jsx(Pl,{draggableId:`collaboration-member:${_r.id}`,index:Ve.indexOf(_r.id),disableInteractiveElementBlocking:!0,children:(on,bn)=>s.jsxs("div",{ref:on.innerRef,...on.draggableProps,"data-collaboration-member":_r.id,"data-split-member":en.has(_r.id)?"true":void 0,...B?Hn(()=>B(_r.id)):{},className:`${sr.workspace&&It===sr.sessionIds[0]&&se===sr.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 ${bn.combineTargetFor?"bg-primary/15 ring-1 ring-primary/40 ":bn.isDragging?"bg-surface-elevated opacity-90 shadow-lg ":""}${ss(_r.id)??(_r.id===c?"bg-surface-elevated/80 text-foreground":en.has(_r.id)?"bg-primary/[0.05] text-muted-foreground hover:bg-primary/[0.09]":"text-muted-foreground hover:bg-surface-2")}`,children:[Xn(_r,on.dragHandleProps,!0,sr.workspace&&It===sr.sessionIds[0]?Bs(sr.workspace):void 0,R.has(It)?s.jsxs("button",{type:"button","aria-label":`归档 ${_r.name}`,title:"保存 Agent 会话 ID 并停止终端;只回收干净的执行目录,结果和分支保留",disabled:Dr!==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:Jr=>{Jr.stopPropagation(),!St.current&&(St.current=!0,Ce(It),Et(null),_9(It).then(async()=>{$e(mn=>mn+1),await an()}).catch(mn=>Et(mn instanceof Error?mn.message:"归档失败,终端已保留")).finally(()=>{St.current=!1,Ce(null)}))},children:[Dr===It?s.jsx(wn,{size:13,className:"animate-spin"}):s.jsx(Af,{size:13}),s.jsx("span",{className:"text-[10px] md:sr-only",children:"归档"})]}):void 0),!sr.workspace&&en.has(_r.id)&&s.jsx("button",{type:"button",className:"shrink-0 px-1 text-[10px] text-primary",title:`与 ${v.find(Jr=>Jr.sessionIds.includes(_r.id))?.sessionIds.filter(Jr=>Jr!==_r.id).map(Jr=>Fr.get(Jr)?.name??Jr).join("、")} 分屏`,"aria-label":`查看 ${_r.name} 的跨组分屏`,onClick:()=>{me(!1),Pi.getState().terminal(),window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:_r.id})),zr()},children:s.jsx(Fl,{size:10})})]})},_r.id):null})},sr.workspace?.id??sr.sessionIds[0])),Qe.placeholder]})}),s.jsx(_Q,{groupId:W.id,version:rr,onRestore:async Qe=>{me(!1),window.dispatchEvent(new CustomEvent("new-terminal-session",{detail:{mode:"tmux",cwd:Qe.cwd,preferredFrontendSessionId:Qe.sessionId,requireExisting:!0}})),await an(),Pi.getState().terminal(),zr()}}),W.remoteSessions?.map(Qe=>{const ar=k9(Qe),sr=ar==="connected",It=ar==="unknown"?"连接状态未知":"连接已断开";return s.jsxs("button",{type:"button",title:`${bc(Qe)} · ${sr?"服务已连接":It}`,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:()=>{me(!1),G6(Qe.sessionId).catch(()=>{$r(W.id)})},children:[s.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${sr?"bg-primary":"bg-muted-foreground"}`}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:Qe.name}),s.jsx("span",{className:"max-w-20 truncate rounded border border-border/20 px-1 text-[9px]",children:bc(Qe)}),!sr&&s.jsx("span",{className:"shrink-0 text-[9px]",children:It})]},Qe.sessionId)})]})}),s.jsx("div",{"data-collaboration-background":!0,className:Pt?"absolute inset-0 pointer-events-none":"h-1.5"})]})},es=(W,Ie,Ye)=>s.jsx(Vu,{onBeforeCapture:Xr,onDragStart:is,onDragEnd:nt=>Rr(st=>Bn(st,W,Ye),nt),children:s.jsx(Ol,{droppableId:Ie,direction:"vertical",isCombineEnabled:!ur,children:nt=>s.jsxs("div",{ref:nt.innerRef,...nt.droppableProps,"data-sidebar-entity-list-id":Ie,className:"flex-1 space-y-0.5",children:[W.map((st,yt)=>s.jsx(Pl,{draggableId:st.id,index:yt,disableInteractiveElementBlocking:!0,children:(Pt,H)=>s.jsxs("div",{ref:Pt.innerRef,...Pt.draggableProps,"data-sidebar-gesture-ignore":!0,"data-sidebar-entity-index":yt,className:"relative",children:[us(yt),yt===W.length-1&&us(W.length,"bottom"),st.kind==="workspace"?Qr(st.workspace,st.members,H.isDragging,!!H.combineTargetFor,Pt.dragHandleProps):st.kind==="collaboration"?Jn(st.group,st.members,Pt.dragHandleProps,H.isDragging,!!H.combineTargetFor):s.jsx("div",{...B?Hn(()=>B(st.session.id)):{},className:`group relative flex items-center gap-1 rounded-md pr-1 transition-colors ${H.combineTargetFor?"bg-primary/15 text-foreground ring-1 ring-primary/40":H.isDragging?"bg-surface-elevated text-foreground opacity-90 shadow-lg":ss(st.session.id)??(!Se&&st.session.id===c?"bg-surface-elevated text-foreground":"text-muted-foreground hover:bg-surface-2")} cursor-grab active:cursor-grabbing`,children:Xn(st.session,Pt.dragHandleProps)})]})},st.id)),nt.placeholder]})})}),oi=s.jsxs("div",{className:"relative flex min-h-0 flex-1 flex-col",children:[s.jsx(UO,{label:Te("sidebar.sessions"),count:a.length,badge:pn>0?s.jsx(l4,{count:pn,tone:"running",title:Te("agent.aiRunning")}):null,pinned:!!Xe,onClose:r,onTogglePinned:q?()=>{me(!1),q()}:void 0,serverAttention:Zt,onOpenSettings:()=>{me(!1),F()},actions:[...P?[{label:Te("sidebar.subscriptionQuota"),icon:oT,onSelect:()=>{me(!1),P()}}]:[],{label:"Agent 工作台",icon:Up,onSelect:()=>{me(!1),$r(null)}},{label:"服务与设备",icon:T9,onSelect:()=>{me(!1),S9()}},{label:Te("sidebar.settings"),icon:f3,onSelect:()=>{me(!1),F()}}]}),ot&&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:ot}),s.jsx("button",{type:"button","aria-label":"关闭协作错误提示",className:"shrink-0",onClick:()=>Et(null),children:s.jsx(Mn,{size:14})})]}),s.jsxs("div",{ref:un,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:[K.length>0&&s.jsxs("section",{className:"mb-2 rounded-lg border border-primary/20 bg-primary/5","aria-label":"协作待处理事项",children:[K.length>0&&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":Ct,onClick:()=>or(W=>!W),children:[s.jsx(Up,{size:14}),s.jsx("span",{className:"min-w-0 flex-1",children:"需要你处理"}),s.jsx("span",{children:K.length}),s.jsx(Ys,{size:12,className:Ct?"rotate-90":""})]}),(Ct||K.length===0)&&s.jsxs("div",{className:"space-y-1 p-1 pt-0",children:[ct&&s.jsxs("p",{role:"alert",className:"px-2 py-2 text-[11px] text-destructive",children:[ct,s.jsx("button",{type:"button",className:"ml-2 text-primary",onClick:()=>{Ou.getState().refresh()},children:"重试"})]}),K.map(W=>s.jsxs("button",{type:"button",className:"min-h-11 w-full rounded-md px-2 py-2 text-left hover:bg-surface-2",onClick:()=>{cb(W.groupId,W.id),$r(W.groupId).then(Ie=>{Ie&&cb(W.groupId,W.id)})},children:[s.jsx("span",{className:"block truncate text-xs text-foreground",children:W.title}),s.jsxs("span",{className:"mt-1 block truncate text-[10px] text-muted-foreground",children:[Tt.find(Ie=>Ie.id===W.groupId)?.name??"协作组"," · ",ou(W)]})]},W.id))]})]}),s.jsx(RF,{sessions:ve,loading:qe,attachingName:xe,onRefresh:ce,onRestore:nr,onClose:ye}),gr.length>0&&s.jsxs("section",{className:"mb-1","aria-label":"已归档协作组",children:[s.jsxs("button",{type:"button",className:"flex min-h-10 w-full items-center gap-2 rounded-md px-2 text-left text-[11px] text-muted-foreground hover:bg-surface-2","aria-expanded":Cr,onClick:()=>Ir(W=>!W),children:[s.jsx(Af,{size:13}),s.jsx("span",{className:"flex-1",children:"已归档协作组"}),s.jsx("span",{children:gr.length}),s.jsx(Ys,{size:12,className:Cr?"rotate-90":""})]}),Cr&&s.jsx("div",{className:"space-y-1",children:gr.map(W=>s.jsx(Vu,{onDragEnd:()=>{},children:Jn(W,W.sessionIds.flatMap(Ie=>Fr.get(Ie)??[]))},W.id))})]}),Kr.filter(W=>!W.sessionIds.length).map(W=>s.jsx(Vu,{onDragEnd:()=>{},children:Jn(W,[])},W.id)),a.length===0?s.jsxs("div",{className:"rounded-xl bg-surface-2/60 px-4 py-8 text-center",children:[s.jsx(Zo,{size:26,className:"mx-auto mb-2 text-muted-foreground"}),s.jsx("p",{className:"text-[12px] text-muted-foreground",children:Te("sidebar.noSessions")})]}):zn.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:Te("sidebar.noMatchingSessions")})}):wr?s.jsx("div",{className:"flex flex-1 flex-col",children:s.jsx(Vu,{onBeforeCapture:Xr,onDragStart:is,onDragEnd:W=>Rr(vs,W),children:s.jsx(Ol,{droppableId:"sidebar-groups",type:"group",direction:"vertical",children:W=>s.jsxs("div",{ref:W.innerRef,...W.droppableProps,className:"flex flex-1 flex-col space-y-1.5",children:[fn.map((Ie,Ye)=>{const nt=Tn.has(Ie.key),st=!nt&&Ye===fn.length-1,yt=n0(Ie.sessions,v,Fr,Kr);let Pt=0,H=0;for(const R of Ie.sessions){const U=l.get(R.id);U?.agentStatus==="working"&&(Pt+=1),(U?.agentStatus==="waiting"||U?.agentNeedsReview)&&(H+=1)}const ue=Ie.key==="";return s.jsx(Pl,{draggableId:`sidebar-group:${Ie.key||"__ungrouped__"}`,index:Ye,isDragDisabled:ue,disableInteractiveElementBlocking:!0,children:(R,U)=>s.jsxs("div",{ref:R.innerRef,...R.draggableProps,className:`shrink-0 rounded-md transition-colors ${st?"flex flex-1 flex-col ":""}${U.isDragging?"bg-surface-elevated shadow-lg opacity-90":""}`,children:[s.jsxs("button",{type:"button",...ue?{}:R.dragHandleProps,onClick:()=>{Dn(Ie.key),Wr.current.delete(Ie.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 ${ue?"":"cursor-grab active:cursor-grabbing"}`,title:Ie.key||Ie.label,children:[s.jsx(Ys,{size:13,className:`shrink-0 transition-transform ${nt?"":"rotate-90"}`}),s.jsx("span",{className:"min-w-0 flex-1 truncate text-[11.5px] font-semibold uppercase tracking-wide",children:Ie.label}),Pt>0&&s.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--success)] animate-pulse"}),H>0&&s.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--warning)] animate-pulse"}),s.jsx(db,{sessionIds:Ie.sessions.map(X=>X.id)}),s.jsx("span",{className:"shrink-0 text-[10.5px] text-muted-foreground/70",children:Ie.sessions.length})]}),!nt&&s.jsx("div",{className:`mt-0.5 pl-2 ${st?"flex flex-1 flex-col":""}`,children:s.jsx(Ol,{droppableId:`group-sessions:${Ie.key}`,type:"session",direction:"vertical",isCombineEnabled:!ur,children:X=>s.jsxs("div",{ref:X.innerRef,...X.droppableProps,"data-sidebar-entity-list-id":`group-sessions:${Ie.key}`,className:`${st?"flex-1 ":""}space-y-0.5`,children:[yt.map((be,Ee)=>s.jsx(Pl,{draggableId:be.id,index:Ee,disableInteractiveElementBlocking:!0,children:(Ve,ht)=>s.jsxs("div",{ref:Ve.innerRef,...Ve.draggableProps,"data-sidebar-gesture-ignore":!0,"data-sidebar-entity-index":Ee,className:"relative",children:[us(Ee),Ee===yt.length-1&&us(yt.length,"bottom"),be.kind==="workspace"?Qr(be.workspace,be.members,ht.isDragging,!!ht.combineTargetFor,Ve.dragHandleProps):be.kind==="collaboration"?Jn(be.group,be.members,Ve.dragHandleProps,ht.isDragging,!!ht.combineTargetFor):s.jsx("div",{...B?Hn(()=>B(be.session.id)):{},className:`group relative flex items-center gap-1 rounded-md pr-1 transition-colors ${ht.combineTargetFor?"bg-primary/15 text-foreground ring-1 ring-primary/40":ht.isDragging?"bg-surface-elevated text-foreground opacity-90 shadow-lg":ss(be.session.id)??(!Se&&be.session.id===c?"bg-surface-elevated text-foreground":"text-muted-foreground hover:bg-surface-2")} cursor-grab active:cursor-grabbing`,children:Xn(be.session,Ve.dragHandleProps)})]})},be.id)),X.placeholder]})})})]})},Ie.key||"__ungrouped__")}),W.placeholder]})})})}):es(cr,"sidebar-entities")]}),s.jsx(C9,{onReselect:()=>{d&&(Cn.current=null,Fe(W=>W+1),d())}}),_e&&s.jsx(FO,{directories:a.flatMap(W=>{const Ie=l.get(W.id)?.cwd;return Ie?[Ie]:[]}),tmuxAvailable:pe,options:we,launchPending:Je,launchError:ae?Te(l1(ae)):null,agents:bt,selectedAgent:it,detecting:An,resumeHistory:Yt,resumeHistoryLoading:Nt,resumeHistoryPendingId:Mt,resumeHistoryError:Bt,onRefreshAgents:()=>{xn().catch(()=>{})},onSelectAgent:W=>{rn(W).catch(()=>{})},onLaunchAgent:Or,onResumeHistory:W=>{kr(W)},onRemoveResumeHistory:W=>{Zn(W)},onClose:()=>me(!1),onOptionsChange:wt,additionalContent:mt&&$?.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(wn,{size:13,className:$.status==="checking"||$.status==="installing"||$.status==="restarting"?"animate-spin":""})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block font-semibold",children:Te("sidebar.updateAvailable",{version:$.latestVersion})}),s.jsx("span",{className:"mt-0.5 block text-[10.5px] leading-relaxed text-muted-foreground",children:$.status==="checking"?Te("settings.updateChecking"):$.status==="installing"?Te("sidebar.updateInstalling"):$.status==="ready"?Te("sidebar.updateReady"):$.status==="restarting"?Te("sidebar.updateRestarting"):$.error||Te("sidebar.updateFailed")})]})]}),$.status==="ready"&&Z&&s.jsx("button",{type:"button",disabled:ee,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:Te("sidebar.updateRestart")}),$.status==="error"&&V&&s.jsx("button",{type:"button",disabled:ee,onClick:V,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:Te("sidebar.updateRetry")})]})}),dt&&s.jsx(Xb,{onEnterGroup:async W=>{if(!await $r(W))throw new Error("协作组已保存,打开工作区失败,请重试");ft(!1)},onFloatingChange:async W=>{if(W){if(!await $r(W))throw new Error("打开协作工作区失败");ft(!1)}},activeSessionId:c,defaultSessionMode:J,onClose:()=>ft(!1),onNewSession:W=>f(W)}),Object.entries(We).map(([W,Ie])=>s.jsx(Xb,{activeSessionId:c,initialCollaborationGroupId:W,initialFloating:Ie,visible:!Se,onEnterGroup:async Ye=>{if(Ye===W){await $r(Ye);return}if(!await $r(Ye))throw new Error("协作组已保存,打开工作区失败,请重试");await Ya({floatingGroupId:null},W),Le(nt=>{const st={...nt};return delete st[W],st})},onFloatingChange:Ye=>vt(W,Ye),defaultSessionMode:J,onClose:()=>{ie.current=!0,Le(Ye=>{const nt={...Ye};return delete nt[W],nt})},onNewSession:Ye=>f(Ye)},W)),!_e&&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:[ae&&s.jsx("p",{role:"alert",className:"mb-2 text-[11px] leading-relaxed text-destructive",children:Te(l1(ae))}),s.jsxs("div",{className:`grid gap-1.5 [&>button]:min-h-11 [&>button]:shadow-none [&>button]:ring-0 md:[&>button]:min-h-0 ${it?"grid-cols-[minmax(0,1fr)_minmax(0,1fr)_2.5rem]":"grid-cols-[minmax(0,1fr)_2.5rem]"}`,children:[s.jsxs("button",{type:"button",onClick:Qt,disabled:Je,"aria-busy":Je,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] ${it?"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:Te("sidebar.newSession"),"aria-label":Te("sidebar.newSession"),children:[s.jsx(Zo,{size:15,className:"shrink-0"}),s.jsx("span",{className:"truncate",children:Je?Te("sidebar.sessionCreating"):"Terminal"})]}),it&&s.jsxs("button",{type:"button",onClick:er,disabled:Je,"aria-busy":Je,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:Te("sidebar.newSessionWithAgent",{agent:it.displayName}),"aria-label":Te("sidebar.newSessionWithAgent",{agent:it.displayName}),children:[s.jsx(Jc,{agent:it,size:15}),s.jsx("span",{className:"truncate",children:it.displayName})]}),s.jsxs("button",{type:"button",onClick:ys,disabled:Je,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:$t,"aria-label":$t,"aria-expanded":_e,"aria-controls":"sidebar-launch-options",children:[s.jsx(Io,{size:15}),mt&&s.jsx("span",{className:"absolute right-0.5 top-0.5 h-2 w-2 rounded-full bg-[var(--warning)] ring-2 ring-[var(--chrome-bg)]","aria-hidden":"true"})]})]})]})]});return Xe?s.jsx("div",{"data-session-sidebar-pinned":!0,className:"h-full flex flex-col app-chrome-bg border-r border-border",children:oi}):s.jsx(i4,{side:"left",isOpen:e,drawerWidthPx:t,onClose:r,onOpen:n,push:Re,children:oi})}function BF(e,t,r,n,a){let c=t,l=null,d=!1;const f=e.style.width,m=document.body.style.cursor,x=document.body.style.userSelect,y=()=>n(r+c-t),w=()=>{l=null,e.style.width=`${y()}px`},v=N=>{c=N.clientX,l===null&&(l=requestAnimationFrame(w))},T=N=>{d||(d=!0,window.removeEventListener("mousemove",v),window.removeEventListener("mouseup",S),window.removeEventListener("blur",I),l!==null&&cancelAnimationFrame(l),l=null,document.body.style.cursor=m,document.body.style.userSelect=x,N?(w(),y()!==r&&a(y())):e.style.width=f)},S=N=>{c=N.clientX,T(!0)},I=()=>T(!0);return document.body.style.cursor="col-resize",document.body.style.userSelect="none",window.addEventListener("mousemove",v),window.addEventListener("mouseup",S),window.addEventListener("blur",I),()=>T(!1)}function QF(){const{t:e}=Hr();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 PF({slow:e=!1}){const{t}=Hr();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 A4=()=>Vc(()=>import("./RightSidebar-DvYmab8z.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})),OF=b.lazy(A4);function ly(e){const t=b.useRef(!1);b.useEffect(()=>{const f=navigator.connection;if(!(f?.saveData||/2g|3g/.test(f?.effectiveType??"")))return ug(()=>{A4().catch(()=>{})},3e3)},[]);const{t:r}=Hr(),n=Vt(f=>f.rootPath),a=Vt(f=>f.rightTab),c=Vt(f=>f.setRightTab),l=n?.replace(/\/+$/,"").split("/").pop()||r("rightSidebar.workspace");(e.isOpen||e.pinned)&&(t.current=!0);const d=s.jsx(i4,{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:[Wl,AS,Io].map((f,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(f,{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(Mn,{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",$A,"rightSidebar.tabGit"],["diff",zA,"rightSidebar.tabChanges"],["files",tu,"rightSidebar.tabFiles"],["architecture",oS,"architecture.tab"],["computer",I9,"rightSidebar.tabComputer"]].map(([f,m,x])=>s.jsxs("button",{type:"button",onClick:()=>c(f),className:`flex items-center justify-center gap-1 rounded px-2 py-1.5 text-[11px] font-medium ${a===f?"bg-surface-elevated text-foreground":"text-muted-foreground"}`,children:[s.jsx(m,{size:12}),r(x)]},f))}),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(PF,{}):s.jsx(QF,{})})]})});return t.current?s.jsx(b.Suspense,{fallback:d,children:s.jsx(OF,{...e})}):d}const cy=vc(e=>({overlay:"off",setOverlay:t=>e({overlay:t})}));function FF(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 $F=vc((e,t)=>({sessions:new Map,activeSessionId:null,nextSessionNumber:1,createSession:r=>{const n=L3(),a=Date.now(),c=t().sessions,l=FF(c),d={id:n,cwd:r,sessionId:null,name:l,customName:!1,createdAt:a,lastActivity:a};return e(f=>{const m=new Map(f.sessions);return m.set(n,d),{sessions:m,activeSessionId:f.activeSessionId??n,nextSessionNumber:f.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})}})),UF=[7e5,1e6,14e5,18e5,24e5,32e5,4e6,5e6,6e6,8e6,1e7,12e6].map(e=>({id:"auto",maxSize:1600,bitRate:e,maxFps:30}));class zF{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 UF[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 f=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<f)this.level++,this.lastUpgrade=r;else return null;return this.lastChange=r,this.badSince=this.goodSince=null,this.quality}}async function cu(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 HF(){return cu("/api/android/devices")}async function WF(e){return cu("/api/android/connect",{method:"POST",body:JSON.stringify({address:e})})}const np=[{id:"low",maxSize:720,bitRate:12e5,maxFps:30},{id:"medium",maxSize:1080,bitRate:4e6,maxFps:30},{id:"high",maxSize:1600,bitRate:8e6,maxFps:60}],H0=np[1];function X1(e){if(!e||typeof e!="object")return H0;const t=e;if(t.id==="auto")return{id:"auto",maxSize:1600,bitRate:4e6,maxFps:30};const r=np.find(l=>l.id===t.id);if(r)return r;if(t.id!=="custom")return H0;const n=typeof t.maxSize=="number"?Math.max(360,Math.min(2160,Math.round(t.maxSize))):1080,a=typeof t.bitRate=="number"?Math.max(3e5,Math.min(3e7,Math.round(t.bitRate))):4e6,c=typeof t.maxFps=="number"?Math.max(0,Math.min(60,Math.round(t.maxFps))):30;return{id:"custom",maxSize:n,bitRate:a,maxFps:c}}function GF(e,t){if(!/^[0-9a-zA-Z_.:\-]{1,128}$/.test(e))throw new Error("INVALID_SERIAL");const r=new URLSearchParams;t&&(r.set("max_size",String(t.maxSize)),r.set("bit_rate",String(t.bitRate)),t.maxFps>0&&r.set("max_fps",String(t.maxFps)));const n=r.toString();return`/api/android/${e}/ws${n?`?${n}`:""}`}function uy(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 VF(e){return cu(`/api/android/recordings?serial=${encodeURIComponent(e)}`)}function qF(e){return cu("/api/android/recordings",{method:"POST",body:JSON.stringify({serial:e})})}function YF(e){return cu(`/api/android/recordings/${encodeURIComponent(e)}/stop`,{method:"POST"})}function ZF(e,t){return cu(`/api/android/recordings/${encodeURIComponent(e)}/save`,{method:"POST",body:JSON.stringify({directory:t})})}function KF(e){return cu(`/api/android/recordings/${encodeURIComponent(e)}`,{method:"DELETE"})}const XF=0,JF=1,e$=2,t$=3,r$=4,n$=5,s$=7,i$=10,a$=11,o$=16,dy=17,hy=0,qm=1,l$=2,fy=3,Ym=0,py=1,my=1,ju=0xffffffffffffffffn,Wh=0xfffffffffffffffen,s0={HOME:3,APP_SWITCH:187,POWER:26,VOLUME_UP:24,VOLUME_DOWN:25};function T4(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 c$(e,t,r,n,a,c){const l=new Uint8Array(32),d=new DataView(l.buffer);return d.setUint8(0,e$),d.setUint8(1,e),d.setBigUint64(2,t),T4(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 Zm(e,t,r=0,n=0){const a=new Uint8Array(14),c=new DataView(a.buffer);return c.setUint8(0,XF),c.setUint8(1,e),c.setUint32(2,t>>>0),c.setUint32(6,r>>>0),c.setUint32(10,n>>>0),a}function u$(e,t,r,n=0){const a=new Uint8Array(21),c=new DataView(a.buffer);c.setUint8(0,t$),T4(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 d$(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,JF),a.setUint32(1,r.length),n.set(r,5),n}function h$(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]=o$,r[1]=t.length,r.set(t,2),r}function i0(e){return new Uint8Array([e])}function gy(e){return new Uint8Array([r$,e])}function f$(e){return new Uint8Array([i$,e?1:0])}function p$(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}function m$(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 Km(e){return e.toString(16).padStart(2,"0")}function S4(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 f=l+1;for(;f+2<e.length&&!(e[f]===0&&e[f+1]===0&&(e[f+2]===1||e[f+2]===0&&e[f+3]===1));)f++;return e.subarray(l,Math.min(e.length,f))}return null}function g$(e){const t=e?S4(e,7,!1):null;return t&&t.length>=4?`avc1.${Km(t[1])}${Km(t[2])}${Km(t[3])}`:"avc1.42e01e"}function x$(e){const t=e?S4(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 b${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=E9(GF(t,r))}catch(a){this.callbacks.onState("error",a instanceof Error?a.message:"ANDROID_STREAM_FAILED");return}this.socket=n,n.onopen=()=>{this.lastMessageAt=Date.now()},n.onmessage=a=>{this.closedByUser||this.handleMessage(a.data)},n.onerror=()=>{this.closedByUser||this.callbacks.onState("error","SCRCPY_CONNECTION_LOST")},n.onclose=()=>{this.finishBitrate(!1,"BITRATE_CONNECTION_CLOSED: preview connection closed"),this.liveBitrate=!1,this.teardownTimers(),this.closedByUser?this.callbacks.onState("idle"):this.callbacks.onState("error","SCRCPY_CONNECTION_CLOSED")},this.startTimers()}disconnect(){this.closedByUser=!0,this.finishBitrate(!1),this.liveBitrate=!1,this.teardownTimers();try{this.decoder?.close()}catch{}this.decoder=null,this.configured=!1;try{this.socket?.close()}catch{}this.socket=null,this.callbacks.onState("idle")}teardownTimers(){this.heartbeat&&clearInterval(this.heartbeat),this.statsTimer&&clearInterval(this.statsTimer),this.stallTimer&&clearInterval(this.stallTimer),this.heartbeat=null,this.statsTimer=null,this.stallTimer=null}startTimers(){this.lastSampleAt=Date.now(),this.heartbeat=setInterval(()=>{if(!(!this.socket||this.socket.readyState!==1)){if(Date.now()-this.lastMessageAt>45e3){try{this.socket.close()}catch{}return}this.pingAt===null&&(this.pingAt=performance.now(),this.send({type:"ping"}))}},this.autoQuality?2e3:15e3),this.stallTimer=setInterval(()=>{if(!this.header||this.closedByUser)return;const t=Date.now();t-this.lastFrameAt>8e3&&t-this.lastResetAt>8e3&&(this.lastResetAt=t,console.warn("[android] no frames for 8s; requesting keyframe reset"),this.sendControl(i0(dy)))},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:p$(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=m$(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(i0(dy))}})}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=[g$(this.configData),"avc1.42e01e","avc1.4d401e","avc1.64001f"].filter((l,d,f)=>f.indexOf(l)===d),r.avc={format:"annexb"}):t==="h265"?(n=[x$(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===qm||t===fy,l=c?0:1,d=a===ju&&!c?my:0,f=(t===hy||t===qm)&&a===ju?my:0;this.sendControl(c$(t,a,this.pointerPoint(r,n),l,f,d))}pointerDown(t,r,n){this.touch(hy,t,r,n==="mouse"?ju:Wh)}pointerMove(t,r,n){this.touch(l$,t,r,n==="mouse"?ju:Wh)}pointerUp(t,r,n){this.touch(qm,t,r,n==="mouse"?ju:Wh)}pointerCancel(t,r,n){this.touch(fy,t,r,n==="mouse"?ju:Wh)}scroll(t,r,n,a){this.sendControl(u$(this.pointerPoint(t,r),n,a))}key(t,r=Ym){this.sendControl(Zm(r,t))}tapKey(t){this.sendControl(Zm(Ym,t)),this.sendControl(Zm(py,t))}back(){this.sendControl(gy(Ym)),this.sendControl(gy(py))}home(){this.tapKey(s0.HOME)}recents(){this.tapKey(s0.APP_SWITCH)}power(){this.tapKey(s0.POWER)}volumeUp(){this.tapKey(s0.VOLUME_UP)}volumeDown(){this.tapKey(s0.VOLUME_DOWN)}rotate(){this.sendControl(i0(a$))}expandNotifications(){this.sendControl(i0(n$))}collapsePanels(){this.sendControl(i0(s$))}setDisplayPower(t){this.sendControl(f$(t))}sendText(t){this.sendControl(d$(t))}startApp(t){this.sendControl(h$(t))}}function y$(){try{return crypto.randomUUID().slice(0,8)}catch{return Math.random().toString(36).slice(2,10)}}function v$(){return`termdock-mirror-shot-${new Date().toISOString().replace(/[-:T]/g,"").slice(0,14)}-${y$()}.png`}function xy(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 w$(e,t=v$()){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 C4(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 by(e,t,r,n,a){const c=Math.max(1,Math.min(8,e.zoom*a)),l=c/e.zoom;return{zoom:c,pan:C4({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 _4(e,t){return t?new Promise((r,n)=>{const a=crypto.randomUUID(),c=f=>{window.clearTimeout(d),window.removeEventListener("termdock-insert-reference-ack",l),f?r():n(new Error("目标终端不可用,内容尚未插入,请连接终端后重试"))},l=f=>{const m=f.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 yy(e,t){return _4(L1(e,null),t)}const Xm=vc(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 A$({file:e,initialPath:t,onInsert:r,onDone:n}){const{t:a}=Hr(),[c,l]=b.useState(!1),[d,f]=b.useState(!1),[m,x]=b.useState(!1),[y,w]=b.useState(!1),[v,T]=b.useState(null),S=b.useRef(!1),I=b.useRef(null),N=async()=>{if(!S.current){S.current=!0,f(!0),w(!0);try{await KF(e.id),n()}catch(F){T(F instanceof Error?F.message:String(F))}finally{S.current=!1,f(!1),w(!1)}}};b.useEffect(()=>{if(c)return;I.current?.focus();const F=P=>{if(P.stopPropagation(),P.key==="Escape"&&P.preventDefault(),P.key!=="Tab")return;const $=Array.from(I.current?.querySelectorAll("button:not(:disabled)")??[]),ee=$[0],Z=$.at(-1);P.shiftKey&&(document.activeElement===ee||document.activeElement===I.current)?(P.preventDefault(),Z?.focus()):!P.shiftKey&&document.activeElement===Z&&(P.preventDefault(),ee?.focus())};return document.addEventListener("keydown",F,!0),()=>document.removeEventListener("keydown",F,!0)},[c]);const B=async F=>{if(!S.current){S.current=!0,f(!0),x(F!==void 0),l(!1),T(null);try{const P=await ZF(e.id,F);F===void 0&&await r(P.path),n()}catch(P){T(P instanceof Error?P.message:String(P))}finally{S.current=!1,f(!1)}}};return c?s.jsx(yp,{open:!0,initialPath:t||"/",title:a("android.recordingSave"),onCancel:()=>l(!1),onConfirm:F=>{B(F)}}):Ks.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:I,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(jn,{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:()=>{N()},className:"min-h-10 rounded-lg px-3 text-sm text-muted-foreground disabled:opacity-40",children:a("android.recordingDiscard")})]})]})}),document.body)}const g0="android-mirror",a0=g0,k4="termdock:android:quality:v1",Jm=176,T$=204,Ql=1,vf=8,vy=[1,1.25,1.5,2,2.5,3,4,6,8],S$=e=>Math.max(Ql,Math.min(vf,e));function C$(e){return`${Number.isInteger(e)?e:e.toFixed(1)}×`}function Gh(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 _$(e,t){try{e.setPointerCapture?.(t)}catch{}}function wy(e,t){try{e.releasePointerCapture?.(t)}catch{}}const Ay=e=>typeof requestAnimationFrame=="function"?requestAnimationFrame(e):window.setTimeout(e,16),Vh=e=>{typeof cancelAnimationFrame=="function"?cancelAnimationFrame(e):window.clearTimeout(e)},e1={auto:"android.qualityAuto",low:"android.qualityLow",medium:"android.qualityMedium",high:"android.qualityHigh",custom:"android.qualityCustom"},k$=()=>{try{const e=localStorage.getItem(k4);return e?X1(JSON.parse(e)):H0}catch{return H0}},o0=e=>{try{localStorage.setItem(k4,JSON.stringify(e))}catch{}};function L$({sessionId:e,dockOnly:t=!1,onInsertPrompt:r,onInsertFile:n,onRecordingComplete:a,onCloseTab:c}){const{t:l}=Hr(),d=cy(H=>H.overlay),f=cy(H=>H.setOverlay),m=b.useRef(null),x=b.useRef(null),y=b.useRef(null),w=b.useMemo(k$,[]),v=b.useRef(w),T=b.useRef(null),S=b.useRef(null),[I,N]=b.useState(4e6),B=b.useRef(null),F=b.useRef(new Map),P=b.useRef(null),$=b.useRef(!1),[ee,Z]=b.useState(Ql),V=b.useRef(ee),de=b.useRef({x:0,y:0}),pe=b.useRef(null),J=b.useRef(0),Re=b.useRef(0),Xe=b.useRef(null),q=b.useRef(0),[ve,qe]=b.useState(null),[ce,ye]=b.useState(null),[Te,Fe]=b.useState(!0),[se,De]=b.useState(""),[_e,Me]=b.useState(w.id),[Je,Ne]=b.useState([]),[ae,ze]=b.useState(null),[at,ut]=b.useState(""),[me,dt]=b.useState(!0),[ft,Se]=b.useState({maxSize:w.maxSize,bitRate:w.bitRate,maxFps:w.maxFps}),[We,Le]=b.useState("idle"),[z,ie]=b.useState(null),[ge,Ge]=b.useState(null),[rt,vt]=b.useState({fps:0,kbps:0,width:0,height:0,received:0,decoded:0,controls:0,last:""}),[Yt,Ut]=b.useState(null),[Nt,ir]=b.useState(null),[Mt,Xt]=b.useState(!1),[Bt,Wt]=b.useState([]),[xe,et]=b.useState(null),[ot,Et]=b.useState([]),[K,xt]=b.useState(!1),rr=b.useRef(null),$e=b.useRef(0),Dr=b.useRef([]),[Ce,St]=b.useState(!1),[Ot,tr]=b.useState(""),[ct,Ct]=b.useState(!1),[or,Cr]=b.useState(!1),[Ir,$r]=b.useState(""),[Tt,Ft]=b.useState(null),[we,wt]=b.useState(null),[it,bt]=b.useState(!1),[An,xn]=b.useState(0),rn=b.useRef(null),[Oe,_t]=b.useState(!1),mt=b.useRef(!1),Zt=b.useRef(new Set),$t=b.useRef(null),wr=b.useRef(null),Tn=b.useRef(!1),[Dn,yn]=b.useState(!1),un=b.useRef(a);un.current=a;const[Cn,Ur]=b.useState(!1),[ne,Ze]=b.useState(null),Dt=b.useRef(null),ur=b.useRef(null),Pr=$F(H=>H.activeSessionId??H.sessions.keys().next().value??null),qr=e??Pr,sn=ns(H=>!!H.docks[a0]),Nr=ns(H=>H.hosts[a0]),Wr=ns(H=>H.setDock),_n=b.useCallback(async()=>{Fe(!0);try{const H=await HF();qe(H),ye(null)}catch(H){ye(H instanceof Error?H.message:"ADB_UNAVAILABLE")}finally{Fe(!1)}},[]);b.useEffect(()=>{_n()},[_n]);const en=ve?.devices??[],Fr=en.find(H=>H.serial===se)??null,Kr=!!(ce&&/ADB_NOT_FOUND|ADB_UNAVAILABLE/i.test(ce)),gr=!!(ve?.adbAvailable&&!ve.scrcpyVersion),an=b.useCallback(()=>{const H=B.current,ue=[...F.current.keys()];B.current=null,F.current.clear(),P.current=null,$.current=!1,rr.current=null,Vh(J.current),J.current=0,H&&x.current?.pointerCancel(H.x,H.y,H.type);const R=m.current;if(R)for(const U of ue)wy(R,U);et(null),xt(!1),Et([]),Z(V.current)},[]);b.useEffect(()=>{const H=U=>{F.current.has(U.pointerId)&&(U.type==="pointercancel"||U.target!==m.current)&&an()},ue=()=>an(),R=()=>{document.hidden&&an()};return window.addEventListener("pointerup",H,!0),window.addEventListener("pointercancel",H,!0),window.addEventListener("blur",ue),document.addEventListener("visibilitychange",R),()=>{window.removeEventListener("pointerup",H,!0),window.removeEventListener("pointercancel",H,!0),window.removeEventListener("blur",ue),document.removeEventListener("visibilitychange",R),an()}},[an]);const Xr=b.useCallback(()=>{an(),x.current?.disconnect(),x.current=null,Le("idle"),ie(null),Ge(null)},[an]),dn=b.useCallback((H,ue=!1)=>{const R=m.current;if(!R||!H)return;an(),x.current?.disconnect(),ie(null),!ue&&y.current!==H&&Ge(null),y.current=H,ir(null),Ut(null);const U=new b$(R,{onBitrateSupport:(be,Ee)=>{x.current!==U||v.current.id!=="auto"||Ut(be?null:Ee??"BITRATE_REASON_UNAVAILABLE")},onState:(be,Ee)=>{x.current===U&&(Le(be),ie(Ee??null))},onHeader:be=>{x.current===U&&Ge(be)},onStats:be=>{x.current===U&&vt(be)},onWarning:be=>{x.current===U&&ir(be)}});x.current=U;let X=v.current;X.id==="auto"?(T.current?.serial!==H&&(T.current={serial:H,policy:new zF}),T.current.policy.connected(performance.now()),X=T.current.policy.quality,N(X.bitRate)):T.current=null,S.current=X,U.connect(H,X)},[an]);b.useEffect(()=>{if(_e!=="auto"||v.current.id!=="auto"||We!=="streaming"||!rt.adaptation||document.hidden)return;const H=T.current,ue=x.current;if(!H||H.serial!==se||!ue?.canSetBitrate)return;const R=m.current,U=R?Math.max(R.clientWidth,R.clientHeight)*(window.devicePixelRatio||1)*V.current:1600,X=H.policy.sample(rt.adaptation,performance.now(),U||1600);X&&ue.setBitrate(X.bitRate).then(be=>{be&&x.current===ue&&(S.current=X,N(X.bitRate))})},[rt,_e,We,se,dn]);const Rr=b.useCallback(H=>{const ue={...H.quality?{quality:{id:H.quality.id,maxSize:H.quality.maxSize,bitRate:H.quality.bitRate,maxFps:H.quality.maxFps}}:{},...H.activePresetId!==void 0?{activePresetId:H.activePresetId}:{},...H.presets!==void 0?{presets:H.presets}:{},...H.docked!==void 0?{docked:H.docked}:{},...H.deviceSerial!==void 0?{deviceSerial:H.deviceSerial}:{}};ja({androidPanel:ue}).catch(()=>{})},[]);b.useEffect(()=>{let H=!1;return wc().then(ue=>{if(H)return;const R=ue.androidPanel;if(R?.quality){const U=X1(R.quality);v.current=U,Me(U.id),Se({maxSize:U.maxSize,bitRate:U.bitRate,maxFps:U.maxFps}),o0(U)}Ne(R?.presets??[]),ze(R?.activePresetId??null),R?.deviceSerial&&(Xe.current=R.deviceSerial,De(R.deviceSerial))}).catch(()=>{}),()=>{H=!0}},[]);const zn=b.useCallback(H=>{const ue=++$e.current;Wt(U=>[...U,{id:ue,left:H.left,top:H.top}]);const R=window.setTimeout(()=>{Wt(U=>U.filter(X=>X.id!==ue)),Dr.current=Dr.current.filter(U=>U!==R)},300);Dr.current.push(R)},[]),pn=b.useCallback((H,ue)=>{const R=x.current,U=S.current;R?.supportsLiveBitrate&&y.current===H&&U&&U.maxSize===ue.maxSize&&U.maxFps===ue.maxFps?R.setBitrate(ue.bitRate).then(X=>{x.current===R&&(X?(S.current=ue,Ut(null)):Ut(R.lastBitrateFailure??"BITRATE_REASON_UNAVAILABLE"))}):dn(H)},[dn,l]),Gr=b.useCallback(H=>{if(T.current=null,H.startsWith("user:")){const R=Je.find(X=>X.id===H.slice(5));if(!R)return;const U={id:"custom",maxSize:R.maxSize,bitRate:R.bitRate,maxFps:R.maxFps};v.current=U,Me("custom"),ze(R.id),Se({maxSize:R.maxSize,bitRate:R.bitRate,maxFps:R.maxFps}),dt(!0),o0(U),Rr({quality:U,activePresetId:R.id}),se&&dn(se);return}if(H==="custom"){const R=v.current;Me("custom"),ze(null),Se({maxSize:R.maxSize,bitRate:R.bitRate,maxFps:R.maxFps}),dt(!0);return}const ue=H==="auto"?X1({id:"auto"}):np.find(R=>R.id===H)??H0;v.current=ue,Me(ue.id),ze(null),o0(ue),Rr({quality:ue,activePresetId:null}),se&&dn(se)},[dn,se,Je,Rr]),zr=b.useCallback(()=>{const H={id:"custom",maxSize:ft.maxSize,bitRate:ft.bitRate,maxFps:ft.maxFps};v.current=H,o0(H),Rr({quality:H,activePresetId:null}),Me("custom"),ze(null),se&&pn(se,H)},[pn,se,ft,Rr]),Y=b.useCallback(()=>{const H=at.trim();if(!H)return;const ue=`p${Date.now().toString(36)}${Math.random().toString(36).slice(2,6)}`,R={id:ue,name:H,maxSize:ft.maxSize,bitRate:ft.bitRate,maxFps:ft.maxFps},U=[...Je.filter(be=>be.name!==H),R].slice(-12),X={id:"custom",maxSize:ft.maxSize,bitRate:ft.bitRate,maxFps:ft.maxFps};Ne(U),ut(""),ze(ue),Me("custom"),v.current=X,o0(X),Rr({quality:X,activePresetId:ue,presets:U}),se&&pn(se,X)},[at,ft,Je,se,pn,Rr]),Be=b.useCallback(()=>{if(!ae)return;const H=Je.filter(ue=>ue.id!==ae);Ne(H),ze(null),Rr({activePresetId:null,presets:H})},[ae,Je,Rr]);b.useEffect(()=>()=>{x.current?.disconnect(),x.current=null;for(const H of Dr.current)window.clearTimeout(H);Dr.current=[]},[]),b.useEffect(()=>{if(d==="off")return;const H=ue=>{ue.key==="Escape"&&f("off")};return window.addEventListener("keydown",H),()=>window.removeEventListener("keydown",H)},[d,f]),b.useEffect(()=>{const H=en.filter(R=>R.state==="device");if(se||H.length!==1)return;const ue=H[0].serial;Xe.current!==ue&&(Xe.current=ue,De(ue))},[en,se]),b.useEffect(()=>{se&&dn(se)},[se,dn]),b.useEffect(()=>{if(We==="streaming"){q.current=0,Xt(!1);return}if(We!=="error"||!se||!E$(z??""))return;const H=Math.min(8e3,700*2**q.current);q.current+=1,Xt(!0);const ue=window.setTimeout(()=>{Xt(!1),dn(se)},H);return()=>window.clearTimeout(ue)},[We,z,se,dn]);const Qt=b.useCallback((H,ue,R)=>{const U=m.current,X=R??(U?Gh(U):null);return!U||!X?{x:0,y:0}:C4(H,ue,X)},[]),er=b.useCallback(()=>{const H=m.current;if(!H)return;const{x:ue,y:R}=de.current,U=V.current,X=U===Ql&&ue===0&&R===0?"":`translate3d(${ue}px, ${R}px, 0) scale(${U})`;H.style.transform!==X&&(H.style.transform=X);const be=pe.current;be&&(be.textContent=U>Ql?C$(U):"")},[]),nr=b.useCallback((H,ue,R=!0)=>{const U=m.current,X=V.current,be=S$(H);if(!U||be===X)return;const Ee=Gh(U);if(!Ee)return;const Ve=ue??{x:Ee.cx,y:Ee.cy},ht=by({zoom:X,pan:de.current},Ee,Ve,Ve,be/X);V.current=ht.zoom,de.current=ht.pan,R&&er()},[er]),Or=b.useCallback(()=>{const H=V.current;Z(ue=>ue<=Ql+.01==H<=Ql+.01&&ue>=vf-.01==H>=vf-.01?ue:H)},[]);b.useEffect(()=>()=>{Vh(J.current),Vh(Re.current)},[]);const kr=()=>{let H=0,ue=0;for(const U of F.current.values())H+=U.x,ue+=U.y;const R=F.current.size;return R?{x:H/R,y:ue/R}:null},Zn=()=>{const[H,ue]=Array.from(F.current.values());return H&&ue?Math.hypot(H.x-ue.x,H.y-ue.y):0},ys=()=>{const H=kr(),ue=m.current?Gh(m.current):null;!H||!ue||(P.current={startCentroid:H,startDistance:Zn(),box:ue})},ss=b.useCallback(()=>{const H=P.current,ue=kr();if(!H||!ue)return;const R=Zn(),U=H.startDistance>0&&R>0?R/H.startDistance:1,X=by({zoom:V.current,pan:de.current},H.box,H.startCentroid,ue,U);V.current=X.zoom,de.current=X.pan,H.startCentroid=ue,H.startDistance=R},[]),Hn=b.useCallback(()=>{J.current||(J.current=Ay(()=>{J.current=0,ss(),er()}))},[ss,er]),hn=b.useCallback(()=>{J.current&&(Vh(J.current),J.current=0,ss(),er())},[ss,er]);b.useEffect(()=>{const H=m.current;if(!H)return;const ue=H.parentElement;if(!ue)return;const R=X=>{if(X.ctrlKey||X.metaKey){if(X.preventDefault(),!X.deltaY||P.current)return;const Ve=X.deltaMode===1?16:X.deltaMode===2?H.parentElement?.clientHeight||600:1,ht=Math.max(-600,Math.min(600,X.deltaY*Ve));nr(V.current*Math.exp(-ht*.002),{x:X.clientX,y:X.clientY},!1),Re.current||(Re.current=Ay(()=>{Re.current=0,er(),Or()}));return}const be=x.current;if(!be||X.target!==H)return;X.preventDefault();const Ee=Yh(H,X.clientX,X.clientY);be.scroll(Ee.x,Ee.y,X.deltaX,X.deltaY)},U=X=>X.preventDefault();return ue.addEventListener("wheel",R,{passive:!1}),ue.addEventListener("gesturestart",U,{passive:!1}),ue.addEventListener("gesturechange",U,{passive:!1}),()=>{ue.removeEventListener("wheel",R),ue.removeEventListener("gesturestart",U),ue.removeEventListener("gesturechange",U)}},[nr,er,Or]),b.useEffect(()=>{const H=m.current,ue=H?.parentElement;if(!H||!ue||typeof ResizeObserver>"u")return;const R=new ResizeObserver(()=>{P.current&&(P.current.box=Gh(H));const U=Qt(de.current,V.current);U.x===de.current.x&&U.y===de.current.y||(de.current=U,er())});return R.observe(H),R.observe(ue),()=>R.disconnect()},[Qt,er]),b.useLayoutEffect(()=>{er()});const Qn=H=>{const ue=x.current,R=m.current;if(!ue||!R)return;if(H.pointerType==="mouse"&&H.button!==0){H.preventDefault(),H.button===2?ue.back():H.button===1&&ue.home();return}H.preventDefault(),R.closest(".android-mirror-panel")?.focus({preventScroll:!0}),er(),Or(),hn(),_$(R,H.pointerId),F.current.set(H.pointerId,{x:H.clientX,y:H.clientY});const U=H.pointerType==="mouse"&&H.altKey;if(F.current.size>=2||U){const Ee=B.current;Ee&&(ue.pointerCancel(Ee.x,Ee.y,Ee.type),B.current=null,rr.current=null,et(null),xt(!1),Et([])),$.current=!0,ys();return}if($.current)return;const X=Yh(R,H.clientX,H.clientY);B.current={id:H.pointerId,type:H.pointerType,x:X.x,y:X.y},ue.pointerDown(X.x,X.y,H.pointerType);const be=ky(R,H.clientX,H.clientY);be&&(rr.current={left:be.left,top:be.top},Et([]),xt(!1),et(be))},Xn=H=>{const ue=x.current,R=m.current;if(!R||!F.current.has(H.pointerId))return;if(H.pointerType==="mouse"){const Ve=R.getBoundingClientRect(),ht=R.parentElement?.getBoundingClientRect()??Ve;if(!(H.buttons&1)||H.clientX<Math.max(Ve.left,ht.left)||H.clientX>=Math.min(Ve.right,ht.right)||H.clientY<Math.max(Ve.top,ht.top)||H.clientY>=Math.min(Ve.bottom,ht.bottom)){an();return}}if(H.preventDefault(),F.current.set(H.pointerId,{x:H.clientX,y:H.clientY}),P.current){Hn();return}const U=B.current;if(!ue||!U||U.id!==H.pointerId)return;const X=Yh(R,H.clientX,H.clientY);U.x=X.x,U.y=X.y,ue.pointerMove(X.x,X.y,U.type);const be=ky(R,H.clientX,H.clientY),Ee=rr.current;!be||!Ee||(et(be),Math.hypot(be.left-Ee.left,be.top-Ee.top)>=6&&(xt(!0),Et(Ve=>{const ht=Ve[Ve.length-1];if(ht&&Math.hypot(be.left-ht.x,be.top-ht.y)<4)return Ve;const Qe=[...Ve,{x:be.left,y:be.top}];return Qe.length>12?Qe.slice(Qe.length-12):Qe})))},fn=H=>{const ue=x.current,R=m.current;if(!R||!F.current.has(H.pointerId))return;if(hn(),F.current.delete(H.pointerId),wy(R,H.pointerId),F.current.size===0&&($.current=!1),P.current){F.current.size===0?(P.current=null,Z(V.current)):ys();return}const U=B.current;if(!U||U.id!==H.pointerId)return;const X=Yh(R,H.clientX,H.clientY);ue?.pointerUp(X.x,X.y,U.type),xe&&zn(xe),et(null),xt(!1),window.setTimeout(()=>Et([]),200),B.current=null,rr.current=null},cr=H=>{if(Cn||Ce||or)return;const ue=x.current;ue&&(H.key==="Backspace"?(H.preventDefault(),ue.key(67)):H.key==="Escape"?(H.preventDefault(),ue.back()):H.key==="Enter"&&(H.preventDefault(),ue.key(66)))},is=async()=>{const H=Ot.trim();if(H){Ct(!0);try{const ue=await WF(H);tr(""),St(!1),await _n(),De(ue.serial)}catch(ue){ye(ue instanceof Error?ue.message:"ADB_CONNECT_FAILED")}finally{Ct(!1)}}},tn=()=>{const H=x.current,ue=Ir;!H||!ue||(H.sendText(ue),$r(""))},xr=b.useCallback(H=>{Ft(H),wr.current!==null&&window.clearTimeout(wr.current),wr.current=window.setTimeout(()=>{wr.current=null,Ft(null)},2500)},[]),vr=b.useCallback(H=>{const ue=V.current,R=H==="in"?vy.find(U=>U>ue+.01):[...vy].reverse().find(U=>U<ue-.01);R!==void 0&&(ue<=Ql&&R>Ql&&xr(l("android.zoomPanHint")),hn(),nr(R),Z(R))},[nr,hn,xr,l]),br=H=>{Promise.resolve().then(()=>r?.(H)).catch(ue=>{wt(ue instanceof Error?ue.message:String(ue))})},us=b.useCallback(async(H,ue)=>{try{if(!n)throw new Error(l("android.captureUnavailable"));await n(H),xr(ue)}catch(R){wt(l("android.captureFailed")+(R instanceof Error?`:${R.message}`:""))}},[n,xr,l]),Bn=async()=>{const H=m.current;if(!(!H||Tn.current)){Tn.current=!0,yn(!0),wt(null);try{const ue=await w$(H);await us(ue,l("android.captureInserted"))}catch(ue){wt(ue instanceof Error?ue.message:String(ue))}finally{Tn.current=!1,yn(!1)}}},vs=b.useCallback(H=>{(H.status==="ready"||H.status==="error")&&un.current&&!Zt.current.has(H.id)&&(Zt.current.add(H.id),un.current?.(H))},[]),Bs=b.useCallback(async H=>{const ue=rn.current;if(!(!ue||mt.current)){mt.current=!0,_t(!0),wt(null);try{const R=await YF(ue.id);rn.current=null,bt(!1),vs(R)}catch(R){wt(R instanceof Error?R.message:String(R))}finally{mt.current=!1,_t(!1)}}},[vs]),Ls=async()=>{if(!(!se||mt.current||rn.current)){mt.current=!0,_t(!0),wt(null);try{const H=await qF(se);H.status==="recording"||H.status==="starting"||H.status==="stopping"?(rn.current=H,bt(!0),xn(Math.max(0,Date.now()-H.startedAt))):vs(H)}catch(H){wt(H instanceof Error?H.message:String(H))}finally{mt.current=!1,_t(!1)}}};b.useEffect(()=>{let H=!1,ue=!1;rn.current=null,bt(!1);const R=async()=>{if(!(!se||ue||mt.current)){ue=!0;try{const{recordings:X}=await VF(se);if(H||mt.current)return;const be=X.find(Ee=>["starting","recording","stopping"].includes(Ee.status));rn.current=be??null,bt(!!be);for(const Ee of X)vs(Ee)}catch{}finally{ue=!1}}};R();const U=window.setInterval(()=>{R()},2e3);return $t.current=window.setInterval(()=>{rn.current&&xn(Math.max(0,Date.now()-rn.current.startedAt))},500),()=>{H=!0,window.clearInterval(U),$t.current!==null&&window.clearInterval($t.current)}},[se,vs]),b.useEffect(()=>{if(!Cn)return;const H=()=>Ur(!1),ue=U=>{const X=U.target;X instanceof Node&&(Dt.current?.contains(X)||ur.current?.contains(X)||H())},R=U=>{U.key==="Escape"&&(U.preventDefault(),U.stopPropagation(),H())};return document.addEventListener("pointerdown",ue,!0),document.addEventListener("keydown",R,!0),window.addEventListener("resize",H),()=>{document.removeEventListener("pointerdown",ue,!0),document.removeEventListener("keydown",R,!0),window.removeEventListener("resize",H)}},[Cn]),b.useEffect(()=>()=>{wr.current!==null&&window.clearTimeout(wr.current)},[]);const Qr=We==="streaming",yr=sn,Pn=yr?"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",Jn=Fr?(Fr.model||Fr.serial)+Ly(Fr,l):en.length?l("android.selectDevice"):l("android.noDevices"),oi=(ae?Je.find(H=>H.id===ae):null)?.name??(_e==="auto"?`${l("android.qualityAuto")} · ${I/1e6} Mbps`:l(e1[_e])),W=yr?"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",Ie=yr?"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",Ye="absolute inset-0 h-full w-full cursor-pointer opacity-0",nt=()=>{const H=Dt.current?.getBoundingClientRect();H&&Ze({left:Math.max(8,Math.min(H.right-Jm,window.innerWidth-Jm-8)),top:Math.min(H.bottom+4,Math.max(8,window.innerHeight-T$-8))}),Ur(!0)},st=()=>{if(sn){Wr(a0,null),Rr({docked:null});return}if(!qr)return;const H={sessionId:qr,side:"right"};Wr(a0,H),Rr({docked:H})},yt=Ce||sn||d!=="off",Pt=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:cr,tabIndex:-1,children:[s.jsxs("div",{"data-panel-drag-title":sn?"true":void 0,className:yr?"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:[sn&&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(sp,{size:12})}),s.jsx(N9,{size:yr?12:14,className:"shrink-0 text-muted-foreground"}),s.jsxs("div",{className:`${W} flex-1`,children:[s.jsx("span",{"aria-hidden":"true",className:`${Ie} w-full`,children:Jn}),s.jsxs("select",{value:se,onChange:H=>{const ue=H.target.value;De(ue),Xe.current=ue,ue&&Rr({deviceSerial:ue})},className:Ye,"aria-label":l("android.device"),children:[s.jsx("option",{value:"",children:en.length?l("android.selectDevice"):l("android.noDevices")}),en.map(H=>s.jsx("option",{value:H.serial,children:(H.model||H.serial)+Ly(H,l)},H.serial))]})]}),s.jsxs("div",{className:`${W} max-w-[45%] shrink-0`,children:[s.jsx("span",{"aria-hidden":"true",className:Ie,children:oi}),s.jsxs("select",{value:ae?`user:${ae}`:_e,onChange:H=>Gr(H.target.value),className:Ye,title:l(_e==="auto"?"android.qualityAutoHint":"android.quality"),"aria-label":l("android.quality"),children:[s.jsxs("option",{value:"auto",children:[l("android.qualityAuto"),_e==="auto"?` · ${I/1e6} Mbps`:""]}),np.map(H=>s.jsx("option",{value:H.id,children:l(e1[H.id])},H.id)),Je.map(H=>s.jsx("option",{value:`user:${H.id}`,children:H.name},H.id)),s.jsx("option",{value:"custom",children:l(e1.custom)})]})]}),s.jsx("button",{type:"button",onClick:()=>{_n()},className:`${Pn} text-muted-foreground`,title:l("android.refresh"),children:Te?s.jsx(jn,{size:13,className:"animate-spin"}):s.jsx(wn,{size:13})}),Qr?s.jsx("button",{type:"button",onClick:Xr,className:`${Pn} text-destructive`,title:l("android.disconnect"),children:s.jsx(m3,{size:13})}):s.jsx("button",{type:"button",onClick:()=>se&&dn(se),disabled:!se,className:`${Pn} text-primary`,title:l("android.connect"),children:s.jsx(kS,{size:13})}),(Qr||it)&&s.jsx("button",{type:"button",onClick:()=>{Bn()},disabled:!n||Dn,className:`${Pn} text-muted-foreground`,title:l(n?"android.screenshot":"android.captureUnavailable"),"aria-label":l("android.screenshot"),children:Dn?s.jsx(jn,{size:yr?12:13,className:"animate-spin"}):s.jsx(iT,{size:yr?12:13})}),(Qr||it)&&s.jsx("button",{type:"button",onClick:()=>{it?Bs("manual"):Ls()},disabled:Oe||!it&&!a,className:`${Pn} ${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:Oe?s.jsx(jn,{className:"animate-spin",size:13}):it?s.jsx(p3,{size:yr?10:11,fill:"currentColor"}):s.jsx(g3,{size:yr?12:13})}),s.jsx("button",{ref:Dt,type:"button",onClick:()=>Cn?Ur(!1):nt(),"aria-haspopup":"menu","aria-expanded":Cn,className:`${Pn} ${yt?"text-primary":"text-muted-foreground"}`,title:l("android.more"),"aria-label":l("android.more"),children:s.jsx(Io,{size:yr?13:14})}),c&&!t&&s.jsx("button",{type:"button",onClick:()=>{Ur(!1),f("off"),c()},className:`${Pn} text-muted-foreground hover:bg-destructive/20 hover:text-destructive`,title:l("android.closeTab"),"aria-label":l("android.closeTab"),children:s.jsx(Mn,{size:14})})]}),Cn&&ne&&Ks.createPortal(s.jsxs("div",{ref:ur,role:"menu","aria-label":l("android.more"),style:{left:ne.left,top:ne.top,width:Jm},className:"fixed z-popover overflow-hidden rounded-md border border-border bg-surface-elevated py-1 text-[11px] shadow-lg",children:[s.jsx(qh,{icon:s.jsx(Al,{size:13}),label:l("android.addDevice"),active:Ce,onSelect:()=>{St(H=>!H),Ur(!1)}}),s.jsx(qh,{icon:sn?s.jsx(Mn,{size:13}):s.jsx(Fl,{size:13}),label:l(sn?"android.splitClose":"android.splitOpen"),active:sn,disabled:!sn&&!qr,onSelect:()=>{st(),Ur(!1)}}),s.jsx(qh,{icon:d==="window"?s.jsx(JT,{size:13}):s.jsx(YT,{size:13}),label:l(d==="window"?"android.exitFullscreen":"android.fullscreen"),active:d==="window",onSelect:()=>{f(d==="window"?"off":"window"),Ur(!1)}}),!t&&s.jsx(qh,{icon:d==="sidebar"?s.jsx(cS,{size:13}):s.jsx(fS,{size:13}),label:l(d==="sidebar"?"android.exitFullscreen":"android.fillSidebar"),active:d==="sidebar",onSelect:()=>{f(d==="sidebar"?"off":"sidebar"),Ur(!1)}}),ge&&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:`${rt.fps} fps · ${rt.kbps} kbps`}),s.jsx("div",{className:"truncate",children:`${rt.width}×${rt.height}`})]})]}),document.body),(_e==="custom"||ae)&&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:()=>dt(H=>!H),"aria-expanded":me,className:"flex w-full items-center gap-1 rounded text-muted-foreground hover:text-foreground",children:[s.jsx(Al,{size:12,className:`transition-transform ${me?"":"-rotate-90"}`}),s.jsxs("span",{children:[l("android.quality"),ae?` · ${Je.find(H=>H.id===ae)?.name??""}`:""]})]}),me&&s.jsxs("div",{className:"mt-2 grid gap-2",children:[s.jsx(_y,{label:l("android.qualityResolution"),display:`${ft.maxSize}px`,min:360,max:2160,step:8,value:ft.maxSize,onChange:H=>Se(ue=>({...ue,maxSize:H}))}),s.jsx(_y,{label:l("android.qualityBitRate"),display:`${(ft.bitRate/1e6).toFixed(1)} Mbps`,min:.5,max:20,step:.5,value:ft.bitRate/1e6,onChange:H=>Se(ue=>({...ue,bitRate:Math.round(H*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(H=>s.jsx("button",{type:"button",onClick:()=>Se(ue=>({...ue,maxFps:H})),className:`rounded px-2 py-0.5 ${ft.maxFps===H?"bg-surface-elevated text-primary":"text-muted-foreground hover:bg-surface-2"}`,children:H},H)),s.jsx("button",{type:"button",onClick:()=>Se(H=>({...H,maxFps:0})),className:`rounded px-2 py-0.5 ${ft.maxFps===0?"bg-surface-elevated text-primary":"text-muted-foreground hover:bg-surface-2"}`,children:l("android.qualityAuto")})]}),s.jsx("button",{type:"button",onClick:zr,disabled:!se,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:at,onChange:H=>ut(H.target.value),onKeyDown:H=>{H.key==="Enter"&&!H.nativeEvent.isComposing&&Y()},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:Y,disabled:!at.trim(),className:"shrink-0 rounded bg-surface-2 px-2 py-1 text-primary disabled:opacity-40",children:l("android.presetSave")}),ae&&s.jsx("button",{type:"button",onClick:Be,className:"shrink-0 rounded px-2 py-1 text-destructive hover:bg-surface-2",children:l("android.presetDelete")})]})]})]}),Ce&&s.jsxs("div",{className:"flex items-center gap-1.5 border-b border-border px-2 py-2",children:[s.jsx("input",{value:Ot,onChange:H=>tr(H.target.value),onKeyDown:H=>{H.key==="Enter"&&is()},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:()=>{is()},disabled:ct,className:"rounded bg-surface-2 px-2 py-1 text-[11px] text-primary disabled:opacity-40",children:ct?s.jsx(jn,{size:12,className:"animate-spin"}):l("android.connect")})]}),Kr&&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(Sy,{label:l("android.insertFixPrompt"),onClick:()=>br(Cy("adb",ce??"")),enabled:!!r})]}),!Kr&&gr&&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(Sy,{label:l("android.insertFixPrompt"),onClick:()=>br(Cy("scrcpy","")),enabled:!!r})]}),Fr&&Fr.state!=="device"&&s.jsx("div",{className:"border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-warning",children:N$(Fr,l)}),ce&&!Kr&&s.jsx("div",{className:"border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-destructive",children:uy(ce)}),Yt&&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(Yt.startsWith("SCRCPY_VERSION")?"android.qualityAutoVersionError":Yt.startsWith("SCRCPY_BUILD")?"android.qualityAutoBuildError":/EXTENSION|SERVER_READ|PUSH/.test(Yt.split(":")[0])?"android.qualityAutoExtensionError":/TIMEOUT/.test(Yt.split(":")[0])?"android.qualityAutoTimeoutError":/ENCODER_REJECTED/.test(Yt.split(":")[0])?"android.qualityAutoEncoderError":/CHANNEL|TUNNEL|LISTEN|PROTOCOL|CONNECTION/.test(Yt.split(":")[0])?"android.qualityAutoChannelError":"android.qualityAutoUnknownError")]}),s.jsx("pre",{className:"mt-1 select-text whitespace-pre-wrap break-all text-[10px]",children:Yt})]}),Nt&&s.jsx("div",{className:"border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-warning",children:Nt}),we&&s.jsx("div",{role:"alert",className:"border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-destructive",children:we}),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:Qr||ge?"block":"none",transformOrigin:"center",transition:"none"},onPointerDown:Qn,onPointerMove:Xn,onPointerUp:fn,onPointerCancel:()=>an(),onLostPointerCapture:H=>{F.current.has(H.pointerId)&&an()},onPointerLeave:H=>{F.current.has(H.pointerId)&&!H.currentTarget.hasPointerCapture?.(H.pointerId)&&an()},onContextMenu:H=>H.preventDefault()}),xe&&s.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute h-3.5 w-3.5 -translate-x-1/2 -translate-y-1/2 rounded-full border border-primary/80 bg-primary/35",style:{left:xe.left,top:xe.top}}),ot.length>1&&s.jsx("svg",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0 h-full w-full",style:{opacity:K?1:0,transition:"opacity 160ms linear"},children:ot.slice(1).map((H,ue)=>{const R=ot[ue],U=(ue+1)/(ot.length-1);return s.jsx("line",{x1:R.x,y1:R.y,x2:H.x,y2:H.y,stroke:"var(--primary)",strokeWidth:1+1.6*U,strokeLinecap:"round",opacity:.06+.45*U},ue)})}),Bt.map(H=>s.jsx("span",{"aria-hidden":"true",className:"termdock-tap-fade pointer-events-none absolute h-4 w-4 rounded-full bg-primary",style:{left:H.left,top:H.top}},H.id)),!Qr&&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(jn,{size:18,className:"animate-spin"}),s.jsx("span",{children:l("android.connecting")})]}),We==="error"&&s.jsxs(s.Fragment,{children:[s.jsx(V0,{size:14,className:"text-destructive"}),s.jsx("span",{className:"max-w-[80%] text-destructive",children:Mt?l("android.reconnecting"):uy(z||"")}),se&&s.jsx("button",{type:"button",onClick:()=>{q.current=0,dn(se)},className:"rounded bg-surface-2 px-2 py-1 text-foreground",children:l("android.retry")})]}),We==="idle"&&!Kr&&!gr&&s.jsxs(s.Fragment,{children:[s.jsx(tS,{size:22,className:"opacity-60"}),s.jsx("span",{children:en.length?l("android.idleHint"):l("android.noDevicesHint")})]})]})]}),s.jsxs("div",{className:`flex flex-wrap items-center gap-1 border-t border-border ${yr?"px-1.5 py-0.5":"px-2 py-1.5"}`,children:[s.jsx(Wo,{compact:yr,label:l("android.back"),onClick:()=>x.current?.back(),disabled:!Qr,children:s.jsx(e3,{size:14})}),s.jsx(Wo,{compact:yr,label:l("android.home"),onClick:()=>x.current?.home(),disabled:!Qr,children:s.jsx(FT,{size:14})}),s.jsx(Wo,{compact:yr,label:l("android.recents"),onClick:()=>x.current?.recents(),disabled:!Qr,children:s.jsx(c3,{size:14})}),s.jsx(Wo,{compact:yr,label:l("android.notifications"),onClick:()=>x.current?.expandNotifications(),disabled:!Qr,children:s.jsx(i3,{size:14})}),s.jsx(Wo,{compact:yr,label:l("android.rotate"),onClick:()=>x.current?.rotate(),disabled:!Qr,children:s.jsx(MS,{size:14})}),s.jsx(Wo,{compact:yr,label:l("android.volumeDown"),onClick:()=>x.current?.volumeDown(),disabled:!Qr,children:s.jsx(sC,{size:14})}),s.jsx(Wo,{compact:yr,label:l("android.volumeUp"),onClick:()=>x.current?.volumeUp(),disabled:!Qr,children:s.jsx(aC,{size:14})}),s.jsx(Wo,{compact:yr,label:l("android.power"),onClick:()=>x.current?.power(),disabled:!Qr,children:s.jsx(IS,{size:14})}),s.jsx(Wo,{compact:yr,label:l("android.inputText"),active:or,onClick:()=>Cr(H=>!H),disabled:!Qr,children:s.jsx(l3,{size:14})}),s.jsx(Wo,{compact:yr,label:l("android.zoomIn"),onClick:()=>vr("in"),disabled:!Qr||ee>=vf-.01,children:s.jsx(Zs,{size:14})}),s.jsx(Wo,{compact:yr,label:l("android.zoomOut"),onClick:()=>vr("out"),disabled:!Qr||ee<=Ql+.01,children:s.jsx(u3,{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||!!Tt||Dn,className:`block truncate text-right text-[10px] leading-5 tabular-nums text-muted-foreground ${it||Tt||Dn?"invisible":""}`,children:ge?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(I$,{recording:it,elapsed:An,status:Dn?l("android.captureInserting"):Tt,stopLabel:l("android.recordingStop"),onStop:()=>{Bs("manual")}})})]})]}),or&&s.jsxs("div",{className:"flex items-center gap-1.5 border-t border-border px-2 py-1.5",children:[s.jsx("input",{value:Ir,onChange:H=>$r(H.target.value),onKeyDown:H=>{H.key==="Enter"&&!H.nativeEvent.isComposing&&(H.preventDefault(),tn())},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:tn,disabled:!Ir,className:"rounded bg-surface-2 p-1.5 text-primary disabled:opacity-40",title:l("android.send"),children:s.jsx(y0,{size:13})})]})]});return d==="window"?Ks.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:Pt}),document.body):t?sn&&Nr?Ks.createPortal(Pt,Nr):null:sn&&Nr?s.jsxs(s.Fragment,{children:[Ks.createPortal(Pt,Nr),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(Fl,{size:18,className:"opacity-60"}),s.jsx("span",{children:l("android.splitDockedHint")}),s.jsx("button",{type:"button",onClick:()=>{Wr(a0,null),Rr({docked:null})},className:"rounded bg-surface-2 px-2 py-1 text-foreground",children:l("android.splitClose")})]})]}):Pt}function qh({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(ai,{size:12,className:"shrink-0"})]})}function I$({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"}),xy(t),s.jsx("button",{type:"button",onClick:a,title:n,"aria-label":`${n} · ${xy(t)}`,className:"ml-0.5 inline-flex h-4 w-4 items-center justify-center rounded hover:bg-destructive/25",children:s.jsx(p3,{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 Ty({sessionId:e}){const t=ns(x=>x.docks[g0]),r=!!t,n=t?.sessionId??e??null,c=Xm(x=>x.pending)[0],l=b.useCallback(async x=>{if(!n)throw new Error("没有可接收截图的终端");const w=(await W0("/tmp",[x])).files[0]?.path;if(!w)throw new Error("截图上传未返回文件路径");await yy(w,n)},[n]),d=b.useCallback(x=>{Xm.getState().enqueue(x,n)},[n]),f=ns(x=>!!x.hosts[g0]),m=b.useRef(!1);return b.useEffect(()=>{m.current||(m.current=!0,wc().then(x=>{const y=x.androidPanel?.docked;y&&(ns.getState().docks[g0]||ns.getState().setDock(g0,y))}).catch(()=>{}))},[]),s.jsxs(s.Fragment,{children:[r&&f&&s.jsx(L$,{sessionId:n,dockOnly:!0,onInsertFile:n?l:void 0,onInsertPrompt:n?x=>_4(x,n):void 0,onRecordingComplete:d}),c&&s.jsx(A$,{file:c.file,initialPath:c.initialPath,onInsert:x=>c.insert?c.insert(x):yy(x,c.sessionId),onDone:()=>Xm.getState().remove(c.file.id)},c.file.id)]})}function Sy({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 Cy(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 _y({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 Wo({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 ky(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 Yh(e,t,r){const n=e.getBoundingClientRect(),a=e.width||n.width,c=e.height||n.height,l=n.width?(t-n.left)/n.width*a:0,d=n.height?(r-n.top)/n.height*c:0;return{x:Math.max(0,Math.min(a,l)),y:Math.max(0,Math.min(c,d))}}function E$(e){return!(/ADB_NOT_FOUND|SCRCPY_NOT_FOUND|SCRCPY_SERVER_NOT_FOUND|SCRCPY_VERSION_UNKNOWN|SCRCPY_UNSUPPORTED_CODEC|VIDEO_DECODER_UNSUPPORTED|decoder|decode/i.test(e)||/INVALID_SERIAL|INVALID_ADDRESS|API_NOT_ALLOWED|AUTHORIZATION_DENIED/i.test(e))}function Ly(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 N$(e,t){return e.state==="unauthorized"?t("android.unauthorizedHint"):e.state==="offline"?t("android.offlineHint"):t("android.stateUnknown")}function R$(e){return e>=90?"var(--destructive)":e>=70?"var(--warning)":"var(--success)"}function M$(e){return e>=90?"var(--destructive)/0.15":e>=70?"var(--warning)/0.15":"var(--success)/0.12"}function j$(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,f=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 ${f}m`:f>0?y=`${f}m`:y="soon",`resets in ${y} (${m} ${x})`}function D$(e){return{claude:"🧠",codex:"✨",kimi:"🌙",copilot:"🐙",grok:"🚀",gemini:"💎"}[e]||"📊"}function B$({result:e}){const{t}=Hr(),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:D$(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 f=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:M$(d.percent)},children:s.jsx("div",{className:"h-full rounded-full transition-all duration-500",style:{width:`${f}%`,background:R$(d.percent)}})})}),s.jsxs("span",{className:"w-9 shrink-0 text-right tabular-nums font-medium text-foreground",children:[Math.round(d.percent),"%"]})]}),d.resetAt&&s.jsx("p",{className:"mt-1 pl-14 text-[10px] text-muted-foreground sm:pl-16",children:j$(d.resetAt)})]},d.label)})}):c?s.jsx("p",{className:"mt-2 text-[11px] text-muted-foreground",children:e.error}):null]})}function Q$({isOpen:e,onClose:t}){const{t:r}=Hr(),[n,a]=b.useState([]),[c,l]=b.useState(!1),d=async(x=!1)=>{l(!0);try{const y=x?await R9():await M9();a(y.providers||[])}catch{}finally{l(!1)}};if(b.useEffect(()=>{e&&d()},[e]),b.useEffect(()=>{if(!e)return;const x=y=>{const w=y.detail;Array.isArray(w)&&a(w)};return window.addEventListener("termdock:quota-update",x),()=>{window.removeEventListener("termdock:quota-update",x)}},[e]),!e)return null;const f=n.filter(x=>!x.error),m=f.length>0?new Date(Math.max(...f.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(wn,{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(Mn,{size:17})})]})]}),s.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto p-3 sm:p-5",children:[c&&f.length===0?s.jsx(_0,{label:r("common.loading"),className:"py-12"}):f.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:f.map(x=>s.jsx(B$,{result:x},x.slug))}),m&&s.jsx("p",{className:"mt-3 text-center text-[10px] text-muted-foreground",children:r("quota.updated",{time:m.toLocaleTimeString()})})]})]})]})}const Iy=[{label:"Esc",sequence:"\\u001b"},{label:"Tab",sequence:"\\t"},{label:"Enter",sequence:"\\r"},{label:"S-Tab",sequence:"\\u001b[Z"},{label:"C-c",sequence:"\\u0003"},{label:"C-d",sequence:"\\u0004"},{label:"C-l",sequence:"\\u000c"},{label:"C-r",sequence:"\\u0012"},{label:"C-z",sequence:"\\u001a"},{label:"C-w",sequence:"\\u0017"},{label:"Up",sequence:"\\u001b[A"},{label:"Down",sequence:"\\u001b[B"},{label:"Left",sequence:"\\u001b[D"},{label:"Right",sequence:"\\u001b[C"},{label:"PgUp",sequence:"\\u001b[5~"},{label:"PgDn",sequence:"\\u001b[6~"}],P$=2,O$=20;function F$({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 $$({value:e,onChange:t,placeholder:r}){const{t:n}=Hr(),[a,c]=_.useState(""),l=y=>{const w=[];let v="",T=!1;const S=()=>{const N=v.trim();N&&w.push(N),v=""};for(let N=0;N<y.length;N+=1){const B=y[N];if(!T&&B==="/"&&v.trim().length===0){T=!0,v+=B;continue}if(T){if(v+=B,B==="/"&&y[N-1]!=="\\"&&v.length>1){for(;N+1<y.length&&/[gimsuy]/.test(y[N+1]??"");)N+=1,v+=y[N];S(),T=!1}continue}if(B===","||/\s/.test(B)){S();continue}v+=B}if(S(),w.length===0)return;const I=[...e];for(const N of w){const B=Tv(N);B&&(I.includes(B)||I.push(B))}t(I),c("")},d=y=>{t(e.filter(w=>w!==y))},f=a.trim(),m=f.length>0&&r5(f),x=m&&!Df(f);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=r5(y),v=w&&!Df(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(Mn,{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 U$({value:e,min:t,max:r,onChange:n}){const{t:a}=Hr();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(u3,{size:14})}),s.jsx("span",{className:"w-6 text-center text-sm font-medium tabular-nums text-foreground",children:e}),s.jsx("button",{type:"button",onClick:()=>n(Math.min(r,e+1)),disabled:e>=r,className:"h-7 w-7 rounded-full bg-surface-2 text-muted-foreground transition hover:bg-surface-elevated disabled:opacity-40 inline-flex items-center justify-center","aria-label":a("common.increase"),children:s.jsx(Zs,{size:14})})]})}const z$=({presets:e,selectedPresetId:t,onSelectPreset:r,onUpdatePreset:n,onAddPreset:a,onRemovePreset:c,onResetDefaults:l})=>{const{t:d}=Hr(),f=e.find(N=>N.id===t)??e[0]??null,[m,x]=_.useState(null);if(!f)return null;const y=f.actions.length>0,w=[{id:"preview-auto",label:f.label,kind:"preset"},...f.includeAlt?[{id:"preview-alt",label:"Alt"}]:[],...y?f.actions.map((N,B)=>({id:N.id,label:_1(N,B)})):["Enter","Home","End","Ctrl-C","Ctrl-D"].map(N=>({id:N,label:N}))],v=Sv(w,f.rowLayout),T=(N,B)=>{n(f.id,F=>{const P=F.actions.findIndex(Z=>Z.id===N);if(P===-1)return F;const $=P+B;if($<0||$>=F.actions.length)return F;const ee=[...F.actions];return[ee[P],ee[$]]=[ee[$],ee[P]],{...F,actions:ee}})},S=f.rowLayout.reduce((N,B)=>N+B,0),I=1+(f.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:[f.actions.length," button",f.actions.length===1?"":"s"," · ",S," slot",S===1?"":"s"]})]}),s.jsx("div",{className:"space-y-1 rounded-2xl bg-surface-2/60 p-2",children:v.map((N,B)=>{const F=N.items[0]?.kind==="preset",P=Math.max(2,N.columns),$=F?`${Cv}px repeat(${Math.max(1,P-1)}, minmax(0, 1fr))`:`repeat(${P}, minmax(0, 1fr))`;return s.jsx("div",{className:"grid gap-1",style:{gridTemplateColumns:$},children:N.items.map(ee=>ee.kind==="preset"?s.jsx(_v,{mode:"auto",presetLabel:ee.label,title:`Auto preset · ${ee.label}`,disabled:!0},ee.id):s.jsx(F$,{label:ee.label},ee.id))},`preview-row-${B}`)})}),f.actions.length>S-I&&s.jsx("p",{className:"mt-1.5 text-[10px] text-muted-foreground",children:d("toolbarPresets.overCapacityHint")})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"ui-kicker",children:d("toolbarPresets.presets")}),s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsxs("button",{type:"button",onClick:a,className:"inline-flex items-center gap-1 rounded-full bg-surface-2 px-3 py-2 text-xs font-medium hover:bg-surface-elevated transition",children:[s.jsx(Zs,{size:14}),d("toolbarPresets.new")]}),s.jsxs("button",{type:"button",onClick:l,className:"inline-flex items-center gap-1 rounded-full bg-surface-2 px-3 py-2 text-xs font-medium hover:bg-surface-elevated transition",children:[s.jsx(wn,{size:14}),d("toolbarPresets.reset")]})]})]}),s.jsx("div",{className:"-mx-1 flex flex-wrap gap-1.5 px-1",children:e.map(N=>s.jsxs("button",{type:"button",onClick:()=>r(N.id),className:`rounded-full px-3 py-2 text-xs font-medium transition ${N.id===f.id?"bg-primary/20 text-primary ring-1 ring-primary/30":"bg-surface-2 text-muted-foreground hover:bg-surface-elevated"}`,children:[N.label,N.actions.length>0&&s.jsx("span",{className:"ml-1.5 text-[10px] text-muted-foreground",children:N.actions.length})]},N.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:f.label,onChange:N=>n(f.id,B=>({...B,label:N.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"}),f.id!=="default"&&s.jsx("button",{type:"button",onClick:()=>c(f.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:f.label}),children:s.jsx(Ds,{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($$,{value:f.programs,onChange:N=>n(f.id,B=>({...B,programs:N})),placeholder:d("toolbarPresets.programsPlaceholder")}),s.jsx("p",{className:"text-[10px] text-muted-foreground",children:d("toolbarPresets.programsHelp")})]}),s.jsxs("button",{type:"button",onClick:()=>n(f.id,N=>({...N,includeAlt:!N.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(yl,{checked:f.includeAlt})]}),s.jsxs("button",{type:"button",onClick:()=>n(f.id,N=>({...N,showOnDesktop:!N.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(yl,{checked:f.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(f.id,N=>({...N,rowLayout:[...wg(N.rowLayout),3]})),className:"inline-flex items-center gap-1 rounded-full bg-surface-2 px-3 py-1.5 text-xs font-medium hover:bg-surface-elevated",children:[s.jsx(Zs,{size:12}),d("toolbarPresets.addRow")]})]}),s.jsx("div",{className:"space-y-2",children:f.rowLayout.map((N,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(U$,{value:N,min:P$,max:O$,onChange:F=>n(f.id,P=>({...P,rowLayout:P.rowLayout.map(($,ee)=>ee===B?F:$)}))}),f.rowLayout.length>1&&s.jsx("button",{type:"button",onClick:()=>n(f.id,F=>({...F,rowLayout:F.rowLayout.filter((P,$)=>$!==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 N=`${f.id}-action-${Date.now()}`;n(f.id,B=>({...B,actions:[...B.actions,{id:N,label:`Key ${B.actions.length+1}`,sequence:""}]})),x(N)},className:"inline-flex items-center gap-1 rounded-full bg-primary/15 px-3 py-1.5 text-xs font-medium text-primary hover:bg-primary/25",children:[s.jsx(Zs,{size:12}),d("toolbarPresets.addButton")]})]}),f.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")}),f.actions.map((N,B)=>{const F=m===N.id;return s.jsxs("div",{className:`rounded-2xl bg-surface-2 transition ${F?"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:()=>T(N.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(s3,{size:12})}),s.jsx("button",{type:"button",onClick:()=>T(N.id,1),disabled:B===f.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(qA,{size:12})})]}),s.jsxs("button",{type:"button",onClick:()=>x(F?null:N.id),className:"min-w-0 flex-1 text-left",children:[s.jsx("div",{className:"truncate text-sm font-medium text-foreground",children:_1(N,B)}),s.jsxs("div",{className:"truncate text-[11px] text-muted-foreground",children:[N.sequence?N.sequence:d("toolbarPresets.noSequence"),N.doubleTapSequence&&s.jsxs("span",{className:"ml-1 text-accent/70",children:["· 2× ",N.doubleTapSequence]})]})]}),s.jsx("button",{type:"button",onClick:()=>n(f.id,P=>({...P,actions:P.actions.filter($=>$.id!==N.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:N.label}),children:s.jsx(Ds,{size:14})})]}),F&&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:N.label,onChange:P=>n(f.id,$=>({...$,actions:$.actions.map(ee=>ee.id===N.id?{...ee,label:P.target.value}:ee)})),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:N.sequence,onChange:P=>n(f.id,$=>({...$,actions:$.actions.map(ee=>ee.id===N.id?{...ee,sequence:P.target.value}:ee)})),className:"w-full rounded-full bg-surface px-4 py-2.5 font-mono text-sm outline-none ring-1 ring-transparent focus:ring-accent/40",placeholder:d("toolbarPresets.sequencePlaceholder"),autoCapitalize:"off",autoCorrect:"off",spellCheck:!1}),s.jsx("div",{className:"flex flex-wrap gap-1.5 pt-1",children:Iy.map(P=>s.jsx("button",{type:"button",onClick:()=>n(f.id,$=>({...$,actions:$.actions.map(ee=>ee.id===N.id?{...ee,sequence:P.sequence}:ee)})),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:P.label},P.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")}),!N.doubleTapSequence&&s.jsx("button",{type:"button",onClick:()=>n(f.id,P=>({...P,actions:P.actions.map($=>$.id===N.id?{...$,doubleTapSequence:""}:$)})),className:"text-[10px] text-accent hover:text-accent/80",children:d("toolbarPresets.doubleTapAdd")})]}),N.doubleTapSequence!==void 0&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:N.doubleTapSequence,onChange:P=>n(f.id,$=>({...$,actions:$.actions.map(ee=>ee.id===N.id?{...ee,doubleTapSequence:P.target.value}:ee)})),className:"w-full rounded-full bg-surface px-4 py-2.5 font-mono text-sm outline-none ring-1 ring-transparent focus:ring-accent/40",placeholder:d("toolbarPresets.doubleTapPlaceholder"),autoCapitalize:"off",autoCorrect:"off",spellCheck:!1}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 pt-1",children:[Iy.map(P=>s.jsx("button",{type:"button",onClick:()=>n(f.id,$=>({...$,actions:$.actions.map(ee=>ee.id===N.id?{...ee,doubleTapSequence:(ee.doubleTapSequence??"")+P.sequence}:ee)})),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:P.label},P.label)),s.jsx("button",{type:"button",onClick:()=>n(f.id,P=>({...P,actions:P.actions.map($=>{if($.id!==N.id)return $;const{doubleTapSequence:ee,...Z}=$;return Z})})),className:"rounded-full bg-destructive/10 px-2.5 py-1 text-[11px] font-medium text-destructive/70 hover:bg-destructive/20 hover:text-destructive",children:d("toolbarPresets.remove")})]})]})]})]})]},N.id)})]})]})]})},H$={installed:"text-[color:var(--success)]",outdated:"text-[color:var(--warning)]","needs-approval":"text-[color:var(--warning)]","not-installed":"text-muted-foreground"};function W$(){const{t:e}=Hr(),[t,r]=_.useState(null),[n,a]=_.useState(null),[c,l]=_.useState(null),[d,f]=_.useState(null),[m,x]=_.useState(!1),[y,w]=_.useState(!1),[v,T]=_.useState(""),[S,I]=_.useState(""),[N,B]=_.useState(null),[F,P]=_.useState([]),[$,ee]=_.useState([]),[Z,V]=_.useState(null),[de,pe]=_.useState(new Set),[J,Re]=_.useState(null),[Xe,q]=_.useState("auto"),[ve,qe]=_.useState({}),[ce,ye]=_.useState(null),[Te,Fe]=_.useState(null),[se,De]=_.useState(10),[_e,Me]=_.useState(""),[Je,Ne]=_.useState(""),[ae,ze]=_.useState(12e3),[at,ut]=_.useState(null),[me,dt]=_.useState(null),ft=_.useCallback(async()=>{const[xe,et,ot,Et]=await Promise.allSettled([j9(),D9(),wc(),Ld()]);if(r(xe.status==="fulfilled"?xe.value:[]),et.status==="fulfilled"){const K=et.value;P(K.plugins??[]),ee(K.errors??[])}else P([]),ee([]);if(ot.status==="fulfilled"){const K=ot.value;pe(new Set(K.autoRenameAgents??[])),q(K.autoRenameNamer??"auto"),qe(K.autoRenameModels??{}),De(K.autoRenameIntervalMinutes??10),Me(K.autoRenamePromptPreference??""),Ne(K.autoRenamePromptPreference??""),ze(K.autoRenamePromptPayloadChars??12e3)}else pe(new Set);ye(Et.status==="fulfilled"?Et.value:[])},[]);_.useEffect(()=>{ft()},[ft]);const Se=async(xe,et)=>{a(xe),l(null);try{et==="install"?(await B9(xe)).devMode&&f(xe):(await Q9(xe),d===xe&&f(null)),await ft()}catch(ot){l(ot instanceof Error?ot.message:String(ot))}finally{a(null)}},We=xe=>e(xe==="installed"?"settings.agentHooksInstalled":xe==="outdated"?"settings.agentHooksOutdated":xe==="needs-approval"?"settings.agentHooksNeedsApproval":"settings.agentHooksNotInstalled"),Le=async()=>{B(null);let xe;try{xe=JSON.parse(S)}catch{B("Invalid JSON");return}try{await z9(xe),I(""),x(!1),await ft()}catch(et){if(et instanceof H9&&et.migration){ee(ot=>[{slug:typeof xe.slug=="string"?xe.slug:"manifest.json",errors:et.message.split(`
|
|
164
164
|
`),code:et.code,migration:et.migration},...ot.filter(Et=>Et.slug!==xe.slug)]);return}B(et instanceof Error?et.message:String(et))}},z=async()=>{const xe=v.trim();if(xe){ut("install"),B(null);try{await P9(xe),T(""),w(!1),await ft()}catch(et){B(et instanceof Error?et.message:String(et))}finally{ut(null)}}},ie=async xe=>{ut(`remove:${xe}`);try{await U9(xe),dt(et=>et?.slug===xe?null:et),await ft()}catch(et){l(et instanceof Error?et.message:String(et))}finally{ut(null)}},ge=async xe=>{ut(`check:${xe}`),l(null);try{await $9(xe),await ft()}catch(et){l(et instanceof Error?et.message:String(et))}finally{ut(null)}},Ge=async xe=>{ut(`update:${xe}`),l(null);try{const et=await F9(xe),ot=[et.hookWarning,et.titleWarning].filter(Boolean).join(" ");ot&&l(ot),dt(Et=>Et?.slug===xe?null:Et),await ft()}catch(et){l(et instanceof Error?et.message:String(et))}finally{ut(null)}},rt=async xe=>{ut(`doctor:${xe}`),l(null),dt(null);try{const et=await O9(xe);dt(et),ye(await Ld())}catch(et){l(et instanceof Error?et.message:String(et))}finally{ut(null)}},vt=async xe=>{const et=xe.migration?.aiPrompt??xe.errors.join(`
|
|
165
165
|
`);try{await navigator.clipboard.writeText(et),V(xe.slug),window.setTimeout(()=>V(ot=>ot===xe.slug?null:ot),1800)}catch{B(et)}},Yt=async xe=>{if(J)return;const et=de,ot=new Set(et);ot.has(xe)?ot.delete(xe):ot.add(xe),pe(ot),Re(xe),l(null);try{const Et=await ja({autoRenameAgents:[...ot]});pe(new Set(Et.autoRenameAgents??[])),ye(await Ld(!0))}catch(Et){pe(et),l(Et instanceof Error?Et.message:String(Et))}finally{Re(null)}},Ut=async xe=>{const et=Xe;q(xe),Fe("namer"),l(null);try{const ot=await ja({autoRenameNamer:xe});q(ot.autoRenameNamer??"auto"),ye(await Ld(!0))}catch(ot){q(et),l(ot instanceof Error?ot.message:String(ot))}finally{Fe(null)}},Nt=async(xe,et)=>{const ot=ve,Et={...ot};et?Et[xe]=et:delete Et[xe],qe(Et),Fe(xe),l(null);try{const K=await ja({autoRenameModels:Et});qe(K.autoRenameModels??{})}catch(K){qe(ot),l(K instanceof Error?K.message:String(K))}finally{Fe(null)}},ir=async xe=>{const et=se;De(xe),Fe("interval"),l(null);try{const ot=await ja({autoRenameIntervalMinutes:xe});De(ot.autoRenameIntervalMinutes??10)}catch(ot){De(et),l(ot instanceof Error?ot.message:String(ot))}finally{Fe(null)}},Mt=async()=>{const xe=_e.trim();if(xe!==Je){Fe("preference"),l(null);try{const ot=(await ja({autoRenamePromptPreference:xe})).autoRenamePromptPreference??"";Me(ot),Ne(ot)}catch(et){Me(Je),l(et instanceof Error?et.message:String(et))}finally{Fe(null)}}},Xt=async xe=>{const et=Math.max(1e3,Math.min(64e3,Math.round(xe||12e3))),ot=ae;ze(et),Fe("payload-limit"),l(null);try{const Et=await ja({autoRenamePromptPayloadChars:et});ze(Et.autoRenamePromptPayloadChars??12e3)}catch(Et){ze(ot),l(Et instanceof Error?Et.message:String(Et))}finally{Fe(null)}},Bt=new Set(F.map(xe=>xe.slug)),Wt=me?{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")}[me.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:Xe,disabled:Te!==null,onChange:xe=>{Ut(xe.target.value)},className:"min-w-0 rounded-lg bg-surface px-2.5 py-1.5 text-[11px] text-foreground outline-none disabled:opacity-50",children:[s.jsx("option",{value:"auto",children:e("settings.agentAutoRenameFollow")}),ce?.filter(xe=>xe.available).map(xe=>s.jsx("option",{value:xe.slug,children:xe.displayName},xe.slug))]})]}),s.jsxs("label",{className:"mt-2 flex items-center justify-between gap-3",children:[s.jsx("span",{className:"text-[11px] text-muted-foreground",children:e("settings.agentAutoRenameInterval")}),s.jsx("select",{value:se,disabled:Te!==null,onChange:xe=>{ir(Number(xe.target.value))},className:"min-w-0 rounded-lg bg-surface px-2.5 py-1.5 text-[11px] text-foreground outline-none disabled:opacity-50",children:[5,10,30,60].map(xe=>s.jsxs("option",{value:xe,children:[xe," ",e("settings.agentAutoRenameMinutes")]},xe))})]}),s.jsxs("details",{className:"mt-2 border-t border-border/40 pt-2",children:[s.jsx("summary",{className:"cursor-pointer select-none text-[11px] text-muted-foreground transition hover:text-foreground",children:e("settings.agentAutoRenameAdvanced")}),s.jsxs("label",{className:"mt-2 block",children:[s.jsx("span",{className:"text-[11px] font-medium text-foreground",children:e("settings.agentAutoRenamePreference")}),s.jsx("span",{className:"mt-0.5 block text-[10px] text-muted-foreground",children:e("settings.agentAutoRenamePreferenceHint")}),s.jsx("textarea",{value:_e,maxLength:2e3,rows:3,disabled:Te!==null,placeholder:e("settings.agentAutoRenamePreferencePlaceholder"),onChange:xe=>Me(xe.target.value),onBlur:()=>{Mt()},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:Te==="preference"?e("settings.saving"):`${_e.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:ae,disabled:Te!==null,onChange:xe=>ze(Number(xe.target.value)),onBlur:xe=>{Xt(Number(xe.target.value))},className:"mt-1.5 w-full rounded-lg bg-surface px-2.5 py-2 text-[11px] text-foreground outline-none focus:ring-1 focus:ring-primary/50 disabled:opacity-50"})]})]}),s.jsxs("div",{className:"mt-2 space-y-1.5 border-t border-border/40 pt-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[10px] text-muted-foreground",children:e("settings.agentAutoRenameModelsFromCli")}),s.jsx("button",{type:"button",onClick:async()=>{ye(null);try{ye(await Ld(!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(wn,{size:11,className:ce===null?"animate-spin":""})})]}),ce?.filter(xe=>xe.available).map(xe=>{const et=xe.models.find(ot=>ot.id===xe.recommendedModel);return s.jsxs("label",{className:"flex items-center justify-between gap-3",children:[s.jsx("span",{className:"text-[11px] text-muted-foreground",children:xe.displayName}),s.jsxs("select",{value:ve[xe.slug]??"",disabled:Te!==null,onChange:ot=>{Nt(xe.slug,ot.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:et?`${e("settings.agentAutoRenameAutomatic")} · ${et.displayName}`:e("settings.agentAutoRenameCliDefault")}),xe.models.map(ot=>s.jsx("option",{value:ot.id,children:ot.displayName},ot.id))]})]},xe.slug)}),ce?.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(jn,{size:12,className:"animate-spin"})," …"]}),t?.map(xe=>{const et=n===xe.slug,ot=xe.state!=="not-installed",Et=Bt.has(xe.slug);return s.jsxs("div",{className:"flex items-center gap-3 rounded-xl bg-surface-2 px-3 py-2.5",children:[s.jsx(Jc,{agent:{slug:xe.slug,displayName:xe.displayName,accentColor:xe.accentColor??"#878580",icon:xe.icon,isPlugin:Et,iconMode:xe.iconMode,iconVersion:xe.iconVersion??void 0},size:18}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-[13px] font-medium text-foreground",children:xe.displayName}),Et&&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] ${H$[xe.state]}`,children:[xe.state==="installed"&&s.jsx(L0,{size:10,className:"mr-0.5 inline"}),(xe.state==="outdated"||xe.state==="needs-approval")&&s.jsx(sg,{size:10,className:"mr-0.5 inline"}),We(xe.state)]})]}),s.jsxs("div",{className:"truncate text-[10px] text-muted-foreground",title:xe.targetDisplay,children:[e("settings.agentHooksTarget")," ",xe.targetDisplay]}),d===xe.slug&&s.jsx("div",{className:"mt-0.5 text-[10px] text-[color:var(--warning)]",children:e("settings.agentHooksDevMode")}),xe.state==="needs-approval"&&s.jsx("div",{className:"mt-0.5 text-[10px] text-[color:var(--warning)]",children:e("settings.agentHooksApprovalHint")})]}),s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsxs("button",{type:"button",disabled:J!==null,onClick:()=>{Yt(xe.slug)},className:"flex shrink-0 items-center gap-1.5 rounded-full px-2 py-1 text-[10px] text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground disabled:opacity-50","aria-pressed":de.has(xe.slug),title:e("settings.agentAutoRenameToggle"),children:[s.jsx("span",{children:e("settings.agentAutoRenameShort")}),s.jsx(yl,{checked:de.has(xe.slug),disabled:J!==null,size:"sm"})]}),s.jsxs("button",{type:"button",disabled:et,onClick:()=>{Se(xe.slug,ot?"uninstall":"install")},className:`flex shrink-0 items-center gap-1 rounded-full px-2.5 py-1 text-[11px] font-medium transition ${ot?"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:[et?s.jsx(jn,{size:11,className:"animate-spin"}):ot?s.jsx(Ds,{size:11}):xe.state==="outdated"?s.jsx(wn,{size:11}):s.jsx(E0,{size:11}),et?"…":ot?e("settings.agentHooksUninstall"):xe.state==="outdated"?e("settings.agentHooksReinstall"):e("settings.agentHooksInstall")]})]})]},xe.slug)}),c&&s.jsx("div",{className:"rounded-xl bg-[rgb(var(--warning-rgb)_/_0.10)] px-3 py-2 text-[11px] text-[color:var(--warning)]",children:c}),s.jsxs("div",{className:"rounded-xl bg-surface-2 px-3 py-2.5",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-[12px] font-medium text-foreground",children:e("settings.agentPlugins")}),s.jsxs("button",{type:"button",onClick:()=>w(!y),className:"flex items-center gap-1 rounded-full bg-[rgb(var(--success-rgb)_/_0.14)] px-2.5 py-1 text-[11px] font-medium text-[color:var(--success)] hover:bg-[rgb(var(--success-rgb)_/_0.22)] transition",children:[s.jsx(Zs,{size:11}),e("settings.agentPluginAdd")]})]}),s.jsx("p",{className:"mt-1 text-[10px] text-muted-foreground",children:e("settings.agentPluginHint")}),y&&s.jsxs("div",{className:"mt-2 space-y-2",children:[s.jsxs("div",{className:"flex gap-2",children:[s.jsx("input",{value:v,onChange:xe=>T(xe.target.value),onKeyDown:xe=>{xe.key==="Enter"&&z()},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()||at!==null,onClick:()=>{z()},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:[at==="install"?s.jsx(jn,{size:11,className:"animate-spin"}):s.jsx(E0,{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")})]}),F.map(xe=>{const et=xe.revision?.slice(0,8),ot=at?.endsWith(`:${xe.slug}`)===!0;return s.jsxs("div",{className:"mt-2 flex items-center gap-2 border-t border-border/40 pt-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] font-medium text-foreground",children:[s.jsx("span",{className:"truncate",children:xe.displayName}),xe.updateAvailable&&s.jsx("span",{className:"text-[9px] text-[color:var(--warning)]",children:e("settings.agentPluginUpdateAvailable")})]}),s.jsxs("div",{className:"truncate text-[9px] text-muted-foreground",title:xe.source??void 0,children:[xe.source??e("settings.agentPluginManualSource"),et?` · ${et}`:""]})]}),s.jsxs("button",{type:"button",disabled:at!==null,onClick:()=>{rt(xe.slug)},className:"flex items-center gap-1 rounded-full bg-surface px-2 py-1 text-[10px] text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground disabled:opacity-50",title:e("settings.agentPluginDoctorHint"),children:[at===`doctor:${xe.slug}`?s.jsx(jn,{size:10,className:"animate-spin"}):s.jsx(WS,{size:10}),e("settings.agentPluginDoctor")]}),xe.updateSupported&&s.jsxs("button",{type:"button",disabled:at!==null,onClick:()=>{xe.updateAvailable?Ge(xe.slug):ge(xe.slug)},className:"flex items-center gap-1 rounded-full bg-surface px-2 py-1 text-[10px] text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground disabled:opacity-50",children:[ot?s.jsx(jn,{size:10,className:"animate-spin"}):s.jsx(wn,{size:10}),xe.updateAvailable?e("settings.agentPluginUpdate"):e("settings.agentPluginCheck")]}),s.jsx("button",{type:"button",disabled:at!==null,onClick:()=>{ie(xe.slug)},className:"rounded-full p-1 text-muted-foreground transition hover:bg-surface-elevated hover:text-[color:var(--warning)] disabled:opacity-50",title:e("settings.agentPluginDelete"),children:s.jsx(Ds,{size:11})})]},xe.slug)}),me&&s.jsxs("div",{className:`mt-2 rounded-lg px-3 py-2 text-[10px] ${me.status==="ok"||me.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:[me.displayName,": ",Wt]}),s.jsx("div",{className:"mt-1 text-muted-foreground",children:me.models.length>0?`${me.models.length} ${e("settings.agentPluginDoctorModels")}${me.recommendedModel?` · ${e("settings.agentPluginDoctorAutomatic")} ${me.recommendedModel}`:""}`:e("settings.agentPluginDoctorCliDefault")}),me.error&&s.jsx("div",{className:"mt-1 break-words",children:me.error}),me.warnings.length>0&&s.jsx("div",{className:"mt-1 space-y-0.5 text-muted-foreground",children:me.warnings.map(xe=>s.jsxs("div",{children:["• ",xe]},xe))}),me.nextSteps.length>0&&s.jsx("div",{className:"mt-1 space-y-0.5 text-muted-foreground",children:me.nextSteps.map(xe=>s.jsxs("div",{children:["→ ",xe]},xe))})]}),$.map(xe=>s.jsxs("div",{className:"mt-2 rounded-lg bg-[rgb(var(--warning-rgb)_/_0.10)] px-3 py-2 text-[10px] text-[color:var(--warning)]",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("span",{className:"font-medium",children:[xe.slug,": ",xe.code??e("settings.agentPluginInvalid")]}),s.jsxs("button",{type:"button",onClick:()=>{vt(xe)},className:"flex shrink-0 items-center gap-1 rounded-full bg-[rgb(var(--warning-rgb)_/_0.14)] px-2 py-1 font-medium transition hover:bg-[rgb(var(--warning-rgb)_/_0.22)]",children:[Z===xe.slug?s.jsx(L0,{size:10}):s.jsx(a3,{size:10}),Z===xe.slug?e("settings.agentPluginCopied"):e("settings.agentPluginCopyAiPrompt")]})]}),s.jsx("div",{className:"mt-1 whitespace-pre-wrap break-words text-muted-foreground",children:xe.errors.join(`
|
|
@@ -182,5 +182,5 @@ ${dt.map(K=>`待回答:${K.question}`).join(`
|
|
|
182
182
|
{ "hook": "Stop", "event": "stop", "status": "complete" }
|
|
183
183
|
]
|
|
184
184
|
}
|
|
185
|
-
}`}),N&&s.jsx("div",{className:"whitespace-pre-wrap break-words text-[10px] text-[color:var(--warning)]",children:N}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("button",{type:"button",onClick:()=>{Le()},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(yT,{size:11}),e("settings.agentPluginCreate")]}),s.jsx("button",{type:"button",onClick:()=>{x(!1),I(""),B(null)},className:"rounded-full px-3 py-1 text-[11px] text-muted-foreground hover:text-foreground transition",children:e("common.cancel")})]})]})]})]})}function G$({state:e,pending:t,onCheck:r,onConfirmRestart:n,desktopState:a,desktopPending:c=!1,desktopSnapshot:l,desktopActions:d,onCheckDesktop:f,onInstallDesktop:m}){const{t:x}=Hr(),y=e?.status??"idle",w=t||y==="checking"||y==="installing"||y==="restarting",v=y==="ready"&&!!e?.latestVersion,T=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"),S=a?.currentVersion||l?.appVersion,I=a?.status??"idle",N=c||I==="checking"||I==="downloading"||I==="installing",B=I==="ready",F=a?.error||(I==="unsupported"?x("settings.desktopUpdateUnsupported"):I==="checking"?x("settings.desktopUpdateChecking"):I==="current"?x("settings.desktopUpdateCurrent"):I==="downloading"?x("settings.desktopUpdateDownloading"):I==="ready"?x("settings.desktopUpdateReady"):I==="installing"?x("settings.desktopUpdateInstalling"):I==="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(wn,{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:T}),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(wn,{size:15,className:N?"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?F:x(f?"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}`:S?`v${S}`:null})]})]}),B?s.jsx("button",{type:"button",disabled:N||!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||N||I==="unsupported"||!f,onClick:f,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(I==="installing"?"settings.updateInstallingShort":I==="downloading"?"settings.desktopUpdateDownloadingShort":I==="checking"?"settings.updateCheckingShort":I==="current"||I==="error"?"settings.desktopUpdateCheckAgain":"settings.desktopUpdateCheck")})]}),d]})}function V$({quality:e}){const{locale:t}=Hr(),r=(d,f)=>t==="zh"?d:f,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(([f,m])=>s.jsxs(_.Fragment,{children:[s.jsx("dt",{children:f}),s.jsx("dd",{className:"text-right text-foreground break-all",children:m})]},f))}),l=(d,f)=>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}),f]});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 q$({backendSessionId:e}){const{locale:t}=Hr(),r=t==="zh",[n,a]=_.useState(null),[c,l]=_.useState(!1);_.useEffect(()=>{if(a(null),!c||!e)return;const y=()=>a(W9(e));y();const w=setInterval(y,1e3);return document.addEventListener("visibilitychange",y),()=>{clearInterval(w),document.removeEventListener("visibilitychange",y)}},[e,c]);const d=n?.diagnostics,f=n?.rtt,m=n?.connected?n.waiting?r?"等待响应…":"Waiting for reply…":f==null?r?"测量中…":"Measuring…":`${f} ms · ${f<150?r?"流畅":"Low latency":f<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||f!=null&&f>=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(V$,{quality:n})]})]})]})}const Ey={"startup-failure":"settings.serverHealthEventStartupFailure",crash:"settings.serverHealthEventCrash","crash-native":"settings.serverHealthEventCrashNative",killed:"settings.serverHealthEventKilled",wedge:"settings.serverHealthEventWedge","port-conflict":"settings.serverHealthEventPortConflict","gave-up":"settings.serverHealthEventGaveUp","exit-zero-unexpected":"settings.serverHealthEventExitZero","terminated-externally":"settings.serverHealthEventTerminated","supervisor-lost":"settings.serverHealthEventSupervisorLost","uncaught-exception":"settings.serverHealthEventUncaughtException","unhandled-rejection":"settings.serverHealthEventUnhandledRejection","exit-nonzero":"settings.serverHealthEventExitNonzero"};function Y$(e){return e<1e3?`${e}ms`:e<6e4?`${Math.round(e/1e3)}s`:e<36e5?`${Math.round(e/6e4)}m`:`${Math.round(e/36e5)}h`}function Z$({state:e,onDismiss:t}){const{t:r}=Hr(),[n,a]=b.useState(!1),[c,l]=b.useState(!1),d=b.useRef(!1),f=b.useRef(!0);b.useEffect(()=>(f.current=!0,()=>{f.current=!1}),[]),b.useEffect(()=>{e?.supervised&&(d.current=!1,a(!1),l(!1))},[e?.supervised]),b.useEffect(()=>{if(!n)return;const F=window.setTimeout(()=>{d.current=!1,a(!1),l(!0)},45e3);return()=>window.clearTimeout(F)},[n]);const m=async()=>{if(!d.current){d.current=!0,l(!1),a(!0);try{await G9()}catch{if(!f.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,T=e.supervised&&e.supervisor?.alive&&e.supervisor.phase==="running",S=y?r("settings.serverHealthGaveUp",{count:e.supervisor?.consecutiveCrashes??0}):w?r("settings.serverHealthSupervisorLost"):e.supervised?r("settings.serverHealthSupervised"):r("settings.serverHealthUnsupervised"),I=x?r(Ey[x.event]??"settings.serverHealthUnknownEvent"):"",N=x?.causeEvent?r(Ey[x.causeEvent]??"settings.serverHealthUnknownEvent"):"",B=x?[new Date(x.at).toLocaleString(),x.uptimeMs!==null?r("settings.serverHealthUptime",{duration:Y$(x.uptimeMs)}):null,x.signal?`signal ${x.signal}`:null,x.exitCode!==null?`exit ${x.exitCode}`:null].filter(Boolean).join(" · "):"";return s.jsxs("section",{className:"mt-3 overflow-hidden rounded-xl bg-surface-2","aria-labelledby":"server-health-title",children:[s.jsx("div",{id:"server-health-title",className:"px-3 pt-3 text-[12px] font-semibold text-foreground",children:r("settings.serverHealthTitle")}),s.jsxs("div",{className:"flex items-start justify-between gap-3 px-3 py-3",children:[s.jsxs("div",{className:"flex min-w-0 items-start gap-2.5",children:[s.jsx("span",{className:`mt-0.5 inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${v?"bg-destructive/15 text-destructive":"bg-primary/15 text-primary"}`,children:v?s.jsx(OS,{size:15}):s.jsx($S,{size:15})}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12px] font-medium text-foreground",children:S}),s.jsx("div",{className:"mt-0.5 text-[10px] leading-relaxed text-muted-foreground",children:x?`${r(T?"settings.serverHealthHistory":"settings.serverHealthLastIncident")}: ${I}${N?` · ${N}`:""}`:r("settings.serverHealthClean")}),x&&T&&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 K$=()=>()=>{},X$=()=>1/0;function J$(){const{t:e}=Hr(),t=b.useId(),r=Vo(),n=b.useSyncExternalStore(r?.subscribe??K$,r?.retentionLimit??X$);if(!r)return null;const a=V9+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 J1="mobile-session-destroy";function eU(e,t){return t&&e.type==="session"&&e.destination?.droppableId===J1}const Na="termdock-program-rules-cache",Zh="termdock-toolbar-presets-cache",l0="termdock-settings-cache",Ny="termdock-color-theme",Ry="termdock:right-sidebar:file-preview-open-by-session:v2",c0="termdock:running-session-button-enabled:v1",u0="termdock:attention-button-enabled:v1",tU=60,My=320,jy=420,Go=8;function Dy(e,t,r){return Math.min(Math.max(e,t),r)}function By(e){if(typeof window>"u")return{left:Go,top:Go};const t=window.innerWidth/2,r=Math.min(64,window.innerHeight/4),n=e?.x??t,a=e?.y??r,c=Math.max(Go,window.innerWidth-My-Go),l=Math.max(Go,window.innerHeight-jy-Go);return{left:Dy(n+Go,Go,c),top:Dy(a+Go,Go,l),width:My,maxHeight:`min(${jy}px, calc(100vh - ${Go*2}px))`}}function rU(e){return e==="dark"||e==="light"}function nU(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 t1(e){const t=Object.entries(e).filter(([r,n])=>r&&Number.isFinite(n.updatedAt)).sort(([,r],[,n])=>n.updatedAt-r.updatedAt).slice(0,tU);return Object.fromEntries(t)}function sU(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 iU(e){return typeof e=="object"&&e!==null&&typeof e.version=="number"&&Array.isArray(e.presets)}function aU(e,t){const r=D0(),n=new Set(FE()),a=Array.isArray(e)?e:[],c=Wu(a),l=t<p0;if(c.length===0)return r;if(l){const f=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=f.get(w.id),T=m.get(w.id);return v?{...w,rowLayout:v.rowLayout,showOnDesktop:typeof T?.showOnDesktop=="boolean"?T.showOnDesktop:w.showOnDesktop}:w}),...x]}const d=new Set(c.map(f=>f.id));return[...c,...r.filter(f=>!d.has(f.id))]}function oU(e){return typeof e=="object"&&e!==null&&typeof e.preventSleep=="boolean"&&typeof e.networkAvailable=="boolean"}const lU={name:"",source:"auto",hostname:"",fallbackHostname:"",url:"",fallbackUrl:"",onboardingUrl:null,status:"disabled",reason:null,httpsEnabled:!1,caAvailable:!1,lanAddresses:[],interfaces:[]},vp="__termdockOverlay",wp="__termdockBaseAnchor",Ap="__termdockBaseGuard",cU=3,Qy=250,uU="termdock-notification-target-v1",Py="/__termdock-notification-target",Oy=3e4;function dU(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 Du(e){if(!e||typeof e!="object")return null;const t=e[vp];return dU(t)?t:null}function Jg(e){return e&&typeof e=="object"?{...e}:{}}function L4(e){const t=Jg(e);return delete t[vp],t}function hU(e){const t=L4(e);return delete t[Ap],{...t,[wp]:!0}}function fU(){typeof window>"u"||window.history.pushState({...L4(window.history.state),[wp]:!0,[Ap]:!0},"",window.location.href)}function I4(){for(let e=0;e<cU;e+=1)fU()}function Kh(){typeof window>"u"||(window.history.replaceState(hU(window.history.state),"",window.location.href),I4())}function d0(e){typeof window>"u"||window.history.pushState({...Jg(window.history.state),[wp]:!0,[vp]:e,[Ap]:!1},"",window.location.href)}function pU(e){typeof window>"u"||window.history.replaceState({...Jg(window.history.state),[wp]:!0,[vp]:e,[Ap]:!1},"",window.location.href)}const E4=["bash","zsh","fish","sh","dash","ksh","tcsh","csh","nu"];let Ra=new Set(E4);function Fy(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 mU(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 $y(e,t){return s.jsx(pO,{sessionMode:e,state:t})}function gU(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 xU=_.lazy(()=>Vc(()=>import("./CollaborationMainWorkspace-CYpn4j_x.js"),__vite__mapDeps([18,1,2,3,4,5,8,9,15,13])));async function N4(e,t){return lg(e,t)}function bU(){const{t:e,locale:t,setLocale:r}=Hr(),n="env(safe-area-inset-top, 0px)",a="env(safe-area-inset-bottom, 0px)";q9();const c=_.useMemo(()=>typeof window>"u"?!1:/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,[]),[l,d]=_.useState(!1),[f,m]=_.useState(()=>Rc(Ny,rU)??"dark"),x=_.useRef(Rc(l0,oU)).current,[y,w]=_.useState(x?.preventSleep??!1),[v,T]=_.useState(x?.networkAvailable??!0),[S,I]=_.useState(Y9),[N,B]=_.useState(Z9),[F,P]=_.useState(K9),[$,ee]=_.useState(X9),[Z,V]=_.useState(Fp),[de,pe]=_.useState(x?.localAccess??lU),[J,Re]=_.useState(x?.localAccess?.name??""),[Xe,q]=_.useState(!1),[ve,qe]=_.useState(null),[ce,ye]=_.useState(null),[Te,Fe]=_.useState(null),[se,De]=_.useState(!1),_e=b.useRef({busy:!1}),Me=b.useRef(0),Je=b.useRef(Te?.latestVersion);Je.current=Te?.latestVersion;const[Ne,ae]=b.useState(null);b.useEffect(()=>{const C=()=>{Me.current++};for(const Q of["pagehide","auth:unauthorized",$u])window.addEventListener(Q,C);return()=>{C();for(const Q of["pagehide","auth:unauthorized",$u])window.removeEventListener(Q,C)}},[]);const[ze,at]=_.useState(null),ut=_.useMemo(()=>ea(),[]),me=!!(ut?.desktopUpdateState&&ut.checkDesktopUpdate&&ut.installDesktopUpdate),[dt,ft]=_.useState(null),[Se,We]=_.useState(null),[Le,z]=_.useState(!1),ie=b.useRef({busy:!1}),ge=b.useRef(Se);ge.current=Se;const[Ge,rt]=_.useState(null),[vt,Yt]=_.useState(!1),[Ut,Nt]=_.useState(()=>t1(Rc(Ry,nU)??{})),[ir,Mt]=_.useState(0),[Xt,Bt]=_.useState(!1),[Wt,xe]=_.useState(0),[et,ot]=_.useState(!1),[Et,K]=_.useState(0),[xt,rr]=_.useState(!1),[$e,Dr]=_.useState(0),Ce=_.useRef(null),[St,Ot]=_.useState({}),{terminalSettings:tr,updateTerminalSettings:ct}=xQ(),Ct=tr.fontSize,or=tr.rendererMode,[Cr,Ir]=_.useState(!1),$r=_.useRef(J9()).current,[Tt,Ft]=b.useState(()=>$r.sessions.map(C=>({id:C.sessionId,name:C.name,customName:C.customName,mode:C.mode,tmuxSessionName:C.tmuxSessionName}))),we=Pi(C=>C.groupId);_.useEffect(()=>{const C=()=>Pi.getState().terminal();return window.addEventListener("switch-terminal-session",C),()=>window.removeEventListener("switch-terminal-session",C)},[]);const[wt,it]=_.useState($r.activeSessionId),[bt,An]=_.useState(!1);_.useEffect(()=>{bt&&eA({rendered:!0})},[bt]);const[xn,rn]=_.useState(null),[Oe,_t]=_.useState(null),[mt,Zt]=_.useState([]),[$t,wr]=b.useState(()=>{const C=Vr.getState();return $r.sessions.forEach(Q=>{Q.backendSessionId&&C.setTerminalSession(Q.sessionId,{sessionId:Q.backendSessionId,cols:80,rows:24,mode:Q.mode,tmuxSessionName:Q.tmuxSessionName}),Q.activeProgram!=null&&C.setSessionActiveProgram(Q.sessionId,Q.activeProgram),Q.cwd!=null&&C.setSessionCwd(Q.sessionId,Q.cwd),Q.shellTitle!=null&&C.setSessionShellTitle(Q.sessionId,Q.shellTitle)}),Gu("session-chrome-hydrated"),Fy(Vr.getState().sessions)});b.useEffect(()=>{!ut||!Cr||Promise.all([ut.snapshot(),ut.desktopUpdateState?.()??Promise.resolve(null)]).then(([C,Q])=>{ft(C),We(Q)}).catch(C=>rt(C instanceof Error?C.message:String(C)))},[ut,Cr]),b.useEffect(()=>{ut?.onDesktopUpdateState&&ut.onDesktopUpdateState(We)},[ut]),b.useEffect(()=>Vr.subscribe(C=>{const Q=Fy(C.sessions);wr(he=>mU(he,Q)?he:Q)}),[]);const Tn=b.useCallback(async(C,Q)=>{_t(null),rn({sessionId:C,status:"submitting",error:null});try{await tA(Q),rn(he=>he?.sessionId===C?{...he,status:"waiting",error:null}:he)}catch(he){const kt=(he&&typeof he=="object"&&"code"in he?String(he.code??""):"")==="AGENT_SESSION_ACTIVE_ELSEWHERE"?e("tab.resumeAgentConflict"):he instanceof Error&&/busy/i.test(he.message)?e("tab.resumeAgentBusy"):e("tab.resumeAgentFailed");rn(Kt=>Kt?.sessionId===C?{...Kt,error:kt}:Kt),_t({tone:"error",message:kt})}},[e]);b.useEffect(()=>{if(!xn||xn.status!=="waiting")return;const C=$t.get(xn.sessionId);if(!C||C.agentResumeRecovered||C.agentStatus===null&&!C.agent)return;const Q=C.agent?.displayName??"Agent";rn(null),_t({tone:"success",message:e("tab.resumeAgentSuccess",{agent:Q})})},[xn,$t,e]),b.useEffect(()=>{if(!xn||xn.status!=="waiting"||xn.error)return;const C=xn.sessionId,Q=window.setTimeout(()=>{const he=e("tab.resumeAgentTimeout");rn(lt=>lt?.sessionId===C&<.status==="waiting"?{...lt,error:he}:lt),_t({tone:"error",message:he})},15e3);return()=>window.clearTimeout(Q)},[xn,e]),b.useEffect(()=>{if(Oe?.tone!=="success")return;const C=window.setTimeout(()=>_t(null),3200);return()=>window.clearTimeout(C)},[Oe]),b.useEffect(()=>{let C=!1;rA().then(he=>{C||Fe(he)}).catch(()=>{}),nA().then(he=>{C||at(he)}).catch(()=>{});const Q=Rx(he=>{C||(he.type==="update-state"?Fe(he.state):he.type==="server-health"&&at(he.state))});return()=>{C=!0,Q()}},[]);const Dn=b.useCallback(async()=>{try{at(await sA())}catch(C){o1(C instanceof Error?C.message:String(C))}},[]),yn=b.useCallback(async()=>{const C=Te?.latestVersion;if(!C||se)return;const Q=Me.current,he=Ki(),lt=wl(),kt=()=>Q===Me.current&&he===Ki()&<===wl()&&!lt?.closed&&Je.current===C,Kt=ut?.confirmationUI==="page-v1"&&typeof ut.confirm=="function";ae(null),await N4(_e.current,{current:kt,submit:kA,apply:Fe,pending:De,expiredMessage:t==="zh"?"连接已变化,请重新确认。":"Connection changed. Please confirm again.",confirm:()=>Kt?ut.confirm({title:e("sidebar.updateRestart"),message:e("sidebar.updateRestartConfirm",{version:C}),confirmLabel:e("sidebar.updateRestart"),cancelLabel:e("common.cancel")}):window.confirm(e("sidebar.updateRestartConfirm",{version:C})),failure:Mr=>{Kt?ae(Mr):window.alert(Mr)}})},[Te?.latestVersion,e,se,ut,t]),un=b.useCallback(async()=>{if(!se){De(!0);try{Fe(await iA())}catch(C){o1(C instanceof Error?C.message:String(C))}finally{De(!1)}}},[se]),Cn=b.useCallback(async()=>{if(!(!ut?.checkDesktopUpdate||Le)){z(!0);try{We(await ut.checkDesktopUpdate())}catch(C){rt(C instanceof Error?C.message:String(C))}finally{z(!1)}}},[ut,Le]),Ur=b.useCallback(async()=>{const C=Se;if(!ut?.installDesktopUpdate||Le||C?.status!=="ready")return;const Q=Me.current,he=Ki(),lt=wl(),kt=()=>Q===Me.current&&C===ge.current&&C.status==="ready"&&he===Ki()&<===wl()&&!lt?.closed;await lg(ie.current,{current:kt,confirm:()=>y3({title:e("settings.desktopUpdateRestartConfirm"),message:e("settings.desktopUpdateRestartConfirm"),confirmLabel:e("sidebar.updateRestart"),cancelLabel:e("common.cancel")}),submit:async()=>{if(!kt())throw new Error("Desktop update context changed");return ut.installDesktopUpdate()},apply:We,pending:z,failure:rt,expiredMessage:t==="zh"?"连接已变化,请重新确认。":"Connection changed. Please confirm again."})},[ut,Le,Se,e,t]);b.useEffect(()=>{document.documentElement.dataset.theme=f,aA(f),qn(Ny,f)},[f]),b.useEffect(()=>{qn(Ry,t1(Ut))},[Ut]);const ne=Vt(C=>C.leftOpen),Ze=Vt(C=>C.rightOpen),Dt=Vt(C=>C.leftPinned),ur=Vt(C=>C.leftSidebarWidth),Pr=Vt(C=>C.rightPinned),qr=Vt(C=>C.rightSidebarWidth),sn=Vt(C=>C.rootPath),Nr=Vt(C=>C.contextKey),Wr=Vt(C=>C.selectedFilePath),_n=Vt(C=>C.groupByFolder),en=kf(C=>C.collaborationGroups),Fr=Vt(C=>C.collapsedGroups),Kr=Vt(C=>C.toggleGroupCollapsed),[gr,an]=b.useState(()=>typeof window>"u"?!0:window.matchMedia("(min-width: 1024px)").matches),[Xr,dn]=b.useState(()=>typeof window>"u"?1024:window.innerWidth),[Rr,zn]=b.useState(()=>typeof window>"u"?!1:window.matchMedia("(orientation: landscape)").matches),[pn,Gr]=b.useState([]),[zr,Y]=b.useState({available:!0,version:null,reason:null}),[Be,Qt]=b.useState(!1),[er,nr]=b.useState(null),[Or,kr]=b.useState(null),[Zn,ys]=b.useState(null),[ss,Hn]=b.useState(null),[hn,Qn]=b.useState(null),[Xn,fn]=b.useState(null),[cr,is]=b.useState(null),[,tn]=b.useState(0),[xr,vr]=b.useState(null),[br,us]=b.useState(null),[Bn,vs]=b.useState(null),[Bs,Ls]=b.useState(!1),[Qr,yr]=b.useState(()=>Rc(c0,C=>typeof C=="boolean")??!1),Pn=b.useCallback(async C=>{const Q=Qr;yr(C),qn(c0,C);try{const he=await ja({runningSessionButtonEnabled:C});yr(he.runningSessionButtonEnabled),qn(c0,he.runningSessionButtonEnabled)}catch{yr(Q),qn(c0,Q)}},[Qr]),[Jn,es]=b.useState(()=>Rc(u0,C=>typeof C=="boolean")??!0),oi=b.useCallback(async C=>{const Q=Jn;es(C),qn(u0,C);try{const he=await ja({attentionButtonEnabled:C});es(he.attentionButtonEnabled),qn(u0,he.attentionButtonEnabled)}catch{es(Q),qn(u0,Q)}},[Jn]),[W,Ie]=b.useState(null),Ye=b.useCallback(C=>{Ie(C)},[]),nt=b.useRef(!1),[st,yt]=b.useState(null),Pt=_.useRef(null),H=b.useCallback(C=>{const Q=Tt.find(he=>he.id===C);Q&&(Pt.current={id:C,target:Ki(),client:wl(),backend:Vr.getState().sessions.get(C)?.terminalSessionId??null,mode:Q.mode,tmux:Q.tmuxSessionName},yt(C))},[Tt]),ue=b.useCallback(()=>{const C=Pt.current,Q=C&&Tt.find(he=>he.id===C.id);return!!C&&!C.client?.closed&&TQ(C,Q?{id:Q.id,target:Ki(),client:wl(),backend:Vr.getState().sessions.get(Q.id)?.terminalSessionId??null,mode:Q.mode,tmux:Q.tmuxSessionName}:null)},[Tt]),[R,U]=b.useState(null),X=_.useRef(null),be=_.useRef(!1),Ee=_.useRef(null),Ve=_.useRef(!1),ht=b.useCallback(()=>{fn(null),is(null)},[]),Qe=_.useRef(typeof window>"u"?null:new URLSearchParams(window.location.search).get("session")),[ar,sr]=_.useState(Qe.current),[It,_r]=_.useState(!0),on=_.useRef(Qe.current),bn=_.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)"),Q=()=>{an(C.matches),dn(window.innerWidth)};return Q(),C.addEventListener("change",Q),window.addEventListener("resize",Q),()=>{C.removeEventListener("change",Q),window.removeEventListener("resize",Q)}},[]),b.useEffect(()=>{if(typeof window>"u")return;const C=window.matchMedia("(orientation: landscape)"),Q=()=>zn(C.matches);return Q(),C.addEventListener("change",Q),()=>C.removeEventListener("change",Q)},[]);const Jr=_.useMemo(()=>wt?mt.find(C=>C.sessionIds.includes(wt))??null:null,[wt,mt]),mn=Jr?.id??null,dr=Jr?.sessionIds[0]??wt,pr=_.useRef([]);_.useLayoutEffect(()=>{const C=pr.current;if(pr.current=mt,C.length===0)return;const Q=new Set(mt.flatMap(he=>he.sessionIds));for(const he of C){const lt=he.sessionIds.filter(kt=>!Q.has(kt)).map(kt=>({sessionId:kt,rootPath:Vr.getState().sessions.get(kt)?.cwd??null}));lt.length>0&&Vt.getState().inheritRightSidebarStateFromSplitWorkspace(he.id,lt)}},[mt]),_.useLayoutEffect(()=>((()=>{const Q=dr?Vr.getState().sessions.get(dr)?.cwd??null:null;Vt.getState().setRootPath(Q,dr,mn)})(),Vr.subscribe((Q,he)=>{const lt=dr?Q.sessions.get(dr)?.cwd??null:null,kt=dr?he.sessions.get(dr)?.cwd??null:null;lt!==kt&&Vt.getState().setRootPath(lt,dr,mn)})),[mn,dr]);const fs=_.useRef(T3(window.location.search)??TC(Ki()?.targetPeerId)),[ws,Ss]=_.useState("");_.useEffect(()=>{const C=fs.current;if(!C)return;if(C.peerId&&C.peerId!==Ki()?.targetPeerId){const lt=oA().find(kt=>kt.targetPeerId===C.peerId);if(lt&&Vo()){try{AC(C)}catch{Ss(t==="zh"?"无法在此浏览器打开架构链接。":"Cannot open this architecture link in this browser.");return}if(lA(lt)){fs.current=null;const kt=new URL(window.location.href);kt.searchParams.delete("architecture"),window.history.replaceState(window.history.state,"",kt);return}}Ss(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}Ss("");try{sessionStorage.setItem(`termdock.architecture.selection:${C.root}`,C.file)}catch{}const Q=Vt.getState();Q.setRootPath(C.root,dr,mn),Q.setRightTab("architecture"),Q.openRight();const he=new URL(window.location.href);he.searchParams.delete("architecture"),window.history.replaceState(window.history.state,"",he),dr&&(fs.current=null)},[dr,mn,t]);const Fi=gr||Rr,Gl=Xr*.95,As=Fi?Math.min(Math.max(Xr*.22,280),340):Math.min(Xr*.86,380),Is=wt&&sn?`${wt}\0${sn}`:"",li=!!(Is&&Wr&&Ut[Is]),Aa=b.useCallback(C=>{Is&&(C&&!Vt.getState().selectedFilePath||Nt(Q=>{if(!!Q[Is]===C)return Q;if(C)return t1({...Q,[Is]:{updatedAt:Date.now()}});const lt={...Q};return delete lt[Is],lt}))},[Is]);b.useEffect(()=>{CQ(Is,Nr,Wr)&&Nt(C=>{if(!C[Is])return C;const Q={...C};return delete Q[Is],Q})},[Is,Nr,Wr]);const Wn=xt?"markdown-image-lightbox":et?"markdown-outline":Xt?"right-sidebar-repo-picker":Ze&&li?"right-sidebar-file-preview":Cr?"settings":Ze&&!(Pr&&gr)?"right-sidebar":ne&&!(Dt&&gr)?"left-sidebar":null,as=_.useRef(Wn),Es=_.useRef(Wn),eo=_.useRef(!1),zs=_.useRef(!1),Tl=b.useCallback(()=>{if(typeof window>"u")return;const C=window.matchMedia("(hover: hover) and (pointer: fine)").matches;!gr||!C||navigator.maxTouchPoints>0||window.setTimeout(()=>{window.dispatchEvent(new CustomEvent("focus-active-terminal-session"))},0)},[gr]),Da=b.useCallback(C=>{if(C==="markdown-image-lightbox"){rr(!1),Dr(Q=>Q+1);return}if(C==="markdown-outline"){ot(!1),K(Q=>Q+1);return}if(C==="right-sidebar-file-preview"){ot(!1),K(Q=>Q+1),Aa(!1),Mt(Q=>Q+1);return}if(C==="right-sidebar-repo-picker"){Bt(!1),xe(Q=>Q+1);return}if(C==="settings"){Ir(!1),Fa(!1),Wi(!1),jt(!1);return}if(C==="left-sidebar"){Vt.getState().closeLeft();return}ot(!1),K(Q=>Q+1),Bt(!1),xe(Q=>Q+1),rr(!1),Dr(Q=>Q+1),Vt.getState().closeRight()},[Aa]),On=b.useCallback(C=>{if(!c&&typeof window<"u"&&as.current===C&&Du(window.history.state)===C){window.history.back();return}Da(C)},[Da,c]),ki=b.useCallback(()=>{Ir(!1);const C=Vt.getState();C.closeRight(),C.openLeft()},[]),Ba=b.useCallback(()=>{Ir(!1);const C=Vt.getState();C.closeLeft(),C.openRight()},[]),Eo=b.useCallback(()=>{Ir(!1);const C=Vt.getState();C.closeLeft(),C.openRight(),C.setRightTab("files"),C.openRightSearch()},[]),ci=b.useCallback(()=>{const C=Vt.getState();if(C.leftPinned){C.setLeftPinned(!1),C.closeLeft();return}if(ne){On("left-sidebar");return}ki()},[ki,On,ne]),Fn=b.useCallback(()=>{const C=Vt.getState();C.leftPinned?(C.setLeftPinned(!1),C.openLeft()):(C.setLeftPinned(!0),C.openLeft())},[]),Xs=b.useCallback(()=>{const C=Vt.getState();C.setLeftPinned(!1),C.closeLeft()},[]),os=b.useCallback(()=>{const C=Vt.getState();C.rightPinned?(C.setRightPinned(!1),C.openRight()):(C.setRightPinned(!0),C.openRight())},[]),Qa=b.useCallback(()=>{const C=Vt.getState();C.setRightPinned(!1),C.closeRight()},[]),ds=b.useRef(null),No=b.useRef(null);b.useEffect(()=>()=>No.current?.(),[]);const Ko=b.useCallback(C=>{if(C.button!==0||!ds.current)return;C.preventDefault(),No.current?.();const Q=Vt.getState();No.current=BF(ds.current,C.clientX,Q.leftSidebarWidth,he=>Math.min(Math.max(he,200),500),he=>Vt.getState().setLeftSidebarWidth(he))},[]),Ro=b.useRef(0),Ta=b.useRef(0),ra=b.useRef(null),Ac=b.useCallback(C=>{C.preventDefault(),Ro.current=C.clientX;const Q=Vt.getState(),he=Q.leftPinned?Q.leftSidebarWidth:0;Ta.current=Jh(Q.rightSidebarWidth,window.innerWidth,he);const lt=Kt=>{ra.current===null&&(ra.current=requestAnimationFrame(()=>{ra.current=null;const Mr=Ro.current-Kt.clientX,Rn=Vt.getState(),Gn=Rn.leftPinned?Rn.leftSidebarWidth:0;Rn.setRightSidebarWidth(Jh(Ta.current+Mr,window.innerWidth,Gn))}))},kt=()=>{window.removeEventListener("mousemove",lt),window.removeEventListener("mouseup",kt),ra.current!==null&&(cancelAnimationFrame(ra.current),ra.current=null),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",window.addEventListener("mousemove",lt),window.addEventListener("mouseup",kt)},[]),Li=b.useCallback(()=>{const C=Vt.getState();if(C.rightPinned){C.setRightPinned(!1),C.closeRight();return}if(Ze){On("right-sidebar");return}Ba()},[Ba,On,Ze]),Sl=b.useCallback(()=>{!li&&!c&&typeof window<"u"&&as.current==="right-sidebar"&&Du(window.history.state)==="right-sidebar"&&(d0("right-sidebar-file-preview"),Es.current="right-sidebar-file-preview"),Aa(!0)},[li,c,Aa]),ql=b.useCallback(()=>{On("right-sidebar-file-preview")},[On]),ui=b.useCallback(()=>{!Xt&&!c&&typeof window<"u"&&as.current==="right-sidebar"&&Du(window.history.state)==="right-sidebar"&&(d0("right-sidebar-repo-picker"),Es.current="right-sidebar-repo-picker"),Bt(!0)},[Xt,c]),Js=b.useCallback(()=>{On("right-sidebar-repo-picker")},[On]),di=b.useCallback(()=>{!et&&!c&&typeof window<"u"&&as.current&&Du(window.history.state)===as.current&&(d0("markdown-outline"),Es.current="markdown-outline"),ot(!0)},[et,c]),Xo=b.useCallback(()=>{On("markdown-outline")},[On]),na=b.useCallback(()=>{!c&&typeof window<"u"&&as.current&&Du(window.history.state)===as.current&&(d0("markdown-image-lightbox"),Es.current="markdown-image-lightbox"),rr(!0)},[c]),Cs=b.useCallback(()=>{On("markdown-image-lightbox")},[On]),hi=b.useCallback(()=>{!c&&typeof window<"u"&&as.current&&Du(window.history.state)===as.current&&(pU("settings"),Es.current="settings"),Vt.getState().closeAll(),Ir(!0)},[c]),$i=b.useCallback(()=>{On("settings")},[On]);b.useEffect(()=>{if(!ut)return;const C=()=>hi();return window.addEventListener("termdock:open-settings",C),()=>window.removeEventListener("termdock:open-settings",C)},[ut,hi]);const Jo=b.useCallback(()=>{Yt(!0),Ce.current!==null&&(window.clearTimeout(Ce.current),Ce.current=null)},[]),Ii=b.useCallback(()=>{Ce.current!==null&&(window.clearTimeout(Ce.current),Ce.current=null),Yt(!1),zs.current=!0,Kh(),zs.current},[]);b.useEffect(()=>()=>{Ce.current!==null&&window.clearTimeout(Ce.current)},[]),b.useEffect(()=>{c||Kh()},[c]),b.useEffect(()=>{if(typeof window>"u"||c)return;let C=null;const Q=()=>{C!==null&&(window.clearTimeout(C),C=null)},he=Rn=>{if(as.current,zs.current,as.current){as.current;return}!Rn?.force&&zs.current||(Rn?.userActivated&&(zs.current=!0),Kh(),zs.current,void 0)},lt=()=>{Q(),C=window.setTimeout(()=>{C=null,he({force:!0})},Qy)},kt=()=>{he({userActivated:!0})},Kt=()=>{lt()},Mr=()=>{document.visibilityState==="visible"&<()};return window.addEventListener("pointerdown",kt,{capture:!0,passive:!0}),window.addEventListener("touchstart",kt,{capture:!0,passive:!0}),window.addEventListener("keydown",kt,{capture:!0}),window.addEventListener("pageshow",Kt),document.addEventListener("visibilitychange",Mr),()=>{Q(),window.removeEventListener("pointerdown",kt,{capture:!0}),window.removeEventListener("touchstart",kt,{capture:!0}),window.removeEventListener("keydown",kt,{capture:!0}),window.removeEventListener("pageshow",Kt),document.removeEventListener("visibilitychange",Mr)}},[c]),b.useEffect(()=>{as.current=Wn},[Wn]),b.useEffect(()=>{if(typeof window>"u"||Wn||c)return;const C=window.setTimeout(()=>{as.current?(as.current,void 0):Kh()},Qy);return()=>window.clearTimeout(C)},[Wn,c]),b.useEffect(()=>{if(typeof window>"u"||c)return;const C=Es.current;eo.current,Wn&&Wn!==C&&!eo.current&&d0(Wn),!Wn&&C&&Tl(),Es.current=Wn,!Wn&&eo.current&&window.setTimeout(()=>{eo.current=!1},0)},[Wn,c,Tl]),b.useEffect(()=>{if(typeof window>"u"||c)return;const C=()=>{const Q=as.current;if(zs.current,!Q){zs.current=!1,zs.current,Jo(),I4();return}eo.current=!0,Da(Q)};return window.addEventListener("popstate",C),()=>window.removeEventListener("popstate",C)},[Da,Jo,c]),b.useEffect(()=>{const C=Q=>{const he=Q.metaKey||Q.ctrlKey;if(he&&Q.key==="b"&&!Q.shiftKey&&(Q.preventDefault(),ci()),he&&Q.shiftKey&&Q.key==="E"&&(Q.preventDefault(),Li()),he&&Q.shiftKey&&Q.key==="P"&&(Q.preventDefault(),Eo()),he&&!Q.shiftKey&&Q.altKey&&(Q.key==="ArrowLeft"||Q.key==="ArrowRight")){Q.preventDefault();const lt=Q.key==="ArrowRight"?"next":"prev";window.dispatchEvent(new CustomEvent("cycle-terminal-session",{detail:{direction:lt}}));return}if(he&&Q.shiftKey&&!Q.altKey&&(Q.code==="BracketLeft"||Q.code==="BracketRight")){Q.preventDefault();const lt=Q.code==="BracketRight"?"next":"prev";window.dispatchEvent(new CustomEvent("cycle-terminal-session",{detail:{direction:lt}}));return}};return document.addEventListener("keydown",C),()=>{document.removeEventListener("keydown",C)}},[ci,Li,Eo]);const Tc=b.useCallback(async()=>{q(!0),qe(null);try{const C=await ja({localAccess:{name:J}});pe(C.localAccess),Re(C.localAccess.name),qn(l0,{preventSleep:C.preventSleep,networkAvailable:C.networkAvailable,localAccess:C.localAccess})}catch(C){qe(C instanceof Error?C.message:"Failed to save local access name")}finally{q(!1)}},[J]),Sc=b.useCallback(async()=>{q(!0),qe(null);try{const C=await ja({localAccess:{reset:!0}});pe(C.localAccess),Re(C.localAccess.name),qn(l0,{preventSleep:C.preventSleep,networkAvailable:C.networkAvailable,localAccess:C.localAccess})}catch(C){qe(C instanceof Error?C.message:"Failed to reset local access name")}finally{q(!1)}},[]),el=b.useCallback(async(C,Q="url")=>{if(C)try{if(typeof navigator<"u"&&navigator.clipboard)await navigator.clipboard.writeText(C);else{const he=document.createElement("textarea");he.value=C,he.style.position="fixed",he.style.left="-9999px",document.body.appendChild(he),he.focus(),he.select(),document.execCommand("copy"),document.body.removeChild(he)}ye(Q),window.setTimeout(()=>ye(he=>he===Q?null:he),1600)}catch{ye(null)}},[]),Qs=b.useCallback(C=>{const Q=gU(Tt,C);Q.map(he=>he.id).join("\0")!==Tt.map(he=>he.id).join("\0")&&(Ft(Q),window.dispatchEvent(new CustomEvent("reorder-terminal-session",{detail:{sessionIds:Q.map(he=>he.id)}})))},[Tt]),Ei=b.useCallback(C=>{gr||C.type!=="session"||(nt.current=!1,Ls(!1),vs(C.draggableId))},[gr]),Ui=b.useCallback(C=>{if(gr||C.type!=="session")return;const Q=C.destination?.droppableId===J1;Q!==nt.current&&(nt.current=Q,Ls(Q),Q&&navigator.vibrate?.(20))},[gr]),zi=b.useCallback(C=>{const Q=eU(C,!gr);if(nt.current=!1,Ls(!1),vs(null),!Q)return!1;const he=Tt.find(kt=>kt.id===C.draggableId),lt=he?$t.get(he.id):null;return he&&ab({mode:he.mode,activeProgram:lt?.activeProgram??null,promptState:lt?.promptState??null,shellNames:Ra})?(U(null),H(he.id),ys(null)):he&&window.dispatchEvent(new CustomEvent("close-terminal-session",{detail:{sessionId:he.id,source:"other",closeMode:he.mode==="tmux"?"destroy":"auto"}})),!0},[gr,Tt,$t,H]),{groups:sa,arranged:ei}=_.useMemo(()=>Cf(Tt,C=>$t.get(C.id)?.cwd??null,_n,e("sidebar.ungrouped"),mt,en),[Tt,$t,_n,e,mt,en]),Pa=b.useCallback(C=>{zi(C)||!C.destination||C.source.index===C.destination.index||window.dispatchEvent(new CustomEvent("reorder-navigation-session",{detail:{sourceId:ei[C.source.index]?.id,targetId:ei[C.destination.index]?.id}}))},[zi,ei]),Hi=b.useCallback((C,Q)=>{const he=Q.trim();he&&window.dispatchEvent(new CustomEvent("rename-terminal-session",{detail:{sessionId:C,name:he}}))},[]),ls=b.useCallback(C=>{window.dispatchEvent(new CustomEvent("reset-terminal-session-name",{detail:{sessionId:C}}))},[]),{newSessionMode:gn,newSessionTmuxName:ia,userSelectedNewSessionMode:fi,setNewSessionMode:Oa}=vQ(),[aa,to]=b.useState(null),[pi,Fa]=_.useState(!1),[oa,Sa]=_.useState(!1),[mi,Wi]=_.useState(!1),[ps,Ca]=_.useState("idle"),ro=_.useRef(Rc(Zh,iU)).current,[Ps,no]=_.useState(()=>{const C=ro?.presets;if(C&&C.length>0){const Q=Wu(C);if(Q.length>0)return Q}return D0()}),[Cl,Yl]=_.useState(!1),[Mo,so]=_.useState("default"),oe=_.useRef(typeof ro?.updatedAt=="number"?ro.updatedAt:null),He=_.useRef(!1),[At,jt]=_.useState(!1),[tt,Rt]=_.useState(!1),L=_.useRef(Rc(Na,sU)).current,[D,O]=_.useState(L??[]),[G,Pe]=_.useState(L!==null),[ke,Ke]=_.useState(!1),gt=!we&&!Wn&&!oa&&!mi&&!pi&&!At&&!tt&&!Xn&&!st&&!aa,Lt=_.useCallback(C=>{const Q=typeof C.version=="number"?C.version:0,he=aU(Array.isArray(C.presets)?C.presets:[],Q);oe.current=typeof C.updatedAt=="number"?C.updatedAt:null,no(lt=>cA(lt,he)?lt:(He.current=!0,he)),qn(Zh,{version:p0,presets:he,updatedAt:oe.current??void 0})},[]);b.useEffect(()=>{const C=Q=>{if(Q.key!=="Escape"||Q.defaultPrevented||Q.isComposing||rg())return;if(oa){Q.preventDefault(),Sa(!1);return}if(mi){Q.preventDefault(),Wi(!1);return}if(pi){Q.preventDefault(),Fa(!1);return}if(At){Q.preventDefault(),jt(!1);return}if(tt){Q.preventDefault(),Rt(!1);return}if(Xn){Q.preventDefault(),ht();return}if(xr){Q.preventDefault(),Qn(null),vr(null);return}if(Cr){Q.preventDefault(),$i();return}if(Ze&&!(Pr&&gr)){Q.preventDefault(),On("right-sidebar");return}ne&&!(Dt&&gr)&&(Q.preventDefault(),On("left-sidebar"))};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[oa,mi,pi,At,Xn,ht,Cr,Ze,Pr,ne,Dt,gr,$i,On]),b.useEffect(()=>{Pe(!0)},[]);const[Jt,Yr]=_.useState({genericProgramNames:[],wrapperScriptNames:[],shellNames:E4}),[,En]=_.useState(!1),kn=_.useCallback(()=>uA().then(C=>{Yr(C),Ra=new Set(C.shellNames),En(!0)}).catch(()=>{}),[]);b.useEffect(()=>{kn()},[kn]),b.useEffect(()=>Rx(C=>{if(C.type==="config-updated"){if(C.key==="toolbar-presets"){Mx().then(Q=>Lt(Q)).catch(Q=>{console.warn("[toolbar-presets] Failed to refresh after remote update:",Q)});return}C.key==="program-detection"&&kn()}}),[Lt,kn]),b.useEffect(()=>{let C=!1;return(async()=>{try{const Q=await Mx();if(C)return;Lt(Q)}catch(Q){console.warn("[toolbar-presets] Failed to load from server:",Q)}finally{C||Yl(!0)}})(),()=>{C=!0}},[Lt]),b.useEffect(()=>{if(Cl){if(He.current){He.current=!1;return}qn(Zh,{version:p0,presets:Ps,updatedAt:oe.current??void 0}),dA({version:p0,presets:Ps,baseUpdatedAt:oe.current??void 0}).then(C=>{oe.current=typeof C.updatedAt=="number"?C.updatedAt:null,qn(Zh,{version:p0,presets:Ps,updatedAt:oe.current??void 0})}).catch(C=>{const Q=C instanceof Error&&"current"in C?C.current:null;Q&&typeof Q=="object"&&Lt(Q),console.warn("[toolbar-presets] Failed to save to server:",C)})}},[Lt,Ps,Cl]),b.useEffect(()=>{wc().then(C=>{w(Q=>Q===C.preventSleep?Q:C.preventSleep),T(Q=>Q===C.networkAvailable?Q:C.networkAvailable),pe(C.localAccess),Re(C.localAccess.name),yr(C.runningSessionButtonEnabled),qn(c0,C.runningSessionButtonEnabled),es(C.attentionButtonEnabled),qn(u0,C.attentionButtonEnabled),qn(l0,{preventSleep:C.preventSleep,networkAvailable:C.networkAvailable,localAccess:C.localAccess})}).catch(()=>{})},[]),b.useEffect(()=>{if(!S)return;const C=Fp();V(C),C!=="granted"&&(I(!1),gh(!1))},[S]),b.useEffect(()=>{if(!S)return;Id();const C=()=>{document.visibilityState==="visible"&&(Id(),SA())},Q=window.setInterval(()=>{Id()},360*60*1e3);return document.addEventListener("visibilitychange",C),window.addEventListener("focus",C),()=>{window.clearInterval(Q),document.removeEventListener("visibilitychange",C),window.removeEventListener("focus",C)}},[S]);const ms=b.useCallback(async()=>{if(S){I(!1),gh(!1),hA(),V(Fp());return}const C=await fA();if(V(C),C!=="granted"){I(!1),gh(!1);return}I(!0),gh(!0),await Id(!0,!0),Ca("idle")},[S]),Gi=b.useCallback(async()=>{Ca("checking"),await ea()?.prepareNotificationTest?.();const C=await pA({title:"Termdock",body:e("settings.notificationsTestBody"),tag:"termdock-notification-test",requireHidden:!1,data:{url:"/"}});Ca(C?"delivered":"failed")},[e]),Zr=b.useCallback(C=>{B(C),mA(C),$p()},[]),vn=b.useCallback(C=>{P(C),gA(C),$p()},[]),Os=b.useCallback(C=>{ee(C),xA(C),$p()},[]);b.useEffect(()=>{Ps.some(C=>C.id===Mo)||so(Ps[0]?.id??"default")},[Mo,Ps]),b.useEffect(()=>{if(!zr.available&&gn==="tmux"){Oa("shell",{userInitiated:!1});return}zr.available&&fi!=="shell"&&gn!=="tmux"&&Oa("tmux",{userInitiated:!1})},[gn,zr.available,fi,Oa]),b.useEffect(()=>{to(null)},[Cr,gn,zr.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),Ot(C)},[]);const Zl=b.useCallback(C=>{if(zi(C)||!C.destination)return;if(C.type==="group"){if(C.source.index===C.destination.index)return;Qs(b3(sa,C.source.index,C.destination.index));return}if(C.source.droppableId!==C.destination.droppableId||C.source.index===C.destination.index)return;const Q=C.source.droppableId.replace(/^group-sessions:/,""),he=sa.find(lt=>lt.key===Q);he&&window.dispatchEvent(new CustomEvent("reorder-navigation-session",{detail:{sourceId:he.sessions[C.source.index]?.id,targetId:he.sessions[C.destination.index]?.id}}))},[sa,Qs,zi]),Cc=_.useMemo(()=>ei.flatMap(C=>{const Q=$t.get(C.id);if(Q?.agentStatus!=="working")return[];const{primary:he,secondary:lt}=gl(C,Q?.activeProgram??null,Q?.cwd??null,Ra,Q?.shellTitle??null,Q?.promptState??null);return[{id:C.id,label:he,detail:lt}]}),[ei,$t]),Nn=wt?ei.findIndex(C=>C.id===wt):-1,_l=ei.length>0&&Nn>=0?`${Nn+1}/${ei.length}`:`${ei.length}`,ti=_.useMemo(()=>{let C=0;for(const Q of Tt){const he=$t.get(Q.id);(he?.agentStatus==="waiting"||he?.agentNeedsReview)&&(C+=1)}return{running:Cc.length,review:C}},[Cc.length,Tt,$t]),tl=_.useMemo(()=>ei.flatMap(C=>{const Q=$t.get(C.id);if(Q?.agentStatus!=="waiting"&&!Q?.agentNeedsReview)return[];const{primary:he}=gl(C,Q.activeProgram,Q.cwd,Ra,Q.shellTitle,Q.promptState);return[{id:Q.terminalSessionId??C.id,label:he,waiting:Q.agentStatus==="waiting"}]}),[ei,$t]);bA(ti.running,ti.review,tl);const $a=wt?Tt.find(C=>C.id===wt)??null:null,jo=$a?$t.get($a.id):void 0,uu=!!($a&&jo?.agentResumeRecovered&&jo.agentNativeSessionId&&jo.terminalSessionId),Ua=$a&&xn?.sessionId===$a.id?xn:null;_.useLayoutEffect(()=>{if(!It)return;const C=Ee.current;if(!C)return;const Q=!Ve.current;C.scrollIntoView({inline:"nearest",block:"nearest",behavior:Q?"auto":"smooth"}),Ve.current=!0,Q&&Gu("active-tab-positioned")},[wt,It]),b.useEffect(()=>{hn&&X.current&&(X.current.scrollIntoView({block:"nearest",inline:"nearest"}),X.current.focus(),X.current.select()),hn||(be.current=!1)},[hn]);const th=b.useCallback(C=>{window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:C}))},[]),gd=b.useCallback((C,Q)=>{is(Q??null),fn(C)},[]),Tp=Vg(),io=b.useCallback(C=>{if(!C)return;sr(C),bn.current&&Ma("info","PWA_NOTIFICATION_CLICK app-focus-request",{traceId:bn.current,requestedSessionId:C,activeSessionId:wt,sessions:Tt.map(he=>({id:he.id,terminalSessionId:$t.get(he.id)?.terminalSessionId??null}))}),yA(C);const Q=Tt.find(he=>he.id===C||$t.get(he.id)?.terminalSessionId===C);Q?(on.current=null,bn.current&&Ma("info","PWA_NOTIFICATION_CLICK app-focus-dispatch",{traceId:bn.current,requestedSessionId:C,targetSessionId:Q.id}),window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:Q.id}))):(on.current=C,bn.current&&Ma("info","PWA_NOTIFICATION_CLICK app-focus-pending",{traceId:bn.current,requestedSessionId:C}))},[wt,Tt,$t]);b.useEffect(()=>{if(typeof window>"u"||typeof caches>"u")return;let C=!1;const Q=async()=>{if(window.parent!==window&&Vo()){_r(!0);return}try{const lt=await caches.open(uU),kt=await lt.match(Py);if(!kt)return;await lt.delete(Py);const Kt=await kt.json();if(C)return;const Mr=typeof Kt.sessionId=="string"?Kt.sessionId:null,Rn=typeof Kt.traceId=="string"?Kt.traceId:null,Gn=typeof Kt.clickedAt=="number"?Kt.clickedAt:0,$n=Date.now()-Gn;Ma("info","PWA_NOTIFICATION_CLICK app-cache-consumed",{traceId:Rn,sessionId:Mr,ageMs:$n,valid:!!(Mr&&$n>=0&&$n<=Oy),visibilityState:document.visibilityState}),Mr&&$n>=0&&$n<=Oy&&(bn.current=Rn,typeof Kt.targetPeerId=="string"&&Kt.targetPeerId!==Ki()?.targetPeerId?Vo()?.focusSession(Kt.targetPeerId,Mr):io(Mr))}catch(lt){Ma("warn","PWA_NOTIFICATION_CLICK app-cache-failed",{error:lt instanceof Error?lt.message:String(lt)})}finally{C||_r(!0)}},he=()=>{document.visibilityState==="visible"&&Q()};return Q(),document.addEventListener("visibilitychange",he),window.addEventListener("pageshow",Q),()=>{C=!0,document.removeEventListener("visibilitychange",he),window.removeEventListener("pageshow",Q)}},[io]),b.useEffect(()=>{if(typeof window>"u")return;const C=new URLSearchParams(window.location.search),Q=C.get("session");if(!Q)return;Ma("info","PWA_NOTIFICATION_CLICK app-url-received",{traceId:bn.current,targetSessionId:Q,href:window.location.href,visibilityState:document.visibilityState});const he=C.get("service");he&&he!==Ki()?.targetPeerId?Vo()?.focusSession(he,Q):on.current=Q,C.delete("service"),C.delete("session"),C.delete("_notifTrace");const lt=C.toString(),kt=`${window.location.pathname}${lt?`?${lt}`:""}${window.location.hash}`;window.history.replaceState(window.history.state,"",kt)},[]),b.useEffect(()=>{if(typeof window>"u")return;const C=new URLSearchParams(window.location.search);if(C.get("_notif")!=="1")return;const Q=C.get("session");C.delete("_notif");const he=C.toString(),lt=`${window.location.pathname}${he?`?${he}`:""}${window.location.hash}`;if(window.history.replaceState(window.history.state,"",lt),window.parent!==window&&Vo())return;const kt=new BroadcastChannel("termdock:notif");let Kt=!1;const Mr=Gn=>{Gn.data?.type==="termdock:notif-pong"&&!Kt&&(Kt=!0,kt.close(),window.close())};kt.addEventListener("message",Mr),kt.postMessage({type:"termdock:notif-ping",sessionId:Q,targetPeerId:C.get("service")});const Rn=setTimeout(()=>{Kt||kt.close()},500);return()=>{clearTimeout(Rn),Kt||kt.close()}},[]),b.useEffect(()=>{if(typeof window>"u"||window.parent!==window&&Vo())return;const C=new BroadcastChannel("termdock:notif"),Q=he=>{he.data?.type==="termdock:notif-ping"&&(C.postMessage({type:"termdock:notif-pong"}),typeof he.data.sessionId=="string"&&(typeof he.data.targetPeerId=="string"&&he.data.targetPeerId!==Ki()?.targetPeerId?Vo()?.focusSession(he.data.targetPeerId,he.data.sessionId):io(he.data.sessionId)))};return C.addEventListener("message",Q),()=>C.close()},[io]),b.useEffect(()=>{if(typeof navigator>"u"||!("serviceWorker"in navigator))return;const C=Q=>{const he=Q.data;if(he&&he.type==="termdock:focus-session"&&typeof he.sessionId=="string"){if(typeof he.targetPeerId=="string"&&he.targetPeerId!==Ki()?.targetPeerId){Vo()?.focusSession(he.targetPeerId,he.sessionId)&&Q.ports[0]?.postMessage({type:"termdock:focus-session-ack"});return}Q.ports[0]?.postMessage({type:"termdock:focus-session-ack"}),io(he.sessionId)}else he?.type==="termdock:push-subscription-changed"?Id(!0):he?.type};return navigator.serviceWorker.addEventListener("message",C),()=>navigator.serviceWorker.removeEventListener("message",C)},[io]),b.useEffect(()=>{const C=Q=>{const he=Q.detail;typeof he=="string"&&io(he)};return window.addEventListener("termdock:focus-session",C),()=>window.removeEventListener("termdock:focus-session",C)},[io]),b.useEffect(()=>{const C=()=>{const Q=CA(Ki()?.targetPeerId);Q&&io(Q)};return C(),window.addEventListener("termdock:workspace-session",C),()=>window.removeEventListener("termdock:workspace-session",C)},[io]),b.useEffect(()=>{const C=on.current;if(!C)return;const Q=Tt.find(he=>he.id===C||$t.get(he.id)?.terminalSessionId===C);Q?(on.current=null,bn.current&&Ma("info","PWA_NOTIFICATION_CLICK app-pending-dispatch",{traceId:bn.current,requestedSessionId:C,targetSessionId:Q.id,activeSessionId:wt}),window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:Q.id}))):bn.current&&Ma("info","PWA_NOTIFICATION_CLICK app-pending-unmatched",{traceId:bn.current,requestedSessionId:C,activeSessionId:wt,sessions:Tt.map(he=>({id:he.id,terminalSessionId:$t.get(he.id)?.terminalSessionId??null}))})},[wt,Tt,$t]);const za=_.useMemo(()=>{const C=[];for(const Q of Tt){const he=$t.get(Q.id);(he?.agentStatus==="waiting"||he?.agentNeedsReview)&&C.push(Q.id)}return C},[Tt,$t]),rl=b.useCallback(()=>{if(za.length===0)return;wt&&Vr.getState().clearAgentNeedsReview(wt);const C=wt?Tt.findIndex(he=>he.id===wt):-1,Q=za.find(he=>Tt.findIndex(lt=>lt.id===he)>C)??za[0];Q&&window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:Q}))},[za,Tt,wt]),_c=b.useCallback(()=>{if(za.length===0)return;wt&&Vr.getState().clearAgentNeedsReview(wt);const C=wt?Tt.findIndex(he=>he.id===wt):Tt.length,Q=[...za].reverse().find(he=>Tt.findIndex(lt=>lt.id===he)<C)??za[za.length-1];Q&&window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:Q}))},[za,Tt,wt]);b.useEffect(()=>{const C=Q=>{!Q.altKey||!Q.shiftKey||Q.metaKey||Q.ctrlKey||Q.key!=="ArrowUp"&&Q.key!=="ArrowDown"||(Q.preventDefault(),Q.key==="ArrowUp"?_c():rl())};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[rl,_c]);const rh=b.useCallback(async C=>{const he=Vr.getState().sessions.get(C)?.cwd;if(he)try{await navigator.clipboard?.writeText(he),us(he),window.setTimeout(()=>{us(lt=>lt===he?null:lt)},1400)}catch{}},[]),du=b.useCallback(C=>{Ft(C.sessions),it(C.activeSessionId),Zt(C.splitWorkspaces),Vr.getState().setActiveSessionId(C.activeSessionId)},[]),Sp=b.useCallback(()=>{An(!0)},[]),xd=b.useCallback(()=>{An(!0),window.requestAnimationFrame(()=>{window.dispatchEvent(new Event("termdock:initial-viewport-presented"))})},[]);b.useEffect(()=>{if(!ar||!wt)return;Tt.find(Q=>Q.id===ar||$t.get(Q.id)?.terminalSessionId===ar)?.id===wt&&sr(null)},[wt,ar,Tt,$t]);const hu=b.useRef(!1),[fu,nh]=b.useState(!1),Do=b.useCallback(C=>{const Q=!C?.onResult;if(Q&&hu.current)return;Q&&(hu.current=!0,nh(!0));const he=C?.mode??gn,lt=he==="tmux"&&(C?.tmuxSessionName?.trim()||ia.trim())||void 0,kt=C?.cwd||(wt?Vr.getState().sessions.get(wt)?.cwd:void 0);window.dispatchEvent(new CustomEvent("new-terminal-session",{detail:{mode:he,tmuxSessionName:lt,cwd:kt,command:C?.command,shouldActivate:C?.shouldActivate,onResult:C?.onResult??(Kt=>{hu.current=!1,nh(!1),Kt.ok||_t({tone:"error",message:e(l1(Kt.error))})})}}))},[gn,ia,wt,e]),nl=b.useCallback(async()=>{Qt(!0);try{const C=await r1();if(Y(C),!C.available){Gr([]);return}const Q=await n1();Gr(Q)}catch{Y({available:!1,version:null,reason:"tmux integration is unavailable with the current server build."}),Gr([])}finally{Qt(!1)}},[]),pu=b.useCallback(async C=>{const{cleanedSessions:Q}=await qy(C);for(const he of Q)window.dispatchEvent(new CustomEvent("close-terminal-session-by-backend",{detail:he}));await nl()},[nl]),Cp=b.useCallback(async C=>{kr(C),ys(null);try{await pu(C),nr(null)}catch(Q){ys(Q instanceof Error?Q.message:"Failed to kill tmux session")}finally{kr(null)}},[pu]);b.useEffect(()=>{if(!ss)return;if(pn.find(he=>he.name===ss&&(he.connected||he.boundFrontendSessionId))){Hn(null);return}const Q=setTimeout(()=>Hn(null),1e4);return()=>clearTimeout(Q)},[ss,pn]);const Kl=b.useCallback(C=>{window.dispatchEvent(new CustomEvent("close-terminal-session",{detail:C}))},[]),kc=b.useCallback(C=>{const Q=C??wt;Q&&window.dispatchEvent(new CustomEvent("open-terminal-split-chooser",{detail:Q}))},[wt]),Lc=b.useCallback((C,Q)=>{window.dispatchEvent(new CustomEvent("set-terminal-split-direction",{detail:{sessionId:C,layout:Q}}))},[]),bd=b.useCallback((C,Q)=>{window.dispatchEvent(new CustomEvent("reorder-terminal-split-workspace",{detail:{workspaceId:C,sessionIds:Q}}))},[]),sl=b.useCallback((C,Q)=>{window.dispatchEvent(new CustomEvent("rename-terminal-split-workspace",{detail:{workspaceId:C,name:Q}}))},[]),yd=b.useCallback((C,Q)=>{window.dispatchEvent(new CustomEvent("combine-terminal-split-sessions",{detail:{primaryId:C,secondaryId:Q}}))},[]),kl=b.useCallback((C,Q,he)=>{const lt=Tt.find(Kt=>Kt.id===C);if(!lt)return;const kt=$t.get(C);if(he?.skipConfirmation||!ab({mode:lt.mode,activeProgram:kt?.activeProgram??null,promptState:kt?.promptState??null,shellNames:Ra})){Kl({sessionId:C,source:"sidebar",closeMode:lt.mode==="tmux"?"destroy":"auto"});return}U(Q?{x:Q.clientX,y:Q.clientY}:null),H(C),ys(null)},[Tt,$t,Kl,H]);b.useEffect(()=>{if(!ut)return;const C=Q=>{const he=Q.detail;he==="new-session"?Do():he==="close-session"?wt&&!st&&kl(wt):he==="previous-session"||he==="next-session"?window.dispatchEvent(new CustomEvent("cycle-terminal-session",{detail:{direction:he==="next-session"?"next":"prev"}})):he==="toggle-left-sidebar"?ci():he==="toggle-right-sidebar"?Li():he==="previous-attention"?_c():he==="next-attention"&&rl()};return window.addEventListener("termdock:native-command",C),()=>window.removeEventListener("termdock:native-command",C)},[wt,st,ut,Do,kl,ci,Li,rl,_c]);const ao=_.useMemo(()=>Tt.find(C=>C.id===st)??null,[Tt,st]),sh=b.useCallback(()=>{if(!ao||!ue()){yt(null),U(null);return}Kl({sessionId:ao.id,source:"sidebar",closeMode:"destroy"}),yt(null),U(null)},[ao,Kl,ue]),vd=_.useRef(null),mu=b.useCallback(()=>{yt(null),U(null),ys(null)},[]);_.useLayoutEffect(()=>{if(!st)return;const C=()=>{ue()||mu()},Q=()=>mu();C();const he=Vr.subscribe(C);return window.addEventListener($u,C),window.addEventListener("auth:unauthorized",Q),()=>{he(),window.removeEventListener($u,C),window.removeEventListener("auth:unauthorized",Q)}},[st,$t,ue,mu]);const _p=_.useMemo(()=>{if(!ao)return"";const C=$t.get(ao.id);return gl(ao,C?.activeProgram??null,C?.cwd??null,Ra,C?.shellTitle??null,C?.promptState??null).primary},[ao,$t]);b.useEffect(()=>{if(!Cr)return;let C=!1,Q=!1;const he=async()=>{if(!Q)try{const kt=await r1();if(C||Y(kt),!kt.available){C||Gr([]);return}const Kt=await n1();C||Gr(Kt)}catch{Q=!0,C||(Y({available:!1,version:null,reason:"tmux integration is unavailable with the current server build."}),Gr([]))}};he();const lt=setInterval(()=>{he()},4e3);return()=>{C=!0,clearInterval(lt)}},[Cr]);const ih=aa??gn,wd=ih==="shell",gu=ih==="tmux"&&zr.available,oo=_.useMemo(()=>x3(pn.map(C=>({...C,id:C.name})),C=>C.cwd??null,e("sidebar.ungrouped")),[pn,e]),lo=_.useMemo(()=>pn.filter(C=>C.recoveryCandidate===!0&&!C.connected&&!C.boundFrontendSessionId).sort((C,Q)=>(Q.lastActiveAt??Q.createdAt??0)-(C.lastActiveAt??C.createdAt??0)),[pn]);b.useEffect(()=>{!ne&&!(Dt&&gr)||nl()},[ne,Dt,gr,Tt.length,nl]);const Ll=(C,Q,he,lt=!1)=>{const kt=C.id===wt,Kt=C.id===hn,Mr=$t.get(C.id),{primary:Rn,secondary:Gn}=gl(C,Mr?.activeProgram??null,Mr?.cwd??null,Ra,Mr?.shellTitle??null,Mr?.promptState??null),$n=cd(Mr?.cwd??null),Vi=Q?Gn??($n&&$n!==Rn?$n:null):null,Ln=Mr?.gitStatus,la=`${Mr?.cwd||C.name}${Ln?`
|
|
185
|
+
}`}),N&&s.jsx("div",{className:"whitespace-pre-wrap break-words text-[10px] text-[color:var(--warning)]",children:N}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("button",{type:"button",onClick:()=>{Le()},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(yT,{size:11}),e("settings.agentPluginCreate")]}),s.jsx("button",{type:"button",onClick:()=>{x(!1),I(""),B(null)},className:"rounded-full px-3 py-1 text-[11px] text-muted-foreground hover:text-foreground transition",children:e("common.cancel")})]})]})]})]})}function G$({state:e,pending:t,onCheck:r,onConfirmRestart:n,desktopState:a,desktopPending:c=!1,desktopSnapshot:l,desktopActions:d,onCheckDesktop:f,onInstallDesktop:m}){const{t:x}=Hr(),y=e?.status??"idle",w=t||y==="checking"||y==="installing"||y==="restarting",v=y==="ready"&&!!e?.latestVersion,T=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"),S=a?.currentVersion||l?.appVersion,I=a?.status??"idle",N=c||I==="checking"||I==="downloading"||I==="installing",B=I==="ready",F=a?.error||(I==="unsupported"?x("settings.desktopUpdateUnsupported"):I==="checking"?x("settings.desktopUpdateChecking"):I==="current"?x("settings.desktopUpdateCurrent"):I==="downloading"?x("settings.desktopUpdateDownloading"):I==="ready"?x("settings.desktopUpdateReady"):I==="installing"?x("settings.desktopUpdateInstalling"):I==="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(wn,{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:T}),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(wn,{size:15,className:N?"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?F:x(f?"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}`:S?`v${S}`:null})]})]}),B?s.jsx("button",{type:"button",disabled:N||!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||N||I==="unsupported"||!f,onClick:f,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(I==="installing"?"settings.updateInstallingShort":I==="downloading"?"settings.desktopUpdateDownloadingShort":I==="checking"?"settings.updateCheckingShort":I==="current"||I==="error"?"settings.desktopUpdateCheckAgain":"settings.desktopUpdateCheck")})]}),d]})}function V$({quality:e}){const{locale:t}=Hr(),r=(d,f)=>t==="zh"?d:f,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(([f,m])=>s.jsxs(_.Fragment,{children:[s.jsx("dt",{children:f}),s.jsx("dd",{className:"text-right text-foreground break-all",children:m})]},f))}),l=(d,f)=>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}),f]});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 q$({backendSessionId:e}){const{locale:t}=Hr(),r=t==="zh",[n,a]=_.useState(null),[c,l]=_.useState(!1);_.useEffect(()=>{if(a(null),!c||!e)return;const y=()=>a(W9(e));y();const w=setInterval(y,1e3);return document.addEventListener("visibilitychange",y),()=>{clearInterval(w),document.removeEventListener("visibilitychange",y)}},[e,c]);const d=n?.diagnostics,f=n?.rtt,m=n?.connected?n.waiting?r?"等待响应…":"Waiting for reply…":f==null?r?"测量中…":"Measuring…":`${f} ms · ${f<150?r?"流畅":"Low latency":f<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||f!=null&&f>=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(V$,{quality:n})]})]})]})}const Ey={"startup-failure":"settings.serverHealthEventStartupFailure",crash:"settings.serverHealthEventCrash","crash-native":"settings.serverHealthEventCrashNative",killed:"settings.serverHealthEventKilled",wedge:"settings.serverHealthEventWedge","port-conflict":"settings.serverHealthEventPortConflict","gave-up":"settings.serverHealthEventGaveUp","exit-zero-unexpected":"settings.serverHealthEventExitZero","terminated-externally":"settings.serverHealthEventTerminated","supervisor-lost":"settings.serverHealthEventSupervisorLost","uncaught-exception":"settings.serverHealthEventUncaughtException","unhandled-rejection":"settings.serverHealthEventUnhandledRejection","exit-nonzero":"settings.serverHealthEventExitNonzero"};function Y$(e){return e<1e3?`${e}ms`:e<6e4?`${Math.round(e/1e3)}s`:e<36e5?`${Math.round(e/6e4)}m`:`${Math.round(e/36e5)}h`}function Z$({state:e,onDismiss:t}){const{t:r}=Hr(),[n,a]=b.useState(!1),[c,l]=b.useState(!1),d=b.useRef(!1),f=b.useRef(!0);b.useEffect(()=>(f.current=!0,()=>{f.current=!1}),[]),b.useEffect(()=>{e?.supervised&&(d.current=!1,a(!1),l(!1))},[e?.supervised]),b.useEffect(()=>{if(!n)return;const F=window.setTimeout(()=>{d.current=!1,a(!1),l(!0)},45e3);return()=>window.clearTimeout(F)},[n]);const m=async()=>{if(!d.current){d.current=!0,l(!1),a(!0);try{await G9()}catch{if(!f.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,T=e.supervised&&e.supervisor?.alive&&e.supervisor.phase==="running",S=y?r("settings.serverHealthGaveUp",{count:e.supervisor?.consecutiveCrashes??0}):w?r("settings.serverHealthSupervisorLost"):e.supervised?r("settings.serverHealthSupervised"):r("settings.serverHealthUnsupervised"),I=x?r(Ey[x.event]??"settings.serverHealthUnknownEvent"):"",N=x?.causeEvent?r(Ey[x.causeEvent]??"settings.serverHealthUnknownEvent"):"",B=x?[new Date(x.at).toLocaleString(),x.uptimeMs!==null?r("settings.serverHealthUptime",{duration:Y$(x.uptimeMs)}):null,x.signal?`signal ${x.signal}`:null,x.exitCode!==null?`exit ${x.exitCode}`:null].filter(Boolean).join(" · "):"";return s.jsxs("section",{className:"mt-3 overflow-hidden rounded-xl bg-surface-2","aria-labelledby":"server-health-title",children:[s.jsx("div",{id:"server-health-title",className:"px-3 pt-3 text-[12px] font-semibold text-foreground",children:r("settings.serverHealthTitle")}),s.jsxs("div",{className:"flex items-start justify-between gap-3 px-3 py-3",children:[s.jsxs("div",{className:"flex min-w-0 items-start gap-2.5",children:[s.jsx("span",{className:`mt-0.5 inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${v?"bg-destructive/15 text-destructive":"bg-primary/15 text-primary"}`,children:v?s.jsx(OS,{size:15}):s.jsx($S,{size:15})}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12px] font-medium text-foreground",children:S}),s.jsx("div",{className:"mt-0.5 text-[10px] leading-relaxed text-muted-foreground",children:x?`${r(T?"settings.serverHealthHistory":"settings.serverHealthLastIncident")}: ${I}${N?` · ${N}`:""}`:r("settings.serverHealthClean")}),x&&T&&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 K$=()=>()=>{},X$=()=>1/0;function J$(){const{t:e}=Hr(),t=b.useId(),r=Vo(),n=b.useSyncExternalStore(r?.subscribe??K$,r?.retentionLimit??X$);if(!r)return null;const a=V9+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 J1="mobile-session-destroy";function eU(e,t){return t&&e.type==="session"&&e.destination?.droppableId===J1}const Na="termdock-program-rules-cache",Zh="termdock-toolbar-presets-cache",l0="termdock-settings-cache",Ny="termdock-color-theme",Ry="termdock:right-sidebar:file-preview-open-by-session:v2",c0="termdock:running-session-button-enabled:v1",u0="termdock:attention-button-enabled:v1",tU=60,My=320,jy=420,Go=8;function Dy(e,t,r){return Math.min(Math.max(e,t),r)}function By(e){if(typeof window>"u")return{left:Go,top:Go};const t=window.innerWidth/2,r=Math.min(64,window.innerHeight/4),n=e?.x??t,a=e?.y??r,c=Math.max(Go,window.innerWidth-My-Go),l=Math.max(Go,window.innerHeight-jy-Go);return{left:Dy(n+Go,Go,c),top:Dy(a+Go,Go,l),width:My,maxHeight:`min(${jy}px, calc(100vh - ${Go*2}px))`}}function rU(e){return e==="dark"||e==="light"}function nU(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 t1(e){const t=Object.entries(e).filter(([r,n])=>r&&Number.isFinite(n.updatedAt)).sort(([,r],[,n])=>n.updatedAt-r.updatedAt).slice(0,tU);return Object.fromEntries(t)}function sU(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 iU(e){return typeof e=="object"&&e!==null&&typeof e.version=="number"&&Array.isArray(e.presets)}function aU(e,t){const r=D0(),n=new Set(FE()),a=Array.isArray(e)?e:[],c=Wu(a),l=t<p0;if(c.length===0)return r;if(l){const f=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=f.get(w.id),T=m.get(w.id);return v?{...w,rowLayout:v.rowLayout,showOnDesktop:typeof T?.showOnDesktop=="boolean"?T.showOnDesktop:w.showOnDesktop}:w}),...x]}const d=new Set(c.map(f=>f.id));return[...c,...r.filter(f=>!d.has(f.id))]}function oU(e){return typeof e=="object"&&e!==null&&typeof e.preventSleep=="boolean"&&typeof e.networkAvailable=="boolean"}const lU={name:"",source:"auto",hostname:"",fallbackHostname:"",url:"",fallbackUrl:"",onboardingUrl:null,status:"disabled",reason:null,httpsEnabled:!1,caAvailable:!1,lanAddresses:[],interfaces:[]},vp="__termdockOverlay",wp="__termdockBaseAnchor",Ap="__termdockBaseGuard",cU=3,Qy=250,uU="termdock-notification-target-v1",Py="/__termdock-notification-target",Oy=3e4;function dU(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 Du(e){if(!e||typeof e!="object")return null;const t=e[vp];return dU(t)?t:null}function Jg(e){return e&&typeof e=="object"?{...e}:{}}function L4(e){const t=Jg(e);return delete t[vp],t}function hU(e){const t=L4(e);return delete t[Ap],{...t,[wp]:!0}}function fU(){typeof window>"u"||window.history.pushState({...L4(window.history.state),[wp]:!0,[Ap]:!0},"",window.location.href)}function I4(){for(let e=0;e<cU;e+=1)fU()}function Kh(){typeof window>"u"||(window.history.replaceState(hU(window.history.state),"",window.location.href),I4())}function d0(e){typeof window>"u"||window.history.pushState({...Jg(window.history.state),[wp]:!0,[vp]:e,[Ap]:!1},"",window.location.href)}function pU(e){typeof window>"u"||window.history.replaceState({...Jg(window.history.state),[wp]:!0,[vp]:e,[Ap]:!1},"",window.location.href)}const E4=["bash","zsh","fish","sh","dash","ksh","tcsh","csh","nu"];let Ra=new Set(E4);function Fy(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 mU(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 $y(e,t){return s.jsx(pO,{sessionMode:e,state:t})}function gU(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 xU=_.lazy(()=>Vc(()=>import("./CollaborationMainWorkspace-DsIWXeh0.js"),__vite__mapDeps([18,1,2,3,4,5,8,9,15,13])));async function N4(e,t){return lg(e,t)}function bU(){const{t:e,locale:t,setLocale:r}=Hr(),n="env(safe-area-inset-top, 0px)",a="env(safe-area-inset-bottom, 0px)";q9();const c=_.useMemo(()=>typeof window>"u"?!1:/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,[]),[l,d]=_.useState(!1),[f,m]=_.useState(()=>Rc(Ny,rU)??"dark"),x=_.useRef(Rc(l0,oU)).current,[y,w]=_.useState(x?.preventSleep??!1),[v,T]=_.useState(x?.networkAvailable??!0),[S,I]=_.useState(Y9),[N,B]=_.useState(Z9),[F,P]=_.useState(K9),[$,ee]=_.useState(X9),[Z,V]=_.useState(Fp),[de,pe]=_.useState(x?.localAccess??lU),[J,Re]=_.useState(x?.localAccess?.name??""),[Xe,q]=_.useState(!1),[ve,qe]=_.useState(null),[ce,ye]=_.useState(null),[Te,Fe]=_.useState(null),[se,De]=_.useState(!1),_e=b.useRef({busy:!1}),Me=b.useRef(0),Je=b.useRef(Te?.latestVersion);Je.current=Te?.latestVersion;const[Ne,ae]=b.useState(null);b.useEffect(()=>{const C=()=>{Me.current++};for(const Q of["pagehide","auth:unauthorized",$u])window.addEventListener(Q,C);return()=>{C();for(const Q of["pagehide","auth:unauthorized",$u])window.removeEventListener(Q,C)}},[]);const[ze,at]=_.useState(null),ut=_.useMemo(()=>ea(),[]),me=!!(ut?.desktopUpdateState&&ut.checkDesktopUpdate&&ut.installDesktopUpdate),[dt,ft]=_.useState(null),[Se,We]=_.useState(null),[Le,z]=_.useState(!1),ie=b.useRef({busy:!1}),ge=b.useRef(Se);ge.current=Se;const[Ge,rt]=_.useState(null),[vt,Yt]=_.useState(!1),[Ut,Nt]=_.useState(()=>t1(Rc(Ry,nU)??{})),[ir,Mt]=_.useState(0),[Xt,Bt]=_.useState(!1),[Wt,xe]=_.useState(0),[et,ot]=_.useState(!1),[Et,K]=_.useState(0),[xt,rr]=_.useState(!1),[$e,Dr]=_.useState(0),Ce=_.useRef(null),[St,Ot]=_.useState({}),{terminalSettings:tr,updateTerminalSettings:ct}=xQ(),Ct=tr.fontSize,or=tr.rendererMode,[Cr,Ir]=_.useState(!1),$r=_.useRef(J9()).current,[Tt,Ft]=b.useState(()=>$r.sessions.map(C=>({id:C.sessionId,name:C.name,customName:C.customName,mode:C.mode,tmuxSessionName:C.tmuxSessionName}))),we=Pi(C=>C.groupId);_.useEffect(()=>{const C=()=>Pi.getState().terminal();return window.addEventListener("switch-terminal-session",C),()=>window.removeEventListener("switch-terminal-session",C)},[]);const[wt,it]=_.useState($r.activeSessionId),[bt,An]=_.useState(!1);_.useEffect(()=>{bt&&eA({rendered:!0})},[bt]);const[xn,rn]=_.useState(null),[Oe,_t]=_.useState(null),[mt,Zt]=_.useState([]),[$t,wr]=b.useState(()=>{const C=Vr.getState();return $r.sessions.forEach(Q=>{Q.backendSessionId&&C.setTerminalSession(Q.sessionId,{sessionId:Q.backendSessionId,cols:80,rows:24,mode:Q.mode,tmuxSessionName:Q.tmuxSessionName}),Q.activeProgram!=null&&C.setSessionActiveProgram(Q.sessionId,Q.activeProgram),Q.cwd!=null&&C.setSessionCwd(Q.sessionId,Q.cwd),Q.shellTitle!=null&&C.setSessionShellTitle(Q.sessionId,Q.shellTitle)}),Gu("session-chrome-hydrated"),Fy(Vr.getState().sessions)});b.useEffect(()=>{!ut||!Cr||Promise.all([ut.snapshot(),ut.desktopUpdateState?.()??Promise.resolve(null)]).then(([C,Q])=>{ft(C),We(Q)}).catch(C=>rt(C instanceof Error?C.message:String(C)))},[ut,Cr]),b.useEffect(()=>{ut?.onDesktopUpdateState&&ut.onDesktopUpdateState(We)},[ut]),b.useEffect(()=>Vr.subscribe(C=>{const Q=Fy(C.sessions);wr(he=>mU(he,Q)?he:Q)}),[]);const Tn=b.useCallback(async(C,Q)=>{_t(null),rn({sessionId:C,status:"submitting",error:null});try{await tA(Q),rn(he=>he?.sessionId===C?{...he,status:"waiting",error:null}:he)}catch(he){const kt=(he&&typeof he=="object"&&"code"in he?String(he.code??""):"")==="AGENT_SESSION_ACTIVE_ELSEWHERE"?e("tab.resumeAgentConflict"):he instanceof Error&&/busy/i.test(he.message)?e("tab.resumeAgentBusy"):e("tab.resumeAgentFailed");rn(Kt=>Kt?.sessionId===C?{...Kt,error:kt}:Kt),_t({tone:"error",message:kt})}},[e]);b.useEffect(()=>{if(!xn||xn.status!=="waiting")return;const C=$t.get(xn.sessionId);if(!C||C.agentResumeRecovered||C.agentStatus===null&&!C.agent)return;const Q=C.agent?.displayName??"Agent";rn(null),_t({tone:"success",message:e("tab.resumeAgentSuccess",{agent:Q})})},[xn,$t,e]),b.useEffect(()=>{if(!xn||xn.status!=="waiting"||xn.error)return;const C=xn.sessionId,Q=window.setTimeout(()=>{const he=e("tab.resumeAgentTimeout");rn(lt=>lt?.sessionId===C&<.status==="waiting"?{...lt,error:he}:lt),_t({tone:"error",message:he})},15e3);return()=>window.clearTimeout(Q)},[xn,e]),b.useEffect(()=>{if(Oe?.tone!=="success")return;const C=window.setTimeout(()=>_t(null),3200);return()=>window.clearTimeout(C)},[Oe]),b.useEffect(()=>{let C=!1;rA().then(he=>{C||Fe(he)}).catch(()=>{}),nA().then(he=>{C||at(he)}).catch(()=>{});const Q=Rx(he=>{C||(he.type==="update-state"?Fe(he.state):he.type==="server-health"&&at(he.state))});return()=>{C=!0,Q()}},[]);const Dn=b.useCallback(async()=>{try{at(await sA())}catch(C){o1(C instanceof Error?C.message:String(C))}},[]),yn=b.useCallback(async()=>{const C=Te?.latestVersion;if(!C||se)return;const Q=Me.current,he=Ki(),lt=wl(),kt=()=>Q===Me.current&&he===Ki()&<===wl()&&!lt?.closed&&Je.current===C,Kt=ut?.confirmationUI==="page-v1"&&typeof ut.confirm=="function";ae(null),await N4(_e.current,{current:kt,submit:kA,apply:Fe,pending:De,expiredMessage:t==="zh"?"连接已变化,请重新确认。":"Connection changed. Please confirm again.",confirm:()=>Kt?ut.confirm({title:e("sidebar.updateRestart"),message:e("sidebar.updateRestartConfirm",{version:C}),confirmLabel:e("sidebar.updateRestart"),cancelLabel:e("common.cancel")}):window.confirm(e("sidebar.updateRestartConfirm",{version:C})),failure:Mr=>{Kt?ae(Mr):window.alert(Mr)}})},[Te?.latestVersion,e,se,ut,t]),un=b.useCallback(async()=>{if(!se){De(!0);try{Fe(await iA())}catch(C){o1(C instanceof Error?C.message:String(C))}finally{De(!1)}}},[se]),Cn=b.useCallback(async()=>{if(!(!ut?.checkDesktopUpdate||Le)){z(!0);try{We(await ut.checkDesktopUpdate())}catch(C){rt(C instanceof Error?C.message:String(C))}finally{z(!1)}}},[ut,Le]),Ur=b.useCallback(async()=>{const C=Se;if(!ut?.installDesktopUpdate||Le||C?.status!=="ready")return;const Q=Me.current,he=Ki(),lt=wl(),kt=()=>Q===Me.current&&C===ge.current&&C.status==="ready"&&he===Ki()&<===wl()&&!lt?.closed;await lg(ie.current,{current:kt,confirm:()=>y3({title:e("settings.desktopUpdateRestartConfirm"),message:e("settings.desktopUpdateRestartConfirm"),confirmLabel:e("sidebar.updateRestart"),cancelLabel:e("common.cancel")}),submit:async()=>{if(!kt())throw new Error("Desktop update context changed");return ut.installDesktopUpdate()},apply:We,pending:z,failure:rt,expiredMessage:t==="zh"?"连接已变化,请重新确认。":"Connection changed. Please confirm again."})},[ut,Le,Se,e,t]);b.useEffect(()=>{document.documentElement.dataset.theme=f,aA(f),qn(Ny,f)},[f]),b.useEffect(()=>{qn(Ry,t1(Ut))},[Ut]);const ne=Vt(C=>C.leftOpen),Ze=Vt(C=>C.rightOpen),Dt=Vt(C=>C.leftPinned),ur=Vt(C=>C.leftSidebarWidth),Pr=Vt(C=>C.rightPinned),qr=Vt(C=>C.rightSidebarWidth),sn=Vt(C=>C.rootPath),Nr=Vt(C=>C.contextKey),Wr=Vt(C=>C.selectedFilePath),_n=Vt(C=>C.groupByFolder),en=kf(C=>C.collaborationGroups),Fr=Vt(C=>C.collapsedGroups),Kr=Vt(C=>C.toggleGroupCollapsed),[gr,an]=b.useState(()=>typeof window>"u"?!0:window.matchMedia("(min-width: 1024px)").matches),[Xr,dn]=b.useState(()=>typeof window>"u"?1024:window.innerWidth),[Rr,zn]=b.useState(()=>typeof window>"u"?!1:window.matchMedia("(orientation: landscape)").matches),[pn,Gr]=b.useState([]),[zr,Y]=b.useState({available:!0,version:null,reason:null}),[Be,Qt]=b.useState(!1),[er,nr]=b.useState(null),[Or,kr]=b.useState(null),[Zn,ys]=b.useState(null),[ss,Hn]=b.useState(null),[hn,Qn]=b.useState(null),[Xn,fn]=b.useState(null),[cr,is]=b.useState(null),[,tn]=b.useState(0),[xr,vr]=b.useState(null),[br,us]=b.useState(null),[Bn,vs]=b.useState(null),[Bs,Ls]=b.useState(!1),[Qr,yr]=b.useState(()=>Rc(c0,C=>typeof C=="boolean")??!1),Pn=b.useCallback(async C=>{const Q=Qr;yr(C),qn(c0,C);try{const he=await ja({runningSessionButtonEnabled:C});yr(he.runningSessionButtonEnabled),qn(c0,he.runningSessionButtonEnabled)}catch{yr(Q),qn(c0,Q)}},[Qr]),[Jn,es]=b.useState(()=>Rc(u0,C=>typeof C=="boolean")??!0),oi=b.useCallback(async C=>{const Q=Jn;es(C),qn(u0,C);try{const he=await ja({attentionButtonEnabled:C});es(he.attentionButtonEnabled),qn(u0,he.attentionButtonEnabled)}catch{es(Q),qn(u0,Q)}},[Jn]),[W,Ie]=b.useState(null),Ye=b.useCallback(C=>{Ie(C)},[]),nt=b.useRef(!1),[st,yt]=b.useState(null),Pt=_.useRef(null),H=b.useCallback(C=>{const Q=Tt.find(he=>he.id===C);Q&&(Pt.current={id:C,target:Ki(),client:wl(),backend:Vr.getState().sessions.get(C)?.terminalSessionId??null,mode:Q.mode,tmux:Q.tmuxSessionName},yt(C))},[Tt]),ue=b.useCallback(()=>{const C=Pt.current,Q=C&&Tt.find(he=>he.id===C.id);return!!C&&!C.client?.closed&&TQ(C,Q?{id:Q.id,target:Ki(),client:wl(),backend:Vr.getState().sessions.get(Q.id)?.terminalSessionId??null,mode:Q.mode,tmux:Q.tmuxSessionName}:null)},[Tt]),[R,U]=b.useState(null),X=_.useRef(null),be=_.useRef(!1),Ee=_.useRef(null),Ve=_.useRef(!1),ht=b.useCallback(()=>{fn(null),is(null)},[]),Qe=_.useRef(typeof window>"u"?null:new URLSearchParams(window.location.search).get("session")),[ar,sr]=_.useState(Qe.current),[It,_r]=_.useState(!0),on=_.useRef(Qe.current),bn=_.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)"),Q=()=>{an(C.matches),dn(window.innerWidth)};return Q(),C.addEventListener("change",Q),window.addEventListener("resize",Q),()=>{C.removeEventListener("change",Q),window.removeEventListener("resize",Q)}},[]),b.useEffect(()=>{if(typeof window>"u")return;const C=window.matchMedia("(orientation: landscape)"),Q=()=>zn(C.matches);return Q(),C.addEventListener("change",Q),()=>C.removeEventListener("change",Q)},[]);const Jr=_.useMemo(()=>wt?mt.find(C=>C.sessionIds.includes(wt))??null:null,[wt,mt]),mn=Jr?.id??null,dr=Jr?.sessionIds[0]??wt,pr=_.useRef([]);_.useLayoutEffect(()=>{const C=pr.current;if(pr.current=mt,C.length===0)return;const Q=new Set(mt.flatMap(he=>he.sessionIds));for(const he of C){const lt=he.sessionIds.filter(kt=>!Q.has(kt)).map(kt=>({sessionId:kt,rootPath:Vr.getState().sessions.get(kt)?.cwd??null}));lt.length>0&&Vt.getState().inheritRightSidebarStateFromSplitWorkspace(he.id,lt)}},[mt]),_.useLayoutEffect(()=>((()=>{const Q=dr?Vr.getState().sessions.get(dr)?.cwd??null:null;Vt.getState().setRootPath(Q,dr,mn)})(),Vr.subscribe((Q,he)=>{const lt=dr?Q.sessions.get(dr)?.cwd??null:null,kt=dr?he.sessions.get(dr)?.cwd??null:null;lt!==kt&&Vt.getState().setRootPath(lt,dr,mn)})),[mn,dr]);const fs=_.useRef(T3(window.location.search)??TC(Ki()?.targetPeerId)),[ws,Ss]=_.useState("");_.useEffect(()=>{const C=fs.current;if(!C)return;if(C.peerId&&C.peerId!==Ki()?.targetPeerId){const lt=oA().find(kt=>kt.targetPeerId===C.peerId);if(lt&&Vo()){try{AC(C)}catch{Ss(t==="zh"?"无法在此浏览器打开架构链接。":"Cannot open this architecture link in this browser.");return}if(lA(lt)){fs.current=null;const kt=new URL(window.location.href);kt.searchParams.delete("architecture"),window.history.replaceState(window.history.state,"",kt);return}}Ss(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}Ss("");try{sessionStorage.setItem(`termdock.architecture.selection:${C.root}`,C.file)}catch{}const Q=Vt.getState();Q.setRootPath(C.root,dr,mn),Q.setRightTab("architecture"),Q.openRight();const he=new URL(window.location.href);he.searchParams.delete("architecture"),window.history.replaceState(window.history.state,"",he),dr&&(fs.current=null)},[dr,mn,t]);const Fi=gr||Rr,Gl=Xr*.95,As=Fi?Math.min(Math.max(Xr*.22,280),340):Math.min(Xr*.86,380),Is=wt&&sn?`${wt}\0${sn}`:"",li=!!(Is&&Wr&&Ut[Is]),Aa=b.useCallback(C=>{Is&&(C&&!Vt.getState().selectedFilePath||Nt(Q=>{if(!!Q[Is]===C)return Q;if(C)return t1({...Q,[Is]:{updatedAt:Date.now()}});const lt={...Q};return delete lt[Is],lt}))},[Is]);b.useEffect(()=>{CQ(Is,Nr,Wr)&&Nt(C=>{if(!C[Is])return C;const Q={...C};return delete Q[Is],Q})},[Is,Nr,Wr]);const Wn=xt?"markdown-image-lightbox":et?"markdown-outline":Xt?"right-sidebar-repo-picker":Ze&&li?"right-sidebar-file-preview":Cr?"settings":Ze&&!(Pr&&gr)?"right-sidebar":ne&&!(Dt&&gr)?"left-sidebar":null,as=_.useRef(Wn),Es=_.useRef(Wn),eo=_.useRef(!1),zs=_.useRef(!1),Tl=b.useCallback(()=>{if(typeof window>"u")return;const C=window.matchMedia("(hover: hover) and (pointer: fine)").matches;!gr||!C||navigator.maxTouchPoints>0||window.setTimeout(()=>{window.dispatchEvent(new CustomEvent("focus-active-terminal-session"))},0)},[gr]),Da=b.useCallback(C=>{if(C==="markdown-image-lightbox"){rr(!1),Dr(Q=>Q+1);return}if(C==="markdown-outline"){ot(!1),K(Q=>Q+1);return}if(C==="right-sidebar-file-preview"){ot(!1),K(Q=>Q+1),Aa(!1),Mt(Q=>Q+1);return}if(C==="right-sidebar-repo-picker"){Bt(!1),xe(Q=>Q+1);return}if(C==="settings"){Ir(!1),Fa(!1),Wi(!1),jt(!1);return}if(C==="left-sidebar"){Vt.getState().closeLeft();return}ot(!1),K(Q=>Q+1),Bt(!1),xe(Q=>Q+1),rr(!1),Dr(Q=>Q+1),Vt.getState().closeRight()},[Aa]),On=b.useCallback(C=>{if(!c&&typeof window<"u"&&as.current===C&&Du(window.history.state)===C){window.history.back();return}Da(C)},[Da,c]),ki=b.useCallback(()=>{Ir(!1);const C=Vt.getState();C.closeRight(),C.openLeft()},[]),Ba=b.useCallback(()=>{Ir(!1);const C=Vt.getState();C.closeLeft(),C.openRight()},[]),Eo=b.useCallback(()=>{Ir(!1);const C=Vt.getState();C.closeLeft(),C.openRight(),C.setRightTab("files"),C.openRightSearch()},[]),ci=b.useCallback(()=>{const C=Vt.getState();if(C.leftPinned){C.setLeftPinned(!1),C.closeLeft();return}if(ne){On("left-sidebar");return}ki()},[ki,On,ne]),Fn=b.useCallback(()=>{const C=Vt.getState();C.leftPinned?(C.setLeftPinned(!1),C.openLeft()):(C.setLeftPinned(!0),C.openLeft())},[]),Xs=b.useCallback(()=>{const C=Vt.getState();C.setLeftPinned(!1),C.closeLeft()},[]),os=b.useCallback(()=>{const C=Vt.getState();C.rightPinned?(C.setRightPinned(!1),C.openRight()):(C.setRightPinned(!0),C.openRight())},[]),Qa=b.useCallback(()=>{const C=Vt.getState();C.setRightPinned(!1),C.closeRight()},[]),ds=b.useRef(null),No=b.useRef(null);b.useEffect(()=>()=>No.current?.(),[]);const Ko=b.useCallback(C=>{if(C.button!==0||!ds.current)return;C.preventDefault(),No.current?.();const Q=Vt.getState();No.current=BF(ds.current,C.clientX,Q.leftSidebarWidth,he=>Math.min(Math.max(he,200),500),he=>Vt.getState().setLeftSidebarWidth(he))},[]),Ro=b.useRef(0),Ta=b.useRef(0),ra=b.useRef(null),Ac=b.useCallback(C=>{C.preventDefault(),Ro.current=C.clientX;const Q=Vt.getState(),he=Q.leftPinned?Q.leftSidebarWidth:0;Ta.current=Jh(Q.rightSidebarWidth,window.innerWidth,he);const lt=Kt=>{ra.current===null&&(ra.current=requestAnimationFrame(()=>{ra.current=null;const Mr=Ro.current-Kt.clientX,Rn=Vt.getState(),Gn=Rn.leftPinned?Rn.leftSidebarWidth:0;Rn.setRightSidebarWidth(Jh(Ta.current+Mr,window.innerWidth,Gn))}))},kt=()=>{window.removeEventListener("mousemove",lt),window.removeEventListener("mouseup",kt),ra.current!==null&&(cancelAnimationFrame(ra.current),ra.current=null),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",window.addEventListener("mousemove",lt),window.addEventListener("mouseup",kt)},[]),Li=b.useCallback(()=>{const C=Vt.getState();if(C.rightPinned){C.setRightPinned(!1),C.closeRight();return}if(Ze){On("right-sidebar");return}Ba()},[Ba,On,Ze]),Sl=b.useCallback(()=>{!li&&!c&&typeof window<"u"&&as.current==="right-sidebar"&&Du(window.history.state)==="right-sidebar"&&(d0("right-sidebar-file-preview"),Es.current="right-sidebar-file-preview"),Aa(!0)},[li,c,Aa]),ql=b.useCallback(()=>{On("right-sidebar-file-preview")},[On]),ui=b.useCallback(()=>{!Xt&&!c&&typeof window<"u"&&as.current==="right-sidebar"&&Du(window.history.state)==="right-sidebar"&&(d0("right-sidebar-repo-picker"),Es.current="right-sidebar-repo-picker"),Bt(!0)},[Xt,c]),Js=b.useCallback(()=>{On("right-sidebar-repo-picker")},[On]),di=b.useCallback(()=>{!et&&!c&&typeof window<"u"&&as.current&&Du(window.history.state)===as.current&&(d0("markdown-outline"),Es.current="markdown-outline"),ot(!0)},[et,c]),Xo=b.useCallback(()=>{On("markdown-outline")},[On]),na=b.useCallback(()=>{!c&&typeof window<"u"&&as.current&&Du(window.history.state)===as.current&&(d0("markdown-image-lightbox"),Es.current="markdown-image-lightbox"),rr(!0)},[c]),Cs=b.useCallback(()=>{On("markdown-image-lightbox")},[On]),hi=b.useCallback(()=>{!c&&typeof window<"u"&&as.current&&Du(window.history.state)===as.current&&(pU("settings"),Es.current="settings"),Vt.getState().closeAll(),Ir(!0)},[c]),$i=b.useCallback(()=>{On("settings")},[On]);b.useEffect(()=>{if(!ut)return;const C=()=>hi();return window.addEventListener("termdock:open-settings",C),()=>window.removeEventListener("termdock:open-settings",C)},[ut,hi]);const Jo=b.useCallback(()=>{Yt(!0),Ce.current!==null&&(window.clearTimeout(Ce.current),Ce.current=null)},[]),Ii=b.useCallback(()=>{Ce.current!==null&&(window.clearTimeout(Ce.current),Ce.current=null),Yt(!1),zs.current=!0,Kh(),zs.current},[]);b.useEffect(()=>()=>{Ce.current!==null&&window.clearTimeout(Ce.current)},[]),b.useEffect(()=>{c||Kh()},[c]),b.useEffect(()=>{if(typeof window>"u"||c)return;let C=null;const Q=()=>{C!==null&&(window.clearTimeout(C),C=null)},he=Rn=>{if(as.current,zs.current,as.current){as.current;return}!Rn?.force&&zs.current||(Rn?.userActivated&&(zs.current=!0),Kh(),zs.current,void 0)},lt=()=>{Q(),C=window.setTimeout(()=>{C=null,he({force:!0})},Qy)},kt=()=>{he({userActivated:!0})},Kt=()=>{lt()},Mr=()=>{document.visibilityState==="visible"&<()};return window.addEventListener("pointerdown",kt,{capture:!0,passive:!0}),window.addEventListener("touchstart",kt,{capture:!0,passive:!0}),window.addEventListener("keydown",kt,{capture:!0}),window.addEventListener("pageshow",Kt),document.addEventListener("visibilitychange",Mr),()=>{Q(),window.removeEventListener("pointerdown",kt,{capture:!0}),window.removeEventListener("touchstart",kt,{capture:!0}),window.removeEventListener("keydown",kt,{capture:!0}),window.removeEventListener("pageshow",Kt),document.removeEventListener("visibilitychange",Mr)}},[c]),b.useEffect(()=>{as.current=Wn},[Wn]),b.useEffect(()=>{if(typeof window>"u"||Wn||c)return;const C=window.setTimeout(()=>{as.current?(as.current,void 0):Kh()},Qy);return()=>window.clearTimeout(C)},[Wn,c]),b.useEffect(()=>{if(typeof window>"u"||c)return;const C=Es.current;eo.current,Wn&&Wn!==C&&!eo.current&&d0(Wn),!Wn&&C&&Tl(),Es.current=Wn,!Wn&&eo.current&&window.setTimeout(()=>{eo.current=!1},0)},[Wn,c,Tl]),b.useEffect(()=>{if(typeof window>"u"||c)return;const C=()=>{const Q=as.current;if(zs.current,!Q){zs.current=!1,zs.current,Jo(),I4();return}eo.current=!0,Da(Q)};return window.addEventListener("popstate",C),()=>window.removeEventListener("popstate",C)},[Da,Jo,c]),b.useEffect(()=>{const C=Q=>{const he=Q.metaKey||Q.ctrlKey;if(he&&Q.key==="b"&&!Q.shiftKey&&(Q.preventDefault(),ci()),he&&Q.shiftKey&&Q.key==="E"&&(Q.preventDefault(),Li()),he&&Q.shiftKey&&Q.key==="P"&&(Q.preventDefault(),Eo()),he&&!Q.shiftKey&&Q.altKey&&(Q.key==="ArrowLeft"||Q.key==="ArrowRight")){Q.preventDefault();const lt=Q.key==="ArrowRight"?"next":"prev";window.dispatchEvent(new CustomEvent("cycle-terminal-session",{detail:{direction:lt}}));return}if(he&&Q.shiftKey&&!Q.altKey&&(Q.code==="BracketLeft"||Q.code==="BracketRight")){Q.preventDefault();const lt=Q.code==="BracketRight"?"next":"prev";window.dispatchEvent(new CustomEvent("cycle-terminal-session",{detail:{direction:lt}}));return}};return document.addEventListener("keydown",C),()=>{document.removeEventListener("keydown",C)}},[ci,Li,Eo]);const Tc=b.useCallback(async()=>{q(!0),qe(null);try{const C=await ja({localAccess:{name:J}});pe(C.localAccess),Re(C.localAccess.name),qn(l0,{preventSleep:C.preventSleep,networkAvailable:C.networkAvailable,localAccess:C.localAccess})}catch(C){qe(C instanceof Error?C.message:"Failed to save local access name")}finally{q(!1)}},[J]),Sc=b.useCallback(async()=>{q(!0),qe(null);try{const C=await ja({localAccess:{reset:!0}});pe(C.localAccess),Re(C.localAccess.name),qn(l0,{preventSleep:C.preventSleep,networkAvailable:C.networkAvailable,localAccess:C.localAccess})}catch(C){qe(C instanceof Error?C.message:"Failed to reset local access name")}finally{q(!1)}},[]),el=b.useCallback(async(C,Q="url")=>{if(C)try{if(typeof navigator<"u"&&navigator.clipboard)await navigator.clipboard.writeText(C);else{const he=document.createElement("textarea");he.value=C,he.style.position="fixed",he.style.left="-9999px",document.body.appendChild(he),he.focus(),he.select(),document.execCommand("copy"),document.body.removeChild(he)}ye(Q),window.setTimeout(()=>ye(he=>he===Q?null:he),1600)}catch{ye(null)}},[]),Qs=b.useCallback(C=>{const Q=gU(Tt,C);Q.map(he=>he.id).join("\0")!==Tt.map(he=>he.id).join("\0")&&(Ft(Q),window.dispatchEvent(new CustomEvent("reorder-terminal-session",{detail:{sessionIds:Q.map(he=>he.id)}})))},[Tt]),Ei=b.useCallback(C=>{gr||C.type!=="session"||(nt.current=!1,Ls(!1),vs(C.draggableId))},[gr]),Ui=b.useCallback(C=>{if(gr||C.type!=="session")return;const Q=C.destination?.droppableId===J1;Q!==nt.current&&(nt.current=Q,Ls(Q),Q&&navigator.vibrate?.(20))},[gr]),zi=b.useCallback(C=>{const Q=eU(C,!gr);if(nt.current=!1,Ls(!1),vs(null),!Q)return!1;const he=Tt.find(kt=>kt.id===C.draggableId),lt=he?$t.get(he.id):null;return he&&ab({mode:he.mode,activeProgram:lt?.activeProgram??null,promptState:lt?.promptState??null,shellNames:Ra})?(U(null),H(he.id),ys(null)):he&&window.dispatchEvent(new CustomEvent("close-terminal-session",{detail:{sessionId:he.id,source:"other",closeMode:he.mode==="tmux"?"destroy":"auto"}})),!0},[gr,Tt,$t,H]),{groups:sa,arranged:ei}=_.useMemo(()=>Cf(Tt,C=>$t.get(C.id)?.cwd??null,_n,e("sidebar.ungrouped"),mt,en),[Tt,$t,_n,e,mt,en]),Pa=b.useCallback(C=>{zi(C)||!C.destination||C.source.index===C.destination.index||window.dispatchEvent(new CustomEvent("reorder-navigation-session",{detail:{sourceId:ei[C.source.index]?.id,targetId:ei[C.destination.index]?.id}}))},[zi,ei]),Hi=b.useCallback((C,Q)=>{const he=Q.trim();he&&window.dispatchEvent(new CustomEvent("rename-terminal-session",{detail:{sessionId:C,name:he}}))},[]),ls=b.useCallback(C=>{window.dispatchEvent(new CustomEvent("reset-terminal-session-name",{detail:{sessionId:C}}))},[]),{newSessionMode:gn,newSessionTmuxName:ia,userSelectedNewSessionMode:fi,setNewSessionMode:Oa}=vQ(),[aa,to]=b.useState(null),[pi,Fa]=_.useState(!1),[oa,Sa]=_.useState(!1),[mi,Wi]=_.useState(!1),[ps,Ca]=_.useState("idle"),ro=_.useRef(Rc(Zh,iU)).current,[Ps,no]=_.useState(()=>{const C=ro?.presets;if(C&&C.length>0){const Q=Wu(C);if(Q.length>0)return Q}return D0()}),[Cl,Yl]=_.useState(!1),[Mo,so]=_.useState("default"),oe=_.useRef(typeof ro?.updatedAt=="number"?ro.updatedAt:null),He=_.useRef(!1),[At,jt]=_.useState(!1),[tt,Rt]=_.useState(!1),L=_.useRef(Rc(Na,sU)).current,[D,O]=_.useState(L??[]),[G,Pe]=_.useState(L!==null),[ke,Ke]=_.useState(!1),gt=!we&&!Wn&&!oa&&!mi&&!pi&&!At&&!tt&&!Xn&&!st&&!aa,Lt=_.useCallback(C=>{const Q=typeof C.version=="number"?C.version:0,he=aU(Array.isArray(C.presets)?C.presets:[],Q);oe.current=typeof C.updatedAt=="number"?C.updatedAt:null,no(lt=>cA(lt,he)?lt:(He.current=!0,he)),qn(Zh,{version:p0,presets:he,updatedAt:oe.current??void 0})},[]);b.useEffect(()=>{const C=Q=>{if(Q.key!=="Escape"||Q.defaultPrevented||Q.isComposing||rg())return;if(oa){Q.preventDefault(),Sa(!1);return}if(mi){Q.preventDefault(),Wi(!1);return}if(pi){Q.preventDefault(),Fa(!1);return}if(At){Q.preventDefault(),jt(!1);return}if(tt){Q.preventDefault(),Rt(!1);return}if(Xn){Q.preventDefault(),ht();return}if(xr){Q.preventDefault(),Qn(null),vr(null);return}if(Cr){Q.preventDefault(),$i();return}if(Ze&&!(Pr&&gr)){Q.preventDefault(),On("right-sidebar");return}ne&&!(Dt&&gr)&&(Q.preventDefault(),On("left-sidebar"))};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[oa,mi,pi,At,Xn,ht,Cr,Ze,Pr,ne,Dt,gr,$i,On]),b.useEffect(()=>{Pe(!0)},[]);const[Jt,Yr]=_.useState({genericProgramNames:[],wrapperScriptNames:[],shellNames:E4}),[,En]=_.useState(!1),kn=_.useCallback(()=>uA().then(C=>{Yr(C),Ra=new Set(C.shellNames),En(!0)}).catch(()=>{}),[]);b.useEffect(()=>{kn()},[kn]),b.useEffect(()=>Rx(C=>{if(C.type==="config-updated"){if(C.key==="toolbar-presets"){Mx().then(Q=>Lt(Q)).catch(Q=>{console.warn("[toolbar-presets] Failed to refresh after remote update:",Q)});return}C.key==="program-detection"&&kn()}}),[Lt,kn]),b.useEffect(()=>{let C=!1;return(async()=>{try{const Q=await Mx();if(C)return;Lt(Q)}catch(Q){console.warn("[toolbar-presets] Failed to load from server:",Q)}finally{C||Yl(!0)}})(),()=>{C=!0}},[Lt]),b.useEffect(()=>{if(Cl){if(He.current){He.current=!1;return}qn(Zh,{version:p0,presets:Ps,updatedAt:oe.current??void 0}),dA({version:p0,presets:Ps,baseUpdatedAt:oe.current??void 0}).then(C=>{oe.current=typeof C.updatedAt=="number"?C.updatedAt:null,qn(Zh,{version:p0,presets:Ps,updatedAt:oe.current??void 0})}).catch(C=>{const Q=C instanceof Error&&"current"in C?C.current:null;Q&&typeof Q=="object"&&Lt(Q),console.warn("[toolbar-presets] Failed to save to server:",C)})}},[Lt,Ps,Cl]),b.useEffect(()=>{wc().then(C=>{w(Q=>Q===C.preventSleep?Q:C.preventSleep),T(Q=>Q===C.networkAvailable?Q:C.networkAvailable),pe(C.localAccess),Re(C.localAccess.name),yr(C.runningSessionButtonEnabled),qn(c0,C.runningSessionButtonEnabled),es(C.attentionButtonEnabled),qn(u0,C.attentionButtonEnabled),qn(l0,{preventSleep:C.preventSleep,networkAvailable:C.networkAvailable,localAccess:C.localAccess})}).catch(()=>{})},[]),b.useEffect(()=>{if(!S)return;const C=Fp();V(C),C!=="granted"&&(I(!1),gh(!1))},[S]),b.useEffect(()=>{if(!S)return;Id();const C=()=>{document.visibilityState==="visible"&&(Id(),SA())},Q=window.setInterval(()=>{Id()},360*60*1e3);return document.addEventListener("visibilitychange",C),window.addEventListener("focus",C),()=>{window.clearInterval(Q),document.removeEventListener("visibilitychange",C),window.removeEventListener("focus",C)}},[S]);const ms=b.useCallback(async()=>{if(S){I(!1),gh(!1),hA(),V(Fp());return}const C=await fA();if(V(C),C!=="granted"){I(!1),gh(!1);return}I(!0),gh(!0),await Id(!0,!0),Ca("idle")},[S]),Gi=b.useCallback(async()=>{Ca("checking"),await ea()?.prepareNotificationTest?.();const C=await pA({title:"Termdock",body:e("settings.notificationsTestBody"),tag:"termdock-notification-test",requireHidden:!1,data:{url:"/"}});Ca(C?"delivered":"failed")},[e]),Zr=b.useCallback(C=>{B(C),mA(C),$p()},[]),vn=b.useCallback(C=>{P(C),gA(C),$p()},[]),Os=b.useCallback(C=>{ee(C),xA(C),$p()},[]);b.useEffect(()=>{Ps.some(C=>C.id===Mo)||so(Ps[0]?.id??"default")},[Mo,Ps]),b.useEffect(()=>{if(!zr.available&&gn==="tmux"){Oa("shell",{userInitiated:!1});return}zr.available&&fi!=="shell"&&gn!=="tmux"&&Oa("tmux",{userInitiated:!1})},[gn,zr.available,fi,Oa]),b.useEffect(()=>{to(null)},[Cr,gn,zr.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),Ot(C)},[]);const Zl=b.useCallback(C=>{if(zi(C)||!C.destination)return;if(C.type==="group"){if(C.source.index===C.destination.index)return;Qs(b3(sa,C.source.index,C.destination.index));return}if(C.source.droppableId!==C.destination.droppableId||C.source.index===C.destination.index)return;const Q=C.source.droppableId.replace(/^group-sessions:/,""),he=sa.find(lt=>lt.key===Q);he&&window.dispatchEvent(new CustomEvent("reorder-navigation-session",{detail:{sourceId:he.sessions[C.source.index]?.id,targetId:he.sessions[C.destination.index]?.id}}))},[sa,Qs,zi]),Cc=_.useMemo(()=>ei.flatMap(C=>{const Q=$t.get(C.id);if(Q?.agentStatus!=="working")return[];const{primary:he,secondary:lt}=gl(C,Q?.activeProgram??null,Q?.cwd??null,Ra,Q?.shellTitle??null,Q?.promptState??null);return[{id:C.id,label:he,detail:lt}]}),[ei,$t]),Nn=wt?ei.findIndex(C=>C.id===wt):-1,_l=ei.length>0&&Nn>=0?`${Nn+1}/${ei.length}`:`${ei.length}`,ti=_.useMemo(()=>{let C=0;for(const Q of Tt){const he=$t.get(Q.id);(he?.agentStatus==="waiting"||he?.agentNeedsReview)&&(C+=1)}return{running:Cc.length,review:C}},[Cc.length,Tt,$t]),tl=_.useMemo(()=>ei.flatMap(C=>{const Q=$t.get(C.id);if(Q?.agentStatus!=="waiting"&&!Q?.agentNeedsReview)return[];const{primary:he}=gl(C,Q.activeProgram,Q.cwd,Ra,Q.shellTitle,Q.promptState);return[{id:Q.terminalSessionId??C.id,label:he,waiting:Q.agentStatus==="waiting"}]}),[ei,$t]);bA(ti.running,ti.review,tl);const $a=wt?Tt.find(C=>C.id===wt)??null:null,jo=$a?$t.get($a.id):void 0,uu=!!($a&&jo?.agentResumeRecovered&&jo.agentNativeSessionId&&jo.terminalSessionId),Ua=$a&&xn?.sessionId===$a.id?xn:null;_.useLayoutEffect(()=>{if(!It)return;const C=Ee.current;if(!C)return;const Q=!Ve.current;C.scrollIntoView({inline:"nearest",block:"nearest",behavior:Q?"auto":"smooth"}),Ve.current=!0,Q&&Gu("active-tab-positioned")},[wt,It]),b.useEffect(()=>{hn&&X.current&&(X.current.scrollIntoView({block:"nearest",inline:"nearest"}),X.current.focus(),X.current.select()),hn||(be.current=!1)},[hn]);const th=b.useCallback(C=>{window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:C}))},[]),gd=b.useCallback((C,Q)=>{is(Q??null),fn(C)},[]),Tp=Vg(),io=b.useCallback(C=>{if(!C)return;sr(C),bn.current&&Ma("info","PWA_NOTIFICATION_CLICK app-focus-request",{traceId:bn.current,requestedSessionId:C,activeSessionId:wt,sessions:Tt.map(he=>({id:he.id,terminalSessionId:$t.get(he.id)?.terminalSessionId??null}))}),yA(C);const Q=Tt.find(he=>he.id===C||$t.get(he.id)?.terminalSessionId===C);Q?(on.current=null,bn.current&&Ma("info","PWA_NOTIFICATION_CLICK app-focus-dispatch",{traceId:bn.current,requestedSessionId:C,targetSessionId:Q.id}),window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:Q.id}))):(on.current=C,bn.current&&Ma("info","PWA_NOTIFICATION_CLICK app-focus-pending",{traceId:bn.current,requestedSessionId:C}))},[wt,Tt,$t]);b.useEffect(()=>{if(typeof window>"u"||typeof caches>"u")return;let C=!1;const Q=async()=>{if(window.parent!==window&&Vo()){_r(!0);return}try{const lt=await caches.open(uU),kt=await lt.match(Py);if(!kt)return;await lt.delete(Py);const Kt=await kt.json();if(C)return;const Mr=typeof Kt.sessionId=="string"?Kt.sessionId:null,Rn=typeof Kt.traceId=="string"?Kt.traceId:null,Gn=typeof Kt.clickedAt=="number"?Kt.clickedAt:0,$n=Date.now()-Gn;Ma("info","PWA_NOTIFICATION_CLICK app-cache-consumed",{traceId:Rn,sessionId:Mr,ageMs:$n,valid:!!(Mr&&$n>=0&&$n<=Oy),visibilityState:document.visibilityState}),Mr&&$n>=0&&$n<=Oy&&(bn.current=Rn,typeof Kt.targetPeerId=="string"&&Kt.targetPeerId!==Ki()?.targetPeerId?Vo()?.focusSession(Kt.targetPeerId,Mr):io(Mr))}catch(lt){Ma("warn","PWA_NOTIFICATION_CLICK app-cache-failed",{error:lt instanceof Error?lt.message:String(lt)})}finally{C||_r(!0)}},he=()=>{document.visibilityState==="visible"&&Q()};return Q(),document.addEventListener("visibilitychange",he),window.addEventListener("pageshow",Q),()=>{C=!0,document.removeEventListener("visibilitychange",he),window.removeEventListener("pageshow",Q)}},[io]),b.useEffect(()=>{if(typeof window>"u")return;const C=new URLSearchParams(window.location.search),Q=C.get("session");if(!Q)return;Ma("info","PWA_NOTIFICATION_CLICK app-url-received",{traceId:bn.current,targetSessionId:Q,href:window.location.href,visibilityState:document.visibilityState});const he=C.get("service");he&&he!==Ki()?.targetPeerId?Vo()?.focusSession(he,Q):on.current=Q,C.delete("service"),C.delete("session"),C.delete("_notifTrace");const lt=C.toString(),kt=`${window.location.pathname}${lt?`?${lt}`:""}${window.location.hash}`;window.history.replaceState(window.history.state,"",kt)},[]),b.useEffect(()=>{if(typeof window>"u")return;const C=new URLSearchParams(window.location.search);if(C.get("_notif")!=="1")return;const Q=C.get("session");C.delete("_notif");const he=C.toString(),lt=`${window.location.pathname}${he?`?${he}`:""}${window.location.hash}`;if(window.history.replaceState(window.history.state,"",lt),window.parent!==window&&Vo())return;const kt=new BroadcastChannel("termdock:notif");let Kt=!1;const Mr=Gn=>{Gn.data?.type==="termdock:notif-pong"&&!Kt&&(Kt=!0,kt.close(),window.close())};kt.addEventListener("message",Mr),kt.postMessage({type:"termdock:notif-ping",sessionId:Q,targetPeerId:C.get("service")});const Rn=setTimeout(()=>{Kt||kt.close()},500);return()=>{clearTimeout(Rn),Kt||kt.close()}},[]),b.useEffect(()=>{if(typeof window>"u"||window.parent!==window&&Vo())return;const C=new BroadcastChannel("termdock:notif"),Q=he=>{he.data?.type==="termdock:notif-ping"&&(C.postMessage({type:"termdock:notif-pong"}),typeof he.data.sessionId=="string"&&(typeof he.data.targetPeerId=="string"&&he.data.targetPeerId!==Ki()?.targetPeerId?Vo()?.focusSession(he.data.targetPeerId,he.data.sessionId):io(he.data.sessionId)))};return C.addEventListener("message",Q),()=>C.close()},[io]),b.useEffect(()=>{if(typeof navigator>"u"||!("serviceWorker"in navigator))return;const C=Q=>{const he=Q.data;if(he&&he.type==="termdock:focus-session"&&typeof he.sessionId=="string"){if(typeof he.targetPeerId=="string"&&he.targetPeerId!==Ki()?.targetPeerId){Vo()?.focusSession(he.targetPeerId,he.sessionId)&&Q.ports[0]?.postMessage({type:"termdock:focus-session-ack"});return}Q.ports[0]?.postMessage({type:"termdock:focus-session-ack"}),io(he.sessionId)}else he?.type==="termdock:push-subscription-changed"?Id(!0):he?.type};return navigator.serviceWorker.addEventListener("message",C),()=>navigator.serviceWorker.removeEventListener("message",C)},[io]),b.useEffect(()=>{const C=Q=>{const he=Q.detail;typeof he=="string"&&io(he)};return window.addEventListener("termdock:focus-session",C),()=>window.removeEventListener("termdock:focus-session",C)},[io]),b.useEffect(()=>{const C=()=>{const Q=CA(Ki()?.targetPeerId);Q&&io(Q)};return C(),window.addEventListener("termdock:workspace-session",C),()=>window.removeEventListener("termdock:workspace-session",C)},[io]),b.useEffect(()=>{const C=on.current;if(!C)return;const Q=Tt.find(he=>he.id===C||$t.get(he.id)?.terminalSessionId===C);Q?(on.current=null,bn.current&&Ma("info","PWA_NOTIFICATION_CLICK app-pending-dispatch",{traceId:bn.current,requestedSessionId:C,targetSessionId:Q.id,activeSessionId:wt}),window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:Q.id}))):bn.current&&Ma("info","PWA_NOTIFICATION_CLICK app-pending-unmatched",{traceId:bn.current,requestedSessionId:C,activeSessionId:wt,sessions:Tt.map(he=>({id:he.id,terminalSessionId:$t.get(he.id)?.terminalSessionId??null}))})},[wt,Tt,$t]);const za=_.useMemo(()=>{const C=[];for(const Q of Tt){const he=$t.get(Q.id);(he?.agentStatus==="waiting"||he?.agentNeedsReview)&&C.push(Q.id)}return C},[Tt,$t]),rl=b.useCallback(()=>{if(za.length===0)return;wt&&Vr.getState().clearAgentNeedsReview(wt);const C=wt?Tt.findIndex(he=>he.id===wt):-1,Q=za.find(he=>Tt.findIndex(lt=>lt.id===he)>C)??za[0];Q&&window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:Q}))},[za,Tt,wt]),_c=b.useCallback(()=>{if(za.length===0)return;wt&&Vr.getState().clearAgentNeedsReview(wt);const C=wt?Tt.findIndex(he=>he.id===wt):Tt.length,Q=[...za].reverse().find(he=>Tt.findIndex(lt=>lt.id===he)<C)??za[za.length-1];Q&&window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:Q}))},[za,Tt,wt]);b.useEffect(()=>{const C=Q=>{!Q.altKey||!Q.shiftKey||Q.metaKey||Q.ctrlKey||Q.key!=="ArrowUp"&&Q.key!=="ArrowDown"||(Q.preventDefault(),Q.key==="ArrowUp"?_c():rl())};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[rl,_c]);const rh=b.useCallback(async C=>{const he=Vr.getState().sessions.get(C)?.cwd;if(he)try{await navigator.clipboard?.writeText(he),us(he),window.setTimeout(()=>{us(lt=>lt===he?null:lt)},1400)}catch{}},[]),du=b.useCallback(C=>{Ft(C.sessions),it(C.activeSessionId),Zt(C.splitWorkspaces),Vr.getState().setActiveSessionId(C.activeSessionId)},[]),Sp=b.useCallback(()=>{An(!0)},[]),xd=b.useCallback(()=>{An(!0),window.requestAnimationFrame(()=>{window.dispatchEvent(new Event("termdock:initial-viewport-presented"))})},[]);b.useEffect(()=>{if(!ar||!wt)return;Tt.find(Q=>Q.id===ar||$t.get(Q.id)?.terminalSessionId===ar)?.id===wt&&sr(null)},[wt,ar,Tt,$t]);const hu=b.useRef(!1),[fu,nh]=b.useState(!1),Do=b.useCallback(C=>{const Q=!C?.onResult;if(Q&&hu.current)return;Q&&(hu.current=!0,nh(!0));const he=C?.mode??gn,lt=he==="tmux"&&(C?.tmuxSessionName?.trim()||ia.trim())||void 0,kt=C?.cwd||(wt?Vr.getState().sessions.get(wt)?.cwd:void 0);window.dispatchEvent(new CustomEvent("new-terminal-session",{detail:{mode:he,tmuxSessionName:lt,cwd:kt,command:C?.command,shouldActivate:C?.shouldActivate,onResult:C?.onResult??(Kt=>{hu.current=!1,nh(!1),Kt.ok||_t({tone:"error",message:e(l1(Kt.error))})})}}))},[gn,ia,wt,e]),nl=b.useCallback(async()=>{Qt(!0);try{const C=await r1();if(Y(C),!C.available){Gr([]);return}const Q=await n1();Gr(Q)}catch{Y({available:!1,version:null,reason:"tmux integration is unavailable with the current server build."}),Gr([])}finally{Qt(!1)}},[]),pu=b.useCallback(async C=>{const{cleanedSessions:Q}=await qy(C);for(const he of Q)window.dispatchEvent(new CustomEvent("close-terminal-session-by-backend",{detail:he}));await nl()},[nl]),Cp=b.useCallback(async C=>{kr(C),ys(null);try{await pu(C),nr(null)}catch(Q){ys(Q instanceof Error?Q.message:"Failed to kill tmux session")}finally{kr(null)}},[pu]);b.useEffect(()=>{if(!ss)return;if(pn.find(he=>he.name===ss&&(he.connected||he.boundFrontendSessionId))){Hn(null);return}const Q=setTimeout(()=>Hn(null),1e4);return()=>clearTimeout(Q)},[ss,pn]);const Kl=b.useCallback(C=>{window.dispatchEvent(new CustomEvent("close-terminal-session",{detail:C}))},[]),kc=b.useCallback(C=>{const Q=C??wt;Q&&window.dispatchEvent(new CustomEvent("open-terminal-split-chooser",{detail:Q}))},[wt]),Lc=b.useCallback((C,Q)=>{window.dispatchEvent(new CustomEvent("set-terminal-split-direction",{detail:{sessionId:C,layout:Q}}))},[]),bd=b.useCallback((C,Q)=>{window.dispatchEvent(new CustomEvent("reorder-terminal-split-workspace",{detail:{workspaceId:C,sessionIds:Q}}))},[]),sl=b.useCallback((C,Q)=>{window.dispatchEvent(new CustomEvent("rename-terminal-split-workspace",{detail:{workspaceId:C,name:Q}}))},[]),yd=b.useCallback((C,Q)=>{window.dispatchEvent(new CustomEvent("combine-terminal-split-sessions",{detail:{primaryId:C,secondaryId:Q}}))},[]),kl=b.useCallback((C,Q,he)=>{const lt=Tt.find(Kt=>Kt.id===C);if(!lt)return;const kt=$t.get(C);if(he?.skipConfirmation||!ab({mode:lt.mode,activeProgram:kt?.activeProgram??null,promptState:kt?.promptState??null,shellNames:Ra})){Kl({sessionId:C,source:"sidebar",closeMode:lt.mode==="tmux"?"destroy":"auto"});return}U(Q?{x:Q.clientX,y:Q.clientY}:null),H(C),ys(null)},[Tt,$t,Kl,H]);b.useEffect(()=>{if(!ut)return;const C=Q=>{const he=Q.detail;he==="new-session"?Do():he==="close-session"?wt&&!st&&kl(wt):he==="previous-session"||he==="next-session"?window.dispatchEvent(new CustomEvent("cycle-terminal-session",{detail:{direction:he==="next-session"?"next":"prev"}})):he==="toggle-left-sidebar"?ci():he==="toggle-right-sidebar"?Li():he==="previous-attention"?_c():he==="next-attention"&&rl()};return window.addEventListener("termdock:native-command",C),()=>window.removeEventListener("termdock:native-command",C)},[wt,st,ut,Do,kl,ci,Li,rl,_c]);const ao=_.useMemo(()=>Tt.find(C=>C.id===st)??null,[Tt,st]),sh=b.useCallback(()=>{if(!ao||!ue()){yt(null),U(null);return}Kl({sessionId:ao.id,source:"sidebar",closeMode:"destroy"}),yt(null),U(null)},[ao,Kl,ue]),vd=_.useRef(null),mu=b.useCallback(()=>{yt(null),U(null),ys(null)},[]);_.useLayoutEffect(()=>{if(!st)return;const C=()=>{ue()||mu()},Q=()=>mu();C();const he=Vr.subscribe(C);return window.addEventListener($u,C),window.addEventListener("auth:unauthorized",Q),()=>{he(),window.removeEventListener($u,C),window.removeEventListener("auth:unauthorized",Q)}},[st,$t,ue,mu]);const _p=_.useMemo(()=>{if(!ao)return"";const C=$t.get(ao.id);return gl(ao,C?.activeProgram??null,C?.cwd??null,Ra,C?.shellTitle??null,C?.promptState??null).primary},[ao,$t]);b.useEffect(()=>{if(!Cr)return;let C=!1,Q=!1;const he=async()=>{if(!Q)try{const kt=await r1();if(C||Y(kt),!kt.available){C||Gr([]);return}const Kt=await n1();C||Gr(Kt)}catch{Q=!0,C||(Y({available:!1,version:null,reason:"tmux integration is unavailable with the current server build."}),Gr([]))}};he();const lt=setInterval(()=>{he()},4e3);return()=>{C=!0,clearInterval(lt)}},[Cr]);const ih=aa??gn,wd=ih==="shell",gu=ih==="tmux"&&zr.available,oo=_.useMemo(()=>x3(pn.map(C=>({...C,id:C.name})),C=>C.cwd??null,e("sidebar.ungrouped")),[pn,e]),lo=_.useMemo(()=>pn.filter(C=>C.recoveryCandidate===!0&&!C.connected&&!C.boundFrontendSessionId).sort((C,Q)=>(Q.lastActiveAt??Q.createdAt??0)-(C.lastActiveAt??C.createdAt??0)),[pn]);b.useEffect(()=>{!ne&&!(Dt&&gr)||nl()},[ne,Dt,gr,Tt.length,nl]);const Ll=(C,Q,he,lt=!1)=>{const kt=C.id===wt,Kt=C.id===hn,Mr=$t.get(C.id),{primary:Rn,secondary:Gn}=gl(C,Mr?.activeProgram??null,Mr?.cwd??null,Ra,Mr?.shellTitle??null,Mr?.promptState??null),$n=cd(Mr?.cwd??null),Vi=Q?Gn??($n&&$n!==Rn?$n:null):null,Ln=Mr?.gitStatus,la=`${Mr?.cwd||C.name}${Ln?`
|
|
186
186
|
⎇ ${Ln.branch} +${Ln.added} −${Ln.removed}`:""}`,Po=!!(Mr?.tuiProgress&&Mr.tuiProgress.state!=="remove"),Oo=Mr?.agentStatus==="working"||Po?"var(--success)":Mr?.agentStatus==="waiting"||Mr?.agentNeedsReview?"var(--warning)":Mr?.inCopyMode?"var(--tmux)":null;if(Kt&&gr&&!xr){const Ha=C.customName?C.name:Rn,qi=(co,kp)=>{const _d=kp.trim();_d?_d!==Ha&&Hi(co,_d):ls(co),Qn(null)};return s.jsx("input",{ref:co=>{X.current=co},type:"text",defaultValue:Ha,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(Ha.length,5)}ch`},onKeyDown:co=>{co.key==="Enter"?qi(C.id,co.target.value):co.key==="Escape"&&Qn(null)},onBlur:co=>qi(C.id,co.target.value)})}return s.jsx("div",{ref:kt?Ee:null,onContextMenu:Ha=>{Ha.preventDefault(),is({x:Ha.clientX,y:Ha.clientY}),fn(C.id)},...Tp(()=>gd(C.id)),className:lt?`group relative inline-flex h-5 shrink-0 items-center rounded-sm text-[11px] leading-none transition ${kt?"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 ${kt?"bg-surface-elevated text-foreground shadow-sm":"text-muted-foreground hover:bg-surface-elevated/50 hover:text-foreground"}`,style:!lt&&kt&&Oo?{boxShadow:`inset 2px 0 0 0 ${Oo}`}:!lt&&kt?{boxShadow:"inset 2px 0 0 0 rgb(var(--primary-rgb, 99 102 241))"}:void 0,title:la,children:s.jsx("button",{type:"button",...he??{},onClick:()=>th(C.id),className:`inline-flex min-w-0 flex-1 items-center gap-1 overflow-hidden text-left ${lt?"px-1":"py-1 pl-1 pr-1.5 sm:pl-1.5 sm:pr-2"} ${he?"cursor-grab active:cursor-grabbing":""}`,title:la,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:[$y(C.mode,Mr),Mr?.agentResumeRecovered&&s.jsx(Wc,{size:lt?9:10,className:"-ml-0.5 shrink-0 text-[color:var(--warning)]","aria-label":e("tab.resumeAgentAvailable")}),Po&&!Mr?.agentStatus&&s.jsx(jn,{size:lt?9:10,className:"-ml-0.5 shrink-0 animate-spin text-[color:var(--success)]"})]}),Vi?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] ${Mr?.inCopyMode?"text-[color:var(--tmux)]":""}`,children:Rn}),s.jsx("span",{className:"truncate text-[9px] text-muted-foreground/80 sm:text-[9.5px]",children:Vi})]}):s.jsx("span",{className:`whitespace-nowrap text-[11px] sm:text-[12px] ${Mr?.inCopyMode?"text-[color:var(--tmux)]":""}`,children:Rn})]})})})},Xl=()=>s.jsx(Ol,{droppableId:J1,type:"session",isDropDisabled:gr,children:(C,Q)=>{const he=Bs||Q.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":!Bn,"data-mobile-session-destroy-target":"","data-active":he?"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 ${Bn?he?"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(Ds,{size:28,strokeWidth:1.8}),s.jsx("span",{className:"px-2 text-center text-[11px] font-semibold leading-tight",children:e(he?"tab.releaseToClose":"tab.dragToClose")})]}),C.placeholder]})}}),_s=Dt&&gr,Bo=Pr&&gr,Ad=Jh(qr,Xr,_s?ur:0),_a=Bo?Ad+Vy:0,Qo=_s?Tt.find(C=>C.id===wt):null,Fs=Qo?$t.get(Qo.id):void 0,ah=Qo?gl(Qo,Fs?.activeProgram??null,Fs?.cwd??null,Ra,Fs?.shellTitle??null,Fs?.promptState??null).primary:"",Td=gr?Jr:null,oh=_s&&!Td&&Fs?Fs.agentStatus==="working"?"bg-gradient-to-r from-[rgb(var(--success-rgb)_/_0.08)] to-transparent":Fs.agentStatus==="waiting"?"bg-gradient-to-r from-[rgb(var(--warning-rgb)_/_0.14)] to-transparent":Fs.agentNeedsReview?"bg-gradient-to-r from-[rgb(var(--warning-rgb)_/_0.08)] to-transparent":Fs.inCopyMode?"bg-gradient-to-r from-[rgb(var(--tmux-rgb)_/_0.07)] to-transparent":"":"",Sd=s.jsxs("div",{className:"w-full h-full flex flex-col app-chrome-bg text-foreground",children:[Ne&&s.jsxs("div",{role:"alert","data-update-restart-error":!0,className:"fixed right-3 top-3 z-toast flex max-w-md items-start gap-3 rounded-xl border border-border bg-surface p-3 text-sm text-foreground shadow-xl",children:[s.jsx("p",{className:"break-words",children:Ne}),s.jsx("button",{type:"button",className:"shrink-0 text-primary","aria-label":e("common.close"),onClick:()=>ae(null),children:e("common.close")})]}),ws&&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:ws}),s.jsx("button",{type:"button",className:"min-h-11 px-2 text-primary",onClick:()=>Ss(""),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(CC,{rightInset:_a,workspace:we&&s.jsx(_.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(xU,{groupId:we,activeSessionId:wt,defaultSessionMode:gn,onOpenSidebar:ci,leftSidebarVisible:ne||_s,onToggleRightSidebar:Li,rightSidebarOpen:Ze||Bo},we)}),children:[s.jsxs("div",{"data-termdock-window-header":"true",className:`${gr?"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 ${_s?"flex justify-end":"flex justify-between"} ${_n?"h-10 sm:h-10":"h-9 sm:h-10"} ${oh}`,style:{position:gr?"absolute":void 0,marginRight:_a||void 0,display:Td?"none":void 0},children:[!_s&&s.jsxs("button",{type:"button",onClick:ci,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")}: ${ti.running} · ${e("agent.needsReview")}: ${ti.review}`,children:[s.jsx(dS,{size:14}),s.jsx(gO,{runningCount:ti.running,reviewCount:ti.review,className:"sm:hidden"})]}),_s?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:Qo?s.jsxs(s.Fragment,{children:[$y(Qo.mode,Fs),s.jsx("span",{className:`truncate text-[12px] font-medium ${Fs?.inCopyMode?"text-[color:var(--tmux)]":"text-foreground"}`,children:ah}),Fs?.agentStatus==="working"&&s.jsx("span",{title:Fs?.agentMessage??void 0,children:s.jsx(jn,{size:12,className:"shrink-0 animate-spin text-[color:var(--success)]"})}),Fs?.agentStatus==="waiting"&&s.jsx("span",{title:Fs?.agentMessage??void 0,children:s.jsx(Tf,{size:12,className:"shrink-0 animate-bounce-y text-[color:var(--warning)]"})}),!Fs?.agentStatus&&Fs?.agentNeedsReview&&s.jsx("span",{title:Fs?.agentMessage??void 0,children:s.jsx(xc,{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")})}):_n?s.jsxs(Vu,{onDragStart:Ei,onDragUpdate:Ui,onDragEnd:Zl,children:[Xl(),s.jsx(Ol,{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:[sa.map((Q,he)=>{let lt=0,kt=0;for(const Gn of Q.sessions){const $n=$t.get(Gn.id);$n?.agentStatus==="working"&&(lt+=1),($n?.agentStatus==="waiting"||$n?.agentNeedsReview)&&(kt+=1)}const Kt=Q.sessions.some(Gn=>Gn.id===wt),Mr=Fr.has(Q.key),Rn=Q.key==="";return s.jsx(Pl,{draggableId:`group-${Q.key||"__ungrouped__"}`,index:he,isDragDisabled:Rn,disableInteractiveElementBlocking:!0,children:(Gn,$n)=>s.jsxs("div",{ref:Gn.innerRef,...Gn.draggableProps,className:`flex w-fit shrink-0 flex-col justify-center gap-px rounded-md py-0.5 px-1 ring-1 transition-colors ${$n.isDragging?"bg-surface-elevated ring-primary/30 shadow-lg opacity-90":Kt?"bg-primary/[0.06] ring-primary/20":"bg-surface-2/40 ring-border/10"}`,children:[s.jsxs("button",{type:"button",...Rn?{}:Gn.dragHandleProps,onClick:()=>Kr(Q.key),className:`flex ${Mr?"":Q.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 ${Rn?"":"cursor-grab active:cursor-grabbing"} ${Kt?"text-primary/80":"text-muted-foreground/55"}`,title:Q.key||Q.label,children:[s.jsx(Ys,{size:9,className:`shrink-0 opacity-70 transition-transform ${Mr?"":"rotate-90"}`}),s.jsx("span",{className:"min-w-0 truncate",children:Q.label}),lt>0&&s.jsx("span",{className:"ml-auto h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--success)]"}),kt>0&&s.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--warning)] ${lt>0?"":"ml-auto"}`})]}),Mr?s.jsx("span",{className:"flex h-5 items-center text-[10px] leading-none text-muted-foreground/50",children:e("tab.sessionCount",{count:Q.sessions.length})}):s.jsx(Ol,{droppableId:`group-sessions:${Q.key}`,type:"session",direction:"horizontal",children:Vi=>s.jsxs("div",{ref:Vi.innerRef,...Vi.droppableProps,className:"flex items-center gap-px",children:[Q.sessions.map((Ln,la)=>s.jsx(Pl,{draggableId:Ln.id,index:la,disableInteractiveElementBlocking:!0,children:(Po,Oo)=>s.jsx("div",{ref:Po.innerRef,...Po.draggableProps,className:`flex shrink-0 items-center ${Oo.isDragging?"opacity-70":""}`,children:Ll(Ln,!1,Po.dragHandleProps,!0)})},Ln.id)),Vi.placeholder]})})]})},Q.key||"__ungrouped__")}),C.placeholder,s.jsx("button",{type:"button",onClick:()=>Do(),disabled:fu,"aria-busy":fu,className:"my-auto inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-surface-2 text-muted-foreground ring-1 ring-border/10 transition hover:bg-primary/15 hover:text-primary active:scale-95","aria-label":e("tab.new"),title:e("tab.new"),children:s.jsx(Zs,{size:14})})]})})]}):s.jsxs(Vu,{onDragStart:Ei,onDragUpdate:Ui,onDragEnd:Pa,children:[Xl(),s.jsx(Ol,{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:[ei.map((Q,he)=>Q.id===hn?s.jsx(_.Fragment,{children:s.jsx(Pl,{draggableId:Q.id,index:he,isDragDisabled:!0,children:kt=>s.jsx("div",{ref:kt.innerRef,...kt.draggableProps,className:"flex h-full items-center",children:Ll(Q,!0)})})},Q.id):s.jsx(_.Fragment,{children:s.jsx(Pl,{draggableId:Q.id,index:he,disableInteractiveElementBlocking:!0,children:(kt,Kt)=>s.jsx("div",{ref:kt.innerRef,...kt.draggableProps,className:`flex h-full shrink-0 items-center ${Kt.isDragging?"opacity-70":""}`,children:Ll(Q,!0,kt.dragHandleProps)})})},Q.id)),s.jsx("button",{type:"button",onClick:()=>Do(),disabled:fu,"aria-busy":fu,className:"ml-1 inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-surface-2 text-muted-foreground ring-1 ring-border/10 transition hover:bg-primary/15 hover:text-primary active:scale-95","aria-label":e("tab.new"),title:e("tab.new"),children:s.jsx(Zs,{size:14})}),C.placeholder]})})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[!_s&&ti.running>0&&s.jsx("span",{className:"hidden items-center gap-1 sm:inline-flex",children:s.jsx(l4,{count:ti.running,tone:"running",title:e("agent.aiRunning")})}),!_s&&Tt.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 ${Nn+1} of ${Tt.length}`,children:_l}),!Bo&&s.jsx("button",{type:"button",onClick:Li,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(d3,{size:14})})]})]}),uu&&$a&&jo?.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:_a||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:!Ua?.error&&(Ua?.status==="submitting"||Ua?.status==="waiting")?s.jsx(jn,{size:14,className:"animate-spin"}):s.jsx(Wc,{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:jo.agent?.displayName??"Agent"})}),s.jsx("div",{className:`truncate text-[10px] sm:text-[11px] ${Ua?.error?"text-destructive":"text-muted-foreground"}`,children:Ua?.error??(Ua?.status==="submitting"?e("tab.resumeAgentSubmitting"):Ua?.status==="waiting"?e("tab.resumeAgentWaiting"):e("tab.resumeAgentRecoveredHint"))})]}),s.jsx("button",{type:"button",disabled:!Ua?.error&&(Ua?.status==="submitting"||Ua?.status==="waiting"),onClick:()=>{Tn($a.id,jo.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:Ua?.error?e("common.retry"):e("tab.resumeAgentNow")}),s.jsx("button",{type:"button",onClick:()=>{Vr.getState().setAgentResumeRecovered($a.id,!1),rn(C=>C?.sessionId===$a.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(Mn,{size:13})})]}),s.jsx("div",{ref:Ye,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(KN,{terminalSettings:tr,colorTheme:f,toolbarPresets:Ps,showDebug:l&&gr,terminalFocusAvailable:gt,defaultSessionMode:gn,defaultTmuxSessionName:ia,connectionPrioritySessionId:ar,connectionPriorityReady:It,desktopRightSidebarEnabled:gr,onToggleRightSidebar:Li,desktopFloatingTitle:gr,desktopLeftSidebarPinned:_s,desktopPinnedLeftSidebarWidth:_s?ur:0,desktopViewportWidth:Xr,onSessionDataUpdate:du,onInitialViewportReady:xd,onInitialRecoveryRequired:Sp})})})]})}),!we&&s.jsx(wO,{reviewCount:ti.review,runningSessions:Cc,activeSessionId:wt,runningButtonEnabled:Qr,attentionButtonEnabled:Jn,isDesktopLayout:gr,containerElement:W,occlusionInsets:{right:_a}}),Cr&&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:$i,"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(a1,{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:$i,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(Mn,{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:()=>ct({fontSize:Math.max(8,Ct-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:Ct,onChange:C=>ct({fontSize:parseInt(C.target.value,10)}),className:"min-w-0 flex-1","aria-label":e("settings.font")}),s.jsx("button",{type:"button",onClick:()=>ct({fontSize:Math.min(32,Ct+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:[Ct,"px"]})]}),s.jsx(J$,{}),s.jsx("div",{"data-terminal-renderer-controls":"browser-fallback",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 Q=or===C;return s.jsx("button",{type:"button",onClick:()=>ct({rendererMode:C}),className:`flex-1 rounded px-2 py-1 text-[11px] font-medium transition ${Q?"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",nS,e("settings.darkTheme")],["light",VS,e("settings.lightTheme")]].map(([C,Q,he])=>{const lt=f===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 ${lt?"bg-primary/20 text-primary":"text-muted-foreground hover:bg-surface-elevated"}`,children:[s.jsx(Q,{size:12}),s.jsx("span",{children:he})]},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 Q=gn===C,he=C==="tmux"&&!zr.available;return s.jsx("button",{type:"button",disabled:he,onClick:()=>Oa(C,{userInitiated:!0}),className:`flex-1 rounded px-2 py-1 text-[11px] font-medium transition ${Q?"bg-primary/20 text-primary":he?"cursor-not-allowed text-muted-foreground/40":"text-muted-foreground hover:bg-surface-elevated"}`,title:he?zr.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(yl,{checked:l,size:"sm"})]}),s.jsxs("button",{type:"button",onClick:async()=>{const C=!y;w(C);try{const Q=await ja({preventSleep:C});w(Q.preventSleep),T(Q.networkAvailable),pe(Q.localAccess),qn(l0,{preventSleep:Q.preventSleep,networkAvailable:Q.networkAvailable,localAccess:Q.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(yl,{checked:y,size:"sm"})]})]})]}),s.jsxs("div",{className:"mt-3 space-y-2",children:[s.jsxs("button",{type:"button",role:"switch","aria-checked":Qr,"aria-label":e("sidebar.runningSessionButton"),onClick:()=>{Pn(!Qr)},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(Sf,{size:14,className:Qr?"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(yl,{checked:Qr,size:"sm"})]}),s.jsxs("button",{type:"button",role:"switch","aria-checked":Jn,"aria-label":e("sidebar.attentionButton"),onClick:()=>{oi(!Jn)},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(xc,{size:14,className:Jn?"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(yl,{checked:Jn,size:"sm"})]})]}),s.jsxs("button",{type:"button",onClick:()=>Wi(!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(i3,{size:14,className:S?"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(S?N&&F?"settings.notificationsBothOnSummary":N?"settings.notificationsAiOnSummary":F?"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(S?"common.on":"common.off")}),s.jsx("span",{children:"›"})]})]}),s.jsxs("button",{type:"button",onClick:()=>Sa(!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(Ys,{size:16,className:"shrink-0 text-muted-foreground"})]}),s.jsx(G$,{state:Te,pending:se,onCheck:()=>{un()},onConfirmRestart:()=>{yn()},desktopState:me?Se:void 0,desktopPending:Le,onCheckDesktop:me?()=>{Cn()}:void 0,onInstallDesktop:()=>{Ur()},desktopSnapshot:dt,desktopActions:ut?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:()=>{ut.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(tT,{size:13,className:"shrink-0 text-primary"}),e("settings.desktopSwitchService")]}),s.jsxs("button",{type:"button",onClick:()=>{rt(null),ut.revealDataDirectory().catch(C=>rt(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(Yu,{size:13,className:"shrink-0 text-primary"}),e("settings.desktopOpenDataDirectory")]})]}),Ge&&s.jsx("div",{className:"border-t border-border/10 px-3 py-2 text-[10px] text-muted-foreground",children:Ge})]}):void 0}),s.jsx(q$,{backendSessionId:wt?$t.get(wt)?.terminalSessionId??null:null}),s.jsx(Z$,{state:ze,onDismiss:()=>{Dn()}}),s.jsxs("div",{className:"mt-3 flex gap-2",children:[s.jsxs("button",{type:"button",onClick:()=>{to(null),Do({mode:"shell"}),$i()},className:`flex min-w-0 items-center justify-center gap-1.5 rounded-xl text-[13px] font-semibold transition active:scale-[0.98] ${wd?"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(aa==="shell"?"sidebar.confirmNewShell":"settings.shell"),children:[s.jsx(Zs,{size:14,className:wd?"shrink-0":"hidden"}),s.jsx(Zo,{size:12}),s.jsx("span",{className:wd?"whitespace-nowrap":"hidden",children:e(aa==="shell"?"sidebar.confirmNewShell":"settings.shell")})]}),s.jsxs("button",{type:"button",disabled:!zr.available,onClick:()=>{zr.available&&(to(null),Do({mode:"tmux"}),$i())},className:`flex min-w-0 items-center justify-center gap-1.5 rounded-xl text-[13px] font-semibold transition active:scale-[0.98] ${zr.available?gu?"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:zr.available?e(aa==="tmux"?"sidebar.confirmNewTmux":"settings.tmux"):zr.reason||e("settings.installTmuxHint"),children:[s.jsx(Zs,{size:14,className:gu?"shrink-0":"hidden"}),s.jsx(ru,{size:12}),s.jsx("span",{className:gu?"whitespace-nowrap":"hidden",children:e(aa==="tmux"?"sidebar.confirmNewTmux":"settings.tmux")})]})]}),(zr.available||pn.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 ${zr.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:zr.available?e("settings.sessions",{n:pn.length}):e("settings.tmuxUnavailable")})]}),s.jsx("button",{type:"button",onClick:C=>{C.preventDefault(),nl()},disabled:Be,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(wn,{size:12,className:Be?"animate-spin":""})})]}),s.jsx("div",{className:"px-2 pb-2",children:zr.available?pn.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:[oo.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(tu,{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(Q=>{const he=Q.boundFrontendSessionId??null,lt=!!(Q.connected||he),kt=he?Tt.find(qi=>qi.id===he)??null:null,Kt=Q.friendlyName?.trim()||null,Mr=Q.label&&Q.label!==Q.name?Q.label:null,Rn=Kt||Mr||Q.name,Gn=Kt||Mr?`tmux:${Q.name}`:null,$n=Q.clientCount&&Q.clientCount>0?t==="zh"?`网页连接 ${Q.clientCount}`:`Web clients ${Q.clientCount}`:null,Vi=Q.attached>0?t==="zh"?`原生 tmux ${Q.attached}`:`Native tmux ${Q.attached}`:null,Ln=[Gn,lt?Q.restorable?e("settings.restorable"):e("settings.attached"):null,$n,Vi].filter(qi=>!!qi),la=[e("settings.windows",{n:Q.windows}),Q.createdAt?new Date(Q.createdAt).toLocaleDateString():null].filter(qi=>!!qi),Po=er===Q.name,Oo=Or===Q.name,Ha=ss===Q.name;return s.jsxs("div",{className:`flex items-start gap-2 rounded-lg px-2.5 py-2 ${Po?"bg-destructive/10 ring-1 ring-destructive/40":"bg-surface"}`,children:[s.jsx(ru,{size:13,className:lt?"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:Rn}),Q.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"})]}),Ln.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:Ln.map(qi=>s.jsx("span",{className:"max-w-full truncate",children:qi},qi))}),(Q.program||Q.cwd)&&s.jsxs("div",{className:"grid min-w-0 gap-0.5 text-[10px] text-muted-foreground",children:[Q.program&&s.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[s.jsx(QT,{size:10,className:"shrink-0 text-muted-foreground/70"}),s.jsx("span",{className:"truncate text-foreground/75",children:Q.program})]}),Q.cwd&&s.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[s.jsx(tu,{size:10,className:"shrink-0 text-muted-foreground/70"}),s.jsx("span",{className:"truncate",children:Q.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:la.map(qi=>s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(xT,{size:10,className:"shrink-0 text-muted-foreground/60"}),qi]},qi))})]}),Po?s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",disabled:Oo,onClick:()=>{Cp(Q.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:Oo?"…":e("settings.destroy")}),s.jsx("button",{type:"button",disabled:Oo,onClick:()=>{nr(null),ys(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:()=>{kt?th(kt.id):(Hn(Q.name),Do({mode:"tmux",tmuxSessionName:Q.name}))},disabled:Ha,className:`shrink-0 inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-[11px] font-medium transition disabled:opacity-50 ${lt?"bg-surface text-foreground hover:bg-surface-elevated":Ha?"bg-primary/10 text-primary":"bg-primary/15 text-primary hover:bg-primary/25"}`,children:Ha?s.jsxs(s.Fragment,{children:[s.jsx(jn,{size:10,className:"animate-spin"}),e("settings.attaching")]}):e(lt?"settings.attached":"settings.attach")}),s.jsx("button",{type:"button",disabled:Oo,onClick:()=>{ys(null),nr(Q.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 ${Q.name}`,children:s.jsx(Ds,{size:12})})]})]},Q.name)})]},C.key||"__ungrouped_tmux__")),Zn&&s.jsx("p",{className:"px-2 text-[11px] text-destructive",children:Zn})]}):s.jsx("p",{className:"px-2 py-1.5 text-[11px] text-muted-foreground",children:zr.reason||e("settings.installTmuxHint")})})]}),s.jsxs("button",{type:"button",onClick:()=>Fa(!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(l3,{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:Ps.length})}),s.jsx("span",{children:"›"})]})]}),s.jsxs("button",{type:"button",onClick:()=>jt(!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(G0,{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 Q=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 ${Q?"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 vA()}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(m3,{size:14}),e("settings.signOut")]})]})]})})]}),ao&&s.jsxs(s.Fragment,{children:[s.jsx(SQ,{sessionId:ao.id,confirmButton:vd,onConfirm:sh,onCancel:mu,isCurrent:ue}),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:()=>{yt(null),U(null),ys(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 ${R&&gr?"":"inset-x-3 bottom-6 mx-auto max-w-sm sm:bottom-auto sm:top-[15%]"}`,style:R&&gr?{...By(R),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:_p}),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",ref:vd,onClick:sh,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(Ds,{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")})]})]}),Zn&&s.jsx("p",{className:"px-4 py-2 text-[11px] text-destructive",children:Zn})]}),s.jsx("div",{className:"border-t border-border/15 px-3 py-2",children:s.jsx("button",{type:"button",onClick:()=>{yt(null),U(null),ys(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")})})]})]}),Xn&&(()=>{const C=Tt.find($n=>$n.id===Xn);if(!C)return null;const Q=$t.get(C.id),{primary:he}=gl(C,Q?.activeProgram??null,Q?.cwd??null,Ra),lt=gr,kt=lt?By(cr):{paddingBottom:a},Kt=lt?"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%]",Mr=lt?"border-b border-border/15 px-3 py-2":"border-b border-border/15 px-4 py-3",Rn=lt?"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",Gn=lt?"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 ${lt?"bg-transparent":"bg-[var(--app-backdrop-soft)] backdrop-blur-sm"}`,onClick:ht,"aria-label":"Close menu"}),s.jsxs("div",{className:Kt,style:kt,children:[s.jsxs("div",{className:Mr,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:he}),Q?.cwd&&s.jsx("div",{className:"mt-0.5 truncate text-[11px] text-muted-foreground/80",children:Q.cwd})]}),s.jsxs("div",{className:"flex flex-col py-1",children:[s.jsxs("button",{type:"button",onClick:()=>{const $n=cr;ht(),vr($n),Qn(C.id)},className:`${Rn} text-foreground hover:bg-surface-2`,children:[s.jsx("span",{className:`${Gn} bg-primary/15 text-primary`,children:s.jsx(vS,{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:!Q?.cwd,onClick:()=>{rh(C.id),ht()},className:`${Rn} ${Q?.cwd?"text-foreground hover:bg-surface-2":"text-muted-foreground/50 cursor-not-allowed"}`,children:[s.jsx("span",{className:`${Gn} bg-surface-2 text-muted-foreground`,children:s.jsx(c3,{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")})]}),br&&br===Q?.cwd&&s.jsx("span",{className:"ml-auto text-[11px] text-primary",children:e("tab.copied")})]}),(()=>{const $n=s1(C.id),Vi=$n??Ct;return s.jsxs("div",{className:`${Rn} text-foreground`,children:[s.jsx("span",{className:`${Gn} bg-surface-2 text-muted-foreground`,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.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:()=>{Xh(C.id,Vi-1),tn(Ln=>Ln+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:[Vi,"px"]}),s.jsx("button",{type:"button",onClick:()=>{Xh(C.id,Vi+1),tn(Ln=>Ln+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:"+"}),$n!==null&&s.jsx("button",{type:"button",onClick:()=>{Xh(C.id,null),tn(Ln=>Ln+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")})]})]})})(),Q?.agentNativeSessionId&&Q.agentStatus!=="working"&&Q.agentStatus!=="waiting"&&Q.terminalSessionId&&s.jsxs("button",{type:"button",onClick:()=>{const $n=Q.terminalSessionId;$n&&(ht(),Tn(C.id,$n))},className:`${Rn} text-foreground hover:bg-surface-2`,children:[s.jsx("span",{className:`${Gn} bg-[rgb(var(--success-rgb)_/_0.14)] text-[color:var(--success)]`,children:s.jsx(Wc,{size:14})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsxs("span",{className:"block font-medium",children:[e("tab.resumeAgent"),Q.agent?.displayName?` · ${Q.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:()=>{ht(),kl(C.id)},className:`${Rn} text-destructive hover:bg-destructive/10`,children:[s.jsx("span",{className:`${Gn} bg-destructive/15 text-destructive`,children:s.jsx(Ds,{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:()=>{ht(),Kl({sessionId:C.id,source:"tab-menu",closeMode:"auto"})},className:`${Rn} text-destructive hover:bg-destructive/10`,children:[s.jsx("span",{className:`${Gn} bg-destructive/15 text-destructive`,children:s.jsx(Mn,{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")})]})]}),!lt&&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:()=>{ht()},children:e("tab.longPressTip")})]}),!lt&&s.jsx("div",{className:"border-t border-border/15 px-3 py-2",children:s.jsx("button",{type:"button",onClick:ht,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")})})]})]})})(),hn&&xr&&gr&&(()=>{const C=Tt.find(Ln=>Ln.id===hn);if(!C)return null;const Q=$t.get(C.id),{primary:he}=gl(C,Q?.activeProgram??null,Q?.cwd??null,Ra,Q?.shellTitle??null,Q?.promptState??null),lt=C.customName?C.name:he,kt=Ln=>{const la=Ln.trim();la?la!==lt&&Hi(C.id,la):ls(C.id),Qn(null),vr(null)},Kt=300,Mr=160,Rn=xr.x,Gn=xr.y,$n=Math.min(Math.max(Rn-Kt/2,12),window.innerWidth-Kt-12),Vi=Gn+Mr+20>window.innerHeight?Math.max(Gn-Mr-12,12):Gn+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:()=>{Qn(null),vr(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:`${$n}px`,top:`${Vi}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:he}),Q?.cwd&&s.jsx("div",{className:"mt-0.5 truncate text-[11px] text-muted-foreground/70",children:Q.cwd})]}),s.jsxs("form",{className:"px-3 py-2.5",onSubmit:Ln=>{Ln.preventDefault();const la=new FormData(Ln.currentTarget).get("session-name");kt(typeof la=="string"?la:"")},children:[s.jsx("input",{ref:Ln=>{X.current=Ln,Ln&&!be.current&&(be.current=!0,Ln.focus({preventScroll:!0}),Ln.select())},type:"text",name:"session-name",defaultValue:lt,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:Ln=>{Ln.key==="Escape"&&(Ln.stopPropagation(),Qn(null),vr(null))}}),s.jsxs("div",{className:"mt-2.5 flex gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{Qn(null),vr(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")})]})]})]})]})})(),hn&&!gr&&(()=>{const C=Tt.find(Kt=>Kt.id===hn);if(!C)return null;const Q=$t.get(C.id),{primary:he}=gl(C,Q?.activeProgram??null,Q?.cwd??null,Ra,Q?.shellTitle??null,Q?.promptState??null),lt=C.customName?C.name:he,kt=Kt=>{const Mr=Kt.trim();Mr?Mr!==lt&&Hi(C.id,Mr):ls(C.id),Qn(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:()=>Qn(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:Kt=>{Kt.preventDefault();const Mr=new FormData(Kt.currentTarget).get("session-name");kt(typeof Mr=="string"?Mr:"")},children:[s.jsx("input",{ref:Kt=>{X.current=Kt,Kt&&!be.current&&(be.current=!0,Kt.focus({preventScroll:!0}),Kt.select())},type:"text",name:"session-name",defaultValue:lt,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:Kt=>{Kt.key==="Escape"&&(Kt.stopPropagation(),Qn(null))}}),s.jsxs("div",{className:"mt-3 flex gap-2",children:[s.jsx("button",{type:"button",onClick:()=>Qn(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")})]})]})]})]})})(),oa&&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:()=>Sa(!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:()=>Sa(!1),className:"rounded-full bg-surface-2 p-2 text-muted-foreground",children:s.jsx(Mn,{size:18})})]}),s.jsxs("div",{className:"overflow-y-auto overscroll-contain p-4",children:[s.jsx(_C,{state:de,onCopy:C=>{el(C,"setup")},copied:ce==="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:J,onChange:C=>Re(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:Xe,onClick:()=>{Tc()},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(Xe?"settings.saving":"common.save")}),s.jsx("button",{type:"button",disabled:Xe,onClick:()=>{Sc()},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:[de.url&&s.jsxs("button",{type:"button",onClick:()=>{el(de.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: ",de.url]}),s.jsx("span",{className:"shrink-0 rounded-full bg-primary/10 px-2 py-0.5 text-[10px] font-medium",children:ce==="lan"?"Copied":e("common.copy")})]}),de.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:de.interfaces.map(C=>{const Q=C.url??`${de.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 ${Q}`,className:"h-28 w-28"})}),s.jsxs("button",{type:"button",onClick:()=>{el(Q,`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:Q}),s.jsx("span",{className:"shrink-0 text-[10px]",children:ce===`ip-${C.address}`?"Copied":e("common.copy")})]})]},`${C.name}-${C.address}`)})})]}),s.jsxs("div",{className:"text-muted-foreground",children:[de.httpsEnabled?e("settings.httpsActive"):e("settings.httpsInactive"),!de.caAvailable&&` · ${e("settings.caMissing")}`]}),de.reason&&s.jsx("div",{className:"text-[color:var(--warning)]",children:de.reason}),ve&&s.jsx("div",{className:"text-destructive",children:ve})]})]})]})]}),mi&&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:()=>Wi(!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:()=>Wi(!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(Mn,{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"):xh()?e("settings.notificationsMasterHint"):e("settings.notificationsUnsupported")}),xh()&&!wA()&&s.jsx("div",{className:"mt-1.5 text-[11px] leading-relaxed text-[var(--warning)]",children:e("settings.notificationsIOSInstallHint")})]}),s.jsx("button",{type:"button",onClick:()=>{ms()},disabled:!xh()||Z==="denied",className:"shrink-0 transition disabled:cursor-not-allowed","aria-pressed":S,children:s.jsx(yl,{checked:S,disabled:!xh()||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"),": ",ea()?e("settings.notificationsPermissionSystem"):Z]}),s.jsx("button",{type:"button",disabled:!S||Z!=="granted"||ps==="checking",onClick:()=>{Gi()},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(ps==="checking"?"settings.notificationsTestChecking":"settings.notificationsTest")}),ea()?.openNotificationSettings&&s.jsx("button",{type:"button",onClick:()=>{ea()?.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")})]}),ps!=="idle"&&ps!=="checking"&&s.jsx("div",{className:`mt-2 text-[11px] leading-relaxed ${ps==="delivered"?"text-primary":"text-[var(--warning)]"}`,children:e(ps==="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,Q,he])=>{const lt=$===C;return s.jsxs("button",{type:"button",disabled:!S,onClick:()=>Os(C),className:`min-w-0 rounded-lg px-2 py-2 text-left transition ${lt&&S?"bg-primary/15 text-primary":S?"text-muted-foreground hover:bg-surface-elevated hover:text-foreground":"cursor-not-allowed text-muted-foreground/40"}`,title:he,children:[s.jsx("span",{className:"block truncate text-[11px] font-semibold",children:Q}),s.jsx("span",{className:"mt-0.5 block truncate text-[9px] opacity-80",children:he})]},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:!S,onClick:()=>Zr(!N),className:"shrink-0 transition disabled:cursor-not-allowed","aria-pressed":N&&S,children:s.jsx(yl,{checked:N&&S,disabled:!S})})]}),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:!S,onClick:()=>vn(!F),className:"shrink-0 transition disabled:cursor-not-allowed","aria-pressed":F&&S,children:s.jsx(yl,{checked:F&&S,disabled:!S})})]})]}),s.jsx("p",{className:"mt-2 text-[10px] text-muted-foreground",children:e("settings.notificationsFutureHint")})]})]})]})]}),pi&&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:()=>Fa(!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:()=>Fa(!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(Mn,{size:18})})]}),s.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto p-4 sm:p-6",children:s.jsx(z$,{presets:Ps,selectedPresetId:Mo,onSelectPreset:so,onUpdatePreset:(C,Q)=>{no(he=>Wu(he.map(lt=>lt.id===C?Q(lt):lt)))},onAddPreset:()=>{const C=`preset-${Date.now()}`;no(Q=>Wu([...Q,{id:C,label:`Preset ${Q.length}`,programs:[],includeAlt:!1,rowLayout:[3,3],actions:[],showOnDesktop:!1}])),so(C)},onRemovePreset:C=>{no(Q=>Wu(Q.filter(he=>he.id!==C)))},onResetDefaults:()=>{no(D0()),so("default")}})})]})]}),At&&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:()=>jt(!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:()=>jt(!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(Mn,{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(W$,{}),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:Tt.map(C=>{const Q=$t.get(C.id),he=Q?.activeProgramRaw??null,lt=Q?.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:"})," ",lt||"—"]}),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:"})," ",he||"—"]})]},`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:Q,hint:he})=>s.jsxs("div",{children:[s.jsx("div",{className:"mb-0.5 text-[11px] font-medium text-foreground",children:Q}),s.jsx("div",{className:"text-[10px] text-muted-foreground",children:he}),s.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1",children:[Jt[C].map(lt=>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:[lt,s.jsx("button",{type:"button",onClick:()=>{const kt={...Jt,[C]:Jt[C].filter(Kt=>Kt!==lt)};Yr(kt),C==="shellNames"&&(Ra=new Set(kt.shellNames)),jx(kt).catch(()=>{})},className:"ml-0.5 text-muted-foreground hover:text-destructive",children:"×"})]},lt)),s.jsx("input",{placeholder:e("settings.addTag"),className:"w-16 rounded bg-surface px-1.5 py-0.5 text-[11px] font-mono",onKeyDown:lt=>{if(lt.key!=="Enter")return;const kt=lt.target.value.trim().toLowerCase();if(!kt||Jt[C].includes(kt))return;const Kt={...Jt,[C]:[...Jt[C],kt]};Yr(Kt),C==="shellNames"&&(Ra=new Set(Kt.shellNames)),lt.target.value="",jx(Kt).catch(()=>{})}})]})]},C)),s.jsx("button",{type:"button",onClick:()=>{AA().then(C=>{Yr(C),Ra=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")}),D.map((C,Q)=>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:he=>{const lt=D.map((kt,Kt)=>Kt===Q?{...kt,enabled:he.target.checked}:kt);O(lt),qn(Na,lt),Ke(!0),vu(lt).then(kt=>{O(kt),qn(Na,kt)}).catch(()=>{}).finally(()=>Ke(!1))}}),s.jsxs("select",{value:C.matchType,onChange:he=>{const lt=D.map((kt,Kt)=>Kt===Q?{...kt,matchType:he.target.value}:kt);O(lt),qn(Na,lt),Ke(!0),vu(lt).then(kt=>{O(kt),qn(Na,kt)}).catch(()=>{}).finally(()=>Ke(!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:he=>{const lt=D.map((kt,Kt)=>Kt===Q?{...kt,pattern:he.target.value}:kt);O(lt),qn(Na,lt)},onBlur:()=>{Ke(!0),vu(D).then(he=>{O(he),qn(Na,he)}).catch(()=>{}).finally(()=>Ke(!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:he=>{const lt=D.map((kt,Kt)=>Kt===Q?{...kt,output:he.target.value}:kt);O(lt),qn(Na,lt)},onBlur:()=>{Ke(!0),vu(D).then(he=>{O(he),qn(Na,he)}).catch(()=>{}).finally(()=>Ke(!1))},placeholder:"output",className:"w-28 rounded bg-surface px-2 py-1 text-[11px]"}),s.jsx("button",{type:"button",onClick:()=>{const he=D.filter((lt,kt)=>kt!==Q);O(he),qn(Na,he),Ke(!0),vu(he).then(lt=>{O(lt),qn(Na,lt)}).catch(()=>{}).finally(()=>Ke(!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=[...D,{id:`rule-${Date.now()}`,enabled:!0,priority:100,matchType:"includes",pattern:"",output:""}];O(C),qn(Na,C),Ke(!0),vu(C).then(Q=>{O(Q),qn(Na,Q)}).catch(()=>{}).finally(()=>Ke(!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:()=>{Ke(!0),TA().then(C=>{O(C),qn(Na,C)}).catch(()=>{}).finally(()=>Ke(!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:ke?e("settings.saving"):G?`${D.length} rules`:"…"})]})]})]})]})]})]}),tt&&s.jsx(Q$,{isOpen:tt,onClose:()=>Rt(!1)}),!_s&&s.jsx(oy,{isOpen:ne,drawerWidthPx:As,onClose:()=>On("left-sidebar"),onOpen:ki,sessions:Tt,activeSessionId:wt,sessionStates:$t,onNewSession:C=>Do(C),recoverableTmuxSessions:lo,recoverableTmuxSessionsLoading:Be,onRefreshRecoverableTmuxSessions:()=>{nl()},onCloseRecoverableTmuxSession:pu,onCloseSession:kl,onSplitSession:kc,onCloseSplit:C=>window.dispatchEvent(new CustomEvent("close-terminal-split",{detail:C})),onRemoveFromSplit:C=>window.dispatchEvent(new CustomEvent("remove-terminal-split-pane",{detail:C})),splitWorkspaces:mt,onSetSplitLayout:Lc,onReorderSplitWorkspace:bd,onRenameSplitWorkspace:sl,onCombineSplitSessions:yd,onReorderSessions:Qs,onSessionMenu:gd,onOpenSettings:hi,onJumpToNextAttention:za.length>0?rl:void 0,onOpenQuota:()=>Rt(!0),updateState:Te,updateActionPending:se,onConfirmUpdateRestart:yn,onRetryUpdate:un,serverHealthState:ze,tmuxAvailable:zr.available,defaultSessionMode:gn,onTogglePinned:gr?Fn:void 0}),!Bo&&s.jsx(ly,{isOpen:Ze,sessionId:wt,drawerWidthPx:Gl,onClose:()=>On("right-sidebar"),onOpen:Ba,rightSidebarFilePreviewOpen:li,rightSidebarFilePreviewCloseSignal:ir,onOpenRightSidebarFilePreview:Sl,onCloseRightSidebarFilePreview:ql,rightSidebarRepoPickerOpen:Xt,rightSidebarRepoPickerCloseSignal:Wt,onOpenRightSidebarRepoPicker:ui,onCloseRightSidebarRepoPicker:Js,markdownOutlineOpen:et,markdownOutlineCloseSignal:Et,onOpenMarkdownOutline:di,onCloseMarkdownOutline:Xo,markdownImageLightboxOpen:xt,markdownImageLightboxCloseSignal:$e,onOpenMarkdownImageLightbox:na,onCloseMarkdownImageLightbox:Cs,onTogglePinned:gr?os:void 0}),vt&&!c&&s.jsx("button",{type:"button",onClick:Ii,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"})]})}),Oe&&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 ${Oe.tone==="success"?"border-[rgb(var(--success-rgb)_/_0.24)] bg-surface-elevated text-foreground":"border-destructive/30 bg-surface-elevated text-destructive"}`,role:Oe.tone==="error"?"alert":"status",children:[Oe.tone==="success"?s.jsx(Wc,{size:14,className:"shrink-0 text-[color:var(--success)]"}):s.jsx(Tf,{size:14,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1",children:Oe.message}),s.jsx("button",{type:"button",onClick:()=>_t(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(Mn,{size:12})})]}),l&&s.jsxs(s.Fragment,{children:[!gr&&s.jsx(kC,{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(St,null,2)})]})]})]}),Cd=bt?null:s.jsx(_A,{className:"z-modal-panel",status:"正在恢复终端…"});return gr?s.jsxs("div",{className:"w-screen h-full flex flex-row",children:[_s&&s.jsxs(s.Fragment,{children:[s.jsx("div",{ref:ds,style:{width:ur,flexShrink:0,height:"100%"},children:s.jsx(oy,{isOpen:ne,drawerWidthPx:ur,onClose:Xs,onOpen:ki,sessions:Tt,activeSessionId:wt,sessionStates:$t,onNewSession:C=>Do(C),recoverableTmuxSessions:lo,recoverableTmuxSessionsLoading:Be,onRefreshRecoverableTmuxSessions:()=>{nl()},onCloseRecoverableTmuxSession:pu,onCloseSession:kl,onSplitSession:kc,onCloseSplit:C=>window.dispatchEvent(new CustomEvent("close-terminal-split",{detail:C})),onRemoveFromSplit:C=>window.dispatchEvent(new CustomEvent("remove-terminal-split-pane",{detail:C})),splitWorkspaces:mt,onSetSplitLayout:Lc,onReorderSplitWorkspace:bd,onRenameSplitWorkspace:sl,onCombineSplitSessions:yd,onReorderSessions:Qs,onSessionMenu:gd,onOpenSettings:hi,onJumpToNextAttention:za.length>0?rl:void 0,onOpenQuota:()=>Rt(!0),updateState:Te,updateActionPending:se,onConfirmUpdateRestart:yn,onRetryUpdate:un,serverHealthState:ze,tmuxAvailable:zr.available,defaultSessionMode:gn,pinned:!0,onTogglePinned:Fn})}),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:Ko})]}),s.jsxs("div",{className:"relative flex-1 min-w-0 h-full overflow-hidden",children:[Sd,Bo&&s.jsxs("div",{className:"absolute inset-y-0 right-0 z-20 flex",style:{width:_a},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:Ac}),s.jsx("div",{style:{width:Ad,flexShrink:0,height:"100%"},children:s.jsx(ly,{isOpen:!0,sessionId:wt,drawerWidthPx:Ad,onClose:Qa,onOpen:Ba,pinned:!0,onTogglePinned:os,rightSidebarFilePreviewOpen:li,rightSidebarFilePreviewCloseSignal:ir,onOpenRightSidebarFilePreview:Sl,onCloseRightSidebarFilePreview:ql,rightSidebarRepoPickerOpen:Xt,rightSidebarRepoPickerCloseSignal:Wt,onOpenRightSidebarRepoPicker:ui,onCloseRightSidebarRepoPicker:Js,markdownOutlineOpen:et,markdownOutlineCloseSignal:Et,onOpenMarkdownOutline:di,onCloseMarkdownOutline:Xo,markdownImageLightboxOpen:xt,markdownImageLightboxCloseSignal:$e,onOpenMarkdownImageLightbox:na,onCloseMarkdownImageLightbox:Cs})})]})]}),s.jsx(Ty,{sessionId:wt}),Cd]}):s.jsxs(s.Fragment,{children:[Sd,s.jsx(Ty,{sessionId:wt}),Cd]})}const hz=Object.freeze(Object.defineProperty({__proto__:null,default:bU,runServiceUpdateConfirmation:N4},Symbol.toStringTag,{value:"Module"}));export{Up as $,g0 as A,N0 as B,QF as C,gC as D,R0 as E,o3 as F,PF as G,Wc as H,Sf as I,h3 as J,l3 as K,c3 as L,YT as M,oS as N,MS as O,dS as P,y0 as Q,wn as R,Wl as S,i4 as T,a1 as U,VS as V,YI as W,Ds as X,m3 as Y,tC as Z,aC as _,xC as a,vC as a0,LU as a1,_U as a2,A3 as a3,EU as a4,NU as a5,IU as a6,Lv as a7,uz as a8,l5 as a9,L1 as aa,ip as ab,yy as ac,w3 as ad,tf as ae,cg as af,RC as ag,bF as ah,kU as ai,c5 as aj,vN as ak,iu as al,cy as am,Xm as an,Pi as ao,dz as ap,L3 as aq,_f as b,L$ as c,hz as d,yC as e,Af as f,qA as g,GA as h,s3 as i,a3 as j,I0 as k,dF as l,AT as m,E0 as n,QO as o,Yu as p,ag as q,FT as r,VT as s,JT as t,u3 as u,nS as v,d3 as w,bS as x,vS as y,AS as z};
|