@pi-chamber/web 1.0.3-rc.1 → 1.0.4-rc.1
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/assets/DiagramView-DfZMQkXY.js +1 -0
- package/dist/assets/{DiffView-CXg8TAtI.js → DiffView-BjWUdbL5.js} +6 -6
- package/dist/assets/FileSaveConflictDialog-u5L4k_5k.js +3 -0
- package/dist/assets/FilesView-qP1ypN9J.js +6 -0
- package/dist/assets/GitHubDetailScaffold-zCKCy5OJ.js +11 -0
- package/dist/assets/GitHubLinkPicker-CwxKY3lN.js +1 -0
- package/dist/assets/GitHubListPrimitives-Ck3zllel.js +1 -0
- package/dist/assets/GitView-y2k2i4gR.js +9 -0
- package/dist/assets/IssuesSurface-HWgR87N3.js +7 -0
- package/dist/assets/JsonTreeView-DSuC4naV.js +1 -0
- package/dist/assets/{MarkdownRendererImpl-CeYMkg1A.js → MarkdownRendererImpl-CT5ln9em.js} +5 -5
- package/dist/assets/PatchDiff-DArTeWeK.js +1 -0
- package/dist/assets/PierreDiffViewer-DQKujzLb.js +134 -0
- package/dist/assets/PullRequestsSurface-Cfb1wSvC.js +2 -0
- package/dist/assets/SessionSwitcherContent-DEGJyZBl.js +1 -0
- package/dist/assets/SessionSwitcherDropdown-cC9wVBH7.js +2 -0
- package/dist/assets/SessionUnreadDot-CELKNVIM.js +1 -0
- package/dist/assets/SettingsView-CZvRRgJe.js +6 -0
- package/dist/assets/SettingsWindow-CZM1dmVb.js +1 -0
- package/dist/assets/ToolOutputDialog-DClOSbJc.js +8 -0
- package/dist/assets/ToolPartDiffPreview-BaFiGUDE.js +1 -0
- package/dist/assets/{VirtualizedFileDiff-CV_Cpmqu.js → VirtualizedFileDiff-D6KbvKc6.js} +3 -3
- package/dist/assets/Virtualizer-wpC51ZBQ.js +1 -0
- package/dist/assets/collapsible-DhV9d4dT.js +1 -0
- package/dist/assets/computeVirtualFileMetrics-CeMpF2xC.js +3 -0
- package/dist/assets/{contextFileOpenGuard-BA2pkQY_.js → contextFileOpenGuard-Ck5u_kAP.js} +1 -1
- package/dist/assets/gitStatusPredicates-DEBSqUNE.js +1 -0
- package/dist/assets/githubLink-DT7i2NlH.js +10 -0
- package/dist/assets/index-6IO1AcJI.js +10 -0
- package/dist/assets/index-BAmzAlNx.css +1 -0
- package/dist/assets/index-eDf4LKLY.js +1 -0
- package/dist/assets/main-BczEScAA.js +2 -0
- package/dist/assets/main-CHLNMYeJ.js +136 -0
- package/dist/assets/markdownCore-C4Gk5Zht.js +2 -0
- package/dist/assets/miniChat-Do3hE87Z.js +2 -0
- package/dist/assets/mobile-CTnihwfa.js +2 -0
- package/dist/assets/permissionStore-B9Hkrqny.js +1 -0
- package/dist/assets/pi-session-focus-preference-LDVCJ_YR.js +10 -0
- package/dist/assets/renderDiffWithHighlighter-CDsgOnkH.js +1 -0
- package/dist/assets/renderElectronMiniChatApp-DSa3gYqR.js +2 -0
- package/dist/assets/renderFileWithHighlighter-TpKRyfCY.js +1 -0
- package/dist/assets/renderMobileApp-CPE-3uMl.js +11 -0
- package/dist/assets/runtimeEndpointReset-CzJfovWI.js +62 -0
- package/dist/assets/{runtimeSurface-BdndJV2m.js → runtimeSurface-DW_Ia4q3.js} +1 -1
- package/dist/assets/shell-CjFT_Tl9.js +1 -0
- package/dist/assets/sprite-HGQGInUp.js +6510 -0
- package/dist/assets/useAppFontEffects-CG3_yteE.js +212 -0
- package/dist/assets/{useFilesViewSearch-CI5Gy1cp.js → useFilesViewSearch-C_LzYIgD.js} +1 -1
- package/dist/assets/useGitHubRemoteSearch-DsxWOzKZ.js +1 -0
- package/dist/assets/useSwitcherItems-BmoCnS9W.js +1 -0
- package/dist/assets/vendor-base-ui-DIkTOIJS.js +1 -0
- package/dist/assets/{vendor-beautiful-mermaid-D3YCkKz7.js → vendor-beautiful-mermaid-DApbjBp2.js} +1 -1
- package/dist/assets/vendor-boot-DyL2td56.js +69 -0
- package/dist/assets/vendor-codemirror-autocomplete-DsFn4GLp.js +1 -0
- package/dist/assets/vendor-codemirror-lang-angular-B_NMmBbS.js +1 -0
- package/dist/assets/vendor-codemirror-lang-cpp-GOE7Gjd0.js +1 -0
- package/dist/assets/vendor-codemirror-lang-css-Dwf2XpnZ.js +1 -0
- package/dist/assets/vendor-codemirror-lang-go-C2KHbcll.js +7 -0
- package/dist/assets/vendor-codemirror-lang-html-DcKqyeGk.js +1 -0
- package/dist/assets/vendor-codemirror-lang-java-6eGbyB2k.js +1 -0
- package/dist/assets/vendor-codemirror-lang-javascript-DpTUrvx8.js +13 -0
- package/dist/assets/vendor-codemirror-lang-jinja-xSUJjXhr.js +1 -0
- package/dist/assets/vendor-codemirror-lang-json-CLGxdOCz.js +1 -0
- package/dist/assets/vendor-codemirror-lang-less-6nXi1rS9.js +1 -0
- package/dist/assets/vendor-codemirror-lang-liquid-B9hmb9P8.js +1 -0
- package/dist/assets/vendor-codemirror-lang-markdown-DmFP9s6x.js +1 -0
- package/dist/assets/vendor-codemirror-lang-php-DC6To8iX.js +1 -0
- package/dist/assets/vendor-codemirror-lang-python-yuxIkjit.js +3 -0
- package/dist/assets/vendor-codemirror-lang-rust-di1Sjz-0.js +1 -0
- package/dist/assets/vendor-codemirror-lang-sass-BWpV9NPV.js +1 -0
- package/dist/assets/{vendor-codemirror-lang-sql-HpQWHJjv.js → vendor-codemirror-lang-sql-C_RazIaB.js} +2 -2
- package/dist/assets/vendor-codemirror-lang-vue-BYL0r7KR.js +1 -0
- package/dist/assets/vendor-codemirror-lang-wast-BiVarhcz.js +1 -0
- package/dist/assets/vendor-codemirror-lang-xml-Cn1lY1ts.js +1 -0
- package/dist/assets/vendor-codemirror-lang-yaml-BZ6mZw9L.js +1 -0
- package/dist/assets/vendor-codemirror-language-data-DglcKYWT.js +2 -0
- package/dist/assets/vendor-codemirror-search-DaE6R5gH.js +2 -0
- package/dist/assets/{vendor-elkjs-mzfkf0ML.js → vendor-elkjs-D27273Ms.js} +1 -1
- package/dist/assets/{vendor-heic2any-BHsbokcA.js → vendor-heic2any-pq-UTQQR.js} +1 -1
- package/dist/assets/vendor-lezer-cpp-Dt99h3WT.js +1 -0
- package/dist/assets/vendor-lezer-css-DNU_fzPI.js +1 -0
- package/dist/assets/vendor-lezer-go-BEFtcNyS.js +1 -0
- package/dist/assets/vendor-lezer-html-DDGRhRUz.js +1 -0
- package/dist/assets/vendor-lezer-java-DmfZtW09.js +1 -0
- package/dist/assets/vendor-lezer-javascript-oje4tdp_.js +1 -0
- package/dist/assets/vendor-lezer-json-BRXb_bDX.js +1 -0
- package/dist/assets/vendor-lezer-lr-BU2qmu_5.js +1 -0
- package/dist/assets/{vendor-lezer-markdown-C6g-d6P3.js → vendor-lezer-markdown-CicYv7V9.js} +4 -4
- package/dist/assets/vendor-lezer-php-COORrTpE.js +1 -0
- package/dist/assets/vendor-lezer-python-Cuvm9X9Y.js +1 -0
- package/dist/assets/vendor-lezer-rust-C_zOfHbX.js +1 -0
- package/dist/assets/vendor-lezer-sass-DWP4w7O1.js +1 -0
- package/dist/assets/vendor-lezer-xml-Br6nOYeG.js +1 -0
- package/dist/assets/vendor-lezer-yaml-CYQmm6Sb.js +1 -0
- package/dist/assets/{vendor-lru_map-Cy8fTs3_.js → vendor-lru_map-DOPmc7GU.js} +1 -1
- package/dist/assets/{vendor-qrcode-B0KNSajT.js → vendor-qrcode-Dv4uniC1.js} +1 -1
- package/dist/assets/vendor-react-DASdDPIk.js +1 -0
- package/dist/assets/{vendor-react-drawio-BYDptOsj.js → vendor-react-drawio-Duu5LgQA.js} +1 -1
- package/dist/assets/{vendor-replit-codemirror-vim-DaSwPsXt.js → vendor-replit-codemirror-vim-CZy3BUVv.js} +15 -15
- package/dist/assets/vendor-zustand-CUi8eEds.js +6 -0
- package/dist/assets/{web-components-Cdnmh4Xb.js → web-components-CH3-XV-n.js} +4 -4
- package/dist/index.html +7 -9
- package/dist/mini-chat.html +6 -8
- package/dist/mobile.html +6 -8
- package/package.json +1 -1
- package/server/index.js +3 -1
- package/server/lib/fs/DOCUMENTATION.md +1 -1
- package/server/lib/fs/routes.js +1 -50
- package/server/lib/git/DOCUMENTATION.md +18 -11
- package/server/lib/git/index.js +8 -3
- package/server/lib/git/routes.js +0 -129
- package/server/lib/git/service.js +40 -152
- package/server/lib/git/service.test.js +42 -18
- package/server/lib/github/DOCUMENTATION.md +271 -0
- package/server/lib/github/cache.js +164 -0
- package/server/lib/github/checks.js +230 -0
- package/server/lib/github/client.js +305 -0
- package/server/lib/github/context.js +177 -0
- package/server/lib/github/contracts.test.js +235 -0
- package/server/lib/github/correctness.test.js +356 -0
- package/server/lib/github/credential.js +46 -0
- package/server/lib/github/errors.js +151 -0
- package/server/lib/github/gh-cli.js +336 -0
- package/server/lib/github/index.js +27 -0
- package/server/lib/github/issues.js +495 -0
- package/server/lib/github/pulls.js +699 -0
- package/server/lib/github/repo-scope.js +688 -0
- package/server/lib/github/routes.js +599 -0
- package/server/lib/github/security.test.js +275 -0
- package/server/lib/github/templates.js +153 -0
- package/server/lib/package-manager-detect-child.js +12 -0
- package/server/lib/package-manager.js +366 -92
- package/server/lib/package-manager.test.js +109 -0
- package/server/lib/pi/routes-extension-events.test.js +268 -4
- package/server/lib/pi/routes.js +109 -25
- package/server/lib/pi/routes.test.js +118 -0
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +5 -3
- package/server/lib/pi/session-daemon/extension-bridge-draft.test.js +222 -0
- package/server/lib/pi/session-daemon/extension-bridge.js +415 -42
- package/server/lib/pi/session-daemon/extension-name.js +87 -0
- package/server/lib/pi/session-daemon/extension-name.test.js +143 -0
- package/server/lib/pi/session-daemon/extension-theme.js +142 -0
- package/server/lib/pi/session-daemon/extension-theme.test.js +117 -0
- package/server/lib/pi/session-daemon/extension-tool-render.js +365 -0
- package/server/lib/pi/session-daemon/extension-tool-render.test.js +607 -0
- package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +322 -2
- package/server/lib/pi/session-daemon/session-daemon-list-live.test.js +244 -0
- package/server/lib/pi/session-daemon/session-daemon.js +204 -33
- package/server/lib/pi/session-daemon/session-daemon.test.js +218 -0
- package/server/lib/pi/ui-settings-store.js +1 -1
- package/server/lib/static-cache-control.js +18 -0
- package/server/lib/static-cache-control.test.js +25 -0
- package/server/lib/workspace/host.js +2 -0
- package/dist/assets/DiagramView-CXjieF51.js +0 -1
- package/dist/assets/FileSaveConflictDialog-a-HOCgyP.js +0 -3
- package/dist/assets/FilesView-Dcd9ltOX.js +0 -6
- package/dist/assets/GitView-DF2nsuSA.js +0 -8
- package/dist/assets/JsonTreeView-BRU2mRTd.js +0 -1
- package/dist/assets/PatchDiff-kSTpjhu6.js +0 -1
- package/dist/assets/SessionSwitcherContent-BsXDFt24.js +0 -1
- package/dist/assets/SessionSwitcherDropdown-D8fSObHr.js +0 -2
- package/dist/assets/SessionUnreadDot-BpsHyrri.js +0 -1
- package/dist/assets/SettingsView-OEl7QmXC.js +0 -6
- package/dist/assets/SettingsWindow-BMBCj_L_.js +0 -1
- package/dist/assets/ToolOutputDialog-KOVdmTqm.js +0 -8
- package/dist/assets/ToolPartDiffPreview-B9xuVvkm.js +0 -1
- package/dist/assets/Virtualizer-BSHVMKgK.js +0 -1
- package/dist/assets/collapsible-BH1vXEAI.js +0 -1
- package/dist/assets/computeVirtualFileMetrics-yHZbtf5H.js +0 -3
- package/dist/assets/gitStatusPredicates-CpGQLvMK.js +0 -134
- package/dist/assets/index-5fyXnZFi.css +0 -1
- package/dist/assets/index-C-sV_9sb.js +0 -8
- package/dist/assets/index-D_FGGnQQ.js +0 -1
- package/dist/assets/isDiffPlainText-BNyusJZz.js +0 -1
- package/dist/assets/isFilePlainText-CMAUe7qD.js +0 -1
- package/dist/assets/main-BMLgZ5yn.js +0 -2
- package/dist/assets/main-DNq1n9F_.js +0 -135
- package/dist/assets/markdownCore-CZWcaNr2.js +0 -3
- package/dist/assets/miniChat-B2AgUZqL.js +0 -2
- package/dist/assets/mobile-BsGiRUUg.js +0 -2
- package/dist/assets/permissionStore-iKN1K2_x.js +0 -1
- package/dist/assets/renderElectronMiniChatApp-UV9dnnbf.js +0 -2
- package/dist/assets/renderMobileApp-BMifduGA.js +0 -11
- package/dist/assets/runtimeEndpointReset-CkvC02dQ.js +0 -53
- package/dist/assets/useAppFontEffects-CclUs9KY.js +0 -6722
- package/dist/assets/usePushVisibilityBeacon-aDmGZrTW.js +0 -10
- package/dist/assets/useSwitcherItems-BZKyNjhp.js +0 -1
- package/dist/assets/vendor-aria-hidden-DvXkyWUv.js +0 -1
- package/dist/assets/vendor-base-ui-DXSHfszQ.js +0 -1
- package/dist/assets/vendor-class-variance-authority-5VPnzWs2.js +0 -1
- package/dist/assets/vendor-cmdk-zXx6sGnS.js +0 -1
- package/dist/assets/vendor-codemirror-autocomplete-wd6iRebq.js +0 -1
- package/dist/assets/vendor-codemirror-commands-CNlncqrr.js +0 -1
- package/dist/assets/vendor-codemirror-lang-angular-DU_4KiiW.js +0 -1
- package/dist/assets/vendor-codemirror-lang-cpp-CmIT9Z5_.js +0 -1
- package/dist/assets/vendor-codemirror-lang-css-djiuoTi8.js +0 -1
- package/dist/assets/vendor-codemirror-lang-go-COZSwZYW.js +0 -7
- package/dist/assets/vendor-codemirror-lang-html-CKHqhW5R.js +0 -1
- package/dist/assets/vendor-codemirror-lang-java-CNMP5hyC.js +0 -1
- package/dist/assets/vendor-codemirror-lang-javascript-DuOEwJ3f.js +0 -13
- package/dist/assets/vendor-codemirror-lang-jinja-DaKn_b1k.js +0 -1
- package/dist/assets/vendor-codemirror-lang-json-CZ07HmNC.js +0 -1
- package/dist/assets/vendor-codemirror-lang-less-wJdQiDBf.js +0 -1
- package/dist/assets/vendor-codemirror-lang-liquid-0z48Roi8.js +0 -1
- package/dist/assets/vendor-codemirror-lang-markdown-DtcZDGqe.js +0 -1
- package/dist/assets/vendor-codemirror-lang-php-W8plS-JQ.js +0 -1
- package/dist/assets/vendor-codemirror-lang-python-DzzokVau.js +0 -3
- package/dist/assets/vendor-codemirror-lang-rust-C4ulBVpf.js +0 -1
- package/dist/assets/vendor-codemirror-lang-sass-BkZJYEwS.js +0 -1
- package/dist/assets/vendor-codemirror-lang-vue-DiBPljCc.js +0 -1
- package/dist/assets/vendor-codemirror-lang-wast-DoABsogh.js +0 -1
- package/dist/assets/vendor-codemirror-lang-xml-BhLJhOCH.js +0 -1
- package/dist/assets/vendor-codemirror-lang-yaml-D95i1Y5R.js +0 -1
- package/dist/assets/vendor-codemirror-language-BByA_dGF.js +0 -3
- package/dist/assets/vendor-codemirror-language-data-C6LBD7qA.js +0 -2
- package/dist/assets/vendor-codemirror-search-BV44140v.js +0 -2
- package/dist/assets/vendor-codemirror-state-CNWM3Q8V.js +0 -5
- package/dist/assets/vendor-codemirror-view-Ct4T37Ue.js +0 -4
- package/dist/assets/vendor-crelt-C8TCjufn.js +0 -1
- package/dist/assets/vendor-detect-node-es-l0sNRNKZ.js +0 -1
- package/dist/assets/vendor-dnd-kit-accessibility-DZKKhs9S.js +0 -1
- package/dist/assets/vendor-dnd-kit-core-C9qcAm_1.js +0 -5
- package/dist/assets/vendor-dnd-kit-sortable-D8ozj8M-.js +0 -1
- package/dist/assets/vendor-dnd-kit-utilities-DTY1C6ST.js +0 -1
- package/dist/assets/vendor-floating-ui-core-CXmKXOXc.js +0 -1
- package/dist/assets/vendor-floating-ui-dom-WyXykhNi.js +0 -1
- package/dist/assets/vendor-floating-ui-react-dom-BZOGXAGe.js +0 -1
- package/dist/assets/vendor-floating-ui-utils-BzXdqYpP.js +0 -1
- package/dist/assets/vendor-framer-motion-CfplGuM0.js +0 -1
- package/dist/assets/vendor-get-nonce-C-Z93AgS.js +0 -1
- package/dist/assets/vendor-lezer-common-B3-cUCR_.js +0 -1
- package/dist/assets/vendor-lezer-cpp-BleAU9o-.js +0 -1
- package/dist/assets/vendor-lezer-css-C5xB6jxd.js +0 -1
- package/dist/assets/vendor-lezer-go-CXK1UKk8.js +0 -1
- package/dist/assets/vendor-lezer-highlight-CDMHUZ74.js +0 -1
- package/dist/assets/vendor-lezer-html-C0I1p52t.js +0 -1
- package/dist/assets/vendor-lezer-java-D_zzj-NV.js +0 -1
- package/dist/assets/vendor-lezer-javascript-D7Tj24ot.js +0 -1
- package/dist/assets/vendor-lezer-json-Iaex0UN-.js +0 -1
- package/dist/assets/vendor-lezer-lr-bhwg1HMg.js +0 -1
- package/dist/assets/vendor-lezer-php-_DHrbsZG.js +0 -1
- package/dist/assets/vendor-lezer-python-CvuFxeZl.js +0 -1
- package/dist/assets/vendor-lezer-rust-Lqgd5SAo.js +0 -1
- package/dist/assets/vendor-lezer-sass-Dnm2lY4t.js +0 -1
- package/dist/assets/vendor-lezer-xml-hUDuAyS5.js +0 -1
- package/dist/assets/vendor-lezer-yaml-BNIl6S_O.js +0 -1
- package/dist/assets/vendor-marijn-find-cluster-break-DXwl3gUT.js +0 -1
- package/dist/assets/vendor-motion-dom-DhJ-sYS5.js +0 -1
- package/dist/assets/vendor-motion-l0sNRNKZ.js +0 -1
- package/dist/assets/vendor-motion-utils-CKEGc_YG.js +0 -1
- package/dist/assets/vendor-radix-ui-primitive-Dc_FVRD7.js +0 -1
- package/dist/assets/vendor-radix-ui-react-compose-refs-8xy6TJML.js +0 -1
- package/dist/assets/vendor-radix-ui-react-context-CFsX-AUC.js +0 -1
- package/dist/assets/vendor-radix-ui-react-dialog-D2yhEu2p.js +0 -5
- package/dist/assets/vendor-radix-ui-react-dismissable-layer-DrorBNg9.js +0 -1
- package/dist/assets/vendor-radix-ui-react-focus-guards-BfdFmL7c.js +0 -1
- package/dist/assets/vendor-radix-ui-react-focus-scope-D2BkImwt.js +0 -1
- package/dist/assets/vendor-radix-ui-react-id-D2kS9K1j.js +0 -1
- package/dist/assets/vendor-radix-ui-react-portal-YgCRIyi7.js +0 -1
- package/dist/assets/vendor-radix-ui-react-presence-D432pCMB.js +0 -1
- package/dist/assets/vendor-radix-ui-react-primitive-DkH8dMOR.js +0 -1
- package/dist/assets/vendor-radix-ui-react-slot-BIDFZX0-.js +0 -1
- package/dist/assets/vendor-radix-ui-react-use-callback-ref-BwDcSoGV.js +0 -1
- package/dist/assets/vendor-radix-ui-react-use-controllable-state-LiqmKSXO.js +0 -1
- package/dist/assets/vendor-radix-ui-react-use-effect-event-D94va83M.js +0 -1
- package/dist/assets/vendor-radix-ui-react-use-escape-keydown-DTkqjenV.js +0 -1
- package/dist/assets/vendor-radix-ui-react-use-layout-effect-C8Yrsaph.js +0 -1
- package/dist/assets/vendor-react-B5Z1Mdn3.js +0 -9
- package/dist/assets/vendor-react-remove-scroll-bar-CSAHp1YF.js +0 -38
- package/dist/assets/vendor-react-remove-scroll-vR1dy1aP.js +0 -4
- package/dist/assets/vendor-react-style-singleton-Ctw6HnYx.js +0 -1
- package/dist/assets/vendor-reselect-l0sNRNKZ.js +0 -1
- package/dist/assets/vendor-scheduler-7OC5HNn7.js +0 -1
- package/dist/assets/vendor-simplewebauthn-browser-VDA66rT_.js +0 -2
- package/dist/assets/vendor-sonner-BDtm25td.js +0 -1
- package/dist/assets/vendor-style-mod-NZ5MEPvj.js +0 -3
- package/dist/assets/vendor-tanstack-react-virtual-2skouoFw.js +0 -1
- package/dist/assets/vendor-tanstack-virtual-core-Dubg10g5.js +0 -1
- package/dist/assets/vendor-tslib-De9GV7Vy.js +0 -1
- package/dist/assets/vendor-use-callback-ref-CVVuCyLj.js +0 -1
- package/dist/assets/vendor-use-sidecar-Vv4V8Nd1.js +0 -1
- package/dist/assets/vendor-use-sync-external-store-D0AXkdQC.js +0 -1
- package/dist/assets/vendor-w3c-keyname-Vcq4gwWv.js +0 -1
- package/dist/assets/vendor-zustand-GVb4H8HE.js +0 -6
- package/server/lib/git/credentials.js +0 -41
- package/server/lib/git/identity-storage.js +0 -122
- /package/dist/assets/{vendor-katex-CNckGUMB.js → vendor-katex-DZG0Ov6p.js} +0 -0
- /package/dist/assets/{vendor-katex-Cp579UoJ.css → vendor-katex-css-Cp579UoJ.css} +0 -0
- /package/dist/assets/{vendor-xterm-xterm-CrXqRur4.js → vendor-xterm-xterm-B-qIQCd3.js} +0 -0
- /package/dist/assets/{vendor-xterm-xterm-DDGTF8rc.css → vendor-xterm-xterm-css-DDGTF8rc.css} +0 -0
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-eDf4LKLY.js","assets/useAppFontEffects-CG3_yteE.js","assets/index-6IO1AcJI.js","assets/vendor-zustand-CUi8eEds.js","assets/vendor-react-DASdDPIk.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/index-BAmzAlNx.css","assets/vendor-boot-DyL2td56.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/runtimeSurface-DW_Ia4q3.js","assets/computeVirtualFileMetrics-CeMpF2xC.js","assets/vendor-shiki-Bbf2GEcE.js","assets/vendor-shikijs-core-CGM_jqPK.js","assets/vendor-shikijs-types-CPSbSeK6.js","assets/vendor-shikijs-vscode-textmate-BgLrS_2D.js","assets/vendor-hast-util-to-html-BKBhbTDb.js","assets/vendor-html-void-elements-CkdplsNl.js","assets/vendor-property-information-rJCbAzvX.js","assets/vendor-zwitch-C2o2j-tx.js","assets/vendor-stringify-entities-CsH1VEn9.js","assets/vendor-character-entities-legacy-BpoLgcEt.js","assets/vendor-character-entities-html4-D7taRCQ7.js","assets/vendor-ccount-c2V3InAJ.js","assets/vendor-comma-separated-tokens-D8TqSuIK.js","assets/vendor-space-separated-tokens-DD3iYX1K.js","assets/vendor-hast-util-whitespace-D4Wp6AEg.js","assets/vendor-shikijs-engine-oniguruma-DPWuIF1G.js","assets/themeResolver-yJ9XpNMI.js","assets/vendor-pierre-theming-Dgp7B_O4.js","assets/vendor-shikijs-engine-javascript-Cme4830A.js","assets/vendor-oniguruma-to-es-DLBnFDCE.js","assets/vendor-oniguruma-parser-C0D4_9rT.js","assets/vendor-regex-BBWcyTkg.js","assets/vendor-regex-utilities-2BQyy0xI.js","assets/vendor-regex-recursion-JU4mF-dD.js","assets/vendor-shikijs-transformers-CZWsLLKm.js","assets/renderFileWithHighlighter-TpKRyfCY.js","assets/renderDiffWithHighlighter-CDsgOnkH.js","assets/vendor-diff-C3JhlQdm.js","assets/vendor-lru_map-DOPmc7GU.js","assets/appThemeRegistry-gegrE2dq.js","assets/registerCustomTheme-DmolaWWZ.js","assets/vendor-capacitor-keyboard-CYccoJjr.js","assets/vendor-capacitor-core-B4EWRrHz.js","assets/SessionSwitcherDropdown-cC9wVBH7.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{_ as dt}from"./vendor-vite-runtime-DD1OZmLC.js";import{j as s,a_ as Zc,a$ as eu,b0 as tu,b1 as su,b2 as nu,b3 as ru,b4 as ou,aK as sa,aL as qr,aM as iu,aN as na,aO as ra,aR as au,b5 as lu,b6 as cu,b7 as uu,b8 as oa,b9 as ia,ba as aa,bb as la,bc as ca,bd as ua,be as da,aP as du,aX as fu,aU as hu,aV as mu,aS as pu,aT as gu,bf as Yr,aH as bu}from"./vendor-boot-DyL2td56.js";import{a as Ne,R as a}from"./vendor-react-DASdDPIk.js";import{aW as Ws,aX as xu,t as ie,a as ht,f as Me,a4 as tn,B as Ee,I as D,ai as kn,aY as fa,ak as es,al as ts,am as xs,an as as,ao as ys,ap as Ds,aM as Es,aZ as Rs,a_ as yu,g as $s,a$ as Nr,b0 as ti,b1 as si,aF as yn,e as Yn,o as ha,aj as Cs,b2 as ni,ae as bs,a9 as $e,aa as Ke,ac as We,b3 as Qr,b4 as wu,b5 as vu,b6 as Su,b7 as ju,b8 as Cu,b9 as Vr,ba as ku,a8 as Jt,ab as Xt,ad as Zt,H as Ut,bb as Au,bc as Nu,bd as Iu,be as Eu,bf as Ru,bg as Du,aJ as Jr,r as wn,w as ko,at as Pu,aE as Mu,aI as ma,bh as pa,S as Ps,bi as Tu,bj as Fu,bk as Lu,bl as Ou,d as ga,p as Ms,aD as ba,bm as mr,bn as ri,bo as xa,bp as ft,bq as Bu,aK as ya,br as wa,bs as va,bt as Sa,bu as ja,ay as _u,h as Ca,j as Uu,bv as zu,i as $u,bw as Bs,b as oi,c as Ku,bx as Wu,u as Gu,aL as Hu,aO as qu,by as Xr,bz as Yu,bA as Qu,aN as Vu,bB as Ju,bC as Xu,V as Zu,af as mt,ag as Qs,aq as ka,F as ed,n as td,bD as sd,k as nd,bE as rd,bF as Aa,bG as od,bH as id,bI as ad,bJ as ld,bK as cd,bL as ud,bM as dd,bN as fd,bO as hd,bP as md,a5 as pd,bQ as gd}from"./useAppFontEffects-CG3_yteE.js";import{Z as ii,_ as bd,R as Vs,$ as Na,a0 as Ia,a1 as xd,a2 as yd,u as Js,K as wd,a3 as vd,a4 as Sd,t as le,m as Pt,o as K,a5 as jd,f as Je,a as Dt,A as Rn,C as Ae,a6 as Xs,a7 as zt,a8 as ai,a9 as Zr,aa as Ea,v as is,T as Ao,U as sr,ab as Cd,w as Ra,ac as kd,ad as Da,G as Ad,Q as Pa,D as vn,ae as eo,h as to,d as Bn,af as Nd,ag as Id,ah as li,ai as un,aj as Ir,ak as so,al as nr,am as ks,an as ci,ao as no,ap as Ma,aq as ro,ar as Ed,as as Rd,at as Dd,au as Pd,av as Md,aw as Td,ax as Fd,ay as Ld,az as Od,Y as Ta,aA as Bd,P as _d,aB as Ud,J as zd,aC as $d}from"./index-6IO1AcJI.js";import{g as ps,b as Kd,c as Fa,r as Wd,d as La,s as Qn,e as Oa,h as An,i as Nn,j as Gd,k as Hd,l as qd,m as ui,n as pr,f as Yd,a as Qd,S as Vd,t as Jd,o as Xd}from"./SessionUnreadDot-CELKNVIM.js";import{c as Ts,d as gr,p as Ba,a as Zd}from"./vendor-zustand-CUi8eEds.js";/* empty css */import{usePermissionStore as ef}from"./permissionStore-B9Hkrqny.js";const tf="chat";function _a(e){const t=new URLSearchParams;if(e.sessionId&&e.sessionId.trim().length>0&&t.set(Ws.SESSION,e.sessionId),e.isSettingsOpen){const n=e.settingsPath.trim().length>0?e.settingsPath:"home";return t.set(Ws.SETTINGS,n),t}return e.tab!==tf&&t.set(Ws.TAB,e.tab),e.tab==="diff"&&e.diffFile&&e.diffFile.trim().length>0&&t.set(Ws.FILE,e.diffFile),t}function sf(e,t){const n=typeof window<"u"?window.location.pathname:"/",r=n.startsWith("/session")||n.startsWith("/s/")?"/":n,o=e.toString();return o?`${r}?${o}`:r}function nf(e){if(typeof window>"u")return!0;try{const t=new URLSearchParams(window.location.search),n=_a(e),r=window.location.pathname.match(/^\/(?:session|s)\/([^/?#]+)/i),o=r?.[1]?decodeURIComponent(r[1].trim()):null;o&&!t.has(Ws.SESSION)&&t.set(Ws.SESSION,o);const i=[...t.entries()].sort((c,u)=>c[0].localeCompare(u[0])),l=[...n.entries()].sort((c,u)=>c[0].localeCompare(u[0]));if(i.length!==l.length)return!1;for(let c=0;c<i.length;c++)if(i[c][0]!==l[c][0]||i[c][1]!==l[c][1])return!1;return!0}catch{return!0}}function oo(e,t={}){if(!(typeof window>"u")&&!(!t.force&&nf(e)))try{const n=_a(e),r=sf(n);t.replace?window.history.replaceState({...window.history.state,route:e},"",r):window.history.pushState({route:e},"",r)}catch{}}const rf=["typescript","javascript","tsx","jsx","json","markdown"],Ua={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let di=null;const za=()=>(di??=Promise.all([dt(()=>import("./index-eDf4LKLY.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41])),dt(()=>import("./workerFactory-tw7cIdmV.js"),[]),dt(()=>import("./appThemeRegistry-gegrE2dq.js"),__vite__mapDeps([42,43,29,30,10,14,15,16,17,18,19,20,21,22,23,24,25,26,27]))]).then(([e,t,n])=>({WorkerPoolManager:e.WorkerPoolManager,workerFactory:t.workerFactory,ensurePierreThemeRegistered:n.ensurePierreThemeRegistered})),di),In={},fi=new Set,io=new Set;let Vn={light:"pierre-light",dark:"pierre-dark"};const of=()=>{for(const e of io)e()},$a=(e,t)=>{t.setRenderOptions({theme:Vn,lineDiffType:Ua[e].lineDiffType})},ao=e=>{typeof window>"u"||fi.has(e)||(fi.add(e),za().then(t=>{if(In[e])return;const n=Ua[e],r=new t.WorkerPoolManager({workerFactory:t.workerFactory,poolSize:n.poolSize,totalASTLRUCacheSize:n.totalASTLRUCacheSize},{theme:{light:"pierre-light",dark:"pierre-dark"},langs:rf,lineDiffType:n.lineDiffType,preferredHighlighter:"shiki-wasm"});r.initialize(),In[e]=r,$a(e,r),of()}))},af=e=>(io.add(e),()=>io.delete(e)),lf=e=>{if(!(Vn.light===e.light&&Vn.dark===e.dark)){Vn=e;for(const t of Object.keys(In)){const n=In[t];n&&$a(t,n)}}},Db=({children:e})=>{const t=xu(),n=ii(!1),r=ii(!0),o=t?.lightThemeId??n.metadata.id,i=t?.darkThemeId??r.metadata.id,l=t?.availableThemes.find(u=>u.metadata.id===o)??n,c=t?.availableThemes.find(u=>u.metadata.id===i)??r;return Ne.useEffect(()=>{let u=!1;return za().then(d=>{u||(d.ensurePierreThemeRegistered(l),d.ensurePierreThemeRegistered(c),lf({light:l.metadata.id,dark:c.metadata.id}))}),()=>{u=!0}},[c,l]),Ne.useEffect(()=>{if(typeof window>"u")return;const u=()=>{ao("unified"),ao("split")};if(typeof window.requestIdleCallback=="function"){const f=window.requestIdleCallback(u,{timeout:5e3});return()=>window.cancelIdleCallback(f)}const d=window.setTimeout(u,2e3);return()=>window.clearTimeout(d)},[]),s.jsx(s.Fragment,{children:e})},Pb=(e="unified")=>{const t=Ne.useSyncExternalStore(af,()=>In[e],()=>{});return Ne.useEffect(()=>{ao(e)},[e]),t},cf=e=>e==="/",Zs=e=>e.replace(/\\/g,"/"),en=e=>{if(!e||cf(e))return e;let t=e;for(;t.length>1&&t.endsWith("/");)t=t.slice(0,-1);return t},Hs=e=>e.endsWith("/"),rr=e=>{const t=e.trim();return!t||Hs(t)?t:`${t}/`},No=e=>e.lastIndexOf("/"),Ka=e=>{if(Hs(e))return e;const t=No(e);return t<0?e:e.slice(0,t+1)},Wa=e=>{const t=No(e);return e.slice(t+1)},Ga=e=>{const t=en(e.trim());if(!t||t==="~"||t==="~/"||t==="/")return null;const n=No(t);return n<0?null:t.startsWith("~/")&&n<=1?"~/":n===0?"/":`${t.slice(0,n)}/`},Ha=e=>Hs(e)&&Ga(e)!==null,uf=e=>{if(!Ha(e))return null;const t=en(e.trim());return Wa(t)||t},df=(e,t)=>`${Ka(e)}${t}/`,As=e=>{if(!e)return null;const t=en(Zs(e.trim()));return t?t.toLowerCase():null},hi=(e,t)=>{const n=e.trim();return n==="~"?t:n.startsWith("~/")?`${t}${n.slice(1)}`:n},ff=(e,t)=>{const n=en(Zs(e.trim())),r=en(Zs(t.trim()));if(!n)return"";if(!r)return rr(n);if(n.toLowerCase()===r.toLowerCase())return"~/";const o=`${r}/`;return n.toLowerCase().startsWith(o.toLowerCase())?`~/${n.slice(r.length+1)}/`:rr(n)},hf=e=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey,lo=e=>{if(!e)return;e.focus({preventScroll:!0});const t=e.value.length;e.setSelectionRange(t,t),e.scrollLeft=e.scrollWidth},mf=async()=>bd({fresh:!0}),pf=()=>{const[e,t]=Ne.useState(!1),[n,r]=Ne.useState(!1);Ne.useEffect(()=>{t(Vs()),r(Na())},[]);const o=Ne.useCallback(async c=>e?await Ia(c):{success:!0,path:c},[e]),i=Ne.useCallback(async c=>e?await xd():{success:!0},[e]),l=Ne.useCallback(async c=>e?await yd():{success:!0},[e]);return{isDesktop:e,canRequestAccess:n,requestAccess:o,startAccessing:i,stopAccessing:l}};function gf({open:e,addedProjectPaths:t,shouldSuppressAutoFocus:n}){const r=Js(te=>te.homeDirectory),{canRequestAccess:o,startAccessing:i}=pf(),l=a.useRef(null),c=a.useRef(new Map),[u,d]=a.useState(""),[f,p]=a.useState("~/"),[b,g]=a.useState([]),[m,h]=a.useState(!1),[y,x]=a.useState(!1),[C,v]=a.useState(null),[P,S]=a.useState(0),[A,j]=a.useState(0),[w,N]=a.useState(!1),[T,L]=a.useState(!1),[$,z]=a.useState("right"),W=a.useRef("~/"),F=u||r;a.useEffect(()=>{if(!e)return;p("~/"),g([]),j(0),N(!1),L(!1),W.current="~/",z("right"),n||requestAnimationFrame(()=>lo(l.current));let te=!1;return(async()=>{const je=await mf();te||(d(je||r||""),n||requestAnimationFrame(()=>lo(l.current)))})(),()=>{te=!0}},[r,e,n]);const R=a.useMemo(()=>Ka(f),[f]),E=a.useMemo(()=>Hs(f)?"":Wa(f),[f]),I=a.useMemo(()=>F?hi(R,F):"",[R,F]);a.useEffect(()=>{const te=W.current;te!==R&&(z(R.length>=te.length?"right":"left"),W.current=R)},[R]),a.useEffect(()=>{if(!e||!I){g([]),v(null);return}let te=!1;return h(!0),x(!1),v(null),wd(I).then(ae=>{if(te)return;x(!1),v(null);const je=ae.filter(Se=>Se.isDirectory).map(Se=>({name:Se.name,path:Zs(Se.path)})).sort((Se,Ge)=>Se.name.localeCompare(Ge.name));g(je)}).catch(ae=>{if(!te){g([]);const je=vd(ae)?ae.reason:"unknown";v(je),x(je==="not-found")}}).finally(()=>{te||h(!1)}),()=>{te=!0}},[I,P,e]);const M=a.useMemo(()=>{const te=E.toLowerCase(),ae=T||E.startsWith(".");return b.filter(je=>je.name.toLowerCase().startsWith(te)&&(ae||!je.name.startsWith(".")))},[E,b,T]),G=a.useMemo(()=>uf(f),[f]),X=a.useMemo(()=>Ga(f),[f]),U=a.useMemo(()=>{const te=[],ae=As(I);Ha(f)&&G&&X&&te.push({type:"parent",value:"browse:up",name:G,path:X,alreadyAdded:!!(ae&&t.has(ae))});for(const je of M){const Se=As(je.path);te.push({type:"directory",value:`browse:${je.path}`,name:je.name,path:je.path,alreadyAdded:!!(Se&&t.has(Se))})}return te},[t,I,G,M,X,f]);a.useEffect(()=>{j(0)},[f,U.length]);const ve=a.useMemo(()=>F?en(hi(f,F)):"",[F,f]),Z=As(ve),Re=!!(Z&&t.has(Z)),Oe=a.useMemo(()=>E?M.find(te=>te.name===E)??null:null,[E,M]),Q=!!(ve&&!Re&&(C===null||C==="not-found")&&(Hs(f)&&y||!Hs(f)&&E.trim().length>0&&Oe===null)),_=U[A]??null,H=!!_,J=a.useCallback(te=>{p(rr(te))},[]),ne=a.useCallback(te=>{p(df(f,te.name))},[f]),fe=a.useCallback(te=>{if(te){if(te.type==="parent"){J(te.path);return}ne(te)}},[J,ne]),he=a.useCallback(async te=>{const ae=await i(te);if(!ae.success)return ie.error("Failed to open directory",{description:ae.error||"Desktop could not grant file access."}),!1;const je=F?ff(te,F):rr(Zs(te));return J(je),!0},[J,F,i]),q=a.useCallback(async()=>{if(!w){N(!0);try{if(Na()){const ae=await Ia(ve);if(!ae.success||!ae.path){ae.error&&ae.error!=="Directory selection cancelled"&&ie.error("Failed to select directory",{description:ae.error});return}await he(ae.path);return}const te=await Sd(ve);if(te.status==="cancelled")return;if(te.status!=="picked"){ie.error("Couldn't open a folder picker",{description:te.error});return}await he(te.path)}catch(te){ie.error("Failed to select directory",{description:te instanceof Error?te.message:"Unknown error occurred."})}finally{N(!1)}}},[he,w,ve]);return{inputRef:l,rowRefs:c,query:f,setQuery:p,isLoading:m,isBrowseDirectoryMissing:y,browseErrorReason:C,browseReloadKey:P,setBrowseReloadKey:S,highlightedIndex:A,setHighlightedIndex:j,isPickingLocation:w,showHidden:T,setShowHidden:L,folderEnterFrom:$,explorerRootDirectory:F,browseDirectoryDisplayPath:R,browseDirectoryAbsolutePath:I,browseFilterQuery:E,filteredEntries:M,rows:U,targetPath:ve,isAlreadyAdded:Re,shouldCreateTarget:Q,highlightedRow:_,hasHighlightedBrowseItem:H,canRequestAccess:o,browseToDisplayPath:J,browseToEntry:ne,executeRow:fe,applyPickedLocation:he,handleBrowseLocation:q}}function bf({open:e,onClose:t,isMobile:n,addedProjectPaths:r,targetPath:o,shouldCreateTarget:i,browseErrorReason:l,browseDirectoryAbsolutePath:c,isAlreadyAdded:u,isPickingLocation:d}){const f=ht(L=>L.addProject),p=le(L=>L.setActiveMainTab),b=le(L=>L.setSessionSwitcherOpen),g=Me(L=>L.openNewSessionDraft),[m,h]=a.useState(!1),[y,x]=a.useState(!1),[C,v]=a.useState("");a.useEffect(()=>{e&&(h(!1),x(!1),v(""))},[e]);const P=a.useCallback((L,$)=>{p("chat"),n&&b(!1),g({selectedProjectId:L,directoryOverride:$}),t()},[n,t,g,p,b]),S=a.useCallback(async L=>{if(!L||m)return;const $=As(L);if($&&r.has($))return;let z=L;h(!0);try{const W=!y&&i&&As(L)===As(o);if(y){const R=C.trim();if(!R){ie.error("Enter a repository URL before cloning.");return}const E=await Pt("/api/fs/clone",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({remoteUrl:R,destinationPath:L})});if(!E.ok)throw new Error("Failed to clone git repository");z=(await E.json()).path||L}else if(W&&!(await Pt("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json"},query:c?{directory:c}:void 0,body:JSON.stringify({path:L})})).ok)throw new Error("Failed to select directory");const F=f(z);if(!F){ie.error("Failed to add folder",{description:"Please select a valid directory path."});return}P(F.id,F.path)}catch(W){ie.error("Failed to select directory",{description:W instanceof Error?W.message:"Unknown error occurred."})}finally{h(!1)}},[f,r,c,C,y,m,P,i,o]),A=!m&&!d&&!u&&l!=="os-permission"&&l!=="invalid-response"&&l!=="unknown"&&!!o,j=A&&C.trim().length>0,w=y?j:A,N=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl";return{isConfirming:m,isCloneMode:y,setIsCloneMode:x,cloneRemoteUrl:C,setCloneRemoteUrl:v,canSubmit:w,submitActionLabel:u?"Already added":y?m?"Cloning...":"Clone & add":m?"Adding...":i?"Create & add":"Add folder",submitModifierLabel:N,finalizeSelection:S}}const xf=({open:e,onOpenChange:t})=>{const n=ht(q=>q.projects),{isMobile:r,isTablet:o}=tn(),i=r||o,l=a.useMemo(()=>new Set(n.map(q=>As(q.path)).filter(q=>!!q)),[n]),c=a.useCallback(()=>{t(!1)},[t]),{inputRef:u,rowRefs:d,query:f,setQuery:p,isLoading:b,browseErrorReason:g,setBrowseReloadKey:m,highlightedIndex:h,setHighlightedIndex:y,isPickingLocation:x,showHidden:C,setShowHidden:v,folderEnterFrom:P,browseDirectoryDisplayPath:S,browseDirectoryAbsolutePath:A,rows:j,targetPath:w,isAlreadyAdded:N,shouldCreateTarget:T,highlightedRow:L,hasHighlightedBrowseItem:$,canRequestAccess:z,executeRow:W,handleBrowseLocation:F}=gf({open:e,addedProjectPaths:l,shouldSuppressAutoFocus:i}),{isConfirming:R,isCloneMode:E,setIsCloneMode:I,cloneRemoteUrl:M,setCloneRemoteUrl:G,canSubmit:X,submitActionLabel:U,submitModifierLabel:ve,finalizeSelection:Z}=bf({open:e,onClose:c,isMobile:r,addedProjectPaths:l,targetPath:w,shouldCreateTarget:T,browseErrorReason:g,browseDirectoryAbsolutePath:A,isAlreadyAdded:N,isPickingLocation:x});a.useLayoutEffect(()=>{const q=u.current;q&&(q.scrollLeft=q.scrollWidth)},[u,f]),a.useLayoutEffect(()=>{!e||i||lo(u.current)},[u,e,i]),a.useLayoutEffect(()=>{const q=j[h];q&&d.current.get(q.value)?.scrollIntoView({block:"nearest"})},[h,d,j]);const Re=a.useCallback(q=>{if(q.key==="ArrowDown"){q.preventDefault(),y(te=>Math.min(j.length-1,te+1));return}if(q.key==="ArrowUp"){q.preventDefault(),y(te=>Math.max(0,te-1));return}if(q.key==="Enter"){if(q.preventDefault(),hf(q)){Z(w);return}$&&W(L);return}q.key==="Backspace"&&f===""&&(q.preventDefault(),c())},[W,Z,c,$,L,f,j.length,y,w]),Oe=s.jsxs("button",{type:"button",onClick:()=>v(q=>!q),className:"flex flex-shrink-0 items-center gap-2 rounded-lg px-2 py-1 typography-meta text-muted-foreground transition-colors hover:bg-interactive-hover/40",children:[C?s.jsx(D,{name:"checkbox",className:"h-4 w-4 text-primary"}):s.jsx(D,{name:"checkbox-blank",className:"h-4 w-4"}),"Show hidden"]}),Q=s.jsx("div",{className:"py-1.5",children:s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsxs("div",{className:"relative min-w-0 flex-1",children:[s.jsx(D,{name:"folder-3",className:"pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground/80"}),s.jsx(kn,{ref:u,value:f,onChange:q=>p(Zs(q.target.value)),onKeyDown:Re,placeholder:"Enter a folder path...",className:"border-transparent bg-transparent pl-9 font-mono typography-ui-label shadow-none focus-visible:ring-0",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"})]}),s.jsxs(Ee,{variant:"outline",size:"xs",className:"h-8 shrink-0 gap-1 px-2",disabled:R||x,onMouseDown:q=>q.preventDefault(),onClick:()=>{F()},title:"Browse location","aria-label":"Browse location",children:[s.jsx(D,{name:"folder-open",className:"h-3.5 w-3.5"}),x?"Opening...":"Browse"]})]})}),_=j.some(q=>q.type==="parent"),H=s.jsx("div",{className:"relative min-h-0 flex-1 overflow-hidden rounded-xl border border-border/60 bg-[var(--surface-elevated)] shadow-sm",children:s.jsxs("div",{className:"max-h-[min(28rem,58vh)] overflow-y-auto p-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2 px-2 pb-1 pt-0.5",children:[s.jsx("div",{className:"typography-meta font-medium uppercase tracking-wide text-muted-foreground/80",children:"Directories"}),s.jsxs(Ee,{variant:"ghost",size:"xs",className:"h-6 shrink-0 gap-1 text-muted-foreground","aria-pressed":E,disabled:R||x,onClick:()=>I(q=>!q),children:[s.jsx(D,{name:"git-repository",className:"h-3.5 w-3.5"}),"Clone"]})]}),E?s.jsxs("div",{className:"mb-2 space-y-1.5 px-2 pb-1",children:[s.jsx("p",{className:"typography-meta text-muted-foreground",children:"Clone into the folder path above."}),s.jsx("div",{className:"flex items-center gap-1.5",children:s.jsx(kn,{value:M,onChange:q=>G(q.target.value),placeholder:"Repository URL (HTTPS or SSH)",className:"min-w-0 flex-1 font-mono typography-ui-label",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"})})]}):null,N?s.jsx("p",{className:"px-2 pb-2 typography-meta text-muted-foreground",children:"This folder is already added. Open a subfolder to add that instead."}):null,s.jsx("div",{className:K("mt-3","animate-in fade-in-0 duration-200 motion-reduce:animate-none",P==="left"?"slide-in-from-left-2":"slide-in-from-right-2"),children:b?s.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"Loading directories..."}):g&&g!=="not-found"?s.jsxs("div",{className:"flex flex-col items-center gap-3 px-4 py-10 text-center",children:[s.jsx("div",{className:"typography-ui-label text-status-error",children:g==="os-permission"?"PiChamber needs access to this folder.":"Could not load this folder."}),s.jsxs("div",{className:"flex items-center gap-2",children:[g==="os-permission"&&z?s.jsx(Ee,{size:"xs",onClick:()=>{F()},disabled:x,children:"Grant access"}):null,s.jsx(Ee,{variant:"outline",size:"xs",onClick:()=>m(q=>q+1),children:"Try again"})]})]}):j.length===0?s.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"No matching directories."}):s.jsx("div",{className:"space-y-0.5",children:j.map((q,te)=>{const ae=te===h,je=q.type==="directory"&&_;return s.jsxs("button",{ref:Se=>{Se?d.current.set(q.value,Se):d.current.delete(q.value)},type:"button","aria-label":q.type==="parent"?q.alreadyAdded?`Go back from ${q.name}, already added`:`Go back from ${q.name}`:q.alreadyAdded?`Open ${q.name}, already added`:`Open ${q.name}`,onMouseEnter:()=>y(te),onMouseDown:Se=>Se.preventDefault(),onClick:()=>W(q),className:K("flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",ae&&"bg-interactive-selection text-interactive-selection-foreground",!ae&&"hover:bg-interactive-hover/50"),children:[s.jsxs("span",{className:K("flex min-w-0 flex-1 items-center gap-2",je&&"pl-4"),children:[q.type==="parent"?s.jsx(D,{name:"folder-open",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}):s.jsx(D,{name:"folder-6",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}),s.jsx("span",{className:"truncate typography-ui-label text-foreground",children:q.name})]}),q.alreadyAdded?s.jsx("span",{className:K("inline-flex shrink-0 items-center rounded-md px-1.5 py-0.5 typography-meta font-medium",ae?"bg-interactive-selection-foreground/15 text-interactive-selection-foreground":"bg-[var(--surface-muted)] text-foreground"),children:"Added"}):null,q.type==="parent"?s.jsx(D,{name:"arrow-up-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"}):s.jsx(D,{name:"arrow-right-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"})]},q.value)})})},S)]})}),J=s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[Q,H]}),ne=s.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 typography-micro text-muted-foreground",children:[s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(D,{name:"arrow-up-s",className:"h-3.5 w-3.5"}),s.jsx(D,{name:"arrow-down-s",className:"-ml-1 h-3.5 w-3.5"}),"Navigate"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(D,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Open folder"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{children:ve}),s.jsx(D,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Add folder"]})]}),fe=s.jsx(Ee,{size:r?"xs":"default",onClick:()=>{Z(w)},disabled:!X,className:K(r&&"w-full flex-1"),children:U}),he=()=>s.jsxs(s.Fragment,{children:[r?null:ne,s.jsx("div",{className:K("flex w-full flex-row justify-end gap-2 sm:w-auto",r&&"justify-stretch"),children:fe})]});return r?s.jsx(fa,{open:e,onClose:c,title:"Add folder",className:"h-[88dvh] max-h-[720px]",contentMaxHeightClassName:"flex-1",footer:s.jsx("div",{className:"flex flex-col gap-2",children:he()}),children:s.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3",children:[s.jsx("div",{className:"flex justify-end",children:Oe}),J]})}):s.jsx(es,{open:e,onOpenChange:t,children:s.jsxs(ts,{className:"flex w-full max-w-xl flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh]",initialFocus:!1,children:[s.jsx(xs,{className:"px-5 pb-2 pt-5",children:s.jsxs("div",{className:"flex items-start justify-between gap-4",children:[s.jsxs("div",{children:[s.jsx(as,{children:"Add folder"}),s.jsx(ys,{className:"mt-2",children:"Choose a folder from the path above, then add it."})]}),Oe]})}),s.jsx("div",{className:"min-h-0 flex-1 px-5 pb-0",children:J}),s.jsx(Ds,{className:"flex w-full flex-col gap-3 px-5 py-3 sm:flex-row sm:items-center sm:justify-between",children:he()})]})})},_n=e=>e?s.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:e}):void 0,Mb=()=>{const[e,t]=a.useState(!1),[n,r]=a.useState(null),[o,i]=a.useState(!1),l=Me(A=>A.deleteSession),c=Me(A=>A.deleteSessions),u=le(A=>A.showDeletionDialog),d=le(A=>A.setShowDeletionDialog),{isMobile:f,isTablet:p,hasTouchInput:b}=tn(),g=f||p||b;a.useEffect(()=>jd(()=>{t(!1)}),[]);const m=a.useCallback(A=>{r({sessions:A.sessions,dateLabel:A.dateLabel})},[]),h=a.useCallback(()=>{r(null),i(!1)},[]),y=a.useCallback(async A=>{if(A.sessions.length===0)return;if(A.sessions.length===1){const T=A.sessions[0];await l(T.id)?ie.success("Session deleted"):ie.error("Failed to delete session");return}const j=A.sessions.map(T=>T.id),{deletedIds:w,failedIds:N}=await c(j);if(w.length>0){const T=N.length>0?N.length===1?`${N.length} session could not be deleted.`:`${N.length} sessions could not be deleted.`:A.dateLabel?`Removed all sessions from ${A.dateLabel}.`:void 0;ie.success(w.length===1?"Deleted {count} session":`Deleted ${w.length} sessions`,{description:_n(T)})}N.length>0&&ie.error(N.length===1?`Failed to delete ${N.length} session`:`Failed to delete ${N.length} sessions`,{description:_n("Please try again in a moment.")})},[l,c]);a.useEffect(()=>Es.onDeleteRequest(A=>{if(!u){y(A);return}m(A)}),[m,u,y]),a.useEffect(()=>Es.onDirectoryRequest(()=>{t(!0)}),[]);const x=a.useCallback(async()=>{if(n){i(!0);try{if(n.sessions.length===1){const A=n.sessions[0];if(!await l(A.id)){ie.error("Failed to delete session"),i(!1);return}ie.success("Session deleted",{action:{label:"OK",onClick:()=>{}}})}else{const A=n.sessions.map(T=>T.id),j=await c(A),w=j.deletedIds,N=j.failedIds;if(w.length>0){const T=N.length>0?N.length===1?`${N.length} session could not be deleted.`:`${N.length} sessions could not be deleted.`:n.dateLabel?`Removed all sessions from ${n.dateLabel}.`:void 0;ie.success(w.length===1?"Deleted {count} session":`Deleted ${w.length} sessions`,{description:_n(T),action:{label:"OK",onClick:()=>{}}})}if(N.length>0&&(ie.error(N.length===1?`Failed to delete ${N.length} session`:`Failed to delete ${N.length} sessions`,{description:_n("Please try again in a moment.")}),w.length===0)){i(!1);return}}h()}finally{i(!1)}}},[n,l,c,h]),C=n?n.sessions.length===1?n.dateLabel?`This action permanently removes 1 session from ${n.dateLabel}.`:"This action permanently removes 1 session.":n.dateLabel?`This action permanently removes ${n.sessions.length} sessions from ${n.dateLabel}.`:`This action permanently removes ${n.sessions.length} sessions.`:"",v=n?s.jsxs("div",{className:"space-y-2",children:[n.sessions.length>0&&s.jsx("div",{className:"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3",children:s.jsxs("ul",{className:"space-y-0.5",children:[n.sessions.slice(0,5).map(A=>s.jsx("li",{className:"typography-micro text-muted-foreground/80",children:s.jsx("span",{className:"truncate",children:ps(A)})},A.id)),n.sessions.length>5&&s.jsx("li",{className:"typography-micro text-muted-foreground/70",children:`+${n.sessions.length-5} more`})]})}),s.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/60 p-3",children:s.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Worktree directories stay intact. Subsessions linked to the selected sessions will also be removed."})})]}):null,P=s.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[s.jsxs("button",{type:"button",onClick:()=>d(!u),className:"inline-flex items-center gap-1.5 typography-meta text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":!u,children:[u?s.jsx(D,{name:"checkbox-blank",className:"size-4"}):s.jsx(D,{name:"checkbox",className:"size-4 text-primary"}),"Never ask"]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ee,{variant:"ghost",onClick:h,disabled:o,children:"Cancel"}),s.jsx(Ee,{variant:"destructive",onClick:x,disabled:o,children:o?"Deleting…":n?.sessions.length===1?"Delete session":"Delete sessions"})]})]}),S=n?.sessions.length===1?"Delete session":"Delete sessions";return s.jsxs(s.Fragment,{children:[g?s.jsx(fa,{open:!!n,onClose:()=>{o||h()},title:S,footer:s.jsx("div",{className:"flex justify-end gap-2",children:P}),children:s.jsxs("div",{className:"space-y-2 pb-2",children:[C&&s.jsx("p",{className:"typography-meta text-muted-foreground/80",children:C}),v]})}):s.jsx(es,{open:!!n,onOpenChange:A=>{if(!A){if(o)return;h()}},children:s.jsxs(ts,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[s.jsxs(xs,{children:[s.jsx(as,{children:S}),C&&s.jsx(ys,{children:C})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:v}),s.jsx(Ds,{className:"mt-2 gap-2 pt-1 pb-1",children:P})]})}),s.jsx(xf,{open:e,onOpenChange:t})]})},Tb=()=>{const e=Rs(t=>t.entries);return a.useEffect(()=>{for(const t of e.values())!yu(t)||!t.receipt||(Rs.getState().markNotificationSent(t.key),ie.success("Worktree ready",{id:`worktree-ready:${t.key}`,description:t.receipt.branch||t.receipt.path}))},[e]),null},yf=[{slug:"home",title:"Settings",group:"general",kind:"single",description:"Search and jump to common pages.",keywords:["search","settings"]},{slug:"general",title:"General",group:"general",kind:"single",keywords:["general","startup","launch at login","autostart","tray","password","passkey","security","privacy","telemetry","transport","network","lan","binary","cli","diagnostics","performance"]},{slug:"projects",title:"Projects",group:"projects",kind:"single",keywords:["project","projects","worktree","worktrees","repo","repository","directory"]},{slug:"remote-instances",title:"Remote Instances",group:"projects",kind:"single",keywords:["ssh","remote","instances","tunnels","forwarding","connection"]},{slug:"providers",title:"Providers",group:"agent",kind:"single",keywords:["provider","providers","models","model","api key","api keys","openai","anthropic","ollama","credentials"]},{slug:"behavior",title:"Behavior",group:"agent",kind:"single",keywords:["behavior","agents.md","system prompt","global rules","instructions","override"]},{slug:"skills.installed",title:"Skills",group:"agent",kind:"single",keywords:["skill","skills","instructions","install","catalog"]},{slug:"git",title:"Git",group:"projects",kind:"single",keywords:["git","github","ssh","commit","oauth","prs","issues"]},{slug:"appearance",title:"Appearance",group:"general",kind:"single",keywords:["theme","font","spacing","padding","corner radius","radius","input bar","keyboard","viewport","mobile","terminal","pwa","install name","app shortcuts"]},{slug:"chat",title:"Chat",group:"general",kind:"single",keywords:["tools","diff","reasoning","dotfiles","draft","queue","output","copy","image","split messages","message actions"]},{slug:"dictation",title:"Dictation",group:"general",kind:"single",description:"Record speech and insert a final transcript into the composer.",keywords:["voice","speech","microphone","transcription","stt","whisper","parakeet"]},{slug:"shortcuts",title:"Shortcuts",group:"general",kind:"single",keywords:["keyboard","hotkeys","shortcuts","bindings"]},{slug:"sessions",title:"Sessions",group:"general",kind:"single",keywords:["defaults","default agent","default model","retention","memory","limits","zen"]},{slug:"snippets",title:"Snippets",group:"agent",kind:"single",keywords:["snippet","snippets","text expansion"]},{slug:"prompt-templates",title:"Prompt templates",group:"agent",kind:"single",keywords:["prompt template","prompt templates","slash command","slash commands"]},{slug:"notifications",title:"Notifications",group:"general",kind:"single",keywords:["alerts","native","summary","summarization"]},{slug:"tunnel",title:"External Tunnel",group:"projects",kind:"single",keywords:["tunnel","external","cloudflare","qr","remote","mobile","share"],isAvailable:()=>!1},{slug:"about",title:"About",group:"general",kind:"single",keywords:["about","version","updates","release","changelog","pi","pichamber","open source"]}],wf={sessions:"sessions",skills:"skills.installed",providers:"providers","git-identities":"git",settings:"home"};function vf(e){const t=e.trim().toLowerCase();return yf.find(n=>n.slug===t)??null}function Sf(e){const t=(e??"").trim().toLowerCase();if(!t)return"home";const n=wf[t];if(n)return n;const r=vf(t);return r?r.slug:"home"}function Fb(e){switch(e){case"general":return"equalizer";case"projects":return"folders";case"remote-instances":return"server";case"appearance":return"brush";case"chat":return"chat-1";case"dictation":return"voiceprint";case"snippets":return"sticky-note";case"prompt-templates":return"terminal-box";case"notifications":return"notification-3";case"shortcuts":return"command";case"sessions":return"history";case"providers":return"cloud";case"behavior":return"brain";case"skills.installed":return"puzzle";case"git":return"git-repository";case"tunnel":return"global";case"about":return"pichamber";case"home":return null;default:return"robot-2"}}function Lb(){const e=a.useRef(!1),t=a.useRef(!1),n=Me(f=>f.setCurrentSession),r=le(f=>f.setActiveMainTab),o=le(f=>f.setSettingsDialogOpen),i=le(f=>f.setSettingsPage),l=le(f=>f.navigateToDiff),c=a.useCallback(async f=>{if(!t.current){t.current=!0;try{if(f.sessionId){const p=Me.getState().currentSessionId,b=$s().getState().selectedSessionId;if(f.sessionId!==p||f.sessionId!==b){const g=Me.getState().getDirectoryForSession(f.sessionId);n(f.sessionId,g)}}if(f.settingsPath){i(Sf(f.settingsPath)),o(!0);return}le.getState().isSettingsDialogOpen&&o(!1),f.tab&&r(f.tab),f.diffFile&&(f.tab==="diff"||!f.tab)&&l(f.diffFile)}finally{t.current=!1}}},[n,r,o,i,l]),u=a.useCallback(()=>{const f=Me.getState(),p=$s().getState(),b=le.getState();return{sessionId:Nr({currentSessionId:f.currentSessionId,piSelectedSessionId:p.selectedSessionId,draft:f.newSessionDraft}),tab:b.activeMainTab,isSettingsOpen:b.isSettingsDialogOpen,settingsPath:b.settingsPage,diffFile:b.pendingDiffFile}},[]),d=a.useCallback((f={})=>{if(t.current)return;const p=u();oo(p,f)},[u]);a.useEffect(()=>{if(e.current||(e.current=!0,!ti()))return;const f=si();(async()=>(await c(f),oo({...u(),sessionId:f.sessionId??Nr({currentSessionId:Me.getState().currentSessionId,piSelectedSessionId:$s().getState().selectedSessionId,draft:Me.getState().newSessionDraft}),tab:f.tab??le.getState().activeMainTab,settingsPath:f.settingsPath??le.getState().settingsPage,diffFile:f.diffFile??le.getState().pendingDiffFile},{replace:!0,force:!0})))()},[c,u]),a.useEffect(()=>{const f=()=>{const y=Me.getState(),x=$s().getState();return Nr({currentSessionId:y.currentSessionId,piSelectedSessionId:x.selectedSessionId,draft:y.newSessionDraft})};let p=f(),b=Me.getState().newSessionDraft?.open===!0;const g=()=>{const y=Me.getState(),x=f(),C=y.newSessionDraft?.open===!0;x===p&&C===b||t.current||(p=x,b=C,d({replace:!0}))},m=Me.subscribe(()=>{g()}),h=$s().subscribe(()=>{g()});return()=>{m(),h()}},[d]),a.useEffect(()=>{let f=le.getState().activeMainTab,p=le.getState().isSettingsDialogOpen,b=le.getState().settingsPage,g=le.getState().pendingDiffFile;return le.subscribe(h=>{if(t.current)return;const y=h.activeMainTab!==f,x=h.isSettingsDialogOpen!==p,C=h.settingsPage!==b,v=h.pendingDiffFile!==g&&h.activeMainTab==="diff";f=h.activeMainTab,p=h.isSettingsDialogOpen,b=h.settingsPage,g=h.pendingDiffFile,(y||x||C||v)&&d()})},[d]),a.useEffect(()=>{if(typeof window>"u")return;const f=()=>{const p=si();if(ti())c(p);else{const b=le.getState();b.isSettingsDialogOpen&&o(!1),b.activeMainTab!=="chat"&&r("chat")}};return window.addEventListener("popstate",f),()=>{window.removeEventListener("popstate",f)}},[c,r,o])}function jf(e=!0){const t=Yn(r=>r.checkForUpdates),n=a.useRef(t);a.useEffect(()=>{n.current=t},[t]),a.useEffect(()=>{if(!e)return;const r=3e3,o=3600*1e3,i=300*1e3,l=1440*60*1e3;let c=!1,u=null;const d=p=>{const b=Math.round(p*1e3);return Math.max(i,Math.min(l,b))},f=p=>{c||(u=window.setTimeout(async()=>{const b=await n.current(),g=typeof b=="number"&&Number.isFinite(b)?d(b):o;f(g)},p))};return f(r),()=>{c=!0,u!==null&&window.clearTimeout(u)}},[e])}function Ob(){const e=yn(t=>t.connection==="ready",void 0,"chrome");return jf(e),null}const mi=12,Cf=[{id:"left",x:22,y:58,delay:0,radius:120,colorVar:"--status-success"},{id:"center",x:50,y:42,delay:120,radius:150,colorVar:"--primary-base"},{id:"right",x:78,y:55,delay:200,radius:130,colorVar:"--status-info"}],kf=({isActive:e,burstKey:t=0,className:n,durationMs:r=900,bursts:o=Cf,onComplete:i})=>{const l=Ne.useRef(!1);Ne.useEffect(()=>{!e&&l.current&&i?.(),e&&(l.current=!0)},[e,i]);const c=Ne.useMemo(()=>Array.from({length:mi},(u,d)=>{const f=Math.PI*2*d/mi;return{x:Math.cos(f),y:Math.sin(f),delay:d*18}}),[]);return e?s.jsx("div",{className:K("fireworks-overlay pointer-events-none",n),"aria-hidden":"true","data-burst-key":t,children:o.map(u=>{const d={"--burst-delay":`${u.delay}ms`,"--burst-x":`${u.x}%`,"--burst-y":`${u.y}%`,"--firework-color":`var(${u.colorVar})`,"--firework-duration":`${r}ms`};return s.jsx("div",{className:"firework-burst",style:d,children:c.map((f,p)=>{const b=f.x*u.radius,g=f.y*u.radius,m={"--translate-x":`${b}px`,"--translate-y":`${g}px`,"--particle-delay":`${f.delay}ms`,color:`var(${u.colorVar})`};return s.jsx("span",{className:"firework-particle",style:m},`${u.id}-${p}-${t}`)})},`${u.id}-${t}`)})}):null},Af=({durationMs:e=3400}={})=>{const[t,n]=Ne.useState({isActive:!1,cycle:0}),r=Ne.useRef(null),o=Ne.useCallback(()=>{r.current&&(window.clearTimeout(r.current),r.current=null)},[]),i=Ne.useCallback(()=>{o(),n(c=>c.isActive?{...c,isActive:!1}:c)},[o]),l=Ne.useCallback(()=>{o(),n(c=>({isActive:!0,cycle:c.cycle+1})),r.current=window.setTimeout(()=>{n(c=>c.isActive?{...c,isActive:!1}:c),r.current=null},e)},[o,e]);return Ne.useEffect(()=>()=>o(),[o]),{isActive:t.isActive,burstKey:t.cycle,triggerFireworks:l,dismissFireworks:i}},qa=a.createContext(void 0),Bb=({children:e})=>{const{isActive:t,burstKey:n,triggerFireworks:r,dismissFireworks:o}=Af(),i=a.useMemo(()=>({triggerFireworks:r,dismissFireworks:o}),[r,o]);return s.jsxs(qa.Provider,{value:i,children:[e,s.jsx(kf,{isActive:t,burstKey:n})]})},Nf={triggerFireworks:()=>{},dismissFireworks:()=>{}},_b=()=>a.useContext(qa)??Nf,or=2e3,Ya=600*1e3;async function If(){try{const e=await Pt("/api/pi/update-install",{method:"POST",headers:{"Content-Type":"application/json"}});if(!e.ok){const n=await e.json().catch(()=>({}));return{success:!1,error:n.error||`Server error: ${e.status}`,commands:Array.isArray(n.commands)?n.commands.filter(r=>typeof r=="string"):void 0}}const t=await e.json().catch(()=>({}));return{success:!0,autoRestart:t.autoRestart!==!1,jobId:typeof t.jobId=="string"?t.jobId:void 0,channel:t.channel==="rc"?"rc":t.channel==="stable"?"stable":void 0,targetVersion:typeof t.targetVersion=="string"?t.targetVersion:void 0}}catch(e){return{success:!1,error:e instanceof Error?e.message:void 0}}}async function Ef(e,t=Math.ceil(Ya/or),n=or,r=Je()){for(let o=0;o<t;o++){if(Je()!==r)return{applied:!1,stale:!0};try{const i=await Pt("/api/pi/update-check",{method:"GET",headers:{Accept:"application/json"}});if(Je()!==r)return{applied:!1,stale:!0};if(i.ok){const l=await i.json().catch(()=>null);if(Je()!==r)return{applied:!1,stale:!0};if(typeof l?.error=="string"&&l.error.length>0)return{applied:!1,error:l.error};if(l&&l.available===!1)return{applied:!0};if(l&&typeof l.currentVersion=="string"&&typeof e=="string"&&l.currentVersion!==e)return{applied:!0}}else if(i.status===401||i.status===403)return{applied:!1,error:"Authentication was lost while following the update. Reauthenticate to check its status."}}catch{if(Je()!==r)return{applied:!1,stale:!0}}await new Promise(i=>setTimeout(i,n))}return{applied:!1}}async function Rf(e,t,n=Math.ceil(Ya/or),r=or,o=Je()){for(let i=0;i<n;i++){if(Je()!==o)return{applied:!1,stale:!0};try{const l=await Pt(`/api/pi/update-install/${encodeURIComponent(e)}`,{method:"GET",headers:{Accept:"application/json"}});if(Je()!==o)return{applied:!1,stale:!0};if(l.ok){const c=await l.json().catch(()=>null);if(Je()!==o)return{applied:!1,stale:!0};if(c?.state==="complete")return{applied:!0};if(c?.state==="failed")return{applied:!1,error:c.error||"Update failed"};c?.state==="restarting"?t("restarting"):(c?.state==="queued"||c?.state==="installing"||c?.state==="verifying")&&t("updating")}else{if(l.status===401||l.status===403)return{applied:!1,error:"Authentication was lost while following the update. Reauthenticate to check its status."};if(l.status===404)return{applied:!1,error:"The server lost the update status. Check the installed version or run: pichamber update"};if(l.status===503){const c=await l.json().catch(()=>null);if(Je()!==o)return{applied:!1,stale:!0};if(c?.error==="Update status is unavailable")return{applied:!1,error:c.error};t("reconnecting")}else t("reconnecting")}}catch{if(Je()!==o)return{applied:!1,stale:!0};t("reconnecting")}await new Promise(l=>setTimeout(l,r))}return{applied:!1}}const pi="https://github.com/RyderAsKing/PiChamber/releases";function Df(e){const t=new Date(`${e}T00:00:00`);return Number.isNaN(t.getTime())?e:new Intl.DateTimeFormat("en-US",{year:"numeric",month:"short",day:"numeric"}).format(t)}function Pf(e){return e.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function gi(e){return e.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function Mf(e,t){const n=e.split(".").map(o=>Number.parseInt(o,10)),r=t.split(".").map(o=>Number.parseInt(o,10));for(let o=0;o<3;o+=1){const i=Number.isFinite(n[o])?n[o]:0,l=Number.isFinite(r[o])?r[o]:0;if(i!==l)return l-i}return 0}function Tf(e){const t=/^## \[(\d+\.\d+\.\d+)\] - (\d{4}-\d{2}-\d{2})\s*$/gm,n=[];let r;for(;(r=t.exec(e))!==null;)n.push({version:r[1]??"",date:r[2]??"",start:r.index});return n.length===0?[]:n.map((o,i)=>{const l=n[i+1]?.start??e.length,c=e.slice(o.start,l).trim();return{version:o.version,date:o.date,start:o.start,end:l,raw:c}})}const Qa=({open:e,onOpenChange:t,info:n,downloading:r,downloaded:o,progress:i,error:l,onDownload:c,onRestart:u,runtimeType:d="desktop"})=>{const[f,p]=Ne.useState(null),[b,g]=Ne.useState("idle"),[m,h]=Ne.useState(null),[y,x]=Ne.useState(null),[C,v]=Ne.useState({}),P=n?.version?n.releaseUrl||`${pi}/tag/v${n.version}`:pi,S=n?.downloadUrl||P,A=i?.total?Math.round(i.downloaded/i.total*100):0,j=d==="web",w=d==="mobile",N=n?.updateCommand||"pichamber update",T=C.version||n?.version,L=C.channel||n?.channel;Ne.useEffect(()=>{e||(g("idle"),h(null),x(null),v({}))},[e]);const $=async(I=N)=>{(await bs(I)).ok&&(p(I),setTimeout(()=>p(null),2e3))},z=Ne.useCallback(async I=>{await ha(I)},[]),W=Ne.useCallback(async()=>{const I=Je();g("updating"),h(null),x(null),v({});const M=await If();if(Je()!==I)return;if(!M.success){g("error"),h(M.error||"Update failed"),x(M.commands??null);return}if(v({version:M.targetVersion,channel:M.channel}),M.jobId){const X=await Rf(M.jobId,U=>{Je()===I&&g(U)},void 0,void 0,I);if(X.stale||Je()!==I)return;if(X.applied){window.location.reload();return}g("error"),h(X.error||"Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update");return}g(M.autoRestart?"restarting":"reconnecting");const G=await Ef(n?.currentVersion,void 0,void 0,I);if(!(G.stale||Je()!==I)){if(G.applied){window.location.reload();return}g("error"),h(G.error||"Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update")}},[n?.currentVersion]),F=Ne.useCallback(()=>{z(S)},[z,S]),R=b!=="idle"&&b!=="error",E=Ne.useMemo(()=>{if(!n?.body)return null;const I=n.body.trim();if(!I)return null;const M=Tf(I);return M.length===0?{kind:"raw",title:"What's new",content:gi(I)}:{kind:"sections",title:"What's new",sections:[...M].sort((X,U)=>Mf(X.version,U.version)).map(X=>({version:X.version,dateLabel:Df(X.date),content:gi(Pf(X.raw)||I)}))}},[n?.body]);return s.jsx(es,{open:e,onOpenChange:R?void 0:t,children:s.jsxs(ts,{className:"max-w-4xl p-5 bg-background border-[var(--interactive-border)]",showCloseButton:!0,children:[s.jsxs("div",{className:"flex items-center mb-1",children:[s.jsxs(as,{className:"flex items-center gap-2.5",children:[s.jsx(D,{name:"download-cloud",className:"h-5 w-5 text-[var(--primary-base)]"}),s.jsx("span",{className:"text-lg font-semibold text-foreground",children:b==="restarting"||b==="reconnecting"?"Updating PiChamber...":"Update Available"})]}),(n?.currentVersion||T)&&s.jsxs("div",{className:"flex items-center gap-2 font-mono text-sm ml-3",children:[n?.currentVersion&&s.jsx("span",{className:"text-muted-foreground",children:n.currentVersion}),n?.currentVersion&&T&&s.jsx("span",{className:"text-muted-foreground/50",children:"→"}),T&&s.jsx("span",{className:"text-[var(--primary-base)] font-medium",children:T})]}),j&&L&&s.jsx("span",{className:"ml-3 typography-meta text-muted-foreground",children:L==="rc"?"RC subscription":"Stable subscription"})]}),s.jsxs("div",{className:"space-y-2",children:[j&&R&&s.jsxs("div",{className:"rounded-lg bg-[var(--surface-elevated)]/30 p-5 border border-[var(--surface-subtle)]",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(D,{name:"loader",className:"h-5 w-5 animate-spin text-[var(--primary-base)]"}),s.jsxs("div",{className:"typography-ui-label text-foreground",children:[b==="updating"&&"Installing update...",b==="restarting"&&"Server restarting...",b==="reconnecting"&&"Waiting for server..."]})]}),s.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"The page will reload automatically when the update is complete."})]}),E&&!R&&s.jsx("div",{className:"rounded-lg border border-[var(--surface-subtle)] bg-[var(--surface-elevated)]/20 overflow-hidden",children:s.jsx(Cs,{className:"max-h-[400px] p-0",fillContainer:!1,children:E.kind==="raw"?s.jsx("div",{className:"p-4 typography-markdown-body text-foreground leading-relaxed break-words [&_a]:!text-[var(--primary-base)] [&_a]:!no-underline [&_a:hover]:!underline",onClickCapture:I=>{const G=I.target.closest("a");G&&G.href&&(I.preventDefault(),I.stopPropagation(),z(G.href))},children:s.jsx(ni,{content:E.content,disableLinkSafety:!0,enableFileReferences:!1})}):s.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:E.sections.map(I=>s.jsxs("div",{className:"p-4",children:[s.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[s.jsxs("span",{className:"typography-ui-label font-mono text-[var(--primary-base)] bg-[var(--primary-base)]/10 px-1.5 py-0.5 rounded",children:["v",I.version]}),s.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:I.dateLabel})]}),s.jsx("div",{className:"typography-markdown-body text-foreground leading-relaxed break-words [&_a]:!text-[var(--primary-base)] [&_a]:!no-underline [&_a:hover]:!underline",onClickCapture:M=>{const X=M.target.closest("a");X&&X.href&&(M.preventDefault(),M.stopPropagation(),z(X.href))},children:s.jsx(ni,{content:I.content,disableLinkSafety:!0,enableFileReferences:!1})})]},I.version))})})}),(l||m)&&s.jsx("div",{className:"p-3 mt-4 bg-[var(--status-error-background)] border border-[var(--status-error-border)] rounded-lg",children:s.jsx("p",{className:"text-sm text-[var(--status-error)]",children:l||m})}),j&&b==="error"&&(y??[N]).length>0&&s.jsxs("div",{className:"space-y-2 mt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[s.jsx(D,{name:"terminal",className:"h-4 w-4"}),s.jsx("span",{children:y?"Run these commands:":"Or update via terminal:"})]}),(y??[N]).map(I=>s.jsxs("div",{className:"flex items-center gap-2 p-1 pl-3 bg-[var(--surface-elevated)]/50 rounded-md border border-[var(--surface-subtle)]",children:[s.jsx("code",{className:"flex-1 font-mono text-sm text-foreground overflow-x-auto whitespace-nowrap",children:I}),s.jsx(Ee,{variant:"ghost",size:"icon",onClick:()=>{$(I)},className:f===I?"text-[var(--status-success)]":void 0,title:f===I?"Copied!":"Copy command","aria-label":f===I?"Copied!":"Copy command",children:f===I?s.jsx(D,{name:"check",className:"h-4 w-4"}):s.jsx(D,{name:"clipboard",className:"h-4 w-4"})})]},I))]}),!j&&!w&&r&&s.jsxs("div",{className:"space-y-2 mt-4",children:[s.jsxs("div",{className:"flex items-center justify-between text-sm",children:[s.jsx("span",{className:"text-muted-foreground",children:"Downloading update payload..."}),s.jsxs("span",{className:"font-mono text-foreground",children:[A,"%"]})]}),s.jsx("div",{className:"h-1.5 bg-[var(--surface-subtle)] rounded-full overflow-hidden",children:s.jsx("div",{className:"h-full bg-[var(--primary-base)] transition-all duration-300",style:{width:`${A}%`}})})]})]}),s.jsxs("div",{className:"mt-4 flex items-center justify-between gap-4",children:[s.jsxs("a",{href:P,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors shrink-0",children:[s.jsx(D,{name:"external-link",className:"h-4 w-4"}),"GitHub"]}),s.jsxs("div",{className:"flex-1 flex justify-end",children:[!j&&!w&&!o&&!r&&s.jsxs("button",{onClick:c,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)] text-[var(--primary-foreground)] hover:opacity-90 transition-opacity",children:[s.jsx(D,{name:"download",className:"h-4 w-4"}),"Download Update"]}),!j&&!w&&r&&s.jsxs("button",{disabled:!0,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)]/50 text-[var(--primary-foreground)] cursor-not-allowed",children:[s.jsx(D,{name:"loader",className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!j&&!w&&o&&s.jsxs("button",{onClick:u,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--status-success)] text-white hover:opacity-90 transition-opacity",children:[s.jsx(D,{name:"restart",className:"h-4 w-4"}),"Restart to Update"]}),w&&s.jsxs(Ee,{onClick:F,size:"default",children:[s.jsx(D,{name:"external-link",className:"h-4 w-4"}),"Open update"]}),j&&!R&&s.jsxs("button",{onClick:W,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)] text-[var(--primary-foreground)] hover:opacity-90 transition-opacity",children:[s.jsx(D,{name:"download",className:"h-4 w-4"}),"Update Now"]}),j&&R&&s.jsxs("button",{disabled:!0,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)]/50 text-[var(--primary-foreground)] cursor-not-allowed",children:[s.jsx(D,{name:"loader",className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},Ff=a.memo(function({checked:t,onChange:n,disabled:r=!1,ariaLabel:o,className:i,iconClassName:l}){const c=a.useCallback(d=>{d.preventDefault(),d.stopPropagation(),!r&&!t&&n()},[t,r,n]),u=a.useCallback(d=>{(d.key===" "||d.key==="Enter")&&(d.preventDefault(),!r&&!t&&n())},[t,r,n]);return s.jsx("button",{type:"button",role:"radio",onClick:c,onKeyDown:u,disabled:r,"aria-checked":t,"aria-label":o,className:K("group/radio relative flex h-[14px] w-[14px] min-h-[14px] min-w-[14px] shrink-0 self-center items-center justify-center rounded-full outline-none","transition-[background-color,box-shadow] duration-200 ease-out",t?"bg-[color-mix(in_srgb,var(--primary-base)_80%,transparent)] shadow-none hover:bg-[var(--primary-base)]":"bg-[var(--surface-muted)] shadow-[inset_0_0_0_1px_var(--interactive-border)] hover:bg-[var(--interactive-hover)]","focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] focus-visible:ring-offset-1 focus-visible:ring-offset-background","disabled:cursor-not-allowed disabled:opacity-50",i),children:s.jsx("span",{"aria-hidden":!0,className:K("block h-[5px] w-[5px] rounded-full bg-white",!t&&"opacity-0",l)})})}),Dn=({children:e,className:t,contentClassName:n})=>{const[r,o]=a.useState(!1),i=a.useRef(null);return a.useEffect(()=>{if(!r)return;const l=c=>{const u=i.current;u&&c.target instanceof Node&&u.contains(c.target)||o(!1)};return document.addEventListener("pointerdown",l,!0),()=>document.removeEventListener("pointerdown",l,!0)},[r]),s.jsxs($e,{open:r,onOpenChange:o,children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{ref:i,type:"button","aria-label":"More information","aria-expanded":r,onClick:l=>{l.preventDefault(),l.stopPropagation(),o(c=>!c)},className:K("inline-flex h-5 w-5 shrink-0 cursor-help items-center justify-center rounded text-muted-foreground/60 hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",t),children:s.jsx(D,{name:"information",className:"h-3.5 w-3.5"})})}),s.jsx(We,{sideOffset:8,className:K("max-w-sm",n),children:e})]})},Ub="w-full min-w-40 max-w-48",zb="settings",Lf="w-full min-w-40 max-w-48",$b="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",Of="w-full max-w-[24rem]",Kb="min-w-0 flex-1",Wb="flex w-full min-w-0 items-center gap-2",Gb="typography-meta shrink-0 text-muted-foreground tabular-nums",Va="space-y-3.5",Bf="space-y-1.5",Hb="typography-settings-page-title text-muted-foreground",_f="typography-settings-section-title text-foreground",Ja="typography-settings-group-title text-foreground",Io="typography-settings-field-label text-foreground",Uf="typography-settings-description text-muted-foreground",Pn="typography-meta text-muted-foreground",qb="typography-meta font-medium text-foreground",Yb="typography-settings-section-title text-foreground",zf=({title:e,description:t,titleAccessory:n,info:r,headerAction:o,children:i,divider:l=!0,className:c,contentClassName:u,settingsItem:d})=>{const f=e!=null||t!=null||o!=null||r!=null;return s.jsxs("section",{"data-settings-item":d,className:K("space-y-4",l?"border-t border-border/60 py-6":"pb-6",c),children:[f?s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 space-y-1",children:[e!=null?s.jsxs("div",{className:"flex items-center gap-2",children:[typeof e=="string"||typeof e=="number"?s.jsx("h2",{className:_f,children:e}):e,n,r!=null?s.jsx(Dn,{children:r}):null]}):null,t!=null?s.jsx("div",{className:Uf,children:t}):null]}),o?s.jsx("div",{className:"shrink-0",children:o}):null]}):null,s.jsx("div",{className:K(u),children:i})]})},Qb=({children:e,className:t})=>s.jsx("div",{className:K("grid grid-cols-1 gap-6 @3xl:grid-cols-2 @3xl:gap-10",t),children:e}),$f=({children:e,className:t,as:n="h3"})=>s.jsx(n,{className:K(Ja,t),children:e}),Vb=({title:e,description:t,info:n,children:r,className:o,contentClassName:i,settingsItem:l})=>s.jsxs("div",{"data-settings-item":l,className:K("space-y-2",o),children:[e!=null||t!=null||n!=null?s.jsxs("div",{className:"space-y-0.5",children:[e!=null?s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx($f,{children:e}),n!=null?s.jsx(Dn,{children:n}):null]}):null,t!=null?s.jsx("p",{className:Pn,children:t}):null]}):null,s.jsx("div",{className:K(i),children:r})]}),Sn=({label:e,description:t,info:n,descriptionPlacement:r="before",children:o,settingsItem:i,className:l,controlClassName:c})=>{const u=t!=null?s.jsx("p",{className:Pn,children:t}):null;return s.jsxs("div",{"data-settings-item":i,className:K("space-y-2",l),children:[s.jsxs("div",{className:"space-y-0.5",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("div",{className:Io,children:e}),n!=null?s.jsx(Dn,{children:n}):null]}),r==="before"?u:null]}),s.jsx("div",{className:K("flex min-w-0 max-w-[24rem] items-center gap-2",c),children:o}),r==="after"?u:null]})},Jb=({label:e,description:t,info:n,children:r,settingsItem:o,className:i,labelClassName:l,controlClassName:c,alignEnd:u=!0})=>s.jsxs("div",{"data-settings-item":o,className:K("flex flex-col gap-2 py-0.5 @xl:flex-row @xl:items-center @xl:gap-8",i),children:[s.jsxs("div",{className:K("min-w-0 @xl:w-56 @xl:shrink-0",l),children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("div",{className:Io,children:e}),n!=null?s.jsx(Dn,{children:n}):null]}),t!=null?s.jsx("p",{className:K(Pn,"mt-0.5"),children:t}):null]}),s.jsx("div",{className:K("flex min-w-0 flex-1 items-center gap-2 @xl:w-fit @xl:flex-none",u&&"@xl:justify-end",c),children:r})]}),Xb=({children:e,className:t,settingsItem:n})=>s.jsx("div",{"data-settings-item":n,className:K("pt-4",t),children:e}),Kf=({checked:e,onChange:t,label:n,description:r,disabled:o=!1,ariaLabel:i,settingsItem:l,className:c,labelAccessory:u,info:d})=>{const f=()=>{o||t(!e)},p=r!=null;return s.jsxs("div",{"data-settings-item":l,className:K("group flex cursor-pointer gap-2 py-0.5",p?"items-start":"items-center",o&&"cursor-not-allowed opacity-60",c),role:"button",tabIndex:o?-1:0,"aria-pressed":e,"aria-disabled":o||void 0,onClick:f,onKeyDown:b=>{(b.key===" "||b.key==="Enter")&&(b.preventDefault(),f())},children:[s.jsx(Qr,{checked:e,onChange:t,disabled:o,ariaLabel:i}),s.jsxs("div",{className:"flex min-w-0 flex-col",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[s.jsx("span",{className:Io,children:n}),u,d!=null?s.jsx(Dn,{children:d}):null]}),p?s.jsx("span",{className:Pn,children:r}):null]})]})},Zb=({selected:e,onSelect:t,label:n,description:r,ariaLabel:o,disabled:i=!1,className:l})=>s.jsxs("div",{className:K("flex cursor-pointer gap-2 py-0.5",r!=null?"items-start":"items-center",i&&"cursor-not-allowed opacity-60",l),role:"button",tabIndex:i?-1:0,"aria-pressed":e,"aria-disabled":i||void 0,onClick:()=>{i||t()},onKeyDown:c=>{(c.key===" "||c.key==="Enter")&&(c.preventDefault(),i||t())},children:[s.jsx(Ff,{checked:e,onChange:t,disabled:i,ariaLabel:o,className:r!=null?"mt-0.5":void 0}),s.jsxs("div",{className:"flex min-w-0 flex-col",children:[s.jsx("span",{className:K("typography-settings-field-label font-normal",e?"text-foreground":"text-foreground/50"),children:n}),r!=null?s.jsx("span",{className:Pn,children:r}):null]})]}),ex=({"aria-label":e,children:t,className:n})=>s.jsx("div",{role:"radiogroup","aria-label":e,className:K(Bf,n),children:t});function tx({value:e,options:t,onChange:n,className:r,"aria-label":o}){return s.jsx("div",{role:"group","aria-label":o,className:K("flex flex-wrap items-center gap-1",r),children:t.map(i=>s.jsx(Ee,{type:"button",variant:"chip",size:"xs",disabled:i.disabled,"aria-pressed":e===i.value,className:"!font-normal",onClick:()=>n(i.value),children:i.label},i.value))})}const co="pichamber:server-update-channel-changed",sx=()=>{typeof window<"u"&&window.dispatchEvent(new Event(co))},Wf=e=>typeof window>"u"?()=>{}:(window.addEventListener(co,e),()=>window.removeEventListener(co,e));class Gf extends a.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){this.setState({error:t,errorInfo:n})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?s.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:s.jsxs(wu,{className:"w-full max-w-md",children:[s.jsx(vu,{className:"text-center",children:s.jsxs(Su,{className:"flex items-center justify-center gap-2 text-destructive",children:[s.jsx(D,{name:"chat-3",className:"h-5 w-5"}),this.props.texts.title]})}),s.jsxs(ju,{className:"space-y-4",children:[s.jsx("p",{className:"text-sm text-muted-foreground text-center",children:this.props.texts.description}),this.props.sessionId&&s.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:[this.props.texts.sessionLabel,": ",this.props.sessionId]}),this.state.error&&s.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[s.jsx("summary",{className:"cursor-pointer hover:bg-interactive-hover/80",children:this.props.texts.detailsSummary}),s.jsx("pre",{className:"mt-2 max-h-48 overflow-auto",children:this.state.error.toString()})]}),s.jsx("div",{className:"flex gap-2",children:s.jsxs(Ee,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[s.jsx(D,{name:"restart",className:"h-4 w-4 mr-2"}),this.props.texts.resetAction]})}),s.jsx("div",{className:"text-xs text-muted-foreground text-center",children:this.props.texts.persistentHint})]})]})}):this.props.children}}function Hf(e){return s.jsx(Gf,{...e,texts:{title:"Chat Error",description:"The chat interface encountered an error. This might be due to a temporary network issue or corrupted message data.",sessionLabel:"Session",detailsSummary:"Error details",resetAction:"Reset Chat",persistentHint:"If the problem persists, try refreshing the page."}})}const nx=({active:e=!0})=>{const t=Me(n=>n.currentSessionId);return s.jsx(Hf,{sessionId:t||void 0,children:s.jsx(Cu,{active:e},t??"no-session")})};function qf({onResizeStart:e,ariaLabel:t}){return s.jsx("div",{role:"separator","aria-orientation":"horizontal","aria-label":t,onPointerDown:e,className:"pointer-events-auto -m-2 flex size-7 cursor-ns-resize items-end justify-end p-2 touch-none select-none",children:s.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":!0,children:s.jsx("path",{d:"M9.11111 2L2 9.11111M10 6.44444L6.44444 10",className:"stroke-muted-foreground",strokeLinecap:"round"})})})}const Xa=Ne.forwardRef(({className:e,outerClassName:t,scrollbarClassName:n,fillContainer:r=!1,useScrollShadow:o=!1,scrollShadowSize:i,hasError:l,resizedHeight:c,onResizeHeightChange:u,disabled:d,simple:f,endSlot:p,...b},g)=>{const m=Ne.useRef(null),h=Ne.useRef(null),[y,x]=Ne.useState(null),C=c??y,v=Ne.useCallback(S=>{const A=m.current;if(!A)return;h.current={startY:S.clientY,startHeight:A.getBoundingClientRect().height};const j=S.currentTarget;j.setPointerCapture(S.pointerId);const w=T=>{const L=h.current;if(!L)return;const $=L.startHeight+(T.clientY-L.startY),z=Math.max(82,$);u?u(z):x(z)},N=()=>{h.current=null,j.removeEventListener("pointermove",w),j.removeEventListener("pointerup",N),j.removeEventListener("pointercancel",N)};j.addEventListener("pointermove",w),j.addEventListener("pointerup",N),j.addEventListener("pointercancel",N),S.preventDefault()},[u]),P=Ne.useCallback(S=>{if(S.target.closest('textarea, button, [role="separator"]'))return;const j=m.current?.querySelector("textarea");j&&document.activeElement!==j&&(S.preventDefault(),j.focus())},[]);return f?s.jsx(Cs,{as:"textarea",ref:g,disableHorizontal:!0,fillContainer:r,useScrollShadow:o,scrollShadowSize:i,outerClassName:t,scrollbarClassName:n,className:K("block w-full appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","px-3 py-2 md:typography-ui-label","placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",r?"[field-sizing:fixed]":"field-sizing-content",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:d,...b}):s.jsx("div",{ref:m,onPointerDown:P,style:C!==null?{height:`${C}px`}:void 0,className:K("group/textarea relative flex w-full flex-col rounded-[var(--radius-xl)] bg-[var(--surface-elevated)] pb-2.5","ring-1 ring-inset ring-border/60 transition duration-200 ease-out","hover:[&:not(:focus-within)]:bg-[var(--surface-subtle)]","has-[[disabled]]:pointer-events-none has-[[disabled]]:bg-[var(--surface-subtle)] has-[[disabled]]:ring-transparent",!l&&["hover:[&:not(:focus-within)]:ring-transparent","focus-within:ring-2 focus-within:ring-[var(--interactive-focus-ring)]"],l&&["ring-[var(--status-error)]","focus-within:ring-2 focus-within:ring-[var(--status-error)]"],t),children:s.jsxs("div",{className:"flex h-full min-h-0 flex-1 flex-col gap-2",children:[s.jsx("textarea",{ref:g,className:K("block w-full flex-1 min-h-0 appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","min-h-[82px] pl-3 pr-2.5 pt-2.5 md:typography-ui-label","focus-visible:outline-none disabled:cursor-not-allowed",!d&&["placeholder:select-none placeholder:text-muted-foreground placeholder:transition placeholder:duration-200 placeholder:ease-out","group-hover/textarea:placeholder:text-foreground/80","focus:placeholder:text-foreground/80"],d&&"text-muted-foreground/60 placeholder:text-muted-foreground/60",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:d,...b}),s.jsxs("div",{className:"flex items-center justify-end gap-1.5 pl-3 pr-2.5",children:[p,s.jsx(qf,{onResizeStart:v,ariaLabel:"Resize textarea"})]})]})})});Xa.displayName="Textarea";const Za=[{key:"play",label:"Play",Icon:"play"},{key:"build",label:"Build",Icon:"hammer"},{key:"lint",label:"Lint",Icon:"checkbox-circle"},{key:"terminal",label:"Terminal",Icon:"terminal-box"},{key:"tools",label:"Tools",Icon:"tools"},{key:"bug",label:"Bug",Icon:"bug"},{key:"flask",label:"Flask",Icon:"flask"},{key:"rocket",label:"Rocket",Icon:"rocket"},{key:"code",label:"Code",Icon:"code"},{key:"server",label:"Server",Icon:"server"},{key:"branch",label:"Branch",Icon:"git-branch"},{key:"search",label:"Search",Icon:"search"},{key:"settings",label:"Settings",Icon:"settings-3"},{key:"brain",label:"Brain",Icon:"brain-ai-3"},{key:"stack",label:"Stack",Icon:"stack"},{key:"robot",label:"Robot",Icon:"robot-2"},{key:"command",label:"Command",Icon:"command"},{key:"file",label:"File",Icon:"file-text"}],jn=Object.fromEntries(Za.map(e=>[e.key,e.Icon])),uo="pichamber:project-actions-updated",el=e=>{const t=(e||"").trim().replace(/\\/g,"/");return t?t==="/"?"/":t.length>1?t.replace(/\/+$/,""):t:""},rs=(e,t)=>`${el(e)}::${t}`,tl=({title:e,description:t,info:n,settingsItem:r,titleAccessory:o,headerAction:i,children:l,className:c,contentClassName:u,divider:d=!0})=>s.jsx(zf,{title:e,description:t,info:n,settingsItem:r,titleAccessory:o,headerAction:i,divider:d,className:c,contentClassName:u,children:l}),fo=e=>e.name.trim().length>0&&e.command.trim().length>0,Yf=e=>e.name.trim().length===0&&e.command.trim().length===0,Qf=e=>!fo(e)&&!Yf(e),Vf=(e,t)=>e.some(r=>t.has(r.id)&&!fo(r))?{canPersist:!1,actions:e}:{canPersist:!0,actions:e.filter(fo)},Jf=450,Xf=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,Zf=()=>({id:Xf(),name:"",command:"",icon:"play"}),eh=({projectRef:e})=>{const[t,n]=a.useState([]),[r,o]=a.useState(!1),[i,l]=a.useState(null),[c,u]=a.useState(new Set),d=a.useRef(!1);a.useEffect(()=>{let x=!1;return o(!0),(async()=>{try{const C=await Vr(e);if(x)return;n(C.actions),l(JSON.stringify({actions:C.actions})),u(new Set(C.actions.map(v=>v.id)))}catch{if(x)return;n([]),l(JSON.stringify({actions:[]})),u(new Set)}finally{x||o(!1)}})(),()=>{x=!0}},[e]);const f=a.useMemo(()=>Vf(t,c),[t,c]),p=a.useMemo(()=>JSON.stringify({actions:f.actions}),[f.actions]),b=i!==null&&f.canPersist&&p!==i,g=a.useCallback(async x=>await ku(e,{actions:x,primaryActionId:null})?(l(JSON.stringify({actions:x})),u(new Set(x.map(v=>v.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent(uo,{detail:{projectId:e.id}})),!0):(ie.error("Failed to save actions"),!1),[e]);a.useEffect(()=>{if(!b||r||d.current)return;const x=window.setTimeout(()=>{d.current||(d.current=!0,(async()=>{try{await g(f.actions)}finally{d.current=!1}})())},Jf);return()=>{window.clearTimeout(x)}},[b,r,g,f.actions]);const m=a.useCallback(()=>{const x=Zf();n(C=>[...C,x])},[]),h=a.useCallback(x=>{n(C=>C.filter(v=>v.id!==x))},[]),y=a.useCallback((x,C)=>{n(v=>v.map(P=>P.id===x?C(P):P))},[]);return s.jsx(tl,{title:"Actions",info:"Per-project commands shown in the header next to the project name.",settingsItem:"projects.actions",headerAction:s.jsxs(Ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:m,children:[s.jsx(D,{name:"add",className:"h-3.5 w-3.5"}),"Add action"]}),contentClassName:"space-y-4",children:r?s.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):t.length===0?s.jsx("p",{className:"typography-meta text-muted-foreground",children:"No actions configured yet."}):s.jsx("div",{className:K("space-y-6",Of),children:t.map((x,C)=>{const v=x.icon||"play",P=jn[v]||"play",S=x.name.trim()||`Action ${C+1}`,A=Qf(x);return s.jsxs("div",{className:Va,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("h3",{className:Ja,children:S}),s.jsx(Ee,{type:"button",variant:"ghost",size:"xs",className:"h-8 w-8 px-0 text-muted-foreground hover:text-[var(--status-error)]",onClick:()=>h(x.id),"aria-label":`Delete ${S}`,children:s.jsx(D,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),s.jsxs(Sn,{label:"Name",controlClassName:"w-full max-w-none",children:[s.jsxs(Jt,{children:[s.jsx(Xt,{asChild:!0,children:s.jsx("button",{type:"button",className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-[var(--interactive-border)] text-foreground hover:bg-[var(--interactive-hover)]","aria-label":"Select icon",children:s.jsx(D,{name:P,className:"h-4 w-4"})})}),s.jsx(Zt,{align:"start",className:"w-56 p-2",children:s.jsx("div",{className:"grid grid-cols-6 gap-1",children:Za.map(j=>{const w=j.Icon,N=(x.icon||"play")===j.key;return s.jsx("button",{type:"button",onClick:()=>y(x.id,T=>({...T,icon:j.key})),className:K("inline-flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-foreground hover:bg-[var(--interactive-hover)]",N&&"border-[var(--primary-base)] bg-[var(--primary-base)]/10 text-[var(--primary-base)]"),"aria-label":`Icon ${j.label}`,children:s.jsx(D,{name:w,className:"h-4 w-4"})},j.key)})})})]}),s.jsx(kn,{value:x.name,onChange:j=>y(x.id,w=>({...w,name:j.target.value})),placeholder:"Action name",className:"h-8 min-w-0 flex-1 rounded-md px-3"})]}),s.jsx(Sn,{label:"Command",controlClassName:"w-full max-w-none",children:s.jsx(Xa,{value:x.command,onChange:j=>y(x.id,w=>({...w,command:j.target.value})),placeholder:"e.g. bun run lint",className:"min-h-[88px] w-full font-mono text-xs"})}),A?s.jsx("p",{className:"typography-meta text-muted-foreground",children:"Enter a name and command to save this action."}):null,s.jsx(Kf,{checked:x.autoOpenUrl===!0,onChange:j=>y(x.id,w=>({...w,...j?{autoOpenUrl:!0}:{autoOpenUrl:void 0,openUrl:void 0}})),label:"Auto-open URL",info:"Opens a URL from command output, or a custom URL if you set one.",ariaLabel:`Auto-open URL for ${S}`}),x.autoOpenUrl===!0?s.jsx(s.Fragment,{children:s.jsx(Sn,{label:"Custom URL",info:"Leave empty to use the best URL from command output.",controlClassName:"w-full max-w-none",children:s.jsx(kn,{value:x.openUrl||"",onChange:j=>y(x.id,w=>({...w,openUrl:j.target.value})),placeholder:"https://localhost:3000",className:"h-8 w-full rounded-md px-3"})})}):null]},x.id)})})})},th={searchPlaceholder:"Search models",noResults:"No models found",favorites:"Favorites",recent:"Recent",favorite:"Favorite",unfavorite:"Unfavorite",capabilities:"Capabilities",capabilityToolCalling:"Tool calling",capabilityReasoning:"Reasoning",input:"Input",output:"Output",costPerMillion:"Cost ($/1M tokens)"},sh=({value:e,noneLabel:t,ariaLabel:n,disabled:r=!1,className:o,isModelAllowed:i,onChange:l})=>{const c=Ut(w=>w.providers),u=Ut(w=>w.modelsMetadata),d=le(w=>w.hiddenModels),f=le(w=>w.isFavoriteModel),p=le(w=>w.toggleFavoriteModel),b=le(w=>w.reorderFavoriteModel),{favoriteModelsList:g,recentModelsList:m}=Au(),[h,y]=a.useState(!1),[x,C]=a.useState("");a.useEffect(()=>{h?Ut.getState().ensureModelMetadata():C("")},[h]);const v=e?c.find(w=>w.id===e.providerId):void 0,P=e&&v?(Array.isArray(v.models)?v.models:[]).find(w=>w.id===e.modelId):void 0,S=e?Nu(P,e.modelId):t,A=a.useMemo(()=>e?d.filter(w=>!(w.providerID===e.providerId&&w.modelID===e.modelId)):d,[d,e]),j=a.useCallback(w=>{l({providerId:w.providerID,modelId:w.modelID}),y(!1)},[l]);return s.jsxs(Jt,{modal:!1,open:h,onOpenChange:w=>{r||y(w)},children:[s.jsx(Xt,{asChild:!0,disabled:r,children:s.jsxs("button",{type:"button","aria-label":n,disabled:r,className:K(Eu({size:"default"}),Lf,"min-w-0",o),children:[s.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e?.providerId?s.jsx(Iu,{providerId:e.providerId,className:"size-4 shrink-0"}):null,s.jsx("span",{className:K("truncate",e?"text-foreground":"text-muted-foreground"),children:S})]}),s.jsx(D,{name:"arrow-down-s",className:"size-4 shrink-0"})]})}),s.jsx(Zt,{align:"start",portalToBody:!0,positionerClassName:"z-[80]",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",children:s.jsx(Ru,{providers:c,favoriteModels:g,recentModels:m,modelsMetadata:u,searchQuery:x,onSearchQueryChange:C,onSelect:j,labels:{...th,notSelected:t},selectedModel:e?{providerID:e.providerId,modelID:e.modelId}:null,hiddenModels:A,isModelAllowed:i,includeNotSelected:!0,onSelectNone:()=>{l(null),y(!1)},disabled:r,autoFocus:!0,onEscape:()=>y(!1),isFavorite:w=>f(w.providerID,w.modelID),onToggleFavorite:w=>p(w.providerID,w.modelID),onReorderFavorite:(w,N)=>b(w.providerID,w.modelID,N.providerID,N.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite"})})]})},Er="w-full max-w-none",nh=({form:e})=>{const{name:t,setName:n,parsedDefaultModel:r,handleDefaultModelChange:o,project:i}=e,l=Ut(c=>c.loadProviders);return a.useEffect(()=>{l({source:"projectSettings"})},[l]),i?s.jsx(tl,{title:"Project",divider:!1,children:s.jsxs("div",{className:Va,children:[s.jsx(Sn,{label:"Name",settingsItem:"projects.name",controlClassName:Er,children:s.jsx(kn,{value:t,onChange:c=>n(c.target.value),placeholder:"Project name","aria-label":"Project name",className:"h-8 w-full rounded-md px-3"})}),s.jsx(Sn,{label:"Default model",info:"Used when starting a new chat in this project. Unset keeps the global session default.",settingsItem:"projects.default-model",controlClassName:Er,children:s.jsx(sh,{value:r,noneLabel:"Use global default",ariaLabel:"Default model for new chats",className:Er,onChange:c=>{if(!c){o("","");return}o(c.providerId,c.modelId)}})})]})}):null},rh=e=>{const[t,n]=a.useState(""),[r,o]=a.useState(void 0);a.useEffect(()=>{if(!e){n(""),o(void 0);return}n(e.label??""),o(e.defaultModel)},[e]);const i=a.useMemo(()=>Du(r),[r]),l=!!e&&(t.trim()!==(e?.label??"").trim()||(r??void 0)!==(e?.defaultModel??void 0)),c=a.useCallback((d,f)=>{o(d&&f?`${d}/${f}`:void 0)},[]),u=a.useCallback(async()=>{if(!e)return null;const d=t.trim();return d?{label:d,defaultModel:r??null}:null},[r,t,e]);return{name:t,setName:n,defaultModel:r,parsedDefaultModel:i,handleDefaultModelChange:c,hasChanges:l,prepareSaveData:u,project:e}},oh=450,ih=(e,t)=>{const{hasChanges:n,name:r,defaultModel:o,prepareSaveData:i}=e,l=a.useRef(!1);a.useEffect(()=>{if(!n||!r.trim()||l.current)return;const c=window.setTimeout(()=>{l.current||(l.current=!0,(async()=>{try{const u=await i();if(u)try{await t(u)}catch{ie.error("Failed to save project settings")}}finally{l.current=!1}})())},oh);return()=>{window.clearTimeout(c)}},[o,n,r,t,i])},ah=({project:e,onIdentitySave:t})=>{const n=rh(e),r=a.useMemo(()=>e?{id:e.id,path:e.path}:null,[e]),o=a.useCallback(async i=>{await t(i)},[t]);return ih(n,o),!e||!r?null:s.jsxs("div",{className:"space-y-0",children:[s.jsx(nh,{form:n}),s.jsx(eh,{projectRef:r})]})},lh=6e4,ch=3e4,dn=new Map;let bi=0,xi=!1;const uh=()=>{if(xi||typeof window>"u")return;xi=!0;const e=()=>{const t=Date.now();t-bi<ch||typeof document<"u"&&document.hidden||(bi=t,dt(async()=>{const{getRegisteredRuntimeAPIs:n}=await import("./index-6IO1AcJI.js").then(r=>r.cv);return{getRegisteredRuntimeAPIs:n}},__vite__mapDeps([2,3,4,5,6,7,8])).then(({getRegisteredRuntimeAPIs:n})=>{const r=n()?.github;r&&br.getState().refresh(r)}).catch(()=>{}))};window.addEventListener("focus",e),typeof document<"u"&&document.addEventListener("visibilitychange",()=>{document.hidden||e()})},br=Ts()(gr((e,t)=>({status:null,fetchedAt:null,isLoading:!1,error:null,runtimeKey:Dt(),resetForRuntimeSwitch:n=>{const r=n??Dt();dn.clear(),e({status:null,fetchedAt:null,isLoading:!1,error:null,runtimeKey:r})},refresh:async(n,r)=>{uh();const o=Dt();t().runtimeKey!==o&&t().resetForRuntimeSwitch(o);const i=t(),l=Date.now();if(!r?.force&&i.status&&i.fetchedAt&&l-i.fetchedAt<lh)return i.status;const c=dn.get(o);if(c)return c;const u=n??null;if(!u)return t().status;const d=(async()=>{e({isLoading:!0});try{const f=await u.status();return Dt()!==o?null:(e({status:f,fetchedAt:Date.now(),isLoading:!1,error:null,runtimeKey:o}),f)}catch(f){return Dt()!==o?null:(e({isLoading:!1,error:f instanceof Error?f.message:"GitHub status check failed"}),t().status)}})();dn.set(o,d);try{return await d}finally{dn.get(o)===d&&dn.delete(o)}}}),{name:"github-status-store"}));typeof window<"u"&&Rn(e=>{br.getState().resetForRuntimeSwitch(e.runtimeKey)});const dh=()=>br(e=>(e.status?.hosts??[]).find(n=>n.authenticated)?.login??null),Un=100;function rx(){const e=le(w=>w.isArchivePageOpen),t=le(w=>w.setArchivePageOpen),n=le(w=>w.setActiveMainTab),r=Me(w=>w.setCurrentSession),o=Me(w=>w.unarchiveSession),i=Js(w=>w.homeDirectory),l=Jr({archived:!0}),[c,u]=a.useState(""),[d,f]=a.useState(null),[p,b]=a.useState(Un),g=c.trim().toLowerCase(),m=a.useMemo(()=>e?[...l].sort((w,N)=>(N.time?.archived??0)-(w.time?.archived??0)):[],[l,e]),h=a.useMemo(()=>{const w=new Map;for(const N of m){const T=Ae(wn(N))??"",L=w.get(T);if(L){L.sessions.push(N);continue}w.set(T,{directory:T,label:T?Xs(T,i)||T:"other projects",sessions:[N]})}return[...w.values()].sort((N,T)=>T.sessions.length-N.sessions.length)},[i,m]),y=a.useMemo(()=>g?m.filter(w=>(w.title??"").toLowerCase().includes(g)):d===null?m:h.find(w=>w.directory===d)?.sessions??[],[h,g,d,m]),x=y.slice(0,p),C=y.length-x.length,v=l.length,P=a.useCallback(w=>{f(w),b(Un)},[]),S=a.useCallback(w=>{const N=Ae(wn(w));r(w.id,N??void 0),n("chat"),t(!1)},[n,r,t]),A=a.useCallback(w=>{o(w.id).then(N=>{N?ie.success("Session restored"):ie.error("Failed to restore session")})},[o]);if(!e)return null;const j=(w,N,T,L,$,z,W)=>s.jsxs("div",{className:"group/dir relative",children:[s.jsxs("button",{type:"button",onClick:$,title:z,className:K("flex w-full min-w-0 items-center gap-2 rounded-md px-2 py-1.5 text-left typography-ui-label transition-[padding] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",W?"group-hover/dir:pr-8 group-focus-within/dir:pr-8":"",L?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground"),children:[s.jsx("span",{className:"min-w-0 flex-1 truncate",children:N}),s.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground/70",children:T})]}),W?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:()=>Es.requestDelete({sessions:W,mode:"session"}),className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:text-destructive group-hover/dir:opacity-100 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete all archived sessions in ${N}`,children:s.jsx(D,{name:"delete-bin",className:"h-3.5 w-3.5"})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:"Delete all archived sessions in this project"})]}):null]},w);return s.jsx(Zc,{open:e,onOpenChange:t,children:s.jsxs(eu,{children:[s.jsx(tu,{className:"fixed inset-0 z-50 bg-black/25 dark:bg-black/40 transition-opacity duration-150 data-[starting-style]:opacity-0 data-[ending-style]:opacity-0"}),s.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 max-[640px]:p-2 pointer-events-none",children:s.jsxs(su,{className:"pointer-events-auto relative flex h-[min(84vh,720px)] max-h-[calc(100dvh-2rem)] w-[min(92vw,960px)] flex-col overflow-hidden rounded-2xl border border-border/80 bg-background shadow-2xl transition-all duration-150 data-[starting-style]:scale-[0.98] data-[starting-style]:opacity-0 data-[ending-style]:scale-[0.98] data-[ending-style]:opacity-0 max-[640px]:h-[calc(100dvh-1rem)] max-[640px]:max-h-none max-[640px]:w-[calc(100vw-1rem)] max-[640px]:rounded-xl",children:[s.jsx(nu,{className:"sr-only",children:"Archived sessions"}),s.jsx(ru,{className:"sr-only",children:"Browse and restore archived sessions."}),s.jsx(ou,{"aria-label":"Close archived sessions",className:"absolute right-3 top-3 z-10 inline-flex size-8 items-center justify-center rounded-md bg-background/80 text-muted-foreground backdrop-blur-sm hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:s.jsx(D,{name:"close",className:"size-4"})}),s.jsxs("div",{className:"flex min-h-0 flex-1",children:[s.jsx("div",{className:"flex w-64 flex-shrink-0 flex-col border-r border-border/50 max-[640px]:w-40",children:s.jsxs("div",{className:"flex-1 space-y-0.5 overflow-y-auto p-2",children:[j("__all__","All directories",v,d===null,()=>P(null)),h.map(w=>j(w.directory||"__none__",w.label,w.sessions.length,d===w.directory,()=>P(w.directory),w.directory||void 0,w.sessions))]})}),s.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[s.jsxs("div",{className:"flex items-center gap-3 px-6 pr-12 pt-3",children:[s.jsxs("div",{className:"relative min-w-0 flex-1",children:[s.jsx(D,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),s.jsx("input",{value:c,onChange:w=>{u(w.target.value),b(Un)},placeholder:"Search archived sessions",className:"h-8 w-full rounded-md border border-border bg-transparent pl-8 pr-3 typography-ui-label text-foreground outline-none focus-visible:ring-2 focus-visible:ring-primary/50"})]}),s.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:y.length===1?`${y.length} archived session`:`${y.length} archived sessions`})]}),s.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-6 py-3",children:s.jsxs("div",{className:"mx-auto w-full max-w-3xl space-y-0.5",children:[x.length===0?s.jsx("div",{className:"py-10 text-center text-muted-foreground",children:s.jsx("p",{className:"typography-ui-label font-semibold",children:g?"No matching archived sessions":"No archived sessions"})}):x.map(w=>{const N=Ae(wn(w))??"",T=N?Xs(N,i)||N:null;return s.jsxs("div",{className:"group relative flex cursor-pointer items-center gap-3 rounded-md py-1 pl-2 pr-2 transition-[padding] hover:bg-interactive-hover/40 hover:pr-14 focus-within:pr-14",onClick:()=>S(w),role:"button",tabIndex:0,onKeyDown:L=>{(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),S(w))},children:[s.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:ps(w)}),g&&T?s.jsx("span",{className:"max-w-40 flex-shrink-0 truncate text-[0.72rem] text-muted-foreground/70",title:N,children:T}):null,s.jsx("span",{className:"flex-shrink-0 text-[0.72rem] text-muted-foreground/75",children:Kd(w.time?.archived??w.time?.updated??w.time?.created??Date.now())}),s.jsx("button",{type:"button",onClick:L=>{L.stopPropagation(),A(w)},className:"absolute right-7 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity pointer-events-none hover:text-foreground group-hover:opacity-100 group-hover:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Restore ${ps(w)}`,children:s.jsx(D,{name:"inbox-unarchive",className:"h-3.5 w-3.5"})}),s.jsx("button",{type:"button",onClick:L=>{L.stopPropagation(),Es.requestDelete({sessions:[w],mode:"session"})},className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity pointer-events-none hover:text-destructive group-hover:opacity-100 group-hover:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete ${ps(w)}`,children:s.jsx(D,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},w.id)}),C>0?s.jsx("button",{type:"button",onClick:()=>b(w=>w+Un),className:"mt-1 flex items-center justify-start rounded-md px-2 py-1 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:"Show more sessions"}):null]})})]})]})]})})]})})}const fh=e=>{if(!e||typeof e!="object")return{percent:0,hasInput:!1};const t=e.input??0,n=e.cache&&typeof e.cache=="object"?e.cache.read??0:0,r=e.cache&&typeof e.cache=="object"?e.cache.write??0:0,o=t+n+r;if(o<=0)return{percent:0,hasInput:!1};const i=Math.max(0,n);return{percent:Math.min(100,Math.max(0,i/o*100)),hasInput:!0}},hh=e=>{if(!e||typeof e!="object")return 0;const t=typeof e.input=="number"&&Number.isFinite(e.input)&&e.input>=0?e.input:0,n=typeof e.cacheRead=="number"&&Number.isFinite(e.cacheRead)&&e.cacheRead>=0?e.cacheRead:0,r=typeof e.cacheWrite=="number"&&Number.isFinite(e.cacheWrite)&&e.cacheWrite>=0?e.cacheWrite:0;return t+n+r},Qt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:0,mh=e=>{if(!e||typeof e!="object")return null;const t=Qt(e.input),n=Qt(e.output),r=Qt(e.cacheRead),o=Qt(e.cacheWrite);return{input:t,output:n,reasoning:null,cacheRead:r,cacheWrite:o,total:t+n+r+o}},yi=e=>{const t=mh(e.info.usage);if(t)return t;const n=e.info.tokens,r=n!==void 0?n:e.parts.find(f=>f.tokens!==void 0)?.tokens;if(typeof r=="number")return{input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:Qt(r)};if(!r||typeof r!="object")return{input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:0};const o=r,i=Qt(o.input),l=Qt(o.output),c=Qt(o.reasoning),u=Qt(o.cache?.read),d=Qt(o.cache?.write);return{input:i,output:l,reasoning:c,cacheRead:u,cacheWrite:d,total:i+l+c+u+d}},sl=380,Rr=8,ph=140;function gh({open:e,onClose:t,anchorRef:n,closeOnWheel:r=!1}){const o=a.useRef(null),i=a.useRef(null),[l,c]=a.useState(e),[u,d]=a.useState(!1),[f,p]=a.useState(null),{enabled:b}=ko();return a.useLayoutEffect(()=>{if(!e||!b||!l)return;const g=()=>{const y=n.current?.getBoundingClientRect(),x=i.current?.getBoundingClientRect();if(!y||!x){p(null);return}const C=y.left-x.left;p(Math.min(Math.max(C,Rr),Math.max(Rr,x.width-sl-Rr)))};g();const m=i.current;if(typeof ResizeObserver>"u"||!m)return;const h=new ResizeObserver(g);return h.observe(m),()=>h.disconnect()},[n,b,e,l]),a.useEffect(()=>{if(e){c(!0),d(!1);return}if(!l)return;d(!0);const g=window.setTimeout(()=>{c(!1),d(!1)},ph);return()=>window.clearTimeout(g)},[e,l]),a.useEffect(()=>{if(!e)return;const g=m=>{m.key==="Escape"&&t()};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[t,e]),a.useEffect(()=>{if(!e)return;const g=m=>{const h=m.target;if(!(h instanceof Node)){t();return}o.current?.contains(h)||n.current?.contains(h)||t()};return document.addEventListener("pointerdown",g,!0),r&&document.addEventListener("wheel",g,!0),()=>{document.removeEventListener("pointerdown",g,!0),r&&document.removeEventListener("wheel",g,!0)}},[n,r,t,e]),{panelRef:o,wrapperRef:i,shouldRender:l,isExiting:u,anchorLeft:f,isPopover:b&&f!==null}}const wi=(e,t)=>{if(!e||typeof e!="object")return;const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0},ir=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e),zn=({icon:e,iconNode:t,label:n,children:r})=>s.jsxs("div",{className:"flex min-w-0 items-center gap-3 rounded-xl px-2.5 py-2.5",children:[s.jsx("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:t??(e?s.jsx(D,{name:e,className:"size-[18px]"}):null)}),s.jsx("span",{className:"shrink-0 typography-ui-label text-muted-foreground",children:n}),s.jsx("span",{className:"min-w-0 flex-1 truncate text-right typography-ui-label font-medium text-foreground",children:r})]}),bh=({open:e,onClose:t,anchorRef:n,contextDisplay:r})=>{const{panelRef:o,wrapperRef:i,shouldRender:l,isExiting:c,anchorLeft:u,isPopover:d}=gh({open:e,onClose:t,anchorRef:n,closeOnWheel:!0});return l?s.jsxs("div",{ref:i,className:"fixed inset-x-0 bottom-0 top-[calc(var(--oc-safe-area-top,0px)+var(--oc-header-height,56px))] z-20 pointer-events-none",children:[s.jsx("div",{ref:o,role:"tooltip","aria-label":"Context usage for current conversation",className:K("overflow-y-auto overscroll-contain rounded-lg border border-border/70 bg-[var(--surface-elevated)] p-2 shadow-[0_8px_24px_rgb(0_0_0_/_0.18)] will-change-transform",d?"absolute origin-top-left":"mx-3 mt-2",c?"pointer-events-none":"pointer-events-auto"),style:{animation:`${c?"session-metadata-out":"session-metadata-in"} ${c?140:170}ms cubic-bezier(0.32, 0.72, 0, 1) forwards`,maxHeight:"min(72dvh, calc(100dvh - var(--oc-safe-area-top, 0px) - var(--oc-header-height, 56px) - 1rem))",...d?{top:8,left:u??8,width:`min(${sl}px, calc(100% - 16px))`}:null},children:s.jsx("div",{className:"space-y-1",children:r?s.jsxs(s.Fragment,{children:[s.jsx(zn,{iconNode:s.jsx(ma,{percentage:r.percentage}),label:"Context",children:s.jsxs("span",{className:"inline-flex items-baseline gap-1.5 tabular-nums",children:[s.jsxs("span",{className:K("font-semibold",r.colorClass),children:[r.percentage.toFixed(1),"%"]}),s.jsx("span",{className:"text-muted-foreground",children:r.tokens})]})}),r.cacheRead!==null&&r.cacheWrite!==null?s.jsxs(s.Fragment,{children:[s.jsx(zn,{icon:"stack",label:"Cache read",children:s.jsx("span",{className:"tabular-nums",children:ir(r.cacheRead)})}),s.jsx(zn,{icon:"edit",label:"Cache write",children:s.jsx("span",{className:"tabular-nums",children:ir(r.cacheWrite)})})]}):null,r.cacheHitPercent!==null?s.jsx(zn,{icon:"check",label:"Cache hit",children:s.jsxs("span",{className:"tabular-nums",children:[r.cacheHitPercent.toFixed(1),"%"]})}):null]}):s.jsx("div",{className:"px-2.5 py-2 typography-meta text-muted-foreground",children:"Context usage is not available for this conversation yet."})})}),s.jsx("style",{children:`
|
|
3
|
+
@keyframes session-metadata-in {
|
|
4
|
+
from { opacity: 0; transform: translateY(-8px) scale(0.985); }
|
|
5
|
+
to { opacity: 1; transform: translateY(0) scale(1); }
|
|
6
|
+
}
|
|
7
|
+
@keyframes session-metadata-out {
|
|
8
|
+
from { opacity: 1; transform: translateY(0) scale(1); }
|
|
9
|
+
to { opacity: 0; transform: translateY(-6px) scale(0.985); }
|
|
10
|
+
}
|
|
11
|
+
`})]}):null},xh=a.memo(function({open:t,onOpenChange:n,currentSessionId:r,effectiveDirectory:o,isNewSessionDraftOpen:i}){const l=a.useRef(null),c=Pu(r??""),u=Ut(R=>R.providers),d=Ut(R=>R.currentProviderId),f=Ut(R=>R.currentModelId),p=Ut(R=>R.getCurrentModel()),b=Ut(R=>R.getModelMetadata);Ut(R=>R.modelsMetadata.size);const g=Mu(a.useCallback(R=>r?R.sessionModelSelections.get(r)??null:null,[r])),m=a.useMemo(()=>{for(let R=c.length-1;R>=0;R-=1){const E=c[R]?.info;if(E.role!=="user")continue;const I=E.model,M=I?.providerID??I?.providerId,G=I?.modelID??I?.modelId,X=typeof M=="string"&&M.trim().length>0?M:void 0,U=typeof G=="string"&&G.trim().length>0?G:void 0;if(X&&U)return{providerID:X,modelID:U}}return null},[c]),h=a.useMemo(()=>{for(let R=c.length-1;R>=0;R-=1){const E=c[R];if(E?.info.role==="assistant"&&yi(E).total>0)return E}return null},[c]),y=m??(()=>{const R=h?.info.model,E=R?.providerID??R?.providerId,I=R?.modelID??R?.modelId;return E&&I?{providerID:E,modelID:I}:null})()??(g?{providerID:g.providerId,modelID:g.modelId}:null)??(d&&f?{providerID:d,modelID:f}:null),C=(y?u.find(R=>R.id===y.providerID):void 0)?.models.find(R=>R.id===y?.modelID),v=y?b(y.providerID,y.modelID):void 0,P=wi(C?.limit,"context")??v?.limit?.context??wi(p?.limit,"context")??0,S=h?yi(h):null,A=h?.info?.usage,j=A?hh(A):S?.total??0,w=!i&&j>0&&P>0?Math.min(j/P*100,999):null,N=w!==null?`${ir(j)}/${ir(P)}`:null,T=w===null?"":w>=90?"text-[var(--status-error)]":w>=75?"text-[var(--status-warning)]":"text-[var(--status-success)]",L=S?.cacheRead??null,$=S?.cacheWrite??null,z=S?fh({input:S.input,cache:{read:S.cacheRead,write:S.cacheWrite}}):{percent:0,hasInput:!1},W=z.hasInput?z.percent:null,F=w!==null&&N?{percentage:w,tokens:N,colorClass:T,cacheRead:L,cacheWrite:$,cacheHitPercent:W}:null;return s.jsxs(s.Fragment,{children:[s.jsx("button",{ref:l,type:"button",className:"flex size-10 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Show context usage for current conversation",title:"Context usage","aria-expanded":t,onClick:()=>n(R=>!R),style:{touchAction:"manipulation"},children:s.jsx(ma,{percentage:F?.percentage??0,size:20,className:"size-5 -rotate-90"})}),s.jsx(bh,{open:t,onClose:()=>n(!1),anchorRef:l,contextDisplay:F})]})}),sn="app-region-no-drag inline-flex h-8 w-8 items-center justify-center gap-2 rounded-md typography-ui-label font-medium text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:bg-interactive-hover transition-colors",yh="app-region-no-drag inline-flex h-9 w-9 items-center justify-center gap-2 p-2 rounded-md typography-ui-label font-medium text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:text-foreground hover:bg-interactive-hover transition-colors",wh=a.memo(function({visible:t=!0,title:n,ariaLabel:r,onClick:o,className:i,Icon:l,iconClassName:c,pressed:u=!1}){return t?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:o,"aria-label":r,"aria-pressed":u,className:K(i??sn,u&&"bg-interactive-selection text-interactive-selection-foreground"),children:s.jsx(D,{name:l,className:c??"h-[18px] w-[18px]"})})}),s.jsx(We,{children:s.jsx("p",{children:n})})]}):null}),vh=e=>{let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(36).padStart(7,"0").slice(-6)},nl=({variant:e="desktop"})=>{const t=Rs(f=>f.entries),[n,r]=a.useState(!1),o=a.useRef(null),i=a.useMemo(()=>[...t.values()].sort((f,p)=>p.startedAt-f.startedAt),[t]),l=i.filter(f=>f.state&&f.state.phase!=="failed"||pa(f)).length,c=a.useCallback(()=>{o.current&&(clearTimeout(o.current),o.current=null)},[]),u=a.useCallback(()=>{c(),o.current=setTimeout(()=>r(!1),150)},[c]);if(a.useEffect(()=>()=>c(),[c]),i.length===0)return null;const d=f=>{if(!Ou(f))return;const p=f.receipt;if(!p)return;const b=Me.getState();b.newSessionDraft.open?b.setNewSessionDraftTarget({directoryOverride:p.path,worktreeIntent:null}):b.openNewSessionDraft({directoryOverride:p.path}),Rs.getState().clearEntry(f.key),le.getState().setActiveMainTab("chat"),r(!1)};return s.jsxs(Jt,{open:n,onOpenChange:r,children:[s.jsx(Xt,{asChild:!0,children:s.jsxs("button",{type:"button",className:K(e==="desktop"?sn:"pointer-events-auto inline-flex h-10 w-full items-center justify-center gap-2 rounded-lg border border-border bg-sidebar px-3 typography-ui-label font-medium text-foreground shadow-lg hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",e==="desktop"&&"relative w-auto px-2.5"),"aria-label":"Background tasks",onPointerEnter:f=>{f.pointerType==="mouse"&&(c(),r(!0))},onPointerLeave:f=>{f.pointerType==="mouse"&&u()},children:[l>0?s.jsx(Ps,{variant:"inline",text:null,animationType:"spinner"}):s.jsx(D,{name:"task",className:"size-[18px]"}),s.jsx("span",{children:"Background tasks"})]})}),s.jsxs(Zt,{align:"end",side:e==="mobile"?"top":"bottom",className:"w-[min(26rem,calc(100vw-2rem))] max-h-[70vh] overflow-y-auto p-0",onPointerEnter:c,onPointerLeave:u,children:[s.jsxs("div",{className:"border-b border-border px-3 py-2.5",children:[s.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:"Background tasks"}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:l===1?"1 worktree is being created":`${l} worktrees are being created`})]}),s.jsx("div",{className:"divide-y divide-border",children:i.map(f=>s.jsx(Sh,{entry:f,onOpen:()=>d(f)},f.key))})]})]})},Sh=({entry:e,onOpen:t})=>{const n=e.state?.phase==="failed",r=!!(e.state&&!n),o=pa(e),i=Tu(e),l=n?e.state?.label??"Worktree creation failed":r?e.state?.label??"Creating worktree...":o?"Sending prompt...":`Worktree ready: ${e.branch??e.receipt?.branch??"new worktree"}`;return s.jsxs("div",{className:"flex items-start gap-3 px-3 py-3",children:[s.jsx("div",{className:"mt-0.5 shrink-0",children:r||o?s.jsx(Ps,{variant:"inline",text:null,animationType:"spinner"}):n?s.jsx(D,{name:"alert",className:"size-4 text-[var(--status-error)]"}):s.jsx(D,{name:"git-branch",className:"size-4 text-[var(--status-success)]"})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"truncate typography-ui-label text-foreground",children:l}),s.jsx("p",{className:"mt-0.5 truncate typography-micro text-muted-foreground",children:n?e.state?.error:e.path??e.intent.sourceDirectory})]}),n?s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[e.failedSend?s.jsx(Ee,{type:"button",size:"xs","aria-label":`Restore draft for ${e.intent.sourceDirectory} from ${e.intent.startRef} (task ${vh(e.key)})`,onClick:()=>{const c=Fu(e.key),u=Lu(c,"background-task");u&&ie.error(u.title,{description:u.description})},children:"Restore draft"}):null,s.jsx(Ee,{type:"button",variant:"ghost",size:"xs",onClick:()=>Rs.getState().dismissFailed(e.key),children:"Dismiss"})]}):null,i?s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[s.jsx(Ee,{type:"button",size:"xs",onClick:t,children:"Open"}),s.jsx(Ee,{type:"button",variant:"ghost",size:"icon",className:"size-6",onClick:()=>Rs.getState().clearEntry(e.key),"aria-label":"Dismiss completed task",children:s.jsx(D,{name:"close",className:"size-3.5"})})]}):null]})},jh=e=>{const{normalizedProjects:t,enabled:n=!0,ownership:r,hasAuthoritativeGlobalSessions:o,isWorktreeTopologyLoading:i,unresolvedWorktreeProjectPaths:l,foldersMap:c,createFolder:u,addSessionToFolder:d}=e;a.useEffect(()=>{!n||!o||i||t.forEach(f=>{if(l.has(f.normalizedPath))return;const p=Fa(f.normalizedPath),b=r.archivedSessionsByProject.get(f.id)??[],g=c[p]??[],m=new Map(g.map(h=>[h.name.toLowerCase(),h]));b.forEach(h=>{const y=Wd(h,f.normalizedPath),x=y.toLowerCase();let C=m.get(x);C||(C=u(p,y),m.set(x,C)),C.sessionIds.includes(h.id)||d(p,C.id,h.id)})})},[t,n,r,o,i,l,c,u,d])},Ch=e=>({getOrderedGroups:a.useCallback((n,r)=>{const o=e.get(n);if(!o||o.length===0)return r;const i=new Map(r.map(d=>[d.id,d])),l=[];o.forEach(d=>{const f=i.get(d);f&&(l.push(f),i.delete(d))});const c=[],u=[];return r.forEach(d=>{i.has(d.id)&&(d.isArchivedBucket?u.push(d):c.push(d))}),[...c,...l,...u]},[e])}),kh=e=>{const{normalizedProjects:t,getSessionsForProject:n,getArchivedSessionsForProject:r,availableWorktreesByProject:o,projectRepoStatus:i,projectRootBranches:l,lastRepoStatus:c,buildGroupedSessions:u,hasSessionSearchQuery:d,normalizedSessionSearchQuery:f,filterSessionNodesForSearch:p,buildGroupSearchText:b,foldersMap:g}=e,m=a.useRef(new Map),h=a.useMemo(()=>{const j=m.current,w=new Map;let N=0,T=0;const L=(z,W)=>z.length===W.length&&z.every((F,R)=>F===W[R]),$=t.map(z=>{const W=n(z.id),F=r(z.id),R=i.has(z.id)?!!i.get(z.id):c,E=l.get(z.id)??null,I=o.get(z.normalizedPath)??[],M=j.get(z.id);if(M&&M.project===z&&L(M.activeSessions,W)&&L(M.archivedSessions,F)&&M.rootBranch===E&&M.isRepo===R&&M.worktrees===I&&M.buildGroupedSessions===u)return N+=1,w.set(z.id,M),M.section;T+=1;const G=La([...W,...F]),X=u(G,z.normalizedPath,I,E,R),U={project:z,groups:X};return w.set(z.id,{project:z,activeSessions:W,archivedSessions:F,rootBranch:E,isRepo:R,worktrees:I,buildGroupedSessions:u,section:U}),U});return m.current=w,N>0&&zt("ui.sidebar.project_section.reused",N),T>0&&zt("ui.sidebar.project_section.rebuilt",T),$},[t,n,r,o,i,c,u,l]),y=a.useMemo(()=>h,[h]),x=a.useMemo(()=>{const j=new WeakMap;if(!d)return j;const w=N=>N.reduce((T,L)=>T+1+w(L.children),0);return y.forEach(N=>{N.groups.forEach(T=>{const L=p(T.sessions,f),$=w(L),z=b(T).includes(f),W=Ae(T.directory??null),R=(W?g[W]??[]:[]).filter(E=>E.name.toLowerCase().includes(f)).length;j.set(T,{filteredNodes:L,matchedSessionCount:$,folderNameMatchCount:R,groupMatches:z,hasMatch:z||$>0||R>0})})}),j},[d,y,p,f,b,g]),C=a.useMemo(()=>d?y.map(j=>({...j,groups:j.groups.filter(w=>x.get(w)?.hasMatch===!0)})).filter(j=>j.groups.length>0):y,[d,y,x]),v=d?C:y,P=a.useRef(new WeakMap),S=a.useMemo(()=>{const j=P.current;return v.map(w=>{const N=j.get(w);if(N&&N.query===f)return N.section;const T=w.groups.filter(E=>!E.isArchivedBucket),L=w.groups.filter(E=>E.isArchivedBucket),$=T.flatMap(E=>d?x.get(E)?.filteredNodes??[]:E.sessions),z=T.map(E=>({scopeKey:E.folderScopeKey??Ae(E.directory??null),directory:E.directory??null})).filter(E=>!!E.scopeKey),W=T.find(E=>E.isMain)??null,F={id:"flat",label:W?.label??"",branch:W?.branch??null,description:W?.description??null,isMain:!0,isArchivedBucket:!1,directory:W?.directory??w.project.normalizedPath,folderScopeKey:W?.folderScopeKey??w.project.normalizedPath,folderScopes:z,sessions:$};if(d){const E=T.map(I=>x.get(I)).filter(I=>!!I);x.set(F,{filteredNodes:$,matchedSessionCount:E.reduce((I,M)=>I+M.matchedSessionCount,0),folderNameMatchCount:E.reduce((I,M)=>I+M.folderNameMatchCount,0),groupMatches:E.some(I=>I.groupMatches),hasMatch:E.some(I=>I.hasMatch)})}const R={project:w.project,groups:[F,...L]};return j.set(w,{query:f,section:R}),R})},[x,d,f,v]),A=a.useMemo(()=>d?v.reduce((j,w)=>j+w.groups.reduce((N,T)=>{const L=x.get(T);if(!L)return N;const $=L.folderNameMatchCount+(L.groupMatches?1:0);return N+L.matchedSessionCount+$},0),0):0,[d,v,x]);return{projectSections:h,visibleProjectSections:y,groupSearchDataByGroup:x,searchableProjectSections:C,sectionsForRender:v,flatSectionsForRender:S,searchMatchCount:A}},Ah=e=>{const{projectSections:t,activeProjectId:n,activeSessionByProject:r,setActiveSessionByProject:o,currentSessionId:i,handleSessionSelect:l,newSessionDraftOpen:c,mobileVariant:u,openNewSessionDraft:d,setActiveMainTab:f,setSessionSwitcherOpen:p}=e,b=a.useMemo(()=>{const m=new Map,h=new Map,y=(x,C,v,P)=>{m.has(x)||m.set(x,new Map);const S=m.get(x);P.forEach(A=>{const j=Ae(A.session.directory??v??C);S.set(A.session.id,{directory:j}),h.has(x)||h.set(x,{id:A.session.id,directory:j}),A.children.length>0&&y(x,C,j,A.children)})};return t.forEach(x=>{x.groups.forEach(C=>{y(x.project.id,x.project.normalizedPath,C.directory,C.sessions)})}),{metaByProject:m,firstSessionByProject:h}},[t]),g=a.useRef(null);a.useLayoutEffect(()=>{if(!n)return;if(c){g.current=n;return}if(g.current===n)return;const m=t.find(A=>A.project.id===n);if(!m)return;g.current=n;const h=b.metaByProject.get(n);if(i&&h&&h.has(i)){o(A=>{if(A.get(n)===i)return A;const j=new Map(A);return j.set(n,i),j});return}const y=i?Array.from(b.metaByProject.entries()).some(([A,j])=>A!==n&&j.has(i)):!1;if(i&&h&&!y)return;if(!h||h.size===0){f("chat"),u&&p(!1),d({selectedProjectId:m.project.id,directoryOverride:m.project.normalizedPath});return}const x=r.get(n),C=x&&h.has(x)?x:null,v=b.firstSessionByProject.get(n)?.id??null,P=C??v;if(!P||P===i)return;const S=h.get(P)?.directory??null;l(P,S,{keepPanelOpen:!0})},[n,r,i,l,c,u,d,t,b,f,p,o]),a.useEffect(()=>{if(!n||!i)return;const m=b.metaByProject.get(n);!m||!m.has(i)||o(h=>{if(h.get(n)===i)return h;const y=new Map(h);return y.set(n,i),y})},[n,i,b,o])},Nh=({initialActiveSessionByProject:e,persistActiveSessionByProject:t,...n})=>{const r=Me(c=>c.currentSessionId),o=Me(c=>!!c.newSessionDraft?.open),[i,l]=a.useState(()=>new Map(e));return Ah({...n,activeSessionByProject:i,setActiveSessionByProject:l,currentSessionId:r,newSessionDraftOpen:o}),a.useEffect(()=>{t(i)},[i,t]),null},vi=["var(--chart-1)","var(--chart-2)","var(--chart-3)","var(--chart-4)","var(--chart-5)"],Ih=e=>{let t=5381;for(let n=0;n<e.length;n+=1)t=t*33^e.charCodeAt(n);return t>>>0},Eh=(e,t,n)=>(n.get(e)??0)>0?e:t.get(e)??null,rl=e=>{if(!e||typeof e!="string"||e.trim().length===0)return null;const t=Ih(e.trim())%vi.length;return vi[t]},Rh=(e,t)=>{const n=rl(e);return n?t?.active?`color-mix(in srgb, ${n} 30%, var(--interactive-selection))`:`color-mix(in srgb, ${n} 18%, transparent)`:null},Si=e=>!!e.time?.archived,Dh=e=>{const t=a.useCallback(i=>[i.label,i.branch??"",i.description??"",i.directory??""].join(" ").toLowerCase(),[]),n=a.useCallback(i=>{const l=Ae(i.directory??null)??"";return`${ps(i)} ${l}`.toLowerCase()},[]),r=a.useCallback((i,l)=>l?i.flatMap(c=>{if(n(c.session).includes(l))return[c];const d=r(c.children,l);return d.length===0?[]:[{...c,children:d}]}):i,[n]),o=a.useCallback((i,l,c=[],u,d)=>{const f=Ae(l??null),p=La(i).sort(ga(e.pinnedSessionIds,e.sessionOrderRanks)),b=new Map(p.map(j=>[j.id,j])),g=new Map,m=new Map;p.forEach(j=>{const w=j.parentID??null,N=w?b.get(w):null,T=N&&Si(N)===Si(j)?w:null;g.set(j.id,T),T&&m.set(T,(m.get(T)??0)+1)});const h=c.map(j=>({worktree:j,directory:Ae(j.path)})).filter(j=>!!j.directory&&!j.worktree.isPrimary).sort((j,w)=>w.directory.length-j.directory.length),y=(j,w)=>w===j||w.startsWith(`${j}/`),x=j=>{const w=Ae(j.directory??null);return w?h.find(N=>y(N.directory,w))?.worktree??null:null},C=(j,w)=>{const N=Eh(j.id,g,m);return{session:j,children:[],worktree:w,forkColorId:N}},v=[],P=new Map,S=[];for(const j of h)P.set(j.directory,[]);p.forEach(j=>{const w=x(j),N=C(j,w);j.time?.archived?S.push(N):w?P.get(Ae(w.path)??"")?.push(N):v.push(N)});const A=[{id:"root",label:d&&u&&u!=="HEAD"?`project root: ${u}`:"project root",branch:u??null,description:f?ai(f,e.homeDirectory):null,isMain:!0,isArchivedBucket:!1,worktree:null,directory:f,folderScopeKey:f,sessions:v}];for(const{worktree:j,directory:w}of h)A.push({id:`worktree:${w}`,label:j.branch||(j.detached?"Detached HEAD":j.name),branch:j.branch,description:ai(w,e.homeDirectory),isMain:!1,isArchivedBucket:!1,worktree:j,directory:w,folderScopeKey:w,sessions:P.get(w)??[]});return S.length>0&&A.push({id:"archived",label:"archived",branch:null,description:"Archived and unassigned sessions",isMain:!1,isArchivedBucket:!0,worktree:null,directory:null,folderScopeKey:f?Fa(f):null,sessions:S}),A},[e.homeDirectory,e.pinnedSessionIds,e.sessionOrderRanks]);return{buildGroupSearchText:t,buildSessionSearchText:n,filterSessionNodesForSearch:r,buildGroupedSessions:o}},Ph=({mobileVariant:e,isTablet:t})=>!e&&!t,Mh=({enabled:e=!0,isSessionSearchOpen:t,setIsSessionSearchOpen:n,sessionSearchInputRef:r,sessionSearchContainerRef:o})=>{a.useEffect(()=>{if(!e||!t||typeof window>"u")return;const i=window.requestAnimationFrame(()=>{r.current?.focus(),r.current?.select()});return()=>window.cancelAnimationFrame(i)},[e,t,r]),a.useEffect(()=>{if(!e||!t||typeof document>"u")return;const i=l=>{o.current&&(o.current.contains(l.target)||n(!1))};return document.addEventListener("mousedown",i),()=>document.removeEventListener("mousedown",i)},[e,t,n,o])},Th=e=>{const[t,n]=a.useState(null),r=a.useRef(null);a.useEffect(()=>()=>{r.current&&clearTimeout(r.current)},[]);const o=a.useCallback((v,P,S)=>{Zr("navigation.session_select"),le.getState().closeMainSurfaces();const A=()=>{!e.isSessionSearchOpen&&e.sessionSearchQuery.length===0||(e.setSessionSearchQuery(""),e.setIsSessionSearchOpen(!1))},j=S?.keepPanelOpen!==!0;if(e.mobileVariant&&(e.setActiveMainTab("chat"),e.setSessionSwitcherOpen(!1)),v===Me.getState().currentSessionId){e.allowReselect&&j&&e.onSessionSelected?.(v),A();return}Zr("navigation.session_state_set"),e.setCurrentSession(v,P??null),j&&e.onSessionSelected?.(v),A()},[e]),i=a.useCallback((v,P)=>{e.setEditingId(v),e.setEditTitle(P)},[e]),l=a.useCallback(async v=>{if(!e.editingId)return;const P=(v??e.editTitle).trim();P&&await e.updateSessionTitle(e.editingId,P),e.setEditingId(null),e.setEditTitle("")},[e]),c=a.useCallback(()=>{e.setEditingId(null),e.setEditTitle("")},[e]),u=a.useCallback(async(v,P)=>{try{return(await bs(v)).ok?(n(P),r.current&&clearTimeout(r.current),r.current=window.setTimeout(()=>{n(null),r.current=null},2e3),!0):!1}catch{return!1}},[]),d=a.useCallback(async v=>{const P=await e.shareSession(v.id);if(!P?.share?.url){ie.error("Unable to share session");return}const S=await u(P.share.url,v.id);ie[S?"success":"warning"]("Session shared",{description:S?"Share link copied to clipboard.":"Failed to copy URL"})},[e,u]),f=a.useCallback((v,P)=>{u(v,P).then(S=>{S||ie.error("Failed to copy URL")})},[u]),p=a.useCallback(v=>{bs(v).then(P=>{if(P.ok){ie.success("Session ID copied");return}ie.error("Failed to copy session ID")}).catch(()=>ie.error("Failed to copy session ID"))},[]),b=a.useCallback(async v=>{await e.unshareSession(v)?ie.success("Session unshared"):ie.error("Unable to unshare session")},[e]),g=a.useCallback(v=>{const P=[],S=A=>{(e.childrenMap.get(A)??[]).forEach(w=>{P.push(w),S(w.id)})};return S(v),P},[e.childrenMap]),m=a.useCallback((v,P)=>P?v:v.filter(S=>!S.time?.archived),[]),h=a.useCallback(async(v,P,S)=>{const A=P?.archivedBucket===!0||P?.hardDelete===!0,j=S?.descendantIds??m(g(v.id),A).map(L=>L.id);if(j.length===0){(A?await e.deleteSession(v.id):await e.archiveSession(v.id))?ie.success(A?"Session deleted":"Session archived"):ie.error(A?"Failed to delete session":"Failed to archive session");return}const w=[v.id,...j];if(A){const{deletedIds:L,failedIds:$}=await e.deleteSessions(w);if($.length===0){const z=L.length;ie.success(z===1?`Deleted ${z} session`:`Deleted ${z} sessions`)}else ie.error("Failed to delete session");return}const{archivedIds:N,failedIds:T}=await e.archiveSessions(w);N.length>0&&ie.success(N.length===1?`Archived ${N.length} session`:`Archived ${N.length} sessions`),T.length>0&&ie.error(T.length===1?`Failed to archive ${T.length} session`:`Failed to archive ${T.length} sessions`)},[e,g,m]),y=a.useCallback((v,P)=>{const S=P?.archivedBucket===!0||P?.hardDelete===!0,A=m(g(v.id),S).map(j=>j.id);if(!e.showDeletionDialog||P?.skipConfirm===!0){h(v,P,{descendantIds:A});return}e.setDeleteSessionConfirm({session:v,descendantCount:A.length,descendantIds:A,archivedBucket:S})},[e,g,h,m]),x=a.useCallback(async()=>{if(!e.deleteSessionConfirm)return;const{session:v,archivedBucket:P,descendantIds:S}=e.deleteSessionConfirm;e.setDeleteSessionConfirm(null),await h(v,{archivedBucket:P},{descendantIds:S})},[e,h]),C=a.useCallback(async v=>{await e.unarchiveSession(v.id)?ie.success("Session restored"):ie.error("Failed to restore session")},[e]);return{copiedSessionId:t,handleSessionSelect:o,handleSessionDoubleClick:i,handleSaveEdit:l,handleCancelEdit:c,handleShareSession:d,handleCopyShareUrl:f,handleCopySessionId:p,handleUnshareSession:b,handleDeleteSession:y,handleRestoreSession:C,confirmDeleteSession:x}},Fh=e=>{const{safeStorage:t,keys:n,groupOrderByProject:r,collapsedGroups:o,setExpandedParents:i,setCollapsedProjects:l}=e,c=a.useRef(null),u=a.useRef(null),d=a.useCallback(()=>{const p=u.current;if(u.current=null,c.current=null,!p)return;const{projects:b}=ht.getState(),g=b.map(m=>({...m,sidebarCollapsed:p.has(m.id)}));Ea({projects:g}).catch(()=>{})},[]),f=a.useCallback(p=>{typeof window>"u"||(u.current=p,c.current!==null&&window.clearTimeout(c.current),c.current=window.setTimeout(()=>{d()},700))},[d]);return a.useEffect(()=>()=>{typeof window<"u"&&c.current!==null&&window.clearTimeout(c.current),c.current=null,u.current=null},[]),a.useEffect(()=>{try{const p=t.getItem(n.sessionExpanded);if(p){const g=JSON.parse(p);Array.isArray(g)&&i(new Set(g.filter(m=>typeof m=="string")))}const b=t.getItem(n.projectCollapse);if(b){const g=JSON.parse(b);Array.isArray(g)&&l(new Set(g.filter(m=>typeof m=="string")))}}catch{}},[n.projectCollapse,n.sessionExpanded,t,l,i]),a.useEffect(()=>{try{const p=Object.fromEntries(r.entries());t.setItem(n.groupOrder,JSON.stringify(p))}catch{}},[r,n.groupOrder,t]),a.useEffect(()=>{try{t.setItem(n.groupCollapse,JSON.stringify(Array.from(o)))}catch{}},[o,n.groupCollapse,t]),{scheduleCollapsedProjectsPersist:f}},Lh=3;let ar=0;const ol=[],Oh=()=>ar<Lh?(ar+=1,Promise.resolve()):new Promise(e=>{ol.push(e)}),Bh=()=>{const e=ol.shift();if(e){e();return}ar=Math.max(0,ar-1)},_h=async e=>{await Oh();try{return await e()}finally{Bh()}},Uh=5*6e4,zh=e=>{const{normalizedProjects:t,enabled:n=!0,gitRepoStatus:r,setProjectRepoStatus:o,setProjectRootBranches:i}=e,{git:l}=Ms(),c=ba(m=>m.ensureStatus),u=a.useMemo(()=>t.map(m=>m.normalizedPath).slice().sort().join("\0"),[t]),d=a.useRef(null);a.useEffect(()=>{if(!n||!l||t.length===0){d.current=null,o(new Map);return}const m=`${Dt()}\0${u}`;d.current!==m&&(d.current=m,t.forEach(h=>{_h(()=>c(h.normalizedPath,l))}))},[n,t,u,l,c,o]);const f=a.useRef(null);a.useEffect(()=>{if(!n){f.current=null;return}const m=new Map;t.forEach(y=>{m.set(y.id,r.get(y.normalizedPath)?.isGitRepo??null)});const h=t.map(y=>`${y.id}:${String(m.get(y.id))}`).join("|");f.current!==h&&(f.current=h,o(m))},[n,t,u,r,o]);const p=a.useMemo(()=>t.map(m=>{const h=r.get(m.normalizedPath)?.branch??"";return`${m.id}:${h}`}).join("|"),[t,r]),b=a.useRef(new Map),g=a.useRef(new Map);a.useEffect(()=>{if(!n)return;let m=!1;const h=setTimeout(()=>{(async()=>{const x=new Set(t.map(A=>A.id));for(const A of b.current.keys())x.has(A)||(b.current.delete(A),g.current.delete(A));const C=Date.now();if(t.filter(A=>{const j=r.get(A.normalizedPath);if(j?.isGitRepo===!1)return b.current.delete(A.id),g.current.delete(A.id),!1;if(j?.isGitRepo!==!0||j.branch===null)return!1;const w=j.branch.trim(),N=`${A.normalizedPath}\0${w}`,T=b.current.get(A.id);if(T===N){const L=g.current.get(A.id);return L&&(L.at=C),!1}return!(T!==void 0&&C-(g.current.get(A.id)?.at??0)<Uh)}).length===0)return;const P=[];if(t.forEach(A=>{const j=r.get(A.normalizedPath)?.branch?.trim()??"",w=`${A.normalizedPath}\0${j}`;j&&P.push({id:A.id,inputKey:w,branch:j})}),m||P.length===0)return;const S=Date.now();i(A=>{const j=new Map(A);return P.forEach(({id:w,branch:N})=>{N&&j.set(w,N)}),j}),P.forEach(({id:A,inputKey:j,branch:w})=>{b.current.set(A,j),w&&g.current.set(A,{branch:w,at:S})})})()},150);return()=>{m=!0,clearTimeout(h)}},[n,t,p,r,i])},$h=e=>{const{ownership:t}=e,n=a.useCallback(o=>t.sessionsByProject.get(o)??[],[t]),r=a.useCallback(o=>t.archivedSessionsByProject.get(o)??[],[t]);return{getSessionsForProject:n,getArchivedSessionsForProject:r}},Kh=e=>{const t=new Map;for(const n of e){const r=wn(n);r&&t.set(n.id,{directory:r,sessionId:n.id})}return t},Wh=(e,t)=>{if(!e)return[];const n=[];return e.forEach((r,o)=>{t.has(o)||n.push(r)}),n},Gh=e=>{const{enabled:t=!0,hasAuthoritativeGlobalSessions:n,sessions:r}=e,o=a.useRef(null);a.useEffect(()=>{if(!t||!n)return;const i=Dt(),l=Kh(r),c=o.current?.runtimeKey===i?o.current.identities:null;for(const u of Wh(c,l))$s().commitMissedDeletion(u.sessionId,u.directory);o.current={runtimeKey:i,identities:l}},[t,n,r])},Hh=(e,t)=>e?t.kind!==e.kind?t.kind==="project":t.projectRoot.length!==e.projectRoot.length?t.projectRoot.length>e.projectRoot.length:t.projectId.localeCompare(e.projectId)<0:!0,ji=(e,t,n)=>{Hh(e.get(t),n)&&e.set(t,n)},il=e=>{const t=e;return Ae(t.directory)??Ae(t.project?.worktree)},qh=(e,t,n)=>{if(e.time?.archived)return!0;const r=il(e);if(!r)return n?.allowUnknownDirectory??!0;if(mr(r,n?.homeDirectory))return!0;if(t.size===0)return n?.allowEmptyDirectorySet??!0;const o=r.toLowerCase();for(const i of t)if(Ae(i)?.toLowerCase()===o)return!0;return!1},Yh=e=>{if(e==="/"||/^[A-Z]:$/.test(e))return null;const t=e.lastIndexOf("/");return t<0?null:t===0?"/":t===2&&/^[A-Z]:\//.test(e)?e.slice(0,2):e.slice(0,t)},Qh=(e,t,n,r=[])=>{const o=new Map,i=new Map;for(const g of t){const m=Ae(g.normalizedPath);if(!m)continue;const h=i.get(m);(!h||g.id.localeCompare(h.id)<0)&&i.set(m,g),ji(o,m,{projectId:g.id,projectRoot:m,scopeDirectory:m,kind:"project"})}if(n)for(const[g,m]of n){const h=Ae(g),y=h?i.get(h):void 0;if(!(!y||!h))for(const x of m||[]){const C=Ae(x?.path);C&&ji(o,C,{projectId:y.id,projectRoot:h,scopeDirectory:C,kind:"worktree"})}}const l=new Map,c=new Map,u=new Map,d=new Map,f=new Map,p=g=>{if(!g)return null;if(l.has(g))return l.get(g)??null;const m=[];let h=g,y=null;for(;h;){if(l.has(h)){y=l.get(h)??null;break}if(m.push(h),y=o.get(h)??null,y)break;h=Yh(h)}for(const x of m)l.set(x,y);return y},b=(g,m,h)=>{for(const y of g){const x=il(y);if(mr(x))continue;const C=p(x);if(!C)continue;c.set(y.id,C);const v=m.get(C.projectId);if(v?v.push(y):m.set(C.projectId,[y]),!h)continue;const P=h.get(C.scopeDirectory);P?P.add(y.id):h.set(C.scopeDirectory,new Set([y.id]))}};return b(e,u,f),b(r,d),{bySessionId:c,sessionsByProject:u,archivedSessionsByProject:d,sessionsByScope:f,directoryResolutions:l.size}};function al({state:e,activeLabel:t,unreadLabel:n,className:r}){return e==="unread"?s.jsx("span",{className:K("inline-flex items-center",r),"aria-label":n??t,title:n??t,children:s.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-foreground"})}):s.jsx("span",{className:K("inline-flex items-center",r),"aria-label":t,title:t,children:s.jsx(Ps,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})})}const Vh=({folder:e,displayName:t,sessions:n,subFolderItems:r,isCollapsed:o,collapsedActivityState:i=null,onToggle:l,onRename:c,onDelete:u,renderSessionNode:d,getRenderExtras:f,groupDirectory:p,projectId:b,mobileVariant:g=!1,alwaysShowActions:m=g,isRenaming:h=!1,renameDraft:y="",onRenameDraftChange:x,onRenameSave:C,onRenameCancel:v,droppableRef:P,isDropTarget:S=!1,onNewSession:A,depth:j=0,hideActions:w=!1,archivedBucket:N=!1})=>{const[T,L]=a.useState(!1),[$,z]=a.useState(""),W=a.useRef(null),F=h||T,R=h?y:$,E=a.useCallback(()=>{z(e.name),L(!0)},[e.name]),I=a.useCallback(()=>{const U=R.trim();U&&U!==e.name&&c(U),h&&C&&C(),L(!1),z("")},[R,e.name,h,c,C]),M=a.useCallback(()=>{h&&v&&v(),L(!1),z("")},[h,v]),G=a.useCallback(U=>{h&&x?x(U):z(U)},[h,x]);a.useEffect(()=>{if(!h)return;const U=()=>{const Re=W.current;Re&&(Re.focus(),Re.select())},ve=requestAnimationFrame(U),Z=window.setTimeout(U,0);return()=>{cancelAnimationFrame(ve),window.clearTimeout(Z)}},[h]);const X=o?"folder":"folder-open";return s.jsxs("div",{className:"oc-folder",children:[s.jsxs("div",{ref:P,className:K("group/folder relative flex items-center justify-between gap-2 px-3 py-1.5 min-w-0 rounded-lg transition-colors","cursor-pointer hover:bg-interactive-hover",S&&"bg-primary/10 ring-1 ring-inset ring-primary/30"),onClick:F?void 0:U=>{U.currentTarget.blur(),l()},role:F?void 0:"button",tabIndex:F?void 0:0,onKeyDown:F?void 0:U=>{(U.key==="Enter"||U.key===" ")&&(U.preventDefault(),l())},"aria-label":o?`Expand folder ${e.name}`:`Collapse folder ${e.name}`,children:[s.jsxs("div",{className:K("min-w-0 flex items-center gap-1.5 flex-1 transition-[padding]",N?m?"pr-7":"group-hover/folder:pr-7 group-focus-within/folder:pr-7":m?"pr-20":"group-hover/folder:pr-20 group-focus-within/folder:pr-20"),children:[s.jsx(D,{name:X,className:K(Qn,S?"text-primary":"text-muted-foreground")}),F?s.jsxs("form",{className:"flex min-w-0 flex-1 items-center gap-1",onPointerDown:U=>U.stopPropagation(),onMouseDown:U=>U.stopPropagation(),onSubmit:U=>{U.preventDefault(),I()},children:[s.jsx("input",{ref:W,value:R,onChange:U=>G(U.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:"Folder name",onClick:U=>U.stopPropagation(),onPointerDown:U=>U.stopPropagation(),onMouseDown:U=>U.stopPropagation(),onKeyDown:U=>{if(U.key==="Escape"){U.stopPropagation(),M();return}(U.key===" "||U.key==="Enter")&&U.stopPropagation()}}),s.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",onClick:U=>U.stopPropagation(),onPointerDown:U=>U.stopPropagation(),onMouseDown:U=>U.stopPropagation(),children:s.jsx(D,{name:"check",className:"size-4"})}),s.jsx("button",{type:"button",onClick:U=>{U.stopPropagation(),M()},onPointerDown:U=>U.stopPropagation(),onMouseDown:U=>U.stopPropagation(),className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(D,{name:"close",className:"size-4"})})]}):s.jsxs("div",{className:"min-w-0 flex items-center gap-1.5 flex-1",children:[s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("span",{className:K(Oa,S?"text-primary":"text-muted-foreground"),children:t??e.name})}),s.jsx(We,{side:"right",sideOffset:8,className:"max-w-xs",children:t??e.name})]}),s.jsxs("span",{className:"typography-micro text-muted-foreground/70 flex-shrink-0",children:["• ",n.length]}),i?s.jsx(al,{state:i,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,o?s.jsx(D,{name:"arrow-right-s",className:K(Qn,"text-muted-foreground")}):s.jsx(D,{name:"arrow-down-s",className:K(Qn,"text-muted-foreground")})]})]}),!F&&(!w||N)?s.jsx("div",{className:K("absolute right-0.5 top-1/2 z-10 flex -translate-y-1/2 items-center gap-0.5 transition-opacity",m?"opacity-100":"opacity-0 pointer-events-none group-hover/folder:opacity-100 group-hover/folder:pointer-events-auto group-focus-within/folder:opacity-100 group-focus-within/folder:pointer-events-auto"),children:s.jsxs("div",{className:"flex items-center gap-0.5",children:[!N&&A?s.jsx("button",{type:"button",onClick:U=>{U.stopPropagation(),A()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`New session in ${e.name}`,title:"New session",children:s.jsx(D,{name:"add",className:"size-4"})}):null,N?null:s.jsx("button",{type:"button",onClick:U=>{U.stopPropagation(),E()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Rename folder ${e.name}`,children:s.jsx(D,{name:"pencil-ai",className:"size-4"})}),s.jsx("button",{type:"button",onClick:U=>{U.stopPropagation(),u()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":N?`Delete archived sessions in folder ${e.name}`:`Delete folder ${e.name}`,children:s.jsx(D,{name:"delete-bin",className:"size-4"})})]})}):null]}),o?null:s.jsxs("div",{className:"pb-1",children:[r,n.length>0?n.map(U=>s.jsx(a.Fragment,{children:d(U,0,p??null,b??null,N,void 0,"project",f?.(U))},U.session.id)):r?null:s.jsx("div",{className:"py-1 px-3 text-left typography-micro text-muted-foreground/70",children:"Empty folder"})]})]})},Jh=a.memo(Vh),Xh=({sessionId:e,sessionDirectory:t,sessionTitle:n,children:r})=>{const{attributes:o,listeners:i,setNodeRef:l,isDragging:c}=lu({id:`session-drag:${e}`,data:{type:"session",sessionId:e,sessionDirectory:t,sessionTitle:n}}),u=a.useCallback(d=>{d.stopPropagation(),i?.onPointerDown&&i.onPointerDown(d)},[i]);return s.jsx("div",{ref:l,...o,onPointerDown:u,className:c?"opacity-30":void 0,children:r})},Zh=({folderId:e,children:t})=>{const{setNodeRef:n,isOver:r}=cu({id:`folder-drop:${e}`,data:{type:"folder",folderId:e}});return s.jsx(s.Fragment,{children:t(n,r)})},em=({scopeKey:e,hasFolders:t,onSessionDroppedOnFolder:n,children:r})=>{const o=sa(qr(iu,{activationConstraint:{distance:8}})),[i,l]=a.useState(null),[c,u]=a.useState("Session"),[d,f]=a.useState(null),[p,b]=a.useState(null);if(!e)return s.jsx(s.Fragment,{children:r});const g=m=>{l(null),f(null),b(null);const{active:h,over:y}=m;if(!y)return;const x=h.data.current,C=y.data.current;x?.type==="session"&&x.sessionId&&C?.type==="folder"&&C.folderId&&n(x.sessionId,C.folderId)};return s.jsxs(na,{sensors:o,collisionDetection:ra,onDragStart:m=>{const h=m.active.data.current;if(h?.type==="session"&&h.sessionId){l(h.sessionId),u(h.sessionTitle??"Session");const y=m.active.rect.current.initial?.width,x=m.active.rect.current.initial?.height;f(typeof y=="number"?y:null),b(typeof x=="number"?x:null)}},onDragCancel:()=>{l(null),f(null),b(null)},onDragEnd:g,children:[r,s.jsx(au,{children:i&&t?s.jsxs("div",{style:{width:d?`${d}px`:"auto",height:p?`${p}px`:"auto"},className:"flex items-center rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-3 py-1 shadow-none pointer-events-none",children:[s.jsx(D,{name:"sticky-note",className:"h-4 w-4 text-muted-foreground mr-2 flex-shrink-0"}),s.jsx("div",{className:"min-w-0 flex-1 truncate typography-ui-label font-normal text-foreground",children:c})]}):null})]})},Ns=({icon:e,children:t,onClick:n,className:r,mobileVariant:o=!1})=>s.jsxs("button",{type:"button",onClick:n,className:K(o?Gd:Hd,r),children:[s.jsx(D,{name:e,className:K(An(o),"text-muted-foreground")}),s.jsx("span",{className:K(Nn(o),"flex-1 text-muted-foreground"),children:t})]}),Ci=(e,t,n)=>{if(!t)return;const r=o=>{let i=o.session.id===t;for(const l of o.children)i=r(l)||i;return i&&n.add(o.session.id),i};for(const o of e)r(o)},os=(e,t)=>{if(!t)return!1;if(e.session.id===t)return!0;for(const n of e.children)if(os(n,t))return!0;return!1},tm=(e,t)=>{const n=new Set(e);return e.map(r=>t.get(r)).filter(r=>{if(!r)return!1;const o=new Set;let i=r.session.parentID??null;for(;i&&!o.has(i);){if(n.has(i)&&t.has(i))return!1;o.add(i),i=t.get(i)?.session?.parentID??null}return!0})},ki=new WeakMap;let Ai=1;const sm=e=>{const t=ki.get(e);if(t!==void 0)return t;const n=Ai;return Ai+=1,ki.set(e,n),n},ho=e=>e.children.length===0?"":e.children.map(n=>{const r=sm(n.session);return n.children.length===0?`${n.session.id}@${r}`:`${n.session.id}@${r}:${ho(n)}`}).join("|"),ll=(e,t,n,r,o,i)=>{const l=Dt(),c=(u,d)=>{if(u.session.id!==d.session.id||u.children.length!==d.children.length)return!0;const f=u.session.directory??o,p=d.session.directory??i,b=ri(l,f??"",u.session.id),g=ri(l,p??"",d.session.id);return(b?n.has(b):!1)!==(g?r.has(g):!1)?!0:u.children.some((m,h)=>c(m,d.children[h]))};return c(e,t)},lr=(e,t,n,r)=>{if(!t)return null;const o=r?"archived":"active";let i=null;const l=c=>{if(`${n}:${o}:${c.session.id}`===t)return i=c.session.id,!0;for(const d of c.children)if(l(d))return!0;return!1};return e.forEach(c=>l(c)),i},nm=5*6e4,rm=6e4,Ni=5*6e4,Ii=100,fn=new Map,Ks=new Map,Is=new Map,qs=new Map,En=(e,t)=>{const n=is((e??"").trim()),r=(t??"").trim();return!n||!r?"":`${Dt()}
|
|
12
|
+
${n}
|
|
13
|
+
${r}`},Ei=()=>({pr:null,checks:null,fetchedAt:null,isLoading:!1,stale:!1,error:null}),om=e=>{const t=e?.body;return t&&typeof t.kind=="string"?t:{kind:"failed",message:e instanceof Error?e.message:"PR status check failed"}},im=e=>{const t=Object.keys(e);if(t.length<=Ii)return e;const n=t.sort((o,i)=>(qs.get(o)??0)-(qs.get(i)??0)),r={...e};for(let o=0;o<n.length-Ii;o+=1){const i=n[o];delete r[i],qs.delete(i),Ks.delete(i);const l=Is.get(i);l!==void 0&&(clearTimeout(l),Is.delete(i))}return r},cl=e=>e.pr?e.pr.state!=="open"?Ni:e.checks?.state==="pending"?rm:Ni:nm,mo=(e,t,n,r)=>{if(typeof window>"u"||Is.has(e))return;const o=Vt.getState().results[e];if(!o)return;const i=cl(o),l=setTimeout(()=>{if(Is.delete(e),!!Vt.getState().results[e]){if(typeof document<"u"&&document.hidden){mo(e,t,n,r);return}Vt.getState().refresh(t,n,r)}},i);typeof l=="object"&&l!==null&&typeof l.unref=="function"&&l.unref(),Is.set(e,l)},Vt=Ts()(gr((e,t)=>({results:{},refresh:async(n,r,o,i)=>{const l=is((n||"").trim()),c=(r||"").trim();if(!l||!c)return null;const u=En(l,c);if(!u)return null;const d=fn.get(u);if(d&&!i?.force)return d;const f=o??null;if(!f)return t().results[u]??null;const p=(Ks.get(u)??0)+1;Ks.set(u,p);const b=t().results[u]??Ei();e(m=>({results:{...m.results,[u]:{...b,isLoading:!0}}}));const g=(async()=>{try{const m=await f.prStatus(l,c);if(Ks.get(u)!==p||Dt()!==u.split(`
|
|
14
|
+
`)[0])return t().results[u]??null;const h={pr:m.pr??null,checks:m.checks??null,checksStale:m.checksStale,defaultBranch:m.defaultBranch??null,skippedDefaultBranch:m.skippedDefaultBranch,fetchedAt:m.fetchedAt??Date.now(),isLoading:!1,stale:!1,error:null};return qs.set(u,Date.now()),e(y=>({results:im({...y.results,[u]:h})})),mo(u,l,c,f),h}catch(m){if(Ks.get(u)!==p)return t().results[u]??null;const h=om(m),y=b.pr||b.fetchedAt?{...b,isLoading:!1,stale:!0,error:h}:{...Ei(),error:h};return e(x=>({results:{...x.results,[u]:y}})),mo(u,l,c,f),y}})();fn.set(u,g);try{return await g}finally{fn.get(u)===g&&fn.delete(u)}},load:async(n,r,o)=>{const i=is((n||"").trim()),l=(r||"").trim();if(!i||!l)return null;const c=En(i,l);qs.set(c,Date.now());const u=t().results[c];return u&&(u.pr||u.fetchedAt)?(t().refresh(i,l,o),u):t().refresh(i,l,o)},resetForRuntimeSwitch:()=>{fn.clear(),Ks.clear(),qs.clear(),pn=null;for(const n of Is.values())clearTimeout(n);Is.clear(),e({results:{}})}}),{name:"github-pr-status-store"}));typeof window<"u"&&(Rn(()=>{Vt.getState().resetForRuntimeSwitch()}),document.addEventListener("visibilitychange",()=>{document.hidden||(async()=>{const e=await dt(async()=>{const{getRegisteredRuntimeAPIs:r}=await import("./index-6IO1AcJI.js").then(o=>o.cv);return{getRegisteredRuntimeAPIs:r}},__vite__mapDeps([2,3,4,5,6,7,8])).then(({getRegisteredRuntimeAPIs:r})=>r()?.github??null).catch(()=>null);if(!e)return;const t=Date.now(),n=Object.entries(Vt.getState().results).filter(([,r])=>r.fetchedAt&&t-r.fetchedAt>=cl(r)).map(([r])=>r);for(const r of n){const[,o,i]=r.split(`
|
|
15
|
+
`);if(!(!o||!i)){if(typeof document<"u"&&document.hidden)return;await Vt.getState().refresh(o,i,e).catch(()=>null)}}})()}));let pn=null;const ox=e=>{if(pn&&pn.results===e)return pn.index;const t=new Map;for(const n of Object.values(e)){const r=n.pr?.url;!r||t.has(r)||t.set(r,n.checks?.state??null)}return pn={results:e,index:t},t},am=e=>{const t=e?.pr;if(!t)return null;if(t.state==="merged")return{visualState:"merged",number:t.number,draft:t.draft,title:t.title};if(t.state==="closed")return{visualState:"closed",number:t.number,draft:t.draft,title:t.title};if(t.draft)return{visualState:"draft",number:t.number,draft:!0,title:t.title,mergeableState:t.mergeableState??void 0,checks:e?.checks?{state:e.checks.state}:void 0};const n=e?.checks?.state,r=t.mergeableState??void 0;return r==="dirty"||r==="blocked"||n==="failure"?{visualState:"blocked",number:t.number,draft:!1,title:t.title,mergeableState:r,checks:e?.checks?{state:e.checks.state,total:e.checks.total,failure:e.checks.failure,pending:e.checks.pending,success:e.checks.success}:void 0}:{visualState:"open",number:t.number,draft:!1,title:t.title,mergeableState:r,checks:e?.checks?{state:e.checks.state,total:e.checks.total,failure:e.checks.failure,pending:e.checks.pending,success:e.checks.success}:void 0}},ul=e=>{const t=Vt(n=>e?n.results[e]??null:null);return a.useMemo(()=>am(t),[t])},dl=(e,t,n)=>{const r=a.useMemo(()=>En(e,t),[e,t]),o=n??null;a.useEffect(()=>{if(!r||!e?.trim()||!t?.trim())return;let i=!1;return dt(async()=>{const{getRegisteredRuntimeAPIs:l}=await import("./index-6IO1AcJI.js").then(c=>c.cv);return{getRegisteredRuntimeAPIs:l}},__vite__mapDeps([2,3,4,5,6,7,8])).then(({getRegisteredRuntimeAPIs:l})=>{if(i)return;const c=o??l()?.github??null;c&&Vt.getState().load(e,t,c)}).catch(()=>{}),()=>{i=!0}},[r,e,t,o])},Eo=(e,t)=>e==="active"||t==="active"?"active":e==="unread"||t==="unread"?"unread":null,fl=(e,t,n)=>{if(t.has(e.session.id))return"active";let r=n.has(e.session.id)?"unread":null;for(const o of e.children)if(r=Eo(r,fl(o,t,n)),r==="active")return r;return r},hl=(e,t,n)=>{let r=null;for(const o of e)if(r=Eo(r,fl(o,t,n)),r==="active")return r;return r},lm=50,cm=28;function um({visibleSessions:e,shouldVirtualize:t,hasExpandedParent:n,scrollContainerRef:r,groupDirectory:o,projectId:i,isArchivedBucket:l,renderSessionNode:c,getRenderExtras:u}){const d=a.useRef(null),[f,p]=a.useState(null),[b,g]=a.useState(0),[,m]=a.useState(0);a.useEffect(()=>{if(!t)return;const x=d.current;if(!x||typeof ResizeObserver>"u")return;const C=new ResizeObserver(()=>m(v=>v+1));return C.observe(x),()=>C.disconnect()},[t]),a.useLayoutEffect(()=>{if(!t){f!==null&&p(null),b!==0&&g(0);return}const x=d.current;if(!x)return;let C=f;const v=r?.current??null;if(v&&v.contains(x)){if(C=v,C!==f){p(C);return}}else if(!C||!C.contains(x)){let S=x.parentElement;for(;S;){const A=window.getComputedStyle(S);if(A.overflowY==="auto"||A.overflowY==="scroll"){C=S;break}S=S.parentElement}if(C!==f){p(C);return}}if(!C)return;const P=x.getBoundingClientRect().top-C.getBoundingClientRect().top+C.scrollTop;g(S=>Math.abs(S-P)<1?S:P)},[f,b,r,t]);const h=t&&f!==null,y=uu({count:e.length,enabled:h,getScrollElement:()=>f,initialOffset:()=>f?.scrollTop??0,estimateSize:()=>cm,overscan:n?20:8,scrollMargin:b,getItemKey:x=>e[x]?.session.id??x});return s.jsx("div",{ref:d,children:t?s.jsx("div",{style:{height:y.getTotalSize(),position:"relative"},children:y.getVirtualItems().map(x=>{const C=e[x.index];return C?s.jsx("div",{"data-index":x.index,ref:y.measureElement,className:"[&_[data-session-row]]:my-px",style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${x.start-b}px)`},children:c(C,0,o,i,l,void 0,"project",u(C))},C.session.id):null})}):e.map(x=>s.jsx(a.Fragment,{children:c(x,0,o,i,l,void 0,"project",u(x))},x.session.id))})}const Jn=(e,t)=>{if(!t)return e;const n=e.toLowerCase(),r=t.toLowerCase(),o=r.length;if(o===0)return e;const i=[];let l=0,c=n.indexOf(r,l);for(;c!==-1;){c>l&&i.push(e.slice(l,c));const u=e.slice(c,c+o);i.push(s.jsx("mark",{className:"bg-primary text-primary-foreground ring-1 ring-primary/90",children:u},`${c}-${u}`)),l=c+o,c=n.indexOf(r,l)}return l<e.length&&i.push(e.slice(l)),i.length>0?i:e},nn=e=>[Dt(),...e.map(t=>(t??"").toString())].join(`
|
|
16
|
+
`),$n=e=>{const t=e?.body;return t&&typeof t.kind=="string"?t:{kind:"failed",message:e instanceof Error?e.message:"GitHub request failed"}},dm=200,Gs=(e={})=>{const t=e.maxEntries??dm,n=new Map,r=new Map,o=new Map;let i=0;const l=new Map,c=new Map,u=h=>{const y=n.get(h)??null;return y&&l.set(h,i+=1),y},d=h=>{const y=c.get(h);if(y)for(const x of[...y])try{x()}catch{}},f=()=>{if(n.size<=t)return;const h=[...n.keys()].filter(x=>!r.has(x)&&(c.get(x)?.size??0)===0).sort((x,C)=>(l.get(x)??0)-(l.get(C)??0)),y=n.size-t;for(let x=0;x<y&&x<h.length;x+=1){const C=h[x];n.delete(C),l.delete(C),o.set(C,(o.get(C)??0)+1)}};let p=!1;const b=()=>{if(p||n.size<=t)return;p=!0;const h=()=>{p=!1,f()};typeof queueMicrotask=="function"?queueMicrotask(h):setTimeout(h,0)},g=(h,y)=>{const C={...n.get(h)??{data:null,fetchedAt:null,isLoading:!1,stale:!1,error:null,generation:o.get(h)??0},...y};return n.set(h,C),l.set(h,i+=1),b(),d(h),C},m=async(h,y)=>{const x=r.get(h);if(x)return x;const C=(o.get(h)??0)+1;o.set(h,C);const v=n.get(h);g(h,{isLoading:!0,generation:C});const P=(async()=>{try{const S=await y();return o.get(h)!==C?n.get(h)??{data:S,fetchedAt:Date.now(),isLoading:!1,stale:!1,error:null,generation:C}:g(h,{data:S,fetchedAt:Date.now(),isLoading:!1,stale:!1,error:null,generation:C})}catch(S){return o.get(h)!==C?n.get(h)??{data:v?.data??null,fetchedAt:v?.fetchedAt??null,isLoading:!1,stale:!0,error:$n(S),generation:C}:v?.data!=null?g(h,{isLoading:!1,stale:!0,error:$n(S),generation:C}):g(h,{data:null,fetchedAt:null,isLoading:!1,stale:!1,error:$n(S),generation:C})}})();r.set(h,P);try{return await P}finally{r.get(h)===P&&r.delete(h),e.onSettle?.(h)}};return{getEntry:u,snapshot:()=>Object.fromEntries(n),subscribe:(h,y)=>{let x=c.get(h);return x||(x=new Set,c.set(h,x)),x.add(y),()=>{const C=c.get(h);C&&(C.delete(y),C.size===0&&c.delete(h))}},ensure:(h,y,x)=>!x?.force&&r.has(h)?r.get(h):!x?.force&&n.get(h)?.data!=null&&n.get(h)?.isLoading?r.get(h)??Promise.resolve(n.get(h)):!x?.force&&n.get(h)?.data!=null?(m(h,y),Promise.resolve(n.get(h))):m(h,y),refresh:(h,y)=>m(h,y),invalidate:async(h,y,x)=>{if(x?.exact??!0)return o.set(h,(o.get(h)??0)+1),n.delete(h),l.delete(h),r.has(h)&&r.delete(h),d(h),y?m(h,y):null;for(const v of[...n.keys()])(v===h||v.startsWith(h))&&(o.set(v,(o.get(v)??0)+1),n.delete(v),l.delete(v),r.delete(v),d(v));return null},markStale:h=>{const y=n.get(h);y?.data&&(y.stale||g(h,{stale:!0}))},setError:(h,y)=>{const x=n.get(h);return x?.data?g(h,{isLoading:!1,stale:!0,error:$n(y)}):x??null},remove:h=>{o.set(h,(o.get(h)??0)+1),n.delete(h),l.delete(h),r.delete(h),d(h)},reset:()=>{const h=[...n.keys()];n.clear(),r.clear(),o.clear(),l.clear();for(const y of h)d(y)}}},rn=(e,t)=>Ne.useSyncExternalStore(n=>t?e.subscribe(t,n):()=>{},()=>t?e.getEntry(t):null,()=>t?e.getEntry(t):null),ix=e=>{const t=e.trim().match(/^#?(\d{1,7})$/);if(!t)return null;const n=Number(t[1]);return Number.isSafeInteger(n)&&n>0?n:null},ml=(e,t)=>!e||!t?!1:e.toLowerCase()===t.toLowerCase(),po=e=>{if(!e)return[];const t=[];for(const n of e)n?.login&&t.push(n.login.toLowerCase());return t},pl=e=>{const t=[],n=[];for(const r of e.trim().toLowerCase().split(/\s+/))r&&(r.startsWith("label:")&&r.length>6?n.push(r.slice(6)):t.push(r));return{tokens:t,labelTokens:n}},Ro=e=>{if(!e)return[];const t=[];for(const n of e)n?.name&&t.push(n.name.toLowerCase());return t},gl=(e,t,n)=>{const r=Ro(e??null),o=t.split(",").map(i=>i.trim().toLowerCase()).filter(Boolean);for(const i of[...o,...n])if(!r.some(l=>l===i||l.includes(i)))return!1;return!0},fm=e=>{const t=[e.title.toLowerCase(),`#${e.number}`,`${e.number}`,e.author?.login?.toLowerCase()??"",e.head.toLowerCase(),e.base.toLowerCase()];for(const n of Ro(e.labels))t.push(n);return t},hm=e=>{const t=[e.title.toLowerCase(),`#${e.number}`,`${e.number}`,e.author?.login?.toLowerCase()??""];for(const n of Ro(e.labels))t.push(n);return t},bl=(e,t)=>{for(const n of t){let r=!1;for(const o of e)if(o.includes(n)){r=!0;break}if(!r)return!1}return!0},Ri=e=>e.state==="merged"||!!e.mergedAt,mm=(e,t)=>t==="all"?e:t==="open"?e.filter(n=>n.state==="open"):t==="merged"?e.filter(n=>Ri(n)):e.filter(n=>n.state==="closed"&&!Ri(n)),pm=(e,t)=>t==="all"?e:e.filter(n=>n.state===t),gm=(e,t,n)=>t==="all"||!n?!0:t==="mine"?ml(e.author?.login,n):t==="review"?po(e.requestedReviewers).includes(n.toLowerCase()):po(e.assignees).includes(n.toLowerCase()),bm=(e,t,n)=>t==="all"||!n||t==="mentioned"?!0:t==="mine"?ml(e.author?.login,n):po(e.assignees).includes(n.toLowerCase()),_s=e=>{if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0},xl=(e,t)=>{const n=[...e];return t==="newest"?(n.sort((r,o)=>_s(o.createdAt)-_s(r.createdAt)||o.number-r.number),n):t==="oldest"?(n.sort((r,o)=>_s(r.createdAt)-_s(o.createdAt)||r.number-o.number),n):(n.sort((r,o)=>_s(o.updatedAt)-_s(r.updatedAt)||o.number-r.number),n)},ax=(e,t)=>{const{tokens:n,labelTokens:r}=pl(t.search),o=[];for(const i of mm(e,t.state))gm(i,t.involvement,t.viewerLogin)&&gl(i.labels,"",r)&&bl(fm(i),n)&&o.push(i);return xl(o,t.sort)},lx=(e,t)=>{const{tokens:n,labelTokens:r}=pl(t.search),o=[];for(const i of pm(e,t.state))bm(i,t.involvement,t.viewerLogin)&&gl(i.labels,t.labels,r)&&bl(hm(i),n)&&o.push(i);return xl(o,t.sort)},Kn=(e,t)=>{if(t.length===0)return e;const n=new Map;for(const i of t)n.set(i.number,i);const r=e.map(i=>n.get(i.number)??i),o=new Set(e.map(i=>i.number));for(const i of t)o.has(i.number)||r.push(i);return r},cx=(e,t)=>e.filter(n=>!t.has(n.number)),xm=(e,t)=>{if(t.length===0)return e;const n=new Set(e.map(o=>o.id)),r=[...e];for(const o of t)n.has(o.id)||(n.add(o.id),r.push(o));return r},Di=Object.freeze({repo:null,number:null}),Dr=e=>e.split(`
|
|
17
|
+
`)[1]??"",go=(e,t)=>`${is(e)}
|
|
18
|
+
${t}`,hn=(e,t)=>`${e}#${t}`,ym=(e,t)=>{const n=e?.body;return n&&typeof n.kind=="string"?n:{kind:"failed",message:e instanceof Error?e.message:t}},js=async(e,t)=>{if(e)try{await e.invalidate(t)}catch{}},Pi=(e,t)=>!e?.data||!e.fetchedAt?!1:Date.now()-e.fetchedAt<t,Mi=10,wm=(e,t)=>{const n=Gs(),r=Gs({maxEntries:60}),o=Gs(),i=Gs(),l=new Map,c=new Map,u=async(F,R)=>{const E=c.get(F);if(E)return await E.catch(()=>null),{ran:!1,result:null};const I=R();c.set(F,I);try{return{ran:!0,result:await I}}finally{c.get(F)===I&&c.delete(F)}},d=(F,R)=>{if(R.length===0)return;const E=e.collectionKeyFor(F,e.openCollection);let I=l.get(E);I||(I=new Map,l.set(E,I));for(const M of R)I.set(M.number,M)},f=F=>{const R=Object.keys(r.snapshot()).filter(I=>Dr(I)===F&&!r.getEntry(I)?.isLoading);if(R.length<=Mi)return;const E=R.map(I=>({key:I,fetchedAt:r.getEntry(I)?.data?.fetchedAt??0})).sort((I,M)=>I.fetchedAt-M.fetchedAt);for(let I=0;I<E.length-Mi;I+=1)r.remove(E[I].key)},p=F=>{const R=n.getEntry(e.collectionKeyFor(F,e.openCollection))?.data?.items??[],E=n.getEntry(e.collectionKeyFor(F,e.closedCollection))?.data?.items??[],I=Kn(R,E),M=l.get(e.collectionKeyFor(F,e.openCollection));return!M||M.size===0?I:Kn(I,[...M.values()])},b=(F,R,E)=>{const I=go(F,R),M=t.get().filtersByScope[I]??e.defaultFilters;t.set(G=>({filtersByScope:{...G.filtersByScope,[I]:{...M,...E}}}))},g=(F,R)=>{const E=go(F,R);t.set(I=>({filtersByScope:{...I.filtersByScope,[E]:{...e.defaultFilters}}}))},m=(F,R,E)=>{const I=is(F);I&&t.set(M=>({selectionByDirectory:{...M.selectionByDirectory,[I]:{repo:R,number:E}}}))},h=(F,R,E,I)=>{const M=e.collectionKeyFor(R,E);return n.ensure(M,async()=>{const G=await e.fetchList(I,F,R,e.buildCollectionQuery(E));return{items:G.items,nextCursor:G.nextCursor,fetchedAt:G.fetchedAt}})},y=(F,R,E)=>{const I=e.collectionKeyFor(R,e.closedCollection);n.getEntry(I)?.data||n.getEntry(I)?.isLoading||h(F,R,e.closedCollection,E).catch(()=>null)},x=async(F,R,E,I)=>{const M=E==="open"||E==="both",G=E==="closed"||E==="both",X=[],U=n.getEntry(e.collectionKeyFor(R,e.openCollection)),ve=n.getEntry(e.collectionKeyFor(R,e.closedCollection));M&&(!Pi(U,e.freshWindowMs)||U?.stale)&&X.push(h(F,R,e.openCollection,I)),G&&(!Pi(ve,e.freshWindowMs)||ve?.stale)&&X.push(h(F,R,e.closedCollection,I)),await Promise.all(X.map(Z=>Z.catch(()=>null))),M&&!n.getEntry(e.collectionKeyFor(R,e.closedCollection))?.data&&y(F,R,I)},C=async(F,R,E,I)=>{const M=e.collectionKeyFor(R,E),G=n.getEntry(M),X=G?.data?.nextCursor??null;if(!X||G?.isLoading)return G;try{const U=await u(`${M}:more`,async()=>{const ve=await e.fetchList(I,F,R,{...e.buildCollectionQuery(E),cursor:X}),Z=n.getEntry(M)?.data,Re={items:Kn(Z?.items??[],ve.items),nextCursor:ve.nextCursor,fetchedAt:ve.fetchedAt};return n.refresh(M,async()=>Re)});return U.ran?U.result??n.getEntry(M):n.getEntry(M)}catch(U){return n.setError(M,U)??n.getEntry(M)}},v=async(F,R,E,I)=>{const M=E==="both"?[e.openCollection,e.closedCollection]:[E];await Promise.all(M.map(G=>{const X=e.collectionKeyFor(R,G);return n.refresh(X,async()=>{const U=await e.fetchList(I,F,R,e.buildCollectionQuery(G));return{items:U.items,nextCursor:U.nextCursor,fetchedAt:U.fetchedAt}}).catch(()=>null)}))},P=async(F,R,E,I)=>{const M=e.remoteKeyFor(R,E),G=await r.refresh(M,async()=>{const X=await e.fetchList(I,F,R,e.buildRemoteQuery(E));return{items:X.items,nextCursor:X.nextCursor,fetchedAt:X.fetchedAt}});return G.data&&(d(R,G.data.items),f(R)),G},S=async(F,R,E,I)=>{const M=e.remoteKeyFor(R,E),G=r.getEntry(M),X=G?.data?.nextCursor??null;if(!X||G?.isLoading)return G;try{const U=await e.fetchList(I,F,R,e.buildRemoteQuery(E,X)),ve=r.getEntry(M)?.data,Z={items:Kn(ve?.items??[],U.items),nextCursor:U.nextCursor,fetchedAt:U.fetchedAt},Re=await r.refresh(M,async()=>Z);return Re.data&&(d(R,Re.data.items),f(R)),Re}catch(U){return r.setError(M,U)??r.getEntry(M)}},A=F=>{for(const R of Object.keys(r.snapshot()))Dr(R)===F&&r.remove(R);for(const R of[...l.keys()])Dr(R)===F&&l.delete(R)},j=(F,R,E,I)=>{const M=e.detailKeyFor(R,E);return o.refresh(M,async()=>({detail:await e.fetchDetail(I,F,R,E)}))};return{initialState:{filtersByScope:{},selectionByDirectory:{}},resources:{collections:n,remote:r,details:o,comments:i},setFilters:b,resetFilters:g,select:m,ensureCollection:h,ensureCollectionsFresh:x,prefetchClosedCollection:y,loadMoreCollection:C,refreshCollections:v,searchRemote:P,loadMoreRemote:S,dropRemoteForRepo:A,refreshAllForScope:async(F,R,E)=>{await js(E,{directory:F,repo:R,kind:e.serverKind}),A(R),await v(F,R,"both",E).catch(()=>null);const I=t.get().selectionByDirectory[is(F)];I?.repo===R&&typeof I.number=="number"&&await j(F,R,I.number,E).catch(()=>null)},ensureDetail:(F,R,E,I)=>{const M=e.detailKeyFor(R,E);return o.ensure(M,async()=>({detail:await e.fetchDetail(I,F,R,E)}))},refreshDetail:j,ensureComments:(F,R,E,I)=>{const M=e.commentsKeyFor(R,E);return i.ensure(M,async()=>{const G=await e.fetchComments(I,F,R,E);return{comments:G.comments,nextCursor:G.nextCursor,fetchedAt:G.fetchedAt}})},loadMoreComments:async(F,R,E,I)=>{const M=e.commentsKeyFor(R,E),G=i.getEntry(M),X=G?.data?.nextCursor??null;if(!X||G?.isLoading)return G;try{const U=await e.fetchComments(I,F,R,E,X),ve=i.getEntry(M)?.data,Z={comments:xm(ve?.comments??[],U.comments),nextCursor:U.nextCursor,fetchedAt:U.fetchedAt};return await i.refresh(M,async()=>Z)}catch(U){return i.setError(M,U)??i.getEntry(M)}},refreshComments:(F,R,E,I)=>{const M=e.commentsKeyFor(R,E);return i.refresh(M,async()=>{const G=await e.fetchComments(I,F,R,E);return{comments:G.comments,nextCursor:G.nextCursor,fetchedAt:G.fetchedAt}})},markCollectionsStale:F=>{n.markStale(e.collectionKeyFor(F,e.openCollection)),n.markStale(e.collectionKeyFor(F,e.closedCollection))},getLocalIndex:p,withSingleFlight:u,resetCore:()=>{n.reset(),r.reset(),l.clear(),o.reset(),i.reset(),c.clear(),t.set({filtersByScope:{},selectionByDirectory:{}})},toStoreError:F=>ym(F,e.errorFallback)}},bo={state:"open",involvement:"all",search:"",sort:"updated"},vm=3e4,Sm=100,jm=50,yl=(e,t)=>nn([e,"pulls-collection",t]),wl=(e,t)=>nn([e,"pulls-remote",t.state,t.involvement,t.q.trim()]),cr=(e,t)=>nn([e,"pull-detail",t]),Do=(e,t)=>nn([e,"pull-comments",t]),xo=(e,t)=>nn([e,"pull-files",t]),yo=(e,t)=>nn([e,"pull-checks",t]),Cm=e=>({state:e,perPage:Sm}),km=(e,t)=>({state:e.state,filter:e.involvement,q:e.q.trim()?e.q.trim():void 0,perPage:jm,...t?{cursor:t}:{}}),ur=e=>`pichamber:pr-merge-method:${e}`,vl=new Map,Am=e=>{try{if(typeof localStorage<"u")return localStorage.getItem(e)}catch{}return null},Nm=(e,t)=>{try{if(typeof localStorage<"u"){localStorage.setItem(e,t);return}}catch{}},ux=e=>{if(!e)return null;const t=Am(ur(e));return t==="merge"||t==="squash"||t==="rebase"?t:vl.get(ur(e))??null},Im=(e,t)=>{if(e){vl.set(ur(e),t);try{Nm(ur(e),t)}catch{}}},Em={set:e=>{typeof e=="function"?gs.setState(t=>{const n={filtersByScope:t.filtersByScope,selectionByDirectory:t.selectionByDirectory};return e(n)}):gs.setState(e)},get:()=>{const e=gs.getState();return{filtersByScope:e.filtersByScope,selectionByDirectory:e.selectionByDirectory}}},Ie=wm({openCollection:"open",closedCollection:"closed",defaultFilters:bo,freshWindowMs:vm,serverKind:"pulls",errorFallback:"Pull request request failed",collectionKeyFor:yl,remoteKeyFor:wl,detailKeyFor:cr,commentsKeyFor:Do,buildCollectionQuery:e=>({...Cm(e)}),buildRemoteQuery:(e,t)=>({...km(e,t)}),fetchList:async(e,t,n,r)=>{const o=await e.pullsList(t,n,r);return{items:o.items,nextCursor:o.nextCursor,fetchedAt:o.fetchedAt}},fetchDetail:async(e,t,n,r)=>e.pullGet(t,n,r),fetchComments:async(e,t,n,r,o)=>{const i=await e.pullComments(t,n,r,o);return{comments:i.comments,nextCursor:i.nextCursor,fetchedAt:i.fetchedAt}}},Em),Yt=Gs(),Xn=Gs(),gs=Ts()(gr((e,t)=>({...Ie.initialState,actionErrorByDetail:{},actingActions:{},setFilters:Ie.setFilters,resetFilters:Ie.resetFilters,selectPullRequest:Ie.select,ensureCollection:Ie.ensureCollection,ensureCollectionsFresh:Ie.ensureCollectionsFresh,prefetchClosedCollection:Ie.prefetchClosedCollection,loadMoreCollection:Ie.loadMoreCollection,refreshCollections:Ie.refreshCollections,searchRemote:Ie.searchRemote,loadMoreRemote:Ie.loadMoreRemote,dropRemoteForRepo:Ie.dropRemoteForRepo,refreshAllForScope:Ie.refreshAllForScope,ensureDetail:Ie.ensureDetail,refreshDetail:Ie.refreshDetail,ensureComments:Ie.ensureComments,loadMoreComments:Ie.loadMoreComments,refreshComments:Ie.refreshComments,ensureFiles:(n,r,o,i)=>{const l=xo(r,o);return Yt.ensure(l,async()=>i.pullFiles(n,r,o))},loadMoreFiles:async(n,r,o,i)=>{const l=xo(r,o),c=Yt.getEntry(l),u=c?.data?.nextCursor??null;if(!u||c?.isLoading)return c;try{const d=await Ie.withSingleFlight(`${l}:more`,async()=>{const f=await i.pullFiles(n,r,o,u),p=Yt.getEntry(l)?.data,b=new Set((p?.files??[]).map(m=>m.filename)),g={repo:f.repo,number:f.number,files:[...p?.files??[],...f.files.filter(m=>!b.has(m.filename))],nextCursor:f.nextCursor,fetchedAt:f.fetchedAt};return Yt.refresh(l,async()=>g)});return d.ran?d.result??Yt.getEntry(l):Yt.getEntry(l)}catch(d){return Yt.setError(l,d)??Yt.getEntry(l)}},ensureChecks:(n,r,o,i)=>{const l=yo(r,o);return Xn.ensure(l,async()=>i.pullChecks(n,r,o,!0))},refreshChecks:(n,r,o,i)=>{const l=yo(r,o);return Xn.refresh(l,async()=>i.pullChecks(n,r,o,!0))},performAction:async(n,r,o,i,l)=>{const c=hn(r,o),u=cr(r,o);if(t().actingActions[c])return{ok:!1,error:{kind:"failed",message:"Action already in progress"}};e(b=>({actingActions:{...b.actingActions,[c]:!0},actionErrorByDetail:{...b.actionErrorByDetail,[c]:null}}));const d=Ie.resources.details.getEntry(u)?.data?.detail??null,f=d?.pr??null,p=f?{...f,state:i==="close"?"closed":i==="reopen"?"open":i==="merge"||i==="squash"||i==="rebase"?"merged":f.state,draft:i==="ready"?!1:i==="draft"?!0:f.draft}:null;p&&d&&await Ie.resources.details.refresh(u,async()=>({detail:{...d,pr:p}})).catch(()=>null);try{return await l.pullAction(n,r,o,i),(i==="merge"||i==="squash"||i==="rebase")&&t().setMergeMethod(r,i),await js(l,{directory:n,repo:r,kind:"pulls",number:o}),t().dropRemoteForRepo(r),await t().refreshCollections(n,r,"both",l).catch(()=>null),await t().refreshDetail(n,r,o,l).catch(()=>null),await t().refreshChecks(n,r,o,l).catch(()=>null),e(b=>({actingActions:{...b.actingActions,[c]:!1}})),{ok:!0}}catch(b){const g=Ie.toStoreError(b);return d&&await Ie.resources.details.refresh(u,async()=>({detail:d})).catch(()=>null),e(m=>({actingActions:{...m.actingActions,[c]:!1},actionErrorByDetail:{...m.actionErrorByDetail,[c]:g}})),{ok:!1,error:g}}},updateTitleBody:async(n,r,o,i,l)=>{const c=hn(r,o),u=cr(r,o),d=Ie.resources.details.getEntry(u)?.data?.detail??null,f=d?.pr??null,p=f&&(i.title!==void 0||i.body!==void 0)?{...f,title:i.title??f.title,body:i.body??f.body}:null;p&&d&&await Ie.resources.details.refresh(u,async()=>({detail:{...d,pr:p}})).catch(()=>null);try{return await l.pullUpdate(n,r,o,i),await js(l,{directory:n,repo:r,kind:"pulls",number:o}),t().dropRemoteForRepo(r),await t().refreshCollections(n,r,"both",l).catch(()=>null),await t().refreshDetail(n,r,o,l).catch(()=>null),{ok:!0}}catch(b){const g=Ie.toStoreError(b);return d&&await Ie.resources.details.refresh(u,async()=>({detail:d})).catch(()=>null),e(m=>({actionErrorByDetail:{...m.actionErrorByDetail,[c]:g}})),{ok:!1,error:g}}},addComment:async(n,r,o,i,l)=>{const c=hn(r,o),u=Do(r,o),d=i.trim(),f={id:-Date.now(),url:"",body:d,author:null,createdAt:new Date().toISOString(),updatedAt:null},p=Ie.resources.comments.getEntry(u)?.data??null;if(p){const b={comments:[...p.comments,f],nextCursor:p.nextCursor,fetchedAt:p.fetchedAt};await Ie.resources.comments.refresh(u,async()=>b).catch(()=>null)}try{return await l.pullComment(n,r,o,d),await js(l,{directory:n,repo:r,kind:"pulls",number:o}),await t().refreshComments(n,r,o,l).catch(()=>null),await t().refreshDetail(n,r,o,l).catch(()=>null),{ok:!0}}catch(b){const g=Ie.toStoreError(b);return p?await Ie.resources.comments.refresh(u,async()=>p).catch(()=>null):Ie.resources.comments.remove(u),e(m=>({actionErrorByDetail:{...m.actionErrorByDetail,[c]:g}})),{ok:!1,error:g}}},submitReview:async(n,r,o,i,l)=>{const c=hn(r,o);try{return await l.pullReview(n,r,o,{event:i.event,body:i.body,comments:i.comments}),await js(l,{directory:n,repo:r,kind:"pulls",number:o}),await t().refreshDetail(n,r,o,l).catch(()=>null),{ok:!0}}catch(u){const d=Ie.toStoreError(u);return e(f=>({actionErrorByDetail:{...f.actionErrorByDetail,[c]:d}})),{ok:!1,error:d}}},threadAction:async(n,r,o,i,l,c)=>{const u=hn(r,o);try{return await c.pullThread(n,r,o,i,l),await js(c,{directory:n,repo:r,kind:"pulls",number:o}),await t().refreshDetail(n,r,o,c).catch(()=>null),{ok:!0}}catch(d){const f=Ie.toStoreError(d);return e(p=>({actionErrorByDetail:{...p.actionErrorByDetail,[u]:f}})),{ok:!1,error:f}}},checkout:async(n,r,o,i,l)=>{try{const c=await l.pullCheckout(n,r,o,i);return{ok:!0,path:c.path,branch:c.branch}}catch(c){return{ok:!1,error:Ie.toStoreError(c)}}},createPullRequest:async(n,r)=>{try{const o=await r.pullCreate(n);return await js(r,{directory:n.directory,repo:n.repo,kind:"pulls"}),t().dropRemoteForRepo(n.repo),await t().refreshCollections(n.directory,n.repo,"both",r).catch(()=>null),{ok:!0,number:o.pr.number}}catch(o){return{ok:!1,error:Ie.toStoreError(o)}}},rerunFailedChecks:async(n,r,o,i)=>{try{return await i.checksRerun(n,r,o),{ok:!0}}catch(l){return{ok:!1,error:Ie.toStoreError(l)}}},setMergeMethod:(n,r)=>{Im(n,r)},notifyAgentTurnComplete:n=>{const r=is((n||"").trim());if(!r)return;const o=Vt.getState();for(const l of Object.keys(o.results)){const[,c]=l.split(`
|
|
19
|
+
`);if(c!==r)continue;const[,,u]=l.split(`
|
|
20
|
+
`);u&&dt(async()=>{const{getRegisteredRuntimeAPIs:d}=await import("./index-6IO1AcJI.js").then(f=>f.cv);return{getRegisteredRuntimeAPIs:d}},__vite__mapDeps([2,3,4,5,6,7,8])).then(({getRegisteredRuntimeAPIs:d})=>{const f=d()?.github??null;if(f)return o.refresh(r,u,f,{force:!0})}).catch(()=>{})}const i=t().selectionByDirectory[r];i?.repo&&typeof i.number=="number"&&(Ie.markCollectionsStale(i.repo),dt(async()=>{const{getRegisteredRuntimeAPIs:l}=await import("./index-6IO1AcJI.js").then(c=>c.cv);return{getRegisteredRuntimeAPIs:l}},__vite__mapDeps([2,3,4,5,6,7,8])).then(({getRegisteredRuntimeAPIs:l})=>{const c=l()?.github??null;if(c)return t().refreshDetail(r,i.repo,i.number,c)}).catch(()=>{}))},resetForRuntimeSwitch:()=>{Ie.resetCore(),Yt.reset(),Xn.reset(),e({actionErrorByDetail:{},actingActions:{}})}}),{name:"github-pull-requests-store"}));typeof window<"u"&&(Rn(()=>{gs.getState().resetForRuntimeSwitch()}),window.addEventListener("focus",()=>{typeof document<"u"&&document.hidden}));const dx=e=>{if(typeof window>"u")return()=>{};let t=new Set,n=!1,r=!1,o=null;return dt(async()=>{const{useNotificationStore:i}=await import("./useAppFontEffects-CG3_yteE.js").then(l=>l.dR);return{useNotificationStore:i}},__vite__mapDeps([1,2,3,4,5,6,7,8,9,10,11])).then(({useNotificationStore:i})=>{if(r)return;const l=()=>{const c=i.getState().list,u=new Set(c.map(d=>`${d.type}:${d.session??""}:${d.time}`));if(!n){t=u,n=!0;return}for(const d of c){const f=`${d.type}:${d.session??""}:${d.time}`;t.has(f)||(t.add(f),d.type==="turn-complete"&&d.directory&&(gs.getState().notifyAgentTurnComplete(d.directory),e?.(d.directory)))}};l(),o=i.subscribe(l)}).catch(()=>{}),()=>{r=!0,o?.(),o=null}},fx=e=>Ie.getLocalIndex(e),hx=(e,t)=>Ie.getLocalIndex(e).find(n=>n.number===t)??null,mx=(e,t)=>rn(Ie.resources.collections,e?yl(e,t):null),px=(e,t)=>rn(Ie.resources.remote,e?wl(e,t):null),gx=(e,t)=>rn(Ie.resources.details,e!=null&&t!=null?cr(e,t):null),bx=(e,t)=>rn(Ie.resources.comments,e!=null&&t!=null?Do(e,t):null),xx=(e,t)=>rn(Yt,e!=null&&t!=null?xo(e,t):null),yx=(e,t)=>rn(Xn,e!=null&&t!=null?yo(e,t):null),wx=(e,t)=>gs(n=>!e||!t?bo:n.filtersByScope[go(e,t)]??bo),vx=e=>gs(t=>e?t.selectionByDirectory[is(e)]??Di:Di),Sl=(e,t,n)=>{gs.getState().selectPullRequest(e,t,n);const r=is(e);dt(async()=>{const{useUIStore:o}=await import("./index-6IO1AcJI.js").then(i=>i.cy);return{useUIStore:o}},__vite__mapDeps([2,3,4,5,6,7,8])).then(({useUIStore:o})=>{o.getState().openContextSurface(r,"pull-requests")}).catch(()=>{}),dt(async()=>{const{useGitHubScopeStore:o}=await import("./useAppFontEffects-CG3_yteE.js").then(i=>i.dT);return{useGitHubScopeStore:o}},__vite__mapDeps([1,2,3,4,5,6,7,8,9,10,11])).then(({useGitHubScopeStore:o})=>{o.getState().setSelectedRepo(e,t)}).catch(()=>{})},Rm=({directory:e,number:t,color:n})=>{const r=xa(e);return!e||!r?s.jsxs("span",{className:"ml-auto flex-shrink-0 text-[0.72rem] font-medium leading-none",style:n?{color:n}:void 0,children:["#",t]}):s.jsxs("button",{type:"button",onClick:o=>{o.stopPropagation(),Sl(e,r,t)},className:"ml-auto flex-shrink-0 rounded text-[0.72rem] font-medium leading-none hover:bg-interactive-hover",style:n?{color:n}:void 0,title:`Open PR #${t} in Pull requests`,"aria-label":`Open pull request #${t} in Pull requests`,children:["#",t]})};function Dm({group:e,groupKey:t,isCollapsed:n,onToggleCollapsedGroup:r,normalizedSessionSearchQuery:o,alwaysShowActions:i,groupHeaderRightPadding:l,dragHandleProps:c,groupPrColor:u,groupPrSummary:d,groupActivityIndicator:f,showBranchSubtitle:p,statusLine:b,allGroupSessions:g,projectId:m,activeProjectId:h,setActiveProjectIdOnly:y,setActiveMainTab:x,mobileVariant:C,setSessionSwitcherOpen:v,openNewSessionDraft:P}){return s.jsxs("div",{className:K("group/gh relative flex items-start justify-between gap-1 py-1 px-3 min-w-0 rounded-md","cursor-pointer"),onClick:()=>r(t),role:"button",tabIndex:0,onKeyDown:S=>{(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),r(t))},"aria-label":n?`Expand ${e.label}`:`Collapse ${e.label}`,"aria-expanded":!n,children:[s.jsx("div",{ref:c?.setActivatorNodeRef,className:K("min-w-0 flex flex-1 items-start gap-1 overflow-hidden transition-[padding]",l),...c?.listeners??{},children:s.jsxs("div",{className:"min-w-0 flex flex-1 flex-col justify-center gap-0.5 overflow-hidden",children:[s.jsx("p",{className:"typography-ui-label font-normal truncate text-foreground/92",children:e.isArchivedBucket?s.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[s.jsxs("span",{className:"inline-flex size-4 shrink-0 items-center justify-center",children:[s.jsx(D,{name:"archive",className:K("size-4 shrink-0 text-muted-foreground",i?"hidden":"group-hover/gh:hidden")}),s.jsx("span",{className:K("text-muted-foreground size-4 items-center justify-center",i?"inline-flex":"hidden group-hover/gh:inline-flex"),children:n?s.jsx(D,{name:"arrow-right-s",className:"size-4"}):s.jsx(D,{name:"arrow-down-s",className:"size-4"})})]}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:Jn(e.label,o)}),f]}):!e.isMain||e.worktree?s.jsxs("span",{className:"flex w-full min-w-0 items-center gap-1.5",children:[s.jsxs("span",{className:"inline-flex size-4 shrink-0 items-center justify-center",children:[s.jsx(D,{name:"git-branch",className:K("size-4 shrink-0",!u&&"text-muted-foreground",i?"hidden":"group-hover/gh:hidden"),style:u?{color:u}:void 0}),s.jsx("span",{className:K("text-muted-foreground size-4 items-center justify-center",i?"inline-flex":"hidden group-hover/gh:inline-flex"),children:n?s.jsx(D,{name:"arrow-right-s",className:"size-4"}):s.jsx(D,{name:"arrow-down-s",className:"size-4"})})]}),s.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal text-muted-foreground",children:Jn(e.label,o)}),f,d?s.jsx(Rm,{directory:e.directory??null,number:d.number,color:u}):null]}):s.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[s.jsx("span",{className:"min-w-0 truncate",children:Jn(e.label,o)}),f]})}),p&&b?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 leading-tight",children:[e.isArchivedBucket?s.jsx(D,{name:"archive",className:"size-4 flex-shrink-0 text-muted-foreground"}):s.jsx(D,{name:"git-branch",className:"size-4 flex-shrink-0 text-muted-foreground"}),s.jsx("span",{className:"min-w-0 truncate text-[11px] font-medium text-muted-foreground/80",children:b.label})]}):null]})}),e.isArchivedBucket&&g.length>0?s.jsx("div",{className:K("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",i?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:S=>{S.stopPropagation(),Es.requestDelete({sessions:g,mode:"session"})},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete archived sessions in ${e.label}`,children:s.jsx(D,{name:"delete-bin",className:"h-4 w-4"})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Delete archived sessions"})})]})}):null,e.directory?s.jsx("div",{className:K("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",i?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:S=>{S.stopPropagation(),m&&m!==h&&y(m),x("chat"),C&&v(!1),P({selectedProjectId:m,directoryOverride:e.directory})},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`New draft session in ${e.label}`,children:s.jsx(D,{name:"add",className:"h-4 w-4"})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"New draft session"})})]})}):null]})}const Wn=(e,t)=>t?e.sessions.some(n=>os(n,t)):!1,Pm=(e,t,n)=>e.sessions.some(r=>ll(r,r,t,n,e.directory,e.directory)),Mm=(e,t,n)=>{const r=o=>{const i=o.session.id;return t.get(i)!==n.get(i)?!0:o.children.some(r)};return e.sessions.some(r)},Ti=(e,t,n)=>{const r=o=>t.has(o.session.id)!==n.has(o.session.id)?!0:o.children.some(r);return e.sessions.some(r)},Tm=(e,t,n)=>{const r=e.isArchivedBucket?"archived":"active",o=i=>{const l=`project:${r}:${i.session.id}`;return t.has(l)!==n.has(l)?!0:i.children.some(o)};return e.sessions.some(o)},Fm=(e,t)=>{if(e.group!==t.group||e.groupKey!==t.groupKey||e.projectId!==t.projectId||e.hideGroupLabel!==t.hideGroupLabel||e.compactBodyPadding!==t.compactBodyPadding||e.groupSearchDataByGroup!==t.groupSearchDataByGroup||e.visibleSessionCount!==t.visibleSessionCount||e.collapsedGroups!==t.collapsedGroups&&e.collapsedGroups.has(e.groupKey)!==t.collapsedGroups.has(t.groupKey)||e.pinnedSessionIds!==t.pinnedSessionIds&&Pm(t.group,e.pinnedSessionIds,t.pinnedSessionIds)||e.expandedParents!==t.expandedParents&&Tm(t.group,e.expandedParents,t.expandedParents)||e.sessionOrderIndex!==t.sessionOrderIndex&&Mm(t.group,e.sessionOrderIndex,t.sessionOrderIndex)||e.editingId!==t.editingId&&(Wn(e.group,e.editingId)||Wn(t.group,t.editingId))||e.editTitle!==t.editTitle&&(Wn(e.group,e.editingId)||Wn(t.group,t.editingId)))return!1;if(e.openSidebarMenuKey!==t.openSidebarMenuKey){const n=lr(e.group.sessions,e.openSidebarMenuKey,"project",!!e.group.isArchivedBucket),r=lr(t.group.sessions,t.openSidebarMenuKey,"project",!!t.group.isArchivedBucket);if(n||r)return!1}return e.activeActivitySessionIds!==t.activeActivitySessionIds&&Ti(t.group,e.activeActivitySessionIds,t.activeActivitySessionIds)||e.unreadActivitySessionIds!==t.unreadActivitySessionIds&&Ti(t.group,e.unreadActivitySessionIds,t.unreadActivitySessionIds)?!1:e.hasSessionSearchQuery===t.hasSessionSearchQuery&&e.normalizedSessionSearchQuery===t.normalizedSessionSearchQuery&&e.hideDirectoryControls===t.hideDirectoryControls&&e.collapsedFolderIds===t.collapsedFolderIds&&e.toggleFolderCollapse===t.toggleFolderCollapse&&e.renameFolder===t.renameFolder&&e.deleteFolder===t.deleteFolder&&e.showDeletionDialog===t.showDeletionDialog&&e.setDeleteFolderConfirm===t.setDeleteFolderConfirm&&e.renderSessionNode===t.renderSessionNode&&e.showMoreGroupSessions===t.showMoreGroupSessions&&e.resetGroupSessionLimit===t.resetGroupSessionLimit&&e.mobileVariant===t.mobileVariant&&e.alwaysShowActions===t.alwaysShowActions&&e.activeProjectId===t.activeProjectId&&e.setActiveProjectIdOnly===t.setActiveProjectIdOnly&&e.setActiveMainTab===t.setActiveMainTab&&e.setSessionSwitcherOpen===t.setSessionSwitcherOpen&&e.openNewSessionDraft===t.openNewSessionDraft&&e.addSessionToFolder===t.addSessionToFolder&&e.createFolderAndStartRename===t.createFolderAndStartRename&&e.renamingFolderId===t.renamingFolderId&&e.renameFolderDraft===t.renameFolderDraft&&e.setRenameFolderDraft===t.setRenameFolderDraft&&e.setRenamingFolderId===t.setRenamingFolderId&&e.onToggleCollapsedGroup===t.onToggleCollapsedGroup&&e.dragHandleProps===t.dragHandleProps&&e.scrollContainerRef===t.scrollContainerRef};function Lm({group:e,sourceGroupNodes:t,hasSessionSearchQuery:n,normalizedSessionSearchQuery:r,compareSessionNodes:o,activeActivitySessionIds:i,unreadActivitySessionIds:l,collectGroupSessions:c}){const u=ft(S=>S.foldersMap),d=e.folderScopeKey??Ae(e.directory??null),f=a.useMemo(()=>e.folderScopes&&e.folderScopes.length>0?e.folderScopes:d?[{scopeKey:d,directory:e.directory??null}]:[],[d,e.directory,e.folderScopes]),p=a.useMemo(()=>f.flatMap(({scopeKey:S,directory:A})=>(u[S]??[]).map(j=>({folder:j,scopeKey:S,scopeDirectory:A}))),[f,u]),b=a.useMemo(()=>{const S=new Map,A=j=>{j.forEach(w=>{S.set(w.session.id,w),w.children.length>0&&A(w.children)})};return A(t),S},[t]),g=a.useMemo(()=>p.map(({folder:S,scopeKey:A,scopeDirectory:j})=>{const w=tm(S.sessionIds,b).sort(o);return{folder:S,scopeKey:A,scopeDirectory:j,nodes:w}}),[p,b,o]),m=a.useMemo(()=>{const S=new Map(g.map(N=>[N.folder.id,N])),A=new Map;for(const{folder:N}of g){if(!N.parentId)continue;const T=A.get(N.parentId);T?T.push(N.id):A.set(N.parentId,[N.id])}const j=new Map,w=N=>{const T=j.get(N);if(T!==void 0)return T;const L=S.get(N);if(!L)return j.set(N,!1),!1;const $=A.get(N)??[];if(e.isArchivedBucket&&L.nodes.length===0){const F=$.some(R=>w(R));return j.set(N,F),F}if(!n||L.folder.name.toLowerCase().includes(r)||L.nodes.length>0)return j.set(N,!0),!0;const W=$.some(F=>w(F));return j.set(N,W),W};return g.filter(({folder:N})=>w(N.id))},[g,e.isArchivedBucket,n,r]),h=a.useMemo(()=>new Set(m.flatMap(S=>S.folder.sessionIds)),[m]),y=a.useMemo(()=>t.filter(S=>!h.has(S.session.id)),[t,h]),x=a.useMemo(()=>m.filter(({folder:S})=>!S.parentId),[m]),C=a.useMemo(()=>{const S=new Map;return m.forEach(A=>{if(!A.folder.parentId)return;const j=S.get(A.folder.parentId)??[];j.push(A),S.set(A.folder.parentId,j)}),S},[m]),v=a.useMemo(()=>{const S=new Map(m.map(w=>[w.folder.id,w])),A=new Map,j=(w,N)=>{const T=A.get(w);if(T!==void 0)return T;if(N.has(w))return null;N.add(w);const L=S.get(w);let $=L?hl(L.nodes,i,l):null;for(const z of C.get(w)??[])if($=Eo($,j(z.folder.id,N)),$==="active")break;return A.set(w,$),$};return m.forEach(({folder:w})=>j(w.id,new Set)),A},[i,m,C,l]),P=a.useMemo(()=>{if(!e.isArchivedBucket)return new Map;const S=new Map,A=new Map;for(const{folder:w}of m){if(!w.parentId)continue;const N=A.get(w.parentId)??[];N.push(w.id),A.set(w.parentId,N)}const j=(w,N)=>{if(N.has(w))return[];N.add(w);const T=m.find(({folder:z})=>z.id===w),L=T?c(T.nodes):[],$=A.get(w)??[];for(const z of $)L.push(...j(z,N));return L};for(const{folder:w}of m)S.set(w.id,j(w.id,new Set));return S},[m,c,e.isArchivedBucket]);return{folderScopeKey:d,folderScopes:f,allFoldersForGroup:m,rootFolders:x,ungroupedSessions:y,folderActivityStateById:v,folderSessionsForDeleteById:P}}function Om(e){const{group:t,groupKey:n,projectId:r,hideGroupLabel:o,hasSessionSearchQuery:i,normalizedSessionSearchQuery:l,groupSearchDataByGroup:c,visibleSessionCount:u,collapsedGroups:d,hideDirectoryControls:f,collapsedFolderIds:p,toggleFolderCollapse:b,renameFolder:g,deleteFolder:m,showDeletionDialog:h,setDeleteFolderConfirm:y,renderSessionNode:x,showMoreGroupSessions:C,resetGroupSessionLimit:v,mobileVariant:P,alwaysShowActions:S,activeProjectId:A,setActiveProjectIdOnly:j,setActiveMainTab:w,setSessionSwitcherOpen:N,openNewSessionDraft:T,addSessionToFolder:L,createFolderAndStartRename:$,renamingFolderId:z,renameFolderDraft:W,setRenameFolderDraft:F,setRenamingFolderId:R,pinnedSessionIds:E,expandedParents:I,sessionOrderIndex:M,editingId:G,openSidebarMenuKey:X,activeActivitySessionIds:U,unreadActivitySessionIds:ve,onToggleCollapsedGroup:Z,dragHandleProps:Re,compactBodyPadding:Oe=!1,scrollContainerRef:Q}=e,_=a.useCallback((ke,He)=>{const Ce=M.get(ke.session.id),Te=M.get(He.session.id);if(Ce!==void 0||Te!==void 0){if(Ce===void 0)return 1;if(Te===void 0)return-1;if(Ce!==Te)return Ce-Te}return Bu(ke.session,He.session,E,ya)},[E,M]),H=i?c.get(t):null,J=i?!1:d.has(n),ne=!t.isMain&&!t.isArchivedBucket&&!o?Ae(t.directory??null):null,fe=!t.isMain&&!t.isArchivedBucket&&!o&&t.branch?.trim()||null,he=a.useMemo(()=>ne&&fe?En(ne,fe):null,[ne,fe]),q=ul(he);dl(ne,fe);const te=q?`var(--pr-${q.visualState})`:void 0,ae=f?10:5,je=Math.max(ae,u??ae),Se=i?H?.groupMatches===!0:!1,Ge=i,B=a.useMemo(()=>[...Ge?H?.filteredNodes??[]:t.sessions].sort(_),[_,t.sessions,H?.filteredNodes,Ge]),re=a.useCallback(ke=>{const He=[],Ce=Te=>{Te.forEach(Be=>{He.push(Be.session),Be.children.length>0&&Ce(Be.children)})};return Ce(ke),He},[]),{folderScopeKey:pe,folderScopes:ge,allFoldersForGroup:ce,rootFolders:Fe,ungroupedSessions:ye,folderActivityStateById:ee,folderSessionsForDeleteById:xe}=Lm({group:t,sourceGroupNodes:B,hasSessionSearchQuery:i,normalizedSessionSearchQuery:l,compareSessionNodes:_,activeActivitySessionIds:U,unreadActivitySessionIds:ve,collectGroupSessions:re}),ue="project",we=a.useMemo(()=>{const ke=new Set;return Ci(B,G,ke),ce.forEach(({nodes:He})=>{Ci(He,G,ke)}),ke},[B,ce,G]),ze=a.useMemo(()=>{if(!X)return null;const ke=lr(B,X,ue,!!t.isArchivedBucket);if(ke)return ke;for(const{nodes:He}of ce){const Ce=lr(He,X,ue,!!t.isArchivedBucket);if(Ce)return Ce}return null},[X,B,ce,t.isArchivedBucket]),qe=a.useCallback(ke=>{const He=new WeakMap,Ce=Te=>{He.set(Te,ho(Te));for(const Be of Te.children)Ce(Be)};return ke.forEach(Ce),He},[]),De=a.useMemo(()=>qe(B),[qe,B]),Ye=a.useMemo(()=>{const ke=new WeakMap;return ce.forEach(({nodes:He})=>{He.forEach(Ce=>ke.set(Ce,ho(Ce)))}),ke},[ce]),se=a.useCallback(ke=>De.get(ke)??Ye.get(ke)??"",[De,Ye]),Le=a.useCallback(ke=>({subtreeContainsEditing:we,menuOpenSessionId:ze,nodeStructureKey:se(ke)}),[we,ze,se]),ct=ye.length,et=t.isArchivedBucket||i?ye:ye.slice(0,je),Qe=ct-et.length,yt=!t.isArchivedBucket&&!i&&ct>ae&&Qe===0,it=t.isArchivedBucket===!0&&!i&&et.length>=lm,ss=t.isArchivedBucket?"archived":"active",Mt=it&&et.some(ke=>{if(ke.children.length===0)return!1;const He=`project:${ss}:${ke.session.id}`;return I.has(He)}),at=a.useMemo(()=>re(B),[re,B]);if(i&&!Se&&Fe.length===0&&ye.length===0)return null;const nt=!t.isMain&&!!t.branch,wt=t.branch&&qd(t.branch,t.label)?{label:t.branch,color:null}:null,tt=J?hl(B,U,ve):null,Tt=tt?s.jsx(al,{state:tt,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,$t=(ke,He)=>{const{folder:Ce,scopeKey:Te,scopeDirectory:Be,nodes:pt}=ke,rt=xe.get(Ce.id)??[],kt=i?!1:p.has(Ce.id);return s.jsx(Zh,{folderId:Ce.id,children:(vt,gt)=>s.jsx(Jh,{folder:Ce,displayName:He,sessions:pt,isCollapsed:kt,collapsedActivityState:kt?ee.get(Ce.id)??null:null,onToggle:()=>b(Ce.id),onRename:Ze=>{g(Te,Ce.id,Ze)},onDelete:()=>{if(t.isArchivedBucket){Es.requestDelete({sessions:rt,mode:"session"});return}if(!h){m(Te,Ce.id);return}const Ze=ce.filter(({folder:ws})=>ws.parentId===Ce.id).length,cs=pt.length;y({scopeKey:Te,folderId:Ce.id,folderName:Ce.name,subFolderCount:Ze,sessionCount:cs})},renderSessionNode:x,getRenderExtras:se?Ze=>({subtreeContainsEditing:we,menuOpenSessionId:ze,nodeStructureKey:se(Ze),childRenderExtrasFor:Le}):void 0,groupDirectory:Be??t.directory,projectId:r,mobileVariant:P,alwaysShowActions:S,isRenaming:z===Ce.id,renameDraft:z===Ce.id?W:void 0,onRenameDraftChange:Ze=>F(Ze),onRenameSave:()=>{const Ze=W.trim();Ze&&g(Te,Ce.id,Ze),R(null),F("")},onRenameCancel:()=>{R(null),F("")},droppableRef:vt,isDropTarget:gt,depth:0,onNewSession:()=>{r&&r!==A&&j(r),w("chat"),P&&N(!1),T({selectedProjectId:r,directoryOverride:Be??t.directory,targetFolderId:Ce.id})},hideActions:!1,archivedBucket:t.isArchivedBucket===!0})},Ce.id)},ls=()=>{const ke=new Map;for(const Te of ce){const Be=Te.folder.parentId;if(!Be)continue;const pt=ke.get(Be);pt?pt.push(Te):ke.set(Be,[Te])}const He=[],Ce=(Te,Be)=>{const pt=Be?`${Be} / ${Te.folder.name}`:Te.folder.name;He.push($t(Te,pt)),!(!i&&p.has(Te.folder.id))&&(ke.get(Te.folder.id)??[]).forEach(kt=>Ce(kt,pt))};return Fe.forEach(Te=>Ce(Te,"")),He},Ct=S?"pr-7":"pr-2 group-hover/gh:pr-7 group-focus-within/gh:pr-7",Ft=s.jsxs(em,{scopeKey:ge[0]?.scopeKey??pe,hasFolders:ce.length>0,onSessionDroppedOnFolder:(ke,He)=>{const Ce=ce.find(({folder:Be})=>Be.id===He);if(!Ce)return;const Te=ft.getState();for(const{scopeKey:Be}of ge)Be!==Ce.scopeKey&&Te.getSessionFolderId(Be,ke)&&Te.removeSessionFromFolder(Be,ke);L(Ce.scopeKey,He,ke)},children:[ls(),t.isArchivedBucket?s.jsx(um,{visibleSessions:et,shouldVirtualize:it,hasExpandedParent:Mt,scrollContainerRef:Q,groupDirectory:t.directory,projectId:r,isArchivedBucket:t.isArchivedBucket===!0,renderSessionNode:x,getRenderExtras:ke=>({subtreeContainsEditing:we,menuOpenSessionId:ze,nodeStructureKey:se(ke),childRenderExtrasFor:Le})}):et.map(ke=>s.jsx(a.Fragment,{children:x(ke,0,t.directory,r,t.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:we,menuOpenSessionId:ze,nodeStructureKey:se(ke),childRenderExtrasFor:Le})},ke.session.id)),ct===0&&ce.length===0?t.isArchivedBucket?s.jsx("div",{className:"py-1 px-3 text-left typography-ui-label text-muted-foreground",children:"No archived sessions yet."}):s.jsx(Ns,{icon:"chat-new",onClick:()=>{T({selectedProjectId:r,directoryOverride:t.directory})},children:"New session"}):null,Qe>0?s.jsx(Ns,{icon:"arrow-down-s",onClick:()=>C(n,et.length),children:Qe===1?"Show 1 more session":`Show ${Qe} more sessions`}):null,yt?s.jsx(Ns,{icon:"arrow-up-s",onClick:()=>v(n),children:"Show fewer sessions"}):null]});return o?s.jsx("div",{className:"oc-group",children:s.jsx("div",{className:"oc-group-body",children:Ft})}):s.jsxs("div",{className:"oc-group",children:[s.jsx(Dm,{group:t,groupKey:n,isCollapsed:J,onToggleCollapsedGroup:Z,normalizedSessionSearchQuery:l,alwaysShowActions:S,groupHeaderRightPadding:Ct,dragHandleProps:Re,groupPrColor:te,groupPrSummary:q,groupActivityIndicator:Tt,showBranchSubtitle:nt,statusLine:wt,allGroupSessions:at,projectId:r,activeProjectId:A,setActiveProjectIdOnly:j,setActiveMainTab:w,mobileVariant:P,setSessionSwitcherOpen:N,openNewSessionDraft:T}),J?null:s.jsx("div",{className:"oc-group-body",children:Ft})]})}const Bm=a.memo(Om,Fm);function _m(e){const{hideDirectoryControls:t,handleOpenDirectoryDialog:n,onOpenArchive:r,onOpenSettings:o,onOpenInstances:i,instanceLabel:l,onOpenUpdate:c,headerActionIconClass:u,headerActionButtonClass:d,isSessionSearchOpen:f,setIsSessionSearchOpen:p,sessionSearchInputRef:b,sessionSearchQuery:g,setSessionSearchQuery:m,hasSessionSearchQuery:h,searchMatchCount:y,selectionModeEnabled:x,onToggleSelectionMode:C,mobileVariant:v=!1}=e;if(t)return null;const P=K(d,"text-muted-foreground hover:text-foreground",!v&&"hover:bg-transparent");return s.jsx("div",{className:K("select-none flex-shrink-0",v?"px-2":"px-3 py-1"),children:s.jsxs("div",{className:K("flex flex-col",v?"gap-0":"h-auto min-h-8 gap-1"),children:[s.jsxs("div",{className:K("flex items-center justify-between",v?"h-[var(--oc-header-height,56px)] gap-1":"min-h-8 gap-2"),children:[s.jsxs("div",{className:K("flex min-w-0 items-center",v?"gap-1 overflow-x-auto":"gap-1.5"),"data-no-drawer-swipe":v?"true":void 0,children:[o?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:o,className:P,"aria-label":"Settings",children:s.jsx(D,{name:"settings-3",className:u})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Settings"})})]}):null,!v&&i?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:i,className:P,"aria-label":l?`Instances: ${l}`:"Instances",children:s.jsx(D,{name:"server",className:u})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:l||"Instances"})})]}):null,c?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:c,className:P,"aria-label":"Update",children:s.jsx(D,{name:"download",className:u})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Update"})})]}):null,v?null:s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,className:P,"aria-label":"Add project",children:s.jsx(D,{name:"folder-add",className:u})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Add project"})})]}),v?null:s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:r,className:P,"aria-label":"Archive",children:s.jsx(D,{name:"archive",className:u})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Archive"})})]})]}),s.jsxs("div",{className:K("flex shrink-0 items-center",v?"gap-1":"gap-1.5"),children:[s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:()=>p(S=>!S),className:P,"aria-label":"Search sessions","aria-expanded":f,children:s.jsx(D,{name:"search",className:u})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Search sessions"})})]}),s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:C,className:K(P,x&&"bg-interactive-hover text-primary"),"aria-label":x?"Exit selection":"Select sessions","aria-pressed":x,children:s.jsx(D,{name:"checkbox-multiple",className:u})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:x?"Exit selection":"Select sessions"})})]})]})]}),f?s.jsxs("div",{className:K(v?"pb-2":"pb-1"),children:[s.jsx("div",{className:"mb-1 flex items-center justify-between px-0.5 typography-micro text-muted-foreground/80",children:h?s.jsx("span",{children:y===1?`${y} match`:`${y} matches`}):s.jsx("span",{})}),s.jsxs("div",{className:"relative",children:[s.jsx(D,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),s.jsx("input",{ref:b,value:g,onChange:S=>m(S.target.value),placeholder:"Search sessions...",className:"h-8 w-full rounded-md border border-border bg-transparent pl-8 pr-8 typography-ui-label text-foreground outline-none focus-visible:ring-2 focus-visible:ring-primary/50",onKeyDown:S=>{S.key==="Escape"&&(S.stopPropagation(),h?m(""):p(!1))}}),g.length>0?s.jsx("button",{type:"button",onClick:()=>m(""),className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Clear search",children:s.jsx(D,{name:"close",className:"h-3.5 w-3.5"})}):null]})]}):null]})})}function Um(e){const t=le(o=>o.toggleSidebar),n=le(o=>o.shortcutOverrides),r=Ao(sr("toggle_sidebar",n));return s.jsxs("div",{className:"app-region-drag select-none flex h-[var(--oc-header-height,3rem)] shrink-0 items-center pr-3",children:[s.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:`var(--oc-titlebar-left-inset, ${ui})`}}),s.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:`max(0px, calc(var(--oc-titlebar-overlay-width, 0px) - var(--oc-titlebar-left-inset, ${ui})))`}}),s.jsxs("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center gap-1.5",children:[s.jsxs("button",{type:"button",onClick:e.onNewSession,className:K("group flex min-w-0 flex-1 items-center gap-1.5 pl-[3px] text-left text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",e.touchFriendly&&"min-h-11"),children:[s.jsx(D,{name:"chat-new",className:K(Qn,"text-current")}),s.jsx("span",{className:Oa,children:"New session"})]}),e.showSidebarToggle?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:t,className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Hide sessions",children:s.jsx(D,{name:"layout-left",className:"size-4"})})}),s.jsx(We,{children:s.jsx("p",{children:`Hide sessions (${r})`})})]}):null]})]})}function Po({...e}){return s.jsx(oa,{...e})}function Mo({...e}){return s.jsx(ia,{...e})}function To({className:e,positionerClassName:t,children:n,style:r,...o}){return s.jsx(aa,{children:s.jsx(la,{className:K("app-region-no-drag z-50",t),children:s.jsx(ca,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...r},className:K(wa,e),...o,children:n})})})}function Ys({className:e,...t}){return s.jsx(ua,{className:K(va,e),...t})}function jl({className:e,...t}){return s.jsx(da,{className:K(Sa,e),...t})}const Cl=500,zm=({projectId:e,worktree:t,isSelected:n,hasActive:r,onSelect:o,onClose:i,mobileVariant:l=!1})=>{const[c,u]=a.useState(!1),d=a.useRef(null),f=t.branch||(t.detached?"Detached HEAD":t.name),p=a.useCallback(()=>{d.current!==null&&(window.clearTimeout(d.current),d.current=null)},[]);a.useEffect(()=>()=>p(),[p]);const b=a.useCallback(()=>{p(),d.current=window.setTimeout(()=>{d.current=null,u(!0)},Cl)},[p]);return s.jsxs(Po,{open:c,onOpenChange:u,children:[s.jsxs(Mo,{render:s.jsx("button",{type:"button",onClick:()=>{c||o()},onTouchStart:b,onTouchMove:p,onTouchEnd:p,onTouchCancel:p,style:{touchAction:"manipulation"},className:K(dr(l,n),"pl-6"),"aria-pressed":n,title:t.path}),children:[s.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[s.jsx(D,{name:"git-branch",className:K(An(l),"text-muted-foreground")}),s.jsx("span",{className:Nn(l),children:f})]}),s.jsx("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:r?s.jsx(Ps,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null})]}),s.jsx(To,{className:"min-w-[160px]",children:s.jsxs(Ys,{disabled:!i,title:r?"Stop the active session before closing this worktree.":void 0,onClick:()=>i?.(e,t),className:"text-destructive focus:text-destructive",children:[s.jsx(D,{name:"close",className:"mr-2 h-3.5 w-3.5"}),s.jsx("span",{children:"Close worktree"})]})})]})},dr=(e,t)=>K("relative flex w-full items-center gap-1.5 rounded-xl px-3 py-2 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",e&&"py-1.5",t?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover hover:text-foreground"),$m=({project:e,label:t,isSelected:n,hasActive:r,hasWorktrees:o,worktreeError:i,isExpanded:l,canDrag:c,onSelect:u,onOpenProjectEditDialog:d,onRemoveProject:f,mobileVariant:p=!1})=>{const{listeners:b,setNodeRef:g,transform:m,transition:h,isDragging:y}=pu({id:e.id,disabled:!c}),[x,C]=a.useState(!1),v=a.useRef(null),P=a.useCallback(()=>{v.current!==null&&(window.clearTimeout(v.current),v.current=null)},[]);a.useEffect(()=>()=>P(),[P]);const S=a.useCallback(()=>{P(),v.current=window.setTimeout(()=>{v.current=null,C(!0)},Cl)},[P]);return s.jsx("div",{ref:g,style:{transform:gu.Translate.toString(m),transition:h},className:K(y&&"opacity-60"),children:s.jsxs(Po,{open:x,onOpenChange:C,children:[s.jsxs(Mo,{render:s.jsx("button",{type:"button",onClick:()=>{x||u()},onTouchStart:S,onTouchMove:P,onTouchEnd:P,onTouchCancel:P,style:{touchAction:"manipulation"},className:dr(p,n),"aria-pressed":n}),children:[s.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[s.jsx("span",{className:K("inline-flex size-4 shrink-0 items-center justify-center",c&&"touch-none select-none cursor-grab active:cursor-grabbing"),"aria-label":c?`Reorder ${t}`:void 0,...c?b:{},children:s.jsx(D,{name:"folder",className:K(An(p),"text-muted-foreground")})}),s.jsx("span",{className:Nn(p),children:t})]}),s.jsxs("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:[r?s.jsx(Ps,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null,i?s.jsx("span",{title:i,"aria-label":"Worktree discovery failed",children:s.jsx(D,{name:"error-warning",className:"size-4 text-[var(--status-warning)]"})}):null,o?s.jsx(D,{name:l?"arrow-down-s":"arrow-right-s",className:"size-4 text-muted-foreground"}):null]})]}),s.jsxs(To,{className:"min-w-[160px]",children:[s.jsxs(Ys,{onClick:()=>d(e.id),children:[s.jsx(D,{name:"edit",className:"mr-2 h-3.5 w-3.5"}),s.jsx("span",{children:"Edit folder"})]}),s.jsx(jl,{}),s.jsxs(Ys,{onClick:()=>f(e.id),className:"text-destructive focus:text-destructive",children:[s.jsx(D,{name:"close",className:"mr-2 h-3.5 w-3.5"}),s.jsx("span",{children:"Close folder"})]})]})]})})},Km=({projects:e,selectedProjectId:t,selectedWorktreePath:n=null,worktreesByProject:r=new Map,worktreeErrorsByProject:o=new Map,onSelectProject:i,onSelectWorktree:l,onCloseWorktree:c,onOpenDirectoryDialog:u,onOpenProjectEditDialog:d,onRemoveProject:f,hasActiveSessionByProject:p,activeDirectoriesByProject:b,homeDirectory:g,className:m,mobileVariant:h=!1})=>{const y=t===null,x=ht(S=>S.reorderProjects),C=e.length>1,v=sa(qr(mu,{activationConstraint:{distance:8}}),qr(hu,{activationConstraint:{delay:200,tolerance:6}})),P=a.useCallback(S=>{const{active:A,over:j}=S;if(!j||A.id===j.id)return;const w=ht.getState().projects,N=w.findIndex(L=>L.id===A.id),T=w.findIndex(L=>L.id===j.id);N<0||T<0||x(N,T)},[x]);return s.jsxs("div",{className:K("select-none px-3 pt-1 pb-2 border-b border-border/40 space-y-0.5",m),children:[s.jsx("button",{type:"button",onClick:()=>i(null),className:dr(h,y),"aria-pressed":y,children:s.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[s.jsx(D,{name:"chat-history",className:An(h)}),s.jsx("span",{className:Nn(h),children:"All sessions"})]})}),s.jsx(na,{sensors:v,collisionDetection:ra,onDragEnd:P,children:s.jsx(du,{items:e.map(S=>S.id),strategy:fu,children:e.map(S=>{const A=t===S.id,j=A&&!n,w=r.get(S.normalizedPath)??[],N=pr(S.label?.trim()||Xs(S.normalizedPath,g)||S.normalizedPath),T=b?.get(S.id),L=Ae(S.normalizedPath)?.toLowerCase()??"",$=L?T?.has(L)??!1:!1,z=(T?.size??0)>0,W=p?.(S.id)??!1,F=b?A?$:z:W;return s.jsxs(a.Fragment,{children:[s.jsx($m,{project:S,label:N,isSelected:j,hasActive:F,hasWorktrees:w.length>0,worktreeError:o.get(S.normalizedPath),isExpanded:A,canDrag:C,onSelect:()=>i(S.id),onOpenProjectEditDialog:d,onRemoveProject:f,mobileVariant:h}),A?w.map(R=>{const E=n===R.path,I=Ae(R.path)?.toLowerCase()??"",M=I?T?.has(I)??!1:!1,G=b?M:!1;return s.jsx(zm,{projectId:S.id,worktree:R,isSelected:E,hasActive:G,onSelect:()=>l?.(S.id,R.path),onClose:c,mobileVariant:h},R.path)}):null]},S.id)})})}),s.jsxs("button",{type:"button",onClick:u,className:dr(h,!1),children:[s.jsx(D,{name:"add",className:An(h)}),s.jsx("span",{className:Nn(h),children:"Add folder"})]})]})},Pr="inline-flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50";function Wm({onOpenSettings:e,onOpenShortcuts:t,onOpenAbout:n,onOpenUpdate:r,showRuntimeButtons:o=!0,showUpdateButton:i=!0}){return!o&&!i?null:s.jsxs("div",{className:"flex shrink-0 items-center justify-start gap-1 px-3 py-2",children:[o?s.jsxs(s.Fragment,{children:[s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:e,className:Pr,"aria-label":"Settings",children:s.jsx(D,{name:"settings-3",className:"h-4.5 w-4.5"})})}),s.jsx(We,{side:"top",sideOffset:4,children:s.jsx("p",{children:"Settings"})})]}),s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:t,className:Pr,"aria-label":"Shortcuts",children:s.jsx(D,{name:"command",className:"h-4.5 w-4.5"})})}),s.jsx(We,{side:"top",sideOffset:4,children:s.jsx("p",{children:"Shortcuts"})})]}),s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,className:Pr,"aria-label":"About PiChamber",children:s.jsx(D,{name:"information",className:"h-4.5 w-4.5"})})}),s.jsx(We,{side:"top",sideOffset:4,children:s.jsx("p",{children:"About PiChamber"})})]})]}):null,i?s.jsx(Ee,{type:"button",variant:"default",size:"xs",className:"ml-auto border-[var(--status-info-border)] bg-[var(--status-info-background)] text-[var(--status-info)] hover:bg-[var(--status-info-background)]/80 hover:text-[var(--status-info)] dark:border-[var(--status-info-border)] dark:bg-[var(--status-info-background)] dark:hover:bg-[var(--status-info-background)]/80",onClick:r,children:"Update"}):null]})}const Gm=(e,t)=>pr(e.label?.trim()||Xs(e.normalizedPath,t)||e.normalizedPath);function Hm(e){zt("ui.sidebar_projects_list.render");const t=a.useRef(new Map),n=a.useRef(e.getOrderedGroups);n.current!==e.getOrderedGroups&&(n.current=e.getOrderedGroups,t.current.clear());const r=(p,b)=>{const g=t.current,m=g.get(p);if(m&&m.groups===b)return m.ordered;const h=e.getOrderedGroups(p,b);if(g.set(p,{groups:b,ordered:h}),g.size>256){const y=g.keys().next().value;y!==void 0&&g.delete(y)}return h},o=a.useRef(null),i=a.useMemo(()=>{if(!e.isAllFoldersView)return[];const p=[],b=e.allFoldersOnlySection?[e.allFoldersOnlySection,...e.sectionsForRender]:e.sectionsForRender;for(const g of b){const m=Gm(g.project,e.homeDirectory);for(const h of g.groups)if(!h.isArchivedBucket)for(const y of h.sessions){const x=!!e.pinnedSessionIds?.has(y.session.id),C=y.session.time?.updated||y.session.time?.created||0;p.push({node:y,project:g.project,projectLabel:m,isPinned:x,timestamp:C,globalSession:g===e.allFoldersOnlySection})}}return p.sort((g,m)=>g.isPinned!==m.isPinned?g.isPinned?-1:1:m.timestamp-g.timestamp),p},[e.allFoldersOnlySection,e.isAllFoldersView,e.sectionsForRender,e.homeDirectory,e.pinnedSessionIds]),[l,c]=a.useState(30);a.useEffect(()=>{c(30)},[e.hasSessionSearchQuery]);const u=i.slice(0,l),d=i.length-u.length;if(e.sharedSessionsOnly)return s.jsx(Cs,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:K("pt-2 pb-1",e.mobileVariant&&"pb-32"),children:s.jsxs("div",{className:"space-y-1 px-3",children:[e.topContent,e.hasSharedSessions?null:e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState]})});const f=e.isAllFoldersView&&!!e.allFoldersOnlySection;return e.projectSections.length===0&&!f?s.jsx(Cs,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:K("pt-2 pb-1",e.mobileVariant&&"pb-32"),children:s.jsxs("div",{className:"space-y-1 px-3",children:[e.topContent,e.emptyState]})}):e.sectionsForRender.length===0&&!f?s.jsx(Cs,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:K("pt-2 pb-1",e.mobileVariant&&"pb-32"),children:s.jsx("div",{className:"space-y-1 px-3",children:e.searchEmptyState})}):s.jsx("div",{className:"relative flex min-h-0 flex-1",children:s.jsx(Cs,{ref:o,useScrollShadow:!0,hideTopScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:K("oc-sidebar-scroller pt-2 pb-1 [overflow-anchor:none]",e.mobileVariant&&"pb-32"),children:s.jsxs("div",{className:"space-y-1 px-3",children:[e.topContent,e.showOnlyMainWorkspace?s.jsx("div",{className:"space-y-[0.6rem]",children:(()=>{const p=e.sectionsForRender.find(h=>h.project.id===e.activeProjectId)??e.sectionsForRender[0];if(!p)return e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState;const b=p.groups.find(h=>h.isMain&&h.sessions.length>0)??p.groups.find(h=>h.sessions.length>0)??p.groups.find(h=>h.isMain)??p.groups[0];if(!b)return s.jsx(Ns,{icon:"chat-new",onClick:()=>e.openNewSessionDraft({selectedProjectId:p.project.id,directoryOverride:p.project.normalizedPath}),children:"New session"});const g=p.groups.find(h=>h.isArchivedBucket);return[b,...g&&g.id!==b.id?[g]:[]].map(h=>{const y=`${p.project.id}:${h.id}`,x=h.id===b.id;return s.jsx(a.Fragment,{children:e.renderGroupSessions(h,y,p.project.id,x,null,!0,o)},y)})})()}):e.isAllFoldersView&&e.renderSessionNode?s.jsx("div",{children:i.length===0?e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState:s.jsxs(s.Fragment,{children:[u.map(({node:p,project:b,projectLabel:g,globalSession:m})=>{const h=p.session.directory??b.normalizedPath;return s.jsx(a.Fragment,{children:e.renderSessionNode(p,0,h,b.id,!1,{projectLabel:g,showFolderLabel:!0,globalSession:m},"project")},p.session.id)}),d>0?s.jsx(Ns,{icon:"arrow-down-s",onClick:()=>c(p=>p+30),children:d===1?"Show 1 more session":`Show ${d} more sessions`}):null,l>30&&i.length>30?s.jsx(Ns,{icon:"arrow-up-s",onClick:()=>c(30),children:"Show fewer sessions"}):null]})}):s.jsx("div",{children:e.sectionsForRender.map(p=>{const b=p.project.id,g=r(b,p.groups),m=g.find(y=>y.isMain)??null,h=m?g.filter(y=>y.id!==m.id):g;return s.jsxs("div",{children:[m?e.renderGroupSessions(m,`${b}:${m.id}`,b,!0,null,void 0,o):null,h.map(y=>{const x=`${b}:${y.id}`,C=g.length===1;return s.jsx(a.Fragment,{children:e.renderGroupSessions(y,x,b,C,null,void 0,o)},y.id)})]},b)})})]})})})}const qm=a.memo(Hm);let wo=!1;const vo=new Set;let Fi=!1;function Ym(){for(const e of vo)e()}function Fo(e){wo!==e&&(wo=e,Ym())}function Qm(e){e.key==="Shift"&&Fo(!0)}function Vm(e){e.key==="Shift"&&Fo(!1)}function Jm(){Fo(!1)}function Xm(){Fi||typeof window>"u"||(Fi=!0,window.addEventListener("keydown",Qm),window.addEventListener("keyup",Vm),window.addEventListener("blur",Jm))}function Zm(e){return Xm(),vo.add(e),()=>{vo.delete(e)}}function ep(){return wo}function tp(){return!1}function sp(){return Ne.useSyncExternalStore(Zm,ep,tp)}const np=a.memo(function({archiveLabel:t,deleteLabel:n,buttonSizeClass:r,iconSizeClass:o,onPointerDown:i,onMouseDown:l,onArchive:c,onDelete:u}){const d=sp(),f=d?n:t,p=b=>{if(d||b.shiftKey){u(b);return}c(b)};return s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",className:K("inline-flex items-center justify-center rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",d?"text-destructive hover:text-destructive":"text-muted-foreground hover:text-foreground",r),"aria-label":f,onPointerDown:i,onMouseDown:l,onClick:p,onKeyDown:b=>b.stopPropagation(),children:s.jsx(D,{name:d?"delete-bin":"archive",className:o})})}),s.jsx(We,{side:"left",sideOffset:8,children:f})]})}),rp=a.memo(function({open:t,onOpenChange:n,descendantCount:r,exportIncludeSubtasks:o,setExportIncludeSubtasks:i,onExport:l}){return s.jsx(es,{open:t,onOpenChange:n,children:s.jsxs(ts,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(xs,{children:[s.jsx(as,{children:"Export Markdown"}),s.jsx(ys,{children:r===1?`This session has ${r} sub-agent task. Include it in the export?`:`This session has ${r} sub-agent tasks. Include them in the export?`})]}),s.jsxs("label",{className:"flex items-center gap-2 typography-ui-label cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:o,onChange:c=>i(c.target.checked),className:"h-4 w-4 rounded border-border accent-primary"}),"Include sub-agent tasks"]}),s.jsxs(Ds,{children:[s.jsx(Ee,{type:"button",onClick:()=>n(!1),variant:"outline",size:"sm",children:"Cancel"}),s.jsx(Ee,{type:"button",onClick:()=>{n(!1),l(o)},size:"sm",children:"Export"})]})]})})});function op(e,t){const{session:n,sessionTitle:r,sessionDirectory:o,isPinnedSession:i,archivedBucket:l,isElectron:c,pendingRenameRef:u,handleCopySessionId:d,togglePinnedSession:f,handleExportSession:p,handleOpenMiniChatWindow:b,handleDeleteSession:g,handleRestoreSession:m}=e,{Item:h,Separator:y}=t;return s.jsxs(s.Fragment,{children:[s.jsxs(h,{onClick:()=>{u.current={id:n.id,title:r}},className:"[&>svg]:mr-1",children:[s.jsx(D,{name:"pencil-ai",className:"mr-1 h-4 w-4"}),"Rename"]}),s.jsxs(h,{onClick:()=>d(n.id),className:"[&>svg]:mr-1",children:[s.jsx(D,{name:"file-copy",className:"mr-1 h-4 w-4"}),"Copy session ID"]}),s.jsxs(h,{onClick:()=>o&&f({directory:o,sessionId:n.id}),className:"[&>svg]:mr-1",children:[i?s.jsx(D,{name:"unpin",className:"mr-1 h-4 w-4"}):s.jsx(D,{name:"pushpin",className:"mr-1 h-4 w-4"}),i?"Unpin session":"Pin session"]}),s.jsxs(h,{onClick:()=>{p()},className:"[&>svg]:mr-1",children:[s.jsx(D,{name:"download",className:"mr-1 h-4 w-4"}),"Export Markdown"]}),c?s.jsxs(h,{disabled:!o,onClick:b,className:"[&>svg]:mr-1",children:[s.jsx(D,{name:"window",className:"mr-1 h-4 w-4"}),s.jsx("span",{className:"truncate",children:"Open in Mini Chat Window"})]}):null,s.jsx(y,{}),l?null:s.jsxs(h,{className:"[&>svg]:mr-1",onClick:()=>g(n,{archivedBucket:l}),children:[s.jsx(D,{name:"inbox-archive",className:"mr-1 h-4 w-4"}),"Archive"]}),l?s.jsxs(h,{className:"[&>svg]:mr-1",onClick:()=>m(n),children:[s.jsx(D,{name:"inbox-unarchive",className:"mr-1 h-4 w-4"}),"Restore"]}):null,s.jsxs(h,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>g(n,{archivedBucket:l,hardDelete:!0}),children:[s.jsx(D,{name:"delete-bin",className:"mr-1 h-4 w-4"}),"Delete"]})]})}function ip(e){const{renamingFolderId:t,editingIdRef:n}=e;return s.jsx(aa,{children:s.jsx(la,{className:"app-region-no-drag z-50",children:s.jsx(ca,{"data-slot":"dropdown-menu-content",finalFocus:()=>!(t||n.current),style:{color:"var(--surface-elevated-foreground)"},className:K(wa,"min-w-[180px]"),children:op(e,{Item:({className:r,...o})=>s.jsx(ua,{className:K(va,r),...o}),Separator:({className:r,...o})=>s.jsx(da,{className:K(Sa,r),...o})})})})})}const Mr=new WeakMap,ap=e=>{if(typeof window>"u")return;const t=e.closest("[data-session-row]"),n=t?.closest(".overlay-scrollbar-container");if(!t||!n)return;Mr.get(n)?.();const r=t.getBoundingClientRect().top;let o=3,i=!1,l=null;const c=()=>{i=!0,l!==null&&window.cancelAnimationFrame(l),l=null,Mr.delete(n),n.removeEventListener("wheel",c),n.removeEventListener("touchstart",c)},u=()=>{if(i||!t.isConnected||!n.isConnected){c();return}const d=t.getBoundingClientRect().top-r;if(Math.abs(d)>.5&&(n.scrollTop+=d,zt("ui.sidebar.selection_scroll_anchor_adjustment")),o-=1,o<=0){c();return}l=window.requestAnimationFrame(u)};n.addEventListener("wheel",c,{passive:!0}),n.addEventListener("touchstart",c,{passive:!0}),Mr.set(n,c),l=window.requestAnimationFrame(u)};function lp(e){if(typeof e!="number"||!Number.isFinite(e))return"";const t=new Date(e);if(Number.isNaN(t.getTime()))return"";const n=t.toLocaleString("en-US",{month:"short"}),r=t.getDate(),o=t.getFullYear(),i=String(t.getHours()).padStart(2,"0"),l=String(t.getMinutes()).padStart(2,"0");return`${n} ${r}, ${o}, ${i}:${l}`}function cp(e){if(e.info.role==="user")return"";const t=typeof e.info.providerID=="string"?e.info.providerID.trim():"",n=typeof e.info.modelID=="string"?e.info.modelID.trim():"";return t&&n?`${t}/${n}`:n||t}function up(e){const t=e.info.role==="user"?"User":"Assistant",n=lp(e.info.time?.created),r=cp(e),o=n&&r?`${n} (${r})`:n||r;return o?`**${t}**
|
|
21
|
+
|
|
22
|
+
*${o}*`:`**${t}**`}function dp(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join("")}function kl(e){const t=up(e),n=dp(e.parts).trim();return n?`${t}
|
|
23
|
+
|
|
24
|
+
${n}`:""}function Al(e,t){const n="#".repeat(Math.min(t+1,6)),r=e.agent?` — ${e.agent}`:"",o=`${n} Sub-agent: ${e.title}${r}
|
|
25
|
+
|
|
26
|
+
---
|
|
27
|
+
|
|
28
|
+
`,i=e.records.map(kl).filter(Boolean).join(`
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
`),l=[o+i];for(const c of e.children)l.push(Al(c,t+1));return l.join(`
|
|
33
|
+
|
|
34
|
+
---
|
|
35
|
+
|
|
36
|
+
`)}function Nl(e,t,n){const r=t?.trim()||"Session",o=new Date().toISOString().split("T")[0],i=`# ${r}
|
|
37
|
+
|
|
38
|
+
*Exported on ${o}*
|
|
39
|
+
|
|
40
|
+
---
|
|
41
|
+
|
|
42
|
+
`,l=e.map(kl).filter(Boolean).join(`
|
|
43
|
+
|
|
44
|
+
---
|
|
45
|
+
|
|
46
|
+
`);let c=i+l;if(n&&n.length>0){const u=n.map(d=>Al(d,1)).join(`
|
|
47
|
+
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
`);c+=`
|
|
51
|
+
|
|
52
|
+
---
|
|
53
|
+
|
|
54
|
+
`+u}return c}function Il(e,t){const n=new Blob([e],{type:"text/markdown;charset=utf-8"}),r=URL.createObjectURL(n),o=document.createElement("a");o.href=r,o.download=t,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(r)}async function El(e,t){const n=await Cd(t,e);return n||null}async function fp(e){const t=Ra()?.files;if(t?.revealPath)try{return!!(await t.revealPath(e))?.success}catch{return!1}return await kd(e)?!0:Da(e)}function hp(){return Ad()}function Rl(e){const r=(e?.trim()||"session").normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"").slice(0,60)||"session",o=new Date().toISOString().split("T")[0];return`${r}-${o}.md`}const fr=e=>{const t=[],n=r=>{r.children.forEach(o=>{t.push(o.session.id),n(o)})};return n(e),t};function mp(e,t){const[n,r]=a.useState(!1),[o,i]=a.useState(!0),l=e.session,c=a.useMemo(()=>fr(e).length,[e]),u=a.useCallback(async b=>{const g=[];let m=0;for(const h of b)try{if(!t)throw new Error("Session directory is required for export");const y=[],x=h.session.title||"Untitled Sub-agent",C=typeof h.session.agent=="string"?h.session.agent:void 0,v=await u(h.children);m+=v.skipped,g.push({title:x,agent:C,records:y,children:v.children})}catch{m+=fr(h).length+1}return{children:g,skipped:m}},[t]),d=a.useCallback(b=>{b<=0||ie.warning(b===1?`Exported session, but skipped ${b} sub-agent task that could not be loaded.`:`Exported session, but skipped ${b} sub-agent tasks that could not be loaded.`)},[]),f=a.useCallback(async b=>{if(!t){ie.error("Nothing to export");return}const g=[];if(g.length===0){ie.error("Nothing to export");return}let m,h=0;if(b&&e.children.length>0){const v=await u(e.children);m=v.children,h=v.skipped}const y=Nl(g,l.title??null,m),x=Rl(l.title??null),C=await El(y,x);if(C){ie.success("Session exported",{action:{label:hp(),onClick:()=>{fp(C).then(v=>{v||ie.error("Failed to reveal path")})}}}),d(h);return}Il(y,x),ie.success("Session exported"),d(h)},[u,e.children,l.title,t,d]),p=a.useCallback(async()=>{if(e.children.length>0){i(!0),r(!0);return}await f(!1)},[f,e.children.length]);return{exportDialogOpen:n,setExportDialogOpen:r,exportIncludeSubtasks:o,setExportIncludeSubtasks:i,descendantCount:c,handleExportSession:p,doExportSession:f}}const pp=(e,t)=>{if(!t)return Array.from(e);const n=[],r=new Set;for(const o of e){r.has(o)||(r.add(o),n.push(o));const i=t.get(o);if(i)for(const l of i)r.has(l)||(r.add(l),n.push(l))}return n},ut=Ts()((e,t)=>({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null,enable:()=>{t().enabled||e({enabled:!0})},disable:()=>{e({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null})},toggleMode:()=>{t().enabled?e({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null}):e({enabled:!0})},toggleSelected:(n,r,o)=>{const i=t(),l=new Set(i.selectedIds);let c=i.scopeKey,u=i.anchorId;r!==null&&i.scopeKey!==null&&r!==i.scopeKey?(l.clear(),c=r,u=null):c===null&&r!==null&&(c=r);const f=o&&o.length>0?[n,...o]:[n];if(l.has(n)){for(const b of f)l.delete(b);u===n&&(u=null)}else{for(const b of f)l.add(b);u=n}l.size===0?e({selectedIds:l,scopeKey:null,anchorId:null}):e({selectedIds:l,scopeKey:c,anchorId:u})},setRange:(n,r,o,i,l)=>{const c=t();if(o.length===0)return;const u=n&&o.includes(n)?n:o[0],d=o.indexOf(u),f=o.indexOf(r);if(d<0||f<0)return;const[p,b]=d<=f?[d,f]:[f,d],g=o.slice(p,b+1),m=pp(g,l),y=i!==null&&c.scopeKey!==null&&i!==c.scopeKey?new Set:new Set(c.selectedIds);for(const x of m)y.add(x);e({selectedIds:y,scopeKey:i??c.scopeKey,anchorId:u})},replaceAll:(n,r)=>{if(n.length===0){e({selectedIds:new Set,scopeKey:null,anchorId:null});return}e({selectedIds:new Set(n),scopeKey:r,anchorId:n[0]??null})},clear:()=>{e({selectedIds:new Set,scopeKey:null,anchorId:null})},removeMany:n=>{const r=t();if(r.selectedIds.size===0||n.length===0)return;const o=new Set(r.selectedIds);for(const i of n)o.delete(i);o.size!==r.selectedIds.size&&(o.size===0?e({selectedIds:o,scopeKey:null,anchorId:null}):e({selectedIds:o}))}})),Li=e=>Ae(e.session.directory??null),gp=(e,t)=>(e?.projectLabel??null)===(t?.projectLabel??null)&&(e?.branchLabel??null)===(t?.branchLabel??null)&&(e?.showFolderLabel??!1)===(t?.showFolderLabel??!1),bp=e=>{if(!e.openSidebarMenuKey)return null;const t=e.archivedBucket?"archived":"active",n=`${e.renderContext??"project"}:${t}:`;return e.openSidebarMenuKey.startsWith(n)?e.openSidebarMenuKey.slice(n.length):null},Gn=e=>e.menuOpenSessionId??bp(e),Hn=(e,t,n)=>t?n.has(e.node.session.id)?!0:os(e.node,t):!1,So=(e,t,n,r,o)=>{if(e.session.id!==t.session.id)return!0;const i=o(e);if(n.has(i)!==r.has(i)||e.children.length!==t.children.length)return!0;for(let l=0;l<e.children.length;l+=1)if(So(e.children[l],t.children[l],n,r,o))return!0;return!1},xp=(e,t)=>{if(e.hasSessionSearchQuery||t.hasSessionSearchQuery)return!1;const n=e.archivedBucket?"archived":"active",r=t.archivedBucket?"archived":"active";return So(e.node,t.node,e.expandedParents,t.expandedParents,o=>`${e.renderContext??"project"}:${n}:${o.session.id}`)||So(e.node,t.node,e.expandedParents,t.expandedParents,o=>`${t.renderContext??"project"}:${r}:${o.session.id}`)},yp=(e,t)=>{if(e.node.session.id!==t.node.session.id||e.node.session!==t.node.session||e.depth!==t.depth||e.groupDirectory!==t.groupDirectory||e.projectId!==t.projectId||e.archivedBucket!==t.archivedBucket||(e.renderContext??"project")!==(t.renderContext??"project")||e.mobileVariant!==t.mobileVariant||e.alwaysShowActions!==t.alwaysShowActions||e.allowQuickArchiveAction!==t.allowQuickArchiveAction||e.hasSessionSearchQuery!==t.hasSessionSearchQuery||e.normalizedSessionSearchQuery!==t.normalizedSessionSearchQuery||e.nodeStructureKey!==t.nodeStructureKey||Li(e.node)!==Li(t.node)||!gp(e.secondaryMeta,t.secondaryMeta)||e.pinnedSessionIds!==t.pinnedSessionIds&&ll(e.node,t.node,e.pinnedSessionIds,t.pinnedSessionIds,e.groupDirectory,t.groupDirectory)||e.expandedParents!==t.expandedParents&&xp(e,t)||e.editingId!==t.editingId&&(Hn(e,e.editingId,e.subtreeContainsEditing)||Hn(t,t.editingId,t.subtreeContainsEditing))||e.editTitle!==t.editTitle&&(Hn(e,e.editingId,e.subtreeContainsEditing)||Hn(t,t.editingId,t.subtreeContainsEditing))||e.copiedSessionId!==t.copiedSessionId&&(os(e.node,e.copiedSessionId)||os(t.node,t.copiedSessionId)))return!1;if(e.openSidebarMenuKey!==t.openSidebarMenuKey){const n=Gn(e),r=Gn(t);if(os(e.node,n)||os(t.node,r))return!1}if(e.renamingFolderId!==t.renamingFolderId){const n=Gn(e),r=Gn(t);if(os(e.node,n)||os(t.node,r))return!1}return e.setEditingId===t.setEditingId&&e.setEditTitle===t.setEditTitle&&e.handleSaveEdit===t.handleSaveEdit&&e.handleCancelEdit===t.handleCancelEdit&&e.toggleParent===t.toggleParent&&e.handleSessionSelect===t.handleSessionSelect&&e.handleSessionDoubleClick===t.handleSessionDoubleClick&&e.togglePinnedSession===t.togglePinnedSession&&e.handleShareSession===t.handleShareSession&&e.handleCopyShareUrl===t.handleCopyShareUrl&&e.handleCopySessionId===t.handleCopySessionId&&e.handleUnshareSession===t.handleUnshareSession&&e.setOpenSidebarMenuKey===t.setOpenSidebarMenuKey&&e.getFoldersForScope===t.getFoldersForScope&&e.getSessionFolderId===t.getSessionFolderId&&e.removeSessionFromFolder===t.removeSessionFromFolder&&e.addSessionToFolder===t.addSessionToFolder&&e.createFolderAndStartRename===t.createFolderAndStartRename&&e.handleDeleteSession===t.handleDeleteSession&&e.handleRestoreSession===t.handleRestoreSession&&e.renderSessionNode===t.renderSessionNode};function wp({node:e,groupDirectory:t,projectId:n,secondaryMeta:r,pinnedSessionIds:o,expandedParents:i,expansionKey:l,hasSessionSearchQuery:c}){const u=e.session,d=Ae(u.directory??null)??Ae(t??null),f=Me(fe=>fe.currentSessionId===u.id),p=ja(d),b=_u(d),g=ht(a.useCallback(fe=>{if(r?.projectLabel||!n)return null;const he=fe.projects.find(q=>q.id===n);return he?he.label?.trim()||Xs(Ae(he.path)??he.path,null)||he.path:null},[n,r?.projectLabel])),m=r?.projectLabel??(g?pr(g):null),h=e.worktree,y=r?.branchLabel??h?.branch??(p&&p!=="HEAD"?p:null),x=y,C=b===!0||!!(y||h),v=e.children.length,P=u.agent,S=h?.branch?.trim()||y?.trim()||null,A=Ae(h?.path??d),j=a.useMemo(()=>S&&A?En(A,S):null,[S,A]),w=ul(j);dl(A,S);const N=w?`var(--pr-${w.visualState})`:void 0,T=a.useMemo(()=>{if(!w)return null;switch(w.visualState){case"merged":return"Merged";case"open":return w.canMerge===!0||w.mergeableState==="clean"||w.checks?.state==="success"?"Ready to merge":"PR open";case"blocked":return w.mergeableState==="dirty"?"Merge conflicts":"Merge blocked";case"draft":return"Draft PR";case"closed":return"Closed";default:return null}},[w]),L=n??d??null,$=ut(fe=>fe.enabled),z=ut(a.useCallback(fe=>fe.selectedIds.has(u.id),[u.id])),W=ut(fe=>fe.toggleSelected),F=ut(fe=>fe.setRange),E=Ca(u.id)?.type??"idle",I=E==="busy"||E==="retry",M=Uu(u.id,I),G=ps(u),X=e.children.length>0,U=zu(o,d,u.id),ve=c?!0:i.has(l),Re=$u(u.id)>0,Oe=u.time?.updated||u.time?.created||Date.now(),Q=Yd(Oe),_=a.useMemo(()=>rl(e.forkColorId),[e.forkColorId]),H=a.useMemo(()=>Rh(e.forkColorId,{active:f||z}),[e.forkColorId,f,z]),J=r?.globalSession&&!f&&!z?"var(--surface-elevated)":null,ne=H??J;return{session:u,sessionDirectory:d,prDirectory:A,prBranch:S,prNumber:w?.number??null,isActive:f,tooltipProjectLabel:m,tooltipBranchLabel:x,isGitRepo:C,subtaskCount:v,agentName:P,prSummary:w,prIconColor:N,prStatusLabel:T,selectionScopeKey:L,selectionModeEnabled:$,isRowSelected:z,toggleRowSelected:W,setRowRange:F,isStreaming:I,hasActivityDuration:M,sessionTitle:G,hasChildren:X,isPinnedSession:U,isExpanded:ve,needsAttention:Re,sessionCompactUpdatedLabel:Q,forkSolid:_,rowBackground:ne}}const vp=({prDirectory:e,prNumber:t,prStatusLabel:n,prIconColor:r})=>{const o=xa(e);if(!e||!o)return s.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",style:r?{color:r}:void 0,title:n?`PR #${t} — ${n}`:`PR #${t}`,children:[s.jsx(D,{name:"git-pull-request",className:"size-3.5 shrink-0"}),s.jsxs("span",{children:["#",t]})]});const i=l=>{l.stopPropagation(),l.preventDefault(),Sl(e,o,t)};return s.jsxs("span",{role:"button",tabIndex:0,onClick:i,onDoubleClick:l=>{l.stopPropagation(),l.preventDefault()},onKeyDown:l=>{if(!(l.key!=="Enter"&&l.key!==" ")){if(l.repeat){l.stopPropagation(),l.preventDefault();return}i(l)}},className:"inline-flex shrink-0 cursor-pointer items-center gap-1 rounded hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",style:r?{color:r}:void 0,title:n?`PR #${t} — ${n}. Open in Pull requests`:`Open PR #${t} in Pull requests`,"aria-label":n?`Open pull request #${t}, ${n}, in Pull requests`:`Open pull request #${t} in Pull requests`,children:[s.jsx(D,{name:"git-pull-request",className:"size-3.5 shrink-0"}),s.jsxs("span",{children:["#",t]})]})};function Sp(e){zt("ui.sidebar_session_node.render");const{node:t,depth:n=0,groupDirectory:r,projectId:o,archivedBucket:i=!1,pinnedSessionIds:l,expandedParents:c,hasSessionSearchQuery:u,normalizedSessionSearchQuery:d,editingId:f,setEditingId:p,editTitle:b,setEditTitle:g,handleSaveEdit:m,handleCancelEdit:h,toggleParent:y,handleSessionSelect:x,handleSessionDoubleClick:C,togglePinnedSession:v,handleShareSession:P,copiedSessionId:S,handleCopyShareUrl:A,handleCopySessionId:j,handleUnshareSession:w,openSidebarMenuKey:N,setOpenSidebarMenuKey:T,renamingFolderId:L,getFoldersForScope:$,getSessionFolderId:z,removeSessionFromFolder:W,addSessionToFolder:F,createFolderAndStartRename:R,handleDeleteSession:E,handleRestoreSession:I,alwaysShowActions:M,allowQuickArchiveAction:G,renderSessionNode:X,secondaryMeta:U,renderContext:ve="project",subtreeContainsEditing:Z,menuOpenSessionId:Re,childRenderExtrasFor:Oe}=e,Q=a.useMemo(()=>Pa(),[]),_=!i&&G,H=a.useRef(!1),J=a.useRef(f);J.current=f;const ne=a.useRef(null),fe=a.useRef(m);fe.current=m;const[he,q]=a.useState(b),te=a.useRef(he);te.current=he;const ae=a.useRef(null),je=a.useRef(null),Ge=`${ve}:${i?"archived":"active"}:${t.session.id}`,{session:B,sessionDirectory:re,prDirectory:pe,prNumber:ge,isActive:ce,tooltipProjectLabel:Fe,tooltipBranchLabel:ye,isGitRepo:ee,subtaskCount:xe,agentName:ue,prSummary:we,prIconColor:ze,prStatusLabel:qe,selectionScopeKey:De,selectionModeEnabled:Ye,isRowSelected:se,toggleRowSelected:Le,setRowRange:ct,isStreaming:et,hasActivityDuration:Qe,sessionTitle:yt,hasChildren:it,isPinnedSession:ss,isExpanded:Mt,needsAttention:at,sessionCompactUpdatedLabel:nt,forkSolid:wt,rowBackground:tt}=wp({node:t,groupDirectory:r,projectId:o,secondaryMeta:U,pinnedSessionIds:l,expandedParents:c,expansionKey:Ge,hasSessionSearchQuery:u}),{exportDialogOpen:Tt,setExportDialogOpen:$t,exportIncludeSubtasks:ls,setExportIncludeSubtasks:Ct,descendantCount:Ft,handleExportSession:ke,doExportSession:He}=mp(t,re),[Ce,Te]=a.useState(!1),Be=a.useCallback(()=>{re&&vn("desktop_open_session_mini_chat_window",{sessionId:B.id,directory:re,apiBaseUrl:to(),clientToken:eo()}).catch(de=>{console.warn("[session-sidebar] failed to open mini chat window",de)})},[B.id,re]);a.useEffect(()=>{if(f!==B.id)return;const de=ot=>{const ds=ot.target?.closest?.(`[data-session-rename-form="${CSS.escape(B.id)}"]`);je.current&&!ds&&fe.current(te.current)};return document.addEventListener("mousedown",de),()=>document.removeEventListener("mousedown",de)},[f,B.id]),a.useLayoutEffect(()=>{if(f!==B.id){ae.current===B.id&&(ae.current=null);return}ae.current!==B.id&&(ae.current=B.id,q(b))},[f,b,B.id]);const pt=!et&&at&&!ce,rt=et&&Qe,kt=ss,vt=s.jsx(D,{name:"pushpin",className:"h-3 w-3 flex-shrink-0 text-primary","aria-label":"Pinned session"}),gt=kt?s.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:vt}):null,Ze=it?s.jsx("button",{type:"button",onClick:de=>{de.stopPropagation(),y(Ge)},onKeyDown:de=>{(de.key==="Enter"||de.key===" ")&&(de.preventDefault(),de.stopPropagation(),y(Ge))},className:"inline-flex h-4 w-4 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-label":Mt?"Collapse subsessions":"Expand subsessions",children:Mt?s.jsx(D,{name:"arrow-down-s",className:"h-3 w-3"}):s.jsx(D,{name:"arrow-right-s",className:"h-3 w-3"})}):null,cs=de=>{if(!de&&ne.current){const{id:ot,title:It}=ne.current;ne.current=null,p(ot),g(It)}},ws=de=>{Te(de)},vs=de=>{de.preventDefault(),de.stopPropagation()},us=de=>{de.preventDefault(),de.stopPropagation()},At=de=>{de.preventDefault(),de.stopPropagation(),T(null),E(B,{archivedBucket:i})},Kt=de=>{de.preventDefault(),de.stopPropagation(),T(null),E(B,{archivedBucket:i,hardDelete:!0,skipConfirm:!0})},bt=de=>{if(H.current){H.current=!1;return}if(Ye){if(de?.preventDefault(),de?.stopPropagation(),de?.shiftKey){const It=(typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[]).map(Gt=>Gt.getAttribute("data-session-row")).filter(Gt=>typeof Gt=="string"&&Gt.length>0),ds=ut.getState().anchorId,Lt=new Map;Lt.set(B.id,fr(t)),ct(ds,B.id,It,De,Lt);return}Le(B.id,De,fr(t));return}de?.currentTarget&&ap(de.currentTarget),x(B.id,re)},on=de=>{de.defaultPrevented||de.target?.closest('button, a, input, [role="menuitem"], [role="menu"]')||bt(de)},Wt=de=>{(de.button===2||de.button===0&&de.ctrlKey&&!Ye)&&(H.current=!0)},St={session:B,sessionTitle:yt,sessionDirectory:re,isPinnedSession:ss,archivedBucket:i,isElectron:Q,renamingFolderId:L,editingIdRef:J,pendingRenameRef:ne,handleCopySessionId:j,togglePinnedSession:v,handleExportSession:ke,handleOpenMiniChatWindow:Be,handleDeleteSession:E,handleRestoreSession:I},Nt=s.jsx(ip,{...St});return s.jsxs(a.Fragment,{children:[s.jsx(Xh,{sessionId:B.id,sessionDirectory:re??null,sessionTitle:yt,children:s.jsxs(oa,{open:Ce,onOpenChange:ws,onOpenChangeComplete:cs,children:[s.jsxs(ia,{render:s.jsx("div",{"data-session-row":B.id,"data-session-scope":De??"","data-session-archived":i?"1":"0","data-fork-color":wt?t.forkColorId:void 0,"data-global-session":U?.globalSession?"1":void 0,onClick:on,style:{...n>0?{marginLeft:`${n*14}px`}:void 0,...tt?{backgroundColor:tt}:void 0},className:K("group relative my-0.5 flex cursor-pointer items-center rounded-xl px-3 py-2 transition-colors",!tt&&n>0?"bg-secondary/30 hover:bg-interactive-hover":tt?"hover:brightness-[1.07] dark:hover:brightness-[1.18]":"hover:bg-interactive-hover",!tt&&ce&&!se&&"bg-interactive-selection",!tt&&se&&"bg-interactive-selection")}),children:[s.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[Ze,gt,f===B.id?s.jsxs("form",{ref:je,"data-session-rename-form":B.id,className:"flex min-h-8 min-w-0 flex-1 items-center gap-2",onPointerDown:de=>de.stopPropagation(),onMouseDown:de=>de.stopPropagation(),onSubmit:de=>{de.preventDefault(),m(he)},children:[s.jsx("input",{value:he,onChange:de=>q(de.target.value),className:"min-w-0 flex-1 bg-transparent typography-ui-label text-foreground outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:"Rename",onKeyDown:de=>{de.stopPropagation(),de.key==="Escape"&&h()}}),s.jsx("button",{type:"submit","aria-label":"Save session name",title:"Save session name",className:"shrink-0 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:s.jsx(D,{name:"check",className:"size-4"})}),s.jsx("button",{type:"button",onClick:h,"aria-label":"Cancel renaming session",title:"Cancel renaming session",className:"shrink-0 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:s.jsx(D,{name:"close",className:"size-4"})})]}):s.jsxs("button",{type:"button",onMouseDown:Wt,onClick:de=>bt(de),onDoubleClick:de=>{de.stopPropagation(),C(B.id,yt)},className:"flex min-w-0 flex-1 cursor-pointer flex-col gap-0.5 overflow-hidden text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 text-foreground select-none",children:[s.jsx("div",{className:"flex w-full items-center min-w-0 flex-1 gap-1.5 overflow-hidden",children:s.jsx("div",{className:K("block min-w-0 flex-1 truncate font-normal typography-ui-label",at?"text-foreground":"text-foreground/90"),children:Jn(yt,d)})}),U?.showFolderLabel&&Fe||ye||ee||we||xe>0||ue&&ue!=="default"||rt?s.jsxs("div",{className:"flex w-full min-w-0 items-center gap-2 overflow-hidden pt-0.5 typography-ui-label font-normal text-muted-foreground",children:[U?.showFolderLabel&&Fe?s.jsx("span",{className:"min-w-0 max-w-[110px] shrink-0 truncate",children:Fe}):null,ye?s.jsxs("span",{className:"inline-flex min-w-0 max-w-[160px] shrink-0 items-center gap-1",children:[s.jsx(D,{name:"git-branch",className:K("size-3.5 shrink-0",!ze&&"text-muted-foreground"),style:ze?{color:ze}:void 0}),s.jsx("span",{className:"truncate",children:ye})]}):ee?s.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[s.jsx(D,{name:"git-repository",className:"size-3.5 shrink-0 text-muted-foreground"}),s.jsx("span",{children:"git"})]}):null,we&&ge!=null?s.jsx(vp,{prDirectory:pe,prNumber:ge,prStatusLabel:qe,prIconColor:ze}):null,xe>0?s.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[s.jsx(D,{name:"node-tree",className:"size-3.5 shrink-0"}),s.jsx("span",{children:xe})]}):null,ue&&ue!=="default"?s.jsx("span",{className:"min-w-0 max-w-[80px] shrink-0 truncate",children:ue}):null,rt?s.jsx(Qd,{sessionId:B.id,running:et,className:"text-muted-foreground/70"}):null]}):null]})]}),ss?s.jsx(D,{name:"star-fill",className:"h-3 w-3 text-primary shrink-0"}):null,s.jsxs("div",{className:"relative ml-1 flex h-6 min-w-6 shrink-0 items-center justify-end",children:[s.jsx("div",{className:K("flex items-center justify-end",_&&(M||Ce)?"opacity-0":_?"group-hover:opacity-0 group-focus-within:opacity-0":null),children:et?s.jsx(Ps,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):pt?s.jsx(Vd,{label:"Session complete"}):s.jsx("span",{className:"text-[11px] text-muted-foreground/75 whitespace-nowrap",children:nt})}),_?s.jsx("div",{className:K("absolute inset-0 flex items-center justify-end",M||Ce?"opacity-100":"pointer-events-none opacity-0 group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100"),children:s.jsx(np,{archiveLabel:"Archive",deleteLabel:"Delete",buttonSizeClass:"h-6 w-6",iconSizeClass:"h-3.5 w-3.5",onPointerDown:vs,onMouseDown:us,onArchive:At,onDelete:Kt})}):null]})]}),Nt]})}),it&&Mt?t.children.map(de=>{const ot=Oe?Oe(de):{subtreeContainsEditing:Z,menuOpenSessionId:Re,nodeStructureKey:""};return s.jsx(a.Fragment,{children:X(de,n+1,re??r,o,i,U?.globalSession?{globalSession:!0}:void 0,ve,ot)},de.session.id)}):null,s.jsx(rp,{open:Tt,onOpenChange:$t,descendantCount:Ft,exportIncludeSubtasks:ls,setExportIncludeSubtasks:Ct,onExport:He})]},B.id)}const jp=a.memo(Sp,yp),Cp=({open:e,onOpenChange:t,project:n,onSave:r})=>s.jsx(es,{open:e,onOpenChange:t,children:s.jsx(ts,{className:"w-full max-w-2xl gap-0 overflow-hidden p-0",children:s.jsx(Cs,{outerClassName:"max-h-[min(90vh,48rem)]",className:"w-full bg-background",children:s.jsx("div",{className:"w-full p-3 sm:p-6 sm:pt-8",children:e&&n?s.jsx(ah,{project:n,onIdentitySave:r}):null})})})});function Dl(e){const{showDeletionDialog:t,setShowDeletionDialog:n,onCancel:r,onConfirm:o,confirmLabel:i}=e;return s.jsxs(Ds,{className:"w-full sm:items-center sm:justify-between",children:[s.jsxs("button",{type:"button",onClick:()=>n(!t),className:"inline-flex items-center gap-1.5 typography-ui-label text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":!t,children:[t?s.jsx(D,{name:"checkbox-blank",className:"h-4 w-4"}):s.jsx(D,{name:"checkbox",className:"h-4 w-4 text-primary"}),"Never ask"]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",onClick:r,className:"inline-flex h-8 items-center justify-center rounded-md border border-border px-3 typography-ui-label text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:"Cancel"}),s.jsx("button",{type:"button",onClick:()=>{o()},className:"inline-flex h-8 items-center justify-center rounded-md bg-destructive px-3 typography-ui-label text-destructive-foreground hover:bg-destructive/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50",children:i})]})]})}function kp(e){const{value:t,setValue:n,showDeletionDialog:r,setShowDeletionDialog:o,onConfirm:i}=e,l=c=>ps(c);return s.jsx(es,{open:!!t,onOpenChange:c=>{c||n(null)},children:s.jsxs(ts,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(xs,{children:[s.jsx(as,{children:t?.archivedBucket?"Delete session?":"Archive session?"}),s.jsx(ys,{children:t&&t.descendantCount>0?t.archivedBucket?t.descendantCount===1?`"${l(t.session)}" and its ${t.descendantCount} sub-task will be permanently deleted.`:`"${l(t.session)}" and its ${t.descendantCount} sub-tasks will be permanently deleted.`:t.descendantCount===1?`"${l(t.session)}" and its ${t.descendantCount} sub-task will be archived.`:`"${l(t.session)}" and its ${t.descendantCount} sub-tasks will be archived.`:t?.archivedBucket?`"${t?.session?l(t.session):"Untitled Session"}" will be permanently deleted.`:`"${t?.session?l(t.session):"Untitled Session"}" will be archived.`})]}),s.jsx(Dl,{showDeletionDialog:r,setShowDeletionDialog:o,onCancel:()=>n(null),onConfirm:i,confirmLabel:t?.archivedBucket?"Delete":"Archive"})]})})}function Ap(e){const{value:t,setValue:n,showDeletionDialog:r,setShowDeletionDialog:o,onConfirm:i}=e,l=t?.archivedBucket===!0,c=t?.sessionCount??0,u=l?c===1?"Delete session?":"Delete sessions?":c===1?"Archive session?":"Archive sessions?",d=l?c===1?`${c} session will be permanently deleted.`:`${c} sessions will be permanently deleted.`:c===1?`${c} session will be archived.`:`${c} sessions will be archived.`;return s.jsx(es,{open:!!t,onOpenChange:f=>{f||n(null)},children:s.jsxs(ts,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(xs,{children:[s.jsx(as,{children:u}),s.jsx(ys,{children:d})]}),s.jsx(Dl,{showDeletionDialog:r,setShowDeletionDialog:o,onCancel:()=>n(null),onConfirm:i,confirmLabel:l?"Delete":"Archive"})]})})}function Np(e){const{value:t,setValue:n,onConfirm:r}=e,{git:o}=Ms(),[i,l]=a.useState(null),[c,u]=a.useState(!1),[d,f]=a.useState(!1),[p,b]=a.useState(!1),g=t?.worktree.path??null;a.useEffect(()=>{let S=!1;return l(null),u(!1),f(!1),b(!1),!t||!g?()=>{S=!0}:(o.getGitStatus(g).then(A=>{if(!S){if(typeof A?.isClean!="boolean"){u(!0);return}l(A)}}).catch(()=>{S||u(!0)}),()=>{S=!0})},[o,t,g]);const m=i?.isClean===!1,h=(i?.ahead??0)>0,y=h&&!t?.worktree.branch,x=t?.worktree.branch?"The local branch will be kept.":"No local branch will be deleted.",C=!!(t&&i&&!c&&!t.hasActiveSession&&(!m&&!y||d)&&!p),v=t?.worktree.branch||t?.worktree.name||t?.worktree.path||"",P=async()=>{if(C){b(!0);try{await r({force:m})}finally{b(!1)}}};return s.jsx(es,{open:!!t,onOpenChange:S=>{!S&&!p&&n(null)},children:s.jsxs(ts,{showCloseButton:!1,className:"max-w-md gap-5",children:[s.jsxs(xs,{children:[s.jsx(as,{children:"Close worktree?"}),s.jsx(ys,{children:`Closing "${v}" removes its worktree directory. ${x}`})]}),c?s.jsxs("div",{role:"alert",className:"flex items-start gap-2 rounded-lg border border-[var(--status-error-border)] bg-[var(--status-error-background)] p-3",children:[s.jsx(D,{name:"alert",className:"mt-0.5 size-4 shrink-0 text-[var(--status-error)]"}),s.jsx("p",{className:"typography-ui-label text-foreground",children:"Unable to check this worktree's status. Refresh and try again."})]}):i===null?s.jsx("p",{className:"typography-ui-label text-muted-foreground","aria-live":"polite",children:"Checking worktree status…"}):null,t?.hasActiveSession?s.jsxs("div",{role:"alert",className:"flex items-start gap-2 rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:[s.jsx(D,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),s.jsx("p",{className:"typography-ui-label text-foreground",children:"Stop the active session before closing this worktree."})]}):null,m?s.jsxs("div",{className:"space-y-3 rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:[s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(D,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),s.jsx("p",{className:"typography-ui-label text-foreground",children:"This worktree has uncommitted changes. They will be permanently removed."})]}),s.jsxs("label",{className:"flex items-start gap-2 pl-6 typography-ui-label text-foreground",children:[s.jsx(Qr,{checked:d,onChange:f,ariaLabel:"Confirm removal of uncommitted changes",className:"mt-0.5"}),s.jsx("span",{children:"I understand that the uncommitted changes will be lost."})]})]}):null,h?s.jsxs("div",{className:"space-y-3",children:[s.jsx("p",{className:"typography-ui-label text-muted-foreground",children:i?.ahead===1?`This worktree has 1 unpushed commit. ${x}`:`This worktree has ${i?.ahead} unpushed commits. ${x}`}),y?s.jsxs("div",{className:"space-y-3 rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:[s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(D,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),s.jsx("p",{className:"typography-ui-label text-foreground",children:"Because this worktree is detached, its unpushed commits may be lost."})]}),s.jsxs("label",{className:"flex items-start gap-2 pl-6 typography-ui-label text-foreground",children:[s.jsx(Qr,{checked:d,onChange:f,ariaLabel:"Confirm removal of unpushed detached commits",className:"mt-0.5"}),s.jsx("span",{children:"I understand that the unpushed commits may be lost."})]})]}):null]}):null,s.jsxs(Ds,{className:"sm:justify-end",children:[s.jsx(Ee,{variant:"outline",size:"sm",onClick:()=>n(null),disabled:p,children:"Cancel"}),s.jsx(Ee,{variant:"destructive",size:"sm",onClick:()=>{P()},disabled:!C,children:p?"Closing…":"Close worktree"})]})]})})}function Ip(e){const{value:t,setValue:n,onConfirm:r}=e;return s.jsx(es,{open:!!t,onOpenChange:o=>{o||n(null)},children:s.jsxs(ts,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(xs,{children:[s.jsx(as,{children:"Delete folder?"}),s.jsx(ys,{children:t&&(t.subFolderCount>0||t.sessionCount>0)?t.subFolderCount>0?t.subFolderCount===1?`"${t.folderName}" will be deleted along with ${t.subFolderCount} sub-folder. Sessions inside will not be deleted.`:`"${t.folderName}" will be deleted along with ${t.subFolderCount} sub-folders. Sessions inside will not be deleted.`:`"${t.folderName}" will be deleted. Sessions inside will not be deleted.`:`"${t?.folderName??""}" will be permanently deleted.`})]}),s.jsxs(Ds,{children:[s.jsx("button",{type:"button",onClick:()=>n(null),className:"inline-flex h-8 items-center justify-center rounded-md border border-border px-3 typography-ui-label text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:"Cancel"}),s.jsx("button",{type:"button",onClick:r,className:"inline-flex h-8 items-center justify-center rounded-md bg-destructive px-3 typography-ui-label text-destructive-foreground hover:bg-destructive/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50",children:"Delete"})]})]})})}const Ep=({updateDialogOpen:e,setUpdateDialogOpen:t,updateStore:n,editingProject:r,setEditingProjectDialogId:o,handleSaveProjectEdit:i,deleteSessionConfirm:l,setDeleteSessionConfirm:c,showDeletionDialog:u,setShowDeletionDialog:d,confirmDeleteSession:f,deleteFolderConfirm:p,setDeleteFolderConfirm:b,confirmDeleteFolder:g,closeWorktreeConfirm:m,setCloseWorktreeConfirm:h,confirmCloseWorktree:y,bulkDeleteConfirm:x,setBulkDeleteConfirm:C,confirmBulkDelete:v})=>s.jsxs(s.Fragment,{children:[s.jsx(Qa,{open:e,onOpenChange:t,info:n.info,downloading:n.downloading,downloaded:n.downloaded,progress:n.progress,error:n.error,onDownload:n.downloadUpdate,onRestart:n.restartToUpdate,runtimeType:n.runtimeType}),s.jsx(Cp,{open:!!r,onOpenChange:P=>{P||o(null)},project:r,onSave:i}),s.jsx(kp,{value:l,setValue:c,showDeletionDialog:u,setShowDeletionDialog:d,onConfirm:f}),s.jsx(Ip,{value:p,setValue:b,onConfirm:g}),s.jsx(Np,{value:m,setValue:h,onConfirm:y}),s.jsx(Ap,{value:x,setValue:C,showDeletionDialog:u,setShowDeletionDialog:d,onConfirm:v})]}),Rp=({directories:e})=>{const t=a.useMemo(()=>{const r=new Set;return e.forEach(o=>{const i=Ae(o)?.toLowerCase();i&&r.add(i)}),r},[e]);return yn(r=>{for(const o of r.catalog.byId.values()){if(o.lifecycle!=="busy"&&o.lifecycle!=="retry")continue;const i=Ae(o.directory)?.toLowerCase();if(i&&t.has(i))return!0}return!1},void 0,"catalog")?s.jsx("span",{className:"inline-flex items-center","aria-label":"Session active",title:"Session active",children:s.jsx(Ps,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})}):null},Dp=e=>{let t=0;for(const n of e)for(const r of n.groups)r.isArchivedBucket||(t+=r.sessions.length);return t},Pp=e=>{const t=new Map;for(const n of e){let r=0;for(const o of n.groups)o.isArchivedBucket||(r+=o.sessions.length);t.set(n.project.id,r)}return t},Mp=(e,t)=>e.groups.some(n=>n.isArchivedBucket?!1:n.sessions.some(r=>t.has(r.session.id))),Tp=(e,t)=>e.groups.some(n=>n.isArchivedBucket?!1:n.sessions.some(r=>t.has(r.session.id))),Fp=(e,t)=>{const n=new Map;for(const r of e){const o=new Set;for(const i of r.groups){if(i.isArchivedBucket)continue;if(i.sessions.some(c=>t.has(c.session.id))&&i.directory){const c=Ae(i.directory)?.toLowerCase();c&&o.add(c)}}o.size>0&&n.set(r.project.id,o)}return n},Lp=e=>e.map(t=>t.groups.some(n=>n.isArchivedBucket)?{...t,groups:t.groups.filter(n=>!n.isArchivedBucket)}:t),Op=(e,t,n,r)=>{if(!n)return t;const o=e.find(c=>c.project.id===n);if(!o)return[];const i=Ae(r??o.project.normalizedPath),l=o.groups.find(c=>!c.isArchivedBucket&&Ae(c.directory)===i);return l?[{...o,groups:[l]}]:[]},Bp=(e,t)=>{const n=new Map,r=new Map;return e.forEach(o=>{const i=pr(o.project.label?.trim()||Xs(o.project.normalizedPath,t)||o.project.normalizedPath);o.groups.forEach(l=>{const c=l.branch&&l.branch!=="HEAD"&&l.branch!==i?l.branch:null,u={projectLabel:i,branchLabel:c},d=f=>{f.forEach(p=>{const b=o.project.normalizedPath.length,g=r.get(p.session.id)??-1;b<g||(n.set(p.session.id,{node:p,projectId:o.project.id,groupDirectory:l.directory,secondaryMeta:u}),r.set(p.session.id,b),p.children.length>0&&d(p.children))})};d(l.sessions)})}),n};function _p({projectSections:e,flatSectionsForRender:t,sectionsForRender:n,selectedSpaceId:r,selectedWorktreePath:o,homeDirectory:i,activeSessionIdSet:l,unreadSessionIdSet:c}){const u=a.useMemo(()=>Bp(e,i),[e,i]),d=a.useMemo(()=>Lp(t),[t]),f=a.useMemo(()=>Op(n,d,r,o),[n,d,r,o]),p=a.useMemo(()=>Dp(e),[e]),b=a.useMemo(()=>Pp(e),[e]),g=a.useCallback(y=>{const x=e.find(C=>C.project.id===y);return x?Mp(x,l):!1},[l,e]),m=a.useMemo(()=>Fp(e,l),[l,e]),h=a.useCallback(y=>{const x=e.find(C=>C.project.id===y);return x?Tp(x,c):!1},[e,c]);return{sessionSidebarMetaById:u,sectionsForSidebarRender:d,filteredSectionsForSidebarRender:f,totalSessionCount:p,sessionCountByProject:b,hasActiveSessionByProject:g,activeDirectoriesByProject:m,hasUnseenByProject:h}}const Up=({selectedCount:e,archivedBucket:t,onRestore:n,onDelete:r,onDone:o})=>{const i=t?"Delete":"Archive",l="inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50";return s.jsxs("div",{className:"flex shrink-0 items-center gap-1 border-t border-border px-3 py-1.5",children:[s.jsx("span",{className:"typography-ui-label text-muted-foreground whitespace-nowrap",children:`${e} selected`}),s.jsxs("div",{className:"ml-auto flex items-center gap-0.5",children:[t?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,className:l,"aria-label":"Restore",children:s.jsx(D,{name:"inbox-unarchive",className:"h-4 w-4"})})}),s.jsx(We,{side:"top",sideOffset:4,children:s.jsx("p",{children:"Restore"})})]}):null,s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:r,className:K("inline-flex h-7 w-7 items-center justify-center rounded-md text-destructive hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50"),"aria-label":i,children:s.jsx(D,{name:"delete-bin",className:"h-4 w-4"})})}),s.jsx(We,{side:"top",sideOffset:4,children:s.jsx("p",{children:i})})]}),s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:o,className:l,"aria-label":"Exit selection",children:s.jsx(D,{name:"close",className:"h-4 w-4"})})}),s.jsx(We,{side:"top",sideOffset:4,children:s.jsx("p",{children:"Exit selection"})})]})]})]})},zp=e=>{const{isInlineEditing:t,showDeletionDialog:n,foldersMap:r,folderScopesByProject:o,addSessionsToFolder:i,removeSessionsFromFolders:l,createFolderAndStartRename:c,archiveSessions:u,unarchiveSessions:d,deleteSessions:f,setBulkDeleteConfirm:p}=e,b=ut(E=>E.enabled),g=ut(E=>E.selectedIds.size),m=g>0,h=ut(E=>E.selectedIds),y=ut(E=>E.scopeKey),x=a.useCallback(()=>{ut.getState().toggleMode()},[]),C=a.useCallback(()=>{ut.getState().disable()},[]),v=a.useMemo(()=>{if(!m||typeof document>"u")return!1;let E=!1,I=!1;for(const M of h){const G=document.querySelectorAll(`[data-session-row="${CSS.escape(M)}"]`);for(const X of G)X.getAttribute("data-session-archived")==="1"?I=!0:E=!0}return I&&!E},[m,h]),P=a.useMemo(()=>{if(y)return y;if(!m||typeof document>"u")return null;for(const E of h){const M=document.querySelector(`[data-session-row="${CSS.escape(E)}"]`)?.getAttribute("data-session-scope");if(M&&M.length>0)return M}return null},[m,h,y]),S=a.useMemo(()=>{if(!P)return[];const E=o.get(P);return E&&E.length>0?E.map(I=>I.scopeKey):[P]},[P,o]),A=a.useMemo(()=>S.flatMap(E=>r[E]??[]),[r,S]),j=a.useCallback(E=>{for(const I of S)if((r[I]??[]).some(M=>M.id===E))return I;return null},[r,S]),w=a.useMemo(()=>{if(!m)return!1;for(const E of S)for(const I of r[E]??[])for(const M of I.sessionIds)if(h.has(M))return!0;return!1},[r,S,m,h]),N=a.useCallback((E,I)=>{const M=Array.from(h);for(const G of S)G!==E&&l(G,M);i(E,I,M)},[i,l,h,S]),T=a.useCallback(E=>{if(!m)return;const I=j(E);I&&N(I,E)},[m,N,j]),L=a.useCallback(()=>{const E=S[0];if(!E||!m)return;const I=c(E);I&&N(E,I.id)},[c,m,N,S]),$=a.useCallback(()=>{if(!m)return;const E=Array.from(h);for(const I of S)l(I,E)},[l,h,S,m]),z=a.useCallback(async()=>{const E=Array.from(h);if(E.length!==0){if(v){const{deletedIds:I,failedIds:M}=await f(E);I.length>0&&ie.success(I.length===1?`Deleted ${I.length} session`:`Deleted ${I.length} sessions`),M.length>0&&ie.error(M.length===1?`Failed to delete ${M.length} session`:`Failed to delete ${M.length} sessions`)}else{const{archivedIds:I,failedIds:M}=await u(E);I.length>0&&ie.success(I.length===1?`Archived ${I.length} session`:`Archived ${I.length} sessions`),M.length>0&&ie.error(M.length===1?`Failed to archive ${M.length} session`:`Failed to archive ${M.length} sessions`)}ut.getState().clear()}},[u,v,f,h]),W=a.useCallback(()=>{if(!m)return;const E=h.size;if(!n){z();return}p({sessionCount:E,archivedBucket:v})},[v,z,h,n,p,m]),F=a.useCallback(async()=>{if(!m||!v)return;const E=Array.from(h),{restoredIds:I,failedIds:M}=await d(E);I.length>0&&ie.success(I.length===1?`Restored ${I.length} session`:`Restored ${I.length} sessions`),M.length>0&&ie.error(M.length===1?`Failed to restore ${M.length} session`:`Failed to restore ${M.length} sessions`),ut.getState().clear()},[v,m,h,d]),R=a.useCallback(async()=>{p(null),await z()},[z]);return a.useEffect(()=>{if(!b)return;const E=typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""),I=M=>{if(t)return;const G=M.target;if(G&&(G.tagName==="INPUT"||G.tagName==="TEXTAREA"||G.isContentEditable))return;const X=E?M.metaKey:M.ctrlKey;if(M.key==="Escape"){M.preventDefault(),ut.getState().disable();return}if(X&&M.key==="Backspace"){M.preventDefault(),W();return}if(X&&(M.key==="a"||M.key==="A")){const U=typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[];if(U.length===0)return;M.preventDefault();const Z=ut.getState().scopeKey??U[0]?.getAttribute("data-session-scope")??null,Re=Q=>Z?Q.getAttribute("data-session-scope")===Z:!0,Oe=U.filter(Re).map(Q=>Q.getAttribute("data-session-row")).filter(Q=>typeof Q=="string"&&Q.length>0);if(Oe.length===0)return;ut.getState().replaceAll(Oe,Z||null)}};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[W,t,b]),{selectionModeEnabled:b,hasSelection:m,selectedIdsSize:g,bulkScopeIsArchived:v,derivedSelectionScope:P,bulkScopeFolders:A,bulkCanRemoveFromFolder:w,handleToggleSelectionMode:x,handleExitSelectionMode:C,handleBulkMoveToFolder:T,handleBulkCreateFolderAndMove:L,handleBulkRemoveFromFolder:$,handleBulkDelete:W,handleBulkRestore:F,confirmBulkDelete:R}},$p=(e,t)=>{const n=e??{};return delete n.projectSortOrder,t<4&&delete n.displayMode,t<5&&delete n.sessionGroupingMode,n},Kp=Ts()(Ba(e=>({stickyZoneHeaders:!0,toggleStickyZoneHeaders:()=>e(t=>({stickyZoneHeaders:!t.stickyZoneHeaders})),showRecentSection:!0,showArchivedSessions:!1,setShowRecentSection:t=>e({showRecentSection:t}),setShowArchivedSessions:t=>e({showArchivedSessions:t}),toggleRecentSection:()=>e(t=>({showRecentSection:!t.showRecentSection})),toggleArchivedSessions:()=>e(t=>({showArchivedSessions:!t.showArchivedSessions}))}),{name:"pichamber:session-display-settings",version:6,migrate:$p})),Oi="oc.sessions.projectCollapse",Bi="oc.sessions.groupOrder",_i="oc.sessions.groupCollapse",Ui="oc.sessions.activeSessionByProject",zi="oc.sessions.expandedParents.v3",Wp=new Set,Tr=[],Et=e=>{const t=a.useRef(e);return t.current=e,a.useCallback((...n)=>t.current(...n),[])},Gp=({isVisible:e=!0,mobileVariant:t=!1,onSessionSelected:n,onNavigateAway:r,allowReselect:o=!1,hideDirectoryControls:i=!1,showOnlyMainWorkspace:l=!1})=>{Zr("react.session_sidebar_render"),zt("ui.session_sidebar.render"),zt(`ui.session_sidebar.render.${t?"mobile":"desktop"}`),zt(`ui.session_sidebar.render.${e?"visible":"hidden"}`);const[c,u]=a.useState(!1),[d,f]=a.useState(""),p=a.useRef(null),b=a.useRef(null),[g,m]=a.useState(null),[h,y]=a.useState(""),[x,C]=a.useState(null),[v,P]=a.useState(new Set),S=a.useMemo(()=>Bn(),[]),[A,j]=a.useState(new Set),w=Bs(k=>k.selectedSpaceId),N=Bs(k=>k.selectedWorktreePath),[T,L]=a.useState(new Map),[$,z]=a.useState(new Map),[W,F]=a.useState(!1),[R,E]=a.useState(null),[I,M]=a.useState(null),[G,X]=a.useState(""),[U,ve]=a.useState(null),[Z,Re]=a.useState(null),[Oe,Q]=a.useState(null),[_,H]=a.useState(null),J=oi(k=>k.ids),ne=Ku(a.useCallback(k=>e?k.rankById:ya,[e])),fe=yn(k=>e?Wu(k.catalog):"",void 0,"catalog"),he=a.useMemo(()=>fe?fe.split("|"):Tr,[fe]),q=a.useMemo(()=>new Set(he),[he]),te=Gu(Yr(k=>e?Object.entries(k.index.session.unseenCount).filter(([,Y])=>Y>0).map(([Y])=>Y).sort():Tr)),ae=a.useMemo(()=>new Set(te),[te]),je=oi(k=>k.toggle),[Se,Ge]=a.useState(()=>{try{const k=Bn().getItem(_i);if(!k)return new Set;const Y=JSON.parse(k);return new Set(Array.isArray(Y)?Y.filter(V=>typeof V=="string"):[])}catch{return new Set}}),[B,re]=a.useState(()=>{try{const k=Bn().getItem(Bi);if(!k)return new Map;const Y=JSON.parse(k),V=new Map;return Object.entries(Y).forEach(([Pe,Ue])=>{Array.isArray(Ue)&&V.set(Pe,Ue.filter(Xe=>typeof Xe=="string"))}),V}catch{return new Map}}),pe=a.useMemo(()=>{try{const k=Bn().getItem(Ui);if(!k)return new Map;const Y=JSON.parse(k),V=new Map;return Object.entries(Y).forEach(([Pe,Ue])=>{typeof Ue=="string"&&Ue.length>0&&V.set(Pe,Ue)}),V}catch{return new Map}},[]),ge=a.useCallback(k=>{try{S.setItem(Ui,JSON.stringify(Object.fromEntries(k.entries())))}catch{}},[S]),[ce,Fe]=a.useState(new Map),ye=a.useRef(0),ee=Js(k=>k.homeDirectory),xe=Js(k=>k.currentDirectory),ue=ht(k=>k.projects),we=ht(k=>k.activeProjectId),ze=ht(k=>k.removeProject),qe=ht(k=>k.setActiveProjectIdOnly),De=ht(k=>k.updateProjectMeta),Ye=ht(k=>k.reorderProjects),se=le(k=>k.setActiveMainTab),Le=le(k=>k.setSettingsDialogOpen),ct=le(k=>k.setSettingsPage),et=le(k=>k.toggleHelpDialog),Qe=le(k=>k.setSessionSwitcherOpen),yt=le(k=>k.setArchivePageOpen),it=le(k=>k.showDeletionDialog),ss=le(k=>k.setShowDeletionDialog),Mt=Hu(d,120),at=a.useMemo(()=>Mt.trim().toLowerCase(),[Mt]),nt=at.length>0,wt=ft(k=>k.collapsedFolderIds),tt=ft(k=>k.foldersMap),Tt=ft(k=>k.getFoldersForScope),$t=ft(k=>k.createFolder),ls=ft(k=>k.renameFolder),Ct=ft(k=>k.deleteFolder),Ft=ft(k=>k.addSessionToFolder),ke=ft(k=>k.addSessionsToFolder),He=ft(k=>k.removeSessionFromFolder),Ce=ft(k=>k.removeSessionsFromFolders),Te=ft(k=>k.toggleFolderCollapse),Be=ft(k=>k.getSessionFolderId);Mh({enabled:e,isSessionSearchOpen:c,setIsSessionSearchOpen:u,sessionSearchInputRef:b,sessionSearchContainerRef:p});const pt=qu(e),{git:rt}=Ms(),kt=yn(k=>k.connection,void 0,"chrome"),vt=yn(k=>{for(const Y of k.catalog.listStatusByDirectory.values())if(Y==="ready")return!0;return!1},void 0,"catalog"),gt=Jr({archived:!1}),Ze=Jr({archived:!0}),cs=Me(k=>k.setCurrentSession),ws=Me(k=>k.updateSessionTitle),vs=Me(k=>k.shareSession),us=Me(k=>k.unshareSession),At=Xr(k=>k.projects),Kt=Xr(k=>k.refreshProject),bt=a.useMemo(()=>Yu(ue,{projects:At}),[ue,At]),on=a.useMemo(()=>{const k=new Map;for(const Y of ue){const V=Ae(Y.path);if(!V)continue;const Pe=At.get(V)?.error;Pe&&k.set(V,Pe)}return k},[ue,At]);a.useEffect(()=>{if(!w)return;const k=ue.find(V=>V.id===w);if(!k){Bs.getState().clearSpaceSelection();return}if(!N)return;(bt.get(Ae(k.path)??k.path)??[]).some(V=>Ae(V.path)===Ae(N))||(Bs.getState().clearSelectedWorktree(),ie.warning("The selected worktree is no longer available. Showing the project checkout instead."))},[bt,ue,w,N]);const Wt=Me(k=>k.openNewSessionDraft),St=a.useCallback(k=>{le.getState().closeMainSurfaces(),Wt(k),r?.()},[r,Wt]),Nt=Yn(Yr(k=>({checkForUpdates:k.checkForUpdates,available:k.available,runtimeType:k.runtimeType,info:k.info,downloading:k.downloading,downloaded:k.downloaded,progress:k.progress,error:k.error,downloadUpdate:k.downloadUpdate,restartToUpdate:k.restartToUpdate}))),de=a.useMemo(()=>Qu(ue,bt,{includeWorktrees:!0}),[bt,ue]),ot=a.useMemo(()=>gt.filter(k=>qh(k,de,{allowUnknownDirectory:!0,allowEmptyDirectorySet:!0,homeDirectory:ee})),[gt,ee,de]),It=a.useMemo(()=>[...ot,...Ze],[Ze,ot]),ds=Dt(),Lt=a.useMemo(()=>`${ds}|${ue.map(k=>`${k.id}:${Ae(k.path)??""}`).join("|")}`,[ue,ds]),Gt=a.useMemo(()=>{const k=new Set;let Y=!0;for(const V of ue){const Pe=Ae(V.path);if(!Pe)continue;const Ue=At.get(Pe)?.status??"idle";Ue==="failed"&&k.add(Pe),(Ue==="idle"||Ue==="loading")&&(Y=!1)}return{complete:Y,unresolved:k}},[ue,At]),xr=Gt.complete?Lt:null,yr=!Gt.complete,Mn=Gt.unresolved,{isTablet:an}=tn(),Fs=t||an,wr=Ph({mobileVariant:t,isTablet:an}),{buildGroupSearchText:O,filterSessionNodesForSearch:oe,buildGroupedSessions:be}=Dh({homeDirectory:ee,pinnedSessionIds:J,sessionOrderRanks:ne}),{scheduleCollapsedProjectsPersist:_e}=Fh({safeStorage:S,keys:{sessionExpanded:zi,projectCollapse:Oi,groupOrder:Bi,groupCollapse:_i},groupOrderByProject:B,collapsedGroups:Se,setExpandedParents:P,setCollapsedProjects:j}),st=a.useMemo(()=>Vu(ot,J,ne),[J,ne,ot]),Ve=a.useMemo(()=>st.map(k=>k.id).join("|"),[st]),ns=a.useRef(null),Ht=a.useMemo(()=>{const k=ns.current;if(k&&k.signature===Ve)return k.map;const Y=new Map(st.map((V,Pe)=>[V.id,Pe]));return ns.current={signature:Ve,map:Y},Y},[st,Ve]),Ll=a.useMemo(()=>{const k=new Map;st.forEach(V=>{const Pe=V.parentID;if(!Pe)return;const Ue=k.get(Pe)??[];Ue.push(V),k.set(Pe,Ue)});const Y=ga(J,ne);return k.forEach(V=>V.sort(Y)),k},[st,J,ne]),Ol=a.useMemo(()=>s.jsx(Ns,{icon:"chat-new",mobileVariant:t,onClick:()=>St(),children:"New session"}),[t,St]),Bl=a.useMemo(()=>ue.find(k=>k.id===x)??null,[ue,x]),_l=a.useCallback(k=>{x&&De(x,{label:k.label,defaultModel:k.defaultModel??null})},[x,De]),Ul=a.useCallback(()=>{const k=Yn.getState();if(k.available&&k.info){F(!0);return}Nt.checkForUpdates().then(()=>{const{available:Y,error:V}=Yn.getState();if(V){ie.error("Failed to check for updates",{description:V});return}if(!Y){ie.success("You are on the latest version");return}F(!0)})},[Nt]),Ls=Ju(),Lo=a.useCallback(()=>{if(t&&Qe(!1),r?.(),Ls?.openSettings){Ls.openSettings();return}Le(!0)},[Ls,t,r,Qe,Le]),zl=Nt.available&&(Nt.runtimeType==="desktop"||Nt.runtimeType==="web"),$l=Me(k=>k.deleteSession),Oo=Me(k=>k.deleteSessions),Kl=Me(k=>k.archiveSession),Bo=Me(k=>k.archiveSessions),Wl=Me(k=>k.unarchiveSession),Gl=Me(k=>k.unarchiveSessions),{copiedSessionId:Hl,handleSessionSelect:ql,handleSessionDoubleClick:Yl,handleSaveEdit:Ql,handleCancelEdit:Vl,handleShareSession:Jl,handleCopyShareUrl:Xl,handleCopySessionId:Zl,handleUnshareSession:ec,handleDeleteSession:tc,handleRestoreSession:sc,confirmDeleteSession:nc}=Th({mobileVariant:t,allowReselect:o,onSessionSelected:n,isSessionSearchOpen:c,sessionSearchQuery:d,setSessionSearchQuery:f,setIsSessionSearchOpen:u,setActiveMainTab:se,setSessionSwitcherOpen:Qe,setCurrentSession:cs,updateSessionTitle:ws,shareSession:vs,unshareSession:us,deleteSession:$l,deleteSessions:Oo,archiveSession:Kl,archiveSessions:Bo,unarchiveSession:Wl,childrenMap:Ll,showDeletionDialog:it,setDeleteSessionConfirm:ve,deleteSessionConfirm:U,setEditingId:m,setEditTitle:y,editingId:g,editTitle:h}),rc=a.useCallback(()=>{if(!Z)return;const{scopeKey:k,folderId:Y}=Z;Re(null),Ct(k,Y)},[Z,Ct]),_o=a.useCallback(()=>{Es.requestDirectoryDialog()},[]),oc=a.useCallback(k=>{P(Y=>{const V=Jd(Y,k);try{S.setItem(zi,JSON.stringify(Array.from(V)))}catch{}return V})},[S]),Uo=a.useCallback((k,Y)=>{if(!k)return null;Y&&wt.has(Y)&&Te(Y);const V=$t(k,"New folder",Y);return M(V.id),X(V.name),V},[wt,Te,$t]),ln=Et(ql),ic=Et(Yl),ac=Et(Ql),lc=Et(Vl),cc=Et(Jl),uc=Et(Xl),dc=Et(Zl),fc=Et(ec),hc=Et(tc),mc=Et(sc),vr=Et(Uo),zo=a.useCallback((k,Y)=>{z(V=>{const Pe=new Map(V);return Pe.set(k,Y+7),Pe})},[]),Tn=a.useCallback(k=>{z(Y=>{if(!Y.has(k))return Y;const V=new Map(Y);return V.delete(k),V})},[]),$o=a.useCallback(k=>{z(Y=>{let V=!1;const Pe=new Map(Y),Ue=`${k}:`;for(const Xe of Pe.keys())Xe.startsWith(Ue)&&(Pe.delete(Xe),V=!0);return V?Pe:Y})},[]),pc=a.useCallback(k=>{ye.current=Date.now()+150,$o(k),j(Y=>{const V=new Set(Y);V.has(k)?V.delete(k):V.add(k);try{S.setItem(Oi,JSON.stringify(Array.from(V)))}catch{}return _e(V),V})},[$o,S,_e]),fs=a.useMemo(()=>ue.map(k=>({...k,normalizedPath:Ae(k.path)})).filter(k=>!!k.normalizedPath),[ue]),gc=a.useMemo(()=>fs.map(k=>k.normalizedPath),[fs]),Ko=Xu(e?gc:Tr);zh({enabled:e,normalizedProjects:fs,gitRepoStatus:Ko,setProjectRepoStatus:L,setProjectRootBranches:Fe});const Wo=a.useMemo(()=>Qh(ot,fs,bt,Ze),[Ze,bt,fs,ot]);Gh({enabled:e,hasAuthoritativeGlobalSessions:vt,sessions:It});const{getSessionsForProject:bc,getArchivedSessionsForProject:xc}=$h({ownership:Wo});jh({enabled:e,normalizedProjects:fs,ownership:Wo,hasAuthoritativeGlobalSessions:vt,isWorktreeTopologyLoading:yr,unresolvedWorktreeProjectPaths:Mn,foldersMap:tt,createFolder:$t,addSessionToFolder:Ft});const Go=a.useRef(!1);we&&T.has(we)&&(Go.current=!!T.get(we));const yc=Kp(k=>k.showArchivedSessions),Sr=ht(k=>k.manualProjectOrder),Ho=a.useRef(new Set),Fn=Xd(Ho.current,v,"project");Ho.current=Fn;const jr={isVisible:e,mobileVariant:t,onSessionSelected:n,allowReselect:o,hideDirectoryControls:i,showOnlyMainWorkspace:l,isTablet:an,catalogSessions:gt,archivedSessions:Ze,projects:ue,activeProjectId:we,manualProjectOrder:Sr,currentDirectory:xe,availableWorktreesByProject:bt,pinnedSessionIds:J,sessionOrderRanks:ne,foldersMap:tt,collapsedFolderIds:wt,gitBranches:pt,gitRepoStatus:Ko,updateStore:Nt,showArchivedSessions:yc,projectRepoStatus:T,projectRootBranches:ce,resolvedWorktreeTopologyKey:xr,unresolvedWorktreeProjectPaths:Mn,isSessionSearchOpen:c,sessionSearchQuery:d,editingId:g,editTitle:h,editingProjectDialogId:x,expandedParents:v,collapsedProjects:A,visibleSessionCountByGroup:$,updateDialogOpen:W,openSidebarMenuKey:R,renamingFolderId:I,renameFolderDraft:G,deleteSessionConfirm:U,deleteFolderConfirm:Z,bulkDeleteConfirm:_,collapsedGroups:Se},qo=a.useRef(null),Yo=qo.current;if(Yo){let k=!1;for(const Y of Object.keys(jr))Object.is(Yo[Y],jr[Y])||(zt(`ui.session_sidebar.source.${Y}`),k=!0);k||zt("ui.session_sidebar.source.parent_or_context")}qo.current=jr;const wc=a.useMemo(()=>{const k=new Map(Sr.map((Y,V)=>[Y,V]));return[...fs].sort((Y,V)=>(k.get(Y.id)??1/0)-(k.get(V.id)??1/0))},[Sr,fs]),{projectSections:Ot,groupSearchDataByGroup:Qo,sectionsForRender:vc,flatSectionsForRender:Cr,searchMatchCount:Sc}=kh({normalizedProjects:wc,getSessionsForProject:bc,getArchivedSessionsForProject:xc,availableWorktreesByProject:bt,projectRepoStatus:T,projectRootBranches:ce,lastRepoStatus:Go.current,buildGroupedSessions:be,hasSessionSearchQuery:nt,normalizedSessionSearchQuery:at,filterSessionNodesForSearch:oe,buildGroupSearchText:O,foldersMap:tt}),Ln=a.useMemo(()=>{const k=ot.filter(V=>mr(wn(V),ee));if(k.length===0)return null;const Y=be(k,"~",[],null,!1).map(V=>nt?{...V,sessions:oe(V.sessions,at)}:V).filter(V=>V.sessions.length>0&&!V.isArchivedBucket);return Y.length===0?null:{project:{id:"__home__",path:"~",normalizedPath:"~",label:"No folder"},groups:Y}},[be,oe,nt,ee,at,ot]),jc=a.useMemo(()=>{if(!nt||!Ln)return 0;const k=Y=>Y.reduce((V,Pe)=>V+1+k(Pe.children),0);return Ln.groups.reduce((Y,V)=>Y+k(V.sessions),0)},[Ln,nt]),Cc=a.useMemo(()=>s.jsxs("div",{className:"py-6 text-center text-muted-foreground",children:[s.jsx("p",{className:"typography-ui-label font-semibold",children:"No matching sessions"}),s.jsx("p",{className:"typography-meta mt-1",children:"Try a different title, branch, folder, or path."})]}),[]),{getOrderedGroups:kc}=Ch(B),Vo=a.useRef(!1);a.useEffect(()=>{if(Vo.current||Ot.length===0)return;const k=Ot.flatMap(Y=>Y.groups.filter(V=>V.isArchivedBucket).map(V=>`${Y.project.id}:${V.id}`));k.length>0&&Ge(Y=>new Set([...Y,...k])),Vo.current=!0},[Ot]);const{filteredSectionsForSidebarRender:Ac,totalSessionCount:Nc,sessionCountByProject:Ic,hasActiveSessionByProject:Ec,activeDirectoriesByProject:cn,hasUnseenByProject:Rc}=_p({projectSections:Ot,flatSectionsForRender:Cr,sectionsForRender:vc,selectedSpaceId:w,selectedWorktreePath:N,homeDirectory:ee,activeSessionIdSet:q,unreadSessionIdSet:ae}),kr=a.useCallback(k=>{if(Bs.getState().selectSpace(k),!k)return;qe(k);const Y=Ot.find(Ue=>Ue.project.id===k),V=Y?.groups.find(Ue=>Ue.isMain),Pe=V?.sessions[0]?.session;Pe?ln(Pe.id,V?.directory??Y?.project.normalizedPath??null,{keepPanelOpen:!0}):Y&&St({selectedProjectId:k,directoryOverride:Y.project.normalizedPath})},[St,Ot,qe,ln]),Dc=t?"flex size-10 shrink-0 items-center justify-center rounded-full leading-none text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed":"inline-flex h-6 w-6 cursor-pointer items-center justify-center rounded-md leading-none text-foreground hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed",Pc=t?"size-5":"h-4.5 w-4.5",On=Et((k,Y=0,V,Pe,Ue=!1,Xe,qt="project",Os)=>s.jsx(jp,{node:k,depth:Y,groupDirectory:V,projectId:Pe,archivedBucket:Ue,pinnedSessionIds:J,expandedParents:Fn,hasSessionSearchQuery:nt,normalizedSessionSearchQuery:at,editingId:g,setEditingId:m,editTitle:h,setEditTitle:y,handleSaveEdit:ac,handleCancelEdit:lc,toggleParent:oc,handleSessionSelect:ln,handleSessionDoubleClick:ic,togglePinnedSession:je,handleShareSession:cc,copiedSessionId:Hl,handleCopyShareUrl:uc,handleCopySessionId:dc,handleUnshareSession:fc,openSidebarMenuKey:R,setOpenSidebarMenuKey:E,renamingFolderId:I,getFoldersForScope:Tt,getSessionFolderId:Be,removeSessionFromFolder:He,addSessionToFolder:Ft,createFolderAndStartRename:vr,handleDeleteSession:hc,handleRestoreSession:mc,mobileVariant:t,alwaysShowActions:Fs,allowQuickArchiveAction:wr,renderSessionNode:On,secondaryMeta:Xe,renderContext:qt,subtreeContainsEditing:Os?.subtreeContainsEditing??Wp,menuOpenSessionId:Os?.menuOpenSessionId??null,nodeStructureKey:Os?.nodeStructureKey??"",childRenderExtrasFor:Os?.childRenderExtrasFor})),Mc=a.useMemo(()=>{const k=new Map;return Cr.forEach(Y=>{const V=Y.groups.find(Pe=>!Pe.isArchivedBucket);V?.folderScopes&&V.folderScopes.length>0&&k.set(Y.project.id,V.folderScopes)}),k},[Cr]),Tc=a.useCallback((k,Y)=>{const V=[];return Y.forEach(Pe=>{Pe.isArchivedBucket||(V.push(Pe.directory),Pe.folderScopes?.forEach(Ue=>V.push(Ue.directory)))}),s.jsx(Rp,{directories:V})},[]),Jo=a.useCallback(k=>{Tn(k),Ge(Y=>{const V=new Set(Y);return V.has(k)?V.delete(k):V.add(k),V})},[Tn]),Fc=a.useCallback((k,Y,V,Pe,Ue,Xe,qt)=>s.jsx(Bm,{group:k,groupKey:Y,projectId:V,hideGroupLabel:Pe,dragHandleProps:Ue,compactBodyPadding:Xe,hasSessionSearchQuery:nt,normalizedSessionSearchQuery:at,groupSearchDataByGroup:Qo,visibleSessionCount:$.get(Y),collapsedGroups:Se,hideDirectoryControls:i,collapsedFolderIds:wt,toggleFolderCollapse:Te,renameFolder:ls,deleteFolder:Ct,showDeletionDialog:it,setDeleteFolderConfirm:Re,renderSessionNode:On,showMoreGroupSessions:zo,resetGroupSessionLimit:Tn,mobileVariant:t,alwaysShowActions:Fs,activeProjectId:we,setActiveProjectIdOnly:qe,setActiveMainTab:se,setSessionSwitcherOpen:Qe,openNewSessionDraft:St,addSessionToFolder:Ft,createFolderAndStartRename:vr,renamingFolderId:I,renameFolderDraft:G,setRenameFolderDraft:X,setRenamingFolderId:M,pinnedSessionIds:J,expandedParents:Fn,sessionOrderIndex:Ht,editingId:g,editTitle:h,openSidebarMenuKey:R,activeActivitySessionIds:q,unreadActivitySessionIds:ae,onToggleCollapsedGroup:Jo,scrollContainerRef:qt}),[nt,at,Qo,$,Se,i,wt,Te,ls,Ct,it,On,zo,Tn,t,Fs,we,qe,se,Qe,St,Ft,vr,I,G,J,Fn,Ht,g,h,R,q,ae,Jo]),Xo=!!(I||g||x),{selectionModeEnabled:Ar,hasSelection:Zo,selectedIdsSize:Lc,bulkScopeIsArchived:Oc,derivedSelectionScope:Bc,bulkScopeFolders:_c,bulkCanRemoveFromFolder:Uc,handleToggleSelectionMode:zc,handleExitSelectionMode:$c,handleBulkMoveToFolder:Kc,handleBulkCreateFolderAndMove:Wc,handleBulkRemoveFromFolder:Gc,handleBulkDelete:Hc,handleBulkRestore:qc,confirmBulkDelete:Yc}=zp({isInlineEditing:Xo,showDeletionDialog:it,foldersMap:tt,folderScopesByProject:Mc,addSessionsToFolder:ke,removeSessionsFromFolders:Ce,createFolderAndStartRename:Uo,archiveSessions:Bo,unarchiveSessions:Gl,deleteSessions:Oo,setBulkDeleteConfirm:H}),ei=a.useCallback(()=>{le.getState().closeMainSurfaces(),se("chat"),t&&Qe(!1),Wt(),r?.()},[t,r,Wt,se,Qe]),Qc=a.useCallback((k,Y)=>{const V=ue.find(Xe=>Xe.id===k);if(!V)return;const Pe=Ae(Y.path)?.toLowerCase(),Ue=!!(Pe&&cn.get(k)?.has(Pe));Q({projectId:k,projectPath:V.path,worktree:Y,hasActiveSession:Ue})},[cn,ue]),Vc=a.useCallback(async({force:k})=>{const Y=Oe;if(!Y)return;const V=Ae(Y.worktree.path)?.toLowerCase();if(!!(V&&cn.get(Y.projectId)?.has(V))){Q({...Y,hasActiveSession:!0}),ie.warning("Stop the active session before closing this worktree.");return}if(!rt.deleteGitWorktree){ie.error("Closing worktrees is not supported by this runtime.");return}try{if(!(await rt.deleteGitWorktree(Y.projectPath,{directory:Y.worktree.path,force:k}))?.success)throw new Error("Git worktree removal was not confirmed by the server.");let Xe=await Kt(Y.projectPath,rt,{force:!0});const qt=Ae(Y.worktree.path);Xe!==null&&qt!==null&&Xe.some(Xc=>Ae(Xc.path)===qt)&&(Xe=await Kt(Y.projectPath,rt,{force:!0}));const Os=qt!==null&&Ae(xe)===qt,Jc=qt!==null&&w===Y.projectId&&Ae(N)===qt;(Os||Jc)&&kr(Y.projectId),Q(null),Xe===null?ie.warning("Worktree closed, but the sidebar could not be refreshed."):ie.success("Worktree closed.")}catch(Ue){const Xe=Ue instanceof Error?Ue.message:"Try again.";ie.error("Failed to close worktree.",{description:Xe})}},[cn,Oe,xe,rt,kr,Kt,w,N]);return s.jsx(Zu,{delay:400,closeDelay:150,timeout:600,children:s.jsxs("div",{ref:p,className:K("relative flex h-full flex-col text-foreground overflow-x-hidden",t?"":"bg-transparent"),children:[s.jsx(Nh,{projectSections:Ot,activeProjectId:we,initialActiveSessionByProject:pe,persistActiveSessionByProject:ge,handleSessionSelect:ln,mobileVariant:t,openNewSessionDraft:Wt,setActiveMainTab:se,setSessionSwitcherOpen:Qe}),!i&&!t?s.jsx(Um,{onNewSession:ei,showSidebarToggle:!0}):null,s.jsx(_m,{hideDirectoryControls:i,handleOpenDirectoryDialog:_o,onOpenArchive:()=>{t&&Qe(!1),yt(!0)},onOpenSettings:t?Lo:void 0,onOpenInstances:t?Ls?.openInstances:void 0,instanceLabel:t?Ls?.instanceLabel:void 0,onOpenUpdate:t?Ls?.openUpdate:void 0,headerActionIconClass:Pc,headerActionButtonClass:Dc,isSessionSearchOpen:c,setIsSessionSearchOpen:u,sessionSearchInputRef:b,sessionSearchQuery:d,setSessionSearchQuery:f,hasSessionSearchQuery:nt,searchMatchCount:Sc+(w===null?jc:0),selectionModeEnabled:Ar,onToggleSelectionMode:zc,mobileVariant:t}),kt==="error"||kt==="unavailable"?s.jsx("div",{role:"alert",className:"mx-3 mb-2 rounded border border-[var(--status-error-border)] bg-[var(--status-error-background)] p-2 text-xs text-foreground",children:"Unable to reach server"}):null,!i&&Ot.length>0?s.jsx(Km,{projects:Ot.map(k=>k.project),selectedProjectId:w,selectedWorktreePath:N,worktreesByProject:bt,worktreeErrorsByProject:on,onSelectProject:kr,onSelectWorktree:(k,Y)=>{Bs.getState().selectWorktree(k,Y),qe(k);const Ue=Ot.find(Xe=>Xe.project.id===k)?.groups.find(Xe=>Ae(Xe.directory)===Ae(Y))?.sessions[0]?.session;Ue?ln(Ue.id,Y,{keepPanelOpen:!0}):St({selectedProjectId:k,directoryOverride:Y})},onCloseWorktree:Qc,onOpenDirectoryDialog:_o,onOpenProjectEditDialog:C,onRemoveProject:ze,totalSessionCount:Nc,getSessionCountForProject:k=>Ic.get(k)??0,hasActiveSessionByProject:Ec,activeDirectoriesByProject:cn,hasUnseenByProject:Rc,homeDirectory:ee,mobileVariant:t}):null,s.jsx(qm,{sectionsForRender:Ac,allFoldersOnlySection:w===null?Ln:null,projectSections:Ot,activeProjectId:we,showOnlyMainWorkspace:l,hasSessionSearchQuery:nt,emptyState:Ol,searchEmptyState:Cc,isAllFoldersView:w===null,pinnedSessionIds:J,renderSessionNode:On,renderGroupSessions:Fc,homeDirectory:ee,collapsedProjects:A,hideDirectoryControls:i,projectRepoStatus:T,mobileVariant:t,alwaysShowActions:Fs,toggleProject:pc,setActiveProjectIdOnly:qe,setActiveMainTab:se,setSessionSwitcherOpen:Qe,openNewSessionDraft:St,openProjectEditDialog:C,removeProject:ze,reorderProjects:Ye,getOrderedGroups:kc,setGroupOrderByProject:re,renderProjectStatusIndicator:Tc,openSidebarMenuKey:R,setOpenSidebarMenuKey:E,isInlineEditing:Xo}),t&&!(Ar&&Zo)?s.jsxs("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 z-10 flex flex-col gap-2 bg-gradient-to-t from-sidebar via-sidebar/85 to-transparent px-4 pb-[calc(0.75rem+var(--oc-safe-area-bottom,0px))] pt-10",children:[s.jsx(nl,{variant:"mobile"}),s.jsx(Ee,{type:"button",variant:"default",size:"lg",className:"pointer-events-auto w-full shadow-lg",onClick:ei,"aria-label":"New session",children:s.jsx(D,{name:"chat-new",className:"size-4"})})]}):null,Ar&&Zo?s.jsx(Up,{selectedCount:Lc,scopeKey:Bc,scopeFolders:_c,archivedBucket:Oc,onMoveToFolder:Kc,onCreateFolderAndMove:Wc,onRemoveFromFolder:Gc,canRemoveFromFolder:Uc,onRestore:qc,onDelete:Hc,onDone:$c}):null,t?null:s.jsx(Wm,{onOpenSettings:Lo,onOpenShortcuts:et,onOpenAbout:()=>{ct("about"),Le(!0)},onOpenUpdate:Ul,showRuntimeButtons:!0,showUpdateButton:zl}),s.jsx(Ep,{updateDialogOpen:W,setUpdateDialogOpen:F,updateStore:Nt,editingProject:Bl,setEditingProjectDialogId:C,handleSaveProjectEdit:_l,deleteSessionConfirm:U,setDeleteSessionConfirm:ve,showDeletionDialog:it,setShowDeletionDialog:ss,confirmDeleteSession:nc,deleteFolderConfirm:Z,setDeleteFolderConfirm:Re,confirmDeleteFolder:rc,closeWorktreeConfirm:Oe,setCloseWorktreeConfirm:Q,confirmCloseWorktree:Vc,bulkDeleteConfirm:_,setBulkDeleteConfirm:H,confirmBulkDelete:Yc})]})})},Sx=a.memo(Gp),$i=6,Rt=.18,gn=1.2,bn=.38,Zn=48,Hp=(e,t)=>e==="left"?t<0:t>0,jx=(e,t,n)=>Math.min(1,Math.max(0,e==="left"?1+t/n:1-t/n)),Cx=(e,t)=>t>=.999?"none":e==="left"?`translateX(${(t-1)*100}%)`:`translateX(${(1-t)*100}%)`,Ki=(e,t,n,r)=>e==="left"?t?Math.min(1,Math.max(0,1+n/r)):Math.min(1,Math.max(0,n/r)):t?Math.min(1,Math.max(0,1-n/r)):Math.min(1,Math.max(0,-n/r)),kx=e=>{const{side:t,dx:n,dy:r,dt:o,progress:i,isDragging:l}=e,c=n/Math.max(1,o);if(l){const u=t==="left"?c<-Rt:c>Rt,d=t==="left"?c>Rt:c<-Rt;return u||!d&&i<bn}return Math.abs(n)>=Zn&&Math.abs(r)<=Math.abs(n)*gn&&Hp(t,n)},qp=e=>{const{side:t,isOpenAtStart:n,dx:r,dt:o,progress:i}=e,l=r/Math.max(1,o);return t==="left"?n?l<-Rt?!1:l>Rt?!0:i>bn:l>Rt?!0:l<-Rt?!1:i>bn:n?l>Rt?!1:l<-Rt?!0:i>bn:l<-Rt?!0:l>Rt?!1:i>bn},Yp='button, a, input, textarea, select, [contenteditable="true"], [data-no-drawer-swipe]',Qp=(e,t,n)=>{if(!(e instanceof Element))return!1;if(n?.excludeInteractive??!0){const i=e.closest(Yp);if(i&&t.contains(i))return!0}else{const i=e.closest("[data-no-drawer-swipe]");if(i&&t.contains(i))return!0}let o=e;for(;o&&o!==t;){if(o instanceof HTMLElement&&o.scrollWidth>o.clientWidth){const i=getComputedStyle(o).overflowX;if(i==="auto"||i==="scroll")return!0}o=o.parentElement}return!1},er=Object.freeze({chunks:Object.freeze([]),byteLength:0,lastSequence:-1}),jo=512*1024,Vp=new TextEncoder,Jp=new TextDecoder,Fr=e=>{const t=Vp.encode(e);if(t.byteLength<=jo)return{text:e,byteLength:t.byteLength};let n=t.byteLength-jo;for(;n<t.byteLength&&(t[n]&192)===128;)n+=1;const r=t.subarray(n);return{text:Jp.decode(r),byteLength:r.byteLength}},Us=(e,t)=>`${e}\0${t}`,Lr=(e,t)=>{let n=null;for(const r of e.keys())t(r)&&(n??=new Map(e),n.delete(r));return n},Xp="terminal-store";let Wi=!1,Gi=0;const qn=()=>typeof globalThis.crypto?.randomUUID=="function"?`tab-${globalThis.crypto.randomUUID()}`:(Gi+=1,`tab-${Date.now().toString(36)}-${Gi.toString(36)}`),Or=e=>typeof e=="object"&&e!==null,Zp=e=>{const t=/^tab-(\d+)$/.exec(e);if(!t)return null;const n=Number(t[1]);return Number.isFinite(n)?n:null};function lt(e){let t=e.trim();for(;t.length>1&&t.endsWith("/");)t=t.slice(0,-1);return t}const eg=/^Terminal(?: (\d+))?$/,tg=e=>{let t=0;for(const n of e){const r=eg.exec(n.label);if(!r)continue;const o=r[1]?Number.parseInt(r[1],10):1;Number.isSafeInteger(o)&&(t=Math.max(t,o))}return t===0?"Terminal":`Terminal ${t+1}`},Br=(e,t)=>({id:e,terminalSessionId:null,lifecycle:"idle",label:t,iconKey:null,isConnecting:!1,createdAt:Date.now(),previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1}),_r=e=>({tabs:[e],activeTabId:e.id}),Bt=(e,t)=>e.tabs.findIndex(n=>n.id===t);let Ur=null,zr=null;const sg=e=>{if(zr&&Ur?.sessions===e.sessions&&Ur.nextTabId===e.nextTabId)return zr;const t={sessions:Array.from(e.sessions.entries()).map(([n,r])=>[n,{activeTabId:r.activeTabId,tabs:r.tabs.map(o=>({id:o.id,label:o.label,iconKey:o.iconKey,createdAt:o.createdAt}))}]),nextTabId:e.nextTabId};return Ur={sessions:e.sessions,nextTabId:e.nextTabId},zr=t,t},ng=()=>{const e=Zd(()=>Nd());if(!e)return;let t=null;return{getItem:n=>e.getItem(n),setItem:(n,r)=>{if(r.state!==t)return t=r.state,e.setItem(n,r)},removeItem:n=>(t=null,e.removeItem(n))}},me=Ts()(gr(Ba((e,t)=>({sessions:new Map,buffers:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1,hasHydrated:typeof window>"u",ensureDirectory:n=>{const r=lt(n);r&&e(o=>{if(o.sessions.has(r))return o;const i=new Map(o.sessions),l=qn(),c=Br(l,"Terminal");return i.set(r,_r(c)),{sessions:i,nextTabId:o.nextTabId+1}})},getDirectoryState:n=>{const r=lt(n);return t().sessions.get(r)},getActiveTab:n=>{const r=lt(n),o=t().sessions.get(r);if(!o)return;const i=o.activeTabId;return i?o.tabs.find(l=>l.id===i)??o.tabs[0]:o.tabs[0]},getBuffer:(n,r)=>t().buffers.get(Us(lt(n),r))??er,createTab:n=>{const r=lt(n);if(!r)return"tab-invalid";const o=qn();return e(i=>{const l=new Map(i.sessions),c=l.get(r),u=i.nextTabId+1,d=tg(c?.tabs??[]),f=Br(o,d);return c?l.set(r,{...c,tabs:[...c.tabs,f]}):l.set(r,_r(f)),{sessions:l,nextTabId:u}}),o},setActiveTab:(n,r)=>{const o=lt(n);e(i=>{const l=new Map(i.sessions),c=l.get(o);return!c||c.activeTabId===r||Bt(c,r)<0?i:(l.set(o,{...c,activeTabId:r}),{sessions:l})})},setTabLabel:(n,r,o)=>{const i=lt(n),l=o.trim();l&&e(c=>{const u=new Map(c.sessions),d=u.get(i);if(!d)return c;const f=Bt(d,r);if(f<0||d.tabs[f]?.label===l)return c;const p=[...d.tabs];return p[f]={...p[f],label:l},u.set(i,{...d,tabs:p}),{sessions:u}})},setTabIconKey:(n,r,o)=>{const i=lt(n);e(l=>{const c=new Map(l.sessions),u=c.get(i);if(!u)return l;const d=Bt(u,r);if(d<0)return l;const f=o?.trim()||null;if(u.tabs[d]?.iconKey===f)return l;const p=[...u.tabs];return p[d]={...p[d],iconKey:f},c.set(i,{...u,tabs:p}),{sessions:c}})},closeTab:(n,r)=>{const o=lt(n);e(i=>{const l=new Map(i.sessions),c=l.get(o);if(!c)return i;const u=Bt(c,r);if(u<0)return i;const d=c.tabs.filter(h=>h.id!==r),f=Object.fromEntries(Object.entries(i.projectActionRuns).filter(([,h])=>!(h.directory===o&&h.tabId===r))),p=Object.keys(f).length!==Object.keys(i.projectActionRuns).length,b=Us(o,r),g=i.buffers.has(b)?Lr(i.buffers,h=>h===b):null;if(d.length===0){const h=qn(),y=Br(h,"Terminal");return l.set(o,_r(y)),{sessions:l,nextTabId:i.nextTabId+1,...g?{buffers:g}:{},...p?{projectActionRuns:f}:{}}}let m=c.activeTabId;return c.activeTabId===r&&(m=d[Math.min(u,d.length-1)]?.id??d[0]?.id??null),l.set(o,{...c,tabs:d,activeTabId:m}),{sessions:l,...g?{buffers:g}:{},...p?{projectActionRuns:f}:{}}})},setTabSessionId:(n,r,o)=>{const i=lt(n);e(l=>{const c=new Map(l.sessions),u=c.get(i);if(!u)return l;const d=Bt(u,r);if(d<0)return l;const f=u.tabs[d],p=o!==null&&f.terminalSessionId!==o,b=o?"running":f.terminalSessionId?"exited":f.lifecycle,g={...f,terminalSessionId:o,lifecycle:b,isConnecting:!1},m=Us(i,r),h=p&&l.buffers.has(m)?Lr(l.buffers,x=>x===m):null,y=[...u.tabs];return y[d]=g,c.set(i,{...u,tabs:y}),{sessions:c,...h?{buffers:h}:{}}})},setTabLifecycle:(n,r,o)=>{const i=lt(n);e(l=>{const c=new Map(l.sessions),u=c.get(i);if(!u)return l;const d=Bt(u,r);if(d<0)return l;const f=[...u.tabs];return f[d]={...f[d],lifecycle:o,isConnecting:!1},c.set(i,{...u,tabs:f}),{sessions:c}})},setConnecting:(n,r,o)=>{const i=lt(n);e(l=>{const c=new Map(l.sessions),u=c.get(i);if(!u)return l;const d=Bt(u,r);if(d<0)return l;const f=[...u.tabs];return f[d]={...f[d],isConnecting:o},c.set(i,{...u,tabs:f}),{sessions:c}})},replaceBuffer:(n,r,o,i)=>{const l=lt(n);e(c=>{const u=c.sessions.get(l);if(!u||Bt(u,r)<0)return c;const d=Us(l,r),f=c.buffers.get(d)??er;if(f.lastSequence>i)return c;const p=Fr(o);if(f.lastSequence===i&&f.byteLength===p.byteLength&&f.chunks.map(m=>m.data).join("")===p.text)return c;const b=c.nextChunkId,g=new Map(c.buffers);return g.set(d,{chunks:p.text?[{id:b,data:p.text,byteLength:p.byteLength}]:[],byteLength:p.byteLength,lastSequence:i}),{buffers:g,nextChunkId:p.text?b+1:b}})},appendToBuffer:(n,r,o,i,l)=>{if(!o)return;const c=lt(n);e(u=>{const d=u.sessions.get(c);if(!d||Bt(d,r)<0)return u;const f=Us(c,r),p=u.buffers.get(f)??er;if(i!==void 0&&i<=p.lastSequence)return u;const b=u.nextChunkId,g=Fr(o),m=l!==void 0&&l!==o?Fr(l).text:void 0,h={id:b,data:g.text,...m!==void 0?{replayData:m}:{},byteLength:g.byteLength},y=[...p.chunks,h];let x=p.byteLength+h.byteLength;for(;x>jo&&y.length>1;){const v=y.shift();if(!v)break;x-=v.byteLength}const C=new Map(u.buffers);return C.set(f,{chunks:y,byteLength:x,lastSequence:i??p.lastSequence}),{buffers:C,nextChunkId:b+1}})},setTabPreviewUrl:(n,r,o,i={})=>{const l=lt(n);e(c=>{const u=new Map(c.sessions),d=u.get(l);if(!d)return c;const f=Bt(d,r);if(f<0)return c;const p=d.tabs[f],b=i.autoOpened??p.previewAutoOpened,g=i.locked??p.previewUrlLocked;if(p.previewUrl===o&&p.previewAutoOpened===b&&p.previewUrlLocked===g)return c;const m=[...d.tabs];return m[f]={...p,previewUrl:o,previewAutoOpened:b,previewUrlLocked:g},u.set(l,{...d,tabs:m}),{sessions:u}})},markPreviewAutoOpened:(n,r)=>{const o=lt(n);e(i=>{const l=new Map(i.sessions),c=l.get(o);if(!c)return i;const u=Bt(c,r);if(u<0)return i;const d=c.tabs[u];if(!d.previewUrl||d.previewAutoOpened)return i;const f=[...c.tabs];return f[u]={...d,previewAutoOpened:!0},l.set(o,{...c,tabs:f}),{sessions:l}})},setProjectActionRun:n=>{e(r=>{const o=r.projectActionRuns[n.key];return o&&o.directory===n.directory&&o.actionId===n.actionId&&o.tabId===n.tabId&&o.sessionId===n.sessionId&&o.status===n.status?r:{projectActionRuns:{...r.projectActionRuns,[n.key]:n}}})},updateProjectActionRunStatus:(n,r)=>{e(o=>{const i=o.projectActionRuns[n];return!i||i.status===r?o:{projectActionRuns:{...o.projectActionRuns,[n]:{...i,status:r}}}})},removeProjectActionRun:n=>{e(r=>{if(!r.projectActionRuns[n])return r;const o={...r.projectActionRuns};return delete o[n],{projectActionRuns:o}})},removeDirectory:n=>{const r=lt(n);e(o=>{const i=new Map(o.sessions);i.delete(r);const l=Us(r,""),c=Lr(o.buffers,d=>d.startsWith(l)),u=Object.fromEntries(Object.entries(o.projectActionRuns).filter(([,d])=>d.directory!==r));return{sessions:i,...c?{buffers:c}:{},projectActionRuns:u}})},clearAll:()=>{e({sessions:new Map,buffers:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1})}}),{name:Xp,storage:ng(),partialize:sg,merge:(e,t)=>{if(!Or(e))return t;const n=Array.isArray(e.sessions)?e.sessions:[],r=new Map;let o=0;for(const c of n){if(!Array.isArray(c)||c.length!==2)continue;const[u,d]=c;if(typeof u!="string"||!Or(d))continue;const f=Array.isArray(d.tabs)?d.tabs:[],p=[],b=new Map;for(const y of f){if(!Or(y))continue;const x=typeof y.id=="string"?y.id:null;if(!x)continue;const C=Zp(x);C!==null&&(o=Math.max(o,C));const v=C===null?x:qn();b.set(x,v),p.push({id:v,label:typeof y.label=="string"?y.label:"Terminal",iconKey:typeof y.iconKey=="string"?y.iconKey:null,terminalSessionId:null,lifecycle:"idle",createdAt:typeof y.createdAt=="number"?y.createdAt:Date.now(),isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(p.length===0)continue;const g=typeof d.activeTabId=="string"?d.activeTabId:null,m=g?b.get(g)??g:null,h=m?p.some(y=>y.id===m):!1;r.set(u,{tabs:p,activeTabId:h?m:p[0].id})}const i=typeof e.nextTabId=="number"&&Number.isFinite(e.nextTabId)?e.nextTabId:1,l=Math.max(t.nextTabId,i,o+1);return{...t,sessions:r,buffers:new Map,nextChunkId:1,nextTabId:l,hasHydrated:!0}}})));if(typeof window<"u"&&!Wi){Wi=!0;const e=me.persist,t=()=>{me.getState().hasHydrated||me.setState({hasHydrated:!0})};e?.hasHydrated?.()?t():e?.onFinishHydration?e.onFinishHydration(t):t()}function rg(e){const{colors:t}=e,n=t.syntax.base;return{background:t.surface.background,foreground:n.foreground,cursor:t.interactive.cursor,cursorAccent:t.surface.background,selectionBackground:t.interactive.selection,selectionForeground:t.interactive.selectionForeground,selectionInactiveBackground:t.interactive.selection+"50",black:t.surface.muted,red:t.status.error,green:t.status.success,yellow:t.status.warning,blue:n.function,magenta:n.keyword,cyan:n.type,white:n.foreground,brightBlack:n.comment,brightRed:t.status.error,brightGreen:t.status.success,brightYellow:t.status.warning,brightBlue:n.function,brightMagenta:n.keyword,brightCyan:n.type,brightWhite:t.surface.elevatedForeground}}function $r(e,t,n){const o=`${e}, "JetBrainsMonoNL Nerd Font", "FiraCode Nerd Font", "Cascadia Code PL", "Fira Code", "JetBrains Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", "Courier New", monospace`;return{cursorBlink:!1,cursorStyle:"bar",cursorInactiveStyle:"none",fontSize:t,fontFamily:o,allowTransparency:!1,convertEol:!0,scrollback:1e4,theme:{background:n.background,foreground:n.foreground,cursor:n.cursor,cursorAccent:n.cursorAccent,selectionBackground:n.selectionBackground,selectionForeground:n.selectionForeground,selectionInactiveBackground:n.selectionInactiveBackground,black:n.black,red:n.red,green:n.green,yellow:n.yellow,blue:n.blue,magenta:n.magenta,cyan:n.cyan,white:n.white,brightBlack:n.brightBlack,brightRed:n.brightRed,brightGreen:n.brightGreen,brightYellow:n.brightYellow,brightBlue:n.brightBlue,brightMagenta:n.brightMagenta,brightCyan:n.brightCyan,brightWhite:n.brightWhite}}}const og=(e,t)=>{const n=`${e??""} ${t??""}`;return/mac|iphone|ipad|darwin/i.test(n)?"mac":"other"},ig=e=>e.key.length===1?e.key.toLowerCase():e.code==="KeyC"?"c":e.code==="KeyV"?"v":e.code==="Insert"?"insert":e.key.toLowerCase(),ag=(e,t,n)=>{if(e.altKey)return null;const r=ig(e);return t==="mac"?!e.metaKey||e.ctrlKey?null:r==="c"&&!e.shiftKey?n?"copy":"ignore":null:e.metaKey?null:e.ctrlKey&&!e.shiftKey&&r==="insert"?n?"copy":"ignore":!e.ctrlKey||!e.shiftKey?null:r==="c"?n?"copy":"ignore":null},xn=e=>typeof e=="string"&&e.trim().length>0;async function Hi(e){return xn(e)?(await bs(e)).ok:!1}async function lg(){if(typeof navigator>"u"||!navigator.clipboard?.readText)return null;try{return await navigator.clipboard.readText()||null}catch{return null}}const cg=(e,t,n,r,o)=>{if(n.width<=0||n.height<=0||r<=0||o<=0)return null;const i=Math.floor((e-n.left)/n.width*r),l=Math.floor((t-n.top)/n.height*o);return{column:Math.max(0,Math.min(r-1,i)),row:Math.max(0,Math.min(o-1,l))}},ug=(e,t)=>{const n=Math.max(0,Math.min(e.length-1,t)),r=l=>!!(l&&!/^\s+$/u.test(l));if(!r(e[n]))return{startColumn:n,endColumn:n};let o=n,i=n;for(;o>0&&r(e[o-1]);)o-=1;for(;i<e.length-1&&r(e[i+1]);)i+=1;return{startColumn:o,endColumn:i}};let dg=null;const fg=()=>dg??=Promise.all([dt(()=>import("./vendor-xterm-xterm-B-qIQCd3.js"),[]),dt(()=>import("./vendor-xterm-addon-fit-DX4qG4td.js"),[])]).then(([e,t])=>({Xterm:e,Fit:t})),hg=2e3,mg=()=>{if(typeof window>"u")return Promise.resolve();const e=window.__pichamberEnsureNerdFonts;return typeof e!="function"?Promise.resolve():Promise.race([Promise.resolve(e()).catch(()=>{}),new Promise(t=>setTimeout(t,hg))]).then(()=>{})},pg=(e,t,n)=>{if(typeof window>"u"||typeof document>"u")return null;const r=document.createElement("canvas").getContext("2d");if(!r||e.clientWidth<24||e.clientHeight<24)return null;r.font=`${n}px ${t}`;const o=r.measureText("M"),i=Math.ceil(o.width),l=Math.ceil((o.actualBoundingBoxAscent||n*.8)+(o.actualBoundingBoxDescent||n*.2))+2;if(i<1||l<1)return null;const c=window.getComputedStyle(e),u=(Number.parseInt(c.paddingLeft,10)||0)+(Number.parseInt(c.paddingRight,10)||0),d=(Number.parseInt(c.paddingTop,10)||0)+(Number.parseInt(c.paddingBottom,10)||0);return{cols:Math.max(2,Math.floor((e.clientWidth-u-15)/i)),rows:Math.max(1,Math.floor((e.clientHeight-d)/l))}},Pl=a.forwardRef(({sessionKey:e,chunks:t,onInput:n,onResize:r,theme:o,fontFamily:i,fontSize:l,className:c,enableTouchScroll:u=!1,autoFocus:d=!0,isVisible:f=!0},p)=>{const b=a.useRef(null),g=a.useRef(null),m=a.useRef(null),h=a.useRef(n),y=a.useRef(r),x=a.useRef(o),C=a.useRef(i),v=a.useRef(l),P=a.useRef(null),S=a.useRef(null),A=a.useRef(null),j=a.useRef(""),w=a.useRef(!1),N=a.useRef(0),T=a.useRef(f),L=a.useRef(!1),[$,z]=a.useState(0),[W,F]=a.useState(0),[R,E]=a.useState(!1),[I,M]=a.useState(!1);h.current=n,y.current=r,T.current=f,x.current=o,C.current=i,v.current=l,a.useLayoutEffect(()=>{const Q=b.current;if(!Q)return;const _=pg(Q,i,l);S.current=_,_&&y.current(_.cols,_.rows)},[i,l]);const G=a.useCallback(()=>{const Q=b.current,_=g.current;if(!Q||!_||!m.current||!T.current)return;const H=Q.getBoundingClientRect();if(!(H.width<24||H.height<24))try{m.current.fit();const J={cols:_.cols,rows:_.rows};(!P.current||P.current.cols!==J.cols||P.current.rows!==J.rows)&&(P.current=J,y.current(J.cols,J.rows)),L.current||(L.current=!0,z(ne=>ne+1))}catch{}},[]),X=a.useCallback(()=>{if(w.current||!j.current||!g.current)return;const Q=g.current,_=j.current;if(j.current="",!_)return;w.current=!0;const H=N.current;Q.write(_,()=>{g.current!==Q||N.current!==H||(w.current=!1,j.current&&X())})},[]),U=a.useCallback(()=>{A.current=null,j.current="",w.current=!1,N.current+=1;const Q=g.current;if(!Q){F(_=>_+1);return}try{Q.reset()}catch{F(_=>_+1)}},[]),ve=a.useCallback(Q=>{Q?.preventDefault(),M(xn(g.current?.getSelection())),E(!0)},[]),Z=a.useCallback(Q=>{Q.stopPropagation();const _=g.current,H=_?.getSelection()??"";_?.focus(),xn(H)&&Hi(H)},[]),Re=a.useCallback(Q=>{Q.stopPropagation();const _=g.current;_?.focus(),lg().then(H=>{H&&g.current===_&&_&&_.paste(H)})},[]),Oe=a.useCallback(Q=>{Q.stopPropagation();const _=g.current;_?.focus();try{_?.selectAll()}catch{}M(xn(_?.getSelection()))},[]);return a.useEffect(()=>{const Q=b.current;if(!Q)return;let _=!1,H=null,J=null,ne=null,fe=null,he=[];const q=()=>{H&&T.current&&(H.options.cursorBlink=!0)},te=Se=>{Se.relatedTarget instanceof Node&&Q.contains(Se.relatedTarget)||H&&(H.options.cursorBlink=!1)},ae=()=>{H&&T.current&&Q.contains(document.activeElement)&&(H.options.cursorBlink=!0)},je=()=>{H&&(H.options.cursorBlink=!1)};return Q.addEventListener("focusin",q),Q.addEventListener("focusout",te),window.addEventListener("focus",ae),window.addEventListener("blur",je),Promise.all([fg(),mg()]).then(([{Xterm:Se,Fit:Ge}])=>{if(_)return;const B=x.current,re=C.current,pe=v.current;H=new Se.Terminal({...$r(re,pe,B),...S.current??{}});const ge=new Ge.FitAddon;H.loadAddon(ge),H.open(Q),g.current=H,m.current=ge;const ce=typeof navigator>"u"?"other":og(navigator.userAgentData?.platform??navigator.platform??"",navigator.userAgent??""),Fe=H;H.attachCustomKeyEventHandler(ye=>{if(ye.type!=="keydown")return!0;const ee=Fe.getSelection(),xe=ag({key:ye.key,code:ye.code,ctrlKey:ye.ctrlKey,shiftKey:ye.shiftKey,metaKey:ye.metaKey,altKey:ye.altKey},ce,xn(ee));return xe==="copy"?(Hi(ee),!1):xe!=="ignore"}),he=[H.onData(ye=>h.current(ye))],J=new ResizeObserver(()=>{ne&&clearTimeout(ne),ne=setTimeout(G,80)}),J.observe(Q),G(),fe=requestAnimationFrame(G)}),()=>{_=!0;const Se=document.activeElement;Se instanceof HTMLElement&&Q.contains(Se)&&(Se.blur(),window.Capacitor?.getPlatform?.()==="android"&&dt(async()=>{const{Keyboard:B}=await import("./vendor-capacitor-keyboard-CYccoJjr.js");return{Keyboard:B}},__vite__mapDeps([44,45])).then(({Keyboard:B})=>B.hide()).catch(()=>{})),J?.disconnect(),ne&&clearTimeout(ne),fe!==null&&cancelAnimationFrame(fe),Q.removeEventListener("focusin",q),Q.removeEventListener("focusout",te),window.removeEventListener("focus",ae),window.removeEventListener("blur",je),he.forEach(Ge=>Ge.dispose()),H?.dispose(),g.current=null,m.current=null,P.current=null,A.current=null,j.current="",w.current=!1,N.current+=1,L.current=!1}},[G,W]),a.useEffect(()=>{const Q=g.current;Q&&(Q.options.theme=$r(i,l,o).theme,Q.options.fontFamily=$r(i,l,o).fontFamily,Q.options.fontSize=l)},[i,l,o]),a.useEffect(()=>{const Q=g.current,_=b.current;!Q||!_||(Q.options.cursorBlink=f&&document.hasFocus()&&_.contains(document.activeElement))},[f,$]),a.useEffect(()=>{if(!g.current)return;if(t.length===0){A.current!==null&&U();return}const _=A.current;let H=-1;if(_!==null){for(let fe=t.length-1;fe>=0;fe-=1){const he=t[fe].id;if(he===_){H=fe;break}if(he<_)break}if(H<0){U();return}}const J=H<0,ne=H>=0?t.slice(H+1):t;j.current+=ne.map(fe=>J?fe.replayData??fe.data:fe.data).join(""),A.current=t.at(-1)?.id??null,X()},[t,X,$,U]),a.useEffect(()=>{if(!d||!f)return;const Q=requestAnimationFrame(()=>g.current?.focus());return()=>cancelAnimationFrame(Q)},[d,f,$,e]),a.useEffect(()=>{const Q=b.current,_=g.current;if(!u||!Q||!_)return;let H=null,J=null,ne="idle",fe=0,he=0,q=0,te=0,ae=null;const je=Math.max(12,l+2),Se=()=>{window.Capacitor?.getPlatform?.()==="android"&&dt(async()=>{const{Keyboard:xe}=await import("./vendor-capacitor-keyboard-CYccoJjr.js");return{Keyboard:xe}},__vite__mapDeps([44,45])).then(({Keyboard:xe})=>xe.show()).catch(()=>{})},Ge=()=>{J&&(clearTimeout(J),J=null)},B=(ee,xe)=>{const ue=Q.querySelector("canvas");return ue?cg(ee,xe,ue.getBoundingClientRect(),_.cols,_.rows):null},re=(ee,xe)=>{const ue=Q.querySelector("canvas");if(!ue)return;const we=ue.getBoundingClientRect(),ze=we.left+(xe.column+.5)/_.cols*we.width,qe=we.top+(xe.row+.5)/_.rows*we.height;ue.dispatchEvent(new MouseEvent(ee,{bubbles:!0,cancelable:!0,button:0,buttons:1,clientX:ze,clientY:qe}))},pe=()=>{document.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0,button:0,buttons:0}))},ge=ee=>{ee.pointerType!=="touch"||H!==null||(H=ee.pointerId,ne="pending",fe=ee.clientX,he=ee.clientY,q=ee.clientY,te=0,ae=null,Q.setPointerCapture(ee.pointerId),J=setTimeout(()=>{if(J=null,H!==ee.pointerId||ne!=="pending")return;const xe=B(fe,he);if(!xe)return;const ue=_.buffer.active,we=Math.max(0,ue.length-_.rows-ue.viewportY+xe.row),ze=ue.getLine(we),qe=Array.from({length:_.cols},(se,Le)=>ze?.getCell(Le)?.getChars()??""),De=ug(qe,xe.column),Ye={column:De.startColumn,row:xe.row};ae={column:De.endColumn,row:xe.row},ne="selecting",re("mousedown",Ye),re("mousemove",ae)},350))},ce=ee=>{if(H!==ee.pointerId)return;if(ne==="selecting"){const we=B(ee.clientX,ee.clientY);we&&(!ae||we.column!==ae.column||we.row!==ae.row)&&(ae=we,re("mousemove",we)),ee.cancelable&&ee.preventDefault();return}if(ne==="pending"){if(Math.hypot(ee.clientX-fe,ee.clientY-he)<8)return;Ge(),ne="scrolling"}if(ne!=="scrolling")return;const xe=q-ee.clientY;q=ee.clientY,te+=xe;const ue=Math.trunc(te/je);ue&&(_.scrollLines(ue),te-=ue*je),ee.cancelable&&ee.preventDefault()},Fe=ee=>{if(H!==ee.pointerId)return;const xe=ne==="pending",ue=ne==="selecting";Ge(),Q.hasPointerCapture(ee.pointerId)&&Q.releasePointerCapture(ee.pointerId),H=null,ne="idle",ue&&pe(),xe&&(_.focus(),Se())},ye=ee=>{if(H!==ee.pointerId)return;const xe=ne==="selecting";Ge(),Q.hasPointerCapture(ee.pointerId)&&Q.releasePointerCapture(ee.pointerId),H=null,ne="idle",xe&&pe()};return Q.addEventListener("pointerdown",ge),Q.addEventListener("pointermove",ce,{passive:!1}),Q.addEventListener("pointerup",Fe),Q.addEventListener("pointercancel",ye),()=>{Ge(),Q.removeEventListener("pointerdown",ge),Q.removeEventListener("pointermove",ce),Q.removeEventListener("pointerup",Fe),Q.removeEventListener("pointercancel",ye)}},[u,l,$]),a.useImperativeHandle(p,()=>({focus:()=>g.current?.focus(),fit:G,getSelection:()=>{const Q=g.current,_=Q?.getSelectionPosition(),H=Q?.getSelection()??"";return!_||!H.trim()?null:{text:H,startLine:_.start.y+1,endLine:_.end.y+1}}}),[G]),s.jsxs(Po,{open:R,onOpenChange:E,children:[s.jsx(Mo,{render:s.jsx("div",{ref:b,"data-terminal-owner":"main",className:K("terminal-viewport-container h-full w-full overflow-hidden touch-none",c),onContextMenu:ve})}),s.jsxs(To,{className:"min-w-[180px]",children:[s.jsxs(Ys,{disabled:!I,onClick:Z,children:[s.jsx(D,{name:"file-copy",className:"mr-2 h-4 w-4"})," ","Copy"]}),s.jsxs(Ys,{onClick:Re,children:[s.jsx(D,{name:"clipboard",className:"mr-2 h-4 w-4"})," ","Paste"]}),s.jsx(jl,{}),s.jsx(Ys,{onClick:Oe,children:"Select All"})]})]})});Pl.displayName="TerminalViewport";const gg=({directory:e,tabId:t,sessionId:n,sessionKey:r,isActive:o,isTerminalVisible:i,terminal:l,theme:c,fontFamily:u,fontSize:d,enableTouchScroll:f,lastViewportSizeRef:p,onInput:b,controllerRef:g})=>{const m=me(v=>e&&t?v.getBuffer(e,t).chunks:er.chunks),h=a.useRef(null),y=o&&i,x=a.useCallback(v=>{h.current=v,g&&(g.current=o?v:g.current),!o&&g&&g.current===v&&(g.current=null)},[g,o]);a.useEffect(()=>{if(!o||!i)return;const v=requestAnimationFrame(()=>{h.current?.fit()});return()=>cancelAnimationFrame(v)},[o,i,r,n]);const C=a.useCallback((v,P)=>{if(!o)return;const S=p.current;(!S||S.cols!==v||S.rows!==P)&&(p.current={cols:v,rows:P}),n&&l.resize({sessionId:n,cols:v,rows:P}).catch(()=>{})},[o,p,n,l]);return s.jsx("div",{className:K("h-full w-full",o?"block":"hidden"),"aria-hidden":!o,children:s.jsx(Pl,{ref:x,sessionKey:r,chunks:m,onInput:b,onResize:C,theme:c,fontFamily:u,fontSize:d,enableTouchScroll:f,autoFocus:y,isVisible:y},r)})},qi=({items:e,activeId:t,onSelect:n,onClose:r,onCreate:o,disabled:i=!1})=>{const l=e.find(c=>c.id===t)??e[0]??null;return s.jsxs(Jt,{modal:!1,children:[s.jsx(Xt,{asChild:!0,children:s.jsxs(Ee,{type:"button",variant:"ghost",size:"sm",disabled:i,title:l?`Switch terminal, current: ${l.label}`:"Switch terminal","aria-label":l?`Switch terminal, current: ${l.label}`:"Switch terminal",className:"h-8 min-w-0 max-w-full justify-start gap-1.5 px-2 py-1 normal-case",children:[l?.icon??s.jsx(D,{name:"terminal",className:"size-4 shrink-0"}),s.jsx("span",{className:"min-w-0 truncate font-medium text-left",children:l?.label??"Terminal"}),s.jsx(D,{name:"arrow-down-s",className:"size-4 shrink-0 opacity-60"})]})}),s.jsxs(Zt,{align:"start",className:"w-64",children:[e.map(c=>{const u=c.id===(l?.id??t);return s.jsxs(mt,{title:c.title??c.label,onClick:()=>n(c.id),className:"group/tab min-w-0",children:[s.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[c.icon,s.jsx("span",{className:"min-w-0 flex-1 truncate",children:c.label})]}),u?s.jsx(D,{name:"check",className:"size-3.5 shrink-0 text-primary"}):null,s.jsx("button",{type:"button",title:c.closeLabel,"aria-label":c.closeLabel,onClick:d=>{d.preventDefault(),d.stopPropagation(),r(c.id)},className:"flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground opacity-0 transition-opacity hover:bg-interactive-hover hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none group-hover/tab:opacity-100",children:s.jsx(D,{name:"close",className:"size-3"})})]},c.id)}),s.jsx(Qs,{}),s.jsxs(mt,{onClick:o,children:[s.jsx(D,{name:"add",className:"size-3.5"}),"New tab"]})]})]})},bg=({leading:e,icon:t,title:n,actions:r,className:o})=>s.jsxs("header",{className:K("flex h-11 shrink-0 items-center gap-1 border-b border-border bg-background pl-3 pr-2",o),children:[e,n!=null?typeof n=="string"?s.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[typeof t=="string"?s.jsx(D,{name:t,className:"size-4 shrink-0 text-muted-foreground","aria-hidden":"true"}):t??null,s.jsx("h2",{className:"truncate typography-ui-label font-medium text-foreground",children:n})]}):s.jsx("div",{className:"min-w-0 flex-1",children:n}):null,r?s.jsx("div",{className:"flex shrink-0 items-center gap-1",children:r}):null]}),xg=({isTouchTerminal:e,activeModifier:t,disabled:n,onKeyPress:r,onModifierToggle:o})=>{const i=e?"lg":"xs",l=e?"w-10 p-0":"w-9 p-0",c=u=>{e&&u.preventDefault()};return s.jsxs(s.Fragment,{children:[s.jsx(Ee,{type:"button",size:i,variant:"outline",onPointerDown:c,onClick:()=>r("esc"),disabled:n,children:"Esc"}),s.jsxs(Ee,{type:"button",size:i,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("tab"),disabled:n,children:[s.jsx(D,{name:"arrow-right",className:"h-4 w-4"}),s.jsx("span",{className:"sr-only",children:"Tab"})]}),s.jsxs(Ee,{type:"button",size:i,variant:"chip","aria-pressed":t==="ctrl",className:e?"px-3":"px-2",onPointerDown:c,onClick:()=>o("ctrl"),disabled:n,children:[s.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}),s.jsx("span",{className:"sr-only",children:"Control modifier"})]}),s.jsxs(Ee,{type:"button",size:i,variant:"chip","aria-pressed":t==="alt",className:e?"px-3":"px-2",onPointerDown:c,onClick:()=>o("alt"),disabled:n,children:[s.jsx("span",{className:"text-xs font-medium",children:"Alt"}),s.jsx("span",{className:"sr-only",children:"Alt modifier"})]}),s.jsxs(Ee,{type:"button",size:i,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("arrow-up"),disabled:n,children:[s.jsx(D,{name:"arrow-up"}),s.jsx("span",{className:"sr-only",children:"Arrow up"})]}),s.jsxs(Ee,{type:"button",size:i,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("arrow-left"),disabled:n,children:[s.jsx(D,{name:"arrow-left"}),s.jsx("span",{className:"sr-only",children:"Arrow left"})]}),s.jsxs(Ee,{type:"button",size:i,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("arrow-down"),disabled:n,children:[s.jsx(D,{name:"arrow-down"}),s.jsx("span",{className:"sr-only",children:"Arrow down"})]}),s.jsxs(Ee,{type:"button",size:i,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("arrow-right"),disabled:n,children:[s.jsx(D,{name:"arrow-right"}),s.jsx("span",{className:"sr-only",children:"Arrow right"})]}),s.jsxs(Ee,{type:"button",size:i,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("enter"),disabled:n,children:[s.jsx(D,{name:"arrow-go-back"}),s.jsx("span",{className:"sr-only",children:"Enter"})]})]})},yg="\x1B",wg=new RegExp(`${yg}\\[[0-9;?]*[ -/]*[@-~]`,"g"),vg=/(https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[(?:::1|::)\])(?::\d{2,5})?(?:\/[^\s<>'"`]*)?)/gi,Sg=/(?:➜\s*(?:Local|Network):)|\b(?:local|network|loopback|serving|listening|available|ready|started|running|server|vite|webpack|next\.js|astro|sveltekit|nuxt)\b/i,jg=/Serving HTTP on .*? port (\d{2,5})/i,Cg=new Set([".",",",";",":","!","?"]),kg=e=>{let t=e;for(;t.length>0;){const n=t[t.length-1];if(n===")"||n==="]"||n==="}"||n===">"){const r=n===")"?"(":n==="]"?"[":n==="}"?"{":"<",o=t.slice(0,-1),i=(o.match(new RegExp(`\\${r}`,"g"))||[]).length,l=(o.match(new RegExp(`\\${n}`,"g"))||[]).length;if(i>l)break;t=o;continue}if(Cg.has(n)){t=t.slice(0,-1);continue}break}return t},Yi=e=>{let t=kg(e);return t=t.replace("0.0.0.0","127.0.0.1"),t=t.replace("[::1]","127.0.0.1"),t=t.replace("[::]","127.0.0.1"),t},Ag=e=>{if(!e)return null;const t=e.replace(wg,""),n=t.match(jg);if(n?.[1]){const o=Number.parseInt(n[1],10);if(Number.isFinite(o)&&o>0&&o<=65535)return`http://127.0.0.1:${o}/`}const r=t.split(`
|
|
55
|
+
`);for(const o of r){if(!Sg.test(o))continue;const i=Array.from(o.matchAll(vg));if(i.length===0)continue;const l=i.find(c=>{try{return!!new URL(Yi(c[1])).port}catch{return!1}});return Yi((l??i[0])[1])}return null},Ng=async(e,t=1500)=>{if(!e||typeof window>"u")return!1;let n;try{n=new URL(e)}catch{return!1}if(n.protocol!=="http:"&&n.protocol!=="https:")return!1;const r=n.hostname.toLowerCase();if(r!=="localhost"&&r!=="127.0.0.1"&&r!=="0.0.0.0"&&r!=="::1"&&r!=="::")return!1;const o=new AbortController,i=window.setTimeout(()=>o.abort(),t);try{const l=await Pt("/api/system/probe-url",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:n.toString()}),cache:"no-store",signal:o.signal});return l.ok?(await l.json().catch(()=>null))?.ok===!0:!1}catch{return!1}finally{window.clearTimeout(i)}},Ig={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},Eg=(e,t)=>{if(t&&e.startsWith("arrow-")){const n=t==="ctrl"?"5":"3",r={"arrow-up":"A","arrow-down":"B","arrow-right":"C","arrow-left":"D"}[e];return`\x1B[1;${n}${r}`}return Ig[e]},Ml=e=>{const t=e[0]?.toUpperCase();return!t||t<"A"||t>"Z"?null:String.fromCharCode(t.charCodeAt(0)&31)},Rg=(e,t)=>e&&(t==="ctrl"?Ml(e)??e:e.length===1&&e!=="\x1B"?`\x1B${e}`:e),Tl={cols:80,rows:24},Qi={Tab:"tab",Enter:"enter",ArrowUp:"arrow-up",ArrowDown:"arrow-down",ArrowLeft:"arrow-left",ArrowRight:"arrow-right",Escape:"esc"};class Dg{tail="";pendingUrls=new Set;probeGeneration=0;reset(){this.tail="",this.pendingUrls.clear(),this.probeGeneration+=1}scan(t,n,r,o){if(!r)return;const i=`${this.tail}${r}`.replace(/\r\n|\r/g,`
|
|
56
|
+
`),l=i.split(`
|
|
57
|
+
`),c=i.endsWith(`
|
|
58
|
+
`)?l.join(`
|
|
59
|
+
`):l.slice(0,-1).join(`
|
|
60
|
+
`);if(this.tail=i.endsWith(`
|
|
61
|
+
`)?"":(l[l.length-1]??"").slice(-1024),!c)return;const u=Ag(c);if(!u||this.pendingUrls.has(u))return;const d=this.probeGeneration;this.pendingUrls.add(u),Ng(u).then(f=>{if(this.pendingUrls.delete(u),!f||this.probeGeneration!==d)return;const p=me.getState().getDirectoryState(t)?.tabs.find(b=>b.id===n);!p||p.previewUrlLocked||p.previewUrl===u||o(t,n,u,{locked:!1,autoOpened:!1})})}}const Pg=(e,t)=>{if(t!=="ctrl")return null;const n=e.key,r=e.code??"",o=n.length===1&&/[a-zA-Z]/.test(n)?n.toUpperCase():r.startsWith("Key")&&r.length===4?r.slice(3).toUpperCase():null;return o&&o.length===1&&o>="A"&&o<="Z"?Ml(o):null};function Mg({terminal:e,effectiveDirectory:t,activeTabId:n,terminalSessionId:r,terminalLifecycle:o,hasOpenedTerminalViewport:i,terminalHydrated:l,terminalShell:c,terminalLoginShell:u,terminalAppearanceRef:d,enableTabs:f,hasActiveContext:p,focusTerminalWhenWindowActive:b,tabs:g}){const m=me(_=>_.ensureDirectory),h=me(_=>_.setTabSessionId),y=me(_=>_.setTabLifecycle),x=me(_=>_.setConnecting),C=me(_=>_.appendToBuffer),v=me(_=>_.replaceBuffer),P=me(_=>_.setTabPreviewUrl),[S,A]=a.useState(null),[j,w]=a.useState(!1),[N,T]=a.useState(!1),L=a.useRef(new Map),$=a.useRef(null),z=a.useRef(n),W=a.useRef(r),F=a.useRef(t),R=a.useRef(null),E=a.useRef(new Set),I=a.useRef(new Map),M=a.useRef(g),G=a.useRef(l),X=a.useRef(i),U=a.useRef(e);M.current=g,G.current=l,X.current=i,U.current=e;const ve=a.useCallback(()=>{const _=z.current;_&&I.current.get(_)?.reset()},[]);a.useEffect(()=>{W.current=r},[r]),a.useEffect(()=>{!r||!e.updateAppearance||e.updateAppearance(r,d.current).catch(()=>{})},[d,e,r]),a.useEffect(()=>{z.current=n},[n]),a.useEffect(()=>{F.current=t},[t]);const Z=a.useCallback(()=>{for(const _ of L.current.values())try{_()}catch{}L.current.clear(),$.current=null,T(!1)},[]);a.useEffect(()=>()=>{Z(),W.current=null},[Z]);const Re=a.useCallback((_,H,J)=>{let ne=I.current.get(H);ne||(ne=new Dg,I.current.set(H,ne)),ne.scan(_,H,J,P)},[P]),Oe=a.useCallback((_,H,J)=>{if(L.current.has(J)){$.current=J;return}const ne=li(),fe=()=>li()===ne&&F.current===_&&me.getState().getDirectoryState(_)?.tabs.find(q=>q.id===H)?.terminalSessionId===J,he=e.connect(J,{onEvent:q=>{if(fe())switch(q.type){case"snapshot":{z.current===H&&W.current===J?(x(_,H,!1),A(null),w(!1),T(!1),b()):x(_,H,!1),v(_,H,q.data??"",q.sequence??0),Re(_,H,q.data??""),q.status==="exited"&&y(_,H,"exited");break}case"reconnecting":{z.current===H&&(A(null),w(!1),T(!0));break}case"data":{q.data&&(C(_,H,q.data,q.sequence,q.replayData),Re(_,H,q.data));break}case"exit":{const te=typeof q.exitCode=="number"?q.exitCode:null,ae=typeof q.signal=="number"?q.signal:null,Se=!!me.getState().getDirectoryState(_)?.tabs.find(Ge=>Ge.id===H)?.label?.startsWith("Action:");C(_,H,`\\r\\n[Process exited${te!==null?` with code ${te}`:""}${ae!==null?` (signal ${ae})`:""}]\\r\\n`),y(_,H,"exited"),z.current===H&&(x(_,H,!1),A(Se?null:"Terminal session ended"),w(!1),T(!1));break}}},onError:(q,te)=>{if(!fe())return;const ae=z.current===H;if(!te){ae&&(A(null),w(!1));return}if(q.code==="SESSION_NOT_FOUND"&&!me.getState().getDirectoryState(_)?.tabs.find(Se=>Se.id===H)?.label?.startsWith("Action:")){ae&&(A(null),w(!1),x(_,H,!1),T(!1)),h(_,H,null),y(_,H,"idle");return}ae&&(T(!1),A(`Connection failed: ${q.message}`),w(!0),x(_,H,!1),y(_,H,"exited"),h(_,H,null))}});L.current.set(J,()=>he.close()),$.current=J},[C,b,v,Re,x,y,h,e]),Q=a.useMemo(()=>g.map(_=>`${_.id}:${_.terminalSessionId??""}`).join(","),[g]);return a.useEffect(()=>{if(!l||!i||!t)return;const _=t,H=new Set;for(const J of g)J.terminalSessionId&&(H.add(J.terminalSessionId),Oe(_,J.id,J.terminalSessionId));for(const[J,ne]of L.current)if(!H.has(J)){try{ne()}catch{}L.current.delete(J)}},[Q,g,t,l,i,Oe]),a.useEffect(()=>Id(()=>{if(!G.current||!X.current)return;const _=F.current;if(!_)return;const H=[];for(const ne of M.current){if(!ne.terminalSessionId)continue;me.getState().getDirectoryState(_)?.tabs.find(he=>he.id===ne.id)?.terminalSessionId===ne.terminalSessionId&&H.push({id:ne.id,terminalSessionId:ne.terminalSessionId})}if(L.current.clear(),$.current=null,H.length===0)return;T(!0),A(null),w(!1);for(const ne of H)Oe(_,ne.id,ne.terminalSessionId);const J=R.current;if(J)for(const ne of H)U.current.resize({sessionId:ne.terminalSessionId,...J}).catch(()=>{})}),[Oe]),a.useEffect(()=>{let _=!1;if(!l||!i)return;if(!t){A(p?"No working directory available for terminal.":"Select a session to open the terminal.");return}return(async()=>{const J=t;if(!F.current||F.current!==J)return;if(!me.getState().getDirectoryState(J)){m(J);return}const fe=me.getState().getDirectoryState(J);if(!fe||fe.tabs.length===0)return;const he=fe.activeTabId??fe.tabs[0]?.id??null;if(!he)return;const q=fe.tabs.find(B=>B.id===he)??fe.tabs[0],te=q?.terminalSessionId??null,ae=q?.lifecycle??"idle",je=!!q?.label?.startsWith("Action:"),Se=me.getState().getBuffer(J,he),Ge=Se.byteLength>0||Se.chunks.length>0;if(!te){if(ae==="exited"){x(J,he,!1);return}if(je&&Ge){x(J,he,!1);return}const B=`${J}\0${he}`;if(E.current.has(B))return;const re=R.current??Tl;E.current.add(B),A(null),w(!1),T(!1),x(J,he,!0);try{const pe=await e.createSession({cwd:J,sessionId:he,cols:re.cols,rows:re.rows,shell:c,loginShell:u,...d.current});if(!me.getState().getDirectoryState(J)?.tabs.find(Fe=>Fe.id===he)){try{await e.close(pe.sessionId)}catch{}return}h(J,he,pe.sessionId);const ce=R.current;ce&&(ce.cols!==re.cols||ce.rows!==re.rows)&&e.resize({sessionId:pe.sessionId,...ce}).catch(()=>{});return}catch(pe){const ge=me.getState().getDirectoryState(J)?.tabs.find(ce=>ce.id===he);if(!ge||ge.terminalSessionId||(x(J,he,!1),F.current!==J||z.current!==he))return;A(pe instanceof Error?pe.message:"Failed to start terminal session"),w(!0),T(!1);return}finally{E.current.delete(B)}}!te||_||(W.current=te)})(),()=>{_=!0}},[p,t,r,o,n,i,f,l,m,x,y,h,e,u,c,d]),{connectionError:S,setConnectionError:A,isFatalError:j,setIsFatalError:w,isReconnectPending:N,setIsReconnectPending:T,terminalIdRef:W,lastViewportSizeRef:R,directoryRef:F,activeTabIdRef:z,disconnectStream:Z,resetTerminalPreviewScan:ve,startStream:Oe}}function Tg({terminal:e,terminalIdRef:t,isReconnectPending:n,setConnectionError:r,showQuickKeys:o,isTerminalVisible:i,lastViewportSizeRef:l,terminalSessionId:c,useTouchTerminalInput:u}){const[d,f]=a.useState(null),p=a.useRef(null),b=a.useCallback(()=>{u||p.current?.focus()},[u]),g=a.useCallback(()=>{u||typeof document<"u"&&!document.hasFocus()||p.current?.focus()},[u]);a.useEffect(()=>{!o&&d!==null&&f(null)},[o,d]),a.useEffect(()=>{!c&&d!==null&&f(null)},[c,d]);const m=a.useCallback(v=>{if(!v||n)return;let P=v,S=!1;d&&v.length>0&&(P=Rg(v,d),S=!0);const A=t.current;A&&(e.sendInput(A,P).catch(j=>{n||r(j instanceof Error?j.message:"Failed to send input")}),S&&(f(null),b()))},[d,b,n,r,e,t]),h=a.useCallback((v,P)=>{const S=l.current;if((!S||S.cols!==v||S.rows!==P)&&(l.current={cols:v,rows:P}),!i)return;const A=t.current;A&&e.resize({sessionId:A,cols:v,rows:P}).catch(()=>{})},[i,l,e,t]),y=a.useCallback(v=>{f(P=>P===v?null:v),b()},[b]),x=a.useCallback(v=>{const P=Eg(v,d);P&&(m(P),f(null),b())},[d,b,m]),C=a.useCallback(v=>{if(v.repeat)return;const P=v.key;if(!P||P==="Control"||P==="Meta"||P==="Alt"||P==="Shift")return;const S=P.length===1?P.toLowerCase():P;if(S in Qi){v.preventDefault(),v.stopPropagation(),x(Qi[S]);return}const A=Pg(v,d);A&&(v.preventDefault(),v.stopPropagation(),m(A),f(null),b())},[d,b,x,m]);return a.useEffect(()=>{if(!(!o||!d||!c))return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[d,C,o,c]),{activeModifier:d,setActiveModifier:f,terminalControllerRef:p,focusTerminalController:b,focusTerminalWhenWindowActive:g,handleViewportInput:m,handleViewportResize:h,handleModifierToggle:y,handleMobileKeyPress:x}}function Fg({terminal:e,effectiveDirectory:t,activeTabId:n,enableTabs:r,terminalShell:o,terminalLoginShell:i,terminalAppearanceRef:l,lastViewportSizeRef:c,directoryRef:u,activeTabIdRef:d,terminalIdRef:f,resetTerminalPreviewScan:p,startStream:b,setConnectionError:g,setIsFatalError:m,setIsReconnectPending:h}){const y=me($=>$.createTab),x=me($=>$.setActiveTab),C=me($=>$.closeTab),v=me($=>$.setTabSessionId),P=me($=>$.setTabLifecycle),[S,A]=a.useState(!1),j=a.useCallback(async()=>{if(!t||S)return;const $=me.getState().getDirectoryState(t),z=n??$?.activeTabId??$?.tabs[0]?.id??null;if(!z)return;const W=$?.tabs.find(F=>F.id===z)?.terminalSessionId??null;if(!(!W||!e.restartSession)){A(!0),g(null),m(!1),h(!1),p();try{const F=c.current??Tl,R=await e.restartSession(W,{cwd:t,shell:o,loginShell:i,...F,...l.current});if(me.getState().getDirectoryState(t)?.tabs.find(I=>I.id===z)?.terminalSessionId!==W||(v(t,z,R.sessionId),P(t,z,"running"),u.current!==t||d.current!==z))return;f.current=R.sessionId,b(t,z,R.sessionId)}catch(F){if(me.getState().getDirectoryState(t)?.tabs.find(E=>E.id===z)?.terminalSessionId!==W||u.current!==t||d.current!==z)return;g(F instanceof Error?F.message:"Failed to restart terminal"),m(!1),h(!1),f.current=W,b(t,z,W)}finally{A(!1)}}},[n,d,u,t,r,S,c,p,g,m,h,P,v,b,e,l,f,i,o]),w=a.useCallback(async()=>{await j()},[j]),N=a.useCallback(()=>{if(!t)return;const $=y(t);x(t,$),g(null),m(!1),h(!1)},[y,t,x,g,m,h]),T=a.useCallback($=>{t&&(x(t,$),g(null),m(!1),h(!1))},[t,x,g,m,h]),L=a.useCallback($=>{if(!t)return;g(null),m(!1),h(!1);const z=me.getState().getDirectoryState(t)?.tabs.find(W=>W.id===$)?.terminalSessionId;(async()=>{z&&await e.close(z),C(t,$)})().catch(W=>g(W instanceof Error?W.message:"Terminal session ended"))},[C,t,g,m,h,e]);return{isRestarting:S,handleRestart:j,handleHardRestart:w,handleCreateTab:N,handleSelectTab:T,handleCloseTab:L}}const Ax=({visible:e,onCloseView:t,terminalHeaderSlot:n})=>{const{terminal:r,runtime:o}=Ms(),{currentTheme:i}=ka(),l=a.useRef({themeMode:"dark",terminalBackground:"",terminalForeground:""});l.current={themeMode:i.metadata.variant==="light"?"light":"dark",terminalBackground:i.colors.surface.background,terminalForeground:i.colors.syntax.base.foreground};const{monoFont:c}=ed(),u=le(se=>se.terminalFontSize),d=le(se=>se.terminalShell),f=le(se=>se.terminalLoginShells.includes(se.terminalShell)),{isMobile:p,isTablet:b,hasTouchOnlyPointer:g}=tn(),m=p||b,h=(m||g)&&o.platform==="web",y=!0,x=le(se=>se.showTerminalQuickKeysOnDesktop),C=m||x,v=Me(se=>se.currentSessionId),P=Me(se=>se.newSessionDraft),S=v!==null||P?.open===!0,A=td()??null,j=me(se=>A?se.sessions.get(A):void 0),w=me(se=>se.hasHydrated),N=le(se=>se.openContextPreview),T=a.useMemo(()=>j?j.activeTabId??j.tabs[0]?.id??null:null,[j,y]),L=a.useMemo(()=>{if(j)return T?j.tabs.find(se=>se.id===T)??j.tabs[0]:j.tabs[0]},[j,T]),$=a.useMemo(()=>(j?.tabs??[]).map(se=>({icon:(()=>{const Le=se.iconKey?jn[se.iconKey]??"terminal":"terminal";return s.jsx(D,{name:Le,className:"h-4 w-4"})})(),id:se.id,label:se.label,title:se.label,closeLabel:"Close tab"})),[j?.tabs]),z=L?.terminalSessionId??null,W=L?.lifecycle??"idle",F=a.useMemo(()=>(j?.tabs??[]).map(se=>({id:se.id,terminalSessionId:se.terminalSessionId,label:se.label})),[j?.tabs]),R=L?.isConnecting??!1,E=L?.previewUrl??null,M=le(se=>se.activeMainTab)==="terminal",G=e??M,[X,U]=a.useState(G);a.useEffect(()=>{G&&U(!0)},[G]);const{connectionError:ve,setConnectionError:Z,isFatalError:Re,setIsFatalError:Oe,isReconnectPending:Q,setIsReconnectPending:_,terminalIdRef:H,lastViewportSizeRef:J,directoryRef:ne,activeTabIdRef:fe,resetTerminalPreviewScan:he,startStream:q}=Mg({terminal:r,effectiveDirectory:A,activeTabId:T,terminalSessionId:z,terminalLifecycle:W,hasOpenedTerminalViewport:X,terminalHydrated:w,terminalShell:d,terminalLoginShell:f,terminalAppearanceRef:l,enableTabs:y,hasActiveContext:S,tabs:F,focusTerminalWhenWindowActive:()=>{!h&&typeof document<"u"&&document.hasFocus()&&ae.current?.focus()}}),{activeModifier:te,terminalControllerRef:ae,focusTerminalWhenWindowActive:je,handleViewportInput:Se,handleModifierToggle:Ge,handleMobileKeyPress:B}=Tg({terminal:r,terminalIdRef:H,isReconnectPending:Q,setConnectionError:Z,showQuickKeys:C,isTerminalVisible:G,lastViewportSizeRef:J,terminalSessionId:z,useTouchTerminalInput:h}),{isRestarting:re,handleRestart:pe,handleHardRestart:ge,handleCreateTab:ce,handleSelectTab:Fe,handleCloseTab:ye}=Fg({terminal:r,effectiveDirectory:A,activeTabId:T,enableTabs:y,terminalShell:d,terminalLoginShell:f,terminalAppearanceRef:l,lastViewportSizeRef:J,directoryRef:ne,activeTabIdRef:fe,terminalIdRef:H,resetTerminalPreviewScan:he,startStream:q,setConnectionError:Z,setIsFatalError:Oe,setIsReconnectPending:_});a.useEffect(()=>{if(!G||h)return;if(typeof window>"u"){je();return}const se=window.requestAnimationFrame(()=>{je()});return()=>{window.cancelAnimationFrame(se)}},[T,je,G,h]);const ee=a.useMemo(()=>{const se=un[Ir].stack;if(typeof window>"u")return(un[c]??un[Ir]).stack;const ct=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return ct&&ct.trim().length>0?ct.trim():(un[c]??un[Ir]).stack??se},[c]),xe=a.useMemo(()=>rg(i),[i]),ue=`${A??"no-dir"}::${T??"no-tab"}`;if(a.useEffect(()=>{if(!G||h)return;const se=ae.current;if(!se)return;const Le=()=>{se.fit()};if(typeof window<"u"){const ct=window.requestAnimationFrame(()=>{Le(),je()}),et=[220,400].map(Qe=>window.setTimeout(Le,Qe));return()=>{window.cancelAnimationFrame(ct),et.forEach(Qe=>window.clearTimeout(Qe))}}Le()},[je,G,h,ae,ue,z]),a.useEffect(()=>{if(!G||!h)return;let se=null;const Le=()=>{se!==null&&window.cancelAnimationFrame(se),se=window.requestAnimationFrame(()=>{se=null,ae.current?.fit()})};return window.addEventListener("oc:keyboard-settled",Le),()=>{window.removeEventListener("oc:keyboard-settled",Le),se!==null&&window.cancelAnimationFrame(se)}},[G,ae,ue,h]),!S)return s.jsx("div",{className:"flex h-full items-center justify-center p-4 text-center text-sm text-muted-foreground",children:"Select a session to open the terminal."});if(!A)return s.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 p-4 text-center text-sm text-muted-foreground",children:[s.jsx("p",{children:"No working directory available for this session."}),s.jsx("button",{onClick:pe,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const we=!z||R||re||Q,ze=X,qe=j?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"min-w-0 flex-1",children:s.jsx(qi,{items:$,activeId:T,onSelect:Fe,onClose:ye,onCreate:ce})}),s.jsx(Ee,{type:"button",size:"xs",variant:"ghost",className:"h-8 w-8 shrink-0 p-0",onClick:ce,title:"New tab","aria-label":"New tab",children:s.jsx(D,{name:"add",className:"h-4 w-4"})}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1 overflow-visible",children:[s.jsx(Ee,{type:"button",size:"xs",variant:"ghost",className:"h-8 w-8 p-0",onClick:()=>{pe()},disabled:re,title:"Restart terminal","aria-label":"Restart terminal",children:s.jsx(D,{name:"restart",className:"h-4 w-4"})}),E?s.jsxs(Ee,{type:"button",size:"xs",variant:"outline",className:"h-6 shrink-0 gap-1 px-2",onClick:()=>{A&&N(A,E)},title:"Open preview pane",children:[s.jsx(D,{name:"global",className:"h-3.5 w-3.5 shrink-0"}),s.jsx("span",{className:"whitespace-nowrap",children:"Preview"})]}):null]})]}):null,De=s.jsx(xg,{isTouchTerminal:m,activeModifier:te,disabled:we,onKeyPress:B,onModifierToggle:Ge}),Ye=!n||m||C;return s.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[qe&&n?bu.createPortal(s.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:qe}),n):null,m&&qe&&!n&&j?s.jsx(bg,{leading:s.jsx("div",{className:"min-w-0 flex-1 -ml-2",children:s.jsx(qi,{items:$,activeId:T,onSelect:Fe,onClose:ye,onCreate:ce})}),actions:s.jsxs(s.Fragment,{children:[s.jsx(Ee,{type:"button",variant:"ghost",size:"icon",onClick:ce,title:"New tab","aria-label":"New tab",children:s.jsx(D,{name:"add",className:"size-4"})}),s.jsx(Ee,{type:"button",variant:"ghost",size:"icon",onClick:()=>{pe()},disabled:re,title:"Restart terminal","aria-label":"Restart terminal",children:s.jsx(D,{name:"restart",className:"size-4"})}),E?s.jsxs(Ee,{type:"button",variant:"outline",size:"sm",className:"h-8 shrink-0 gap-1 px-2",onClick:()=>{A&&N(A,E)},title:"Open preview pane",children:[s.jsx(D,{name:"global",className:"size-3.5 shrink-0"}),s.jsx("span",{className:"whitespace-nowrap",children:"Preview"})]}):null,t?s.jsx(Ee,{type:"button",variant:"ghost",size:"icon",onClick:t,title:"Close terminal view","aria-label":"Close terminal view",children:s.jsx(D,{name:"close",className:"size-4"})}):null]})}):null,!m&&Ye?s.jsxs("div",{className:K("app-region-no-drag sticky top-0 z-20 shrink-0 bg-background text-xs","px-3 py-2"),children:[qe&&!n?s.jsxs("div",{className:"flex items-center gap-2 pl-1 pr-1",children:[qe,t?s.jsx(Ee,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 shrink-0 p-0",onClick:t,title:"Close terminal view","aria-label":"Close terminal view",children:s.jsx(D,{name:"close",className:"h-4 w-4"})}):null]}):null,!m&&C&&y&&j?s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1 pl-1 pr-1",children:De}):null,!m&&C&&!j?s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:De}):null]}):null,s.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:xe.background},children:[s.jsx("div",{className:"h-full w-full box-border pl-4 pr-1.5 pt-3 pb-4",children:ze&&A&&j?j.tabs.map(se=>{const Le=se.id===T;return s.jsx(gg,{directory:A,tabId:se.id,sessionId:se.terminalSessionId,sessionKey:`${A}::${se.id}`,isActive:Le,isTerminalVisible:G,terminal:r,theme:xe,fontFamily:ee,fontSize:u,enableTouchScroll:h,lastViewportSizeRef:J,onInput:Se,controllerRef:ae},se.id)}):null}),!Q&&ve&&s.jsxs("div",{className:"absolute inset-x-0 bottom-0 border-t border-[var(--status-error-border)] bg-[var(--status-error-background)] px-3 py-2 text-xs text-foreground flex items-center justify-between gap-2",children:[s.jsx("span",{children:ve}),Re&&m&&s.jsx(Ee,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:ge,disabled:re,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]}),m&&C?s.jsx("div",{className:"shrink-0 overflow-x-auto border-t border-border/40 bg-[var(--surface-background)] px-2 pt-1.5 pb-[max(0.375rem,calc(var(--oc-app-bottom-safe,0px)-var(--oc-keyboard-inset,0px)))] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden","data-no-drawer-swipe":"true",children:s.jsx("div",{className:"flex min-w-max items-center gap-1.5",children:De})}):null]})},Co=[{id:"changes",label:"Changes",icon:"git-branch"},{id:"files",label:"Files",icon:"file-text"},{id:"terminal",label:"Terminal",icon:"terminal-box"},{id:"pull-requests",label:"PRs",icon:"git-pull-request"},{id:"issues",label:"Issues",icon:"task"}],Lg=new Set(Co.map(e=>e.id)),Og=e=>typeof e=="string"&&Lg.has(e),Nx=e=>Og(e)?e:"changes",Fl=e=>e==="pull-requests"||e==="issues",Bg=e=>e?Co:Co.filter(t=>!Fl(t.id)),Ix=(e,t)=>Fl(e)?"changes":e,_g=48,Ug=96,xt=(e,...t)=>{try{e?.(...t)}catch{}},Kr=(e,t)=>{if(typeof e=="function"){const n=e();return n>0?n:t}return typeof e=="number"&&e>0?e:t},Ex=(e,t)=>{const n=a.useRef(t);n.current=t;const r=t.enabled;a.useEffect(()=>{const o=e.current;if(!o||r===!1)return;const i=o.style.touchAction;o.style.touchAction="pan-x pan-y";const c=window.Capacitor?.getPlatform?.()==="android"?Ug:_g;let u=!1,d=!1,f=!1,p=null,b=!1,g=0,m=0,h=0,y=0;const x=()=>{u=!1,d=!1,f=!1,p=null},C=()=>{const N=n.current,T=p,L=b;d&&T&&(xt(T==="left"?N.onLeftProgress:N.onRightProgress,L?1:0),xt(N.onDragEnd,T,L)),x()},v=()=>{C(),d||x()},P=N=>{const T=n.current;if(T.enabled===!1){d&&p?C():x();return}if(N.touches.length!==1){d&&p?C():x();return}const L=N.touches[0],$=o.getBoundingClientRect(),z=o.clientWidth,W=!!T.leftOpen,F=!!T.rightOpen,R=E=>Qp(E,o);if(W||F){if(R(N.target)){x();return}if(W&&F){const E=L.clientX<=$.left+c;L.clientX>=$.right-c?(p="right",b=!0):E?(p="left",b=!0):(p=W?"left":"right",b=!0)}else W?(p="left",b=!0):(p="right",b=!0);y=Kr(p==="left"?T.leftWidth:T.rightWidth,z),y<10&&(y=z||window.innerWidth||320),y<10&&(y=320),u=!0}else{if(R(N.target)){x();return}p=null,b=!1,y=0,u=!0}g=L.clientX,m=L.clientY,h=Date.now(),d=!1,f=!1},S=N=>{if(!u)return;if(N.touches.length!==1){v();return}const T=N.touches[0],L=T.clientX-g,$=T.clientY-m;if(!f){if(Math.abs(L)<$i&&Math.abs($)<$i)return;if(Math.abs($)>Math.abs(L)*gn){x();return}if(!p){const F=n.current;p=L>0?"left":"right",y=Kr(p==="left"?F.leftWidth:F.rightWidth,o.clientWidth),y<10&&(y=window.innerWidth||320)}if(p==="left"){if(!b&&L<=0){x();return}if(b&&L>=0){x();return}}else{if(!b&&L>=0){x();return}if(b&&L<=0){x();return}}f=!0,d=!0,xt(n.current.onDragStart,p)}if(!d)return;N.cancelable&&N.preventDefault();const z=n.current,W=Ki(p,b,L,y);xt(p==="left"?z.onLeftProgress:z.onRightProgress,W)},A=(N,T)=>{if(!u){x();return}const L=N-g,$=T-m;if(!p&&!b&&Math.abs(L)>=Zn&&Math.abs($)<=Math.abs(L)*gn){const I=n.current;p=L>0?"left":"right",y=Kr(p==="left"?I.leftWidth:I.rightWidth,o.clientWidth),y<10&&(y=window.innerWidth||320)}if(!p){x();return}const z=Math.max(1,Date.now()-h),W=n.current;if(!d){const I=Math.abs(L),M=Math.abs($);I>=Zn&&M<=I*gn?p==="left"&&!b&&L>0?(xt(W.onLeftProgress,1),xt(W.onLeftOpen)):p==="right"&&!b&&L<0?(xt(W.onRightProgress,1),xt(W.onRightOpen)):xt(p==="left"?W.onLeftProgress:W.onRightProgress,b?1:0):xt(p==="left"?W.onLeftProgress:W.onRightProgress,b?1:0);const G=p;x(),xt(W.onDragEnd,G);return}const F=Ki(p,b,L,y),R=qp({side:p,isOpenAtStart:b,dx:L,dt:z,progress:F}),E=p;xt(E==="left"?R?W.onLeftOpen:W.onLeftClose:R?W.onRightOpen:W.onRightClose),x(),xt(W.onDragEnd,E,R)},j=N=>{const T=N.changedTouches[0];if(!T){x();return}const L=T.clientX-g,$=T.clientY-m;u&&(d||Math.abs(L)>=Zn&&Math.abs($)<=Math.abs(L)*gn)&&N.cancelable&&N.preventDefault(),A(T.clientX,T.clientY)},w=()=>{v()};return o.addEventListener("touchstart",P,{passive:!0}),o.addEventListener("touchmove",S,{passive:!1}),o.addEventListener("touchend",j,{passive:!1}),o.addEventListener("touchcancel",w,{passive:!0}),()=>{try{d&&p&&C()}catch{}o.style.touchAction=i,o.removeEventListener("touchstart",P),o.removeEventListener("touchmove",S),o.removeEventListener("touchend",j),o.removeEventListener("touchcancel",w)}},[e,r])};function Rx({className:e="h-5 w-5"}){return s.jsxs("span",{"aria-hidden":"true",className:`relative inline-block overflow-hidden rounded-[2px] ${e}`,children:[s.jsx("span",{className:"absolute left-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-error)]/25"}),s.jsx("span",{className:"absolute right-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-success)]/25"}),s.jsx(D,{name:"layout-column",className:"absolute inset-0 h-full w-full"})]})}function Vi({size:e,className:t,style:n,...r}){return s.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 256 256",fill:"currentColor",className:t,style:{width:typeof e=="number"?`${e}px`:e,height:typeof e=="number"?`${e}px`:e,...n},...r,children:s.jsx("path",{d:"M112,148a12,12,0,0,0-12,12v19L69.17,148.2A4,4,0,0,1,68,145.37V97.94a36,36,0,1,0-24,0v47.43a27.81,27.81,0,0,0,8.2,19.8L83,196H64a12,12,0,0,0,0,24h48a12,12,0,0,0,12-12V160A12,12,0,0,0,112,148ZM56,52A12,12,0,1,1,44,64,12,12,0,0,1,56,52ZM212,158.06V110.63a27.81,27.81,0,0,0-8.2-19.8L173,60h19a12,12,0,0,0,0-24H144a12,12,0,0,0-12,12V96a12,12,0,0,0,24,0V77l30.83,30.83a4,4,0,0,1,1.17,2.83v47.43a36,36,0,1,0,24,0ZM200,204a12,12,0,1,1,12-12A12,12,0,0,1,200,204Z"})})}const zg=({sessionDirectory:e,draftDirectory:t,isNewSessionDraftOpen:n})=>n?t:e,$g=({activeProjectLabel:e,openDirectory:t,homeDirectory:n})=>mr(t,n)?null:e,Wr=()=>ks.filter(e=>no.has(e.id)).map(e=>({...Ma(e)})),Kg=()=>{if(typeof window>"u")return ro;const e=window.localStorage.getItem("openInAppId");return e&&so(e)?e:ro};let Gr=!1,zs=!1,hs=!1,ms=0,Cn=null;const Ji=()=>{Cn&&(clearTimeout(Cn),Cn=null)},Ss=Ts()((e,t)=>({selectedAppId:Kg(),availableApps:Wr(),hasLoadedApps:!1,isCacheStale:!1,isScanning:!1,initialize:()=>{if(Gr||typeof window>"u")return;Gr=!0;const n=(u,d=!0)=>{if(!Array.isArray(u)||u.length===0){e({availableApps:Wr(),hasLoadedApps:d});return}const f=new Set(u.map(m=>m.name)),p=new Map(u.map(m=>[m.name,m.iconDataUrl??void 0])),g=ks.filter(m=>f.has(m.appName)||no.has(m.id)).map(m=>({...Ma(m),iconDataUrl:p.get(m.appName)}));e({availableApps:g,hasLoadedApps:!0})},r=async u=>{if(!Vs()||!nr()||zs||t().hasLoadedApps&&!u)return;const f=ks.map(p=>p.appName);Ji(),zs=!0,hs=!1,e({isScanning:!0});try{const{apps:p,success:b,hasCache:g,isCacheStale:m}=await ci(f,u),h=b&&!g&&p.length===0&&ms<3;if(e({isCacheStale:g?m:!1}),n(p,b?!h:!1),b){if(h){const x=[800,1600,3200][ms]??3200;ms+=1,hs=!0,Cn=setTimeout(()=>{r()},x);return}ms=0,hs=!1;return}if(ms<3){const x=[1e3,3e3,7e3][ms]??7e3;ms+=1,hs=!0,Cn=setTimeout(()=>{r()},x)}}finally{zs=!1,hs||e({isScanning:!1})}};r();const o=u=>{const d=u.detail,f=d&&typeof d.openInAppId=="string"&&d.openInAppId.length>0&&so(d.openInAppId)?d.openInAppId:null;f&&(window.localStorage.setItem("openInAppId",f),e({selectedAppId:f}))},i=()=>{r()},l=u=>{const d=u.detail;Array.isArray(d)&&(ms=3,hs=!1,e({isScanning:!1,isCacheStale:!1}),n(d))};window.addEventListener("pichamber:settings-synced",o),window.addEventListener("pichamber:app-ready",i),window.addEventListener("pichamber:installed-apps-updated",l),window.__pichamberAppReady&&r(),window.setTimeout(()=>{t().hasLoadedApps||r()},5e3)},loadInstalledApps:async n=>{if(Gr||t().initialize(),!Vs()||!nr()||zs||t().hasLoadedApps&&!n)return;const o=ks.map(i=>i.appName);Ji(),n&&e({hasLoadedApps:!1}),zs=!0,hs=!1,e({isScanning:!0});try{const{apps:i,hasCache:l,isCacheStale:c}=await ci(o,n),u=new Set(i.map(b=>b.name)),d=new Map(i.map(b=>[b.name,b.iconDataUrl??void 0])),p=ks.filter(b=>u.has(b.appName)||no.has(b.id)).map(b=>({...b,iconDataUrl:d.get(b.appName)}));e({availableApps:p.length>0?p:Wr(),hasLoadedApps:p.length>0,isCacheStale:l?c:!1})}finally{zs=!1,hs||e({isScanning:!1})}},selectApp:async n=>{so(n)&&(e({selectedAppId:n}),typeof window<"u"&&window.localStorage.setItem("openInAppId",n),await Ea({openInAppId:n}))}})),Wg="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAeGVYSWZNTQAqAAAACAAEARoABQAAAAEAAAA+ARsABQAAAAEAAABGASgAAwAAAAEAAgAAh2kABAAAAAEAAABOAAAAAAAAAJAAAAABAAAAkAAAAAEAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAIKADAAQAAAABAAAAIAAAAAB+C9pSAAAACXBIWXMAABYlAAAWJQFJUiTwAAABnWlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyI+CiAgICAgICAgIDxleGlmOlBpeGVsWERpbWVuc2lvbj4yNTY8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpQaXhlbFlEaW1lbnNpb24+MjU2PC9leGlmOlBpeGVsWURpbWVuc2lvbj4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+Cl6wHhsAAAXaSURBVFgJ7VddbBRVFP5mdme6dOnu2tZawOAPjfxU+bGQYCRAsvw8qNGEQPTRJ0I0amL0wfjgA/HBR8KLD8YgDxJEUkVFxSYYTSRii6DQQCMGIQqlW7p0u+zMzo/fuTuzO9Nt0Td94CRn7pl7z5zznZ977y5wh/7jDGiz+T979qD5Ujbfd90xlll+stOF1uI40B1+4HhkjnZk9CgLQ9iXp2/BdcbgVc/h0sAgduywudJEMwLY9Of4ugtW5p3CpL7W1jTN88VmjdQYvnDKF1mczkYuNZLeCVg3X8fa9u+nqzUB2HRpdN2pSseRQknPoUL1Jo2ICTrPGcCzdwPdHENcAnicKRqcAk7cpL5J1r0JlAtPYV1XDETM/FtH3m19r+f5by+XjNX/xnmCX3/cCzydi4CKiC7lw+PArhGgoPPFq/6E0+9vwM6d5VBNpuv03cLNfeNTRh9KnJIiV2/PvSngycC5RD+dE5zb3g7s6QESzAZc2l6wuY9SnWIAxv10r81uU85Vt1FvtpEtlc/SMFUkUofeZ2IBta0DWDmXgkfbyTRz1qAYAMczOz3p1elOxYPyEllj421hdELViPO6Kudk3ia3UGe5ABDbvtnJZ52SdYmCZ3stdeexBabFdeAbYopEowtagVUZqFapBrtAGqpiVaFrGgyjZlrmTD5yEqoEJj4iFMuA62i6L3WPZkAiuHgarZ/vbWSBkTzO2rfTR4XOJVJhjfX44MBn+OTocVWbcF5MalxXPeVL6zYonoGo44YOtDI7qHC1lkL5nHnOc+tJRi3K6iygLNGMjt1A1XVV6iUzOvVtAvMlS2I/yBYlRf8MgA6szmXQ1jDfKhSgjft6DRtrkgarAiAw5nI9v2WDSn+Zxfd9DawGxIlPPQUg0A2HGABfEIYlCDU4+q0d8O+jRzHCCFYy+nu4BaeYAoksBCDrPYsXQQ6iitgiSQaS1FHHtMzFil4DpxTl4UhORSn4WOaaiGsbu4iFRkMnYQlEV0oSJQGQ4FyYgSRDjpqPZcCR6EOOWonIEsBqArAIQOMLzw0VXRRERF2VoA6Atk1+MzsASekMJYgaFEeHR4Cr85lNGntYzgKCYd/NSNIDCXr0ZJ2jwTsjSvEMzFQCCVmKHBRahn2DNb4rDRx8pnbXOOIg0JELLMHOF1AUkaRj1V8c2TookkMS83WK9QCVpRwtf5wCykQWRKDyJ44Ytc452QUV6inmN9IDIv/6y2+YLDuqTywBEHxv8rsoxQC4Fpf4cZ2pbJ4/huxXr0EvFmoRCrAIVymLQ3Eid0GJYPsPfISBLwdwi79YQnCqBNS7LQDP5qYSAKEDypOrX4WVWYLsFy+i9cwh6CUmUKIJI2Gq5cSbnLLw849D2Ld3L4olC1u3P0c1ow5Ozgixa3puWChONG1D3eLZUQOglvng+Vp5dBfseesx5/yHyI4cBTL3wsssRGs2g6/ppHijiMLoNSSMNHofy6Nn6SPsAR02nUoTtrDTSrdoi8CTni55rlOsCf1ypaDxlFMNU1epCV5XL6Y6dmOq+BeS48NIlq7Anpjg5dOFbPdDWLQyj/aubnUKSkMKi3NhkUd4kieYtbRbYS0bFAOQKI8NO363z1RJHmamtnlwhGksxV2w/gl29WRtm8kWtWUnRShLnQvXgDOXmLg2HzlvbDiyHD8Y517YP2i4FtueFPbB9FFqKcyobk4A5y7zquUFa7IXojyHoeXmAFcY755vaI6A56Xsofm/7+cmblBTpOldQ5vs3PJDVS+RVSAaus2SpJTO80t4NTNSOQfCDrtFkBevA0ME6HGvPdDpFlekzm7rf3nFQNRQEwBZTL9warObWfx21Uv1+fx1ERqVNampGoOHpF1tsdp07RnoGMxK1vT97rbK4IP6+Tc+fWXVsahaYGL6VO09d//GXHXr7jVeqmuppqU6ff4x0RO6lqRxgxHJpWKSlcw5eWfjq5rq/CdhaL5l6JWxjDc6bP7w5sn+/uMs2B36H2bgb6v9raK0+o9IAAAAAElFTkSuQmCC",Gg="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAeGVYSWZNTQAqAAAACAAEARoABQAAAAEAAAA+ARsABQAAAAEAAABGASgAAwAAAAEAAgAAh2kABAAAAAEAAABOAAAAAAAAAJAAAAABAAAAkAAAAAEAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAIKADAAQAAAABAAAAIAAAAAB+C9pSAAAACXBIWXMAABYlAAAWJQFJUiTwAAABnWlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyI+CiAgICAgICAgIDxleGlmOlBpeGVsWERpbWVuc2lvbj4yNTY8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpQaXhlbFlEaW1lbnNpb24+MjU2PC9leGlmOlBpeGVsWURpbWVuc2lvbj4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+Cl6wHhsAAAQzSURBVFgJ7VZNbBNHFH67Xv9RxwnBDqlUoQglcZK6qSIEJIQWAYJQoVY9IE5RTzn20FMvqdpDesq9B24+NdwthAJCkZChJg1JSOXYQIwQKQIaBdtENbs73t2+N8miGWOcpFHUHniyd97OvJ9v3nv7ZgDe038cAeVd/jOZjC94sKdfU+Bj24G9igpexwYPyiu2bauKqqqirkOTqmrjnIOyFsoyUKDocSCj/7mU7ujoMER5l68JYOFZ4YSiwPjd9O0jjx7ch1KhAJZVAcdx0LxDv3XetYKjggr4I4bzHo8G4aYmONjZBYf6+2dUzfd9PNowJajUZmef/PX5zcWl0rmvvnbQHrra+f/M+S+dqYXs2t3Hz09Ve5UicCmZ3NPb1Zv66btv+65dSULA64WGxkbw+Xx8V9XK9d4pWowxeFUqgW6acHroC/j5l0sLD/PZY98MDf3t6mouQ+On3X1H7/2e7rtOztHpgbY2+CAUgperq+D3+7cNgtLSEA7D0+VluDF5FS7cSff2HT56DF1dd/3KhQTWJ/lclsc8jIrk9IfRURgZGQEvRqNSWa8D2t1W/liXXK8Ro0i0lF0ExaPEXec0SgAqhrm3VCzwdS9GQNd1GBsbg0AgAIlEAlpbW7EYLVF/U56AagieiGwbuhERlSQApmEE8c/XKXxU0fF4HNowFfPz81Aul7edBjLGbeHITANsZga4g42HVAM2Y74KM/kSIQ/izgcHB2FiYgJmZmZ4MZpYULRG5PF4+Bx/2cLDxuhhYUqFLwGoWCaQEBGhNjAa4+Pj/J3SQA6pHpqbm/kcNitIJpOgaZIZvlbrQbZNJvcjSZOZDKhwRKLic4l2Pjc3B8FgkE+trKxAVUN0RWuOZNtCHyJJACj/bgREIZcnA9PT029SQM63unuywSOwUWOuTQmAhfmnlluPxIjUk6u1RrbJh0jyV0Ap2OZnJhrbjOcRqEqBBMDCAtltAORDJAkAVj2mWS5CUXinPDUx+oxFkgBYjO0qANu2wKoqQgkAfgW7C4AiYMmfoQSgwpjj7GYRUh/Q66SAmdisNxql227FfP1bXrRlVExdtCNHwDRLdPkgwmi8OUREhe3y1NLJFpEfbWMNvBRtSI2o+KqYi+zbx4NQwptMCO8E1HjEHYjKm/HknG5FZIsCG4lEoLS2lhP1JAB3bt1KH//s+GJPd3dPJpvlN5kwXiYIhHukisr1eAItXsm6YzGItrTcn5+dvS3qSQBSqVQhFouNnj039CsaCC7mcqDjgbNT6op1AtrU8Wo3Ojk5KaVAOptdR8PDwxf3t7SMvXjxvJNOPP31a35Krt8CXKl3j2SUDip/IAjRaBRaP9z/cHW18GMikbhcrVUTAAm1t7d/NDAwcDIUCvVqmtqkyLe3ajtvvTtg4x3SLpbLa3+kUr9N5fP55beE3k/8HyLwDx2/HIx7q3WfAAAAAElFTkSuQmCC",Hr=e=>({...e,fallbackIconDataUrl:e.id==="finder"&&window.__PICHAMBER_PLATFORM__==="darwin"?Wg:e.id==="terminal"?Gg:void 0}),Xi=({label:e,iconDataUrl:t,fallbackIconDataUrl:n})=>{const[r,o]=a.useState(!1),i=e.trim().slice(0,1).toUpperCase()||"?",l=t||n;return l&&!r?s.jsx("img",{src:l,alt:"",className:"h-4 w-4 rounded-sm",onError:()=>o(!0)}):s.jsx("span",{className:K("h-4 w-4 rounded-sm flex items-center justify-center","bg-[var(--surface-muted)] text-[9px] font-medium text-muted-foreground"),children:i})},Hg=({directory:e,className:t})=>{const n=Ss(m=>m.selectedAppId),r=Ss(m=>m.availableApps),o=Ss(m=>m.isCacheStale),i=Ss(m=>m.isScanning),l=Ss(m=>m.initialize),c=Ss(m=>m.loadInstalledApps),u=Ss(m=>m.selectApp);a.useEffect(()=>{l()},[l]);const d=Vs()&&nr(),f=a.useMemo(()=>{const m=r.find(h=>h.id===n)??r.find(h=>h.id===ro)??r[0]??ks[0];return Hr(m||ks[0])},[r,n]);if(!d||!e||r.length===0)return null;const p=async m=>{await Ed(e,m.id,m.appName)||await Da(e,m.appName)},b=async m=>{await u(m.id),await p(m)},g=async()=>{(await bs(e)).ok&&ie.success("Path copied to clipboard")};return s.jsxs("div",{className:K("app-region-no-drag inline-flex h-7 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",t),children:[s.jsx("button",{type:"button",onClick:()=>{p(f)},className:K("inline-flex h-full items-center px-2.5 typography-ui-label font-medium","text-foreground hover:bg-interactive-hover transition-colors",i&&"animate-pulse"),"aria-label":`Open in ${f.label}`,children:s.jsx(Xi,{label:f.label,iconDataUrl:f.iconDataUrl,fallbackIconDataUrl:f.fallbackIconDataUrl})}),s.jsxs(Jt,{children:[s.jsx(Xt,{asChild:!0,children:s.jsx("button",{type:"button",className:K("inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors"),"aria-label":"Choose app to open",children:s.jsx(D,{name:"arrow-down-s",className:"h-4 w-4"})})}),s.jsxs(Zt,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[s.jsxs(mt,{className:"flex items-center gap-2",onClick:()=>{g()},children:[s.jsx(D,{name:"file-copy",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:"Copy Path"})]}),s.jsx(Qs,{}),r.map(m=>{const h=Hr(m);return s.jsxs(mt,{className:"flex items-center gap-2",onClick:()=>{b(m)},children:[s.jsx(Xi,{label:m.label,iconDataUrl:m.iconDataUrl,fallbackIconDataUrl:h.fallbackIconDataUrl}),s.jsx("span",{className:"typography-ui-label text-foreground",children:m.label}),f.id===m.id?s.jsx(D,{name:"check",className:"ml-auto h-4 w-4 text-primary"}):null]},m.id)}),o?s.jsxs(mt,{className:"flex items-center gap-2",onClick:()=>{c(!0)},children:[s.jsx(D,{name:"refresh",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:"Refresh Apps"})]}):null]})]})]})},qg="\x1B",Yg=new RegExp(`${qg}\\[[0-9;?]*[ -/]*[@-~]`,"g"),Qg=/https?:\/\/[^\s<>'"`]+/gi,jt="__pichamber_auto_discover_preview__",Vg=15e3,Jg=e=>{let t="";for(let n=0;n<e.length;n+=1){const r=e.charCodeAt(n);r>=0&&r<=8||r===11||r===12||r>=14&&r<=31||r===127||(t+=e[n])}return t},Xg=e=>{const t=(e||"").trim();if(!t)return null;const n=/^https?:\/\//i.test(t)?t:`http://${t}`;try{const r=new URL(n);return r.protocol!=="http:"&&r.protocol!=="https:"?null:r.toString()}catch{return null}},Zg=e=>{const n=e.replace(Yg,"").match(Qg);if(!n||n.length===0)return null;const r=n.map(i=>i.replace(/[),.;]+$/,"")).filter(Boolean);if(r.length===0)return null;const o=[];for(const i of r)try{const l=new URL(i);l.port&&l.port.length>0&&o.push({raw:i,parsed:l})}catch{}if(o.length>0){const i=l=>{const{parsed:c}=l,u=c.hostname.toLowerCase(),d=u==="localhost"||u==="127.0.0.1"||u==="0.0.0.0"||u==="::1",f=c.pathname||"/",p=f.split("/").filter(Boolean).length,b=f==="/"||f==="",g=!!(c.search||c.hash);let m=0;return d&&(m+=50),b&&(m+=30),m-=Math.min(p*5,20),g&&(m-=10),m};return o.sort((l,c)=>i(c)-i(l)),o[0]?.parsed.origin??o[0]?.raw??null}return r[0]??null},eb=[{pattern:/^dev(:.*)?$/i},{pattern:/^start(:.*)?$/i},{pattern:/^preview(:.*)?$/i},{pattern:/^serve(:.*)?$/i},{pattern:/^develop(:.*)?$/i}],tb=["dev","start","preview","serve"];async function sb(e,t,n){if(!e)return null;const r=ob(t);if(r)return{command:r.command,label:r.name||"Start Preview",actionId:r.id,previewUrlHint:r.openUrl};if(n){const o=ib(n);if(o){const i=await ab(e);return{command:`${i==="npm"?"npm run":i==="yarn"?"yarn":i==="pnpm"?"pnpm":i==="bun"?"bun run --shell=bun":"npm run"} ${o}`,label:`Start (${o})`}}}if(await nb(e)){const o=await rb(),i=typeof o=="number"&&Number.isFinite(o)&&o>0?o:8e3;return{command:`python3 -m http.server ${i}`,label:"Static preview",previewUrlHint:`http://127.0.0.1:${i}/`}}return null}async function nb(e){const t=`${e}/index.html`,n=await hr(t,e);return typeof n=="string"&&n.trim().length>0}async function rb(){try{const e=await Pt("/api/system/free-port",{cache:"no-store"});if(!e.ok)return null;const t=await e.json().catch(()=>null),n=typeof t?.port=="number"?t.port:null;return n&&Number.isFinite(n)?n:null}catch{return null}}function ob(e){for(const t of e){const n=`${t.name} ${t.command}`.toLowerCase();if(tb.some(o=>n.includes(o)))return t}return null}function ib(e){for(const{pattern:t}of eb)for(const n of Object.keys(e))if(t.test(n))return n;return null}async function ab(e){const t=await hr(`${e}/package.json`,e);if(t)try{const r=JSON.parse(t),o=typeof r.packageManager=="string"?r.packageManager.toLowerCase():"";if(o.startsWith("bun@"))return"bun";if(o.startsWith("pnpm@"))return"pnpm";if(o.startsWith("yarn@"))return"yarn";if(o.startsWith("npm@"))return"npm"}catch{}const n=[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"],["package-lock.json","npm"]];for(const[r,o]of n){const i=await hr(`${e}/${r}`,e);if(typeof i=="string"&&i.trim().length>0)return o}return"npm"}async function hr(e,t){if(t?.trim())try{const r=new URLSearchParams({path:e,directory:t,optional:"true"}),o=await Pt(`/api/fs/read?${r.toString()}`,{cache:"no-store"});if(o.ok)return o.text()}catch{}const n=Ra()?.files;if(n?.readFile)try{const r=await n.readFile(e,{optional:!0});return typeof r?.content=="string"?r.content:null}catch{return null}try{const r=await Pt(`/api/fs/read?path=${encodeURIComponent(e)}&optional=true`,{cache:"no-store"});return r.ok?r.text():null}catch{return null}}async function lb(e){try{const t=await hr(`${e}/package.json`,e);if(t==null)return null;const r=JSON.parse(t).scripts;return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}const cb=(e,t,n)=>new Promise(r=>{let o=!1,i=null,l=null;const c=u=>{o||(o=!0,l&&clearTimeout(l),i?.close(),r(u))};i=e.connect(t,{onEvent:u=>{(u.type==="exit"||u.type==="snapshot"&&u.status==="exited")&&c(!0)},onError:(u,d)=>{d&&c(!0)}}),o?i.close():l=setTimeout(()=>c(!1),n)});function ub({projectRef:e,directory:t,allowMobile:n=!1}){const{currentTheme:r}=ka(),{terminal:o}=Ms(),{isMobile:i}=tn(),l=le(B=>B.terminalShell),c=le(B=>B.terminalLoginShells.includes(B.terminalShell)),u=le(B=>B.setSettingsPage),d=le(B=>B.setSettingsDialogOpen),f=le(B=>B.setSettingsProjectsSelectedId),p=le(B=>B.openContextPreview),b=me(B=>B.ensureDirectory),g=me(B=>B.setTabLabel),m=me(B=>B.setTabIconKey),h=me(B=>B.setActiveTab),y=me(B=>B.setConnecting),x=me(B=>B.setTabSessionId),C=me(B=>B.setTabPreviewUrl),v=me(B=>B.projectActionRuns),P=me(B=>B.setProjectActionRun),S=me(B=>B.updateProjectActionRunStatus),A=me(B=>B.removeProjectActionRun),[j,w]=a.useState([]),[N,T]=a.useState(null),[L,$]=a.useState(!1),z=a.useRef({}),W=a.useRef({}),F=a.useRef({}),R=a.useRef({}),E=a.useRef(new Set),I=a.useRef(0),M=e?.id??null,G=e?.path??"",X=a.useMemo(()=>M?{id:M,path:G}:null,[M,G]),U=a.useCallback(async B=>{await ha(B)},[]),ve=a.useCallback(async()=>{if(!X)return;const B=I.current+1;I.current=B,$(!0);try{const re=await Vr(X);if(I.current!==B)return;const pe=re.actions;w(pe),T(ge=>ge===jt||ge&&pe.some(ce=>ce.id===ge)?ge:null)}catch{if(I.current!==B)return}finally{I.current===B&&$(!1)}},[X]),Z=a.useMemo(()=>el(t||X?.path||""),[t,X?.path]),Re=a.useMemo(()=>N?j.find(B=>B.id===N)??null:null,[j,N]),Oe=a.useMemo(()=>({id:jt,name:"Auto-discover",command:"",icon:"scan-2",autoOpenUrl:!0}),[]),Q=!i,_=a.useMemo(()=>Q?[Oe,...j]:j,[j,Oe,Q]);a.useEffect(()=>{ve()},[ve]),a.useEffect(()=>{if(typeof window>"u")return;const B=re=>{const pe=re.detail;M&&(pe?.projectId&&pe.projectId!==M||ve())};return window.addEventListener(uo,B),()=>{window.removeEventListener(uo,B)}},[ve,M]),a.useEffect(()=>{N&&(N===jt&&Q||j.some(B=>B.id===N)||T(null))},[j,Q,N]),a.useEffect(()=>{const B=()=>{const re=me.getState(),pe=re.sessions,ge=re.projectActionRuns;for(const[ce,Fe]of Object.entries(ge)){const ee=pe.get(Fe.directory)?.tabs.find(Le=>Le.id===Fe.tabId);if(!ee||ee.terminalSessionId!==Fe.sessionId){A(ce);continue}const xe=W.current[ce]??{lastSeenChunkId:null,openedUrl:!1,tail:"",openInPreview:!1};W.current[ce]=xe;const ue=_.find(Le=>Le.id===Fe.actionId),we=re.getBuffer(Fe.directory,Fe.tabId).chunks;if(!ue||we.length===0)continue;const ze=we.filter(Le=>xe.lastSeenChunkId===null||Le.id>xe.lastSeenChunkId);if(ze.length===0)continue;const qe=ze.map(Le=>Le.data).join(""),De=`${xe.tail}${qe}`,Ye=!xe.openedUrl&&ue.autoOpenUrl===!0?Zg(De):null,se=ze[ze.length-1]?.id??xe.lastSeenChunkId;if(xe.lastSeenChunkId=se,xe.tail=De.slice(-512),Ye)if(xe.openedUrl=!0,xe.openInPreview){const Le=ge[ce];Le&&(C(Le.directory,Le.tabId,Ye,{locked:!1,autoOpened:!1}),Le.status==="waiting-for-preview"&&S(ce,"running"),window.clearTimeout(R.current[ce]),delete R.current[ce],p(Le.directory,Ye))}else U(Ye),ie.success("Opened URL from action output");W.current[ce]=xe}for(const ce of Object.keys(W.current))ge[ce]||(delete W.current[ce],window.clearTimeout(R.current[ce]),delete R.current[ce])};return B(),me.subscribe((re,pe)=>{(re.sessions!==pe.sessions||re.buffers!==pe.buffers)&&B()})},[_,p,U,v,A,C,S]);const H=a.useCallback(async(B,re={})=>{if(!Z)throw new Error("No active directory");const pe=rs(Z,B.id);b(Z);const ge=me.getState(),ce=ge.getDirectoryState(Z);let Fe=z.current[pe]||null;const ye=Fe?!!ce?.tabs.some(ue=>ue.id===Fe):!1;(!Fe||!ye)&&(Fe=ge.createTab(Z),z.current[pe]=Fe),g(Z,Fe,`Action: ${B.name}`),m(Z,Fe,B.icon||"play"),h(Z,Fe),re.revealTerminal!==!1&&le.getState().openContextPanelTab(Z,{mode:"terminal"});const xe=me.getState().getDirectoryState(Z)?.tabs.find(ue=>ue.id===Fe);return{key:pe,tabId:Fe,sessionId:xe?.terminalSessionId??null}},[b,Z,h,m,g]),J=a.useCallback(async B=>{if(!n&&i)return;if(!Z){ie.error("No active directory for action");return}const re=rs(Z,B.id),pe=v[re];if(!(pe&&pe.status==="running")&&!E.current.has(re)){E.current.add(re);try{const ge=B.id===jt?await(async()=>{const[De,Ye]=await Promise.all([Vr({id:X?.id??"",path:Z}),lb(Z)]),se=await sb(Z,De.actions,Ye);if(!se)throw new Error('No dev server command found. Configure a project action or add a "dev" script to package.json.');return{id:jt,name:"Auto-discover",command:se.command,icon:"scan-2",autoOpenUrl:!0,openUrl:se.previewUrlHint||""}})():B,ce=ge.autoOpenUrl===!0&&(ge.openUrl||"").trim().length>0,Fe=!ce&&B.id!==jt,{key:ye,tabId:ee,sessionId:xe}=await H(ge,{revealTerminal:Fe});let ue=xe;if(!ue){y(Z,ee,!0);try{ue=(await o.createSession({cwd:Z,sessionId:ee,shell:l,loginShell:c,themeMode:r.metadata.variant==="light"?"light":"dark",terminalBackground:r.colors.surface.background,terminalForeground:r.colors.syntax.base.foreground})).sessionId,x(Z,ee,ue)}finally{y(Z,ee,!1)}}if(!ue)throw new Error("Failed to create terminal session");F.current[ye]?.(),y(Z,ee,!0);const we=o.connect(ue,{onEvent:De=>{De.type==="snapshot"&&(me.getState().replaceBuffer(Z,ee,De.data??"",De.sequence??0),me.getState().setConnecting(Z,ee,!1)),De.type==="data"&&typeof De.data=="string"&&De.data.length>0&&me.getState().appendToBuffer(Z,ee,De.data,De.sequence,De.replayData),De.type==="exit"&&(me.getState().setTabLifecycle(Z,ee,"exited"),me.getState().setConnecting(Z,ee,!1),me.getState().removeProjectActionRun(ye),delete W.current[ye],F.current[ye]?.(),delete F.current[ye],window.clearTimeout(R.current[ye]),delete R.current[ye])},onError:(De,Ye)=>{me.getState().setConnecting(Z,ee,!1),Ye&&(me.getState().setTabLifecycle(Z,ee,"exited"),me.getState().setTabSessionId(Z,ee,null),me.getState().removeProjectActionRun(ye))}});F.current[ye]=we.close;const ze=ge.autoOpenUrl?Xg(ge.openUrl):null;P({key:ye,directory:Z,actionId:ge.id,tabId:ee,sessionId:ue,status:ge.id===jt&&!ze?"waiting-for-preview":"running"}),window.clearTimeout(R.current[ye]),delete R.current[ye],ge.id===jt&&!ze&&(R.current[ye]=window.setTimeout(()=>{const De=me.getState(),Ye=De.projectActionRuns[ye];De.updateProjectActionRunStatus(ye,"running"),Ye&&(De.setActiveTab(Ye.directory,Ye.tabId),le.getState().openContextPanelTab(Ye.directory,{mode:"terminal"})),delete R.current[ye]},Vg)),W.current[ye]={lastSeenChunkId:null,openedUrl:!!ze||ce,tail:"",openInPreview:ge.id===jt};const qe=Jg(ge.command.trim().replace(/\r\n|\r/g,`
|
|
62
|
+
`));await o.sendInput(ue,`${qe}\r`),ze?(C(Z,ee,ze,{locked:!0,autoOpened:!0}),p(Z,ze),ie.success("Opened action URL")):ce?(C(Z,ee,null,{locked:!0}),ie.error("Invalid custom URL format")):C(Z,ee,null,{locked:!1,autoOpened:!1})}catch(ge){A(re),delete W.current[re],F.current[re]?.(),delete F.current[re],window.clearTimeout(R.current[re]),delete R.current[re],ie.error(ge instanceof Error?ge.message:"Failed to run action")}finally{E.current.delete(re)}}},[r.colors.surface.background,r.colors.syntax.base.foreground,r.metadata.variant,H,n,i,Z,c,l,p,v,A,y,P,C,x,X?.id,o]),ne=a.useCallback(async B=>{const re=rs(Z,B.id),pe=v[re];if(!pe)return;S(re,"stopping");const ge=cb(o,pe.sessionId,1e3);try{await o.sendInput(pe.sessionId,"")}catch{}const ce=await ge;if(me.getState().getDirectoryState(pe.directory)?.tabs.find(ee=>ee.id===pe.tabId)?.terminalSessionId===pe.sessionId&&!ce){if(typeof o.forceKill=="function")try{await o.forceKill({sessionId:pe.sessionId})}catch{}else try{await o.close(pe.sessionId)}catch{}x(pe.directory,pe.tabId,null)}A(re),delete W.current[re],F.current[re]?.(),delete F.current[re],window.clearTimeout(R.current[re]),delete R.current[re]},[Z,v,A,x,o,S]),fe=a.useCallback(()=>{const B=Re??_[0];if(!B)return;const re=rs(Z,B.id),pe=v[re];if(pe?.status!=="stopping"){if(pe){ne(B);return}J(B)}},[_,Z,J,v,Re,ne]),he=a.useCallback((B,re=!1)=>{if(T(B.id),!re){J(B);return}const pe=rs(Z,B.id),ge=v[pe];if(ge?.status!=="stopping"){if(ge){ne(B);return}J(B)}},[Z,J,v,ne]),q=a.useCallback(()=>{X?.id&&(f(X.id),u("projects"),d(!0))},[d,u,f,X?.id]),te=Re??_[0]??null,ae=te?v[rs(Z,te.id)]:null,je=me(B=>ae?B.sessions.get(ae.directory)?.tabs.find(re=>re.id===ae.tabId)?.previewUrl??null:null),Se=!!((n||!i)&&X&&Z),Ge=Re??_[0]??null;return{shouldRender:Se,isLoading:L,normalizedDirectory:Z,resolvedSelected:Ge,displayActions:_,projectActionRuns:v,selectedRunPreviewUrl:je,handlePrimaryClick:fe,handleSelectAction:he,openProjectActionsSettings:q,openContextPreview:p}}const Zi=({projectRef:e,directory:t,className:n,compact:r=!1,allowMobile:o=!1})=>{const{shouldRender:i,isLoading:l,normalizedDirectory:c,resolvedSelected:u,displayActions:d,projectActionRuns:f,selectedRunPreviewUrl:p,handlePrimaryClick:b,handleSelectAction:g,openProjectActionsSettings:m,openContextPreview:h}=ub({projectRef:e,directory:t,allowMobile:o});if(!i||!u)return null;const y=u.icon||"play",x=u.id===jt?"scan-2":jn[y]||"play",C=rs(c,u.id),v=f[C],P=v?.status==="stopping",S=v?.status==="waiting-for-preview",A=!!(v&&p),j=()=>{!v||!p||h(v.directory,p)},w=u.id===jt;return r?s.jsxs("div",{className:"inline-flex items-center",children:[s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",disabled:l||P,className:K("app-region-no-drag inline-flex h-9 w-9 items-center justify-center rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] p-2","typography-ui-label font-medium text-muted-foreground hover:bg-interactive-hover hover:text-foreground transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","disabled:cursor-not-allowed",n),onClick:b,"aria-label":v?`Stop ${u.name}`:`Run ${u.name}`,children:P||S?s.jsx(D,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):v?s.jsx(D,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):s.jsx(D,{name:x,className:"h-5 w-5"})})}),w?s.jsx(We,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),A?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",className:"app-region-no-drag -ml-1 inline-flex h-9 w-7 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Open Preview",onClick:j,children:s.jsx(D,{name:"global",className:"h-4 w-4"})})}),s.jsx(We,{sideOffset:6,children:"Open Preview"})]}):null,s.jsxs(Jt,{children:[s.jsx(Xt,{asChild:!0,children:s.jsx("button",{type:"button",className:"app-region-no-drag -ml-1 inline-flex h-9 w-5 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Choose project action",children:s.jsx(D,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})}),s.jsxs(Zt,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[s.jsxs(mt,{className:"flex items-center gap-2",onClick:m,children:[s.jsx(D,{name:"add",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),s.jsx(Qs,{}),d.map(N=>{const T=N.icon||"play",L=N.id===jt?"scan-2":jn[T]||"play",$=rs(c,N.id),z=f[$],W=!!z,F=z?.status==="stopping";return s.jsxs(mt,{className:"flex items-center gap-2",onClick:()=>{g(N,!0)},children:[s.jsx(D,{name:L,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:N.name}),F||z?.status==="waiting-for-preview"?s.jsx(D,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):W?s.jsx(D,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},N.id)})]})]})]}):s.jsxs("div",{className:K("app-region-no-drag inline-flex shrink-0 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",r?"h-9":"h-7",n),children:[s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:b,disabled:l||P,className:K("inline-flex h-full items-center justify-center typography-ui-label font-medium text-foreground hover:bg-interactive-hover",r?"w-9 px-0":"px-2.5","transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed"),"aria-label":v?`Stop ${u.name}`:`Run ${u.name}`,children:s.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center",children:P||S?s.jsx(D,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):v?s.jsx(D,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):s.jsx(D,{name:x,className:"h-4 w-4"})})})}),w?s.jsx(We,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),A?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:j,className:K(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-foreground","hover:bg-interactive-hover transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":"Open Preview",children:s.jsx(D,{name:"global",className:"h-4 w-4"})})}),s.jsx(We,{sideOffset:6,children:"Open Preview"})]}):null,s.jsxs(Jt,{children:[s.jsx(Xt,{asChild:!0,children:s.jsx("button",{type:"button",className:K(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":"Choose project action",children:s.jsx(D,{name:"arrow-down-s",className:"h-4 w-4"})})}),s.jsxs(Zt,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[s.jsxs(mt,{className:"flex items-center gap-2",onClick:m,children:[s.jsx(D,{name:"add",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),s.jsx(Qs,{}),d.map(N=>{const T=N.icon||"play",L=N.id===jt?"scan-2":jn[T]||"play",$=rs(c,N.id),z=f[$],W=!!z,F=z?.status==="stopping";return s.jsxs(mt,{className:"flex items-center gap-2",onClick:()=>{g(N,!0)},children:[s.jsx(D,{name:L,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:N.name}),F||z?.status==="waiting-for-preview"?s.jsx(D,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):W?s.jsx(D,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},N.id)})]})]})]})},_t={docker:"docker",windows:"windows",ubuntu:"ubuntu-fill",arch:"arch-linux",nixos:"nixos",fedora:"fedora",debian:"debian",centos:"centos-fill",linux:"terminal-box",darwin:"apple",unknown:"server"};function tr(e){return e?.deploymentKind==="docker"?{name:_t.docker,color:"#2496ED"}:e?.serverPlatform==="win32"?{name:_t.windows,color:"#0078D4"}:e?.serverPlatform==="linux"?e.serverDistribution==="ubuntu"?{name:_t.ubuntu,color:"#E95420"}:e.serverDistribution==="arch"?{name:_t.arch,color:"#1793D1"}:e.serverDistribution==="nixos"?{name:_t.nixos,color:"#5277C3"}:e.serverDistribution==="fedora"?{name:_t.fedora,color:"#51A2DA"}:e.serverDistribution==="debian"?{name:_t.debian,color:"#A81D33"}:e.serverDistribution==="centos"?{name:_t.centos,color:"#932279"}:{name:_t.linux}:e?.serverPlatform==="darwin"?{name:_t.darwin}:{name:_t.unknown}}const db=e=>e?.deploymentKind==="docker"?"Docker":e?.serverPlatform==="win32"?"Windows":e?.serverPlatform==="darwin"?"macOS":e?.serverPlatform==="linux"?typeof e.serverDistribution=="string"&&e.serverDistribution.trim()?{ubuntu:"Ubuntu",arch:"Arch Linux",nixos:"NixOS",fedora:"Fedora",debian:"Debian",centos:"CentOS"}[e.serverDistribution]??"Linux":"Linux":"Server";function fb({open:e,onOpenChange:t}){const[n,r]=a.useState(null),o=a.useCallback(async()=>{const d=Je();try{const f=await Pt("/api/version");if(!f.ok)throw new Error("Version request failed");const p=await f.json().catch(()=>null);d===Je()&&r(p)}catch{d===Je()&&r(null)}},[]);a.useEffect(()=>(o(),Rn(()=>{o()})),[o]);const i=tr(n),l=db(n),c=typeof n?.pichamberVersion=="string"?n.pichamberVersion:null,u=typeof window<"u"?window.location.origin:"";return s.jsxs(Jt,{open:e,onOpenChange:d=>{t(d),d&&o()},children:[s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx(Xt,{asChild:!0,children:s.jsxs("button",{type:"button","aria-label":"Show connected server information",className:K(sn,"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5"),children:[s.jsx(D,{name:i.name,className:"h-[18px] w-[18px] shrink-0",style:i.color?{color:i.color}:void 0}),s.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:"This server"})]})})}),s.jsx(We,{children:s.jsx("p",{children:"Connected server information"})})]}),s.jsxs(Zt,{align:"end",className:"w-80 max-w-[calc(100vw-2rem)] p-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-4",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-2.5",children:[s.jsx(D,{name:i.name,className:"size-5 shrink-0",style:i.color?{color:i.color}:void 0}),s.jsx("div",{className:"truncate typography-ui-label font-medium text-foreground",children:l})]}),c?s.jsx("div",{className:"shrink-0 typography-micro text-muted-foreground",children:`v${c}`}):null]}),s.jsx("div",{className:"mt-3 border-t border-[var(--interactive-border)] pt-3 typography-micro",children:s.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[s.jsx("span",{className:"shrink-0 text-muted-foreground",children:"Address"}),s.jsxs("button",{type:"button",className:"ml-auto flex min-w-0 items-center gap-1.5 rounded px-1 py-0.5 text-foreground hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",title:`Copy ${u}`,"aria-label":"Copy server address",onClick:()=>{bs(u).then(d=>{d.ok?ie.success("Server address copied"):ie.error("Could not copy server address")})},children:[s.jsx("span",{className:"block max-w-[30ch] truncate font-mono",children:u}),s.jsx(D,{name:"file-copy",className:"size-3.5 shrink-0 text-muted-foreground"})]})]})})]})]})}const hb=({isMobile:e})=>{const n=Ms().github??null,r=br(i=>i.refresh),o=dh();return a.useEffect(()=>{!n||e||r(n)},[n,e,r]),e||!n||!o?null:s.jsxs("span",{className:K(sn,"app-region-no-drag inline-flex w-auto cursor-default gap-1.5 px-2"),title:`${o} via GitHub CLI`,"aria-label":`Signed in to GitHub as ${o} via GitHub CLI`,children:[s.jsx(D,{name:"github-fill",className:"h-3.5 w-3.5 shrink-0 text-foreground"}),s.jsxs("span",{className:"max-w-28 truncate typography-micro text-muted-foreground",children:["@",o]})]})},mb=a.memo(function({isDesktopApp:t,currentInstanceLabel:n,compactCurrentInstanceLabel:r,currentInstanceIsLocal:o,currentInstanceIcon:i,isDesktopServicesOpen:l,setIsDesktopServicesOpen:c,refreshCurrentInstanceLabel:u,shortcutLabel:d,remoteUpdateInfo:f,remoteUpdateChecking:p,remoteUpdateError:b,onOpenRemoteUpdate:g}){return s.jsxs(Jt,{open:l,onOpenChange:m=>{c(m),m&&u()},children:[s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx(Xt,{asChild:!0,children:s.jsxs("button",{type:"button","aria-label":t?`Open instance, usage and MCP (current: ${n})`:"Open services, usage and MCP",className:K(sn,t?"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5":"h-8 w-8"),children:[s.jsx(D,{name:i.name,className:"h-[18px] w-[18px]",style:i.color?{color:i.color}:void 0}),t?s.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:r}):null]})})}),s.jsx(We,{children:s.jsx("p",{children:`Current instance: ${n} (${d("toggle_services_menu")})`})})]}),s.jsx(Zt,{align:"end",className:"w-[min(27rem,calc(100vw-2rem))] max-h-[75vh] overflow-y-auto p-0",children:t?s.jsxs("div",{children:[o?null:s.jsx("div",{className:"border-b border-[var(--interactive-border)] px-4 py-2.5",children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Remote instance update"}),s.jsx("div",{className:"typography-micro text-muted-foreground",children:f?.available?`Version ${f.version||""} is available for this instance.`:p?"Looking for updates...":b||"This instance is up to date."})]}),f?.available?s.jsx("button",{type:"button",className:"shrink-0 rounded-md bg-[var(--primary-base)] px-3 py-1.5 typography-ui-label font-medium text-[var(--primary-foreground)] hover:opacity-90",onClick:g,children:"Update"}):null]})}),s.jsx(sd,{embedded:!0,open:l,onOpenChange:()=>{},onHostSwitched:()=>c(!1)})]}):null})]})}),pb=({action:e,onClose:t,sessionTitle:n,onConfirm:r})=>s.jsx(es,{open:e!==null,onOpenChange:o=>{o||t()},children:s.jsxs(ts,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(xs,{children:[s.jsx(as,{children:e==="delete"?"Delete session?":"Archive session?"}),s.jsx(ys,{children:e==="delete"?`"${n}" will be permanently deleted.`:`"${n}" will be archived.`})]}),s.jsxs(Ds,{children:[s.jsx(Ee,{variant:"outline",size:"sm",onClick:t,children:"Cancel"}),s.jsx(Ee,{variant:"destructive",size:"sm",onClick:r,children:e==="delete"?"Delete":"Archive"})]})]})}),gb=e=>{const t=e.trim();if(!t)return"";const n=t.split(/\s+/).filter(Boolean);if(n.length>=2){const r=n[0],o=n[1].slice(0,3),i=`${r} ${o}`.trim();return n.length>2||i.length<t.length?`${i}...`:i}return t.length>12?`${t.slice(0,9).trimEnd()}...`:t},mn=e=>{if(!e)return"";const t=e.replace(/\\/g,"/");return t==="/"?"/":t.replace(/\/+$/,"")},bb=a.lazy(()=>dt(()=>import("./SessionSwitcherDropdown-cC9wVBH7.js"),__vite__mapDeps([46,10,9,4,5,1,2,3,6,7,8,11])).then(e=>({default:e.SessionSwitcherDropdown}))),Dx=({onToggleLeftDrawer:e,onToggleRightDrawer:t,leftDrawerOpen:n,rightDrawerOpen:r,tabletWorkspaceTab:o,onSelectTabletWorkspaceTab:i,tabletGitHubTabsAvailable:l=!1})=>{zt("ui.header.render");const c=le(O=>O.setSessionSwitcherOpen),u=le(O=>O.toggleSidebar),d=le(O=>O.isSidebarOpen),f=le(O=>O.activeMainTab),p=le(O=>O.setActiveMainTab),b=le(O=>O.shortcutOverrides);le(O=>O.timeFormatPreference),Ms();const g=Me(O=>!!O.newSessionDraft?.open),m=Me(O=>O.currentSessionId),h=Ca(m??""),y=nd(m),x=a.useMemo(()=>{if(!y)return null;const O=y;return{title:y.title??null,directory:O.directory??null,created:y.time?.created??null,slug:O.slug??null,shareUrl:y.share?.url??null,parentId:y.parentID??null}},[y]),C=ht(Yr(O=>{if(!O.activeProjectId)return null;const oe=O.projects.find(be=>be.id===O.activeProjectId);return oe?{id:oe.id,path:oe.path,label:oe.label}:null})),v=Js(O=>O.homeDirectory),P=a.useMemo(()=>{if(!C)return null;const O=C.label?.trim();if(O)return O;const oe=C.path.split(/[\\/]/).filter(Boolean);return oe[oe.length-1]??null},[C]),{isMobile:S}=tn(),{enabled:A}=ko(),j=!!(A&&i&&o!==void 0),w=a.useMemo(()=>[...Bg(l)],[l]),[N,T]=a.useState(!1),L=a.useRef(null),[$,z]=a.useState(()=>typeof window>"u"?!1:Vs()),W=a.useMemo(()=>Pa(),[]),F=rd(),[R,E]=a.useState(!1),I=a.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),M=Aa(),G=a.useMemo(()=>{if(typeof window>"u")return null;const O=window.__PICHAMBER_MACOS_MAJOR__;if(typeof O=="number"&&Number.isFinite(O)&&O>0)return O;if(typeof navigator>"u")return null;const oe=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!oe)return null;const be=Number.parseInt(oe[1],10),_e=Number.parseInt(oe[2],10);return Number.isNaN(be)?null:be===10?_e:be},[]);Ne.useEffect(()=>{typeof window>"u"||z(Vs())},[]);const X=le(O=>O.isSessionSwitcherOpen),[U,ve]=a.useState(!1),[Z,Re]=a.useState("Local"),[Oe,Q]=a.useState(!0),[_,H]=a.useState(()=>tr(null)),[J,ne]=a.useState(!1),[fe,he]=a.useState(null),[q,te]=a.useState(!1),[ae,je]=a.useState(null),Se=a.useRef(0),Ge=a.useMemo(()=>gb(Z),[Z]),B=a.useCallback(async()=>{if(typeof window>"u"||!$)return;const O=Je(),oe=()=>Je()===O;try{const be=await Pt("/api/version");if(!oe())return;const _e=be.ok?await be.json().catch(()=>null):null;if(!oe())return;if(H(tr(_e)),nr()){Re("Local"),Q(!0);return}Q(!1);const st=await Rd();if(!oe())return;const Ve=Dd(),ns=Pd([Md(Ve),...st.hosts]);if(ns.id===Td){Re("Local"),Q(!0);return}Re(Fd(ns.label.trim()||"Instance"))}catch{oe()&&(Re("Local"),Q(!0),H(tr(null)))}},[$]);Ne.useEffect(()=>(B(),Rn(()=>{Se.current+=1,he(null),je(null),te(!1),ne(!1),B()})),[B]);const re=a.useCallback(async()=>{const O=Se.current+1;Se.current=O;const oe=Je(),be=()=>Se.current===O&&Je()===oe;if(Oe){he(null),je(null);return}te(!0),je(null);try{const _e=new URLSearchParams({appType:"web",instanceMode:"remote"}),st=await Pt(`/api/pi/update-check?${_e.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!st.ok)throw new Error(`Server responded with ${st.status}`);const Ve=await st.json();if(!be())return;he({available:Ve.available??!1,version:Ve.version,currentVersion:Ve.currentVersion??"unknown",body:Ve.body,nextSuggestedCheckInSec:typeof Ve.nextSuggestedCheckInSec=="number"?Ve.nextSuggestedCheckInSec:void 0,packageManager:Ve.packageManager,updateCommand:Ve.updateCommand,channel:Ve.channel==="rc"?"rc":"stable"})}catch(_e){if(!be())return;he(null),je(_e instanceof Error?_e.message:"Failed to check remote instance updates")}finally{be()&&te(!1)}},[Oe]);a.useEffect(()=>Wf(()=>{Oe||re()}),[re,Oe]),a.useEffect(()=>{Se.current+=1,he(null),je(null),te(!1),ne(!1)},[Oe,Z]),a.useEffect(()=>{if(!$||Oe)return;const O=3e3,oe=3600*1e3;let be=!1,_e=null;const st=Ve=>{_e=window.setTimeout(()=>{if(be||typeof document<"u"&&document.visibilityState!=="visible"){st(oe);return}re().finally(()=>{be||st(oe)})},Ve)};return st(O),()=>{be=!0,_e!==null&&window.clearTimeout(_e)}},[re,Oe,Z,$]);const pe=a.useCallback(()=>{if(fe?.available){ne(!0);return}re()},[re,fe?.available]),ge=m?x??null:null,ce=a.useRef(null),[Fe,ye]=a.useState(0);a.useEffect(()=>{if(!m){ce.current&&(ce.current=null,ye(_e=>_e+1));return}if(ge){ce.current={sessionId:m,session:ge,expiresAt:Date.now()+2e3};return}const O=ce.current;if(!O||O.sessionId!==m)return;const oe=O.expiresAt-Date.now();if(oe<=0){ce.current=null,ye(_e=>_e+1);return}const be=window.setTimeout(()=>{ce.current?.sessionId===m&&(ce.current=null),ye(_e=>_e+1)},oe);return()=>{window.clearTimeout(be)}},[m,ge]);const ee=(()=>{if(ge)return ge;if(!m)return null;const O=ce.current;return O&&O.sessionId===m&&O.expiresAt>Date.now()?O.session:null})(),xe=a.useMemo(()=>{const O=typeof ee?.directory=="string"?ee.directory:"";return mn(O||"")},[ee?.directory]),ue=Me(O=>O.newSessionDraft?.open?mn(O.newSessionDraft.directoryOverride??""):""),we=a.useMemo(()=>zg({sessionDirectory:xe,draftDirectory:ue,isNewSessionDraftOpen:g}),[ue,g,xe]),qe=ja(we||null),De=a.useMemo(()=>$g({activeProjectLabel:P,openDirectory:we,homeDirectory:v}),[P,v,we]),Ye=!!(De||qe),se=a.useMemo(()=>m?ps(ee):De??"PiChamber",[ee,m,De]),Le=od(),ct=Me(O=>O.updateSessionTitle),et=Me(O=>O.archiveSessions),Qe=Me(O=>O.deleteSessions),[yt,it]=a.useState(!1),[ss,Mt]=a.useState(!1),at=a.useRef(!1),[nt,wt]=a.useState(""),[tt,Tt]=a.useState(null),$t=a.useRef(null);a.useEffect(()=>{at.current=!1,Mt(!1),it(!1),wt(""),Tt(null)},[m]);const ls=a.useCallback(()=>{m&&(wt(ee?.title?.trim()||se),it(!0))},[ee?.title,m,se]),Ct=a.useCallback(async()=>{if(!m)return;const O=nt.trim();O&&O!==ee?.title?.trim()&&await ct(m,O),it(!1)},[ee?.title,m,nt,ct]);a.useEffect(()=>{if(!yt)return;const O=oe=>{const be=oe.target;(!be||!$t.current?.contains(be))&&Ct()};return document.addEventListener("mousedown",O),()=>document.removeEventListener("mousedown",O)},[yt,Ct]);const Ft=a.useCallback(()=>{m&&bs(m).then(O=>{ie[O.ok?"success":"error"](O.ok?"Session ID copied":"Failed to copy session ID")}).catch(()=>ie.error("Failed to copy session ID"))},[m]),ke=a.useCallback(async()=>{if(!m||!we){ie.error("Nothing to export");return}try{await Le.syncSession(m)}catch{ie.error("Failed to load the complete session history");return}const O=[];if(O.length===0){ie.error("Nothing to export");return}const oe=Nl(O,ee?.title??null),be=Rl(ee?.title??null);await El(oe,be)||Il(oe,be),ie.success("Session exported")},[ee?.title,m,we,Le]);h?.type==="busy"||h?.type;const He=a.useCallback(async()=>{if(!m||!tt)return;const O=id(),oe=[m];for(let Ve=0;Ve<oe.length;Ve+=1){const ns=oe[Ve];for(const Ht of O)Ht.parentID===ns&&!oe.includes(Ht.id)&&oe.push(Ht.id)}const be=tt;if(Tt(null),(be==="archive"?await et(oe):await Qe(oe)).failedIds.length>0){ie.error(be==="archive"?"Failed to archive session":"Failed to delete session");return}ie.success(be==="archive"?"Session archived":"Session deleted")},[et,m,Qe,tt]),Ce=le(O=>O.isArchivePageOpen),Te=a.useMemo(()=>Ce?{title:"Archive",subtitle:null}:null,[Ce]),Be=a.useMemo(()=>mn(we||C?.path||""),[C?.path,we]),pt=a.useCallback(()=>{Be&&bs(Be).then(O=>{ie[O.ok?"success":"error"](O.ok?"Working directory copied":"Failed to copy working directory")}).catch(()=>ie.error("Failed to copy working directory"))},[Be]),rt=a.useMemo(()=>C?{id:C.id,path:C.path}:null,[C]),kt=a.useRef(null);a.useEffect(()=>{!rt||!Be||(kt.current={projectRef:rt,directory:Be})},[Be,rt]);const vt=a.useMemo(()=>rt&&Be?{projectRef:rt,directory:Be}:kt.current,[Be,rt]),gt=a.useCallback(()=>{if(typeof document>"u")return;const O=document.activeElement;if(!O)return;const oe=O.tagName;(oe==="INPUT"||oe==="TEXTAREA"||oe==="SELECT"||O.isContentEditable)&&O.blur()},[]),Ze=a.useCallback(()=>{if(S){gt(),c(!X);return}u()},[gt,S,X,c,u]),cs=a.useCallback(()=>{vn("desktop_open_draft_mini_chat_window",{directory:mn(we||C?.path||""),projectId:C?.id??null,apiBaseUrl:to(),clientToken:eo()}).catch(O=>{console.warn("[header] failed to open draft mini chat window",O)})},[C?.id,C?.path,we]),ws=a.useCallback(()=>{if(g){cs();return}m&&vn("desktop_open_session_mini_chat_window",{sessionId:m,directory:mn(we||C?.path||""),apiBaseUrl:to(),clientToken:eo()}).catch(O=>{console.warn("[header] failed to open session mini chat window",O)})},[C?.path,m,cs,g,we]),vs=sn,us=yh,At=a.useMemo(()=>n?"sessions":j?r&&o?o:null:r?"git":f,[f,j,n,r,o]),Kt=a.useCallback(()=>{n&&e&&e(),r&&t&&t(),!e&&X&&c(!1)},[X,n,e,t,r,c]),bt=a.useCallback(()=>{e?.()},[e]),on=a.useCallback(()=>{t?.()},[t]),Wt=a.useMemo(()=>$&&I&&!R?"5.5rem":F?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":!$||M?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[$,R,I,F,M]);Ne.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",Wt)},[Wt]);const St=d?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",Nt=d?"0px":$&&M?"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)":A?"2.75rem":"2.5rem";Ne.useEffect(()=>{if(!$||!I){E(!1);return}let O=!1;const oe=async()=>{try{const _e=await vn("desktop_is_window_fullscreen");O||E(_e===!0)}catch{O||E(!1)}},be=()=>{oe()};return oe(),window.addEventListener("pichamber:window-resized",be),()=>{O=!0,window.removeEventListener("pichamber:window-resized",be)}},[$,I]);const de=a.useMemo(()=>!$||!I||G===null?"":G>=26?"h-12":G<=15?"h-14":"",[$,I,G]),ot=a.useMemo(()=>{if(!($&&!M))return{paddingRight:"calc(0.75rem + var(--oc-wco-right-inset, 0px))",minHeight:"max(3rem, var(--oc-wco-titlebar-height, 0px))",height:"max(3rem, var(--oc-wco-titlebar-height, 0px))"}},[$,M]),It=a.useCallback(()=>{if(typeof document>"u")return;const O=L.current?.getBoundingClientRect().height;if(O){const oe=`${O}px`,be=document.documentElement.style;be.getPropertyValue("--oc-header-height")!==oe&&be.setProperty("--oc-header-height",oe)}},[]);Ne.useEffect(()=>{if(typeof window>"u")return;It();const O=L.current;if(!O||typeof ResizeObserver>"u")return()=>{};let oe=0;const be=()=>{oe||(oe=requestAnimationFrame(()=>{oe=0,It()}))},_e=new ResizeObserver(be);return _e.observe(O),window.addEventListener("resize",be),window.addEventListener("orientationchange",be),()=>{oe&&cancelAnimationFrame(oe),_e.disconnect(),window.removeEventListener("resize",be),window.removeEventListener("orientationchange",be)}},[It]),Ne.useEffect(()=>{It()},[It,S,de]);const ds=a.useCallback(async O=>{const oe=O.target;oe.closest(".app-region-no-drag")||oe.closest("button, a, input, select, textarea")||O.button===0&&$&&await ad()},[$]),Lt=a.useMemo(()=>S?[{id:"chat",label:"Chat",icon:"chat-4"},{id:"diff",label:"Diff",icon:"diff"},{id:"files",label:"Files",icon:"file-text"},{id:"terminal",label:"Terminal",icon:"terminal-box"},{id:"context",label:"Context",icon:"file-list-2"},{id:"diagram",label:"Diagram",icon:"file"}]:[],[S]),Gt=a.useCallback(O=>Ao(sr(O,b)),[b]);Ne.useEffect(()=>{!S&&f!=="chat"&&f!=="terminal"&&f!=="diagram"&&p("chat")},[f,S,p]),Ne.useEffect(()=>{const O=oe=>{if(Ld(oe)&&!oe.shiftKey&&!oe.altKey){const be=parseInt(oe.key,10);be>=1&&be<=Lt.length&&(oe.preventDefault(),S&&(gt(),Kt()),p(Lt[be-1].id))}};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[gt,Kt,S,p,Lt]),Ne.useEffect(()=>{const O=oe=>{const be=sr("toggle_services_menu",b);if(Od(oe,be)){oe.preventDefault(),U?ve(!1):(ve(!0),B());return}};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[b,U,B]);const xr=O=>{const oe=f===O.id,be=O.icon==="diff",_e=be?null:O.icon,st=O.id==="chat",Ve=Ht=>be?s.jsx(Vi,{size:Ht}):_e?s.jsx(D,{name:_e,className:`h-${Ht/4} w-${Ht/4}`}):null,ns=s.jsxs("button",{type:"button",onClick:()=>p(O.id),className:K("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",oe?"app-region-no-drag bg-interactive-selection text-interactive-selection-foreground shadow-none":"app-region-no-drag text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",st&&!S&&"min-w-[100px] justify-center"),"aria-label":O.label,"aria-selected":oe,role:"tab",children:[S?Ve(20):s.jsxs(s.Fragment,{children:[Ve(16),s.jsx("span",{className:"header-tab-label",children:O.label})]}),O.badge!==void 0&&O.badge>0&&s.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:O.badge})]});return s.jsx(a.Fragment,{children:ns},O.id)},yr=s.jsxs(s.Fragment,{children:[s.jsx(Hg,{directory:Be,className:"mr-1"}),$?s.jsx(mb,{isDesktopApp:$,currentInstanceLabel:Z,compactCurrentInstanceLabel:Ge,currentInstanceIsLocal:Oe,currentInstanceIcon:_,isDesktopServicesOpen:U,setIsDesktopServicesOpen:ve,refreshCurrentInstanceLabel:B,shortcutLabel:Gt,remoteUpdateInfo:fe,remoteUpdateChecking:q,remoteUpdateError:ae,onOpenRemoteUpdate:pe}):s.jsx(fb,{open:U,onOpenChange:ve}),s.jsx(hb,{isMobile:S})]}),Mn=W&&(g||!!m),an=()=>s.jsxs("div",{onMouseDown:ds,className:K("app-region-drag relative flex h-12 select-none items-center pr-3",de),style:ot,role:"tablist","aria-label":"Main navigation",children:[s.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:St}}),s.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:Nt}}),s.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[Te?s.jsxs("div",{className:"mr-3 flex min-w-0 items-center gap-1.5 px-1 py-0.5 -my-0.5 text-left",children:[s.jsx("span",{className:"truncate typography-ui-label text-[14px] font-normal leading-tight text-foreground max-w-full",children:Te.title}),Te.subtitle?s.jsxs(s.Fragment,{children:[s.jsx("span",{"aria-hidden":"true",className:"h-3 w-px shrink-0 bg-border"}),s.jsx("span",{className:"truncate typography-ui-label font-normal leading-tight text-muted-foreground/75 max-w-full",children:Te.subtitle})]}):null]}):s.jsxs("div",{className:"app-region-no-drag mr-3 flex min-w-0 max-w-full items-center gap-0.5 py-0.5 -my-0.5 text-left",children:[d?null:s.jsx(a.Suspense,{fallback:s.jsx("button",{type:"button",className:vs,"aria-label":"Open session switcher",children:s.jsx(D,{name:"history",className:"h-[18px] w-[18px]"})}),children:s.jsx(bb,{align:"start",children:s.jsx("button",{type:"button",className:vs,"aria-label":"Open session switcher",children:s.jsx(D,{name:"history",className:"h-[18px] w-[18px]"})})})}),s.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 px-1",children:[yt?s.jsxs("form",{ref:$t,className:"flex w-full min-w-0 items-center gap-2 leading-tight",onSubmit:O=>{O.preventDefault(),Ct()},children:[s.jsx("input",{value:nt,onChange:O=>wt(O.target.value),autoFocus:!0,onKeyDown:O=>{O.stopPropagation(),O.key==="Escape"&&it(!1)},placeholder:"Rename",className:"min-w-0 flex-1 bg-transparent typography-ui-label font-normal leading-tight outline-none placeholder:text-muted-foreground"}),s.jsx("button",{type:"submit","aria-label":"Save session name",title:"Save session name",className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(D,{name:"check",className:"size-4"})}),s.jsx("button",{type:"button",onClick:()=>it(!1),"aria-label":"Cancel renaming session",title:"Cancel renaming session",className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(D,{name:"close",className:"size-4"})})]}):s.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal leading-tight text-foreground",children:g?"New session":se}),Ye?s.jsxs(s.Fragment,{children:[s.jsx("span",{"aria-hidden":"true",className:"h-3 w-px shrink-0 bg-border"}),s.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 truncate typography-ui-label font-normal leading-tight text-muted-foreground/75",children:[De?s.jsx("span",{className:"truncate",children:De}):null,qe?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[s.jsx(D,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),s.jsx("span",{className:"truncate",children:qe})]}):null]})]}):null]}),s.jsx("div",{className:"flex h-[18px] shrink-0 items-center justify-center self-center",children:m&&!g&&!yt?s.jsxs(Jt,{open:ss,onOpenChange:Mt,onOpenChangeComplete:O=>{!O&&at.current&&(at.current=!1,ls())},children:[s.jsx(Xt,{asChild:!0,children:s.jsx(Ee,{variant:"ghost",size:"xs",className:"h-[18px] w-6 px-0 text-muted-foreground hover:bg-transparent hover:text-foreground","aria-label":"Open session actions",children:s.jsx(D,{name:"more",className:"size-4"})})}),s.jsxs(Zt,{align:"end",className:"min-w-[190px]",children:[s.jsxs(mt,{onClick:()=>{at.current=!0},children:[s.jsx(D,{name:"pencil-ai",className:"mr-2 size-4"}),"Rename"]}),s.jsxs(mt,{onClick:Ft,children:[s.jsx(D,{name:"file-copy",className:"mr-2 size-4"}),"Copy session ID"]}),s.jsxs(mt,{onClick:pt,disabled:!Be,children:[s.jsx(D,{name:"folder",className:"mr-2 size-4"}),"Copy working directory"]}),s.jsx(Qs,{}),s.jsxs(mt,{onClick:()=>{ke()},children:[s.jsx(D,{name:"download",className:"mr-2 size-4"}),"Export Markdown"]}),s.jsx(Qs,{}),s.jsxs(mt,{onClick:()=>Tt("archive"),children:[s.jsx(D,{name:"inbox-archive",className:"mr-2 size-4"}),"Archive"]}),s.jsxs(mt,{className:"text-destructive focus:text-destructive",onClick:()=>Tt("delete"),children:[s.jsx(D,{name:"delete-bin",className:"mr-2 size-4"}),"Delete"]})]})]}):null})]}),Lt.length>0&&s.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:Lt.map(O=>xr(O))}),s.jsx("div",{className:"flex-1"}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[s.jsx(nl,{}),vt?s.jsx(Zi,{projectRef:vt.projectRef,directory:vt.directory,className:"mr-1"}):null,s.jsx(wh,{visible:Mn,title:g?"New Mini Chat Window":"Open Session in Mini Chat",ariaLabel:g?"Open a new Mini Chat window":"Open current session in Mini Chat",onClick:ws,className:K(vs,"mr-1"),Icon:"picture-in-picture-2"}),yr,s.jsx(ld,{visible:M})]})]})]}),Fs=()=>s.jsxs("div",{className:"app-region-drag relative flex items-center gap-2 px-3 py-2 select-none",children:[A&&s.jsxs(s.Fragment,{children:[s.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:St}}),s.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:Nt}})]}),!A&&s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e?s.jsx("button",{type:"button",onClick:bt,className:K(us,At==="sessions"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":n?"Close sessions":"Open sessions",children:s.jsx(D,{name:"layout-left",className:"h-5 w-5"})}):X?s.jsx("button",{type:"button",onClick:()=>c(!1),className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":"Back",children:s.jsx(D,{name:"arrow-left-s",className:"h-5 w-5"})}):s.jsx("button",{type:"button",onClick:Ze,className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":"Open sessions",children:s.jsx(D,{name:"play-list-add",className:"h-5 w-5"})}),!e&&X&&s.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:"Sessions"})]}),(!X||!!e)&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center",children:!j&&s.jsx("div",{className:"flex min-w-0 flex-1 overflow-x-auto overflow-y-hidden scrollbar-hidden touch-pan-x overscroll-x-contain","data-no-drawer-swipe":"true",children:s.jsx("div",{className:"flex w-max items-center gap-1 pr-1",children:s.jsx("div",{className:"flex items-center gap-0.5 rounded-lg bg-[var(--surface-muted)]/50 p-0.5",role:"tablist","aria-label":"Main navigation",children:Lt.map(O=>{const oe=f===O.id,be=O.icon==="diff",_e=be?null:O.icon;return s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsxs("button",{type:"button",onClick:()=>{S&&(gt(),Kt()),p(O.id)},"aria-label":O.label,"aria-selected":oe,role:"tab",className:K(us,"relative rounded-lg",At===O.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[be?s.jsx(Vi,{className:"h-5 w-5"}):_e?s.jsx(D,{name:_e,className:"h-5 w-5"}):null,O.badge!==void 0&&O.badge>0&&s.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:O.badge}),O.showDot&&s.jsx("span",{className:"absolute top-1.5 right-1.5 h-2 w-2 rounded-full bg-primary","aria-label":"Changes available"})]})}),s.jsx(We,{children:s.jsx("p",{children:O.label})})]},O.id)})})})})}),s.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[j&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex items-center gap-0.5 rounded-lg bg-[var(--surface-muted)]/50 p-0.5",role:"tablist","aria-label":"Workspace",children:w.map(O=>{const oe=r&&o===O.id;return s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:()=>{S&&(gt(),Kt()),T(!1),i?.(O.id)},"aria-label":O.label,"aria-selected":oe,role:"tab",className:K(us,"relative h-11 w-11 rounded-lg",oe&&"bg-interactive-selection text-interactive-selection-foreground"),children:s.jsx(D,{name:O.icon,className:"h-5 w-5"})})}),s.jsx(We,{children:s.jsx("p",{children:O.label})})]},O.id)})}),s.jsx(xh,{open:N,onOpenChange:T,currentSessionId:m,effectiveDirectory:we||null,isNewSessionDraftOpen:g})]}),vt&&s.jsx(Zi,{projectRef:vt.projectRef,directory:vt.directory,compact:!0,allowMobile:!0,className:"h-9"}),t&&!j?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:on,className:K(us,"relative",At==="git"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":r?"Close git sidebar":"Open git sidebar",children:s.jsx(D,{name:"layout-right",className:"h-5 w-5"})})}),s.jsx(We,{children:s.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),wr=K("header-safe-area relative z-10 bg-background",S&&"border-b border-border/50");return s.jsxs(s.Fragment,{children:[s.jsx("header",{ref:L,className:wr,style:{"--padding-scale":"1"},children:S?Fs():an()}),s.jsx(pb,{action:tt,onClose:()=>Tt(null),sessionTitle:se,onConfirm:()=>{He()}}),s.jsx(Qa,{open:J,onOpenChange:ne,info:fe,downloading:!1,downloaded:!1,progress:null,error:ae,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})},ea="app-region-no-drag inline-flex h-8 w-8 items-center justify-center gap-2 rounded-md typography-ui-label font-medium text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary hover:bg-interactive-hover transition-colors",xb="app-region-no-drag flex size-10 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50",Px=()=>{const e=le(g=>g.isSidebarOpen),t=le(g=>g.toggleSidebar),n=le(g=>g.shortcutOverrides),r=a.useRef(null),o=a.useRef(null),i=Ao(sr("toggle_sidebar",n)),l=Aa(),{enabled:c}=ko(),u=!e,d=l,f=u||d,p=d,b=a.useCallback(()=>{vn("desktop_show_app_menu").catch(g=>{console.warn("[titlebar] failed to open app menu",g)})},[]);return a.useEffect(()=>{if(typeof document>"u")return;const g=v=>{document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(v)}px`)},m=v=>{document.documentElement.style.setProperty("--oc-titlebar-overlay-width",`${Math.round(v)}px`)};if(!p)return;const h=o.current,y=r.current;if(!h||!y){g(0),m(0);return}const x=()=>{const v=Math.max(h.getBoundingClientRect().width,h.scrollWidth);g(v),m(y.getBoundingClientRect().width)};if(x(),typeof ResizeObserver>"u")return;const C=new ResizeObserver(x);return C.observe(h),C.observe(y),()=>{C.disconnect()}},[p]),f?s.jsx("div",{ref:r,className:"app-region-no-drag absolute left-0 z-40 flex select-none items-center pr-2",style:{top:"var(--oc-safe-area-top, 0px)",height:"calc(var(--oc-header-height, 3rem) - var(--oc-safe-area-top, 0px))",paddingLeft:"var(--oc-titlebar-left-inset, 0.75rem)"},children:s.jsxs("div",{ref:o,className:"flex items-center gap-2",children:[d?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:b,"aria-label":"Open PiChamber menu",className:K(ea,"shrink-0"),children:s.jsx(D,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),s.jsx(We,{children:s.jsx("p",{children:"PiChamber menu"})})]}):null,u?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:t,"aria-label":"Open sessions",className:K(c?xb:ea,"shrink-0"),children:s.jsx(D,{name:"layout-left",className:c?"size-[18px]":"h-[18px] w-[18px]"})})}),s.jsx(We,{children:s.jsx("p",{children:`Open sessions (${i})`})})]}):null]})}):null},ta=200,yb="cubic-bezier(0.22, 1, 0.36, 1)",Mx=e=>{const t=a.useMemo(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches,[]),[n,r]=a.useState(e),[o,i]=a.useState(e);return a.useLayoutEffect(()=>{if(t){i(e),r(e);return}if(e){i(!0),r(!1);let c=0;const u=window.requestAnimationFrame(()=>{c=window.requestAnimationFrame(()=>r(!0))});return()=>{window.cancelAnimationFrame(u),window.cancelAnimationFrame(c)}}r(!1);const l=window.setTimeout(()=>i(!1),ta);return()=>window.clearTimeout(l)},[e,t]),{slidIn:n,layoutVisible:o,prefersReducedMotion:t,transition:t?"none":`transform ${ta}ms ${yb}`}},Tx=()=>{Ta()},Fx=e=>{Me.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),le.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),me.getState().clearAll(),Ta(),Js.getState().resetForRuntimeSwitch(),cd.getState().resetForRuntimeSwitch(),ud.getState().resetForRuntimeSwitch(),dd(),Bd(),$d(),gd(),fd.getState().resetForRuntimeSwitch(),Ut.setState({providers:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),ht.getState().resetForRuntimeSwitch(),hd(),md(),ef.getState().reset(),_d.getState().resetForRuntimeSwitch(),ba.getState().resetForRuntimeSwitch(e.runtimeKey),Xr.getState().resetForRuntimeSwitch(e.runtimeKey),Ud(),Rs.getState().resetForRuntimeSwitch(e.runtimeKey),pd.getState().resetForRuntimeSwitch(),Vt.getState().resetForRuntimeSwitch(),ft.getState().resetForRuntimeSwitch(e.runtimeKey),zd.getState().resetForRuntimeSwitch(e.runtimeKey),Me.getState().restoreForRuntimeSwitch(e.runtimeKey),le.getState().restoreForRuntimeSwitch(e.runtimeKey);const t=le.getState();oo({sessionId:Me.getState().currentSessionId,tab:t.activeMainTab,isSettingsOpen:t.isSettingsDialogOpen,settingsPath:t.settingsPage,diffFile:t.pendingDiffFile},{replace:!0,force:!0})};export{ox as $,rx as A,Ys as B,nx as C,$i as D,jl as E,Bb as F,fh as G,Dx as H,hh as I,yi as J,Rx as K,yf as L,sl as M,Fb as N,Ss as O,gs as P,Vt as Q,Sl as R,Sx as S,Ax as T,dl as U,En as V,Tb as W,ul as X,_b as Y,Xa as Z,ux as _,xh as a,dx as a0,wx as a1,vx as a2,dh as a3,mx as a4,fx as a5,ax as a6,hx as a7,gx as a8,bx as a9,$f as aA,Dn as aB,Pn as aC,$b as aD,Kf as aE,Va as aF,Qb as aG,Sn as aH,Ub as aI,Of as aJ,Bf as aK,Vb as aL,ex as aM,Zb as aN,Xb as aO,tx as aP,Kb as aQ,Wb as aR,Gb as aS,sh as aT,qb as aU,vf as aV,_f as aW,Sf as aX,Pb as aY,xx as aa,yx as ab,px as ac,go as ad,Di as ae,js as af,hn as ag,rn as ah,wm as ai,nn as aj,lx as ak,br as al,cx as am,ix as an,zf as ao,Jb as ap,Lf as aq,zb as ar,sx as as,Yb as at,Qa as au,Io as av,Hb as aw,Uf as ax,ah as ay,Ff as az,gn as b,Hp as c,jx as d,Zn as e,Bg as f,Cx as g,bg as h,Qp as i,Nx as j,Fl as k,Mx as l,Ex as m,Px as n,Tx as o,Fx as p,Lb as q,Ix as r,kx as s,Ob as t,gh as u,Mb as v,Db as w,Po as x,Mo as y,To as z};
|