@pi-chamber/web 1.0.5-rc.4 → 1.0.6-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-CiAfS52a.js → DiagramView-DUxXEKjQ.js} +1 -1
- package/dist/assets/DiffView-DEd3rdnu.js +18 -0
- package/dist/assets/FileSaveConflictDialog-C6o4fYIn.js +3 -0
- package/dist/assets/{FilesView-DAEtByHZ.js → FilesView-Ccl4CxjR.js} +3 -3
- package/dist/assets/{GitHubDetailScaffold-CtFeWl_3.js → GitHubDetailScaffold-DlgVm5uD.js} +3 -3
- package/dist/assets/{GitHubLinkPicker-BEB6WkNO.js → GitHubLinkPicker-BgDZR-3K.js} +1 -1
- package/dist/assets/{GitHubListPrimitives-BilsEUSt.js → GitHubListPrimitives-BTeI3B3C.js} +1 -1
- package/dist/assets/{GitView-C19-aC7A.js → GitView-BkrH0HFQ.js} +4 -4
- package/dist/assets/{IssuesSurface-zvICpciG.js → IssuesSurface-CD1m8BHP.js} +3 -3
- package/dist/assets/{JsonTreeView-D99tzKTq.js → JsonTreeView-RLgBKik9.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-CRfobHRu.js → MarkdownRendererImpl-BkfhE9NN.js} +2 -2
- package/dist/assets/{PatchDiff-Fbf3Mt_o.js → PatchDiff-BLNLrGYa.js} +1 -1
- package/dist/assets/{PierreDiffViewer-C2nEOax_.js → PierreDiffViewer-iLnLAFeL.js} +3 -3
- package/dist/assets/PullRequestsSurface-_kgJMFTh.js +2 -0
- package/dist/assets/{SessionSwitcherContent-DByH7H41.js → SessionSwitcherContent-BCOUKRch.js} +1 -1
- package/dist/assets/SessionSwitcherDropdown-CA64t2xd.js +2 -0
- package/dist/assets/SessionUnreadDot-BZy2DM6H.js +1 -0
- package/dist/assets/SettingsView-TwUy1kXV.js +6 -0
- package/dist/assets/{SettingsWindow-B1_mMQyb.js → SettingsWindow-BXE4JP-T.js} +1 -1
- package/dist/assets/{StickyHorizontalScrollbar-BMITjK4e.js → StickyHorizontalScrollbar-p7EbL2-E.js} +2 -2
- package/dist/assets/{ToolOutputDialog-BO3d88qF.js → ToolOutputDialog-tiXT-Xts.js} +4 -4
- package/dist/assets/{ToolPartDiffPreview-BgbLfmmd.js → ToolPartDiffPreview-CylbiIKd.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-D7kxYBDG.js → VirtualizedFileDiff-Cccy1L8L.js} +4 -4
- package/dist/assets/{Virtualizer-DP6HbEeC.js → Virtualizer-DNJrJKVb.js} +1 -1
- package/dist/assets/{appThemeRegistry-gegrE2dq.js → appThemeRegistry-Ca8eGRB9.js} +1 -1
- package/dist/assets/{collapsible-9MJx4VhA.js → collapsible-0yfy07W2.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-8pZIB8G2.js → computeVirtualFileMetrics-ydVGT2RY.js} +2 -2
- package/dist/assets/{contextFileOpenGuard-BNtzRA7B.js → contextFileOpenGuard--7BLkncT.js} +1 -1
- package/dist/assets/{document-attachments-BslE4Ns7.js → document-attachments-CZl9rK1z.js} +5 -5
- package/dist/assets/{gitStatusPredicates-B7adeDSu.js → gitStatusPredicates-BzR54iPh.js} +1 -1
- package/dist/assets/{githubLink-DVRaj2ms.js → githubLink-WO5BkC0U.js} +5 -5
- package/dist/assets/{index-D4n3TVp2.js → index-C2ISrmRR.js} +10 -10
- package/dist/assets/index-DgwThEwf.css +1 -0
- package/dist/assets/index-nOAE6UDy.js +1 -0
- package/dist/assets/{lua-BgMRiT3U.js → lua-VAEuO923.js} +1 -1
- package/dist/assets/main-B4UP1bOp.js +2 -0
- package/dist/assets/main-DxYfmK5D.js +137 -0
- package/dist/assets/{markdown-shiki.worker-DnvH1S1x.js → markdown-shiki.worker-BVA5NZBT.js} +5 -5
- package/dist/assets/markdownCore-DIn2dwA6.js +2 -0
- package/dist/assets/miniChat-CMGH4R_p.js +2 -0
- package/dist/assets/mobile-BJz0lBjK.js +2 -0
- package/dist/assets/{nativeFileSave-BJsGPh58.js → nativeFileSave-Bhafll_7.js} +1 -1
- package/dist/assets/nsis-LY0VT_u5.js +1 -0
- package/dist/assets/permissionStore-zIpxq9Pq.js +1 -0
- package/dist/assets/pi-session-focus-preference-D6vrJGbH.js +9 -0
- package/dist/assets/{registerCustomTheme-DmolaWWZ.js → registerCustomTheme-C-h6lsYW.js} +1 -1
- package/dist/assets/{renderDiffWithHighlighter-BamhejwM.js → renderDiffWithHighlighter-JwKOWdBN.js} +1 -1
- package/dist/assets/renderElectronMiniChatApp-DYdkuv5N.js +2 -0
- package/dist/assets/{renderFileWithHighlighter-CFlqKZg7.js → renderFileWithHighlighter-RJTrDxFH.js} +1 -1
- package/dist/assets/renderMobileApp-x1P9U65-.js +11 -0
- package/dist/assets/ruby-BK5aLJev.js +1 -0
- package/dist/assets/runtimeEndpointReset-OqTh3bbO.js +62 -0
- package/dist/assets/runtimeSurface-CJN1oo_1.js +1 -0
- package/dist/assets/themeResolver-DrfmQi8i.js +1 -0
- package/dist/assets/useAppFontEffects-CHnpTOtc.js +215 -0
- package/dist/assets/useFilesViewSearch-DeVixiGZ.js +7 -0
- package/dist/assets/{useGitHubRemoteSearch-BoCzq4zs.js → useGitHubRemoteSearch-GjQca1iD.js} +1 -1
- package/dist/assets/{useSwitcherItems-C8IKoSTL.js → useSwitcherItems-DYtnl0T2.js} +1 -1
- package/dist/assets/vendor-aparajita-capacitor-secure-storage-BLsm9T1Y.js +1 -0
- package/dist/assets/vendor-base-ui-C7vVMZTg.js +1 -0
- package/dist/assets/{vendor-beautiful-mermaid-DApbjBp2.js → vendor-beautiful-mermaid-b48gT2g0.js} +1 -1
- package/dist/assets/vendor-boot-CoTxysn6.js +65 -0
- package/dist/assets/{vendor-capacitor-app-BaupizkW.js → vendor-capacitor-app-NX6DULfp.js} +1 -1
- package/dist/assets/{vendor-capacitor-keyboard-9BVxykO7.js → vendor-capacitor-keyboard-DJD81I9f.js} +1 -1
- package/dist/assets/{vendor-capacitor-status-bar-BsrUwiaA.js → vendor-capacitor-status-bar-DV24OoQV.js} +1 -1
- package/dist/assets/vendor-codemirror-autocomplete-qsuH4Dh-.js +1 -0
- package/dist/assets/vendor-codemirror-lang-angular-ZHWyBf7j.js +1 -0
- package/dist/assets/vendor-codemirror-lang-cpp-pCTOmv-k.js +1 -0
- package/dist/assets/vendor-codemirror-lang-css-2bFuyM70.js +1 -0
- package/dist/assets/{vendor-codemirror-lang-go-Crwca_X7.js → vendor-codemirror-lang-go-DrG_c7D7.js} +2 -2
- package/dist/assets/vendor-codemirror-lang-html-BV8lrR8v.js +1 -0
- package/dist/assets/vendor-codemirror-lang-java-DrsvH6T2.js +1 -0
- package/dist/assets/vendor-codemirror-lang-javascript-Dkzl3s07.js +13 -0
- package/dist/assets/vendor-codemirror-lang-jinja-8Nn3bnoP.js +1 -0
- package/dist/assets/vendor-codemirror-lang-json-CsdmtHhi.js +1 -0
- package/dist/assets/vendor-codemirror-lang-less-DJuZ4cZe.js +1 -0
- package/dist/assets/vendor-codemirror-lang-liquid-D2RO-Pzr.js +1 -0
- package/dist/assets/vendor-codemirror-lang-markdown-C0Zu3b3n.js +1 -0
- package/dist/assets/vendor-codemirror-lang-php-CuDtt2Zj.js +1 -0
- package/dist/assets/vendor-codemirror-lang-python-Cv2exx_M.js +3 -0
- package/dist/assets/vendor-codemirror-lang-rust-C4TxJ6Rg.js +1 -0
- package/dist/assets/vendor-codemirror-lang-sass-BmtPz8kf.js +1 -0
- package/dist/assets/{vendor-codemirror-lang-sql-B0f-qCZo.js → vendor-codemirror-lang-sql-BF1ZaXqJ.js} +2 -2
- package/dist/assets/vendor-codemirror-lang-vue-DZgXrP2k.js +1 -0
- package/dist/assets/vendor-codemirror-lang-wast-DsnaGtL_.js +1 -0
- package/dist/assets/vendor-codemirror-lang-xml-D8DzzFat.js +1 -0
- package/dist/assets/vendor-codemirror-lang-yaml-D5hBv7m6.js +1 -0
- package/dist/assets/{vendor-codemirror-language-data-CqU7kHmg.js → vendor-codemirror-language-data-vn2RyN9T.js} +2 -2
- package/dist/assets/vendor-codemirror-search-BVCYIV0D.js +2 -0
- package/dist/assets/vendor-dompurify-BGCr_sdL.js +3 -0
- package/dist/assets/vendor-elkjs-D1S1RCAO.js +24 -0
- package/dist/assets/vendor-fuse.js-t_7AcMTv.js +1 -0
- package/dist/assets/{vendor-hast-util-to-html-BKBhbTDb.js → vendor-hast-util-to-html-O3stl53j.js} +1 -1
- package/dist/assets/{vendor-heic2any-pq-UTQQR.js → vendor-heic2any-sztndhZI.js} +1 -1
- package/dist/assets/vendor-lezer-cpp-vqXSn3lv.js +1 -0
- package/dist/assets/vendor-lezer-css-JnEzSyZR.js +1 -0
- package/dist/assets/{vendor-lezer-go-CHIhCNY6.js → vendor-lezer-go-dD2gQMIL.js} +1 -1
- package/dist/assets/{vendor-lezer-html-B3h0MOrG.js → vendor-lezer-html-Cr3U-1pu.js} +1 -1
- package/dist/assets/vendor-lezer-java-CRM0IMCo.js +1 -0
- package/dist/assets/vendor-lezer-javascript-B3s21DIS.js +1 -0
- package/dist/assets/{vendor-lezer-json-BP_UAzLL.js → vendor-lezer-json-DPFM6EBV.js} +1 -1
- package/dist/assets/vendor-lezer-lr-Bllrq8hY.js +1 -0
- package/dist/assets/vendor-lezer-markdown-6-3PLvXG.js +6 -0
- package/dist/assets/vendor-lezer-php-DOyzfHRl.js +1 -0
- package/dist/assets/{vendor-lezer-python-EJ4Im4y2.js → vendor-lezer-python-CdHdN5qt.js} +1 -1
- package/dist/assets/vendor-lezer-rust-CqnW8EMH.js +1 -0
- package/dist/assets/{vendor-lezer-sass-CMi6zfXI.js → vendor-lezer-sass-BbcF4y6A.js} +1 -1
- package/dist/assets/{vendor-lezer-xml-0MHMeZDp.js → vendor-lezer-xml-C31AyWoo.js} +1 -1
- package/dist/assets/{vendor-lezer-yaml-BE2EFjpA.js → vendor-lezer-yaml-Cv908yC2.js} +1 -1
- package/dist/assets/{vendor-lru_map-DOPmc7GU.js → vendor-lru_map-BbiDqlyL.js} +1 -1
- package/dist/assets/vendor-marked-Be78pDn1.js +59 -0
- package/dist/assets/{vendor-oniguruma-parser-C0D4_9rT.js → vendor-oniguruma-parser-BrbMHgHx.js} +1 -1
- package/dist/assets/vendor-oniguruma-to-es-DgwFOwdE.js +94 -0
- package/dist/assets/{vendor-pierre-theming-Dgp7B_O4.js → vendor-pierre-theming-BO6EPniU.js} +1 -1
- package/dist/assets/vendor-property-information-C40bX6nM.js +1 -0
- package/dist/assets/{vendor-qrcode-Dv4uniC1.js → vendor-qrcode-gzL9QFkg.js} +5 -5
- package/dist/assets/vendor-react-Bz1tRBxM.js +1 -0
- package/dist/assets/{vendor-react-drawio-Duu5LgQA.js → vendor-react-drawio-IYnLUY5N.js} +1 -1
- package/dist/assets/vendor-remend-DcBOpbSu.js +24 -0
- package/dist/assets/vendor-replit-codemirror-vim-Cwhyn_5f.js +6 -0
- package/dist/assets/vendor-replit-codemirror-vim-core-FHzKdNUS.js +34 -0
- package/dist/assets/vendor-shiki-BEwTOAFg.js +1 -0
- package/dist/assets/{vendor-shikijs-core-CGM_jqPK.js → vendor-shikijs-core-Ck_OPM_T.js} +1 -1
- package/dist/assets/{vendor-shikijs-engine-javascript-Cme4830A.js → vendor-shikijs-engine-javascript-DL394yyj.js} +1 -1
- package/dist/assets/vendor-shikijs-vscode-textmate-DPFxvYtK.js +3 -0
- package/dist/assets/vendor-tailwind-merge-BKkUfl9q.js +1 -0
- package/dist/assets/vendor-workbox-window-BBnX5xw4.js +2 -0
- package/dist/assets/vendor-zumer-snapdom-SJzqoCHV.js +8 -0
- package/dist/assets/vendor-zustand-CXhN0IMY.js +6 -0
- package/dist/assets/{web-components-DTteDmIQ.js → web-components-CIPJC1JE.js} +1 -1
- package/dist/assets/worker-CKCfxIfO.js +153 -0
- package/dist/assets/workerFactory-DlGfNFqf.js +1 -0
- package/dist/assets/zig-BB16gwVL.js +1 -0
- package/dist/index.html +8 -8
- package/dist/mini-chat.html +7 -7
- package/dist/mobile.html +7 -7
- package/package.json +54 -53
- package/server/index.js +18 -1
- package/server/lib/client-auth/live-revocation.test.js +4 -0
- package/server/lib/fs/DOCUMENTATION.md +10 -0
- package/server/lib/fs/project-icon.js +243 -0
- package/server/lib/fs/project-icon.test.js +114 -0
- package/server/lib/fs/routes.js +35 -0
- package/server/lib/fs/routes.test.js +74 -0
- package/server/lib/git/DOCUMENTATION.md +2 -1
- package/server/lib/git/routes.js +11 -3
- package/server/lib/git/routes.test.js +80 -0
- package/server/lib/git/service.js +38 -3
- package/server/lib/git/service.test.js +93 -0
- package/server/lib/open-url/DOCUMENTATION.md +35 -0
- package/server/lib/open-url/browser-env.js +199 -0
- package/server/lib/open-url/browser-env.test.js +147 -0
- package/server/lib/open-url/browser-handler.mjs +154 -0
- package/server/lib/open-url/browser-handler.test.js +69 -0
- package/server/lib/open-url/intake.js +187 -0
- package/server/lib/open-url/intake.test.js +75 -0
- package/server/lib/pi/extension-protocol.js +149 -0
- package/server/lib/pi/extension-protocol.test.js +20 -1
- package/server/lib/pi/routes.js +195 -1
- package/server/lib/pi/routes.test.js +129 -0
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +38 -10
- package/server/lib/pi/session-daemon/builtin-extensions.js +14 -4
- package/server/lib/pi/session-daemon/daemon-process.js +13 -0
- package/server/lib/pi/session-daemon/extension-bridge-draft.test.js +6 -1
- package/server/lib/pi/session-daemon/extension-bridge.js +40 -6
- package/server/lib/pi/session-daemon/extension-custom-host.js +1259 -0
- package/server/lib/pi/session-daemon/extension-custom-host.test.js +759 -0
- package/server/lib/pi/session-daemon/extension-keybindings.js +21 -0
- package/server/lib/pi/session-daemon/extension-keybindings.test.js +37 -0
- package/server/lib/pi/session-daemon/extension-message-render.js +7 -4
- package/server/lib/pi/session-daemon/extension-message-render.test.js +14 -2
- package/server/lib/pi/session-daemon/extension-tool-render.js +7 -0
- package/server/lib/pi/session-daemon/extension-tool-render.test.js +26 -0
- package/server/lib/pi/session-daemon/open-request.js +60 -0
- package/server/lib/pi/session-daemon/open-request.test.js +54 -0
- package/server/lib/pi/session-daemon/prompt-preflight.test.js +134 -0
- package/server/lib/pi/session-daemon/sdk-upgrade.test.js +21 -4
- package/server/lib/pi/session-daemon/session-daemon-bash.e2e.test.js +225 -0
- package/server/lib/pi/session-daemon/session-daemon-directory-catalog.e2e.test.js +156 -0
- package/server/lib/pi/session-daemon/session-daemon-directory-catalog.test.js +381 -0
- package/server/lib/pi/session-daemon/session-daemon-engines.test.js +11 -2
- package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +30 -4
- package/server/lib/pi/session-daemon/session-daemon-list-live.test.js +20 -0
- package/server/lib/pi/session-daemon/session-daemon-mcp.e2e.test.js +16 -4
- package/server/lib/pi/session-daemon/session-daemon-turn.e2e.test.js +7 -2
- package/server/lib/pi/session-daemon/session-daemon.js +448 -49
- package/server/lib/pi/session-daemon/session-daemon.test.js +91 -4
- package/server/lib/pi/session-daemon/session-engine-router.js +9 -3
- package/server/lib/pi/session-daemon/session-engine-router.test.js +12 -2
- package/server/lib/pi/session-daemon/session-engines.js +7 -2
- package/server/lib/pi/session-daemon/session-jsonl.js +170 -75
- package/server/lib/pi/session-daemon/session-jsonl.test.js +106 -2
- package/server/lib/pi/session-daemon/supervisor.js +4 -0
- package/server/lib/pi/session-daemon/user-bash.js +326 -0
- package/server/lib/pi/session-daemon/user-bash.test.js +371 -0
- package/server/lib/preview/proxy-runtime.js +140 -45
- package/server/lib/preview/proxy-runtime.test.js +174 -3
- package/server/lib/preview/proxy-runtime.websocket.test.js +89 -0
- package/server/lib/relay/tunnel-host.js +1 -0
- package/server/lib/security/request-security.js +37 -0
- package/server/lib/security/request-security.test.js +54 -0
- package/server/lib/security/server-network-host.js +107 -0
- package/server/lib/security/server-network-host.test.js +70 -0
- package/server/lib/server-browser/DOCUMENTATION.md +243 -0
- package/server/lib/server-browser/browser-tab.js +524 -0
- package/server/lib/server-browser/chrome-executable.js +138 -0
- package/server/lib/server-browser/chrome-launch.js +138 -0
- package/server/lib/server-browser/dev-servers.js +288 -0
- package/server/lib/server-browser/dev-servers.test.js +152 -0
- package/server/lib/server-browser/downloads.js +75 -0
- package/server/lib/server-browser/frame-policy.js +183 -0
- package/server/lib/server-browser/frame-policy.test.js +98 -0
- package/server/lib/server-browser/network-guard.js +235 -0
- package/server/lib/server-browser/page-scripts.js +209 -0
- package/server/lib/server-browser/runtime.integration.test.js +474 -0
- package/server/lib/server-browser/runtime.js +300 -0
- package/server/lib/server-browser/runtime.test.js +50 -0
- package/server/lib/server-browser/server-browser.js +431 -0
- package/server/lib/server-browser/server-browser.test.js +975 -0
- package/server/lib/server-browser/tab-input.js +241 -0
- package/server/lib/server-browser/tab-prompts.js +125 -0
- package/server/lib/server-browser/tab-stream.js +252 -0
- package/server/lib/server-browser/uploads.js +98 -0
- package/server/lib/stt/runtime.js +4 -1
- package/server/lib/stt/runtime.test.js +43 -0
- package/server/lib/terminal/runtime.js +4 -1
- package/server/lib/terminal/runtime.test.js +41 -0
- package/server/lib/ui-auth/DOCUMENTATION.md +29 -1
- package/server/lib/ui-auth/ui-auth.js +1 -0
- package/server/lib/ui-auth/ui-auth.test.js +9 -1
- package/server/lib/workspace/host.js +20 -3
- package/dist/assets/DiffView-CEAAlJ4b.js +0 -18
- package/dist/assets/FileSaveConflictDialog-yvhJRLj7.js +0 -3
- package/dist/assets/PullRequestsSurface-DMWgrwmP.js +0 -2
- package/dist/assets/SessionSwitcherDropdown-D-kE5IJ_.js +0 -2
- package/dist/assets/SessionUnreadDot-DNbvtMOd.js +0 -1
- package/dist/assets/SettingsView-BhXkRsZT.js +0 -6
- package/dist/assets/abap-BdImnpbu.js +0 -1
- package/dist/assets/actionscript-3-CoDkCxhg.js +0 -1
- package/dist/assets/ada-bCR0ucgS.js +0 -1
- package/dist/assets/angular-html-CU67Zn6k.js +0 -1
- package/dist/assets/angular-ts-BwZT4LLn.js +0 -1
- package/dist/assets/apache-Pmp26Uib.js +0 -1
- package/dist/assets/apex-D8_7TLub.js +0 -1
- package/dist/assets/apl-dKokRX4l.js +0 -1
- package/dist/assets/applescript-Co6uUVPk.js +0 -1
- package/dist/assets/ara-BRHolxvo.js +0 -1
- package/dist/assets/asciidoc-Ve4PFQV2.js +0 -1
- package/dist/assets/asm-D_Q5rh1f.js +0 -1
- package/dist/assets/astro-CbQHKStN.js +0 -1
- package/dist/assets/awk-DMzUqQB5.js +0 -1
- package/dist/assets/ballerina-BFfxhgS-.js +0 -1
- package/dist/assets/bat-BkioyH1T.js +0 -1
- package/dist/assets/beancount-k_qm7-4y.js +0 -1
- package/dist/assets/berry-uYugtg8r.js +0 -1
- package/dist/assets/bibtex-CHM0blh-.js +0 -1
- package/dist/assets/bicep-Bmn6On1c.js +0 -1
- package/dist/assets/bird2-DPOp833l.js +0 -1
- package/dist/assets/blade-D4QpJJKB.js +0 -1
- package/dist/assets/bsl-BO_Y6i37.js +0 -1
- package/dist/assets/c-BIGW1oBm.js +0 -1
- package/dist/assets/c3-eo99z4R2.js +0 -1
- package/dist/assets/cadence-Bv_4Rxtq.js +0 -1
- package/dist/assets/cairo-KRGpt6FW.js +0 -1
- package/dist/assets/clarity-D53aC0YG.js +0 -1
- package/dist/assets/clojure-P80f7IUj.js +0 -1
- package/dist/assets/cmake-D1j8_8rp.js +0 -1
- package/dist/assets/cobol-nwyudZeR.js +0 -1
- package/dist/assets/codeowners-Bp6g37R7.js +0 -1
- package/dist/assets/codeql-DsOJ9woJ.js +0 -1
- package/dist/assets/coffee-Ch7k5sss.js +0 -1
- package/dist/assets/common-lisp-Cg-RD9OK.js +0 -1
- package/dist/assets/coq-DkFqJrB1.js +0 -1
- package/dist/assets/cpp-CofmeUqb.js +0 -1
- package/dist/assets/crystal-tKQVLTB8.js +0 -1
- package/dist/assets/csharp-COcwbKMJ.js +0 -1
- package/dist/assets/css-DPfMkruS.js +0 -1
- package/dist/assets/csv-fuZLfV_i.js +0 -1
- package/dist/assets/cue-D82EKSYY.js +0 -1
- package/dist/assets/cypher-COkxafJQ.js +0 -1
- package/dist/assets/d-85-TOEBH.js +0 -1
- package/dist/assets/dart-CF10PKvl.js +0 -1
- package/dist/assets/dax-CEL-wOlO.js +0 -1
- package/dist/assets/desktop-BmXAJ9_W.js +0 -1
- package/dist/assets/diff-D97Zzqfu.js +0 -1
- package/dist/assets/docker-BcOcwvcX.js +0 -1
- package/dist/assets/dotenv-Da5cRb03.js +0 -1
- package/dist/assets/dream-maker-BtqSS_iP.js +0 -1
- package/dist/assets/edge-BkV0erSs.js +0 -1
- package/dist/assets/elixir-CDX3lj18.js +0 -1
- package/dist/assets/elm-DbKCFpqz.js +0 -1
- package/dist/assets/emacs-lisp-C9XAeP06.js +0 -1
- package/dist/assets/erb-B12qg9BL.js +0 -1
- package/dist/assets/erlang-DsQrWhSR.js +0 -1
- package/dist/assets/fennel-BYunw83y.js +0 -1
- package/dist/assets/fish-BvzEVeQv.js +0 -1
- package/dist/assets/fluent-C4IJs8-o.js +0 -1
- package/dist/assets/fortran-fixed-form-CkoXwp7k.js +0 -1
- package/dist/assets/fortran-free-form-BxgE0vQu.js +0 -1
- package/dist/assets/fsharp-CXgrBDvD.js +0 -1
- package/dist/assets/gdresource-BOOCDP_w.js +0 -1
- package/dist/assets/gdscript-C5YyOfLZ.js +0 -1
- package/dist/assets/gdshader-DkwncUOv.js +0 -1
- package/dist/assets/genie-D0YGMca9.js +0 -1
- package/dist/assets/gherkin-DyxjwDmM.js +0 -1
- package/dist/assets/git-commit-F4YmCXRG.js +0 -1
- package/dist/assets/git-rebase-r7XF79zn.js +0 -1
- package/dist/assets/gleam-BspZqrRM.js +0 -1
- package/dist/assets/glimmer-js-Rg0-pVw9.js +0 -1
- package/dist/assets/glimmer-ts-U6CK756n.js +0 -1
- package/dist/assets/glsl-DplSGwfg.js +0 -1
- package/dist/assets/gn-n2N0HUVH.js +0 -1
- package/dist/assets/gnuplot-DdkO51Og.js +0 -1
- package/dist/assets/go-CxLEBnE3.js +0 -1
- package/dist/assets/graphql-ChdNCCLP.js +0 -1
- package/dist/assets/groovy-gcz8RCvz.js +0 -1
- package/dist/assets/hack-CaT9iCJl.js +0 -1
- package/dist/assets/haml-B8DHNrY2.js +0 -1
- package/dist/assets/handlebars-BL8al0AC.js +0 -1
- package/dist/assets/haskell-Df6bDoY_.js +0 -1
- package/dist/assets/haxe-CzTSHFRz.js +0 -1
- package/dist/assets/hcl-BWvSN4gD.js +0 -1
- package/dist/assets/hjson-D5-asLiD.js +0 -1
- package/dist/assets/hlsl-D3lLCCz7.js +0 -1
- package/dist/assets/html-GMplVEZG.js +0 -1
- package/dist/assets/html-derivative-BFtXZ54Q.js +0 -1
- package/dist/assets/http-jrhK8wxY.js +0 -1
- package/dist/assets/hurl-irOxFIW8.js +0 -1
- package/dist/assets/hxml-Bvhsp5Yf.js +0 -1
- package/dist/assets/hy-DFXneXwc.js +0 -1
- package/dist/assets/imba-DGztddWO.js +0 -1
- package/dist/assets/index-B7HgGIB0.js +0 -1
- package/dist/assets/index-BwoW_-vk.css +0 -1
- package/dist/assets/ini-BEwlwnbL.js +0 -1
- package/dist/assets/java-CylS5w8V.js +0 -1
- package/dist/assets/javascript-wDzz0qaB.js +0 -1
- package/dist/assets/jinja-4LBKfQ-Z.js +0 -1
- package/dist/assets/jison-wvAkD_A8.js +0 -1
- package/dist/assets/json-Cp-IABpG.js +0 -1
- package/dist/assets/json5-C9tS-k6U.js +0 -1
- package/dist/assets/jsonc-Des-eS-w.js +0 -1
- package/dist/assets/jsonl-DcaNXYhu.js +0 -1
- package/dist/assets/jsonnet-DFQXde-d.js +0 -1
- package/dist/assets/jssm-C2t-YnRu.js +0 -1
- package/dist/assets/jsx-g9-lgVsj.js +0 -1
- package/dist/assets/julia-CxzCAyBv.js +0 -1
- package/dist/assets/just-Cw27pwNe.js +0 -1
- package/dist/assets/kdl-DV7GczEv.js +0 -1
- package/dist/assets/kotlin-BdnUsdx6.js +0 -1
- package/dist/assets/kusto-DZf3V79B.js +0 -1
- package/dist/assets/latex-CWtU0Tv5.js +0 -1
- package/dist/assets/lean-BZvkOJ9d.js +0 -1
- package/dist/assets/less-B1dDrJ26.js +0 -1
- package/dist/assets/liquid-DYVedYrR.js +0 -1
- package/dist/assets/llvm-DjAJT7YJ.js +0 -1
- package/dist/assets/log-2UxHyX5q.js +0 -1
- package/dist/assets/logo-BtOb2qkB.js +0 -1
- package/dist/assets/lua-BaeVxFsk.js +0 -1
- package/dist/assets/luau-C-HG3fhB.js +0 -1
- package/dist/assets/main-BWWBkkNK.js +0 -136
- package/dist/assets/main-C-nlfc4f.js +0 -2
- package/dist/assets/make-CHLpvVh8.js +0 -1
- package/dist/assets/markdown-Cvjx9yec.js +0 -1
- package/dist/assets/markdownCore-B6YzRefV.js +0 -2
- package/dist/assets/marko-CnJfTvn9.js +0 -1
- package/dist/assets/matlab-D7o27uSR.js +0 -1
- package/dist/assets/mdc-BMNejdWA.js +0 -1
- package/dist/assets/mdx-Cmh6b_Ma.js +0 -1
- package/dist/assets/mermaid-mWjccvbQ.js +0 -1
- package/dist/assets/miniChat-b8DbqBHL.js +0 -2
- package/dist/assets/mipsasm-CKIfxQSi.js +0 -1
- package/dist/assets/mobile-BDDUPrDt.js +0 -2
- package/dist/assets/mojo-rZm6bMo-.js +0 -1
- package/dist/assets/moonbit-_H4v1dQx.js +0 -1
- package/dist/assets/move-IF9eRakj.js +0 -1
- package/dist/assets/narrat-DRg8JJMk.js +0 -1
- package/dist/assets/nextflow-Zz6hmt5N.js +0 -1
- package/dist/assets/nextflow-groovy-BeH2EWoN.js +0 -1
- package/dist/assets/nginx-BpAMiNFr.js +0 -1
- package/dist/assets/nim-CVrawwO9.js +0 -1
- package/dist/assets/nix-CwoSXNpI.js +0 -1
- package/dist/assets/nsis-LdVXkNf5.js +0 -1
- package/dist/assets/nushell-Cz2AlsmD.js +0 -1
- package/dist/assets/objective-c-DXmwc3jG.js +0 -1
- package/dist/assets/objective-cpp-CLxacb5B.js +0 -1
- package/dist/assets/ocaml-C0hk2d4L.js +0 -1
- package/dist/assets/odin-BBf5iR-q.js +0 -1
- package/dist/assets/openscad-C4EeE6gA.js +0 -1
- package/dist/assets/pascal-D93ZcfNL.js +0 -1
- package/dist/assets/perl-C0TMdlhV.js +0 -1
- package/dist/assets/permissionStore-B9Hkrqny.js +0 -1
- package/dist/assets/php-Dhbhpdrm.js +0 -1
- package/dist/assets/pi-session-focus-preference-gLalTsQo.js +0 -9
- package/dist/assets/pkl-u5AG7uiY.js +0 -1
- package/dist/assets/plsql-ChMvpjG-.js +0 -1
- package/dist/assets/po-BTJTHyun.js +0 -1
- package/dist/assets/polar-C0HS_06l.js +0 -1
- package/dist/assets/postcss-CXtECtnM.js +0 -1
- package/dist/assets/powerquery-CEu0bR-o.js +0 -1
- package/dist/assets/powershell-Dpen1YoG.js +0 -1
- package/dist/assets/prisma-Dd19v3D-.js +0 -1
- package/dist/assets/prolog-CbFg5uaA.js +0 -1
- package/dist/assets/proto-C7zT0LnQ.js +0 -1
- package/dist/assets/pug-CGlum2m_.js +0 -1
- package/dist/assets/puppet-BMWR74SV.js +0 -1
- package/dist/assets/purescript-CklMAg4u.js +0 -1
- package/dist/assets/python-B6aJPvgy.js +0 -1
- package/dist/assets/qml-3beO22l8.js +0 -1
- package/dist/assets/qmldir-C8lEn-DE.js +0 -1
- package/dist/assets/qss-IeuSbFQv.js +0 -1
- package/dist/assets/r-Dspwwk_N.js +0 -1
- package/dist/assets/racket-BqYA7rlc.js +0 -1
- package/dist/assets/raku-DXvB9xmW.js +0 -1
- package/dist/assets/razor-Uh8Bk_45.js +0 -1
- package/dist/assets/reg-C-SQnVFl.js +0 -1
- package/dist/assets/regexp-CDVJQ6XC.js +0 -1
- package/dist/assets/rel-C3B-1QV4.js +0 -1
- package/dist/assets/renderElectronMiniChatApp-CiWui-Wg.js +0 -2
- package/dist/assets/renderMobileApp-C27Xb0G7.js +0 -11
- package/dist/assets/riscv-BM1_JUlF.js +0 -1
- package/dist/assets/ron-D8l8udqQ.js +0 -1
- package/dist/assets/rosmsg-BJDFO7_C.js +0 -1
- package/dist/assets/rst-BrH8l1NY.js +0 -1
- package/dist/assets/ruby-B2Rjki9n.js +0 -1
- package/dist/assets/ruby-Dw2BHqvy.js +0 -1
- package/dist/assets/runtimeEndpointReset-O-OHpVl7.js +0 -62
- package/dist/assets/runtimeSurface-k1Eit61v.js +0 -1
- package/dist/assets/rust-B1yitclQ.js +0 -1
- package/dist/assets/sas-cz2c8ADy.js +0 -1
- package/dist/assets/sass-Cj5Yp3dK.js +0 -1
- package/dist/assets/scala-C151Ov-r.js +0 -1
- package/dist/assets/scheme-C98Dy4si.js +0 -1
- package/dist/assets/scss-OYdSNvt2.js +0 -1
- package/dist/assets/sdbl-DVxCFoDh.js +0 -1
- package/dist/assets/shaderlab-Dg9Lc6iA.js +0 -1
- package/dist/assets/shellscript-Yzrsuije.js +0 -1
- package/dist/assets/shellsession-BADoaaVG.js +0 -1
- package/dist/assets/smalltalk-BERRCDM3.js +0 -1
- package/dist/assets/solidity-rGO070M0.js +0 -1
- package/dist/assets/soy-Brmx7dQM.js +0 -1
- package/dist/assets/sparql-rVzFXLq3.js +0 -1
- package/dist/assets/splunk-BtCnVYZw.js +0 -1
- package/dist/assets/sql-BLtJtn59.js +0 -1
- package/dist/assets/ssh-config-_ykCGR6B.js +0 -1
- package/dist/assets/stata-BH5u7GGu.js +0 -1
- package/dist/assets/stylus-BEDo0Tqx.js +0 -1
- package/dist/assets/surrealql-Bq5Q-fJD.js +0 -1
- package/dist/assets/svelte-C_ipcX3V.js +0 -1
- package/dist/assets/swift-D82vCrfD.js +0 -1
- package/dist/assets/system-verilog-CnnmHF94.js +0 -1
- package/dist/assets/systemd-4A_iFExJ.js +0 -1
- package/dist/assets/talonscript-CkByrt1z.js +0 -1
- package/dist/assets/tasl-QIJgUcNo.js +0 -1
- package/dist/assets/tcl-dwOrl1Do.js +0 -1
- package/dist/assets/templ-P3uqSqPl.js +0 -1
- package/dist/assets/terraform-BETggiCN.js +0 -1
- package/dist/assets/tex-idrVyKtj.js +0 -1
- package/dist/assets/themeResolver-yJ9XpNMI.js +0 -1
- package/dist/assets/toml-vGWfd6FD.js +0 -1
- package/dist/assets/ts-tags-zn1MmPIZ.js +0 -1
- package/dist/assets/tsv-B_m7g4N7.js +0 -1
- package/dist/assets/tsx-COt5Ahok.js +0 -1
- package/dist/assets/turtle-BsS91CYL.js +0 -1
- package/dist/assets/twig-DNn4PbVi.js +0 -1
- package/dist/assets/typescript-BPQ3VLAy.js +0 -1
- package/dist/assets/typespec-BGHnOYBU.js +0 -1
- package/dist/assets/typst-DHCkPAjA.js +0 -1
- package/dist/assets/useAppFontEffects-B6Bro-YP.js +0 -212
- package/dist/assets/useFilesViewSearch-jAAdikwo.js +0 -7
- package/dist/assets/v-BcVCzyr7.js +0 -1
- package/dist/assets/vala-CsfeWuGM.js +0 -1
- package/dist/assets/vb-D17OF-Vu.js +0 -1
- package/dist/assets/vendor-aparajita-capacitor-secure-storage-BDrMx_CE.js +0 -1
- package/dist/assets/vendor-base-ui-CKRUCG-f.js +0 -1
- package/dist/assets/vendor-boot-EC6IyLt1.js +0 -69
- package/dist/assets/vendor-codemirror-autocomplete-CGpAsPWp.js +0 -1
- package/dist/assets/vendor-codemirror-lang-angular-CDJoHJSY.js +0 -1
- package/dist/assets/vendor-codemirror-lang-cpp-BmHofQls.js +0 -1
- package/dist/assets/vendor-codemirror-lang-css-RM2HqXZ0.js +0 -1
- package/dist/assets/vendor-codemirror-lang-html-CHSHUpwq.js +0 -1
- package/dist/assets/vendor-codemirror-lang-java-lhQXgWu0.js +0 -1
- package/dist/assets/vendor-codemirror-lang-javascript-Dw4kFO4e.js +0 -13
- package/dist/assets/vendor-codemirror-lang-jinja-_pAC3UTN.js +0 -1
- package/dist/assets/vendor-codemirror-lang-json-B-b1vAv-.js +0 -1
- package/dist/assets/vendor-codemirror-lang-less-xIgOi1ze.js +0 -1
- package/dist/assets/vendor-codemirror-lang-liquid-CP49m5dB.js +0 -1
- package/dist/assets/vendor-codemirror-lang-markdown-BTht2ATe.js +0 -1
- package/dist/assets/vendor-codemirror-lang-php-BguZDhaO.js +0 -1
- package/dist/assets/vendor-codemirror-lang-python-CH6_em9L.js +0 -3
- package/dist/assets/vendor-codemirror-lang-rust-EG_DtGyi.js +0 -1
- package/dist/assets/vendor-codemirror-lang-sass-BknY5Qpo.js +0 -1
- package/dist/assets/vendor-codemirror-lang-vue-CyGn9snv.js +0 -1
- package/dist/assets/vendor-codemirror-lang-wast-CsFfSyyB.js +0 -1
- package/dist/assets/vendor-codemirror-lang-xml-Cdan_Jp1.js +0 -1
- package/dist/assets/vendor-codemirror-lang-yaml-COI5hck8.js +0 -1
- package/dist/assets/vendor-codemirror-search-DUfSCF9S.js +0 -2
- package/dist/assets/vendor-dompurify-r8glNMJW.js +0 -2
- package/dist/assets/vendor-elkjs-D27273Ms.js +0 -24
- package/dist/assets/vendor-fuse.js-Dw8P0qyA.js +0 -1
- package/dist/assets/vendor-lezer-cpp-DMZOJzBa.js +0 -1
- package/dist/assets/vendor-lezer-css-DUkkbMp7.js +0 -1
- package/dist/assets/vendor-lezer-java-tMazV_6X.js +0 -1
- package/dist/assets/vendor-lezer-javascript-ctwLWf4v.js +0 -1
- package/dist/assets/vendor-lezer-lr-B8TQctNw.js +0 -1
- package/dist/assets/vendor-lezer-markdown-aGLZf_3h.js +0 -6
- package/dist/assets/vendor-lezer-php-D5zCNzlt.js +0 -1
- package/dist/assets/vendor-lezer-rust-DO5c7OtA.js +0 -1
- package/dist/assets/vendor-marked-CX41MkDF.js +0 -59
- package/dist/assets/vendor-oniguruma-to-es-DLBnFDCE.js +0 -94
- package/dist/assets/vendor-property-information-rJCbAzvX.js +0 -1
- package/dist/assets/vendor-react-DASdDPIk.js +0 -1
- package/dist/assets/vendor-remend-BWYYytN3.js +0 -22
- package/dist/assets/vendor-replit-codemirror-vim-AnOuN8yJ.js +0 -39
- package/dist/assets/vendor-shiki-Bbf2GEcE.js +0 -2
- package/dist/assets/vendor-shikijs-vscode-textmate-BgLrS_2D.js +0 -3
- package/dist/assets/vendor-tailwind-merge-CPcsbTWB.js +0 -1
- package/dist/assets/vendor-workbox-window-BIl4cyR9.js +0 -2
- package/dist/assets/vendor-zumer-snapdom-Btyu_Xi2.js +0 -8
- package/dist/assets/vendor-zustand-CUi8eEds.js +0 -6
- package/dist/assets/verilog-BQ8w6xss.js +0 -1
- package/dist/assets/vhdl-CeAyd5Ju.js +0 -1
- package/dist/assets/viml-CJc9bBzg.js +0 -1
- package/dist/assets/vue-DN_0RTcg.js +0 -1
- package/dist/assets/vue-html-AaS7Mt5G.js +0 -1
- package/dist/assets/vue-vine-CQOfvN7w.js +0 -1
- package/dist/assets/vyper-CDx5xZoG.js +0 -1
- package/dist/assets/wasm-MzD3tlZU.js +0 -1
- package/dist/assets/wenyan-BV7otONQ.js +0 -1
- package/dist/assets/wgsl-Dx-B1_4e.js +0 -1
- package/dist/assets/wikitext-BhOHFoWU.js +0 -1
- package/dist/assets/wit-5i3qLPDT.js +0 -1
- package/dist/assets/wolfram-lXgVvXCa.js +0 -1
- package/dist/assets/worker-BBk7yuNN.js +0 -153
- package/dist/assets/workerFactory-tw7cIdmV.js +0 -1
- package/dist/assets/xml-sdJ4AIDG.js +0 -1
- package/dist/assets/xsl-CtQFsRM5.js +0 -1
- package/dist/assets/yaml-Buea-lGh.js +0 -1
- package/dist/assets/zenscript-DVFEvuxE.js +0 -1
- package/dist/assets/zig-VOosw3JB.js +0 -1
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-nOAE6UDy.js","assets/useAppFontEffects-CHnpTOtc.js","assets/index-C2ISrmRR.js","assets/vendor-zustand-CXhN0IMY.js","assets/vendor-react-Bz1tRBxM.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tailwind-merge-BKkUfl9q.js","assets/vendor-fuse.js-t_7AcMTv.js","assets/index-DgwThEwf.css","assets/vendor-boot-CoTxysn6.js","assets/runtimeSurface-CJN1oo_1.js","assets/nativeFileSave-Bhafll_7.js","assets/computeVirtualFileMetrics-ydVGT2RY.js","assets/vendor-shiki-BEwTOAFg.js","assets/vendor-shikijs-core-Ck_OPM_T.js","assets/vendor-shikijs-types-CPSbSeK6.js","assets/vendor-shikijs-vscode-textmate-DPFxvYtK.js","assets/vendor-hast-util-to-html-O3stl53j.js","assets/vendor-html-void-elements-CkdplsNl.js","assets/vendor-property-information-C40bX6nM.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-DrfmQi8i.js","assets/vendor-pierre-theming-BO6EPniU.js","assets/vendor-shikijs-engine-javascript-DL394yyj.js","assets/vendor-oniguruma-to-es-DgwFOwdE.js","assets/vendor-oniguruma-parser-BrbMHgHx.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-RJTrDxFH.js","assets/renderDiffWithHighlighter-JwKOWdBN.js","assets/vendor-diff-C3JhlQdm.js","assets/vendor-lru_map-BbiDqlyL.js","assets/appThemeRegistry-Ca8eGRB9.js","assets/registerCustomTheme-C-h6lsYW.js","assets/vendor-capacitor-keyboard-DJD81I9f.js","assets/SessionSwitcherDropdown-CA64t2xd.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{_ as mt}from"./vendor-vite-runtime-DD1OZmLC.js";import{j as s,aS as Dd,aT as Pd,aU as Md,aV as Td,aW as Fd,aX as Ld,aY as Od,aZ as _o,a_ as Fn,a$ as Bd,b0 as Uo,b1 as zo,b2 as _d,b3 as Ud,b4 as zd,b5 as $d,b6 as Ca,b7 as Aa,b8 as Na,b9 as Ia,ba as Ea,bb as Ra,bc as Da,bd as Pa,be as Ma,bf as Ta,bg as Fa,bh as $o,bi as Ko,bj as oo,aP as Kd}from"./vendor-boot-CoTxysn6.js";import{a as Re,R as a}from"./vendor-react-Bz1tRBxM.js";import{aq as Zs,ar as Wd,t as oe,a as ct,h as Te,as as dn,B as Ne,I as P,at as Ln,au as La,av as ts,aw as ss,ax as ws,ay as ds,az as vs,aA as Ls,aB as Ms,v as gs,aC as Ts,aD as Gd,g as Js,aE as Br,aF as Si,aG as ji,aH as En,e as sr,aI as Hd,aJ as qd,aK as Yd,aL as Vd,aM as Qd,aN as Jd,o as Oa,aO as Is,aP as ki,ah as xs,aQ as $e,aR as Ke,aS as We,aT as io,aU as Xd,aV as Zd,aW as eu,aX as tu,aY as su,aZ as ao,a_ as nu,a$ as Gt,b0 as Ht,b1 as qt,O as Kt,b2 as ru,b3 as ou,b4 as iu,b5 as au,b6 as lu,b7 as cu,b8 as lo,r as Rn,G as Wo,b9 as du,ba as uu,bb as Ba,bc as _a,Z as ys,bd as fu,be as hu,bf as mu,bg as pu,d as Ua,z as Os,bh as za,bi as Sr,bj as Ci,bk as $a,bl as bt,bm as gu,bn as bu,bo as Ka,bp as Wa,bq as Ga,br as Ha,bs as Go,bt as qa,bu as ht,bv as Ya,bw as xu,i as Va,p as yu,bx as wu,j as vu,u as Qa,k as Su,m as ju,by as Ja,n as ku,q as Ai,bz as Cu,bA as qs,b as Ni,c as Au,bB as Nu,bC as Iu,bD as Eu,bE as co,bF as Ru,bG as Du,bH as Pu,bI as Mu,bJ as Tu,a4 as Fu,bK as nn,bL as Xa,M as Lu,y as Ou,bM as Bu,w as _u,bN as Uu,bO as Za,bP as zu,aj as $u,bQ as Ku,bR as Wu,bS as Gu,bT as Hu,bU as qu,bV as Yu,bW as Vu,bX as Qu,bY as Ju,bZ as Xu}from"./useAppFontEffects-CHnpTOtc.js";import{A as Ii,B as Zu,a as rn,C as el,D as tl,E as ef,F as tf,u as on,G as sf,H as nf,I as rf,h as ce,z as nt,f as _,J as of,K as Je,b as Ft,o as Un,L as af,M as lf,N as cf,O as df,q as Ee,P as On,Q as Wt,R as uo,T as fo,U as sl,n as cs,V as Ho,W as dr,X as uf,v as nl,Y as ff,Z as rl,_ as hf,$ as ol,a0 as Dn,a1 as ho,j as mo,e as Hn,a2 as mf,a3 as pf,a4 as gf,a5 as Ei,a6 as wn,a7 as _r,a8 as po,a9 as ur,aa as Es,ab as Ri,ac as go,ad as il,ae as bo,af as bf,ag as xf,ah as yf,ai as wf,aj as vf,ak as Sf,al as jf,am as kf,an as Cf,ao as al,ap as Af,aq as Nf,ar as If,as as Ef,at as Rf}from"./index-C2ISrmRR.js";import{b as Df,g as ll,r as Pf,d as cl,s as nr,c as dl,e as Fs,h as an,i as Mf,j as Tf,k as Ff,l as Lf,m as qo,n as ul,f as Of,a as Di,S as Bf,t as _f,o as Uf}from"./SessionUnreadDot-BZy2DM6H.js";import{c as Bs,d as jr,p as fl,a as zf}from"./vendor-zustand-CXhN0IMY.js";/* empty css */import{saveOrShareFile as $f}from"./nativeFileSave-Bhafll_7.js";import{usePermissionStore as Kf}from"./permissionStore-zIpxq9Pq.js";const Wf="chat";function hl(e){const t=new URLSearchParams;if(e.sessionId&&e.sessionId.trim().length>0&&t.set(Zs.SESSION,e.sessionId),e.isSettingsOpen){const n=e.settingsPath.trim().length>0?e.settingsPath:"home";return t.set(Zs.SETTINGS,n),t}return e.tab!==Wf&&t.set(Zs.TAB,e.tab),e.tab==="diff"&&e.diffFile&&e.diffFile.trim().length>0&&t.set(Zs.FILE,e.diffFile),t}function Gf(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 Hf(e){if(typeof window>"u")return!0;try{const t=new URLSearchParams(window.location.search),n=hl(e),r=window.location.pathname.match(/^\/(?:session|s)\/([^/?#]+)/i),o=r?.[1]?decodeURIComponent(r[1].trim()):null;o&&!t.has(Zs.SESSION)&&t.set(Zs.SESSION,o);const i=[...t.entries()].sort((c,d)=>c[0].localeCompare(d[0])),l=[...n.entries()].sort((c,d)=>c[0].localeCompare(d[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 xo(e,t={}){if(!(typeof window>"u")&&!(!t.force&&Hf(e)))try{const n=hl(e),r=Gf(n);t.replace?window.history.replaceState({...window.history.state,route:e},"",r):window.history.pushState({route:e},"",r)}catch{}}const qf=["typescript","javascript","tsx","jsx","json","markdown"],ml={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let Pi=null;const pl=()=>(Pi??=Promise.all([mt(()=>import("./index-nOAE6UDy.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,42])),mt(()=>import("./workerFactory-DlGfNFqf.js"),[]),mt(()=>import("./appThemeRegistry-Ca8eGRB9.js"),__vite__mapDeps([43,44,30,31,5,15,16,17,18,19,20,21,22,23,24,25,26,27,28]))]).then(([e,t,n])=>({WorkerPoolManager:e.WorkerPoolManager,workerFactory:t.workerFactory,ensurePierreThemeRegistered:n.ensurePierreThemeRegistered})),Pi),Bn={},Mi=new Set,yo=new Set;let rr={light:"pierre-light",dark:"pierre-dark"};const Yf=()=>{for(const e of yo)e()},gl=(e,t)=>{t.setRenderOptions({theme:rr,lineDiffType:ml[e].lineDiffType})},wo=e=>{typeof window>"u"||Mi.has(e)||(Mi.add(e),pl().then(t=>{if(Bn[e])return;const n=ml[e],r=new t.WorkerPoolManager({workerFactory:t.workerFactory,poolSize:n.poolSize,totalASTLRUCacheSize:n.totalASTLRUCacheSize},{theme:{light:"pierre-light",dark:"pierre-dark"},langs:qf,lineDiffType:n.lineDiffType,preferredHighlighter:"shiki-wasm"});r.initialize(),Bn[e]=r,gl(e,r),Yf()}))},Vf=e=>(yo.add(e),()=>yo.delete(e)),Qf=e=>{if(!(rr.light===e.light&&rr.dark===e.dark)){rr=e;for(const t of Object.keys(Bn)){const n=Bn[t];n&&gl(t,n)}}},Px=({children:e})=>{const t=Wd(),n=Ii(!1),r=Ii(!0),o=t?.lightThemeId??n.metadata.id,i=t?.darkThemeId??r.metadata.id,l=t?.availableThemes.find(d=>d.metadata.id===o)??n,c=t?.availableThemes.find(d=>d.metadata.id===i)??r;return Re.useEffect(()=>{let d=!1;return pl().then(u=>{d||(u.ensurePierreThemeRegistered(l),u.ensurePierreThemeRegistered(c),Qf({light:l.metadata.id,dark:c.metadata.id}))}),()=>{d=!0}},[c,l]),Re.useEffect(()=>{if(typeof window>"u")return;const d=()=>{wo("unified"),wo("split")};if(typeof window.requestIdleCallback=="function"){const f=window.requestIdleCallback(d,{timeout:5e3});return()=>window.cancelIdleCallback(f)}const u=window.setTimeout(d,2e3);return()=>window.clearTimeout(u)},[]),s.jsx(s.Fragment,{children:e})},Mx=(e="unified")=>{const t=Re.useSyncExternalStore(Vf,()=>Bn[e],()=>{});return Re.useEffect(()=>{wo(e)},[e]),t},Jf=e=>e==="/",ln=e=>e.replace(/\\/g,"/"),cn=e=>{if(!e||Jf(e))return e;let t=e;for(;t.length>1&&t.endsWith("/");)t=t.slice(0,-1);return t},tn=e=>e.endsWith("/"),fr=e=>{const t=e.trim();return!t||tn(t)?t:`${t}/`},Yo=e=>e.lastIndexOf("/"),bl=e=>{if(tn(e))return e;const t=Yo(e);return t<0?e:e.slice(0,t+1)},xl=e=>{const t=Yo(e);return e.slice(t+1)},yl=e=>{const t=cn(e.trim());if(!t||t==="~"||t==="~/"||t==="/")return null;const n=Yo(t);return n<0?null:t.startsWith("~/")&&n<=1?"~/":n===0?"/":`${t.slice(0,n)}/`},wl=e=>tn(e)&&yl(e)!==null,Xf=e=>{if(!wl(e))return null;const t=cn(e.trim());return xl(t)||t},Zf=(e,t)=>`${bl(e)}${t}/`,Rs=e=>{if(!e)return null;const t=cn(ln(e.trim()));return t?t.toLowerCase():null},Ti=(e,t)=>{const n=e.trim();return n==="~"?t:n.startsWith("~/")?`${t}${n.slice(1)}`:n},eh=(e,t)=>{const n=cn(ln(e.trim())),r=cn(ln(t.trim()));if(!n)return"";if(!r)return fr(n);if(n.toLowerCase()===r.toLowerCase())return"~/";const o=`${r}/`;return n.toLowerCase().startsWith(o.toLowerCase())?`~/${n.slice(r.length+1)}/`:fr(n)},th=e=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey,vo=e=>{if(!e)return;e.focus({preventScroll:!0});const t=e.value.length;e.setSelectionRange(t,t),e.scrollLeft=e.scrollWidth},sh=async()=>Zu({fresh:!0}),nh=()=>{const[e,t]=Re.useState(!1),[n,r]=Re.useState(!1);Re.useEffect(()=>{t(rn()),r(el())},[]);const o=Re.useCallback(async c=>e?await tl(c):{success:!0,path:c},[e]),i=Re.useCallback(async c=>e?await ef():{success:!0},[e]),l=Re.useCallback(async c=>e?await tf():{success:!0},[e]);return{isDesktop:e,canRequestAccess:n,requestAccess:o,startAccessing:i,stopAccessing:l}};function rh({open:e,addedProjectPaths:t,shouldSuppressAutoFocus:n}){const r=on(Q=>Q.homeDirectory),{canRequestAccess:o,startAccessing:i}=nh(),l=a.useRef(null),c=a.useRef(new Map),[d,u]=a.useState(""),[f,p]=a.useState("~/"),[x,y]=a.useState([]),[m,h]=a.useState(!1),[b,g]=a.useState(!1),[S,w]=a.useState(null),[E,A]=a.useState(0),[k,j]=a.useState(0),[v,N]=a.useState(!1),[M,L]=a.useState(!1),[K,z]=a.useState("right"),$=a.useRef("~/"),O=d||r;a.useEffect(()=>{if(!e)return;p("~/"),y([]),j(0),N(!1),L(!1),$.current="~/",z("right"),n||requestAnimationFrame(()=>vo(l.current));let Q=!1;return(async()=>{const ke=await sh();Q||(u(ke||r||""),n||requestAnimationFrame(()=>vo(l.current)))})(),()=>{Q=!0}},[r,e,n]);const R=a.useMemo(()=>bl(f),[f]),D=a.useMemo(()=>tn(f)?"":xl(f),[f]),I=a.useMemo(()=>O?Ti(R,O):"",[R,O]);a.useEffect(()=>{const Q=$.current;Q!==R&&(z(R.length>=Q.length?"right":"left"),$.current=R)},[R]),a.useEffect(()=>{if(!e||!I){y([]),w(null);return}let Q=!1;return h(!0),g(!1),w(null),sf(I).then(ie=>{if(Q)return;g(!1),w(null);const ke=ie.filter(Se=>Se.isDirectory).map(Se=>({name:Se.name,path:ln(Se.path)})).sort((Se,He)=>Se.name.localeCompare(He.name));y(ke)}).catch(ie=>{if(!Q){y([]);const ke=nf(ie)?ie.reason:"unknown";w(ke),g(ke==="not-found")}}).finally(()=>{Q||h(!1)}),()=>{Q=!0}},[I,E,e]);const T=a.useMemo(()=>{const Q=D.toLowerCase(),ie=M||D.startsWith(".");return x.filter(ke=>ke.name.toLowerCase().startsWith(Q)&&(ie||!ke.name.startsWith(".")))},[D,x,M]),W=a.useMemo(()=>Xf(f),[f]),Z=a.useMemo(()=>yl(f),[f]),F=a.useMemo(()=>{const Q=[],ie=Rs(I);wl(f)&&W&&Z&&Q.push({type:"parent",value:"browse:up",name:W,path:Z,alreadyAdded:!!(ie&&t.has(ie))});for(const ke of T){const Se=Rs(ke.path);Q.push({type:"directory",value:`browse:${ke.path}`,name:ke.name,path:ke.path,alreadyAdded:!!(Se&&t.has(Se))})}return Q},[t,I,W,T,Z,f]);a.useEffect(()=>{j(0)},[f,F.length]);const me=a.useMemo(()=>O?cn(Ti(f,O)):"",[O,f]),q=Rs(me),Ae=!!(q&&t.has(q)),Ie=a.useMemo(()=>D?T.find(Q=>Q.name===D)??null:null,[D,T]),G=!!(me&&!Ae&&(S===null||S==="not-found")&&(tn(f)&&b||!tn(f)&&D.trim().length>0&&Ie===null)),U=F[k]??null,Y=!!U,X=a.useCallback(Q=>{p(fr(Q))},[]),se=a.useCallback(Q=>{p(Zf(f,Q.name))},[f]),we=a.useCallback(Q=>{if(Q){if(Q.type==="parent"){X(Q.path);return}se(Q)}},[X,se]),pe=a.useCallback(async Q=>{const ie=await i(Q);if(!ie.success)return oe.error("Failed to open directory",{description:ie.error||"Desktop could not grant file access."}),!1;const ke=O?eh(Q,O):fr(ln(Q));return X(ke),!0},[X,O,i]),V=a.useCallback(async()=>{if(!v){N(!0);try{if(el()){const ie=await tl(me);if(!ie.success||!ie.path){ie.error&&ie.error!=="Directory selection cancelled"&&oe.error("Failed to select directory",{description:ie.error});return}await pe(ie.path);return}const Q=await rf(me);if(Q.status==="cancelled")return;if(Q.status!=="picked"){oe.error("Couldn't open a folder picker",{description:Q.error});return}await pe(Q.path)}catch(Q){oe.error("Failed to select directory",{description:Q instanceof Error?Q.message:"Unknown error occurred."})}finally{N(!1)}}},[pe,v,me]);return{inputRef:l,rowRefs:c,query:f,setQuery:p,isLoading:m,isBrowseDirectoryMissing:b,browseErrorReason:S,browseReloadKey:E,setBrowseReloadKey:A,highlightedIndex:k,setHighlightedIndex:j,isPickingLocation:v,showHidden:M,setShowHidden:L,folderEnterFrom:K,explorerRootDirectory:O,browseDirectoryDisplayPath:R,browseDirectoryAbsolutePath:I,browseFilterQuery:D,filteredEntries:T,rows:F,targetPath:me,isAlreadyAdded:Ae,shouldCreateTarget:G,highlightedRow:U,hasHighlightedBrowseItem:Y,canRequestAccess:o,browseToDisplayPath:X,browseToEntry:se,executeRow:we,applyPickedLocation:pe,handleBrowseLocation:V}}function oh({open:e,onClose:t,isMobile:n,addedProjectPaths:r,targetPath:o,shouldCreateTarget:i,browseErrorReason:l,browseDirectoryAbsolutePath:c,isAlreadyAdded:d,isPickingLocation:u}){const f=ct(L=>L.addProject),p=ce(L=>L.setActiveMainTab),x=ce(L=>L.setSessionSwitcherOpen),y=Te(L=>L.openNewSessionDraft),[m,h]=a.useState(!1),[b,g]=a.useState(!1),[S,w]=a.useState("");a.useEffect(()=>{e&&(h(!1),g(!1),w(""))},[e]);const E=a.useCallback((L,K)=>{p("chat"),n&&x(!1),y({selectedProjectId:L,directoryOverride:K}),t()},[n,t,y,p,x]),A=a.useCallback(async L=>{if(!L||m)return;const K=Rs(L);if(K&&r.has(K))return;let z=L;h(!0);try{const $=!b&&i&&Rs(L)===Rs(o);if(b){const R=S.trim();if(!R){oe.error("Enter a repository URL before cloning.");return}const D=await nt("/api/fs/clone",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({remoteUrl:R,destinationPath:L})});if(!D.ok)throw new Error("Failed to clone git repository");z=(await D.json()).path||L}else if($&&!(await nt("/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 O=f(z);if(!O){oe.error("Failed to add folder",{description:"Please select a valid directory path."});return}E(O.id,O.path)}catch($){oe.error("Failed to select directory",{description:$ instanceof Error?$.message:"Unknown error occurred."})}finally{h(!1)}},[f,r,c,S,b,m,E,i,o]),k=!m&&!u&&!d&&l!=="os-permission"&&l!=="invalid-response"&&l!=="unknown"&&!!o,j=k&&S.trim().length>0,v=b?j:k,N=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl";return{isConfirming:m,isCloneMode:b,setIsCloneMode:g,cloneRemoteUrl:S,setCloneRemoteUrl:w,canSubmit:v,submitActionLabel:d?"Already added":b?m?"Cloning...":"Clone & add":m?"Adding...":i?"Create & add":"Add folder",submitModifierLabel:N,finalizeSelection:A}}const ih=({open:e,onOpenChange:t})=>{const n=ct(V=>V.projects),{isMobile:r,isTablet:o}=dn(),i=r||o,l=a.useMemo(()=>new Set(n.map(V=>Rs(V.path)).filter(V=>!!V)),[n]),c=a.useCallback(()=>{t(!1)},[t]),{inputRef:d,rowRefs:u,query:f,setQuery:p,isLoading:x,browseErrorReason:y,setBrowseReloadKey:m,highlightedIndex:h,setHighlightedIndex:b,isPickingLocation:g,showHidden:S,setShowHidden:w,folderEnterFrom:E,browseDirectoryDisplayPath:A,browseDirectoryAbsolutePath:k,rows:j,targetPath:v,isAlreadyAdded:N,shouldCreateTarget:M,highlightedRow:L,hasHighlightedBrowseItem:K,canRequestAccess:z,executeRow:$,handleBrowseLocation:O}=rh({open:e,addedProjectPaths:l,shouldSuppressAutoFocus:i}),{isConfirming:R,isCloneMode:D,setIsCloneMode:I,cloneRemoteUrl:T,setCloneRemoteUrl:W,canSubmit:Z,submitActionLabel:F,submitModifierLabel:me,finalizeSelection:q}=oh({open:e,onClose:c,isMobile:r,addedProjectPaths:l,targetPath:v,shouldCreateTarget:M,browseErrorReason:y,browseDirectoryAbsolutePath:k,isAlreadyAdded:N,isPickingLocation:g});a.useLayoutEffect(()=>{const V=d.current;V&&(V.scrollLeft=V.scrollWidth)},[d,f]),a.useLayoutEffect(()=>{!e||i||vo(d.current)},[d,e,i]),a.useLayoutEffect(()=>{const V=j[h];V&&u.current.get(V.value)?.scrollIntoView({block:"nearest"})},[h,u,j]);const Ae=a.useCallback(V=>{if(V.key==="ArrowDown"){V.preventDefault(),b(Q=>Math.min(j.length-1,Q+1));return}if(V.key==="ArrowUp"){V.preventDefault(),b(Q=>Math.max(0,Q-1));return}if(V.key==="Enter"){if(V.preventDefault(),th(V)){q(v);return}K&&$(L);return}V.key==="Backspace"&&f===""&&(V.preventDefault(),c())},[$,q,c,K,L,f,j.length,b,v]),Ie=s.jsxs("button",{type:"button",onClick:()=>w(V=>!V),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:[S?s.jsx(P,{name:"checkbox",className:"h-4 w-4 text-primary"}):s.jsx(P,{name:"checkbox-blank",className:"h-4 w-4"}),"Show hidden"]}),G=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(P,{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(Ln,{ref:d,value:f,onChange:V=>p(ln(V.target.value)),onKeyDown:Ae,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(Ne,{variant:"outline",size:"xs",className:"h-8 shrink-0 gap-1 px-2",disabled:R||g,onMouseDown:V=>V.preventDefault(),onClick:()=>{O()},title:"Browse location","aria-label":"Browse location",children:[s.jsx(P,{name:"folder-open",className:"h-3.5 w-3.5"}),g?"Opening...":"Browse"]})]})}),U=j.some(V=>V.type==="parent"),Y=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(Ne,{variant:"ghost",size:"xs",className:"h-6 shrink-0 gap-1 text-muted-foreground","aria-pressed":D,disabled:R||g,onClick:()=>I(V=>!V),children:[s.jsx(P,{name:"git-repository",className:"h-3.5 w-3.5"}),"Clone"]})]}),D?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(Ln,{value:T,onChange:V=>W(V.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:_("mt-3","animate-in fade-in-0 duration-200 motion-reduce:animate-none",E==="left"?"slide-in-from-left-2":"slide-in-from-right-2"),children:x?s.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"Loading directories..."}):y&&y!=="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:y==="os-permission"?"PiChamber needs access to this folder.":"Could not load this folder."}),s.jsxs("div",{className:"flex items-center gap-2",children:[y==="os-permission"&&z?s.jsx(Ne,{size:"xs",onClick:()=>{O()},disabled:g,children:"Grant access"}):null,s.jsx(Ne,{variant:"outline",size:"xs",onClick:()=>m(V=>V+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((V,Q)=>{const ie=Q===h,ke=V.type==="directory"&&U;return s.jsxs("button",{ref:Se=>{Se?u.current.set(V.value,Se):u.current.delete(V.value)},type:"button","aria-label":V.type==="parent"?V.alreadyAdded?`Go back from ${V.name}, already added`:`Go back from ${V.name}`:V.alreadyAdded?`Open ${V.name}, already added`:`Open ${V.name}`,onMouseEnter:()=>b(Q),onMouseDown:Se=>Se.preventDefault(),onClick:()=>$(V),className:_("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",ie&&"bg-interactive-selection text-interactive-selection-foreground",!ie&&"hover:bg-interactive-hover/50"),children:[s.jsxs("span",{className:_("flex min-w-0 flex-1 items-center gap-2",ke&&"pl-4"),children:[V.type==="parent"?s.jsx(P,{name:"folder-open",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}):s.jsx(P,{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:V.name})]}),V.alreadyAdded?s.jsx("span",{className:_("inline-flex shrink-0 items-center rounded-md px-1.5 py-0.5 typography-meta font-medium",ie?"bg-interactive-selection-foreground/15 text-interactive-selection-foreground":"bg-[var(--surface-muted)] text-foreground"),children:"Added"}):null,V.type==="parent"?s.jsx(P,{name:"arrow-up-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"}):s.jsx(P,{name:"arrow-right-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"})]},V.value)})})},A)]})}),X=s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[G,Y]}),se=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(P,{name:"arrow-up-s",className:"h-3.5 w-3.5"}),s.jsx(P,{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(P,{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:me}),s.jsx(P,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Add folder"]})]}),we=s.jsx(Ne,{size:r?"xs":"default",onClick:()=>{q(v)},disabled:!Z,className:_(r&&"w-full flex-1"),children:F}),pe=()=>s.jsxs(s.Fragment,{children:[r?null:se,s.jsx("div",{className:_("flex w-full flex-row justify-end gap-2 sm:w-auto",r&&"justify-stretch"),children:we})]});return r?s.jsx(La,{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:pe()}),children:s.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3",children:[s.jsx("div",{className:"flex justify-end",children:Ie}),X]})}):s.jsx(ts,{open:e,onOpenChange:t,children:s.jsxs(ss,{className:"flex w-full max-w-xl flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh]",initialFocus:!1,children:[s.jsx(ws,{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(ds,{children:"Add folder"}),s.jsx(vs,{className:"mt-2",children:"Choose a folder from the path above, then add it."})]}),Ie]})}),s.jsx("div",{className:"min-h-0 flex-1 px-5 pb-0",children:X}),s.jsx(Ls,{className:"flex w-full flex-col gap-3 px-5 py-3 sm:flex-row sm:items-center sm:justify-between",children:pe()})]})})},qn=e=>e?s.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:e}):void 0,Tx=()=>{const[e,t]=a.useState(!1),[n,r]=a.useState(null),[o,i]=a.useState(!1),l=Te(k=>k.deleteSession),c=Te(k=>k.deleteSessions),d=ce(k=>k.showDeletionDialog),u=ce(k=>k.setShowDeletionDialog),{isMobile:f,isTablet:p,hasTouchInput:x}=dn(),y=f||p||x;a.useEffect(()=>of(()=>{t(!1)}),[]);const m=a.useCallback(k=>{r({sessions:k.sessions,dateLabel:k.dateLabel})},[]),h=a.useCallback(()=>{r(null),i(!1)},[]),b=a.useCallback(async k=>{if(k.sessions.length===0)return;if(k.sessions.length===1){const M=k.sessions[0];await l(M.id)?oe.success("Session deleted"):oe.error("Failed to delete session");return}const j=k.sessions.map(M=>M.id),{deletedIds:v,failedIds:N}=await c(j);if(v.length>0){const M=N.length>0?N.length===1?`${N.length} session could not be deleted.`:`${N.length} sessions could not be deleted.`:k.dateLabel?`Removed all sessions from ${k.dateLabel}.`:void 0;oe.success(v.length===1?"Deleted {count} session":`Deleted ${v.length} sessions`,{description:qn(M)})}N.length>0&&oe.error(N.length===1?`Failed to delete ${N.length} session`:`Failed to delete ${N.length} sessions`,{description:qn("Please try again in a moment.")})},[l,c]);a.useEffect(()=>Ms.onDeleteRequest(k=>{if(!d){b(k);return}m(k)}),[m,d,b]),a.useEffect(()=>Ms.onDirectoryRequest(()=>{t(!0)}),[]);const g=a.useCallback(async()=>{if(n){i(!0);try{if(n.sessions.length===1){const k=n.sessions[0];if(!await l(k.id)){oe.error("Failed to delete session"),i(!1);return}oe.success("Session deleted",{action:{label:"OK",onClick:()=>{}}})}else{const k=n.sessions.map(M=>M.id),j=await c(k),v=j.deletedIds,N=j.failedIds;if(v.length>0){const M=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;oe.success(v.length===1?"Deleted {count} session":`Deleted ${v.length} sessions`,{description:qn(M),action:{label:"OK",onClick:()=>{}}})}if(N.length>0&&(oe.error(N.length===1?`Failed to delete ${N.length} session`:`Failed to delete ${N.length} sessions`,{description:qn("Please try again in a moment.")}),v.length===0)){i(!1);return}}h()}finally{i(!1)}}},[n,l,c,h]),S=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.`:"",w=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(k=>s.jsx("li",{className:"typography-micro text-muted-foreground/80",children:s.jsx("span",{className:"truncate",children:gs(k)})},k.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,E=s.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[s.jsxs("button",{type:"button",onClick:()=>u(!d),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":!d,children:[d?s.jsx(P,{name:"checkbox-blank",className:"size-4"}):s.jsx(P,{name:"checkbox",className:"size-4 text-primary"}),"Never ask"]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ne,{variant:"ghost",onClick:h,disabled:o,children:"Cancel"}),s.jsx(Ne,{variant:"destructive",onClick:g,disabled:o,children:o?"Deleting…":n?.sessions.length===1?"Delete session":"Delete sessions"})]})]}),A=n?.sessions.length===1?"Delete session":"Delete sessions";return s.jsxs(s.Fragment,{children:[y?s.jsx(La,{open:!!n,onClose:()=>{o||h()},title:A,footer:s.jsx("div",{className:"flex justify-end gap-2",children:E}),children:s.jsxs("div",{className:"space-y-2 pb-2",children:[S&&s.jsx("p",{className:"typography-meta text-muted-foreground/80",children:S}),w]})}):s.jsx(ts,{open:!!n,onOpenChange:k=>{if(!k){if(o)return;h()}},children:s.jsxs(ss,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[s.jsxs(ws,{children:[s.jsx(ds,{children:A}),S&&s.jsx(vs,{children:S})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:w}),s.jsx(Ls,{className:"mt-2 gap-2 pt-1 pb-1",children:E})]})}),s.jsx(ih,{open:e,onOpenChange:t})]})},Fx=()=>{const e=Ts(t=>t.entries);return a.useEffect(()=>{for(const t of e.values())!Gd(t)||!t.receipt||(Ts.getState().markNotificationSent(t.key),oe.success("Worktree ready",{id:`worktree-ready:${t.key}`,description:t.receipt.branch||t.receipt.path}))},[e]),null},ah=[{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-access",title:"Remote Access",group:"projects",kind:"single",description:"How other devices reach this computer.",keywords:["remote","access","mobile","phone","pair","qr","device","devices","tailscale","funnel","lan","network","wifi","password","passkey"],isAvailable:e=>!e.isMobile&&(e.isDesktop||e.isWeb)},{slug:"servers",title:"Servers",group:"projects",kind:"single",description:"Which PiChamber server this app uses.",keywords:["server","servers","instance","switch","connect","import link","host"],isAvailable:e=>!e.isMobile&&e.isDesktop||e.isMobile&&e.isCapacitor===!0},{slug:"remote-instances",title:"Remote Instances",group:"projects",kind:"single",keywords:["ssh","remote","instances","tunnels","forwarding","connection"],isAvailable:()=>!1},{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"]}],lh={sessions:"sessions",skills:"skills.installed",providers:"providers","git-identities":"git",settings:"home"};function ch(e){const t=e.trim().toLowerCase();return ah.find(n=>n.slug===t)??null}function dh(e){const t=(e??"").trim().toLowerCase();if(!t)return"home";if(t==="remote-instances")return"remote-access";const n=lh[t];if(n)return n;const r=ch(t);return r?r.slug:"home"}function Lx(e){switch(e){case"general":return"equalizer";case"projects":return"folders";case"remote-access":return"server";case"servers":return"server";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 Ox(){const e=a.useRef(!1),t=a.useRef(!1),n=Te(f=>f.setCurrentSession),r=ce(f=>f.setActiveMainTab),o=ce(f=>f.setSettingsDialogOpen),i=ce(f=>f.setSettingsPage),l=ce(f=>f.navigateToDiff),c=a.useCallback(async f=>{if(!t.current){t.current=!0;try{if(f.sessionId){const p=Te.getState().currentSessionId,x=Js().getState().selectedSessionId;if(f.sessionId!==p||f.sessionId!==x){const y=Te.getState().getDirectoryForSession(f.sessionId);n(f.sessionId,y)}}if(f.settingsPath){i(dh(f.settingsPath)),o(!0);return}ce.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]),d=a.useCallback(()=>{const f=Te.getState(),p=Js().getState(),x=ce.getState();return{sessionId:Br({currentSessionId:f.currentSessionId,piSelectedSessionId:p.selectedSessionId,draft:f.newSessionDraft}),tab:x.activeMainTab,isSettingsOpen:x.isSettingsDialogOpen,settingsPath:x.settingsPage,diffFile:x.pendingDiffFile}},[]),u=a.useCallback((f={})=>{if(t.current)return;const p=d();xo(p,f)},[d]);a.useEffect(()=>{if(e.current||(e.current=!0,!Si()))return;const f=ji();(async()=>(await c(f),xo({...d(),sessionId:f.sessionId??Br({currentSessionId:Te.getState().currentSessionId,piSelectedSessionId:Js().getState().selectedSessionId,draft:Te.getState().newSessionDraft}),tab:f.tab??ce.getState().activeMainTab,settingsPath:f.settingsPath??ce.getState().settingsPage,diffFile:f.diffFile??ce.getState().pendingDiffFile},{replace:!0,force:!0})))()},[c,d]),a.useEffect(()=>{const f=()=>{const b=Te.getState(),g=Js().getState();return Br({currentSessionId:b.currentSessionId,piSelectedSessionId:g.selectedSessionId,draft:b.newSessionDraft})};let p=f(),x=Te.getState().newSessionDraft?.open===!0;const y=()=>{const b=Te.getState(),g=f(),S=b.newSessionDraft?.open===!0;g===p&&S===x||t.current||(p=g,x=S,u({replace:!0}))},m=Te.subscribe(()=>{y()}),h=Js().subscribe(()=>{y()});return()=>{m(),h()}},[u]),a.useEffect(()=>{let f=ce.getState().activeMainTab,p=ce.getState().isSettingsDialogOpen,x=ce.getState().settingsPage,y=ce.getState().pendingDiffFile;return ce.subscribe(h=>{if(t.current)return;const b=h.activeMainTab!==f,g=h.isSettingsDialogOpen!==p,S=h.settingsPage!==x,w=h.pendingDiffFile!==y&&h.activeMainTab==="diff";f=h.activeMainTab,p=h.isSettingsDialogOpen,x=h.settingsPage,y=h.pendingDiffFile,(b||g||S||w)&&u()})},[u]),a.useEffect(()=>{if(typeof window>"u")return;const f=()=>{const p=ji();if(Si())c(p);else{const x=ce.getState();x.isSettingsDialogOpen&&o(!1),x.activeMainTab!=="chat"&&r("chat")}};return window.addEventListener("popstate",f),()=>{window.removeEventListener("popstate",f)}},[c,r,o])}function uh(e=!0){const t=sr(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,d=null;const u=p=>{const x=Math.round(p*1e3);return Math.max(i,Math.min(l,x))},f=p=>{c||(d=window.setTimeout(async()=>{const x=await n.current(),y=typeof x=="number"&&Number.isFinite(x)?u(x):o;f(y)},p))};return f(r),()=>{c=!0,d!==null&&window.clearTimeout(d)}},[e])}function Bx(){const e=En(t=>t.connection==="ready",void 0,"chrome");return uh(e),null}const fh=200,hh=15e3,mh=e=>{const{id:t,url:n}=e.payload,r=qd(e.payload);if(!r.showNotice)return;const o=`open-request:${t}`,i=Yd(Vd(n),r.target,{isMobile:ce.getState().isMobile});if(!i.canOpen){oe.info(i.title,{id:o,description:i.description,duration:hh});return}oe.info(i.title,{id:o,description:i.description,duration:1/0,action:{label:"Open",onClick:()=>{Qd(r.target,n,Jd()||e.directory)}},cancel:{label:"Dismiss",onClick:()=>{oe.dismiss(o)}}})},_x=()=>(a.useEffect(()=>{const e=new Set;return Hd(t=>{if(!e.has(t.payload.id)){if(e.add(t.payload.id),e.size>fh){const n=e.values().next().value;n!==void 0&&e.delete(n)}mh(t)}})},[]),null),Fi=12,ph=[{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"}],gh=({isActive:e,burstKey:t=0,className:n,durationMs:r=900,bursts:o=ph,onComplete:i})=>{const l=Re.useRef(!1);Re.useEffect(()=>{!e&&l.current&&i?.(),e&&(l.current=!0)},[e,i]);const c=Re.useMemo(()=>Array.from({length:Fi},(d,u)=>{const f=Math.PI*2*u/Fi;return{x:Math.cos(f),y:Math.sin(f),delay:u*18}}),[]);return e?s.jsx("div",{className:_("fireworks-overlay pointer-events-none",n),"aria-hidden":"true","data-burst-key":t,children:o.map(d=>{const u={"--burst-delay":`${d.delay}ms`,"--burst-x":`${d.x}%`,"--burst-y":`${d.y}%`,"--firework-color":`var(${d.colorVar})`,"--firework-duration":`${r}ms`};return s.jsx("div",{className:"firework-burst",style:u,children:c.map((f,p)=>{const x=f.x*d.radius,y=f.y*d.radius,m={"--translate-x":`${x}px`,"--translate-y":`${y}px`,"--particle-delay":`${f.delay}ms`,color:`var(${d.colorVar})`};return s.jsx("span",{className:"firework-particle",style:m},`${d.id}-${p}-${t}`)})},`${d.id}-${t}`)})}):null},bh=({durationMs:e=3400}={})=>{const[t,n]=Re.useState({isActive:!1,cycle:0}),r=Re.useRef(null),o=Re.useCallback(()=>{r.current&&(window.clearTimeout(r.current),r.current=null)},[]),i=Re.useCallback(()=>{o(),n(c=>c.isActive?{...c,isActive:!1}:c)},[o]),l=Re.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 Re.useEffect(()=>()=>o(),[o]),{isActive:t.isActive,burstKey:t.cycle,triggerFireworks:l,dismissFireworks:i}},vl=a.createContext(void 0),Ux=({children:e})=>{const{isActive:t,burstKey:n,triggerFireworks:r,dismissFireworks:o}=bh(),i=a.useMemo(()=>({triggerFireworks:r,dismissFireworks:o}),[r,o]);return s.jsxs(vl.Provider,{value:i,children:[e,s.jsx(gh,{isActive:t,burstKey:n})]})},xh={triggerFireworks:()=>{},dismissFireworks:()=>{}},zx=()=>a.useContext(vl)??xh,hr=2e3,Sl=600*1e3;async function yh(){try{const e=await nt("/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 wh(e,t=Math.ceil(Sl/hr),n=hr,r=Je()){for(let o=0;o<t;o++){if(Je()!==r)return{applied:!1,stale:!0};try{const i=await nt("/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 vh(e,t,n=Math.ceil(Sl/hr),r=hr,o=Je()){for(let i=0;i<n;i++){if(Je()!==o)return{applied:!1,stale:!0};try{const l=await nt(`/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 Li="https://github.com/RyderAsKing/PiChamber/releases";function Sh(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 jh(e){return e.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function Oi(e){return e.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function kh(e,t){const n=u=>{const f=u.indexOf("-");return f<0?[u,""]:[u.slice(0,f),u.slice(f+1)]},[r,o]=n(e),[i,l]=n(t),c=r.split(".").map(u=>Number.parseInt(u,10)),d=i.split(".").map(u=>Number.parseInt(u,10));for(let u=0;u<3;u+=1){const f=Number.isFinite(c[u])?c[u]:0,p=Number.isFinite(d[u])?d[u]:0;if(f!==p)return p-f}return!o||!l?(o?1:0)-(l?1:0):l.localeCompare(o,void 0,{numeric:!0})}function Ch(e){const t=/^## \[(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)\] - (\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 jl=({open:e,onOpenChange:t,info:n,downloading:r,downloaded:o,progress:i,error:l,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[f,p]=Re.useState(null),[x,y]=Re.useState("idle"),[m,h]=Re.useState(null),[b,g]=Re.useState(null),[S,w]=Re.useState({}),E=n?.version?n.releaseUrl||`${Li}/tag/v${n.version}`:Li,A=n?.downloadUrl||E,k=i?.total?Math.round(i.downloaded/i.total*100):0,j=u==="web",v=u==="mobile",N=n?.updateCommand||"pichamber update",M=S.version||n?.version,L=S.channel||n?.channel;Re.useEffect(()=>{e||(y("idle"),h(null),g(null),w({}))},[e]);const K=async(I=N)=>{(await xs(I)).ok&&(p(I),setTimeout(()=>p(null),2e3))},z=Re.useCallback(async I=>{await Oa(I)},[]),$=Re.useCallback(async()=>{const I=Je();y("updating"),h(null),g(null),w({});const T=await yh();if(Je()!==I)return;if(!T.success){y("error"),h(T.error||"Update failed"),g(T.commands??null);return}if(w({version:T.targetVersion,channel:T.channel}),T.jobId){const Z=await vh(T.jobId,F=>{Je()===I&&y(F)},void 0,void 0,I);if(Z.stale||Je()!==I)return;if(Z.applied){window.location.reload();return}y("error"),h(Z.error||"Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update");return}y(T.autoRestart?"restarting":"reconnecting");const W=await wh(n?.currentVersion,void 0,void 0,I);if(!(W.stale||Je()!==I)){if(W.applied){window.location.reload();return}y("error"),h(W.error||"Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update")}},[n?.currentVersion]),O=Re.useCallback(()=>{z(A)},[z,A]),R=x!=="idle"&&x!=="error",D=Re.useMemo(()=>{if(!n?.body)return null;const I=n.body.trim();if(!I)return null;const T=Ch(I);return T.length===0?{kind:"raw",title:"What's new",content:Oi(I)}:{kind:"sections",title:"What's new",sections:[...T].sort((Z,F)=>kh(Z.version,F.version)).map(Z=>({version:Z.version,dateLabel:Sh(Z.date),content:Oi(jh(Z.raw)||I)}))}},[n?.body]);return s.jsx(ts,{open:e,onOpenChange:R?void 0:t,children:s.jsxs(ss,{className:"max-w-4xl p-4 sm:p-5 bg-background border-[var(--interactive-border)]",showCloseButton:!0,children:[s.jsxs("div",{className:"mb-1 space-y-1 pr-8",children:[s.jsxs(ds,{className:"flex items-center gap-2.5",children:[s.jsx(P,{name:"download-cloud",className:"h-5 w-5 shrink-0 text-[var(--primary-base)]"}),s.jsx("span",{className:"text-lg font-semibold text-foreground",children:x==="restarting"||x==="reconnecting"?"Updating PiChamber...":"Update available"})]}),(n?.currentVersion||M||j&&L)&&s.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 pl-[1.875rem]",children:[(n?.currentVersion||M)&&s.jsxs("div",{className:"flex items-center gap-2 whitespace-nowrap font-mono text-sm",children:[n?.currentVersion&&s.jsx("span",{className:"text-muted-foreground",children:n.currentVersion}),n?.currentVersion&&M&&s.jsx("span",{className:"text-muted-foreground/50","aria-hidden":"true",children:"→"}),M&&s.jsx("span",{className:"text-[var(--primary-base)] font-medium",children:M})]}),j&&L&&s.jsx("span",{className:"whitespace-nowrap typography-meta text-muted-foreground",children:L==="rc"?"RC channel":"Stable channel"})]})]}),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(P,{name:"loader",className:"h-5 w-5 animate-spin text-[var(--primary-base)]"}),s.jsxs("div",{className:"typography-ui-label text-foreground",children:[x==="updating"&&"Installing update...",x==="restarting"&&"Server restarting...",x==="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."})]}),D&&!R&&s.jsx("div",{className:"rounded-lg border border-[var(--surface-subtle)] bg-[var(--surface-elevated)]/20 overflow-hidden",children:s.jsx(Is,{className:"max-h-[min(400px,50dvh)] p-0",fillContainer:!1,children:D.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 W=I.target.closest("a");W&&W.href&&(I.preventDefault(),I.stopPropagation(),z(W.href))},children:s.jsx(ki,{content:D.content,disableLinkSafety:!0,enableFileReferences:!1})}):s.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:D.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:T=>{const Z=T.target.closest("a");Z&&Z.href&&(T.preventDefault(),T.stopPropagation(),z(Z.href))},children:s.jsx(ki,{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&&x==="error"&&(b??[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(P,{name:"terminal",className:"h-4 w-4"}),s.jsx("span",{children:b?"Run these commands:":"Or update via terminal:"})]}),(b??[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(Ne,{variant:"ghost",size:"icon",onClick:()=>{K(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(P,{name:"check",className:"h-4 w-4"}):s.jsx(P,{name:"clipboard",className:"h-4 w-4"})})]},I))]}),!j&&!v&&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:[k,"%"]})]}),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:`${k}%`}})})]})]}),s.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-between gap-x-4 gap-y-2",children:[s.jsxs("a",{href:E,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(P,{name:"external-link",className:"h-4 w-4"}),"GitHub"]}),s.jsxs("div",{className:"flex-1 flex justify-end",children:[!j&&!v&&!o&&!r&&s.jsxs(Ne,{onClick:c,children:[s.jsx(P,{name:"download",className:"h-4 w-4"}),"Download update"]}),!j&&!v&&r&&s.jsxs(Ne,{disabled:!0,children:[s.jsx(P,{name:"loader",className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!j&&!v&&o&&s.jsxs("button",{onClick:d,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(P,{name:"restart",className:"h-4 w-4"}),"Restart to Update"]}),v&&s.jsxs(Ne,{onClick:O,size:"default",children:[s.jsx(P,{name:"external-link",className:"h-4 w-4"}),"Open update"]}),j&&!R&&s.jsxs(Ne,{onClick:$,children:[s.jsx(P,{name:"download",className:"h-4 w-4"}),"Update now"]}),j&&R&&s.jsxs(Ne,{disabled:!0,children:[s.jsx(P,{name:"loader",className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},kl=a.memo(function({checked:t,onChange:n,disabled:r=!1,ariaLabel:o,decorative:i=!1,className:l,iconClassName:c}){const d=a.useCallback(x=>{x.preventDefault(),x.stopPropagation(),!r&&!t&&n()},[t,r,n]),u=a.useCallback(x=>{(x.key===" "||x.key==="Enter")&&(x.preventDefault(),!r&&!t&&n())},[t,r,n]),f=s.jsx("span",{"aria-hidden":!0,className:_("block h-[5px] w-[5px] rounded-full bg-white",!t&&"opacity-0",c)}),p=_("relative flex h-[14px] w-[14px] min-h-[14px] min-w-[14px] shrink-0 self-center items-center justify-center rounded-full","transition-[background-color,box-shadow] duration-200 ease-out",t?"bg-[color-mix(in_srgb,var(--primary-base)_80%,transparent)] shadow-none":"bg-[var(--surface-muted)] shadow-[inset_0_0_0_1px_var(--interactive-border)]");return i?s.jsx("span",{"aria-hidden":!0,className:_(p,r&&"opacity-50",l),children:f}):s.jsx("button",{type:"button",role:"radio",onClick:d,onKeyDown:u,disabled:r,"aria-checked":t,"aria-label":o,className:_("group/radio outline-none",p,t?"hover:bg-[var(--primary-base)]":"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",l),children:f})}),zn=({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 d=i.current;d&&c.target instanceof Node&&d.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:_("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(P,{name:"information",className:"h-3.5 w-3.5"})})}),s.jsx(We,{sideOffset:8,className:_("max-w-sm",n),children:e})]})},$x="w-full min-w-40 max-w-48",Kx="settings",Ah="w-full min-w-40 max-w-48",Wx="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",Nh="w-full max-w-[24rem]",Gx="min-w-0 flex-1",Hx="flex w-full min-w-0 items-center gap-2",qx="typography-meta shrink-0 text-muted-foreground tabular-nums",Cl="space-y-3.5",Ih="space-y-1.5",Yx="typography-settings-page-title text-muted-foreground",Eh="typography-settings-section-title text-foreground",Al="typography-settings-group-title text-foreground",Vo="typography-settings-field-label text-foreground",Rh="typography-settings-description text-muted-foreground",$n="typography-meta text-muted-foreground",Vx="typography-meta font-medium text-foreground",Qx="typography-settings-section-title text-foreground",Dh=({title:e,description:t,titleAccessory:n,info:r,headerAction:o,children:i,divider:l=!0,className:c,contentClassName:d,settingsItem:u})=>{const f=e!=null||t!=null||o!=null||r!=null;return s.jsxs("section",{"data-settings-item":u,className:_("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:Eh,children:e}):e,n,r!=null?s.jsx(zn,{children:r}):null]}):null,t!=null?s.jsx("div",{className:Rh,children:t}):null]}),o?s.jsx("div",{className:"shrink-0",children:o}):null]}):null,s.jsx("div",{className:_(d),children:i})]})},Jx=({children:e,className:t})=>s.jsx("div",{className:_("grid grid-cols-1 gap-6 @3xl:grid-cols-2 @3xl:gap-10",t),children:e}),Ph=({children:e,className:t,as:n="h3"})=>s.jsx(n,{className:_(Al,t),children:e}),Xx=({title:e,description:t,info:n,children:r,className:o,contentClassName:i,settingsItem:l})=>s.jsxs("div",{"data-settings-item":l,className:_("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(Ph,{children:e}),n!=null?s.jsx(zn,{children:n}):null]}):null,t!=null?s.jsx("p",{className:$n,children:t}):null]}):null,s.jsx("div",{className:_(i),children:r})]}),Pn=({label:e,description:t,info:n,descriptionPlacement:r="before",children:o,settingsItem:i,className:l,controlClassName:c})=>{const d=t!=null?s.jsx("p",{className:$n,children:t}):null;return s.jsxs("div",{"data-settings-item":i,className:_("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:Vo,children:e}),n!=null?s.jsx(zn,{children:n}):null]}),r==="before"?d:null]}),s.jsx("div",{className:_("flex min-w-0 max-w-[24rem] items-center gap-2",c),children:o}),r==="after"?d:null]})},Zx=({label:e,description:t,info:n,children:r,settingsItem:o,className:i,labelClassName:l,controlClassName:c,alignEnd:d=!0})=>s.jsxs("div",{"data-settings-item":o,className:_("flex flex-col gap-2 py-0.5 @xl:flex-row @xl:items-center @xl:gap-8",i),children:[s.jsxs("div",{className:_("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:Vo,children:e}),n!=null?s.jsx(zn,{children:n}):null]}),t!=null?s.jsx("p",{className:_($n,"mt-0.5"),children:t}):null]}),s.jsx("div",{className:_("flex min-w-0 flex-1 items-center gap-2 @xl:w-fit @xl:flex-none",d&&"@xl:justify-end",c),children:r})]}),ey=({children:e,className:t,settingsItem:n})=>s.jsx("div",{"data-settings-item":n,className:_("pt-4",t),children:e}),ty=({label:e,children:t,divider:n=!0,className:r,contentClassName:o})=>s.jsxs("details",{className:_("group/disclosure",n?"border-t border-border/60 py-6":"pb-6",r),children:[s.jsxs("summary",{className:"flex w-fit cursor-pointer list-none items-center gap-1.5 rounded-md typography-ui-label text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] [&::-webkit-details-marker]:hidden",children:[s.jsx(P,{name:"arrow-right-s",className:"size-4 transition-transform group-open/disclosure:rotate-90"}),e]}),s.jsx("div",{className:_("pt-4",o),children:t})]}),Mh=({checked:e,onChange:t,label:n,description:r,disabled:o=!1,ariaLabel:i,settingsItem:l,className:c,labelAccessory:d,info:u})=>{const f=()=>{o||t(!e)},p=r!=null;return s.jsxs("div",{"data-settings-item":l,className:_("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:x=>{(x.key===" "||x.key==="Enter")&&(x.preventDefault(),f())},children:[s.jsx(io,{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:Vo,children:n}),d,u!=null?s.jsx(zn,{children:u}):null]}),p?s.jsx("span",{className:$n,children:r}):null]})]})},sy=({selected:e,onSelect:t,label:n,description:r,ariaLabel:o,disabled:i=!1,className:l})=>s.jsxs("div",{className:_("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(kl,{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:_("typography-settings-field-label font-normal",e?"text-foreground":"text-foreground/50"),children:n}),r!=null?s.jsx("span",{className:$n,children:r}):null]})]}),ny=({selected:e,onSelect:t,label:n,preview:r,ariaLabel:o,disabled:i=!1,className:l})=>s.jsxs("div",{className:_("group/preview flex min-w-0 cursor-pointer flex-col gap-2",i&&"cursor-not-allowed opacity-60",l),role:"radio",tabIndex:i?-1:0,"aria-checked":e,"aria-label":o,"aria-disabled":i||void 0,onClick:()=>{i||t()},onKeyDown:c=>{(c.key===" "||c.key==="Enter")&&(c.preventDefault(),i||t())},children:[s.jsx("div",{"aria-hidden":!0,className:_("aspect-[4/3] overflow-hidden rounded-lg border transition-colors",e?"border-[var(--primary-base)] ring-1 ring-[var(--primary-base)]":"border-border group-hover/preview:border-foreground/30"),children:r}),s.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[s.jsx(kl,{checked:e,onChange:t,disabled:i,decorative:!0}),s.jsx("span",{className:_("min-w-0 truncate typography-settings-field-label font-normal",e?"text-foreground":"text-foreground/50"),children:n})]})]}),ry=({"aria-label":e,children:t,className:n})=>s.jsx("div",{role:"radiogroup","aria-label":e,className:_(Ih,n),children:t});function oy({value:e,options:t,onChange:n,className:r,"aria-label":o}){return s.jsx("div",{role:"group","aria-label":o,className:_("flex flex-wrap items-center gap-1",r),children:t.map(i=>s.jsx(Ne,{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 So="pichamber:server-update-channel-changed",iy=()=>{typeof window<"u"&&window.dispatchEvent(new Event(So))},Th=e=>typeof window>"u"?()=>{}:(window.addEventListener(So,e),()=>window.removeEventListener(So,e));class Fh 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(Xd,{className:"w-full max-w-md",children:[s.jsx(Zd,{className:"text-center",children:s.jsxs(eu,{className:"flex items-center justify-center gap-2 text-destructive",children:[s.jsx(P,{name:"chat-3",className:"h-5 w-5"}),this.props.texts.title]})}),s.jsxs(tu,{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(Ne,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[s.jsx(P,{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 Lh(e){return s.jsx(Fh,{...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 ay=({active:e=!0})=>{const t=Te(n=>n.currentSessionId);return s.jsx(Lh,{sessionId:t||void 0,children:s.jsx(su,{active:e},t??"no-session")})};function Oh({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 Nl=Re.forwardRef(({className:e,outerClassName:t,scrollbarClassName:n,fillContainer:r=!1,useScrollShadow:o=!1,scrollShadowSize:i,hasError:l,resizedHeight:c,onResizeHeightChange:d,disabled:u,simple:f,endSlot:p,...x},y)=>{const m=Re.useRef(null),h=Re.useRef(null),[b,g]=Re.useState(null),S=c??b,w=Re.useCallback(A=>{const k=m.current;if(!k)return;h.current={startY:A.clientY,startHeight:k.getBoundingClientRect().height};const j=A.currentTarget;j.setPointerCapture(A.pointerId);const v=M=>{const L=h.current;if(!L)return;const K=L.startHeight+(M.clientY-L.startY),z=Math.max(82,K);d?d(z):g(z)},N=()=>{h.current=null,j.removeEventListener("pointermove",v),j.removeEventListener("pointerup",N),j.removeEventListener("pointercancel",N)};j.addEventListener("pointermove",v),j.addEventListener("pointerup",N),j.addEventListener("pointercancel",N),A.preventDefault()},[d]),E=Re.useCallback(A=>{if(A.target.closest('textarea, button, [role="separator"]'))return;const j=m.current?.querySelector("textarea");j&&document.activeElement!==j&&(A.preventDefault(),j.focus())},[]);return f?s.jsx(Is,{as:"textarea",ref:y,disableHorizontal:!0,fillContainer:r,useScrollShadow:o,scrollShadowSize:i,outerClassName:t,scrollbarClassName:n,className:_("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:u,...x}):s.jsx("div",{ref:m,onPointerDown:E,style:S!==null?{height:`${S}px`}:void 0,className:_("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:y,className:_("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",!u&&["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"],u&&"text-muted-foreground/60 placeholder:text-muted-foreground/60",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...x}),s.jsxs("div",{className:"flex items-center justify-end gap-1.5 pl-3 pr-2.5",children:[p,s.jsx(Oh,{onResizeStart:w,ariaLabel:"Resize textarea"})]})]})})});Nl.displayName="Textarea";const Il=[{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"}],Mn=Object.fromEntries(Il.map(e=>[e.key,e.Icon])),jo="pichamber:project-actions-updated",El=e=>{const t=(e||"").trim().replace(/\\/g,"/");return t?t==="/"?"/":t.length>1?t.replace(/\/+$/,""):t:""},as=(e,t)=>`${El(e)}::${t}`,Rl=({title:e,description:t,info:n,settingsItem:r,titleAccessory:o,headerAction:i,children:l,className:c,contentClassName:d,divider:u=!0})=>s.jsx(Dh,{title:e,description:t,info:n,settingsItem:r,titleAccessory:o,headerAction:i,divider:u,className:c,contentClassName:d,children:l}),ko=e=>e.name.trim().length>0&&e.command.trim().length>0,Bh=e=>e.name.trim().length===0&&e.command.trim().length===0,_h=e=>!ko(e)&&!Bh(e),Uh=(e,t)=>e.some(r=>t.has(r.id)&&!ko(r))?{canPersist:!1,actions:e}:{canPersist:!0,actions:e.filter(ko)},zh=450,$h=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,Kh=()=>({id:$h(),name:"",command:"",icon:"play"}),Wh=({projectRef:e})=>{const[t,n]=a.useState([]),[r,o]=a.useState(!1),[i,l]=a.useState(null),[c,d]=a.useState(new Set),u=a.useRef(!1);a.useEffect(()=>{let g=!1;return o(!0),(async()=>{try{const S=await ao(e);if(g)return;n(S.actions),l(JSON.stringify({actions:S.actions})),d(new Set(S.actions.map(w=>w.id)))}catch{if(g)return;n([]),l(JSON.stringify({actions:[]})),d(new Set)}finally{g||o(!1)}})(),()=>{g=!0}},[e]);const f=a.useMemo(()=>Uh(t,c),[t,c]),p=a.useMemo(()=>JSON.stringify({actions:f.actions}),[f.actions]),x=i!==null&&f.canPersist&&p!==i,y=a.useCallback(async g=>await nu(e,{actions:g,primaryActionId:null})?(l(JSON.stringify({actions:g})),d(new Set(g.map(w=>w.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent(jo,{detail:{projectId:e.id}})),!0):(oe.error("Failed to save actions"),!1),[e]);a.useEffect(()=>{if(!x||r||u.current)return;const g=window.setTimeout(()=>{u.current||(u.current=!0,(async()=>{try{await y(f.actions)}finally{u.current=!1}})())},zh);return()=>{window.clearTimeout(g)}},[x,r,y,f.actions]);const m=a.useCallback(()=>{const g=Kh();n(S=>[...S,g])},[]),h=a.useCallback(g=>{n(S=>S.filter(w=>w.id!==g))},[]),b=a.useCallback((g,S)=>{n(w=>w.map(E=>E.id===g?S(E):E))},[]);return s.jsx(Rl,{title:"Actions",info:"Per-project commands shown in the header next to the project name.",settingsItem:"projects.actions",headerAction:s.jsxs(Ne,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:m,children:[s.jsx(P,{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:_("space-y-6",Nh),children:t.map((g,S)=>{const w=g.icon||"play",E=Mn[w]||"play",A=g.name.trim()||`Action ${S+1}`,k=_h(g);return s.jsxs("div",{className:Cl,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("h3",{className:Al,children:A}),s.jsx(Ne,{type:"button",variant:"ghost",size:"xs",className:"h-8 w-8 px-0 text-muted-foreground hover:text-[var(--status-error)]",onClick:()=>h(g.id),"aria-label":`Delete ${A}`,children:s.jsx(P,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),s.jsxs(Pn,{label:"Name",controlClassName:"w-full max-w-none",children:[s.jsxs(Gt,{children:[s.jsx(Ht,{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(P,{name:E,className:"h-4 w-4"})})}),s.jsx(qt,{align:"start",className:"w-56 p-2",children:s.jsx("div",{className:"grid grid-cols-6 gap-1",children:Il.map(j=>{const v=j.Icon,N=(g.icon||"play")===j.key;return s.jsx("button",{type:"button",onClick:()=>b(g.id,M=>({...M,icon:j.key})),className:_("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(P,{name:v,className:"h-4 w-4"})},j.key)})})})]}),s.jsx(Ln,{value:g.name,onChange:j=>b(g.id,v=>({...v,name:j.target.value})),placeholder:"Action name",className:"h-8 min-w-0 flex-1 rounded-md px-3"})]}),s.jsx(Pn,{label:"Command",controlClassName:"w-full max-w-none",children:s.jsx(Nl,{value:g.command,onChange:j=>b(g.id,v=>({...v,command:j.target.value})),placeholder:"e.g. bun run lint",className:"min-h-[88px] w-full font-mono text-xs"})}),k?s.jsx("p",{className:"typography-meta text-muted-foreground",children:"Enter a name and command to save this action."}):null,s.jsx(Mh,{checked:g.autoOpenUrl===!0,onChange:j=>b(g.id,v=>({...v,...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 ${A}`}),g.autoOpenUrl===!0?s.jsx(s.Fragment,{children:s.jsx(Pn,{label:"Custom URL",info:"Leave empty to use the best URL from command output.",controlClassName:"w-full max-w-none",children:s.jsx(Ln,{value:g.openUrl||"",onChange:j=>b(g.id,v=>({...v,openUrl:j.target.value})),placeholder:"https://localhost:3000",className:"h-8 w-full rounded-md px-3"})})}):null]},g.id)})})})},Gh={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)"},Hh=({value:e,noneLabel:t,ariaLabel:n,disabled:r=!1,className:o,isModelAllowed:i,onChange:l})=>{const c=Kt(v=>v.providers),d=Kt(v=>v.modelsMetadata),u=ce(v=>v.hiddenModels),f=ce(v=>v.isFavoriteModel),p=ce(v=>v.toggleFavoriteModel),x=ce(v=>v.reorderFavoriteModel),{favoriteModelsList:y,recentModelsList:m}=ru(),[h,b]=a.useState(!1),[g,S]=a.useState("");a.useEffect(()=>{h?Kt.getState().ensureModelMetadata():S("")},[h]);const w=e?c.find(v=>v.id===e.providerId):void 0,E=e&&w?(Array.isArray(w.models)?w.models:[]).find(v=>v.id===e.modelId):void 0,A=e?ou(E,e.modelId):t,k=a.useMemo(()=>e?u.filter(v=>!(v.providerID===e.providerId&&v.modelID===e.modelId)):u,[u,e]),j=a.useCallback(v=>{l({providerId:v.providerID,modelId:v.modelID}),b(!1)},[l]);return s.jsxs(Gt,{modal:!1,open:h,onOpenChange:v=>{r||b(v)},children:[s.jsx(Ht,{asChild:!0,disabled:r,children:s.jsxs("button",{type:"button","aria-label":n,disabled:r,className:_(au({size:"default"}),Ah,"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:_("truncate",e?"text-foreground":"text-muted-foreground"),children:A})]}),s.jsx(P,{name:"arrow-down-s",className:"size-4 shrink-0"})]})}),s.jsx(qt,{align:"start",portalToBody:!0,positionerClassName:"z-[80]",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",children:s.jsx(lu,{providers:c,favoriteModels:y,recentModels:m,modelsMetadata:d,searchQuery:g,onSearchQueryChange:S,onSelect:j,labels:{...Gh,notSelected:t},selectedModel:e?{providerID:e.providerId,modelID:e.modelId}:null,hiddenModels:k,isModelAllowed:i,includeNotSelected:!0,onSelectNone:()=>{l(null),b(!1)},disabled:r,autoFocus:!0,onEscape:()=>b(!1),isFavorite:v=>f(v.providerID,v.modelID),onToggleFavorite:v=>p(v.providerID,v.modelID),onReorderFavorite:(v,N)=>x(v.providerID,v.modelID,N.providerID,N.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite"})})]})},Ur="w-full max-w-none",qh=({form:e})=>{const{name:t,setName:n,parsedDefaultModel:r,handleDefaultModelChange:o,project:i}=e,l=Kt(c=>c.loadProviders);return a.useEffect(()=>{l({source:"projectSettings"})},[l]),i?s.jsx(Rl,{title:"Project",divider:!1,children:s.jsxs("div",{className:Cl,children:[s.jsx(Pn,{label:"Name",settingsItem:"projects.name",controlClassName:Ur,children:s.jsx(Ln,{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(Pn,{label:"Default model",info:"Used when starting a new chat in this project. Unset keeps the global session default.",settingsItem:"projects.default-model",controlClassName:Ur,children:s.jsx(Hh,{value:r,noneLabel:"Use global default",ariaLabel:"Default model for new chats",className:Ur,onChange:c=>{if(!c){o("","");return}o(c.providerId,c.modelId)}})})]})}):null},Yh=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(()=>cu(r),[r]),l=!!e&&(t.trim()!==(e?.label??"").trim()||(r??void 0)!==(e?.defaultModel??void 0)),c=a.useCallback((u,f)=>{o(u&&f?`${u}/${f}`:void 0)},[]),d=a.useCallback(async()=>{if(!e)return null;const u=t.trim();return u?{label:u,defaultModel:r??null}:null},[r,t,e]);return{name:t,setName:n,defaultModel:r,parsedDefaultModel:i,handleDefaultModelChange:c,hasChanges:l,prepareSaveData:d,project:e}},Vh=450,Qh=(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 d=await i();if(d)try{await t(d)}catch{oe.error("Failed to save project settings")}}finally{l.current=!1}})())},Vh);return()=>{window.clearTimeout(c)}},[o,n,r,t,i])},Jh=({project:e,onIdentitySave:t})=>{const n=Yh(e),r=a.useMemo(()=>e?{id:e.id,path:e.path}:null,[e]),o=a.useCallback(async i=>{await t(i)},[t]);return Qh(n,o),!e||!r?null:s.jsxs("div",{className:"space-y-0",children:[s.jsx(qh,{form:n}),s.jsx(Wh,{projectRef:r})]})},Xh=6e4,Zh=3e4,vn=new Map;let Bi=0,_i=!1;const em=()=>{if(_i||typeof window>"u")return;_i=!0;const e=()=>{const t=Date.now();t-Bi<Zh||typeof document<"u"&&document.hidden||(Bi=t,mt(async()=>{const{getRegisteredRuntimeAPIs:n}=await import("./index-C2ISrmRR.js").then(r=>r.cI);return{getRegisteredRuntimeAPIs:n}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:n})=>{const r=n()?.github;r&&kr.getState().refresh(r)}).catch(()=>{}))};window.addEventListener("focus",e),typeof document<"u"&&document.addEventListener("visibilitychange",()=>{document.hidden||e()})},kr=Bs()(jr((e,t)=>({status:null,fetchedAt:null,isLoading:!1,error:null,runtimeKey:Ft(),resetForRuntimeSwitch:n=>{const r=n??Ft();vn.clear(),e({status:null,fetchedAt:null,isLoading:!1,error:null,runtimeKey:r})},refresh:async(n,r)=>{em();const o=Ft();t().runtimeKey!==o&&t().resetForRuntimeSwitch(o);const i=t(),l=Date.now();if(!r?.force&&i.status&&i.fetchedAt&&l-i.fetchedAt<Xh)return i.status;const c=vn.get(o);if(c)return c;const d=n??null;if(!d)return t().status;const u=(async()=>{e({isLoading:!0});try{const f=await d.status();return Ft()!==o?null:(e({status:f,fetchedAt:Date.now(),isLoading:!1,error:null,runtimeKey:o}),f)}catch(f){return Ft()!==o?null:(e({isLoading:!1,error:f instanceof Error?f.message:"GitHub status check failed"}),t().status)}})();vn.set(o,u);try{return await u}finally{vn.get(o)===u&&vn.delete(o)}}}),{name:"github-status-store"}));typeof window<"u"&&Un(e=>{kr.getState().resetForRuntimeSwitch(e.runtimeKey)});const tm=()=>kr(e=>(e.status?.hosts??[]).find(n=>n.authenticated)?.login??null),ly=e=>{if(e.byteLength<4)return null;const t=new DataView(e).getUint32(0);if(t<=0||4+t>e.byteLength)return null;try{const n=JSON.parse(new TextDecoder().decode(new Uint8Array(e,4,t)));return!Number.isFinite(n?.width)||!Number.isFinite(n?.height)?null:{header:n,jpeg:new Uint8Array(e,4+t)}}catch{return null}},cy=e=>{try{const t=JSON.parse(e);return t&&typeof t=="object"&&typeof t.type=="string"?t:null}catch{return null}},dy=e=>e===4003?"unavailable":e===4004?"stop":e===4005?"closed":"reconnect",uy=50*1024*1024-1,fy=[250,1e3,2e3,4e3,8e3],sm=(e,t)=>{const n=r=>{let o=r>>>0;for(const i of`${e}\0${t}`)o^=i.codePointAt(0)??0,o=Math.imul(o,16777619)>>>0;return o.toString(36).padStart(7,"0")};return`tab-${n(2166136261)}${n(16777619)}`},hy=e=>({alt:e.altKey,ctrl:e.ctrlKey,meta:e.metaKey,shift:e.shiftKey}),my=(e,t,n,r)=>{if(n.width<=0||n.height<=0)return null;const o=(e-n.left)/n.width*r.width,i=(t-n.top)/n.height*r.height;return{x:Math.round(Math.max(0,Math.min(r.width-1,o))*100)/100,y:Math.round(Math.max(0,Math.min(r.height-1,i))*100)/100}},py=(e,t)=>e.key.toLowerCase()!=="v"||e.altKey?!1:t?e.metaKey:e.ctrlKey,gy=(e,t)=>{const n=Math.min(1,t.width/e.width,t.height/e.height),r=Number.isFinite(n)&&n>0?n:1;return{width:Math.round(e.width*r),height:Math.round(e.height*r),scale:r}},un=async(e,t)=>{const n=await e.json().catch(()=>null);return new Error(typeof n?.error=="string"?n.error:t)},by=async()=>{const e=await nt("/api/server-browser/status");if(!e.ok)throw await un(e,"Could not check the server browser");return await e.json()},xy=async e=>{const t=await nt("/api/server-browser/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw await un(t,"Could not save the server browser settings");return await t.json()},yy=async(e,t)=>{const n=await nt("/api/server-browser/dev-servers",{query:e?{directory:e}:void 0,signal:t});if(!n.ok)throw await un(n,"Could not find dev servers");const r=await n.json();return Array.isArray(r.servers)?r.servers:[]},wy=async(e,t,n)=>{const r=await nt("/api/server-browser/frame-policy",{query:{url:e,origin:t},signal:n});if(!r.ok)return{framing:"unknown"};const o=await r.json().catch(()=>null);return o?.framing==="refused"||o?.framing==="allowed"?{framing:o.framing,reason:o.reason==="frame-ancestors"?"frame-ancestors":"x-frame-options"}:{framing:"unknown"}},vy=async()=>{const e=await nt("/api/server-browser/clear-data",{method:"POST"});if(!e.ok)throw await un(e,"Could not clear browsing data")},Sy=(e,t)=>{const n=sm(e,t);nt(`/api/server-browser/tabs/${encodeURIComponent(n)}`,{method:"DELETE"}).catch(()=>{})},jy=async e=>{const t=new URLSearchParams({name:e.name,type:e.type,lastModified:String(e.lastModified)}),n=await nt(`/api/server-browser/uploads?${t}`,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:e});if(!n.ok)throw await un(n,`Could not upload ${e.name}`);const r=await n.json();if(typeof r.id!="string")throw new Error(`Could not upload ${e.name}`);return r.id},ky=async(e,t)=>{const n=await nt(`/api/server-browser/downloads/${encodeURIComponent(e)}`);if(!n.ok)throw await un(n,`Could not download ${t}`);const r=await n.blob(),o=URL.createObjectURL(r);try{const i=document.createElement("a");i.href=o,i.download=t,i.rel="noopener",document.body.appendChild(i),i.click(),i.remove()}finally{setTimeout(()=>URL.revokeObjectURL(o),6e4)}},Cy=async(e,t,n)=>{const r=await lf();return{socket:cf(df().websocket("/api/server-browser/ws",{tab:e,url:t,popup:n},r)),urlAuthToken:r}},Ay=e=>{af(e)},Yn=100;function Ny(){const e=ce(v=>v.isArchivePageOpen),t=ce(v=>v.setArchivePageOpen),n=ce(v=>v.setActiveMainTab),r=Te(v=>v.setCurrentSession),o=Te(v=>v.unarchiveSession),i=on(v=>v.homeDirectory),l=lo({archived:!0}),[c,d]=a.useState(""),[u,f]=a.useState(null),[p,x]=a.useState(Yn),y=c.trim().toLowerCase(),m=a.useMemo(()=>e?[...l].sort((v,N)=>(N.time?.archived??0)-(v.time?.archived??0)):[],[l,e]),h=a.useMemo(()=>{const v=new Map;for(const N of m){const M=Ee(Rn(N))??"",L=v.get(M);if(L){L.sessions.push(N);continue}v.set(M,{directory:M,label:M?On(M,i)||M:"other projects",sessions:[N]})}return[...v.values()].sort((N,M)=>M.sessions.length-N.sessions.length)},[i,m]),b=a.useMemo(()=>y?m.filter(v=>(v.title??"").toLowerCase().includes(y)):u===null?m:h.find(v=>v.directory===u)?.sessions??[],[h,y,u,m]),g=b.slice(0,p),S=b.length-g.length,w=l.length,E=a.useCallback(v=>{f(v),x(Yn)},[]),A=a.useCallback(v=>{const N=Ee(Rn(v));r(v.id,N??void 0),n("chat"),t(!1)},[n,r,t]),k=a.useCallback(v=>{o(v.id).then(N=>{N?oe.success("Session restored"):oe.error("Failed to restore session")})},[o]);if(!e)return null;const j=(v,N,M,L,K,z,$)=>s.jsxs("div",{className:"group/dir relative",children:[s.jsxs("button",{type:"button",onClick:K,title:z,className:_("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",$?"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:M})]}),$?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:()=>Ms.requestDelete({sessions:$,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(P,{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]},v);return s.jsx(Dd,{open:e,onOpenChange:t,children:s.jsxs(Pd,{children:[s.jsx(Md,{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(Td,{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(Fd,{className:"sr-only",children:"Archived sessions"}),s.jsx(Ld,{className:"sr-only",children:"Browse and restore archived sessions."}),s.jsx(Od,{"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(P,{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",w,u===null,()=>E(null)),h.map(v=>j(v.directory||"__none__",v.label,v.sessions.length,u===v.directory,()=>E(v.directory),v.directory||void 0,v.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(P,{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:v=>{d(v.target.value),x(Yn)},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:b.length===1?`${b.length} archived session`:`${b.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:[g.length===0?s.jsx("div",{className:"py-10 text-center text-muted-foreground",children:s.jsx("p",{className:"typography-ui-label font-semibold",children:y?"No matching archived sessions":"No archived sessions"})}):g.map(v=>{const N=Ee(Rn(v))??"",M=N?On(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:()=>A(v),role:"button",tabIndex:0,onKeyDown:L=>{(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),A(v))},children:[s.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:gs(v)}),y&&M?s.jsx("span",{className:"max-w-40 flex-shrink-0 truncate text-[0.72rem] text-muted-foreground/70",title:N,children:M}):null,s.jsx("span",{className:"flex-shrink-0 text-[0.72rem] text-muted-foreground/75",children:Df(v.time?.archived??v.time?.updated??v.time?.created??Date.now())}),s.jsx("button",{type:"button",onClick:L=>{L.stopPropagation(),k(v)},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 ${gs(v)}`,children:s.jsx(P,{name:"inbox-unarchive",className:"h-3.5 w-3.5"})}),s.jsx("button",{type:"button",onClick:L=>{L.stopPropagation(),Ms.requestDelete({sessions:[v],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 ${gs(v)}`,children:s.jsx(P,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},v.id)}),S>0?s.jsx("button",{type:"button",onClick:()=>x(v=>v+Yn),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 nm=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}},rm=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},Xt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:0,om=e=>{if(!e||typeof e!="object")return null;const t=Xt(e.input),n=Xt(e.output),r=Xt(e.cacheRead),o=Xt(e.cacheWrite);return{input:t,output:n,reasoning:null,cacheRead:r,cacheWrite:o,total:t+n+r+o}},Ui=e=>{const t=om(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:Xt(r)};if(!r||typeof r!="object")return{input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:0};const o=r,i=Xt(o.input),l=Xt(o.output),c=Xt(o.reasoning),d=Xt(o.cache?.read),u=Xt(o.cache?.write);return{input:i,output:l,reasoning:c,cacheRead:d,cacheWrite:u,total:i+l+c+d+u}},Dl=380,zr=8,im=140;function am({open:e,onClose:t,anchorRef:n,closeOnWheel:r=!1}){const o=a.useRef(null),i=a.useRef(null),[l,c]=a.useState(e),[d,u]=a.useState(!1),[f,p]=a.useState(null),{enabled:x}=Wo();return a.useLayoutEffect(()=>{if(!e||!x||!l)return;const y=()=>{const b=n.current?.getBoundingClientRect(),g=i.current?.getBoundingClientRect();if(!b||!g){p(null);return}const S=b.left-g.left;p(Math.min(Math.max(S,zr),Math.max(zr,g.width-Dl-zr)))};y();const m=i.current;if(typeof ResizeObserver>"u"||!m)return;const h=new ResizeObserver(y);return h.observe(m),()=>h.disconnect()},[n,x,e,l]),a.useEffect(()=>{if(e){c(!0),u(!1);return}if(!l)return;u(!0);const y=window.setTimeout(()=>{c(!1),u(!1)},im);return()=>window.clearTimeout(y)},[e,l]),a.useEffect(()=>{if(!e)return;const y=m=>{m.key==="Escape"&&t()};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[t,e]),a.useEffect(()=>{if(!e)return;const y=m=>{const h=m.target;if(!(h instanceof Node)){t();return}o.current?.contains(h)||n.current?.contains(h)||t()};return document.addEventListener("pointerdown",y,!0),r&&document.addEventListener("wheel",y,!0),()=>{document.removeEventListener("pointerdown",y,!0),r&&document.removeEventListener("wheel",y,!0)}},[n,r,t,e]),{panelRef:o,wrapperRef:i,shouldRender:l,isExiting:d,anchorLeft:f,isPopover:x&&f!==null}}const zi=(e,t)=>{if(!e||typeof e!="object")return;const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0},mr=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e),Vn=({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(P,{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})]}),lm=({open:e,onClose:t,anchorRef:n,contextDisplay:r})=>{const{panelRef:o,wrapperRef:i,shouldRender:l,isExiting:c,anchorLeft:d,isPopover:u}=am({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:_("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",u?"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))",...u?{top:8,left:d??8,width:`min(${Dl}px, calc(100% - 16px))`}:null},children:s.jsx("div",{className:"space-y-1",children:r?s.jsxs(s.Fragment,{children:[s.jsx(Vn,{iconNode:s.jsx(Ba,{percentage:r.percentage}),label:"Context",children:s.jsxs("span",{className:"inline-flex items-baseline gap-1.5 tabular-nums",children:[s.jsxs("span",{className:_("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(Vn,{icon:"stack",label:"Cache read",children:s.jsx("span",{className:"tabular-nums",children:mr(r.cacheRead)})}),s.jsx(Vn,{icon:"edit",label:"Cache write",children:s.jsx("span",{className:"tabular-nums",children:mr(r.cacheWrite)})})]}):null,r.cacheHitPercent!==null?s.jsx(Vn,{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},cm=a.memo(function({open:t,onOpenChange:n,currentSessionId:r,effectiveDirectory:o,isNewSessionDraftOpen:i}){const l=a.useRef(null),c=du(r??""),d=Kt(R=>R.providers),u=Kt(R=>R.currentProviderId),f=Kt(R=>R.currentModelId),p=Kt(R=>R.getCurrentModel()),x=Kt(R=>R.getModelMetadata);Kt(R=>R.modelsMetadata.size);const y=uu(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 D=c[R]?.info;if(D.role!=="user")continue;const I=D.model,T=I?.providerID??I?.providerId,W=I?.modelID??I?.modelId,Z=typeof T=="string"&&T.trim().length>0?T:void 0,F=typeof W=="string"&&W.trim().length>0?W:void 0;if(Z&&F)return{providerID:Z,modelID:F}}return null},[c]),h=a.useMemo(()=>{for(let R=c.length-1;R>=0;R-=1){const D=c[R];if(D?.info.role==="assistant"&&Ui(D).total>0)return D}return null},[c]),b=m??(()=>{const R=h?.info.model,D=R?.providerID??R?.providerId,I=R?.modelID??R?.modelId;return D&&I?{providerID:D,modelID:I}:null})()??(y?{providerID:y.providerId,modelID:y.modelId}:null)??(u&&f?{providerID:u,modelID:f}:null),S=(b?d.find(R=>R.id===b.providerID):void 0)?.models.find(R=>R.id===b?.modelID),w=b?x(b.providerID,b.modelID):void 0,E=zi(S?.limit,"context")??w?.limit?.context??zi(p?.limit,"context")??0,A=h?Ui(h):null,k=h?.info?.usage,j=k?rm(k):A?.total??0,v=!i&&j>0&&E>0?Math.min(j/E*100,999):null,N=v!==null?`${mr(j)}/${mr(E)}`:null,M=v===null?"":v>=90?"text-[var(--status-error)]":v>=75?"text-[var(--status-warning)]":"text-[var(--status-success)]",L=A?.cacheRead??null,K=A?.cacheWrite??null,z=A?nm({input:A.input,cache:{read:A.cacheRead,write:A.cacheWrite}}):{percent:0,hasInput:!1},$=z.hasInput?z.percent:null,O=v!==null&&N?{percentage:v,tokens:N,colorClass:M,cacheRead:L,cacheWrite:K,cacheHitPercent:$}: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(Ba,{percentage:O?.percentage??0,size:20,className:"size-5 -rotate-90"})}),s.jsx(lm,{open:t,onClose:()=>n(!1),anchorRef:l,contextDisplay:O})]})}),fn="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",dm="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",um=a.memo(function({visible:t=!0,title:n,ariaLabel:r,onClick:o,className:i,Icon:l,iconClassName:c,pressed:d=!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":d,className:_(i??fn,d&&"bg-interactive-selection text-interactive-selection-foreground"),children:s.jsx(P,{name:l,className:c??"h-[18px] w-[18px]"})})}),s.jsx(We,{children:s.jsx("p",{children:n})})]}):null}),fm=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)},Pl=({variant:e="desktop"})=>{const t=Ts(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"||_a(f)).length,c=a.useCallback(()=>{o.current&&(clearTimeout(o.current),o.current=null)},[]),d=a.useCallback(()=>{c(),o.current=setTimeout(()=>r(!1),150)},[c]);if(a.useEffect(()=>()=>c(),[c]),i.length===0)return null;const u=f=>{if(!pu(f))return;const p=f.receipt;if(!p)return;const x=Te.getState();x.newSessionDraft.open?x.setNewSessionDraftTarget({directoryOverride:p.path,worktreeIntent:null}):x.openNewSessionDraft({directoryOverride:p.path}),Ts.getState().clearEntry(f.key),ce.getState().setActiveMainTab("chat"),r(!1)};return s.jsxs(Gt,{open:n,onOpenChange:r,children:[s.jsx(Ht,{asChild:!0,children:s.jsxs("button",{type:"button",className:_(e==="desktop"?fn:"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"&&d()},children:[l>0?s.jsx(ys,{variant:"inline",text:null,animationType:"spinner"}):s.jsx(P,{name:"task",className:"size-[18px]"}),s.jsx("span",{children:"Background tasks"})]})}),s.jsxs(qt,{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:d,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(hm,{entry:f,onOpen:()=>u(f)},f.key))})]})]})},hm=({entry:e,onOpen:t})=>{const n=e.state?.phase==="failed",r=!!(e.state&&!n),o=_a(e),i=fu(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(ys,{variant:"inline",text:null,animationType:"spinner"}):n?s.jsx(P,{name:"alert",className:"size-4 text-[var(--status-error)]"}):s.jsx(P,{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(Ne,{type:"button",size:"xs","aria-label":`Restore draft for ${e.intent.sourceDirectory} from ${e.intent.startRef} (task ${fm(e.key)})`,onClick:()=>{const c=hu(e.key),d=mu(c,"background-task");d&&oe.error(d.title,{description:d.description})},children:"Restore draft"}):null,s.jsx(Ne,{type:"button",variant:"ghost",size:"xs",onClick:()=>Ts.getState().dismissFailed(e.key),children:"Dismiss"})]}):null,i?s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[s.jsx(Ne,{type:"button",size:"xs",onClick:t,children:"Open"}),s.jsx(Ne,{type:"button",variant:"ghost",size:"icon",className:"size-6",onClick:()=>Ts.getState().clearEntry(e.key),"aria-label":"Dismiss completed task",children:s.jsx(P,{name:"close",className:"size-3.5"})})]}):null]})},mm=["pinned","today","yesterday","thisWeek","lastWeek","older"],pm={pinned:"Pinned",today:"Today",yesterday:"Yesterday",thisWeek:"This week",lastWeek:"Last week",older:"Older"},gm=(e,t)=>{if(e==="sunday")return 0;if(e==="monday")return 1;try{const n=t||(typeof Intl<"u"&&Intl.DateTimeFormat?Intl.DateTimeFormat().resolvedOptions().locale:"en-US");if(typeof Intl<"u"&&typeof Intl.Locale=="function"){const r=new Intl.Locale(n),i=(typeof r.getWeekInfo=="function"?r.getWeekInfo():r.weekInfo)?.firstDay;if(i===7||i===0)return 0;if(i!==void 0)return 1}}catch{}return 1},Co=(e,t)=>{const n=new Date(e);n.setHours(0,0,0,0);const r=n.getTime(),o=new Date(r);o.setDate(o.getDate()-1),o.setHours(0,0,0,0);const i=o.getTime(),c=(n.getDay()-t+7)%7,d=new Date(r);d.setDate(d.getDate()-c),d.setHours(0,0,0,0);const u=d.getTime(),f=new Date(u);f.setDate(f.getDate()-7),f.setHours(0,0,0,0);const p=f.getTime();return{startOfToday:r,startOfYesterday:i,startOfThisWeek:u,startOfLastWeek:p}},bm=(e,t)=>!Number.isFinite(e)||e<=0?"older":e>=t.startOfToday?"today":e>=t.startOfYesterday?"yesterday":e>=t.startOfThisWeek?"thisWeek":e>=t.startOfLastWeek?"lastWeek":"older",xm=(e,t)=>{const n={pinned:[],today:[],yesterday:[],thisWeek:[],lastWeek:[],older:[]},{getTimestamp:r,isPinned:o,boundaries:i}=t,l=e.length;for(let d=0;d<l;d++){const u=e[d];if(o(u))n.pinned.push(u);else{const f=r(u),p=bm(f,i);n[p].push(u)}}const c=[];for(const d of mm){const u=n[d];u.length>0&&c.push({id:d,items:u})}return c},ym=e=>{const t=new Date(e);return t.setDate(t.getDate()+1),t.setHours(0,0,0,0),t.getTime()},wm=(e,t)=>{const[n,r]=a.useState(0),o=a.useMemo(()=>e?Co(Date.now(),t):null,[e,t,n]),i=o?.startOfToday??null;return a.useEffect(()=>{if(i===null||typeof window>"u"||typeof document>"u")return;const l=Date.now(),c=window.setTimeout(()=>{r(u=>u+1)},Math.max(50,ym(l)-l+50)),d=()=>{document.visibilityState==="visible"&&Co(Date.now(),t).startOfToday!==i&&r(u=>u+1)};return document.addEventListener("visibilitychange",d),()=>{window.clearTimeout(c),document.removeEventListener("visibilitychange",d)}},[i,t,n]),o},vm=e=>{const{normalizedProjects:t,enabled:n=!0,ownership:r,hasAuthoritativeGlobalSessions:o,isWorktreeTopologyLoading:i,unresolvedWorktreeProjectPaths:l,foldersMap:c,createFolder:d,addSessionToFolder:u}=e;a.useEffect(()=>{!n||!o||i||t.forEach(f=>{if(l.has(f.normalizedPath))return;const p=ll(f.normalizedPath),x=r.archivedSessionsByProject.get(f.id)??[],y=c[p]??[],m=new Map(y.map(h=>[h.name.toLowerCase(),h]));x.forEach(h=>{const b=Pf(h,f.normalizedPath),g=b.toLowerCase();let S=m.get(g);S||(S=d(p,b),m.set(g,S)),S.sessionIds.includes(h.id)||u(p,S.id,h.id)})})},[t,n,r,o,i,l,c,d,u])},Sm=e=>({getOrderedGroups:a.useCallback((n,r)=>{const o=e.get(n);if(!o||o.length===0)return r;const i=new Map(r.map(u=>[u.id,u])),l=[];o.forEach(u=>{const f=i.get(u);f&&(l.push(f),i.delete(u))});const c=[],d=[];return r.forEach(u=>{i.has(u.id)&&(u.isArchivedBucket?d.push(u):c.push(u))}),[...c,...l,...d]},[e])}),jm=e=>{const{normalizedProjects:t,getSessionsForProject:n,getArchivedSessionsForProject:r,availableWorktreesByProject:o,projectRepoStatus:i,projectRootBranches:l,lastRepoStatus:c,buildGroupedSessions:d,hasSessionSearchQuery:u,normalizedSessionSearchQuery:f,filterSessionNodesForSearch:p,buildGroupSearchText:x,foldersMap:y}=e,m=a.useRef(new Map),h=a.useMemo(()=>{const j=m.current,v=new Map;let N=0,M=0;const L=(z,$)=>z.length===$.length&&z.every((O,R)=>O===$[R]),K=t.map(z=>{const $=n(z.id),O=r(z.id),R=i.has(z.id)?!!i.get(z.id):c,D=l.get(z.id)??null,I=o.get(z.normalizedPath)??[],T=j.get(z.id);if(T&&T.project===z&&L(T.activeSessions,$)&&L(T.archivedSessions,O)&&T.rootBranch===D&&T.isRepo===R&&T.worktrees===I&&T.buildGroupedSessions===d)return N+=1,v.set(z.id,T),T.section;M+=1;const W=cl([...$,...O]),Z=d(W,z.normalizedPath,I,D,R),F={project:z,groups:Z};return v.set(z.id,{project:z,activeSessions:$,archivedSessions:O,rootBranch:D,isRepo:R,worktrees:I,buildGroupedSessions:d,section:F}),F});return m.current=v,N>0&&Wt("ui.sidebar.project_section.reused",N),M>0&&Wt("ui.sidebar.project_section.rebuilt",M),K},[t,n,r,o,i,c,d,l]),b=a.useMemo(()=>h,[h]),g=a.useMemo(()=>{const j=new WeakMap;if(!u)return j;const v=N=>N.reduce((M,L)=>M+1+v(L.children),0);return b.forEach(N=>{N.groups.forEach(M=>{const L=p(M.sessions,f),K=v(L),z=x(M).includes(f),$=Ee(M.directory??null),R=($?y[$]??[]:[]).filter(D=>D.name.toLowerCase().includes(f)).length;j.set(M,{filteredNodes:L,matchedSessionCount:K,folderNameMatchCount:R,groupMatches:z,hasMatch:z||K>0||R>0})})}),j},[u,b,p,f,x,y]),S=a.useMemo(()=>u?b.map(j=>({...j,groups:j.groups.filter(v=>g.get(v)?.hasMatch===!0)})).filter(j=>j.groups.length>0):b,[u,b,g]),w=u?S:b,E=a.useRef(new WeakMap),A=a.useMemo(()=>{const j=E.current;return w.map(v=>{const N=j.get(v);if(N&&N.query===f)return N.section;const M=v.groups.filter(D=>!D.isArchivedBucket),L=v.groups.filter(D=>D.isArchivedBucket),K=M.flatMap(D=>u?g.get(D)?.filteredNodes??[]:D.sessions),z=M.map(D=>({scopeKey:D.folderScopeKey??Ee(D.directory??null),directory:D.directory??null})).filter(D=>!!D.scopeKey),$=M.find(D=>D.isMain)??null,O={id:"flat",label:$?.label??"",branch:$?.branch??null,description:$?.description??null,isMain:!0,isArchivedBucket:!1,directory:$?.directory??v.project.normalizedPath,folderScopeKey:$?.folderScopeKey??v.project.normalizedPath,folderScopes:z,sessions:K};if(u){const D=M.map(I=>g.get(I)).filter(I=>!!I);g.set(O,{filteredNodes:K,matchedSessionCount:D.reduce((I,T)=>I+T.matchedSessionCount,0),folderNameMatchCount:D.reduce((I,T)=>I+T.folderNameMatchCount,0),groupMatches:D.some(I=>I.groupMatches),hasMatch:D.some(I=>I.hasMatch)})}const R={project:v.project,groups:[O,...L]};return j.set(v,{query:f,section:R}),R})},[g,u,f,w]),k=a.useMemo(()=>u?w.reduce((j,v)=>j+v.groups.reduce((N,M)=>{const L=g.get(M);if(!L)return N;const K=L.folderNameMatchCount+(L.groupMatches?1:0);return N+L.matchedSessionCount+K},0),0):0,[u,w,g]);return{projectSections:h,visibleProjectSections:b,groupSearchDataByGroup:g,searchableProjectSections:S,sectionsForRender:w,flatSectionsForRender:A,searchMatchCount:k}},km=e=>{const{projectSections:t,activeProjectId:n,activeSessionByProject:r,setActiveSessionByProject:o,currentSessionId:i,handleSessionSelect:l,newSessionDraftOpen:c,mobileVariant:d,openNewSessionDraft:u,setActiveMainTab:f,setSessionSwitcherOpen:p}=e,x=a.useMemo(()=>{const m=new Map,h=new Map,b=(g,S,w,E)=>{m.has(g)||m.set(g,new Map);const A=m.get(g);E.forEach(k=>{const j=Ee(k.session.directory??w??S);A.set(k.session.id,{directory:j}),h.has(g)||h.set(g,{id:k.session.id,directory:j}),k.children.length>0&&b(g,S,j,k.children)})};return t.forEach(g=>{g.groups.forEach(S=>{b(g.project.id,g.project.normalizedPath,S.directory,S.sessions)})}),{metaByProject:m,firstSessionByProject:h}},[t]),y=a.useRef(null);a.useLayoutEffect(()=>{if(!n)return;if(c){y.current=n;return}if(y.current===n)return;const m=t.find(k=>k.project.id===n);if(!m)return;y.current=n;const h=x.metaByProject.get(n);if(i&&h&&h.has(i)){o(k=>{if(k.get(n)===i)return k;const j=new Map(k);return j.set(n,i),j});return}const b=i?Array.from(x.metaByProject.entries()).some(([k,j])=>k!==n&&j.has(i)):!1;if(i&&h&&!b)return;if(!h||h.size===0){f("chat"),d&&p(!1),u({selectedProjectId:m.project.id,directoryOverride:m.project.normalizedPath});return}const g=r.get(n),S=g&&h.has(g)?g:null,w=x.firstSessionByProject.get(n)?.id??null,E=S??w;if(!E||E===i)return;const A=h.get(E)?.directory??null;l(E,A,{keepPanelOpen:!0})},[n,r,i,l,c,d,u,t,x,f,p,o]),a.useEffect(()=>{if(!n||!i)return;const m=x.metaByProject.get(n);!m||!m.has(i)||o(h=>{if(h.get(n)===i)return h;const b=new Map(h);return b.set(n,i),b})},[n,i,x,o])},Cm=({initialActiveSessionByProject:e,persistActiveSessionByProject:t,...n})=>{const r=Te(c=>c.currentSessionId),o=Te(c=>!!c.newSessionDraft?.open),[i,l]=a.useState(()=>new Map(e));return km({...n,activeSessionByProject:i,setActiveSessionByProject:l,currentSessionId:r,newSessionDraftOpen:o}),a.useEffect(()=>{t(i)},[i,t]),null},$i=["var(--chart-1)","var(--chart-2)","var(--chart-3)","var(--chart-4)","var(--chart-5)"],Am=e=>{let t=5381;for(let n=0;n<e.length;n+=1)t=t*33^e.charCodeAt(n);return t>>>0},Nm=(e,t,n)=>(n.get(e)??0)>0?e:t.get(e)??null,Ml=e=>{if(!e||typeof e!="string"||e.trim().length===0)return null;const t=Am(e.trim())%$i.length;return $i[t]},Im=(e,t)=>{const n=Ml(e);return n?t?.active?`color-mix(in srgb, ${n} 30%, var(--interactive-selection))`:`color-mix(in srgb, ${n} 18%, transparent)`:null},Ki=e=>!!e.time?.archived,Em=e=>{const t=a.useCallback(i=>[i.label,i.branch??"",i.description??"",i.directory??""].join(" ").toLowerCase(),[]),n=a.useCallback(i=>{const l=Ee(i.directory??null)??"";return`${gs(i)} ${l}`.toLowerCase()},[]),r=a.useCallback((i,l)=>l?i.flatMap(c=>{if(n(c.session).includes(l))return[c];const u=r(c.children,l);return u.length===0?[]:[{...c,children:u}]}):i,[n]),o=a.useCallback((i,l,c=[],d,u)=>{const f=Ee(l??null),p=cl(i).sort(Ua(e.pinnedSessionIds,e.sessionOrderRanks)),x=new Map(p.map(j=>[j.id,j])),y=new Map,m=new Map;p.forEach(j=>{const v=j.parentID??null,N=v?x.get(v):null,M=N&&Ki(N)===Ki(j)?v:null;y.set(j.id,M),M&&m.set(M,(m.get(M)??0)+1)});const h=c.map(j=>({worktree:j,directory:Ee(j.path)})).filter(j=>!!j.directory&&!j.worktree.isPrimary).sort((j,v)=>v.directory.length-j.directory.length),b=(j,v)=>v===j||v.startsWith(`${j}/`),g=j=>{const v=Ee(j.directory??null);return v?h.find(N=>b(N.directory,v))?.worktree??null:null},S=(j,v)=>{const N=Nm(j.id,y,m);return{session:j,children:[],worktree:v,forkColorId:N}},w=[],E=new Map,A=[];for(const j of h)E.set(j.directory,[]);p.forEach(j=>{const v=g(j),N=S(j,v);j.time?.archived?A.push(N):v?E.get(Ee(v.path)??"")?.push(N):w.push(N)});const k=[{id:"root",label:u&&d&&d!=="HEAD"?`project root: ${d}`:"project root",branch:d??null,description:f?uo(f,e.homeDirectory):null,isMain:!0,isArchivedBucket:!1,worktree:null,directory:f,folderScopeKey:f,sessions:w}];for(const{worktree:j,directory:v}of h)k.push({id:`worktree:${v}`,label:j.branch||(j.detached?"Detached HEAD":j.name),branch:j.branch,description:uo(v,e.homeDirectory),isMain:!1,isArchivedBucket:!1,worktree:j,directory:v,folderScopeKey:v,sessions:E.get(v)??[]});return A.length>0&&k.push({id:"archived",label:"archived",branch:null,description:"Archived and unassigned sessions",isMain:!1,isArchivedBucket:!0,worktree:null,directory:null,folderScopeKey:f?ll(f):null,sessions:A}),k},[e.homeDirectory,e.pinnedSessionIds,e.sessionOrderRanks]);return{buildGroupSearchText:t,buildSessionSearchText:n,filterSessionNodesForSearch:r,buildGroupedSessions:o}},Rm=({mobileVariant:e,isTablet:t})=>!e&&!t,Dm=({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])},Pm=e=>{const[t,n]=a.useState(null),r=a.useRef(null);a.useEffect(()=>()=>{r.current&&clearTimeout(r.current)},[]);const o=a.useCallback((w,E,A)=>{fo("navigation.session_select"),ce.getState().closeMainSurfaces();const k=()=>{!e.isSessionSearchOpen&&e.sessionSearchQuery.length===0||(e.setSessionSearchQuery(""),e.setIsSessionSearchOpen(!1))},j=A?.keepPanelOpen!==!0;if(e.mobileVariant&&(e.setActiveMainTab("chat"),e.setSessionSwitcherOpen(!1)),w===Te.getState().currentSessionId){e.allowReselect&&j&&e.onSessionSelected?.(w),k();return}fo("navigation.session_state_set"),e.setCurrentSession(w,E??null),j&&e.onSessionSelected?.(w),k()},[e]),i=a.useCallback((w,E)=>{e.setEditingId(w),e.setEditTitle(E)},[e]),l=a.useCallback(async w=>{if(!e.editingId)return;const E=(w??e.editTitle).trim();E&&await e.updateSessionTitle(e.editingId,E),e.setEditingId(null),e.setEditTitle("")},[e]),c=a.useCallback(()=>{e.setEditingId(null),e.setEditTitle("")},[e]),d=a.useCallback(async(w,E)=>{try{return(await xs(w)).ok?(n(E),r.current&&clearTimeout(r.current),r.current=window.setTimeout(()=>{n(null),r.current=null},2e3),!0):!1}catch{return!1}},[]),u=a.useCallback(async w=>{const E=await e.shareSession(w.id);if(!E?.share?.url){oe.error("Unable to share session");return}const A=await d(E.share.url,w.id);oe[A?"success":"warning"]("Session shared",{description:A?"Share link copied to clipboard.":"Failed to copy URL"})},[e,d]),f=a.useCallback((w,E)=>{d(w,E).then(A=>{A||oe.error("Failed to copy URL")})},[d]),p=a.useCallback(w=>{xs(w).then(E=>{if(E.ok){oe.success("Session ID copied");return}oe.error("Failed to copy session ID")}).catch(()=>oe.error("Failed to copy session ID"))},[]),x=a.useCallback(async w=>{await e.unshareSession(w)?oe.success("Session unshared"):oe.error("Unable to unshare session")},[e]),y=a.useCallback(w=>{const E=[],A=k=>{(e.childrenMap.get(k)??[]).forEach(v=>{E.push(v),A(v.id)})};return A(w),E},[e.childrenMap]),m=a.useCallback((w,E)=>E?w:w.filter(A=>!A.time?.archived),[]),h=a.useCallback(async(w,E,A)=>{const k=E?.archivedBucket===!0||E?.hardDelete===!0,j=A?.descendantIds??m(y(w.id),k).map(L=>L.id);if(j.length===0){(k?await e.deleteSession(w.id):await e.archiveSession(w.id))?oe.success(k?"Session deleted":"Session archived"):oe.error(k?"Failed to delete session":"Failed to archive session");return}const v=[w.id,...j];if(k){const{deletedIds:L,failedIds:K}=await e.deleteSessions(v);if(K.length===0){const z=L.length;oe.success(z===1?`Deleted ${z} session`:`Deleted ${z} sessions`)}else oe.error("Failed to delete session");return}const{archivedIds:N,failedIds:M}=await e.archiveSessions(v);N.length>0&&oe.success(N.length===1?`Archived ${N.length} session`:`Archived ${N.length} sessions`),M.length>0&&oe.error(M.length===1?`Failed to archive ${M.length} session`:`Failed to archive ${M.length} sessions`)},[e,y,m]),b=a.useCallback((w,E)=>{const A=E?.archivedBucket===!0||E?.hardDelete===!0,k=m(y(w.id),A).map(j=>j.id);if(!e.showDeletionDialog||E?.skipConfirm===!0){h(w,E,{descendantIds:k});return}e.setDeleteSessionConfirm({session:w,descendantCount:k.length,descendantIds:k,archivedBucket:A})},[e,y,h,m]),g=a.useCallback(async()=>{if(!e.deleteSessionConfirm)return;const{session:w,archivedBucket:E,descendantIds:A}=e.deleteSessionConfirm;e.setDeleteSessionConfirm(null),await h(w,{archivedBucket:E},{descendantIds:A})},[e,h]),S=a.useCallback(async w=>{await e.unarchiveSession(w.id)?oe.success("Session restored"):oe.error("Failed to restore session")},[e]);return{copiedSessionId:t,handleSessionSelect:o,handleSessionDoubleClick:i,handleSaveEdit:l,handleCancelEdit:c,handleShareSession:u,handleCopyShareUrl:f,handleCopySessionId:p,handleUnshareSession:x,handleDeleteSession:b,handleRestoreSession:S,confirmDeleteSession:g}},Mm=e=>{const{safeStorage:t,keys:n,groupOrderByProject:r,collapsedGroups:o,setExpandedParents:i,setCollapsedProjects:l}=e,c=a.useRef(null),d=a.useRef(null),u=a.useCallback(()=>{const p=d.current;if(d.current=null,c.current=null,!p)return;const{projects:x}=ct.getState(),y=x.map(m=>({...m,sidebarCollapsed:p.has(m.id)}));sl({projects:y}).catch(()=>{})},[]),f=a.useCallback(p=>{typeof window>"u"||(d.current=p,c.current!==null&&window.clearTimeout(c.current),c.current=window.setTimeout(()=>{u()},700))},[u]);return a.useEffect(()=>()=>{typeof window<"u"&&c.current!==null&&window.clearTimeout(c.current),c.current=null,d.current=null},[]),a.useEffect(()=>{try{const p=t.getItem(n.sessionExpanded);if(p){const y=JSON.parse(p);Array.isArray(y)&&i(new Set(y.filter(m=>typeof m=="string")))}const x=t.getItem(n.projectCollapse);if(x){const y=JSON.parse(x);Array.isArray(y)&&l(new Set(y.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}},Tm=3;let pr=0;const Tl=[],Fm=()=>pr<Tm?(pr+=1,Promise.resolve()):new Promise(e=>{Tl.push(e)}),Lm=()=>{const e=Tl.shift();if(e){e();return}pr=Math.max(0,pr-1)},Om=async e=>{await Fm();try{return await e()}finally{Lm()}},Bm=5*6e4,_m=e=>{const{normalizedProjects:t,enabled:n=!0,gitRepoStatus:r,setProjectRepoStatus:o,setProjectRootBranches:i}=e,{git:l}=Os(),c=za(m=>m.ensureStatus),d=a.useMemo(()=>t.map(m=>m.normalizedPath).slice().sort().join("\0"),[t]),u=a.useRef(null);a.useEffect(()=>{if(!n||!l||t.length===0){u.current=null,o(new Map);return}const m=`${Ft()}\0${d}`;u.current!==m&&(u.current=m,t.forEach(h=>{Om(()=>c(h.normalizedPath,l))}))},[n,t,d,l,c,o]);const f=a.useRef(null);a.useEffect(()=>{if(!n){f.current=null;return}const m=new Map;t.forEach(b=>{m.set(b.id,r.get(b.normalizedPath)?.isGitRepo??null)});const h=t.map(b=>`${b.id}:${String(m.get(b.id))}`).join("|");f.current!==h&&(f.current=h,o(m))},[n,t,d,r,o]);const p=a.useMemo(()=>t.map(m=>{const h=r.get(m.normalizedPath)?.branch??"";return`${m.id}:${h}`}).join("|"),[t,r]),x=a.useRef(new Map),y=a.useRef(new Map);a.useEffect(()=>{if(!n)return;let m=!1;const h=setTimeout(()=>{(async()=>{const g=new Set(t.map(k=>k.id));for(const k of x.current.keys())g.has(k)||(x.current.delete(k),y.current.delete(k));const S=Date.now();if(t.filter(k=>{const j=r.get(k.normalizedPath);if(j?.isGitRepo===!1)return x.current.delete(k.id),y.current.delete(k.id),!1;if(j?.isGitRepo!==!0||j.branch===null)return!1;const v=j.branch.trim(),N=`${k.normalizedPath}\0${v}`,M=x.current.get(k.id);if(M===N){const L=y.current.get(k.id);return L&&(L.at=S),!1}return!(M!==void 0&&S-(y.current.get(k.id)?.at??0)<Bm)}).length===0)return;const E=[];if(t.forEach(k=>{const j=r.get(k.normalizedPath)?.branch?.trim()??"",v=`${k.normalizedPath}\0${j}`;j&&E.push({id:k.id,inputKey:v,branch:j})}),m||E.length===0)return;const A=Date.now();i(k=>{const j=new Map(k);return E.forEach(({id:v,branch:N})=>{N&&j.set(v,N)}),j}),E.forEach(({id:k,inputKey:j,branch:v})=>{x.current.set(k,j),v&&y.current.set(k,{branch:v,at:A})})})()},150);return()=>{m=!0,clearTimeout(h)}},[n,t,p,r,i])},Um=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}},zm=e=>{const t=new Map;for(const n of e){const r=Rn(n);r&&t.set(n.id,{directory:r,sessionId:n.id})}return t},$m=(e,t)=>{if(!e)return[];const n=[];return e.forEach((r,o)=>{t.has(o)||n.push(r)}),n},Km=e=>{const{enabled:t=!0,hasAuthoritativeGlobalSessions:n,sessions:r}=e,o=a.useRef(null);a.useEffect(()=>{if(!t||!n)return;const i=Ft(),l=zm(r),c=o.current?.runtimeKey===i?o.current.identities:null;for(const d of $m(c,l))Js().commitMissedDeletion(d.sessionId,d.directory);o.current={runtimeKey:i,identities:l}},[t,n,r])},Wm=(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,Wi=(e,t,n)=>{Wm(e.get(t),n)&&e.set(t,n)},Fl=e=>{const t=e;return Ee(t.directory)??Ee(t.project?.worktree)},Gm=(e,t,n)=>{if(e.time?.archived)return!0;const r=Fl(e);if(!r)return n?.allowUnknownDirectory??!0;if(Sr(r,n?.homeDirectory))return!0;if(t.size===0)return n?.allowEmptyDirectorySet??!0;const o=r.toLowerCase();for(const i of t)if(Ee(i)?.toLowerCase()===o)return!0;return!1},Hm=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)},qm=(e,t,n,r=[])=>{const o=new Map,i=new Map;for(const y of t){const m=Ee(y.normalizedPath);if(!m)continue;const h=i.get(m);(!h||y.id.localeCompare(h.id)<0)&&i.set(m,y),Wi(o,m,{projectId:y.id,projectRoot:m,scopeDirectory:m,kind:"project"})}if(n)for(const[y,m]of n){const h=Ee(y),b=h?i.get(h):void 0;if(!(!b||!h))for(const g of m||[]){const S=Ee(g?.path);S&&Wi(o,S,{projectId:b.id,projectRoot:h,scopeDirectory:S,kind:"worktree"})}}const l=new Map,c=new Map,d=new Map,u=new Map,f=new Map,p=y=>{if(!y)return null;if(l.has(y))return l.get(y)??null;const m=[];let h=y,b=null;for(;h;){if(l.has(h)){b=l.get(h)??null;break}if(m.push(h),b=o.get(h)??null,b)break;h=Hm(h)}for(const g of m)l.set(g,b);return b},x=(y,m,h)=>{for(const b of y){const g=Fl(b);if(Sr(g))continue;const S=p(g);if(!S)continue;c.set(b.id,S);const w=m.get(S.projectId);if(w?w.push(b):m.set(S.projectId,[b]),!h)continue;const E=h.get(S.scopeDirectory);E?E.add(b.id):h.set(S.scopeDirectory,new Set([b.id]))}};return x(e,d,f),x(r,u),{bySessionId:c,sessionsByProject:d,archivedSessionsByProject:u,sessionsByScope:f,directoryResolutions:l.size}};function Ll({state:e,activeLabel:t,unreadLabel:n,inputLabel:r,className:o}){if(e==="input"){const i=r??"Needs input";return s.jsx("span",{className:_("inline-flex items-center",o),"aria-label":i,title:i,children:s.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-status-warning"})})}return e==="unread"?s.jsx("span",{className:_("inline-flex items-center",o),"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:_("inline-flex items-center",o),"aria-label":t,title:t,children:s.jsx(ys,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})})}const Ym=({folder:e,displayName:t,sessions:n,subFolderItems:r,isCollapsed:o,collapsedActivityState:i=null,onToggle:l,onRename:c,onDelete:d,renderSessionNode:u,getRenderExtras:f,groupDirectory:p,projectId:x,mobileVariant:y=!1,alwaysShowActions:m=y,isRenaming:h=!1,renameDraft:b="",onRenameDraftChange:g,onRenameSave:S,onRenameCancel:w,droppableRef:E,isDropTarget:A=!1,onNewSession:k,depth:j=0,hideActions:v=!1,archivedBucket:N=!1})=>{const[M,L]=a.useState(!1),[K,z]=a.useState(""),$=a.useRef(null),O=h||M,R=h?b:K,D=a.useCallback(()=>{z(e.name),L(!0)},[e.name]),I=a.useCallback(()=>{const F=R.trim();F&&F!==e.name&&c(F),h&&S&&S(),L(!1),z("")},[R,e.name,h,c,S]),T=a.useCallback(()=>{h&&w&&w(),L(!1),z("")},[h,w]),W=a.useCallback(F=>{h&&g?g(F):z(F)},[h,g]);a.useEffect(()=>{if(!h)return;const F=()=>{const Ae=$.current;Ae&&(Ae.focus(),Ae.select())},me=requestAnimationFrame(F),q=window.setTimeout(F,0);return()=>{cancelAnimationFrame(me),window.clearTimeout(q)}},[h]);const Z=o?"folder":"folder-open";return s.jsxs("div",{className:"oc-folder",children:[s.jsxs("div",{ref:E,className:_("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",A&&"bg-primary/10 ring-1 ring-inset ring-primary/30"),onClick:O?void 0:F=>{F.currentTarget.blur(),l()},role:O?void 0:"button",tabIndex:O?void 0:0,onKeyDown:O?void 0:F=>{(F.key==="Enter"||F.key===" ")&&(F.preventDefault(),l())},"aria-label":o?`Expand folder ${e.name}`:`Collapse folder ${e.name}`,children:[s.jsxs("div",{className:_("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(P,{name:Z,className:_(nr,A?"text-primary":"text-muted-foreground")}),O?s.jsxs("form",{className:"flex min-w-0 flex-1 items-center gap-1",onPointerDown:F=>F.stopPropagation(),onMouseDown:F=>F.stopPropagation(),onSubmit:F=>{F.preventDefault(),I()},children:[s.jsx("input",{ref:$,value:R,onChange:F=>W(F.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:F=>F.stopPropagation(),onPointerDown:F=>F.stopPropagation(),onMouseDown:F=>F.stopPropagation(),onKeyDown:F=>{if(F.key==="Escape"){F.stopPropagation(),T();return}(F.key===" "||F.key==="Enter")&&F.stopPropagation()}}),s.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",onClick:F=>F.stopPropagation(),onPointerDown:F=>F.stopPropagation(),onMouseDown:F=>F.stopPropagation(),children:s.jsx(P,{name:"check",className:"size-4"})}),s.jsx("button",{type:"button",onClick:F=>{F.stopPropagation(),T()},onPointerDown:F=>F.stopPropagation(),onMouseDown:F=>F.stopPropagation(),className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(P,{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:_(dl,A?"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(Ll,{state:i,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,o?s.jsx(P,{name:"arrow-right-s",className:_(nr,"text-muted-foreground")}):s.jsx(P,{name:"arrow-down-s",className:_(nr,"text-muted-foreground")})]})]}),!O&&(!v||N)?s.jsx("div",{className:_("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&&k?s.jsx("button",{type:"button",onClick:F=>{F.stopPropagation(),k()},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(P,{name:"add",className:"size-4"})}):null,N?null:s.jsx("button",{type:"button",onClick:F=>{F.stopPropagation(),D()},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(P,{name:"pencil-ai",className:"size-4"})}),s.jsx("button",{type:"button",onClick:F=>{F.stopPropagation(),d()},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(P,{name:"delete-bin",className:"size-4"})})]})}):null]}),o?null:s.jsxs("div",{className:"pb-1",children:[r,n.length>0?n.map(F=>s.jsx(a.Fragment,{children:u(F,0,p??null,x??null,N,void 0,"project",f?.(F))},F.session.id)):r?null:s.jsx("div",{className:"py-1 px-3 text-left typography-micro text-muted-foreground/70",children:"Empty folder"})]})]})},Vm=a.memo(Ym),Qm=({sessionId:e,sessionDirectory:t,sessionTitle:n,children:r})=>{const{attributes:o,listeners:i,setNodeRef:l,isDragging:c}=Ud({id:`session-drag:${e}`,data:{type:"session",sessionId:e,sessionDirectory:t,sessionTitle:n}}),d=a.useCallback(u=>{u.stopPropagation(),i?.onPointerDown&&i.onPointerDown(u)},[i]);return s.jsx("div",{ref:l,...o,onPointerDown:d,className:c?"opacity-30":void 0,children:r})},Jm=({folderId:e,children:t})=>{const{setNodeRef:n,isOver:r}=zd({id:`folder-drop:${e}`,data:{type:"folder",folderId:e}});return s.jsx(s.Fragment,{children:t(n,r)})},Xm=({scopeKey:e,hasFolders:t,onSessionDroppedOnFolder:n,children:r})=>{const o=_o(Fn(Bd,{activationConstraint:{distance:8}})),[i,l]=a.useState(null),[c,d]=a.useState("Session"),[u,f]=a.useState(null),[p,x]=a.useState(null);if(!e)return s.jsx(s.Fragment,{children:r});const y=m=>{l(null),f(null),x(null);const{active:h,over:b}=m;if(!b)return;const g=h.data.current,S=b.data.current;g?.type==="session"&&g.sessionId&&S?.type==="folder"&&S.folderId&&n(g.sessionId,S.folderId)};return s.jsxs(Uo,{sensors:o,collisionDetection:zo,onDragStart:m=>{const h=m.active.data.current;if(h?.type==="session"&&h.sessionId){l(h.sessionId),d(h.sessionTitle??"Session");const b=m.active.rect.current.initial?.width,g=m.active.rect.current.initial?.height;f(typeof b=="number"?b:null),x(typeof g=="number"?g:null)}},onDragCancel:()=>{l(null),f(null),x(null)},onDragEnd:y,children:[r,s.jsx(_d,{children:i&&t?s.jsxs("div",{style:{width:u?`${u}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(P,{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})]})},Cr="gap-2",Ol="my-0.5 rounded-lg py-1.5",Qo=a.createContext("card"),Zt=({icon:e,children:t,onClick:n,className:r,mobileVariant:o=!1})=>{const i=a.useContext(Qo)==="tree";return s.jsxs("button",{type:"button",onClick:n,"data-sidebar-tree-row":i?"":void 0,className:_(o?Mf:Tf,i&&Cr,i&&Ol,r),children:[s.jsx(P,{name:e,className:_(Fs(o),"text-muted-foreground")}),s.jsx("span",{className:_(an(o),"flex-1 text-muted-foreground"),children:t})]})},Gi=(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)},ls=(e,t)=>{if(!t)return!1;if(e.session.id===t)return!0;for(const n of e.children)if(ls(n,t))return!0;return!1},Zm=(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})},Hi=new WeakMap;let qi=1;const ep=e=>{const t=Hi.get(e);if(t!==void 0)return t;const n=qi;return qi+=1,Hi.set(e,n),n},Ao=e=>e.children.length===0?"":e.children.map(n=>{const r=ep(n.session);return n.children.length===0?`${n.session.id}@${r}`:`${n.session.id}@${r}:${Ao(n)}`}).join("|"),Bl=(e,t,n,r,o,i)=>{const l=Ft(),c=(d,u)=>{if(d.session.id!==u.session.id||d.children.length!==u.children.length)return!0;const f=d.session.directory??o,p=u.session.directory??i,x=Ci(l,f??"",d.session.id),y=Ci(l,p??"",u.session.id);return(x?n.has(x):!1)!==(y?r.has(y):!1)?!0:d.children.some((m,h)=>c(m,u.children[h]))};return c(e,t)},gr=(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 u of c.children)if(l(u))return!0;return!1};return e.forEach(c=>l(c)),i},tp=5*6e4,sp=6e4,Yi=5*6e4,Vi=100,Sn=new Map,Xs=new Map,Ds=new Map,sn=new Map,_n=(e,t)=>{const n=cs((e??"").trim()),r=(t??"").trim();return!n||!r?"":`${Ft()}
|
|
12
|
+
${n}
|
|
13
|
+
${r}`},Qi=()=>({pr:null,checks:null,fetchedAt:null,isLoading:!1,stale:!1,error:null}),np=e=>{const t=e?.body;return t&&typeof t.kind=="string"?t:{kind:"failed",message:e instanceof Error?e.message:"PR status check failed"}},rp=e=>{const t=Object.keys(e);if(t.length<=Vi)return e;const n=t.sort((o,i)=>(sn.get(o)??0)-(sn.get(i)??0)),r={...e};for(let o=0;o<n.length-Vi;o+=1){const i=n[o];delete r[i],sn.delete(i),Xs.delete(i);const l=Ds.get(i);l!==void 0&&(clearTimeout(l),Ds.delete(i))}return r},_l=e=>e.pr?e.pr.state!=="open"?Yi:e.checks?.state==="pending"?sp:Yi:tp,No=(e,t,n,r)=>{if(typeof window>"u"||Ds.has(e))return;const o=es.getState().results[e];if(!o)return;const i=_l(o),l=setTimeout(()=>{if(Ds.delete(e),!!es.getState().results[e]){if(typeof document<"u"&&document.hidden){No(e,t,n,r);return}es.getState().refresh(t,n,r)}},i);typeof l=="object"&&l!==null&&typeof l.unref=="function"&&l.unref(),Ds.set(e,l)},es=Bs()(jr((e,t)=>({results:{},refresh:async(n,r,o,i)=>{const l=cs((n||"").trim()),c=(r||"").trim();if(!l||!c)return null;const d=_n(l,c);if(!d)return null;const u=Sn.get(d);if(u&&!i?.force)return u;const f=o??null;if(!f)return t().results[d]??null;const p=(Xs.get(d)??0)+1;Xs.set(d,p);const x=t().results[d]??Qi();e(m=>({results:{...m.results,[d]:{...x,isLoading:!0}}}));const y=(async()=>{try{const m=await f.prStatus(l,c);if(Xs.get(d)!==p||Ft()!==d.split(`
|
|
14
|
+
`)[0])return t().results[d]??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 sn.set(d,Date.now()),e(b=>({results:rp({...b.results,[d]:h})})),No(d,l,c,f),h}catch(m){if(Xs.get(d)!==p)return t().results[d]??null;const h=np(m),b=x.pr||x.fetchedAt?{...x,isLoading:!1,stale:!0,error:h}:{...Qi(),error:h};return e(g=>({results:{...g.results,[d]:b}})),No(d,l,c,f),b}})();Sn.set(d,y);try{return await y}finally{Sn.get(d)===y&&Sn.delete(d)}},load:async(n,r,o)=>{const i=cs((n||"").trim()),l=(r||"").trim();if(!i||!l)return null;const c=_n(i,l);sn.set(c,Date.now());const d=t().results[c];return d&&(d.pr||d.fetchedAt)?(t().refresh(i,l,o),d):t().refresh(i,l,o)},resetForRuntimeSwitch:()=>{Sn.clear(),Xs.clear(),sn.clear(),Cn=null;for(const n of Ds.values())clearTimeout(n);Ds.clear(),e({results:{}})}}),{name:"github-pr-status-store"}));typeof window<"u"&&(Un(()=>{es.getState().resetForRuntimeSwitch()}),document.addEventListener("visibilitychange",()=>{document.hidden||(async()=>{const e=await mt(async()=>{const{getRegisteredRuntimeAPIs:r}=await import("./index-C2ISrmRR.js").then(o=>o.cI);return{getRegisteredRuntimeAPIs:r}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:r})=>r()?.github??null).catch(()=>null);if(!e)return;const t=Date.now(),n=Object.entries(es.getState().results).filter(([,r])=>r.fetchedAt&&t-r.fetchedAt>=_l(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 es.getState().refresh(o,i,e).catch(()=>null)}}})()}));let Cn=null;const Iy=e=>{if(Cn&&Cn.results===e)return Cn.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 Cn={results:e,index:t},t},op=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=es(n=>e?n.results[e]??null:null);return a.useMemo(()=>op(t),[t])},zl=(e,t,n)=>{const r=a.useMemo(()=>_n(e,t),[e,t]),o=n??null;a.useEffect(()=>{if(!r||!e?.trim()||!t?.trim())return;let i=!1;return mt(async()=>{const{getRegisteredRuntimeAPIs:l}=await import("./index-C2ISrmRR.js").then(c=>c.cI);return{getRegisteredRuntimeAPIs:l}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:l})=>{if(i)return;const c=o??l()?.github??null;c&&es.getState().load(e,t,c)}).catch(()=>{}),()=>{i=!0}},[r,e,t,o])},$l=new Set,Jo=(e,t)=>e==="input"||t==="input"?"input":e==="active"||t==="active"?"active":e==="unread"||t==="unread"?"unread":null,Io=(e,t,n,r=$l)=>{if(r.has(e.session.id))return"input";if(t.has(e.session.id)){for(const i of e.children)if(Io(i,t,n,r)==="input")return"input";return"active"}let o=n.has(e.session.id)?"unread":null;for(const i of e.children)if(o=Jo(o,Io(i,t,n,r)),o==="input")return o;return o},Kl=(e,t,n,r=$l)=>{let o=null;for(const i of e)if(o=Jo(o,Io(i,t,n,r)),o==="input")return o;return o},ip=50,ap=28;function lp({visibleSessions:e,shouldVirtualize:t,hasExpandedParent:n,scrollContainerRef:r,groupDirectory:o,projectId:i,isArchivedBucket:l,renderSessionNode:c,getRenderExtras:d}){const u=a.useRef(null),[f,p]=a.useState(null),[x,y]=a.useState(0),[,m]=a.useState(0);a.useEffect(()=>{if(!t)return;const g=u.current;if(!g||typeof ResizeObserver>"u")return;const S=new ResizeObserver(()=>m(w=>w+1));return S.observe(g),()=>S.disconnect()},[t]),a.useLayoutEffect(()=>{if(!t){f!==null&&p(null),x!==0&&y(0);return}const g=u.current;if(!g)return;let S=f;const w=r?.current??null;if(w&&w.contains(g)){if(S=w,S!==f){p(S);return}}else if(!S||!S.contains(g)){let A=g.parentElement;for(;A;){const k=window.getComputedStyle(A);if(k.overflowY==="auto"||k.overflowY==="scroll"){S=A;break}A=A.parentElement}if(S!==f){p(S);return}}if(!S)return;const E=g.getBoundingClientRect().top-S.getBoundingClientRect().top+S.scrollTop;y(A=>Math.abs(A-E)<1?A:E)},[f,x,r,t]);const h=t&&f!==null,b=$d({count:e.length,enabled:h,getScrollElement:()=>f,initialOffset:()=>f?.scrollTop??0,estimateSize:()=>ap,overscan:n?20:8,scrollMargin:x,getItemKey:g=>e[g]?.session.id??g});return s.jsx("div",{ref:u,children:t?s.jsx("div",{style:{height:b.getTotalSize(),position:"relative"},children:b.getVirtualItems().map(g=>{const S=e[g.index];return S?s.jsx("div",{"data-index":g.index,ref:b.measureElement,className:"[&_[data-session-row]]:my-px",style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${g.start-x}px)`},children:c(S,0,o,i,l,void 0,"project",d(S))},S.session.id):null})}):e.map(g=>s.jsx(a.Fragment,{children:c(g,0,o,i,l,void 0,"project",d(g))},g.session.id))})}const or=(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 d=e.slice(c,c+o);i.push(s.jsx("mark",{className:"bg-primary text-primary-foreground ring-1 ring-primary/90",children:d},`${c}-${d}`)),l=c+o,c=n.indexOf(r,l)}return l<e.length&&i.push(e.slice(l)),i.length>0?i:e},hn=e=>[Ft(),...e.map(t=>(t??"").toString())].join(`
|
|
16
|
+
`),Qn=e=>{const t=e?.body;return t&&typeof t.kind=="string"?t:{kind:"failed",message:e instanceof Error?e.message:"GitHub request failed"}},cp=200,en=(e={})=>{const t=e.maxEntries??cp,n=new Map,r=new Map,o=new Map;let i=0;const l=new Map,c=new Map,d=h=>{const b=n.get(h)??null;return b&&l.set(h,i+=1),b},u=h=>{const b=c.get(h);if(b)for(const g of[...b])try{g()}catch{}},f=()=>{if(n.size<=t)return;const h=[...n.keys()].filter(g=>!r.has(g)&&(c.get(g)?.size??0)===0).sort((g,S)=>(l.get(g)??0)-(l.get(S)??0)),b=n.size-t;for(let g=0;g<b&&g<h.length;g+=1){const S=h[g];n.delete(S),l.delete(S),o.set(S,(o.get(S)??0)+1)}};let p=!1;const x=()=>{if(p||n.size<=t)return;p=!0;const h=()=>{p=!1,f()};typeof queueMicrotask=="function"?queueMicrotask(h):setTimeout(h,0)},y=(h,b)=>{const S={...n.get(h)??{data:null,fetchedAt:null,isLoading:!1,stale:!1,error:null,generation:o.get(h)??0},...b};return n.set(h,S),l.set(h,i+=1),x(),u(h),S},m=async(h,b)=>{const g=r.get(h);if(g)return g;const S=(o.get(h)??0)+1;o.set(h,S);const w=n.get(h);y(h,{isLoading:!0,generation:S});const E=(async()=>{try{const A=await b();return o.get(h)!==S?n.get(h)??{data:A,fetchedAt:Date.now(),isLoading:!1,stale:!1,error:null,generation:S}:y(h,{data:A,fetchedAt:Date.now(),isLoading:!1,stale:!1,error:null,generation:S})}catch(A){return o.get(h)!==S?n.get(h)??{data:w?.data??null,fetchedAt:w?.fetchedAt??null,isLoading:!1,stale:!0,error:Qn(A),generation:S}:w?.data!=null?y(h,{isLoading:!1,stale:!0,error:Qn(A),generation:S}):y(h,{data:null,fetchedAt:null,isLoading:!1,stale:!1,error:Qn(A),generation:S})}})();r.set(h,E);try{return await E}finally{r.get(h)===E&&r.delete(h),e.onSettle?.(h)}};return{getEntry:d,snapshot:()=>Object.fromEntries(n),subscribe:(h,b)=>{let g=c.get(h);return g||(g=new Set,c.set(h,g)),g.add(b),()=>{const S=c.get(h);S&&(S.delete(b),S.size===0&&c.delete(h))}},ensure:(h,b,g)=>!g?.force&&r.has(h)?r.get(h):!g?.force&&n.get(h)?.data!=null&&n.get(h)?.isLoading?r.get(h)??Promise.resolve(n.get(h)):!g?.force&&n.get(h)?.data!=null?(m(h,b),Promise.resolve(n.get(h))):m(h,b),refresh:(h,b)=>m(h,b),invalidate:async(h,b,g)=>{if(g?.exact??!0)return o.set(h,(o.get(h)??0)+1),n.delete(h),l.delete(h),r.has(h)&&r.delete(h),u(h),b?m(h,b):null;for(const w of[...n.keys()])(w===h||w.startsWith(h))&&(o.set(w,(o.get(w)??0)+1),n.delete(w),l.delete(w),r.delete(w),u(w));return null},markStale:h=>{const b=n.get(h);b?.data&&(b.stale||y(h,{stale:!0}))},setError:(h,b)=>{const g=n.get(h);return g?.data?y(h,{isLoading:!1,stale:!0,error:Qn(b)}):g??null},remove:h=>{o.set(h,(o.get(h)??0)+1),n.delete(h),l.delete(h),r.delete(h),u(h)},reset:()=>{const h=[...n.keys()];n.clear(),r.clear(),o.clear(),l.clear();for(const b of h)u(b)}}},mn=(e,t)=>Re.useSyncExternalStore(n=>t?e.subscribe(t,n):()=>{},()=>t?e.getEntry(t):null,()=>t?e.getEntry(t):null),Ey=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},Wl=(e,t)=>!e||!t?!1:e.toLowerCase()===t.toLowerCase(),Eo=e=>{if(!e)return[];const t=[];for(const n of e)n?.login&&t.push(n.login.toLowerCase());return t},Gl=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}},Xo=e=>{if(!e)return[];const t=[];for(const n of e)n?.name&&t.push(n.name.toLowerCase());return t},Hl=(e,t,n)=>{const r=Xo(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},dp=e=>{const t=[e.title.toLowerCase(),`#${e.number}`,`${e.number}`,e.author?.login?.toLowerCase()??"",e.head.toLowerCase(),e.base.toLowerCase()];for(const n of Xo(e.labels))t.push(n);return t},up=e=>{const t=[e.title.toLowerCase(),`#${e.number}`,`${e.number}`,e.author?.login?.toLowerCase()??""];for(const n of Xo(e.labels))t.push(n);return t},ql=(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},Ji=e=>e.state==="merged"||!!e.mergedAt,fp=(e,t)=>t==="all"?e:t==="open"?e.filter(n=>n.state==="open"):t==="merged"?e.filter(n=>Ji(n)):e.filter(n=>n.state==="closed"&&!Ji(n)),hp=(e,t)=>t==="all"?e:e.filter(n=>n.state===t),mp=(e,t,n)=>t==="all"||!n?!0:t==="mine"?Wl(e.author?.login,n):t==="review"?Eo(e.requestedReviewers).includes(n.toLowerCase()):Eo(e.assignees).includes(n.toLowerCase()),pp=(e,t,n)=>t==="all"||!n||t==="mentioned"?!0:t==="mine"?Wl(e.author?.login,n):Eo(e.assignees).includes(n.toLowerCase()),Ys=e=>{if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0},Yl=(e,t)=>{const n=[...e];return t==="newest"?(n.sort((r,o)=>Ys(o.createdAt)-Ys(r.createdAt)||o.number-r.number),n):t==="oldest"?(n.sort((r,o)=>Ys(r.createdAt)-Ys(o.createdAt)||r.number-o.number),n):(n.sort((r,o)=>Ys(o.updatedAt)-Ys(r.updatedAt)||o.number-r.number),n)},Ry=(e,t)=>{const{tokens:n,labelTokens:r}=Gl(t.search),o=[];for(const i of fp(e,t.state))mp(i,t.involvement,t.viewerLogin)&&Hl(i.labels,"",r)&&ql(dp(i),n)&&o.push(i);return Yl(o,t.sort)},Dy=(e,t)=>{const{tokens:n,labelTokens:r}=Gl(t.search),o=[];for(const i of hp(e,t.state))pp(i,t.involvement,t.viewerLogin)&&Hl(i.labels,t.labels,r)&&ql(up(i),n)&&o.push(i);return Yl(o,t.sort)},Jn=(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},Py=(e,t)=>e.filter(n=>!t.has(n.number)),gp=(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},Xi=Object.freeze({repo:null,number:null}),$r=e=>e.split(`
|
|
17
|
+
`)[1]??"",Ro=(e,t)=>`${cs(e)}
|
|
18
|
+
${t}`,jn=(e,t)=>`${e}#${t}`,bp=(e,t)=>{const n=e?.body;return n&&typeof n.kind=="string"?n:{kind:"failed",message:e instanceof Error?e.message:t}},Ns=async(e,t)=>{if(e)try{await e.invalidate(t)}catch{}},Zi=(e,t)=>!e?.data||!e.fetchedAt?!1:Date.now()-e.fetchedAt<t,ea=10,xp=(e,t)=>{const n=en(),r=en({maxEntries:60}),o=en(),i=en(),l=new Map,c=new Map,d=async(O,R)=>{const D=c.get(O);if(D)return await D.catch(()=>null),{ran:!1,result:null};const I=R();c.set(O,I);try{return{ran:!0,result:await I}}finally{c.get(O)===I&&c.delete(O)}},u=(O,R)=>{if(R.length===0)return;const D=e.collectionKeyFor(O,e.openCollection);let I=l.get(D);I||(I=new Map,l.set(D,I));for(const T of R)I.set(T.number,T)},f=O=>{const R=Object.keys(r.snapshot()).filter(I=>$r(I)===O&&!r.getEntry(I)?.isLoading);if(R.length<=ea)return;const D=R.map(I=>({key:I,fetchedAt:r.getEntry(I)?.data?.fetchedAt??0})).sort((I,T)=>I.fetchedAt-T.fetchedAt);for(let I=0;I<D.length-ea;I+=1)r.remove(D[I].key)},p=O=>{const R=n.getEntry(e.collectionKeyFor(O,e.openCollection))?.data?.items??[],D=n.getEntry(e.collectionKeyFor(O,e.closedCollection))?.data?.items??[],I=Jn(R,D),T=l.get(e.collectionKeyFor(O,e.openCollection));return!T||T.size===0?I:Jn(I,[...T.values()])},x=(O,R,D)=>{const I=Ro(O,R),T=t.get().filtersByScope[I]??e.defaultFilters;t.set(W=>({filtersByScope:{...W.filtersByScope,[I]:{...T,...D}}}))},y=(O,R)=>{const D=Ro(O,R);t.set(I=>({filtersByScope:{...I.filtersByScope,[D]:{...e.defaultFilters}}}))},m=(O,R,D)=>{const I=cs(O);I&&t.set(T=>({selectionByDirectory:{...T.selectionByDirectory,[I]:{repo:R,number:D}}}))},h=(O,R,D,I)=>{const T=e.collectionKeyFor(R,D);return n.ensure(T,async()=>{const W=await e.fetchList(I,O,R,e.buildCollectionQuery(D));return{items:W.items,nextCursor:W.nextCursor,fetchedAt:W.fetchedAt}})},b=(O,R,D)=>{const I=e.collectionKeyFor(R,e.closedCollection);n.getEntry(I)?.data||n.getEntry(I)?.isLoading||h(O,R,e.closedCollection,D).catch(()=>null)},g=async(O,R,D,I)=>{const T=D==="open"||D==="both",W=D==="closed"||D==="both",Z=[],F=n.getEntry(e.collectionKeyFor(R,e.openCollection)),me=n.getEntry(e.collectionKeyFor(R,e.closedCollection));T&&(!Zi(F,e.freshWindowMs)||F?.stale)&&Z.push(h(O,R,e.openCollection,I)),W&&(!Zi(me,e.freshWindowMs)||me?.stale)&&Z.push(h(O,R,e.closedCollection,I)),await Promise.all(Z.map(q=>q.catch(()=>null))),T&&!n.getEntry(e.collectionKeyFor(R,e.closedCollection))?.data&&b(O,R,I)},S=async(O,R,D,I)=>{const T=e.collectionKeyFor(R,D),W=n.getEntry(T),Z=W?.data?.nextCursor??null;if(!Z||W?.isLoading)return W;try{const F=await d(`${T}:more`,async()=>{const me=await e.fetchList(I,O,R,{...e.buildCollectionQuery(D),cursor:Z}),q=n.getEntry(T)?.data,Ae={items:Jn(q?.items??[],me.items),nextCursor:me.nextCursor,fetchedAt:me.fetchedAt};return n.refresh(T,async()=>Ae)});return F.ran?F.result??n.getEntry(T):n.getEntry(T)}catch(F){return n.setError(T,F)??n.getEntry(T)}},w=async(O,R,D,I)=>{const T=D==="both"?[e.openCollection,e.closedCollection]:[D];await Promise.all(T.map(W=>{const Z=e.collectionKeyFor(R,W);return n.refresh(Z,async()=>{const F=await e.fetchList(I,O,R,e.buildCollectionQuery(W));return{items:F.items,nextCursor:F.nextCursor,fetchedAt:F.fetchedAt}}).catch(()=>null)}))},E=async(O,R,D,I)=>{const T=e.remoteKeyFor(R,D),W=await r.refresh(T,async()=>{const Z=await e.fetchList(I,O,R,e.buildRemoteQuery(D));return{items:Z.items,nextCursor:Z.nextCursor,fetchedAt:Z.fetchedAt}});return W.data&&(u(R,W.data.items),f(R)),W},A=async(O,R,D,I)=>{const T=e.remoteKeyFor(R,D),W=r.getEntry(T),Z=W?.data?.nextCursor??null;if(!Z||W?.isLoading)return W;try{const F=await e.fetchList(I,O,R,e.buildRemoteQuery(D,Z)),me=r.getEntry(T)?.data,q={items:Jn(me?.items??[],F.items),nextCursor:F.nextCursor,fetchedAt:F.fetchedAt},Ae=await r.refresh(T,async()=>q);return Ae.data&&(u(R,Ae.data.items),f(R)),Ae}catch(F){return r.setError(T,F)??r.getEntry(T)}},k=O=>{for(const R of Object.keys(r.snapshot()))$r(R)===O&&r.remove(R);for(const R of[...l.keys()])$r(R)===O&&l.delete(R)},j=(O,R,D,I)=>{const T=e.detailKeyFor(R,D);return o.refresh(T,async()=>({detail:await e.fetchDetail(I,O,R,D)}))};return{initialState:{filtersByScope:{},selectionByDirectory:{}},resources:{collections:n,remote:r,details:o,comments:i},setFilters:x,resetFilters:y,select:m,ensureCollection:h,ensureCollectionsFresh:g,prefetchClosedCollection:b,loadMoreCollection:S,refreshCollections:w,searchRemote:E,loadMoreRemote:A,dropRemoteForRepo:k,refreshAllForScope:async(O,R,D)=>{await Ns(D,{directory:O,repo:R,kind:e.serverKind}),k(R),await w(O,R,"both",D).catch(()=>null);const I=t.get().selectionByDirectory[cs(O)];I?.repo===R&&typeof I.number=="number"&&await j(O,R,I.number,D).catch(()=>null)},ensureDetail:(O,R,D,I)=>{const T=e.detailKeyFor(R,D);return o.ensure(T,async()=>({detail:await e.fetchDetail(I,O,R,D)}))},refreshDetail:j,ensureComments:(O,R,D,I)=>{const T=e.commentsKeyFor(R,D);return i.ensure(T,async()=>{const W=await e.fetchComments(I,O,R,D);return{comments:W.comments,nextCursor:W.nextCursor,fetchedAt:W.fetchedAt}})},loadMoreComments:async(O,R,D,I)=>{const T=e.commentsKeyFor(R,D),W=i.getEntry(T),Z=W?.data?.nextCursor??null;if(!Z||W?.isLoading)return W;try{const F=await e.fetchComments(I,O,R,D,Z),me=i.getEntry(T)?.data,q={comments:gp(me?.comments??[],F.comments),nextCursor:F.nextCursor,fetchedAt:F.fetchedAt};return await i.refresh(T,async()=>q)}catch(F){return i.setError(T,F)??i.getEntry(T)}},refreshComments:(O,R,D,I)=>{const T=e.commentsKeyFor(R,D);return i.refresh(T,async()=>{const W=await e.fetchComments(I,O,R,D);return{comments:W.comments,nextCursor:W.nextCursor,fetchedAt:W.fetchedAt}})},markCollectionsStale:O=>{n.markStale(e.collectionKeyFor(O,e.openCollection)),n.markStale(e.collectionKeyFor(O,e.closedCollection))},getLocalIndex:p,withSingleFlight:d,resetCore:()=>{n.reset(),r.reset(),l.clear(),o.reset(),i.reset(),c.clear(),t.set({filtersByScope:{},selectionByDirectory:{}})},toStoreError:O=>bp(O,e.errorFallback)}},Do={state:"open",involvement:"all",search:"",sort:"updated"},yp=3e4,wp=100,vp=50,Vl=(e,t)=>hn([e,"pulls-collection",t]),Ql=(e,t)=>hn([e,"pulls-remote",t.state,t.involvement,t.q.trim()]),br=(e,t)=>hn([e,"pull-detail",t]),Zo=(e,t)=>hn([e,"pull-comments",t]),Po=(e,t)=>hn([e,"pull-files",t]),Mo=(e,t)=>hn([e,"pull-checks",t]),Sp=e=>({state:e,perPage:wp}),jp=(e,t)=>({state:e.state,filter:e.involvement,q:e.q.trim()?e.q.trim():void 0,perPage:vp,...t?{cursor:t}:{}}),xr=e=>`pichamber:pr-merge-method:${e}`,Jl=new Map,kp=e=>{try{if(typeof localStorage<"u")return localStorage.getItem(e)}catch{}return null},Cp=(e,t)=>{try{if(typeof localStorage<"u"){localStorage.setItem(e,t);return}}catch{}},My=e=>{if(!e)return null;const t=kp(xr(e));return t==="merge"||t==="squash"||t==="rebase"?t:Jl.get(xr(e))??null},Ap=(e,t)=>{if(e){Jl.set(xr(e),t);try{Cp(xr(e),t)}catch{}}},Np={set:e=>{typeof e=="function"?bs.setState(t=>{const n={filtersByScope:t.filtersByScope,selectionByDirectory:t.selectionByDirectory};return e(n)}):bs.setState(e)},get:()=>{const e=bs.getState();return{filtersByScope:e.filtersByScope,selectionByDirectory:e.selectionByDirectory}}},Pe=xp({openCollection:"open",closedCollection:"closed",defaultFilters:Do,freshWindowMs:yp,serverKind:"pulls",errorFallback:"Pull request request failed",collectionKeyFor:Vl,remoteKeyFor:Ql,detailKeyFor:br,commentsKeyFor:Zo,buildCollectionQuery:e=>({...Sp(e)}),buildRemoteQuery:(e,t)=>({...jp(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}}},Np),Jt=en(),ir=en(),bs=Bs()(jr((e,t)=>({...Pe.initialState,actionErrorByDetail:{},actingActions:{},setFilters:Pe.setFilters,resetFilters:Pe.resetFilters,selectPullRequest:Pe.select,ensureCollection:Pe.ensureCollection,ensureCollectionsFresh:Pe.ensureCollectionsFresh,prefetchClosedCollection:Pe.prefetchClosedCollection,loadMoreCollection:Pe.loadMoreCollection,refreshCollections:Pe.refreshCollections,searchRemote:Pe.searchRemote,loadMoreRemote:Pe.loadMoreRemote,dropRemoteForRepo:Pe.dropRemoteForRepo,refreshAllForScope:Pe.refreshAllForScope,ensureDetail:Pe.ensureDetail,refreshDetail:Pe.refreshDetail,ensureComments:Pe.ensureComments,loadMoreComments:Pe.loadMoreComments,refreshComments:Pe.refreshComments,ensureFiles:(n,r,o,i)=>{const l=Po(r,o);return Jt.ensure(l,async()=>i.pullFiles(n,r,o))},loadMoreFiles:async(n,r,o,i)=>{const l=Po(r,o),c=Jt.getEntry(l),d=c?.data?.nextCursor??null;if(!d||c?.isLoading)return c;try{const u=await Pe.withSingleFlight(`${l}:more`,async()=>{const f=await i.pullFiles(n,r,o,d),p=Jt.getEntry(l)?.data,x=new Set((p?.files??[]).map(m=>m.filename)),y={repo:f.repo,number:f.number,files:[...p?.files??[],...f.files.filter(m=>!x.has(m.filename))],nextCursor:f.nextCursor,fetchedAt:f.fetchedAt};return Jt.refresh(l,async()=>y)});return u.ran?u.result??Jt.getEntry(l):Jt.getEntry(l)}catch(u){return Jt.setError(l,u)??Jt.getEntry(l)}},ensureChecks:(n,r,o,i)=>{const l=Mo(r,o);return ir.ensure(l,async()=>i.pullChecks(n,r,o,!0))},refreshChecks:(n,r,o,i)=>{const l=Mo(r,o);return ir.refresh(l,async()=>i.pullChecks(n,r,o,!0))},performAction:async(n,r,o,i,l)=>{const c=jn(r,o),d=br(r,o);if(t().actingActions[c])return{ok:!1,error:{kind:"failed",message:"Action already in progress"}};e(x=>({actingActions:{...x.actingActions,[c]:!0},actionErrorByDetail:{...x.actionErrorByDetail,[c]:null}}));const u=Pe.resources.details.getEntry(d)?.data?.detail??null,f=u?.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&&u&&await Pe.resources.details.refresh(d,async()=>({detail:{...u,pr:p}})).catch(()=>null);try{return await l.pullAction(n,r,o,i),(i==="merge"||i==="squash"||i==="rebase")&&t().setMergeMethod(r,i),await Ns(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(x=>({actingActions:{...x.actingActions,[c]:!1}})),{ok:!0}}catch(x){const y=Pe.toStoreError(x);return u&&await Pe.resources.details.refresh(d,async()=>({detail:u})).catch(()=>null),e(m=>({actingActions:{...m.actingActions,[c]:!1},actionErrorByDetail:{...m.actionErrorByDetail,[c]:y}})),{ok:!1,error:y}}},updateTitleBody:async(n,r,o,i,l)=>{const c=jn(r,o),d=br(r,o),u=Pe.resources.details.getEntry(d)?.data?.detail??null,f=u?.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&&u&&await Pe.resources.details.refresh(d,async()=>({detail:{...u,pr:p}})).catch(()=>null);try{return await l.pullUpdate(n,r,o,i),await Ns(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(x){const y=Pe.toStoreError(x);return u&&await Pe.resources.details.refresh(d,async()=>({detail:u})).catch(()=>null),e(m=>({actionErrorByDetail:{...m.actionErrorByDetail,[c]:y}})),{ok:!1,error:y}}},addComment:async(n,r,o,i,l)=>{const c=jn(r,o),d=Zo(r,o),u=i.trim(),f={id:-Date.now(),url:"",body:u,author:null,createdAt:new Date().toISOString(),updatedAt:null},p=Pe.resources.comments.getEntry(d)?.data??null;if(p){const x={comments:[...p.comments,f],nextCursor:p.nextCursor,fetchedAt:p.fetchedAt};await Pe.resources.comments.refresh(d,async()=>x).catch(()=>null)}try{return await l.pullComment(n,r,o,u),await Ns(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(x){const y=Pe.toStoreError(x);return p?await Pe.resources.comments.refresh(d,async()=>p).catch(()=>null):Pe.resources.comments.remove(d),e(m=>({actionErrorByDetail:{...m.actionErrorByDetail,[c]:y}})),{ok:!1,error:y}}},submitReview:async(n,r,o,i,l)=>{const c=jn(r,o);try{return await l.pullReview(n,r,o,{event:i.event,body:i.body,comments:i.comments}),await Ns(l,{directory:n,repo:r,kind:"pulls",number:o}),await t().refreshDetail(n,r,o,l).catch(()=>null),{ok:!0}}catch(d){const u=Pe.toStoreError(d);return e(f=>({actionErrorByDetail:{...f.actionErrorByDetail,[c]:u}})),{ok:!1,error:u}}},threadAction:async(n,r,o,i,l,c)=>{const d=jn(r,o);try{return await c.pullThread(n,r,o,i,l),await Ns(c,{directory:n,repo:r,kind:"pulls",number:o}),await t().refreshDetail(n,r,o,c).catch(()=>null),{ok:!0}}catch(u){const f=Pe.toStoreError(u);return e(p=>({actionErrorByDetail:{...p.actionErrorByDetail,[d]: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:Pe.toStoreError(c)}}},createPullRequest:async(n,r)=>{try{const o=await r.pullCreate(n);return await Ns(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:Pe.toStoreError(o)}}},rerunFailedChecks:async(n,r,o,i)=>{try{return await i.checksRerun(n,r,o),{ok:!0}}catch(l){return{ok:!1,error:Pe.toStoreError(l)}}},setMergeMethod:(n,r)=>{Ap(n,r)},notifyAgentTurnComplete:n=>{const r=cs((n||"").trim());if(!r)return;const o=es.getState();for(const l of Object.keys(o.results)){const[,c]=l.split(`
|
|
19
|
+
`);if(c!==r)continue;const[,,d]=l.split(`
|
|
20
|
+
`);d&&mt(async()=>{const{getRegisteredRuntimeAPIs:u}=await import("./index-C2ISrmRR.js").then(f=>f.cI);return{getRegisteredRuntimeAPIs:u}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:u})=>{const f=u()?.github??null;if(f)return o.refresh(r,d,f,{force:!0})}).catch(()=>{})}const i=t().selectionByDirectory[r];i?.repo&&typeof i.number=="number"&&(Pe.markCollectionsStale(i.repo),mt(async()=>{const{getRegisteredRuntimeAPIs:l}=await import("./index-C2ISrmRR.js").then(c=>c.cI);return{getRegisteredRuntimeAPIs:l}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:l})=>{const c=l()?.github??null;if(c)return t().refreshDetail(r,i.repo,i.number,c)}).catch(()=>{}))},resetForRuntimeSwitch:()=>{Pe.resetCore(),Jt.reset(),ir.reset(),e({actionErrorByDetail:{},actingActions:{}})}}),{name:"github-pull-requests-store"}));typeof window<"u"&&(Un(()=>{bs.getState().resetForRuntimeSwitch()}),window.addEventListener("focus",()=>{typeof document<"u"&&document.hidden}));const Ty=e=>{if(typeof window>"u")return()=>{};let t=new Set,n=!1,r=!1,o=null;return mt(async()=>{const{useNotificationStore:i}=await import("./useAppFontEffects-CHnpTOtc.js").then(l=>l.el);return{useNotificationStore:i}},__vite__mapDeps([1,2,3,4,5,6,7,8,9,10,11,12])).then(({useNotificationStore:i})=>{if(r)return;const l=()=>{const c=i.getState().list,d=new Set(c.map(u=>`${u.type}:${u.session??""}:${u.time}`));if(!n){t=d,n=!0;return}for(const u of c){const f=`${u.type}:${u.session??""}:${u.time}`;t.has(f)||(t.add(f),u.type==="turn-complete"&&u.directory&&(bs.getState().notifyAgentTurnComplete(u.directory),e?.(u.directory)))}};l(),o=i.subscribe(l)}).catch(()=>{}),()=>{r=!0,o?.(),o=null}},Fy=e=>Pe.getLocalIndex(e),Ly=(e,t)=>Pe.getLocalIndex(e).find(n=>n.number===t)??null,Oy=(e,t)=>mn(Pe.resources.collections,e?Vl(e,t):null),By=(e,t)=>mn(Pe.resources.remote,e?Ql(e,t):null),_y=(e,t)=>mn(Pe.resources.details,e!=null&&t!=null?br(e,t):null),Uy=(e,t)=>mn(Pe.resources.comments,e!=null&&t!=null?Zo(e,t):null),zy=(e,t)=>mn(Jt,e!=null&&t!=null?Po(e,t):null),$y=(e,t)=>mn(ir,e!=null&&t!=null?Mo(e,t):null),Ky=(e,t)=>bs(n=>!e||!t?Do:n.filtersByScope[Ro(e,t)]??Do),Wy=e=>bs(t=>e?t.selectionByDirectory[cs(e)]??Xi:Xi),Xl=(e,t,n)=>{bs.getState().selectPullRequest(e,t,n);const r=cs(e);mt(async()=>{const{useUIStore:o}=await import("./index-C2ISrmRR.js").then(i=>i.cL);return{useUIStore:o}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({useUIStore:o})=>{o.getState().openContextSurface(r,"pull-requests")}).catch(()=>{}),mt(async()=>{const{useGitHubScopeStore:o}=await import("./useAppFontEffects-CHnpTOtc.js").then(i=>i.en);return{useGitHubScopeStore:o}},__vite__mapDeps([1,2,3,4,5,6,7,8,9,10,11,12])).then(({useGitHubScopeStore:o})=>{o.getState().setSelectedRepo(e,t)}).catch(()=>{})},Ip=({directory:e,number:t,color:n})=>{const r=$a(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(),Xl(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 Ep({group:e,groupKey:t,isCollapsed:n,onToggleCollapsedGroup:r,normalizedSessionSearchQuery:o,alwaysShowActions:i,groupHeaderRightPadding:l,dragHandleProps:c,groupPrColor:d,groupPrSummary:u,groupActivityIndicator:f,showBranchSubtitle:p,statusLine:x,allGroupSessions:y,projectId:m,activeProjectId:h,setActiveProjectIdOnly:b,setActiveMainTab:g,mobileVariant:S,setSessionSwitcherOpen:w,openNewSessionDraft:E}){return s.jsxs("div",{className:_("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:A=>{(A.key==="Enter"||A.key===" ")&&(A.preventDefault(),r(t))},"aria-label":n?`Expand ${e.label}`:`Collapse ${e.label}`,"aria-expanded":!n,children:[s.jsx("div",{ref:c?.setActivatorNodeRef,className:_("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(P,{name:"archive",className:_("size-4 shrink-0 text-muted-foreground",i?"hidden":"group-hover/gh:hidden")}),s.jsx("span",{className:_("text-muted-foreground size-4 items-center justify-center",i?"inline-flex":"hidden group-hover/gh:inline-flex"),children:n?s.jsx(P,{name:"arrow-right-s",className:"size-4"}):s.jsx(P,{name:"arrow-down-s",className:"size-4"})})]}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:or(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(P,{name:"git-branch",className:_("size-4 shrink-0",!d&&"text-muted-foreground",i?"hidden":"group-hover/gh:hidden"),style:d?{color:d}:void 0}),s.jsx("span",{className:_("text-muted-foreground size-4 items-center justify-center",i?"inline-flex":"hidden group-hover/gh:inline-flex"),children:n?s.jsx(P,{name:"arrow-right-s",className:"size-4"}):s.jsx(P,{name:"arrow-down-s",className:"size-4"})})]}),s.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal text-muted-foreground",children:or(e.label,o)}),f,u?s.jsx(Ip,{directory:e.directory??null,number:u.number,color:d}):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:or(e.label,o)}),f]})}),p&&x?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 leading-tight",children:[e.isArchivedBucket?s.jsx(P,{name:"archive",className:"size-4 flex-shrink-0 text-muted-foreground"}):s.jsx(P,{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:x.label})]}):null]})}),e.isArchivedBucket&&y.length>0?s.jsx("div",{className:_("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:A=>{A.stopPropagation(),Ms.requestDelete({sessions:y,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(P,{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:_("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:A=>{A.stopPropagation(),m&&m!==h&&b(m),g("chat"),S&&w(!1),E({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(P,{name:"add",className:"h-4 w-4"})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"New draft session"})})]})}):null]})}const Xn=(e,t)=>t?e.sessions.some(n=>ls(n,t)):!1,Rp=(e,t,n)=>e.sessions.some(r=>Bl(r,r,t,n,e.directory,e.directory)),Dp=(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)},ta=(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)},Pp=(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)},Mp=(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&&Rp(t.group,e.pinnedSessionIds,t.pinnedSessionIds)||e.expandedParents!==t.expandedParents&&Pp(t.group,e.expandedParents,t.expandedParents)||e.sessionOrderIndex!==t.sessionOrderIndex&&Dp(t.group,e.sessionOrderIndex,t.sessionOrderIndex)||e.editingId!==t.editingId&&(Xn(e.group,e.editingId)||Xn(t.group,t.editingId))||e.editTitle!==t.editTitle&&(Xn(e.group,e.editingId)||Xn(t.group,t.editingId)))return!1;if(e.openSidebarMenuKey!==t.openSidebarMenuKey){const n=gr(e.group.sessions,e.openSidebarMenuKey,"project",!!e.group.isArchivedBucket),r=gr(t.group.sessions,t.openSidebarMenuKey,"project",!!t.group.isArchivedBucket);if(n||r)return!1}return e.activeActivitySessionIds!==t.activeActivitySessionIds&&ta(t.group,e.activeActivitySessionIds,t.activeActivitySessionIds)||e.unreadActivitySessionIds!==t.unreadActivitySessionIds&&ta(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 Tp({group:e,sourceGroupNodes:t,hasSessionSearchQuery:n,normalizedSessionSearchQuery:r,compareSessionNodes:o,activeActivitySessionIds:i,unreadActivitySessionIds:l,inputActivitySessionIds:c,collectGroupSessions:d}){const u=bt(k=>k.foldersMap),f=e.folderScopeKey??Ee(e.directory??null),p=a.useMemo(()=>e.folderScopes&&e.folderScopes.length>0?e.folderScopes:f?[{scopeKey:f,directory:e.directory??null}]:[],[f,e.directory,e.folderScopes]),x=a.useMemo(()=>p.flatMap(({scopeKey:k,directory:j})=>(u[k]??[]).map(v=>({folder:v,scopeKey:k,scopeDirectory:j}))),[p,u]),y=a.useMemo(()=>{const k=new Map,j=v=>{v.forEach(N=>{k.set(N.session.id,N),N.children.length>0&&j(N.children)})};return j(t),k},[t]),m=a.useMemo(()=>x.map(({folder:k,scopeKey:j,scopeDirectory:v})=>{const N=Zm(k.sessionIds,y).sort(o);return{folder:k,scopeKey:j,scopeDirectory:v,nodes:N}}),[x,y,o]),h=a.useMemo(()=>{const k=new Map(m.map(M=>[M.folder.id,M])),j=new Map;for(const{folder:M}of m){if(!M.parentId)continue;const L=j.get(M.parentId);L?L.push(M.id):j.set(M.parentId,[M.id])}const v=new Map,N=M=>{const L=v.get(M);if(L!==void 0)return L;const K=k.get(M);if(!K)return v.set(M,!1),!1;const z=j.get(M)??[];if(e.isArchivedBucket&&K.nodes.length===0){const R=z.some(D=>N(D));return v.set(M,R),R}if(!n||K.folder.name.toLowerCase().includes(r)||K.nodes.length>0)return v.set(M,!0),!0;const O=z.some(R=>N(R));return v.set(M,O),O};return m.filter(({folder:M})=>N(M.id))},[m,e.isArchivedBucket,n,r]),b=a.useMemo(()=>new Set(h.flatMap(k=>k.folder.sessionIds)),[h]),g=a.useMemo(()=>t.filter(k=>!b.has(k.session.id)),[t,b]),S=a.useMemo(()=>h.filter(({folder:k})=>!k.parentId),[h]),w=a.useMemo(()=>{const k=new Map;return h.forEach(j=>{if(!j.folder.parentId)return;const v=k.get(j.folder.parentId)??[];v.push(j),k.set(j.folder.parentId,v)}),k},[h]),E=a.useMemo(()=>{const k=new Map(h.map(N=>[N.folder.id,N])),j=new Map,v=(N,M)=>{const L=j.get(N);if(L!==void 0)return L;if(M.has(N))return null;M.add(N);const K=k.get(N);let z=K?Kl(K.nodes,i,l,c):null;for(const $ of w.get(N)??[])if(z=Jo(z,v($.folder.id,M)),z==="input")break;return j.set(N,z),z};return h.forEach(({folder:N})=>v(N.id,new Set)),j},[i,h,w,c,l]),A=a.useMemo(()=>{if(!e.isArchivedBucket)return new Map;const k=new Map,j=new Map;for(const{folder:N}of h){if(!N.parentId)continue;const M=j.get(N.parentId)??[];M.push(N.id),j.set(N.parentId,M)}const v=(N,M)=>{if(M.has(N))return[];M.add(N);const L=h.find(({folder:$})=>$.id===N),K=L?d(L.nodes):[],z=j.get(N)??[];for(const $ of z)K.push(...v($,M));return K};for(const{folder:N}of h)k.set(N.id,v(N.id,new Set));return k},[h,d,e.isArchivedBucket]);return{folderScopeKey:f,folderScopes:p,allFoldersForGroup:h,rootFolders:S,ungroupedSessions:g,folderActivityStateById:E,folderSessionsForDeleteById:A}}function Fp(e){const{group:t,groupKey:n,projectId:r,hideGroupLabel:o,hasSessionSearchQuery:i,normalizedSessionSearchQuery:l,groupSearchDataByGroup:c,visibleSessionCount:d,collapsedGroups:u,hideDirectoryControls:f,collapsedFolderIds:p,toggleFolderCollapse:x,renameFolder:y,deleteFolder:m,showDeletionDialog:h,setDeleteFolderConfirm:b,renderSessionNode:g,showMoreGroupSessions:S,resetGroupSessionLimit:w,mobileVariant:E,alwaysShowActions:A,activeProjectId:k,setActiveProjectIdOnly:j,setActiveMainTab:v,setSessionSwitcherOpen:N,openNewSessionDraft:M,addSessionToFolder:L,createFolderAndStartRename:K,renamingFolderId:z,renameFolderDraft:$,setRenameFolderDraft:O,setRenamingFolderId:R,pinnedSessionIds:D,expandedParents:I,sessionOrderIndex:T,editingId:W,openSidebarMenuKey:Z,activeActivitySessionIds:F,unreadActivitySessionIds:me,onToggleCollapsedGroup:q,dragHandleProps:Ae,compactBodyPadding:Ie=!1,scrollContainerRef:G}=e,U=a.useCallback((Ce,Ue)=>{const ge=T.get(Ce.session.id),Oe=T.get(Ue.session.id);if(ge!==void 0||Oe!==void 0){if(ge===void 0)return 1;if(Oe===void 0)return-1;if(ge!==Oe)return ge-Oe}return gu(Ce.session,Ue.session,D,Ka)},[D,T]),Y=i?c.get(t):null,X=i?!1:u.has(n),se=!t.isMain&&!t.isArchivedBucket&&!o?Ee(t.directory??null):null,we=!t.isMain&&!t.isArchivedBucket&&!o&&t.branch?.trim()||null,pe=a.useMemo(()=>se&&we?_n(se,we):null,[se,we]),V=Ul(pe);zl(se,we);const Q=V?`var(--pr-${V.visualState})`:void 0,ie=f?10:5,ke=Math.max(ie,d??ie),Se=i?Y?.groupMatches===!0:!1,He=i,H=a.useMemo(()=>[...He?Y?.filteredNodes??[]:t.sessions].sort(U),[U,t.sessions,Y?.filteredNodes,He]),de=a.useCallback(Ce=>{const Ue=[],ge=Oe=>{Oe.forEach(Ge=>{Ue.push(Ge.session),Ge.children.length>0&&ge(Ge.children)})};return ge(Ce),Ue},[]),ne=bu(),ue=a.useMemo(()=>new Set(ne.map(Ce=>Ce.sessionId)),[ne]),{folderScopeKey:ve,folderScopes:Le,allFoldersForGroup:be,rootFolders:te,ungroupedSessions:xe,folderActivityStateById:fe,folderSessionsForDeleteById:je}=Tp({group:t,sourceGroupNodes:H,hasSessionSearchQuery:i,normalizedSessionSearchQuery:l,compareSessionNodes:U,activeActivitySessionIds:F,unreadActivitySessionIds:me,inputActivitySessionIds:ue,collectGroupSessions:de}),Ye="project",_e=a.useMemo(()=>{const Ce=new Set;return Gi(H,W,Ce),be.forEach(({nodes:Ue})=>{Gi(Ue,W,Ce)}),Ce},[H,be,W]),De=a.useMemo(()=>{if(!Z)return null;const Ce=gr(H,Z,Ye,!!t.isArchivedBucket);if(Ce)return Ce;for(const{nodes:Ue}of be){const ge=gr(Ue,Z,Ye,!!t.isArchivedBucket);if(ge)return ge}return null},[Z,H,be,t.isArchivedBucket]),Ve=a.useCallback(Ce=>{const Ue=new WeakMap,ge=Oe=>{Ue.set(Oe,Ao(Oe));for(const Ge of Oe.children)ge(Ge)};return Ce.forEach(ge),Ue},[]),ae=a.useMemo(()=>Ve(H),[Ve,H]),Fe=a.useMemo(()=>{const Ce=new WeakMap;return be.forEach(({nodes:Ue})=>{Ue.forEach(ge=>Ce.set(ge,Ao(ge)))}),Ce},[be]),tt=a.useCallback(Ce=>ae.get(Ce)??Fe.get(Ce)??"",[ae,Fe]),xt=a.useCallback(Ce=>({subtreeContainsEditing:_e,menuOpenSessionId:De,nodeStructureKey:tt(Ce)}),[_e,De,tt]),Qe=xe.length,pt=t.isArchivedBucket||i?xe:xe.slice(0,ke),Xe=Qe-pt.length,Ss=!t.isArchivedBucket&&!i&&Qe>ie&&Xe===0,St=t.isArchivedBucket===!0&&!i&&pt.length>=ip,st=t.isArchivedBucket?"archived":"active",Et=St&&pt.some(Ce=>{if(Ce.children.length===0)return!1;const Ue=`project:${st}:${Ce.session.id}`;return I.has(Ue)}),Lt=a.useMemo(()=>de(H),[de,H]);if(i&&!Se&&te.length===0&&xe.length===0)return null;const Yt=!t.isMain&&!!t.branch,jt=t.branch&&Ff(t.branch,t.label)?{label:t.branch,color:null}:null,Ot=X?Kl(H,F,me,ue):null,yt=Ot?s.jsx(Ll,{state:Ot,activeLabel:"Session active",unreadLabel:"Unread updates",inputLabel:"Needs input"}):null,rt=(Ce,Ue)=>{const{folder:ge,scopeKey:Oe,scopeDirectory:Ge,nodes:it}=Ce,kt=je.get(ge.id)??[],ot=i?!1:p.has(ge.id);return s.jsx(Jm,{folderId:ge.id,children:(Bt,ns)=>s.jsx(Vm,{folder:ge,displayName:Ue,sessions:it,isCollapsed:ot,collapsedActivityState:ot?fe.get(ge.id)??null:null,onToggle:()=>x(ge.id),onRename:Ze=>{y(Oe,ge.id,Ze)},onDelete:()=>{if(t.isArchivedBucket){Ms.requestDelete({sessions:kt,mode:"session"});return}if(!h){m(Oe,ge.id);return}const Ze=be.filter(({folder:Dt})=>Dt.parentId===ge.id).length,Rt=it.length;b({scopeKey:Oe,folderId:ge.id,folderName:ge.name,subFolderCount:Ze,sessionCount:Rt})},renderSessionNode:g,getRenderExtras:tt?Ze=>({subtreeContainsEditing:_e,menuOpenSessionId:De,nodeStructureKey:tt(Ze),childRenderExtrasFor:xt}):void 0,groupDirectory:Ge??t.directory,projectId:r,mobileVariant:E,alwaysShowActions:A,isRenaming:z===ge.id,renameDraft:z===ge.id?$:void 0,onRenameDraftChange:Ze=>O(Ze),onRenameSave:()=>{const Ze=$.trim();Ze&&y(Oe,ge.id,Ze),R(null),O("")},onRenameCancel:()=>{R(null),O("")},droppableRef:Bt,isDropTarget:ns,depth:0,onNewSession:()=>{r&&r!==k&&j(r),v("chat"),E&&N(!1),M({selectedProjectId:r,directoryOverride:Ge??t.directory,targetFolderId:ge.id})},hideActions:!1,archivedBucket:t.isArchivedBucket===!0})},ge.id)},dt=()=>{const Ce=new Map;for(const Oe of be){const Ge=Oe.folder.parentId;if(!Ge)continue;const it=Ce.get(Ge);it?it.push(Oe):Ce.set(Ge,[Oe])}const Ue=[],ge=(Oe,Ge)=>{const it=Ge?`${Ge} / ${Oe.folder.name}`:Oe.folder.name;Ue.push(rt(Oe,it)),!(!i&&p.has(Oe.folder.id))&&(Ce.get(Oe.folder.id)??[]).forEach(ot=>ge(ot,it))};return te.forEach(Oe=>ge(Oe,"")),Ue},Vt=A?"pr-7":"pr-2 group-hover/gh:pr-7 group-focus-within/gh:pr-7",us=s.jsxs(Xm,{scopeKey:Le[0]?.scopeKey??ve,hasFolders:be.length>0,onSessionDroppedOnFolder:(Ce,Ue)=>{const ge=be.find(({folder:Ge})=>Ge.id===Ue);if(!ge)return;const Oe=bt.getState();for(const{scopeKey:Ge}of Le)Ge!==ge.scopeKey&&Oe.getSessionFolderId(Ge,Ce)&&Oe.removeSessionFromFolder(Ge,Ce);L(ge.scopeKey,Ue,Ce)},children:[dt(),t.isArchivedBucket?s.jsx(lp,{visibleSessions:pt,shouldVirtualize:St,hasExpandedParent:Et,scrollContainerRef:G,groupDirectory:t.directory,projectId:r,isArchivedBucket:t.isArchivedBucket===!0,renderSessionNode:g,getRenderExtras:Ce=>({subtreeContainsEditing:_e,menuOpenSessionId:De,nodeStructureKey:tt(Ce),childRenderExtrasFor:xt})}):pt.map(Ce=>s.jsx(a.Fragment,{children:g(Ce,0,t.directory,r,t.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:_e,menuOpenSessionId:De,nodeStructureKey:tt(Ce),childRenderExtrasFor:xt})},Ce.session.id)),Qe===0&&be.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(Zt,{icon:"chat-new",onClick:()=>{M({selectedProjectId:r,directoryOverride:t.directory})},children:"New session"}):null,Xe>0?s.jsx(Zt,{icon:"arrow-down-s",onClick:()=>S(n,pt.length),children:Xe===1?"Show 1 more session":`Show ${Xe} more sessions`}):null,Ss?s.jsx(Zt,{icon:"arrow-up-s",onClick:()=>w(n),children:"Show fewer sessions"}):null]});return o?s.jsx("div",{className:"oc-group",children:s.jsx("div",{className:"oc-group-body",children:us})}):s.jsxs("div",{className:"oc-group",children:[s.jsx(Ep,{group:t,groupKey:n,isCollapsed:X,onToggleCollapsedGroup:q,normalizedSessionSearchQuery:l,alwaysShowActions:A,groupHeaderRightPadding:Vt,dragHandleProps:Ae,groupPrColor:Q,groupPrSummary:V,groupActivityIndicator:yt,showBranchSubtitle:Yt,statusLine:jt,allGroupSessions:Lt,projectId:r,activeProjectId:k,setActiveProjectIdOnly:j,setActiveMainTab:v,mobileVariant:E,setSessionSwitcherOpen:N,openNewSessionDraft:M}),X?null:s.jsx("div",{className:"oc-group-body",children:us})]})}const Lp=a.memo(Fp,Mp);function Op(e){const{hideDirectoryControls:t,handleOpenDirectoryDialog:n,onOpenArchive:r,onOpenSettings:o,onOpenInstances:i,instanceLabel:l,onOpenUpdate:c,headerActionIconClass:d,headerActionButtonClass:u,isSessionSearchOpen:f,setIsSessionSearchOpen:p,sessionSearchInputRef:x,sessionSearchQuery:y,setSessionSearchQuery:m,hasSessionSearchQuery:h,searchMatchCount:b,selectionModeEnabled:g,onToggleSelectionMode:S,mobileVariant:w=!1}=e;if(t)return null;const E=_(u,"text-muted-foreground hover:text-foreground",!w&&"hover:bg-transparent");return s.jsx("div",{className:_("select-none flex-shrink-0",w?"px-2":"px-2 py-1"),children:s.jsxs("div",{className:_("flex flex-col",w?"gap-0":"h-auto min-h-8 gap-1"),children:[s.jsxs("div",{className:_("flex items-center justify-between",w?"h-[var(--oc-header-height,56px)] gap-1":"min-h-8 gap-2 px-2"),children:[s.jsxs("div",{className:_("flex min-w-0 items-center",w?"gap-1 overflow-x-auto":"gap-1.5"),"data-no-drawer-swipe":w?"true":void 0,children:[o?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:o,className:E,"aria-label":"Settings",children:s.jsx(P,{name:"settings-3",className:d})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Settings"})})]}):null,!w&&i?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:i,className:E,"aria-label":l?`Servers: ${l}`:"Servers",children:s.jsx(P,{name:"server",className:d})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:l||"Servers"})})]}):null,c?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:c,className:E,"aria-label":"Update",children:s.jsx(P,{name:"download",className:d})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Update"})})]}):null,w?null:s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,className:E,"aria-label":"Add project",children:s.jsx(P,{name:"folder-add",className:d})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Add project"})})]}),w?null:s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:r,className:E,"aria-label":"Archive",children:s.jsx(P,{name:"archive",className:d})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Archive"})})]})]}),s.jsxs("div",{className:_("flex shrink-0 items-center",w?"gap-1":"gap-1.5"),children:[s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:()=>p(A=>!A),className:E,"aria-label":"Search sessions","aria-expanded":f,children:s.jsx(P,{name:"search",className:d})})}),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:S,className:_(E,g&&"bg-interactive-hover text-primary"),"aria-label":g?"Exit selection":"Select sessions","aria-pressed":g,children:s.jsx(P,{name:"checkbox-multiple",className:d})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:g?"Exit selection":"Select sessions"})})]})]})]}),f?s.jsxs("div",{className:_(w?"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:b===1?`${b} match`:`${b} matches`}):s.jsx("span",{})}),s.jsxs("div",{className:"relative",children:[s.jsx(P,{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:x,value:y,onChange:A=>m(A.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:A=>{A.key==="Escape"&&(A.stopPropagation(),h?m(""):p(!1))}}),y.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(P,{name:"close",className:"h-3.5 w-3.5"})}):null]})]}):null]})})}const Kr="0.75rem";function Bp(e){const t=ce(o=>o.toggleSidebar),n=ce(o=>o.shortcutOverrides),r=Ho(dr("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, ${Kr})`}}),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, ${Kr})))`}}),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:_("group flex min-w-0 flex-1 items-center gap-1.5 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"),style:{paddingLeft:`max(3px, calc(${Lf} - max(var(--oc-titlebar-left-inset, ${Kr}), var(--oc-titlebar-overlay-width, 0px))))`},children:[s.jsx(P,{name:"chat-new",className:_(nr,"text-current")}),s.jsx("span",{className:dl,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(P,{name:"layout-left",className:"size-4"})})}),s.jsx(We,{children:s.jsx("p",{children:`Hide sessions (${r})`})})]}):null]})]})}function Ar({...e}){return s.jsx(Ca,{...e})}function Nr({...e}){return s.jsx(Aa,{...e})}function Ir({className:e,positionerClassName:t,children:n,style:r,...o}){return s.jsx(Na,{children:s.jsx(Ia,{className:_("app-region-no-drag z-50",t),children:s.jsx(Ea,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...r},className:_(Wa,e),...o,children:n})})})}function Ps({className:e,...t}){return s.jsx(Ra,{className:_(Ga,e),...t})}function Zl({className:e,...t}){return s.jsx(Da,{className:_(Ha,e),...t})}const ec=500,_p=({projectId:e,worktree:t,isSelected:n,hasActive:r,onSelect:o,onClose:i,mobileVariant:l=!1})=>{const[c,d]=a.useState(!1),u=a.useRef(null),f=t.branch||(t.detached?"Detached HEAD":t.name),p=a.useCallback(()=>{u.current!==null&&(window.clearTimeout(u.current),u.current=null)},[]);a.useEffect(()=>()=>p(),[p]);const x=a.useCallback(()=>{p(),u.current=window.setTimeout(()=>{u.current=null,d(!0)},ec)},[p]);return s.jsxs(Ar,{open:c,onOpenChange:d,children:[s.jsxs(Nr,{render:s.jsx("button",{type:"button",onClick:()=>{c||o()},onTouchStart:x,onTouchMove:p,onTouchEnd:p,onTouchCancel:p,style:{touchAction:"manipulation"},className:_(yr(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(P,{name:"git-branch",className:_(Fs(l),"text-muted-foreground")}),t.branch?s.jsx(qa,{value:f,showTitle:!1,className:"typography-ui-label font-normal"}):s.jsx("span",{className:an(l),children:f})]}),s.jsx("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:r?s.jsx(ys,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null})]}),s.jsx(Ir,{className:"min-w-[160px]",children:s.jsxs(Ps,{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(P,{name:"close",className:"mr-2 h-3.5 w-3.5"}),s.jsx("span",{children:"Close worktree"})]})})]})},yr=(e,t)=>_("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"),Up=({project:e,label:t,isSelected:n,hasActive:r,hasWorktrees:o,worktreeError:i,isExpanded:l,canDrag:c,onSelect:d,onOpenProjectEditDialog:u,onRemoveProject:f,mobileVariant:p=!1})=>{const{listeners:x,setNodeRef:y,transform:m,transition:h,isDragging:b}=$o({id:e.id,disabled:!c}),[g,S]=a.useState(!1),w=a.useRef(null),E=a.useCallback(()=>{w.current!==null&&(window.clearTimeout(w.current),w.current=null)},[]);a.useEffect(()=>()=>E(),[E]);const A=a.useCallback(()=>{E(),w.current=window.setTimeout(()=>{w.current=null,S(!0)},ec)},[E]);return s.jsx("div",{ref:y,style:{transform:Ko.Translate.toString(m),transition:h},className:_(b&&"opacity-60"),children:s.jsxs(Ar,{open:g,onOpenChange:S,children:[s.jsxs(Nr,{render:s.jsx("button",{type:"button",onClick:()=>{g||d()},onTouchStart:A,onTouchMove:E,onTouchEnd:E,onTouchCancel:E,style:{touchAction:"manipulation"},className:yr(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:_("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?x:{},children:s.jsx(Go,{directory:e.normalizedPath,label:t,className:Fs(p)})}),s.jsx("span",{className:an(p),children:t})]}),s.jsxs("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:[r?s.jsx(ys,{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(P,{name:"error-warning",className:"size-4 text-[var(--status-warning)]"})}):null,o?s.jsx(P,{name:l?"arrow-down-s":"arrow-right-s",className:"size-4 text-muted-foreground"}):null]})]}),s.jsxs(Ir,{className:"min-w-[160px]",children:[s.jsxs(Ps,{onClick:()=>u(e.id),children:[s.jsx(P,{name:"edit",className:"mr-2 h-3.5 w-3.5"}),s.jsx("span",{children:"Edit folder"})]}),s.jsx(Zl,{}),s.jsxs(Ps,{onClick:()=>f(e.id),className:"text-destructive focus:text-destructive",children:[s.jsx(P,{name:"close",className:"mr-2 h-3.5 w-3.5"}),s.jsx("span",{children:"Close folder"})]})]})]})})},zp=({projects:e,selectedProjectId:t,selectedWorktreePath:n=null,worktreesByProject:r=new Map,worktreeErrorsByProject:o=new Map,onSelectProject:i,onSelectWorktree:l,onCloseWorktree:c,onOpenDirectoryDialog:d,onOpenProjectEditDialog:u,onRemoveProject:f,hasActiveSessionByProject:p,activeDirectoriesByProject:x,homeDirectory:y,className:m,mobileVariant:h=!1})=>{const b=t===null,g=ct(A=>A.reorderProjects),S=e.length>1,w=_o(Fn(Fa,{activationConstraint:{distance:8}}),Fn(Ta,{activationConstraint:{delay:200,tolerance:6}})),E=a.useCallback(A=>{const{active:k,over:j}=A;if(!j||k.id===j.id)return;const v=ct.getState().projects,N=v.findIndex(L=>L.id===k.id),M=v.findIndex(L=>L.id===j.id);N<0||M<0||g(N,M)},[g]);return s.jsxs("div",{className:_("select-none px-2 pt-1 pb-2 border-b border-border/40 space-y-0.5",m),children:[s.jsx("button",{type:"button",onClick:()=>i(null),className:yr(h,b),"aria-pressed":b,children:s.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[s.jsx(P,{name:"chat-history",className:Fs(h)}),s.jsx("span",{className:an(h),children:"All sessions"})]})}),s.jsx(Uo,{sensors:w,collisionDetection:zo,onDragEnd:E,children:s.jsx(Pa,{items:e.map(A=>A.id),strategy:Ma,children:e.map(A=>{const k=t===A.id,j=k&&!n,v=r.get(A.normalizedPath)??[],N=qo(A.label?.trim()||On(A.normalizedPath,y)||A.normalizedPath),M=x?.get(A.id),L=Ee(A.normalizedPath)?.toLowerCase()??"",K=L?M?.has(L)??!1:!1,z=(M?.size??0)>0,$=p?.(A.id)??!1,O=x?k?K:z:$;return s.jsxs(a.Fragment,{children:[s.jsx(Up,{project:A,label:N,isSelected:j,hasActive:O,hasWorktrees:v.length>0,worktreeError:o.get(A.normalizedPath),isExpanded:k,canDrag:S,onSelect:()=>i(A.id),onOpenProjectEditDialog:u,onRemoveProject:f,mobileVariant:h}),k?v.map(R=>{const D=n===R.path,I=Ee(R.path)?.toLowerCase()??"",T=I?M?.has(I)??!1:!1,W=x?T:!1;return s.jsx(_p,{projectId:A.id,worktree:R,isSelected:D,hasActive:W,onSelect:()=>l?.(A.id,R.path),onClose:c,mobileVariant:h},R.path)}):null]},A.id)})})}),s.jsxs("button",{type:"button",onClick:d,className:yr(h,!1),children:[s.jsx(P,{name:"add",className:Fs(h)}),s.jsx("span",{className:an(h),children:"Add folder"})]})]})},Wr="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 $p({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:Wr,"aria-label":"Settings",children:s.jsx(P,{name:"settings-3",className:"size-4"})})}),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:Wr,"aria-label":"Shortcuts",children:s.jsx(P,{name:"command",className:"size-4"})})}),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:Wr,"aria-label":"About PiChamber",children:s.jsx(P,{name:"information",className:"size-4"})})}),s.jsx(We,{side:"top",sideOffset:4,children:s.jsx("p",{children:"About PiChamber"})})]})]}):null,i?s.jsx(Ne,{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 tc=({projectLabel:e,projectPath:t=null,mobileVariant:n=!1})=>{const r=Fs(n),o=an(n);return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:_("inline-flex shrink-0 items-center justify-center",r),children:t?s.jsx(Go,{directory:t,label:e,className:r}):s.jsx(P,{name:"folder",className:_(r,"text-muted-foreground/80")})}),s.jsx("span",{className:_(o,"text-foreground"),children:e})]})},sc=({isCollapsed:e,mobileVariant:t=!1,className:n})=>s.jsx("span",{className:_("ml-auto inline-flex shrink-0 items-center text-muted-foreground",n),children:s.jsx(P,{name:e?"arrow-right-s":"arrow-down-s",className:Fs(t)})}),Kp=({id:e,disabled:t=!1,projectLabel:n,projectPath:r=null,projectDescription:o,isCollapsed:i,hideDirectoryControls:l,mobileVariant:c,alwaysShowActions:d,stickyHeader:u=!1,onToggle:f,onNewSession:p,onRenameStart:x,onClose:y,children:m,showCreateButtons:h=!0,hideHeader:b=!1,openSidebarMenuKey:g,setOpenSidebarMenuKey:S,statusIndicator:w=null})=>{const{listeners:E,setNodeRef:A,transform:k,transition:j,isDragging:v}=$o({id:e,disabled:t}),N=a.useRef(!1),M=`project:${e}`,L=g===M,[K,z]=a.useState(!1),$=u&&!i,O=a.useCallback(F=>{F&&z(!1),S(F?M:null)},[M,S]),R=F=>s.jsxs(s.Fragment,{children:[h&&!l&&p&&s.jsxs(F,{onClick:p,children:[s.jsx(P,{name:"add",className:"mr-1.5 h-4 w-4"}),"New session"]}),s.jsxs(F,{onClick:x,children:[s.jsx(P,{name:"pencil-ai",className:"mr-1.5 h-4 w-4"}),"Edit folder"]}),s.jsxs(F,{onClick:y,className:"text-destructive focus:text-destructive",children:[s.jsx(P,{name:"close",className:"mr-1.5 h-4 w-4"}),"Close folder"]})]}),D=a.useCallback(F=>{F.stopPropagation()},[]),I=a.useCallback(F=>{F.stopPropagation()},[]),T=a.useCallback(F=>{F.stopPropagation()},[]),W=a.useCallback(F=>{(F.button===2||F.button===0&&F.ctrlKey)&&(N.current=!0)},[]),Z=a.useCallback(F=>{if(F.currentTarget.blur(),N.current){N.current=!1;return}f()},[f]);return s.jsxs("div",{ref:A,style:{transform:Ko.Translate.toString(k),transition:j},className:_("relative",v&&"opacity-60"),children:[b?null:s.jsxs(Ar,{open:K,onOpenChange:z,children:[s.jsxs(Nr,{render:s.jsx("div",{className:_("text-left group/project select-none",$&&"oc-sidebar-sticky-header sticky top-0 z-20 bg-sidebar before:pointer-events-none before:absolute before:inset-x-0 before:bottom-full before:h-2 before:bg-sidebar"),"data-sidebar-sticky-header":$?"true":void 0,onContextMenu:F=>{l||v||(F.preventDefault(),z(!0))}}),children:[s.jsxs("div",{"data-sidebar-tree-row":"",className:"relative flex items-center gap-1 py-1.5 px-3 rounded-xl transition-colors hover:bg-interactive-hover",children:[s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsxs("button",{type:"button","aria-expanded":!i,style:{touchAction:"manipulation"},onMouseDown:W,onClick:Z,...E,className:_(Cr,"flex-1 min-w-0 flex items-center text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 rounded-md cursor-grab active:cursor-grabbing"),children:[s.jsx(tc,{id:e,projectLabel:n,projectPath:r,mobileVariant:c}),w?s.jsx("span",{className:"ml-1 inline-flex flex-shrink-0 items-center",children:w}):null,s.jsx(sc,{isCollapsed:i,mobileVariant:c,className:_("transition-[padding]",d?"pl-16":"pl-2 group-hover/project:pl-14 group-focus-within/project:pl-14")})]})}),s.jsx(We,{side:"right",sideOffset:8,children:o})]}),s.jsx("div",{className:"absolute right-[calc(3.25rem*var(--padding-scale,1))] top-1/2 z-10 -translate-y-1/2",children:l?null:s.jsxs(Gt,{open:L,onOpenChange:O,children:[s.jsx(Ht,{asChild:!0,children:s.jsx("button",{type:"button",className:_("inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 hover:text-foreground",L?"opacity-100 pointer-events-auto":d?"opacity-100":"opacity-0 pointer-events-none group-hover/project:opacity-100 group-hover/project:pointer-events-auto group-focus-within/project:opacity-100 group-focus-within/project:pointer-events-auto"),"aria-label":"Folder menu",onPointerDown:I,onMouseDown:T,onClick:D,children:s.jsx(P,{name:"more-2",className:"size-4"})})}),s.jsx(qt,{align:"end",className:"min-w-[180px]",children:R(ht)})]})}),h&&!l&&p?s.jsx("div",{className:"absolute right-7 top-1/2 z-10 -translate-y-1/2",children:s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:F=>{F.stopPropagation(),p()},className:_("inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",d?"opacity-100":"opacity-0 pointer-events-none group-hover/project:opacity-100 group-hover/project:pointer-events-auto group-focus-within/project:opacity-100 group-focus-within/project:pointer-events-auto"),"aria-label":"New session",children:s.jsx(P,{name:"add",className:"h-4 w-4"})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"New session"})})]})}):null]}),$?s.jsx("span",{"aria-hidden":!0,className:"oc-sidebar-sticky-header-fade pointer-events-none absolute inset-x-0 top-full h-4 bg-gradient-to-b from-sidebar to-transparent"}):null]}),s.jsx(Ir,{className:"min-w-[180px]",children:R(Ps)})]}),m]})},Wp=({id:e,disabled:t=!1,children:n})=>{const{listeners:r,setNodeRef:o,setActivatorNodeRef:i,transform:l,transition:c,isDragging:d}=$o({id:e,disabled:t}),u=a.useMemo(()=>({listeners:r,setActivatorNodeRef:i}),[r,i]);return s.jsx("div",{ref:o,style:{transform:Ko.Transform.toString(l),transition:c},className:_("space-y-0.5 rounded-md",d&&"opacity-50"),children:typeof n=="function"?n(u):n})};a.memo(Wp);const sa="pt-0.5 pb-1",Gp=({sections:e,homeSection:t,homeDirectory:n,collapsedProjects:r,toggleProject:o,hasSessionSearchQuery:i,activeProjectId:l,hideDirectoryControls:c,mobileVariant:d,alwaysShowActions:u,isInlineEditing:f,stickyFolderHeaders:p,renderGroupSessions:x,renderSessionNode:y,getOrderedGroups:m,renderProjectStatusIndicator:h,scrollContainerRef:b,setActiveProjectIdOnly:g,setActiveMainTab:S,setSessionSwitcherOpen:w,openNewSessionDraft:E,openProjectEditDialog:A,removeProject:k,reorderProjects:j,openSidebarMenuKey:v,setOpenSidebarMenuKey:N,onOpenDirectoryDialog:M,emptyState:L,searchEmptyState:K})=>{const z=_o(Fn(Fa,{activationConstraint:{distance:8}}),Fn(Ta,{activationConstraint:{delay:200,tolerance:6}})),$=e.length>1&&!i&&!f,O=a.useCallback(F=>{if(f||i)return;const{active:me,over:q}=F;if(!q||me.id===q.id)return;const Ae=ct.getState().projects,Ie=Ae.findIndex(U=>U.id===me.id),G=Ae.findIndex(U=>U.id===q.id);Ie<0||G<0||Ie===G||j(Ie,G)},[f,i,j]),[R,D]=a.useState(5);a.useEffect(()=>{D(5)},[i]);const I=a.useMemo(()=>t?t.groups.filter(F=>!F.isArchivedBucket).flatMap(F=>F.sessions):[],[t]),T=i?I:I.slice(0,R),W=I.length-T.length,Z=i?!1:r.has("__home__");return e.length===0&&!t?i?K:L:s.jsxs("div",{className:"space-y-2",children:[s.jsx(Uo,{sensors:z,collisionDetection:zo,onDragEnd:O,children:s.jsx(Pa,{items:e.map(F=>F.project.id),strategy:Ma,children:e.map(F=>{const me=F.project,q=me.id,Ae=ul(me,n),Ie=uo(me.normalizedPath,n),G=i?!1:r.has(q),U=G?[]:m(q,F.groups),Y=G?null:U.find(se=>se.isMain)??null,X=G?[]:Y?U.filter(se=>se.id!==Y.id):U;return s.jsx(Kp,{id:q,disabled:!$,projectLabel:Ae,projectPath:me.normalizedPath,projectDescription:Ie,isCollapsed:G,hideDirectoryControls:c,mobileVariant:d,alwaysShowActions:u,stickyHeader:p,statusIndicator:G?h?.(q,F.groups):null,onToggle:()=>o(q),onNewSession:()=>{q!==l&&g(q),S("chat"),d&&w(!1),E({selectedProjectId:q,directoryOverride:me.normalizedPath})},onRenameStart:()=>A(q),onClose:()=>k(q),openSidebarMenuKey:v,setOpenSidebarMenuKey:N,children:G?null:s.jsxs("div",{className:sa,children:[Y?x(Y,`${q}:${Y.id}`,q,!0,null,void 0,b):null,X.map(se=>{const we=`${q}:${se.id}`,pe=U.length===1;return s.jsx(a.Fragment,{children:x(se,we,q,pe,null,void 0,b)},se.id)})]})},q)})})}),t?s.jsxs("div",{children:[s.jsx("div",{"data-sidebar-tree-row":"",className:"relative flex items-center gap-1 py-1.5 px-3 rounded-xl transition-colors hover:bg-interactive-hover",children:s.jsxs("button",{type:"button","aria-expanded":!Z,style:{touchAction:"manipulation"},onClick:()=>o("__home__"),className:`${Cr} flex-1 min-w-0 flex items-center text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 rounded-md`,children:[s.jsx(tc,{id:"__home__",projectLabel:"No folder",mobileVariant:d}),s.jsx(sc,{isCollapsed:Z,mobileVariant:d})]})}),Z?null:s.jsxs("div",{className:sa,children:[T.map(F=>s.jsx(a.Fragment,{children:y?.(F,0,F.session.directory??"~","__home__",!1,{globalSession:!0},"project")},F.session.id)),!i&&W>0?s.jsx(Zt,{icon:"arrow-down-s",mobileVariant:d,onClick:()=>D(F=>F+7),children:W===1?"Show 1 more session":`Show ${W} more sessions`}):null,!i&&R>5&&I.length>5?s.jsx(Zt,{icon:"arrow-up-s",mobileVariant:d,onClick:()=>D(5),children:"Show fewer sessions"}):null]})]}):null,!c&&M?s.jsx(Zt,{icon:"add",mobileVariant:d,onClick:M,children:"Add folder"}):null]})},Hp=a.memo(Gp);function qp(e){Wt("ui.sidebar_projects_list.render");const t=e.viewMode??"workspace",n=t==="timeline",r=a.useRef(new Map),o=a.useRef(e.getOrderedGroups);o.current!==e.getOrderedGroups&&(o.current=e.getOrderedGroups,r.current.clear());const i=(b,g)=>{const S=r.current,w=S.get(b);if(w&&w.groups===g)return w.ordered;const E=e.getOrderedGroups(b,g);if(S.set(b,{groups:g,ordered:E}),S.size>256){const A=S.keys().next().value;A!==void 0&&S.delete(A)}return E},l=a.useRef(null),c=!!(e.isAllFoldersView||n),d=a.useMemo(()=>{if(!c)return[];const b=[],g=e.allFoldersOnlySection?[e.allFoldersOnlySection,...e.sectionsForRender]:e.sectionsForRender;for(const S of g){const w=ul(S.project,e.homeDirectory);for(const E of S.groups)if(!E.isArchivedBucket)for(const A of E.sessions){const k=!!e.pinnedSessionIds?.has(A.session.id),j=A.session.time?.updated||A.session.time?.created||0;b.push({node:A,project:S.project,projectLabel:w,isPinned:k,timestamp:j,globalSession:S===e.allFoldersOnlySection})}}return b.sort((S,w)=>S.isPinned!==w.isPinned?S.isPinned?-1:1:w.timestamp-S.timestamp),b},[e.allFoldersOnlySection,c,e.sectionsForRender,e.homeDirectory,e.pinnedSessionIds]),[u,f]=a.useState(30);a.useEffect(()=>{f(30)},[e.hasSessionSearchQuery]);const p=a.useMemo(()=>d.slice(0,u),[d,u]),x=a.useMemo(()=>e.timelineBoundaries??Co(Date.now(),1),[e.timelineBoundaries]),y=a.useMemo(()=>n?xm(p,{getTimestamp:b=>b.timestamp,isPinned:b=>b.isPinned,boundaries:x}):[],[n,p,x]);if(e.sharedSessionsOnly)return s.jsx(Is,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:_("pt-2 pb-1",e.mobileVariant&&"pb-32"),children:s.jsxs("div",{className:"space-y-1 px-2",children:[e.topContent,e.hasSharedSessions?null:e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState]})});const m=(e.isAllFoldersView||t==="timeline"||t==="folder")&&!!e.allFoldersOnlySection;if(e.projectSections.length===0&&!m)return s.jsx(Is,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:_("pt-2 pb-1",e.mobileVariant&&"pb-32"),children:s.jsxs("div",{className:"space-y-1 px-2",children:[e.topContent,e.emptyState]})});if(e.sectionsForRender.length===0&&!m)return s.jsx(Is,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:_("pt-2 pb-1",e.mobileVariant&&"pb-32"),children:s.jsx("div",{className:"space-y-1 px-2",children:e.searchEmptyState})});const h=()=>{const b=d.length-p.length;return s.jsxs(s.Fragment,{children:[b>0?s.jsx(Zt,{icon:"arrow-down-s",onClick:()=>f(g=>g+30),children:b===1?"Show 1 more session":`Show ${b} more sessions`}):null,u>30&&d.length>30?s.jsx(Zt,{icon:"arrow-up-s",onClick:()=>f(30),children:"Show fewer sessions"}):null]})};return s.jsx("div",{className:"relative flex min-h-0 flex-1",children:s.jsx(Is,{ref:l,useScrollShadow:!0,hideTopScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:_("oc-sidebar-scroller pt-2 pb-1 [overflow-anchor:none]",e.mobileVariant&&"pb-32"),children:s.jsxs("div",{className:"space-y-1 px-2",children:[e.topContent,e.showOnlyMainWorkspace?s.jsx("div",{className:"space-y-[0.6rem]",children:(()=>{const b=e.sectionsForRender.find(E=>E.project.id===e.activeProjectId)??e.sectionsForRender[0];if(!b)return e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState;const g=b.groups.find(E=>E.isMain&&E.sessions.length>0)??b.groups.find(E=>E.sessions.length>0)??b.groups.find(E=>E.isMain)??b.groups[0];if(!g)return s.jsx(Zt,{icon:"chat-new",onClick:()=>e.openNewSessionDraft({selectedProjectId:b.project.id,directoryOverride:b.project.normalizedPath}),children:"New session"});const S=b.groups.find(E=>E.isArchivedBucket);return[g,...S&&S.id!==g.id?[S]:[]].map(E=>{const A=`${b.project.id}:${E.id}`,k=E.id===g.id;return s.jsx(a.Fragment,{children:e.renderGroupSessions(E,A,b.project.id,k,null,!0,l)},A)})})()}):t==="folder"?s.jsx(Qo.Provider,{value:"tree",children:s.jsx(Hp,{sections:e.sectionsForRender,homeSection:e.allFoldersOnlySection,homeDirectory:e.homeDirectory,collapsedProjects:e.collapsedProjects,toggleProject:e.toggleProject,hasSessionSearchQuery:e.hasSessionSearchQuery,activeProjectId:e.activeProjectId,hideDirectoryControls:e.hideDirectoryControls,mobileVariant:e.mobileVariant,alwaysShowActions:e.alwaysShowActions,isInlineEditing:e.isInlineEditing,stickyFolderHeaders:e.stickyFolderHeaders,renderGroupSessions:e.renderGroupSessions,renderSessionNode:e.renderSessionNode,getOrderedGroups:i,renderProjectStatusIndicator:e.renderProjectStatusIndicator,scrollContainerRef:l,setActiveProjectIdOnly:e.setActiveProjectIdOnly,setActiveMainTab:e.setActiveMainTab,setSessionSwitcherOpen:e.setSessionSwitcherOpen,openNewSessionDraft:e.openNewSessionDraft,openProjectEditDialog:e.openProjectEditDialog,removeProject:e.removeProject,reorderProjects:e.reorderProjects,openSidebarMenuKey:e.openSidebarMenuKey,setOpenSidebarMenuKey:e.setOpenSidebarMenuKey,onOpenDirectoryDialog:e.onOpenDirectoryDialog,emptyState:e.emptyState,searchEmptyState:e.searchEmptyState})}):t==="timeline"&&e.renderSessionNode?s.jsx("div",{children:d.length===0?e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState:s.jsxs(s.Fragment,{children:[y.map((b,g)=>{const S=pm[b.id];return s.jsxs("section",{"aria-label":S,"data-timeline-bucket":b.id,children:[s.jsx("div",{role:"heading","aria-level":3,className:_("select-none px-3 pb-1 text-xs leading-4 font-medium text-muted-foreground",g===0?"pt-1":"pt-3"),children:S}),b.items.map(({node:w,project:E,projectLabel:A,globalSession:k})=>{const j=w.session.directory??E.normalizedPath;return s.jsx(a.Fragment,{children:e.renderSessionNode(w,0,j,E.id,!1,{projectLabel:A,showFolderLabel:!0,globalSession:k},"project")},w.session.id)})]},b.id)}),h()]})}):e.isAllFoldersView&&e.renderSessionNode?s.jsx("div",{children:d.length===0?e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState:s.jsxs(s.Fragment,{children:[p.map(({node:b,project:g,projectLabel:S,globalSession:w})=>{const E=b.session.directory??g.normalizedPath;return s.jsx(a.Fragment,{children:e.renderSessionNode(b,0,E,g.id,!1,{projectLabel:S,showFolderLabel:!0,globalSession:w},"project")},b.session.id)}),h()]})}):s.jsx("div",{children:e.sectionsForRender.map(b=>{const g=b.project.id,S=i(g,b.groups),w=S.find(A=>A.isMain)??null,E=w?S.filter(A=>A.id!==w.id):S;return s.jsxs("div",{children:[w?e.renderGroupSessions(w,`${g}:${w.id}`,g,!0,null,void 0,l):null,E.map(A=>{const k=`${g}:${A.id}`,j=S.length===1;return s.jsx(a.Fragment,{children:e.renderGroupSessions(A,k,g,j,null,void 0,l)},A.id)})]},g)})})]})})})}const Yp=a.memo(qp);let To=!1;const Fo=new Set;let na=!1;function Vp(){for(const e of Fo)e()}function ei(e){To!==e&&(To=e,Vp())}function Qp(e){e.key==="Shift"&&ei(!0)}function Jp(e){e.key==="Shift"&&ei(!1)}function Xp(){ei(!1)}function Zp(){na||typeof window>"u"||(na=!0,window.addEventListener("keydown",Qp),window.addEventListener("keyup",Jp),window.addEventListener("blur",Xp))}function eg(e){return Zp(),Fo.add(e),()=>{Fo.delete(e)}}function tg(){return To}function sg(){return!1}function ng(){return Re.useSyncExternalStore(eg,tg,sg)}const rg=a.memo(function({archiveLabel:t,deleteLabel:n,buttonSizeClass:r,iconSizeClass:o,onPointerDown:i,onMouseDown:l,onArchive:c,onDelete:d}){const u=ng(),f=u?n:t,p=x=>{if(u||x.shiftKey){d(x);return}c(x)};return s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",className:_("inline-flex items-center justify-center rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",u?"text-destructive hover:text-destructive":"text-muted-foreground hover:text-foreground",r),"aria-label":f,onPointerDown:i,onMouseDown:l,onClick:p,onKeyDown:x=>x.stopPropagation(),children:s.jsx(P,{name:u?"delete-bin":"archive",className:o})})}),s.jsx(We,{side:"left",sideOffset:8,children:f})]})}),og=a.memo(function({open:t,onOpenChange:n,descendantCount:r,exportIncludeSubtasks:o,setExportIncludeSubtasks:i,onExport:l}){return s.jsx(ts,{open:t,onOpenChange:n,children:s.jsxs(ss,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(ws,{children:[s.jsx(ds,{children:"Export Markdown"}),s.jsx(vs,{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(Ls,{children:[s.jsx(Ne,{type:"button",onClick:()=>n(!1),variant:"outline",size:"sm",children:"Cancel"}),s.jsx(Ne,{type:"button",onClick:()=>{n(!1),l(o)},size:"sm",children:"Export"})]})]})})});function ig(e,t){const{session:n,sessionTitle:r,sessionDirectory:o,isPinnedSession:i,archivedBucket:l,isElectron:c,pendingRenameRef:d,handleCopySessionId:u,togglePinnedSession:f,handleExportSession:p,handleOpenMiniChatWindow:x,handleDeleteSession:y,handleRestoreSession:m}=e,{Item:h,Separator:b}=t;return s.jsxs(s.Fragment,{children:[s.jsxs(h,{onClick:()=>{d.current={id:n.id,title:r}},className:"[&>svg]:mr-1",children:[s.jsx(P,{name:"pencil-ai",className:"mr-1 h-4 w-4"}),"Rename"]}),s.jsxs(h,{onClick:()=>u(n.id),className:"[&>svg]:mr-1",children:[s.jsx(P,{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(P,{name:"unpin",className:"mr-1 h-4 w-4"}):s.jsx(P,{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(P,{name:"download",className:"mr-1 h-4 w-4"}),"Export Markdown"]}),c?s.jsxs(h,{disabled:!o,onClick:x,className:"[&>svg]:mr-1",children:[s.jsx(P,{name:"window",className:"mr-1 h-4 w-4"}),s.jsx("span",{className:"truncate",children:"Open in Mini Chat Window"})]}):null,s.jsx(b,{}),l?null:s.jsxs(h,{className:"[&>svg]:mr-1",onClick:()=>y(n,{archivedBucket:l}),children:[s.jsx(P,{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(P,{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:()=>y(n,{archivedBucket:l,hardDelete:!0}),children:[s.jsx(P,{name:"delete-bin",className:"mr-1 h-4 w-4"}),"Delete"]})]})}function ag(e){const{renamingFolderId:t,editingIdRef:n}=e;return s.jsx(Na,{children:s.jsx(Ia,{className:"app-region-no-drag z-50",children:s.jsx(Ea,{"data-slot":"dropdown-menu-content",finalFocus:()=>!(t||n.current),style:{color:"var(--surface-elevated-foreground)"},className:_(Wa,"min-w-[180px]"),children:ig(e,{Item:({className:r,...o})=>s.jsx(Ra,{className:_(Ga,r),...o}),Separator:({className:r,...o})=>s.jsx(Da,{className:_(Ha,r),...o})})})})})}const Gr=new WeakMap,lg=e=>{if(typeof window>"u")return;const t=e.closest("[data-session-row]"),n=t?.closest(".overlay-scrollbar-container");if(!t||!n)return;Gr.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,Gr.delete(n),n.removeEventListener("wheel",c),n.removeEventListener("touchstart",c)},d=()=>{if(i||!t.isConnected||!n.isConnected){c();return}const u=t.getBoundingClientRect().top-r;if(Math.abs(u)>.5&&(n.scrollTop+=u,Wt("ui.sidebar.selection_scroll_anchor_adjustment")),o-=1,o<=0){c();return}l=window.requestAnimationFrame(d)};n.addEventListener("wheel",c,{passive:!0}),n.addEventListener("touchstart",c,{passive:!0}),Gr.set(n,c),l=window.requestAnimationFrame(d)};function cg(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 dg(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 ug(e){const t=e.info.role==="user"?"User":"Assistant",n=cg(e.info.time?.created),r=dg(e),o=n&&r?`${n} (${r})`:n||r;return o?`**${t}**
|
|
21
|
+
|
|
22
|
+
*${o}*`:`**${t}**`}function fg(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join("")}function nc(e){const t=ug(e),n=fg(e.parts).trim();return n?`${t}
|
|
23
|
+
|
|
24
|
+
${n}`:""}function rc(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(nc).filter(Boolean).join(`
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
`),l=[o+i];for(const c of e.children)l.push(rc(c,t+1));return l.join(`
|
|
33
|
+
|
|
34
|
+
---
|
|
35
|
+
|
|
36
|
+
`)}function oc(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(nc).filter(Boolean).join(`
|
|
43
|
+
|
|
44
|
+
---
|
|
45
|
+
|
|
46
|
+
`);let c=i+l;if(n&&n.length>0){const d=n.map(u=>rc(u,1)).join(`
|
|
47
|
+
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
`);c+=`
|
|
51
|
+
|
|
52
|
+
---
|
|
53
|
+
|
|
54
|
+
`+d}return c}function ic(e,t){$f({filename:t,mimeType:"text/markdown;charset=utf-8",data:e}).catch(n=>console.warn("[export] Markdown save failed",n))}async function ac(e,t){const n=await uf(t,e);return n||null}async function hg(e){const t=nl()?.files;if(t?.revealPath)try{return!!(await t.revealPath(e))?.success}catch{return!1}return await ff(e)?!0:rl(e)}function mg(){return hf()}function lc(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 wr=e=>{const t=[],n=r=>{r.children.forEach(o=>{t.push(o.session.id),n(o)})};return n(e),t};function pg(e,t){const[n,r]=a.useState(!1),[o,i]=a.useState(!0),l=e.session,c=a.useMemo(()=>wr(e).length,[e]),d=a.useCallback(async x=>{const y=[];let m=0;for(const h of x)try{if(!t)throw new Error("Session directory is required for export");const b=[],g=h.session.title||"Untitled Sub-agent",S=typeof h.session.agent=="string"?h.session.agent:void 0,w=await d(h.children);m+=w.skipped,y.push({title:g,agent:S,records:b,children:w.children})}catch{m+=wr(h).length+1}return{children:y,skipped:m}},[t]),u=a.useCallback(x=>{x<=0||oe.warning(x===1?`Exported session, but skipped ${x} sub-agent task that could not be loaded.`:`Exported session, but skipped ${x} sub-agent tasks that could not be loaded.`)},[]),f=a.useCallback(async x=>{if(!t){oe.error("Nothing to export");return}const y=[];if(y.length===0){oe.error("Nothing to export");return}let m,h=0;if(x&&e.children.length>0){const w=await d(e.children);m=w.children,h=w.skipped}const b=oc(y,l.title??null,m),g=lc(l.title??null),S=await ac(b,g);if(S){oe.success("Session exported",{action:{label:mg(),onClick:()=>{hg(S).then(w=>{w||oe.error("Failed to reveal path")})}}}),u(h);return}ic(b,g),oe.success("Session exported"),u(h)},[d,e.children,l.title,t,u]),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 gg=(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},ft=Bs()((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,d=i.anchorId;r!==null&&i.scopeKey!==null&&r!==i.scopeKey?(l.clear(),c=r,d=null):c===null&&r!==null&&(c=r);const f=o&&o.length>0?[n,...o]:[n];if(l.has(n)){for(const x of f)l.delete(x);d===n&&(d=null)}else{for(const x of f)l.add(x);d=n}l.size===0?e({selectedIds:l,scopeKey:null,anchorId:null}):e({selectedIds:l,scopeKey:c,anchorId:d})},setRange:(n,r,o,i,l)=>{const c=t();if(o.length===0)return;const d=n&&o.includes(n)?n:o[0],u=o.indexOf(d),f=o.indexOf(r);if(u<0||f<0)return;const[p,x]=u<=f?[u,f]:[f,u],y=o.slice(p,x+1),m=gg(y,l),b=i!==null&&c.scopeKey!==null&&i!==c.scopeKey?new Set:new Set(c.selectedIds);for(const g of m)b.add(g);e({selectedIds:b,scopeKey:i??c.scopeKey,anchorId:d})},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}))}})),ra=e=>Ee(e.session.directory??null),bg=(e,t)=>(e?.projectLabel??null)===(t?.projectLabel??null)&&(e?.branchLabel??null)===(t?.branchLabel??null)&&(e?.showFolderLabel??!1)===(t?.showFolderLabel??!1),xg=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},Zn=e=>e.menuOpenSessionId??xg(e),er=(e,t,n)=>t?n.has(e.node.session.id)?!0:ls(e.node,t):!1,Lo=(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(Lo(e.children[l],t.children[l],n,r,o))return!0;return!1},yg=(e,t)=>{if(e.hasSessionSearchQuery||t.hasSessionSearchQuery)return!1;const n=e.archivedBucket?"archived":"active",r=t.archivedBucket?"archived":"active";return Lo(e.node,t.node,e.expandedParents,t.expandedParents,o=>`${e.renderContext??"project"}:${n}:${o.session.id}`)||Lo(e.node,t.node,e.expandedParents,t.expandedParents,o=>`${t.renderContext??"project"}:${r}:${o.session.id}`)},wg=(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||ra(e.node)!==ra(t.node)||!bg(e.secondaryMeta,t.secondaryMeta)||e.pinnedSessionIds!==t.pinnedSessionIds&&Bl(e.node,t.node,e.pinnedSessionIds,t.pinnedSessionIds,e.groupDirectory,t.groupDirectory)||e.expandedParents!==t.expandedParents&&yg(e,t)||e.editingId!==t.editingId&&(er(e,e.editingId,e.subtreeContainsEditing)||er(t,t.editingId,t.subtreeContainsEditing))||e.editTitle!==t.editTitle&&(er(e,e.editingId,e.subtreeContainsEditing)||er(t,t.editingId,t.subtreeContainsEditing))||e.copiedSessionId!==t.copiedSessionId&&(ls(e.node,e.copiedSessionId)||ls(t.node,t.copiedSessionId)))return!1;if(e.openSidebarMenuKey!==t.openSidebarMenuKey){const n=Zn(e),r=Zn(t);if(ls(e.node,n)||ls(t.node,r))return!1}if(e.renamingFolderId!==t.renamingFolderId){const n=Zn(e),r=Zn(t);if(ls(e.node,n)||ls(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 vg({node:e,groupDirectory:t,projectId:n,secondaryMeta:r,pinnedSessionIds:o,expandedParents:i,expansionKey:l,hasSessionSearchQuery:c}){const d=e.session,u=Ee(d.directory??null)??Ee(t??null),f=Te(Q=>Q.currentSessionId===d.id),p=Ya(u),x=xu(u),y=ct(a.useCallback(Q=>{if(r?.projectLabel||!n)return null;const ie=Q.projects.find(ke=>ke.id===n);return ie?ie.label?.trim()||On(Ee(ie.path)??ie.path,null)||ie.path:null},[n,r?.projectLabel])),m=r?.projectLabel??(y?qo(y):null),h=ct(a.useCallback(Q=>n?Q.projects.find(ie=>ie.id===n)?.path??null:null,[n])),b=e.worktree,g=r?.branchLabel??b?.branch??(p&&p!=="HEAD"?p:null),S=g,w=x===!0||!!(g||b),E=e.children.length,A=d.agent,k=b?.branch?.trim()||g?.trim()||null,j=Ee(b?.path??u),v=a.useMemo(()=>k&&j?_n(j,k):null,[k,j]),N=Ul(v);zl(j,k);const M=N?`var(--pr-${N.visualState})`:void 0,L=a.useMemo(()=>{if(!N)return null;switch(N.visualState){case"merged":return"Merged";case"open":return N.canMerge===!0||N.mergeableState==="clean"||N.checks?.state==="success"?"Ready to merge":"PR open";case"blocked":return N.mergeableState==="dirty"?"Merge conflicts":"Merge blocked";case"draft":return"Draft PR";case"closed":return"Closed";default:return null}},[N]),K=n??u??null,z=ft(Q=>Q.enabled),$=ft(a.useCallback(Q=>Q.selectedIds.has(d.id),[d.id])),O=ft(Q=>Q.toggleSelected),R=ft(Q=>Q.setRange),I=Va(d.id)?.type??"idle",T=I==="busy"||I==="retry",W=yu(d.id,T),Z=gs(d,"Untitled session"),F=e.children.length>0,me=wu(o,u,d.id),q=c?!0:i.has(l),Ae=vu(d.id);Qa(a.useCallback(Q=>Q.index.session.unseenHasError[d.id]??!1,[d.id]));const Ie=Su(d.id),G=ju({pendingInput:Ie,isStreaming:T,unseenCount:Ae,isActive:f}),U=Ae>0||Ja(Ie),Y=d.time?.updated||d.time?.created||Date.now(),X=Of(Y),se=a.useMemo(()=>Ml(e.forkColorId),[e.forkColorId]),we=a.useMemo(()=>Im(e.forkColorId,{active:f||$}),[e.forkColorId,f,$]),pe=r?.globalSession&&!f&&!$?"var(--surface-elevated)":null,V=we??pe;return{session:d,sessionDirectory:u,prDirectory:j,prBranch:k,prNumber:N?.number??null,isActive:f,tooltipProjectLabel:m,projectPath:h,tooltipBranchLabel:S,isGitRepo:w,subtaskCount:E,agentName:A,prSummary:N,prIconColor:M,prStatusLabel:L,selectionScopeKey:K,selectionModeEnabled:z,isRowSelected:$,toggleRowSelected:O,setRowRange:R,isStreaming:T,hasActivityDuration:W,sessionTitle:Z,hasChildren:F,isPinnedSession:me,isExpanded:q,needsAttention:U,pendingInput:Ie,attention:G,sessionCompactUpdatedLabel:X,forkSolid:se,rowBackground:V}}const Sg=({prDirectory:e,prNumber:t,prStatusLabel:n,prIconColor:r})=>{const o=$a(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(P,{name:"git-pull-request",className:"size-3.5 shrink-0"}),s.jsxs("span",{children:["#",t]})]});const i=l=>{l.stopPropagation(),l.preventDefault(),Xl(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(P,{name:"git-pull-request",className:"size-3.5 shrink-0"}),s.jsxs("span",{children:["#",t]})]})};function jg(e){Wt("ui.sidebar_session_node.render");const{node:t,depth:n=0,groupDirectory:r,projectId:o,archivedBucket:i=!1,pinnedSessionIds:l,expandedParents:c,hasSessionSearchQuery:d,normalizedSessionSearchQuery:u,editingId:f,setEditingId:p,editTitle:x,setEditTitle:y,handleSaveEdit:m,handleCancelEdit:h,toggleParent:b,handleSessionSelect:g,handleSessionDoubleClick:S,togglePinnedSession:w,handleShareSession:E,copiedSessionId:A,handleCopyShareUrl:k,handleCopySessionId:j,handleUnshareSession:v,openSidebarMenuKey:N,setOpenSidebarMenuKey:M,renamingFolderId:L,getFoldersForScope:K,getSessionFolderId:z,removeSessionFromFolder:$,addSessionToFolder:O,createFolderAndStartRename:R,handleDeleteSession:D,handleRestoreSession:I,alwaysShowActions:T,allowQuickArchiveAction:W,renderSessionNode:Z,secondaryMeta:F,renderContext:me="project",subtreeContainsEditing:q,menuOpenSessionId:Ae,childRenderExtrasFor:Ie}=e,G=a.useContext(Qo)==="tree",U="size-3 shrink-0",Y=a.useMemo(()=>ol(),[]),X=!i&&W,se=a.useRef(!1),we=a.useRef(f);we.current=f;const pe=a.useRef(null),V=a.useRef(m);V.current=m;const[Q,ie]=a.useState(x),ke=a.useRef(Q);ke.current=Q;const Se=a.useRef(null),He=a.useRef(null),de=`${me}:${i?"archived":"active"}:${t.session.id}`,{session:ne,sessionDirectory:ue,prDirectory:ve,prNumber:Le,isActive:be,tooltipProjectLabel:te,projectPath:xe,tooltipBranchLabel:fe,isGitRepo:je,subtaskCount:Ye,agentName:_e,prSummary:De,prIconColor:Ve,prStatusLabel:ae,selectionScopeKey:Fe,selectionModeEnabled:tt,isRowSelected:xt,toggleRowSelected:Qe,setRowRange:pt,isStreaming:Xe,hasActivityDuration:Ss,sessionTitle:St,hasChildren:st,isPinnedSession:Et,isExpanded:Lt,needsAttention:Yt,pendingInput:jt,attention:Ot,sessionCompactUpdatedLabel:yt,forkSolid:rt,rowBackground:dt}=vg({node:t,groupDirectory:r,projectId:o,secondaryMeta:F,pinnedSessionIds:l,expandedParents:c,expansionKey:de,hasSessionSearchQuery:d}),{exportDialogOpen:Vt,setExportDialogOpen:us,exportIncludeSubtasks:Ce,setExportIncludeSubtasks:Ue,descendantCount:ge,handleExportSession:Oe,doExportSession:Ge}=pg(t,ue),[it,kt]=a.useState(!1),ot=a.useCallback(()=>{ue&&Dn("desktop_open_session_mini_chat_window",{sessionId:ne.id,directory:ue,apiBaseUrl:mo(),clientToken:ho()}).catch(re=>{console.warn("[session-sidebar] failed to open mini chat window",re)})},[ne.id,ue]);a.useEffect(()=>{if(f!==ne.id)return;const re=qe=>{const gt=qe.target?.closest?.(`[data-session-rename-form="${CSS.escape(ne.id)}"]`);He.current&&!gt&&V.current(ke.current)};return document.addEventListener("mousedown",re),()=>document.removeEventListener("mousedown",re)},[f,ne.id]),a.useLayoutEffect(()=>{if(f!==ne.id){Se.current===ne.id&&(Se.current=null);return}Se.current!==ne.id&&(Se.current=ne.id,ie(x))},[f,x,ne.id]);const Bt=Ot==="needs-input",ns=Bt&&jt?ku(jt.kind,jt.count):null,Ze=Ot==="unread",Rt=Xe&&Ss,Dt=X&&(T||it),wt=Xe&&!G&&!Dt&&f!==ne.id,ut=!!(F?.showFolderLabel&&te),_s=!!fe||je,Us=!!(_e&&_e!=="default"),js=!!De&&Le!=null,ks=Rt&&!wt,Ct=ut&&_s||js||Ye>0||Us||ks,rs=re=>fe?s.jsxs("span",{className:_("inline-flex min-w-0 items-center gap-1",re?"shrink":"flex-1"),children:[s.jsx(P,{name:"git-branch",className:U,style:Ve?{color:Ve}:void 0}),s.jsx(qa,{value:fe})]}):je?s.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[s.jsx(P,{name:"git-repository",className:U}),s.jsx("span",{children:"git"})]}):null,At=Et,os=s.jsx(P,{name:"pushpin",className:"h-3 w-3 flex-shrink-0 text-primary","aria-label":"Pinned session"}),is=At?s.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:os}):null,at=st?s.jsx("button",{type:"button",onClick:re=>{re.stopPropagation(),b(de)},onKeyDown:re=>{(re.key==="Enter"||re.key===" ")&&(re.preventDefault(),re.stopPropagation(),b(de))},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":Lt?"Collapse subsessions":"Expand subsessions",children:Lt?s.jsx(P,{name:"arrow-down-s",className:"h-3 w-3"}):s.jsx(P,{name:"arrow-right-s",className:"h-3 w-3"})}):null,_t=re=>{if(!re&&pe.current){const{id:qe,title:Nt}=pe.current;pe.current=null,p(qe),y(Nt)}},zs=re=>{kt(re)},Pt=re=>{re.preventDefault(),re.stopPropagation()},pn=re=>{re.preventDefault(),re.stopPropagation()},$s=re=>{re.preventDefault(),re.stopPropagation(),M(null),D(ne,{archivedBucket:i})},gn=re=>{re.preventDefault(),re.stopPropagation(),M(null),D(ne,{archivedBucket:i,hardDelete:!0,skipConfirm:!0})},fs=re=>{if(se.current){se.current=!1;return}if(tt){if(re?.preventDefault(),re?.stopPropagation(),re?.shiftKey){const Nt=(typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[]).map(Cs=>Cs.getAttribute("data-session-row")).filter(Cs=>typeof Cs=="string"&&Cs.length>0),gt=ft.getState().anchorId,Ks=new Map;Ks.set(ne.id,wr(t)),pt(gt,ne.id,Nt,Fe,Ks);return}Qe(ne.id,Fe,wr(t));return}re?.currentTarget&&lg(re.currentTarget),g(ne.id,ue)},B=re=>{re.defaultPrevented||re.target?.closest('button, a, input, [role="menuitem"], [role="menu"]')||fs(re)},le=re=>{(re.button===2||re.button===0&&re.ctrlKey&&!tt)&&(se.current=!0)},ye={session:ne,sessionTitle:St,sessionDirectory:ue,isPinnedSession:Et,archivedBucket:i,isElectron:Y,renamingFolderId:L,editingIdRef:we,pendingRenameRef:pe,handleCopySessionId:j,togglePinnedSession:w,handleExportSession:Oe,handleOpenMiniChatWindow:ot,handleDeleteSession:D,handleRestoreSession:I},Be=s.jsx(ag,{...ye});return s.jsxs(a.Fragment,{children:[s.jsx(Qm,{sessionId:ne.id,sessionDirectory:ue??null,sessionTitle:St,children:s.jsxs(Ca,{open:it,onOpenChange:zs,onOpenChangeComplete:_t,children:[s.jsxs(Aa,{render:s.jsx("div",{"data-session-row":ne.id,"data-session-scope":Fe??"","data-session-archived":i?"1":"0","data-fork-color":rt?t.forkColorId:void 0,"data-global-session":F?.globalSession?"1":void 0,"data-sidebar-tree-row":G?"":void 0,onClick:B,style:{...n>0?{marginLeft:`${n*14}px`}:void 0,...dt?{backgroundColor:dt}:void 0},className:_("group relative flex cursor-pointer items-start px-3 transition-colors",G?Ol:"my-0.5 rounded-xl py-2",!dt&&n>0?"bg-secondary/30 hover:bg-interactive-hover":dt?"hover:brightness-[1.07] dark:hover:brightness-[1.18]":"hover:bg-interactive-hover",!dt&&be&&!xt&&"bg-interactive-selection",!dt&&xt&&"bg-interactive-selection")}),children:[s.jsxs("div",{className:_("flex min-w-0 flex-1 items-start",wt&&"oc-session-row-working-fade"),"data-clear-on-hover":wt&&X?"true":void 0,"data-working-duration":wt&&Rt?"true":void 0,children:[s.jsxs("div",{className:_("flex min-w-0 flex-1 items-center",G?Cr:"gap-1.5"),children:[G?s.jsx("span",{"data-session-row-gutter":!0,className:"inline-flex size-4 shrink-0 items-center justify-center",children:Xe&&!Bt?s.jsx(ys,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null}):null,at,is,f===ne.id?s.jsxs("form",{ref:He,"data-session-rename-form":ne.id,className:_("flex min-w-0 flex-1 items-center gap-2",G?"min-h-5":"min-h-8"),onPointerDown:re=>re.stopPropagation(),onMouseDown:re=>re.stopPropagation(),onSubmit:re=>{re.preventDefault(),m(Q)},children:[s.jsx("input",{value:Q,onChange:re=>ie(re.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:re=>{re.stopPropagation(),re.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(P,{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(P,{name:"close",className:"size-4"})})]}):s.jsxs("button",{type:"button",onMouseDown:le,onClick:re=>fs(re),onDoubleClick:re=>{re.stopPropagation(),S(ne.id,St)},className:"flex min-w-0 flex-1 cursor-pointer flex-col gap-1 overflow-hidden text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 text-foreground select-none",children:[s.jsxs("div",{className:"flex w-full items-center min-w-0 flex-1 gap-1.5 overflow-hidden",children:[s.jsx("div",{className:_("block min-w-0 flex-1 truncate font-normal typography-ui-label",Yt?"text-foreground":G&&!be?"text-muted-foreground transition-colors group-hover:text-foreground":"text-foreground/90"),children:or(St,u)}),Et?s.jsx(P,{name:"star-fill",className:"h-3 w-3 text-primary shrink-0"}):null,s.jsx("span",{"aria-hidden":"true",className:"invisible ml-1 min-w-6 shrink-0 whitespace-nowrap text-[11px]",children:Ze?null:yt})]}),!G&&(ut||_s||Ct)?s.jsxs("div",{className:"flex w-full min-w-0 items-center justify-between gap-2 overflow-hidden text-xs leading-4 font-normal text-muted-foreground/80",children:[ut?s.jsxs("span",{className:_("inline-flex min-w-0 items-center gap-1",Ct?"max-w-[60%] shrink-0":"flex-1"),children:[xe?s.jsx(Go,{directory:xe,label:te??"",className:U}):s.jsx(P,{name:"folder",className:U}),s.jsx("span",{className:"truncate",children:te})]}):rs(!1),Ct?s.jsxs("span",{className:_("ml-auto flex min-w-0 items-center justify-end gap-2 overflow-hidden",ut?"flex-1":"shrink-0"),children:[ut?rs(!0):null,js?s.jsx(Sg,{prDirectory:ve,prNumber:Le,prStatusLabel:ae,prIconColor:Ve}):null,Ye>0?s.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[s.jsx(P,{name:"node-tree",className:U}),s.jsx("span",{children:Ye})]}):null,Us?s.jsx("span",{className:"min-w-0 max-w-[80px] shrink-0 truncate",children:_e}):null,ks?s.jsx(Di,{sessionId:ne.id,running:Xe,className:"shrink-0 text-muted-foreground/70"}):null]}):null]}):null]})]}),s.jsxs("div",{className:_("absolute right-3 flex h-5 min-w-6 items-center justify-end",G?"top-1/2 -translate-y-1/2":"top-2",f===ne.id&&"hidden"),children:[s.jsx("div",{className:_("flex items-center justify-end",Dt?"opacity-0":X?"group-hover:opacity-0 group-focus-within:opacity-0":null),children:Bt&&!wt?s.jsx(Ai,{label:ns??"Needs input"}):Ze?s.jsx(Bf,{label:"Session complete"}):s.jsx("span",{className:"text-[11px] text-muted-foreground/75 whitespace-nowrap",children:yt})}),X?s.jsx("div",{className:_("absolute inset-0 flex items-center justify-end",T||it?"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(rg,{archiveLabel:"Archive",deleteLabel:"Delete",buttonSizeClass:"h-6 w-6",iconSizeClass:"h-3.5 w-3.5",onPointerDown:Pt,onMouseDown:pn,onArchive:$s,onDelete:gn})}):null]})]}),wt?s.jsxs("span",{"data-session-working":!0,className:_("pointer-events-none absolute inset-y-0 right-0 flex items-center rounded-r-[inherit] pr-3 transition-opacity",X&&"group-hover:opacity-0 group-focus-within:opacity-0"),children:[Bt?null:s.jsx("span",{"aria-hidden":"true",className:"oc-session-row-working-aura absolute inset-y-0 right-0 w-24 rounded-r-[inherit] bg-gradient-to-l from-primary/15 to-transparent"}),s.jsxs("span",{className:"relative flex flex-col items-end gap-1",children:[s.jsx("span",{className:"flex h-5 items-center",children:Bt?s.jsx("span",{className:"inline-flex size-3 shrink-0 items-center justify-center",children:s.jsx(Ai,{label:ns??"Needs input"})}):s.jsx(ys,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})}),Rt?s.jsx(Di,{sessionId:ne.id,running:Xe,className:"text-[11px] leading-4"}):null]})]}):null]}),Be]})}),st&&Lt?t.children.map(re=>{const qe=Ie?Ie(re):{subtreeContainsEditing:q,menuOpenSessionId:Ae,nodeStructureKey:""};return s.jsx(a.Fragment,{children:Z(re,n+1,ue??r,o,i,F?.globalSession?{globalSession:!0}:void 0,me,qe)},re.session.id)}):null,s.jsx(og,{open:Vt,onOpenChange:us,descendantCount:ge,exportIncludeSubtasks:Ce,setExportIncludeSubtasks:Ue,onExport:Ge})]},ne.id)}const kg=a.memo(jg,wg),Cg=({open:e,onOpenChange:t,project:n,onSave:r})=>s.jsx(ts,{open:e,onOpenChange:t,children:s.jsx(ss,{className:"w-full max-w-2xl gap-0 overflow-hidden p-0",children:s.jsx(Is,{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(Jh,{project:n,onIdentitySave:r}):null})})})});function cc(e){const{showDeletionDialog:t,setShowDeletionDialog:n,onCancel:r,onConfirm:o,confirmLabel:i}=e;return s.jsxs(Ls,{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(P,{name:"checkbox-blank",className:"h-4 w-4"}):s.jsx(P,{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 Ag(e){const{value:t,setValue:n,showDeletionDialog:r,setShowDeletionDialog:o,onConfirm:i}=e,l=c=>gs(c);return s.jsx(ts,{open:!!t,onOpenChange:c=>{c||n(null)},children:s.jsxs(ss,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(ws,{children:[s.jsx(ds,{children:t?.archivedBucket?"Delete session?":"Archive session?"}),s.jsx(vs,{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(cc,{showDeletionDialog:r,setShowDeletionDialog:o,onCancel:()=>n(null),onConfirm:i,confirmLabel:t?.archivedBucket?"Delete":"Archive"})]})})}function Ng(e){const{value:t,setValue:n,showDeletionDialog:r,setShowDeletionDialog:o,onConfirm:i}=e,l=t?.archivedBucket===!0,c=t?.sessionCount??0,d=l?c===1?"Delete session?":"Delete sessions?":c===1?"Archive session?":"Archive sessions?",u=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(ts,{open:!!t,onOpenChange:f=>{f||n(null)},children:s.jsxs(ss,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(ws,{children:[s.jsx(ds,{children:d}),s.jsx(vs,{children:u})]}),s.jsx(cc,{showDeletionDialog:r,setShowDeletionDialog:o,onCancel:()=>n(null),onConfirm:i,confirmLabel:l?"Delete":"Archive"})]})})}function Ig(e){const{value:t,setValue:n,onConfirm:r}=e,{git:o}=Os(),[i,l]=a.useState(null),[c,d]=a.useState(!1),[u,f]=a.useState(!1),[p,x]=a.useState(!1),y=t?.worktree.path??null;a.useEffect(()=>{let A=!1;return l(null),d(!1),f(!1),x(!1),!t||!y?()=>{A=!0}:(o.getGitStatus(y).then(k=>{if(!A){if(typeof k?.isClean!="boolean"){d(!0);return}l(k)}}).catch(()=>{A||d(!0)}),()=>{A=!0})},[o,t,y]);const m=i?.isClean===!1,h=(i?.ahead??0)>0,b=h&&!t?.worktree.branch,g=t?.worktree.branch?"The local branch will be kept.":"No local branch will be deleted.",S=!!(t&&i&&!c&&!t.hasActiveSession&&(!m&&!b||u)&&!p),w=t?.worktree.branch||t?.worktree.name||t?.worktree.path||"",E=async()=>{if(S){x(!0);try{await r({force:m})}finally{x(!1)}}};return s.jsx(ts,{open:!!t,onOpenChange:A=>{!A&&!p&&n(null)},children:s.jsxs(ss,{showCloseButton:!1,className:"max-w-md gap-5",children:[s.jsxs(ws,{children:[s.jsx(ds,{children:"Close worktree?"}),s.jsx(vs,{children:`Closing "${w}" removes its worktree directory. ${g}`})]}),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(P,{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(P,{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(P,{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(io,{checked:u,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. ${g}`:`This worktree has ${i?.ahead} unpushed commits. ${g}`}),b?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(P,{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(io,{checked:u,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(Ls,{className:"sm:justify-end",children:[s.jsx(Ne,{variant:"outline",size:"sm",onClick:()=>n(null),disabled:p,children:"Cancel"}),s.jsx(Ne,{variant:"destructive",size:"sm",onClick:()=>{E()},disabled:!S,children:p?"Closing…":"Close worktree"})]})]})})}function Eg(e){const{value:t,setValue:n,onConfirm:r}=e;return s.jsx(ts,{open:!!t,onOpenChange:o=>{o||n(null)},children:s.jsxs(ss,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(ws,{children:[s.jsx(ds,{children:"Delete folder?"}),s.jsx(vs,{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(Ls,{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 Rg=({updateDialogOpen:e,setUpdateDialogOpen:t,updateStore:n,editingProject:r,setEditingProjectDialogId:o,handleSaveProjectEdit:i,deleteSessionConfirm:l,setDeleteSessionConfirm:c,showDeletionDialog:d,setShowDeletionDialog:u,confirmDeleteSession:f,deleteFolderConfirm:p,setDeleteFolderConfirm:x,confirmDeleteFolder:y,closeWorktreeConfirm:m,setCloseWorktreeConfirm:h,confirmCloseWorktree:b,bulkDeleteConfirm:g,setBulkDeleteConfirm:S,confirmBulkDelete:w})=>s.jsxs(s.Fragment,{children:[s.jsx(jl,{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(Cg,{open:!!r,onOpenChange:E=>{E||o(null)},project:r,onSave:i}),s.jsx(Ag,{value:l,setValue:c,showDeletionDialog:d,setShowDeletionDialog:u,onConfirm:f}),s.jsx(Eg,{value:p,setValue:x,onConfirm:y}),s.jsx(Ig,{value:m,setValue:h,onConfirm:b}),s.jsx(Ng,{value:g,setValue:S,showDeletionDialog:d,setShowDeletionDialog:u,onConfirm:w})]}),Dg=({directories:e})=>{const t=a.useMemo(()=>{const r=new Set;return e.forEach(o=>{const i=Ee(o)?.toLowerCase();i&&r.add(i)}),r},[e]),n=En(r=>{let o=0,i=!1;for(const l of r.catalog.byId.values()){const c=Ee(l.directory)?.toLowerCase();!c||!t.has(c)||(Ja(l.pendingInput)?o+=1:(l.lifecycle==="busy"||l.lifecycle==="retry")&&(i=!0))}return{inputCount:o,hasBusySession:i}},(r,o)=>r.inputCount===o.inputCount&&r.hasBusySession===o.hasBusySession,"catalog");if(n.inputCount>0){const r=Cu(n.inputCount);return s.jsx("span",{className:"inline-flex items-center","aria-label":r,title:r,children:s.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-status-warning"})})}return n.hasBusySession?s.jsx("span",{className:"inline-flex items-center","aria-label":"Session active",title:"Session active",children:s.jsx(ys,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})}):null},Pg=e=>{let t=0;for(const n of e)for(const r of n.groups)r.isArchivedBucket||(t+=r.sessions.length);return t},Mg=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},Tg=(e,t)=>e.groups.some(n=>n.isArchivedBucket?!1:n.sessions.some(r=>t.has(r.session.id))),Fg=(e,t)=>e.groups.some(n=>n.isArchivedBucket?!1:n.sessions.some(r=>t.has(r.session.id))),Lg=(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=Ee(i.directory)?.toLowerCase();c&&o.add(c)}}o.size>0&&n.set(r.project.id,o)}return n},Og=e=>e.map(t=>t.groups.some(n=>n.isArchivedBucket)?{...t,groups:t.groups.filter(n=>!n.isArchivedBucket)}:t),Bg=(e,t,n,r)=>{if(!n)return t;const o=e.find(c=>c.project.id===n);if(!o)return[];const i=Ee(r??o.project.normalizedPath),l=o.groups.find(c=>!c.isArchivedBucket&&Ee(c.directory)===i);return l?[{...o,groups:[l]}]:[]},_g=(e,t)=>{const n=new Map,r=new Map;return e.forEach(o=>{const i=qo(o.project.label?.trim()||On(o.project.normalizedPath,t)||o.project.normalizedPath);o.groups.forEach(l=>{const c=l.branch&&l.branch!=="HEAD"&&l.branch!==i?l.branch:null,d={projectLabel:i,branchLabel:c},u=f=>{f.forEach(p=>{const x=o.project.normalizedPath.length,y=r.get(p.session.id)??-1;x<y||(n.set(p.session.id,{node:p,projectId:o.project.id,groupDirectory:l.directory,secondaryMeta:d}),r.set(p.session.id,x),p.children.length>0&&u(p.children))})};u(l.sessions)})}),n};function Ug({projectSections:e,flatSectionsForRender:t,sectionsForRender:n,selectedSpaceId:r,selectedWorktreePath:o,homeDirectory:i,activeSessionIdSet:l,unreadSessionIdSet:c}){const d=a.useMemo(()=>_g(e,i),[e,i]),u=a.useMemo(()=>Og(t),[t]),f=a.useMemo(()=>Bg(n,u,r,o),[n,u,r,o]),p=a.useMemo(()=>Pg(e),[e]),x=a.useMemo(()=>Mg(e),[e]),y=a.useCallback(b=>{const g=e.find(S=>S.project.id===b);return g?Tg(g,l):!1},[l,e]),m=a.useMemo(()=>Lg(e,l),[l,e]),h=a.useCallback(b=>{const g=e.find(S=>S.project.id===b);return g?Fg(g,c):!1},[e,c]);return{sessionSidebarMetaById:d,sectionsForSidebarRender:u,filteredSectionsForSidebarRender:f,totalSessionCount:p,sessionCountByProject:x,hasActiveSessionByProject:y,activeDirectoriesByProject:m,hasUnseenByProject:h}}const zg=({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 pl-5 pr-3.5 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(P,{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:_("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(P,{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(P,{name:"close",className:"h-4 w-4"})})}),s.jsx(We,{side:"top",sideOffset:4,children:s.jsx("p",{children:"Exit selection"})})]})]})]})},$g=e=>{const{isInlineEditing:t,showDeletionDialog:n,foldersMap:r,folderScopesByProject:o,addSessionsToFolder:i,removeSessionsFromFolders:l,createFolderAndStartRename:c,archiveSessions:d,unarchiveSessions:u,deleteSessions:f,setBulkDeleteConfirm:p}=e,x=ft(D=>D.enabled),y=ft(D=>D.selectedIds.size),m=y>0,h=ft(D=>D.selectedIds),b=ft(D=>D.scopeKey),g=a.useCallback(()=>{ft.getState().toggleMode()},[]),S=a.useCallback(()=>{ft.getState().disable()},[]),w=a.useMemo(()=>{if(!m||typeof document>"u")return!1;let D=!1,I=!1;for(const T of h){const W=document.querySelectorAll(`[data-session-row="${CSS.escape(T)}"]`);for(const Z of W)Z.getAttribute("data-session-archived")==="1"?I=!0:D=!0}return I&&!D},[m,h]),E=a.useMemo(()=>{if(b)return b;if(!m||typeof document>"u")return null;for(const D of h){const T=document.querySelector(`[data-session-row="${CSS.escape(D)}"]`)?.getAttribute("data-session-scope");if(T&&T.length>0)return T}return null},[m,h,b]),A=a.useMemo(()=>{if(!E)return[];const D=o.get(E);return D&&D.length>0?D.map(I=>I.scopeKey):[E]},[E,o]),k=a.useMemo(()=>A.flatMap(D=>r[D]??[]),[r,A]),j=a.useCallback(D=>{for(const I of A)if((r[I]??[]).some(T=>T.id===D))return I;return null},[r,A]),v=a.useMemo(()=>{if(!m)return!1;for(const D of A)for(const I of r[D]??[])for(const T of I.sessionIds)if(h.has(T))return!0;return!1},[r,A,m,h]),N=a.useCallback((D,I)=>{const T=Array.from(h);for(const W of A)W!==D&&l(W,T);i(D,I,T)},[i,l,h,A]),M=a.useCallback(D=>{if(!m)return;const I=j(D);I&&N(I,D)},[m,N,j]),L=a.useCallback(()=>{const D=A[0];if(!D||!m)return;const I=c(D);I&&N(D,I.id)},[c,m,N,A]),K=a.useCallback(()=>{if(!m)return;const D=Array.from(h);for(const I of A)l(I,D)},[l,h,A,m]),z=a.useCallback(async()=>{const D=Array.from(h);if(D.length!==0){if(w){const{deletedIds:I,failedIds:T}=await f(D);I.length>0&&oe.success(I.length===1?`Deleted ${I.length} session`:`Deleted ${I.length} sessions`),T.length>0&&oe.error(T.length===1?`Failed to delete ${T.length} session`:`Failed to delete ${T.length} sessions`)}else{const{archivedIds:I,failedIds:T}=await d(D);I.length>0&&oe.success(I.length===1?`Archived ${I.length} session`:`Archived ${I.length} sessions`),T.length>0&&oe.error(T.length===1?`Failed to archive ${T.length} session`:`Failed to archive ${T.length} sessions`)}ft.getState().clear()}},[d,w,f,h]),$=a.useCallback(()=>{if(!m)return;const D=h.size;if(!n){z();return}p({sessionCount:D,archivedBucket:w})},[w,z,h,n,p,m]),O=a.useCallback(async()=>{if(!m||!w)return;const D=Array.from(h),{restoredIds:I,failedIds:T}=await u(D);I.length>0&&oe.success(I.length===1?`Restored ${I.length} session`:`Restored ${I.length} sessions`),T.length>0&&oe.error(T.length===1?`Failed to restore ${T.length} session`:`Failed to restore ${T.length} sessions`),ft.getState().clear()},[w,m,h,u]),R=a.useCallback(async()=>{p(null),await z()},[z]);return a.useEffect(()=>{if(!x)return;const D=typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""),I=T=>{if(t)return;const W=T.target;if(W&&(W.tagName==="INPUT"||W.tagName==="TEXTAREA"||W.isContentEditable))return;const Z=D?T.metaKey:T.ctrlKey;if(T.key==="Escape"){T.preventDefault(),ft.getState().disable();return}if(Z&&T.key==="Backspace"){T.preventDefault(),$();return}if(Z&&(T.key==="a"||T.key==="A")){const F=typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[];if(F.length===0)return;T.preventDefault();const q=ft.getState().scopeKey??F[0]?.getAttribute("data-session-scope")??null,Ae=G=>q?G.getAttribute("data-session-scope")===q:!0,Ie=F.filter(Ae).map(G=>G.getAttribute("data-session-row")).filter(G=>typeof G=="string"&&G.length>0);if(Ie.length===0)return;ft.getState().replaceAll(Ie,q||null)}};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[$,t,x]),{selectionModeEnabled:x,hasSelection:m,selectedIdsSize:y,bulkScopeIsArchived:w,derivedSelectionScope:E,bulkScopeFolders:k,bulkCanRemoveFromFolder:v,handleToggleSelectionMode:g,handleExitSelectionMode:S,handleBulkMoveToFolder:M,handleBulkCreateFolderAndMove:L,handleBulkRemoveFromFolder:K,handleBulkDelete:$,handleBulkRestore:O,confirmBulkDelete:R}},Kg=(e,t)=>{const n=e??{};return delete n.projectSortOrder,t<4&&delete n.displayMode,t<5&&delete n.sessionGroupingMode,n},oa=Bs()(fl(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:Kg})),ia="oc.sessions.projectCollapse",aa="oc.sessions.groupOrder",la="oc.sessions.groupCollapse",ca="oc.sessions.activeSessionByProject",da="oc.sessions.expandedParents.v3",Wg=new Set,Hr=[],Mt=e=>{const t=a.useRef(e);return t.current=e,a.useCallback((...n)=>t.current(...n),[])},Gg=({isVisible:e=!0,mobileVariant:t=!1,onSessionSelected:n,onNavigateAway:r,allowReselect:o=!1,hideDirectoryControls:i=!1,showOnlyMainWorkspace:l=!1})=>{fo("react.session_sidebar_render"),Wt("ui.session_sidebar.render"),Wt(`ui.session_sidebar.render.${t?"mobile":"desktop"}`),Wt(`ui.session_sidebar.render.${e?"visible":"hidden"}`);const[c,d]=a.useState(!1),[u,f]=a.useState(""),p=a.useRef(null),x=a.useRef(null),[y,m]=a.useState(null),[h,b]=a.useState(""),[g,S]=a.useState(null),[w,E]=a.useState(new Set),A=a.useMemo(()=>Hn(),[]),[k,j]=a.useState(new Set),v=qs(C=>C.selectedSpaceId),N=qs(C=>C.selectedWorktreePath),[M,L]=a.useState(new Map),[K,z]=a.useState(new Map),[$,O]=a.useState(!1),[R,D]=a.useState(null),[I,T]=a.useState(null),[W,Z]=a.useState(""),[F,me]=a.useState(null),[q,Ae]=a.useState(null),[Ie,G]=a.useState(null),[U,Y]=a.useState(null),X=Ni(C=>C.ids),se=Au(a.useCallback(C=>e?C.rankById:Ka,[e])),we=En(C=>e?Nu(C.catalog):"",void 0,"catalog"),pe=a.useMemo(()=>we?we.split("|"):Hr,[we]),V=a.useMemo(()=>new Set(pe),[pe]),Q=Qa(oo(C=>e?Object.entries(C.index.session.unseenCount).filter(([,J])=>J>0).map(([J])=>J).sort():Hr)),ie=a.useMemo(()=>new Set(Q),[Q]),ke=Ni(C=>C.toggle),[Se,He]=a.useState(()=>{try{const C=Hn().getItem(la);if(!C)return new Set;const J=JSON.parse(C);return new Set(Array.isArray(J)?J.filter(ee=>typeof ee=="string"):[])}catch{return new Set}}),[H,de]=a.useState(()=>{try{const C=Hn().getItem(aa);if(!C)return new Map;const J=JSON.parse(C),ee=new Map;return Object.entries(J).forEach(([Me,ze])=>{Array.isArray(ze)&&ee.set(Me,ze.filter(et=>typeof et=="string"))}),ee}catch{return new Map}}),ne=a.useMemo(()=>{try{const C=Hn().getItem(ca);if(!C)return new Map;const J=JSON.parse(C),ee=new Map;return Object.entries(J).forEach(([Me,ze])=>{typeof ze=="string"&&ze.length>0&&ee.set(Me,ze)}),ee}catch{return new Map}},[]),ue=a.useCallback(C=>{try{A.setItem(ca,JSON.stringify(Object.fromEntries(C.entries())))}catch{}},[A]),[ve,Le]=a.useState(new Map),be=a.useRef(0),te=on(C=>C.homeDirectory),xe=on(C=>C.currentDirectory),fe=ct(C=>C.projects),je=ct(C=>C.activeProjectId),Ye=ct(C=>C.removeProject),_e=ct(C=>C.setActiveProjectIdOnly),De=ct(C=>C.updateProjectMeta),Ve=ct(C=>C.reorderProjects),ae=ce(C=>C.setActiveMainTab),Fe=ce(C=>C.setSettingsDialogOpen),tt=ce(C=>C.setSettingsPage),xt=ce(C=>C.toggleHelpDialog),Qe=ce(C=>C.setSessionSwitcherOpen),pt=ce(C=>C.setArchivePageOpen),Xe=ce(C=>C.showDeletionDialog),Ss=ce(C=>C.setShowDeletionDialog),St=ce(C=>C.sidebarViewMode),st=i||l||!mf(St)?"workspace":St,Et=ce(C=>C.weekStartPreference),Lt=a.useMemo(()=>gm(Et),[Et]),Yt=wm(e&&st==="timeline",Lt),jt=oa(C=>C.stickyZoneHeaders),Ot=Iu(u,120),yt=a.useMemo(()=>Ot.trim().toLowerCase(),[Ot]),rt=yt.length>0,dt=bt(C=>C.collapsedFolderIds),Vt=bt(C=>C.foldersMap),us=bt(C=>C.getFoldersForScope),Ce=bt(C=>C.createFolder),Ue=bt(C=>C.renameFolder),ge=bt(C=>C.deleteFolder),Oe=bt(C=>C.addSessionToFolder),Ge=bt(C=>C.addSessionsToFolder),it=bt(C=>C.removeSessionFromFolder),kt=bt(C=>C.removeSessionsFromFolders),ot=bt(C=>C.toggleFolderCollapse),Bt=bt(C=>C.getSessionFolderId);Dm({enabled:e,isSessionSearchOpen:c,setIsSessionSearchOpen:d,sessionSearchInputRef:x,sessionSearchContainerRef:p});const ns=Eu(e),{git:Ze}=Os(),Rt=En(C=>C.connection,void 0,"chrome"),Dt=En(C=>{for(const J of C.catalog.listStatusByDirectory.values())if(J==="ready")return!0;return!1},void 0,"catalog"),wt=lo({archived:!1}),ut=lo({archived:!0}),_s=Te(C=>C.setCurrentSession),Us=Te(C=>C.updateSessionTitle),js=Te(C=>C.shareSession),ks=Te(C=>C.unshareSession),Ct=co(C=>C.projects),rs=co(C=>C.refreshProject),At=a.useMemo(()=>Ru(fe,{projects:Ct}),[fe,Ct]),os=a.useMemo(()=>{const C=new Map;for(const J of fe){const ee=Ee(J.path);if(!ee)continue;const Me=Ct.get(ee)?.error;Me&&C.set(ee,Me)}return C},[fe,Ct]);a.useEffect(()=>{if(!v)return;const C=fe.find(ee=>ee.id===v);if(!C){qs.getState().clearSpaceSelection();return}if(!N)return;(At.get(Ee(C.path)??C.path)??[]).some(ee=>Ee(ee.path)===Ee(N))||(qs.getState().clearSelectedWorktree(),oe.warning("The selected worktree is no longer available. Showing the project checkout instead."))},[At,fe,v,N]);const is=Te(C=>C.openNewSessionDraft),at=a.useCallback(C=>{ce.getState().closeMainSurfaces(),is(C),r?.()},[r,is]),_t=sr(oo(C=>({checkForUpdates:C.checkForUpdates,available:C.available,runtimeType:C.runtimeType,info:C.info,downloading:C.downloading,downloaded:C.downloaded,progress:C.progress,error:C.error,downloadUpdate:C.downloadUpdate,restartToUpdate:C.restartToUpdate}))),zs=a.useMemo(()=>Du(fe,At,{includeWorktrees:!0}),[At,fe]),Pt=a.useMemo(()=>wt.filter(C=>Gm(C,zs,{allowUnknownDirectory:!0,allowEmptyDirectorySet:!0,homeDirectory:te})),[wt,te,zs]),pn=a.useMemo(()=>[...Pt,...ut],[ut,Pt]),$s=Ft(),gn=a.useMemo(()=>`${$s}|${fe.map(C=>`${C.id}:${Ee(C.path)??""}`).join("|")}`,[fe,$s]),fs=a.useMemo(()=>{const C=new Set;let J=!0;for(const ee of fe){const Me=Ee(ee.path);if(!Me)continue;const ze=Ct.get(Me)?.status??"idle";ze==="failed"&&C.add(Me),(ze==="idle"||ze==="loading")&&(J=!1)}return{complete:J,unresolved:C}},[fe,Ct]),B=fs.complete?gn:null,le=!fs.complete,ye=fs.unresolved,{isTablet:Be}=dn(),re=t||Be,qe=Rm({mobileVariant:t,isTablet:Be}),{buildGroupSearchText:Nt,filterSessionNodesForSearch:gt,buildGroupedSessions:Ks}=Em({homeDirectory:te,pinnedSessionIds:X,sessionOrderRanks:se}),{scheduleCollapsedProjectsPersist:Cs}=Mm({safeStorage:A,keys:{sessionExpanded:da,projectCollapse:ia,groupOrder:aa,groupCollapse:la},groupOrderByProject:H,collapsedGroups:Se,setExpandedParents:E,setCollapsedProjects:j}),Ws=a.useMemo(()=>Pu(Pt,X,se),[X,se,Pt]),Er=a.useMemo(()=>Ws.map(C=>C.id).join("|"),[Ws]),ti=a.useRef(null),si=a.useMemo(()=>{const C=ti.current;if(C&&C.signature===Er)return C.map;const J=new Map(Ws.map((ee,Me)=>[ee.id,Me]));return ti.current={signature:Er,map:J},J},[Ws,Er]),mc=a.useMemo(()=>{const C=new Map;Ws.forEach(ee=>{const Me=ee.parentID;if(!Me)return;const ze=C.get(Me)??[];ze.push(ee),C.set(Me,ze)});const J=Ua(X,se);return C.forEach(ee=>ee.sort(J)),C},[Ws,X,se]),pc=a.useMemo(()=>s.jsx(Zt,{icon:"chat-new",mobileVariant:t,onClick:()=>at(),children:"New session"}),[t,at]),gc=a.useMemo(()=>fe.find(C=>C.id===g)??null,[fe,g]),bc=a.useCallback(C=>{g&&De(g,{label:C.label,defaultModel:C.defaultModel??null})},[g,De]),xc=a.useCallback(()=>{const C=sr.getState();if(C.available&&C.info){O(!0);return}_t.checkForUpdates().then(()=>{const{available:J,error:ee}=sr.getState();if(ee){oe.error("Failed to check for updates",{description:ee});return}if(!J){oe.success("You are on the latest version");return}O(!0)})},[_t]),Gs=Mu(),ni=a.useCallback(()=>{if(t&&Qe(!1),r?.(),Gs?.openSettings){Gs.openSettings();return}Fe(!0)},[Gs,t,r,Qe,Fe]),yc=_t.available&&(_t.runtimeType==="desktop"||_t.runtimeType==="web"),wc=Te(C=>C.deleteSession),ri=Te(C=>C.deleteSessions),vc=Te(C=>C.archiveSession),oi=Te(C=>C.archiveSessions),Sc=Te(C=>C.unarchiveSession),jc=Te(C=>C.unarchiveSessions),{copiedSessionId:kc,handleSessionSelect:Cc,handleSessionDoubleClick:Ac,handleSaveEdit:Nc,handleCancelEdit:Ic,handleShareSession:Ec,handleCopyShareUrl:Rc,handleCopySessionId:Dc,handleUnshareSession:Pc,handleDeleteSession:Mc,handleRestoreSession:Tc,confirmDeleteSession:Fc}=Pm({mobileVariant:t,allowReselect:o,onSessionSelected:n,isSessionSearchOpen:c,sessionSearchQuery:u,setSessionSearchQuery:f,setIsSessionSearchOpen:d,setActiveMainTab:ae,setSessionSwitcherOpen:Qe,setCurrentSession:_s,updateSessionTitle:Us,shareSession:js,unshareSession:ks,deleteSession:wc,deleteSessions:ri,archiveSession:vc,archiveSessions:oi,unarchiveSession:Sc,childrenMap:mc,showDeletionDialog:Xe,setDeleteSessionConfirm:me,deleteSessionConfirm:F,setEditingId:m,setEditTitle:b,editingId:y,editTitle:h}),Lc=a.useCallback(()=>{if(!q)return;const{scopeKey:C,folderId:J}=q;Ae(null),ge(C,J)},[q,ge]),Rr=a.useCallback(()=>{Ms.requestDirectoryDialog()},[]),Oc=a.useCallback(C=>{E(J=>{const ee=_f(J,C);try{A.setItem(da,JSON.stringify(Array.from(ee)))}catch{}return ee})},[A]),ii=a.useCallback((C,J)=>{if(!C)return null;J&&dt.has(J)&&ot(J);const ee=Ce(C,"New folder",J);return T(ee.id),Z(ee.name),ee},[dt,ot,Ce]),bn=Mt(Cc),Bc=Mt(Ac),_c=Mt(Nc),Uc=Mt(Ic),zc=Mt(Ec),$c=Mt(Rc),Kc=Mt(Dc),Wc=Mt(Pc),Gc=Mt(Mc),Hc=Mt(Tc),Dr=Mt(ii),ai=a.useCallback((C,J)=>{z(ee=>{const Me=new Map(ee);return Me.set(C,J+7),Me})},[]),Kn=a.useCallback(C=>{z(J=>{if(!J.has(C))return J;const ee=new Map(J);return ee.delete(C),ee})},[]),li=a.useCallback(C=>{z(J=>{let ee=!1;const Me=new Map(J),ze=`${C}:`;for(const et of Me.keys())et.startsWith(ze)&&(Me.delete(et),ee=!0);return ee?Me:J})},[]),Pr=a.useCallback(C=>{be.current=Date.now()+150,li(C),j(J=>{const ee=new Set(J);ee.has(C)?ee.delete(C):ee.add(C);try{A.setItem(ia,JSON.stringify(Array.from(ee)))}catch{}return Cs(ee),ee})},[li,A,Cs]),ci=a.useRef(null);a.useEffect(()=>{const C=ci.current;ci.current=je,st==="folder"&&(!C||!je||C===je||k.has(je)&&Pr(je))},[je,k,st,Pr]);const hs=a.useMemo(()=>fe.map(C=>({...C,normalizedPath:Ee(C.path)})).filter(C=>!!C.normalizedPath),[fe]),qc=a.useMemo(()=>hs.map(C=>C.normalizedPath),[hs]),di=Tu(e?qc:Hr);_m({enabled:e,normalizedProjects:hs,gitRepoStatus:di,setProjectRepoStatus:L,setProjectRootBranches:Le});const ui=a.useMemo(()=>qm(Pt,hs,At,ut),[ut,At,hs,Pt]);Km({enabled:e,hasAuthoritativeGlobalSessions:Dt,sessions:pn});const{getSessionsForProject:Yc,getArchivedSessionsForProject:Vc}=Um({ownership:ui});vm({enabled:e,normalizedProjects:hs,ownership:ui,hasAuthoritativeGlobalSessions:Dt,isWorktreeTopologyLoading:le,unresolvedWorktreeProjectPaths:ye,foldersMap:Vt,createFolder:Ce,addSessionToFolder:Oe});const fi=a.useRef(!1);je&&M.has(je)&&(fi.current=!!M.get(je));const Qc=oa(C=>C.showArchivedSessions),Mr=ct(C=>C.manualProjectOrder),hi=a.useRef(new Set),Wn=Uf(hi.current,w,"project");hi.current=Wn;const Tr={isVisible:e,mobileVariant:t,onSessionSelected:n,allowReselect:o,hideDirectoryControls:i,showOnlyMainWorkspace:l,isTablet:Be,catalogSessions:wt,archivedSessions:ut,projects:fe,activeProjectId:je,manualProjectOrder:Mr,currentDirectory:xe,availableWorktreesByProject:At,pinnedSessionIds:X,sessionOrderRanks:se,foldersMap:Vt,collapsedFolderIds:dt,gitBranches:ns,gitRepoStatus:di,updateStore:_t,showArchivedSessions:Qc,projectRepoStatus:M,projectRootBranches:ve,resolvedWorktreeTopologyKey:B,unresolvedWorktreeProjectPaths:ye,isSessionSearchOpen:c,sessionSearchQuery:u,editingId:y,editTitle:h,editingProjectDialogId:g,expandedParents:w,collapsedProjects:k,visibleSessionCountByGroup:K,updateDialogOpen:$,openSidebarMenuKey:R,renamingFolderId:I,renameFolderDraft:W,deleteSessionConfirm:F,deleteFolderConfirm:q,bulkDeleteConfirm:U,collapsedGroups:Se},mi=a.useRef(null),pi=mi.current;if(pi){let C=!1;for(const J of Object.keys(Tr))Object.is(pi[J],Tr[J])||(Wt(`ui.session_sidebar.source.${J}`),C=!0);C||Wt("ui.session_sidebar.source.parent_or_context")}mi.current=Tr;const Jc=a.useMemo(()=>{const C=new Map(Mr.map((J,ee)=>[J,ee]));return[...hs].sort((J,ee)=>(C.get(J.id)??1/0)-(C.get(ee.id)??1/0))},[Mr,hs]),{projectSections:Ut,groupSearchDataByGroup:gi,sectionsForRender:Xc,flatSectionsForRender:Fr,searchMatchCount:Zc}=jm({normalizedProjects:Jc,getSessionsForProject:Yc,getArchivedSessionsForProject:Vc,availableWorktreesByProject:At,projectRepoStatus:M,projectRootBranches:ve,lastRepoStatus:fi.current,buildGroupedSessions:Ks,hasSessionSearchQuery:rt,normalizedSessionSearchQuery:yt,filterSessionNodesForSearch:gt,buildGroupSearchText:Nt,foldersMap:Vt}),xn=a.useMemo(()=>{const C=Pt.filter(ee=>Sr(Rn(ee),te));if(C.length===0)return null;const J=Ks(C,"~",[],null,!1).map(ee=>rt?{...ee,sessions:gt(ee.sessions,yt)}:ee).filter(ee=>ee.sessions.length>0&&!ee.isArchivedBucket);return J.length===0?null:{project:{id:"__home__",path:"~",normalizedPath:"~",label:"No folder"},groups:J}},[Ks,gt,rt,te,yt,Pt]),ed=a.useMemo(()=>{if(!rt||!xn)return 0;const C=J=>J.reduce((ee,Me)=>ee+1+C(Me.children),0);return xn.groups.reduce((J,ee)=>J+C(ee.sessions),0)},[xn,rt]),td=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:sd}=Sm(H),bi=a.useRef(!1);a.useEffect(()=>{if(bi.current||Ut.length===0)return;const C=Ut.flatMap(J=>J.groups.filter(ee=>ee.isArchivedBucket).map(ee=>`${J.project.id}:${ee.id}`));C.length>0&&He(J=>new Set([...J,...C])),bi.current=!0},[Ut]);const{sectionsForSidebarRender:nd,filteredSectionsForSidebarRender:rd,totalSessionCount:od,sessionCountByProject:id,hasActiveSessionByProject:ad,activeDirectoriesByProject:yn,hasUnseenByProject:ld}=Ug({projectSections:Ut,flatSectionsForRender:Fr,sectionsForRender:Xc,selectedSpaceId:v,selectedWorktreePath:N,homeDirectory:te,activeSessionIdSet:V,unreadSessionIdSet:ie}),Lr=a.useCallback(C=>{if(qs.getState().selectSpace(C),!C)return;_e(C);const J=Ut.find(ze=>ze.project.id===C),ee=J?.groups.find(ze=>ze.isMain),Me=ee?.sessions[0]?.session;Me?bn(Me.id,ee?.directory??J?.project.normalizedPath??null,{keepPanelOpen:!0}):J&&at({selectedProjectId:C,directoryOverride:J.project.normalizedPath})},[at,Ut,_e,bn]),cd=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",dd=t?"size-5":"size-4",Gn=Mt((C,J=0,ee,Me,ze=!1,et,Qt="project",Hs)=>s.jsx(kg,{node:C,depth:J,groupDirectory:ee,projectId:Me,archivedBucket:ze,pinnedSessionIds:X,expandedParents:Wn,hasSessionSearchQuery:rt,normalizedSessionSearchQuery:yt,editingId:y,setEditingId:m,editTitle:h,setEditTitle:b,handleSaveEdit:_c,handleCancelEdit:Uc,toggleParent:Oc,handleSessionSelect:bn,handleSessionDoubleClick:Bc,togglePinnedSession:ke,handleShareSession:zc,copiedSessionId:kc,handleCopyShareUrl:$c,handleCopySessionId:Kc,handleUnshareSession:Wc,openSidebarMenuKey:R,setOpenSidebarMenuKey:D,renamingFolderId:I,getFoldersForScope:us,getSessionFolderId:Bt,removeSessionFromFolder:it,addSessionToFolder:Oe,createFolderAndStartRename:Dr,handleDeleteSession:Gc,handleRestoreSession:Hc,mobileVariant:t,alwaysShowActions:re,allowQuickArchiveAction:qe,renderSessionNode:Gn,secondaryMeta:et,renderContext:Qt,subtreeContainsEditing:Hs?.subtreeContainsEditing??Wg,menuOpenSessionId:Hs?.menuOpenSessionId??null,nodeStructureKey:Hs?.nodeStructureKey??"",childRenderExtrasFor:Hs?.childRenderExtrasFor})),ud=a.useMemo(()=>{const C=new Map;return Fr.forEach(J=>{const ee=J.groups.find(Me=>!Me.isArchivedBucket);ee?.folderScopes&&ee.folderScopes.length>0&&C.set(J.project.id,ee.folderScopes)}),C},[Fr]),fd=a.useCallback((C,J)=>{const ee=[];return J.forEach(Me=>{Me.isArchivedBucket||(ee.push(Me.directory),Me.folderScopes?.forEach(ze=>ee.push(ze.directory)))}),s.jsx(Dg,{directories:ee})},[]),xi=a.useCallback(C=>{Kn(C),He(J=>{const ee=new Set(J);return ee.has(C)?ee.delete(C):ee.add(C),ee})},[Kn]),hd=a.useCallback((C,J,ee,Me,ze,et,Qt)=>s.jsx(Lp,{group:C,groupKey:J,projectId:ee,hideGroupLabel:Me,dragHandleProps:ze,compactBodyPadding:et,hasSessionSearchQuery:rt,normalizedSessionSearchQuery:yt,groupSearchDataByGroup:gi,visibleSessionCount:K.get(J),collapsedGroups:Se,hideDirectoryControls:i,collapsedFolderIds:dt,toggleFolderCollapse:ot,renameFolder:Ue,deleteFolder:ge,showDeletionDialog:Xe,setDeleteFolderConfirm:Ae,renderSessionNode:Gn,showMoreGroupSessions:ai,resetGroupSessionLimit:Kn,mobileVariant:t,alwaysShowActions:re,activeProjectId:je,setActiveProjectIdOnly:_e,setActiveMainTab:ae,setSessionSwitcherOpen:Qe,openNewSessionDraft:at,addSessionToFolder:Oe,createFolderAndStartRename:Dr,renamingFolderId:I,renameFolderDraft:W,setRenameFolderDraft:Z,setRenamingFolderId:T,pinnedSessionIds:X,expandedParents:Wn,sessionOrderIndex:si,editingId:y,editTitle:h,openSidebarMenuKey:R,activeActivitySessionIds:V,unreadActivitySessionIds:ie,onToggleCollapsedGroup:xi,scrollContainerRef:Qt}),[rt,yt,gi,K,Se,i,dt,ot,Ue,ge,Xe,Gn,ai,Kn,t,re,je,_e,ae,Qe,at,Oe,Dr,I,W,X,Wn,si,y,h,R,V,ie,xi]),yi=!!(I||y||g),{selectionModeEnabled:Or,hasSelection:wi,selectedIdsSize:md,bulkScopeIsArchived:pd,derivedSelectionScope:gd,bulkScopeFolders:bd,bulkCanRemoveFromFolder:xd,handleToggleSelectionMode:yd,handleExitSelectionMode:wd,handleBulkMoveToFolder:vd,handleBulkCreateFolderAndMove:Sd,handleBulkRemoveFromFolder:jd,handleBulkDelete:kd,handleBulkRestore:Cd,confirmBulkDelete:Ad}=$g({isInlineEditing:yi,showDeletionDialog:Xe,foldersMap:Vt,folderScopesByProject:ud,addSessionsToFolder:Ge,removeSessionsFromFolders:kt,createFolderAndStartRename:ii,archiveSessions:oi,unarchiveSessions:jc,deleteSessions:ri,setBulkDeleteConfirm:Y}),vi=a.useCallback(()=>{ce.getState().closeMainSurfaces(),ae("chat"),t&&Qe(!1),is(),r?.()},[t,r,is,ae,Qe]),Nd=a.useCallback((C,J)=>{const ee=fe.find(et=>et.id===C);if(!ee)return;const Me=Ee(J.path)?.toLowerCase(),ze=!!(Me&&yn.get(C)?.has(Me));G({projectId:C,projectPath:ee.path,worktree:J,hasActiveSession:ze})},[yn,fe]),Id=a.useCallback(async({force:C})=>{const J=Ie;if(!J)return;const ee=Ee(J.worktree.path)?.toLowerCase();if(!!(ee&&yn.get(J.projectId)?.has(ee))){G({...J,hasActiveSession:!0}),oe.warning("Stop the active session before closing this worktree.");return}if(!Ze.deleteGitWorktree){oe.error("Closing worktrees is not supported by this runtime.");return}try{if(!(await Ze.deleteGitWorktree(J.projectPath,{directory:J.worktree.path,force:C}))?.success)throw new Error("Git worktree removal was not confirmed by the server.");let et=await rs(J.projectPath,Ze,{force:!0});const Qt=Ee(J.worktree.path);et!==null&&Qt!==null&&et.some(Rd=>Ee(Rd.path)===Qt)&&(et=await rs(J.projectPath,Ze,{force:!0}));const Hs=Qt!==null&&Ee(xe)===Qt,Ed=Qt!==null&&v===J.projectId&&Ee(N)===Qt;(Hs||Ed)&&Lr(J.projectId),G(null),et===null?oe.warning("Worktree closed, but the sidebar could not be refreshed."):oe.success("Worktree closed.")}catch(ze){const et=ze instanceof Error?ze.message:"Try again.";oe.error("Failed to close worktree.",{description:et})}},[yn,Ie,xe,Ze,Lr,rs,v,N]);return s.jsx(Fu,{delay:400,closeDelay:150,timeout:600,children:s.jsxs("div",{ref:p,className:_("relative flex h-full flex-col text-foreground overflow-x-hidden",t?"":"bg-transparent"),children:[s.jsx(Cm,{projectSections:Ut,activeProjectId:je,initialActiveSessionByProject:ne,persistActiveSessionByProject:ue,handleSessionSelect:bn,mobileVariant:t,openNewSessionDraft:is,setActiveMainTab:ae,setSessionSwitcherOpen:Qe}),!i&&!t?s.jsx(Bp,{onNewSession:vi,showSidebarToggle:!0}):null,s.jsx(Op,{hideDirectoryControls:i,handleOpenDirectoryDialog:Rr,onOpenArchive:()=>{t&&Qe(!1),pt(!0)},onOpenSettings:t?ni:void 0,onOpenInstances:t?Gs?.openInstances:void 0,instanceLabel:t?Gs?.instanceLabel:void 0,onOpenUpdate:t?Gs?.openUpdate:void 0,headerActionIconClass:dd,headerActionButtonClass:cd,isSessionSearchOpen:c,setIsSessionSearchOpen:d,sessionSearchInputRef:x,sessionSearchQuery:u,setSessionSearchQuery:f,hasSessionSearchQuery:rt,searchMatchCount:Zc+(st!=="workspace"||v===null?ed:0),selectionModeEnabled:Or,onToggleSelectionMode:yd,mobileVariant:t}),Rt==="error"||Rt==="unavailable"?s.jsx("div",{role:"alert",className:"mx-2 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&&Ut.length>0&&st==="workspace"?s.jsx(zp,{projects:Ut.map(C=>C.project),selectedProjectId:v,selectedWorktreePath:N,worktreesByProject:At,worktreeErrorsByProject:os,onSelectProject:Lr,onSelectWorktree:(C,J)=>{qs.getState().selectWorktree(C,J),_e(C);const ze=Ut.find(et=>et.project.id===C)?.groups.find(et=>Ee(et.directory)===Ee(J))?.sessions[0]?.session;ze?bn(ze.id,J,{keepPanelOpen:!0}):at({selectedProjectId:C,directoryOverride:J})},onCloseWorktree:Nd,onOpenDirectoryDialog:Rr,onOpenProjectEditDialog:S,onRemoveProject:Ye,totalSessionCount:od,getSessionCountForProject:C=>id.get(C)??0,hasActiveSessionByProject:ad,activeDirectoriesByProject:yn,hasUnseenByProject:ld,homeDirectory:te,mobileVariant:t}):null,s.jsx(Yp,{viewMode:st,timelineBoundaries:Yt,onOpenDirectoryDialog:Rr,stickyFolderHeaders:jt,sectionsForRender:st==="workspace"?rd:nd,allFoldersOnlySection:st==="workspace"?v===null?xn:null:xn,isAllFoldersView:st==="workspace"?v===null:st==="timeline",projectSections:Ut,activeProjectId:je,showOnlyMainWorkspace:l,hasSessionSearchQuery:rt,emptyState:pc,searchEmptyState:td,pinnedSessionIds:X,renderSessionNode:Gn,renderGroupSessions:hd,homeDirectory:te,collapsedProjects:k,hideDirectoryControls:i,projectRepoStatus:M,mobileVariant:t,alwaysShowActions:re,toggleProject:Pr,setActiveProjectIdOnly:_e,setActiveMainTab:ae,setSessionSwitcherOpen:Qe,openNewSessionDraft:at,openProjectEditDialog:S,removeProject:Ye,reorderProjects:Ve,getOrderedGroups:sd,setGroupOrderByProject:de,renderProjectStatusIndicator:fd,openSidebarMenuKey:R,setOpenSidebarMenuKey:D,isInlineEditing:yi}),t&&!(Or&&wi)?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(Pl,{variant:"mobile"}),s.jsx(Ne,{type:"button",variant:"default",size:"lg",className:"pointer-events-auto w-full shadow-lg",onClick:vi,"aria-label":"New session",children:s.jsx(P,{name:"chat-new",className:"size-4"})})]}):null,Or&&wi?s.jsx(zg,{selectedCount:md,scopeKey:gd,scopeFolders:bd,archivedBucket:pd,onMoveToFolder:vd,onCreateFolderAndMove:Sd,onRemoveFromFolder:jd,canRemoveFromFolder:xd,onRestore:Cd,onDelete:kd,onDone:wd}):null,t?null:s.jsx($p,{onOpenSettings:ni,onOpenShortcuts:xt,onOpenAbout:()=>{tt("about"),Fe(!0)},onOpenUpdate:xc,showRuntimeButtons:!0,showUpdateButton:yc}),s.jsx(Rg,{updateDialogOpen:$,setUpdateDialogOpen:O,updateStore:_t,editingProject:gc,setEditingProjectDialogId:S,handleSaveProjectEdit:bc,deleteSessionConfirm:F,setDeleteSessionConfirm:me,showDeletionDialog:Xe,setShowDeletionDialog:Ss,confirmDeleteSession:Fc,deleteFolderConfirm:q,setDeleteFolderConfirm:Ae,confirmDeleteFolder:Lc,closeWorktreeConfirm:Ie,setCloseWorktreeConfirm:G,confirmCloseWorktree:Id,bulkDeleteConfirm:U,setBulkDeleteConfirm:Y,confirmBulkDelete:Ad})]})})},Gy=a.memo(Gg),ua=6,Tt=.18,An=1.2,Nn=.38,ar=48,Hg=(e,t)=>e==="left"?t<0:t>0,Hy=(e,t,n)=>Math.min(1,Math.max(0,e==="left"?1+t/n:1-t/n)),qy=(e,t)=>t>=.999?"none":e==="left"?`translateX(${(t-1)*100}%)`:`translateX(${(1-t)*100}%)`,fa=(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)),Yy=e=>{const{side:t,dx:n,dy:r,dt:o,progress:i,isDragging:l}=e,c=n/Math.max(1,o);if(l){const d=t==="left"?c<-Tt:c>Tt,u=t==="left"?c>Tt:c<-Tt;return d||!u&&i<Nn}return Math.abs(n)>=ar&&Math.abs(r)<=Math.abs(n)*An&&Hg(t,n)},qg=e=>{const{side:t,isOpenAtStart:n,dx:r,dt:o,progress:i}=e,l=r/Math.max(1,o);return t==="left"?n?l<-Tt?!1:l>Tt?!0:i>Nn:l>Tt?!0:l<-Tt?!1:i>Nn:n?l>Tt?!1:l<-Tt?!0:i>Nn:l<-Tt?!0:l>Tt?!1:i>Nn},Yg='button, a, input, textarea, select, [contenteditable="true"], [data-no-drawer-swipe]',Vg=(e,t,n)=>{if(!(e instanceof Element))return!1;if(n?.excludeInteractive??!0){const i=e.closest(Yg);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},lr=Object.freeze({chunks:Object.freeze([]),byteLength:0,lastSequence:-1}),Oo=512*1024,Qg=new TextEncoder,Jg=new TextDecoder,qr=e=>{const t=Qg.encode(e);if(t.byteLength<=Oo)return{text:e,byteLength:t.byteLength};let n=t.byteLength-Oo;for(;n<t.byteLength&&(t[n]&192)===128;)n+=1;const r=t.subarray(n);return{text:Jg.decode(r),byteLength:r.byteLength}},Vs=(e,t)=>`${e}\0${t}`,Yr=(e,t)=>{let n=null;for(const r of e.keys())t(r)&&(n??=new Map(e),n.delete(r));return n},Xg="terminal-store";let ha=!1,ma=0;const tr=()=>typeof globalThis.crypto?.randomUUID=="function"?`tab-${globalThis.crypto.randomUUID()}`:(ma+=1,`tab-${Date.now().toString(36)}-${ma.toString(36)}`),Vr=e=>typeof e=="object"&&e!==null,Zg=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 eb=/^Terminal(?: (\d+))?$/,tb=e=>{let t=0;for(const n of e){const r=eb.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}`},Qr=(e,t)=>({id:e,terminalSessionId:null,lifecycle:"idle",label:t,iconKey:null,isConnecting:!1,createdAt:Date.now(),previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1}),Jr=e=>({tabs:[e],activeTabId:e.id}),zt=(e,t)=>e.tabs.findIndex(n=>n.id===t);let Xr=null,Zr=null;const sb=e=>{if(Zr&&Xr?.sessions===e.sessions&&Xr.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 Xr={sessions:e.sessions,nextTabId:e.nextTabId},Zr=t,t},nb=()=>{const e=zf(()=>pf());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))}},he=Bs()(jr(fl((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=tr(),c=Qr(l,"Terminal");return i.set(r,Jr(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(Vs(lt(n),r))??lr,createTab:n=>{const r=lt(n);if(!r)return"tab-invalid";const o=tr();return e(i=>{const l=new Map(i.sessions),c=l.get(r),d=i.nextTabId+1,u=tb(c?.tabs??[]),f=Qr(o,u);return c?l.set(r,{...c,tabs:[...c.tabs,f]}):l.set(r,Jr(f)),{sessions:l,nextTabId:d}}),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||zt(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 d=new Map(c.sessions),u=d.get(i);if(!u)return c;const f=zt(u,r);if(f<0||u.tabs[f]?.label===l)return c;const p=[...u.tabs];return p[f]={...p[f],label:l},d.set(i,{...u,tabs:p}),{sessions:d}})},setTabIconKey:(n,r,o)=>{const i=lt(n);e(l=>{const c=new Map(l.sessions),d=c.get(i);if(!d)return l;const u=zt(d,r);if(u<0)return l;const f=o?.trim()||null;if(d.tabs[u]?.iconKey===f)return l;const p=[...d.tabs];return p[u]={...p[u],iconKey:f},c.set(i,{...d,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 d=zt(c,r);if(d<0)return i;const u=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,x=Vs(o,r),y=i.buffers.has(x)?Yr(i.buffers,h=>h===x):null;if(u.length===0){const h=tr(),b=Qr(h,"Terminal");return l.set(o,Jr(b)),{sessions:l,nextTabId:i.nextTabId+1,...y?{buffers:y}:{},...p?{projectActionRuns:f}:{}}}let m=c.activeTabId;return c.activeTabId===r&&(m=u[Math.min(d,u.length-1)]?.id??u[0]?.id??null),l.set(o,{...c,tabs:u,activeTabId:m}),{sessions:l,...y?{buffers:y}:{},...p?{projectActionRuns:f}:{}}})},setTabSessionId:(n,r,o)=>{const i=lt(n);e(l=>{const c=new Map(l.sessions),d=c.get(i);if(!d)return l;const u=zt(d,r);if(u<0)return l;const f=d.tabs[u],p=o!==null&&f.terminalSessionId!==o,x=o?"running":f.terminalSessionId?"exited":f.lifecycle,y={...f,terminalSessionId:o,lifecycle:x,isConnecting:!1},m=Vs(i,r),h=p&&l.buffers.has(m)?Yr(l.buffers,g=>g===m):null,b=[...d.tabs];return b[u]=y,c.set(i,{...d,tabs:b}),{sessions:c,...h?{buffers:h}:{}}})},setTabLifecycle:(n,r,o)=>{const i=lt(n);e(l=>{const c=new Map(l.sessions),d=c.get(i);if(!d)return l;const u=zt(d,r);if(u<0)return l;const f=[...d.tabs];return f[u]={...f[u],lifecycle:o,isConnecting:!1},c.set(i,{...d,tabs:f}),{sessions:c}})},setConnecting:(n,r,o)=>{const i=lt(n);e(l=>{const c=new Map(l.sessions),d=c.get(i);if(!d)return l;const u=zt(d,r);if(u<0)return l;const f=[...d.tabs];return f[u]={...f[u],isConnecting:o},c.set(i,{...d,tabs:f}),{sessions:c}})},replaceBuffer:(n,r,o,i)=>{const l=lt(n);e(c=>{const d=c.sessions.get(l);if(!d||zt(d,r)<0)return c;const u=Vs(l,r),f=c.buffers.get(u)??lr;if(f.lastSequence>i)return c;const p=qr(o);if(f.lastSequence===i&&f.byteLength===p.byteLength&&f.chunks.map(m=>m.data).join("")===p.text)return c;const x=c.nextChunkId,y=new Map(c.buffers);return y.set(u,{chunks:p.text?[{id:x,data:p.text,byteLength:p.byteLength}]:[],byteLength:p.byteLength,lastSequence:i}),{buffers:y,nextChunkId:p.text?x+1:x}})},appendToBuffer:(n,r,o,i,l)=>{if(!o)return;const c=lt(n);e(d=>{const u=d.sessions.get(c);if(!u||zt(u,r)<0)return d;const f=Vs(c,r),p=d.buffers.get(f)??lr;if(i!==void 0&&i<=p.lastSequence)return d;const x=d.nextChunkId,y=qr(o),m=l!==void 0&&l!==o?qr(l).text:void 0,h={id:x,data:y.text,...m!==void 0?{replayData:m}:{},byteLength:y.byteLength},b=[...p.chunks,h];let g=p.byteLength+h.byteLength;for(;g>Oo&&b.length>1;){const w=b.shift();if(!w)break;g-=w.byteLength}const S=new Map(d.buffers);return S.set(f,{chunks:b,byteLength:g,lastSequence:i??p.lastSequence}),{buffers:S,nextChunkId:x+1}})},setTabPreviewUrl:(n,r,o,i={})=>{const l=lt(n);e(c=>{const d=new Map(c.sessions),u=d.get(l);if(!u)return c;const f=zt(u,r);if(f<0)return c;const p=u.tabs[f],x=i.autoOpened??p.previewAutoOpened,y=i.locked??p.previewUrlLocked;if(p.previewUrl===o&&p.previewAutoOpened===x&&p.previewUrlLocked===y)return c;const m=[...u.tabs];return m[f]={...p,previewUrl:o,previewAutoOpened:x,previewUrlLocked:y},d.set(l,{...u,tabs:m}),{sessions:d}})},markPreviewAutoOpened:(n,r)=>{const o=lt(n);e(i=>{const l=new Map(i.sessions),c=l.get(o);if(!c)return i;const d=zt(c,r);if(d<0)return i;const u=c.tabs[d];if(!u.previewUrl||u.previewAutoOpened)return i;const f=[...c.tabs];return f[d]={...u,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=Vs(r,""),c=Yr(o.buffers,u=>u.startsWith(l)),d=Object.fromEntries(Object.entries(o.projectActionRuns).filter(([,u])=>u.directory!==r));return{sessions:i,...c?{buffers:c}:{},projectActionRuns:d}})},clearAll:()=>{e({sessions:new Map,buffers:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1})}}),{name:Xg,storage:nb(),partialize:sb,merge:(e,t)=>{if(!Vr(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[d,u]=c;if(typeof d!="string"||!Vr(u))continue;const f=Array.isArray(u.tabs)?u.tabs:[],p=[],x=new Map;for(const b of f){if(!Vr(b))continue;const g=typeof b.id=="string"?b.id:null;if(!g)continue;const S=Zg(g);S!==null&&(o=Math.max(o,S));const w=S===null?g:tr();x.set(g,w),p.push({id:w,label:typeof b.label=="string"?b.label:"Terminal",iconKey:typeof b.iconKey=="string"?b.iconKey:null,terminalSessionId:null,lifecycle:"idle",createdAt:typeof b.createdAt=="number"?b.createdAt:Date.now(),isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(p.length===0)continue;const y=typeof u.activeTabId=="string"?u.activeTabId:null,m=y?x.get(y)??y:null,h=m?p.some(b=>b.id===m):!1;r.set(d,{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"&&!ha){ha=!0;const e=he.persist,t=()=>{he.getState().hasHydrated||he.setState({hasHydrated:!0})};e?.hasHydrated?.()?t():e?.onFinishHydration?e.onFinishHydration(t):t()}function rb(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 eo(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 ob=(e,t)=>{const n=`${e??""} ${t??""}`;return/mac|iphone|ipad|darwin/i.test(n)?"mac":"other"},ib=e=>e.key.length===1?e.key.toLowerCase():e.code==="KeyC"?"c":e.code==="KeyV"?"v":e.code==="Insert"?"insert":e.key.toLowerCase(),ab=(e,t,n)=>{if(e.altKey)return null;const r=ib(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},In=e=>typeof e=="string"&&e.trim().length>0;async function pa(e){return In(e)?(await xs(e)).ok:!1}async function lb(){if(typeof navigator>"u"||!navigator.clipboard?.readText)return null;try{return await navigator.clipboard.readText()||null}catch{return null}}const cb=(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))}},db=(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 ub=null;const fb=()=>ub??=Promise.all([mt(()=>import("./vendor-xterm-xterm-B-qIQCd3.js"),[]),mt(()=>import("./vendor-xterm-addon-fit-DX4qG4td.js"),[])]).then(([e,t])=>({Xterm:e,Fit:t})),hb=2e3,mb=()=>{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,hb))]).then(()=>{})},pb=(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),d=(Number.parseInt(c.paddingLeft,10)||0)+(Number.parseInt(c.paddingRight,10)||0),u=(Number.parseInt(c.paddingTop,10)||0)+(Number.parseInt(c.paddingBottom,10)||0);return{cols:Math.max(2,Math.floor((e.clientWidth-d-15)/i)),rows:Math.max(1,Math.floor((e.clientHeight-u)/l))}},dc=a.forwardRef(({sessionKey:e,chunks:t,onInput:n,onResize:r,theme:o,fontFamily:i,fontSize:l,className:c,enableTouchScroll:d=!1,autoFocus:u=!0,isVisible:f=!0},p)=>{const x=a.useRef(null),y=a.useRef(null),m=a.useRef(null),h=a.useRef(n),b=a.useRef(r),g=a.useRef(o),S=a.useRef(i),w=a.useRef(l),E=a.useRef(null),A=a.useRef(null),k=a.useRef(null),j=a.useRef(""),v=a.useRef(!1),N=a.useRef(0),M=a.useRef(f),L=a.useRef(!1),[K,z]=a.useState(0),[$,O]=a.useState(0),[R,D]=a.useState(!1),[I,T]=a.useState(!1);h.current=n,b.current=r,M.current=f,g.current=o,S.current=i,w.current=l,a.useLayoutEffect(()=>{const G=x.current;if(!G)return;const U=pb(G,i,l);A.current=U,U&&b.current(U.cols,U.rows)},[i,l]);const W=a.useCallback(()=>{const G=x.current,U=y.current;if(!G||!U||!m.current||!M.current)return;const Y=G.getBoundingClientRect();if(!(Y.width<24||Y.height<24))try{m.current.fit();const X={cols:U.cols,rows:U.rows};(!E.current||E.current.cols!==X.cols||E.current.rows!==X.rows)&&(E.current=X,b.current(X.cols,X.rows)),L.current||(L.current=!0,z(se=>se+1))}catch{}},[]),Z=a.useCallback(()=>{if(v.current||!j.current||!y.current)return;const G=y.current,U=j.current;if(j.current="",!U)return;v.current=!0;const Y=N.current;G.write(U,()=>{y.current!==G||N.current!==Y||(v.current=!1,j.current&&Z())})},[]),F=a.useCallback(()=>{k.current=null,j.current="",v.current=!1,N.current+=1;const G=y.current;if(!G){O(U=>U+1);return}try{G.reset()}catch{O(U=>U+1)}},[]),me=a.useCallback(G=>{G?.preventDefault(),T(In(y.current?.getSelection())),D(!0)},[]),q=a.useCallback(G=>{G.stopPropagation();const U=y.current,Y=U?.getSelection()??"";U?.focus(),In(Y)&&pa(Y)},[]),Ae=a.useCallback(G=>{G.stopPropagation();const U=y.current;U?.focus(),lb().then(Y=>{Y&&y.current===U&&U&&U.paste(Y)})},[]),Ie=a.useCallback(G=>{G.stopPropagation();const U=y.current;U?.focus();try{U?.selectAll()}catch{}T(In(U?.getSelection()))},[]);return a.useEffect(()=>{const G=x.current;if(!G)return;let U=!1,Y=null,X=null,se=null,we=null,pe=[];const V=()=>{Y&&M.current&&(Y.options.cursorBlink=!0)},Q=Se=>{Se.relatedTarget instanceof Node&&G.contains(Se.relatedTarget)||Y&&(Y.options.cursorBlink=!1)},ie=()=>{Y&&M.current&&G.contains(document.activeElement)&&(Y.options.cursorBlink=!0)},ke=()=>{Y&&(Y.options.cursorBlink=!1)};return G.addEventListener("focusin",V),G.addEventListener("focusout",Q),window.addEventListener("focus",ie),window.addEventListener("blur",ke),Promise.all([fb(),mb()]).then(([{Xterm:Se,Fit:He}])=>{if(U)return;const H=g.current,de=S.current,ne=w.current;Y=new Se.Terminal({...eo(de,ne,H),...A.current??{}});const ue=new He.FitAddon;Y.loadAddon(ue),Y.open(G),y.current=Y,m.current=ue;const ve=typeof navigator>"u"?"other":ob(navigator.userAgentData?.platform??navigator.platform??"",navigator.userAgent??""),Le=Y;Y.attachCustomKeyEventHandler(be=>{if(be.type!=="keydown")return!0;const te=Le.getSelection(),xe=ab({key:be.key,code:be.code,ctrlKey:be.ctrlKey,shiftKey:be.shiftKey,metaKey:be.metaKey,altKey:be.altKey},ve,In(te));return xe==="copy"?(pa(te),!1):xe!=="ignore"}),pe=[Y.onData(be=>h.current(be))],X=new ResizeObserver(()=>{se&&clearTimeout(se),se=setTimeout(W,80)}),X.observe(G),W(),we=requestAnimationFrame(W)}),()=>{U=!0;const Se=document.activeElement;Se instanceof HTMLElement&&G.contains(Se)&&(Se.blur(),window.Capacitor?.getPlatform?.()==="android"&&mt(async()=>{const{Keyboard:H}=await import("./vendor-capacitor-keyboard-DJD81I9f.js");return{Keyboard:H}},__vite__mapDeps([45,10,4,6])).then(({Keyboard:H})=>H.hide()).catch(()=>{})),X?.disconnect(),se&&clearTimeout(se),we!==null&&cancelAnimationFrame(we),G.removeEventListener("focusin",V),G.removeEventListener("focusout",Q),window.removeEventListener("focus",ie),window.removeEventListener("blur",ke),pe.forEach(He=>He.dispose()),Y?.dispose(),y.current=null,m.current=null,E.current=null,k.current=null,j.current="",v.current=!1,N.current+=1,L.current=!1}},[W,$]),a.useEffect(()=>{const G=y.current;G&&(G.options.theme=eo(i,l,o).theme,G.options.fontFamily=eo(i,l,o).fontFamily,G.options.fontSize=l)},[i,l,o]),a.useEffect(()=>{const G=y.current,U=x.current;!G||!U||(G.options.cursorBlink=f&&document.hasFocus()&&U.contains(document.activeElement))},[f,K]),a.useEffect(()=>{if(!y.current)return;if(t.length===0){k.current!==null&&F();return}const U=k.current;let Y=-1;if(U!==null){for(let we=t.length-1;we>=0;we-=1){const pe=t[we].id;if(pe===U){Y=we;break}if(pe<U)break}if(Y<0){F();return}}const X=Y<0,se=Y>=0?t.slice(Y+1):t;j.current+=se.map(we=>X?we.replayData??we.data:we.data).join(""),k.current=t.at(-1)?.id??null,Z()},[t,Z,K,F]),a.useEffect(()=>{if(!u||!f)return;const G=requestAnimationFrame(()=>y.current?.focus());return()=>cancelAnimationFrame(G)},[u,f,K,e]),a.useEffect(()=>{const G=x.current,U=y.current;if(!d||!G||!U)return;let Y=null,X=null,se="idle",we=0,pe=0,V=0,Q=0,ie=null;const ke=Math.max(12,l+2),Se=()=>{window.Capacitor?.getPlatform?.()==="android"&&mt(async()=>{const{Keyboard:xe}=await import("./vendor-capacitor-keyboard-DJD81I9f.js");return{Keyboard:xe}},__vite__mapDeps([45,10,4,6])).then(({Keyboard:xe})=>xe.show()).catch(()=>{})},He=()=>{X&&(clearTimeout(X),X=null)},H=(te,xe)=>{const fe=G.querySelector("canvas");return fe?cb(te,xe,fe.getBoundingClientRect(),U.cols,U.rows):null},de=(te,xe)=>{const fe=G.querySelector("canvas");if(!fe)return;const je=fe.getBoundingClientRect(),Ye=je.left+(xe.column+.5)/U.cols*je.width,_e=je.top+(xe.row+.5)/U.rows*je.height;fe.dispatchEvent(new MouseEvent(te,{bubbles:!0,cancelable:!0,button:0,buttons:1,clientX:Ye,clientY:_e}))},ne=()=>{document.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0,button:0,buttons:0}))},ue=te=>{te.pointerType!=="touch"||Y!==null||(Y=te.pointerId,se="pending",we=te.clientX,pe=te.clientY,V=te.clientY,Q=0,ie=null,G.setPointerCapture(te.pointerId),X=setTimeout(()=>{if(X=null,Y!==te.pointerId||se!=="pending")return;const xe=H(we,pe);if(!xe)return;const fe=U.buffer.active,je=Math.max(0,fe.length-U.rows-fe.viewportY+xe.row),Ye=fe.getLine(je),_e=Array.from({length:U.cols},(ae,Fe)=>Ye?.getCell(Fe)?.getChars()??""),De=db(_e,xe.column),Ve={column:De.startColumn,row:xe.row};ie={column:De.endColumn,row:xe.row},se="selecting",de("mousedown",Ve),de("mousemove",ie)},350))},ve=te=>{if(Y!==te.pointerId)return;if(se==="selecting"){const je=H(te.clientX,te.clientY);je&&(!ie||je.column!==ie.column||je.row!==ie.row)&&(ie=je,de("mousemove",je)),te.cancelable&&te.preventDefault();return}if(se==="pending"){if(Math.hypot(te.clientX-we,te.clientY-pe)<8)return;He(),se="scrolling"}if(se!=="scrolling")return;const xe=V-te.clientY;V=te.clientY,Q+=xe;const fe=Math.trunc(Q/ke);fe&&(U.scrollLines(fe),Q-=fe*ke),te.cancelable&&te.preventDefault()},Le=te=>{if(Y!==te.pointerId)return;const xe=se==="pending",fe=se==="selecting";He(),G.hasPointerCapture(te.pointerId)&&G.releasePointerCapture(te.pointerId),Y=null,se="idle",fe&&ne(),xe&&(U.focus(),Se())},be=te=>{if(Y!==te.pointerId)return;const xe=se==="selecting";He(),G.hasPointerCapture(te.pointerId)&&G.releasePointerCapture(te.pointerId),Y=null,se="idle",xe&&ne()};return G.addEventListener("pointerdown",ue),G.addEventListener("pointermove",ve,{passive:!1}),G.addEventListener("pointerup",Le),G.addEventListener("pointercancel",be),()=>{He(),G.removeEventListener("pointerdown",ue),G.removeEventListener("pointermove",ve),G.removeEventListener("pointerup",Le),G.removeEventListener("pointercancel",be)}},[d,l,K]),a.useImperativeHandle(p,()=>({focus:()=>y.current?.focus(),fit:W,getSelection:()=>{const G=y.current,U=G?.getSelectionPosition(),Y=G?.getSelection()??"";return!U||!Y.trim()?null:{text:Y,startLine:U.start.y+1,endLine:U.end.y+1}}}),[W]),s.jsxs(Ar,{open:R,onOpenChange:D,children:[s.jsx(Nr,{render:s.jsx("div",{ref:x,"data-terminal-owner":"main",className:_("terminal-viewport-container h-full w-full overflow-hidden touch-none",c),onContextMenu:me})}),s.jsxs(Ir,{className:"min-w-[180px]",children:[s.jsxs(Ps,{disabled:!I,onClick:q,children:[s.jsx(P,{name:"file-copy",className:"mr-2 h-4 w-4"})," ","Copy"]}),s.jsxs(Ps,{onClick:Ae,children:[s.jsx(P,{name:"clipboard",className:"mr-2 h-4 w-4"})," ","Paste"]}),s.jsx(Zl,{}),s.jsx(Ps,{onClick:Ie,children:"Select All"})]})]})});dc.displayName="TerminalViewport";const gb=({directory:e,tabId:t,sessionId:n,sessionKey:r,isActive:o,isTerminalVisible:i,terminal:l,theme:c,fontFamily:d,fontSize:u,enableTouchScroll:f,lastViewportSizeRef:p,onInput:x,controllerRef:y})=>{const m=he(w=>e&&t?w.getBuffer(e,t).chunks:lr.chunks),h=a.useRef(null),b=o&&i,g=a.useCallback(w=>{h.current=w,y&&(y.current=o?w:y.current),!o&&y&&y.current===w&&(y.current=null)},[y,o]);a.useEffect(()=>{if(!o||!i)return;const w=requestAnimationFrame(()=>{h.current?.fit()});return()=>cancelAnimationFrame(w)},[o,i,r,n]);const S=a.useCallback((w,E)=>{if(!o)return;const A=p.current;(!A||A.cols!==w||A.rows!==E)&&(p.current={cols:w,rows:E}),n&&l.resize({sessionId:n,cols:w,rows:E}).catch(()=>{})},[o,p,n,l]);return s.jsx("div",{className:_("h-full w-full",o?"block":"hidden"),"aria-hidden":!o,children:s.jsx(dc,{ref:g,sessionKey:r,chunks:m,onInput:x,onResize:S,theme:c,fontFamily:d,fontSize:u,enableTouchScroll:f,autoFocus:b,isVisible:b},r)})},ga=({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(Gt,{modal:!1,children:[s.jsx(Ht,{asChild:!0,children:s.jsxs(Ne,{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(P,{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(P,{name:"arrow-down-s",className:"size-4 shrink-0 opacity-60"})]})}),s.jsxs(qt,{align:"start",className:"w-64",children:[e.map(c=>{const d=c.id===(l?.id??t);return s.jsxs(ht,{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})]}),d?s.jsx(P,{name:"check",className:"size-3.5 shrink-0 text-primary"}):null,s.jsx("button",{type:"button",title:c.closeLabel,"aria-label":c.closeLabel,onClick:u=>{u.preventDefault(),u.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(P,{name:"close",className:"size-3"})})]},c.id)}),s.jsx(nn,{}),s.jsxs(ht,{onClick:o,children:[s.jsx(P,{name:"add",className:"size-3.5"}),"New tab"]})]})]})},bb=({leading:e,icon:t,title:n,actions:r,className:o})=>s.jsxs("header",{className:_("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(P,{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]}),xb=({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=d=>{e&&d.preventDefault()};return s.jsxs(s.Fragment,{children:[s.jsx(Ne,{type:"button",size:i,variant:"outline",onPointerDown:c,onClick:()=>r("esc"),disabled:n,children:"Esc"}),s.jsxs(Ne,{type:"button",size:i,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("tab"),disabled:n,children:[s.jsx(P,{name:"arrow-right",className:"h-4 w-4"}),s.jsx("span",{className:"sr-only",children:"Tab"})]}),s.jsxs(Ne,{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(Ne,{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(Ne,{type:"button",size:i,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("arrow-up"),disabled:n,children:[s.jsx(P,{name:"arrow-up"}),s.jsx("span",{className:"sr-only",children:"Arrow up"})]}),s.jsxs(Ne,{type:"button",size:i,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("arrow-left"),disabled:n,children:[s.jsx(P,{name:"arrow-left"}),s.jsx("span",{className:"sr-only",children:"Arrow left"})]}),s.jsxs(Ne,{type:"button",size:i,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("arrow-down"),disabled:n,children:[s.jsx(P,{name:"arrow-down"}),s.jsx("span",{className:"sr-only",children:"Arrow down"})]}),s.jsxs(Ne,{type:"button",size:i,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("arrow-right"),disabled:n,children:[s.jsx(P,{name:"arrow-right"}),s.jsx("span",{className:"sr-only",children:"Arrow right"})]}),s.jsxs(Ne,{type:"button",size:i,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("enter"),disabled:n,children:[s.jsx(P,{name:"arrow-go-back"}),s.jsx("span",{className:"sr-only",children:"Enter"})]})]})},yb="\x1B",wb=new RegExp(`${yb}\\[[0-9;?]*[ -/]*[@-~]`,"g"),vb=/(https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[(?:::1|::)\])(?::\d{2,5})?(?:\/[^\s<>'"`]*)?)/gi,Sb=/(?:➜\s*(?:Local|Network):)|\b(?:local|network|loopback|serving|listening|available|ready|started|running|server|vite|webpack|next\.js|astro|sveltekit|nuxt)\b/i,jb=/Serving HTTP on .*? port (\d{2,5})/i,kb=new Set([".",",",";",":","!","?"]),Cb=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(kb.has(n)){t=t.slice(0,-1);continue}break}return t},ba=e=>{let t=Cb(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},Ab=e=>{if(!e)return null;const t=e.replace(wb,""),n=t.match(jb);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(!Sb.test(o))continue;const i=Array.from(o.matchAll(vb));if(i.length===0)continue;const l=i.find(c=>{try{return!!new URL(ba(c[1])).port}catch{return!1}});return ba((l??i[0])[1])}return null},Nb=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 nt("/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)}},Ib={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},Eb=(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 Ib[e]},uc=e=>{const t=e[0]?.toUpperCase();return!t||t<"A"||t>"Z"?null:String.fromCharCode(t.charCodeAt(0)&31)},Rb=(e,t)=>e&&(t==="ctrl"?uc(e)??e:e.length===1&&e!=="\x1B"?`\x1B${e}`:e),fc={cols:80,rows:24},xa={Tab:"tab",Enter:"enter",ArrowUp:"arrow-up",ArrowDown:"arrow-down",ArrowLeft:"arrow-left",ArrowRight:"arrow-right",Escape:"esc"};class Db{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 d=Ab(c);if(!d||this.pendingUrls.has(d))return;const u=this.probeGeneration;this.pendingUrls.add(d),Nb(d).then(f=>{if(this.pendingUrls.delete(d),!f||this.probeGeneration!==u)return;const p=he.getState().getDirectoryState(t)?.tabs.find(x=>x.id===n);!p||p.previewUrlLocked||p.previewUrl===d||o(t,n,d,{locked:!1,autoOpened:!1})})}}const Pb=(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"?uc(o):null};function Mb({terminal:e,effectiveDirectory:t,activeTabId:n,terminalSessionId:r,terminalLifecycle:o,hasOpenedTerminalViewport:i,terminalHydrated:l,terminalShell:c,terminalLoginShell:d,terminalAppearanceRef:u,enableTabs:f,hasActiveContext:p,focusTerminalWhenWindowActive:x,tabs:y}){const m=he(U=>U.ensureDirectory),h=he(U=>U.setTabSessionId),b=he(U=>U.setTabLifecycle),g=he(U=>U.setConnecting),S=he(U=>U.appendToBuffer),w=he(U=>U.replaceBuffer),E=he(U=>U.setTabPreviewUrl),[A,k]=a.useState(null),[j,v]=a.useState(!1),[N,M]=a.useState(!1),L=a.useRef(new Map),K=a.useRef(null),z=a.useRef(n),$=a.useRef(r),O=a.useRef(t),R=a.useRef(null),D=a.useRef(new Set),I=a.useRef(new Map),T=a.useRef(y),W=a.useRef(l),Z=a.useRef(i),F=a.useRef(e);T.current=y,W.current=l,Z.current=i,F.current=e;const me=a.useCallback(()=>{const U=z.current;U&&I.current.get(U)?.reset()},[]);a.useEffect(()=>{$.current=r},[r]),a.useEffect(()=>{!r||!e.updateAppearance||e.updateAppearance(r,u.current).catch(()=>{})},[u,e,r]),a.useEffect(()=>{z.current=n},[n]),a.useEffect(()=>{O.current=t},[t]);const q=a.useCallback(()=>{for(const U of L.current.values())try{U()}catch{}L.current.clear(),K.current=null,M(!1)},[]);a.useEffect(()=>()=>{q(),$.current=null},[q]);const Ae=a.useCallback((U,Y,X)=>{let se=I.current.get(Y);se||(se=new Db,I.current.set(Y,se)),se.scan(U,Y,X,E)},[E]),Ie=a.useCallback((U,Y,X)=>{if(L.current.has(X)){K.current=X;return}const se=Ei(),we=()=>Ei()===se&&O.current===U&&he.getState().getDirectoryState(U)?.tabs.find(V=>V.id===Y)?.terminalSessionId===X,pe=e.connect(X,{onEvent:V=>{if(we())switch(V.type){case"snapshot":{z.current===Y&&$.current===X?(g(U,Y,!1),k(null),v(!1),M(!1),x()):g(U,Y,!1),w(U,Y,V.data??"",V.sequence??0),Ae(U,Y,V.data??""),V.status==="exited"&&b(U,Y,"exited");break}case"reconnecting":{z.current===Y&&(k(null),v(!1),M(!0));break}case"data":{V.data&&(S(U,Y,V.data,V.sequence,V.replayData),Ae(U,Y,V.data));break}case"exit":{const Q=typeof V.exitCode=="number"?V.exitCode:null,ie=typeof V.signal=="number"?V.signal:null,Se=!!he.getState().getDirectoryState(U)?.tabs.find(He=>He.id===Y)?.label?.startsWith("Action:");S(U,Y,`\\r\\n[Process exited${Q!==null?` with code ${Q}`:""}${ie!==null?` (signal ${ie})`:""}]\\r\\n`),b(U,Y,"exited"),z.current===Y&&(g(U,Y,!1),k(Se?null:"Terminal session ended"),v(!1),M(!1));break}}},onError:(V,Q)=>{if(!we())return;const ie=z.current===Y;if(!Q){ie&&(k(null),v(!1));return}if(V.code==="SESSION_NOT_FOUND"&&!he.getState().getDirectoryState(U)?.tabs.find(Se=>Se.id===Y)?.label?.startsWith("Action:")){ie&&(k(null),v(!1),g(U,Y,!1),M(!1)),h(U,Y,null),b(U,Y,"idle");return}ie&&(M(!1),k(`Connection failed: ${V.message}`),v(!0),g(U,Y,!1),b(U,Y,"exited"),h(U,Y,null))}});L.current.set(X,()=>pe.close()),K.current=X},[S,x,w,Ae,g,b,h,e]),G=a.useMemo(()=>y.map(U=>`${U.id}:${U.terminalSessionId??""}`).join(","),[y]);return a.useEffect(()=>{if(!l||!i||!t)return;const U=t,Y=new Set;for(const X of y)X.terminalSessionId&&(Y.add(X.terminalSessionId),Ie(U,X.id,X.terminalSessionId));for(const[X,se]of L.current)if(!Y.has(X)){try{se()}catch{}L.current.delete(X)}},[G,y,t,l,i,Ie]),a.useEffect(()=>gf(()=>{if(!W.current||!Z.current)return;const U=O.current;if(!U)return;const Y=[];for(const se of T.current){if(!se.terminalSessionId)continue;he.getState().getDirectoryState(U)?.tabs.find(pe=>pe.id===se.id)?.terminalSessionId===se.terminalSessionId&&Y.push({id:se.id,terminalSessionId:se.terminalSessionId})}if(L.current.clear(),K.current=null,Y.length===0)return;M(!0),k(null),v(!1);for(const se of Y)Ie(U,se.id,se.terminalSessionId);const X=R.current;if(X)for(const se of Y)F.current.resize({sessionId:se.terminalSessionId,...X}).catch(()=>{})}),[Ie]),a.useEffect(()=>{let U=!1;if(!l||!i)return;if(!t){k(p?"No working directory available for terminal.":"Select a session to open the terminal.");return}return(async()=>{const X=t;if(!O.current||O.current!==X)return;if(!he.getState().getDirectoryState(X)){m(X);return}const we=he.getState().getDirectoryState(X);if(!we||we.tabs.length===0)return;const pe=we.activeTabId??we.tabs[0]?.id??null;if(!pe)return;const V=we.tabs.find(H=>H.id===pe)??we.tabs[0],Q=V?.terminalSessionId??null,ie=V?.lifecycle??"idle",ke=!!V?.label?.startsWith("Action:"),Se=he.getState().getBuffer(X,pe),He=Se.byteLength>0||Se.chunks.length>0;if(!Q){if(ie==="exited"){g(X,pe,!1);return}if(ke&&He){g(X,pe,!1);return}const H=`${X}\0${pe}`;if(D.current.has(H))return;const de=R.current??fc;D.current.add(H),k(null),v(!1),M(!1),g(X,pe,!0);try{const ne=await e.createSession({cwd:X,sessionId:pe,cols:de.cols,rows:de.rows,shell:c,loginShell:d,...u.current});if(!he.getState().getDirectoryState(X)?.tabs.find(Le=>Le.id===pe)){try{await e.close(ne.sessionId)}catch{}return}h(X,pe,ne.sessionId);const ve=R.current;ve&&(ve.cols!==de.cols||ve.rows!==de.rows)&&e.resize({sessionId:ne.sessionId,...ve}).catch(()=>{});return}catch(ne){const ue=he.getState().getDirectoryState(X)?.tabs.find(ve=>ve.id===pe);if(!ue||ue.terminalSessionId||(g(X,pe,!1),O.current!==X||z.current!==pe))return;k(ne instanceof Error?ne.message:"Failed to start terminal session"),v(!0),M(!1);return}finally{D.current.delete(H)}}!Q||U||($.current=Q)})(),()=>{U=!0}},[p,t,r,o,n,i,f,l,m,g,b,h,e,d,c,u]),{connectionError:A,setConnectionError:k,isFatalError:j,setIsFatalError:v,isReconnectPending:N,setIsReconnectPending:M,terminalIdRef:$,lastViewportSizeRef:R,directoryRef:O,activeTabIdRef:z,disconnectStream:q,resetTerminalPreviewScan:me,startStream:Ie}}function Tb({terminal:e,terminalIdRef:t,isReconnectPending:n,setConnectionError:r,showQuickKeys:o,isTerminalVisible:i,lastViewportSizeRef:l,terminalSessionId:c,useTouchTerminalInput:d}){const[u,f]=a.useState(null),p=a.useRef(null),x=a.useCallback(()=>{d||p.current?.focus()},[d]),y=a.useCallback(()=>{d||typeof document<"u"&&!document.hasFocus()||p.current?.focus()},[d]);a.useEffect(()=>{!o&&u!==null&&f(null)},[o,u]),a.useEffect(()=>{!c&&u!==null&&f(null)},[c,u]);const m=a.useCallback(w=>{if(!w||n)return;let E=w,A=!1;u&&w.length>0&&(E=Rb(w,u),A=!0);const k=t.current;k&&(e.sendInput(k,E).catch(j=>{n||r(j instanceof Error?j.message:"Failed to send input")}),A&&(f(null),x()))},[u,x,n,r,e,t]),h=a.useCallback((w,E)=>{const A=l.current;if((!A||A.cols!==w||A.rows!==E)&&(l.current={cols:w,rows:E}),!i)return;const k=t.current;k&&e.resize({sessionId:k,cols:w,rows:E}).catch(()=>{})},[i,l,e,t]),b=a.useCallback(w=>{f(E=>E===w?null:w),x()},[x]),g=a.useCallback(w=>{const E=Eb(w,u);E&&(m(E),f(null),x())},[u,x,m]),S=a.useCallback(w=>{if(w.repeat)return;const E=w.key;if(!E||E==="Control"||E==="Meta"||E==="Alt"||E==="Shift")return;const A=E.length===1?E.toLowerCase():E;if(A in xa){w.preventDefault(),w.stopPropagation(),g(xa[A]);return}const k=Pb(w,u);k&&(w.preventDefault(),w.stopPropagation(),m(k),f(null),x())},[u,x,g,m]);return a.useEffect(()=>{if(!(!o||!u||!c))return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[u,S,o,c]),{activeModifier:u,setActiveModifier:f,terminalControllerRef:p,focusTerminalController:x,focusTerminalWhenWindowActive:y,handleViewportInput:m,handleViewportResize:h,handleModifierToggle:b,handleMobileKeyPress:g}}function Fb({terminal:e,effectiveDirectory:t,activeTabId:n,enableTabs:r,terminalShell:o,terminalLoginShell:i,terminalAppearanceRef:l,lastViewportSizeRef:c,directoryRef:d,activeTabIdRef:u,terminalIdRef:f,resetTerminalPreviewScan:p,startStream:x,setConnectionError:y,setIsFatalError:m,setIsReconnectPending:h}){const b=he(K=>K.createTab),g=he(K=>K.setActiveTab),S=he(K=>K.closeTab),w=he(K=>K.setTabSessionId),E=he(K=>K.setTabLifecycle),[A,k]=a.useState(!1),j=a.useCallback(async()=>{if(!t||A)return;const K=he.getState().getDirectoryState(t),z=n??K?.activeTabId??K?.tabs[0]?.id??null;if(!z)return;const $=K?.tabs.find(O=>O.id===z)?.terminalSessionId??null;if(!(!$||!e.restartSession)){k(!0),y(null),m(!1),h(!1),p();try{const O=c.current??fc,R=await e.restartSession($,{cwd:t,shell:o,loginShell:i,...O,...l.current});if(he.getState().getDirectoryState(t)?.tabs.find(I=>I.id===z)?.terminalSessionId!==$||(w(t,z,R.sessionId),E(t,z,"running"),d.current!==t||u.current!==z))return;f.current=R.sessionId,x(t,z,R.sessionId)}catch(O){if(he.getState().getDirectoryState(t)?.tabs.find(D=>D.id===z)?.terminalSessionId!==$||d.current!==t||u.current!==z)return;y(O instanceof Error?O.message:"Failed to restart terminal"),m(!1),h(!1),f.current=$,x(t,z,$)}finally{k(!1)}}},[n,u,d,t,r,A,c,p,y,m,h,E,w,x,e,l,f,i,o]),v=a.useCallback(async()=>{await j()},[j]),N=a.useCallback(()=>{if(!t)return;const K=b(t);g(t,K),y(null),m(!1),h(!1)},[b,t,g,y,m,h]),M=a.useCallback(K=>{t&&(g(t,K),y(null),m(!1),h(!1))},[t,g,y,m,h]),L=a.useCallback(K=>{if(!t)return;y(null),m(!1),h(!1);const z=he.getState().getDirectoryState(t)?.tabs.find($=>$.id===K)?.terminalSessionId;(async()=>{z&&await e.close(z),S(t,K)})().catch($=>y($ instanceof Error?$.message:"Terminal session ended"))},[S,t,y,m,h,e]);return{isRestarting:A,handleRestart:j,handleHardRestart:v,handleCreateTab:N,handleSelectTab:M,handleCloseTab:L}}const Vy=({visible:e,onCloseView:t,terminalHeaderSlot:n})=>{const{terminal:r,runtime:o}=Os(),{currentTheme:i}=Xa(),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}=Lu(),d=ce(ae=>ae.terminalFontSize),u=ce(ae=>ae.terminalShell),f=ce(ae=>ae.terminalLoginShells.includes(ae.terminalShell)),{isMobile:p,isTablet:x,hasTouchOnlyPointer:y}=dn(),m=p||x,h=(m||y)&&o.platform==="web",b=!0,g=ce(ae=>ae.showTerminalQuickKeysOnDesktop),S=m||g,w=Te(ae=>ae.currentSessionId),E=Te(ae=>ae.newSessionDraft),A=w!==null||E?.open===!0,k=Ou()??null,j=he(ae=>k?ae.sessions.get(k):void 0),v=he(ae=>ae.hasHydrated),N=ce(ae=>ae.openContextPreview),M=a.useMemo(()=>j?j.activeTabId??j.tabs[0]?.id??null:null,[j,b]),L=a.useMemo(()=>{if(j)return M?j.tabs.find(ae=>ae.id===M)??j.tabs[0]:j.tabs[0]},[j,M]),K=a.useMemo(()=>(j?.tabs??[]).map(ae=>({icon:(()=>{const Fe=ae.iconKey?Mn[ae.iconKey]??"terminal":"terminal";return s.jsx(P,{name:Fe,className:"h-4 w-4"})})(),id:ae.id,label:ae.label,title:ae.label,closeLabel:"Close tab"})),[j?.tabs]),z=L?.terminalSessionId??null,$=L?.lifecycle??"idle",O=a.useMemo(()=>(j?.tabs??[]).map(ae=>({id:ae.id,terminalSessionId:ae.terminalSessionId,label:ae.label})),[j?.tabs]),R=L?.isConnecting??!1,D=L?.previewUrl??null,T=ce(ae=>ae.activeMainTab)==="terminal",W=e??T,[Z,F]=a.useState(W);a.useEffect(()=>{W&&F(!0)},[W]);const{connectionError:me,setConnectionError:q,isFatalError:Ae,setIsFatalError:Ie,isReconnectPending:G,setIsReconnectPending:U,terminalIdRef:Y,lastViewportSizeRef:X,directoryRef:se,activeTabIdRef:we,resetTerminalPreviewScan:pe,startStream:V}=Mb({terminal:r,effectiveDirectory:k,activeTabId:M,terminalSessionId:z,terminalLifecycle:$,hasOpenedTerminalViewport:Z,terminalHydrated:v,terminalShell:u,terminalLoginShell:f,terminalAppearanceRef:l,enableTabs:b,hasActiveContext:A,tabs:O,focusTerminalWhenWindowActive:()=>{!h&&typeof document<"u"&&document.hasFocus()&&ie.current?.focus()}}),{activeModifier:Q,terminalControllerRef:ie,focusTerminalWhenWindowActive:ke,handleViewportInput:Se,handleModifierToggle:He,handleMobileKeyPress:H}=Tb({terminal:r,terminalIdRef:Y,isReconnectPending:G,setConnectionError:q,showQuickKeys:S,isTerminalVisible:W,lastViewportSizeRef:X,terminalSessionId:z,useTouchTerminalInput:h}),{isRestarting:de,handleRestart:ne,handleHardRestart:ue,handleCreateTab:ve,handleSelectTab:Le,handleCloseTab:be}=Fb({terminal:r,effectiveDirectory:k,activeTabId:M,enableTabs:b,terminalShell:u,terminalLoginShell:f,terminalAppearanceRef:l,lastViewportSizeRef:X,directoryRef:se,activeTabIdRef:we,terminalIdRef:Y,resetTerminalPreviewScan:pe,startStream:V,setConnectionError:q,setIsFatalError:Ie,setIsReconnectPending:U});a.useEffect(()=>{if(!W||h)return;if(typeof window>"u"){ke();return}const ae=window.requestAnimationFrame(()=>{ke()});return()=>{window.cancelAnimationFrame(ae)}},[M,ke,W,h]);const te=a.useMemo(()=>{const ae=wn[_r].stack;if(typeof window>"u")return(wn[c]??wn[_r]).stack;const tt=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return tt&&tt.trim().length>0?tt.trim():(wn[c]??wn[_r]).stack??ae},[c]),xe=a.useMemo(()=>rb(i),[i]),fe=`${k??"no-dir"}::${M??"no-tab"}`;if(a.useEffect(()=>{if(!W||h)return;const ae=ie.current;if(!ae)return;const Fe=()=>{ae.fit()};if(typeof window<"u"){const tt=window.requestAnimationFrame(()=>{Fe(),ke()}),xt=[220,400].map(Qe=>window.setTimeout(Fe,Qe));return()=>{window.cancelAnimationFrame(tt),xt.forEach(Qe=>window.clearTimeout(Qe))}}Fe()},[ke,W,h,ie,fe,z]),a.useEffect(()=>{if(!W||!h)return;let ae=null;const Fe=()=>{ae!==null&&window.cancelAnimationFrame(ae),ae=window.requestAnimationFrame(()=>{ae=null,ie.current?.fit()})};return window.addEventListener("oc:keyboard-settled",Fe),()=>{window.removeEventListener("oc:keyboard-settled",Fe),ae!==null&&window.cancelAnimationFrame(ae)}},[W,ie,fe,h]),!A)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(!k)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:ne,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const je=!z||R||de||G,Ye=Z,_e=j?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"min-w-0 flex-1",children:s.jsx(ga,{items:K,activeId:M,onSelect:Le,onClose:be,onCreate:ve})}),s.jsx(Ne,{type:"button",size:"xs",variant:"ghost",className:"h-8 w-8 shrink-0 p-0",onClick:ve,title:"New tab","aria-label":"New tab",children:s.jsx(P,{name:"add",className:"h-4 w-4"})}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1 overflow-visible",children:[s.jsx(Ne,{type:"button",size:"xs",variant:"ghost",className:"h-8 w-8 p-0",onClick:()=>{ne()},disabled:de,title:"Restart terminal","aria-label":"Restart terminal",children:s.jsx(P,{name:"restart",className:"h-4 w-4"})}),D?s.jsxs(Ne,{type:"button",size:"xs",variant:"outline",className:"h-6 shrink-0 gap-1 px-2",onClick:()=>{k&&N(k,D)},title:"Open preview pane",children:[s.jsx(P,{name:"global",className:"h-3.5 w-3.5 shrink-0"}),s.jsx("span",{className:"whitespace-nowrap",children:"Preview"})]}):null]})]}):null,De=s.jsx(xb,{isTouchTerminal:m,activeModifier:Q,disabled:je,onKeyPress:H,onModifierToggle:He}),Ve=!n||m||S;return s.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[_e&&n?Kd.createPortal(s.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:_e}),n):null,m&&_e&&!n&&j?s.jsx(bb,{leading:s.jsx("div",{className:"min-w-0 flex-1 -ml-2",children:s.jsx(ga,{items:K,activeId:M,onSelect:Le,onClose:be,onCreate:ve})}),actions:s.jsxs(s.Fragment,{children:[s.jsx(Ne,{type:"button",variant:"ghost",size:"icon",onClick:ve,title:"New tab","aria-label":"New tab",children:s.jsx(P,{name:"add",className:"size-4"})}),s.jsx(Ne,{type:"button",variant:"ghost",size:"icon",onClick:()=>{ne()},disabled:de,title:"Restart terminal","aria-label":"Restart terminal",children:s.jsx(P,{name:"restart",className:"size-4"})}),D?s.jsxs(Ne,{type:"button",variant:"outline",size:"sm",className:"h-8 shrink-0 gap-1 px-2",onClick:()=>{k&&N(k,D)},title:"Open preview pane",children:[s.jsx(P,{name:"global",className:"size-3.5 shrink-0"}),s.jsx("span",{className:"whitespace-nowrap",children:"Preview"})]}):null,t?s.jsx(Ne,{type:"button",variant:"ghost",size:"icon",onClick:t,title:"Close terminal view","aria-label":"Close terminal view",children:s.jsx(P,{name:"close",className:"size-4"})}):null]})}):null,!m&&Ve?s.jsxs("div",{className:_("app-region-no-drag sticky top-0 z-20 shrink-0 bg-background text-xs","px-3 py-2"),children:[_e&&!n?s.jsxs("div",{className:"flex items-center gap-2 pl-1 pr-1",children:[_e,t?s.jsx(Ne,{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(P,{name:"close",className:"h-4 w-4"})}):null]}):null,!m&&S&&b&&j?s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1 pl-1 pr-1",children:De}):null,!m&&S&&!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:Ye&&k&&j?j.tabs.map(ae=>{const Fe=ae.id===M;return s.jsx(gb,{directory:k,tabId:ae.id,sessionId:ae.terminalSessionId,sessionKey:`${k}::${ae.id}`,isActive:Fe,isTerminalVisible:W,terminal:r,theme:xe,fontFamily:te,fontSize:d,enableTouchScroll:h,lastViewportSizeRef:X,onInput:Se,controllerRef:ie},ae.id)}):null}),!G&&me&&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:me}),Ae&&m&&s.jsx(Ne,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:ue,disabled:de,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]}),m&&S?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]})},Bo=[{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"}],Lb=new Set(Bo.map(e=>e.id)),Ob=e=>typeof e=="string"&&Lb.has(e),Qy=e=>Ob(e)?e:"changes",hc=e=>e==="pull-requests"||e==="issues",Bb=e=>e?Bo:Bo.filter(t=>!hc(t.id)),Jy=(e,t)=>hc(e)?"changes":e,_b=48,Ub=96,vt=(e,...t)=>{try{e?.(...t)}catch{}},to=(e,t)=>{if(typeof e=="function"){const n=e();return n>0?n:t}return typeof e=="number"&&e>0?e:t},Xy=(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"?Ub:_b;let d=!1,u=!1,f=!1,p=null,x=!1,y=0,m=0,h=0,b=0;const g=()=>{d=!1,u=!1,f=!1,p=null},S=()=>{const N=n.current,M=p,L=x;u&&M&&(vt(M==="left"?N.onLeftProgress:N.onRightProgress,L?1:0),vt(N.onDragEnd,M,L)),g()},w=()=>{S(),u||g()},E=N=>{const M=n.current;if(M.enabled===!1){u&&p?S():g();return}if(N.touches.length!==1){u&&p?S():g();return}const L=N.touches[0],K=o.getBoundingClientRect(),z=o.clientWidth,$=!!M.leftOpen,O=!!M.rightOpen,R=D=>Vg(D,o);if($||O){if(R(N.target)){g();return}if($&&O){const D=L.clientX<=K.left+c;L.clientX>=K.right-c?(p="right",x=!0):D?(p="left",x=!0):(p=$?"left":"right",x=!0)}else $?(p="left",x=!0):(p="right",x=!0);b=to(p==="left"?M.leftWidth:M.rightWidth,z),b<10&&(b=z||window.innerWidth||320),b<10&&(b=320),d=!0}else{if(R(N.target)){g();return}p=null,x=!1,b=0,d=!0}y=L.clientX,m=L.clientY,h=Date.now(),u=!1,f=!1},A=N=>{if(!d)return;if(N.touches.length!==1){w();return}const M=N.touches[0],L=M.clientX-y,K=M.clientY-m;if(!f){if(Math.abs(L)<ua&&Math.abs(K)<ua)return;if(Math.abs(K)>Math.abs(L)*An){g();return}if(!p){const O=n.current;p=L>0?"left":"right",b=to(p==="left"?O.leftWidth:O.rightWidth,o.clientWidth),b<10&&(b=window.innerWidth||320)}if(p==="left"){if(!x&&L<=0){g();return}if(x&&L>=0){g();return}}else{if(!x&&L>=0){g();return}if(x&&L<=0){g();return}}f=!0,u=!0,vt(n.current.onDragStart,p)}if(!u)return;N.cancelable&&N.preventDefault();const z=n.current,$=fa(p,x,L,b);vt(p==="left"?z.onLeftProgress:z.onRightProgress,$)},k=(N,M)=>{if(!d){g();return}const L=N-y,K=M-m;if(!p&&!x&&Math.abs(L)>=ar&&Math.abs(K)<=Math.abs(L)*An){const I=n.current;p=L>0?"left":"right",b=to(p==="left"?I.leftWidth:I.rightWidth,o.clientWidth),b<10&&(b=window.innerWidth||320)}if(!p){g();return}const z=Math.max(1,Date.now()-h),$=n.current;if(!u){const I=Math.abs(L),T=Math.abs(K);I>=ar&&T<=I*An?p==="left"&&!x&&L>0?(vt($.onLeftProgress,1),vt($.onLeftOpen)):p==="right"&&!x&&L<0?(vt($.onRightProgress,1),vt($.onRightOpen)):vt(p==="left"?$.onLeftProgress:$.onRightProgress,x?1:0):vt(p==="left"?$.onLeftProgress:$.onRightProgress,x?1:0);const W=p;g(),vt($.onDragEnd,W);return}const O=fa(p,x,L,b),R=qg({side:p,isOpenAtStart:x,dx:L,dt:z,progress:O}),D=p;vt(D==="left"?R?$.onLeftOpen:$.onLeftClose:R?$.onRightOpen:$.onRightClose),g(),vt($.onDragEnd,D,R)},j=N=>{const M=N.changedTouches[0];if(!M){g();return}const L=M.clientX-y,K=M.clientY-m;d&&(u||Math.abs(L)>=ar&&Math.abs(K)<=Math.abs(L)*An)&&N.cancelable&&N.preventDefault(),k(M.clientX,M.clientY)},v=()=>{w()};return o.addEventListener("touchstart",E,{passive:!0}),o.addEventListener("touchmove",A,{passive:!1}),o.addEventListener("touchend",j,{passive:!1}),o.addEventListener("touchcancel",v,{passive:!0}),()=>{try{u&&p&&S()}catch{}o.style.touchAction=i,o.removeEventListener("touchstart",E),o.removeEventListener("touchmove",A),o.removeEventListener("touchend",j),o.removeEventListener("touchcancel",v)}},[e,r])};function Zy({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(P,{name:"layout-column",className:"absolute inset-0 h-full w-full"})]})}function ya({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 zb=({sessionDirectory:e,draftDirectory:t,isNewSessionDraftOpen:n})=>n?t:e,$b=({activeProjectLabel:e,openDirectory:t,homeDirectory:n})=>Sr(t,n)?null:e,so=()=>Es.filter(e=>go.has(e.id)).map(e=>({...il(e)})),Kb=()=>{if(typeof window>"u")return bo;const e=window.localStorage.getItem("openInAppId");return e&&po(e)?e:bo};let no=!1,Qs=!1,ms=!1,ps=0,Tn=null;const wa=()=>{Tn&&(clearTimeout(Tn),Tn=null)},As=Bs()((e,t)=>({selectedAppId:Kb(),availableApps:so(),hasLoadedApps:!1,isCacheStale:!1,isScanning:!1,initialize:()=>{if(no||typeof window>"u")return;no=!0;const n=(d,u=!0)=>{if(!Array.isArray(d)||d.length===0){e({availableApps:so(),hasLoadedApps:u});return}const f=new Set(d.map(m=>m.name)),p=new Map(d.map(m=>[m.name,m.iconDataUrl??void 0])),y=Es.filter(m=>f.has(m.appName)||go.has(m.id)).map(m=>({...il(m),iconDataUrl:p.get(m.appName)}));e({availableApps:y,hasLoadedApps:!0})},r=async d=>{if(!rn()||!ur()||Qs||t().hasLoadedApps&&!d)return;const f=Es.map(p=>p.appName);wa(),Qs=!0,ms=!1,e({isScanning:!0});try{const{apps:p,success:x,hasCache:y,isCacheStale:m}=await Ri(f,d),h=x&&!y&&p.length===0&&ps<3;if(e({isCacheStale:y?m:!1}),n(p,x?!h:!1),x){if(h){const g=[800,1600,3200][ps]??3200;ps+=1,ms=!0,Tn=setTimeout(()=>{r()},g);return}ps=0,ms=!1;return}if(ps<3){const g=[1e3,3e3,7e3][ps]??7e3;ps+=1,ms=!0,Tn=setTimeout(()=>{r()},g)}}finally{Qs=!1,ms||e({isScanning:!1})}};r();const o=d=>{const u=d.detail,f=u&&typeof u.openInAppId=="string"&&u.openInAppId.length>0&&po(u.openInAppId)?u.openInAppId:null;f&&(window.localStorage.setItem("openInAppId",f),e({selectedAppId:f}))},i=()=>{r()},l=d=>{const u=d.detail;Array.isArray(u)&&(ps=3,ms=!1,e({isScanning:!1,isCacheStale:!1}),n(u))};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(no||t().initialize(),!rn()||!ur()||Qs||t().hasLoadedApps&&!n)return;const o=Es.map(i=>i.appName);wa(),n&&e({hasLoadedApps:!1}),Qs=!0,ms=!1,e({isScanning:!0});try{const{apps:i,hasCache:l,isCacheStale:c}=await Ri(o,n),d=new Set(i.map(x=>x.name)),u=new Map(i.map(x=>[x.name,x.iconDataUrl??void 0])),p=Es.filter(x=>d.has(x.appName)||go.has(x.id)).map(x=>({...x,iconDataUrl:u.get(x.appName)}));e({availableApps:p.length>0?p:so(),hasLoadedApps:p.length>0,isCacheStale:l?c:!1})}finally{Qs=!1,ms||e({isScanning:!1})}},selectApp:async n=>{po(n)&&(e({selectedAppId:n}),typeof window<"u"&&window.localStorage.setItem("openInAppId",n),await sl({openInAppId:n}))}})),Wb="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",Gb="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",ro=e=>({...e,fallbackIconDataUrl:e.id==="finder"&&window.__PICHAMBER_PLATFORM__==="darwin"?Wb:e.id==="terminal"?Gb:void 0}),va=({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:_("h-4 w-4 rounded-sm flex items-center justify-center","bg-[var(--surface-muted)] text-[9px] font-medium text-muted-foreground"),children:i})},Hb=({directory:e,className:t})=>{const n=As(m=>m.selectedAppId),r=As(m=>m.availableApps),o=As(m=>m.isCacheStale),i=As(m=>m.isScanning),l=As(m=>m.initialize),c=As(m=>m.loadInstalledApps),d=As(m=>m.selectApp);a.useEffect(()=>{l()},[l]);const u=rn()&&ur(),f=a.useMemo(()=>{const m=r.find(h=>h.id===n)??r.find(h=>h.id===bo)??r[0]??Es[0];return ro(m||Es[0])},[r,n]);if(!u||!e||r.length===0)return null;const p=async m=>{await bf(e,m.id,m.appName)||await rl(e,m.appName)},x=async m=>{await d(m.id),await p(m)},y=async()=>{(await xs(e)).ok&&oe.success("Path copied to clipboard")};return s.jsxs("div",{className:_("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:_("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(va,{label:f.label,iconDataUrl:f.iconDataUrl,fallbackIconDataUrl:f.fallbackIconDataUrl})}),s.jsxs(Gt,{children:[s.jsx(Ht,{asChild:!0,children:s.jsx("button",{type:"button",className:_("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(P,{name:"arrow-down-s",className:"h-4 w-4"})})}),s.jsxs(qt,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[s.jsxs(ht,{className:"flex items-center gap-2",onClick:()=>{y()},children:[s.jsx(P,{name:"file-copy",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:"Copy Path"})]}),s.jsx(nn,{}),r.map(m=>{const h=ro(m);return s.jsxs(ht,{className:"flex items-center gap-2",onClick:()=>{x(m)},children:[s.jsx(va,{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(P,{name:"check",className:"ml-auto h-4 w-4 text-primary"}):null]},m.id)}),o?s.jsxs(ht,{className:"flex items-center gap-2",onClick:()=>{c(!0)},children:[s.jsx(P,{name:"refresh",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:"Refresh Apps"})]}):null]})]})]})},qb="\x1B",Yb=new RegExp(`${qb}\\[[0-9;?]*[ -/]*[@-~]`,"g"),Vb=/https?:\/\/[^\s<>'"`]+/gi,It="__pichamber_auto_discover_preview__",Qb=15e3,Jb=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},Xb=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}},Zb=e=>{const n=e.replace(Yb,"").match(Vb);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,d=c.hostname.toLowerCase(),u=d==="localhost"||d==="127.0.0.1"||d==="0.0.0.0"||d==="::1",f=c.pathname||"/",p=f.split("/").filter(Boolean).length,x=f==="/"||f==="",y=!!(c.search||c.hash);let m=0;return u&&(m+=50),x&&(m+=30),m-=Math.min(p*5,20),y&&(m-=10),m};return o.sort((l,c)=>i(c)-i(l)),o[0]?.parsed.origin??o[0]?.raw??null}return r[0]??null},ex=[{pattern:/^dev(:.*)?$/i},{pattern:/^start(:.*)?$/i},{pattern:/^preview(:.*)?$/i},{pattern:/^serve(:.*)?$/i},{pattern:/^develop(:.*)?$/i}],tx=["dev","start","preview","serve"];async function sx(e,t,n){if(!e)return null;const r=ox(t);if(r)return{command:r.command,label:r.name||"Start Preview",actionId:r.id,previewUrlHint:r.openUrl};if(n){const o=ix(n);if(o){const i=await ax(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 nx(e)){const o=await rx(),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 nx(e){const t=`${e}/index.html`,n=await vr(t,e);return typeof n=="string"&&n.trim().length>0}async function rx(){try{const e=await nt("/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 ox(e){for(const t of e){const n=`${t.name} ${t.command}`.toLowerCase();if(tx.some(o=>n.includes(o)))return t}return null}function ix(e){for(const{pattern:t}of ex)for(const n of Object.keys(e))if(t.test(n))return n;return null}async function ax(e){const t=await vr(`${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 vr(`${e}/${r}`,e);if(typeof i=="string"&&i.trim().length>0)return o}return"npm"}async function vr(e,t){if(t?.trim())try{const r=new URLSearchParams({path:e,directory:t,optional:"true"}),o=await nt(`/api/fs/read?${r.toString()}`,{cache:"no-store"});if(o.ok)return o.text()}catch{}const n=nl()?.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 nt(`/api/fs/read?path=${encodeURIComponent(e)}&optional=true`,{cache:"no-store"});return r.ok?r.text():null}catch{return null}}async function lx(e){try{const t=await vr(`${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 cx=(e,t,n)=>new Promise(r=>{let o=!1,i=null,l=null;const c=d=>{o||(o=!0,l&&clearTimeout(l),i?.close(),r(d))};i=e.connect(t,{onEvent:d=>{(d.type==="exit"||d.type==="snapshot"&&d.status==="exited")&&c(!0)},onError:(d,u)=>{u&&c(!0)}}),o?i.close():l=setTimeout(()=>c(!1),n)});function dx({projectRef:e,directory:t,allowMobile:n=!1}){const{currentTheme:r}=Xa(),{terminal:o}=Os(),{isMobile:i}=dn(),l=ce(H=>H.terminalShell),c=ce(H=>H.terminalLoginShells.includes(H.terminalShell)),d=ce(H=>H.setSettingsPage),u=ce(H=>H.setSettingsDialogOpen),f=ce(H=>H.setSettingsProjectsSelectedId),p=ce(H=>H.openContextPreview),x=he(H=>H.ensureDirectory),y=he(H=>H.setTabLabel),m=he(H=>H.setTabIconKey),h=he(H=>H.setActiveTab),b=he(H=>H.setConnecting),g=he(H=>H.setTabSessionId),S=he(H=>H.setTabPreviewUrl),w=he(H=>H.projectActionRuns),E=he(H=>H.setProjectActionRun),A=he(H=>H.updateProjectActionRunStatus),k=he(H=>H.removeProjectActionRun),[j,v]=a.useState([]),[N,M]=a.useState(null),[L,K]=a.useState(!1),z=a.useRef({}),$=a.useRef({}),O=a.useRef({}),R=a.useRef({}),D=a.useRef(new Set),I=a.useRef(0),T=e?.id??null,W=e?.path??"",Z=a.useMemo(()=>T?{id:T,path:W}:null,[T,W]),F=a.useCallback(async H=>{await Oa(H)},[]),me=a.useCallback(async()=>{if(!Z)return;const H=I.current+1;I.current=H,K(!0);try{const de=await ao(Z);if(I.current!==H)return;const ne=de.actions;v(ne),M(ue=>ue===It||ue&&ne.some(ve=>ve.id===ue)?ue:null)}catch{if(I.current!==H)return}finally{I.current===H&&K(!1)}},[Z]),q=a.useMemo(()=>El(t||Z?.path||""),[t,Z?.path]),Ae=a.useMemo(()=>N?j.find(H=>H.id===N)??null:null,[j,N]),Ie=a.useMemo(()=>({id:It,name:"Auto-discover",command:"",icon:"scan-2",autoOpenUrl:!0}),[]),G=!i,U=a.useMemo(()=>G?[Ie,...j]:j,[j,Ie,G]);a.useEffect(()=>{me()},[me]),a.useEffect(()=>{if(typeof window>"u")return;const H=de=>{const ne=de.detail;T&&(ne?.projectId&&ne.projectId!==T||me())};return window.addEventListener(jo,H),()=>{window.removeEventListener(jo,H)}},[me,T]),a.useEffect(()=>{N&&(N===It&&G||j.some(H=>H.id===N)||M(null))},[j,G,N]),a.useEffect(()=>{const H=()=>{const de=he.getState(),ne=de.sessions,ue=de.projectActionRuns;for(const[ve,Le]of Object.entries(ue)){const te=ne.get(Le.directory)?.tabs.find(Fe=>Fe.id===Le.tabId);if(!te||te.terminalSessionId!==Le.sessionId){k(ve);continue}const xe=$.current[ve]??{lastSeenChunkId:null,openedUrl:!1,tail:"",openInPreview:!1};$.current[ve]=xe;const fe=U.find(Fe=>Fe.id===Le.actionId),je=de.getBuffer(Le.directory,Le.tabId).chunks;if(!fe||je.length===0)continue;const Ye=je.filter(Fe=>xe.lastSeenChunkId===null||Fe.id>xe.lastSeenChunkId);if(Ye.length===0)continue;const _e=Ye.map(Fe=>Fe.data).join(""),De=`${xe.tail}${_e}`,Ve=!xe.openedUrl&&fe.autoOpenUrl===!0?Zb(De):null,ae=Ye[Ye.length-1]?.id??xe.lastSeenChunkId;if(xe.lastSeenChunkId=ae,xe.tail=De.slice(-512),Ve)if(xe.openedUrl=!0,xe.openInPreview){const Fe=ue[ve];Fe&&(S(Fe.directory,Fe.tabId,Ve,{locked:!1,autoOpened:!1}),Fe.status==="waiting-for-preview"&&A(ve,"running"),window.clearTimeout(R.current[ve]),delete R.current[ve],p(Fe.directory,Ve))}else F(Ve),oe.success("Opened URL from action output");$.current[ve]=xe}for(const ve of Object.keys($.current))ue[ve]||(delete $.current[ve],window.clearTimeout(R.current[ve]),delete R.current[ve])};return H(),he.subscribe((de,ne)=>{(de.sessions!==ne.sessions||de.buffers!==ne.buffers)&&H()})},[U,p,F,w,k,S,A]);const Y=a.useCallback(async(H,de={})=>{if(!q)throw new Error("No active directory");const ne=as(q,H.id);x(q);const ue=he.getState(),ve=ue.getDirectoryState(q);let Le=z.current[ne]||null;const be=Le?!!ve?.tabs.some(fe=>fe.id===Le):!1;(!Le||!be)&&(Le=ue.createTab(q),z.current[ne]=Le),y(q,Le,`Action: ${H.name}`),m(q,Le,H.icon||"play"),h(q,Le),de.revealTerminal!==!1&&ce.getState().openContextPanelTab(q,{mode:"terminal"});const xe=he.getState().getDirectoryState(q)?.tabs.find(fe=>fe.id===Le);return{key:ne,tabId:Le,sessionId:xe?.terminalSessionId??null}},[x,q,h,m,y]),X=a.useCallback(async H=>{if(!n&&i)return;if(!q){oe.error("No active directory for action");return}const de=as(q,H.id),ne=w[de];if(!(ne&&ne.status==="running")&&!D.current.has(de)){D.current.add(de);try{const ue=H.id===It?await(async()=>{const[De,Ve]=await Promise.all([ao({id:Z?.id??"",path:q}),lx(q)]),ae=await sx(q,De.actions,Ve);if(!ae)throw new Error('No dev server command found. Configure a project action or add a "dev" script to package.json.');return{id:It,name:"Auto-discover",command:ae.command,icon:"scan-2",autoOpenUrl:!0,openUrl:ae.previewUrlHint||""}})():H,ve=ue.autoOpenUrl===!0&&(ue.openUrl||"").trim().length>0,Le=!ve&&H.id!==It,{key:be,tabId:te,sessionId:xe}=await Y(ue,{revealTerminal:Le});let fe=xe;if(!fe){b(q,te,!0);try{fe=(await o.createSession({cwd:q,sessionId:te,shell:l,loginShell:c,themeMode:r.metadata.variant==="light"?"light":"dark",terminalBackground:r.colors.surface.background,terminalForeground:r.colors.syntax.base.foreground})).sessionId,g(q,te,fe)}finally{b(q,te,!1)}}if(!fe)throw new Error("Failed to create terminal session");O.current[be]?.(),b(q,te,!0);const je=o.connect(fe,{onEvent:De=>{De.type==="snapshot"&&(he.getState().replaceBuffer(q,te,De.data??"",De.sequence??0),he.getState().setConnecting(q,te,!1)),De.type==="data"&&typeof De.data=="string"&&De.data.length>0&&he.getState().appendToBuffer(q,te,De.data,De.sequence,De.replayData),De.type==="exit"&&(he.getState().setTabLifecycle(q,te,"exited"),he.getState().setConnecting(q,te,!1),he.getState().removeProjectActionRun(be),delete $.current[be],O.current[be]?.(),delete O.current[be],window.clearTimeout(R.current[be]),delete R.current[be])},onError:(De,Ve)=>{he.getState().setConnecting(q,te,!1),Ve&&(he.getState().setTabLifecycle(q,te,"exited"),he.getState().setTabSessionId(q,te,null),he.getState().removeProjectActionRun(be))}});O.current[be]=je.close;const Ye=ue.autoOpenUrl?Xb(ue.openUrl):null;E({key:be,directory:q,actionId:ue.id,tabId:te,sessionId:fe,status:ue.id===It&&!Ye?"waiting-for-preview":"running"}),window.clearTimeout(R.current[be]),delete R.current[be],ue.id===It&&!Ye&&(R.current[be]=window.setTimeout(()=>{const De=he.getState(),Ve=De.projectActionRuns[be];De.updateProjectActionRunStatus(be,"running"),Ve&&(De.setActiveTab(Ve.directory,Ve.tabId),ce.getState().openContextPanelTab(Ve.directory,{mode:"terminal"})),delete R.current[be]},Qb)),$.current[be]={lastSeenChunkId:null,openedUrl:!!Ye||ve,tail:"",openInPreview:ue.id===It};const _e=Jb(ue.command.trim().replace(/\r\n|\r/g,`
|
|
62
|
+
`));await o.sendInput(fe,`${_e}\r`),Ye?(S(q,te,Ye,{locked:!0,autoOpened:!0}),p(q,Ye),oe.success("Opened action URL")):ve?(S(q,te,null,{locked:!0}),oe.error("Invalid custom URL format")):S(q,te,null,{locked:!1,autoOpened:!1})}catch(ue){k(de),delete $.current[de],O.current[de]?.(),delete O.current[de],window.clearTimeout(R.current[de]),delete R.current[de],oe.error(ue instanceof Error?ue.message:"Failed to run action")}finally{D.current.delete(de)}}},[r.colors.surface.background,r.colors.syntax.base.foreground,r.metadata.variant,Y,n,i,q,c,l,p,w,k,b,E,S,g,Z?.id,o]),se=a.useCallback(async H=>{const de=as(q,H.id),ne=w[de];if(!ne)return;A(de,"stopping");const ue=cx(o,ne.sessionId,1e3);try{await o.sendInput(ne.sessionId,"")}catch{}const ve=await ue;if(he.getState().getDirectoryState(ne.directory)?.tabs.find(te=>te.id===ne.tabId)?.terminalSessionId===ne.sessionId&&!ve){if(typeof o.forceKill=="function")try{await o.forceKill({sessionId:ne.sessionId})}catch{}else try{await o.close(ne.sessionId)}catch{}g(ne.directory,ne.tabId,null)}k(de),delete $.current[de],O.current[de]?.(),delete O.current[de],window.clearTimeout(R.current[de]),delete R.current[de]},[q,w,k,g,o,A]),we=a.useCallback(()=>{const H=Ae??U[0];if(!H)return;const de=as(q,H.id),ne=w[de];if(ne?.status!=="stopping"){if(ne){se(H);return}X(H)}},[U,q,X,w,Ae,se]),pe=a.useCallback((H,de=!1)=>{if(M(H.id),!de){X(H);return}const ne=as(q,H.id),ue=w[ne];if(ue?.status!=="stopping"){if(ue){se(H);return}X(H)}},[q,X,w,se]),V=a.useCallback(()=>{Z?.id&&(f(Z.id),d("projects"),u(!0))},[u,d,f,Z?.id]),Q=Ae??U[0]??null,ie=Q?w[as(q,Q.id)]:null,ke=he(H=>ie?H.sessions.get(ie.directory)?.tabs.find(de=>de.id===ie.tabId)?.previewUrl??null:null),Se=!!((n||!i)&&Z&&q),He=Ae??U[0]??null;return{shouldRender:Se,isLoading:L,normalizedDirectory:q,resolvedSelected:He,displayActions:U,projectActionRuns:w,selectedRunPreviewUrl:ke,handlePrimaryClick:we,handleSelectAction:pe,openProjectActionsSettings:V,openContextPreview:p}}const Sa=({projectRef:e,directory:t,className:n,compact:r=!1,allowMobile:o=!1})=>{const{shouldRender:i,isLoading:l,normalizedDirectory:c,resolvedSelected:d,displayActions:u,projectActionRuns:f,selectedRunPreviewUrl:p,handlePrimaryClick:x,handleSelectAction:y,openProjectActionsSettings:m,openContextPreview:h}=dx({projectRef:e,directory:t,allowMobile:o});if(!i||!d)return null;const b=d.icon||"play",g=d.id===It?"scan-2":Mn[b]||"play",S=as(c,d.id),w=f[S],E=w?.status==="stopping",A=w?.status==="waiting-for-preview",k=!!(w&&p),j=()=>{!w||!p||h(w.directory,p)},v=d.id===It;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||E,className:_("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:x,"aria-label":w?`Stop ${d.name}`:`Run ${d.name}`,children:E||A?s.jsx(P,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):w?s.jsx(P,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):s.jsx(P,{name:g,className:"h-5 w-5"})})}),v?s.jsx(We,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),k?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(P,{name:"global",className:"h-4 w-4"})})}),s.jsx(We,{sideOffset:6,children:"Open Preview"})]}):null,s.jsxs(Gt,{children:[s.jsx(Ht,{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(P,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})}),s.jsxs(qt,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[s.jsxs(ht,{className:"flex items-center gap-2",onClick:m,children:[s.jsx(P,{name:"add",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),s.jsx(nn,{}),u.map(N=>{const M=N.icon||"play",L=N.id===It?"scan-2":Mn[M]||"play",K=as(c,N.id),z=f[K],$=!!z,O=z?.status==="stopping";return s.jsxs(ht,{className:"flex items-center gap-2",onClick:()=>{y(N,!0)},children:[s.jsx(P,{name:L,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:N.name}),O||z?.status==="waiting-for-preview"?s.jsx(P,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):$?s.jsx(P,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},N.id)})]})]})]}):s.jsxs("div",{className:_("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:x,disabled:l||E,className:_("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":w?`Stop ${d.name}`:`Run ${d.name}`,children:s.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center",children:E||A?s.jsx(P,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):w?s.jsx(P,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):s.jsx(P,{name:g,className:"h-4 w-4"})})})}),v?s.jsx(We,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),k?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:j,className:_(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(P,{name:"global",className:"h-4 w-4"})})}),s.jsx(We,{sideOffset:6,children:"Open Preview"})]}):null,s.jsxs(Gt,{children:[s.jsx(Ht,{asChild:!0,children:s.jsx("button",{type:"button",className:_(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(P,{name:"arrow-down-s",className:"h-4 w-4"})})}),s.jsxs(qt,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[s.jsxs(ht,{className:"flex items-center gap-2",onClick:m,children:[s.jsx(P,{name:"add",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),s.jsx(nn,{}),u.map(N=>{const M=N.icon||"play",L=N.id===It?"scan-2":Mn[M]||"play",K=as(c,N.id),z=f[K],$=!!z,O=z?.status==="stopping";return s.jsxs(ht,{className:"flex items-center gap-2",onClick:()=>{y(N,!0)},children:[s.jsx(P,{name:L,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:N.name}),O||z?.status==="waiting-for-preview"?s.jsx(P,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):$?s.jsx(P,{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 cr(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 ux=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 fx({open:e,onOpenChange:t}){const[n,r]=a.useState(null),o=a.useCallback(async()=>{const u=Je();try{const f=await nt("/api/version");if(!f.ok)throw new Error("Version request failed");const p=await f.json().catch(()=>null);u===Je()&&r(p)}catch{u===Je()&&r(null)}},[]);a.useEffect(()=>(o(),Un(()=>{o()})),[o]);const i=cr(n),l=ux(n),c=typeof n?.pichamberVersion=="string"?n.pichamberVersion:null,d=typeof window<"u"?window.location.origin:"";return s.jsxs(Gt,{open:e,onOpenChange:u=>{t(u),u&&o()},children:[s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx(Ht,{asChild:!0,children:s.jsxs("button",{type:"button","aria-label":"Show connected server information",className:_(fn,"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5"),children:[s.jsx(P,{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(qt,{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(P,{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 ${d}`,"aria-label":"Copy server address",onClick:()=>{xs(d).then(u=>{u.ok?oe.success("Server address copied"):oe.error("Could not copy server address")})},children:[s.jsx("span",{className:"block max-w-[30ch] truncate font-mono",children:d}),s.jsx(P,{name:"file-copy",className:"size-3.5 shrink-0 text-muted-foreground"})]})]})})]})]})}const hx=({isMobile:e})=>{const n=Os().github??null,r=kr(i=>i.refresh),o=tm();return a.useEffect(()=>{!n||e||r(n)},[n,e,r]),e||!n||!o?null:s.jsxs("span",{className:_(fn,"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(P,{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]})]})},mx=a.memo(function({isDesktopApp:t,currentInstanceLabel:n,compactCurrentInstanceLabel:r,currentInstanceIsLocal:o,currentInstanceIcon:i,isDesktopServicesOpen:l,setIsDesktopServicesOpen:c,refreshCurrentInstanceLabel:d,shortcutLabel:u,remoteUpdateInfo:f,remoteUpdateChecking:p,remoteUpdateError:x,onOpenRemoteUpdate:y}){return s.jsxs(Gt,{open:l,onOpenChange:m=>{c(m),m&&d()},children:[s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx(Ht,{asChild:!0,children:s.jsxs("button",{type:"button","aria-label":t?`Open instance, usage and MCP (current: ${n})`:"Open services, usage and MCP",className:_(fn,t?"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5":"h-8 w-8"),children:[s.jsx(P,{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} (${u("toggle_services_menu")})`})})]}),s.jsx(qt,{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...":x||"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:y,children:"Update"}):null]})}),s.jsx(Bu,{embedded:!0,open:l,onOpenChange:()=>{},onHostSwitched:()=>c(!1)})]}):null})]})}),px=({action:e,onClose:t,sessionTitle:n,onConfirm:r})=>s.jsx(ts,{open:e!==null,onOpenChange:o=>{o||t()},children:s.jsxs(ss,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(ws,{children:[s.jsx(ds,{children:e==="delete"?"Delete session?":"Archive session?"}),s.jsx(vs,{children:e==="delete"?`"${n}" will be permanently deleted.`:`"${n}" will be archived.`})]}),s.jsxs(Ls,{children:[s.jsx(Ne,{variant:"outline",size:"sm",onClick:t,children:"Cancel"}),s.jsx(Ne,{variant:"destructive",size:"sm",onClick:r,children:e==="delete"?"Delete":"Archive"})]})]})}),gx=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},kn=e=>{if(!e)return"";const t=e.replace(/\\/g,"/");return t==="/"?"/":t.replace(/\/+$/,"")},bx=a.lazy(()=>mt(()=>import("./SessionSwitcherDropdown-CA64t2xd.js"),__vite__mapDeps([46,5,10,4,6,1,2,3,7,8,9,11,12])).then(e=>({default:e.SessionSwitcherDropdown}))),ew=({onToggleLeftDrawer:e,onToggleRightDrawer:t,leftDrawerOpen:n,rightDrawerOpen:r,tabletWorkspaceTab:o,onSelectTabletWorkspaceTab:i,tabletGitHubTabsAvailable:l=!1})=>{Wt("ui.header.render");const c=ce(B=>B.setSessionSwitcherOpen),d=ce(B=>B.toggleSidebar),u=ce(B=>B.isSidebarOpen),f=ce(B=>B.activeMainTab),p=ce(B=>B.setActiveMainTab),x=ce(B=>B.shortcutOverrides);ce(B=>B.timeFormatPreference),Os();const y=Te(B=>!!B.newSessionDraft?.open),m=Te(B=>B.currentSessionId),h=Va(m??""),b=_u(m),g=a.useMemo(()=>{if(!b)return null;const B=b;return{title:b.title??null,directory:B.directory??null,created:b.time?.created??null,slug:B.slug??null,shareUrl:b.share?.url??null,parentId:b.parentID??null,messageCount:typeof b.messageCount=="number"?b.messageCount:null}},[b]),S=ct(oo(B=>{if(!B.activeProjectId)return null;const le=B.projects.find(ye=>ye.id===B.activeProjectId);return le?{id:le.id,path:le.path,label:le.label}:null})),w=on(B=>B.homeDirectory),E=a.useMemo(()=>{if(!S)return null;const B=S.label?.trim();if(B)return B;const le=S.path.split(/[\\/]/).filter(Boolean);return le[le.length-1]??null},[S]),{isMobile:A}=dn(),{enabled:k}=Wo(),j=!!(k&&i&&o!==void 0),v=a.useMemo(()=>[...Bb(l)],[l]),[N,M]=a.useState(!1),L=a.useRef(null),[K,z]=a.useState(()=>typeof window>"u"?!1:rn()),$=a.useMemo(()=>ol(),[]),O=Uu(),[R,D]=a.useState(!1),I=a.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),T=Za(),W=a.useMemo(()=>{if(typeof window>"u")return null;const B=window.__PICHAMBER_MACOS_MAJOR__;if(typeof B=="number"&&Number.isFinite(B)&&B>0)return B;if(typeof navigator>"u")return null;const le=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!le)return null;const ye=Number.parseInt(le[1],10),Be=Number.parseInt(le[2],10);return Number.isNaN(ye)?null:ye===10?Be:ye},[]);Re.useEffect(()=>{typeof window>"u"||z(rn())},[]);const Z=ce(B=>B.isSessionSwitcherOpen),[F,me]=a.useState(!1),[q,Ae]=a.useState("Local"),[Ie,G]=a.useState(!0),[U,Y]=a.useState(()=>cr(null)),[X,se]=a.useState(!1),[we,pe]=a.useState(null),[V,Q]=a.useState(!1),[ie,ke]=a.useState(null),Se=a.useRef(0),He=a.useMemo(()=>gx(q),[q]),H=a.useCallback(async()=>{if(typeof window>"u"||!K)return;const B=Je(),le=()=>Je()===B;try{const ye=await nt("/api/version");if(!le())return;const Be=ye.ok?await ye.json().catch(()=>null):null;if(!le())return;if(Y(cr(Be)),ur()){Ae("Local"),G(!0);return}G(!1);const re=await xf();if(!le())return;const qe=yf(),Nt=wf([vf(qe),...re.hosts]);if(Nt.id===Sf){Ae("Local"),G(!0);return}Ae(jf(Nt.label.trim()||"Instance"))}catch{le()&&(Ae("Local"),G(!0),Y(cr(null)))}},[K]);Re.useEffect(()=>(H(),Un(()=>{Se.current+=1,pe(null),ke(null),Q(!1),se(!1),H()})),[H]);const de=a.useCallback(async()=>{const B=Se.current+1;Se.current=B;const le=Je(),ye=()=>Se.current===B&&Je()===le;if(Ie){pe(null),ke(null);return}Q(!0),ke(null);try{const Be=new URLSearchParams({appType:"web",instanceMode:"remote"}),re=await nt(`/api/pi/update-check?${Be.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!re.ok)throw new Error(`Server responded with ${re.status}`);const qe=await re.json();if(!ye())return;pe({available:qe.available??!1,version:qe.version,currentVersion:qe.currentVersion??"unknown",body:qe.body,nextSuggestedCheckInSec:typeof qe.nextSuggestedCheckInSec=="number"?qe.nextSuggestedCheckInSec:void 0,packageManager:qe.packageManager,updateCommand:qe.updateCommand,channel:qe.channel==="rc"?"rc":"stable"})}catch(Be){if(!ye())return;pe(null),ke(Be instanceof Error?Be.message:"Failed to check remote instance updates")}finally{ye()&&Q(!1)}},[Ie]);a.useEffect(()=>Th(()=>{Ie||de()}),[de,Ie]),a.useEffect(()=>{Se.current+=1,pe(null),ke(null),Q(!1),se(!1)},[Ie,q]),a.useEffect(()=>{if(!K||Ie)return;const B=3e3,le=3600*1e3;let ye=!1,Be=null;const re=qe=>{Be=window.setTimeout(()=>{if(ye||typeof document<"u"&&document.visibilityState!=="visible"){re(le);return}de().finally(()=>{ye||re(le)})},qe)};return re(B),()=>{ye=!0,Be!==null&&window.clearTimeout(Be)}},[de,Ie,q,K]);const ne=a.useCallback(()=>{if(we?.available){se(!0);return}de()},[de,we?.available]),ue=m?g??null:null,ve=a.useRef(null),[Le,be]=a.useState(0);a.useEffect(()=>{if(!m){ve.current&&(ve.current=null,be(Be=>Be+1));return}if(ue){ve.current={sessionId:m,session:ue,expiresAt:Date.now()+2e3};return}const B=ve.current;if(!B||B.sessionId!==m)return;const le=B.expiresAt-Date.now();if(le<=0){ve.current=null,be(Be=>Be+1);return}const ye=window.setTimeout(()=>{ve.current?.sessionId===m&&(ve.current=null),be(Be=>Be+1)},le);return()=>{window.clearTimeout(ye)}},[m,ue]);const te=(()=>{if(ue)return ue;if(!m)return null;const B=ve.current;return B&&B.sessionId===m&&B.expiresAt>Date.now()?B.session:null})(),xe=a.useMemo(()=>{const B=typeof te?.directory=="string"?te.directory:"";return kn(B||"")},[te?.directory]),fe=Te(B=>B.newSessionDraft?.open?kn(B.newSessionDraft.directoryOverride??""):""),je=a.useMemo(()=>zb({sessionDirectory:xe,draftDirectory:fe,isNewSessionDraftOpen:y}),[fe,y,xe]),_e=Ya(je||null),De=a.useMemo(()=>$b({activeProjectLabel:E,openDirectory:je,homeDirectory:w}),[E,w,je]),Ve=!!(De||_e),ae=a.useMemo(()=>m?gs(te,"Untitled session"):De??"PiChamber",[te,m,De]),Fe=zu(),tt=Te(B=>B.updateSessionTitle),xt=Te(B=>B.archiveSessions),Qe=Te(B=>B.deleteSessions),[pt,Xe]=a.useState(!1),[Ss,St]=a.useState(!1),st=a.useRef(!1),[Et,Lt]=a.useState(""),[Yt,jt]=a.useState(null),Ot=a.useRef(null);a.useEffect(()=>{st.current=!1,St(!1),Xe(!1),Lt(""),jt(null)},[m]);const yt=a.useCallback(()=>{m&&(Lt(te?.title?.trim()||ae),Xe(!0))},[te?.title,m,ae]),rt=a.useCallback(async()=>{if(!m)return;const B=Et.trim();B&&B!==te?.title?.trim()&&await tt(m,B),Xe(!1)},[te?.title,m,Et,tt]);a.useEffect(()=>{if(!pt)return;const B=le=>{const ye=le.target;(!ye||!Ot.current?.contains(ye))&&rt()};return document.addEventListener("mousedown",B),()=>document.removeEventListener("mousedown",B)},[pt,rt]);const dt=a.useCallback(()=>{m&&xs(m).then(B=>{oe[B.ok?"success":"error"](B.ok?"Session ID copied":"Failed to copy session ID")}).catch(()=>oe.error("Failed to copy session ID"))},[m]),Vt=a.useCallback(async()=>{if(!m||!je){oe.error("Nothing to export");return}try{await Fe.syncSession(m)}catch{oe.error("Failed to load the complete session history");return}const B=[];if(B.length===0){oe.error("Nothing to export");return}const le=oc(B,te?.title??null),ye=lc(te?.title??null);await ac(le,ye)||ic(le,ye),oe.success("Session exported")},[te?.title,m,je,Fe]);h?.type==="busy"||h?.type;const us=a.useCallback(async()=>{if(!m||!Yt)return;const B=$u(),le=[m];for(let qe=0;qe<le.length;qe+=1){const Nt=le[qe];for(const gt of B)gt.parentID===Nt&&!le.includes(gt.id)&&le.push(gt.id)}const ye=Yt;if(jt(null),(ye==="archive"?await xt(le):await Qe(le)).failedIds.length>0){oe.error(ye==="archive"?"Failed to archive session":"Failed to delete session");return}oe.success(ye==="archive"?"Session archived":"Session deleted")},[xt,m,Qe,Yt]),Ce=ce(B=>B.isArchivePageOpen),Ue=a.useMemo(()=>Ce?{title:"Archive",subtitle:null}:null,[Ce]),ge=a.useMemo(()=>kn(je||S?.path||""),[S?.path,je]),Oe=a.useCallback(()=>{ge&&xs(ge).then(B=>{oe[B.ok?"success":"error"](B.ok?"Working directory copied":"Failed to copy working directory")}).catch(()=>oe.error("Failed to copy working directory"))},[ge]),Ge=a.useMemo(()=>S?{id:S.id,path:S.path}:null,[S]),it=a.useRef(null);a.useEffect(()=>{!Ge||!ge||(it.current={projectRef:Ge,directory:ge})},[ge,Ge]);const kt=a.useMemo(()=>Ge&&ge?{projectRef:Ge,directory:ge}:it.current,[ge,Ge]),ot=a.useCallback(()=>{if(typeof document>"u")return;const B=document.activeElement;if(!B)return;const le=B.tagName;(le==="INPUT"||le==="TEXTAREA"||le==="SELECT"||B.isContentEditable)&&B.blur()},[]),Bt=a.useCallback(()=>{if(A){ot(),c(!Z);return}d()},[ot,A,Z,c,d]),ns=a.useCallback(()=>{Dn("desktop_open_draft_mini_chat_window",{directory:kn(je||S?.path||""),projectId:S?.id??null,apiBaseUrl:mo(),clientToken:ho()}).catch(B=>{console.warn("[header] failed to open draft mini chat window",B)})},[S?.id,S?.path,je]),Ze=a.useCallback(()=>{if(y){ns();return}m&&Dn("desktop_open_session_mini_chat_window",{sessionId:m,directory:kn(je||S?.path||""),apiBaseUrl:mo(),clientToken:ho()}).catch(B=>{console.warn("[header] failed to open session mini chat window",B)})},[S?.path,m,ns,y,je]),Rt=fn,Dt=dm,wt=a.useMemo(()=>n?"sessions":j?r&&o?o:null:r?"git":f,[f,j,n,r,o]),ut=a.useCallback(()=>{n&&e&&e(),r&&t&&t(),!e&&Z&&c(!1)},[Z,n,e,t,r,c]),_s=a.useCallback(()=>{e?.()},[e]),Us=a.useCallback(()=>{t?.()},[t]),js=a.useMemo(()=>K&&I&&!R?"5.5rem":O?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":!K||T?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[K,R,I,O,T]);Re.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",js)},[js]);const ks=u?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",Ct=u?"0px":K&&T?"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)":k?"2.75rem":"2.5rem";Re.useEffect(()=>{if(!K||!I){D(!1);return}let B=!1;const le=async()=>{try{const Be=await Dn("desktop_is_window_fullscreen");B||D(Be===!0)}catch{B||D(!1)}},ye=()=>{le()};return le(),window.addEventListener("pichamber:window-resized",ye),()=>{B=!0,window.removeEventListener("pichamber:window-resized",ye)}},[K,I]);const rs=a.useMemo(()=>!K||!I||W===null?"":W>=26?"h-12":W<=15?"h-14":"",[K,I,W]),At=a.useMemo(()=>{if(!(K&&!T))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))"}},[K,T]),os=a.useCallback(()=>{if(typeof document>"u")return;const B=L.current?.getBoundingClientRect().height;if(B){const le=`${B}px`,ye=document.documentElement.style;ye.getPropertyValue("--oc-header-height")!==le&&ye.setProperty("--oc-header-height",le)}},[]);Re.useEffect(()=>{if(typeof window>"u")return;os();const B=L.current;if(!B||typeof ResizeObserver>"u")return()=>{};let le=0;const ye=()=>{le||(le=requestAnimationFrame(()=>{le=0,os()}))},Be=new ResizeObserver(ye);return Be.observe(B),window.addEventListener("resize",ye),window.addEventListener("orientationchange",ye),()=>{le&&cancelAnimationFrame(le),Be.disconnect(),window.removeEventListener("resize",ye),window.removeEventListener("orientationchange",ye)}},[os]),Re.useEffect(()=>{os()},[os,A,rs]);const is=a.useCallback(async B=>{const le=B.target;le.closest(".app-region-no-drag")||le.closest("button, a, input, select, textarea")||B.button===0&&K&&await Ku()},[K]),at=a.useMemo(()=>A?[{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"}]:[],[A]),_t=a.useCallback(B=>Ho(dr(B,x)),[x]);Re.useEffect(()=>{!A&&f!=="chat"&&f!=="terminal"&&f!=="diagram"&&p("chat")},[f,A,p]),Re.useEffect(()=>{const B=le=>{if(kf(le)&&!le.shiftKey&&!le.altKey){const ye=parseInt(le.key,10);ye>=1&&ye<=at.length&&(le.preventDefault(),A&&(ot(),ut()),p(at[ye-1].id))}};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[ot,ut,A,p,at]),Re.useEffect(()=>{const B=le=>{const ye=dr("toggle_services_menu",x);if(Cf(le,ye)){le.preventDefault(),F?me(!1):(me(!0),H());return}};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[x,F,H]);const zs=B=>{const le=f===B.id,ye=B.icon==="diff",Be=ye?null:B.icon,re=B.id==="chat",qe=gt=>ye?s.jsx(ya,{size:gt}):Be?s.jsx(P,{name:Be,className:`h-${gt/4} w-${gt/4}`}):null,Nt=s.jsxs("button",{type:"button",onClick:()=>p(B.id),className:_("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",le?"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",re&&!A&&"min-w-[100px] justify-center"),"aria-label":B.label,"aria-selected":le,role:"tab",children:[A?qe(20):s.jsxs(s.Fragment,{children:[qe(16),s.jsx("span",{className:"header-tab-label",children:B.label})]}),B.badge!==void 0&&B.badge>0&&s.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:B.badge})]});return s.jsx(a.Fragment,{children:Nt},B.id)},Pt=s.jsxs(s.Fragment,{children:[s.jsx(Hb,{directory:ge,className:"mr-1"}),K?s.jsx(mx,{isDesktopApp:K,currentInstanceLabel:q,compactCurrentInstanceLabel:He,currentInstanceIsLocal:Ie,currentInstanceIcon:U,isDesktopServicesOpen:F,setIsDesktopServicesOpen:me,refreshCurrentInstanceLabel:H,shortcutLabel:_t,remoteUpdateInfo:we,remoteUpdateChecking:V,remoteUpdateError:ie,onOpenRemoteUpdate:ne}):s.jsx(fx,{open:F,onOpenChange:me}),s.jsx(hx,{isMobile:A})]}),pn=$&&(y||!!m),$s=()=>s.jsxs("div",{onMouseDown:is,className:_("app-region-drag relative flex h-12 select-none items-center pr-3",rs),style:At,role:"tablist","aria-label":"Main navigation",children:[s.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:ks}}),s.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:Ct}}),s.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[Ue?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:Ue.title}),Ue.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:Ue.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:[u?null:s.jsx(a.Suspense,{fallback:s.jsx("button",{type:"button",className:Rt,"aria-label":"Open session switcher",children:s.jsx(P,{name:"history",className:"h-[18px] w-[18px]"})}),children:s.jsx(bx,{align:"start",children:s.jsx("button",{type:"button",className:Rt,"aria-label":"Open session switcher",children:s.jsx(P,{name:"history",className:"h-[18px] w-[18px]"})})})}),s.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 px-1",children:[pt?s.jsxs("form",{ref:Ot,className:"flex w-full min-w-0 items-center gap-2 leading-tight",onSubmit:B=>{B.preventDefault(),rt()},children:[s.jsx("input",{value:Et,onChange:B=>Lt(B.target.value),autoFocus:!0,onKeyDown:B=>{B.stopPropagation(),B.key==="Escape"&&Xe(!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(P,{name:"check",className:"size-4"})}),s.jsx("button",{type:"button",onClick:()=>Xe(!1),"aria-label":"Cancel renaming session",title:"Cancel renaming session",className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(P,{name:"close",className:"size-4"})})]}):s.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal leading-tight text-foreground",children:y?"New session":ae}),Ve?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,_e?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[s.jsx(P,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),s.jsx("span",{className:"truncate",children:_e})]}):null]})]}):null]}),s.jsx("div",{className:"flex h-[18px] shrink-0 items-center justify-center self-center",children:m&&!y&&!pt?s.jsxs(Gt,{open:Ss,onOpenChange:St,onOpenChangeComplete:B=>{!B&&st.current&&(st.current=!1,yt())},children:[s.jsx(Ht,{asChild:!0,children:s.jsx(Ne,{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(P,{name:"more",className:"size-4"})})}),s.jsxs(qt,{align:"end",className:"min-w-[190px]",children:[s.jsxs(ht,{onClick:()=>{st.current=!0},children:[s.jsx(P,{name:"pencil-ai",className:"mr-2 size-4"}),"Rename"]}),s.jsxs(ht,{onClick:dt,children:[s.jsx(P,{name:"file-copy",className:"mr-2 size-4"}),"Copy session ID"]}),s.jsxs(ht,{onClick:Oe,disabled:!ge,children:[s.jsx(P,{name:"folder",className:"mr-2 size-4"}),"Copy working directory"]}),s.jsx(nn,{}),s.jsxs(ht,{onClick:()=>{Vt()},children:[s.jsx(P,{name:"download",className:"mr-2 size-4"}),"Export Markdown"]}),s.jsx(nn,{}),s.jsxs(ht,{onClick:()=>jt("archive"),children:[s.jsx(P,{name:"inbox-archive",className:"mr-2 size-4"}),"Archive"]}),s.jsxs(ht,{className:"text-destructive focus:text-destructive",onClick:()=>jt("delete"),children:[s.jsx(P,{name:"delete-bin",className:"mr-2 size-4"}),"Delete"]})]})]}):null})]}),at.length>0&&s.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:at.map(B=>zs(B))}),s.jsx("div",{className:"flex-1"}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[s.jsx(Pl,{}),kt?s.jsx(Sa,{projectRef:kt.projectRef,directory:kt.directory,className:"mr-1"}):null,s.jsx(um,{visible:pn,title:y?"New Mini Chat Window":"Open Session in Mini Chat",ariaLabel:y?"Open a new Mini Chat window":"Open current session in Mini Chat",onClick:Ze,className:_(Rt,"mr-1"),Icon:"picture-in-picture-2"}),Pt,s.jsx(Wu,{visible:T})]})]})]}),gn=()=>s.jsxs("div",{className:"app-region-drag relative flex items-center gap-2 px-3 py-2 select-none",children:[k&&s.jsxs(s.Fragment,{children:[s.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:ks}}),s.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:Ct}})]}),!k&&s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e?s.jsx("button",{type:"button",onClick:_s,className:_(Dt,wt==="sessions"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":n?"Close sessions":"Open sessions",children:s.jsx(P,{name:"layout-left",className:"h-5 w-5"})}):Z?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(P,{name:"arrow-left-s",className:"h-5 w-5"})}):s.jsx("button",{type:"button",onClick:Bt,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(P,{name:"play-list-add",className:"h-5 w-5"})}),!e&&Z&&s.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:"Sessions"})]}),(!Z||!!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:at.map(B=>{const le=f===B.id,ye=B.icon==="diff",Be=ye?null:B.icon;return s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsxs("button",{type:"button",onClick:()=>{A&&(ot(),ut()),p(B.id)},"aria-label":B.label,"aria-selected":le,role:"tab",className:_(Dt,"relative rounded-lg",wt===B.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[ye?s.jsx(ya,{className:"h-5 w-5"}):Be?s.jsx(P,{name:Be,className:"h-5 w-5"}):null,B.badge!==void 0&&B.badge>0&&s.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:B.badge}),B.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:B.label})})]},B.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:v.map(B=>{const le=r&&o===B.id;return s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:()=>{A&&(ot(),ut()),M(!1),i?.(B.id)},"aria-label":B.label,"aria-selected":le,role:"tab",className:_(Dt,"relative h-11 w-11 rounded-lg",le&&"bg-interactive-selection text-interactive-selection-foreground"),children:s.jsx(P,{name:B.icon,className:"h-5 w-5"})})}),s.jsx(We,{children:s.jsx("p",{children:B.label})})]},B.id)})}),s.jsx(cm,{open:N,onOpenChange:M,currentSessionId:m,effectiveDirectory:je||null,isNewSessionDraftOpen:y})]}),kt&&s.jsx(Sa,{projectRef:kt.projectRef,directory:kt.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:Us,className:_(Dt,"relative",wt==="git"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":r?"Close git sidebar":"Open git sidebar",children:s.jsx(P,{name:"layout-right",className:"h-5 w-5"})})}),s.jsx(We,{children:s.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),fs=_("header-safe-area relative z-10 bg-background",A&&"border-b border-border/50");return s.jsxs(s.Fragment,{children:[s.jsx("header",{ref:L,className:fs,style:{"--padding-scale":"1"},children:A?gn():$s()}),s.jsx(px,{action:Yt,onClose:()=>jt(null),sessionTitle:ae,onConfirm:()=>{us()}}),s.jsx(jl,{open:X,onOpenChange:se,info:we,downloading:!1,downloaded:!1,progress:null,error:ie,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})},ja="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",xx="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",tw=()=>{const e=ce(y=>y.isSidebarOpen),t=ce(y=>y.toggleSidebar),n=ce(y=>y.shortcutOverrides),r=a.useRef(null),o=a.useRef(null),i=Ho(dr("toggle_sidebar",n)),l=Za(),{enabled:c}=Wo(),d=!e,u=l,f=d||u,p=u,x=a.useCallback(()=>{Dn("desktop_show_app_menu").catch(y=>{console.warn("[titlebar] failed to open app menu",y)})},[]);return a.useEffect(()=>{if(typeof document>"u")return;const y=w=>{document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(w)}px`)},m=w=>{document.documentElement.style.setProperty("--oc-titlebar-overlay-width",`${Math.round(w)}px`)};if(!p)return;const h=o.current,b=r.current;if(!h||!b){y(0),m(0);return}const g=()=>{const w=Math.max(h.getBoundingClientRect().width,h.scrollWidth);y(w),m(b.getBoundingClientRect().width)};if(g(),typeof ResizeObserver>"u")return;const S=new ResizeObserver(g);return S.observe(h),S.observe(b),()=>{S.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:[u?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:x,"aria-label":"Open PiChamber menu",className:_(ja,"shrink-0"),children:s.jsx(P,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),s.jsx(We,{children:s.jsx("p",{children:"PiChamber menu"})})]}):null,d?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:t,"aria-label":"Open sessions",className:_(c?xx:ja,"shrink-0"),children:s.jsx(P,{name:"layout-left",className:c?"size-[18px]":"h-[18px] w-[18px]"})})}),s.jsx(We,{children:s.jsx("p",{children:`Open sessions (${i})`})})]}):null]})}):null},ka=200,yx="cubic-bezier(0.22, 1, 0.36, 1)",sw=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 d=window.requestAnimationFrame(()=>{c=window.requestAnimationFrame(()=>r(!0))});return()=>{window.cancelAnimationFrame(d),window.cancelAnimationFrame(c)}}r(!1);const l=window.setTimeout(()=>i(!1),ka);return()=>window.clearTimeout(l)},[e,t]),{slidIn:n,layoutVisible:o,prefersReducedMotion:t,transition:t?"none":`transform ${ka}ms ${yx}`}},nw=()=>{al()},rw=e=>{Te.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),ce.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),he.getState().clearAll(),al(),on.getState().resetForRuntimeSwitch(),Gu.getState().resetForRuntimeSwitch(),Hu.getState().resetForRuntimeSwitch(),qu(),Af(),Nf(),Xu(),Yu.getState().resetForRuntimeSwitch(),Kt.setState({providers:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),ct.getState().resetForRuntimeSwitch(),Vu(),Qu(),Kf.getState().reset(),If.getState().resetForRuntimeSwitch(),za.getState().resetForRuntimeSwitch(e.runtimeKey),co.getState().resetForRuntimeSwitch(e.runtimeKey),Ef(),Ts.getState().resetForRuntimeSwitch(e.runtimeKey),Ju.getState().resetForRuntimeSwitch(),es.getState().resetForRuntimeSwitch(),bt.getState().resetForRuntimeSwitch(e.runtimeKey),Rf.getState().resetForRuntimeSwitch(e.runtimeKey),Te.getState().restoreForRuntimeSwitch(e.runtimeKey),ce.getState().restoreForRuntimeSwitch(e.runtimeKey);const t=ce.getState();xo({sessionId:Te.getState().currentSessionId,tab:t.activeMainTab,isSettingsOpen:t.isSettingsDialogOpen,settingsPath:t.settingsPage,diffFile:t.pendingDiffFile},{replace:!0,force:!0})};export{Ph as $,Ny as A,Kx as B,ay as C,ua as D,iy as E,Ux as F,Qx as G,ew as H,Vo as I,Yx as J,Rh as K,Nl as L,Dl as M,Pn as N,_x as O,Jh as P,Wx as Q,Ih as R,Gy as S,Vy as T,jl as U,Mh as V,Fx as W,Xx as X,Al as Y,$n as Z,ty as _,cm as a,Ky as a$,zn as a0,Cl as a1,Jx as a2,$x as a3,Nh as a4,ry as a5,sy as a6,kr as a7,ny as a8,oy as a9,Ay as aA,Cy as aB,uy as aC,jy as aD,Sy as aE,wy as aF,Ar as aG,Nr as aH,Ir as aI,Ps as aJ,Zl as aK,nm as aL,rm as aM,Ui as aN,Zy as aO,As as aP,bs as aQ,es as aR,Xl as aS,zl as aT,_n as aU,Ul as aV,zx as aW,Mx as aX,My as aY,Iy as aZ,Ty as a_,ey as aa,Gx as ab,Hx as ac,qx as ad,vy as ae,Hh as af,Vx as ag,kl as ah,ch as ai,Eh as aj,Lx as ak,dh as al,ah as am,fy as an,cy as ao,ly as ap,dy as aq,yy as ar,xy as as,my as at,hy as au,py as av,sm as aw,by as ax,gy as ay,ky as az,An as b,Wy as b0,tm as b1,Oy as b2,Fy as b3,Ry as b4,Ly as b5,_y as b6,Uy as b7,zy as b8,$y as b9,By as ba,Py as bb,Ey as bc,Ro as bd,Xi as be,Ns as bf,jn as bg,mn as bh,xp as bi,hn as bj,Dy as bk,Hg as c,Hy as d,ar as e,Bb as f,qy as g,bb as h,Vg as i,Qy as j,hc as k,sw as l,Xy as m,tw as n,nw as o,rw as p,Ox as q,Jy as r,Yy as s,Bx as t,am as u,Tx as v,Px as w,Dh as x,Zx as y,Ah as z};
|