@pi-chamber/web 1.0.7-rc.1 → 1.0.8-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/AgentsSurface-BmHImX8m.js +1 -0
- package/dist/assets/ChoicesArtifact-C71fGOm2.js +1 -0
- package/dist/assets/DiagramView-BZQxoiZu.js +1 -0
- package/dist/assets/{DiffView-C3rA5DfE.js → DiffView-C70pbgk-.js} +6 -6
- package/dist/assets/FileSaveConflictDialog-Cu8c3gBV.js +3 -0
- package/dist/assets/FilesView-nFJYEdRw.js +6 -0
- package/dist/assets/GitHubDetailScaffold-Jvv_tgbl.js +11 -0
- package/dist/assets/GitHubLinkPicker-BXD2ODRi.js +1 -0
- package/dist/assets/GitHubListPrimitives-BWI706F0.js +1 -0
- package/dist/assets/{GitView-OpFCss_4.js → GitView-MIDG5RYW.js} +5 -5
- package/dist/assets/{IssuesSurface-DD6Gz5Ox.js → IssuesSurface-uNlozeu0.js} +2 -2
- package/dist/assets/{JsonTreeView-Dj75jgH6.js → JsonTreeView-CSLsTriz.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-CnIzmT1p.js → MarkdownRendererImpl-Cs-7BfWi.js} +3 -3
- package/dist/assets/PatchDiff-axbsnbTJ.js +1 -0
- package/dist/assets/PierreDiffViewer-lwn6w_5w.js +147 -0
- package/dist/assets/PullRequestsSurface-o_AXDjbO.js +2 -0
- package/dist/assets/{SessionSwitcherContent-CUz6Cc1-.js → SessionSwitcherContent-C4CMlcbv.js} +1 -1
- package/dist/assets/SessionSwitcherDropdown-DCBVuCoo.js +2 -0
- package/dist/assets/SessionUnreadDot-DyeIrsro.js +1 -0
- package/dist/assets/SettingsView-BHBpt2Um.js +7 -0
- package/dist/assets/{SettingsWindow-J6YOvGcV.js → SettingsWindow-Cb4st5y5.js} +1 -1
- package/dist/assets/{StickyHorizontalScrollbar-DNsbTLS7.js → StickyHorizontalScrollbar-CMbTn5WQ.js} +1 -1
- package/dist/assets/SubagentsArtifact-BzeMEoFP.js +1 -0
- package/dist/assets/ToolOutputDialog-BP2mOWdV.js +8 -0
- package/dist/assets/ToolPartDiffPreview-D49XBR9b.js +1 -0
- package/dist/assets/{VirtualizedFileDiff-Dq8pyTGy.js → VirtualizedFileDiff-CLgDONEQ.js} +4 -4
- package/dist/assets/{Virtualizer-okhy9Aq3.js → Virtualizer-PxblpQn6.js} +1 -1
- package/dist/assets/VisualFrame-CJrAvWSo.js +22 -0
- package/dist/assets/VisualsArtifact-DqLGgU-Q.js +1 -0
- package/dist/assets/{collapsible-D6qdoq7-.js → collapsible-BeyKtQGB.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-uXZ9uhI_.js → computeVirtualFileMetrics-DmO6H8u6.js} +2 -2
- package/dist/assets/contextFileOpenGuard-DOK251YW.js +1 -0
- package/dist/assets/{fileTreeStatus-C_7jbeGv.js → fileTreeStatus-CnzR7kxA.js} +2 -2
- package/dist/assets/gitStatusPredicates-4kPg2t6j.js +1 -0
- package/dist/assets/githubLink-QvaLfNNT.js +10 -0
- package/dist/assets/{index-I2QYqABE.js → index-B2v0_mez.js} +8 -8
- package/dist/assets/index-D3F4JrPN.css +1 -0
- package/dist/assets/{index-DD0xW5WE.js → index-DMX9wT1Z.js} +1 -1
- package/dist/assets/{main-BnWf2tm9.js → main-BW9J3Y72.js} +2 -2
- package/dist/assets/main-BirYxac2.js +137 -0
- package/dist/assets/{markdownCore-C-Ulh4n9.js → markdownCore-CxmcPur8.js} +2 -2
- package/dist/assets/miniChat-BRB11eEs.js +2 -0
- package/dist/assets/{mobile-BuAWpKj9.js → mobile-DJZYYCuB.js} +2 -2
- package/dist/assets/{nativeFileSave-Cp9i5QGd.js → nativeFileSave-B6QpoPRn.js} +1 -1
- package/dist/assets/pi-session-focus-preference-PWoh3LNA.js +9 -0
- package/dist/assets/{renderDiffWithHighlighter-DD-iWWus.js → renderDiffWithHighlighter-C48T6YFJ.js} +1 -1
- package/dist/assets/renderElectronMiniChatApp-N-BQdJl0.js +2 -0
- package/dist/assets/{renderFileWithHighlighter-B0pofdV1.js → renderFileWithHighlighter-8Kt2MyTN.js} +1 -1
- package/dist/assets/{renderMobileApp-B3P_bita.js → renderMobileApp-B7cT7m5b.js} +3 -3
- package/dist/assets/runtimeEndpointReset-BC6yGnxN.js +62 -0
- package/dist/assets/runtimeSurface-kIEoYsPP.js +1 -0
- package/dist/assets/selection-BTEdLRVK.js +1 -0
- package/dist/assets/useAppFontEffects-EcTZ_I_I.js +225 -0
- package/dist/assets/useGitHubRemoteSearch-DIBHNu8r.js +1 -0
- package/dist/assets/useSwitcherItems-DfLbfX37.js +1 -0
- package/dist/assets/{vendor-aparajita-capacitor-secure-storage-DVZvgYu4.js → vendor-aparajita-capacitor-secure-storage-DUoR8t1G.js} +1 -1
- package/dist/assets/{vendor-base-ui-BCqPBzDj.js → vendor-base-ui-DE6jnTiC.js} +1 -1
- package/dist/assets/{vendor-boot-3SaHYVb1.js → vendor-boot-D-KEJjsM.js} +29 -29
- package/dist/assets/{vendor-capacitor-app-NbQ-WiPS.js → vendor-capacitor-app-CO5jS31X.js} +1 -1
- package/dist/assets/{vendor-capacitor-keyboard-CgrHt8iN.js → vendor-capacitor-keyboard-335osRpd.js} +1 -1
- package/dist/assets/{vendor-capacitor-status-bar-CWt0OF5t.js → vendor-capacitor-status-bar-lB9y4H9d.js} +1 -1
- package/dist/assets/{vendor-codemirror-autocomplete-WThuuUAz.js → vendor-codemirror-autocomplete-BKvJ8PfM.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-angular-BbLGCxF6.js → vendor-codemirror-lang-angular-wjCUD0bM.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-cpp-Cceks-9O.js → vendor-codemirror-lang-cpp-LJzlG8sJ.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-css-D1wpUg3Z.js → vendor-codemirror-lang-css-DoEEdEpW.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-go-Cv0zXHHM.js → vendor-codemirror-lang-go-DexsLPb8.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-html-DbL8oT9H.js → vendor-codemirror-lang-html-h25V-Hp5.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-java-CNugenuC.js → vendor-codemirror-lang-java-D8xoT8cv.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-javascript-Bx_FIyZF.js → vendor-codemirror-lang-javascript-DF3GDYje.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-jinja-DDGjB3Zq.js → vendor-codemirror-lang-jinja-BboTHFdn.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-json-DIvqf9Pb.js → vendor-codemirror-lang-json-DCqvG1nE.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-less-D8r9dGG1.js → vendor-codemirror-lang-less-B8ZrSKJM.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-liquid-B24mguYi.js → vendor-codemirror-lang-liquid-DF9S5m5F.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-markdown-v3yG2sbf.js → vendor-codemirror-lang-markdown-6BNbCEPe.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-php-BcZGalqy.js → vendor-codemirror-lang-php-CQwAz1Hd.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-python-b-JqEwQy.js → vendor-codemirror-lang-python-DQym-8Tx.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-rust-B1uZxDW-.js → vendor-codemirror-lang-rust-DknzOTkO.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-sass-DqPrngKp.js → vendor-codemirror-lang-sass-dB0Rm5HI.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-sql-UyCnpt-k.js → vendor-codemirror-lang-sql-CCQUnnD-.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-vue-xDwYkovV.js → vendor-codemirror-lang-vue-h1M5bF00.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-wast-CF3169p_.js → vendor-codemirror-lang-wast-DWgtlGfu.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-xml-FCtVhuOb.js → vendor-codemirror-lang-xml-DncwoCUY.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-yaml-g0sPmAnv.js → vendor-codemirror-lang-yaml-C7QkS5ER.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-B03xgzP2.js → vendor-codemirror-language-data-BUZIlm3G.js} +2 -2
- package/dist/assets/{vendor-codemirror-search-Dw3Wpu15.js → vendor-codemirror-search-BlDCaCMK.js} +1 -1
- package/dist/assets/{vendor-lezer-cpp-Cu3E-KUI.js → vendor-lezer-cpp-B4JK1BC1.js} +1 -1
- package/dist/assets/{vendor-lezer-css-Cb8vp67u.js → vendor-lezer-css-DRxDmhcy.js} +1 -1
- package/dist/assets/{vendor-lezer-go-BTsIaOm7.js → vendor-lezer-go-DsUgfmxi.js} +1 -1
- package/dist/assets/{vendor-lezer-html-UQMsUwj-.js → vendor-lezer-html-qr9pUPmM.js} +1 -1
- package/dist/assets/{vendor-lezer-java-BIWrFrAx.js → vendor-lezer-java-6UyNiQiB.js} +1 -1
- package/dist/assets/{vendor-lezer-javascript-BH2Etgoy.js → vendor-lezer-javascript-CUdJ0VGA.js} +1 -1
- package/dist/assets/{vendor-lezer-json-CE-QUCwM.js → vendor-lezer-json-BKYAA8Hu.js} +1 -1
- package/dist/assets/{vendor-lezer-lr-HY6Yc0Vr.js → vendor-lezer-lr-DluApmOX.js} +1 -1
- package/dist/assets/{vendor-lezer-markdown-xFL3Evwf.js → vendor-lezer-markdown-B-uzYzYT.js} +1 -1
- package/dist/assets/{vendor-lezer-php-Cr_mQGrG.js → vendor-lezer-php-DI6PNjlz.js} +1 -1
- package/dist/assets/{vendor-lezer-python-BNRFWCb0.js → vendor-lezer-python-Bj232yb5.js} +1 -1
- package/dist/assets/{vendor-lezer-rust-BvfOK5cU.js → vendor-lezer-rust-DlPG_Yau.js} +1 -1
- package/dist/assets/{vendor-lezer-sass-qoxiLisk.js → vendor-lezer-sass-CBsyWB2A.js} +1 -1
- package/dist/assets/{vendor-lezer-xml--x8SSpqU.js → vendor-lezer-xml-C1FmgtmE.js} +1 -1
- package/dist/assets/{vendor-lezer-yaml-BDo1JaEr.js → vendor-lezer-yaml-DpHmjriG.js} +1 -1
- package/dist/assets/{vendor-replit-codemirror-vim-D1Fe7FiY.js → vendor-replit-codemirror-vim-Cvk64got.js} +1 -1
- package/dist/assets/{web-components-DB-GDG7P.js → web-components-C_DsTJis.js} +4 -4
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +2 -1
- package/plugins/registry.json +7 -0
- package/plugins/subagents/LICENSE +25 -0
- package/plugins/subagents/agents/planner.md +36 -0
- package/plugins/subagents/agents/reviewer.md +34 -0
- package/plugins/subagents/agents/scout.md +49 -0
- package/plugins/subagents/agents/worker.md +23 -0
- package/plugins/subagents/extension.js +631 -0
- package/plugins/subagents/extension.test.js +295 -0
- package/plugins/subagents/package.json +41 -0
- package/plugins/visuals/choices.js +168 -0
- package/plugins/visuals/extension.js +87 -0
- package/plugins/visuals/files.js +74 -0
- package/plugins/visuals/package.json +32 -0
- package/server/index.js +20 -0
- package/server/lib/github/DOCUMENTATION.md +4 -2
- package/server/lib/github/gh-cli.js +35 -9
- package/server/lib/github/gh-cli.test.js +122 -0
- package/server/lib/notifications/pi-notification-watcher.js +3 -0
- package/server/lib/notifications/pi-notification-watcher.test.js +10 -0
- package/server/lib/open-url/DOCUMENTATION.md +1 -1
- package/server/lib/pi/extension-protocol.js +54 -0
- package/server/lib/pi/fixtures/pichamber-gui-demo.ts +12 -13
- package/server/lib/pi/routes-extension-events.test.js +115 -0
- package/server/lib/pi/routes.js +307 -5
- package/server/lib/pi/routes.test.js +296 -1
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +25 -8
- package/server/lib/pi/session-daemon/extension-bridge.js +89 -29
- package/server/lib/pi/session-daemon/extension-config.js +719 -0
- package/server/lib/pi/session-daemon/extension-config.test.js +618 -0
- package/server/lib/pi/session-daemon/extension-controls.js +177 -0
- package/server/lib/pi/session-daemon/extension-controls.test.js +181 -0
- package/server/lib/pi/session-daemon/extension-name.js +6 -0
- package/server/lib/pi/session-daemon/extension-name.test.js +5 -0
- package/server/lib/pi/session-daemon/extension-palette.js +146 -0
- package/server/lib/pi/session-daemon/extension-palette.test.js +107 -0
- package/server/lib/pi/session-daemon/extension-replacements.js +138 -0
- package/server/lib/pi/session-daemon/extension-replacements.test.js +116 -0
- package/server/lib/pi/session-daemon/extension-ui-mode.js +30 -0
- package/server/lib/pi/session-daemon/extension-ui-mode.test.js +34 -0
- package/server/lib/pi/session-daemon/pichamber-ui.js +44 -0
- package/server/lib/pi/session-daemon/plugin-host.js +245 -0
- package/server/lib/pi/session-daemon/plugin-host.test.js +192 -0
- package/server/lib/pi/session-daemon/session-daemon-controls.e2e.test.js +205 -0
- package/server/lib/pi/session-daemon/session-daemon-drafts.e2e.test.js +409 -0
- package/server/lib/pi/session-daemon/session-daemon-extension-config.e2e.test.js +196 -0
- package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +137 -6
- package/server/lib/pi/session-daemon/session-daemon-plugins.e2e.test.js +272 -0
- package/server/lib/pi/session-daemon/session-daemon-providers.e2e.test.js +153 -0
- package/server/lib/pi/session-daemon/session-daemon.js +568 -61
- package/server/lib/pi/session-daemon/session-daemon.test.js +164 -4
- package/server/lib/pi/session-daemon/session-engine-router.js +7 -0
- package/server/lib/pi/session-daemon/session-engine-router.test.js +20 -0
- package/server/lib/pi/session-daemon/supervisor.js +22 -3
- package/server/lib/pi/settings-store.js +14 -0
- package/server/lib/pi/settings-store.test.js +11 -0
- package/server/lib/plugins/DOCUMENTATION.md +186 -0
- package/server/lib/plugins/daemon-sync.js +78 -0
- package/server/lib/plugins/daemon-sync.supervisor.test.js +83 -0
- package/server/lib/plugins/daemon-sync.test.js +96 -0
- package/server/lib/plugins/impact.js +139 -0
- package/server/lib/plugins/impact.test.js +82 -0
- package/server/lib/plugins/manifest.js +195 -0
- package/server/lib/plugins/manifest.test.js +118 -0
- package/server/lib/plugins/registry.js +59 -0
- package/server/lib/plugins/routes.js +92 -0
- package/server/lib/plugins/routes.test.js +219 -0
- package/server/lib/plugins/service.js +161 -0
- package/server/lib/plugins/store.js +261 -0
- package/server/lib/plugins/store.test.js +188 -0
- package/server/lib/plugins/visuals-extension.test.js +237 -0
- package/server/lib/server-browser/DOCUMENTATION.md +32 -7
- package/server/lib/server-browser/browser-tab.js +4 -1
- package/server/lib/server-browser/downloads.js +261 -34
- package/server/lib/server-browser/downloads.test.js +171 -0
- package/server/lib/server-browser/runtime.integration.test.js +47 -0
- package/server/lib/server-browser/runtime.js +16 -0
- package/server/lib/server-browser/server-browser.js +25 -6
- package/server/lib/tunnels/executable-search.js +5 -1
- package/server/lib/tunnels/executable-search.test.js +26 -0
- package/dist/assets/DiagramView-DyF8zzYx.js +0 -1
- package/dist/assets/FileSaveConflictDialog-CC4F--8H.js +0 -3
- package/dist/assets/FilesView-Dsg-QTJu.js +0 -6
- package/dist/assets/GitHubDetailScaffold-C9WuBMGr.js +0 -11
- package/dist/assets/GitHubLinkPicker-BkVdYxZT.js +0 -1
- package/dist/assets/GitHubListPrimitives-CcVlv_rJ.js +0 -1
- package/dist/assets/PatchDiff-DND5RBnF.js +0 -1
- package/dist/assets/PierreDiffViewer-Cq5CIrmH.js +0 -147
- package/dist/assets/PullRequestsSurface-g8HAvbFg.js +0 -2
- package/dist/assets/SessionSwitcherDropdown-COZ50Y5a.js +0 -2
- package/dist/assets/SessionUnreadDot-DOUcgBw6.js +0 -1
- package/dist/assets/SettingsView-AFymxZYC.js +0 -6
- package/dist/assets/ToolOutputDialog-5Tc7HM4z.js +0 -8
- package/dist/assets/ToolPartDiffPreview-7GiFbVl7.js +0 -1
- package/dist/assets/contextFileOpenGuard-CckKFYjI.js +0 -1
- package/dist/assets/gitStatusPredicates-CNLvdt2V.js +0 -1
- package/dist/assets/githubLink-0EoMGZKd.js +0 -10
- package/dist/assets/index-BaLCg7tL.css +0 -1
- package/dist/assets/main-yQe-k30g.js +0 -137
- package/dist/assets/miniChat-DKK1hotU.js +0 -2
- package/dist/assets/pi-session-focus-preference-DaWQ2rEE.js +0 -9
- package/dist/assets/renderElectronMiniChatApp-CKuFQBRo.js +0 -2
- package/dist/assets/runtimeEndpointReset-DutinXZK.js +0 -62
- package/dist/assets/runtimeSurface-CFwnvks_.js +0 -1
- package/dist/assets/useAppFontEffects-DQlUEhzN.js +0 -213
- package/dist/assets/useGitHubRemoteSearch-BoZvJAk3.js +0 -1
- package/dist/assets/useSwitcherItems-Dy2yumiU.js +0 -1
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-DMX9wT1Z.js","assets/useAppFontEffects-EcTZ_I_I.js","assets/index-B2v0_mez.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-D3F4JrPN.css","assets/vendor-boot-D-KEJjsM.js","assets/runtimeSurface-kIEoYsPP.js","assets/nativeFileSave-B6QpoPRn.js","assets/computeVirtualFileMetrics-DmO6H8u6.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-8Kt2MyTN.js","assets/renderDiffWithHighlighter-C48T6YFJ.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-335osRpd.js","assets/SessionSwitcherDropdown-DCBVuCoo.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{_ as pt}from"./vendor-vite-runtime-DD1OZmLC.js";import{j as n,aP as fu,aQ as hu,aR as pu,aS as mu,aT as gu,aU as bu,aV as xu,bi as Kr,bj as hs,bk as hl,bl as Wr,bm as wi,bp as pl,by as yu,bz as ml,bA as gl,bB as bl,bC as Fo,bD as Lo,bE as Oo,aW as xl,bF as yl,bn as wl,bv as vl,bs as Sl,bt as jl,bq as vi,br as Si,bG as wu,bH as vu,bI as Su,bh as Bo,b1 as ju}from"./vendor-boot-D-KEJjsM.js";import{a as Te,R as l}from"./vendor-react-Bz1tRBxM.js";import{dS as is,v as Cu,a as dt,x as Me,t as oe,ai as xs,I as R,bi as Qs,cA as Ks,m as en,n as tn,p as mn,q as An,B as Ae,d6 as ku,dT as Ji,bS as Js,C as un,M as Au,o as $n,U as ys,dU as zn,dV as Nu,a5 as rs,dW as lo,dX as Xi,dY as Zi,w as Ws,bV as Cr,dZ as Iu,d_ as Eu,d$ as Du,e0 as Ru,e1 as Pu,e2 as Tu,af as Cl,aj as Ln,ag as ea,a0 as fn,ap as Ke,aq as We,ar as Ge,dQ as kl,e3 as Mu,e4 as Fu,e5 as Lu,e6 as Ou,au as Bu,e7 as _o,e8 as _u,D as Ht,h as qt,i as Vt,f as zo,ak as Kt,e9 as zu,am as Uu,dB as $u,cJ as Ku,ea as Wu,dN as Gu,u as Uo,r as cs,c4 as ji,bR as Hu,cY as qu,d0 as Al,eb as Nl,ci as Cn,ec as Vu,ed as Yu,ee as Qu,ef as Ju,e as Il,b as Xs,eg as or,j as Kn,ax as El,d4 as Zs,eh as ta,l as Dl,ei as bt,ej as Xu,ek as Zu,d1 as Rl,b1 as $o,b2 as Pl,el as Tl,d5 as Ci,a1 as ut,em as ef,en as tf,eo as nf,ep as er,eq as sf,er as rf,es as of,et as af,az as Ko,bO as lf,y as Ml,b_ as cf,z as df,bU as Fl,A as uf,E as ff,eu as Ll,F as hf,ev as pf,G as na,ew as mf,ex as Zn,c as gf,ey as bf,aV as xf,d as yf,bB as Wo,bA as wf,ez as vf,d2 as Sf,dR as jf,eA as Cf,aI as kf,eB as co,aY as ps,$ as Ol,c9 as Af,aZ as Nf,eC as If,eD as Ef,b$ as Df,g as Rf,eE as Pf,ay as Bl,aM as Tf,a7 as Mf,eF as Ff,aA as Lf,dH as Of,dI as Bf,eG as _f,dh as zf,_ as Uf,eH as $f,eI as Kf,eJ as Wf,N as Gf,eK as Hf}from"./useAppFontEffects-EcTZ_I_I.js";import{a as sa,c as _,b5 as qf,u as ue,r as tt,f as ms,b6 as _l,b7 as zl,b8 as Vf,b9 as Yf,k as gs,ba as Qf,T as Jf,bb as Xf,bc as Zf,ad as Ze,b as rt,p as Ps,s as ws,bd as eh,P as th,be as nh,Z as sh,n as Re,bf as ra,C as Wt,at as Go,aP as oa,bg as Ho,aj as Ul,A as hn,a7 as ki,w as Pr,G as as,bh as rh,l as $l,bi as oh,Y as Kl,N as ih,v as Wl,q as Gs,bj as qo,I as Vo,bk as ah,bl as lh,bm as ch,bn as ia,bo as Ts,aG as uo,bp as Yo,B as Tr,bq as On,br as aa,bs as Qo,bt as Gl,bu as Jo,bv as dh,am as uh,ar as fh,an as hh,ao as ph,ap as mh,aq as gh,_ as bh,t as xh,ab as Hl,bw as yh,bx as wh,z as vh,by as Sh,R as jh}from"./index-B2v0_mez.js";import{saveOrShareFile as ql}from"./nativeFileSave-B6QpoPRn.js";import{d as Ch,e as Vl,g as vs,h as kr,i as Yl,s as Un,b as bs,c as kh,j as Ah,k as Nh,l as Ih,f as Eh,S as la,a as Dh,t as Rh,m as Ph}from"./SessionUnreadDot-DyeIrsro.js";import{c as Nn,d as Gr,p as Ql,a as Th}from"./vendor-zustand-CXhN0IMY.js";/* empty css */import{usePermissionStore as Mh}from"./permissionStore-zIpxq9Pq.js";const Fh="chat";function Jl(e){const t=new URLSearchParams;if(e.sessionId&&e.sessionId.trim().length>0&&t.set(is.SESSION,e.sessionId),e.isSettingsOpen){const s=e.settingsPath.trim().length>0?e.settingsPath:"home";return t.set(is.SETTINGS,s),t}return e.tab!==Fh&&t.set(is.TAB,e.tab),e.tab==="diff"&&e.diffFile&&e.diffFile.trim().length>0&&t.set(is.FILE,e.diffFile),t}function Lh(e,t){const s=typeof window<"u"?window.location.pathname:"/",r=s.startsWith("/session")||s.startsWith("/s/")?"/":s,o=e.toString();return o?`${r}?${o}`:r}function Oh(e){if(typeof window>"u")return!0;try{const t=new URLSearchParams(window.location.search),s=Jl(e),r=window.location.pathname.match(/^\/(?:session|s)\/([^/?#]+)/i),o=r?.[1]?decodeURIComponent(r[1].trim()):null;o&&!t.has(is.SESSION)&&t.set(is.SESSION,o);const i=[...t.entries()].sort((c,d)=>c[0].localeCompare(d[0])),a=[...s.entries()].sort((c,d)=>c[0].localeCompare(d[0]));if(i.length!==a.length)return!1;for(let c=0;c<i.length;c++)if(i[c][0]!==a[c][0]||i[c][1]!==a[c][1])return!1;return!0}catch{return!0}}function Xo(e,t={}){if(!(typeof window>"u")&&!(!t.force&&Oh(e)))try{const s=Jl(e),r=Lh(s);t.replace?window.history.replaceState({...window.history.state,route:e},"",r):window.history.pushState({route:e},"",r)}catch{}}const Bh=["typescript","javascript","tsx","jsx","json","markdown"],Xl={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let ca=null;const Zl=()=>(ca??=Promise.all([pt(()=>import("./index-DMX9wT1Z.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])),pt(()=>import("./workerFactory-DlGfNFqf.js"),[]),pt(()=>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,s])=>({WorkerPoolManager:e.WorkerPoolManager,workerFactory:t.workerFactory,ensurePierreThemeRegistered:s.ensurePierreThemeRegistered})),ca),tr={},da=new Set,Zo=new Set;let Ar={light:"pierre-light",dark:"pierre-dark"};const _h=()=>{for(const e of Zo)e()},ec=(e,t)=>{t.setRenderOptions({theme:Ar,lineDiffType:Xl[e].lineDiffType})},ei=e=>{typeof window>"u"||da.has(e)||(da.add(e),Zl().then(t=>{if(tr[e])return;const s=Xl[e],r=new t.WorkerPoolManager({workerFactory:t.workerFactory,poolSize:s.poolSize,totalASTLRUCacheSize:s.totalASTLRUCacheSize},{theme:{light:"pierre-light",dark:"pierre-dark"},langs:Bh,lineDiffType:s.lineDiffType,preferredHighlighter:"shiki-wasm"});r.initialize(),tr[e]=r,ec(e,r),_h()}))},zh=e=>(Zo.add(e),()=>Zo.delete(e)),Uh=e=>{if(!(Ar.light===e.light&&Ar.dark===e.dark)){Ar=e;for(const t of Object.keys(tr)){const s=tr[t];s&&ec(t,s)}}},dw=({children:e})=>{const t=Cu(),s=sa(!1),r=sa(!0),o=t?.lightThemeId??s.metadata.id,i=t?.darkThemeId??r.metadata.id,a=t?.availableThemes.find(d=>d.metadata.id===o)??s,c=t?.availableThemes.find(d=>d.metadata.id===i)??r;return Te.useEffect(()=>{let d=!1;return Zl().then(u=>{d||(u.ensurePierreThemeRegistered(a),u.ensurePierreThemeRegistered(c),Uh({light:a.metadata.id,dark:c.metadata.id}))}),()=>{d=!0}},[c,a]),Te.useEffect(()=>{if(typeof window>"u")return;const d=()=>{ei("unified"),ei("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)},[]),n.jsx(n.Fragment,{children:e})},uw=(e="unified")=>{const t=Te.useSyncExternalStore(zh,()=>tr[e],()=>{});return Te.useEffect(()=>{ei(e)},[e]),t},$h=e=>{const t=e.trim();return t&&(t.split(/[?#]/,1)[0]||t).match(/([^/:]+?)(?:\.git)?\/?$/)?.[1]?.trim()||""},Kh=e=>{const t=e.trim();return t?/[/\\]/.test(t)?"A name can’t contain / or \\.":t==="."||t===".."?"Choose a different name.":null:"Enter a name for the folder."},ua=(e,t)=>e?e.endsWith("/")?`${e}${t}`:`${e}/${t}`:t,tc=l.forwardRef(({id:e,active:t,onSelect:s,onHover:r,ariaLabel:o,ariaChecked:i,className:a,quiet:c=!1,children:d},u)=>n.jsx("div",{ref:u,id:e,role:"option","aria-selected":t,"aria-checked":i,"aria-label":o,onMouseMove:t?void 0:r,onMouseDown:f=>f.preventDefault(),onClick:s,className:_("flex w-full cursor-pointer select-none items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-left typography-ui-label text-foreground",t&&(c?"group-focus-within/palette:bg-interactive-hover":"group-focus-within/palette:bg-interactive-selection group-focus-within/palette:text-interactive-selection-foreground"),!t&&"hover:bg-interactive-hover/60",a),children:d}));tc.displayName="PaletteRow";const Wh=e=>e==="/",kn=e=>e.replace(/\\/g,"/"),pn=e=>{if(!e||Wh(e))return e;let t=e;for(;t.length>1&&t.endsWith("/");)t=t.slice(0,-1);return t},ds=e=>e.endsWith("/"),Hs=e=>{const t=e.trim();return!t||ds(t)?t:`${t}/`},Ai=e=>e.lastIndexOf("/"),Gh=e=>{if(ds(e))return e;const t=Ai(e);return t<0?e:e.slice(0,t+1)},Hh=e=>{const t=Ai(e);return e.slice(t+1)},nc=e=>{const t=pn(e.trim());if(!t||t==="~"||t==="~/"||t==="/")return null;const s=Ai(t);return s<0?null:t.startsWith("~/")&&s<=1?"~/":s===0?"/":`${t.slice(0,s)}/`},qh=e=>ds(e)&&nc(e)!==null,Nr=e=>{if(!e)return null;const t=pn(kn(e.trim()));return t?t.toLowerCase():null},fo=(e,t)=>{const s=e.trim();return s==="~"?t:s.startsWith("~/")?`${t}${s.slice(1)}`:s},Vh=(e,t)=>{const s=pn(kn(e.trim())),r=pn(kn(t.trim()));if(!s)return"";if(!r)return Hs(s);if(s.toLowerCase()===r.toLowerCase())return"~/";const o=`${r}/`;return s.toLowerCase().startsWith(o.toLowerCase())?`~/${s.slice(r.length+1)}/`:Hs(s)},sc=()=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform),Yh=e=>sc()?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey,Qh=()=>sc()?"⌘":"Ctrl",Jh=e=>{if(!e)return;e.focus({preventScroll:!0});const t=e.value.length;e.setSelectionRange(t,t),e.scrollLeft=e.scrollWidth},Xh=async()=>qf({fresh:!0}),hr=async(e,t)=>{try{const s=await e.json();if(typeof s.error=="string"&&s.error.trim())return s.error.trim()}catch{}return t},ho=(e,t,s)=>tt(e,{method:"POST",headers:{"Content-Type":"application/json"},query:s,body:JSON.stringify(t)});function Zh({open:e,onClose:t,isMobile:s}){const r=dt(x=>x.addProject),o=ue(x=>x.setActiveMainTab),i=ue(x=>x.setSessionSwitcherOpen),a=Me(x=>x.openNewSessionDraft),[c,d]=l.useState(null),[u,f]=l.useState(null);l.useEffect(()=>{e&&(d(null),f(null))},[e]);const m=l.useCallback(x=>{const k=r(x);return k?(o("chat"),s&&i(!1),a({selectedProjectId:k.id,directoryOverride:k.path}),t(),!0):(f("PiChamber couldn’t add this folder. Check that the path is a folder."),!1)},[r,s,t,a,o,i]),b=l.useCallback(async(x,k)=>{if(!c){d(x),f(null);try{await k()}catch(v){f(v instanceof Error&&v.message?v.message:"Something went wrong. Try again.")}finally{d(null)}}},[c]),g=l.useCallback((x,k)=>b("add",async()=>{if(k.create){const v=await ho("/api/fs/mkdir",{path:x},{directory:k.location});if(!v.ok)throw new Error(await hr(v,"Couldn’t create the folder."))}m(x)}),[m,b]),p=l.useCallback((x,k)=>b("clone",async()=>{const v=await ho("/api/fs/clone",{remoteUrl:x.trim(),destinationPath:`${pn(k)}/`});if(!v.ok){const w=(await hr(v,"The clone failed.")).replace(/^Cloning into '[^']*'\.\.\.\s*/,"").replace(/^fatal:\s*/,"");throw new Error(w.charAt(0).toUpperCase()+w.slice(1))}const A=await v.json();if(typeof A.path!="string"||!A.path)throw new Error("The clone finished, but the server didn’t say where. Add the folder from Folder on this server.");m(A.path)}),[m,b]),h=l.useCallback((x,k,v)=>b("create",async()=>{const A=`${pn(x)}/${k.trim()}`,w=await ho("/api/fs/mkdir",{path:A},{directory:x});if(!w.ok)throw new Error(await hr(w,"Couldn’t create the folder."));if(v){const j=await tt("/api/git/init",{method:"POST",query:{directory:A}});if(!j.ok){const S=await hr(j,"git init failed.");throw new Error(`The folder was created, but git init failed: ${S}`)}}m(A)}),[m,b]),y=l.useCallback(()=>f(null),[]);return{pending:c,error:u,clearError:y,addFolder:g,cloneRepository:p,createProject:h}}const ep=()=>{const[e,t]=Te.useState(!1),[s,r]=Te.useState(!1);Te.useEffect(()=>{t(ms()),r(_l())},[]);const o=Te.useCallback(async c=>e?await zl(c):{success:!0,path:c},[e]),i=Te.useCallback(async c=>e?await Vf():{success:!0},[e]),a=Te.useCallback(async c=>e?await Yf():{success:!0},[e]);return{isDesktop:e,canRequestAccess:s,requestAccess:o,startAccessing:i,stopAccessing:a}},po=async(e,t)=>{try{const r=(await Jf(t)).filter(o=>o.isDirectory).map(o=>({name:o.name,path:kn(o.path)})).sort((o,i)=>o.name.localeCompare(i.name));return{displayDir:e,absoluteDir:t,entries:r,error:null}}catch(s){return{displayDir:e,absoluteDir:t,entries:[],error:Xf(s)?s.reason:"unknown"}}},tp=250;function np({open:e,addedProjectPaths:t}){const s=gs(W=>W.homeDirectory),{canRequestAccess:r,startAccessing:o}=ep(),[i,a]=l.useState(""),[c,d]=l.useState("~/"),[u,f]=l.useState(null),[m,b]=l.useState(!1),[g,p]=l.useState(!1),[h,y]=l.useState(!1),x=l.useRef(0),k=i||s;l.useEffect(()=>{if(!e)return;x.current+=1,d("~/"),f(null),p(!1),y(!1);let W=!1;return(async()=>{const ae=await Xh();W||a(ae||s||"")})(),()=>{W=!0}},[s,e]);const v=l.useMemo(()=>Gh(c),[c]),A=l.useMemo(()=>ds(c)?"":Hh(c),[c]),w=l.useMemo(()=>k?fo(v,k):"",[v,k]),j=!!(u&&u.displayDir===v&&u.absoluteDir===w);l.useEffect(()=>{if(!e||!w||j)return;const W=++x.current;po(v,w).then(L=>{W===x.current&&f(L)})},[w,v,j,e]),l.useEffect(()=>{if(j||!w){b(!1);return}const W=window.setTimeout(()=>b(!0),tp);return()=>window.clearTimeout(W)},[w,j]);const S=l.useCallback(async W=>{const L=Hs(W);if(!k)return d(L),!0;const ae=++x.current,J=await po(L,fo(L,k));return ae!==x.current?!1:(f(J),d(L),!0)},[k]),C=l.useCallback(()=>{if(!w)return;const W=++x.current;po(v,w).then(L=>{W===x.current&&f(L)})},[w,v]),E=l.useMemo(()=>j?A:!u||!c.startsWith(u.displayDir)?"":c.slice(u.displayDir.length).split("/")[0]??"",[A,j,u,c]),P=l.useMemo(()=>{if(!u)return[];const W=E.toLowerCase(),L=h||E.startsWith(".");return u.entries.filter(ae=>ae.name.toLowerCase().startsWith(W)&&(L||!ae.name.startsWith(".")))},[E,u,h]),z=l.useMemo(()=>{if(!u||u.error)return[];const W=[],L=qh(u.displayDir)?nc(u.displayDir):null;if(L){const ae=Nr(u.absoluteDir);W.push({type:"parent",value:"browse:up",name:"..",path:u.absoluteDir,target:L,alreadyAdded:!!(ae&&t.has(ae))})}for(const ae of P){const J=Nr(ae.path);W.push({type:"directory",value:`browse:${ae.path}`,name:ae.name,path:ae.path,target:`${Hs(u.displayDir)}${ae.name}/`,alreadyAdded:!!(J&&t.has(J))})}return W},[t,P,u]),K=j?u?.error??null:null,q=l.useMemo(()=>j&&u?u.entries:[],[j,u]),H=l.useMemo(()=>k?pn(fo(c,k)):"",[k,c]),F=Nr(H),D=!!(F&&t.has(F)),T=l.useMemo(()=>A?q.find(W=>W.name===A)??null:null,[A,q]),I=!!(j&&H&&!D&&(K===null||K==="not-found")&&(ds(c)&&K==="not-found"||!ds(c)&&A.trim().length>0&&T===null)),M=l.useCallback(async W=>{const L=await o(W);if(!L.success)return oe.error("Failed to open directory",{description:L.error||"Desktop could not grant file access."}),!1;const ae=k?Vh(W,k):Hs(kn(W));return await S(ae),!0},[k,S,o]),G=l.useCallback(async()=>{if(!g){p(!0);try{if(_l()){const L=await zl(H);if(!L.success||!L.path){L.error&&L.error!=="Directory selection cancelled"&&oe.error("Failed to select directory",{description:L.error});return}await M(L.path);return}const W=await Qf(H);if(W.status==="cancelled")return;if(W.status!=="picked"){oe.error("Couldn't open a folder picker",{description:W.error});return}await M(W.path)}catch(W){oe.error("Failed to select directory",{description:W instanceof Error?W.message:"Unknown error occurred."})}finally{p(!1)}}},[M,g,H]);return{query:c,setQuery:d,isSettled:j,showLoading:m,browseErrorReason:K,reload:C,isPickingLocation:g,showHidden:h,setShowHidden:y,explorerRootDirectory:k,browseDirectoryDisplayPath:v,browseDirectoryAbsolutePath:w,browseFilterQuery:A,entries:q,rows:z,targetPath:H,isAlreadyAdded:D,shouldCreateTarget:I,canRequestAccess:r,navigate:S,handleBrowseLocation:G}}const sp={folder:"source","clone-url":"source","clone-location":"clone-url","new-name":"source","new-location":"new-name"},zt=e=>e==="folder"||e==="clone-location"||e==="new-location",rp=[{step:"folder",icon:"folder-6",title:"Folder on this server",description:"Pick a folder that’s already here."},{step:"clone-url",icon:"download-cloud",title:"Clone a repository",description:"Copy a Git repository from a URL."},{step:"new-name",icon:"folder-add",title:"New project",description:"Start an empty folder, with Git if you want it."}],op={folder:"Open folder","clone-url":"Clone","clone-location":"Clone","new-name":"New project","new-location":"New project"},ip={source:"Choose where the project comes from, type a folder path, or paste a Git URL.",folder:"Pick a folder on this server or type its path.","clone-url":"Paste the URL of the repository to clone.","clone-location":"Pick the folder the repository is cloned into.","new-name":"Name the new project.","new-location":"Pick the folder the new project goes in."},ap={source:"Filter sources, type a folder path, or paste a Git URL",folder:"Folder path","clone-url":"Repository URL","clone-location":"Location","new-name":"Project name","new-location":"Location"},lp={source:"Choose a source, type a path, or paste a Git URL",folder:"~/","clone-url":"https://github.com/owner/repo.git","clone-location":"~/","new-name":"Project name","new-location":"~/"},cp=e=>/^(~|\/|[a-zA-Z]:[\\/])/.test(e),dp=e=>/^(https?:\/\/|ssh:\/\/|git:\/\/|git@)/i.test(e)||/^[\w.-]+@[\w.-]+:/.test(e),up=e=>pn(kn(e)).split("/").pop()??"",fp=({open:e,onOpenChange:t})=>{const s=dt(U=>U.projects),{isMobile:r,isTablet:o}=xs(),i=r||o,[a,c]=l.useState("source"),[d,u]=l.useState(""),[f,m]=l.useState(""),[b,g]=l.useState(""),[p,h]=l.useState(!0),[y,x]=l.useState(null),k=l.useRef(null),v=l.useRef(new Map),A=l.useId(),w=l.useMemo(()=>new Set(s.map(U=>Nr(U.path)).filter(U=>!!U)),[s]),j=l.useCallback(()=>t(!1),[t]),S=np({open:e,addedProjectPaths:w}),{pending:C,error:E,clearError:P,addFolder:z,cloneRepository:K,createProject:q}=Zh({open:e,onClose:j,isMobile:r});l.useEffect(()=>{e&&(c("source"),u(""),m(""),g(""),h(!0),x(null))},[e]),l.useEffect(()=>{P()},[S.query,P,b,f,a]),l.useLayoutEffect(()=>{e&&(i&&a!=="clone-url"&&a!=="new-name"||Jh(k.current))},[i,e,a]);const H=l.useCallback(U=>{c(U),x(null)},[]),F=l.useCallback(()=>{C||a==="source"||H(sp[a])},[H,C,a]),{navigate:D}=S,T=l.useCallback(U=>{const ge=U.type==="parent"?`dir:${up(U.path)}`:null;D(U.target).then(se=>{se&&x(ge)})},[D]),I=l.useMemo(()=>new Set(S.entries.map(U=>U.name)),[S.entries]),M=S.browseDirectoryDisplayPath,G=S.browseErrorReason==="not-found"?"This folder doesn’t exist. Pick a location that does.":S.browseErrorReason?"PiChamber can’t read this location.":null,W=!S.isSettled||S.isPickingLocation,L=$h(f),ae=b.trim(),J=Kh(ae);let le=!1,Ie="",Y="",B=null;if(a==="folder"){Y="Adding…";const U=pn(S.query.trim())||S.query.trim();if(S.isAlreadyAdded)Ie="Added",U&&(B={tone:"outcome",text:"Already added:",path:U});else{Ie=S.shouldCreateTarget?"Create and add":"Add";const ge=S.browseErrorReason&&S.browseErrorReason!=="not-found";le=!!S.targetPath&&!ge&&!W,U&&!ge&&(B={tone:"outcome",text:S.shouldCreateTarget?"Creates and adds":"Adds",path:U})}}else if(a==="clone-location"){Ie="Clone",Y="Cloning…";const U=ua(M,L);G?B={tone:"problem",text:G}:I.has(L)?B={tone:"problem",text:"Already exists:",path:U}:(B={tone:"outcome",text:"Clones into",path:U},le=!!L&&!W)}else if(a==="new-location"){Ie="Create",Y="Creating…";const U=ua(M,ae);G?B={tone:"problem",text:G}:J?B={tone:"problem",text:J,path:U}:I.has(ae)?B={tone:"problem",text:"Already exists:",path:U}:(B={tone:"outcome",text:"Creates",path:U},le=!W)}le=le&&C===null;const $=()=>{le&&(a==="folder"?z(S.targetPath,{create:S.shouldCreateTarget,location:S.browseDirectoryAbsolutePath}):a==="clone-location"?K(f,S.browseDirectoryAbsolutePath):a==="new-location"&&q(S.browseDirectoryAbsolutePath,ae,p))},X=a==="clone-url"?!!L:a==="new-name"?!!ae&&!J:!1,ee=()=>{X&&H(a==="clone-url"?"clone-location":"new-location")},ie=[];if(a==="source"){const U=d.trim().toLowerCase();for(const ge of rp)U&&!`${ge.title} ${ge.description}`.toLowerCase().includes(U)||ie.push({key:`source:${ge.step}`,kind:"source",select:()=>H(ge.step),content:n.jsxs(n.Fragment,{children:[n.jsx(R,{name:ge.icon,className:"size-4 shrink-0 text-muted-foreground"}),n.jsxs("span",{className:"flex min-w-0 flex-1 flex-col py-0.5",children:[n.jsx("span",{className:"truncate",children:ge.title}),n.jsx("span",{className:"truncate typography-meta text-muted-foreground",children:ge.description})]})]})})}else if(zt(a)){a==="new-location"&&ie.push({key:"toggle:git",kind:"toggle",select:()=>h(U=>!U),ariaChecked:p,ariaLabel:"Initialize a Git repository",content:n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"pointer-events-none flex size-4 shrink-0 items-center justify-center",children:n.jsx(Qs,{checked:p,onChange:h})}),n.jsx("span",{className:"flex-1 truncate",children:"Initialize a Git repository"})]})});for(const U of S.rows){const ge=U.type==="parent";ie.push({key:ge?"browse:up":`dir:${U.name}`,kind:ge?"parent":"directory",select:()=>T(U),ariaLabel:ge?`Up to ${U.target}`:`${U.name}${U.alreadyAdded?", already added":""}`,content:n.jsxs(n.Fragment,{children:[n.jsx(R,{name:ge?"arrow-up-s":"folder-6",className:"size-4 shrink-0 text-muted-foreground"}),ge?n.jsxs("span",{className:"flex min-w-0 flex-1 items-baseline gap-2",children:[n.jsx("span",{className:"shrink-0",children:"Up to"}),n.jsx(Ks,{value:U.target,className:"min-w-0 font-mono typography-meta text-muted-foreground"})]}):n.jsx("span",{className:"min-w-0 flex-1 truncate",children:U.name}),!ge&&U.alreadyAdded?n.jsx("span",{className:"shrink-0 typography-micro text-muted-foreground",children:"Added"}):null]})})}}const ke=zt(a)?ie.findIndex(U=>U.kind==="directory"):ie.length>0?0:-1,pe=y?ie.findIndex(U=>U.key===y):-1,je=pe>=0?pe:ke,be=je>=0?ie[je]:void 0,ze=be?.key,me=U=>`${A}-option-${U}`;l.useLayoutEffect(()=>{ze&&v.current.get(ze)?.scrollIntoView({block:"nearest"})},[ze]);const Pe=U=>{if(ie.length===0)return;const ge=je>=0?je:U>0?-1:ie.length,se=Math.min(ie.length-1,Math.max(0,ge+U));x(ie[se]?.key??null)},V=a==="source"?d:a==="clone-url"?f:a==="new-name"?b:S.query,fe=U=>{if(x(null),a==="source"){const ge=U.trimStart();if(dp(ge)){u(""),m(ge),H("clone-url");return}if(cp(ge)){u(""),S.setQuery(ge==="~"?"~/":kn(ge)),H("folder");return}u(U);return}if(a==="clone-url"){m(U);return}if(a==="new-name"){g(U);return}S.setQuery(kn(U).replace(/\/{2,}/g,"/"))},xe=U=>{if(!U.nativeEvent.isComposing){if(U.key==="ArrowDown"||U.key==="ArrowUp"){if(ie.length===0)return;U.preventDefault(),Pe(U.key==="ArrowDown"?1:-1);return}if(U.key==="Enter"){if(U.preventDefault(),C)return;if(zt(a)&&Yh(U)){$();return}if(a==="clone-url"||a==="new-name"){ee();return}be?be.select():zt(a)&&$();return}if(U.key==="Tab"&&!U.shiftKey&&be?.kind==="directory"){U.preventDefault(),be.select();return}U.key==="Backspace"&&V===""&&a!=="source"&&(U.preventDefault(),F())}},te=Qh(),re=[];ie.length>1&&re.push({keys:["↑","↓"],label:"Navigate"}),a==="source"?be&&re.push({keys:["↵"],label:"Select"}):a==="clone-url"||a==="new-name"?re.push({keys:["↵"],label:"Continue"}):be?re.push({keys:["↵"],label:be.kind==="toggle"?"Toggle":"Open"}):re.push({keys:["↵"],label:Ie}),a!=="source"&&V===""&&re.push({keys:["⌫"],label:"Back"}),re.push({keys:["Esc"],label:"Close",onSelect:()=>t(!1)});const Be=zt(a)&&be?[te,"↵"]:["↵"];let Ce=null;zt(a)?Ce=n.jsxs(Ae,{variant:"solid",size:"sm",className:"shrink-0 gap-1.5",disabled:!le,onMouseDown:U=>U.preventDefault(),onClick:$,children:[C?Y:Ie,!r&&!C&&le?n.jsx("span",{className:"flex items-center gap-0.5",children:Be.map(U=>n.jsx(Ji,{className:"border-current/30 bg-transparent text-current",children:U},U))}):null]}):(a==="clone-url"||a==="new-name")&&(Ce=n.jsxs(Ae,{variant:"solid",size:"sm",className:"shrink-0 gap-1.5",disabled:!X,onMouseDown:U=>U.preventDefault(),onClick:ee,children:["Continue",!r&&X?n.jsx(Ji,{className:"border-current/30 bg-transparent text-current",children:"↵"}):null]}));let Q=null;const ve=ie.filter(U=>U.kind==="directory").length;a==="source"&&ie.length===0?Q={tone:"quiet",text:"Nothing matches. Type a folder path, or paste a Git URL."}:a==="clone-url"?f.trim()?L?Q={tone:"quiet",text:n.jsxs(n.Fragment,{children:["Clones as ",n.jsx("span",{className:"font-mono text-foreground",children:L}),". Press Enter to choose where it goes."]})}:Q={tone:"problem",text:"This URL doesn’t name a repository."}:Q={tone:"quiet",text:"Paste the repository’s HTTPS or SSH URL, then press Enter to choose where it goes."}:a==="new-name"?ae?J?Q={tone:"problem",text:J}:Q={tone:"quiet",text:n.jsxs(n.Fragment,{children:["Press Enter to choose where ",n.jsx("span",{className:"font-mono text-foreground",children:ae})," goes."]})}:Q={tone:"quiet",text:"Name the project, then press Enter to choose where it goes."}:zt(a)&&(S.browseErrorReason==="not-found"?Q=a==="folder"?{tone:"quiet",text:"This folder doesn’t exist yet. Adding it creates it."}:{tone:"problem",text:"This folder doesn’t exist. Pick a location that does."}:S.browseErrorReason?Q={tone:"problem",text:S.browseErrorReason==="os-permission"?"PiChamber needs access to this folder.":"Couldn’t read this folder.",actions:n.jsxs(n.Fragment,{children:[S.browseErrorReason==="os-permission"&&S.canRequestAccess?n.jsx(Ae,{size:"xs",onClick:()=>{S.handleBrowseLocation()},disabled:S.isPickingLocation,children:"Grant access"}):null,n.jsx(Ae,{variant:"outline",size:"xs",onClick:S.reload,children:"Try again"})]})}:S.showLoading&&ve===0?Q={tone:"quiet",text:"Loading folders…"}:S.isSettled&&ve===0&&(Q={tone:"quiet",text:S.browseFilterQuery?a==="folder"?n.jsxs(n.Fragment,{children:["No folder named ",n.jsx("span",{className:"font-mono text-foreground",children:S.browseFilterQuery})," here. Adding it creates it."]}):"No folders match.":"No folders in here."}));const he=E?n.jsx("p",{role:"alert",className:"border-b border-border/60 px-4 py-2 typography-meta text-[var(--status-error)] text-pretty",children:E}):null,Se=(U,ge)=>n.jsx("button",{type:"button",onClick:F,disabled:C!==null,"aria-label":ge,className:"ml-auto shrink-0 rounded px-1 typography-ui-label text-muted-foreground underline-offset-2 hover:text-foreground hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:pointer-events-none disabled:opacity-50",children:U}),qe=B?n.jsxs("div",{className:"flex flex-col gap-1 border-b border-border/60 px-4 py-2",children:[a==="new-location"?n.jsxs("div",{className:"flex min-w-0 items-center gap-2 typography-ui-label",children:[n.jsx("label",{htmlFor:"new-project-name",className:"shrink-0 text-muted-foreground",children:"Name"}),n.jsx("input",{value:b,onChange:U=>g(U.target.value),onKeyDown:U=>{U.nativeEvent.isComposing||U.key==="Enter"&&(U.preventDefault(),$())},id:"new-project-name",spellCheck:!1,autoComplete:"off",disabled:C!==null,className:"h-7 min-w-0 flex-1 rounded-md border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-1.5 font-mono text-foreground outline-none focus-visible:border-[var(--interactive-focus)] focus-visible:ring-2 focus-visible:ring-primary/30"})]}):null,n.jsxs("p",{className:_("flex min-w-0 items-baseline gap-1.5 typography-ui-label",B.tone==="problem"?"text-[var(--status-error)]":"text-muted-foreground"),children:[n.jsx("span",{className:"shrink-0",children:B.text}),B.path?n.jsx(Ks,{value:B.path,className:"min-w-0 font-mono text-foreground"}):null]}),a==="clone-location"?n.jsxs("p",{className:"flex min-w-0 items-baseline gap-1.5 typography-ui-label text-muted-foreground",children:[n.jsx("span",{className:"shrink-0",children:"From"}),n.jsx(Ks,{value:f.trim(),className:"min-w-0 font-mono text-foreground"}),Se("Change","Change the repository URL")]}):null]}):null,Ue=a!=="source"&&a!=="new-name";return n.jsx(en,{open:e,onOpenChange:t,children:n.jsxs(tn,{showCloseButton:!1,initialFocus:i?!1:k,className:_("group/palette w-full max-w-xl gap-0 self-start overflow-hidden rounded-2xl p-0","mt-[max(env(safe-area-inset-top),0.25rem)] max-h-[calc(100%-0.5rem)] sm:mt-[10vh] sm:max-h-[80vh]"),children:[n.jsx(mn,{className:"sr-only",children:"Add folder"}),n.jsx(An,{className:"sr-only",children:ip[a]}),n.jsxs("div",{className:"flex h-12 shrink-0 items-center gap-2 border-b border-border/60 pl-2.5 pr-2",children:[a==="source"?n.jsx("span",{className:"flex size-7 shrink-0 items-center justify-center text-muted-foreground",children:n.jsx(R,{name:"folder-add",className:"size-4"})}):n.jsx(Ae,{variant:"ghost",size:"icon",className:"size-7 shrink-0",onMouseDown:U=>U.preventDefault(),onClick:F,disabled:C!==null,"aria-label":"Back",title:"Back",children:n.jsx(R,{name:"arrow-left-s",className:"size-4"})}),a!=="source"?n.jsxs("span",{className:"flex shrink-0 items-center gap-2 typography-ui-label font-medium text-foreground","aria-hidden":"true",children:[op[a],n.jsx("span",{className:"h-4 w-px bg-border"})]}):null,n.jsx("input",{ref:k,value:V,onChange:U=>fe(U.target.value),onKeyDown:xe,readOnly:C!==null,"aria-busy":C!==null||void 0,"aria-label":ap[a],placeholder:lp[a],role:"combobox","aria-expanded":ie.length>0,"aria-controls":A,"aria-autocomplete":"list","aria-activedescendant":je>=0?me(je):void 0,"aria-invalid":Q?.tone==="problem"&&!zt(a)?!0:void 0,spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",className:_("min-w-0 flex-1 text-foreground outline-none placeholder:text-muted-foreground",a==="source"?"h-full bg-transparent":"h-8 rounded-md border border-[var(--interactive-border)] bg-[var(--surface-muted)] px-2","typography-markdown md:typography-ui-label",Ue&&"font-mono")}),Ce]}),qe,he,n.jsxs("div",{className:"min-h-0 overflow-y-auto overscroll-contain sm:max-h-[min(24rem,52vh)]",children:[ie.length>0?n.jsx("div",{id:A,role:"listbox","aria-label":a==="source"?"Sources":"Folders",className:"flex flex-col gap-px p-1.5",children:ie.map((U,ge)=>n.jsxs(l.Fragment,{children:[ge>0&&ie[ge-1]?.kind==="toggle"?n.jsx("div",{role:"presentation",className:"mx-2.5 my-1 h-px bg-border/60"}):null,n.jsx(tc,{ref:se=>{se?v.current.set(U.key,se):v.current.delete(U.key)},id:me(ge),active:ge===je,onSelect:U.select,onHover:()=>x(U.key),ariaLabel:U.ariaLabel,ariaChecked:U.ariaChecked,className:U.kind==="source"?"py-2":void 0,quiet:zt(a),children:U.content})]},U.key))}):null,Q?n.jsxs("div",{className:_("flex flex-col items-center gap-3 px-6 text-center",ie.length>0?"pb-6 pt-3":"py-8"),children:[n.jsx("p",{className:_("typography-meta text-balance",Q.tone==="problem"?"text-[var(--status-error)]":"text-muted-foreground"),children:Q.text}),Q.actions?n.jsx("div",{className:"flex items-center gap-2",children:Q.actions}):null]}):null]}),!r||zt(a)?n.jsxs("div",{className:"flex min-h-10 shrink-0 items-center justify-between gap-3 border-t border-border/60 bg-[var(--surface-muted)]/40 px-3 py-2 typography-micro text-muted-foreground",children:[r?n.jsx("span",{}):n.jsx(ku,{hints:re}),zt(a)?n.jsxs("span",{className:"flex shrink-0 items-center gap-3",children:[n.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5",children:[n.jsx(Qs,{checked:S.showHidden,onChange:S.setShowHidden,ariaLabel:"Show hidden folders"}),"Hidden"]}),n.jsx(Ae,{variant:"ghost",size:"xs",disabled:C!==null||S.isPickingLocation,onMouseDown:U=>U.preventDefault(),onClick:()=>{S.handleBrowseLocation()},title:"Pick a folder with the system dialog",children:S.isPickingLocation?"Opening…":"Browse…"})]}):null]}):null]})})},pr=e=>e?n.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:e}):void 0,fw=()=>{const[e,t]=l.useState(!1),[s,r]=l.useState(null),[o,i]=l.useState(!1),a=Me(j=>j.deleteSession),c=Me(j=>j.deleteSessions),d=ue(j=>j.showDeletionDialog),u=ue(j=>j.setShowDeletionDialog),{isMobile:f,isTablet:m,hasTouchInput:b}=xs(),g=f||m||b;l.useEffect(()=>Zf(()=>{t(!1)}),[]);const p=l.useCallback(j=>{r({sessions:j.sessions,dateLabel:j.dateLabel})},[]),h=l.useCallback(()=>{r(null),i(!1)},[]),y=l.useCallback(async j=>{if(j.sessions.length===0)return;if(j.sessions.length===1){const P=j.sessions[0];await a(P.id)?oe.success("Session deleted"):oe.error("Failed to delete session");return}const S=j.sessions.map(P=>P.id),{deletedIds:C,failedIds:E}=await c(S);if(C.length>0){const P=E.length>0?E.length===1?`${E.length} session could not be deleted.`:`${E.length} sessions could not be deleted.`:j.dateLabel?`Removed all sessions from ${j.dateLabel}.`:void 0;oe.success(C.length===1?"Deleted {count} session":`Deleted ${C.length} sessions`,{description:pr(P)})}E.length>0&&oe.error(E.length===1?`Failed to delete ${E.length} session`:`Failed to delete ${E.length} sessions`,{description:pr("Please try again in a moment.")})},[a,c]);l.useEffect(()=>Js.onDeleteRequest(j=>{if(!d){y(j);return}p(j)}),[p,d,y]),l.useEffect(()=>Js.onDirectoryRequest(()=>{t(!0)}),[]);const x=l.useCallback(async()=>{if(s){i(!0);try{if(s.sessions.length===1){const j=s.sessions[0];if(!await a(j.id)){oe.error("Failed to delete session"),i(!1);return}oe.success("Session deleted",{action:{label:"OK",onClick:()=>{}}})}else{const j=s.sessions.map(P=>P.id),S=await c(j),C=S.deletedIds,E=S.failedIds;if(C.length>0){const P=E.length>0?E.length===1?`${E.length} session could not be deleted.`:`${E.length} sessions could not be deleted.`:s.dateLabel?`Removed all sessions from ${s.dateLabel}.`:void 0;oe.success(C.length===1?"Deleted {count} session":`Deleted ${C.length} sessions`,{description:pr(P),action:{label:"OK",onClick:()=>{}}})}if(E.length>0&&(oe.error(E.length===1?`Failed to delete ${E.length} session`:`Failed to delete ${E.length} sessions`,{description:pr("Please try again in a moment.")}),C.length===0)){i(!1);return}}h()}finally{i(!1)}}},[s,a,c,h]),k=s?s.sessions.length===1?s.dateLabel?`This action permanently removes 1 session from ${s.dateLabel}.`:"This action permanently removes 1 session.":s.dateLabel?`This action permanently removes ${s.sessions.length} sessions from ${s.dateLabel}.`:`This action permanently removes ${s.sessions.length} sessions.`:"",v=s?n.jsxs("div",{className:"space-y-2",children:[s.sessions.length>0&&n.jsx("div",{className:"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3",children:n.jsxs("ul",{className:"space-y-0.5",children:[s.sessions.slice(0,5).map(j=>n.jsx("li",{className:"typography-micro text-subtle-foreground",children:n.jsx("span",{className:"truncate",children:un(j)})},j.id)),s.sessions.length>5&&n.jsx("li",{className:"typography-micro text-subtle-foreground",children:`+${s.sessions.length-5} more`})]})}),n.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/60 p-3",children:n.jsx("p",{className:"typography-meta text-subtle-foreground",children:"Worktree directories stay intact. Subsessions linked to the selected sessions will also be removed."})})]}):null,A=n.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[n.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?n.jsx(R,{name:"checkbox-blank",className:"size-4"}):n.jsx(R,{name:"checkbox",className:"size-4 text-primary"}),"Never ask"]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Ae,{variant:"ghost",onClick:h,disabled:o,children:"Cancel"}),n.jsx(Ae,{variant:"destructive",onClick:x,disabled:o,children:o?"Deleting…":s?.sessions.length===1?"Delete session":"Delete sessions"})]})]}),w=s?.sessions.length===1?"Delete session":"Delete sessions";return n.jsxs(n.Fragment,{children:[g?n.jsx(Au,{open:!!s,onClose:()=>{o||h()},title:w,footer:n.jsx("div",{className:"flex justify-end gap-2",children:A}),children:n.jsxs("div",{className:"space-y-2 pb-2",children:[k&&n.jsx("p",{className:"typography-meta text-subtle-foreground",children:k}),v]})}):n.jsx(en,{open:!!s,onOpenChange:j=>{if(!j){if(o)return;h()}},children:n.jsxs(tn,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[n.jsxs($n,{children:[n.jsx(mn,{children:w}),k&&n.jsx(An,{children:k})]}),n.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:v}),n.jsx(ys,{className:"mt-2 gap-2 pt-1 pb-1",children:A})]})}),n.jsx(fp,{open:e,onOpenChange:t})]})},hw=()=>{const e=zn(t=>t.entries);return l.useEffect(()=>{for(const t of e.values())!Nu(t)||!t.receipt||(zn.getState().markNotificationSent(t.key),oe.success("Worktree ready",{id:`worktree-ready:${t.key}`,description:t.receipt.branch||t.receipt.path}))},[e]),null},hp=[{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:"plugins",title:"Extensions & Plugins",group:"agent",kind:"single",description:"PiChamber plugins, and the extensions and packages Pi loads.",keywords:["plugin","plugins","extension","extensions","package","packages","pi config","pi list","pi remove","add-ons","visuals","html","render","chart","diagram","tools","sub-agents","subagents","composer","toggles"]},{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"]}],pp={sessions:"sessions",skills:"skills.installed",providers:"providers","git-identities":"git",settings:"home"};function mp(e){const t=e.trim().toLowerCase();return hp.find(s=>s.slug===t)??null}function gp(e){const t=(e??"").trim().toLowerCase();if(!t)return"home";if(t==="remote-instances")return"remote-access";const s=pp[t];if(s)return s;const r=mp(t);return r?r.slug:"home"}function pw(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"plugins":return"plug";case"git":return"git-repository";case"tunnel":return"global";case"about":return"pichamber";case"home":return null;default:return"robot-2"}}function mw(){const e=l.useRef(!1),t=l.useRef(!1),s=Me(f=>f.setCurrentSession),r=ue(f=>f.setActiveMainTab),o=ue(f=>f.setSettingsDialogOpen),i=ue(f=>f.setSettingsPage),a=ue(f=>f.navigateToDiff),c=l.useCallback(async f=>{if(!t.current){t.current=!0;try{if(f.sessionId){const m=Me.getState().currentSessionId,b=rs().getState().selectedSessionId;if(f.sessionId!==m||f.sessionId!==b){const g=Me.getState().getDirectoryForSession(f.sessionId);s(f.sessionId,g)}}if(f.settingsPath){i(gp(f.settingsPath)),o(!0);return}ue.getState().isSettingsDialogOpen&&o(!1),f.tab&&r(f.tab),f.diffFile&&(f.tab==="diff"||!f.tab)&&a(f.diffFile)}finally{t.current=!1}}},[s,r,o,i,a]),d=l.useCallback(()=>{const f=Me.getState(),m=rs().getState(),b=ue.getState();return{sessionId:lo({currentSessionId:f.currentSessionId,piSelectedSessionId:m.selectedSessionId,draft:f.newSessionDraft}),tab:b.activeMainTab,isSettingsOpen:b.isSettingsDialogOpen,settingsPath:b.settingsPage,diffFile:b.pendingDiffFile}},[]),u=l.useCallback((f={})=>{if(t.current)return;const m=d();Xo(m,f)},[d]);l.useEffect(()=>{if(e.current||(e.current=!0,!Xi()))return;const f=Zi();(async()=>(await c(f),Xo({...d(),sessionId:f.sessionId??lo({currentSessionId:Me.getState().currentSessionId,piSelectedSessionId:rs().getState().selectedSessionId,draft:Me.getState().newSessionDraft}),tab:f.tab??ue.getState().activeMainTab,settingsPath:f.settingsPath??ue.getState().settingsPage,diffFile:f.diffFile??ue.getState().pendingDiffFile},{replace:!0,force:!0})))()},[c,d]),l.useEffect(()=>{const f=()=>{const y=Me.getState(),x=rs().getState();return lo({currentSessionId:y.currentSessionId,piSelectedSessionId:x.selectedSessionId,draft:y.newSessionDraft})};let m=f(),b=Me.getState().newSessionDraft?.open===!0;const g=()=>{const y=Me.getState(),x=f(),k=y.newSessionDraft?.open===!0;x===m&&k===b||t.current||(m=x,b=k,u({replace:!0}))},p=Me.subscribe(()=>{g()}),h=rs().subscribe(()=>{g()});return()=>{p(),h()}},[u]),l.useEffect(()=>{let f=ue.getState().activeMainTab,m=ue.getState().isSettingsDialogOpen,b=ue.getState().settingsPage,g=ue.getState().pendingDiffFile;return ue.subscribe(h=>{if(t.current)return;const y=h.activeMainTab!==f,x=h.isSettingsDialogOpen!==m,k=h.settingsPage!==b,v=h.pendingDiffFile!==g&&h.activeMainTab==="diff";f=h.activeMainTab,m=h.isSettingsDialogOpen,b=h.settingsPage,g=h.pendingDiffFile,(y||x||k||v)&&u()})},[u]),l.useEffect(()=>{if(typeof window>"u")return;const f=()=>{const m=Zi();if(Xi())c(m);else{const b=ue.getState();b.isSettingsDialogOpen&&o(!1),b.activeMainTab!=="chat"&&r("chat")}};return window.addEventListener("popstate",f),()=>{window.removeEventListener("popstate",f)}},[c,r,o])}function bp(e=!0){const t=Cr(r=>r.checkForUpdates),s=l.useRef(t);l.useEffect(()=>{s.current=t},[t]),l.useEffect(()=>{if(!e)return;const r=3e3,o=3600*1e3,i=300*1e3,a=1440*60*1e3;let c=!1,d=null;const u=m=>{const b=Math.round(m*1e3);return Math.max(i,Math.min(a,b))},f=m=>{c||(d=window.setTimeout(async()=>{const b=await s.current(),g=typeof b=="number"&&Number.isFinite(b)?u(b):o;f(g)},m))};return f(r),()=>{c=!0,d!==null&&window.clearTimeout(d)}},[e])}function gw(){const e=Ws(t=>t.connection==="ready",void 0,"chrome");return bp(e),null}const xp=200,yp=15e3,wp=e=>{const{id:t,url:s}=e.payload,r=Eu(e.payload);if(!r.showNotice)return;const o=`open-request:${t}`,i=Du(Ru(s),r.target,{isMobile:ue.getState().isMobile});if(!i.canOpen){oe.info(i.title,{id:o,description:i.description,duration:yp});return}oe.info(i.title,{id:o,description:i.description,duration:1/0,action:{label:"Open",onClick:()=>{Pu(r.target,s,Tu()||e.directory)}},cancel:{label:"Dismiss",onClick:()=>{oe.dismiss(o)}}})},bw=()=>(l.useEffect(()=>{const e=new Set;return Iu(t=>{if(!e.has(t.payload.id)){if(e.add(t.payload.id),e.size>xp){const s=e.values().next().value;s!==void 0&&e.delete(s)}wp(t)}})},[]),null),fa=12,vp=[{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"}],Sp=({isActive:e,burstKey:t=0,className:s,durationMs:r=900,bursts:o=vp,onComplete:i})=>{const a=Te.useRef(!1);Te.useEffect(()=>{!e&&a.current&&i?.(),e&&(a.current=!0)},[e,i]);const c=Te.useMemo(()=>Array.from({length:fa},(d,u)=>{const f=Math.PI*2*u/fa;return{x:Math.cos(f),y:Math.sin(f),delay:u*18}}),[]);return e?n.jsx("div",{className:_("fireworks-overlay pointer-events-none",s),"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 n.jsx("div",{className:"firework-burst",style:u,children:c.map((f,m)=>{const b=f.x*d.radius,g=f.y*d.radius,p={"--translate-x":`${b}px`,"--translate-y":`${g}px`,"--particle-delay":`${f.delay}ms`,color:`var(${d.colorVar})`};return n.jsx("span",{className:"firework-particle",style:p},`${d.id}-${m}-${t}`)})},`${d.id}-${t}`)})}):null},jp=({durationMs:e=3400}={})=>{const[t,s]=Te.useState({isActive:!1,cycle:0}),r=Te.useRef(null),o=Te.useCallback(()=>{r.current&&(window.clearTimeout(r.current),r.current=null)},[]),i=Te.useCallback(()=>{o(),s(c=>c.isActive?{...c,isActive:!1}:c)},[o]),a=Te.useCallback(()=>{o(),s(c=>({isActive:!0,cycle:c.cycle+1})),r.current=window.setTimeout(()=>{s(c=>c.isActive?{...c,isActive:!1}:c),r.current=null},e)},[o,e]);return Te.useEffect(()=>()=>o(),[o]),{isActive:t.isActive,burstKey:t.cycle,triggerFireworks:a,dismissFireworks:i}},rc=l.createContext(void 0),xw=({children:e})=>{const{isActive:t,burstKey:s,triggerFireworks:r,dismissFireworks:o}=jp(),i=l.useMemo(()=>({triggerFireworks:r,dismissFireworks:o}),[r,o]);return n.jsxs(rc.Provider,{value:i,children:[e,n.jsx(Sp,{isActive:t,burstKey:s})]})},Cp={triggerFireworks:()=>{},dismissFireworks:()=>{}},yw=()=>l.useContext(rc)??Cp,Mr=2e3,oc=600*1e3;async function kp(){try{const e=await tt("/api/pi/update-install",{method:"POST",headers:{"Content-Type":"application/json"}});if(!e.ok){const s=await e.json().catch(()=>({}));return{success:!1,error:s.error||`Server error: ${e.status}`,commands:Array.isArray(s.commands)?s.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 Ap(e,t=Math.ceil(oc/Mr),s=Mr,r=Ze()){for(let o=0;o<t;o++){if(Ze()!==r)return{applied:!1,stale:!0};try{const i=await tt("/api/pi/update-check",{method:"GET",headers:{Accept:"application/json"}});if(Ze()!==r)return{applied:!1,stale:!0};if(i.ok){const a=await i.json().catch(()=>null);if(Ze()!==r)return{applied:!1,stale:!0};if(typeof a?.error=="string"&&a.error.length>0)return{applied:!1,error:a.error};if(a&&a.available===!1)return{applied:!0};if(a&&typeof a.currentVersion=="string"&&typeof e=="string"&&a.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(Ze()!==r)return{applied:!1,stale:!0}}await new Promise(i=>setTimeout(i,s))}return{applied:!1}}async function Np(e,t,s=Math.ceil(oc/Mr),r=Mr,o=Ze()){for(let i=0;i<s;i++){if(Ze()!==o)return{applied:!1,stale:!0};try{const a=await tt(`/api/pi/update-install/${encodeURIComponent(e)}`,{method:"GET",headers:{Accept:"application/json"}});if(Ze()!==o)return{applied:!1,stale:!0};if(a.ok){const c=await a.json().catch(()=>null);if(Ze()!==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(a.status===401||a.status===403)return{applied:!1,error:"Authentication was lost while following the update. Reauthenticate to check its status."};if(a.status===404)return{applied:!1,error:"The server lost the update status. Check the installed version or run: pichamber update"};if(a.status===503){const c=await a.json().catch(()=>null);if(Ze()!==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(Ze()!==o)return{applied:!1,stale:!0};t("reconnecting")}await new Promise(a=>setTimeout(a,r))}return{applied:!1}}const ha="https://github.com/RyderAsKing/PiChamber/releases";function Ip(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 Ep(e){return e.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function pa(e){return e.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function Dp(e,t){const s=u=>{const f=u.indexOf("-");return f<0?[u,""]:[u.slice(0,f),u.slice(f+1)]},[r,o]=s(e),[i,a]=s(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,m=Number.isFinite(d[u])?d[u]:0;if(f!==m)return m-f}return!o||!a?(o?1:0)-(a?1:0):a.localeCompare(o,void 0,{numeric:!0})}function Rp(e){const t=/^## \[(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)\] - (\d{4}-\d{2}-\d{2})\s*$/gm,s=[];let r;for(;(r=t.exec(e))!==null;)s.push({version:r[1]??"",date:r[2]??"",start:r.index});return s.length===0?[]:s.map((o,i)=>{const a=s[i+1]?.start??e.length,c=e.slice(o.start,a).trim();return{version:o.version,date:o.date,start:o.start,end:a,raw:c}})}const ic=({open:e,onOpenChange:t,info:s,downloading:r,downloaded:o,progress:i,error:a,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[f,m]=Te.useState(null),[b,g]=Te.useState("idle"),[p,h]=Te.useState(null),[y,x]=Te.useState(null),[k,v]=Te.useState({}),A=s?.version?s.releaseUrl||`${ha}/tag/v${s.version}`:ha,w=s?.downloadUrl||A,j=i?.total?Math.round(i.downloaded/i.total*100):0,S=u==="web",C=u==="mobile",E=s?.updateCommand||"pichamber update",P=k.version||s?.version,z=k.channel||s?.channel;Te.useEffect(()=>{e||(g("idle"),h(null),x(null),v({}))},[e]);const K=async(I=E)=>{(await fn(I)).ok&&(m(I),setTimeout(()=>m(null),2e3))},q=Te.useCallback(async I=>{await Cl(I)},[]),H=Te.useCallback(async()=>{const I=Ze();g("updating"),h(null),x(null),v({});const M=await kp();if(Ze()!==I)return;if(!M.success){g("error"),h(M.error||"Update failed"),x(M.commands??null);return}if(v({version:M.targetVersion,channel:M.channel}),M.jobId){const W=await Np(M.jobId,L=>{Ze()===I&&g(L)},void 0,void 0,I);if(W.stale||Ze()!==I)return;if(W.applied){window.location.reload();return}g("error"),h(W.error||"Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update");return}g(M.autoRestart?"restarting":"reconnecting");const G=await Ap(s?.currentVersion,void 0,void 0,I);if(!(G.stale||Ze()!==I)){if(G.applied){window.location.reload();return}g("error"),h(G.error||"Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update")}},[s?.currentVersion]),F=Te.useCallback(()=>{q(w)},[q,w]),D=b!=="idle"&&b!=="error",T=Te.useMemo(()=>{if(!s?.body)return null;const I=s.body.trim();if(!I)return null;const M=Rp(I);return M.length===0?{kind:"raw",title:"What's new",content:pa(I)}:{kind:"sections",title:"What's new",sections:[...M].sort((W,L)=>Dp(W.version,L.version)).map(W=>({version:W.version,dateLabel:Ip(W.date),content:pa(Ep(W.raw)||I)}))}},[s?.body]);return n.jsx(en,{open:e,onOpenChange:D?void 0:t,children:n.jsxs(tn,{className:"max-w-4xl p-4 sm:p-5 bg-background border-[var(--interactive-border)]",showCloseButton:!0,children:[n.jsxs("div",{className:"mb-1 space-y-1 pr-8",children:[n.jsxs(mn,{className:"flex items-center gap-2.5",children:[n.jsx(R,{name:"download-cloud",className:"h-5 w-5 shrink-0 text-[var(--primary-base)]"}),n.jsx("span",{className:"text-lg font-semibold text-foreground",children:b==="restarting"||b==="reconnecting"?"Updating PiChamber...":"Update available"})]}),(s?.currentVersion||P||S&&z)&&n.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 pl-[1.875rem]",children:[(s?.currentVersion||P)&&n.jsxs("div",{className:"flex items-center gap-2 whitespace-nowrap font-mono text-sm",children:[s?.currentVersion&&n.jsx("span",{className:"text-muted-foreground",children:s.currentVersion}),s?.currentVersion&&P&&n.jsx("span",{className:"text-subtle-foreground","aria-hidden":"true",children:"→"}),P&&n.jsx("span",{className:"text-[var(--primary-base)] font-medium",children:P})]}),S&&z&&n.jsx("span",{className:"whitespace-nowrap typography-meta text-muted-foreground",children:z==="rc"?"RC channel":"Stable channel"})]})]}),n.jsxs("div",{className:"space-y-2",children:[S&&D&&n.jsxs("div",{className:"rounded-lg bg-[var(--surface-elevated)]/30 p-5 border border-[var(--surface-subtle)]",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx(R,{name:"loader",className:"h-5 w-5 animate-spin text-[var(--primary-base)]"}),n.jsxs("div",{className:"typography-ui-label text-foreground",children:[b==="updating"&&"Installing update...",b==="restarting"&&"Server restarting...",b==="reconnecting"&&"Waiting for server..."]})]}),n.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"The page will reload automatically when the update is complete."})]}),T&&!D&&n.jsx("div",{className:"rounded-lg border border-[var(--surface-subtle)] bg-[var(--surface-elevated)]/20 overflow-hidden",children:n.jsx(Ln,{className:"max-h-[min(400px,50dvh)] p-0",fillContainer:!1,children:T.kind==="raw"?n.jsx("div",{className:"p-4 typography-markdown-body text-foreground leading-relaxed break-words [&_a]:!text-[var(--primary-base)] [&_a]:!no-underline [&_a:hover]:!underline",onClickCapture:I=>{const G=I.target.closest("a");G&&G.href&&(I.preventDefault(),I.stopPropagation(),q(G.href))},children:n.jsx(ea,{content:T.content,disableLinkSafety:!0,enableFileReferences:!1})}):n.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:T.sections.map(I=>n.jsxs("div",{className:"p-4",children:[n.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[n.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]}),n.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:I.dateLabel})]}),n.jsx("div",{className:"typography-markdown-body text-foreground leading-relaxed break-words [&_a]:!text-[var(--primary-base)] [&_a]:!no-underline [&_a:hover]:!underline",onClickCapture:M=>{const W=M.target.closest("a");W&&W.href&&(M.preventDefault(),M.stopPropagation(),q(W.href))},children:n.jsx(ea,{content:I.content,disableLinkSafety:!0,enableFileReferences:!1})})]},I.version))})})}),(a||p)&&n.jsx("div",{className:"p-3 mt-4 bg-[var(--status-error-background)] border border-[var(--status-error-border)] rounded-lg",children:n.jsx("p",{className:"text-sm text-[var(--status-error)]",children:a||p})}),S&&b==="error"&&(y??[E]).length>0&&n.jsxs("div",{className:"space-y-2 mt-4",children:[n.jsxs("div",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[n.jsx(R,{name:"terminal",className:"h-4 w-4"}),n.jsx("span",{children:y?"Run these commands:":"Or update via terminal:"})]}),(y??[E]).map(I=>n.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:[n.jsx("code",{className:"flex-1 font-mono text-sm text-foreground overflow-x-auto whitespace-nowrap",children:I}),n.jsx(Ae,{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?n.jsx(R,{name:"check",className:"h-4 w-4"}):n.jsx(R,{name:"clipboard",className:"h-4 w-4"})})]},I))]}),!S&&!C&&r&&n.jsxs("div",{className:"space-y-2 mt-4",children:[n.jsxs("div",{className:"flex items-center justify-between text-sm",children:[n.jsx("span",{className:"text-muted-foreground",children:"Downloading update payload..."}),n.jsxs("span",{className:"font-mono text-foreground",children:[j,"%"]})]}),n.jsx("div",{className:"h-1.5 bg-[var(--surface-subtle)] rounded-full overflow-hidden",children:n.jsx("div",{className:"h-full bg-[var(--primary-base)] transition-all duration-300",style:{width:`${j}%`}})})]})]}),n.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-between gap-x-4 gap-y-2",children:[n.jsxs("a",{href:A,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:[n.jsx(R,{name:"external-link",className:"h-4 w-4"}),"GitHub"]}),n.jsxs("div",{className:"flex-1 flex justify-end",children:[!S&&!C&&!o&&!r&&n.jsxs(Ae,{onClick:c,children:[n.jsx(R,{name:"download",className:"h-4 w-4"}),"Download update"]}),!S&&!C&&r&&n.jsxs(Ae,{disabled:!0,children:[n.jsx(R,{name:"loader",className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!S&&!C&&o&&n.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:[n.jsx(R,{name:"restart",className:"h-4 w-4"}),"Restart to update"]}),C&&n.jsxs(Ae,{onClick:F,size:"default",children:[n.jsx(R,{name:"external-link",className:"h-4 w-4"}),"Open update"]}),S&&!D&&n.jsxs(Ae,{onClick:H,children:[n.jsx(R,{name:"download",className:"h-4 w-4"}),"Update now"]}),S&&D&&n.jsxs(Ae,{disabled:!0,children:[n.jsx(R,{name:"loader",className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},ir=({children:e,className:t,contentClassName:s})=>{const[r,o]=l.useState(!1),i=l.useRef(null);return l.useEffect(()=>{if(!r)return;const a=c=>{const d=i.current;d&&c.target instanceof Node&&d.contains(c.target)||o(!1)};return document.addEventListener("pointerdown",a,!0),()=>document.removeEventListener("pointerdown",a,!0)},[r]),n.jsxs(Ke,{open:r,onOpenChange:o,children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{ref:i,type:"button","aria-label":"More information","aria-expanded":r,onClick:a=>{a.preventDefault(),a.stopPropagation(),o(c=>!c)},className:_("inline-flex h-5 w-5 shrink-0 cursor-help items-center justify-center rounded text-subtle-foreground hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",t),children:n.jsx(R,{name:"information",className:"h-3.5 w-3.5"})})}),n.jsx(Ge,{sideOffset:8,className:_("max-w-sm",s),children:e})]})},ww="w-full min-w-40 max-w-48",vw="settings",Pp="w-full min-w-40 max-w-48",Sw="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",Tp="w-full max-w-[24rem]",jw="min-w-0 flex-1",Cw="flex w-full min-w-0 items-center gap-2",kw="typography-meta shrink-0 text-muted-foreground tabular-nums",ac="space-y-3.5",Mp="space-y-1.5",Aw="typography-settings-page-title text-foreground",Fp="typography-settings-section-title text-foreground",lc="typography-settings-group-title text-foreground",Ni="typography-settings-field-label text-foreground",Lp="typography-settings-description text-muted-foreground",ar="typography-meta text-muted-foreground",Op="typography-meta font-medium text-foreground",Bp=({title:e,description:t,titleAccessory:s,info:r,headerAction:o,children:i,divider:a=!0,className:c,contentClassName:d,settingsItem:u})=>{const f=e!=null||t!=null||o!=null||r!=null;return n.jsxs("section",{"data-settings-item":u,className:_("space-y-4",a?"border-t border-border/60 py-6":"pb-6",c),children:[f?n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("div",{className:"min-w-0 space-y-1",children:[e!=null?n.jsxs("div",{className:"flex items-center gap-2",children:[typeof e=="string"||typeof e=="number"?n.jsx("h2",{className:Fp,children:e}):e,s,r!=null?n.jsx(ir,{children:r}):null]}):null,t!=null?n.jsx("div",{className:Lp,children:t}):null]}),o?n.jsx("div",{className:"shrink-0",children:o}):null]}):null,n.jsx("div",{className:_(d),children:i})]})},Nw=({children:e,className:t})=>n.jsx("div",{className:_("grid grid-cols-1 gap-6 @3xl:grid-cols-2 @3xl:gap-10",t),children:e}),_p=({children:e,className:t,as:s="h3"})=>n.jsx(s,{className:_(lc,t),children:e}),Iw=({title:e,description:t,info:s,children:r,className:o,contentClassName:i,settingsItem:a})=>n.jsxs("div",{"data-settings-item":a,className:_("space-y-2",o),children:[e!=null||t!=null||s!=null?n.jsxs("div",{className:"space-y-0.5",children:[e!=null?n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx(_p,{children:e}),s!=null?n.jsx(ir,{children:s}):null]}):null,t!=null?n.jsx("p",{className:ar,children:t}):null]}):null,n.jsx("div",{className:_(i),children:r})]}),qs=({label:e,description:t,info:s,descriptionPlacement:r="before",children:o,settingsItem:i,className:a,controlClassName:c})=>{const d=t!=null?n.jsx("p",{className:ar,children:t}):null;return n.jsxs("div",{"data-settings-item":i,className:_("space-y-2",a),children:[n.jsxs("div",{className:"space-y-0.5",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("div",{className:Ni,children:e}),s!=null?n.jsx(ir,{children:s}):null]}),r==="before"?d:null]}),n.jsx("div",{className:_("flex min-w-0 max-w-[24rem] items-center gap-2",c),children:o}),r==="after"?d:null]})},Ew=({label:e,description:t,info:s,children:r,settingsItem:o,className:i,labelClassName:a,controlClassName:c,alignEnd:d=!0})=>n.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:[n.jsxs("div",{className:_("min-w-0 @xl:w-56 @xl:shrink-0",a),children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("div",{className:Ni,children:e}),s!=null?n.jsx(ir,{children:s}):null]}),t!=null?n.jsx("p",{className:_(ar,"mt-0.5"),children:t}):null]}),n.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})]}),zp="typography-meta text-muted-foreground",Dw=({children:e,className:t,"aria-label":s})=>n.jsx("ul",{"aria-label":s,className:_("divide-y divide-border/60 overflow-hidden rounded-xl border border-border/60 bg-[var(--surface-elevated)]",t),children:e}),Rw=({title:e,titleAccessory:t,leading:s,detail:r,trailing:o,mono:i=!1,dimmed:a=!1,wrap:c=!1,heading:d=!1,interactive:u=!1,stackTrailing:f=!1,className:m,settingsItem:b})=>{const g=r!=null&&r!==!1,p=o!=null&&o!==!1;return n.jsxs("li",{"data-settings-item":b,className:_("relative flex min-w-0 items-center gap-x-3 px-3.5 py-2.5",d&&"bg-muted/50",u&&"transition-colors hover:bg-interactive-hover/60",m),children:[s,n.jsxs("div",{className:_("grid min-w-0 flex-1 items-center gap-x-3 gap-y-0.5",p&&!f?"grid-cols-[minmax(0,1fr)_auto]":"grid-cols-1",p&&f&&"@xl:grid-cols-[minmax(0,1fr)_auto]"),children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[typeof e=="string"||typeof e=="number"?n.jsx("span",{className:_("min-w-0",c?"text-pretty":"truncate",i?"font-mono typography-code":"typography-ui-label",d&&"font-medium",a?"text-muted-foreground":"text-foreground"),children:e}):e,t]}),p?n.jsx("div",{className:_("flex min-w-0 items-center gap-2",f?"order-last mt-1 @xl:order-none @xl:mt-0 @xl:justify-self-end":"justify-self-end",g&&"@xl:row-span-2"),children:o}):null,g?n.jsx("div",{className:_("min-w-0 space-y-0.5",p&&!f&&"col-span-2 @xl:col-span-1"),children:typeof r=="string"||typeof r=="number"?n.jsx("p",{className:_(zp,"line-clamp-2 text-pretty"),children:r}):r}):null]})]})},Pw=({title:e,children:t,action:s,className:r})=>n.jsxs("div",{role:"status",className:_("flex flex-col gap-x-4 gap-y-2.5 rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] px-3.5 py-3","@xl:flex-row @xl:items-center @xl:justify-between",r),children:[n.jsxs("div",{className:"min-w-0 space-y-0.5",children:[e!=null?n.jsx("p",{className:Op,children:e}):null,t!=null?n.jsx("p",{className:"typography-meta text-pretty text-foreground",children:t}):null]}),s!=null?n.jsx("div",{className:"shrink-0",children:s}):null]}),Tw=({children:e,className:t,settingsItem:s})=>n.jsx("div",{"data-settings-item":s,className:_("pt-4",t),children:e}),Mw=({label:e,children:t,divider:s=!0,className:r,contentClassName:o,defaultOpen:i=!1})=>{const[a]=l.useState(i);return n.jsxs("details",{open:a||void 0,className:_("group/disclosure",s?"border-t border-border/60 py-6":"pb-6",r),children:[n.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:[n.jsx(R,{name:"arrow-right-s",className:"size-4 transition-transform group-open/disclosure:rotate-90"}),e]}),n.jsx("div",{className:_("pt-4",o),children:t})]})},Up=({checked:e,onChange:t,label:s,description:r,disabled:o=!1,ariaLabel:i,settingsItem:a,className:c,labelAccessory:d,info:u})=>{const f=()=>{o||t(!e)},m=r!=null;return n.jsxs("div",{"data-settings-item":a,className:_("group flex cursor-pointer gap-2 py-0.5",m?"items-start":"items-center",o&&"cursor-not-allowed opacity-60",c),role:"button",tabIndex:o?-1:0,"aria-pressed":e,"aria-disabled":o||void 0,onClick:f,onKeyDown:b=>{(b.key===" "||b.key==="Enter")&&(b.preventDefault(),f())},children:[n.jsx(Qs,{checked:e,onChange:t,disabled:o,ariaLabel:i}),n.jsxs("div",{className:"flex min-w-0 flex-col",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[n.jsx("span",{className:Ni,children:s}),d,u!=null?n.jsx(ir,{children:u}):null]}),m?n.jsx("span",{className:ar,children:r}):null]})]})},Fw=({selected:e,onSelect:t,label:s,description:r,ariaLabel:o,disabled:i=!1,className:a})=>n.jsxs("div",{className:_("flex cursor-pointer gap-2 py-0.5",r!=null?"items-start":"items-center",i&&"cursor-not-allowed opacity-60",a),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:[n.jsx(kl,{checked:e,onChange:t,disabled:i,ariaLabel:o,className:r!=null?"mt-0.5":void 0}),n.jsxs("div",{className:"flex min-w-0 flex-col",children:[n.jsx("span",{className:_("typography-settings-field-label font-normal","text-foreground"),children:s}),r!=null?n.jsx("span",{className:ar,children:r}):null]})]}),Lw=({selected:e,onSelect:t,label:s,preview:r,description:o,ariaLabel:i,disabled:a=!1,className:c})=>{const d=l.useId();return n.jsxs("div",{className:_("group/preview flex min-w-0 cursor-pointer flex-col gap-2",a&&"cursor-not-allowed opacity-60",c),role:"radio",tabIndex:a?-1:0,"aria-checked":e,"aria-label":i,"aria-describedby":o?d:void 0,"aria-disabled":a||void 0,onClick:()=>{a||t()},onKeyDown:u=>{(u.key===" "||u.key==="Enter")&&(u.preventDefault(),a||t())},children:[n.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-[var(--interactive-border)] group-hover/preview:border-foreground/30"),children:r}),n.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[n.jsx(kl,{checked:e,onChange:t,disabled:a,decorative:!0}),n.jsx("span",{className:_("min-w-0 truncate typography-settings-field-label font-normal","text-foreground"),children:s})]}),o?n.jsx("p",{id:d,className:"-mt-1 pl-[20px] typography-meta text-muted-foreground text-pretty",children:o}):null]})},Ow=({"aria-label":e,children:t,className:s})=>n.jsx("div",{role:"radiogroup","aria-label":e,className:_(Mp,s),children:t});function Bw({value:e,options:t,onChange:s,className:r,"aria-label":o}){return n.jsx("div",{role:"group","aria-label":o,className:_("flex flex-wrap items-center gap-1",r),children:t.map(i=>n.jsx(Ae,{type:"button",variant:"chip",size:"xs",disabled:i.disabled,"aria-pressed":e===i.value,className:"!font-normal",onClick:()=>s(i.value),children:i.label},i.value))})}const ti="pichamber:server-update-channel-changed",_w=()=>{typeof window<"u"&&window.dispatchEvent(new Event(ti))},$p=e=>typeof window>"u"?()=>{}:(window.addEventListener(ti,e),()=>window.removeEventListener(ti,e));class Kp extends l.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,s){this.setState({error:t,errorInfo:s})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?n.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:n.jsxs(Mu,{className:"w-full max-w-md",children:[n.jsx(Fu,{className:"text-center",children:n.jsxs(Lu,{className:"flex items-center justify-center gap-2 text-destructive",children:[n.jsx(R,{name:"chat-3",className:"h-5 w-5"}),this.props.texts.title]})}),n.jsxs(Ou,{className:"space-y-4",children:[n.jsx("p",{className:"text-sm text-muted-foreground text-center",children:this.props.texts.description}),this.props.sessionId&&n.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:[this.props.texts.sessionLabel,": ",this.props.sessionId]}),this.state.error&&n.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[n.jsx("summary",{className:"cursor-pointer hover:bg-interactive-hover/80",children:this.props.texts.detailsSummary}),n.jsx("pre",{className:"mt-2 max-h-48 overflow-auto",children:this.state.error.toString()})]}),n.jsx("div",{className:"flex gap-2",children:n.jsxs(Ae,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[n.jsx(R,{name:"restart",className:"h-4 w-4 mr-2"}),this.props.texts.resetAction]})}),n.jsx("div",{className:"text-xs text-muted-foreground text-center",children:this.props.texts.persistentHint})]})]})}):this.props.children}}function Wp(e){return n.jsx(Kp,{...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 zw=({active:e=!0})=>{const t=Me(s=>s.currentSessionId);return n.jsx(Wp,{sessionId:t||void 0,children:n.jsx(Bu,{active:e},t??"no-session")})};function Gp({onResizeStart:e,ariaLabel:t}){return n.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:n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":!0,children:n.jsx("path",{d:"M9.11111 2L2 9.11111M10 6.44444L6.44444 10",className:"stroke-muted-foreground",strokeLinecap:"round"})})})}const cc=Te.forwardRef(({className:e,outerClassName:t,scrollbarClassName:s,fillContainer:r=!1,useScrollShadow:o=!1,scrollShadowSize:i,hasError:a,resizedHeight:c,onResizeHeightChange:d,disabled:u,simple:f,endSlot:m,...b},g)=>{const p=Te.useRef(null),h=Te.useRef(null),[y,x]=Te.useState(null),k=c??y,v=Te.useCallback(w=>{const j=p.current;if(!j)return;h.current={startY:w.clientY,startHeight:j.getBoundingClientRect().height};const S=w.currentTarget;S.setPointerCapture(w.pointerId);const C=P=>{const z=h.current;if(!z)return;const K=z.startHeight+(P.clientY-z.startY),q=Math.max(82,K);d?d(q):x(q)},E=()=>{h.current=null,S.removeEventListener("pointermove",C),S.removeEventListener("pointerup",E),S.removeEventListener("pointercancel",E)};S.addEventListener("pointermove",C),S.addEventListener("pointerup",E),S.addEventListener("pointercancel",E),w.preventDefault()},[d]),A=Te.useCallback(w=>{if(w.target.closest('textarea, button, [role="separator"]'))return;const S=p.current?.querySelector("textarea");S&&document.activeElement!==S&&(w.preventDefault(),S.focus())},[]);return f?n.jsx(Ln,{as:"textarea",ref:g,disableHorizontal:!0,fillContainer:r,useScrollShadow:o,scrollShadowSize:i,outerClassName:t,scrollbarClassName:s,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,...b}):n.jsx("div",{ref:p,onPointerDown:A,style:k!==null?{height:`${k}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",!a&&["hover:[&:not(:focus-within)]:ring-transparent","focus-within:ring-2 focus-within:ring-[var(--interactive-focus-ring)]"],a&&["ring-[var(--status-error)]","focus-within:ring-2 focus-within:ring-[var(--status-error)]"],t),children:n.jsxs("div",{className:"flex h-full min-h-0 flex-1 flex-col gap-2",children:[n.jsx("textarea",{ref:g,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-subtle-foreground placeholder:text-subtle-foreground",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...b}),n.jsxs("div",{className:"flex items-center justify-end gap-1.5 pl-3 pr-2.5",children:[m,n.jsx(Gp,{onResizeStart:v,ariaLabel:"Resize textarea"})]})]})})});cc.displayName="Textarea";const Hp=5e3,mr=e=>e?.trim()??"",qp=e=>e instanceof Error&&e.message?e.message:"Could not reach the server.";let wn=0,mo=0;const Ms=new Map,es=new Map,ma=e=>{if(e.deferred===void 0)return e;const t={...e};return delete t.deferred,t},Vp=(e,t)=>e.project.available===!!t,ga=(e,t,s)=>{if(!e?.config)return e;let r=!1;const o=e.config.extensions.map(i=>{if(i.id!==t)return i;const a=s(i);return a!==i&&(r=!0),a});return r?{...e,config:{...e.config,extensions:o}}:e},Yp=Nn()((e,t)=>{const s=(c,d)=>c===wn&&rt()===d,r=(c,d,u)=>{const f=Vp(u,c)&&es.get(c)===d;e(m=>{const b={};for(const[g,p]of Object.entries(m.entries))b[g]=g===c?p:{...p,loadedAt:0};return f&&(b[c]={config:ma(u),status:"ready",error:null,loadedAt:Date.now()}),{entries:b}}),!f&&es.get(c)===d&&o(c)},o=async c=>{const d=Ms.get(c);d&&await d,await t().load(c||null,{force:!0})},i=c=>{e(d=>{if(!d.pending[c])return d;const u={...d.pending};return delete u[c],{pending:u}})},a=async(c,d,u,f)=>{if(t().pending[c])return{ok:!1,error:new Error("A change to this extension is still saving.")};const m=rt(),b=wn,g=++mo;es.set(d,g);let p;e(h=>{const y=ga(h.entries[d],c,x=>(p=x,u(x)));return{pending:{...h.pending,[c]:!0},entries:y?{...h.entries,[d]:y}:h.entries}});try{const h=await f(m);return s(b,m)?(r(d,g,h),i(c),{ok:!0,deferred:h.deferred===!0}):{ok:!0,deferred:h.deferred===!0}}catch(h){return s(b,m)?(e(y=>{const x=p,k=x?ga(y.entries[d],c,()=>x):y.entries[d];return k?{entries:{...y.entries,[d]:k}}:y}),i(c),o(d),{ok:!1,error:h}):{ok:!1,error:h}}};return{entries:{},pending:{},load:async(c,d)=>{const u=mr(c),f=t().entries[u];if(!d?.force&&f?.status==="ready"&&Date.now()-f.loadedAt<Hp)return;const m=Ms.get(u);if(m)return m;const b=rt(),g=wn,p=mo;e(y=>({entries:{...y.entries,[u]:{config:y.entries[u]?.config??null,status:"loading",error:null,loadedAt:y.entries[u]?.loadedAt??0}}}));const h=(async()=>{try{const y=await Ps.getExtensionConfig(u||void 0,{runtimeKey:b});if(g!==wn||rt()!==b)return;e(x=>{const k=x.entries[u],v=(es.get(u)??0)>p&&!!k?.config;return{entries:{...x.entries,[u]:v&&k?{...k,status:"ready",error:null}:{config:ma(y),status:"ready",error:null,loadedAt:Date.now()}}}})}catch(y){if(g!==wn||rt()!==b)return;e(x=>({entries:{...x.entries,[u]:{config:x.entries[u]?.config??null,status:"error",error:qp(y),loadedAt:x.entries[u]?.loadedAt??0}}}))}finally{g===wn&&Ms.delete(u)}})();return Ms.set(u,h),h},setGlobal:(c,d)=>a(c,"",u=>u.global===d?u:{...u,global:d},u=>Ps.setExtensionConfig(c,{scope:"global",enabled:d},{runtimeKey:u})),setProjectEnabled:(c,d,u)=>{const f=mr(u);return f?a(c,f,m=>{if(!m.project||m.project.enabled===d)return m;const b=d===m.project.inherited?"inherit":d?"load":"unload";return{...m,project:{...m.project,state:b,enabled:d}}},m=>Ps.setExtensionConfig(c,{scope:"project",enabled:d,directory:f},{runtimeKey:m})):Promise.resolve({ok:!1,error:new Error("A project setting needs a project.")})},setProjectState:(c,d,u)=>{const f=mr(u);return f?a(c,f,m=>{if(!m.project||m.project.state===d)return m;const b=d==="inherit"?m.project.inherited:d==="load";return{...m,project:{...m.project,state:d,enabled:b}}},m=>Ps.setExtensionConfig(c,{scope:"project",state:d,directory:f},{runtimeKey:m})):Promise.resolve({ok:!1,error:new Error("A project setting needs a project.")})},removePackage:async(c,d)=>{if(t().pending[c])return{ok:!1,error:new Error("This package is already being removed.")};const u=mr(d),f=rt(),m=wn,b=++mo;es.set(u,b),e(g=>({pending:{...g.pending,[c]:!0}}));try{const g=await Ps.removeExtensionPackage(c,u||void 0,{runtimeKey:f});return s(m,f)?(r(u,b,g),i(c),{ok:!0,deferred:g.deferred===!0}):{ok:!0,deferred:g.deferred===!0}}catch(g){return s(m,f)?(i(c),o(u),{ok:!1,error:g}):{ok:!1,error:g}}},invalidate:()=>{e(c=>{const d={};for(const[u,f]of Object.entries(c.entries))d[u]={...f,loadedAt:0};return{entries:d}})},resetForRuntimeSwitch:()=>{wn+=1,Ms.clear(),es.clear(),e({entries:{},pending:{}})}}}),dc=[{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"}],Vs=Object.fromEntries(dc.map(e=>[e.key,e.Icon])),ni="pichamber:project-actions-updated",uc=e=>{const t=(e||"").trim().replace(/\\/g,"/");return t?t==="/"?"/":t.length>1?t.replace(/\/+$/,""):t:""},cn=(e,t)=>`${uc(e)}::${t}`,fc=({title:e,description:t,info:s,settingsItem:r,titleAccessory:o,headerAction:i,children:a,className:c,contentClassName:d,divider:u=!0})=>n.jsx(Bp,{title:e,description:t,info:s,settingsItem:r,titleAccessory:o,headerAction:i,divider:u,className:c,contentClassName:d,children:a}),si=e=>e.name.trim().length>0&&e.command.trim().length>0,Qp=e=>e.name.trim().length===0&&e.command.trim().length===0,Jp=e=>!si(e)&&!Qp(e),Xp=(e,t)=>e.some(r=>t.has(r.id)&&!si(r))?{canPersist:!1,actions:e}:{canPersist:!0,actions:e.filter(si)},Zp=450,em=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,tm=()=>({id:em(),name:"",command:"",icon:"play"}),nm=({projectRef:e})=>{const[t,s]=l.useState([]),[r,o]=l.useState(!1),[i,a]=l.useState(null),[c,d]=l.useState(new Set),u=l.useRef(!1);l.useEffect(()=>{let x=!1;return o(!0),(async()=>{try{const k=await _o(e);if(x)return;s(k.actions),a(JSON.stringify({actions:k.actions})),d(new Set(k.actions.map(v=>v.id)))}catch{if(x)return;s([]),a(JSON.stringify({actions:[]})),d(new Set)}finally{x||o(!1)}})(),()=>{x=!0}},[e]);const f=l.useMemo(()=>Xp(t,c),[t,c]),m=l.useMemo(()=>JSON.stringify({actions:f.actions}),[f.actions]),b=i!==null&&f.canPersist&&m!==i,g=l.useCallback(async x=>await _u(e,{actions:x,primaryActionId:null})?(a(JSON.stringify({actions:x})),d(new Set(x.map(v=>v.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent(ni,{detail:{projectId:e.id}})),!0):(oe.error("Failed to save actions"),!1),[e]);l.useEffect(()=>{if(!b||r||u.current)return;const x=window.setTimeout(()=>{u.current||(u.current=!0,(async()=>{try{await g(f.actions)}finally{u.current=!1}})())},Zp);return()=>{window.clearTimeout(x)}},[b,r,g,f.actions]);const p=l.useCallback(()=>{const x=tm();s(k=>[...k,x])},[]),h=l.useCallback(x=>{s(k=>k.filter(v=>v.id!==x))},[]),y=l.useCallback((x,k)=>{s(v=>v.map(A=>A.id===x?k(A):A))},[]);return n.jsx(fc,{title:"Actions",info:"Per-project commands shown in the header next to the project name.",settingsItem:"projects.actions",headerAction:n.jsxs(Ae,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:p,children:[n.jsx(R,{name:"add",className:"h-3.5 w-3.5"}),"Add action"]}),contentClassName:"space-y-4",children:r?n.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):t.length===0?n.jsx("p",{className:"typography-meta text-muted-foreground",children:"No actions configured yet."}):n.jsx("div",{className:_("space-y-6",Tp),children:t.map((x,k)=>{const v=x.icon||"play",A=Vs[v]||"play",w=x.name.trim()||`Action ${k+1}`,j=Jp(x);return n.jsxs("div",{className:ac,children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("h3",{className:lc,children:w}),n.jsx(Ae,{type:"button",variant:"ghost",size:"xs",className:"h-8 w-8 px-0 text-muted-foreground hover:text-[var(--status-error)]",onClick:()=>h(x.id),"aria-label":`Delete ${w}`,children:n.jsx(R,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),n.jsxs(qs,{label:"Name",controlClassName:"w-full max-w-none",children:[n.jsxs(Ht,{children:[n.jsx(qt,{asChild:!0,children:n.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:n.jsx(R,{name:A,className:"h-4 w-4"})})}),n.jsx(Vt,{align:"start",className:"w-56 p-2",children:n.jsx("div",{className:"grid grid-cols-6 gap-1",children:dc.map(S=>{const C=S.Icon,E=(x.icon||"play")===S.key;return n.jsx("button",{type:"button",onClick:()=>y(x.id,P=>({...P,icon:S.key})),className:_("inline-flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-foreground hover:bg-[var(--interactive-hover)]",E&&"border-[var(--primary-base)] bg-[var(--primary-base)]/10 text-[var(--primary-base)]"),"aria-label":`Icon ${S.label}`,children:n.jsx(R,{name:C,className:"h-4 w-4"})},S.key)})})})]}),n.jsx(zo,{value:x.name,onChange:S=>y(x.id,C=>({...C,name:S.target.value})),placeholder:"Action name",className:"h-8 min-w-0 flex-1 rounded-md px-3"})]}),n.jsx(qs,{label:"Command",controlClassName:"w-full max-w-none",children:n.jsx(cc,{value:x.command,onChange:S=>y(x.id,C=>({...C,command:S.target.value})),placeholder:"e.g. bun run lint",className:"min-h-[88px] w-full font-mono text-xs"})}),j?n.jsx("p",{className:"typography-meta text-muted-foreground",children:"Enter a name and command to save this action."}):null,n.jsx(Up,{checked:x.autoOpenUrl===!0,onChange:S=>y(x.id,C=>({...C,...S?{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 ${w}`}),x.autoOpenUrl===!0?n.jsx(n.Fragment,{children:n.jsx(qs,{label:"Custom URL",info:"Leave empty to use the best URL from command output.",controlClassName:"w-full max-w-none",children:n.jsx(zo,{value:x.openUrl||"",onChange:S=>y(x.id,C=>({...C,openUrl:S.target.value})),placeholder:"https://localhost:3000",className:"h-8 w-full rounded-md px-3"})})}):null]},x.id)})})})},sm={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)"},rm=({value:e,noneLabel:t,ariaLabel:s,disabled:r=!1,className:o,isModelAllowed:i,onChange:a})=>{const c=Kt(C=>C.providers),d=Kt(C=>C.modelsMetadata),u=ue(C=>C.hiddenModels),f=ue(C=>C.isFavoriteModel),m=ue(C=>C.toggleFavoriteModel),b=ue(C=>C.reorderFavoriteModel),{favoriteModelsList:g,recentModelsList:p}=zu(),[h,y]=l.useState(!1),[x,k]=l.useState("");l.useEffect(()=>{h?Kt.getState().ensureModelMetadata():k("")},[h]);const v=e?c.find(C=>C.id===e.providerId):void 0,A=e&&v?(Array.isArray(v.models)?v.models:[]).find(C=>C.id===e.modelId):void 0,w=e?Uu(A,e.modelId):t,j=l.useMemo(()=>e?u.filter(C=>!(C.providerID===e.providerId&&C.modelID===e.modelId)):u,[u,e]),S=l.useCallback(C=>{a({providerId:C.providerID,modelId:C.modelID}),y(!1)},[a]);return n.jsxs(Ht,{modal:!1,open:h,onOpenChange:C=>{r||y(C)},children:[n.jsx(qt,{asChild:!0,disabled:r,children:n.jsxs("button",{type:"button","aria-label":s,disabled:r,className:_(Ku({size:"default"}),Pp,"min-w-0",o),children:[n.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e?.providerId?n.jsx($u,{providerId:e.providerId,className:"size-4 shrink-0"}):null,n.jsx("span",{className:_("truncate",e?"text-foreground":"text-muted-foreground"),children:w})]}),n.jsx(R,{name:"arrow-down-s",className:"size-4 shrink-0"})]})}),n.jsx(Vt,{align:"start",portalToBody:!0,positionerClassName:"z-[80]",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",children:n.jsx(Wu,{providers:c,favoriteModels:g,recentModels:p,modelsMetadata:d,searchQuery:x,onSearchQueryChange:k,onSelect:S,labels:{...sm,notSelected:t},selectedModel:e?{providerID:e.providerId,modelID:e.modelId}:null,hiddenModels:j,isModelAllowed:i,includeNotSelected:!0,onSelectNone:()=>{a(null),y(!1)},disabled:r,autoFocus:!0,onEscape:()=>y(!1),isFavorite:C=>f(C.providerID,C.modelID),onToggleFavorite:C=>m(C.providerID,C.modelID),onReorderFavorite:(C,E)=>b(C.providerID,C.modelID,E.providerID,E.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite"})})]})},go="w-full max-w-none",om=({form:e})=>{const{name:t,setName:s,parsedDefaultModel:r,handleDefaultModelChange:o,project:i}=e,a=Kt(c=>c.loadProviders);return l.useEffect(()=>{a({source:"projectSettings"})},[a]),i?n.jsx(fc,{title:"Project",divider:!1,children:n.jsxs("div",{className:ac,children:[n.jsx(qs,{label:"Name",settingsItem:"projects.name",controlClassName:go,children:n.jsx(zo,{value:t,onChange:c=>s(c.target.value),placeholder:"Project name","aria-label":"Project name",className:"h-8 w-full rounded-md px-3"})}),n.jsx(qs,{label:"Default model",info:"Used when starting a new chat in this project. Unset keeps the global session default.",settingsItem:"projects.default-model",controlClassName:go,children:n.jsx(rm,{value:r,noneLabel:"Use global default",ariaLabel:"Default model for new chats",className:go,onChange:c=>{if(!c){o("","");return}o(c.providerId,c.modelId)}})})]})}):null},im=e=>{const[t,s]=l.useState(""),[r,o]=l.useState(void 0);l.useEffect(()=>{if(!e){s(""),o(void 0);return}s(e.label??""),o(e.defaultModel)},[e]);const i=l.useMemo(()=>Gu(r),[r]),a=!!e&&(t.trim()!==(e?.label??"").trim()||(r??void 0)!==(e?.defaultModel??void 0)),c=l.useCallback((u,f)=>{o(u&&f?`${u}/${f}`:void 0)},[]),d=l.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:s,defaultModel:r,parsedDefaultModel:i,handleDefaultModelChange:c,hasChanges:a,prepareSaveData:d,project:e}},am=450,lm=(e,t)=>{const{hasChanges:s,name:r,defaultModel:o,prepareSaveData:i}=e,a=l.useRef(!1);l.useEffect(()=>{if(!s||!r.trim()||a.current)return;const c=window.setTimeout(()=>{a.current||(a.current=!0,(async()=>{try{const d=await i();if(d)try{await t(d)}catch{oe.error("Failed to save project settings")}}finally{a.current=!1}})())},am);return()=>{window.clearTimeout(c)}},[o,s,r,t,i])},cm=({project:e,onIdentitySave:t})=>{const s=im(e),r=l.useMemo(()=>e?{id:e.id,path:e.path}:null,[e]),o=l.useCallback(async i=>{await t(i)},[t]);return lm(s,o),!e||!r?null:n.jsxs("div",{className:"space-y-0",children:[n.jsx(om,{form:s}),n.jsx(nm,{projectRef:r})]})},dm=6e4,um=3e4,Fs=new Map;let ba=0,xa=!1;const fm=()=>{if(xa||typeof window>"u")return;xa=!0;const e=()=>{const t=Date.now();t-ba<um||typeof document<"u"&&document.hidden||(ba=t,pt(async()=>{const{getRegisteredRuntimeAPIs:s}=await import("./index-B2v0_mez.js").then(r=>r.cJ);return{getRegisteredRuntimeAPIs:s}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:s})=>{const r=s()?.github;r&&Hr.getState().refresh(r)}).catch(()=>{}))};window.addEventListener("focus",e),typeof document<"u"&&document.addEventListener("visibilitychange",()=>{document.hidden||e()})},Hr=Nn()(Gr((e,t)=>({status:null,fetchedAt:null,isLoading:!1,error:null,runtimeKey:rt(),resetForRuntimeSwitch:s=>{const r=s??rt();Fs.clear(),e({status:null,fetchedAt:null,isLoading:!1,error:null,runtimeKey:r})},refresh:async(s,r)=>{fm();const o=rt();t().runtimeKey!==o&&t().resetForRuntimeSwitch(o);const i=t(),a=Date.now();if(!r?.force&&i.status&&i.fetchedAt&&a-i.fetchedAt<dm)return i.status;const c=Fs.get(o);if(c)return c;const d=s??null;if(!d)return t().status;const u=(async()=>{e({isLoading:!0});try{const f=await d.status();return rt()!==o?null:(e({status:f,fetchedAt:Date.now(),isLoading:!1,error:null,runtimeKey:o}),f)}catch(f){return rt()!==o?null:(e({isLoading:!1,error:f instanceof Error?f.message:"GitHub status check failed"}),t().status)}})();Fs.set(o,u);try{return await u}finally{Fs.get(o)===u&&Fs.delete(o)}}}),{name:"github-status-store"}));typeof window<"u"&&ws(e=>{Hr.getState().resetForRuntimeSwitch(e.runtimeKey)});const hm=()=>Hr(e=>(e.status?.hosts??[]).find(s=>s.authenticated)?.login??null),Uw=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 s=JSON.parse(new TextDecoder().decode(new Uint8Array(e,4,t)));return!Number.isFinite(s?.width)||!Number.isFinite(s?.height)?null:{header:s,jpeg:new Uint8Array(e,4+t)}}catch{return null}},$w=e=>{try{const t=JSON.parse(e);return t&&typeof t=="object"&&typeof t.type=="string"?t:null}catch{return null}},Kw=e=>e===4003?"unavailable":e===4004?"stop":e===4005?"closed":"reconnect",Ww=50*1024*1024-1,Gw=[250,1e3,2e3,4e3,8e3],pm=(e,t)=>{const s=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-${s(2166136261)}${s(16777619)}`},Hw=e=>({alt:e.altKey,ctrl:e.ctrlKey,meta:e.metaKey,shift:e.shiftKey}),qw=(e,t,s,r)=>{if(s.width<=0||s.height<=0)return null;const o=(e-s.left)/s.width*r.width,i=(t-s.top)/s.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}},Vw=(e,t)=>e.key.toLowerCase()!=="v"||e.altKey?!1:t?e.metaKey:e.ctrlKey,Yw=(e,t)=>{const s=Math.min(1,t.width/e.width,t.height/e.height),r=Number.isFinite(s)&&s>0?s:1;return{width:Math.round(e.width*r),height:Math.round(e.height*r),scale:r}},Wn=async(e,t)=>{const s=await e.json().catch(()=>null);return new Error(typeof s?.error=="string"?s.error:t)},Qw=async()=>{const e=await tt("/api/server-browser/status");if(!e.ok)throw await Wn(e,"Could not check the server browser");return await e.json()},Jw=async e=>{const t=await tt("/api/server-browser/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw await Wn(t,"Could not save the server browser settings");return await t.json()},Xw=async(e,t)=>{const s=await tt("/api/server-browser/dev-servers",{query:e?{directory:e}:void 0,signal:t});if(!s.ok)throw await Wn(s,"Could not find dev servers");const r=await s.json();return Array.isArray(r.servers)?r.servers:[]},Zw=async(e,t,s)=>{const r=await tt("/api/server-browser/frame-policy",{query:{url:e,origin:t},signal:s});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"}},ev=async()=>{const e=await tt("/api/server-browser/clear-data",{method:"POST"});if(!e.ok)throw await Wn(e,"Could not clear browsing data")},tv=(e,t)=>{const s=pm(e,t);tt(`/api/server-browser/tabs/${encodeURIComponent(s)}`,{method:"DELETE"}).catch(()=>{})},nv=async e=>{const t=new URLSearchParams({name:e.name,type:e.type,lastModified:String(e.lastModified)}),s=await tt(`/api/server-browser/uploads?${t}`,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:e});if(!s.ok)throw await Wn(s,`Could not upload ${e.name}`);const r=await s.json();if(typeof r.id!="string")throw new Error(`Could not upload ${e.name}`);return r.id},sv=async(e,t,{onProgress:s,signal:r}={})=>{const o=await tt(`/api/server-browser/downloads/${encodeURIComponent(e)}`,{signal:r??new AbortController().signal});if(!o.ok)throw await Wn(o,`Could not download ${t}`);const i=Number(o.headers.get("content-length"))||0,a=o.headers.get("content-type")||"application/octet-stream";let c;if(o.body&&s){const d=o.body.getReader(),u=[];let f=0;for(s(0,i);;){const{done:m,value:b}=await d.read();if(m)break;u.push(b),f+=b.byteLength,s(f,i)}c=new Blob(u,{type:a})}else c=await o.blob();return c},rv=(e,t)=>ql({filename:t,mimeType:e.type||void 0,data:e}),ov=e=>e instanceof Error&&(e.name==="NotAllowedError"||e.message.includes("NotAllowedError")),iv=async e=>{const t=await tt(`/api/server-browser/downloads/${encodeURIComponent(e)}/save-to-server`,{method:"POST"});if(!t.ok)throw await Wn(t,"Could not save the download on the server");const s=await t.json();if(typeof s.path!="string")throw new Error("Could not save the download on the server");return s.path},av=async(e,t,s)=>{const r=await th();return{socket:nh(sh().websocket("/api/server-browser/ws",{tab:e,url:t,popup:s},r)),urlAuthToken:r}},lv=e=>{eh(e)},gr=100;function cv(){const e=ue(C=>C.isArchivePageOpen),t=ue(C=>C.setArchivePageOpen),s=ue(C=>C.setActiveMainTab),r=Me(C=>C.setCurrentSession),o=Me(C=>C.unarchiveSession),i=gs(C=>C.homeDirectory),a=Uo({archived:!0}),[c,d]=l.useState(""),[u,f]=l.useState(null),[m,b]=l.useState(gr),g=c.trim().toLowerCase(),p=l.useMemo(()=>e?[...a].sort((C,E)=>(E.time?.archived??0)-(C.time?.archived??0)):[],[a,e]),h=l.useMemo(()=>{const C=new Map;for(const E of p){const P=Re(cs(E))??"",z=C.get(P);if(z){z.sessions.push(E);continue}C.set(P,{directory:P,label:P?ra(P,i)||P:"other projects",sessions:[E]})}return[...C.values()].sort((E,P)=>P.sessions.length-E.sessions.length)},[i,p]),y=l.useMemo(()=>g?p.filter(C=>(C.title??"").toLowerCase().includes(g)):u===null?p:h.find(C=>C.directory===u)?.sessions??[],[h,g,u,p]),x=y.slice(0,m),k=y.length-x.length,v=a.length,A=l.useCallback(C=>{f(C),b(gr)},[]),w=l.useCallback(C=>{const E=Re(cs(C));r(C.id,E??void 0),s("chat"),t(!1)},[s,r,t]),j=l.useCallback(C=>{o(C.id).then(E=>{E?oe.success("Session restored"):oe.error("Failed to restore session")})},[o]);if(!e)return null;const S=(C,E,P,z,K,q,H)=>n.jsxs("div",{className:"group/dir relative",children:[n.jsxs("button",{type:"button",onClick:K,title:q,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",H?"group-hover/dir:pr-8 group-focus-within/dir:pr-8":"",z?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground"),children:[n.jsx("span",{className:"min-w-0 flex-1 truncate",children:E}),n.jsx("span",{className:"flex-shrink-0 typography-micro text-subtle-foreground",children:P})]}),H?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:()=>Js.requestDelete({sessions:H,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 ${E}`,children:n.jsx(R,{name:"delete-bin",className:"h-3.5 w-3.5"})})}),n.jsx(Ge,{side:"bottom",sideOffset:4,children:"Delete all archived sessions in this project"})]}):null]},C);return n.jsx(fu,{open:e,onOpenChange:t,children:n.jsxs(hu,{children:[n.jsx(pu,{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"}),n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 max-[640px]:p-2 pointer-events-none",children:n.jsxs(mu,{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:[n.jsx(gu,{className:"sr-only",children:"Archived sessions"}),n.jsx(bu,{className:"sr-only",children:"Browse and restore archived sessions."}),n.jsx(xu,{"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:n.jsx(R,{name:"close",className:"size-4"})}),n.jsxs("div",{className:"flex min-h-0 flex-1",children:[n.jsx("div",{className:"flex w-64 flex-shrink-0 flex-col border-r border-border/50 max-[640px]:w-40",children:n.jsxs("div",{className:"flex-1 space-y-0.5 overflow-y-auto p-2",children:[S("__all__","All directories",v,u===null,()=>A(null)),h.map(C=>S(C.directory||"__none__",C.label,C.sessions.length,u===C.directory,()=>A(C.directory),C.directory||void 0,C.sessions))]})}),n.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[n.jsxs("div",{className:"flex items-center gap-3 px-6 pr-12 pt-3",children:[n.jsxs("div",{className:"relative min-w-0 flex-1",children:[n.jsx(R,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),n.jsx("input",{value:c,onChange:C=>{d(C.target.value),b(gr)},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"})]}),n.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:y.length===1?`${y.length} archived session`:`${y.length} archived sessions`})]}),n.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-6 py-3",children:n.jsxs("div",{className:"mx-auto w-full max-w-3xl space-y-0.5",children:[x.length===0?n.jsx("div",{className:"py-10 text-center text-muted-foreground",children:n.jsx("p",{className:"typography-ui-label font-semibold",children:g?"No matching archived sessions":"No archived sessions"})}):x.map(C=>{const E=Re(cs(C))??"",P=E?ra(E,i)||E:null;return n.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:()=>w(C),role:"button",tabIndex:0,onKeyDown:z=>{(z.key==="Enter"||z.key===" ")&&(z.preventDefault(),w(C))},children:[n.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:un(C)}),g&&P?n.jsx("span",{className:"max-w-40 flex-shrink-0 truncate typography-micro text-subtle-foreground",title:E,children:P}):null,n.jsx("span",{className:"flex-shrink-0 typography-micro text-subtle-foreground",children:Ch(C.time?.archived??C.time?.updated??C.time?.created??Date.now())}),n.jsx("button",{type:"button",onClick:z=>{z.stopPropagation(),j(C)},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 ${un(C)}`,children:n.jsx(R,{name:"inbox-unarchive",className:"h-3.5 w-3.5"})}),n.jsx("button",{type:"button",onClick:z=>{z.stopPropagation(),Js.requestDelete({sessions:[C],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 ${un(C)}`,children:n.jsx(R,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},C.id)}),k>0?n.jsx("button",{type:"button",onClick:()=>b(C=>C+gr),className:"mt-1 flex items-center justify-start rounded-md px-2 py-1 text-left text-xs text-subtle-foreground leading-tight hover:text-foreground hover:underline",children:"Show more sessions"}):null]})})]})]})]})})]})})}const mm=e=>{if(!e||typeof e!="object")return{percent:0,hasInput:!1};const t=e.input??0,s=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+s+r;if(o<=0)return{percent:0,hasInput:!1};const i=Math.max(0,s);return{percent:Math.min(100,Math.max(0,i/o*100)),hasInput:!0}},gm=e=>{if(!e||typeof e!="object")return 0;const t=typeof e.input=="number"&&Number.isFinite(e.input)&&e.input>=0?e.input:0,s=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+s+r},Xt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:0,bm=e=>{if(!e||typeof e!="object")return null;const t=Xt(e.input),s=Xt(e.output),r=Xt(e.cacheRead),o=Xt(e.cacheWrite);return{input:t,output:s,reasoning:null,cacheRead:r,cacheWrite:o,total:t+s+r+o}},ya=e=>{const t=bm(e.info.usage);if(t)return t;const s=e.info.tokens,r=s!==void 0?s: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),a=Xt(o.output),c=Xt(o.reasoning),d=Xt(o.cache?.read),u=Xt(o.cache?.write);return{input:i,output:a,reasoning:c,cacheRead:d,cacheWrite:u,total:i+a+c+d+u}},hc=380,bo=8,xm=140;function ym({open:e,onClose:t,anchorRef:s,closeOnWheel:r=!1}){const o=l.useRef(null),i=l.useRef(null),[a,c]=l.useState(e),[d,u]=l.useState(!1),[f,m]=l.useState(null),{enabled:b}=ji();return l.useLayoutEffect(()=>{if(!e||!b||!a)return;const g=()=>{const y=s.current?.getBoundingClientRect(),x=i.current?.getBoundingClientRect();if(!y||!x){m(null);return}const k=y.left-x.left;m(Math.min(Math.max(k,bo),Math.max(bo,x.width-hc-bo)))};g();const p=i.current;if(typeof ResizeObserver>"u"||!p)return;const h=new ResizeObserver(g);return h.observe(p),()=>h.disconnect()},[s,b,e,a]),l.useEffect(()=>{if(e){c(!0),u(!1);return}if(!a)return;u(!0);const g=window.setTimeout(()=>{c(!1),u(!1)},xm);return()=>window.clearTimeout(g)},[e,a]),l.useEffect(()=>{if(!e)return;const g=p=>{p.key==="Escape"&&t()};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[t,e]),l.useEffect(()=>{if(!e)return;const g=p=>{const h=p.target;if(!(h instanceof Node)){t();return}o.current?.contains(h)||s.current?.contains(h)||t()};return document.addEventListener("pointerdown",g,!0),r&&document.addEventListener("wheel",g,!0),()=>{document.removeEventListener("pointerdown",g,!0),r&&document.removeEventListener("wheel",g,!0)}},[s,r,t,e]),{panelRef:o,wrapperRef:i,shouldRender:a,isExiting:d,anchorLeft:f,isPopover:b&&f!==null}}const wa=(e,t)=>{if(!e||typeof e!="object")return;const s=e[t];return typeof s=="number"&&Number.isFinite(s)?s:void 0},Fr=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e),br=({icon:e,iconNode:t,label:s,children:r})=>n.jsxs("div",{className:"flex min-w-0 items-center gap-3 rounded-xl px-2.5 py-2.5",children:[n.jsx("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:t??(e?n.jsx(R,{name:e,className:"size-[18px]"}):null)}),n.jsx("span",{className:"shrink-0 typography-ui-label text-muted-foreground",children:s}),n.jsx("span",{className:"min-w-0 flex-1 truncate text-right typography-ui-label font-medium text-foreground",children:r})]}),wm=({open:e,onClose:t,anchorRef:s,contextDisplay:r})=>{const{panelRef:o,wrapperRef:i,shouldRender:a,isExiting:c,anchorLeft:d,isPopover:u}=ym({open:e,onClose:t,anchorRef:s,closeOnWheel:!0});return a?n.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:[n.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(${hc}px, calc(100% - 16px))`}:null},children:n.jsx("div",{className:"space-y-1",children:r?n.jsxs(n.Fragment,{children:[n.jsx(br,{iconNode:n.jsx(Al,{percentage:r.percentage}),label:"Context",children:n.jsxs("span",{className:"inline-flex items-baseline gap-1.5 tabular-nums",children:[n.jsxs("span",{className:_("font-semibold",r.colorClass),children:[r.percentage.toFixed(1),"%"]}),n.jsx("span",{className:"text-muted-foreground",children:r.tokens})]})}),r.cacheRead!==null&&r.cacheWrite!==null?n.jsxs(n.Fragment,{children:[n.jsx(br,{icon:"stack",label:"Cache read",children:n.jsx("span",{className:"tabular-nums",children:Fr(r.cacheRead)})}),n.jsx(br,{icon:"edit",label:"Cache write",children:n.jsx("span",{className:"tabular-nums",children:Fr(r.cacheWrite)})})]}):null,r.cacheHitPercent!==null?n.jsx(br,{icon:"check",label:"Cache hit",children:n.jsxs("span",{className:"tabular-nums",children:[r.cacheHitPercent.toFixed(1),"%"]})}):null]}):n.jsx("div",{className:"px-2.5 py-2 typography-meta text-muted-foreground",children:"Context usage is not available for this conversation yet."})})}),n.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},vm=l.memo(function({open:t,onOpenChange:s,currentSessionId:r,effectiveDirectory:o,isNewSessionDraftOpen:i}){const a=l.useRef(null),c=Hu(r??""),d=Kt(D=>D.providers),u=Kt(D=>D.currentProviderId),f=Kt(D=>D.currentModelId),m=Kt(D=>D.getCurrentModel()),b=Kt(D=>D.getModelMetadata);Kt(D=>D.modelsMetadata.size);const g=qu(l.useCallback(D=>r?D.sessionModelSelections.get(r)??null:null,[r])),p=l.useMemo(()=>{for(let D=c.length-1;D>=0;D-=1){const T=c[D]?.info;if(T.role!=="user")continue;const I=T.model,M=I?.providerID??I?.providerId,G=I?.modelID??I?.modelId,W=typeof M=="string"&&M.trim().length>0?M:void 0,L=typeof G=="string"&&G.trim().length>0?G:void 0;if(W&&L)return{providerID:W,modelID:L}}return null},[c]),h=l.useMemo(()=>{for(let D=c.length-1;D>=0;D-=1){const T=c[D];if(T?.info.role==="assistant"&&ya(T).total>0)return T}return null},[c]),y=p??(()=>{const D=h?.info.model,T=D?.providerID??D?.providerId,I=D?.modelID??D?.modelId;return T&&I?{providerID:T,modelID:I}:null})()??(g?{providerID:g.providerId,modelID:g.modelId}:null)??(u&&f?{providerID:u,modelID:f}:null),k=(y?d.find(D=>D.id===y.providerID):void 0)?.models.find(D=>D.id===y?.modelID),v=y?b(y.providerID,y.modelID):void 0,A=wa(k?.limit,"context")??v?.limit?.context??wa(m?.limit,"context")??0,w=h?ya(h):null,j=h?.info?.usage,S=j?gm(j):w?.total??0,C=!i&&S>0&&A>0?Math.min(S/A*100,999):null,E=C!==null?`${Fr(S)}/${Fr(A)}`:null,P=C===null?"":C>=90?"text-[var(--status-error)]":C>=75?"text-[var(--status-warning)]":"text-[var(--status-success)]",z=w?.cacheRead??null,K=w?.cacheWrite??null,q=w?mm({input:w.input,cache:{read:w.cacheRead,write:w.cacheWrite}}):{percent:0,hasInput:!1},H=q.hasInput?q.percent:null,F=C!==null&&E?{percentage:C,tokens:E,colorClass:P,cacheRead:z,cacheWrite:K,cacheHitPercent:H}:null;return n.jsxs(n.Fragment,{children:[n.jsx("button",{ref:a,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:()=>s(D=>!D),style:{touchAction:"manipulation"},children:F?n.jsx(Al,{percentage:F.percentage,size:20,className:"size-5 -rotate-90"}):n.jsx(R,{name:"pie-chart",className:"size-5"})}),n.jsx(wm,{open:t,onClose:()=>s(!1),anchorRef:a,contextDisplay:F})]})}),Ss="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",Sm="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",jm=l.memo(function({visible:t=!0,title:s,ariaLabel:r,onClick:o,className:i,Icon:a,iconClassName:c,pressed:d=!1}){return t?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:o,"aria-label":r,"aria-pressed":d,className:_(i??Ss,d&&"bg-interactive-selection text-interactive-selection-foreground"),children:n.jsx(R,{name:a,className:c??"h-[18px] w-[18px]"})})}),n.jsx(Ge,{children:n.jsx("p",{children:s})})]}):null}),Cm=e=>{let t=2166136261;for(let s=0;s<e.length;s+=1)t^=e.charCodeAt(s),t=Math.imul(t,16777619);return(t>>>0).toString(36).padStart(7,"0").slice(-6)},pc=({variant:e="desktop"})=>{const t=zn(f=>f.entries),[s,r]=l.useState(!1),o=l.useRef(null),i=l.useMemo(()=>[...t.values()].sort((f,m)=>m.startedAt-f.startedAt),[t]),a=i.filter(f=>f.state&&f.state.phase!=="failed"||Nl(f)).length,c=l.useCallback(()=>{o.current&&(clearTimeout(o.current),o.current=null)},[]),d=l.useCallback(()=>{c(),o.current=setTimeout(()=>r(!1),150)},[c]);if(l.useEffect(()=>()=>c(),[c]),i.length===0)return null;const u=f=>{if(!Ju(f))return;const m=f.receipt;if(!m)return;const b=Me.getState();b.newSessionDraft.open?b.setNewSessionDraftTarget({directoryOverride:m.path,worktreeIntent:null}):b.openNewSessionDraft({directoryOverride:m.path}),zn.getState().clearEntry(f.key),ue.getState().setActiveMainTab("chat"),r(!1)};return n.jsxs(Ht,{open:s,onOpenChange:r,children:[n.jsx(qt,{asChild:!0,children:n.jsxs("button",{type:"button",className:_(e==="desktop"?Ss:"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:[a>0?n.jsx(Cn,{variant:"inline",text:null,animationType:"spinner"}):n.jsx(R,{name:"task",className:"size-[18px]"}),n.jsx("span",{children:"Background tasks"})]})}),n.jsxs(Vt,{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:[n.jsxs("div",{className:"border-b border-border px-3 py-2.5",children:[n.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:"Background tasks"}),n.jsx("p",{className:"typography-micro text-muted-foreground",children:a===1?"1 worktree is being created":`${a} worktrees are being created`})]}),n.jsx("div",{className:"divide-y divide-border",children:i.map(f=>n.jsx(km,{entry:f,onOpen:()=>u(f)},f.key))})]})]})},km=({entry:e,onOpen:t})=>{const s=e.state?.phase==="failed",r=!!(e.state&&!s),o=Nl(e),i=Vu(e),a=s?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 n.jsxs("div",{className:"flex items-start gap-3 px-3 py-3",children:[n.jsx("div",{className:"mt-0.5 shrink-0",children:r||o?n.jsx(Cn,{variant:"inline",text:null,animationType:"spinner"}):s?n.jsx(R,{name:"alert",className:"size-4 text-[var(--status-error)]"}):n.jsx(R,{name:"git-branch",className:"size-4 text-[var(--status-success)]"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"truncate typography-ui-label text-foreground",children:a}),n.jsx("p",{className:"mt-0.5 truncate typography-micro text-muted-foreground",children:s?e.state?.error:e.path??e.intent.sourceDirectory})]}),s?n.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[e.failedSend?n.jsx(Ae,{type:"button",size:"xs","aria-label":`Restore draft for ${e.intent.sourceDirectory} from ${e.intent.startRef} (task ${Cm(e.key)})`,onClick:()=>{const c=Yu(e.key),d=Qu(c,"background-task");d&&oe.error(d.title,{description:d.description})},children:"Restore draft"}):null,n.jsx(Ae,{type:"button",variant:"ghost",size:"xs",onClick:()=>zn.getState().dismissFailed(e.key),children:"Dismiss"})]}):null,i?n.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[n.jsx(Ae,{type:"button",size:"xs",onClick:t,children:"Open"}),n.jsx(Ae,{type:"button",variant:"ghost",size:"icon",className:"size-6",onClick:()=>zn.getState().clearEntry(e.key),"aria-label":"Dismiss completed task",children:n.jsx(R,{name:"close",className:"size-3.5"})})]}):null]})},Am=["pinned","today","yesterday","thisWeek","lastWeek","older"],Nm={pinned:"Pinned",today:"Today",yesterday:"Yesterday",thisWeek:"This week",lastWeek:"Last week",older:"Older"},Im=(e,t)=>{if(e==="sunday")return 0;if(e==="monday")return 1;try{const s=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(s),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},ri=(e,t)=>{const s=new Date(e);s.setHours(0,0,0,0);const r=s.getTime(),o=new Date(r);o.setDate(o.getDate()-1),o.setHours(0,0,0,0);const i=o.getTime(),c=(s.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 m=f.getTime();return{startOfToday:r,startOfYesterday:i,startOfThisWeek:u,startOfLastWeek:m}},Em=(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",Dm=(e,t)=>{const s={pinned:[],today:[],yesterday:[],thisWeek:[],lastWeek:[],older:[]},{getTimestamp:r,isPinned:o,boundaries:i}=t,a=e.length;for(let d=0;d<a;d++){const u=e[d];if(o(u))s.pinned.push(u);else{const f=r(u),m=Em(f,i);s[m].push(u)}}const c=[];for(const d of Am){const u=s[d];u.length>0&&c.push({id:d,items:u})}return c},Rm=e=>{const t=new Date(e);return t.setDate(t.getDate()+1),t.setHours(0,0,0,0),t.getTime()},Pm=(e,t)=>{const[s,r]=l.useState(0),o=l.useMemo(()=>e?ri(Date.now(),t):null,[e,t,s]),i=o?.startOfToday??null;return l.useEffect(()=>{if(i===null||typeof window>"u"||typeof document>"u")return;const a=Date.now(),c=window.setTimeout(()=>{r(u=>u+1)},Math.max(50,Rm(a)-a+50)),d=()=>{document.visibilityState==="visible"&&ri(Date.now(),t).startOfToday!==i&&r(u=>u+1)};return document.addEventListener("visibilitychange",d),()=>{window.clearTimeout(c),document.removeEventListener("visibilitychange",d)}},[i,t,s]),o},Tm=e=>({getOrderedGroups:l.useCallback((s,r)=>{const o=e.get(s);if(!o||o.length===0)return r;const i=new Map(r.map(d=>[d.id,d])),a=[];o.forEach(d=>{const u=i.get(d);u&&(a.push(u),i.delete(d))});const c=[];return r.forEach(d=>{i.has(d.id)&&c.push(d)}),[...c,...a]},[e])}),Mm=[],Fm=e=>{const{normalizedProjects:t,getSessionsForProject:s,getArchivedSessionsForProject:r,availableWorktreesByProject:o,projectRepoStatus:i,projectRootBranches:a,lastRepoStatus:c,buildGroupedSessions:d,hasSessionSearchQuery:u,normalizedSessionSearchQuery:f,filterSessionNodesForSearch:m,buildGroupSearchText:b,foldersMap:g,alwaysIncludeArchived:p=!1}=e,h=l.useRef(new Map),y=u||p,x=l.useMemo(()=>{const E=h.current,P=new Map;let z=0,K=0;const q=(F,D)=>F.length===D.length&&F.every((T,I)=>T===D[I]),H=t.map(F=>{const D=s(F.id),T=y?r(F.id):Mm,I=i.has(F.id)?!!i.get(F.id):c,M=a.get(F.id)??null,G=o.get(F.normalizedPath)??[],W=E.get(F.id);if(W&&W.project===F&&q(W.activeSessions,D)&&q(W.archivedSessions,T)&&W.rootBranch===M&&W.isRepo===I&&W.worktrees===G&&W.buildGroupedSessions===d)return z+=1,P.set(F.id,W),W.section;K+=1;const L=Vl([...D,...T]),ae=d(L,F.normalizedPath,G,M,I),J={project:F,groups:ae};return P.set(F.id,{project:F,activeSessions:D,archivedSessions:T,rootBranch:M,isRepo:I,worktrees:G,buildGroupedSessions:d,section:J}),J});return h.current=P,z>0&&Wt("ui.sidebar.project_section.reused",z),K>0&&Wt("ui.sidebar.project_section.rebuilt",K),H},[t,s,r,y,o,i,c,d,a]),k=l.useMemo(()=>x,[x]),v=l.useMemo(()=>{const E=new WeakMap;if(!u)return E;const P=z=>z.reduce((K,q)=>K+1+P(q.children),0);return k.forEach(z=>{z.groups.forEach(K=>{const q=m(K.sessions,f),H=P(q),F=b(K).includes(f),D=Re(K.directory??null),I=(D?g[D]??[]:[]).filter(M=>M.name.toLowerCase().includes(f)).length;E.set(K,{filteredNodes:q,matchedSessionCount:H,folderNameMatchCount:I,groupMatches:F,hasMatch:F||H>0||I>0})})}),E},[u,k,m,f,b,g]),A=l.useMemo(()=>u?k.map(E=>({...E,groups:E.groups.filter(P=>v.get(P)?.hasMatch===!0)})).filter(E=>E.groups.length>0):k,[u,k,v]),w=u?A:k,j=l.useRef(new WeakMap),S=l.useMemo(()=>{const E=j.current;return w.map(P=>{const z=E.get(P);if(z&&z.query===f)return z.section;const K=P.groups,q=K.flatMap(I=>u?v.get(I)?.filteredNodes??[]:I.sessions),H=K.map(I=>({scopeKey:I.folderScopeKey??Re(I.directory??null),directory:I.directory??null})).filter(I=>!!I.scopeKey),F=K.find(I=>I.isMain)??null,D={id:"flat",label:F?.label??"",branch:F?.branch??null,description:F?.description??null,isMain:!0,directory:F?.directory??P.project.normalizedPath,folderScopeKey:F?.folderScopeKey??P.project.normalizedPath,folderScopes:H,sessions:q};if(u){const I=K.map(M=>v.get(M)).filter(M=>!!M);v.set(D,{filteredNodes:q,matchedSessionCount:I.reduce((M,G)=>M+G.matchedSessionCount,0),folderNameMatchCount:I.reduce((M,G)=>M+G.folderNameMatchCount,0),groupMatches:I.some(M=>M.groupMatches),hasMatch:I.some(M=>M.hasMatch)})}const T={project:P.project,groups:[D]};return E.set(P,{query:f,section:T}),T})},[v,u,f,w]),C=l.useMemo(()=>u?w.reduce((E,P)=>E+P.groups.reduce((z,K)=>{const q=v.get(K);if(!q)return z;const H=q.folderNameMatchCount+(q.groupMatches?1:0);return z+q.matchedSessionCount+H},0),0):0,[u,w,v]);return{projectSections:x,visibleProjectSections:k,groupSearchDataByGroup:v,searchableProjectSections:A,sectionsForRender:w,flatSectionsForRender:S,searchMatchCount:C}},qr=e=>!!e.session.time?.archived,mc=e=>{let t=0;for(const s of e)qr(s)||(t+=1);return t},Lm=e=>{let t=0;for(const s of e)for(const r of s.groups)t+=mc(r.sessions);return t},Om=e=>{const t=new Map;for(const s of e){let r=0;for(const o of s.groups)r+=mc(o.sessions);t.set(s.project.id,r)}return t},Bm=(e,t)=>e.groups.some(s=>s.sessions.some(r=>!qr(r)&&t.has(r.session.id))),_m=(e,t)=>e.groups.some(s=>s.sessions.some(r=>!qr(r)&&t.has(r.session.id))),zm=(e,t)=>{const s=new Map;for(const r of e){const o=new Set;for(const i of r.groups)if(i.sessions.some(c=>!qr(c)&&t.has(c.session.id))&&i.directory){const c=Re(i.directory)?.toLowerCase();c&&o.add(c)}o.size>0&&s.set(r.project.id,o)}return s},gc=(e,t,s,r)=>{if(!s)return t;const o=e.find(c=>c.project.id===s);if(!o)return[];const i=Re(r??o.project.normalizedPath),a=o.groups.find(c=>Re(c.directory)===i);return a?[{...o,groups:[a]}]:[]},Um=(e,t)=>{const s=new Map,r=new Map;return e.forEach(o=>{const i=vs(o.project,t);o.groups.forEach(a=>{const c=a.branch&&a.branch!=="HEAD"&&a.branch!==i?a.branch:null,d={projectLabel:i,branchLabel:c},u=f=>{f.forEach(m=>{const b=o.project.normalizedPath.length,g=r.get(m.session.id)??-1;b<g||(s.set(m.session.id,{node:m,projectId:o.project.id,groupDirectory:a.directory,secondaryMeta:d}),r.set(m.session.id,b),m.children.length>0&&u(m.children))})};u(a.sessions)})}),s};function $m({projectSections:e,flatSectionsForRender:t,sectionsForRender:s,selectedSpaceId:r,selectedWorktreePath:o,homeDirectory:i,activeSessionIdSet:a,unreadSessionIdSet:c}){const d=l.useMemo(()=>Um(e,i),[e,i]),u=t,f=l.useMemo(()=>gc(s,u,r,o),[s,u,r,o]),m=l.useMemo(()=>Lm(e),[e]),b=l.useMemo(()=>Om(e),[e]),g=l.useCallback(y=>{const x=e.find(k=>k.project.id===y);return x?Bm(x,a):!1},[a,e]),p=l.useMemo(()=>zm(e,a),[a,e]),h=l.useCallback(y=>{const x=e.find(k=>k.project.id===y);return x?_m(x,c):!1},[e,c]);return{sessionSidebarMetaById:d,sectionsForSidebarRender:u,filteredSectionsForSidebarRender:f,totalSessionCount:m,sessionCountByProject:b,hasActiveSessionByProject:g,activeDirectoriesByProject:p,hasUnseenByProject:h}}const va=[],Km={id:"__home__",path:"~",normalizedPath:"~",label:"No folder"},Wm=(e,t,s)=>{const r=[],o=new Set,i=(a,c)=>{const d=vs(a.project,s);for(const u of a.groups)for(const f of u.sessions){if(o.has(f.session.id))continue;o.add(f.session.id);const m=f.session.time;r.push({node:f,project:a.project,projectLabel:d,isPinned:!1,timestamp:m?.archived||m?.updated||m?.created||0,globalSession:c})}};t&&i(t,!0);for(const a of e)i(a,!1);return r.sort((a,c)=>c.timestamp-a.timestamp)},Gm=({viewMode:e,enabled:t,projects:s,archivedSessions:r,getArchivedSessionsForProject:o,isGlobalSession:i,buildGroupedSessions:a,availableWorktreesByProject:c,projectRepoStatus:d,projectRootBranches:u,lastRepoStatus:f,selectedSpaceId:m,selectedWorktreePath:b,homeDirectory:g})=>{const h=t&&(e==="threads"||e==="folder"||e==="workspace"),y=e==="workspace"?m:null,x=l.useMemo(()=>{if(!h)return[];const v=[];for(const A of s){if(y!==null&&A.id!==y)continue;const w=o(A.id);if(w.length===0)continue;const j=d.has(A.id)?!!d.get(A.id):f;v.push({project:A,groups:a(w,A.normalizedPath,c.get(A.normalizedPath)??[],u.get(A.id)??null,j)})}return v},[h,c,a,o,f,d,u,s,y]),k=l.useMemo(()=>{if(!h||y!==null)return null;const v=r.filter(i);return v.length===0?null:{project:Km,groups:a(v,"~",[],null,!1)}},[h,r,a,i,y]);return l.useMemo(()=>{if(!h)return va;const v=y!==null?gc(x,x,y,b):x,A=Wm(v,k,g);return A.length>0?A:va},[h,g,k,x,y,b])},Hm=e=>{const{projectSections:t,activeProjectId:s,activeSessionByProject:r,setActiveSessionByProject:o,currentSessionId:i,handleSessionSelect:a,newSessionDraftOpen:c,mobileVariant:d,openNewSessionDraft:u,setActiveMainTab:f,setSessionSwitcherOpen:m}=e,b=l.useMemo(()=>{const p=new Map,h=new Map,y=(x,k,v,A)=>{p.has(x)||p.set(x,new Map);const w=p.get(x);A.forEach(j=>{const S=Re(j.session.directory??v??k);w.set(j.session.id,{directory:S}),h.has(x)||h.set(x,{id:j.session.id,directory:S}),j.children.length>0&&y(x,k,S,j.children)})};return t.forEach(x=>{x.groups.forEach(k=>{y(x.project.id,x.project.normalizedPath,k.directory,k.sessions)})}),{metaByProject:p,firstSessionByProject:h}},[t]),g=l.useRef(null);l.useLayoutEffect(()=>{if(!s)return;if(c){g.current=s;return}if(g.current===s)return;const p=t.find(j=>j.project.id===s);if(!p)return;g.current=s;const h=b.metaByProject.get(s);if(i&&h&&h.has(i)){o(j=>{if(j.get(s)===i)return j;const S=new Map(j);return S.set(s,i),S});return}const y=i?Array.from(b.metaByProject.entries()).some(([j,S])=>j!==s&&S.has(i)):!1;if(i&&h&&!y)return;if(!h||h.size===0){f("chat"),d&&m(!1),u({selectedProjectId:p.project.id,directoryOverride:p.project.normalizedPath});return}const x=r.get(s),k=x&&h.has(x)?x:null,v=b.firstSessionByProject.get(s)?.id??null,A=k??v;if(!A||A===i)return;const w=h.get(A)?.directory??null;a(A,w,{keepPanelOpen:!0})},[s,r,i,a,c,d,u,t,b,f,m,o]),l.useEffect(()=>{if(!s||!i)return;const p=b.metaByProject.get(s);!p||!p.has(i)||o(h=>{if(h.get(s)===i)return h;const y=new Map(h);return y.set(s,i),y})},[s,i,b,o])},qm=({initialActiveSessionByProject:e,persistActiveSessionByProject:t,...s})=>{const r=Me(c=>c.currentSessionId),o=Me(c=>!!c.newSessionDraft?.open),[i,a]=l.useState(()=>new Map(e));return Hm({...s,activeSessionByProject:i,setActiveSessionByProject:a,currentSessionId:r,newSessionDraftOpen:o}),l.useEffect(()=>{t(i)},[i,t]),null},Sa=["var(--chart-1)","var(--chart-2)","var(--chart-3)","var(--chart-4)","var(--chart-5)"],Vm=e=>{let t=5381;for(let s=0;s<e.length;s+=1)t=t*33^e.charCodeAt(s);return t>>>0},Ym=(e,t,s)=>(s.get(e)??0)>0?e:t.get(e)??null,bc=e=>{if(!e||typeof e!="string"||e.trim().length===0)return null;const t=Vm(e.trim())%Sa.length;return Sa[t]},Qm=(e,t)=>{const s=bc(e);return s?t?.active?`color-mix(in srgb, ${s} 30%, var(--interactive-selection))`:`color-mix(in srgb, ${s} 18%, transparent)`:null},ja=e=>!!e.time?.archived,Jm=e=>{const t=l.useCallback(i=>[i.label,i.branch??"",i.description??"",i.directory??""].join(" ").toLowerCase(),[]),s=l.useCallback(i=>{const a=Re(i.directory??null)??"";return`${un(i)} ${a}`.toLowerCase()},[]),r=l.useCallback((i,a)=>a?i.flatMap(c=>{if(s(c.session).includes(a))return[c];const u=r(c.children,a);return u.length===0?[]:[{...c,children:u}]}):i,[s]),o=l.useCallback((i,a,c=[],d,u)=>{const f=Re(a??null),m=Vl(i).sort(Il(e.pinnedSessionIds,e.sessionOrderRanks)),b=new Map(m.map(j=>[j.id,j])),g=new Map,p=new Map;m.forEach(j=>{const S=j.parentID??null,C=S?b.get(S):null,E=C&&ja(C)===ja(j)?S:null;g.set(j.id,E),E&&p.set(E,(p.get(E)??0)+1)});const h=c.map(j=>({worktree:j,directory:Re(j.path)})).filter(j=>!!j.directory&&!j.worktree.isPrimary).sort((j,S)=>S.directory.length-j.directory.length),y=(j,S)=>S===j||S.startsWith(`${j}/`),x=j=>{const S=Re(j.directory??null);return S?h.find(C=>y(C.directory,S))?.worktree??null:null},k=(j,S)=>{const C=Ym(j.id,g,p);return{session:j,children:[],worktree:S,forkColorId:C}},v=[],A=new Map;for(const j of h)A.set(j.directory,[]);m.forEach(j=>{const S=x(j),C=k(j,S);S?A.get(Re(S.path)??"")?.push(C):v.push(C)});const w=[{id:"root",label:u&&d&&d!=="HEAD"?`project root: ${d}`:"project root",branch:d??null,description:f?Go(f,e.homeDirectory):null,isMain:!0,worktree:null,directory:f,folderScopeKey:f,sessions:v}];for(const{worktree:j,directory:S}of h)w.push({id:`worktree:${S}`,label:j.branch||(j.detached?"Detached HEAD":j.name),branch:j.branch,description:Go(S,e.homeDirectory),isMain:!1,worktree:j,directory:S,folderScopeKey:S,sessions:A.get(S)??[]});return w},[e.homeDirectory,e.pinnedSessionIds,e.sessionOrderRanks]);return{buildGroupSearchText:t,buildSessionSearchText:s,filterSessionNodesForSearch:r,buildGroupedSessions:o}},Xm=({mobileVariant:e,isTablet:t})=>!e&&!t,Zm=({enabled:e=!0,isSessionSearchOpen:t,setIsSessionSearchOpen:s,sessionSearchInputRef:r,sessionSearchContainerRef:o})=>{l.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]),l.useEffect(()=>{if(!e||!t||typeof document>"u")return;const i=a=>{o.current&&(o.current.contains(a.target)||s(!1))};return document.addEventListener("mousedown",i),()=>document.removeEventListener("mousedown",i)},[e,t,s,o])},xo=(e,t)=>t===1?`Could not ${e} the session`:`Could not ${e} the sessions`,Ca=(e,t)=>{if(!e.directory)return;const s=Xs.getState();or(s.ids,e.directory,e.sessionId)!==t&&s.toggle({directory:e.directory,sessionId:e.sessionId})},xc=async(e,t={})=>{if(e.length===0)return;const s=Xs.getState(),r=new Set(e.filter(g=>or(s.ids,g.directory,g.sessionId)).map(g=>g.sessionId));for(const g of e)r.has(g.sessionId)&&Ca(g,!1);const o=g=>{for(const p of g)r.has(p.sessionId)&&Ca(p,!0)},i=[...new Set(e.flatMap(g=>[g.sessionId,...g.forkIds]))];let a;try{a=await Me.getState().archiveSessions(i)}catch(g){console.warn("[session-archive] archive failed",g),a={archivedIds:[],failedIds:i}}const c=new Set(a.archivedIds),d=e.filter(g=>c.has(g.sessionId));if(o(e.filter(g=>!c.has(g.sessionId))),d.length===0){c.size>0&&Me.getState().unarchiveSessions([...c]),oe.error(xo("archive",e.length));return}const f=e.length===1&&t.title?`Archived “${t.title}”`:`Archived ${oa(d.length)}`,m=a.archivedIds;oe.success(f,{action:{label:"Undo",onClick:()=>{o(d),Me.getState().unarchiveSessions(m).then(({failedIds:g})=>{g.length>0&&oe.error(xo("unarchive",m.length))}).catch(g=>{console.warn("[session-archive] undo failed",g),oe.error(xo("unarchive",m.length))})}}});const b=i.length-c.size;b>0&&oe.error(`Could not archive ${oa(b)}`)},eg=e=>{const[t,s]=l.useState(null),r=l.useRef(null);l.useEffect(()=>()=>{r.current&&clearTimeout(r.current)},[]);const o=l.useCallback((v,A,w)=>{Ho("navigation.session_select"),ue.getState().closeMainSurfaces();const j=()=>{!e.isSessionSearchOpen&&e.sessionSearchQuery.length===0||(e.setSessionSearchQuery(""),e.setIsSessionSearchOpen(!1))},S=w?.keepPanelOpen!==!0;if(e.mobileVariant&&(e.setActiveMainTab("chat"),e.setSessionSwitcherOpen(!1)),v===Me.getState().currentSessionId){e.allowReselect&&S&&e.onSessionSelected?.(v),j();return}Ho("navigation.session_state_set"),e.setCurrentSession(v,A??null),S&&e.onSessionSelected?.(v),j()},[e]),i=l.useCallback((v,A)=>{e.setEditingId(v),e.setEditTitle(A)},[e]),a=l.useCallback(async v=>{if(!e.editingId)return;const A=(v??e.editTitle).trim();A&&await e.updateSessionTitle(e.editingId,A),e.setEditingId(null),e.setEditTitle("")},[e]),c=l.useCallback(()=>{e.setEditingId(null),e.setEditTitle("")},[e]),d=l.useCallback(async(v,A)=>{try{return(await fn(v)).ok?(s(A),r.current&&clearTimeout(r.current),r.current=window.setTimeout(()=>{s(null),r.current=null},2e3),!0):!1}catch{return!1}},[]),u=l.useCallback(async v=>{const A=await e.shareSession(v.id);if(!A?.share?.url){oe.error("Unable to share session");return}const w=await d(A.share.url,v.id);oe[w?"success":"warning"]("Session shared",{description:w?"Share link copied to clipboard.":"Failed to copy URL"})},[e,d]),f=l.useCallback((v,A)=>{d(v,A).then(w=>{w||oe.error("Failed to copy URL")})},[d]),m=l.useCallback(v=>{fn(v).then(A=>{if(A.ok){oe.success("Session ID copied");return}oe.error("Failed to copy session ID")}).catch(()=>oe.error("Failed to copy session ID"))},[]),b=l.useCallback(async v=>{await e.unshareSession(v)?oe.success("Session unshared"):oe.error("Unable to unshare session")},[e]),g=l.useCallback(v=>{const A=[],w=j=>{(e.childrenMap.get(j)??[]).forEach(C=>{A.push(C),w(C.id)})};return w(v),A},[e.childrenMap]),p=l.useCallback((v,A)=>A?v:v.filter(w=>!w.time?.archived),[]),h=l.useCallback(async(v,A)=>{const w=A?.descendantIds??p(g(v.id),!0).map(C=>C.id);if(w.length===0){await e.deleteSession(v.id)?oe.success("Session deleted"):oe.error("Failed to delete session");return}const{deletedIds:j,failedIds:S}=await e.deleteSessions([v.id,...w]);if(S.length===0){const C=j.length;oe.success(C===1?`Deleted ${C} session`:`Deleted ${C} sessions`)}else oe.error("Failed to delete session")},[e,g,p]),y=l.useCallback((v,A)=>{const w=A?.archivedBucket===!0||A?.hardDelete===!0,j=p(g(v.id),w).map(S=>S.id);if(!w){xc([{sessionId:v.id,directory:v.directory??null,forkIds:j}],{title:un(v,"Untitled session")});return}if(!e.showDeletionDialog||A?.skipConfirm===!0){h(v,{descendantIds:j});return}e.setDeleteSessionConfirm({session:v,descendantCount:j.length,descendantIds:j})},[e,g,h,p]),x=l.useCallback(async()=>{if(!e.deleteSessionConfirm)return;const{session:v,descendantIds:A}=e.deleteSessionConfirm;e.setDeleteSessionConfirm(null),await h(v,{descendantIds:A})},[e,h]),k=l.useCallback(async v=>{await e.unarchiveSession(v.id)?oe.success("Session unarchived"):oe.error("Could not unarchive the session")},[e]);return{copiedSessionId:t,handleSessionSelect:o,handleSessionDoubleClick:i,handleSaveEdit:a,handleCancelEdit:c,handleShareSession:u,handleCopyShareUrl:f,handleCopySessionId:m,handleUnshareSession:b,handleDeleteSession:y,handleRestoreSession:k,confirmDeleteSession:x}},tg=e=>{const{safeStorage:t,keys:s,groupOrderByProject:r,collapsedGroups:o,setExpandedParents:i,setCollapsedProjects:a}=e,c=l.useRef(null),d=l.useRef(null),u=l.useCallback(()=>{const m=d.current;if(d.current=null,c.current=null,!m)return;const{projects:b}=dt.getState(),g=b.map(p=>({...p,sidebarCollapsed:m.has(p.id)}));Ul({projects:g}).catch(()=>{})},[]),f=l.useCallback(m=>{typeof window>"u"||(d.current=m,c.current!==null&&window.clearTimeout(c.current),c.current=window.setTimeout(()=>{u()},700))},[u]);return l.useEffect(()=>()=>{typeof window<"u"&&c.current!==null&&window.clearTimeout(c.current),c.current=null,d.current=null},[]),l.useEffect(()=>{try{const m=t.getItem(s.sessionExpanded);if(m){const g=JSON.parse(m);Array.isArray(g)&&i(new Set(g.filter(p=>typeof p=="string")))}const b=t.getItem(s.projectCollapse);if(b){const g=JSON.parse(b);Array.isArray(g)&&a(new Set(g.filter(p=>typeof p=="string")))}}catch{}},[s.projectCollapse,s.sessionExpanded,t,a,i]),l.useEffect(()=>{try{const m=Object.fromEntries(r.entries());t.setItem(s.groupOrder,JSON.stringify(m))}catch{}},[r,s.groupOrder,t]),l.useEffect(()=>{try{t.setItem(s.groupCollapse,JSON.stringify(Array.from(o)))}catch{}},[o,s.groupCollapse,t]),{scheduleCollapsedProjectsPersist:f}},ng=3;let Lr=0;const yc=[],sg=()=>Lr<ng?(Lr+=1,Promise.resolve()):new Promise(e=>{yc.push(e)}),rg=()=>{const e=yc.shift();if(e){e();return}Lr=Math.max(0,Lr-1)},og=async e=>{await sg();try{return await e()}finally{rg()}},ig=5*6e4,ag=e=>{const{normalizedProjects:t,enabled:s=!0,gitRepoStatus:r,setProjectRepoStatus:o,setProjectRootBranches:i}=e,{git:a}=Kn(),c=El(p=>p.ensureStatus),d=l.useMemo(()=>t.map(p=>p.normalizedPath).slice().sort().join("\0"),[t]),u=l.useRef(null);l.useEffect(()=>{if(!s||!a||t.length===0){u.current=null,o(new Map);return}const p=`${rt()}\0${d}`;u.current!==p&&(u.current=p,t.forEach(h=>{og(()=>c(h.normalizedPath,a))}))},[s,t,d,a,c,o]);const f=l.useRef(null);l.useEffect(()=>{if(!s){f.current=null;return}const p=new Map;t.forEach(y=>{p.set(y.id,r.get(y.normalizedPath)?.isGitRepo??null)});const h=t.map(y=>`${y.id}:${String(p.get(y.id))}`).join("|");f.current!==h&&(f.current=h,o(p))},[s,t,d,r,o]);const m=l.useMemo(()=>t.map(p=>{const h=r.get(p.normalizedPath)?.branch??"";return`${p.id}:${h}`}).join("|"),[t,r]),b=l.useRef(new Map),g=l.useRef(new Map);l.useEffect(()=>{if(!s)return;let p=!1;const h=setTimeout(()=>{(async()=>{const x=new Set(t.map(j=>j.id));for(const j of b.current.keys())x.has(j)||(b.current.delete(j),g.current.delete(j));const k=Date.now();if(t.filter(j=>{const S=r.get(j.normalizedPath);if(S?.isGitRepo===!1)return b.current.delete(j.id),g.current.delete(j.id),!1;if(S?.isGitRepo!==!0||S.branch===null)return!1;const C=S.branch.trim(),E=`${j.normalizedPath}\0${C}`,P=b.current.get(j.id);if(P===E){const z=g.current.get(j.id);return z&&(z.at=k),!1}return!(P!==void 0&&k-(g.current.get(j.id)?.at??0)<ig)}).length===0)return;const A=[];if(t.forEach(j=>{const S=r.get(j.normalizedPath)?.branch?.trim()??"",C=`${j.normalizedPath}\0${S}`;S&&A.push({id:j.id,inputKey:C,branch:S})}),p||A.length===0)return;const w=Date.now();i(j=>{const S=new Map(j);return A.forEach(({id:C,branch:E})=>{E&&S.set(C,E)}),S}),A.forEach(({id:j,inputKey:S,branch:C})=>{b.current.set(j,S),C&&g.current.set(j,{branch:C,at:w})})})()},150);return()=>{p=!0,clearTimeout(h)}},[s,t,m,r,i])},lg=e=>{const{ownership:t}=e,s=l.useCallback(o=>t.sessionsByProject.get(o)??[],[t]),r=l.useCallback(o=>t.archivedSessionsByProject.get(o)??[],[t]);return{getSessionsForProject:s,getArchivedSessionsForProject:r}},cg=e=>{const t=new Map;for(const s of e){const r=cs(s);r&&t.set(s.id,{directory:r,sessionId:s.id})}return t},dg=(e,t)=>{if(!e)return[];const s=[];return e.forEach((r,o)=>{t.has(o)||s.push(r)}),s},ug=e=>{const{enabled:t=!0,hasAuthoritativeGlobalSessions:s,sessions:r}=e,o=l.useRef(null);l.useEffect(()=>{if(!t||!s)return;const i=rt(),a=cg(r),c=o.current?.runtimeKey===i?o.current.identities:null;for(const d of dg(c,a))rs().commitMissedDeletion(d.sessionId,d.directory);o.current={runtimeKey:i,identities:a}},[t,s,r])},fg=(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,ka=(e,t,s)=>{fg(e.get(t),s)&&e.set(t,s)},wc=e=>{const t=e;return Re(t.directory)??Re(t.project?.worktree)},hg=(e,t,s)=>{if(e.time?.archived)return!0;const r=wc(e);if(!r)return s?.allowUnknownDirectory??!0;if(Zs(r,s?.homeDirectory))return!0;if(t.size===0)return s?.allowEmptyDirectorySet??!0;const o=r.toLowerCase();for(const i of t)if(Re(i)?.toLowerCase()===o)return!0;return!1},pg=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)},mg=(e,t,s,r=[])=>{const o=new Map,i=new Map;for(const g of t){const p=Re(g.normalizedPath);if(!p)continue;const h=i.get(p);(!h||g.id.localeCompare(h.id)<0)&&i.set(p,g),ka(o,p,{projectId:g.id,projectRoot:p,scopeDirectory:p,kind:"project"})}if(s)for(const[g,p]of s){const h=Re(g),y=h?i.get(h):void 0;if(!(!y||!h))for(const x of p||[]){const k=Re(x?.path);k&&ka(o,k,{projectId:y.id,projectRoot:h,scopeDirectory:k,kind:"worktree"})}}const a=new Map,c=new Map,d=new Map,u=new Map,f=new Map,m=g=>{if(!g)return null;if(a.has(g))return a.get(g)??null;const p=[];let h=g,y=null;for(;h;){if(a.has(h)){y=a.get(h)??null;break}if(p.push(h),y=o.get(h)??null,y)break;h=pg(h)}for(const x of p)a.set(x,y);return y},b=(g,p,h)=>{for(const y of g){const x=wc(y);if(Zs(x))continue;const k=m(x);if(!k)continue;c.set(y.id,k);const v=p.get(k.projectId);if(v?v.push(y):p.set(k.projectId,[y]),!h)continue;const A=h.get(k.scopeDirectory);A?A.add(y.id):h.set(k.scopeDirectory,new Set([y.id]))}};return b(e,d,f),b(r,u),{bySessionId:c,sessionsByProject:d,archivedSessionsByProject:u,sessionsByScope:f,directoryResolutions:a.size}};function vc({state:e,activeLabel:t,unreadLabel:s,inputLabel:r,className:o}){if(e==="input"){const i=r??"Needs input";return n.jsx("span",{className:_("inline-flex items-center",o),"aria-label":i,title:i,children:n.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-status-warning"})})}return e==="unread"?n.jsx("span",{className:_("inline-flex items-center",o),"aria-label":s??t,title:s??t,children:n.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-foreground"})}):n.jsx("span",{className:_("inline-flex items-center",o),"aria-label":t,title:t,children:n.jsx(Cn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})})}const gg=({folder:e,displayName:t,sessions:s,subFolderItems:r,isCollapsed:o,collapsedActivityState:i=null,onToggle:a,onRename:c,onDelete:d,renderSessionNode:u,getRenderExtras:f,groupDirectory:m,projectId:b,mobileVariant:g=!1,alwaysShowActions:p=g,isRenaming:h=!1,renameDraft:y="",onRenameDraftChange:x,onRenameSave:k,onRenameCancel:v,droppableRef:A,isDropTarget:w=!1,onNewSession:j,depth:S=0,hideActions:C=!1,archivedBucket:E=!1})=>{const[P,z]=l.useState(!1),[K,q]=l.useState(""),H=l.useRef(null),F=h||P,D=h?y:K,T=l.useCallback(()=>{q(e.name),z(!0)},[e.name]),I=l.useCallback(()=>{const L=D.trim();L&&L!==e.name&&c(L),h&&k&&k(),z(!1),q("")},[D,e.name,h,c,k]),M=l.useCallback(()=>{h&&v&&v(),z(!1),q("")},[h,v]),G=l.useCallback(L=>{h&&x?x(L):q(L)},[h,x]);l.useEffect(()=>{if(!h)return;const L=()=>{const le=H.current;le&&(le.focus(),le.select())},ae=requestAnimationFrame(L),J=window.setTimeout(L,0);return()=>{cancelAnimationFrame(ae),window.clearTimeout(J)}},[h]);const W=o?"folder":"folder-open";return n.jsxs("div",{className:"oc-folder",children:[n.jsxs("div",{ref:A,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",w&&"bg-primary/10 ring-1 ring-inset ring-primary/30"),onClick:F?void 0:L=>{L.currentTarget.blur(),a()},role:F?void 0:"button",tabIndex:F?void 0:0,onKeyDown:F?void 0:L=>{(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),a())},"aria-label":o?`Expand folder ${e.name}`:`Collapse folder ${e.name}`,children:[n.jsxs("div",{className:_("min-w-0 flex items-center gap-1.5 flex-1 transition-[padding]",E?p?"pr-7":"group-hover/folder:pr-7 group-focus-within/folder:pr-7":p?"pr-20":"group-hover/folder:pr-20 group-focus-within/folder:pr-20"),children:[n.jsx(R,{name:W,className:_(kr,w?"text-primary":"text-muted-foreground")}),F?n.jsxs("form",{className:"flex min-w-0 flex-1 items-center gap-1",onPointerDown:L=>L.stopPropagation(),onMouseDown:L=>L.stopPropagation(),onSubmit:L=>{L.preventDefault(),I()},children:[n.jsx("input",{ref:H,value:D,onChange:L=>G(L.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:L=>L.stopPropagation(),onPointerDown:L=>L.stopPropagation(),onMouseDown:L=>L.stopPropagation(),onKeyDown:L=>{if(L.key==="Escape"){L.stopPropagation(),M();return}(L.key===" "||L.key==="Enter")&&L.stopPropagation()}}),n.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",onClick:L=>L.stopPropagation(),onPointerDown:L=>L.stopPropagation(),onMouseDown:L=>L.stopPropagation(),children:n.jsx(R,{name:"check",className:"size-4"})}),n.jsx("button",{type:"button",onClick:L=>{L.stopPropagation(),M()},onPointerDown:L=>L.stopPropagation(),onMouseDown:L=>L.stopPropagation(),className:"shrink-0 text-muted-foreground hover:text-foreground",children:n.jsx(R,{name:"close",className:"size-4"})})]}):n.jsxs("div",{className:"min-w-0 flex items-center gap-1.5 flex-1",children:[n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("span",{className:_(Yl,w?"text-primary":"text-muted-foreground"),children:t??e.name})}),n.jsx(Ge,{side:"right",sideOffset:8,className:"max-w-xs",children:t??e.name})]}),n.jsxs("span",{className:"typography-micro text-subtle-foreground flex-shrink-0",children:["• ",s.length]}),i?n.jsx(vc,{state:i,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,o?n.jsx(R,{name:"arrow-right-s",className:_(kr,"text-muted-foreground")}):n.jsx(R,{name:"arrow-down-s",className:_(kr,"text-muted-foreground")})]})]}),!F&&(!C||E)?n.jsx("div",{className:_("absolute right-0.5 top-1/2 z-10 flex -translate-y-1/2 items-center gap-0.5 transition-opacity",p?"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:n.jsxs("div",{className:"flex items-center gap-0.5",children:[!E&&j?n.jsx("button",{type:"button",onClick:L=>{L.stopPropagation(),j()},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:n.jsx(R,{name:"add",className:"size-4"})}):null,E?null:n.jsx("button",{type:"button",onClick:L=>{L.stopPropagation(),T()},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:n.jsx(R,{name:"pencil-ai",className:"size-4"})}),n.jsx("button",{type:"button",onClick:L=>{L.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":E?`Delete archived sessions in folder ${e.name}`:`Delete folder ${e.name}`,children:n.jsx(R,{name:"delete-bin",className:"size-4"})})]})}):null]}),o?null:n.jsxs("div",{className:"pb-1",children:[r,s.length>0?s.map(L=>n.jsx(l.Fragment,{children:u(L,0,m??null,b??null,E,void 0,"project",f?.(L))},L.session.id)):r?null:n.jsx("div",{className:"py-1 px-3 text-left typography-micro text-subtle-foreground",children:"Empty folder"})]})]})},bg=l.memo(gg),Vr=l.createContext(null),xg=({sessionId:e,sessionDirectory:t,sessionTitle:s,children:r})=>{const{attributes:o,listeners:i,setNodeRef:a,isDragging:c}=yu({id:`session-drag:${e}`,data:{type:"session",sessionId:e,sessionDirectory:t,sessionTitle:s}}),d=l.useCallback(u=>{u.stopPropagation(),i?.onPointerDown&&i.onPointerDown(u)},[i]);return n.jsx("div",{ref:a,...o,onPointerDown:d,className:c?"opacity-30":void 0,children:r})},yg=({folderId:e,children:t})=>{const{setNodeRef:s,isOver:r}=ml({id:`folder-drop:${e}`,data:{type:"folder",folderId:e}});return n.jsx(n.Fragment,{children:t(s,r)})},wg=({scopeKey:e,hasFolders:t,onSessionDroppedOnFolder:s,children:r})=>{const o=Kr(hs(hl,{activationConstraint:{distance:8}})),[i,a]=l.useState(null),[c,d]=l.useState("Session"),[u,f]=l.useState(null),[m,b]=l.useState(null);if(!e)return n.jsx(n.Fragment,{children:r});const g=p=>{a(null),f(null),b(null);const{active:h,over:y}=p;if(!y)return;const x=h.data.current,k=y.data.current;x?.type==="session"&&x.sessionId&&k?.type==="folder"&&k.folderId&&s(x.sessionId,k.folderId)};return n.jsxs(Wr,{sensors:o,collisionDetection:wi,onDragStart:p=>{const h=p.active.data.current;if(h?.type==="session"&&h.sessionId){a(h.sessionId),d(h.sessionTitle??"Session");const y=p.active.rect.current.initial?.width,x=p.active.rect.current.initial?.height;f(typeof y=="number"?y:null),b(typeof x=="number"?x:null)}},onDragCancel:()=>{a(null),f(null),b(null)},onDragEnd:g,children:[r,n.jsx(pl,{children:i&&t?n.jsxs("div",{style:{width:u?`${u}px`:"auto",height:m?`${m}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:[n.jsx(R,{name:"sticky-note",className:"h-4 w-4 text-muted-foreground mr-2 flex-shrink-0"}),n.jsx("div",{className:"min-w-0 flex-1 truncate typography-ui-label font-normal text-foreground",children:c})]}):null})]})},Yr="gap-2",Sc="my-0.5 rounded-lg py-1.5",nr=l.createContext("card"),Gt=({icon:e,children:t,onClick:s,className:r,mobileVariant:o=!1})=>{const i=l.useContext(nr)==="tree";return n.jsxs("button",{type:"button",onClick:s,"data-sidebar-tree-row":i?"":void 0,className:_(o?kh:Ah,i&&Yr,i&&Sc,r),children:[n.jsx(R,{name:e,className:_(Un(o),"text-muted-foreground")}),n.jsx("span",{className:_(bs(o),"flex-1 text-muted-foreground"),children:t})]})},vg="select-none px-3 pb-0.5 typography-ui-label font-medium text-muted-foreground",us=({label:e,first:t=!1,count:s,expanded:r,onToggle:o})=>{const i=t?"pt-1":"pt-3",a=typeof s=="number"?n.jsx("span",{className:"font-normal tabular-nums text-subtle-foreground",children:s}):null;return o?n.jsx("div",{role:"heading","aria-level":3,className:i,children:n.jsxs("button",{type:"button","aria-expanded":r,onClick:o,className:"group/heading flex h-7 w-full select-none items-center gap-1.5 rounded-md px-3 text-left typography-ui-label font-medium text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:[e,a,n.jsx(R,{name:r?"arrow-down-s":"arrow-right-s",className:"ml-auto size-4 shrink-0 text-muted-foreground group-hover/heading:text-foreground"})]})}):n.jsxs("div",{role:"heading","aria-level":3,className:_(vg,i,"flex items-center gap-1.5"),children:[e,a]})},Aa=(e,t,s)=>{if(!t)return;const r=o=>{let i=o.session.id===t;for(const a of o.children)i=r(a)||i;return i&&s.add(o.session.id),i};for(const o of e)r(o)},dn=(e,t)=>{if(!t)return!1;if(e.session.id===t)return!0;for(const s of e.children)if(dn(s,t))return!0;return!1},Sg=(e,t)=>{const s=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(s.has(i)&&t.has(i))return!1;o.add(i),i=t.get(i)?.session?.parentID??null}return!0})},Na=new WeakMap;let Ia=1;const jg=e=>{const t=Na.get(e);if(t!==void 0)return t;const s=Ia;return Ia+=1,Na.set(e,s),s},oi=e=>e.children.length===0?"":e.children.map(s=>{const r=jg(s.session);return s.children.length===0?`${s.session.id}@${r}`:`${s.session.id}@${r}:${oi(s)}`}).join("|"),jc=(e,t,s,r,o,i)=>{const a=rt(),c=(d,u)=>{if(d.session.id!==u.session.id||d.children.length!==u.children.length)return!0;const f=d.session.directory??o,m=u.session.directory??i,b=ta(a,f??"",d.session.id),g=ta(a,m??"",u.session.id);return(b?s.has(b):!1)!==(g?r.has(g):!1)?!0:d.children.some((p,h)=>c(p,u.children[h]))};return c(e,t)},sr=(e,t)=>`${e}:${t.time?.archived?"archived":"active"}:${t.id}`,Or=(e,t,s)=>{if(!t)return null;let r=null;const o=i=>{if(sr(s,i.session)===t)return r=i.session.id,!0;for(const c of i.children)if(o(c))return!0;return!1};return e.forEach(i=>o(i)),r},Cg=5*6e4,kg=6e4,Ea=5*6e4,Da=100,Ls=new Map,os=new Map,Bn=new Map,fs=new Map,rr=(e,t)=>{const s=hn((e??"").trim()),r=(t??"").trim();return!s||!r?"":`${rt()}
|
|
12
|
+
${s}
|
|
13
|
+
${r}`},Ra=()=>({pr:null,checks:null,fetchedAt:null,isLoading:!1,stale:!1,error:null}),Ag=e=>{const t=e?.body;return t&&typeof t.kind=="string"?t:{kind:"failed",message:e instanceof Error?e.message:"PR status check failed"}},Ng=e=>{const t=Object.keys(e);if(t.length<=Da)return e;const s=t.sort((o,i)=>(fs.get(o)??0)-(fs.get(i)??0)),r={...e};for(let o=0;o<s.length-Da;o+=1){const i=s[o];delete r[i],fs.delete(i),os.delete(i);const a=Bn.get(i);a!==void 0&&(clearTimeout(a),Bn.delete(i))}return r},Cc=e=>e.pr?e.pr.state!=="open"?Ea:e.checks?.state==="pending"?kg:Ea:Cg,ii=(e,t,s,r)=>{if(typeof window>"u"||Bn.has(e))return;const o=Zt.getState().results[e];if(!o)return;const i=Cc(o),a=setTimeout(()=>{if(Bn.delete(e),!!Zt.getState().results[e]){if(typeof document<"u"&&document.hidden){ii(e,t,s,r);return}Zt.getState().refresh(t,s,r)}},i);typeof a=="object"&&a!==null&&typeof a.unref=="function"&&a.unref(),Bn.set(e,a)},Zt=Nn()(Gr((e,t)=>({results:{},refresh:async(s,r,o,i)=>{const a=hn((s||"").trim()),c=(r||"").trim();if(!a||!c)return null;const d=rr(a,c);if(!d)return null;const u=Ls.get(d);if(u&&!i?.force)return u;const f=o??null;if(!f)return t().results[d]??null;const m=(os.get(d)??0)+1;os.set(d,m);const b=t().results[d]??Ra();e(p=>({results:{...p.results,[d]:{...b,isLoading:!0}}}));const g=(async()=>{try{const p=await f.prStatus(a,c);if(os.get(d)!==m||rt()!==d.split(`
|
|
14
|
+
`)[0])return t().results[d]??null;const h={pr:p.pr??null,checks:p.checks??null,checksStale:p.checksStale,defaultBranch:p.defaultBranch??null,skippedDefaultBranch:p.skippedDefaultBranch,fetchedAt:p.fetchedAt??Date.now(),isLoading:!1,stale:!1,error:null};return fs.set(d,Date.now()),e(y=>({results:Ng({...y.results,[d]:h})})),ii(d,a,c,f),h}catch(p){if(os.get(d)!==m)return t().results[d]??null;const h=Ag(p),y=b.pr||b.fetchedAt?{...b,isLoading:!1,stale:!0,error:h}:{...Ra(),error:h};return e(x=>({results:{...x.results,[d]:y}})),ii(d,a,c,f),y}})();Ls.set(d,g);try{return await g}finally{Ls.get(d)===g&&Ls.delete(d)}},load:async(s,r,o)=>{const i=hn((s||"").trim()),a=(r||"").trim();if(!i||!a)return null;const c=rr(i,a);fs.set(c,Date.now());const d=t().results[c];return d&&(d.pr||d.fetchedAt)?(t().refresh(i,a,o),d):t().refresh(i,a,o)},resetForRuntimeSwitch:()=>{Ls.clear(),os.clear(),fs.clear(),_s=null;for(const s of Bn.values())clearTimeout(s);Bn.clear(),e({results:{}})}}),{name:"github-pr-status-store"}));typeof window<"u"&&(ws(()=>{Zt.getState().resetForRuntimeSwitch()}),document.addEventListener("visibilitychange",()=>{document.hidden||(async()=>{const e=await pt(async()=>{const{getRegisteredRuntimeAPIs:r}=await import("./index-B2v0_mez.js").then(o=>o.cJ);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(),s=Object.entries(Zt.getState().results).filter(([,r])=>r.fetchedAt&&t-r.fetchedAt>=Cc(r)).map(([r])=>r);for(const r of s){const[,o,i]=r.split(`
|
|
15
|
+
`);if(!(!o||!i)){if(typeof document<"u"&&document.hidden)return;await Zt.getState().refresh(o,i,e).catch(()=>null)}}})()}));let _s=null;const dv=e=>{if(_s&&_s.results===e)return _s.index;const t=new Map;for(const s of Object.values(e)){const r=s.pr?.url;!r||t.has(r)||t.set(r,s.checks?.state??null)}return _s={results:e,index:t},t},Ig=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 s=e?.checks?.state,r=t.mergeableState??void 0;return r==="dirty"||r==="blocked"||s==="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}},kc=e=>{const t=Zt(s=>e?s.results[e]??null:null);return l.useMemo(()=>Ig(t),[t])},Ac=(e,t,s)=>{const r=l.useMemo(()=>rr(e,t),[e,t]),o=s??null;l.useEffect(()=>{if(!r||!e?.trim()||!t?.trim())return;let i=!1;return pt(async()=>{const{getRegisteredRuntimeAPIs:a}=await import("./index-B2v0_mez.js").then(c=>c.cJ);return{getRegisteredRuntimeAPIs:a}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:a})=>{if(i)return;const c=o??a()?.github??null;c&&Zt.getState().load(e,t,c)}).catch(()=>{}),()=>{i=!0}},[r,e,t,o])},Nc=new Set,Ii=(e,t)=>e==="input"||t==="input"?"input":e==="active"||t==="active"?"active":e==="unread"||t==="unread"?"unread":null,ai=(e,t,s,r=Nc)=>{if(r.has(e.session.id))return"input";if(t.has(e.session.id)){for(const i of e.children)if(ai(i,t,s,r)==="input")return"input";return"active"}let o=s.has(e.session.id)?"unread":null;for(const i of e.children)if(o=Ii(o,ai(i,t,s,r)),o==="input")return o;return o},Ic=(e,t,s,r=Nc)=>{let o=null;for(const i of e)if(o=Ii(o,ai(i,t,s,r)),o==="input")return o;return o},li=(e,t)=>{if(!t)return e;const s=e.toLowerCase(),r=t.toLowerCase(),o=r.length;if(o===0)return e;const i=[];let a=0,c=s.indexOf(r,a);for(;c!==-1;){c>a&&i.push(e.slice(a,c));const d=e.slice(c,c+o);i.push(n.jsx("mark",{className:"bg-primary text-primary-foreground ring-1 ring-primary/90",children:d},`${c}-${d}`)),a=c+o,c=s.indexOf(r,a)}return a<e.length&&i.push(e.slice(a)),i.length>0?i:e},js=e=>[rt(),...e.map(t=>(t??"").toString())].join(`
|
|
16
|
+
`),xr=e=>{const t=e?.body;return t&&typeof t.kind=="string"?t:{kind:"failed",message:e instanceof Error?e.message:"GitHub request failed"}},Eg=200,ls=(e={})=>{const t=e.maxEntries??Eg,s=new Map,r=new Map,o=new Map;let i=0;const a=new Map,c=new Map,d=h=>{const y=s.get(h)??null;return y&&a.set(h,i+=1),y},u=h=>{const y=c.get(h);if(y)for(const x of[...y])try{x()}catch{}},f=()=>{if(s.size<=t)return;const h=[...s.keys()].filter(x=>!r.has(x)&&(c.get(x)?.size??0)===0).sort((x,k)=>(a.get(x)??0)-(a.get(k)??0)),y=s.size-t;for(let x=0;x<y&&x<h.length;x+=1){const k=h[x];s.delete(k),a.delete(k),o.set(k,(o.get(k)??0)+1)}};let m=!1;const b=()=>{if(m||s.size<=t)return;m=!0;const h=()=>{m=!1,f()};typeof queueMicrotask=="function"?queueMicrotask(h):setTimeout(h,0)},g=(h,y)=>{const k={...s.get(h)??{data:null,fetchedAt:null,isLoading:!1,stale:!1,error:null,generation:o.get(h)??0},...y};return s.set(h,k),a.set(h,i+=1),b(),u(h),k},p=async(h,y)=>{const x=r.get(h);if(x)return x;const k=(o.get(h)??0)+1;o.set(h,k);const v=s.get(h);g(h,{isLoading:!0,generation:k});const A=(async()=>{try{const w=await y();return o.get(h)!==k?s.get(h)??{data:w,fetchedAt:Date.now(),isLoading:!1,stale:!1,error:null,generation:k}:g(h,{data:w,fetchedAt:Date.now(),isLoading:!1,stale:!1,error:null,generation:k})}catch(w){return o.get(h)!==k?s.get(h)??{data:v?.data??null,fetchedAt:v?.fetchedAt??null,isLoading:!1,stale:!0,error:xr(w),generation:k}:v?.data!=null?g(h,{isLoading:!1,stale:!0,error:xr(w),generation:k}):g(h,{data:null,fetchedAt:null,isLoading:!1,stale:!1,error:xr(w),generation:k})}})();r.set(h,A);try{return await A}finally{r.get(h)===A&&r.delete(h),e.onSettle?.(h)}};return{getEntry:d,snapshot:()=>Object.fromEntries(s),subscribe:(h,y)=>{let x=c.get(h);return x||(x=new Set,c.set(h,x)),x.add(y),()=>{const k=c.get(h);k&&(k.delete(y),k.size===0&&c.delete(h))}},ensure:(h,y,x)=>!x?.force&&r.has(h)?r.get(h):!x?.force&&s.get(h)?.data!=null&&s.get(h)?.isLoading?r.get(h)??Promise.resolve(s.get(h)):!x?.force&&s.get(h)?.data!=null?(p(h,y),Promise.resolve(s.get(h))):p(h,y),refresh:(h,y)=>p(h,y),invalidate:async(h,y,x)=>{if(x?.exact??!0)return o.set(h,(o.get(h)??0)+1),s.delete(h),a.delete(h),r.has(h)&&r.delete(h),u(h),y?p(h,y):null;for(const v of[...s.keys()])(v===h||v.startsWith(h))&&(o.set(v,(o.get(v)??0)+1),s.delete(v),a.delete(v),r.delete(v),u(v));return null},markStale:h=>{const y=s.get(h);y?.data&&(y.stale||g(h,{stale:!0}))},setError:(h,y)=>{const x=s.get(h);return x?.data?g(h,{isLoading:!1,stale:!0,error:xr(y)}):x??null},remove:h=>{o.set(h,(o.get(h)??0)+1),s.delete(h),a.delete(h),r.delete(h),u(h)},reset:()=>{const h=[...s.keys()];s.clear(),r.clear(),o.clear(),a.clear();for(const y of h)u(y)}}},Cs=(e,t)=>Te.useSyncExternalStore(s=>t?e.subscribe(t,s):()=>{},()=>t?e.getEntry(t):null,()=>t?e.getEntry(t):null),uv=e=>{const t=e.trim().match(/^#?(\d{1,7})$/);if(!t)return null;const s=Number(t[1]);return Number.isSafeInteger(s)&&s>0?s:null},Ec=(e,t)=>!e||!t?!1:e.toLowerCase()===t.toLowerCase(),ci=e=>{if(!e)return[];const t=[];for(const s of e)s?.login&&t.push(s.login.toLowerCase());return t},Dc=e=>{const t=[],s=[];for(const r of e.trim().toLowerCase().split(/\s+/))r&&(r.startsWith("label:")&&r.length>6?s.push(r.slice(6)):t.push(r));return{tokens:t,labelTokens:s}},Ei=e=>{if(!e)return[];const t=[];for(const s of e)s?.name&&t.push(s.name.toLowerCase());return t},Rc=(e,t,s)=>{const r=Ei(e??null),o=t.split(",").map(i=>i.trim().toLowerCase()).filter(Boolean);for(const i of[...o,...s])if(!r.some(a=>a===i||a.includes(i)))return!1;return!0},Dg=e=>{const t=[e.title.toLowerCase(),`#${e.number}`,`${e.number}`,e.author?.login?.toLowerCase()??"",e.head.toLowerCase(),e.base.toLowerCase()];for(const s of Ei(e.labels))t.push(s);return t},Rg=e=>{const t=[e.title.toLowerCase(),`#${e.number}`,`${e.number}`,e.author?.login?.toLowerCase()??""];for(const s of Ei(e.labels))t.push(s);return t},Pc=(e,t)=>{for(const s of t){let r=!1;for(const o of e)if(o.includes(s)){r=!0;break}if(!r)return!1}return!0},Pa=e=>e.state==="merged"||!!e.mergedAt,Pg=(e,t)=>t==="all"?e:t==="open"?e.filter(s=>s.state==="open"):t==="merged"?e.filter(s=>Pa(s)):e.filter(s=>s.state==="closed"&&!Pa(s)),Tg=(e,t)=>t==="all"?e:e.filter(s=>s.state===t),Mg=(e,t,s)=>t==="all"||!s?!0:t==="mine"?Ec(e.author?.login,s):t==="review"?ci(e.requestedReviewers).includes(s.toLowerCase()):ci(e.assignees).includes(s.toLowerCase()),Fg=(e,t,s)=>t==="all"||!s||t==="mentioned"?!0:t==="mine"?Ec(e.author?.login,s):ci(e.assignees).includes(s.toLowerCase()),ts=e=>{if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0},Tc=(e,t)=>{const s=[...e];return t==="newest"?(s.sort((r,o)=>ts(o.createdAt)-ts(r.createdAt)||o.number-r.number),s):t==="oldest"?(s.sort((r,o)=>ts(r.createdAt)-ts(o.createdAt)||r.number-o.number),s):(s.sort((r,o)=>ts(o.updatedAt)-ts(r.updatedAt)||o.number-r.number),s)},fv=(e,t)=>{const{tokens:s,labelTokens:r}=Dc(t.search),o=[];for(const i of Pg(e,t.state))Mg(i,t.involvement,t.viewerLogin)&&Rc(i.labels,"",r)&&Pc(Dg(i),s)&&o.push(i);return Tc(o,t.sort)},hv=(e,t)=>{const{tokens:s,labelTokens:r}=Dc(t.search),o=[];for(const i of Tg(e,t.state))Fg(i,t.involvement,t.viewerLogin)&&Rc(i.labels,t.labels,r)&&Pc(Rg(i),s)&&o.push(i);return Tc(o,t.sort)},yr=(e,t)=>{if(t.length===0)return e;const s=new Map;for(const i of t)s.set(i.number,i);const r=e.map(i=>s.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},pv=(e,t)=>e.filter(s=>!t.has(s.number)),Lg=(e,t)=>{if(t.length===0)return e;const s=new Set(e.map(o=>o.id)),r=[...e];for(const o of t)s.has(o.id)||(s.add(o.id),r.push(o));return r},Ta=Object.freeze({repo:null,number:null}),yo=e=>e.split(`
|
|
17
|
+
`)[1]??"",di=(e,t)=>`${hn(e)}
|
|
18
|
+
${t}`,Os=(e,t)=>`${e}#${t}`,Og=(e,t)=>{const s=e?.body;return s&&typeof s.kind=="string"?s:{kind:"failed",message:e instanceof Error?e.message:t}},Fn=async(e,t)=>{if(e)try{await e.invalidate(t)}catch{}},Ma=(e,t)=>!e?.data||!e.fetchedAt?!1:Date.now()-e.fetchedAt<t,Fa=10,Bg=(e,t)=>{const s=ls(),r=ls({maxEntries:60}),o=ls(),i=ls(),a=new Map,c=new Map,d=async(F,D)=>{const T=c.get(F);if(T)return await T.catch(()=>null),{ran:!1,result:null};const I=D();c.set(F,I);try{return{ran:!0,result:await I}}finally{c.get(F)===I&&c.delete(F)}},u=(F,D)=>{if(D.length===0)return;const T=e.collectionKeyFor(F,e.openCollection);let I=a.get(T);I||(I=new Map,a.set(T,I));for(const M of D)I.set(M.number,M)},f=F=>{const D=Object.keys(r.snapshot()).filter(I=>yo(I)===F&&!r.getEntry(I)?.isLoading);if(D.length<=Fa)return;const T=D.map(I=>({key:I,fetchedAt:r.getEntry(I)?.data?.fetchedAt??0})).sort((I,M)=>I.fetchedAt-M.fetchedAt);for(let I=0;I<T.length-Fa;I+=1)r.remove(T[I].key)},m=F=>{const D=s.getEntry(e.collectionKeyFor(F,e.openCollection))?.data?.items??[],T=s.getEntry(e.collectionKeyFor(F,e.closedCollection))?.data?.items??[],I=yr(D,T),M=a.get(e.collectionKeyFor(F,e.openCollection));return!M||M.size===0?I:yr(I,[...M.values()])},b=(F,D,T)=>{const I=di(F,D),M=t.get().filtersByScope[I]??e.defaultFilters;t.set(G=>({filtersByScope:{...G.filtersByScope,[I]:{...M,...T}}}))},g=(F,D)=>{const T=di(F,D);t.set(I=>({filtersByScope:{...I.filtersByScope,[T]:{...e.defaultFilters}}}))},p=(F,D,T)=>{const I=hn(F);I&&t.set(M=>({selectionByDirectory:{...M.selectionByDirectory,[I]:{repo:D,number:T}}}))},h=(F,D,T,I)=>{const M=e.collectionKeyFor(D,T);return s.ensure(M,async()=>{const G=await e.fetchList(I,F,D,e.buildCollectionQuery(T));return{items:G.items,nextCursor:G.nextCursor,fetchedAt:G.fetchedAt}})},y=(F,D,T)=>{const I=e.collectionKeyFor(D,e.closedCollection);s.getEntry(I)?.data||s.getEntry(I)?.isLoading||h(F,D,e.closedCollection,T).catch(()=>null)},x=async(F,D,T,I)=>{const M=T==="open"||T==="both",G=T==="closed"||T==="both",W=[],L=s.getEntry(e.collectionKeyFor(D,e.openCollection)),ae=s.getEntry(e.collectionKeyFor(D,e.closedCollection));M&&(!Ma(L,e.freshWindowMs)||L?.stale)&&W.push(h(F,D,e.openCollection,I)),G&&(!Ma(ae,e.freshWindowMs)||ae?.stale)&&W.push(h(F,D,e.closedCollection,I)),await Promise.all(W.map(J=>J.catch(()=>null))),M&&!s.getEntry(e.collectionKeyFor(D,e.closedCollection))?.data&&y(F,D,I)},k=async(F,D,T,I)=>{const M=e.collectionKeyFor(D,T),G=s.getEntry(M),W=G?.data?.nextCursor??null;if(!W||G?.isLoading)return G;try{const L=await d(`${M}:more`,async()=>{const ae=await e.fetchList(I,F,D,{...e.buildCollectionQuery(T),cursor:W}),J=s.getEntry(M)?.data,le={items:yr(J?.items??[],ae.items),nextCursor:ae.nextCursor,fetchedAt:ae.fetchedAt};return s.refresh(M,async()=>le)});return L.ran?L.result??s.getEntry(M):s.getEntry(M)}catch(L){return s.setError(M,L)??s.getEntry(M)}},v=async(F,D,T,I)=>{const M=T==="both"?[e.openCollection,e.closedCollection]:[T];await Promise.all(M.map(G=>{const W=e.collectionKeyFor(D,G);return s.refresh(W,async()=>{const L=await e.fetchList(I,F,D,e.buildCollectionQuery(G));return{items:L.items,nextCursor:L.nextCursor,fetchedAt:L.fetchedAt}}).catch(()=>null)}))},A=async(F,D,T,I)=>{const M=e.remoteKeyFor(D,T),G=await r.refresh(M,async()=>{const W=await e.fetchList(I,F,D,e.buildRemoteQuery(T));return{items:W.items,nextCursor:W.nextCursor,fetchedAt:W.fetchedAt}});return G.data&&(u(D,G.data.items),f(D)),G},w=async(F,D,T,I)=>{const M=e.remoteKeyFor(D,T),G=r.getEntry(M),W=G?.data?.nextCursor??null;if(!W||G?.isLoading)return G;try{const L=await e.fetchList(I,F,D,e.buildRemoteQuery(T,W)),ae=r.getEntry(M)?.data,J={items:yr(ae?.items??[],L.items),nextCursor:L.nextCursor,fetchedAt:L.fetchedAt},le=await r.refresh(M,async()=>J);return le.data&&(u(D,le.data.items),f(D)),le}catch(L){return r.setError(M,L)??r.getEntry(M)}},j=F=>{for(const D of Object.keys(r.snapshot()))yo(D)===F&&r.remove(D);for(const D of[...a.keys()])yo(D)===F&&a.delete(D)},S=(F,D,T,I)=>{const M=e.detailKeyFor(D,T);return o.refresh(M,async()=>({detail:await e.fetchDetail(I,F,D,T)}))};return{initialState:{filtersByScope:{},selectionByDirectory:{}},resources:{collections:s,remote:r,details:o,comments:i},setFilters:b,resetFilters:g,select:p,ensureCollection:h,ensureCollectionsFresh:x,prefetchClosedCollection:y,loadMoreCollection:k,refreshCollections:v,searchRemote:A,loadMoreRemote:w,dropRemoteForRepo:j,refreshAllForScope:async(F,D,T)=>{await Fn(T,{directory:F,repo:D,kind:e.serverKind}),j(D),await v(F,D,"both",T).catch(()=>null);const I=t.get().selectionByDirectory[hn(F)];I?.repo===D&&typeof I.number=="number"&&await S(F,D,I.number,T).catch(()=>null)},ensureDetail:(F,D,T,I)=>{const M=e.detailKeyFor(D,T);return o.ensure(M,async()=>({detail:await e.fetchDetail(I,F,D,T)}))},refreshDetail:S,ensureComments:(F,D,T,I)=>{const M=e.commentsKeyFor(D,T);return i.ensure(M,async()=>{const G=await e.fetchComments(I,F,D,T);return{comments:G.comments,nextCursor:G.nextCursor,fetchedAt:G.fetchedAt}})},loadMoreComments:async(F,D,T,I)=>{const M=e.commentsKeyFor(D,T),G=i.getEntry(M),W=G?.data?.nextCursor??null;if(!W||G?.isLoading)return G;try{const L=await e.fetchComments(I,F,D,T,W),ae=i.getEntry(M)?.data,J={comments:Lg(ae?.comments??[],L.comments),nextCursor:L.nextCursor,fetchedAt:L.fetchedAt};return await i.refresh(M,async()=>J)}catch(L){return i.setError(M,L)??i.getEntry(M)}},refreshComments:(F,D,T,I)=>{const M=e.commentsKeyFor(D,T);return i.refresh(M,async()=>{const G=await e.fetchComments(I,F,D,T);return{comments:G.comments,nextCursor:G.nextCursor,fetchedAt:G.fetchedAt}})},markCollectionsStale:F=>{s.markStale(e.collectionKeyFor(F,e.openCollection)),s.markStale(e.collectionKeyFor(F,e.closedCollection))},getLocalIndex:m,withSingleFlight:d,resetCore:()=>{s.reset(),r.reset(),a.clear(),o.reset(),i.reset(),c.clear(),t.set({filtersByScope:{},selectionByDirectory:{}})},toStoreError:F=>Og(F,e.errorFallback)}},ui={state:"open",involvement:"all",search:"",sort:"updated"},_g=3e4,zg=100,Ug=50,Mc=(e,t)=>js([e,"pulls-collection",t]),Fc=(e,t)=>js([e,"pulls-remote",t.state,t.involvement,t.q.trim()]),Br=(e,t)=>js([e,"pull-detail",t]),Di=(e,t)=>js([e,"pull-comments",t]),fi=(e,t)=>js([e,"pull-files",t]),hi=(e,t)=>js([e,"pull-checks",t]),$g=e=>({state:e,perPage:zg}),Kg=(e,t)=>({state:e.state,filter:e.involvement,q:e.q.trim()?e.q.trim():void 0,perPage:Ug,...t?{cursor:t}:{}}),_r=e=>`pichamber:pr-merge-method:${e}`,Lc=new Map,Wg=e=>{try{if(typeof localStorage<"u")return localStorage.getItem(e)}catch{}return null},Gg=(e,t)=>{try{if(typeof localStorage<"u"){localStorage.setItem(e,t);return}}catch{}},mv=e=>{if(!e)return null;const t=Wg(_r(e));return t==="merge"||t==="squash"||t==="rebase"?t:Lc.get(_r(e))??null},Hg=(e,t)=>{if(e){Lc.set(_r(e),t);try{Gg(_r(e),t)}catch{}}},qg={set:e=>{typeof e=="function"?jn.setState(t=>{const s={filtersByScope:t.filtersByScope,selectionByDirectory:t.selectionByDirectory};return e(s)}):jn.setState(e)},get:()=>{const e=jn.getState();return{filtersByScope:e.filtersByScope,selectionByDirectory:e.selectionByDirectory}}},Fe=Bg({openCollection:"open",closedCollection:"closed",defaultFilters:ui,freshWindowMs:_g,serverKind:"pulls",errorFallback:"Pull request request failed",collectionKeyFor:Mc,remoteKeyFor:Fc,detailKeyFor:Br,commentsKeyFor:Di,buildCollectionQuery:e=>({...$g(e)}),buildRemoteQuery:(e,t)=>({...Kg(e,t)}),fetchList:async(e,t,s,r)=>{const o=await e.pullsList(t,s,r);return{items:o.items,nextCursor:o.nextCursor,fetchedAt:o.fetchedAt}},fetchDetail:async(e,t,s,r)=>e.pullGet(t,s,r),fetchComments:async(e,t,s,r,o)=>{const i=await e.pullComments(t,s,r,o);return{comments:i.comments,nextCursor:i.nextCursor,fetchedAt:i.fetchedAt}}},qg),Jt=ls(),Ir=ls(),jn=Nn()(Gr((e,t)=>({...Fe.initialState,actionErrorByDetail:{},actingActions:{},setFilters:Fe.setFilters,resetFilters:Fe.resetFilters,selectPullRequest:Fe.select,ensureCollection:Fe.ensureCollection,ensureCollectionsFresh:Fe.ensureCollectionsFresh,prefetchClosedCollection:Fe.prefetchClosedCollection,loadMoreCollection:Fe.loadMoreCollection,refreshCollections:Fe.refreshCollections,searchRemote:Fe.searchRemote,loadMoreRemote:Fe.loadMoreRemote,dropRemoteForRepo:Fe.dropRemoteForRepo,refreshAllForScope:Fe.refreshAllForScope,ensureDetail:Fe.ensureDetail,refreshDetail:Fe.refreshDetail,ensureComments:Fe.ensureComments,loadMoreComments:Fe.loadMoreComments,refreshComments:Fe.refreshComments,ensureFiles:(s,r,o,i)=>{const a=fi(r,o);return Jt.ensure(a,async()=>i.pullFiles(s,r,o))},loadMoreFiles:async(s,r,o,i)=>{const a=fi(r,o),c=Jt.getEntry(a),d=c?.data?.nextCursor??null;if(!d||c?.isLoading)return c;try{const u=await Fe.withSingleFlight(`${a}:more`,async()=>{const f=await i.pullFiles(s,r,o,d),m=Jt.getEntry(a)?.data,b=new Set((m?.files??[]).map(p=>p.filename)),g={repo:f.repo,number:f.number,files:[...m?.files??[],...f.files.filter(p=>!b.has(p.filename))],nextCursor:f.nextCursor,fetchedAt:f.fetchedAt};return Jt.refresh(a,async()=>g)});return u.ran?u.result??Jt.getEntry(a):Jt.getEntry(a)}catch(u){return Jt.setError(a,u)??Jt.getEntry(a)}},ensureChecks:(s,r,o,i)=>{const a=hi(r,o);return Ir.ensure(a,async()=>i.pullChecks(s,r,o,!0))},refreshChecks:(s,r,o,i)=>{const a=hi(r,o);return Ir.refresh(a,async()=>i.pullChecks(s,r,o,!0))},performAction:async(s,r,o,i,a)=>{const c=Os(r,o),d=Br(r,o);if(t().actingActions[c])return{ok:!1,error:{kind:"failed",message:"Action already in progress"}};e(b=>({actingActions:{...b.actingActions,[c]:!0},actionErrorByDetail:{...b.actionErrorByDetail,[c]:null}}));const u=Fe.resources.details.getEntry(d)?.data?.detail??null,f=u?.pr??null,m=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;m&&u&&await Fe.resources.details.refresh(d,async()=>({detail:{...u,pr:m}})).catch(()=>null);try{return await a.pullAction(s,r,o,i),(i==="merge"||i==="squash"||i==="rebase")&&t().setMergeMethod(r,i),await Fn(a,{directory:s,repo:r,kind:"pulls",number:o}),t().dropRemoteForRepo(r),await t().refreshCollections(s,r,"both",a).catch(()=>null),await t().refreshDetail(s,r,o,a).catch(()=>null),await t().refreshChecks(s,r,o,a).catch(()=>null),e(b=>({actingActions:{...b.actingActions,[c]:!1}})),{ok:!0}}catch(b){const g=Fe.toStoreError(b);return u&&await Fe.resources.details.refresh(d,async()=>({detail:u})).catch(()=>null),e(p=>({actingActions:{...p.actingActions,[c]:!1},actionErrorByDetail:{...p.actionErrorByDetail,[c]:g}})),{ok:!1,error:g}}},updateTitleBody:async(s,r,o,i,a)=>{const c=Os(r,o),d=Br(r,o),u=Fe.resources.details.getEntry(d)?.data?.detail??null,f=u?.pr??null,m=f&&(i.title!==void 0||i.body!==void 0)?{...f,title:i.title??f.title,body:i.body??f.body}:null;m&&u&&await Fe.resources.details.refresh(d,async()=>({detail:{...u,pr:m}})).catch(()=>null);try{return await a.pullUpdate(s,r,o,i),await Fn(a,{directory:s,repo:r,kind:"pulls",number:o}),t().dropRemoteForRepo(r),await t().refreshCollections(s,r,"both",a).catch(()=>null),await t().refreshDetail(s,r,o,a).catch(()=>null),{ok:!0}}catch(b){const g=Fe.toStoreError(b);return u&&await Fe.resources.details.refresh(d,async()=>({detail:u})).catch(()=>null),e(p=>({actionErrorByDetail:{...p.actionErrorByDetail,[c]:g}})),{ok:!1,error:g}}},addComment:async(s,r,o,i,a)=>{const c=Os(r,o),d=Di(r,o),u=i.trim(),f={id:-Date.now(),url:"",body:u,author:null,createdAt:new Date().toISOString(),updatedAt:null},m=Fe.resources.comments.getEntry(d)?.data??null;if(m){const b={comments:[...m.comments,f],nextCursor:m.nextCursor,fetchedAt:m.fetchedAt};await Fe.resources.comments.refresh(d,async()=>b).catch(()=>null)}try{return await a.pullComment(s,r,o,u),await Fn(a,{directory:s,repo:r,kind:"pulls",number:o}),await t().refreshComments(s,r,o,a).catch(()=>null),await t().refreshDetail(s,r,o,a).catch(()=>null),{ok:!0}}catch(b){const g=Fe.toStoreError(b);return m?await Fe.resources.comments.refresh(d,async()=>m).catch(()=>null):Fe.resources.comments.remove(d),e(p=>({actionErrorByDetail:{...p.actionErrorByDetail,[c]:g}})),{ok:!1,error:g}}},submitReview:async(s,r,o,i,a)=>{const c=Os(r,o);try{return await a.pullReview(s,r,o,{event:i.event,body:i.body,comments:i.comments}),await Fn(a,{directory:s,repo:r,kind:"pulls",number:o}),await t().refreshDetail(s,r,o,a).catch(()=>null),{ok:!0}}catch(d){const u=Fe.toStoreError(d);return e(f=>({actionErrorByDetail:{...f.actionErrorByDetail,[c]:u}})),{ok:!1,error:u}}},threadAction:async(s,r,o,i,a,c)=>{const d=Os(r,o);try{return await c.pullThread(s,r,o,i,a),await Fn(c,{directory:s,repo:r,kind:"pulls",number:o}),await t().refreshDetail(s,r,o,c).catch(()=>null),{ok:!0}}catch(u){const f=Fe.toStoreError(u);return e(m=>({actionErrorByDetail:{...m.actionErrorByDetail,[d]:f}})),{ok:!1,error:f}}},checkout:async(s,r,o,i,a)=>{try{const c=await a.pullCheckout(s,r,o,i);return{ok:!0,path:c.path,branch:c.branch}}catch(c){return{ok:!1,error:Fe.toStoreError(c)}}},createPullRequest:async(s,r)=>{try{const o=await r.pullCreate(s);return await Fn(r,{directory:s.directory,repo:s.repo,kind:"pulls"}),t().dropRemoteForRepo(s.repo),await t().refreshCollections(s.directory,s.repo,"both",r).catch(()=>null),{ok:!0,number:o.pr.number}}catch(o){return{ok:!1,error:Fe.toStoreError(o)}}},rerunFailedChecks:async(s,r,o,i)=>{try{return await i.checksRerun(s,r,o),{ok:!0}}catch(a){return{ok:!1,error:Fe.toStoreError(a)}}},setMergeMethod:(s,r)=>{Hg(s,r)},notifyAgentTurnComplete:s=>{const r=hn((s||"").trim());if(!r)return;const o=Zt.getState();for(const a of Object.keys(o.results)){const[,c]=a.split(`
|
|
19
|
+
`);if(c!==r)continue;const[,,d]=a.split(`
|
|
20
|
+
`);d&&pt(async()=>{const{getRegisteredRuntimeAPIs:u}=await import("./index-B2v0_mez.js").then(f=>f.cJ);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"&&(Fe.markCollectionsStale(i.repo),pt(async()=>{const{getRegisteredRuntimeAPIs:a}=await import("./index-B2v0_mez.js").then(c=>c.cJ);return{getRegisteredRuntimeAPIs:a}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:a})=>{const c=a()?.github??null;if(c)return t().refreshDetail(r,i.repo,i.number,c)}).catch(()=>{}))},resetForRuntimeSwitch:()=>{Fe.resetCore(),Jt.reset(),Ir.reset(),e({actionErrorByDetail:{},actingActions:{}})}}),{name:"github-pull-requests-store"}));typeof window<"u"&&(ws(()=>{jn.getState().resetForRuntimeSwitch()}),window.addEventListener("focus",()=>{typeof document<"u"&&document.hidden}));const gv=e=>{if(typeof window>"u")return()=>{};let t=new Set,s=!1,r=!1,o=null;return pt(async()=>{const{useNotificationStore:i}=await import("./useAppFontEffects-EcTZ_I_I.js").then(a=>a.eM);return{useNotificationStore:i}},__vite__mapDeps([1,2,3,4,5,6,7,8,9,10,11,12])).then(({useNotificationStore:i})=>{if(r)return;const a=()=>{const c=i.getState().list,d=new Set(c.map(u=>`${u.type}:${u.session??""}:${u.time}`));if(!s){t=d,s=!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&&(jn.getState().notifyAgentTurnComplete(u.directory),e?.(u.directory)))}};a(),o=i.subscribe(a)}).catch(()=>{}),()=>{r=!0,o?.(),o=null}},bv=e=>Fe.getLocalIndex(e),xv=(e,t)=>Fe.getLocalIndex(e).find(s=>s.number===t)??null,yv=(e,t)=>Cs(Fe.resources.collections,e?Mc(e,t):null),wv=(e,t)=>Cs(Fe.resources.remote,e?Fc(e,t):null),vv=(e,t)=>Cs(Fe.resources.details,e!=null&&t!=null?Br(e,t):null),Sv=(e,t)=>Cs(Fe.resources.comments,e!=null&&t!=null?Di(e,t):null),jv=(e,t)=>Cs(Jt,e!=null&&t!=null?fi(e,t):null),Cv=(e,t)=>Cs(Ir,e!=null&&t!=null?hi(e,t):null),kv=(e,t)=>jn(s=>!e||!t?ui:s.filtersByScope[di(e,t)]??ui),Av=e=>jn(t=>e?t.selectionByDirectory[hn(e)]??Ta:Ta),Oc=(e,t,s)=>{jn.getState().selectPullRequest(e,t,s);const r=hn(e);pt(async()=>{const{useUIStore:o}=await import("./index-B2v0_mez.js").then(i=>i.cM);return{useUIStore:o}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({useUIStore:o})=>{o.getState().openContextSurface(r,"pull-requests")}).catch(()=>{}),pt(async()=>{const{useGitHubScopeStore:o}=await import("./useAppFontEffects-EcTZ_I_I.js").then(i=>i.eO);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(()=>{})},Vg=({directory:e,number:t,color:s})=>{const r=Dl(e);return!e||!r?n.jsxs("span",{className:"ml-auto flex-shrink-0 typography-micro font-medium leading-none",style:s?{color:s}:void 0,children:["#",t]}):n.jsxs("button",{type:"button",onClick:o=>{o.stopPropagation(),Oc(e,r,t)},className:"ml-auto flex-shrink-0 rounded typography-micro font-medium leading-none hover:bg-interactive-hover",style:s?{color:s}:void 0,title:`Open PR #${t} in Pull requests`,"aria-label":`Open pull request #${t} in Pull requests`,children:["#",t]})};function Yg({group:e,groupKey:t,isCollapsed:s,onToggleCollapsedGroup:r,normalizedSessionSearchQuery:o,alwaysShowActions:i,groupHeaderRightPadding:a,dragHandleProps:c,groupPrColor:d,groupPrSummary:u,groupActivityIndicator:f,showBranchSubtitle:m,statusLine:b,projectId:g,activeProjectId:p,setActiveProjectIdOnly:h,setActiveMainTab:y,mobileVariant:x,setSessionSwitcherOpen:k,openNewSessionDraft:v}){return n.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":s?`Expand ${e.label}`:`Collapse ${e.label}`,"aria-expanded":!s,children:[n.jsx("div",{ref:c?.setActivatorNodeRef,className:_("min-w-0 flex flex-1 items-start gap-1 overflow-hidden transition-[padding]",a),...c?.listeners??{},children:n.jsxs("div",{className:"min-w-0 flex flex-1 flex-col justify-center gap-0.5 overflow-hidden",children:[n.jsx("p",{className:"typography-ui-label font-normal truncate text-foreground",children:!e.isMain||e.worktree?n.jsxs("span",{className:"flex w-full min-w-0 items-center gap-1.5",children:[n.jsxs("span",{className:"inline-flex size-4 shrink-0 items-center justify-center",children:[n.jsx(R,{name:"git-branch",className:_("size-4 shrink-0",!d&&"text-muted-foreground",i?"hidden":"group-hover/gh:hidden"),style:d?{color:d}:void 0}),n.jsx("span",{className:_("text-muted-foreground size-4 items-center justify-center",i?"inline-flex":"hidden group-hover/gh:inline-flex"),children:s?n.jsx(R,{name:"arrow-right-s",className:"size-4"}):n.jsx(R,{name:"arrow-down-s",className:"size-4"})})]}),n.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal text-muted-foreground",children:li(e.label,o)}),f,u?n.jsx(Vg,{directory:e.directory??null,number:u.number,color:d}):null]}):n.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[n.jsx("span",{className:"min-w-0 truncate",children:li(e.label,o)}),f]})}),m&&b?n.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 leading-tight",children:[n.jsx(R,{name:"git-branch",className:"size-4 flex-shrink-0 text-muted-foreground"}),n.jsx("span",{className:"min-w-0 truncate typography-micro font-medium text-subtle-foreground",children:b.label})]}):null]})}),e.directory?n.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:n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:A=>{A.stopPropagation(),g&&g!==p&&h(g),y("chat"),x&&k(!1),v({selectedProjectId:g,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:n.jsx(R,{name:"add",className:"h-4 w-4"})})}),n.jsx(Ge,{side:"bottom",sideOffset:4,children:n.jsx("p",{children:"New draft session"})})]})}):null]})}const wr=(e,t)=>t?e.sessions.some(s=>dn(s,t)):!1,Qg=(e,t,s)=>e.sessions.some(r=>jc(r,r,t,s,e.directory,e.directory)),Jg=(e,t,s)=>{const r=o=>{const i=o.session.id;return t.get(i)!==s.get(i)?!0:o.children.some(r)};return e.sessions.some(r)},La=(e,t,s)=>{const r=o=>t.has(o.session.id)!==s.has(o.session.id)?!0:o.children.some(r);return e.sessions.some(r)},Xg=(e,t,s)=>{const r=o=>{const i=sr("project",o.session);return t.has(i)!==s.has(i)?!0:o.children.some(r)};return e.sessions.some(r)},Zg=(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&&Qg(t.group,e.pinnedSessionIds,t.pinnedSessionIds)||e.expandedParents!==t.expandedParents&&Xg(t.group,e.expandedParents,t.expandedParents)||e.sessionOrderIndex!==t.sessionOrderIndex&&Jg(t.group,e.sessionOrderIndex,t.sessionOrderIndex)||e.editingId!==t.editingId&&(wr(e.group,e.editingId)||wr(t.group,t.editingId))||e.editTitle!==t.editTitle&&(wr(e.group,e.editingId)||wr(t.group,t.editingId)))return!1;if(e.openSidebarMenuKey!==t.openSidebarMenuKey){const s=Or(e.group.sessions,e.openSidebarMenuKey,"project"),r=Or(t.group.sessions,t.openSidebarMenuKey,"project");if(s||r)return!1}return e.activeActivitySessionIds!==t.activeActivitySessionIds&&La(t.group,e.activeActivitySessionIds,t.activeActivitySessionIds)||e.unreadActivitySessionIds!==t.unreadActivitySessionIds&&La(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};function eb({group:e,sourceGroupNodes:t,hasSessionSearchQuery:s,normalizedSessionSearchQuery:r,compareSessionNodes:o,activeActivitySessionIds:i,unreadActivitySessionIds:a,inputActivitySessionIds:c}){const d=bt(A=>A.foldersMap),u=e.folderScopeKey??Re(e.directory??null),f=l.useMemo(()=>e.folderScopes&&e.folderScopes.length>0?e.folderScopes:u?[{scopeKey:u,directory:e.directory??null}]:[],[u,e.directory,e.folderScopes]),m=l.useMemo(()=>f.flatMap(({scopeKey:A,directory:w})=>(d[A]??[]).map(j=>({folder:j,scopeKey:A,scopeDirectory:w}))),[f,d]),b=l.useMemo(()=>{const A=new Map,w=j=>{j.forEach(S=>{A.set(S.session.id,S),S.children.length>0&&w(S.children)})};return w(t),A},[t]),g=l.useMemo(()=>m.map(({folder:A,scopeKey:w,scopeDirectory:j})=>{const S=Sg(A.sessionIds,b).sort(o);return{folder:A,scopeKey:w,scopeDirectory:j,nodes:S}}),[m,b,o]),p=l.useMemo(()=>{const A=new Map(g.map(C=>[C.folder.id,C])),w=new Map;for(const{folder:C}of g){if(!C.parentId)continue;const E=w.get(C.parentId);E?E.push(C.id):w.set(C.parentId,[C.id])}const j=new Map,S=C=>{const E=j.get(C);if(E!==void 0)return E;const P=A.get(C);if(!P)return j.set(C,!1),!1;const z=w.get(C)??[];if(!s||P.folder.name.toLowerCase().includes(r)||P.nodes.length>0)return j.set(C,!0),!0;const q=z.some(H=>S(H));return j.set(C,q),q};return g.filter(({folder:C})=>S(C.id))},[g,s,r]),h=l.useMemo(()=>new Set(p.flatMap(A=>A.folder.sessionIds)),[p]),y=l.useMemo(()=>t.filter(A=>!h.has(A.session.id)),[t,h]),x=l.useMemo(()=>p.filter(({folder:A})=>!A.parentId),[p]),k=l.useMemo(()=>{const A=new Map;return p.forEach(w=>{if(!w.folder.parentId)return;const j=A.get(w.folder.parentId)??[];j.push(w),A.set(w.folder.parentId,j)}),A},[p]),v=l.useMemo(()=>{const A=new Map(p.map(S=>[S.folder.id,S])),w=new Map,j=(S,C)=>{const E=w.get(S);if(E!==void 0)return E;if(C.has(S))return null;C.add(S);const P=A.get(S);let z=P?Ic(P.nodes,i,a,c):null;for(const K of k.get(S)??[])if(z=Ii(z,j(K.folder.id,C)),z==="input")break;return w.set(S,z),z};return p.forEach(({folder:S})=>j(S.id,new Set)),w},[i,p,k,c,a]);return{folderScopeKey:u,folderScopes:f,allFoldersForGroup:p,rootFolders:x,ungroupedSessions:y,folderActivityStateById:v}}function tb(e){const{group:t,groupKey:s,projectId:r,hideGroupLabel:o,hasSessionSearchQuery:i,normalizedSessionSearchQuery:a,groupSearchDataByGroup:c,visibleSessionCount:d,collapsedGroups:u,hideDirectoryControls:f,collapsedFolderIds:m,toggleFolderCollapse:b,renameFolder:g,deleteFolder:p,showDeletionDialog:h,setDeleteFolderConfirm:y,renderSessionNode:x,showMoreGroupSessions:k,resetGroupSessionLimit:v,mobileVariant:A,alwaysShowActions:w,activeProjectId:j,setActiveProjectIdOnly:S,setActiveMainTab:C,setSessionSwitcherOpen:E,openNewSessionDraft:P,addSessionToFolder:z,createFolderAndStartRename:K,renamingFolderId:q,renameFolderDraft:H,setRenameFolderDraft:F,setRenamingFolderId:D,pinnedSessionIds:T,sessionOrderIndex:I,editingId:M,openSidebarMenuKey:G,activeActivitySessionIds:W,unreadActivitySessionIds:L,onToggleCollapsedGroup:ae,dragHandleProps:J,compactBodyPadding:le=!1}=e,Ie=l.useCallback((Ee,Ye)=>{const Ne=I.get(Ee.session.id),De=I.get(Ye.session.id);if(Ne!==void 0||De!==void 0){if(Ne===void 0)return 1;if(De===void 0)return-1;if(Ne!==De)return Ne-De}return Xu(Ee.session,Ye.session,T,Rl)},[T,I]),Y=i?c.get(t):null,B=i?!1:u.has(s),$=!t.isMain&&!o?Re(t.directory??null):null,X=!t.isMain&&!o&&t.branch?.trim()||null,ee=l.useMemo(()=>$&&X?rr($,X):null,[$,X]),ie=kc(ee);Ac($,X);const ke=ie?`var(--pr-${ie.visualState})`:void 0,pe=l.useContext(Vr)!==null,je=f?10:5,be=Math.max(je,d??je),ze=i?Y?.groupMatches===!0:!1,me=i,Pe=l.useMemo(()=>[...me?Y?.filteredNodes??[]:t.sessions].sort(Ie),[Ie,t.sessions,Y?.filteredNodes,me]),V=Zu(),fe=l.useMemo(()=>new Set(V.map(Ee=>Ee.sessionId)),[V]),{folderScopeKey:xe,folderScopes:te,allFoldersForGroup:re,rootFolders:Be,ungroupedSessions:Ce,folderActivityStateById:Q}=eb({group:t,sourceGroupNodes:Pe,hasSessionSearchQuery:i,normalizedSessionSearchQuery:a,compareSessionNodes:Ie,activeActivitySessionIds:W,unreadActivitySessionIds:L,inputActivitySessionIds:fe}),ve="project",he=l.useMemo(()=>{const Ee=new Set;return Aa(Pe,M,Ee),re.forEach(({nodes:Ye})=>{Aa(Ye,M,Ee)}),Ee},[Pe,re,M]),Se=l.useMemo(()=>{if(!G)return null;const Ee=Or(Pe,G,ve);if(Ee)return Ee;for(const{nodes:Ye}of re){const Ne=Or(Ye,G,ve);if(Ne)return Ne}return null},[G,Pe,re]),qe=l.useCallback(Ee=>{const Ye=new WeakMap,Ne=De=>{Ye.set(De,oi(De));for(const He of De.children)Ne(He)};return Ee.forEach(Ne),Ye},[]),Ue=l.useMemo(()=>qe(Pe),[qe,Pe]),U=l.useMemo(()=>{const Ee=new WeakMap;return re.forEach(({nodes:Ye})=>{Ye.forEach(Ne=>Ee.set(Ne,oi(Ne)))}),Ee},[re]),ge=l.useCallback(Ee=>Ue.get(Ee)??U.get(Ee)??"",[Ue,U]),se=l.useCallback(Ee=>({subtreeContainsEditing:he,menuOpenSessionId:Se,nodeStructureKey:ge(Ee)}),[he,Se,ge]),_e=Ce.length,st=pe||i?Ce:Ce.slice(0,be),mt=_e-st.length,Xe=!pe&&!i&&_e>je&&mt===0;if(i&&!ze&&Be.length===0&&Ce.length===0)return null;const Yt=!t.isMain&&!!t.branch,gt=t.branch&&Nh(t.branch,t.label)?{label:t.branch,color:null}:null,It=B?Ic(Pe,W,L,fe):null,nn=It?n.jsx(vc,{state:It,activeLabel:"Session active",unreadLabel:"Unread updates",inputLabel:"Needs input"}):null,Qe=(Ee,Ye)=>{const{folder:Ne,scopeKey:De,scopeDirectory:He,nodes:ft}=Ee,sn=i?!1:m.has(Ne.id);return n.jsx(yg,{folderId:Ne.id,children:(Lt,Ot)=>n.jsx(bg,{folder:Ne,displayName:Ye,sessions:ft,isCollapsed:sn,collapsedActivityState:sn?Q.get(Ne.id)??null:null,onToggle:()=>b(Ne.id),onRename:Ve=>{g(De,Ne.id,Ve)},onDelete:()=>{if(!h){p(De,Ne.id);return}const Ve=re.filter(({folder:In})=>In.parentId===Ne.id).length,rn=ft.length;y({scopeKey:De,folderId:Ne.id,folderName:Ne.name,subFolderCount:Ve,sessionCount:rn})},renderSessionNode:x,getRenderExtras:ge?Ve=>({subtreeContainsEditing:he,menuOpenSessionId:Se,nodeStructureKey:ge(Ve),childRenderExtrasFor:se}):void 0,groupDirectory:He??t.directory,projectId:r,mobileVariant:A,alwaysShowActions:w,isRenaming:q===Ne.id,renameDraft:q===Ne.id?H:void 0,onRenameDraftChange:Ve=>F(Ve),onRenameSave:()=>{const Ve=H.trim();Ve&&g(De,Ne.id,Ve),D(null),F("")},onRenameCancel:()=>{D(null),F("")},droppableRef:Lt,isDropTarget:Ot,depth:0,onNewSession:()=>{r&&r!==j&&S(r),C("chat"),A&&E(!1),P({selectedProjectId:r,directoryOverride:He??t.directory,targetFolderId:Ne.id})},hideActions:!1})},Ne.id)},Mt=()=>{const Ee=new Map;for(const De of re){const He=De.folder.parentId;if(!He)continue;const ft=Ee.get(He);ft?ft.push(De):Ee.set(He,[De])}const Ye=[],Ne=(De,He)=>{const ft=He?`${He} / ${De.folder.name}`:De.folder.name;Ye.push(Qe(De,ft)),!(!i&&m.has(De.folder.id))&&(Ee.get(De.folder.id)??[]).forEach(Lt=>Ne(Lt,ft))};return Be.forEach(De=>Ne(De,"")),Ye},Ft=w?"pr-7":"pr-2 group-hover/gh:pr-7 group-focus-within/gh:pr-7",Ct=n.jsxs(wg,{scopeKey:te[0]?.scopeKey??xe,hasFolders:re.length>0,onSessionDroppedOnFolder:(Ee,Ye)=>{const Ne=re.find(({folder:He})=>He.id===Ye);if(!Ne)return;const De=bt.getState();for(const{scopeKey:He}of te)He!==Ne.scopeKey&&De.getSessionFolderId(He,Ee)&&De.removeSessionFromFolder(He,Ee);z(Ne.scopeKey,Ye,Ee)},children:[Mt(),st.map(Ee=>n.jsx(l.Fragment,{children:x(Ee,0,t.directory,r,!1,void 0,"project",{subtreeContainsEditing:he,menuOpenSessionId:Se,nodeStructureKey:ge(Ee),childRenderExtrasFor:se})},Ee.session.id)),_e===0&&re.length===0&&!pe?n.jsx(Gt,{icon:"chat-new",onClick:()=>{P({selectedProjectId:r,directoryOverride:t.directory})},children:"New session"}):null,mt>0?n.jsx(Gt,{icon:"arrow-down-s",onClick:()=>k(s,st.length),children:mt===1?"Show 1 more session":`Show ${mt} more sessions`}):null,Xe?n.jsx(Gt,{icon:"arrow-up-s",onClick:()=>v(s),children:"Show fewer sessions"}):null]});return o?n.jsx("div",{className:"oc-group",children:n.jsx("div",{className:"oc-group-body",children:Ct})}):n.jsxs("div",{className:"oc-group",children:[n.jsx(Yg,{group:t,groupKey:s,isCollapsed:B,onToggleCollapsedGroup:ae,normalizedSessionSearchQuery:a,alwaysShowActions:w,groupHeaderRightPadding:Ft,dragHandleProps:J,groupPrColor:ke,groupPrSummary:ie,groupActivityIndicator:nn,showBranchSubtitle:Yt,statusLine:gt,projectId:r,activeProjectId:j,setActiveProjectIdOnly:S,setActiveMainTab:C,mobileVariant:A,setSessionSwitcherOpen:E,openNewSessionDraft:P}),B?null:n.jsx("div",{className:"oc-group-body",children:Ct})]})}const nb=l.memo(tb,Zg);function sb(e){const{hideDirectoryControls:t,handleOpenDirectoryDialog:s,onOpenArchive:r,onOpenSettings:o,onOpenInstances:i,instanceLabel:a,onOpenUpdate:c,headerActionIconClass:d,headerActionButtonClass:u,isSessionSearchOpen:f,setIsSessionSearchOpen:m,sessionSearchInputRef:b,sessionSearchQuery:g,setSessionSearchQuery:p,hasSessionSearchQuery:h,searchMatchCount:y,selectionModeEnabled:x,onToggleSelectionMode:k,mobileVariant:v=!1,onClose:A}=e;if(t)return null;const w=_(u,"text-muted-foreground hover:text-foreground",!v&&"hover:bg-transparent"),j=o?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:o,className:w,"aria-label":"Settings",children:n.jsx(R,{name:"settings-3",className:d})})}),n.jsx(Ge,{side:"bottom",sideOffset:4,children:n.jsx("p",{children:"Settings"})})]}):null,S=c?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:c,className:w,"aria-label":"Update",children:n.jsx(R,{name:"download",className:d})})}),n.jsx(Ge,{side:"bottom",sideOffset:4,children:n.jsx("p",{children:"Update"})})]}):null;return n.jsx("div",{className:_("select-none flex-shrink-0",v?"px-2":"px-2 py-1"),children:n.jsxs("div",{className:_("flex flex-col",v?"gap-0":"h-auto min-h-8 gap-1"),children:[n.jsxs("div",{className:_("flex items-center justify-between",v?"h-[var(--oc-header-height,56px)] gap-1":"min-h-8 gap-2 px-2"),children:[n.jsxs("div",{className:_("flex min-w-0 items-center",v?"gap-1 overflow-x-auto":"gap-1.5"),"data-no-drawer-swipe":v?"true":void 0,children:[v?n.jsx("h2",{className:"truncate pl-2 typography-ui-header font-semibold text-foreground",children:"Sessions"}):n.jsxs(n.Fragment,{children:[j,S]}),!v&&i?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:i,className:w,"aria-label":a?`Servers: ${a}`:"Servers",children:n.jsx(R,{name:"server",className:d})})}),n.jsx(Ge,{side:"bottom",sideOffset:4,children:n.jsx("p",{children:a||"Servers"})})]}):null,v?null:n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:s,className:w,"aria-label":"Add folder",children:n.jsx(R,{name:"folder-add",className:d})})}),n.jsx(Ge,{side:"bottom",sideOffset:4,children:n.jsx("p",{children:"Add folder"})})]}),v?null:n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:r,className:w,"aria-label":"Archive",children:n.jsx(R,{name:"archive",className:d})})}),n.jsx(Ge,{side:"bottom",sideOffset:4,children:n.jsx("p",{children:"Archive"})})]})]}),n.jsxs("div",{className:_("flex shrink-0 items-center",v?"gap-1":"gap-1.5"),children:[v?n.jsxs(n.Fragment,{children:[j,S]}):null,n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:()=>m(C=>!C),className:w,"aria-label":"Search sessions","aria-expanded":f,children:n.jsx(R,{name:"search",className:d})})}),n.jsx(Ge,{side:"bottom",sideOffset:4,children:n.jsx("p",{children:"Search sessions"})})]}),n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:k,className:_(w,x&&"bg-interactive-hover text-primary"),"aria-label":x?"Exit selection":"Select sessions","aria-pressed":x,children:n.jsx(R,{name:"checkbox-multiple",className:d})})}),n.jsx(Ge,{side:"bottom",sideOffset:4,children:n.jsx("p",{children:x?"Exit selection":"Select sessions"})})]}),v&&A?n.jsx("button",{type:"button",onClick:A,className:w,"aria-label":"Close sessions",children:n.jsx(R,{name:"close",className:d})}):null]})]}),f?n.jsxs("div",{className:_(v?"pb-2":"pb-1"),children:[n.jsx("div",{className:"mb-1 flex items-center justify-between px-0.5 typography-micro text-subtle-foreground",children:h?n.jsx("span",{children:y===1?`${y} match`:`${y} matches`}):n.jsx("span",{})}),n.jsxs("div",{className:"relative",children:[n.jsx(R,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),n.jsx("input",{ref:b,value:g,onChange:C=>p(C.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:C=>{C.key==="Escape"&&(C.stopPropagation(),h?p(""):m(!1))}}),g.length>0?n.jsx("button",{type:"button",onClick:()=>p(""),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:n.jsx(R,{name:"close",className:"h-3.5 w-3.5"})}):null]})]}):null]})})}const wo="0.75rem";function rb(e){const t=ue(o=>o.toggleSidebar),s=ue(o=>o.shortcutOverrides),r=ki(Pr("toggle_sidebar",s));return n.jsxs("div",{className:"app-region-drag select-none flex h-[var(--oc-header-height,3rem)] shrink-0 items-center pr-3",children:[n.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:`var(--oc-titlebar-left-inset, ${wo})`}}),n.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, ${wo})))`}}),n.jsxs("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center gap-1.5",children:[n.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(${Ih} - max(var(--oc-titlebar-left-inset, ${wo}), var(--oc-titlebar-overlay-width, 0px))))`},children:[n.jsx(R,{name:"chat-new",className:_(kr,"text-current")}),n.jsx("span",{className:Yl,children:"New session"})]}),e.showSidebarToggle?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.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:n.jsx(R,{name:"layout-left",className:"size-4"})})}),n.jsx(Ge,{children:n.jsx("p",{children:`Hide sessions (${r})`})})]}):null]})]})}function Qr({...e}){return n.jsx(gl,{...e})}function Jr({...e}){return n.jsx(bl,{...e})}function Xr({className:e,positionerClassName:t,children:s,style:r,...o}){return n.jsx(Fo,{children:n.jsx(Lo,{className:_("app-region-no-drag z-50",t),children:n.jsx(Oo,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...r},className:_($o,e),...o,children:s})})})}function _n({className:e,...t}){return n.jsx(xl,{className:_(Pl,e),...t})}function Bc({className:e,...t}){return n.jsx(yl,{className:_(Tl,e),...t})}const _c=500,ob=({projectId:e,worktree:t,isSelected:s,hasActive:r,onSelect:o,onClose:i,mobileVariant:a=!1})=>{const[c,d]=l.useState(!1),u=l.useRef(null),f=t.branch||(t.detached?"Detached HEAD":t.name),m=l.useCallback(()=>{u.current!==null&&(window.clearTimeout(u.current),u.current=null)},[]);l.useEffect(()=>()=>m(),[m]);const b=l.useCallback(()=>{m(),u.current=window.setTimeout(()=>{u.current=null,d(!0)},_c)},[m]);return n.jsxs(Qr,{open:c,onOpenChange:d,children:[n.jsxs(Jr,{render:n.jsx("button",{type:"button",onClick:()=>{c||o()},onTouchStart:b,onTouchMove:m,onTouchEnd:m,onTouchCancel:m,style:{touchAction:"manipulation"},className:_(zr(a,s),"pl-6"),"aria-pressed":s,title:t.path}),children:[n.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[n.jsx(R,{name:"git-branch",className:_(Un(a),"text-muted-foreground")}),t.branch?n.jsx(Ks,{value:f,showTitle:!1,className:"typography-ui-label font-normal"}):n.jsx("span",{className:bs(a),children:f})]}),n.jsx("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:r?n.jsx(Cn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null})]}),n.jsx(Xr,{className:"min-w-[160px]",children:n.jsxs(_n,{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:[n.jsx(R,{name:"close",className:"mr-2 h-3.5 w-3.5"}),n.jsx("span",{children:"Close worktree"})]})})]})},zr=(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"),ib=({project:e,label:t,isSelected:s,hasActive:r,hasWorktrees:o,worktreeError:i,isExpanded:a,canDrag:c,onSelect:d,onOpenProjectEditDialog:u,onRemoveProject:f,mobileVariant:m=!1})=>{const{listeners:b,setNodeRef:g,transform:p,transition:h,isDragging:y}=vi({id:e.id,disabled:!c}),[x,k]=l.useState(!1),v=l.useRef(null),A=l.useCallback(()=>{v.current!==null&&(window.clearTimeout(v.current),v.current=null)},[]);l.useEffect(()=>()=>A(),[A]);const w=l.useCallback(()=>{A(),v.current=window.setTimeout(()=>{v.current=null,k(!0)},_c)},[A]);return n.jsx("div",{ref:g,style:{transform:Si.Translate.toString(p),transition:h},className:_(y&&"opacity-60"),children:n.jsxs(Qr,{open:x,onOpenChange:k,children:[n.jsxs(Jr,{render:n.jsx("button",{type:"button",onClick:()=>{x||d()},onTouchStart:w,onTouchMove:A,onTouchEnd:A,onTouchCancel:A,style:{touchAction:"manipulation"},className:zr(m,s),"aria-pressed":s}),children:[n.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[n.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?b:{},children:n.jsx(Ci,{directory:e.normalizedPath,label:t,className:Un(m)})}),n.jsx("span",{className:bs(m),children:t})]}),n.jsxs("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:[r?n.jsx(Cn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null,i?n.jsx("span",{title:i,"aria-label":"Worktree discovery failed",children:n.jsx(R,{name:"error-warning",className:"size-4 text-[var(--status-warning)]"})}):null,o?n.jsx(R,{name:a?"arrow-down-s":"arrow-right-s",className:"size-4 text-muted-foreground"}):null]})]}),n.jsxs(Xr,{className:"min-w-[160px]",children:[n.jsxs(_n,{onClick:()=>u(e.id),children:[n.jsx(R,{name:"edit",className:"mr-2 h-3.5 w-3.5"}),n.jsx("span",{children:"Edit folder"})]}),n.jsx(Bc,{}),n.jsxs(_n,{onClick:()=>f(e.id),className:"text-destructive focus:text-destructive",children:[n.jsx(R,{name:"close",className:"mr-2 h-3.5 w-3.5"}),n.jsx("span",{children:"Close folder"})]})]})]})})},ab=({projects:e,selectedProjectId:t,selectedWorktreePath:s=null,worktreesByProject:r=new Map,worktreeErrorsByProject:o=new Map,onSelectProject:i,onSelectWorktree:a,onCloseWorktree:c,onOpenDirectoryDialog:d,onOpenProjectEditDialog:u,onRemoveProject:f,hasActiveSessionByProject:m,activeDirectoriesByProject:b,homeDirectory:g,className:p,mobileVariant:h=!1})=>{const y=t===null,x=dt(w=>w.reorderProjects),k=e.length>1,v=Kr(hs(jl,{activationConstraint:{distance:8}}),hs(Sl,{activationConstraint:{delay:200,tolerance:6}})),A=l.useCallback(w=>{const{active:j,over:S}=w;if(!S||j.id===S.id)return;const C=dt.getState().projects,E=C.findIndex(z=>z.id===j.id),P=C.findIndex(z=>z.id===S.id);E<0||P<0||x(E,P)},[x]);return n.jsxs("div",{className:_("select-none px-2 pt-1 pb-2 border-b border-border/40 space-y-0.5",p),children:[n.jsx("button",{type:"button",onClick:()=>i(null),className:zr(h,y),"aria-pressed":y,children:n.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[n.jsx(R,{name:"chat-history",className:Un(h)}),n.jsx("span",{className:bs(h),children:"All sessions"})]})}),n.jsx(Wr,{sensors:v,collisionDetection:wi,onDragEnd:A,children:n.jsx(wl,{items:e.map(w=>w.id),strategy:vl,children:e.map(w=>{const j=t===w.id,S=j&&!s,C=r.get(w.normalizedPath)??[],E=vs(w,g),P=b?.get(w.id),z=Re(w.normalizedPath)?.toLowerCase()??"",K=z?P?.has(z)??!1:!1,q=(P?.size??0)>0,H=m?.(w.id)??!1,F=b?j?K:q:H;return n.jsxs(l.Fragment,{children:[n.jsx(ib,{project:w,label:E,isSelected:S,hasActive:F,hasWorktrees:C.length>0,worktreeError:o.get(w.normalizedPath),isExpanded:j,canDrag:k,onSelect:()=>i(w.id),onOpenProjectEditDialog:u,onRemoveProject:f,mobileVariant:h}),j?C.map(D=>{const T=s===D.path,I=Re(D.path)?.toLowerCase()??"",M=I?P?.has(I)??!1:!1,G=b?M:!1;return n.jsx(ob,{projectId:w.id,worktree:D,isSelected:T,hasActive:G,onSelect:()=>a?.(w.id,D.path),onClose:c,mobileVariant:h},D.path)}):null]},w.id)})})}),n.jsxs("button",{type:"button",onClick:d,className:zr(h,!1),children:[n.jsx(R,{name:"add",className:Un(h)}),n.jsx("span",{className:bs(h),children:"Add folder"})]})]})},vo="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 lb({onOpenSettings:e,onOpenShortcuts:t,onOpenAbout:s,onOpenUpdate:r,showRuntimeButtons:o=!0,showUpdateButton:i=!0}){return!o&&!i?null:n.jsxs("div",{className:"flex shrink-0 items-center justify-start gap-1 px-3 py-2",children:[o?n.jsxs(n.Fragment,{children:[n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:e,className:vo,"aria-label":"Settings",children:n.jsx(R,{name:"settings-3",className:"size-4"})})}),n.jsx(Ge,{side:"top",sideOffset:4,children:n.jsx("p",{children:"Settings"})})]}),n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:t,className:vo,"aria-label":"Shortcuts",children:n.jsx(R,{name:"command",className:"size-4"})})}),n.jsx(Ge,{side:"top",sideOffset:4,children:n.jsx("p",{children:"Shortcuts"})})]}),n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:s,className:vo,"aria-label":"About PiChamber",children:n.jsx(R,{name:"information",className:"size-4"})})}),n.jsx(Ge,{side:"top",sideOffset:4,children:n.jsx("p",{children:"About PiChamber"})})]})]}):null,i?n.jsx(Ae,{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 Oa="inline-flex size-6 items-center justify-center rounded-md text-muted-foreground transition-[opacity,background-color,color] hover:bg-interactive-active hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",Ba="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",zc=({projectLabel:e,projectPath:t=null,mobileVariant:s=!1})=>{const r=Un(s),o=bs(s);return n.jsxs(n.Fragment,{children:[n.jsx("span",{className:_("inline-flex shrink-0 items-center justify-center",r),children:t?n.jsx(Ci,{directory:t,label:e,className:r}):n.jsx(R,{name:"folder",className:_(r,"text-subtle-foreground")})}),n.jsx("span",{className:_(o,"font-medium text-foreground"),children:e})]})},Uc=({isCollapsed:e,mobileVariant:t=!1,className:s})=>n.jsx("span",{className:_("ml-auto inline-flex shrink-0 items-center text-muted-foreground",s),children:n.jsx(R,{name:e?"arrow-right-s":"arrow-down-s",className:Un(t)})}),cb=({id:e,disabled:t=!1,projectLabel:s,projectPath:r=null,projectDescription:o,isCollapsed:i,hideDirectoryControls:a,mobileVariant:c,alwaysShowActions:d,stickyHeader:u=!1,onToggle:f,onNewSession:m,onRenameStart:b,onClose:g,children:p,showCreateButtons:h=!0,hideHeader:y=!1,openSidebarMenuKey:x,setOpenSidebarMenuKey:k,statusIndicator:v=null,sessionCount:A=null,isEmpty:w=!1})=>{const{listeners:j,setNodeRef:S,transform:C,transition:E,isDragging:P}=vi({id:e,disabled:t}),z=l.useRef(!1),K=`project:${e}`,q=x===K,[H,F]=l.useState(!1),D=u&&!i,T=!a&&!d,I=l.useCallback(le=>{le&&F(!1),k(le?K:null)},[K,k]),M=le=>n.jsxs(n.Fragment,{children:[h&&!a&&m&&n.jsxs(le,{onClick:m,children:[n.jsx(R,{name:"add",className:"mr-1.5 h-4 w-4"}),"New session"]}),n.jsxs(le,{onClick:b,children:[n.jsx(R,{name:"pencil-ai",className:"mr-1.5 h-4 w-4"}),"Edit folder"]}),n.jsxs(le,{onClick:g,className:"text-destructive focus:text-destructive",children:[n.jsx(R,{name:"close",className:"mr-1.5 h-4 w-4"}),"Close folder"]})]}),G=l.useCallback(le=>{le.stopPropagation()},[]),W=l.useCallback(le=>{le.stopPropagation()},[]),L=l.useCallback(le=>{le.stopPropagation()},[]),ae=l.useCallback(le=>{(le.button===2||le.button===0&&le.ctrlKey)&&(z.current=!0)},[]),J=l.useCallback(le=>{if(le.currentTarget.blur(),z.current){z.current=!1;return}f()},[f]);return n.jsxs("div",{ref:S,style:{transform:Si.Translate.toString(C),transition:E},className:_("relative",P&&"opacity-60"),children:[y?null:n.jsxs(Qr,{open:H,onOpenChange:F,children:[n.jsxs(Jr,{render:n.jsx("div",{className:_("text-left group/project select-none",D&&"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":D?"true":void 0,onContextMenu:le=>{a||P||(le.preventDefault(),F(!0))}}),children:[n.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:[n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsxs("button",{type:"button","aria-expanded":!i,style:{touchAction:"manipulation"},onMouseDown:ae,onClick:J,...j,className:_(Yr,"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:[n.jsx(zc,{id:e,projectLabel:s,projectPath:r,mobileVariant:c}),A?n.jsx("span",{className:"shrink-0 typography-micro text-subtle-foreground tabular-nums","aria-label":A===1?"1 session":`${A} sessions`,children:A}):null,v?n.jsx("span",{className:"ml-1 inline-flex flex-shrink-0 items-center",children:v}):null,n.jsx(Uc,{isCollapsed:i,mobileVariant:c,className:_("transition-[padding]",w&&"invisible",T&&"group-hover/project:pl-14 group-focus-within/project:pl-14","pl-2")})]})}),d?null:n.jsx(Ge,{side:"right",sideOffset:8,children:o})]}),T?n.jsxs("div",{className:_("absolute top-1/2 z-10 flex -translate-y-1/2 items-center gap-0.5",w?"right-2":"right-7"),children:[h&&m?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:le=>{le.stopPropagation(),m()},className:_(Oa,Ba),"aria-label":"New session",children:n.jsx(R,{name:"add",className:"size-4"})})}),n.jsx(Ge,{side:"bottom",sideOffset:4,children:n.jsx("p",{children:"New session"})})]}):null,n.jsxs(Ht,{open:q,onOpenChange:I,children:[n.jsx(qt,{asChild:!0,children:n.jsx("button",{type:"button",className:_(Oa,q?"opacity-100 pointer-events-auto bg-interactive-active text-foreground":Ba),"aria-label":"Folder menu",onPointerDown:W,onMouseDown:L,onClick:G,children:n.jsx(R,{name:"more-fill",className:"size-4"})})}),n.jsx(Vt,{align:"end",className:"min-w-[180px]",children:M(ut)})]})]}):null]}),D?n.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]}),n.jsx(Xr,{className:"min-w-[180px]",children:M(_n)})]}),p]})},db=({id:e,disabled:t=!1,children:s})=>{const{listeners:r,setNodeRef:o,setActivatorNodeRef:i,transform:a,transition:c,isDragging:d}=vi({id:e,disabled:t}),u=l.useMemo(()=>({listeners:r,setActivatorNodeRef:i}),[r,i]);return n.jsx("div",{ref:o,style:{transform:Si.Transform.toString(a),transition:c},className:_("space-y-0.5 rounded-md",d&&"opacity-50"),children:typeof s=="function"?s(u):s})};l.memo(db);const ub=e=>e.session.time?.updated||e.session.time?.created||0,fb=(e,t)=>{const s={pinned:[],active:[],working:[],snoozed:[]},r=new Map,o=new Set;for(const a of e){const c=a.node.session.id,d=t.entries[c],u={entry:d,pinned:a.isPinned,working:t.working.has(c),needsInput:t.needsInput.has(c),updatedAt:ub(a.node),now:t.now,workingShelf:t.workingShelf},f=ef(u);r.set(c,f),f!=="snoozed"&&tf(d,t.now)&&o.add(c);const m=f==="snoozed"?-(d?.snoozedUntil??0):nf(u);s[f].push({item:a,key:m})}const i=a=>s[a].sort((c,d)=>d.key-c.key).map(({item:c})=>c);return{pinned:i("pinned"),active:i("active"),working:i("working"),snoozed:i("snoozed"),sectionById:r,wokeIds:o}},hb=(e,t)=>{const s=(r,o)=>r.length===o.length&&r.every((i,a)=>i===o[a]);if(e.wokeIds.size!==t.wokeIds.size)return!1;for(const r of e.wokeIds)if(!t.wokeIds.has(r))return!1;return s(e.pinned,t.pinned)&&s(e.active,t.active)&&s(e.working,t.working)&&s(e.snoozed,t.snoozed)},pb=6e4,mb=1500,gb=(e,t)=>{const[s,r]=l.useState(()=>Date.now());return l.useEffect(()=>{if(!e||typeof document>"u")return;let o=null;const i=()=>{r(Date.now()),o===null&&(o=window.setInterval(()=>r(Date.now()),pb))},a=()=>{o!==null&&window.clearInterval(o),o=null},c=()=>document.visibilityState==="visible"?i():a();return c(),document.addEventListener("visibilitychange",c),()=>{a(),document.removeEventListener("visibilitychange",c)}},[e]),l.useEffect(()=>{if(!e||t===null)return;const o=Math.min(Math.max(0,t-Date.now())+50,2**31-1),i=window.setTimeout(()=>r(Date.now()),o);return()=>window.clearTimeout(i)},[e,t]),s},bb=(e,t)=>{const s=er(o=>o.load);l.useEffect(()=>{if(!e)return;s();const o=()=>{document.visibilityState==="visible"&&s()};document.addEventListener("visibilitychange",o);const i=ws(()=>{s()});return()=>{document.removeEventListener("visibilitychange",o),i()}},[e,s]);const r=l.useRef(t);l.useEffect(()=>{const o=r.current;if(r.current=t,!e)return;let i=!1;for(const c of t)if(!o.has(c)){i=!0;break}if(!i)return;const a=window.setTimeout(()=>{s()},mb);return()=>window.clearTimeout(a)},[e,t,s])},xb=(e,{enabled:t,workingShelf:s})=>{const r=er(b=>t?b.entries:yb),{working:o,needsInput:i}=sf(t),a=l.useMemo(()=>rf(r,Date.now()),[r]),c=gb(t,a);bb(t,o);const d=l.useRef(null),u=l.useMemo(()=>{if(!t)return null;const b=fb(e,{entries:r,working:o,needsInput:i,now:c,workingShelf:s});return d.current&&hb(d.current,b)&&d.current.sectionById.size===b.sectionById.size&&[...b.sectionById].every(([p,h])=>d.current.sectionById.get(p)===h)?d.current:b},[t,e,r,o,i,c,s]);d.current=u;const f=Me(b=>b.currentSessionId),m=!!(t&&f&&u?.wokeIds.has(f));return l.useEffect(()=>{!m||!f||er.getState().update(f,{snoozedUntil:null}).catch(b=>console.warn("[session-shelf] could not clear a finished snooze",b))},[m,f]),u},yb=Object.freeze({}),pi=(e,t,s,r)=>{er.getState().update(e,t,s??void 0).catch(o=>{console.warn("[session-shelf] update failed",o),oe.error(r)})},_a={snoozed:"Snoozed",archived:"Archived"},wb=e=>e==="snoozed"||e==="archived",za=10,Ua=20,$c="oc.sidebar.shelves.expanded",vb=()=>{try{const e=as().getItem($c),t=e?JSON.parse(e):[];return Array.isArray(t)?new Set(t.filter(wb)):new Set}catch{return new Set}},Sb=()=>{const[e,t]=l.useState(vb),s=l.useCallback(r=>{t(o=>{const i=new Set(o);i.has(r)?i.delete(r):i.add(r);try{as().setItem($c,JSON.stringify([...i]))}catch{}return i})},[]);return{expanded:e,toggle:s}},$a=({target:e,dragging:t,className:s,children:r})=>{const{setNodeRef:o,isOver:i}=ml({id:`shelf-drop:${e}`,data:{type:"shelf",target:e}});return n.jsx("div",{ref:o,"data-shelf-drop":e,className:_("rounded-xl transition-colors",t&&"outline outline-1 -outline-offset-1 outline-transparent",t&&i&&"bg-interactive-hover outline-[var(--interactive-border)]",s),children:r})},jb=["snoozed","archived"],Ri=({shelfIds:e,shelves:t,renderItem:s,hasSessionSearchQuery:r,mobileVariant:o=!1,className:i})=>{const{expanded:a,toggle:c}=Sb(),d=Me(p=>p.currentSessionId),[u,f]=l.useState(za),m=p=>r||a.has(p),b=e.filter(p=>(t[p]?.length??0)>0);if(b.length===0)return null;const g=(p,h)=>{if(p!=="archived"||r||h.length<=u)return h;const y=h.slice(0,u),x=h.find(k=>k.node.session.id===d);return x&&!y.includes(x)?[...y,x]:y};return n.jsx("div",{className:i,children:b.map(p=>{const h=t[p]??[],y=m(p),x=y?g(p,h):[],k=p==="archived"&&y&&!r?h.length-Math.min(u,h.length):0;return n.jsxs("section",{"aria-label":_a[p],"data-session-shelf":p,children:[n.jsx(us,{label:_a[p],count:h.length,expanded:y,onToggle:()=>{p==="archived"&&f(za),c(p)}}),x.map(s),k>0?n.jsx(Gt,{icon:"arrow-down-s",mobileVariant:o,onClick:()=>f(v=>v+Ua),children:`Show ${Math.min(Ua,k)} more`}):null]},p)})})},Cb=({items:e,shelves:t,archived:s,renderSessionNode:r,hasSessionSearchQuery:o,mobileVariant:i,emptyState:a,searchEmptyState:c})=>{const[d,u]=l.useState(null),f=Kr(hs(hl,{activationConstraint:{distance:8}})),m=l.useMemo(()=>({sectionById:t.sectionById,wokeIds:t.wokeIds}),[t.sectionById,t.wokeIds]),b=A=>n.jsx(l.Fragment,{children:r(A.node,0,A.node.session.directory??A.project.normalizedPath,A.project.id,!1,{projectLabel:A.projectLabel,showFolderLabel:!0,globalSession:A.globalSession},"project")},A.node.session.id),g=A=>{const w=A.active.data.current;if(w?.type!=="session"||!w.sessionId)return;const j=A.active.rect.current.initial?.width;u({sessionId:w.sessionId,title:w.sessionTitle??"Session",width:typeof j=="number"?j:null})},p=A=>{u(null);const w=A.active.data.current,j=A.over?.data.current;if(w?.type!=="session"||!w.sessionId||j?.type!=="shelf"||!j.target)return;const S=w.sessionId,C=w.sessionDirectory??null,E=t.sectionById.get(S);E&&kb(S,C,E,j.target)};if(e.length===0&&s.length===0)return n.jsx(n.Fragment,{children:o?c:a});const h=!!d,y=t.pinned.length>0||h,x=t.working.length>0,k=y||x||t.snoozed.length>0||s.length>0,v=n.jsxs("div",{className:"flex min-h-full flex-1 flex-col","data-sidebar-threads":"",children:[y?n.jsxs($a,{target:"pinned",dragging:h,children:[n.jsx(us,{label:"Pinned",first:!0}),t.pinned.map(b),h&&t.pinned.length===0?n.jsx("div",{className:"px-3 py-2 typography-micro text-subtle-foreground",children:"Drop here to pin"}):null]}):null,x?n.jsxs("section",{"aria-label":"Working","data-session-shelf":"working",children:[n.jsx(us,{label:"Working",first:!y}),t.working.map(b)]}):null,n.jsxs($a,{target:"active",dragging:h,children:[k?n.jsx(us,{label:"Recent",first:!y&&!x}):null,t.active.map(b),t.active.length===0&&!o?n.jsx("div",{className:"px-3 py-1.5 typography-micro text-subtle-foreground",children:h?"Drop here to keep it in the list":t.snoozed.length>0?"Nothing recent. Snoozed sessions are below.":s.length>0?"Nothing recent. Archived sessions are below.":"Nothing recent."}):null]}),n.jsx(Ri,{shelfIds:jb,shelves:{snoozed:t.snoozed,archived:s},renderItem:b,hasSessionSearchQuery:o,mobileVariant:i,className:"mt-auto border-t border-border pt-1"})]});return n.jsx(Vr.Provider,{value:m,children:i?v:n.jsxs(Wr,{sensors:f,collisionDetection:wu,onDragStart:g,onDragCancel:()=>u(null),onDragEnd:p,children:[v,n.jsx(pl,{children:d?n.jsx("div",{style:{width:d.width?`${d.width}px`:"auto"},className:"pointer-events-none flex items-center rounded-xl border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-3 py-2",children:n.jsx("div",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:d.title})}):null})]})})},kb=(e,t,s,r)=>{const o=Xs.getState(),i=or(o.ids,t,e),a=c=>{!t||i===c||o.toggle({directory:t,sessionId:e})};s==="snoozed"&&pi(e,{snoozedUntil:null},t,"Could not wake the session"),a(r==="pinned")},Ab=l.memo(Cb),Nb=[],Ib=["snoozed","archived"],Ka=(e,t)=>{let s=!1;const r=e.groups.map(o=>{const i=o.sessions.filter(a=>!t.has(a.session.id));return i.length===o.sessions.length?o:(s=!0,{...o,sessions:i})});return s?{...e,groups:r}:e},Wa=e=>e.groups.reduce((t,s)=>t+s.sessions.length,0),Ga="pt-0.5 pb-1",Eb=({shelves:e=null,archived:t=Nb,sections:s,homeSection:r,homeDirectory:o,collapsedProjects:i,toggleProject:a,hasSessionSearchQuery:c,activeProjectId:d,hideDirectoryControls:u,mobileVariant:f,alwaysShowActions:m,isInlineEditing:b,stickyFolderHeaders:g,renderGroupSessions:p,renderSessionNode:h,getOrderedGroups:y,renderProjectStatusIndicator:x,setActiveProjectIdOnly:k,setActiveMainTab:v,setSessionSwitcherOpen:A,openNewSessionDraft:w,openProjectEditDialog:j,removeProject:S,reorderProjects:C,openSidebarMenuKey:E,setOpenSidebarMenuKey:P,onOpenDirectoryDialog:z,emptyState:K,searchEmptyState:q})=>{const H=c?null:e,F=l.useMemo(()=>{if(!H)return null;const $=new Set;for(const X of[...H.pinned,...H.snoozed])$.add(X.node.session.id);return $},[H]),D=l.useMemo(()=>F?s.map($=>Ka($,F)):s,[s,F]),T=l.useMemo(()=>F&&r?Ka(r,F):r,[r,F]),I=l.useMemo(()=>e?{sectionById:e.sectionById,wokeIds:e.wokeIds}:null,[e]),M=$=>n.jsx(l.Fragment,{children:h?.($.node,0,$.node.session.directory??$.project.normalizedPath,$.project.id,!1,{projectLabel:$.projectLabel,showFolderLabel:!0,globalSession:$.globalSession},"project")},$.node.session.id),G=Kr(hs(jl,{activationConstraint:{distance:8}}),hs(Sl,{activationConstraint:{delay:200,tolerance:6}})),W=D.length>1&&!c&&!b,L=l.useCallback($=>{if(b||c)return;const{active:X,over:ee}=$;if(!ee||X.id===ee.id)return;const ie=dt.getState().projects,ke=ie.findIndex(je=>je.id===X.id),pe=ie.findIndex(je=>je.id===ee.id);ke<0||pe<0||ke===pe||C(ke,pe)},[b,c,C]),[ae,J]=l.useState(5);l.useEffect(()=>{J(5)},[c]);const le=l.useMemo(()=>T?T.groups.flatMap($=>$.sessions):[],[T]),Ie=c||H?le:le.slice(0,ae),Y=le.length-Ie.length,B=c?!1:i.has("__home__");return D.length===0&&!T&&!(H&&t.length>0)?c?q:K:n.jsx(Vr.Provider,{value:I,children:n.jsxs("div",{className:H?"flex min-h-full flex-1 flex-col gap-1":"space-y-1",children:[H&&H.pinned.length>0?n.jsx(nr.Provider,{value:"card",children:n.jsxs("section",{"aria-label":"Pinned","data-session-shelf":"pinned",children:[n.jsx(us,{label:"Pinned",first:!0}),H.pinned.map(M)]})}):null,n.jsx(Wr,{sensors:G,collisionDetection:wi,onDragEnd:L,children:n.jsx(wl,{items:D.map($=>$.project.id),strategy:vl,children:D.map($=>{const X=$.project,ee=X.id,ie=vs(X,o),ke=Go(X.normalizedPath,o),pe=c?!1:i.has(ee),je=pe?[]:y(ee,$.groups),be=pe?null:je.find(me=>me.isMain)??null,ze=pe?[]:be?je.filter(me=>me.id!==be.id):je;return n.jsx(cb,{id:ee,disabled:!W,projectLabel:ie,projectPath:X.normalizedPath,projectDescription:ke,isCollapsed:pe,hideDirectoryControls:u,mobileVariant:f,alwaysShowActions:m,stickyHeader:g,statusIndicator:pe?x?.(ee,$.groups):null,sessionCount:pe?Wa($):null,isEmpty:!!H&&Wa($)===0,onToggle:()=>a(ee),onNewSession:()=>{ee!==d&&k(ee),v("chat"),f&&A(!1),w({selectedProjectId:ee,directoryOverride:X.normalizedPath})},onRenameStart:()=>j(ee),onClose:()=>S(ee),openSidebarMenuKey:E,setOpenSidebarMenuKey:P,children:pe?null:n.jsxs("div",{className:Ga,children:[be?p(be,`${ee}:${be.id}`,ee,!0,null):null,ze.map(me=>{const Pe=`${ee}:${me.id}`,V=je.length===1;return n.jsx(l.Fragment,{children:p(me,Pe,ee,V,null)},me.id)})]})},ee)})})}),T?n.jsxs("div",{children:[n.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:n.jsxs("button",{type:"button","aria-expanded":!B,style:{touchAction:"manipulation"},onClick:()=>a("__home__"),className:`${Yr} 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:[n.jsx(zc,{id:"__home__",projectLabel:"No folder",mobileVariant:f}),n.jsx(Uc,{isCollapsed:B,mobileVariant:f})]})}),B?null:n.jsxs("div",{className:Ga,children:[Ie.map($=>n.jsx(l.Fragment,{children:h?.($,0,$.session.directory??"~","__home__",!1,{globalSession:!0},"project")},$.session.id)),!c&&Y>0?n.jsx(Gt,{icon:"arrow-down-s",mobileVariant:f,onClick:()=>J($=>$+7),children:Y===1?"Show 1 more session":`Show ${Y} more sessions`}):null,!c&&ae>5&&le.length>5?n.jsx(Gt,{icon:"arrow-up-s",mobileVariant:f,onClick:()=>J(5),children:"Show fewer sessions"}):null]})]}):null,!u&&z?n.jsx(Gt,{icon:"add",mobileVariant:f,onClick:z,children:"Add folder"}):null,H?n.jsx(nr.Provider,{value:"card",children:n.jsx(Ri,{shelfIds:Ib,shelves:{snoozed:H.snoozed,archived:t},renderItem:M,hasSessionSearchQuery:c,mobileVariant:f,className:"mt-auto border-t border-border pt-1"})}):null]})})},Db=l.memo(Eb),Rb=[],Pb=["archived"];function Tb(e){Wt("ui.sidebar_projects_list.render");const t=e.viewMode??"workspace",s=t==="timeline",r=l.useRef(new Map),o=l.useRef(e.getOrderedGroups);o.current!==e.getOrderedGroups&&(o.current=e.getOrderedGroups,r.current.clear());const i=(w,j)=>{const S=r.current,C=S.get(w);if(C&&C.groups===j)return C.ordered;const E=e.getOrderedGroups(w,j);if(S.set(w,{groups:j,ordered:E}),S.size>256){const P=S.keys().next().value;P!==void 0&&S.delete(P)}return E},a=t==="threads",c=t==="folder",d=e.archivedShelfItems??Rb,u=t==="workspace"&&d.length>0&&!e.hasSessionSearchQuery&&!e.showOnlyMainWorkspace,f=!!(e.isAllFoldersView||s||a||c),m=l.useMemo(()=>{if(!f)return[];const w=[],j=e.allFoldersOnlySection?[e.allFoldersOnlySection,...e.sectionsForRender]:e.sectionsForRender;for(const S of j){const C=vs(S.project,e.homeDirectory);for(const E of S.groups)for(const P of E.sessions){const z=e.pinnedSessionIds?or(e.pinnedSessionIds,P.session.directory??S.project.normalizedPath,P.session.id):!1,K=P.session.time?.updated||P.session.time?.created||0;w.push({node:P,project:S.project,projectLabel:C,isPinned:z,timestamp:K,globalSession:S===e.allFoldersOnlySection})}}return w.sort((S,C)=>S.isPinned!==C.isPinned?S.isPinned?-1:1:C.timestamp-S.timestamp),w},[e.allFoldersOnlySection,f,e.sectionsForRender,e.homeDirectory,e.pinnedSessionIds]),b=xb(m,{enabled:a||c,workingShelf:a}),[g,p]=l.useState(30);l.useEffect(()=>{p(30)},[e.hasSessionSearchQuery]);const h=l.useMemo(()=>m.slice(0,g),[m,g]),y=l.useMemo(()=>e.timelineBoundaries??ri(Date.now(),1),[e.timelineBoundaries]),x=l.useMemo(()=>s?Dm(h,{getTimestamp:w=>w.timestamp,isPinned:w=>w.isPinned,boundaries:y}):[],[s,h,y]);if(e.sharedSessionsOnly)return n.jsx(Ln,{useScrollShadow:!0,scrollShadowSize:e.mobileVariant?12:20,outerClassName:"flex-1 min-h-0",className:"pt-2 pb-1",children:n.jsxs("div",{className:"space-y-1 px-2",children:[e.topContent,e.hasSharedSessions?null:e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState]})});const k=(e.isAllFoldersView||s||a||c)&&!!e.allFoldersOnlySection,v=d.length>0&&!e.hasSessionSearchQuery&&!e.showOnlyMainWorkspace;if(e.projectSections.length===0&&!k&&!v)return n.jsx(Ln,{useScrollShadow:!0,scrollShadowSize:e.mobileVariant?12:20,outerClassName:"flex-1 min-h-0",className:"pt-2 pb-1",children:n.jsxs("div",{className:"space-y-1 px-2",children:[e.topContent,e.emptyState]})});if(e.sectionsForRender.length===0&&!k&&!v)return n.jsx(Ln,{useScrollShadow:!0,scrollShadowSize:e.mobileVariant?12:20,outerClassName:"flex-1 min-h-0",className:"pt-2 pb-1",children:n.jsx("div",{className:"space-y-1 px-2",children:e.searchEmptyState})});const A=()=>{const w=m.length-h.length;return n.jsxs(n.Fragment,{children:[w>0?n.jsx(Gt,{icon:"arrow-down-s",onClick:()=>p(j=>j+30),children:w===1?"Show 1 more session":`Show ${w} more sessions`}):null,g>30&&m.length>30?n.jsx(Gt,{icon:"arrow-up-s",onClick:()=>p(30),children:"Show fewer sessions"}):null]})};return n.jsx("div",{className:"relative flex min-h-0 flex-1",children:n.jsx(Ln,{useScrollShadow:!0,hideTopScrollShadow:!0,scrollShadowSize:e.mobileVariant?12:20,outerClassName:"flex-1 min-h-0",className:"oc-sidebar-scroller pt-2 pb-1 [overflow-anchor:none]",children:n.jsxs("div",{className:_((a||c&&b&&!e.hasSessionSearchQuery||u)&&!e.showOnlyMainWorkspace?"flex min-h-full flex-col gap-1 px-2":"space-y-1 px-2"),children:[e.topContent,e.showOnlyMainWorkspace?n.jsx("div",{className:"space-y-[0.6rem]",children:(()=>{const w=e.sectionsForRender.find(C=>C.project.id===e.activeProjectId)??e.sectionsForRender[0];if(!w)return e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState;const j=w.groups.find(C=>C.isMain&&C.sessions.length>0)??w.groups.find(C=>C.sessions.length>0)??w.groups.find(C=>C.isMain)??w.groups[0];if(!j)return n.jsx(Gt,{icon:"chat-new",onClick:()=>e.openNewSessionDraft({selectedProjectId:w.project.id,directoryOverride:w.project.normalizedPath}),children:"New session"});const S=`${w.project.id}:${j.id}`;return n.jsx(l.Fragment,{children:e.renderGroupSessions(j,S,w.project.id,!0,null,!0)},S)})()}):a&&b&&e.renderSessionNode?n.jsx(Ab,{items:m,shelves:b,archived:d,renderSessionNode:e.renderSessionNode,hasSessionSearchQuery:e.hasSessionSearchQuery,mobileVariant:e.mobileVariant,emptyState:e.emptyState,searchEmptyState:e.searchEmptyState}):t==="folder"?n.jsx(nr.Provider,{value:"tree",children:n.jsx(Db,{shelves:b,archived:d,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,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?n.jsx("div",{children:m.length===0?e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState:n.jsxs(n.Fragment,{children:[x.map((w,j)=>{const S=Nm[w.id];return n.jsxs("section",{"aria-label":S,"data-timeline-bucket":w.id,children:[n.jsx(us,{label:S,first:j===0}),w.items.map(({node:C,project:E,projectLabel:P,globalSession:z})=>{const K=C.session.directory??E.normalizedPath;return n.jsx(l.Fragment,{children:e.renderSessionNode(C,0,K,E.id,!1,{projectLabel:P,showFolderLabel:!0,globalSession:z},"project")},C.session.id)})]},w.id)}),A()]})}):e.isAllFoldersView&&e.renderSessionNode?n.jsx("div",{children:m.length===0?e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState:n.jsxs(n.Fragment,{children:[h.map(({node:w,project:j,projectLabel:S,globalSession:C})=>{const E=w.session.directory??j.normalizedPath;return n.jsx(l.Fragment,{children:e.renderSessionNode(w,0,E,j.id,!1,{projectLabel:S,showFolderLabel:!0,globalSession:C},"project")},w.session.id)}),A()]})}):n.jsx("div",{children:e.sectionsForRender.map(w=>{const j=w.project.id,S=i(j,w.groups),C=S.find(P=>P.isMain)??null,E=C?S.filter(P=>P.id!==C.id):S;return n.jsxs("div",{children:[C?e.renderGroupSessions(C,`${j}:${C.id}`,j,!0,null):null,E.map(P=>{const z=`${j}:${P.id}`,K=S.length===1;return n.jsx(l.Fragment,{children:e.renderGroupSessions(P,z,j,K,null)},P.id)})]},j)})}),u&&e.renderSessionNode?n.jsx(Ri,{shelfIds:Pb,shelves:{archived:d},renderItem:w=>n.jsx(l.Fragment,{children:e.renderSessionNode(w.node,0,w.node.session.directory??w.project.normalizedPath,w.project.id,!0,{projectLabel:w.projectLabel,showFolderLabel:!!e.isAllFoldersView,globalSession:w.globalSession},"project")},w.node.session.id),hasSessionSearchQuery:!1,mobileVariant:e.mobileVariant,className:"mt-auto border-t border-border pt-1"}):null]})})})}const Mb=l.memo(Tb);let mi=!1;const gi=new Set;let Ha=!1;function Fb(){for(const e of gi)e()}function Pi(e){mi!==e&&(mi=e,Fb())}function Lb(e){e.key==="Shift"&&Pi(!0)}function Ob(e){e.key==="Shift"&&Pi(!1)}function Bb(){Pi(!1)}function _b(){Ha||typeof window>"u"||(Ha=!0,window.addEventListener("keydown",Lb),window.addEventListener("keyup",Ob),window.addEventListener("blur",Bb))}function zb(e){return _b(),gi.add(e),()=>{gi.delete(e)}}function Ub(){return mi}function $b(){return!1}function Kb(){return Te.useSyncExternalStore(zb,Ub,$b)}const Wb=l.memo(function({archiveLabel:t,deleteLabel:s,buttonSizeClass:r,iconSizeClass:o,onPointerDown:i,onMouseDown:a,onArchive:c,onDelete:d}){const u=Kb(),f=u?s:t,m=b=>{if(u||b.shiftKey){d(b);return}c(b)};return n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.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:a,onClick:m,onKeyDown:b=>b.stopPropagation(),children:n.jsx(R,{name:u?"delete-bin":"archive",className:o})})}),n.jsx(Ge,{side:"left",sideOffset:8,children:f})]})}),Gb=l.memo(function({open:t,onOpenChange:s,descendantCount:r,exportIncludeSubtasks:o,setExportIncludeSubtasks:i,onExport:a}){return n.jsx(en,{open:t,onOpenChange:s,children:n.jsxs(tn,{showCloseButton:!1,className:"max-w-sm gap-5",children:[n.jsxs($n,{children:[n.jsx(mn,{children:"Export Markdown"}),n.jsx(An,{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?`})]}),n.jsxs("label",{className:"flex items-center gap-2 typography-ui-label cursor-pointer",children:[n.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"]}),n.jsxs(ys,{children:[n.jsx(Ae,{type:"button",onClick:()=>s(!1),variant:"outline",size:"sm",children:"Cancel"}),n.jsx(Ae,{type:"button",onClick:()=>{s(!1),a(o)},size:"sm",children:"Export"})]})]})})});function Hb(e,t){const{session:s,sessionTitle:r,sessionDirectory:o,isPinnedSession:i,archivedBucket:a,isElectron:c,pendingRenameRef:d,handleCopySessionId:u,togglePinnedSession:f,handleExportSession:m,handleOpenMiniChatWindow:b,handleDeleteSession:g,handleRestoreSession:p,shelfActions:h}=e,{Item:y,Separator:x,Sub:k,SubTrigger:v,SubContent:A}=t;return n.jsxs(n.Fragment,{children:[n.jsxs(y,{onClick:()=>{d.current={id:s.id,title:r}},className:"[&>svg]:mr-1",children:[n.jsx(R,{name:"pencil-ai",className:"mr-1 h-4 w-4"}),"Rename"]}),n.jsxs(y,{onClick:()=>u(s.id),className:"[&>svg]:mr-1",children:[n.jsx(R,{name:"file-copy",className:"mr-1 h-4 w-4"}),"Copy session ID"]}),n.jsxs(y,{onClick:()=>o&&f({directory:o,sessionId:s.id}),className:"[&>svg]:mr-1",children:[i?n.jsx(R,{name:"unpin",className:"mr-1 h-4 w-4"}):n.jsx(R,{name:"pushpin",className:"mr-1 h-4 w-4"}),i?"Unpin session":"Pin session"]}),h&&!a?n.jsx(n.Fragment,{children:h.section==="snoozed"?n.jsxs(y,{onClick:h.onWake,className:"[&>svg]:mr-1",children:[n.jsx(R,{name:"alarm",className:"mr-1 h-4 w-4"}),"Wake session"]}):n.jsxs(k,{children:[n.jsxs(v,{className:"[&>svg:first-child]:mr-1",children:[n.jsx(R,{name:"alarm",className:"mr-1 h-4 w-4"}),"Snooze"]}),n.jsx(A,{className:"min-w-[200px]",children:of(new Date).map(w=>n.jsxs(y,{onClick:()=>h.onSnooze(w.snoozedUntil),children:[n.jsx("span",{className:"flex-1",children:w.label}),n.jsx("span",{className:"ml-4 typography-micro text-muted-foreground tabular-nums",children:w.whenLabel})]},w.id))})]})}):null,n.jsxs(y,{onClick:()=>{m()},className:"[&>svg]:mr-1",children:[n.jsx(R,{name:"download",className:"mr-1 h-4 w-4"}),"Export Markdown"]}),c?n.jsxs(y,{disabled:!o,onClick:b,className:"[&>svg]:mr-1",children:[n.jsx(R,{name:"window",className:"mr-1 h-4 w-4"}),n.jsx("span",{className:"truncate",children:"Open in Mini Chat window"})]}):null,n.jsx(x,{}),a?null:n.jsxs(y,{className:"[&>svg]:mr-1",onClick:()=>g(s,{archivedBucket:a}),children:[n.jsx(R,{name:"inbox-archive",className:"mr-1 h-4 w-4"}),"Archive"]}),a?n.jsxs(y,{className:"[&>svg]:mr-1",onClick:()=>p(s),children:[n.jsx(R,{name:"inbox-unarchive",className:"mr-1 h-4 w-4"}),"Unarchive"]}):null,n.jsxs(y,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>g(s,{archivedBucket:a,hardDelete:!0}),children:[n.jsx(R,{name:"delete-bin",className:"mr-1 h-4 w-4"}),"Delete"]})]})}function qb(e){const{renamingFolderId:t,editingIdRef:s}=e;return n.jsx(Fo,{children:n.jsx(Lo,{className:"app-region-no-drag z-50",children:n.jsx(Oo,{"data-slot":"dropdown-menu-content",finalFocus:()=>!(t||s.current),style:{color:"var(--surface-elevated-foreground)"},className:_($o,"min-w-[180px]"),children:Hb(e,{Item:({className:r,...o})=>n.jsx(xl,{className:_(Pl,r),...o}),Separator:({className:r,...o})=>n.jsx(yl,{className:_(Tl,r),...o}),Sub:vu,SubTrigger:({className:r,children:o,...i})=>n.jsxs(Su,{className:_(af,r),...i,children:[o,n.jsx(R,{name:"arrow-right-s",className:"ml-auto size-3.5"})]}),SubContent:({className:r,children:o,...i})=>n.jsx(Fo,{children:n.jsx(Lo,{className:"app-region-no-drag z-50",children:n.jsx(Oo,{"data-slot":"dropdown-menu-sub-content",style:{backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},className:_($o,r),...i,children:o})})})})})})})}const So=new WeakMap,Vb=e=>{if(typeof window>"u")return;const t=e.closest("[data-session-row]"),s=t?.closest(".overlay-scrollbar-container");if(!t||!s)return;So.get(s)?.();const r=t.getBoundingClientRect().top;let o=3,i=!1,a=null;const c=()=>{i=!0,a!==null&&window.cancelAnimationFrame(a),a=null,So.delete(s),s.removeEventListener("wheel",c),s.removeEventListener("touchstart",c)},d=()=>{if(i||!t.isConnected||!s.isConnected){c();return}const u=t.getBoundingClientRect().top-r;if(Math.abs(u)>.5&&(s.scrollTop+=u,Wt("ui.sidebar.selection_scroll_anchor_adjustment")),o-=1,o<=0){c();return}a=window.requestAnimationFrame(d)};s.addEventListener("wheel",c,{passive:!0}),s.addEventListener("touchstart",c,{passive:!0}),So.set(s,c),a=window.requestAnimationFrame(d)};function Yb(e){if(typeof e!="number"||!Number.isFinite(e))return"";const t=new Date(e);if(Number.isNaN(t.getTime()))return"";const s=t.toLocaleString("en-US",{month:"short"}),r=t.getDate(),o=t.getFullYear(),i=String(t.getHours()).padStart(2,"0"),a=String(t.getMinutes()).padStart(2,"0");return`${s} ${r}, ${o}, ${i}:${a}`}function Qb(e){if(e.info.role==="user")return"";const t=typeof e.info.providerID=="string"?e.info.providerID.trim():"",s=typeof e.info.modelID=="string"?e.info.modelID.trim():"";return t&&s?`${t}/${s}`:s||t}function Jb(e){const t=e.info.role==="user"?"User":"Assistant",s=Yb(e.info.time?.created),r=Qb(e),o=s&&r?`${s} (${r})`:s||r;return o?`**${t}**
|
|
21
|
+
|
|
22
|
+
*${o}*`:`**${t}**`}function Xb(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join("")}function Kc(e){const t=Jb(e),s=Xb(e.parts).trim();return s?`${t}
|
|
23
|
+
|
|
24
|
+
${s}`:""}function Wc(e,t){const s="#".repeat(Math.min(t+1,6)),r=e.agent?` — ${e.agent}`:"",o=`${s} Sub-agent: ${e.title}${r}
|
|
25
|
+
|
|
26
|
+
---
|
|
27
|
+
|
|
28
|
+
`,i=e.records.map(Kc).filter(Boolean).join(`
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
`),a=[o+i];for(const c of e.children)a.push(Wc(c,t+1));return a.join(`
|
|
33
|
+
|
|
34
|
+
---
|
|
35
|
+
|
|
36
|
+
`)}function Gc(e,t,s){const r=t?.trim()||"Session",o=new Date().toISOString().split("T")[0],i=`# ${r}
|
|
37
|
+
|
|
38
|
+
*Exported on ${o}*
|
|
39
|
+
|
|
40
|
+
---
|
|
41
|
+
|
|
42
|
+
`,a=e.map(Kc).filter(Boolean).join(`
|
|
43
|
+
|
|
44
|
+
---
|
|
45
|
+
|
|
46
|
+
`);let c=i+a;if(s&&s.length>0){const d=s.map(u=>Wc(u,1)).join(`
|
|
47
|
+
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
`);c+=`
|
|
51
|
+
|
|
52
|
+
---
|
|
53
|
+
|
|
54
|
+
`+d}return c}function Hc(e,t){ql({filename:t,mimeType:"text/markdown;charset=utf-8",data:e}).catch(s=>console.warn("[export] Markdown save failed",s))}async function qc(e,t){const s=await rh(t,e);return s||null}async function Zb(e){const t=$l()?.files;if(t?.revealPath)try{return!!(await t.revealPath(e))?.success}catch{return!1}return await oh(e)?!0:Kl(e)}function ex(){return ih()}function Vc(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 Ur=e=>{const t=[],s=r=>{r.children.forEach(o=>{t.push(o.session.id),s(o)})};return s(e),t};function tx(e,t){const[s,r]=l.useState(!1),[o,i]=l.useState(!0),a=e.session,c=l.useMemo(()=>Ur(e).length,[e]),d=l.useCallback(async b=>{const g=[];let p=0;for(const h of b)try{if(!t)throw new Error("Session directory is required for export");const y=[],x=h.session.title||"Untitled Sub-agent",k=typeof h.session.agent=="string"?h.session.agent:void 0,v=await d(h.children);p+=v.skipped,g.push({title:x,agent:k,records:y,children:v.children})}catch{p+=Ur(h).length+1}return{children:g,skipped:p}},[t]),u=l.useCallback(b=>{b<=0||oe.warning(b===1?`Exported session, but skipped ${b} sub-agent task that could not be loaded.`:`Exported session, but skipped ${b} sub-agent tasks that could not be loaded.`)},[]),f=l.useCallback(async b=>{if(!t){oe.error("Nothing to export");return}const g=[];if(g.length===0){oe.error("Nothing to export");return}let p,h=0;if(b&&e.children.length>0){const v=await d(e.children);p=v.children,h=v.skipped}const y=Gc(g,a.title??null,p),x=Vc(a.title??null),k=await qc(y,x);if(k){oe.success("Session exported",{action:{label:ex(),onClick:()=>{Zb(k).then(v=>{v||oe.error("Failed to reveal path")})}}}),u(h);return}Hc(y,x),oe.success("Session exported"),u(h)},[d,e.children,a.title,t,u]),m=l.useCallback(async()=>{if(e.children.length>0){i(!0),r(!0);return}await f(!1)},[f,e.children.length]);return{exportDialogOpen:s,setExportDialogOpen:r,exportIncludeSubtasks:o,setExportIncludeSubtasks:i,descendantCount:c,handleExportSession:m,doExportSession:f}}const nx=(e,t)=>{if(!t)return Array.from(e);const s=[],r=new Set;for(const o of e){r.has(o)||(r.add(o),s.push(o));const i=t.get(o);if(i)for(const a of i)r.has(a)||(r.add(a),s.push(a))}return s},ct=Nn()((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:(s,r,o)=>{const i=t(),a=new Set(i.selectedIds);let c=i.scopeKey,d=i.anchorId;r!==null&&i.scopeKey!==null&&r!==i.scopeKey?(a.clear(),c=r,d=null):c===null&&r!==null&&(c=r);const f=o&&o.length>0?[s,...o]:[s];if(a.has(s)){for(const b of f)a.delete(b);d===s&&(d=null)}else{for(const b of f)a.add(b);d=s}a.size===0?e({selectedIds:a,scopeKey:null,anchorId:null}):e({selectedIds:a,scopeKey:c,anchorId:d})},setRange:(s,r,o,i,a)=>{const c=t();if(o.length===0)return;const d=s&&o.includes(s)?s:o[0],u=o.indexOf(d),f=o.indexOf(r);if(u<0||f<0)return;const[m,b]=u<=f?[u,f]:[f,u],g=o.slice(m,b+1),p=nx(g,a),y=i!==null&&c.scopeKey!==null&&i!==c.scopeKey?new Set:new Set(c.selectedIds);for(const x of p)y.add(x);e({selectedIds:y,scopeKey:i??c.scopeKey,anchorId:d})},replaceAll:(s,r)=>{if(s.length===0){e({selectedIds:new Set,scopeKey:null,anchorId:null});return}e({selectedIds:new Set(s),scopeKey:r,anchorId:s[0]??null})},clear:()=>{e({selectedIds:new Set,scopeKey:null,anchorId:null})},removeMany:s=>{const r=t();if(r.selectedIds.size===0||s.length===0)return;const o=new Set(r.selectedIds);for(const i of s)o.delete(i);o.size!==r.selectedIds.size&&(o.size===0?e({selectedIds:o,scopeKey:null,anchorId:null}):e({selectedIds:o}))}})),qa=e=>Re(e.session.directory??null),sx=(e,t)=>(e?.projectLabel??null)===(t?.projectLabel??null)&&(e?.branchLabel??null)===(t?.branchLabel??null)&&(e?.showFolderLabel??!1)===(t?.showFolderLabel??!1),rx=e=>{if(!e.openSidebarMenuKey)return null;const t=e.renderContext??"project",[s,,...r]=e.openSidebarMenuKey.split(":");return s===t&&r.length>0?r.join(":"):null},vr=e=>e.menuOpenSessionId??rx(e),Sr=(e,t,s)=>t?s.has(e.node.session.id)?!0:dn(e.node,t):!1,bi=(e,t,s,r,o)=>{if(e.session.id!==t.session.id)return!0;const i=o(e);if(s.has(i)!==r.has(i)||e.children.length!==t.children.length)return!0;for(let a=0;a<e.children.length;a+=1)if(bi(e.children[a],t.children[a],s,r,o))return!0;return!1},ox=(e,t)=>e.hasSessionSearchQuery||t.hasSessionSearchQuery?!1:bi(e.node,t.node,e.expandedParents,t.expandedParents,s=>sr(e.renderContext??"project",s.session))||bi(e.node,t.node,e.expandedParents,t.expandedParents,s=>sr(t.renderContext??"project",s.session)),ix=(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||qa(e.node)!==qa(t.node)||!sx(e.secondaryMeta,t.secondaryMeta)||e.pinnedSessionIds!==t.pinnedSessionIds&&jc(e.node,t.node,e.pinnedSessionIds,t.pinnedSessionIds,e.groupDirectory,t.groupDirectory)||e.expandedParents!==t.expandedParents&&ox(e,t)||e.editingId!==t.editingId&&(Sr(e,e.editingId,e.subtreeContainsEditing)||Sr(t,t.editingId,t.subtreeContainsEditing))||e.editTitle!==t.editTitle&&(Sr(e,e.editingId,e.subtreeContainsEditing)||Sr(t,t.editingId,t.subtreeContainsEditing))||e.copiedSessionId!==t.copiedSessionId&&(dn(e.node,e.copiedSessionId)||dn(t.node,t.copiedSessionId)))return!1;if(e.openSidebarMenuKey!==t.openSidebarMenuKey){const s=vr(e),r=vr(t);if(dn(e.node,s)||dn(t.node,r))return!1}if(e.renamingFolderId!==t.renamingFolderId){const s=vr(e),r=vr(t);if(dn(e.node,s)||dn(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 ax({node:e,groupDirectory:t,projectId:s,secondaryMeta:r,pinnedSessionIds:o,expandedParents:i,expansionKey:a,hasSessionSearchQuery:c}){const d=e.session,u=Re(d.directory??null)??Re(t??null),f=Me(me=>me.currentSessionId===d.id),m=Ko(u),b=lf(u),g=dt(l.useCallback(me=>{if(r?.projectLabel||!s)return null;const Pe=me.projects.find(V=>V.id===s);return Pe?vs({label:Pe.label,normalizedPath:Re(Pe.path)??Pe.path},null):null},[s,r?.projectLabel])),p=r?.projectLabel??g,h=dt(l.useCallback(me=>s?me.projects.find(Pe=>Pe.id===s)?.path??null:null,[s])),y=e.worktree,x=r?.branchLabel??y?.branch??(m&&m!=="HEAD"?m:null),k=Re(h),v=Ko(k),w=!!k&&u===k||!!x&&x===v,j=w?null:x,S=!w&&(b===!0||!!(x||y)),C=e.children.length,E=d.agent,P=y?.branch?.trim()||x?.trim()||null,z=Re(y?.path??u),K=l.useMemo(()=>P&&z?rr(z,P):null,[P,z]),q=kc(K);Ac(z,P);const H=q?`var(--pr-${q.visualState})`:void 0,F=l.useMemo(()=>{if(!q)return null;switch(q.visualState){case"merged":return"Merged";case"open":return q.canMerge===!0||q.mergeableState==="clean"||q.checks?.state==="success"?"Ready to merge":"PR open";case"blocked":return q.mergeableState==="dirty"?"Merge conflicts":"Merge blocked";case"draft":return"Draft PR";case"closed":return"Closed";default:return null}},[q]),D=s??u??null,T=ct(me=>me.enabled),I=ct(l.useCallback(me=>me.selectedIds.has(d.id),[d.id])),M=ct(me=>me.toggleSelected),G=ct(me=>me.setRange),L=Ml(d.id)?.type??"idle",ae=L==="busy"||L==="retry",J=cf(d.id,ae),le=un(d,"Untitled session"),Ie=e.children.length>0,Y=or(o,u,d.id),B=c?!0:i.has(a),$=df(d.id);Fl(l.useCallback(me=>me.index.session.unseenHasError[d.id]??!1,[d.id]));const X=uf(d.id),ee=ff({pendingInput:X,isStreaming:ae,unseenCount:$,isActive:f}),ie=$>0||Ll(X),ke=d.time?.updated||d.time?.created||Date.now(),pe=Eh(ke),je=l.useMemo(()=>bc(e.forkColorId),[e.forkColorId]),ze=l.useMemo(()=>Qm(e.forkColorId,{active:f||I}),[e.forkColorId,f,I]);return{session:d,sessionDirectory:u,prDirectory:z,prBranch:P,prNumber:q?.number??null,isActive:f,tooltipProjectLabel:p,projectPath:h,tooltipBranchLabel:j,isGitRepo:S,subtaskCount:C,agentName:E,prSummary:q,prIconColor:H,prStatusLabel:F,selectionScopeKey:D,selectionModeEnabled:T,isRowSelected:I,toggleRowSelected:M,setRowRange:G,isStreaming:ae,hasActivityDuration:J,sessionTitle:le,hasChildren:Ie,isPinnedSession:Y,isExpanded:B,needsAttention:ie,pendingInput:X,attention:ee,sessionCompactUpdatedLabel:pe,forkSolid:je,rowBackground:ze}}const lx=({prDirectory:e,prNumber:t,prStatusLabel:s,prIconColor:r})=>{const o=Dl(e);if(!e||!o)return n.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",style:r?{color:r}:void 0,title:s?`PR #${t} — ${s}`:`PR #${t}`,children:[n.jsx(R,{name:"git-pull-request",className:"size-3.5 shrink-0"}),n.jsxs("span",{children:["#",t]})]});const i=a=>{a.stopPropagation(),a.preventDefault(),Oc(e,o,t)};return n.jsxs("span",{role:"button",tabIndex:0,onClick:i,onDoubleClick:a=>{a.stopPropagation(),a.preventDefault()},onKeyDown:a=>{if(!(a.key!=="Enter"&&a.key!==" ")){if(a.repeat){a.stopPropagation(),a.preventDefault();return}i(a)}},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:s?`PR #${t} — ${s}. Open in Pull requests`:`Open PR #${t} in Pull requests`,"aria-label":s?`Open pull request #${t}, ${s}, in Pull requests`:`Open pull request #${t} in Pull requests`,children:[n.jsx(R,{name:"git-pull-request",className:"size-3.5 shrink-0"}),n.jsxs("span",{children:["#",t]})]})};function cx(e){Wt("ui.sidebar_session_node.render");const{node:t,depth:s=0,groupDirectory:r,projectId:o,archivedBucket:i=!1,pinnedSessionIds:a,expandedParents:c,hasSessionSearchQuery:d,normalizedSessionSearchQuery:u,editingId:f,setEditingId:m,editTitle:b,setEditTitle:g,handleSaveEdit:p,handleCancelEdit:h,toggleParent:y,handleSessionSelect:x,handleSessionDoubleClick:k,togglePinnedSession:v,handleShareSession:A,copiedSessionId:w,handleCopyShareUrl:j,handleCopySessionId:S,handleUnshareSession:C,openSidebarMenuKey:E,setOpenSidebarMenuKey:P,renamingFolderId:z,getFoldersForScope:K,getSessionFolderId:q,removeSessionFromFolder:H,addSessionToFolder:F,createFolderAndStartRename:D,handleDeleteSession:T,handleRestoreSession:I,alwaysShowActions:M,allowQuickArchiveAction:G,renderSessionNode:W,secondaryMeta:L,renderContext:ae="project",subtreeContainsEditing:J,menuOpenSessionId:le,childRenderExtrasFor:Ie}=e,Y=i||!!t.session.time?.archived,B=l.useContext(nr)==="tree",$="size-3 shrink-0",X=l.useMemo(()=>Wl(),[]),ee=!Y&&G,ie=l.useRef(!1),ke=l.useRef(f);ke.current=f;const pe=l.useRef(null),je=l.useRef(p);je.current=p;const[be,ze]=l.useState(b),me=l.useRef(be);me.current=be;const Pe=l.useRef(null),V=l.useRef(null),xe=sr(ae,t.session),{session:te,sessionDirectory:re,prDirectory:Be,prNumber:Ce,isActive:Q,tooltipProjectLabel:ve,projectPath:he,tooltipBranchLabel:Se,isGitRepo:qe,subtaskCount:Ue,agentName:U,prSummary:ge,prIconColor:se,prStatusLabel:_e,selectionScopeKey:st,selectionModeEnabled:mt,isRowSelected:Xe,toggleRowSelected:Yt,setRowRange:gt,isStreaming:It,hasActivityDuration:nn,sessionTitle:Qe,hasChildren:Mt,isPinnedSession:Ft,isExpanded:Ct,pendingInput:Ee,attention:Ye,sessionCompactUpdatedLabel:Ne,forkSolid:De,rowBackground:He}=ax({node:t,groupDirectory:r,projectId:o,secondaryMeta:L,pinnedSessionIds:a,expandedParents:c,expansionKey:xe,hasSessionSearchQuery:d}),{exportDialogOpen:ft,setExportDialogOpen:sn,exportIncludeSubtasks:Lt,setExportIncludeSubtasks:Ot,descendantCount:Ve,handleExportSession:rn,doExportSession:In}=tx(t,re),[Et,Gn]=l.useState(!1),xt=l.useContext(Vr),ot=s===0&&!Y?xt?.sectionById.get(te.id)??null:null,Qt=er(l.useCallback(de=>ot==="snoozed"?de.entries[te.id]?.snoozedUntil??null:null,[ot,te.id])),Bt=ot==="snoozed"||Y,gn=ot!==null&&ot!=="snoozed"&&!!xt?.wokeIds.has(te.id),on=l.useMemo(()=>{if(!ot)return null;const de=re??null;return{section:ot,onSnooze:_t=>pi(te.id,{snoozedUntil:_t},de,"Could not snooze the session"),onWake:()=>pi(te.id,{snoozedUntil:null},de,"Could not wake the session")}},[ot,te.id,re]),yt=on?.section==="snoozed"?{label:"Wake",hint:"Wake now: back to the list",icon:"alarm",run:on.onWake}:null,wt=l.useCallback(()=>{re&&Gs("desktop_open_session_mini_chat_window",{sessionId:te.id,directory:re,apiBaseUrl:Vo(),clientToken:qo()}).catch(de=>{console.warn("[session-sidebar] failed to open mini chat window",de)})},[te.id,re]);l.useEffect(()=>{if(f!==te.id)return;const de=_t=>{const Is=_t.target?.closest?.(`[data-session-rename-form="${CSS.escape(te.id)}"]`);V.current&&!Is&&je.current(me.current)};return document.addEventListener("mousedown",de),()=>document.removeEventListener("mousedown",de)},[f,te.id]),l.useLayoutEffect(()=>{if(f!==te.id){Pe.current===te.id&&(Pe.current=null);return}Pe.current!==te.id&&(Pe.current=te.id,ze(b))},[f,b,te.id]);const Dt=Ye==="needs-input",Hn=Dt&&Ee?hf(Ee.kind,Ee.count):null,En=Ye==="unread",Dn=Qt!==null?pf(Qt,Date.now()):gn?"Woke":Ne,kt=It&&nn,an=ee&&(M||Et),nt=It&&!B&&!an&&f!==te.id,ln=!!(L?.showFolderLabel&&ve),vt=!!Se||qe,At=!!(U&&U!=="default"),it=!!ge&&Ce!=null,Rn=kt&&!nt,at=ln&&vt||it||Ue>0||At||Rn,qn=de=>Se?n.jsxs("span",{className:_("inline-flex min-w-0 items-center gap-1",de?"shrink":"flex-1"),children:[n.jsx(R,{name:"git-branch",className:$,style:se?{color:se}:void 0}),n.jsx(Ks,{value:Se})]}):qe?n.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[n.jsx(R,{name:"git-repository",className:$}),n.jsx("span",{children:"git"})]}):null,Vn=Ft,ks=n.jsx(R,{name:"pushpin",className:"h-3 w-3 flex-shrink-0 text-primary","aria-label":"Pinned session"}),Pn=Vn?n.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:ks}):null,As=Mt?n.jsx("button",{type:"button",onClick:de=>{de.stopPropagation(),y(xe)},onKeyDown:de=>{(de.key==="Enter"||de.key===" ")&&(de.preventDefault(),de.stopPropagation(),y(xe))},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":Ct?"Collapse subsessions":"Expand subsessions",children:Ct?n.jsx(R,{name:"arrow-down-s",className:"h-3 w-3"}):n.jsx(R,{name:"arrow-right-s",className:"h-3 w-3"})}):null,O=de=>{if(!de&&pe.current){const{id:_t,title:Yn}=pe.current;pe.current=null,m(_t),g(Yn)}},ce=de=>{Gn(de)},ye=de=>{de.preventDefault(),de.stopPropagation()},$e=de=>{de.preventDefault(),de.stopPropagation()},ht=de=>{de.preventDefault(),de.stopPropagation(),P(null),T(te,{archivedBucket:Y})},Je=de=>{de.preventDefault(),de.stopPropagation(),P(null),T(te,{archivedBucket:Y,hardDelete:!0,skipConfirm:!0})},St=de=>{if(ie.current){ie.current=!1;return}if(mt){if(de?.preventDefault(),de?.stopPropagation(),de?.shiftKey){const Yn=(typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[]).map(Qn=>Qn.getAttribute("data-session-row")).filter(Qn=>typeof Qn=="string"&&Qn.length>0),Is=ct.getState().anchorId,cr=new Map;cr.set(te.id,Ur(t)),gt(Is,te.id,Yn,st,cr);return}Yt(te.id,st,Ur(t));return}de?.currentTarget&&Vb(de.currentTarget),x(te.id,re)},Rt=de=>{de.defaultPrevented||de.target?.closest('button, a, input, [role="menuitem"], [role="menu"]')||St(de)},bn=de=>{(de.button===2||de.button===0&&de.ctrlKey&&!mt)&&(ie.current=!0)},Ns={session:te,sessionTitle:Qe,sessionDirectory:re,isPinnedSession:Ft,archivedBucket:Y,isElectron:X,renamingFolderId:z,editingIdRef:ke,pendingRenameRef:pe,handleCopySessionId:S,togglePinnedSession:v,handleExportSession:rn,handleOpenMiniChatWindow:wt,handleDeleteSession:T,handleRestoreSession:I,shelfActions:on},lr=n.jsx(qb,{...Ns});return n.jsxs(l.Fragment,{children:[n.jsx(xg,{sessionId:te.id,sessionDirectory:re??null,sessionTitle:Qe,children:n.jsxs(gl,{open:Et,onOpenChange:ce,onOpenChangeComplete:O,children:[n.jsxs(bl,{render:n.jsx("div",{"data-session-row":te.id,"data-session-scope":st??"","data-session-archived":Y?"1":"0","data-fork-color":De?t.forkColorId:void 0,"data-global-session":L?.globalSession?"1":void 0,"data-sidebar-tree-row":B?"":void 0,onClick:Rt,style:{...s>0?{marginLeft:`${s*14}px`}:void 0,...He?{backgroundColor:He}:void 0},className:_("group relative flex cursor-pointer items-start px-3 transition-colors",B?Sc:"my-1 rounded-xl py-2.5",!He&&s>0?"bg-secondary/30 hover:bg-interactive-hover":He?"hover:brightness-[1.07] dark:hover:brightness-[1.18]":"hover:bg-interactive-hover",!He&&Q&&!Xe&&"bg-interactive-selection",!He&&Xe&&"bg-interactive-selection")}),children:[n.jsxs("div",{className:_("flex min-w-0 flex-1 items-start",nt&&"oc-session-row-working-fade"),"data-clear-on-hover":nt&&ee?"true":void 0,"data-working-duration":nt&&kt?"true":void 0,children:[n.jsxs("div",{className:_("flex min-w-0 flex-1 items-center",B?Yr:"gap-1.5"),children:[B?n.jsx("span",{"data-session-row-gutter":!0,className:"inline-flex size-4 shrink-0 items-center justify-center",children:It&&!Dt?n.jsx(Cn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null}):null,As,Pn,f===te.id?n.jsxs("form",{ref:V,"data-session-rename-form":te.id,className:_("flex min-w-0 flex-1 items-center gap-2",B?"min-h-5":"min-h-8"),onPointerDown:de=>de.stopPropagation(),onMouseDown:de=>de.stopPropagation(),onSubmit:de=>{de.preventDefault(),p(be)},children:[n.jsx("input",{value:be,onChange:de=>ze(de.target.value),className:"min-w-0 flex-1 bg-transparent typography-ui-label text-foreground outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:"Rename",onKeyDown:de=>{de.stopPropagation(),de.key==="Escape"&&h()}}),n.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:n.jsx(R,{name:"check",className:"size-4"})}),n.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:n.jsx(R,{name:"close",className:"size-4"})})]}):n.jsxs("button",{type:"button",onMouseDown:bn,onClick:de=>St(de),onDoubleClick:de=>{de.stopPropagation(),k(te.id,Qe)},className:"flex min-w-0 flex-1 cursor-pointer flex-col gap-1.5 overflow-hidden text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 text-foreground select-none",children:[n.jsxs("div",{className:_("flex w-full min-w-0 flex-1 gap-1.5 overflow-hidden",B?"items-center":"items-start"),children:[n.jsx("div",{className:_("block min-w-0 flex-1 truncate typography-ui-label",Q?"font-medium text-foreground":"font-normal",!Q&&(Bt?"text-muted-foreground group-hover:text-foreground":"text-foreground")),children:li(Qe,u)}),Ft?n.jsx(R,{name:"star-fill",className:_("h-3 w-3 text-primary shrink-0",!B&&"mt-1")}):null,n.jsx("span",{"aria-hidden":"true",className:_("invisible ml-1 min-w-6 shrink-0 whitespace-nowrap typography-micro",(Qt!==null||gn)&&!En&&"pl-4"),children:En?null:Dn})]}),!B&&(ln||vt||at)?n.jsxs("div",{className:_("flex w-full min-w-0 items-center justify-between gap-2 overflow-hidden typography-micro leading-4 font-normal",Bt?"text-subtle-foreground":"text-muted-foreground"),children:[ln?n.jsxs("span",{className:_("inline-flex min-w-0 items-center gap-1",at?"max-w-[60%] shrink-0":"flex-1"),children:[he?n.jsx(Ci,{directory:he,label:ve??"",className:$}):n.jsx(R,{name:"folder",className:$}),n.jsx("span",{className:"truncate",children:ve})]}):qn(!1),at?n.jsxs("span",{className:_("ml-auto flex min-w-0 items-center justify-end gap-2 overflow-hidden",ln?"flex-1":"shrink-0"),children:[ln?qn(!0):null,it?n.jsx(lx,{prDirectory:Be,prNumber:Ce,prStatusLabel:_e,prIconColor:se}):null,Ue>0?n.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[n.jsx(R,{name:"node-tree",className:$}),n.jsx("span",{children:Ue})]}):null,At?n.jsx("span",{className:"min-w-0 max-w-[80px] shrink-0 truncate",children:U}):null,Rn?n.jsx(la,{sessionId:te.id,running:It,className:"shrink-0 text-subtle-foreground"}):null]}):null]}):null]})]}),n.jsxs("div",{className:_("absolute right-3 flex h-5 min-w-6 items-center justify-end",B?"top-1/2 -translate-y-1/2":"top-2.5",f===te.id&&"hidden"),children:[n.jsx("div",{className:_("flex items-center justify-end",an?"opacity-0":ee?"group-hover:opacity-0 group-focus-within:opacity-0":null),children:Dt&&!nt?n.jsx(na,{label:Hn??"Needs input"}):En?n.jsx(Dh,{label:"Session complete"}):Qt!==null||gn?n.jsxs("span",{className:"inline-flex items-center gap-1 typography-micro text-muted-foreground whitespace-nowrap",title:Qt!==null?`Snoozed until ${new Date(Qt).toLocaleString()}`:"Back from snooze",children:[n.jsx(R,{name:"alarm",className:"size-3 shrink-0"}),Dn]}):n.jsx("span",{className:"typography-micro text-subtle-foreground whitespace-nowrap",children:Ne})}),ee?n.jsx("div",{className:_("absolute inset-0 flex items-center justify-end",M||Et?"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:yt?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button","aria-label":yt.label,className:"inline-flex size-6 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-interactive-active hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",onPointerDown:ye,onMouseDown:$e,onKeyDown:de=>de.stopPropagation(),onClick:de=>{de.preventDefault(),de.stopPropagation(),P(null),yt.run()},children:n.jsx(R,{name:yt.icon,className:"size-4"})})}),n.jsx(Ge,{side:"top",sideOffset:6,children:yt.hint})]}):n.jsx(Wb,{archiveLabel:"Archive",deleteLabel:"Delete",buttonSizeClass:"h-6 w-6",iconSizeClass:"h-3.5 w-3.5",onPointerDown:ye,onMouseDown:$e,onArchive:ht,onDelete:Je})}):null]})]}),nt?n.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",ee&&"group-hover:opacity-0 group-focus-within:opacity-0"),children:[Dt?null:n.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"}),n.jsxs("span",{className:"relative flex flex-col items-end gap-1.5",children:[n.jsx("span",{className:"flex h-5 items-center",children:Dt?n.jsx("span",{className:"inline-flex size-3 shrink-0 items-center justify-center",children:n.jsx(na,{label:Hn??"Needs input"})}):n.jsx(Cn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})}),kt?n.jsx(la,{sessionId:te.id,running:It,className:"typography-micro leading-4"}):null]})]}):null]}),lr]})}),Mt&&Ct?t.children.map(de=>{const _t=Ie?Ie(de):{subtreeContainsEditing:J,menuOpenSessionId:le,nodeStructureKey:""};return n.jsx(l.Fragment,{children:W(de,s+1,re??r,o,Y,L?.globalSession?{globalSession:!0}:void 0,ae,_t)},de.session.id)}):null,n.jsx(Gb,{open:ft,onOpenChange:sn,descendantCount:Ve,exportIncludeSubtasks:Lt,setExportIncludeSubtasks:Ot,onExport:In})]},te.id)}const dx=l.memo(cx,ix),ux=({open:e,onOpenChange:t,project:s,onSave:r})=>n.jsx(en,{open:e,onOpenChange:t,children:n.jsx(tn,{className:"w-full max-w-2xl gap-0 overflow-hidden p-0",children:n.jsx(Ln,{outerClassName:"max-h-[min(90vh,48rem)]",className:"w-full bg-background",children:n.jsx("div",{className:"w-full p-3 sm:p-6 sm:pt-8",children:e&&s?n.jsx(cm,{project:s,onIdentitySave:r}):null})})})});function Yc(e){const{showDeletionDialog:t,setShowDeletionDialog:s,onCancel:r,onConfirm:o,confirmLabel:i}=e;return n.jsxs(ys,{className:"w-full sm:items-center sm:justify-between",children:[n.jsxs("button",{type:"button",onClick:()=>s(!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?n.jsx(R,{name:"checkbox-blank",className:"h-4 w-4"}):n.jsx(R,{name:"checkbox",className:"h-4 w-4 text-primary"}),"Never ask"]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.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"}),n.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 fx(e){const{value:t,setValue:s,showDeletionDialog:r,setShowDeletionDialog:o,onConfirm:i}=e,a=c=>un(c);return n.jsx(en,{open:!!t,onOpenChange:c=>{c||s(null)},children:n.jsxs(tn,{showCloseButton:!1,className:"max-w-sm gap-5",children:[n.jsxs($n,{children:[n.jsx(mn,{children:"Delete session?"}),n.jsx(An,{children:t&&t.descendantCount>0?t.descendantCount===1?`"${a(t.session)}" and its ${t.descendantCount} sub-task will be permanently deleted.`:`"${a(t.session)}" and its ${t.descendantCount} sub-tasks will be permanently deleted.`:`"${t?.session?a(t.session):"Untitled Session"}" will be permanently deleted.`})]}),n.jsx(Yc,{showDeletionDialog:r,setShowDeletionDialog:o,onCancel:()=>s(null),onConfirm:i,confirmLabel:"Delete"})]})})}function hx(e){const{value:t,setValue:s,showDeletionDialog:r,setShowDeletionDialog:o,onConfirm:i}=e,a=t?.sessionCount??0,c=a===1?"Delete session?":"Delete sessions?",d=a===1?`${a} session will be permanently deleted.`:`${a} sessions will be permanently deleted.`;return n.jsx(en,{open:!!t,onOpenChange:u=>{u||s(null)},children:n.jsxs(tn,{showCloseButton:!1,className:"max-w-sm gap-5",children:[n.jsxs($n,{children:[n.jsx(mn,{children:c}),n.jsx(An,{children:d})]}),n.jsx(Yc,{showDeletionDialog:r,setShowDeletionDialog:o,onCancel:()=>s(null),onConfirm:i,confirmLabel:"Delete"})]})})}function px(e){const{value:t,setValue:s,onConfirm:r}=e,{git:o}=Kn(),[i,a]=l.useState(null),[c,d]=l.useState(!1),[u,f]=l.useState(!1),[m,b]=l.useState(!1),g=t?.worktree.path??null;l.useEffect(()=>{let w=!1;return a(null),d(!1),f(!1),b(!1),!t||!g?()=>{w=!0}:(o.getGitStatus(g).then(j=>{if(!w){if(typeof j?.isClean!="boolean"){d(!0);return}a(j)}}).catch(()=>{w||d(!0)}),()=>{w=!0})},[o,t,g]);const p=i?.isClean===!1,h=(i?.ahead??0)>0,y=h&&!t?.worktree.branch,x=t?.worktree.branch?"The local branch will be kept.":"No local branch will be deleted.",k=!!(t&&i&&!c&&!t.hasActiveSession&&(!p&&!y||u)&&!m),v=t?.worktree.branch||t?.worktree.name||t?.worktree.path||"",A=async()=>{if(k){b(!0);try{await r({force:p})}finally{b(!1)}}};return n.jsx(en,{open:!!t,onOpenChange:w=>{!w&&!m&&s(null)},children:n.jsxs(tn,{showCloseButton:!1,className:"max-w-md gap-5",children:[n.jsxs($n,{children:[n.jsx(mn,{children:"Close worktree?"}),n.jsx(An,{children:`Closing "${v}" removes its worktree directory. ${x}`})]}),c?n.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:[n.jsx(R,{name:"alert",className:"mt-0.5 size-4 shrink-0 text-[var(--status-error)]"}),n.jsx("p",{className:"typography-ui-label text-foreground",children:"Unable to check this worktree's status. Refresh and try again."})]}):i===null?n.jsx("p",{className:"typography-ui-label text-muted-foreground","aria-live":"polite",children:"Checking worktree status…"}):null,t?.hasActiveSession?n.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:[n.jsx(R,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),n.jsx("p",{className:"typography-ui-label text-foreground",children:"Stop the active session before closing this worktree."})]}):null,p?n.jsxs("div",{className:"space-y-3 rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:[n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx(R,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),n.jsx("p",{className:"typography-ui-label text-foreground",children:"This worktree has uncommitted changes. They will be permanently removed."})]}),n.jsxs("label",{className:"flex items-start gap-2 pl-6 typography-ui-label text-foreground",children:[n.jsx(Qs,{checked:u,onChange:f,ariaLabel:"Confirm removal of uncommitted changes",className:"mt-0.5"}),n.jsx("span",{children:"I understand that the uncommitted changes will be lost."})]})]}):null,h?n.jsxs("div",{className:"space-y-3",children:[n.jsx("p",{className:"typography-ui-label text-muted-foreground",children:i?.ahead===1?`This worktree has 1 unpushed commit. ${x}`:`This worktree has ${i?.ahead} unpushed commits. ${x}`}),y?n.jsxs("div",{className:"space-y-3 rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:[n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx(R,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),n.jsx("p",{className:"typography-ui-label text-foreground",children:"Because this worktree is detached, its unpushed commits may be lost."})]}),n.jsxs("label",{className:"flex items-start gap-2 pl-6 typography-ui-label text-foreground",children:[n.jsx(Qs,{checked:u,onChange:f,ariaLabel:"Confirm removal of unpushed detached commits",className:"mt-0.5"}),n.jsx("span",{children:"I understand that the unpushed commits may be lost."})]})]}):null]}):null,n.jsxs(ys,{className:"sm:justify-end",children:[n.jsx(Ae,{variant:"outline",size:"sm",onClick:()=>s(null),disabled:m,children:"Cancel"}),n.jsx(Ae,{variant:"destructive",size:"sm",onClick:()=>{A()},disabled:!k,children:m?"Closing…":"Close worktree"})]})]})})}function mx(e){const{value:t,setValue:s,onConfirm:r}=e;return n.jsx(en,{open:!!t,onOpenChange:o=>{o||s(null)},children:n.jsxs(tn,{showCloseButton:!1,className:"max-w-sm gap-5",children:[n.jsxs($n,{children:[n.jsx(mn,{children:"Delete folder?"}),n.jsx(An,{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.`})]}),n.jsxs(ys,{children:[n.jsx("button",{type:"button",onClick:()=>s(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"}),n.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 gx=({updateDialogOpen:e,setUpdateDialogOpen:t,updateStore:s,editingProject:r,setEditingProjectDialogId:o,handleSaveProjectEdit:i,deleteSessionConfirm:a,setDeleteSessionConfirm:c,showDeletionDialog:d,setShowDeletionDialog:u,confirmDeleteSession:f,deleteFolderConfirm:m,setDeleteFolderConfirm:b,confirmDeleteFolder:g,closeWorktreeConfirm:p,setCloseWorktreeConfirm:h,confirmCloseWorktree:y,bulkDeleteConfirm:x,setBulkDeleteConfirm:k,confirmBulkDelete:v})=>n.jsxs(n.Fragment,{children:[n.jsx(ic,{open:e,onOpenChange:t,info:s.info,downloading:s.downloading,downloaded:s.downloaded,progress:s.progress,error:s.error,onDownload:s.downloadUpdate,onRestart:s.restartToUpdate,runtimeType:s.runtimeType}),n.jsx(ux,{open:!!r,onOpenChange:A=>{A||o(null)},project:r,onSave:i}),n.jsx(fx,{value:a,setValue:c,showDeletionDialog:d,setShowDeletionDialog:u,onConfirm:f}),n.jsx(mx,{value:m,setValue:b,onConfirm:g}),n.jsx(px,{value:p,setValue:h,onConfirm:y}),n.jsx(hx,{value:x,setValue:k,showDeletionDialog:d,setShowDeletionDialog:u,onConfirm:v})]}),bx=({directories:e})=>{const t=l.useMemo(()=>{const r=new Set;return e.forEach(o=>{const i=Re(o)?.toLowerCase();i&&r.add(i)}),r},[e]),s=Ws(r=>{let o=0,i=!1;for(const a of r.catalog.byId.values()){const c=Re(a.directory)?.toLowerCase();!c||!t.has(c)||(Ll(a.pendingInput)?o+=1:(a.lifecycle==="busy"||a.lifecycle==="retry")&&(i=!0))}return{inputCount:o,hasBusySession:i}},(r,o)=>r.inputCount===o.inputCount&&r.hasBusySession===o.hasBusySession,"catalog");if(s.inputCount>0){const r=mf(s.inputCount);return n.jsx("span",{className:"inline-flex items-center","aria-label":r,title:r,children:n.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-status-warning"})})}return s.hasBusySession?n.jsx("span",{className:"inline-flex items-center","aria-label":"Session active",title:"Session active",children:n.jsx(Cn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})}):null},xx=({selectedCount:e,archivedBucket:t,onRestore:s,onDelete:r,onDone:o})=>{const i=t?"Delete":"Archive",a="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 n.jsxs("div",{className:"flex shrink-0 items-center gap-1 border-t border-border pl-5 pr-3.5 py-1.5",children:[n.jsx("span",{className:"typography-ui-label text-muted-foreground whitespace-nowrap",children:`${e} selected`}),n.jsxs("div",{className:"ml-auto flex items-center gap-0.5",children:[t?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:s,className:a,"aria-label":"Unarchive",children:n.jsx(R,{name:"inbox-unarchive",className:"h-4 w-4"})})}),n.jsx(Ge,{side:"top",sideOffset:4,children:n.jsx("p",{children:"Unarchive"})})]}):null,n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:r,className:_(t?"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":a),"aria-label":i,children:n.jsx(R,{name:t?"delete-bin":"inbox-archive",className:"h-4 w-4"})})}),n.jsx(Ge,{side:"top",sideOffset:4,children:n.jsx("p",{children:i})})]}),n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:o,className:a,"aria-label":"Exit selection",children:n.jsx(R,{name:"close",className:"h-4 w-4"})})}),n.jsx(Ge,{side:"top",sideOffset:4,children:n.jsx("p",{children:"Exit selection"})})]})]})]})},yx=e=>{if(typeof document>"u")return!1;const t=document.querySelectorAll(`[data-session-row="${CSS.escape(e)}"]`);if(t.length===0)return!1;for(const s of t)if(s.getAttribute("data-session-archived")!=="1")return!1;return!0},wx=e=>{const{isInlineEditing:t,showDeletionDialog:s,foldersMap:r,folderScopesByProject:o,addSessionsToFolder:i,removeSessionsFromFolders:a,createFolderAndStartRename:c,resolveSessionDirectory:d,unarchiveSessions:u,deleteSessions:f,setBulkDeleteConfirm:m}=e,b=ct(T=>T.enabled),g=ct(T=>T.selectedIds.size),p=g>0,h=ct(T=>T.selectedIds),y=ct(T=>T.scopeKey),x=l.useCallback(()=>{ct.getState().toggleMode()},[]),k=l.useCallback(()=>{ct.getState().disable()},[]),v=l.useMemo(()=>{if(!p||typeof document>"u")return!1;let T=!1,I=!1;for(const M of h){const G=document.querySelectorAll(`[data-session-row="${CSS.escape(M)}"]`);for(const W of G)W.getAttribute("data-session-archived")==="1"?I=!0:T=!0}return I&&!T},[p,h]),A=l.useMemo(()=>{if(y)return y;if(!p||typeof document>"u")return null;for(const T of h){const M=document.querySelector(`[data-session-row="${CSS.escape(T)}"]`)?.getAttribute("data-session-scope");if(M&&M.length>0)return M}return null},[p,h,y]),w=l.useMemo(()=>{if(!A)return[];const T=o.get(A);return T&&T.length>0?T.map(I=>I.scopeKey):[A]},[A,o]),j=l.useMemo(()=>w.flatMap(T=>r[T]??[]),[r,w]),S=l.useCallback(T=>{for(const I of w)if((r[I]??[]).some(M=>M.id===T))return I;return null},[r,w]),C=l.useMemo(()=>{if(!p)return!1;for(const T of w)for(const I of r[T]??[])for(const M of I.sessionIds)if(h.has(M))return!0;return!1},[r,w,p,h]),E=l.useCallback((T,I)=>{const M=Array.from(h);for(const G of w)G!==T&&a(G,M);i(T,I,M)},[i,a,h,w]),P=l.useCallback(T=>{if(!p)return;const I=S(T);I&&E(I,T)},[p,E,S]),z=l.useCallback(()=>{const T=w[0];if(!T||!p)return;const I=c(T);I&&E(T,I.id)},[c,p,E,w]),K=l.useCallback(()=>{if(!p)return;const T=Array.from(h);for(const I of w)a(I,T)},[a,h,w,p]),q=l.useCallback(async()=>{const T=Array.from(h);if(T.length===0)return;const{deletedIds:I,failedIds:M}=await f(T);I.length>0&&oe.success(I.length===1?`Deleted ${I.length} session`:`Deleted ${I.length} sessions`),M.length>0&&oe.error(M.length===1?`Failed to delete ${M.length} session`:`Failed to delete ${M.length} sessions`),ct.getState().clear()},[f,h]),H=l.useCallback(()=>{if(p){if(!v){const T=Array.from(h).filter(I=>!yx(I)).map(I=>({sessionId:I,directory:d(I),forkIds:[]}));ct.getState().clear(),xc(T);return}if(!s){q();return}m({sessionCount:h.size})}},[v,q,d,h,s,m,p]),F=l.useCallback(async()=>{if(!p||!v)return;const T=Array.from(h),{restoredIds:I,failedIds:M}=await u(T);I.length>0&&oe.success(I.length===1?`Unarchived ${I.length} session`:`Unarchived ${I.length} sessions`),M.length>0&&oe.error(M.length===1?`Could not unarchive ${M.length} session`:`Could not unarchive ${M.length} sessions`),ct.getState().clear()},[v,p,h,u]),D=l.useCallback(async()=>{m(null),await q()},[q]);return l.useEffect(()=>{if(!b)return;const T=typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""),I=M=>{if(t)return;const G=M.target;if(G&&(G.tagName==="INPUT"||G.tagName==="TEXTAREA"||G.isContentEditable))return;const W=T?M.metaKey:M.ctrlKey;if(M.key==="Escape"){M.preventDefault(),ct.getState().disable();return}if(W&&M.key==="Backspace"){M.preventDefault(),H();return}if(W&&(M.key==="a"||M.key==="A")){const L=typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[];if(L.length===0)return;M.preventDefault();const J=ct.getState().scopeKey??L[0]?.getAttribute("data-session-scope")??null,le=Y=>J?Y.getAttribute("data-session-scope")===J:!0,Ie=L.filter(le).map(Y=>Y.getAttribute("data-session-row")).filter(Y=>typeof Y=="string"&&Y.length>0);if(Ie.length===0)return;ct.getState().replaceAll(Ie,J||null)}};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[H,t,b]),{selectionModeEnabled:b,hasSelection:p,selectedIdsSize:g,bulkScopeIsArchived:v,derivedSelectionScope:A,bulkScopeFolders:j,bulkCanRemoveFromFolder:C,handleToggleSelectionMode:x,handleExitSelectionMode:k,handleBulkMoveToFolder:P,handleBulkCreateFolderAndMove:z,handleBulkRemoveFromFolder:K,handleBulkDelete:H,handleBulkRestore:F,confirmBulkDelete:D}},vx=(e,t)=>{const s=e??{};return delete s.projectSortOrder,delete s.showArchivedSessions,t<4&&delete s.displayMode,t<5&&delete s.sessionGroupingMode,s},Sx=Nn()(Ql(e=>({stickyZoneHeaders:!0,toggleStickyZoneHeaders:()=>e(t=>({stickyZoneHeaders:!t.stickyZoneHeaders})),showRecentSection:!0,setShowRecentSection:t=>e({showRecentSection:t}),toggleRecentSection:()=>e(t=>({showRecentSection:!t.showRecentSection}))}),{name:"pichamber:session-display-settings",version:7,migrate:vx})),Va="oc.sessions.projectCollapse",Ya="oc.sessions.groupOrder",Qa="oc.sessions.groupCollapse",Ja="oc.sessions.activeSessionByProject",Xa="oc.sessions.expandedParents.v3",jx=new Set,jo=[],Pt=e=>{const t=l.useRef(e);return t.current=e,l.useCallback((...s)=>t.current(...s),[])},Cx=({isVisible:e=!0,mobileVariant:t=!1,onSessionSelected:s,onNavigateAway:r,allowReselect:o=!1,hideDirectoryControls:i=!1,showOnlyMainWorkspace:a=!1})=>{Ho("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]=l.useState(!1),[u,f]=l.useState(""),m=l.useRef(null),b=l.useRef(null),[g,p]=l.useState(null),[h,y]=l.useState(""),[x,k]=l.useState(null),[v,A]=l.useState(new Set),w=l.useMemo(()=>as(),[]),[j,S]=l.useState(new Set),C=Zn(N=>N.selectedSpaceId),E=Zn(N=>N.selectedWorktreePath),[P,z]=l.useState(new Map),[K,q]=l.useState(new Map),[H,F]=l.useState(!1),[D,T]=l.useState(null),[I,M]=l.useState(null),[G,W]=l.useState(""),[L,ae]=l.useState(null),[J,le]=l.useState(null),[Ie,Y]=l.useState(null),[B,$]=l.useState(null),X=Xs(N=>N.ids),ee=gf(l.useCallback(N=>e?N.rankById:Rl,[e])),ie=Ws(N=>e?bf(N.catalog):"",void 0,"catalog"),ke=l.useMemo(()=>ie?ie.split("|"):jo,[ie]),pe=l.useMemo(()=>new Set(ke),[ke]),je=Fl(Bo(N=>e?Object.entries(N.index.session.unseenCount).filter(([,Z])=>Z>0).map(([Z])=>Z).sort():jo)),be=l.useMemo(()=>new Set(je),[je]),ze=Xs(N=>N.toggle),[me,Pe]=l.useState(()=>{try{const N=as().getItem(Qa);if(!N)return new Set;const Z=JSON.parse(N);return new Set(Array.isArray(Z)?Z.filter(ne=>typeof ne=="string"):[])}catch{return new Set}}),[V,fe]=l.useState(()=>{try{const N=as().getItem(Ya);if(!N)return new Map;const Z=JSON.parse(N),ne=new Map;return Object.entries(Z).forEach(([Le,Oe])=>{Array.isArray(Oe)&&ne.set(Le,Oe.filter(et=>typeof et=="string"))}),ne}catch{return new Map}}),xe=l.useMemo(()=>{try{const N=as().getItem(Ja);if(!N)return new Map;const Z=JSON.parse(N),ne=new Map;return Object.entries(Z).forEach(([Le,Oe])=>{typeof Oe=="string"&&Oe.length>0&&ne.set(Le,Oe)}),ne}catch{return new Map}},[]),te=l.useCallback(N=>{try{w.setItem(Ja,JSON.stringify(Object.fromEntries(N.entries())))}catch{}},[w]),[re,Be]=l.useState(new Map),Ce=l.useRef(0),Q=gs(N=>N.homeDirectory),ve=gs(N=>N.currentDirectory),he=dt(N=>N.projects),Se=dt(N=>N.activeProjectId),qe=dt(N=>N.removeProject),Ue=dt(N=>N.setActiveProjectIdOnly),U=dt(N=>N.updateProjectMeta),ge=dt(N=>N.reorderProjects),se=ue(N=>N.setActiveMainTab),_e=ue(N=>N.setSettingsDialogOpen),st=ue(N=>N.setSettingsPage),mt=ue(N=>N.toggleHelpDialog),Xe=ue(N=>N.setSessionSwitcherOpen),Yt=ue(N=>N.setArchivePageOpen),gt=ue(N=>N.showDeletionDialog),It=ue(N=>N.setShowDeletionDialog),nn=ue(N=>N.sidebarViewMode),Qe=i||a||!ah(nn)?"workspace":nn,Mt=ue(N=>N.weekStartPreference),Ft=l.useMemo(()=>Im(Mt),[Mt]),Ct=Pm(e&&Qe==="timeline",Ft),Ee=Sx(N=>N.stickyZoneHeaders),Ye=xf(u,120),Ne=l.useMemo(()=>Ye.trim().toLowerCase(),[Ye]),De=Ne.length>0,He=bt(N=>N.collapsedFolderIds),ft=bt(N=>N.foldersMap),sn=bt(N=>N.getFoldersForScope),Lt=bt(N=>N.createFolder),Ot=bt(N=>N.renameFolder),Ve=bt(N=>N.deleteFolder),rn=bt(N=>N.addSessionToFolder),In=bt(N=>N.addSessionsToFolder),Et=bt(N=>N.removeSessionFromFolder),Gn=bt(N=>N.removeSessionsFromFolders),xt=bt(N=>N.toggleFolderCollapse),ot=bt(N=>N.getSessionFolderId);Zm({enabled:e,isSessionSearchOpen:c,setIsSessionSearchOpen:d,sessionSearchInputRef:b,sessionSearchContainerRef:m});const Qt=yf(e),{git:Bt}=Kn(),gn=Ws(N=>N.connection,void 0,"chrome"),on=Ws(N=>{for(const Z of N.catalog.listStatusByDirectory.values())if(Z==="ready")return!0;return!1},void 0,"catalog"),yt=Uo({archived:!1}),wt=Uo({archived:!0}),Dt=Me(N=>N.setCurrentSession),Hn=Me(N=>N.updateSessionTitle),En=Me(N=>N.shareSession),Dn=Me(N=>N.unshareSession),kt=Wo(N=>N.projects),an=Wo(N=>N.refreshProject),nt=l.useMemo(()=>wf(he,{projects:kt}),[he,kt]),ln=l.useMemo(()=>{const N=new Map;for(const Z of he){const ne=Re(Z.path);if(!ne)continue;const Le=kt.get(ne)?.error;Le&&N.set(ne,Le)}return N},[he,kt]);l.useEffect(()=>{if(!C)return;const N=he.find(ne=>ne.id===C);if(!N){Zn.getState().clearSpaceSelection();return}if(!E)return;(nt.get(Re(N.path)??N.path)??[]).some(ne=>Re(ne.path)===Re(E))||(Zn.getState().clearSelectedWorktree(),oe.warning("The selected worktree is no longer available. Showing the project checkout instead."))},[nt,he,C,E]);const vt=Me(N=>N.openNewSessionDraft),At=l.useCallback(N=>{ue.getState().closeMainSurfaces(),vt(N),r?.()},[r,vt]),it=Cr(Bo(N=>({checkForUpdates:N.checkForUpdates,available:N.available,runtimeType:N.runtimeType,info:N.info,downloading:N.downloading,downloaded:N.downloaded,progress:N.progress,error:N.error,downloadUpdate:N.downloadUpdate,restartToUpdate:N.restartToUpdate}))),Rn=l.useMemo(()=>vf(he,nt,{includeWorktrees:!0}),[nt,he]),at=l.useMemo(()=>yt.filter(N=>hg(N,Rn,{allowUnknownDirectory:!0,allowEmptyDirectorySet:!0,homeDirectory:Q})),[yt,Q,Rn]),qn=l.useMemo(()=>[...at,...wt],[wt,at]),Vn=rt(),ks=l.useMemo(()=>`${Vn}|${he.map(N=>`${N.id}:${Re(N.path)??""}`).join("|")}`,[he,Vn]),Pn=l.useMemo(()=>{const N=new Set;let Z=!0;for(const ne of he){const Le=Re(ne.path);if(!Le)continue;const Oe=kt.get(Le)?.status??"idle";Oe==="failed"&&N.add(Le),(Oe==="idle"||Oe==="loading")&&(Z=!1)}return{complete:Z,unresolved:N}},[he,kt]),As=Pn.complete?ks:null;Pn.complete;const O=Pn.unresolved,{isTablet:ce}=xs(),ye=t||ce,$e=Xm({mobileVariant:t,isTablet:ce}),{buildGroupSearchText:ht,filterSessionNodesForSearch:Je,buildGroupedSessions:St}=Jm({homeDirectory:Q,pinnedSessionIds:X,sessionOrderRanks:ee}),{scheduleCollapsedProjectsPersist:Rt}=tg({safeStorage:w,keys:{sessionExpanded:Xa,projectCollapse:Va,groupOrder:Ya,groupCollapse:Qa},groupOrderByProject:V,collapsedGroups:me,setExpandedParents:A,setCollapsedProjects:S}),bn=l.useMemo(()=>Sf(at,X,ee),[X,ee,at]),Ns=l.useMemo(()=>bn.map(N=>N.id).join("|"),[bn]),lr=l.useRef(null),de=l.useMemo(()=>{const N=lr.current;if(N&&N.signature===Ns)return N.map;const Z=new Map(bn.map((ne,Le)=>[ne.id,Le]));return lr.current={signature:Ns,map:Z},Z},[bn,Ns]),_t=l.useMemo(()=>{const N=new Map;bn.forEach(ne=>{const Le=ne.parentID;if(!Le)return;const Oe=N.get(Le)??[];Oe.push(ne),N.set(Le,Oe)});const Z=Il(X,ee);return N.forEach(ne=>ne.sort(Z)),N},[bn,X,ee]),Yn=l.useMemo(()=>n.jsx(Gt,{icon:"chat-new",mobileVariant:t,onClick:()=>At(),children:"New session"}),[t,At]),Is=l.useMemo(()=>he.find(N=>N.id===x)??null,[he,x]),cr=l.useCallback(N=>{x&&U(x,{label:N.label,defaultModel:N.defaultModel??null})},[x,U]),Qn=l.useCallback(()=>{const N=Cr.getState();if(N.available&&N.info){F(!0);return}it.checkForUpdates().then(()=>{const{available:Z,error:ne}=Cr.getState();if(ne){oe.error("Failed to check for updates",{description:ne});return}if(!Z){oe.success("You are on the latest version");return}F(!0)})},[it]),Jn=jf(),Ti=l.useCallback(()=>{if(t&&Xe(!1),r?.(),Jn?.openSettings){Jn.openSettings();return}_e(!0)},[Jn,t,r,Xe,_e]),ed=it.available&&(it.runtimeType==="desktop"||it.runtimeType==="web"),td=Me(N=>N.deleteSession),Mi=Me(N=>N.deleteSessions),nd=Me(N=>N.unarchiveSession),sd=Me(N=>N.unarchiveSessions),{copiedSessionId:rd,handleSessionSelect:od,handleSessionDoubleClick:id,handleSaveEdit:ad,handleCancelEdit:ld,handleShareSession:cd,handleCopyShareUrl:dd,handleCopySessionId:ud,handleUnshareSession:fd,handleDeleteSession:hd,handleRestoreSession:pd,confirmDeleteSession:md}=eg({mobileVariant:t,allowReselect:o,onSessionSelected:s,isSessionSearchOpen:c,sessionSearchQuery:u,setSessionSearchQuery:f,setIsSessionSearchOpen:d,setActiveMainTab:se,setSessionSwitcherOpen:Xe,setCurrentSession:Dt,updateSessionTitle:Hn,shareSession:En,unshareSession:Dn,deleteSession:td,deleteSessions:Mi,unarchiveSession:nd,childrenMap:_t,showDeletionDialog:gt,setDeleteSessionConfirm:ae,deleteSessionConfirm:L,setEditingId:p,setEditTitle:y,editingId:g,editTitle:h}),gd=l.useCallback(()=>{if(!J)return;const{scopeKey:N,folderId:Z}=J;le(null),Ve(N,Z)},[J,Ve]),Zr=l.useCallback(()=>{Js.requestDirectoryDialog()},[]),bd=l.useCallback(N=>{A(Z=>{const ne=Rh(Z,N);try{w.setItem(Xa,JSON.stringify(Array.from(ne)))}catch{}return ne})},[w]),Fi=l.useCallback((N,Z)=>{if(!N)return null;Z&&He.has(Z)&&xt(Z);const ne=Lt(N,"New folder",Z);return M(ne.id),W(ne.name),ne},[He,xt,Lt]),Es=Pt(od),xd=Pt(id),yd=Pt(ad),wd=Pt(ld),vd=Pt(cd),Sd=Pt(dd),jd=Pt(ud),Cd=Pt(fd),kd=Pt(hd),Ad=Pt(pd),eo=Pt(Fi),Li=l.useCallback((N,Z)=>{q(ne=>{const Le=new Map(ne);return Le.set(N,Z+7),Le})},[]),dr=l.useCallback(N=>{q(Z=>{if(!Z.has(N))return Z;const ne=new Map(Z);return ne.delete(N),ne})},[]),Oi=l.useCallback(N=>{q(Z=>{let ne=!1;const Le=new Map(Z),Oe=`${N}:`;for(const et of Le.keys())et.startsWith(Oe)&&(Le.delete(et),ne=!0);return ne?Le:Z})},[]),to=l.useCallback(N=>{Ce.current=Date.now()+150,Oi(N),S(Z=>{const ne=new Set(Z);ne.has(N)?ne.delete(N):ne.add(N);try{w.setItem(Va,JSON.stringify(Array.from(ne)))}catch{}return Rt(ne),ne})},[Oi,w,Rt]),Bi=l.useRef(null);l.useEffect(()=>{const N=Bi.current;Bi.current=Se,Qe==="folder"&&(!N||!Se||N===Se||j.has(Se)&&to(Se))},[Se,j,Qe,to]);const Tn=l.useMemo(()=>he.map(N=>({...N,normalizedPath:Re(N.path)})).filter(N=>!!N.normalizedPath),[he]),Nd=l.useMemo(()=>Tn.map(N=>N.normalizedPath),[Tn]),_i=Cf(e?Nd:jo);ag({enabled:e,normalizedProjects:Tn,gitRepoStatus:_i,setProjectRepoStatus:z,setProjectRootBranches:Be});const Id=l.useMemo(()=>mg(at,Tn,nt,wt),[wt,nt,Tn,at]);ug({enabled:e,hasAuthoritativeGlobalSessions:on,sessions:qn});const{getSessionsForProject:Ed,getArchivedSessionsForProject:zi}=lg({ownership:Id}),no=l.useRef(!1);Se&&P.has(Se)&&(no.current=!!P.get(Se));const so=dt(N=>N.manualProjectOrder),Ui=l.useRef(new Set),ur=Ph(Ui.current,v,"project");Ui.current=ur;const ro={isVisible:e,mobileVariant:t,onSessionSelected:s,allowReselect:o,hideDirectoryControls:i,showOnlyMainWorkspace:a,isTablet:ce,catalogSessions:yt,archivedSessions:wt,projects:he,activeProjectId:Se,manualProjectOrder:so,currentDirectory:ve,availableWorktreesByProject:nt,pinnedSessionIds:X,sessionOrderRanks:ee,foldersMap:ft,collapsedFolderIds:He,gitBranches:Qt,gitRepoStatus:_i,updateStore:it,projectRepoStatus:P,projectRootBranches:re,resolvedWorktreeTopologyKey:As,unresolvedWorktreeProjectPaths:O,isSessionSearchOpen:c,sessionSearchQuery:u,editingId:g,editTitle:h,editingProjectDialogId:x,expandedParents:v,collapsedProjects:j,visibleSessionCountByGroup:K,updateDialogOpen:H,openSidebarMenuKey:D,renamingFolderId:I,renameFolderDraft:G,deleteSessionConfirm:L,deleteFolderConfirm:J,bulkDeleteConfirm:B,collapsedGroups:me},$i=l.useRef(null),Ki=$i.current;if(Ki){let N=!1;for(const Z of Object.keys(ro))Object.is(Ki[Z],ro[Z])||(Wt(`ui.session_sidebar.source.${Z}`),N=!0);N||Wt("ui.session_sidebar.source.parent_or_context")}$i.current=ro;const Wi=l.useMemo(()=>{const N=new Map(so.map((Z,ne)=>[Z,ne]));return[...Tn].sort((Z,ne)=>(N.get(Z.id)??1/0)-(N.get(ne.id)??1/0))},[so,Tn]),{projectSections:xn,groupSearchDataByGroup:Gi,sectionsForRender:Dd,flatSectionsForRender:oo,searchMatchCount:Rd}=Fm({normalizedProjects:Wi,getSessionsForProject:Ed,getArchivedSessionsForProject:zi,availableWorktreesByProject:nt,projectRepoStatus:P,projectRootBranches:re,lastRepoStatus:no.current,buildGroupedSessions:St,hasSessionSearchQuery:De,normalizedSessionSearchQuery:Ne,filterSessionNodesForSearch:Je,buildGroupSearchText:ht,foldersMap:ft,alwaysIncludeArchived:Qe==="timeline"}),Ds=l.useMemo(()=>{const ne=(De||Qe==="timeline"?[...at,...wt]:at).filter(Oe=>Zs(cs(Oe),Q));if(ne.length===0)return null;const Le=St(ne,"~",[],null,!1).map(Oe=>De?{...Oe,sessions:Je(Oe.sessions,Ne)}:Oe).filter(Oe=>Oe.sessions.length>0);return Le.length===0?null:{project:{id:"__home__",path:"~",normalizedPath:"~",label:"No folder"},groups:Le}},[wt,St,Je,De,Q,Ne,at,Qe]),Pd=l.useCallback(N=>Zs(cs(N),Q),[Q]),Td=Gm({viewMode:Qe,enabled:!De&&!a,projects:Wi,archivedSessions:wt,getArchivedSessionsForProject:zi,isGlobalSession:Pd,buildGroupedSessions:St,availableWorktreesByProject:nt,projectRepoStatus:P,projectRootBranches:re,lastRepoStatus:no.current,selectedSpaceId:C,selectedWorktreePath:E,homeDirectory:Q}),Md=l.useMemo(()=>{if(!De||!Ds)return 0;const N=Z=>Z.reduce((ne,Le)=>ne+1+N(Le.children),0);return Ds.groups.reduce((Z,ne)=>Z+N(ne.sessions),0)},[Ds,De]),Fd=l.useMemo(()=>n.jsxs("div",{className:"py-6 text-center text-muted-foreground",children:[n.jsx("p",{className:"typography-ui-label font-semibold",children:"No matching sessions"}),n.jsx("p",{className:"typography-meta mt-1",children:"Try a different title, branch, folder, or path."})]}),[]),{getOrderedGroups:Ld}=Tm(V),{sectionsForSidebarRender:Od,filteredSectionsForSidebarRender:Bd,totalSessionCount:_d,sessionCountByProject:zd,hasActiveSessionByProject:Ud,activeDirectoriesByProject:Rs,hasUnseenByProject:$d}=$m({projectSections:xn,flatSectionsForRender:oo,sectionsForRender:Dd,selectedSpaceId:C,selectedWorktreePath:E,homeDirectory:Q,activeSessionIdSet:pe,unreadSessionIdSet:be}),io=l.useCallback(N=>{if(Zn.getState().selectSpace(N),!N)return;Ue(N);const Z=xn.find(Oe=>Oe.project.id===N),ne=Z?.groups.find(Oe=>Oe.isMain),Le=ne?.sessions[0]?.session;Le?Es(Le.id,ne?.directory??Z?.project.normalizedPath??null,{keepPanelOpen:!0}):Z&&At({selectedProjectId:N,directoryOverride:Z.project.normalizedPath})},[At,xn,Ue,Es]),Kd=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",Wd=t?"size-5":"size-4",fr=Pt((N,Z=0,ne,Le,Oe=!1,et,yn="project",Xn)=>n.jsx(dx,{node:N,depth:Z,groupDirectory:ne,projectId:Le,archivedBucket:Oe,pinnedSessionIds:X,expandedParents:ur,hasSessionSearchQuery:De,normalizedSessionSearchQuery:Ne,editingId:g,setEditingId:p,editTitle:h,setEditTitle:y,handleSaveEdit:yd,handleCancelEdit:wd,toggleParent:bd,handleSessionSelect:Es,handleSessionDoubleClick:xd,togglePinnedSession:ze,handleShareSession:vd,copiedSessionId:rd,handleCopyShareUrl:Sd,handleCopySessionId:jd,handleUnshareSession:Cd,openSidebarMenuKey:D,setOpenSidebarMenuKey:T,renamingFolderId:I,getFoldersForScope:sn,getSessionFolderId:ot,removeSessionFromFolder:Et,addSessionToFolder:rn,createFolderAndStartRename:eo,handleDeleteSession:kd,handleRestoreSession:Ad,mobileVariant:t,alwaysShowActions:ye,allowQuickArchiveAction:$e,renderSessionNode:fr,secondaryMeta:et,renderContext:yn,subtreeContainsEditing:Xn?.subtreeContainsEditing??jx,menuOpenSessionId:Xn?.menuOpenSessionId??null,nodeStructureKey:Xn?.nodeStructureKey??"",childRenderExtrasFor:Xn?.childRenderExtrasFor})),Gd=l.useMemo(()=>{const N=new Map;return oo.forEach(Z=>{const ne=Z.groups[0];ne?.folderScopes&&ne.folderScopes.length>0&&N.set(Z.project.id,ne.folderScopes)}),N},[oo]),Hd=l.useCallback((N,Z)=>{const ne=[];return Z.forEach(Le=>{ne.push(Le.directory),Le.folderScopes?.forEach(Oe=>ne.push(Oe.directory))}),n.jsx(bx,{directories:ne})},[]),Hi=l.useCallback(N=>{dr(N),Pe(Z=>{const ne=new Set(Z);return ne.has(N)?ne.delete(N):ne.add(N),ne})},[dr]),qd=l.useCallback((N,Z,ne,Le,Oe,et)=>n.jsx(nb,{group:N,groupKey:Z,projectId:ne,hideGroupLabel:Le,dragHandleProps:Oe,compactBodyPadding:et,hasSessionSearchQuery:De,normalizedSessionSearchQuery:Ne,groupSearchDataByGroup:Gi,visibleSessionCount:K.get(Z),collapsedGroups:me,hideDirectoryControls:i,collapsedFolderIds:He,toggleFolderCollapse:xt,renameFolder:Ot,deleteFolder:Ve,showDeletionDialog:gt,setDeleteFolderConfirm:le,renderSessionNode:fr,showMoreGroupSessions:Li,resetGroupSessionLimit:dr,mobileVariant:t,alwaysShowActions:ye,activeProjectId:Se,setActiveProjectIdOnly:Ue,setActiveMainTab:se,setSessionSwitcherOpen:Xe,openNewSessionDraft:At,addSessionToFolder:rn,createFolderAndStartRename:eo,renamingFolderId:I,renameFolderDraft:G,setRenameFolderDraft:W,setRenamingFolderId:M,pinnedSessionIds:X,expandedParents:ur,sessionOrderIndex:de,editingId:g,editTitle:h,openSidebarMenuKey:D,activeActivitySessionIds:pe,unreadActivitySessionIds:be,onToggleCollapsedGroup:Hi}),[De,Ne,Gi,K,me,i,He,xt,Ot,Ve,gt,fr,Li,dr,t,ye,Se,Ue,se,Xe,At,rn,eo,I,G,X,ur,de,g,h,D,pe,be,Hi]),qi=!!(I||g||x),Vi=l.useRef(at);Vi.current=at;const Vd=l.useCallback(N=>Vi.current.find(Z=>Z.id===N)?.directory??null,[]),{selectionModeEnabled:ao,hasSelection:Yi,selectedIdsSize:Yd,bulkScopeIsArchived:Qd,derivedSelectionScope:Jd,bulkScopeFolders:Xd,bulkCanRemoveFromFolder:Zd,handleToggleSelectionMode:eu,handleExitSelectionMode:tu,handleBulkMoveToFolder:nu,handleBulkCreateFolderAndMove:su,handleBulkRemoveFromFolder:ru,handleBulkDelete:ou,handleBulkRestore:iu,confirmBulkDelete:au}=wx({isInlineEditing:qi,showDeletionDialog:gt,foldersMap:ft,folderScopesByProject:Gd,addSessionsToFolder:In,removeSessionsFromFolders:Gn,createFolderAndStartRename:Fi,resolveSessionDirectory:Vd,unarchiveSessions:sd,deleteSessions:Mi,setBulkDeleteConfirm:$}),Qi=l.useCallback(()=>{ue.getState().closeMainSurfaces(),se("chat"),t&&Xe(!1),vt(),r?.()},[t,r,vt,se,Xe]),lu=l.useCallback((N,Z)=>{const ne=he.find(et=>et.id===N);if(!ne)return;const Le=Re(Z.path)?.toLowerCase(),Oe=!!(Le&&Rs.get(N)?.has(Le));Y({projectId:N,projectPath:ne.path,worktree:Z,hasActiveSession:Oe})},[Rs,he]),cu=l.useCallback(async({force:N})=>{const Z=Ie;if(!Z)return;const ne=Re(Z.worktree.path)?.toLowerCase();if(!!(ne&&Rs.get(Z.projectId)?.has(ne))){Y({...Z,hasActiveSession:!0}),oe.warning("Stop the active session before closing this worktree.");return}if(!Bt.deleteGitWorktree){oe.error("Closing worktrees is not supported by this runtime.");return}try{if(!(await Bt.deleteGitWorktree(Z.projectPath,{directory:Z.worktree.path,force:N}))?.success)throw new Error("Git worktree removal was not confirmed by the server.");let et=await an(Z.projectPath,Bt,{force:!0});const yn=Re(Z.worktree.path);et!==null&&yn!==null&&et.some(uu=>Re(uu.path)===yn)&&(et=await an(Z.projectPath,Bt,{force:!0}));const Xn=yn!==null&&Re(ve)===yn,du=yn!==null&&C===Z.projectId&&Re(E)===yn;(Xn||du)&&io(Z.projectId),Y(null),et===null?oe.warning("Worktree closed, but the sidebar could not be refreshed."):oe.success("Worktree closed.")}catch(Oe){const et=Oe instanceof Error?Oe.message:"Try again.";oe.error("Failed to close worktree.",{description:et})}},[Rs,Ie,ve,Bt,io,an,C,E]);return n.jsx(kf,{delay:400,closeDelay:150,timeout:600,children:n.jsxs("div",{ref:m,className:_("relative flex h-full flex-col text-foreground overflow-x-hidden",t?"":"bg-transparent"),children:[n.jsx(qm,{projectSections:xn,activeProjectId:Se,initialActiveSessionByProject:xe,persistActiveSessionByProject:te,handleSessionSelect:Es,mobileVariant:t,openNewSessionDraft:vt,setActiveMainTab:se,setSessionSwitcherOpen:Xe}),!i&&!t?n.jsx(rb,{onNewSession:Qi,showSidebarToggle:!0}):null,n.jsx(sb,{hideDirectoryControls:i,handleOpenDirectoryDialog:Zr,onOpenArchive:()=>{t&&Xe(!1),Yt(!0)},onOpenSettings:t?Ti:void 0,onOpenInstances:t?Jn?.openInstances:void 0,instanceLabel:t?Jn?.instanceLabel:void 0,onOpenUpdate:t?Jn?.openUpdate:void 0,headerActionIconClass:Wd,headerActionButtonClass:Kd,isSessionSearchOpen:c,setIsSessionSearchOpen:d,sessionSearchInputRef:b,sessionSearchQuery:u,setSessionSearchQuery:f,hasSessionSearchQuery:De,searchMatchCount:Rd+(Qe!=="workspace"||C===null?Md:0),selectionModeEnabled:ao,onToggleSelectionMode:eu,mobileVariant:t,onClose:t?()=>Xe(!1):void 0}),gn==="error"||gn==="unavailable"?n.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&&xn.length>0&&Qe==="workspace"?n.jsx(ab,{projects:xn.map(N=>N.project),selectedProjectId:C,selectedWorktreePath:E,worktreesByProject:nt,worktreeErrorsByProject:ln,onSelectProject:io,onSelectWorktree:(N,Z)=>{Zn.getState().selectWorktree(N,Z),Ue(N);const Oe=xn.find(et=>et.project.id===N)?.groups.find(et=>Re(et.directory)===Re(Z))?.sessions[0]?.session;Oe?Es(Oe.id,Z,{keepPanelOpen:!0}):At({selectedProjectId:N,directoryOverride:Z})},onCloseWorktree:lu,onOpenDirectoryDialog:Zr,onOpenProjectEditDialog:k,onRemoveProject:qe,totalSessionCount:_d,getSessionCountForProject:N=>zd.get(N)??0,hasActiveSessionByProject:Ud,activeDirectoriesByProject:Rs,hasUnseenByProject:$d,homeDirectory:Q,mobileVariant:t}):null,n.jsx(Mb,{viewMode:Qe,timelineBoundaries:Ct,onOpenDirectoryDialog:Zr,stickyFolderHeaders:Ee,sectionsForRender:Qe==="workspace"?Bd:Od,allFoldersOnlySection:Qe==="workspace"?C===null?Ds:null:Ds,isAllFoldersView:Qe==="workspace"?C===null:Qe==="timeline",projectSections:xn,activeProjectId:Se,showOnlyMainWorkspace:a,hasSessionSearchQuery:De,emptyState:Yn,searchEmptyState:Fd,pinnedSessionIds:X,archivedShelfItems:Td,renderSessionNode:fr,renderGroupSessions:qd,homeDirectory:Q,collapsedProjects:j,hideDirectoryControls:i,projectRepoStatus:P,mobileVariant:t,alwaysShowActions:ye,toggleProject:to,setActiveProjectIdOnly:Ue,setActiveMainTab:se,setSessionSwitcherOpen:Xe,openNewSessionDraft:At,openProjectEditDialog:k,removeProject:qe,reorderProjects:ge,getOrderedGroups:Ld,setGroupOrderByProject:fe,renderProjectStatusIndicator:Hd,openSidebarMenuKey:D,setOpenSidebarMenuKey:T,isInlineEditing:qi}),t&&!(ao&&Yi)?n.jsxs("div",{className:"flex shrink-0 flex-col gap-2 px-4 pb-[calc(0.75rem+var(--oc-safe-area-bottom,0px))] pt-2",children:[n.jsx(pc,{variant:"mobile"}),n.jsxs(Ae,{type:"button",variant:"default",size:"lg",className:"w-full",onClick:Qi,children:[n.jsx(R,{name:"chat-new",className:"size-4"}),"New session"]})]}):null,ao&&Yi?n.jsx(xx,{selectedCount:Yd,scopeKey:Jd,scopeFolders:Xd,archivedBucket:Qd,onMoveToFolder:nu,onCreateFolderAndMove:su,onRemoveFromFolder:ru,canRemoveFromFolder:Zd,onRestore:iu,onDelete:ou,onDone:tu}):null,t?null:n.jsx(lb,{onOpenSettings:Ti,onOpenShortcuts:mt,onOpenAbout:()=>{st("about"),_e(!0)},onOpenUpdate:Qn,showRuntimeButtons:!0,showUpdateButton:ed}),n.jsx(gx,{updateDialogOpen:H,setUpdateDialogOpen:F,updateStore:it,editingProject:Is,setEditingProjectDialogId:k,handleSaveProjectEdit:cr,deleteSessionConfirm:L,setDeleteSessionConfirm:ae,showDeletionDialog:gt,setShowDeletionDialog:It,confirmDeleteSession:md,deleteFolderConfirm:J,setDeleteFolderConfirm:le,confirmDeleteFolder:gd,closeWorktreeConfirm:Ie,setCloseWorktreeConfirm:Y,confirmCloseWorktree:cu,bulkDeleteConfirm:B,setBulkDeleteConfirm:$,confirmBulkDelete:au})]})})},Nv=l.memo(Cx),Za=6,Tt=.18,zs=1.2,Us=.38,Er=48,kx=(e,t)=>e==="left"?t<0:t>0,Iv=(e,t,s)=>Math.min(1,Math.max(0,e==="left"?1+t/s:1-t/s)),Ev=(e,t)=>t>=.999?"none":e==="left"?`translateX(${(t-1)*100}%)`:`translateX(${(1-t)*100}%)`,el=(e,t,s,r)=>e==="left"?t?Math.min(1,Math.max(0,1+s/r)):Math.min(1,Math.max(0,s/r)):t?Math.min(1,Math.max(0,1-s/r)):Math.min(1,Math.max(0,-s/r)),Dv=e=>{const{side:t,dx:s,dy:r,dt:o,progress:i,isDragging:a}=e,c=s/Math.max(1,o);if(a){const d=t==="left"?c<-Tt:c>Tt,u=t==="left"?c>Tt:c<-Tt;return d||!u&&i<Us}return Math.abs(s)>=Er&&Math.abs(r)<=Math.abs(s)*zs&&kx(t,s)},Ax=e=>{const{side:t,isOpenAtStart:s,dx:r,dt:o,progress:i}=e,a=r/Math.max(1,o);return t==="left"?s?a<-Tt?!1:a>Tt?!0:i>Us:a>Tt?!0:a<-Tt?!1:i>Us:s?a>Tt?!1:a<-Tt?!0:i>Us:a<-Tt?!0:a>Tt?!1:i>Us},Nx='button, a, input, textarea, select, [contenteditable="true"], [data-no-drawer-swipe]',Ix=(e,t,s)=>{if(!(e instanceof Element))return!1;if(s?.excludeInteractive??!0){const i=e.closest(Nx);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},Dr=Object.freeze({chunks:Object.freeze([]),byteLength:0,lastSequence:-1}),xi=512*1024,Ex=new TextEncoder,Dx=new TextDecoder,Co=e=>{const t=Ex.encode(e);if(t.byteLength<=xi)return{text:e,byteLength:t.byteLength};let s=t.byteLength-xi;for(;s<t.byteLength&&(t[s]&192)===128;)s+=1;const r=t.subarray(s);return{text:Dx.decode(r),byteLength:r.byteLength}},ns=(e,t)=>`${e}\0${t}`,ko=(e,t)=>{let s=null;for(const r of e.keys())t(r)&&(s??=new Map(e),s.delete(r));return s},Rx="terminal-store";let tl=!1,nl=0;const jr=()=>typeof globalThis.crypto?.randomUUID=="function"?`tab-${globalThis.crypto.randomUUID()}`:(nl+=1,`tab-${Date.now().toString(36)}-${nl.toString(36)}`),Ao=e=>typeof e=="object"&&e!==null,Px=e=>{const t=/^tab-(\d+)$/.exec(e);if(!t)return null;const s=Number(t[1]);return Number.isFinite(s)?s:null};function lt(e){let t=e.trim();for(;t.length>1&&t.endsWith("/");)t=t.slice(0,-1);return t}const Tx=/^Terminal(?: (\d+))?$/,Mx=e=>{let t=0;for(const s of e){const r=Tx.exec(s.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}`},No=(e,t)=>({id:e,terminalSessionId:null,lifecycle:"idle",label:t,iconKey:null,isConnecting:!1,createdAt:Date.now(),previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1}),Io=e=>({tabs:[e],activeTabId:e.id}),Ut=(e,t)=>e.tabs.findIndex(s=>s.id===t);let Eo=null,Do=null;const Fx=e=>{if(Do&&Eo?.sessions===e.sessions&&Eo.nextTabId===e.nextTabId)return Do;const t={sessions:Array.from(e.sessions.entries()).map(([s,r])=>[s,{activeTabId:r.activeTabId,tabs:r.tabs.map(o=>({id:o.id,label:o.label,iconKey:o.iconKey,createdAt:o.createdAt}))}]),nextTabId:e.nextTabId};return Eo={sessions:e.sessions,nextTabId:e.nextTabId},Do=t,t},Lx=()=>{const e=Th(()=>lh());if(!e)return;let t=null;return{getItem:s=>e.getItem(s),setItem:(s,r)=>{if(r.state!==t)return t=r.state,e.setItem(s,r)},removeItem:s=>(t=null,e.removeItem(s))}},we=Nn()(Gr(Ql((e,t)=>({sessions:new Map,buffers:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1,hasHydrated:typeof window>"u",ensureDirectory:s=>{const r=lt(s);r&&e(o=>{if(o.sessions.has(r))return o;const i=new Map(o.sessions),a=jr(),c=No(a,"Terminal");return i.set(r,Io(c)),{sessions:i,nextTabId:o.nextTabId+1}})},getDirectoryState:s=>{const r=lt(s);return t().sessions.get(r)},getActiveTab:s=>{const r=lt(s),o=t().sessions.get(r);if(!o)return;const i=o.activeTabId;return i?o.tabs.find(a=>a.id===i)??o.tabs[0]:o.tabs[0]},getBuffer:(s,r)=>t().buffers.get(ns(lt(s),r))??Dr,createTab:s=>{const r=lt(s);if(!r)return"tab-invalid";const o=jr();return e(i=>{const a=new Map(i.sessions),c=a.get(r),d=i.nextTabId+1,u=Mx(c?.tabs??[]),f=No(o,u);return c?a.set(r,{...c,tabs:[...c.tabs,f]}):a.set(r,Io(f)),{sessions:a,nextTabId:d}}),o},setActiveTab:(s,r)=>{const o=lt(s);e(i=>{const a=new Map(i.sessions),c=a.get(o);return!c||c.activeTabId===r||Ut(c,r)<0?i:(a.set(o,{...c,activeTabId:r}),{sessions:a})})},setTabLabel:(s,r,o)=>{const i=lt(s),a=o.trim();a&&e(c=>{const d=new Map(c.sessions),u=d.get(i);if(!u)return c;const f=Ut(u,r);if(f<0||u.tabs[f]?.label===a)return c;const m=[...u.tabs];return m[f]={...m[f],label:a},d.set(i,{...u,tabs:m}),{sessions:d}})},setTabIconKey:(s,r,o)=>{const i=lt(s);e(a=>{const c=new Map(a.sessions),d=c.get(i);if(!d)return a;const u=Ut(d,r);if(u<0)return a;const f=o?.trim()||null;if(d.tabs[u]?.iconKey===f)return a;const m=[...d.tabs];return m[u]={...m[u],iconKey:f},c.set(i,{...d,tabs:m}),{sessions:c}})},closeTab:(s,r)=>{const o=lt(s);e(i=>{const a=new Map(i.sessions),c=a.get(o);if(!c)return i;const d=Ut(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))),m=Object.keys(f).length!==Object.keys(i.projectActionRuns).length,b=ns(o,r),g=i.buffers.has(b)?ko(i.buffers,h=>h===b):null;if(u.length===0){const h=jr(),y=No(h,"Terminal");return a.set(o,Io(y)),{sessions:a,nextTabId:i.nextTabId+1,...g?{buffers:g}:{},...m?{projectActionRuns:f}:{}}}let p=c.activeTabId;return c.activeTabId===r&&(p=u[Math.min(d,u.length-1)]?.id??u[0]?.id??null),a.set(o,{...c,tabs:u,activeTabId:p}),{sessions:a,...g?{buffers:g}:{},...m?{projectActionRuns:f}:{}}})},setTabSessionId:(s,r,o)=>{const i=lt(s);e(a=>{const c=new Map(a.sessions),d=c.get(i);if(!d)return a;const u=Ut(d,r);if(u<0)return a;const f=d.tabs[u],m=o!==null&&f.terminalSessionId!==o,b=o?"running":f.terminalSessionId?"exited":f.lifecycle,g={...f,terminalSessionId:o,lifecycle:b,isConnecting:!1},p=ns(i,r),h=m&&a.buffers.has(p)?ko(a.buffers,x=>x===p):null,y=[...d.tabs];return y[u]=g,c.set(i,{...d,tabs:y}),{sessions:c,...h?{buffers:h}:{}}})},setTabLifecycle:(s,r,o)=>{const i=lt(s);e(a=>{const c=new Map(a.sessions),d=c.get(i);if(!d)return a;const u=Ut(d,r);if(u<0)return a;const f=[...d.tabs];return f[u]={...f[u],lifecycle:o,isConnecting:!1},c.set(i,{...d,tabs:f}),{sessions:c}})},setConnecting:(s,r,o)=>{const i=lt(s);e(a=>{const c=new Map(a.sessions),d=c.get(i);if(!d)return a;const u=Ut(d,r);if(u<0)return a;const f=[...d.tabs];return f[u]={...f[u],isConnecting:o},c.set(i,{...d,tabs:f}),{sessions:c}})},replaceBuffer:(s,r,o,i)=>{const a=lt(s);e(c=>{const d=c.sessions.get(a);if(!d||Ut(d,r)<0)return c;const u=ns(a,r),f=c.buffers.get(u)??Dr;if(f.lastSequence>i)return c;const m=Co(o);if(f.lastSequence===i&&f.byteLength===m.byteLength&&f.chunks.map(p=>p.data).join("")===m.text)return c;const b=c.nextChunkId,g=new Map(c.buffers);return g.set(u,{chunks:m.text?[{id:b,data:m.text,byteLength:m.byteLength}]:[],byteLength:m.byteLength,lastSequence:i}),{buffers:g,nextChunkId:m.text?b+1:b}})},appendToBuffer:(s,r,o,i,a)=>{if(!o)return;const c=lt(s);e(d=>{const u=d.sessions.get(c);if(!u||Ut(u,r)<0)return d;const f=ns(c,r),m=d.buffers.get(f)??Dr;if(i!==void 0&&i<=m.lastSequence)return d;const b=d.nextChunkId,g=Co(o),p=a!==void 0&&a!==o?Co(a).text:void 0,h={id:b,data:g.text,...p!==void 0?{replayData:p}:{},byteLength:g.byteLength},y=[...m.chunks,h];let x=m.byteLength+h.byteLength;for(;x>xi&&y.length>1;){const v=y.shift();if(!v)break;x-=v.byteLength}const k=new Map(d.buffers);return k.set(f,{chunks:y,byteLength:x,lastSequence:i??m.lastSequence}),{buffers:k,nextChunkId:b+1}})},setTabPreviewUrl:(s,r,o,i={})=>{const a=lt(s);e(c=>{const d=new Map(c.sessions),u=d.get(a);if(!u)return c;const f=Ut(u,r);if(f<0)return c;const m=u.tabs[f],b=i.autoOpened??m.previewAutoOpened,g=i.locked??m.previewUrlLocked;if(m.previewUrl===o&&m.previewAutoOpened===b&&m.previewUrlLocked===g)return c;const p=[...u.tabs];return p[f]={...m,previewUrl:o,previewAutoOpened:b,previewUrlLocked:g},d.set(a,{...u,tabs:p}),{sessions:d}})},markPreviewAutoOpened:(s,r)=>{const o=lt(s);e(i=>{const a=new Map(i.sessions),c=a.get(o);if(!c)return i;const d=Ut(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},a.set(o,{...c,tabs:f}),{sessions:a}})},setProjectActionRun:s=>{e(r=>{const o=r.projectActionRuns[s.key];return o&&o.directory===s.directory&&o.actionId===s.actionId&&o.tabId===s.tabId&&o.sessionId===s.sessionId&&o.status===s.status?r:{projectActionRuns:{...r.projectActionRuns,[s.key]:s}}})},updateProjectActionRunStatus:(s,r)=>{e(o=>{const i=o.projectActionRuns[s];return!i||i.status===r?o:{projectActionRuns:{...o.projectActionRuns,[s]:{...i,status:r}}}})},removeProjectActionRun:s=>{e(r=>{if(!r.projectActionRuns[s])return r;const o={...r.projectActionRuns};return delete o[s],{projectActionRuns:o}})},removeDirectory:s=>{const r=lt(s);e(o=>{const i=new Map(o.sessions);i.delete(r);const a=ns(r,""),c=ko(o.buffers,u=>u.startsWith(a)),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:Rx,storage:Lx(),partialize:Fx,merge:(e,t)=>{if(!Ao(e))return t;const s=Array.isArray(e.sessions)?e.sessions:[],r=new Map;let o=0;for(const c of s){if(!Array.isArray(c)||c.length!==2)continue;const[d,u]=c;if(typeof d!="string"||!Ao(u))continue;const f=Array.isArray(u.tabs)?u.tabs:[],m=[],b=new Map;for(const y of f){if(!Ao(y))continue;const x=typeof y.id=="string"?y.id:null;if(!x)continue;const k=Px(x);k!==null&&(o=Math.max(o,k));const v=k===null?x:jr();b.set(x,v),m.push({id:v,label:typeof y.label=="string"?y.label:"Terminal",iconKey:typeof y.iconKey=="string"?y.iconKey:null,terminalSessionId:null,lifecycle:"idle",createdAt:typeof y.createdAt=="number"?y.createdAt:Date.now(),isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(m.length===0)continue;const g=typeof u.activeTabId=="string"?u.activeTabId:null,p=g?b.get(g)??g:null,h=p?m.some(y=>y.id===p):!1;r.set(d,{tabs:m,activeTabId:h?p:m[0].id})}const i=typeof e.nextTabId=="number"&&Number.isFinite(e.nextTabId)?e.nextTabId:1,a=Math.max(t.nextTabId,i,o+1);return{...t,sessions:r,buffers:new Map,nextChunkId:1,nextTabId:a,hasHydrated:!0}}})));if(typeof window<"u"&&!tl){tl=!0;const e=we.persist,t=()=>{we.getState().hasHydrated||we.setState({hasHydrated:!0})};e?.hasHydrated?.()?t():e?.onFinishHydration?e.onFinishHydration(t):t()}const Ox=(e,t)=>{const s=`${e??""} ${t??""}`;return/mac|iphone|ipad|darwin/i.test(s)?"mac":"other"},Bx=e=>e.key.length===1?e.key.toLowerCase():e.code==="KeyC"?"c":e.code==="KeyV"?"v":e.code==="Insert"?"insert":e.key.toLowerCase(),_x=(e,t,s)=>{if(e.altKey)return null;const r=Bx(e);return t==="mac"?!e.metaKey||e.ctrlKey?null:r==="c"&&!e.shiftKey?s?"copy":"ignore":null:e.metaKey?null:e.ctrlKey&&!e.shiftKey&&r==="insert"?s?"copy":"ignore":!e.ctrlKey||!e.shiftKey?null:r==="c"?s?"copy":"ignore":null},$s=e=>typeof e=="string"&&e.trim().length>0;async function sl(e){return $s(e)?(await fn(e)).ok:!1}async function zx(){if(typeof navigator>"u"||!navigator.clipboard?.readText)return null;try{return await navigator.clipboard.readText()||null}catch{return null}}const Ux=(e,t,s,r,o)=>{if(s.width<=0||s.height<=0||r<=0||o<=0)return null;const i=Math.floor((e-s.left)/s.width*r),a=Math.floor((t-s.top)/s.height*o);return{column:Math.max(0,Math.min(r-1,i)),row:Math.max(0,Math.min(o-1,a))}},$x=(e,t)=>{const s=Math.max(0,Math.min(e.length-1,t)),r=a=>!!(a&&!/^\s+$/u.test(a));if(!r(e[s]))return{startColumn:s,endColumn:s};let o=s,i=s;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 Kx=null;const Wx=()=>Kx??=Promise.all([pt(()=>import("./vendor-xterm-xterm-B-qIQCd3.js"),[]),pt(()=>import("./vendor-xterm-addon-fit-DX4qG4td.js"),[])]).then(([e,t])=>({Xterm:e,Fit:t})),Gx=2e3,Hx=()=>{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,Gx))]).then(()=>{})},qx=(e,t,s)=>{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=`${s}px ${t}`;const o=r.measureText("M"),i=Math.ceil(o.width),a=Math.ceil((o.actualBoundingBoxAscent||s*.8)+(o.actualBoundingBoxDescent||s*.2))+2;if(i<1||a<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)/a))}},Qc=l.forwardRef(({sessionKey:e,chunks:t,onInput:s,onResize:r,theme:o,fontFamily:i,fontSize:a,className:c,enableTouchScroll:d=!1,autoFocus:u=!0,isVisible:f=!0},m)=>{const b=l.useRef(null),g=l.useRef(null),p=l.useRef(null),h=l.useRef(s),y=l.useRef(r),x=l.useRef(o),k=l.useRef(i),v=l.useRef(a),A=l.useRef(null),w=l.useRef(null),j=l.useRef(null),S=l.useRef(""),C=l.useRef(!1),E=l.useRef(0),P=l.useRef(f),z=l.useRef(!1),[K,q]=l.useState(0),[H,F]=l.useState(0),[D,T]=l.useState(!1),[I,M]=l.useState(!1);h.current=s,y.current=r,P.current=f,x.current=o,k.current=i,v.current=a,l.useLayoutEffect(()=>{const Y=b.current;if(!Y)return;const B=qx(Y,i,a);w.current=B,B&&y.current(B.cols,B.rows)},[i,a]);const G=l.useCallback(()=>{const Y=b.current,B=g.current;if(!Y||!B||!p.current||!P.current)return;const $=Y.getBoundingClientRect();if(!($.width<24||$.height<24))try{p.current.fit();const X={cols:B.cols,rows:B.rows};(!A.current||A.current.cols!==X.cols||A.current.rows!==X.rows)&&(A.current=X,y.current(X.cols,X.rows)),z.current||(z.current=!0,q(ee=>ee+1))}catch{}},[]),W=l.useCallback(()=>{if(C.current||!S.current||!g.current)return;const Y=g.current,B=S.current;if(S.current="",!B)return;C.current=!0;const $=E.current;Y.write(B,()=>{g.current!==Y||E.current!==$||(C.current=!1,S.current&&W())})},[]),L=l.useCallback(()=>{j.current=null,S.current="",C.current=!1,E.current+=1;const Y=g.current;if(!Y){F(B=>B+1);return}try{Y.reset()}catch{F(B=>B+1)}},[]),ae=l.useCallback(Y=>{Y?.preventDefault(),M($s(g.current?.getSelection())),T(!0)},[]),J=l.useCallback(Y=>{Y.stopPropagation();const B=g.current,$=B?.getSelection()??"";B?.focus(),$s($)&&sl($)},[]),le=l.useCallback(Y=>{Y.stopPropagation();const B=g.current;B?.focus(),zx().then($=>{$&&g.current===B&&B&&B.paste($)})},[]),Ie=l.useCallback(Y=>{Y.stopPropagation();const B=g.current;B?.focus();try{B?.selectAll()}catch{}M($s(B?.getSelection()))},[]);return l.useEffect(()=>{const Y=b.current;if(!Y)return;let B=!1,$=null,X=null,ee=null,ie=null,ke=[];const pe=()=>{$&&P.current&&($.options.cursorBlink=!0)},je=me=>{me.relatedTarget instanceof Node&&Y.contains(me.relatedTarget)||$&&($.options.cursorBlink=!1)},be=()=>{$&&P.current&&Y.contains(document.activeElement)&&($.options.cursorBlink=!0)},ze=()=>{$&&($.options.cursorBlink=!1)};return Y.addEventListener("focusin",pe),Y.addEventListener("focusout",je),window.addEventListener("focus",be),window.addEventListener("blur",ze),Promise.all([Wx(),Hx()]).then(([{Xterm:me,Fit:Pe}])=>{if(B)return;const V=x.current,fe=k.current,xe=v.current;$=new me.Terminal({...co(fe,xe,V),...w.current??{}});const te=new Pe.FitAddon;$.loadAddon(te),$.open(Y),g.current=$,p.current=te;const re=typeof navigator>"u"?"other":Ox(navigator.userAgentData?.platform??navigator.platform??"",navigator.userAgent??""),Be=$;$.attachCustomKeyEventHandler(Ce=>{if(Ce.type!=="keydown")return!0;const Q=Be.getSelection(),ve=_x({key:Ce.key,code:Ce.code,ctrlKey:Ce.ctrlKey,shiftKey:Ce.shiftKey,metaKey:Ce.metaKey,altKey:Ce.altKey},re,$s(Q));return ve==="copy"?(sl(Q),!1):ve!=="ignore"}),ke=[$.onData(Ce=>h.current(Ce))],X=new ResizeObserver(()=>{ee&&clearTimeout(ee),ee=setTimeout(G,80)}),X.observe(Y),G(),ie=requestAnimationFrame(G)}),()=>{B=!0;const me=document.activeElement;me instanceof HTMLElement&&Y.contains(me)&&(me.blur(),window.Capacitor?.getPlatform?.()==="android"&&pt(async()=>{const{Keyboard:V}=await import("./vendor-capacitor-keyboard-335osRpd.js");return{Keyboard:V}},__vite__mapDeps([45,10,4,6])).then(({Keyboard:V})=>V.hide()).catch(()=>{})),X?.disconnect(),ee&&clearTimeout(ee),ie!==null&&cancelAnimationFrame(ie),Y.removeEventListener("focusin",pe),Y.removeEventListener("focusout",je),window.removeEventListener("focus",be),window.removeEventListener("blur",ze),ke.forEach(Pe=>Pe.dispose()),$?.dispose(),g.current=null,p.current=null,A.current=null,j.current=null,S.current="",C.current=!1,E.current+=1,z.current=!1}},[G,H]),l.useEffect(()=>{const Y=g.current;Y&&(Y.options.theme=co(i,a,o).theme,Y.options.fontFamily=co(i,a,o).fontFamily,Y.options.fontSize=a)},[i,a,o]),l.useEffect(()=>{const Y=g.current,B=b.current;!Y||!B||(Y.options.cursorBlink=f&&document.hasFocus()&&B.contains(document.activeElement))},[f,K]),l.useEffect(()=>{if(!g.current)return;if(t.length===0){j.current!==null&&L();return}const B=j.current;let $=-1;if(B!==null){for(let ie=t.length-1;ie>=0;ie-=1){const ke=t[ie].id;if(ke===B){$=ie;break}if(ke<B)break}if($<0){L();return}}const X=$<0,ee=$>=0?t.slice($+1):t;S.current+=ee.map(ie=>X?ie.replayData??ie.data:ie.data).join(""),j.current=t.at(-1)?.id??null,W()},[t,W,K,L]),l.useEffect(()=>{if(!u||!f)return;const Y=requestAnimationFrame(()=>g.current?.focus());return()=>cancelAnimationFrame(Y)},[u,f,K,e]),l.useEffect(()=>{const Y=b.current,B=g.current;if(!d||!Y||!B)return;let $=null,X=null,ee="idle",ie=0,ke=0,pe=0,je=0,be=null;const ze=Math.max(12,a+2),me=()=>{window.Capacitor?.getPlatform?.()==="android"&&pt(async()=>{const{Keyboard:ve}=await import("./vendor-capacitor-keyboard-335osRpd.js");return{Keyboard:ve}},__vite__mapDeps([45,10,4,6])).then(({Keyboard:ve})=>ve.show()).catch(()=>{})},Pe=()=>{X&&(clearTimeout(X),X=null)},V=(Q,ve)=>{const he=Y.querySelector("canvas");return he?Ux(Q,ve,he.getBoundingClientRect(),B.cols,B.rows):null},fe=(Q,ve)=>{const he=Y.querySelector("canvas");if(!he)return;const Se=he.getBoundingClientRect(),qe=Se.left+(ve.column+.5)/B.cols*Se.width,Ue=Se.top+(ve.row+.5)/B.rows*Se.height;he.dispatchEvent(new MouseEvent(Q,{bubbles:!0,cancelable:!0,button:0,buttons:1,clientX:qe,clientY:Ue}))},xe=()=>{document.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0,button:0,buttons:0}))},te=Q=>{Q.pointerType!=="touch"||$!==null||($=Q.pointerId,ee="pending",ie=Q.clientX,ke=Q.clientY,pe=Q.clientY,je=0,be=null,Y.setPointerCapture(Q.pointerId),X=setTimeout(()=>{if(X=null,$!==Q.pointerId||ee!=="pending")return;const ve=V(ie,ke);if(!ve)return;const he=B.buffer.active,Se=Math.max(0,he.length-B.rows-he.viewportY+ve.row),qe=he.getLine(Se),Ue=Array.from({length:B.cols},(se,_e)=>qe?.getCell(_e)?.getChars()??""),U=$x(Ue,ve.column),ge={column:U.startColumn,row:ve.row};be={column:U.endColumn,row:ve.row},ee="selecting",fe("mousedown",ge),fe("mousemove",be)},350))},re=Q=>{if($!==Q.pointerId)return;if(ee==="selecting"){const Se=V(Q.clientX,Q.clientY);Se&&(!be||Se.column!==be.column||Se.row!==be.row)&&(be=Se,fe("mousemove",Se)),Q.cancelable&&Q.preventDefault();return}if(ee==="pending"){if(Math.hypot(Q.clientX-ie,Q.clientY-ke)<8)return;Pe(),ee="scrolling"}if(ee!=="scrolling")return;const ve=pe-Q.clientY;pe=Q.clientY,je+=ve;const he=Math.trunc(je/ze);he&&(B.scrollLines(he),je-=he*ze),Q.cancelable&&Q.preventDefault()},Be=Q=>{if($!==Q.pointerId)return;const ve=ee==="pending",he=ee==="selecting";Pe(),Y.hasPointerCapture(Q.pointerId)&&Y.releasePointerCapture(Q.pointerId),$=null,ee="idle",he&&xe(),ve&&(B.focus(),me())},Ce=Q=>{if($!==Q.pointerId)return;const ve=ee==="selecting";Pe(),Y.hasPointerCapture(Q.pointerId)&&Y.releasePointerCapture(Q.pointerId),$=null,ee="idle",ve&&xe()};return Y.addEventListener("pointerdown",te),Y.addEventListener("pointermove",re,{passive:!1}),Y.addEventListener("pointerup",Be),Y.addEventListener("pointercancel",Ce),()=>{Pe(),Y.removeEventListener("pointerdown",te),Y.removeEventListener("pointermove",re),Y.removeEventListener("pointerup",Be),Y.removeEventListener("pointercancel",Ce)}},[d,a,K]),l.useImperativeHandle(m,()=>({focus:()=>g.current?.focus(),fit:G,getSelection:()=>{const Y=g.current,B=Y?.getSelectionPosition(),$=Y?.getSelection()??"";return!B||!$.trim()?null:{text:$,startLine:B.start.y+1,endLine:B.end.y+1}}}),[G]),n.jsxs(Qr,{open:D,onOpenChange:T,children:[n.jsx(Jr,{render:n.jsx("div",{ref:b,"data-terminal-owner":"main",className:_("terminal-viewport-container h-full w-full overflow-hidden touch-none",c),onContextMenu:ae})}),n.jsxs(Xr,{className:"min-w-[180px]",children:[n.jsxs(_n,{disabled:!I,onClick:J,children:[n.jsx(R,{name:"file-copy",className:"mr-2 h-4 w-4"})," ","Copy"]}),n.jsxs(_n,{onClick:le,children:[n.jsx(R,{name:"clipboard",className:"mr-2 h-4 w-4"})," ","Paste"]}),n.jsx(Bc,{}),n.jsx(_n,{onClick:Ie,children:"Select all"})]})]})});Qc.displayName="TerminalViewport";const Vx=({directory:e,tabId:t,sessionId:s,sessionKey:r,isActive:o,isTerminalVisible:i,terminal:a,theme:c,fontFamily:d,fontSize:u,enableTouchScroll:f,lastViewportSizeRef:m,onInput:b,controllerRef:g})=>{const p=we(v=>e&&t?v.getBuffer(e,t).chunks:Dr.chunks),h=l.useRef(null),y=o&&i,x=l.useCallback(v=>{h.current=v,g&&(g.current=o?v:g.current),!o&&g&&g.current===v&&(g.current=null)},[g,o]);l.useEffect(()=>{if(!o||!i)return;const v=requestAnimationFrame(()=>{h.current?.fit()});return()=>cancelAnimationFrame(v)},[o,i,r,s]);const k=l.useCallback((v,A)=>{if(!o)return;const w=m.current;(!w||w.cols!==v||w.rows!==A)&&(m.current={cols:v,rows:A}),s&&a.resize({sessionId:s,cols:v,rows:A}).catch(()=>{})},[o,m,s,a]);return n.jsx("div",{className:_("h-full w-full",o?"block":"hidden"),"aria-hidden":!o,children:n.jsx(Qc,{ref:x,sessionKey:r,chunks:p,onInput:b,onResize:k,theme:c,fontFamily:d,fontSize:u,enableTouchScroll:f,autoFocus:y,isVisible:y},r)})},rl=({items:e,activeId:t,onSelect:s,onClose:r,onCreate:o,disabled:i=!1})=>{const a=e.find(c=>c.id===t)??e[0]??null;return n.jsxs(Ht,{modal:!1,children:[n.jsx(qt,{asChild:!0,children:n.jsxs(Ae,{type:"button",variant:"ghost",size:"sm",disabled:i,title:a?`Switch terminal, current: ${a.label}`:"Switch terminal","aria-label":a?`Switch terminal, current: ${a.label}`:"Switch terminal",className:"h-8 min-w-0 max-w-full justify-start gap-1.5 px-2 py-1 normal-case",children:[a?.icon??n.jsx(R,{name:"terminal",className:"size-4 shrink-0"}),n.jsx("span",{className:"min-w-0 truncate font-medium text-left",children:a?.label??"Terminal"}),n.jsx(R,{name:"arrow-down-s",className:"size-4 shrink-0 opacity-60"})]})}),n.jsxs(Vt,{align:"start",className:"w-64",children:[e.map(c=>{const d=c.id===(a?.id??t);return n.jsxs(ut,{title:c.title??c.label,onClick:()=>s(c.id),className:"group/tab min-w-0",children:[n.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[c.icon,n.jsx("span",{className:"min-w-0 flex-1 truncate",children:c.label})]}),d?n.jsx(R,{name:"check",className:"size-3.5 shrink-0 text-primary"}):null,n.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:n.jsx(R,{name:"close",className:"size-3"})})]},c.id)}),n.jsx(ps,{}),n.jsxs(ut,{onClick:o,children:[n.jsx(R,{name:"add",className:"size-3.5"}),"New tab"]})]})]})},Yx=({leading:e,icon:t,title:s,actions:r,className:o})=>n.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,s!=null?typeof s=="string"?n.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[typeof t=="string"?n.jsx(R,{name:t,className:"size-4 shrink-0 text-muted-foreground","aria-hidden":"true"}):t??null,n.jsx("h2",{className:"truncate typography-ui-label font-medium text-foreground",children:s})]}):n.jsx("div",{className:"min-w-0 flex-1",children:s}):null,r?n.jsx("div",{className:"flex shrink-0 items-center gap-1",children:r}):null]}),Qx=({isTouchTerminal:e,activeModifier:t,disabled:s,onKeyPress:r,onModifierToggle:o})=>{const i=e?"lg":"xs",a=e?"w-10 p-0":"w-9 p-0",c=d=>{e&&d.preventDefault()};return n.jsxs(n.Fragment,{children:[n.jsx(Ae,{type:"button",size:i,variant:"outline",onPointerDown:c,onClick:()=>r("esc"),disabled:s,children:"Esc"}),n.jsxs(Ae,{type:"button",size:i,variant:"outline",className:a,onPointerDown:c,onClick:()=>r("tab"),disabled:s,children:[n.jsx(R,{name:"arrow-right",className:"h-4 w-4"}),n.jsx("span",{className:"sr-only",children:"Tab"})]}),n.jsxs(Ae,{type:"button",size:i,variant:"chip","aria-pressed":t==="ctrl",className:e?"px-3":"px-2",onPointerDown:c,onClick:()=>o("ctrl"),disabled:s,children:[n.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}),n.jsx("span",{className:"sr-only",children:"Control modifier"})]}),n.jsxs(Ae,{type:"button",size:i,variant:"chip","aria-pressed":t==="alt",className:e?"px-3":"px-2",onPointerDown:c,onClick:()=>o("alt"),disabled:s,children:[n.jsx("span",{className:"text-xs font-medium",children:"Alt"}),n.jsx("span",{className:"sr-only",children:"Alt modifier"})]}),n.jsxs(Ae,{type:"button",size:i,variant:"outline",className:a,onPointerDown:c,onClick:()=>r("arrow-up"),disabled:s,children:[n.jsx(R,{name:"arrow-up"}),n.jsx("span",{className:"sr-only",children:"Arrow up"})]}),n.jsxs(Ae,{type:"button",size:i,variant:"outline",className:a,onPointerDown:c,onClick:()=>r("arrow-left"),disabled:s,children:[n.jsx(R,{name:"arrow-left"}),n.jsx("span",{className:"sr-only",children:"Arrow left"})]}),n.jsxs(Ae,{type:"button",size:i,variant:"outline",className:a,onPointerDown:c,onClick:()=>r("arrow-down"),disabled:s,children:[n.jsx(R,{name:"arrow-down"}),n.jsx("span",{className:"sr-only",children:"Arrow down"})]}),n.jsxs(Ae,{type:"button",size:i,variant:"outline",className:a,onPointerDown:c,onClick:()=>r("arrow-right"),disabled:s,children:[n.jsx(R,{name:"arrow-right"}),n.jsx("span",{className:"sr-only",children:"Arrow right"})]}),n.jsxs(Ae,{type:"button",size:i,variant:"outline",className:a,onPointerDown:c,onClick:()=>r("enter"),disabled:s,children:[n.jsx(R,{name:"arrow-go-back"}),n.jsx("span",{className:"sr-only",children:"Enter"})]})]})},Jx="\x1B",Xx=new RegExp(`${Jx}\\[[0-9;?]*[ -/]*[@-~]`,"g"),Zx=/(https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[(?:::1|::)\])(?::\d{2,5})?(?:\/[^\s<>'"`]*)?)/gi,ey=/(?:➜\s*(?:Local|Network):)|\b(?:local|network|loopback|serving|listening|available|ready|started|running|server|vite|webpack|next\.js|astro|sveltekit|nuxt)\b/i,ty=/Serving HTTP on .*? port (\d{2,5})/i,ny=new Set([".",",",";",":","!","?"]),sy=e=>{let t=e;for(;t.length>0;){const s=t[t.length-1];if(s===")"||s==="]"||s==="}"||s===">"){const r=s===")"?"(":s==="]"?"[":s==="}"?"{":"<",o=t.slice(0,-1),i=(o.match(new RegExp(`\\${r}`,"g"))||[]).length,a=(o.match(new RegExp(`\\${s}`,"g"))||[]).length;if(i>a)break;t=o;continue}if(ny.has(s)){t=t.slice(0,-1);continue}break}return t},ol=e=>{let t=sy(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},ry=e=>{if(!e)return null;const t=e.replace(Xx,""),s=t.match(ty);if(s?.[1]){const o=Number.parseInt(s[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(!ey.test(o))continue;const i=Array.from(o.matchAll(Zx));if(i.length===0)continue;const a=i.find(c=>{try{return!!new URL(ol(c[1])).port}catch{return!1}});return ol((a??i[0])[1])}return null},oy=async(e,t=1500)=>{if(!e||typeof window>"u")return!1;let s;try{s=new URL(e)}catch{return!1}if(s.protocol!=="http:"&&s.protocol!=="https:")return!1;const r=s.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 a=await tt("/api/system/probe-url",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:s.toString()}),cache:"no-store",signal:o.signal});return a.ok?(await a.json().catch(()=>null))?.ok===!0:!1}catch{return!1}finally{window.clearTimeout(i)}},iy={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},ay=(e,t)=>{if(t&&e.startsWith("arrow-")){const s=t==="ctrl"?"5":"3",r={"arrow-up":"A","arrow-down":"B","arrow-right":"C","arrow-left":"D"}[e];return`\x1B[1;${s}${r}`}return iy[e]},Jc=e=>{const t=e[0]?.toUpperCase();return!t||t<"A"||t>"Z"?null:String.fromCharCode(t.charCodeAt(0)&31)},ly=(e,t)=>e&&(t==="ctrl"?Jc(e)??e:e.length===1&&e!=="\x1B"?`\x1B${e}`:e),Xc={cols:80,rows:24},il={Tab:"tab",Enter:"enter",ArrowUp:"arrow-up",ArrowDown:"arrow-down",ArrowLeft:"arrow-left",ArrowRight:"arrow-right",Escape:"esc"};class cy{tail="";pendingUrls=new Set;probeGeneration=0;reset(){this.tail="",this.pendingUrls.clear(),this.probeGeneration+=1}scan(t,s,r,o){if(!r)return;const i=`${this.tail}${r}`.replace(/\r\n|\r/g,`
|
|
56
|
+
`),a=i.split(`
|
|
57
|
+
`),c=i.endsWith(`
|
|
58
|
+
`)?a.join(`
|
|
59
|
+
`):a.slice(0,-1).join(`
|
|
60
|
+
`);if(this.tail=i.endsWith(`
|
|
61
|
+
`)?"":(a[a.length-1]??"").slice(-1024),!c)return;const d=ry(c);if(!d||this.pendingUrls.has(d))return;const u=this.probeGeneration;this.pendingUrls.add(d),oy(d).then(f=>{if(this.pendingUrls.delete(d),!f||this.probeGeneration!==u)return;const m=we.getState().getDirectoryState(t)?.tabs.find(b=>b.id===s);!m||m.previewUrlLocked||m.previewUrl===d||o(t,s,d,{locked:!1,autoOpened:!1})})}}const dy=(e,t)=>{if(t!=="ctrl")return null;const s=e.key,r=e.code??"",o=s.length===1&&/[a-zA-Z]/.test(s)?s.toUpperCase():r.startsWith("Key")&&r.length===4?r.slice(3).toUpperCase():null;return o&&o.length===1&&o>="A"&&o<="Z"?Jc(o):null};function uy({terminal:e,effectiveDirectory:t,activeTabId:s,terminalSessionId:r,terminalLifecycle:o,hasOpenedTerminalViewport:i,terminalHydrated:a,terminalShell:c,terminalLoginShell:d,terminalAppearanceRef:u,enableTabs:f,hasActiveContext:m,focusTerminalWhenWindowActive:b,tabs:g}){const p=we(B=>B.ensureDirectory),h=we(B=>B.setTabSessionId),y=we(B=>B.setTabLifecycle),x=we(B=>B.setConnecting),k=we(B=>B.appendToBuffer),v=we(B=>B.replaceBuffer),A=we(B=>B.setTabPreviewUrl),[w,j]=l.useState(null),[S,C]=l.useState(!1),[E,P]=l.useState(!1),z=l.useRef(new Map),K=l.useRef(null),q=l.useRef(s),H=l.useRef(r),F=l.useRef(t),D=l.useRef(null),T=l.useRef(new Set),I=l.useRef(new Map),M=l.useRef(g),G=l.useRef(a),W=l.useRef(i),L=l.useRef(e);M.current=g,G.current=a,W.current=i,L.current=e;const ae=l.useCallback(()=>{const B=q.current;B&&I.current.get(B)?.reset()},[]);l.useEffect(()=>{H.current=r},[r]),l.useEffect(()=>{!r||!e.updateAppearance||e.updateAppearance(r,u.current).catch(()=>{})},[u,e,r]),l.useEffect(()=>{q.current=s},[s]),l.useEffect(()=>{F.current=t},[t]);const J=l.useCallback(()=>{for(const B of z.current.values())try{B()}catch{}z.current.clear(),K.current=null,P(!1)},[]);l.useEffect(()=>()=>{J(),H.current=null},[J]);const le=l.useCallback((B,$,X)=>{let ee=I.current.get($);ee||(ee=new cy,I.current.set($,ee)),ee.scan(B,$,X,A)},[A]),Ie=l.useCallback((B,$,X)=>{if(z.current.has(X)){K.current=X;return}const ee=ia(),ie=()=>ia()===ee&&F.current===B&&we.getState().getDirectoryState(B)?.tabs.find(pe=>pe.id===$)?.terminalSessionId===X,ke=e.connect(X,{onEvent:pe=>{if(ie())switch(pe.type){case"snapshot":{q.current===$&&H.current===X?(x(B,$,!1),j(null),C(!1),P(!1),b()):x(B,$,!1),v(B,$,pe.data??"",pe.sequence??0),le(B,$,pe.data??""),pe.status==="exited"&&y(B,$,"exited");break}case"reconnecting":{q.current===$&&(j(null),C(!1),P(!0));break}case"data":{pe.data&&(k(B,$,pe.data,pe.sequence,pe.replayData),le(B,$,pe.data));break}case"exit":{const je=typeof pe.exitCode=="number"?pe.exitCode:null,be=typeof pe.signal=="number"?pe.signal:null,me=!!we.getState().getDirectoryState(B)?.tabs.find(Pe=>Pe.id===$)?.label?.startsWith("Action:");k(B,$,`\\r\\n[Process exited${je!==null?` with code ${je}`:""}${be!==null?` (signal ${be})`:""}]\\r\\n`),y(B,$,"exited"),q.current===$&&(x(B,$,!1),j(me?null:"Terminal session ended"),C(!1),P(!1));break}}},onError:(pe,je)=>{if(!ie())return;const be=q.current===$;if(!je){be&&(j(null),C(!1));return}if(pe.code==="SESSION_NOT_FOUND"&&!we.getState().getDirectoryState(B)?.tabs.find(me=>me.id===$)?.label?.startsWith("Action:")){be&&(j(null),C(!1),x(B,$,!1),P(!1)),h(B,$,null),y(B,$,"idle");return}be&&(P(!1),j(`Connection failed: ${pe.message}`),C(!0),x(B,$,!1),y(B,$,"exited"),h(B,$,null))}});z.current.set(X,()=>ke.close()),K.current=X},[k,b,v,le,x,y,h,e]),Y=l.useMemo(()=>g.map(B=>`${B.id}:${B.terminalSessionId??""}`).join(","),[g]);return l.useEffect(()=>{if(!a||!i||!t)return;const B=t,$=new Set;for(const X of g)X.terminalSessionId&&($.add(X.terminalSessionId),Ie(B,X.id,X.terminalSessionId));for(const[X,ee]of z.current)if(!$.has(X)){try{ee()}catch{}z.current.delete(X)}},[Y,g,t,a,i,Ie]),l.useEffect(()=>ch(()=>{if(!G.current||!W.current)return;const B=F.current;if(!B)return;const $=[];for(const ee of M.current){if(!ee.terminalSessionId)continue;we.getState().getDirectoryState(B)?.tabs.find(ke=>ke.id===ee.id)?.terminalSessionId===ee.terminalSessionId&&$.push({id:ee.id,terminalSessionId:ee.terminalSessionId})}if(z.current.clear(),K.current=null,$.length===0)return;P(!0),j(null),C(!1);for(const ee of $)Ie(B,ee.id,ee.terminalSessionId);const X=D.current;if(X)for(const ee of $)L.current.resize({sessionId:ee.terminalSessionId,...X}).catch(()=>{})}),[Ie]),l.useEffect(()=>{let B=!1;if(!a||!i)return;if(!t){j(m?"No working directory available for terminal.":"Select a session to open the terminal.");return}return(async()=>{const X=t;if(!F.current||F.current!==X)return;if(!we.getState().getDirectoryState(X)){p(X);return}const ie=we.getState().getDirectoryState(X);if(!ie||ie.tabs.length===0)return;const ke=ie.activeTabId??ie.tabs[0]?.id??null;if(!ke)return;const pe=ie.tabs.find(V=>V.id===ke)??ie.tabs[0],je=pe?.terminalSessionId??null,be=pe?.lifecycle??"idle",ze=!!pe?.label?.startsWith("Action:"),me=we.getState().getBuffer(X,ke),Pe=me.byteLength>0||me.chunks.length>0;if(!je){if(be==="exited"){x(X,ke,!1);return}if(ze&&Pe){x(X,ke,!1);return}const V=`${X}\0${ke}`;if(T.current.has(V))return;const fe=D.current??Xc;T.current.add(V),j(null),C(!1),P(!1),x(X,ke,!0);try{const xe=await e.createSession({cwd:X,sessionId:ke,cols:fe.cols,rows:fe.rows,shell:c,loginShell:d,...u.current});if(!we.getState().getDirectoryState(X)?.tabs.find(Be=>Be.id===ke)){try{await e.close(xe.sessionId)}catch{}return}h(X,ke,xe.sessionId);const re=D.current;re&&(re.cols!==fe.cols||re.rows!==fe.rows)&&e.resize({sessionId:xe.sessionId,...re}).catch(()=>{});return}catch(xe){const te=we.getState().getDirectoryState(X)?.tabs.find(re=>re.id===ke);if(!te||te.terminalSessionId||(x(X,ke,!1),F.current!==X||q.current!==ke))return;j(xe instanceof Error?xe.message:"Failed to start terminal session"),C(!0),P(!1);return}finally{T.current.delete(V)}}!je||B||(H.current=je)})(),()=>{B=!0}},[m,t,r,o,s,i,f,a,p,x,y,h,e,d,c,u]),{connectionError:w,setConnectionError:j,isFatalError:S,setIsFatalError:C,isReconnectPending:E,setIsReconnectPending:P,terminalIdRef:H,lastViewportSizeRef:D,directoryRef:F,activeTabIdRef:q,disconnectStream:J,resetTerminalPreviewScan:ae,startStream:Ie}}function fy({terminal:e,terminalIdRef:t,isReconnectPending:s,setConnectionError:r,showQuickKeys:o,isTerminalVisible:i,lastViewportSizeRef:a,terminalSessionId:c,useTouchTerminalInput:d}){const[u,f]=l.useState(null),m=l.useRef(null),b=l.useCallback(()=>{d||m.current?.focus()},[d]),g=l.useCallback(()=>{d||typeof document<"u"&&!document.hasFocus()||m.current?.focus()},[d]);l.useEffect(()=>{!o&&u!==null&&f(null)},[o,u]),l.useEffect(()=>{!c&&u!==null&&f(null)},[c,u]);const p=l.useCallback(v=>{if(!v||s)return;let A=v,w=!1;u&&v.length>0&&(A=ly(v,u),w=!0);const j=t.current;j&&(e.sendInput(j,A).catch(S=>{s||r(S instanceof Error?S.message:"Failed to send input")}),w&&(f(null),b()))},[u,b,s,r,e,t]),h=l.useCallback((v,A)=>{const w=a.current;if((!w||w.cols!==v||w.rows!==A)&&(a.current={cols:v,rows:A}),!i)return;const j=t.current;j&&e.resize({sessionId:j,cols:v,rows:A}).catch(()=>{})},[i,a,e,t]),y=l.useCallback(v=>{f(A=>A===v?null:v),b()},[b]),x=l.useCallback(v=>{const A=ay(v,u);A&&(p(A),f(null),b())},[u,b,p]),k=l.useCallback(v=>{if(v.repeat)return;const A=v.key;if(!A||A==="Control"||A==="Meta"||A==="Alt"||A==="Shift")return;const w=A.length===1?A.toLowerCase():A;if(w in il){v.preventDefault(),v.stopPropagation(),x(il[w]);return}const j=dy(v,u);j&&(v.preventDefault(),v.stopPropagation(),p(j),f(null),b())},[u,b,x,p]);return l.useEffect(()=>{if(!(!o||!u||!c))return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[u,k,o,c]),{activeModifier:u,setActiveModifier:f,terminalControllerRef:m,focusTerminalController:b,focusTerminalWhenWindowActive:g,handleViewportInput:p,handleViewportResize:h,handleModifierToggle:y,handleMobileKeyPress:x}}function hy({terminal:e,effectiveDirectory:t,activeTabId:s,enableTabs:r,terminalShell:o,terminalLoginShell:i,terminalAppearanceRef:a,lastViewportSizeRef:c,directoryRef:d,activeTabIdRef:u,terminalIdRef:f,resetTerminalPreviewScan:m,startStream:b,setConnectionError:g,setIsFatalError:p,setIsReconnectPending:h}){const y=we(K=>K.createTab),x=we(K=>K.setActiveTab),k=we(K=>K.closeTab),v=we(K=>K.setTabSessionId),A=we(K=>K.setTabLifecycle),[w,j]=l.useState(!1),S=l.useCallback(async()=>{if(!t||w)return;const K=we.getState().getDirectoryState(t),q=s??K?.activeTabId??K?.tabs[0]?.id??null;if(!q)return;const H=K?.tabs.find(F=>F.id===q)?.terminalSessionId??null;if(!(!H||!e.restartSession)){j(!0),g(null),p(!1),h(!1),m();try{const F=c.current??Xc,D=await e.restartSession(H,{cwd:t,shell:o,loginShell:i,...F,...a.current});if(we.getState().getDirectoryState(t)?.tabs.find(I=>I.id===q)?.terminalSessionId!==H||(v(t,q,D.sessionId),A(t,q,"running"),d.current!==t||u.current!==q))return;f.current=D.sessionId,b(t,q,D.sessionId)}catch(F){if(we.getState().getDirectoryState(t)?.tabs.find(T=>T.id===q)?.terminalSessionId!==H||d.current!==t||u.current!==q)return;g(F instanceof Error?F.message:"Failed to restart terminal"),p(!1),h(!1),f.current=H,b(t,q,H)}finally{j(!1)}}},[s,u,d,t,r,w,c,m,g,p,h,A,v,b,e,a,f,i,o]),C=l.useCallback(async()=>{await S()},[S]),E=l.useCallback(()=>{if(!t)return;const K=y(t);x(t,K),g(null),p(!1),h(!1)},[y,t,x,g,p,h]),P=l.useCallback(K=>{t&&(x(t,K),g(null),p(!1),h(!1))},[t,x,g,p,h]),z=l.useCallback(K=>{if(!t)return;g(null),p(!1),h(!1);const q=we.getState().getDirectoryState(t)?.tabs.find(H=>H.id===K)?.terminalSessionId;(async()=>{q&&await e.close(q),k(t,K)})().catch(H=>g(H instanceof Error?H.message:"Terminal session ended"))},[k,t,g,p,h,e]);return{isRestarting:w,handleRestart:S,handleHardRestart:C,handleCreateTab:E,handleSelectTab:P,handleCloseTab:z}}const Rv=({visible:e,onCloseView:t,terminalHeaderSlot:s})=>{const{terminal:r,runtime:o}=Kn(),{currentTheme:i}=Ol(),a=l.useRef({themeMode:"dark",terminalBackground:"",terminalForeground:""});a.current={themeMode:i.metadata.variant==="light"?"light":"dark",terminalBackground:i.colors.surface.background,terminalForeground:i.colors.syntax.base.foreground};const{monoFont:c}=Af(),d=ue(se=>se.terminalFontSize),u=ue(se=>se.terminalShell),f=ue(se=>se.terminalLoginShells.includes(se.terminalShell)),{isMobile:m,isTablet:b,hasTouchOnlyPointer:g}=xs(),p=m||b,h=(p||g)&&o.platform==="web",y=!0,x=ue(se=>se.showTerminalQuickKeysOnDesktop),k=p||x,v=Me(se=>se.currentSessionId),A=Me(se=>se.newSessionDraft),w=v!==null||A?.open===!0,j=Nf()??null,S=we(se=>j?se.sessions.get(j):void 0),C=we(se=>se.hasHydrated),E=ue(se=>se.openContextPreview),P=l.useMemo(()=>S?S.activeTabId??S.tabs[0]?.id??null:null,[S,y]),z=l.useMemo(()=>{if(S)return P?S.tabs.find(se=>se.id===P)??S.tabs[0]:S.tabs[0]},[S,P]),K=l.useMemo(()=>(S?.tabs??[]).map(se=>({icon:(()=>{const _e=se.iconKey?Vs[se.iconKey]??"terminal":"terminal";return n.jsx(R,{name:_e,className:"h-4 w-4"})})(),id:se.id,label:se.label,title:se.label,closeLabel:"Close tab"})),[S?.tabs]),q=z?.terminalSessionId??null,H=z?.lifecycle??"idle",F=l.useMemo(()=>(S?.tabs??[]).map(se=>({id:se.id,terminalSessionId:se.terminalSessionId,label:se.label})),[S?.tabs]),D=z?.isConnecting??!1,T=z?.previewUrl??null,M=ue(se=>se.activeMainTab)==="terminal",G=e??M,[W,L]=l.useState(G);l.useEffect(()=>{G&&L(!0)},[G]);const{connectionError:ae,setConnectionError:J,isFatalError:le,setIsFatalError:Ie,isReconnectPending:Y,setIsReconnectPending:B,terminalIdRef:$,lastViewportSizeRef:X,directoryRef:ee,activeTabIdRef:ie,resetTerminalPreviewScan:ke,startStream:pe}=uy({terminal:r,effectiveDirectory:j,activeTabId:P,terminalSessionId:q,terminalLifecycle:H,hasOpenedTerminalViewport:W,terminalHydrated:C,terminalShell:u,terminalLoginShell:f,terminalAppearanceRef:a,enableTabs:y,hasActiveContext:w,tabs:F,focusTerminalWhenWindowActive:()=>{!h&&typeof document<"u"&&document.hasFocus()&&be.current?.focus()}}),{activeModifier:je,terminalControllerRef:be,focusTerminalWhenWindowActive:ze,handleViewportInput:me,handleModifierToggle:Pe,handleMobileKeyPress:V}=fy({terminal:r,terminalIdRef:$,isReconnectPending:Y,setConnectionError:J,showQuickKeys:k,isTerminalVisible:G,lastViewportSizeRef:X,terminalSessionId:q,useTouchTerminalInput:h}),{isRestarting:fe,handleRestart:xe,handleHardRestart:te,handleCreateTab:re,handleSelectTab:Be,handleCloseTab:Ce}=hy({terminal:r,effectiveDirectory:j,activeTabId:P,enableTabs:y,terminalShell:u,terminalLoginShell:f,terminalAppearanceRef:a,lastViewportSizeRef:X,directoryRef:ee,activeTabIdRef:ie,terminalIdRef:$,resetTerminalPreviewScan:ke,startStream:pe,setConnectionError:J,setIsFatalError:Ie,setIsReconnectPending:B});l.useEffect(()=>{if(!G||h)return;if(typeof window>"u"){ze();return}const se=window.requestAnimationFrame(()=>{ze()});return()=>{window.cancelAnimationFrame(se)}},[P,ze,G,h]);const Q=l.useMemo(()=>{const se=Ts[uo].stack;if(typeof window>"u")return(Ts[c]??Ts[uo]).stack;const st=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return st&&st.trim().length>0?st.trim():(Ts[c]??Ts[uo]).stack??se},[c]),ve=l.useMemo(()=>If(i),[i]),he=`${j??"no-dir"}::${P??"no-tab"}`;if(l.useEffect(()=>{if(!G||h)return;const se=be.current;if(!se)return;const _e=()=>{se.fit()};if(typeof window<"u"){const st=window.requestAnimationFrame(()=>{_e(),ze()}),mt=[220,400].map(Xe=>window.setTimeout(_e,Xe));return()=>{window.cancelAnimationFrame(st),mt.forEach(Xe=>window.clearTimeout(Xe))}}_e()},[ze,G,h,be,he,q]),l.useEffect(()=>{if(!G||!h)return;let se=null;const _e=()=>{se!==null&&window.cancelAnimationFrame(se),se=window.requestAnimationFrame(()=>{se=null,be.current?.fit()})};return window.addEventListener("oc:keyboard-settled",_e),()=>{window.removeEventListener("oc:keyboard-settled",_e),se!==null&&window.cancelAnimationFrame(se)}},[G,be,he,h]),!w)return n.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(!j)return n.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 p-4 text-center text-sm text-muted-foreground",children:[n.jsx("p",{children:"No working directory available for this session."}),n.jsx("button",{onClick:xe,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const Se=!q||D||fe||Y,qe=W,Ue=S?n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"min-w-0 flex-1",children:n.jsx(rl,{items:K,activeId:P,onSelect:Be,onClose:Ce,onCreate:re})}),n.jsx(Ae,{type:"button",size:"xs",variant:"ghost",className:"h-8 w-8 shrink-0 p-0",onClick:re,title:"New tab","aria-label":"New tab",children:n.jsx(R,{name:"add",className:"h-4 w-4"})}),n.jsxs("div",{className:"flex shrink-0 items-center gap-1 overflow-visible",children:[n.jsx(Ae,{type:"button",size:"xs",variant:"ghost",className:"h-8 w-8 p-0",onClick:()=>{xe()},disabled:fe,title:"Restart terminal","aria-label":"Restart terminal",children:n.jsx(R,{name:"restart",className:"h-4 w-4"})}),T?n.jsxs(Ae,{type:"button",size:"xs",variant:"outline",className:"h-6 shrink-0 gap-1 px-2",onClick:()=>{j&&E(j,T)},title:"Open preview pane",children:[n.jsx(R,{name:"global",className:"h-3.5 w-3.5 shrink-0"}),n.jsx("span",{className:"whitespace-nowrap",children:"Preview"})]}):null]})]}):null,U=n.jsx(Qx,{isTouchTerminal:p,activeModifier:je,disabled:Se,onKeyPress:V,onModifierToggle:Pe}),ge=!s||p||k;return n.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[Ue&&s?ju.createPortal(n.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:Ue}),s):null,p&&Ue&&!s&&S?n.jsx(Yx,{leading:n.jsx("div",{className:"min-w-0 flex-1 -ml-2",children:n.jsx(rl,{items:K,activeId:P,onSelect:Be,onClose:Ce,onCreate:re})}),actions:n.jsxs(n.Fragment,{children:[n.jsx(Ae,{type:"button",variant:"ghost",size:"icon",onClick:re,title:"New tab","aria-label":"New tab",children:n.jsx(R,{name:"add",className:"size-4"})}),n.jsx(Ae,{type:"button",variant:"ghost",size:"icon",onClick:()=>{xe()},disabled:fe,title:"Restart terminal","aria-label":"Restart terminal",children:n.jsx(R,{name:"restart",className:"size-4"})}),T?n.jsxs(Ae,{type:"button",variant:"outline",size:"sm",className:"h-8 shrink-0 gap-1 px-2",onClick:()=>{j&&E(j,T)},title:"Open preview pane",children:[n.jsx(R,{name:"global",className:"size-3.5 shrink-0"}),n.jsx("span",{className:"whitespace-nowrap",children:"Preview"})]}):null,t?n.jsx(Ae,{type:"button",variant:"ghost",size:"icon",onClick:t,title:"Close terminal view","aria-label":"Close terminal view",children:n.jsx(R,{name:"close",className:"size-4"})}):null]})}):null,!p&&ge?n.jsxs("div",{className:_("app-region-no-drag sticky top-0 z-20 shrink-0 bg-background text-xs","px-3 py-2"),children:[Ue&&!s?n.jsxs("div",{className:"flex items-center gap-2 pl-1 pr-1",children:[Ue,t?n.jsx(Ae,{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:n.jsx(R,{name:"close",className:"h-4 w-4"})}):null]}):null,!p&&k&&y&&S?n.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1 pl-1 pr-1",children:U}):null,!p&&k&&!S?n.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:U}):null]}):null,n.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:ve.background},children:[n.jsx("div",{className:"h-full w-full box-border pl-4 pr-1.5 pt-3 pb-4",children:qe&&j&&S?S.tabs.map(se=>{const _e=se.id===P;return n.jsx(Vx,{directory:j,tabId:se.id,sessionId:se.terminalSessionId,sessionKey:`${j}::${se.id}`,isActive:_e,isTerminalVisible:G,terminal:r,theme:ve,fontFamily:Q,fontSize:d,enableTouchScroll:h,lastViewportSizeRef:X,onInput:me,controllerRef:be},se.id)}):null}),!Y&&ae&&n.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:[n.jsx("span",{children:ae}),le&&p&&n.jsx(Ae,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:te,disabled:fe,title:"Force kill and create fresh session",type:"button",children:"Hard restart"})]})]}),p&&k?n.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:n.jsx("div",{className:"flex min-w-max items-center gap-1.5",children:U})}):null]})},yi=[{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"}],py=new Set(yi.map(e=>e.id)),my=e=>typeof e=="string"&&py.has(e),Pv=e=>my(e)?e:"changes",Zc=e=>e==="pull-requests"||e==="issues",gy=e=>e?yi:yi.filter(t=>!Zc(t.id)),Tv=(e,t)=>Zc(e)?"changes":e,by=48,xy=96,jt=(e,...t)=>{try{e?.(...t)}catch{}},Ro=(e,t)=>{if(typeof e=="function"){const s=e();return s>0?s:t}return typeof e=="number"&&e>0?e:t},Mv=(e,t)=>{const s=l.useRef(t);s.current=t;const r=t.enabled;l.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"?xy:by;let d=!1,u=!1,f=!1,m=null,b=!1,g=0,p=0,h=0,y=0;const x=()=>{d=!1,u=!1,f=!1,m=null},k=()=>{const E=s.current,P=m,z=b;u&&P&&(jt(P==="left"?E.onLeftProgress:E.onRightProgress,z?1:0),jt(E.onDragEnd,P,z)),x()},v=()=>{k(),u||x()},A=E=>{const P=s.current;if(P.enabled===!1){u&&m?k():x();return}if(E.touches.length!==1){u&&m?k():x();return}const z=E.touches[0],K=o.getBoundingClientRect(),q=o.clientWidth,H=!!P.leftOpen,F=!!P.rightOpen,D=T=>Ix(T,o);if(H||F){if(D(E.target)){x();return}if(H&&F){const T=z.clientX<=K.left+c;z.clientX>=K.right-c?(m="right",b=!0):T?(m="left",b=!0):(m=H?"left":"right",b=!0)}else H?(m="left",b=!0):(m="right",b=!0);y=Ro(m==="left"?P.leftWidth:P.rightWidth,q),y<10&&(y=q||window.innerWidth||320),y<10&&(y=320),d=!0}else{if(D(E.target)){x();return}m=null,b=!1,y=0,d=!0}g=z.clientX,p=z.clientY,h=Date.now(),u=!1,f=!1},w=E=>{if(!d)return;if(E.touches.length!==1){v();return}const P=E.touches[0],z=P.clientX-g,K=P.clientY-p;if(!f){if(Math.abs(z)<Za&&Math.abs(K)<Za)return;if(Math.abs(K)>Math.abs(z)*zs){x();return}if(!m){const F=s.current;m=z>0?"left":"right",y=Ro(m==="left"?F.leftWidth:F.rightWidth,o.clientWidth),y<10&&(y=window.innerWidth||320)}if(m==="left"){if(!b&&z<=0){x();return}if(b&&z>=0){x();return}}else{if(!b&&z>=0){x();return}if(b&&z<=0){x();return}}f=!0,u=!0,jt(s.current.onDragStart,m)}if(!u)return;E.cancelable&&E.preventDefault();const q=s.current,H=el(m,b,z,y);jt(m==="left"?q.onLeftProgress:q.onRightProgress,H)},j=(E,P)=>{if(!d){x();return}const z=E-g,K=P-p;if(!m&&!b&&Math.abs(z)>=Er&&Math.abs(K)<=Math.abs(z)*zs){const I=s.current;m=z>0?"left":"right",y=Ro(m==="left"?I.leftWidth:I.rightWidth,o.clientWidth),y<10&&(y=window.innerWidth||320)}if(!m){x();return}const q=Math.max(1,Date.now()-h),H=s.current;if(!u){const I=Math.abs(z),M=Math.abs(K);I>=Er&&M<=I*zs?m==="left"&&!b&&z>0?(jt(H.onLeftProgress,1),jt(H.onLeftOpen)):m==="right"&&!b&&z<0?(jt(H.onRightProgress,1),jt(H.onRightOpen)):jt(m==="left"?H.onLeftProgress:H.onRightProgress,b?1:0):jt(m==="left"?H.onLeftProgress:H.onRightProgress,b?1:0);const G=m;x(),jt(H.onDragEnd,G);return}const F=el(m,b,z,y),D=Ax({side:m,isOpenAtStart:b,dx:z,dt:q,progress:F}),T=m;jt(T==="left"?D?H.onLeftOpen:H.onLeftClose:D?H.onRightOpen:H.onRightClose),x(),jt(H.onDragEnd,T,D)},S=E=>{const P=E.changedTouches[0];if(!P){x();return}const z=P.clientX-g,K=P.clientY-p;d&&(u||Math.abs(z)>=Er&&Math.abs(K)<=Math.abs(z)*zs)&&E.cancelable&&E.preventDefault(),j(P.clientX,P.clientY)},C=()=>{v()};return o.addEventListener("touchstart",A,{passive:!0}),o.addEventListener("touchmove",w,{passive:!1}),o.addEventListener("touchend",S,{passive:!1}),o.addEventListener("touchcancel",C,{passive:!0}),()=>{try{u&&m&&k()}catch{}o.style.touchAction=i,o.removeEventListener("touchstart",A),o.removeEventListener("touchmove",w),o.removeEventListener("touchend",S),o.removeEventListener("touchcancel",C)}},[e,r])};function Fv({className:e="h-5 w-5"}){return n.jsxs("span",{"aria-hidden":"true",className:`relative inline-block overflow-hidden rounded-[2px] ${e}`,children:[n.jsx("span",{className:"absolute left-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-error)]/25"}),n.jsx("span",{className:"absolute right-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-success)]/25"}),n.jsx(R,{name:"layout-column",className:"absolute inset-0 h-full w-full"})]})}function al({size:e,className:t,style:s,...r}){return n.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,...s},...r,children:n.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 yy=({sessionDirectory:e,draftDirectory:t,isNewSessionDraftOpen:s})=>s?t:e,wy=({activeProjectLabel:e,openDirectory:t,homeDirectory:s})=>Zs(t,s)?null:e,Po=()=>On.filter(e=>Qo.has(e.id)).map(e=>({...Gl(e)})),vy=()=>{if(typeof window>"u")return Jo;const e=window.localStorage.getItem("openInAppId");return e&&Yo(e)?e:Jo};let To=!1,ss=!1,vn=!1,Sn=0,Ys=null;const ll=()=>{Ys&&(clearTimeout(Ys),Ys=null)},Mn=Nn()((e,t)=>({selectedAppId:vy(),availableApps:Po(),hasLoadedApps:!1,isCacheStale:!1,isScanning:!1,initialize:()=>{if(To||typeof window>"u")return;To=!0;const s=(d,u=!0)=>{if(!Array.isArray(d)||d.length===0){e({availableApps:Po(),hasLoadedApps:u});return}const f=new Set(d.map(p=>p.name)),m=new Map(d.map(p=>[p.name,p.iconDataUrl??void 0])),g=On.filter(p=>f.has(p.appName)||Qo.has(p.id)).map(p=>({...Gl(p),iconDataUrl:m.get(p.appName)}));e({availableApps:g,hasLoadedApps:!0})},r=async d=>{if(!ms()||!Tr()||ss||t().hasLoadedApps&&!d)return;const f=On.map(m=>m.appName);ll(),ss=!0,vn=!1,e({isScanning:!0});try{const{apps:m,success:b,hasCache:g,isCacheStale:p}=await aa(f,d),h=b&&!g&&m.length===0&&Sn<3;if(e({isCacheStale:g?p:!1}),s(m,b?!h:!1),b){if(h){const x=[800,1600,3200][Sn]??3200;Sn+=1,vn=!0,Ys=setTimeout(()=>{r()},x);return}Sn=0,vn=!1;return}if(Sn<3){const x=[1e3,3e3,7e3][Sn]??7e3;Sn+=1,vn=!0,Ys=setTimeout(()=>{r()},x)}}finally{ss=!1,vn||e({isScanning:!1})}};r();const o=d=>{const u=d.detail,f=u&&typeof u.openInAppId=="string"&&u.openInAppId.length>0&&Yo(u.openInAppId)?u.openInAppId:null;f&&(window.localStorage.setItem("openInAppId",f),e({selectedAppId:f}))},i=()=>{r()},a=d=>{const u=d.detail;Array.isArray(u)&&(Sn=3,vn=!1,e({isScanning:!1,isCacheStale:!1}),s(u))};window.addEventListener("pichamber:settings-synced",o),window.addEventListener("pichamber:app-ready",i),window.addEventListener("pichamber:installed-apps-updated",a),window.__pichamberAppReady&&r(),window.setTimeout(()=>{t().hasLoadedApps||r()},5e3)},loadInstalledApps:async s=>{if(To||t().initialize(),!ms()||!Tr()||ss||t().hasLoadedApps&&!s)return;const o=On.map(i=>i.appName);ll(),s&&e({hasLoadedApps:!1}),ss=!0,vn=!1,e({isScanning:!0});try{const{apps:i,hasCache:a,isCacheStale:c}=await aa(o,s),d=new Set(i.map(b=>b.name)),u=new Map(i.map(b=>[b.name,b.iconDataUrl??void 0])),m=On.filter(b=>d.has(b.appName)||Qo.has(b.id)).map(b=>({...b,iconDataUrl:u.get(b.appName)}));e({availableApps:m.length>0?m:Po(),hasLoadedApps:m.length>0,isCacheStale:a?c:!1})}finally{ss=!1,vn||e({isScanning:!1})}},selectApp:async s=>{Yo(s)&&(e({selectedAppId:s}),typeof window<"u"&&window.localStorage.setItem("openInAppId",s),await Ul({openInAppId:s}))}})),Sy="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",jy="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",Mo=e=>({...e,fallbackIconDataUrl:e.id==="finder"&&window.__PICHAMBER_PLATFORM__==="darwin"?Sy:e.id==="terminal"?jy:void 0}),cl=({label:e,iconDataUrl:t,fallbackIconDataUrl:s})=>{const[r,o]=l.useState(!1),i=e.trim().slice(0,1).toUpperCase()||"?",a=t||s;return a&&!r?n.jsx("img",{src:a,alt:"",className:"h-4 w-4 rounded-sm",onError:()=>o(!0)}):n.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})},Cy=({directory:e,className:t})=>{const s=Mn(p=>p.selectedAppId),r=Mn(p=>p.availableApps),o=Mn(p=>p.isCacheStale),i=Mn(p=>p.isScanning),a=Mn(p=>p.initialize),c=Mn(p=>p.loadInstalledApps),d=Mn(p=>p.selectApp);l.useEffect(()=>{a()},[a]);const u=ms()&&Tr(),f=l.useMemo(()=>{const p=r.find(h=>h.id===s)??r.find(h=>h.id===Jo)??r[0]??On[0];return Mo(p||On[0])},[r,s]);if(!u||!e||r.length===0)return null;const m=async p=>{await dh(e,p.id,p.appName)||await Kl(e,p.appName)},b=async p=>{await d(p.id),await m(p)},g=async()=>{(await fn(e)).ok&&oe.success("Path copied to clipboard")};return n.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:[n.jsx("button",{type:"button",onClick:()=>{m(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:n.jsx(cl,{label:f.label,iconDataUrl:f.iconDataUrl,fallbackIconDataUrl:f.fallbackIconDataUrl})}),n.jsxs(Ht,{children:[n.jsx(qt,{asChild:!0,children:n.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:n.jsx(R,{name:"arrow-down-s",className:"h-4 w-4"})})}),n.jsxs(Vt,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[n.jsxs(ut,{className:"flex items-center gap-2",onClick:()=>{g()},children:[n.jsx(R,{name:"file-copy",className:"h-4 w-4"}),n.jsx("span",{className:"typography-ui-label text-foreground",children:"Copy path"})]}),n.jsx(ps,{}),r.map(p=>{const h=Mo(p);return n.jsxs(ut,{className:"flex items-center gap-2",onClick:()=>{b(p)},children:[n.jsx(cl,{label:p.label,iconDataUrl:p.iconDataUrl,fallbackIconDataUrl:h.fallbackIconDataUrl}),n.jsx("span",{className:"typography-ui-label text-foreground",children:p.label}),f.id===p.id?n.jsx(R,{name:"check",className:"ml-auto h-4 w-4 text-primary"}):null]},p.id)}),o?n.jsxs(ut,{className:"flex items-center gap-2",onClick:()=>{c(!0)},children:[n.jsx(R,{name:"refresh",className:"h-4 w-4"}),n.jsx("span",{className:"typography-ui-label text-foreground",children:"Refresh apps"})]}):null]})]})]})},ky="\x1B",Ay=new RegExp(`${ky}\\[[0-9;?]*[ -/]*[@-~]`,"g"),Ny=/https?:\/\/[^\s<>'"`]+/gi,Nt="__pichamber_auto_discover_preview__",Iy=15e3,Ey=e=>{let t="";for(let s=0;s<e.length;s+=1){const r=e.charCodeAt(s);r>=0&&r<=8||r===11||r===12||r>=14&&r<=31||r===127||(t+=e[s])}return t},Dy=e=>{const t=(e||"").trim();if(!t)return null;const s=/^https?:\/\//i.test(t)?t:`http://${t}`;try{const r=new URL(s);return r.protocol!=="http:"&&r.protocol!=="https:"?null:r.toString()}catch{return null}},Ry=e=>{const s=e.replace(Ay,"").match(Ny);if(!s||s.length===0)return null;const r=s.map(i=>i.replace(/[),.;]+$/,"")).filter(Boolean);if(r.length===0)return null;const o=[];for(const i of r)try{const a=new URL(i);a.port&&a.port.length>0&&o.push({raw:i,parsed:a})}catch{}if(o.length>0){const i=a=>{const{parsed:c}=a,d=c.hostname.toLowerCase(),u=d==="localhost"||d==="127.0.0.1"||d==="0.0.0.0"||d==="::1",f=c.pathname||"/",m=f.split("/").filter(Boolean).length,b=f==="/"||f==="",g=!!(c.search||c.hash);let p=0;return u&&(p+=50),b&&(p+=30),p-=Math.min(m*5,20),g&&(p-=10),p};return o.sort((a,c)=>i(c)-i(a)),o[0]?.parsed.origin??o[0]?.raw??null}return r[0]??null},Py=[{pattern:/^dev(:.*)?$/i},{pattern:/^start(:.*)?$/i},{pattern:/^preview(:.*)?$/i},{pattern:/^serve(:.*)?$/i},{pattern:/^develop(:.*)?$/i}],Ty=["dev","start","preview","serve"];async function My(e,t,s){if(!e)return null;const r=Oy(t);if(r)return{command:r.command,label:r.name||"Start preview",actionId:r.id,previewUrlHint:r.openUrl};if(s){const o=By(s);if(o){const i=await _y(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 Fy(e)){const o=await Ly(),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 Fy(e){const t=`${e}/index.html`,s=await $r(t,e);return typeof s=="string"&&s.trim().length>0}async function Ly(){try{const e=await tt("/api/system/free-port",{cache:"no-store"});if(!e.ok)return null;const t=await e.json().catch(()=>null),s=typeof t?.port=="number"?t.port:null;return s&&Number.isFinite(s)?s:null}catch{return null}}function Oy(e){for(const t of e){const s=`${t.name} ${t.command}`.toLowerCase();if(Ty.some(o=>s.includes(o)))return t}return null}function By(e){for(const{pattern:t}of Py)for(const s of Object.keys(e))if(t.test(s))return s;return null}async function _y(e){const t=await $r(`${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 s=[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"],["package-lock.json","npm"]];for(const[r,o]of s){const i=await $r(`${e}/${r}`,e);if(typeof i=="string"&&i.trim().length>0)return o}return"npm"}async function $r(e,t){if(t?.trim())try{const r=new URLSearchParams({path:e,directory:t,optional:"true"}),o=await tt(`/api/fs/read?${r.toString()}`,{cache:"no-store"});if(o.ok)return o.text()}catch{}const s=$l()?.files;if(s?.readFile)try{const r=await s.readFile(e,{optional:!0});return typeof r?.content=="string"?r.content:null}catch{return null}try{const r=await tt(`/api/fs/read?path=${encodeURIComponent(e)}&optional=true`,{cache:"no-store"});return r.ok?r.text():null}catch{return null}}async function zy(e){try{const t=await $r(`${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 Uy=(e,t,s)=>new Promise(r=>{let o=!1,i=null,a=null;const c=d=>{o||(o=!0,a&&clearTimeout(a),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():a=setTimeout(()=>c(!1),s)});function $y({projectRef:e,directory:t,allowMobile:s=!1}){const{currentTheme:r}=Ol(),{terminal:o}=Kn(),{isMobile:i}=xs(),a=ue(V=>V.terminalShell),c=ue(V=>V.terminalLoginShells.includes(V.terminalShell)),d=ue(V=>V.setSettingsPage),u=ue(V=>V.setSettingsDialogOpen),f=ue(V=>V.setSettingsProjectsSelectedId),m=ue(V=>V.openContextPreview),b=we(V=>V.ensureDirectory),g=we(V=>V.setTabLabel),p=we(V=>V.setTabIconKey),h=we(V=>V.setActiveTab),y=we(V=>V.setConnecting),x=we(V=>V.setTabSessionId),k=we(V=>V.setTabPreviewUrl),v=we(V=>V.projectActionRuns),A=we(V=>V.setProjectActionRun),w=we(V=>V.updateProjectActionRunStatus),j=we(V=>V.removeProjectActionRun),[S,C]=l.useState([]),[E,P]=l.useState(null),[z,K]=l.useState(!1),q=l.useRef({}),H=l.useRef({}),F=l.useRef({}),D=l.useRef({}),T=l.useRef(new Set),I=l.useRef(0),M=e?.id??null,G=e?.path??"",W=l.useMemo(()=>M?{id:M,path:G}:null,[M,G]),L=l.useCallback(async V=>{await Cl(V)},[]),ae=l.useCallback(async()=>{if(!W)return;const V=I.current+1;I.current=V,K(!0);try{const fe=await _o(W);if(I.current!==V)return;const xe=fe.actions;C(xe),P(te=>te===Nt||te&&xe.some(re=>re.id===te)?te:null)}catch{if(I.current!==V)return}finally{I.current===V&&K(!1)}},[W]),J=l.useMemo(()=>uc(t||W?.path||""),[t,W?.path]),le=l.useMemo(()=>E?S.find(V=>V.id===E)??null:null,[S,E]),Ie=l.useMemo(()=>({id:Nt,name:"Auto-discover",command:"",icon:"scan-2",autoOpenUrl:!0}),[]),Y=!i,B=l.useMemo(()=>Y?[Ie,...S]:S,[S,Ie,Y]);l.useEffect(()=>{ae()},[ae]),l.useEffect(()=>{if(typeof window>"u")return;const V=fe=>{const xe=fe.detail;M&&(xe?.projectId&&xe.projectId!==M||ae())};return window.addEventListener(ni,V),()=>{window.removeEventListener(ni,V)}},[ae,M]),l.useEffect(()=>{E&&(E===Nt&&Y||S.some(V=>V.id===E)||P(null))},[S,Y,E]),l.useEffect(()=>{const V=()=>{const fe=we.getState(),xe=fe.sessions,te=fe.projectActionRuns;for(const[re,Be]of Object.entries(te)){const Q=xe.get(Be.directory)?.tabs.find(_e=>_e.id===Be.tabId);if(!Q||Q.terminalSessionId!==Be.sessionId){j(re);continue}const ve=H.current[re]??{lastSeenChunkId:null,openedUrl:!1,tail:"",openInPreview:!1};H.current[re]=ve;const he=B.find(_e=>_e.id===Be.actionId),Se=fe.getBuffer(Be.directory,Be.tabId).chunks;if(!he||Se.length===0)continue;const qe=Se.filter(_e=>ve.lastSeenChunkId===null||_e.id>ve.lastSeenChunkId);if(qe.length===0)continue;const Ue=qe.map(_e=>_e.data).join(""),U=`${ve.tail}${Ue}`,ge=!ve.openedUrl&&he.autoOpenUrl===!0?Ry(U):null,se=qe[qe.length-1]?.id??ve.lastSeenChunkId;if(ve.lastSeenChunkId=se,ve.tail=U.slice(-512),ge)if(ve.openedUrl=!0,ve.openInPreview){const _e=te[re];_e&&(k(_e.directory,_e.tabId,ge,{locked:!1,autoOpened:!1}),_e.status==="waiting-for-preview"&&w(re,"running"),window.clearTimeout(D.current[re]),delete D.current[re],m(_e.directory,ge))}else L(ge),oe.success("Opened URL from action output");H.current[re]=ve}for(const re of Object.keys(H.current))te[re]||(delete H.current[re],window.clearTimeout(D.current[re]),delete D.current[re])};return V(),we.subscribe((fe,xe)=>{(fe.sessions!==xe.sessions||fe.buffers!==xe.buffers)&&V()})},[B,m,L,v,j,k,w]);const $=l.useCallback(async(V,fe={})=>{if(!J)throw new Error("No active directory");const xe=cn(J,V.id);b(J);const te=we.getState(),re=te.getDirectoryState(J);let Be=q.current[xe]||null;const Ce=Be?!!re?.tabs.some(he=>he.id===Be):!1;(!Be||!Ce)&&(Be=te.createTab(J),q.current[xe]=Be),g(J,Be,`Action: ${V.name}`),p(J,Be,V.icon||"play"),h(J,Be),fe.revealTerminal!==!1&&ue.getState().openContextPanelTab(J,{mode:"terminal"});const ve=we.getState().getDirectoryState(J)?.tabs.find(he=>he.id===Be);return{key:xe,tabId:Be,sessionId:ve?.terminalSessionId??null}},[b,J,h,p,g]),X=l.useCallback(async V=>{if(!s&&i)return;if(!J){oe.error("No active directory for action");return}const fe=cn(J,V.id),xe=v[fe];if(!(xe&&xe.status==="running")&&!T.current.has(fe)){T.current.add(fe);try{const te=V.id===Nt?await(async()=>{const[U,ge]=await Promise.all([_o({id:W?.id??"",path:J}),zy(J)]),se=await My(J,U.actions,ge);if(!se)throw new Error('No dev server command found. Configure a project action or add a "dev" script to package.json.');return{id:Nt,name:"Auto-discover",command:se.command,icon:"scan-2",autoOpenUrl:!0,openUrl:se.previewUrlHint||""}})():V,re=te.autoOpenUrl===!0&&(te.openUrl||"").trim().length>0,Be=!re&&V.id!==Nt,{key:Ce,tabId:Q,sessionId:ve}=await $(te,{revealTerminal:Be});let he=ve;if(!he){y(J,Q,!0);try{he=(await o.createSession({cwd:J,sessionId:Q,shell:a,loginShell:c,themeMode:r.metadata.variant==="light"?"light":"dark",terminalBackground:r.colors.surface.background,terminalForeground:r.colors.syntax.base.foreground})).sessionId,x(J,Q,he)}finally{y(J,Q,!1)}}if(!he)throw new Error("Failed to create terminal session");F.current[Ce]?.(),y(J,Q,!0);const Se=o.connect(he,{onEvent:U=>{U.type==="snapshot"&&(we.getState().replaceBuffer(J,Q,U.data??"",U.sequence??0),we.getState().setConnecting(J,Q,!1)),U.type==="data"&&typeof U.data=="string"&&U.data.length>0&&we.getState().appendToBuffer(J,Q,U.data,U.sequence,U.replayData),U.type==="exit"&&(we.getState().setTabLifecycle(J,Q,"exited"),we.getState().setConnecting(J,Q,!1),we.getState().removeProjectActionRun(Ce),delete H.current[Ce],F.current[Ce]?.(),delete F.current[Ce],window.clearTimeout(D.current[Ce]),delete D.current[Ce])},onError:(U,ge)=>{we.getState().setConnecting(J,Q,!1),ge&&(we.getState().setTabLifecycle(J,Q,"exited"),we.getState().setTabSessionId(J,Q,null),we.getState().removeProjectActionRun(Ce))}});F.current[Ce]=Se.close;const qe=te.autoOpenUrl?Dy(te.openUrl):null;A({key:Ce,directory:J,actionId:te.id,tabId:Q,sessionId:he,status:te.id===Nt&&!qe?"waiting-for-preview":"running"}),window.clearTimeout(D.current[Ce]),delete D.current[Ce],te.id===Nt&&!qe&&(D.current[Ce]=window.setTimeout(()=>{const U=we.getState(),ge=U.projectActionRuns[Ce];U.updateProjectActionRunStatus(Ce,"running"),ge&&(U.setActiveTab(ge.directory,ge.tabId),ue.getState().openContextPanelTab(ge.directory,{mode:"terminal"})),delete D.current[Ce]},Iy)),H.current[Ce]={lastSeenChunkId:null,openedUrl:!!qe||re,tail:"",openInPreview:te.id===Nt};const Ue=Ey(te.command.trim().replace(/\r\n|\r/g,`
|
|
62
|
+
`));await o.sendInput(he,`${Ue}\r`),qe?(k(J,Q,qe,{locked:!0,autoOpened:!0}),m(J,qe),oe.success("Opened action URL")):re?(k(J,Q,null,{locked:!0}),oe.error("Invalid custom URL format")):k(J,Q,null,{locked:!1,autoOpened:!1})}catch(te){j(fe),delete H.current[fe],F.current[fe]?.(),delete F.current[fe],window.clearTimeout(D.current[fe]),delete D.current[fe],oe.error(te instanceof Error?te.message:"Failed to run action")}finally{T.current.delete(fe)}}},[r.colors.surface.background,r.colors.syntax.base.foreground,r.metadata.variant,$,s,i,J,c,a,m,v,j,y,A,k,x,W?.id,o]),ee=l.useCallback(async V=>{const fe=cn(J,V.id),xe=v[fe];if(!xe)return;w(fe,"stopping");const te=Uy(o,xe.sessionId,1e3);try{await o.sendInput(xe.sessionId,"")}catch{}const re=await te;if(we.getState().getDirectoryState(xe.directory)?.tabs.find(Q=>Q.id===xe.tabId)?.terminalSessionId===xe.sessionId&&!re){if(typeof o.forceKill=="function")try{await o.forceKill({sessionId:xe.sessionId})}catch{}else try{await o.close(xe.sessionId)}catch{}x(xe.directory,xe.tabId,null)}j(fe),delete H.current[fe],F.current[fe]?.(),delete F.current[fe],window.clearTimeout(D.current[fe]),delete D.current[fe]},[J,v,j,x,o,w]),ie=l.useCallback(()=>{const V=le??B[0];if(!V)return;const fe=cn(J,V.id),xe=v[fe];if(xe?.status!=="stopping"){if(xe){ee(V);return}X(V)}},[B,J,X,v,le,ee]),ke=l.useCallback((V,fe=!1)=>{if(P(V.id),!fe){X(V);return}const xe=cn(J,V.id),te=v[xe];if(te?.status!=="stopping"){if(te){ee(V);return}X(V)}},[J,X,v,ee]),pe=l.useCallback(()=>{W?.id&&(f(W.id),d("projects"),u(!0))},[u,d,f,W?.id]),je=le??B[0]??null,be=je?v[cn(J,je.id)]:null,ze=we(V=>be?V.sessions.get(be.directory)?.tabs.find(fe=>fe.id===be.tabId)?.previewUrl??null:null),me=!!((s||!i)&&W&&J),Pe=le??B[0]??null;return{shouldRender:me,isLoading:z,normalizedDirectory:J,resolvedSelected:Pe,displayActions:B,projectActionRuns:v,selectedRunPreviewUrl:ze,handlePrimaryClick:ie,handleSelectAction:ke,openProjectActionsSettings:pe,openContextPreview:m}}const dl=({projectRef:e,directory:t,className:s,compact:r=!1,allowMobile:o=!1})=>{const{shouldRender:i,isLoading:a,normalizedDirectory:c,resolvedSelected:d,displayActions:u,projectActionRuns:f,selectedRunPreviewUrl:m,handlePrimaryClick:b,handleSelectAction:g,openProjectActionsSettings:p,openContextPreview:h}=$y({projectRef:e,directory:t,allowMobile:o});if(!i||!d)return null;const y=d.icon||"play",x=d.id===Nt?"scan-2":Vs[y]||"play",k=cn(c,d.id),v=f[k],A=v?.status==="stopping",w=v?.status==="waiting-for-preview",j=!!(v&&m),S=()=>{!v||!m||h(v.directory,m)},C=d.id===Nt;return r?n.jsxs("div",{className:"inline-flex items-center",children:[n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",disabled:a||A,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",s),onClick:b,"aria-label":v?`Stop ${d.name}`:`Run ${d.name}`,children:A||w?n.jsx(R,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):v?n.jsx(R,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):n.jsx(R,{name:x,className:"h-5 w-5"})})}),C?n.jsx(Ge,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),j?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.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:S,children:n.jsx(R,{name:"global",className:"h-4 w-4"})})}),n.jsx(Ge,{sideOffset:6,children:"Open preview"})]}):null,n.jsxs(Ht,{children:[n.jsx(qt,{asChild:!0,children:n.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:n.jsx(R,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})}),n.jsxs(Vt,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[n.jsxs(ut,{className:"flex items-center gap-2",onClick:p,children:[n.jsx(R,{name:"add",className:"h-4 w-4"}),n.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),n.jsx(ps,{}),u.map(E=>{const P=E.icon||"play",z=E.id===Nt?"scan-2":Vs[P]||"play",K=cn(c,E.id),q=f[K],H=!!q,F=q?.status==="stopping";return n.jsxs(ut,{className:"flex items-center gap-2",onClick:()=>{g(E,!0)},children:[n.jsx(R,{name:z,className:"h-4 w-4"}),n.jsx("span",{className:"typography-ui-label text-foreground truncate",children:E.name}),F||q?.status==="waiting-for-preview"?n.jsx(R,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):H?n.jsx(R,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},E.id)})]})]})]}):n.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",s),children:[n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:b,disabled:a||A,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":v?`Stop ${d.name}`:`Run ${d.name}`,children:n.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center",children:A||w?n.jsx(R,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):v?n.jsx(R,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):n.jsx(R,{name:x,className:"h-4 w-4"})})})}),C?n.jsx(Ge,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),j?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:S,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:n.jsx(R,{name:"global",className:"h-4 w-4"})})}),n.jsx(Ge,{sideOffset:6,children:"Open preview"})]}):null,n.jsxs(Ht,{children:[n.jsx(qt,{asChild:!0,children:n.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:n.jsx(R,{name:"arrow-down-s",className:"h-4 w-4"})})}),n.jsxs(Vt,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[n.jsxs(ut,{className:"flex items-center gap-2",onClick:p,children:[n.jsx(R,{name:"add",className:"h-4 w-4"}),n.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),n.jsx(ps,{}),u.map(E=>{const P=E.icon||"play",z=E.id===Nt?"scan-2":Vs[P]||"play",K=cn(c,E.id),q=f[K],H=!!q,F=q?.status==="stopping";return n.jsxs(ut,{className:"flex items-center gap-2",onClick:()=>{g(E,!0)},children:[n.jsx(R,{name:z,className:"h-4 w-4"}),n.jsx("span",{className:"typography-ui-label text-foreground truncate",children:E.name}),F||q?.status==="waiting-for-preview"?n.jsx(R,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):H?n.jsx(R,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},E.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 Rr(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 Ky=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 Wy({open:e,onOpenChange:t}){const[s,r]=l.useState(null),o=l.useCallback(async()=>{const u=Ze();try{const f=await tt("/api/version");if(!f.ok)throw new Error("Version request failed");const m=await f.json().catch(()=>null);u===Ze()&&r(m)}catch{u===Ze()&&r(null)}},[]);l.useEffect(()=>(o(),ws(()=>{o()})),[o]);const i=Rr(s),a=Ky(s),c=typeof s?.pichamberVersion=="string"?s.pichamberVersion:null,d=typeof window<"u"?window.location.origin:"";return n.jsxs(Ht,{open:e,onOpenChange:u=>{t(u),u&&o()},children:[n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx(qt,{asChild:!0,children:n.jsxs("button",{type:"button","aria-label":"Show connected server information",className:_(Ss,"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5"),children:[n.jsx(R,{name:i.name,className:"h-[18px] w-[18px] shrink-0",style:i.color?{color:i.color}:void 0}),n.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:"This server"})]})})}),n.jsx(Ge,{children:n.jsx("p",{children:"Connected server information"})})]}),n.jsxs(Vt,{align:"end",className:"w-80 max-w-[calc(100vw-2rem)] p-3",children:[n.jsxs("div",{className:"flex items-center justify-between gap-4",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-2.5",children:[n.jsx(R,{name:i.name,className:"size-5 shrink-0",style:i.color?{color:i.color}:void 0}),n.jsx("div",{className:"truncate typography-ui-label font-medium text-foreground",children:a})]}),c?n.jsx("div",{className:"shrink-0 typography-micro text-muted-foreground",children:`v${c}`}):null]}),n.jsx("div",{className:"mt-3 border-t border-[var(--interactive-border)] pt-3 typography-micro",children:n.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[n.jsx("span",{className:"shrink-0 text-muted-foreground",children:"Address"}),n.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:()=>{fn(d).then(u=>{u.ok?oe.success("Server address copied"):oe.error("Could not copy server address")})},children:[n.jsx("span",{className:"block max-w-[30ch] truncate font-mono",children:d}),n.jsx(R,{name:"file-copy",className:"size-3.5 shrink-0 text-muted-foreground"})]})]})})]})]})}const Gy=({isMobile:e})=>{const s=Kn().github??null,r=Hr(i=>i.refresh),o=hm();return l.useEffect(()=>{!s||e||r(s)},[s,e,r]),e||!s||!o?null:n.jsxs("span",{className:_(Ss,"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:[n.jsx(R,{name:"github-fill",className:"h-3.5 w-3.5 shrink-0 text-foreground"}),n.jsxs("span",{className:"max-w-28 truncate typography-micro text-muted-foreground",children:["@",o]})]})},Hy=l.memo(function({isDesktopApp:t,currentInstanceLabel:s,compactCurrentInstanceLabel:r,currentInstanceIsLocal:o,currentInstanceIcon:i,isDesktopServicesOpen:a,setIsDesktopServicesOpen:c,refreshCurrentInstanceLabel:d,shortcutLabel:u,remoteUpdateInfo:f,remoteUpdateChecking:m,remoteUpdateError:b,onOpenRemoteUpdate:g}){return n.jsxs(Ht,{open:a,onOpenChange:p=>{c(p),p&&d()},children:[n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx(qt,{asChild:!0,children:n.jsxs("button",{type:"button","aria-label":t?`Open instance, usage and MCP (current: ${s})`:"Open services, usage and MCP",className:_(Ss,t?"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5":"h-8 w-8"),children:[n.jsx(R,{name:i.name,className:"h-[18px] w-[18px]",style:i.color?{color:i.color}:void 0}),t?n.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:r}):null]})})}),n.jsx(Ge,{children:n.jsx("p",{children:`Current instance: ${s} (${u("toggle_services_menu")})`})})]}),n.jsx(Vt,{align:"end",className:"w-[min(27rem,calc(100vw-2rem))] max-h-[75vh] overflow-y-auto p-0",children:t?n.jsxs("div",{children:[o?null:n.jsx("div",{className:"border-b border-[var(--interactive-border)] px-4 py-2.5",children:n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Remote instance update"}),n.jsx("div",{className:"typography-micro text-muted-foreground",children:f?.available?`Version ${f.version||""} is available for this instance.`:m?"Looking for updates...":b||"This instance is up to date."})]}),f?.available?n.jsx("button",{type:"button",className:"shrink-0 rounded-md bg-[var(--primary-base)] px-3 py-1.5 typography-ui-label font-medium text-[var(--primary-foreground)] hover:opacity-90",onClick:g,children:"Update"}):null]})}),n.jsx(Ef,{embedded:!0,open:a,onOpenChange:()=>{},onHostSwitched:()=>c(!1)})]}):null})]})}),qy=({action:e,onClose:t,sessionTitle:s,onConfirm:r})=>n.jsx(en,{open:e!==null,onOpenChange:o=>{o||t()},children:n.jsxs(tn,{showCloseButton:!1,className:"max-w-sm gap-5",children:[n.jsxs($n,{children:[n.jsx(mn,{children:e==="delete"?"Delete session?":"Archive session?"}),n.jsx(An,{children:e==="delete"?`"${s}" will be permanently deleted.`:`"${s}" will be archived.`})]}),n.jsxs(ys,{children:[n.jsx(Ae,{variant:"outline",size:"sm",onClick:t,children:"Cancel"}),n.jsx(Ae,{variant:"destructive",size:"sm",onClick:r,children:e==="delete"?"Delete":"Archive"})]})]})}),Vy=e=>{const t=e.trim();if(!t)return"";const s=t.split(/\s+/).filter(Boolean);if(s.length>=2){const r=s[0],o=s[1].slice(0,3),i=`${r} ${o}`.trim();return s.length>2||i.length<t.length?`${i}...`:i}return t.length>12?`${t.slice(0,9).trimEnd()}...`:t},Bs=e=>{if(!e)return"";const t=e.replace(/\\/g,"/");return t==="/"?"/":t.replace(/\/+$/,"")},Yy=l.lazy(()=>pt(()=>import("./SessionSwitcherDropdown-DCBVuCoo.js"),__vite__mapDeps([46,5,10,4,6,1,2,3,7,8,9,11,12])).then(e=>({default:e.SessionSwitcherDropdown}))),Lv=({onToggleLeftDrawer:e,onToggleRightDrawer:t,leftDrawerOpen:s,rightDrawerOpen:r,tabletWorkspaceTab:o,onSelectTabletWorkspaceTab:i,tabletGitHubTabsAvailable:a=!1})=>{Wt("ui.header.render");const c=ue(O=>O.setSessionSwitcherOpen),d=ue(O=>O.toggleSidebar),u=ue(O=>O.isSidebarOpen),f=ue(O=>O.activeMainTab),m=ue(O=>O.setActiveMainTab),b=ue(O=>O.shortcutOverrides);ue(O=>O.timeFormatPreference),Kn();const g=Me(O=>!!O.newSessionDraft?.open),p=Me(O=>O.currentSessionId),h=Ml(p??""),y=Df(p),x=l.useMemo(()=>{if(!y)return null;const O=y;return{title:y.title??null,directory:O.directory??null,created:y.time?.created??null,slug:O.slug??null,shareUrl:y.share?.url??null,parentId:y.parentID??null,messageCount:typeof y.messageCount=="number"?y.messageCount:null}},[y]),k=dt(Bo(O=>{if(!O.activeProjectId)return null;const ce=O.projects.find(ye=>ye.id===O.activeProjectId);return ce?{id:ce.id,path:ce.path,label:ce.label}:null})),v=gs(O=>O.homeDirectory),A=l.useMemo(()=>k?Rf(k):null,[k]),{isMobile:w}=xs(),{enabled:j}=ji(),S=!!(j&&i&&o!==void 0),C=l.useMemo(()=>[...gy(a)],[a]),[E,P]=l.useState(!1),z=l.useRef(null),[K,q]=l.useState(()=>typeof window>"u"?!1:ms()),H=l.useMemo(()=>Wl(),[]),F=Pf(),[D,T]=l.useState(!1),I=l.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),M=Bl(),G=l.useMemo(()=>{if(typeof window>"u")return null;const O=window.__PICHAMBER_MACOS_MAJOR__;if(typeof O=="number"&&Number.isFinite(O)&&O>0)return O;if(typeof navigator>"u")return null;const ce=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!ce)return null;const ye=Number.parseInt(ce[1],10),$e=Number.parseInt(ce[2],10);return Number.isNaN(ye)?null:ye===10?$e:ye},[]);Te.useEffect(()=>{typeof window>"u"||q(ms())},[]);const W=ue(O=>O.isSessionSwitcherOpen),[L,ae]=l.useState(!1),[J,le]=l.useState("Local"),[Ie,Y]=l.useState(!0),[B,$]=l.useState(()=>Rr(null)),[X,ee]=l.useState(!1),[ie,ke]=l.useState(null),[pe,je]=l.useState(!1),[be,ze]=l.useState(null),me=l.useRef(0),Pe=l.useMemo(()=>Vy(J),[J]),V=l.useCallback(async()=>{if(typeof window>"u"||!K)return;const O=Ze(),ce=()=>Ze()===O;try{const ye=await tt("/api/version");if(!ce())return;const $e=ye.ok?await ye.json().catch(()=>null):null;if(!ce())return;if($(Rr($e)),Tr()){le("Local"),Y(!0);return}Y(!1);const ht=await uh();if(!ce())return;const Je=fh(),St=hh([ph(Je),...ht.hosts]);if(St.id===mh){le("Local"),Y(!0);return}le(gh(St.label.trim()||"Instance"))}catch{ce()&&(le("Local"),Y(!0),$(Rr(null)))}},[K]);Te.useEffect(()=>(V(),ws(()=>{me.current+=1,ke(null),ze(null),je(!1),ee(!1),V()})),[V]);const fe=l.useCallback(async()=>{const O=me.current+1;me.current=O;const ce=Ze(),ye=()=>me.current===O&&Ze()===ce;if(Ie){ke(null),ze(null);return}je(!0),ze(null);try{const $e=new URLSearchParams({appType:"web",instanceMode:"remote"}),ht=await tt(`/api/pi/update-check?${$e.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!ht.ok)throw new Error(`Server responded with ${ht.status}`);const Je=await ht.json();if(!ye())return;ke({available:Je.available??!1,version:Je.version,currentVersion:Je.currentVersion??"unknown",body:Je.body,nextSuggestedCheckInSec:typeof Je.nextSuggestedCheckInSec=="number"?Je.nextSuggestedCheckInSec:void 0,packageManager:Je.packageManager,updateCommand:Je.updateCommand,channel:Je.channel==="rc"?"rc":"stable"})}catch($e){if(!ye())return;ke(null),ze($e instanceof Error?$e.message:"Failed to check remote instance updates")}finally{ye()&&je(!1)}},[Ie]);l.useEffect(()=>$p(()=>{Ie||fe()}),[fe,Ie]),l.useEffect(()=>{me.current+=1,ke(null),ze(null),je(!1),ee(!1)},[Ie,J]),l.useEffect(()=>{if(!K||Ie)return;const O=3e3,ce=3600*1e3;let ye=!1,$e=null;const ht=Je=>{$e=window.setTimeout(()=>{if(ye||typeof document<"u"&&document.visibilityState!=="visible"){ht(ce);return}fe().finally(()=>{ye||ht(ce)})},Je)};return ht(O),()=>{ye=!0,$e!==null&&window.clearTimeout($e)}},[fe,Ie,J,K]);const xe=l.useCallback(()=>{if(ie?.available){ee(!0);return}fe()},[fe,ie?.available]),te=p?x??null:null,re=l.useRef(null),[Be,Ce]=l.useState(0);l.useEffect(()=>{if(!p){re.current&&(re.current=null,Ce($e=>$e+1));return}if(te){re.current={sessionId:p,session:te,expiresAt:Date.now()+2e3};return}const O=re.current;if(!O||O.sessionId!==p)return;const ce=O.expiresAt-Date.now();if(ce<=0){re.current=null,Ce($e=>$e+1);return}const ye=window.setTimeout(()=>{re.current?.sessionId===p&&(re.current=null),Ce($e=>$e+1)},ce);return()=>{window.clearTimeout(ye)}},[p,te]);const Q=(()=>{if(te)return te;if(!p)return null;const O=re.current;return O&&O.sessionId===p&&O.expiresAt>Date.now()?O.session:null})(),ve=l.useMemo(()=>{const O=typeof Q?.directory=="string"?Q.directory:"";return Bs(O||"")},[Q?.directory]),he=Me(O=>O.newSessionDraft?.open?Bs(O.newSessionDraft.directoryOverride??""):""),Se=l.useMemo(()=>yy({sessionDirectory:ve,draftDirectory:he,isNewSessionDraftOpen:g}),[he,g,ve]),Ue=Ko(Se||null),U=l.useMemo(()=>wy({activeProjectLabel:A,openDirectory:Se,homeDirectory:v}),[A,v,Se]),ge=!!(U||Ue),se=l.useMemo(()=>p?un(Q,"Untitled session"):U??"PiChamber",[Q,p,U]),_e=Tf(),st=Me(O=>O.updateSessionTitle),mt=Me(O=>O.archiveSessions),Xe=Me(O=>O.deleteSessions),[Yt,gt]=l.useState(!1),[It,nn]=l.useState(!1),Qe=l.useRef(!1),[Mt,Ft]=l.useState(""),[Ct,Ee]=l.useState(null),Ye=l.useRef(null);l.useEffect(()=>{Qe.current=!1,nn(!1),gt(!1),Ft(""),Ee(null)},[p]);const Ne=l.useCallback(()=>{p&&(Ft(Q?.title?.trim()||se),gt(!0))},[Q?.title,p,se]),De=l.useCallback(async()=>{if(!p)return;const O=Mt.trim();O&&O!==Q?.title?.trim()&&await st(p,O),gt(!1)},[Q?.title,p,Mt,st]);l.useEffect(()=>{if(!Yt)return;const O=ce=>{const ye=ce.target;(!ye||!Ye.current?.contains(ye))&&De()};return document.addEventListener("mousedown",O),()=>document.removeEventListener("mousedown",O)},[Yt,De]);const He=l.useCallback(()=>{p&&fn(p).then(O=>{oe[O.ok?"success":"error"](O.ok?"Session ID copied":"Failed to copy session ID")}).catch(()=>oe.error("Failed to copy session ID"))},[p]),ft=l.useCallback(async()=>{if(!p||!Se){oe.error("Nothing to export");return}try{await _e.syncSession(p)}catch{oe.error("Failed to load the complete session history");return}const O=[];if(O.length===0){oe.error("Nothing to export");return}const ce=Gc(O,Q?.title??null),ye=Vc(Q?.title??null);await qc(ce,ye)||Hc(ce,ye),oe.success("Session exported")},[Q?.title,p,Se,_e]);h?.type==="busy"||h?.type;const sn=l.useCallback(async()=>{if(!p||!Ct)return;const O=Mf(),ce=[p];for(let Je=0;Je<ce.length;Je+=1){const St=ce[Je];for(const Rt of O)Rt.parentID===St&&!ce.includes(Rt.id)&&ce.push(Rt.id)}const ye=Ct;if(Ee(null),(ye==="archive"?await mt(ce):await Xe(ce)).failedIds.length>0){oe.error(ye==="archive"?"Failed to archive session":"Failed to delete session");return}oe.success(ye==="archive"?"Session archived":"Session deleted")},[mt,p,Xe,Ct]),Lt=ue(O=>O.isArchivePageOpen),Ot=l.useMemo(()=>Lt?{title:"Archive",subtitle:null}:null,[Lt]),Ve=l.useMemo(()=>Bs(Se||k?.path||""),[k?.path,Se]),rn=l.useCallback(()=>{Ve&&fn(Ve).then(O=>{oe[O.ok?"success":"error"](O.ok?"Working directory copied":"Failed to copy working directory")}).catch(()=>oe.error("Failed to copy working directory"))},[Ve]),In=l.useCallback(()=>{Ue&&fn(Ue).then(O=>{oe[O.ok?"success":"error"](O.ok?"Branch name copied":"Failed to copy branch name")}).catch(()=>oe.error("Failed to copy branch name"))},[Ue]),Et=l.useMemo(()=>k?{id:k.id,path:k.path}:null,[k]),Gn=l.useRef(null);l.useEffect(()=>{!Et||!Ve||(Gn.current={projectRef:Et,directory:Ve})},[Ve,Et]);const xt=l.useMemo(()=>Et&&Ve?{projectRef:Et,directory:Ve}:Gn.current,[Ve,Et]),ot=l.useCallback(()=>{if(typeof document>"u")return;const O=document.activeElement;if(!O)return;const ce=O.tagName;(ce==="INPUT"||ce==="TEXTAREA"||ce==="SELECT"||O.isContentEditable)&&O.blur()},[]),Qt=l.useCallback(()=>{if(w){ot(),c(!W);return}d()},[ot,w,W,c,d]),Bt=l.useCallback(()=>{Gs("desktop_open_draft_mini_chat_window",{directory:Bs(Se||k?.path||""),projectId:k?.id??null,apiBaseUrl:Vo(),clientToken:qo()}).catch(O=>{console.warn("[header] failed to open draft mini chat window",O)})},[k?.id,k?.path,Se]),gn=l.useCallback(()=>{if(g){Bt();return}p&&Gs("desktop_open_session_mini_chat_window",{sessionId:p,directory:Bs(Se||k?.path||""),apiBaseUrl:Vo(),clientToken:qo()}).catch(O=>{console.warn("[header] failed to open session mini chat window",O)})},[k?.path,p,Bt,g,Se]),on=Ss,yt=Sm,wt=l.useMemo(()=>s?"sessions":S?r&&o?o:null:r?"git":f,[f,S,s,r,o]),Dt=l.useCallback(()=>{s&&e&&e(),r&&t&&t(),!e&&W&&c(!1)},[W,s,e,t,r,c]),Hn=l.useCallback(()=>{e?.()},[e]),En=l.useCallback(()=>{t?.()},[t]),Dn=l.useMemo(()=>K&&I&&!D?"5.5rem":F?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":!K||M?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[K,D,I,F,M]);Te.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",Dn)},[Dn]);const kt=u?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",an=u?"0px":K&&M?"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)":j?"2.75rem":"2.5rem";Te.useEffect(()=>{if(!K||!I){T(!1);return}let O=!1;const ce=async()=>{try{const $e=await Gs("desktop_is_window_fullscreen");O||T($e===!0)}catch{O||T(!1)}},ye=()=>{ce()};return ce(),window.addEventListener("pichamber:window-resized",ye),()=>{O=!0,window.removeEventListener("pichamber:window-resized",ye)}},[K,I]);const nt=l.useMemo(()=>!K||!I||G===null?"":G>=26?"h-12":G<=15?"h-14":"",[K,I,G]),ln=l.useMemo(()=>{if(!(K&&!M))return{paddingRight:"calc(0.75rem + var(--oc-wco-right-inset, 0px))",minHeight:"max(3rem, var(--oc-wco-titlebar-height, 0px))",height:"max(3rem, var(--oc-wco-titlebar-height, 0px))"}},[K,M]),vt=l.useCallback(()=>{if(typeof document>"u")return;const O=z.current?.getBoundingClientRect().height;if(O){const ce=`${O}px`,ye=document.documentElement.style;ye.getPropertyValue("--oc-header-height")!==ce&&ye.setProperty("--oc-header-height",ce)}},[]);Te.useEffect(()=>{if(typeof window>"u")return;vt();const O=z.current;if(!O||typeof ResizeObserver>"u")return()=>{};let ce=0;const ye=()=>{ce||(ce=requestAnimationFrame(()=>{ce=0,vt()}))},$e=new ResizeObserver(ye);return $e.observe(O),window.addEventListener("resize",ye),window.addEventListener("orientationchange",ye),()=>{ce&&cancelAnimationFrame(ce),$e.disconnect(),window.removeEventListener("resize",ye),window.removeEventListener("orientationchange",ye)}},[vt]),Te.useEffect(()=>{vt()},[vt,w,nt]);const At=l.useCallback(async O=>{const ce=O.target;ce.closest(".app-region-no-drag")||ce.closest("button, a, input, select, textarea")||O.button===0&&K&&await Ff()},[K]),it=l.useMemo(()=>w?[{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"}]:[],[w]),Rn=l.useCallback(O=>ki(Pr(O,b)),[b]);Te.useEffect(()=>{!w&&f!=="chat"&&f!=="terminal"&&f!=="diagram"&&m("chat")},[f,w,m]),Te.useEffect(()=>{const O=ce=>{if(bh(ce)&&!ce.shiftKey&&!ce.altKey){const ye=parseInt(ce.key,10);ye>=1&&ye<=it.length&&(ce.preventDefault(),w&&(ot(),Dt()),m(it[ye-1].id))}};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[ot,Dt,w,m,it]),Te.useEffect(()=>{const O=ce=>{const ye=Pr("toggle_services_menu",b);if(xh(ce,ye)){ce.preventDefault(),L?ae(!1):(ae(!0),V());return}};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[b,L,V]);const at=O=>{const ce=f===O.id,ye=O.icon==="diff",$e=ye?null:O.icon,ht=O.id==="chat",Je=Rt=>ye?n.jsx(al,{size:Rt}):$e?n.jsx(R,{name:$e,className:`h-${Rt/4} w-${Rt/4}`}):null,St=n.jsxs("button",{type:"button",onClick:()=>m(O.id),className:_("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",ce?"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",ht&&!w&&"min-w-[100px] justify-center"),"aria-label":O.label,"aria-selected":ce,role:"tab",children:[w?Je(20):n.jsxs(n.Fragment,{children:[Je(16),n.jsx("span",{className:"header-tab-label",children:O.label})]}),O.badge!==void 0&&O.badge>0&&n.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:O.badge})]});return n.jsx(l.Fragment,{children:St},O.id)},qn=n.jsxs(n.Fragment,{children:[n.jsx(Cy,{directory:Ve,className:"mr-1"}),K?n.jsx(Hy,{isDesktopApp:K,currentInstanceLabel:J,compactCurrentInstanceLabel:Pe,currentInstanceIsLocal:Ie,currentInstanceIcon:B,isDesktopServicesOpen:L,setIsDesktopServicesOpen:ae,refreshCurrentInstanceLabel:V,shortcutLabel:Rn,remoteUpdateInfo:ie,remoteUpdateChecking:pe,remoteUpdateError:be,onOpenRemoteUpdate:xe}):n.jsx(Wy,{open:L,onOpenChange:ae}),n.jsx(Gy,{isMobile:w})]}),Vn=H&&(g||!!p),ks=()=>n.jsxs("div",{onMouseDown:At,className:_("app-region-drag relative flex h-12 select-none items-center pr-3",nt),style:ln,role:"tablist","aria-label":"Main navigation",children:[n.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:kt}}),n.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:an}}),n.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[Ot?n.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:[n.jsx("span",{className:"truncate typography-ui-label font-normal leading-tight text-foreground max-w-full",children:Ot.title}),Ot.subtitle?n.jsxs(n.Fragment,{children:[n.jsx("span",{"aria-hidden":"true",className:"h-3 w-px shrink-0 bg-border"}),n.jsx("span",{className:"truncate typography-ui-label font-normal leading-tight text-subtle-foreground max-w-full",children:Ot.subtitle})]}):null]}):n.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:n.jsx(l.Suspense,{fallback:n.jsx("button",{type:"button",className:on,"aria-label":"Open session switcher",children:n.jsx(R,{name:"history",className:"h-[18px] w-[18px]"})}),children:n.jsx(Yy,{align:"start",children:n.jsx("button",{type:"button",className:on,"aria-label":"Open session switcher",children:n.jsx(R,{name:"history",className:"h-[18px] w-[18px]"})})})}),n.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 px-1",children:[Yt?n.jsxs("form",{ref:Ye,className:"flex w-full min-w-0 items-center gap-2 leading-tight",onSubmit:O=>{O.preventDefault(),De()},children:[n.jsx("input",{value:Mt,onChange:O=>Ft(O.target.value),autoFocus:!0,onKeyDown:O=>{O.stopPropagation(),O.key==="Escape"&>(!1)},placeholder:"Rename",className:"min-w-0 flex-1 bg-transparent typography-ui-label font-normal leading-tight outline-none placeholder:text-muted-foreground"}),n.jsx("button",{type:"submit","aria-label":"Save session name",title:"Save session name",className:"shrink-0 text-muted-foreground hover:text-foreground",children:n.jsx(R,{name:"check",className:"size-4"})}),n.jsx("button",{type:"button",onClick:()=>gt(!1),"aria-label":"Cancel renaming session",title:"Cancel renaming session",className:"shrink-0 text-muted-foreground hover:text-foreground",children:n.jsx(R,{name:"close",className:"size-4"})})]}):n.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal leading-tight text-foreground",children:g?"New session":se}),ge?n.jsxs(n.Fragment,{children:[n.jsx("span",{"aria-hidden":"true",className:"h-3 w-px shrink-0 bg-border"}),n.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 truncate typography-ui-label font-normal leading-tight text-subtle-foreground",children:[U?n.jsx("span",{className:"truncate",children:U}):null,Ue?n.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[n.jsx(R,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-subtle-foreground"}),n.jsx("span",{className:"truncate",children:Ue})]}):null]})]}):null]}),n.jsx("div",{className:"flex h-[18px] shrink-0 items-center justify-center self-center",children:p&&!g&&!Yt?n.jsxs(Ht,{open:It,onOpenChange:nn,onOpenChangeComplete:O=>{!O&&Qe.current&&(Qe.current=!1,Ne())},children:[n.jsx(qt,{asChild:!0,children:n.jsx(Ae,{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:n.jsx(R,{name:"more",className:"size-4"})})}),n.jsxs(Vt,{align:"end",className:"min-w-[190px]",children:[n.jsxs(ut,{onClick:()=>{Qe.current=!0},children:[n.jsx(R,{name:"pencil-ai",className:"mr-2 size-4"}),"Rename"]}),n.jsxs(ut,{onClick:He,children:[n.jsx(R,{name:"file-copy",className:"mr-2 size-4"}),"Copy session ID"]}),n.jsxs(ut,{onClick:rn,disabled:!Ve,children:[n.jsx(R,{name:"folder",className:"mr-2 size-4"}),"Copy working directory"]}),Ue?n.jsxs(ut,{onClick:In,children:[n.jsx(R,{name:"git-branch",className:"mr-2 size-4"}),"Copy branch name"]}):null,n.jsx(ps,{}),n.jsxs(ut,{onClick:()=>{ft()},children:[n.jsx(R,{name:"download",className:"mr-2 size-4"}),"Export Markdown"]}),n.jsx(ps,{}),n.jsxs(ut,{onClick:()=>Ee("archive"),children:[n.jsx(R,{name:"inbox-archive",className:"mr-2 size-4"}),"Archive"]}),n.jsxs(ut,{className:"text-destructive focus:text-destructive",onClick:()=>Ee("delete"),children:[n.jsx(R,{name:"delete-bin",className:"mr-2 size-4"}),"Delete"]})]})]}):null})]}),it.length>0&&n.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:it.map(O=>at(O))}),n.jsx("div",{className:"flex-1"}),n.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[n.jsx(pc,{}),xt?n.jsx(dl,{projectRef:xt.projectRef,directory:xt.directory,className:"mr-1"}):null,n.jsx(jm,{visible:Vn,title:g?"New Mini Chat window":"Open session in Mini Chat",ariaLabel:g?"Open a new Mini Chat window":"Open current session in Mini Chat",onClick:gn,className:_(on,"mr-1"),Icon:"picture-in-picture-2"}),qn,n.jsx(Lf,{visible:M})]})]})]}),Pn=()=>n.jsxs("div",{className:"app-region-drag relative flex items-center gap-2 px-3 py-2 select-none",children:[j&&n.jsxs(n.Fragment,{children:[n.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:kt}}),n.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:an}})]}),!j&&n.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e?n.jsx("button",{type:"button",onClick:Hn,className:_(yt,wt==="sessions"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":s?"Close sessions":"Open sessions",children:n.jsx(R,{name:"layout-left",className:"h-5 w-5"})}):W?n.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:n.jsx(R,{name:"arrow-left-s",className:"h-5 w-5"})}):n.jsx("button",{type:"button",onClick:Qt,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:n.jsx(R,{name:"play-list-add",className:"h-5 w-5"})}),!e&&W&&n.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:"Sessions"})]}),(!W||!!e)&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center",children:!S&&n.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:n.jsx("div",{className:"flex w-max items-center gap-1 pr-1",children:n.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:it.map(O=>{const ce=f===O.id,ye=O.icon==="diff",$e=ye?null:O.icon;return n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsxs("button",{type:"button",onClick:()=>{w&&(ot(),Dt()),m(O.id)},"aria-label":O.label,"aria-selected":ce,role:"tab",className:_(yt,"relative rounded-lg",wt===O.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[ye?n.jsx(al,{className:"h-5 w-5"}):$e?n.jsx(R,{name:$e,className:"h-5 w-5"}):null,O.badge!==void 0&&O.badge>0&&n.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:O.badge}),O.showDot&&n.jsx("span",{className:"absolute top-1.5 right-1.5 h-2 w-2 rounded-full bg-primary","aria-label":"Changes available"})]})}),n.jsx(Ge,{children:n.jsx("p",{children:O.label})})]},O.id)})})})})}),n.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[S&&n.jsxs(n.Fragment,{children:[n.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:C.map(O=>{const ce=r&&o===O.id;return n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:()=>{w&&(ot(),Dt()),P(!1),i?.(O.id)},"aria-label":O.label,"aria-selected":ce,role:"tab",className:_(yt,"relative h-11 w-11 rounded-lg",ce&&"bg-interactive-selection text-interactive-selection-foreground"),children:n.jsx(R,{name:O.icon,className:"h-5 w-5"})})}),n.jsx(Ge,{children:n.jsx("p",{children:O.label})})]},O.id)})}),n.jsx(vm,{open:E,onOpenChange:P,currentSessionId:p,effectiveDirectory:Se||null,isNewSessionDraftOpen:g})]}),xt&&n.jsx(dl,{projectRef:xt.projectRef,directory:xt.directory,compact:!0,allowMobile:!0,className:"h-9"}),t&&!S?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:En,className:_(yt,"relative",wt==="git"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":r?"Close git sidebar":"Open git sidebar",children:n.jsx(R,{name:"layout-right",className:"h-5 w-5"})})}),n.jsx(Ge,{children:n.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),As=_("header-safe-area relative z-10 bg-background",w&&"border-b border-border/50");return n.jsxs(n.Fragment,{children:[n.jsx("header",{ref:z,className:As,style:{"--padding-scale":"1"},children:w?Pn():ks()}),n.jsx(qy,{action:Ct,onClose:()=>Ee(null),sessionTitle:se,onConfirm:()=>{sn()}}),n.jsx(ic,{open:X,onOpenChange:ee,info:ie,downloading:!1,downloaded:!1,progress:null,error:be,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})},ul="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",Qy="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",Ov=()=>{const e=ue(g=>g.isSidebarOpen),t=ue(g=>g.toggleSidebar),s=ue(g=>g.shortcutOverrides),r=l.useRef(null),o=l.useRef(null),i=ki(Pr("toggle_sidebar",s)),a=Bl(),{enabled:c}=ji(),d=!e,u=a,f=d||u,m=u,b=l.useCallback(()=>{Gs("desktop_show_app_menu").catch(g=>{console.warn("[titlebar] failed to open app menu",g)})},[]);return l.useEffect(()=>{if(typeof document>"u")return;const g=v=>{document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(v)}px`)},p=v=>{document.documentElement.style.setProperty("--oc-titlebar-overlay-width",`${Math.round(v)}px`)};if(!m)return;const h=o.current,y=r.current;if(!h||!y){g(0),p(0);return}const x=()=>{const v=Math.max(h.getBoundingClientRect().width,h.scrollWidth);g(v),p(y.getBoundingClientRect().width)};if(x(),typeof ResizeObserver>"u")return;const k=new ResizeObserver(x);return k.observe(h),k.observe(y),()=>{k.disconnect()}},[m]),f?n.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:n.jsxs("div",{ref:o,className:"flex items-center gap-2",children:[u?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:b,"aria-label":"Open PiChamber menu",className:_(ul,"shrink-0"),children:n.jsx(R,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),n.jsx(Ge,{children:n.jsx("p",{children:"PiChamber menu"})})]}):null,d?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:t,"aria-label":"Open sessions",className:_(c?Qy:ul,"shrink-0"),children:n.jsx(R,{name:"layout-left",className:c?"size-[18px]":"h-[18px] w-[18px]"})})}),n.jsx(Ge,{children:n.jsx("p",{children:`Open sessions (${i})`})})]}):null]})}):null},fl=200,Jy="cubic-bezier(0.22, 1, 0.36, 1)",Bv=e=>{const t=l.useMemo(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches,[]),[s,r]=l.useState(e),[o,i]=l.useState(e);return l.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 a=window.setTimeout(()=>i(!1),fl);return()=>window.clearTimeout(a)},[e,t]),{slidIn:s,layoutVisible:o,prefersReducedMotion:t,transition:t?"none":`transform ${fl}ms ${Jy}`}},_v=()=>{Hl()},zv=e=>{Me.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),ue.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),we.getState().clearAll(),Hl(),gs.getState().resetForRuntimeSwitch(),Of.getState().resetForRuntimeSwitch(),Bf.getState().resetForRuntimeSwitch(),_f(),yh(),wh(),Hf(),zf.getState().resetForRuntimeSwitch(),Uf.getState().resetForRuntimeSwitch(),$f.getState().resetForRuntimeSwitch(),Yp.getState().resetForRuntimeSwitch(),Kt.setState({providers:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),dt.getState().resetForRuntimeSwitch(),Kf(),Wf(),Mh.getState().reset(),vh.getState().resetForRuntimeSwitch(),El.getState().resetForRuntimeSwitch(e.runtimeKey),Wo.getState().resetForRuntimeSwitch(e.runtimeKey),Sh(),zn.getState().resetForRuntimeSwitch(e.runtimeKey),Gf.getState().resetForRuntimeSwitch(),Zt.getState().resetForRuntimeSwitch(),bt.getState().resetForRuntimeSwitch(e.runtimeKey),jh.getState().resetForRuntimeSwitch(e.runtimeKey),Me.getState().restoreForRuntimeSwitch(e.runtimeKey),ue.getState().restoreForRuntimeSwitch(e.runtimeKey);const t=ue.getState();Xo({sessionId:Me.getState().currentSessionId,tab:t.activeMainTab,isSettingsOpen:t.isSettingsDialogOpen,settingsPath:t.settingsPage,diffFile:t.pendingDiffFile},{replace:!0,force:!0})};export{cv as $,Hr as A,pv as B,uv as C,ym as D,Ta as E,vm as F,Ix as G,Za as H,zs as I,kx as J,Ev as K,Iv as L,hc as M,Er as N,Dv as O,gy as P,Rv as Q,Yx as R,Nv as S,cc as T,Pv as U,Zc as V,Tv as W,Bv as X,Mv as Y,Ov as Z,Lv as _,Fn as a,Rw as a$,zw as a0,_v as a1,zv as a2,mw as a3,bw as a4,xw as a5,gw as a6,fw as a7,hw as a8,dw as a9,lv as aA,av as aB,Ww as aC,nv as aD,tv as aE,Zw as aF,mm as aG,gm as aH,ya as aI,Fv as aJ,hp as aK,pw as aL,vw as aM,Pp as aN,_w as aO,Bp as aP,Ew as aQ,Ni as aR,ic as aS,Aw as aT,Lp as aU,Yp as aV,Pw as aW,Bw as aX,Iw as aY,ar as aZ,Dw as a_,Qr as aa,Jr as ab,Xr as ac,_n as ad,Bc as ae,Mn as af,Ac as ag,rr as ah,kc as ai,yw as aj,Gw as ak,$w as al,Uw as am,Kw as an,iv as ao,sv as ap,rv as aq,ov as ar,Xw as as,Jw as at,qw as au,Hw as av,Vw as aw,pm as ax,Qw as ay,Yw as az,Cs as b,zp as b0,Mp as b1,Up as b2,cm as b3,qs as b4,Sw as b5,lc as b6,Mw as b7,_p as b8,ir as b9,ac as ba,Nw as bb,ww as bc,Tp as bd,Ow as be,Fw as bf,Lw as bg,Tw as bh,jw as bi,Cw as bj,kw as bk,ev as bl,rm as bm,Op as bn,mp as bo,Fp as bp,gp as bq,Bg as c,Os as d,js as e,hm as f,gv as g,hv as h,jn as i,Zt as j,dv as k,kv as l,Av as m,yv as n,Oc as o,bv as p,fv as q,mv as r,di as s,xv as t,uw as u,vv as v,Sv as w,jv as x,Cv as y,wv as z};
|