@pi-chamber/web 1.0.4-rc.1 → 1.0.4-rc.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/DiagramView--BGR3PRZ.js +1 -0
- package/dist/assets/{DiffView-BjWUdbL5.js → DiffView-hz90_htv.js} +5 -5
- package/dist/assets/FileSaveConflictDialog-CcrWHRvd.js +3 -0
- package/dist/assets/{FilesView-qP1ypN9J.js → FilesView-DaqkPMqx.js} +4 -4
- package/dist/assets/{GitHubDetailScaffold-zCKCy5OJ.js → GitHubDetailScaffold-BZhP67Va.js} +2 -2
- package/dist/assets/GitHubLinkPicker-CJZmDljp.js +1 -0
- package/dist/assets/{GitHubListPrimitives-Ck3zllel.js → GitHubListPrimitives-DhF42guB.js} +1 -1
- package/dist/assets/{GitView-y2k2i4gR.js → GitView-JK-QCK9R.js} +4 -4
- package/dist/assets/{IssuesSurface-HWgR87N3.js → IssuesSurface-CAqQzrsv.js} +3 -3
- package/dist/assets/{JsonTreeView-DSuC4naV.js → JsonTreeView-CKTqB1CD.js} +1 -1
- package/dist/assets/MarkdownRendererImpl-B5kJy9Nt.js +12 -0
- package/dist/assets/{PatchDiff-DArTeWeK.js → PatchDiff-BQnRFN30.js} +1 -1
- package/dist/assets/{PierreDiffViewer-DQKujzLb.js → PierreDiffViewer-BeGpdI0x.js} +2 -2
- package/dist/assets/PullRequestsSurface-D9beq2x9.js +2 -0
- package/dist/assets/SessionSwitcherContent-DElQ_cjm.js +1 -0
- package/dist/assets/SessionSwitcherDropdown-JaIDcDIj.js +2 -0
- package/dist/assets/SessionUnreadDot-Czfvjbdi.js +1 -0
- package/dist/assets/SettingsView-C_GC1Mx3.js +6 -0
- package/dist/assets/SettingsWindow-CAxKgYOu.js +1 -0
- package/dist/assets/ToolOutputDialog-lz5exVQ4.js +8 -0
- package/dist/assets/ToolPartDiffPreview-nIUiNLpP.js +1 -0
- package/dist/assets/{VirtualizedFileDiff-D6KbvKc6.js → VirtualizedFileDiff-IWqCJNXu.js} +1 -1
- package/dist/assets/{Virtualizer-wpC51ZBQ.js → Virtualizer-Cp_cJWbI.js} +1 -1
- package/dist/assets/{collapsible-DhV9d4dT.js → collapsible-C7oyikVm.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-CeMpF2xC.js → computeVirtualFileMetrics-CyhUKEfv.js} +1 -1
- package/dist/assets/{contextFileOpenGuard-Ck5u_kAP.js → contextFileOpenGuard-DkjmJ-NU.js} +1 -1
- package/dist/assets/{gitStatusPredicates-DEBSqUNE.js → gitStatusPredicates-DBmUY3kA.js} +1 -1
- package/dist/assets/{githubLink-DT7i2NlH.js → githubLink-BdbPMMAK.js} +5 -5
- package/dist/assets/index-BnZVqcki.js +11 -0
- package/dist/assets/index-BnieExes.css +1 -0
- package/dist/assets/index-CKgYIOis.js +1 -0
- package/dist/assets/{main-BczEScAA.js → main-6YKi4QM2.js} +2 -2
- package/dist/assets/{main-CHLNMYeJ.js → main-CWdWdhdL.js} +8 -8
- package/dist/assets/{markdownCore-C4Gk5Zht.js → markdownCore-D7V46WY9.js} +1 -1
- package/dist/assets/miniChat-PanPmbEK.js +2 -0
- package/dist/assets/mobile-0LY-2fxw.js +2 -0
- package/dist/assets/nativeFileSave-BzhtrDoD.js +1 -0
- package/dist/assets/{pi-session-focus-preference-LDVCJ_YR.js → pi-session-focus-preference-BC-ze1oC.js} +4 -4
- package/dist/assets/{renderDiffWithHighlighter-CDsgOnkH.js → renderDiffWithHighlighter-ByZtK9za.js} +1 -1
- package/dist/assets/renderElectronMiniChatApp-DETQLjFi.js +2 -0
- package/dist/assets/{renderFileWithHighlighter-TpKRyfCY.js → renderFileWithHighlighter-CnN0Tv_8.js} +1 -1
- package/dist/assets/renderMobileApp-DS0FDQLg.js +11 -0
- package/dist/assets/runtimeEndpointReset-BqqXMwE9.js +62 -0
- package/dist/assets/{runtimeSurface-DW_Ia4q3.js → runtimeSurface-DBiUWYK2.js} +1 -1
- package/dist/assets/useAppFontEffects-BisjofNZ.js +212 -0
- package/dist/assets/{useFilesViewSearch-C_LzYIgD.js → useFilesViewSearch-BWABG6pS.js} +3 -3
- package/dist/assets/{useGitHubRemoteSearch-DsxWOzKZ.js → useGitHubRemoteSearch-Bsf2YeQP.js} +1 -1
- package/dist/assets/{useSwitcherItems-BmoCnS9W.js → useSwitcherItems-BSTSev5C.js} +1 -1
- package/dist/assets/vendor-aparajita-capacitor-secure-storage-BYohCVY0.js +1 -0
- package/dist/assets/{vendor-base-ui-DIkTOIJS.js → vendor-base-ui-BscvGUFt.js} +1 -1
- package/dist/assets/vendor-boot-Dgb9NVFe.js +69 -0
- package/dist/assets/vendor-capacitor-app-BjdQVib9.js +1 -0
- package/dist/assets/vendor-capacitor-keyboard-eTtI5go3.js +1 -0
- package/dist/assets/vendor-capacitor-push-notifications-CBKq2Arn.js +1 -0
- package/dist/assets/vendor-capacitor-status-bar-9rNIGxlO.js +1 -0
- package/dist/assets/{vendor-codemirror-autocomplete-DsFn4GLp.js → vendor-codemirror-autocomplete-DxS3jwvE.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-angular-B_NMmBbS.js → vendor-codemirror-lang-angular-DdjXl9e2.js} +1 -1
- package/dist/assets/vendor-codemirror-lang-cpp--aMr7NVt.js +1 -0
- package/dist/assets/vendor-codemirror-lang-css-CZ_qxZY9.js +1 -0
- package/dist/assets/{vendor-codemirror-lang-go-C2KHbcll.js → vendor-codemirror-lang-go-Ca-y2Alu.js} +2 -2
- package/dist/assets/vendor-codemirror-lang-html-COZ0L5wT.js +1 -0
- package/dist/assets/vendor-codemirror-lang-java-D3Rf3QNJ.js +1 -0
- package/dist/assets/{vendor-codemirror-lang-javascript-DpTUrvx8.js → vendor-codemirror-lang-javascript-DwJ-IvCs.js} +2 -2
- package/dist/assets/vendor-codemirror-lang-jinja-D_5lod6k.js +1 -0
- package/dist/assets/vendor-codemirror-lang-json-BG8C7OpC.js +1 -0
- package/dist/assets/vendor-codemirror-lang-less-CVEkoaTw.js +1 -0
- package/dist/assets/vendor-codemirror-lang-liquid-U9vj0m8w.js +1 -0
- package/dist/assets/vendor-codemirror-lang-markdown-DqlYH9gY.js +1 -0
- package/dist/assets/vendor-codemirror-lang-php-BFEiEVA1.js +1 -0
- package/dist/assets/vendor-codemirror-lang-python-Cz1dQXQd.js +3 -0
- package/dist/assets/vendor-codemirror-lang-rust-C_CoD9mj.js +1 -0
- package/dist/assets/vendor-codemirror-lang-sass-BuR0aKh5.js +1 -0
- package/dist/assets/{vendor-codemirror-lang-sql-C_RazIaB.js → vendor-codemirror-lang-sql-DggNUjdM.js} +2 -2
- package/dist/assets/{vendor-codemirror-lang-vue-BYL0r7KR.js → vendor-codemirror-lang-vue-DFZHi2J3.js} +1 -1
- package/dist/assets/vendor-codemirror-lang-wast-zuTN3SHT.js +1 -0
- package/dist/assets/vendor-codemirror-lang-xml-CrcvhI-k.js +1 -0
- package/dist/assets/vendor-codemirror-lang-yaml-DcVWsakb.js +1 -0
- package/dist/assets/{vendor-codemirror-language-data-DglcKYWT.js → vendor-codemirror-language-data-CCLITgCF.js} +2 -2
- package/dist/assets/{vendor-codemirror-search-DaE6R5gH.js → vendor-codemirror-search-H7NOEdbX.js} +2 -2
- package/dist/assets/{vendor-lezer-cpp-Dt99h3WT.js → vendor-lezer-cpp-C8aD2KAr.js} +1 -1
- package/dist/assets/{vendor-lezer-css-DNU_fzPI.js → vendor-lezer-css-2lbTJF-Y.js} +1 -1
- package/dist/assets/{vendor-lezer-go-BEFtcNyS.js → vendor-lezer-go-Bw6LFTrZ.js} +1 -1
- package/dist/assets/{vendor-lezer-html-DDGRhRUz.js → vendor-lezer-html-D7ym2z7S.js} +1 -1
- package/dist/assets/{vendor-lezer-java-DmfZtW09.js → vendor-lezer-java-CZhK7w21.js} +1 -1
- package/dist/assets/{vendor-lezer-javascript-oje4tdp_.js → vendor-lezer-javascript-rpKeTHZp.js} +1 -1
- package/dist/assets/{vendor-lezer-json-BRXb_bDX.js → vendor-lezer-json-C7jwsd2G.js} +1 -1
- package/dist/assets/{vendor-lezer-lr-BU2qmu_5.js → vendor-lezer-lr-DR-ylqNN.js} +1 -1
- package/dist/assets/{vendor-lezer-markdown-CicYv7V9.js → vendor-lezer-markdown-Bir0m5nB.js} +1 -1
- package/dist/assets/{vendor-lezer-php-COORrTpE.js → vendor-lezer-php-y0hIEfo1.js} +1 -1
- package/dist/assets/{vendor-lezer-python-Cuvm9X9Y.js → vendor-lezer-python-D64A9lNV.js} +1 -1
- package/dist/assets/{vendor-lezer-rust-C_zOfHbX.js → vendor-lezer-rust-E3ZA9T2L.js} +1 -1
- package/dist/assets/{vendor-lezer-sass-DWP4w7O1.js → vendor-lezer-sass-C5UFI9SP.js} +1 -1
- package/dist/assets/{vendor-lezer-xml-Br6nOYeG.js → vendor-lezer-xml-DOy7FzCR.js} +1 -1
- package/dist/assets/{vendor-lezer-yaml-CYQmm6Sb.js → vendor-lezer-yaml-kEjaSCvZ.js} +1 -1
- package/dist/assets/{vendor-replit-codemirror-vim-CZy3BUVv.js → vendor-replit-codemirror-vim-BLfh0LPy.js} +1 -1
- package/dist/assets/{web-components-CH3-XV-n.js → web-components-CdMfsnXE.js} +1 -1
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +2 -2
- package/server/lib/pi/routes.js +1 -0
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +22 -9
- package/server/lib/pi/session-daemon/builtin-extensions.js +37 -0
- package/server/lib/pi/session-daemon/daemon-process.js +6 -0
- package/server/lib/pi/session-daemon/extension-theme.js +75 -0
- package/server/lib/pi/session-daemon/extension-theme.test.js +47 -0
- package/server/lib/pi/session-daemon/prompt-operations.test.js +3 -3
- package/server/lib/pi/session-daemon/prompt-preflight.test.js +12 -14
- package/server/lib/pi/session-daemon/sdk-upgrade.test.js +118 -2
- package/server/lib/pi/session-daemon/send-operation-dedup.test.js +1 -1
- package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +1 -1
- package/server/lib/pi/session-daemon/session-daemon-mcp.e2e.test.js +638 -0
- package/server/lib/pi/session-daemon/session-daemon-turn.e2e.test.js +437 -0
- package/server/lib/pi/session-daemon/session-daemon.js +61 -42
- package/server/lib/pi/session-daemon/session-daemon.test.js +53 -5
- package/server/lib/pi/session-daemon/session-idle-residency.test.js +1 -1
- package/server/lib/pi/session-daemon/session-replay.test.js +1 -1
- package/server/lib/pi/session-daemon/supervisor.js +13 -1
- package/server/lib/pi/session-daemon/supervisor.test.js +92 -0
- package/server/lib/pi/session-persistence-gap.test.js +2 -3
- package/server/lib/pi/ui-settings-store.js +1 -0
- package/server/lib/pi/ui-settings-store.test.js +27 -0
- package/server/lib/relay/DOCUMENTATION.md +4 -0
- package/server/lib/terminal/DOCUMENTATION.md +1 -0
- package/dist/assets/DiagramView-DfZMQkXY.js +0 -1
- package/dist/assets/FileSaveConflictDialog-u5L4k_5k.js +0 -3
- package/dist/assets/GitHubLinkPicker-CwxKY3lN.js +0 -1
- package/dist/assets/MarkdownRendererImpl-CT5ln9em.js +0 -12
- package/dist/assets/PullRequestsSurface-Cfb1wSvC.js +0 -2
- package/dist/assets/SessionSwitcherContent-DEGJyZBl.js +0 -1
- package/dist/assets/SessionSwitcherDropdown-cC9wVBH7.js +0 -2
- package/dist/assets/SessionUnreadDot-CELKNVIM.js +0 -1
- package/dist/assets/SettingsView-CZvRRgJe.js +0 -6
- package/dist/assets/SettingsWindow-CZM1dmVb.js +0 -1
- package/dist/assets/ToolOutputDialog-DClOSbJc.js +0 -8
- package/dist/assets/ToolPartDiffPreview-BaFiGUDE.js +0 -1
- package/dist/assets/index-6IO1AcJI.js +0 -10
- package/dist/assets/index-BAmzAlNx.css +0 -1
- package/dist/assets/index-eDf4LKLY.js +0 -1
- package/dist/assets/miniChat-Do3hE87Z.js +0 -2
- package/dist/assets/mobile-CTnihwfa.js +0 -2
- package/dist/assets/renderElectronMiniChatApp-DSa3gYqR.js +0 -2
- package/dist/assets/renderMobileApp-CPE-3uMl.js +0 -11
- package/dist/assets/runtimeEndpointReset-CzJfovWI.js +0 -62
- package/dist/assets/useAppFontEffects-CG3_yteE.js +0 -212
- package/dist/assets/vendor-aparajita-capacitor-secure-storage-5IShChL0.js +0 -1
- package/dist/assets/vendor-boot-DyL2td56.js +0 -69
- package/dist/assets/vendor-capacitor-app-BrDJj9I_.js +0 -1
- package/dist/assets/vendor-capacitor-core-B4EWRrHz.js +0 -1
- package/dist/assets/vendor-capacitor-keyboard-CYccoJjr.js +0 -1
- package/dist/assets/vendor-capacitor-push-notifications-KNe1zSBF.js +0 -1
- package/dist/assets/vendor-capacitor-status-bar-B-N0EOVk.js +0 -1
- package/dist/assets/vendor-codemirror-lang-cpp-GOE7Gjd0.js +0 -1
- package/dist/assets/vendor-codemirror-lang-css-Dwf2XpnZ.js +0 -1
- package/dist/assets/vendor-codemirror-lang-html-DcKqyeGk.js +0 -1
- package/dist/assets/vendor-codemirror-lang-java-6eGbyB2k.js +0 -1
- package/dist/assets/vendor-codemirror-lang-jinja-xSUJjXhr.js +0 -1
- package/dist/assets/vendor-codemirror-lang-json-CLGxdOCz.js +0 -1
- package/dist/assets/vendor-codemirror-lang-less-6nXi1rS9.js +0 -1
- package/dist/assets/vendor-codemirror-lang-liquid-B9hmb9P8.js +0 -1
- package/dist/assets/vendor-codemirror-lang-markdown-DmFP9s6x.js +0 -1
- package/dist/assets/vendor-codemirror-lang-php-DC6To8iX.js +0 -1
- package/dist/assets/vendor-codemirror-lang-python-yuxIkjit.js +0 -3
- package/dist/assets/vendor-codemirror-lang-rust-di1Sjz-0.js +0 -1
- package/dist/assets/vendor-codemirror-lang-sass-BWpV9NPV.js +0 -1
- package/dist/assets/vendor-codemirror-lang-wast-BiVarhcz.js +0 -1
- package/dist/assets/vendor-codemirror-lang-xml-Cn1lY1ts.js +0 -1
- package/dist/assets/vendor-codemirror-lang-yaml-BZ6mZw9L.js +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{c5 as q}from"./useAppFontEffects-CG3_yteE.js";import{R as x,g as L,r as D,p as W,v as A,a as v,b as M,c as P,d as R,e as V,f as _,h as Q,i as m}from"./computeVirtualFileMetrics-CeMpF2xC.js";import{h as w,i as C,a as k,r as N}from"./renderFileWithHighlighter-TpKRyfCY.js";import{a as g,i as I,r as $,b as j}from"./renderDiffWithHighlighter-CDsgOnkH.js";import{t as K}from"./themeResolver-yJ9XpNMI.js";import{L as S}from"./vendor-lru_map-DOPmc7GU.js";import"./index-6IO1AcJI.js";import"./vendor-zustand-CUi8eEds.js";import"./vendor-react-DASdDPIk.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-tailwind-merge-CPcsbTWB.js";import"./vendor-fuse.js-Dw8P0qyA.js";import"./vendor-boot-DyL2td56.js";import"./vendor-vite-runtime-DD1OZmLC.js";import"./runtimeSurface-DW_Ia4q3.js";import"./vendor-shiki-Bbf2GEcE.js";import"./vendor-shikijs-core-CGM_jqPK.js";import"./vendor-shikijs-types-CPSbSeK6.js";import"./vendor-shikijs-vscode-textmate-BgLrS_2D.js";import"./vendor-hast-util-to-html-BKBhbTDb.js";import"./vendor-html-void-elements-CkdplsNl.js";import"./vendor-property-information-rJCbAzvX.js";import"./vendor-zwitch-C2o2j-tx.js";import"./vendor-stringify-entities-CsH1VEn9.js";import"./vendor-character-entities-legacy-BpoLgcEt.js";import"./vendor-character-entities-html4-D7taRCQ7.js";import"./vendor-ccount-c2V3InAJ.js";import"./vendor-comma-separated-tokens-D8TqSuIK.js";import"./vendor-space-separated-tokens-DD3iYX1K.js";import"./vendor-hast-util-whitespace-D4Wp6AEg.js";import"./vendor-shikijs-engine-oniguruma-DPWuIF1G.js";import"./vendor-pierre-theming-Dgp7B_O4.js";import"./vendor-shikijs-engine-javascript-Cme4830A.js";import"./vendor-oniguruma-to-es-DLBnFDCE.js";import"./vendor-oniguruma-parser-C0D4_9rT.js";import"./vendor-regex-BBWcyTkg.js";import"./vendor-regex-utilities-2BQyy0xI.js";import"./vendor-regex-recursion-JU4mF-dD.js";import"./vendor-shikijs-transformers-CZWsLLKm.js";import"./vendor-diff-C3JhlQdm.js";function B(e){const t=[];for(const i of e){const s=x.get(i);if(s==null)throw new Error(`getResolvedLanguages: ${i} is not resolved. Please resolve languages before calling getResolvedLanguages`);t.push(s)}return t}function O(e){for(const t of Array.isArray(e)?e:[e])if(!x.has(t))return!1;return!0}async function b(e){const t=[],i=[];for(const s of e){if(s==="text"||s==="ansi")continue;const r=L(s)??D(s);"then"in r?i.push(r):t.push(r)}return i.length>0&&await Promise.all(i).then(s=>{for(const r of s){if(r==null)throw new Error("resolvedLanguages: unable to resolve language");t.push(r)}}),t}function z(e){return K.getResolvedThemes(e)}async function E(e){for(const i of e)W(i);const t=await K.resolveThemes(e);for(let i=0;i<e.length;i++)A(e[i],t[i]);return t}const p=Symbol("IGNORE_RESPONSE");var T=class extends Error{constructor(){super("WorkerPoolManager: operation canceled because the pool terminated")}},G=class{options;highlighter;preferredHighlighter;renderOptions;renderOptionsRequestVersion=0;renderOptionsVersion=0;initialized=!1;workers=[];queuedTasks=[];queuedTaskByInstance=new Map;taskByHighlightKey=new Map;activeTaskById=new Map;activeRequestByInstance=new Map;nextRequestId=0;themeSubscribers=new Set;workersFailed=!1;statSubscribers=new Set;fileCache;diffCache;_queuedBroadcast;lifecycleGeneration=0;constructor(e,{langs:t,theme:i=q,useTokenTransformer:s=!1,lineDiffType:r="word-alt",maxLineDiffLength:n=1e3,tokenizeMaxLineLength:a=1e3,preferredHighlighter:h="shiki-js"}){this.options=e,this.preferredHighlighter=h,this.renderOptions={theme:i,useTokenTransformer:s,lineDiffType:r,maxLineDiffLength:n,tokenizeMaxLineLength:a},this.fileCache=new S.LRUMap(e.totalASTLRUCacheSize??100),this.diffCache=new S.LRUMap(e.totalASTLRUCacheSize??100),this.queueInitialization(t)}isWorkingPool(){return!this.workersFailed}getFileResultCache(e){return e.cacheKey!=null?this.fileCache.get(e.cacheKey):void 0}getDiffResultCache(e){return e.cacheKey!=null?this.diffCache.get(e.cacheKey):void 0}inspectCaches(){const{fileCache:e,diffCache:t}=this;return{fileCache:e,diffCache:t}}evictFileFromCache(e){try{return this.fileCache.delete(e)!==void 0}finally{this.queueBroadcastStateChanges()}}evictDiffFromCache(e){try{return this.diffCache.delete(e)!==void 0}finally{this.queueBroadcastStateChanges()}}async setRenderOptions({theme:e=this.renderOptions.theme??q,useTokenTransformer:t=this.renderOptions.useTokenTransformer??!1,lineDiffType:i=this.renderOptions.lineDiffType??"word-alt",maxLineDiffLength:s=this.renderOptions.maxLineDiffLength??1e3,tokenizeMaxLineLength:r=this.renderOptions.tokenizeMaxLineLength??1e3}){const{lifecycleGeneration:n}=this,a=++this.renderOptionsRequestVersion,h=()=>this.isCurrentLifecycle(n)&&this.renderOptionsRequestVersion===a;try{const o={theme:e,useTokenTransformer:t,lineDiffType:i,maxLineDiffLength:s,tokenizeMaxLineLength:r};if(this.isInitialized()||await this.initialize(),!h()||g(o,this.renderOptions))return;const l=v(e);let u=[];if(M(o.theme,this.renderOptions.theme)||(w(l)?u=z(l):u=await E(l)),!h())return;if(this.highlighter!=null)P(u,this.highlighter);else{const y=await R({themes:l,langs:["text"],preferredHighlighter:this.preferredHighlighter});if(!h())return;this.highlighter=y}const H=this.setRenderOptionsOnWorkers(o,u);this.renderOptions=o,this.renderOptionsVersion++,this.diffCache.clear(),this.fileCache.clear(),this.invalidateRenderTasks();for(const y of this.themeSubscribers)y.onThemeChange();await H}catch(o){if(o instanceof T||!h())return;throw o}}getFileRenderOptions(){const{tokenizeMaxLineLength:e,theme:t,useTokenTransformer:i}=this.renderOptions;return{theme:t,useTokenTransformer:i,tokenizeMaxLineLength:e}}getDiffRenderOptions(){return{...this.renderOptions}}async setRenderOptionsOnWorkers(e,t){if(this.workersFailed)return;this.isInitialized()||await this.initialize();const i=[];for(const s of this.workers){if(!s.initialized)throw console.log({managedWorker:s}),new Error("setRenderOptionsOnWorkers: Somehow we have an uninitialized worker");i.push(new Promise((r,n)=>{const a=this.generateRequestId(),h={type:"set-render-options",id:a,request:{type:"set-render-options",id:a,renderOptions:e,resolvedThemes:t},resolve:r,reject:n,requestStart:Date.now()};this.activeTaskById.set(a,h),s.pendingSetupRequestId=a,s.worker.postMessage(h.request)}))}await Promise.all(i)}subscribeToThemeChanges(e){return this.themeSubscribers.add(e),this.queueBroadcastStateChanges(),()=>{this.unsubscribeToThemeChanges(e),this.queueBroadcastStateChanges()}}unsubscribeToThemeChanges(e){this.themeSubscribers.delete(e),this.queueBroadcastStateChanges()}subscribeToStatChanges(e){return this.statSubscribers.add(e),e(this.getStats()),()=>{this.statSubscribers.delete(e)}}queueBroadcastStateChanges(){this._queuedBroadcast==null&&(this._queuedBroadcast=requestAnimationFrame(this._broadcastStateChanges))}_broadcastStateChanges=()=>{this._queuedBroadcast!=null&&(cancelAnimationFrame(this._queuedBroadcast),this._queuedBroadcast=void 0);const e=this.getStats();for(const t of this.statSubscribers)t(e)};cleanUpTasks(e){this.detachInstanceFromQueuedTasks(e);const t=this.activeRequestByInstance.get(e);if(t!=null){const i=this.activeTaskById.get(t);c(i)?(this.detachInstanceFromRenderTask(i,e),!i.primeCache&&i.instances.size===0&&this.removeActiveTask(i)):this.activeTaskById.delete(t)}this.activeRequestByInstance.delete(e),this.queueBroadcastStateChanges()}isInitialized(){return this.initialized===!0}async initialize(e=[]){if(this.initialized!==!0)if(this.initialized===!1){const{lifecycleGeneration:t}=this;this.initialized=new Promise((i,s)=>{(async()=>{try{const r=v(this.renderOptions.theme);let n=[];if(w(r)?n=z(r):n=await E(r),!this.isCurrentLifecycle(t)){i();return}let a=[];if(O(e)?a=B(e):a=await b(e),!this.isCurrentLifecycle(t)){i();return}const[h]=await Promise.all([R({themes:r,langs:["text",...e],preferredHighlighter:this.preferredHighlighter}),this.initializeWorkers(n,a)]);if(!this.isCurrentLifecycle(t)){this.terminateWorkers(),i();return}this.highlighter=h,this.initialized=!0,this.diffCache.clear(),this.fileCache.clear(),this.drainQueue(),this.queueBroadcastStateChanges(),i()}catch(r){if(r instanceof T||!this.isCurrentLifecycle(t)){i();return}this.initialized=!1,this.workersFailed=!0,this.queueBroadcastStateChanges(),s(r)}})()}),this.queueBroadcastStateChanges()}else return this.initialized}async initializeWorkers(e,t){this.workersFailed=!1;const i=[],s=void 0;this.workers.length>0&&this.terminateWorkers();for(let r=0;r<(this.options.poolSize??8);r++){const n=this.options.workerFactory(),a={worker:n,requestId:void 0,pendingSetupRequestId:void 0,initialized:!1,langs:new Set(["text",...t.map(({name:h})=>h)]),customExtensionsVersion:0};n.addEventListener("message",h=>{this.handleWorkerMessage(a,h.data)}),n.addEventListener("error",h=>console.error("Worker error:",h,a)),this.workers.push(a),i.push(new Promise((h,o)=>{const l=this.generateRequestId(),u={type:"initialize",id:l,request:{type:"initialize",id:l,renderOptions:this.renderOptions,preferredHighlighter:this.preferredHighlighter,resolvedThemes:e,resolvedLanguages:t,customExtensionsVersion:void 0,customExtensionMap:s},resolve(){a.initialized=!0,h()},reject:o,requestStart:Date.now()};this.activeTaskById.set(l,u),this.executeTask(a,u)}))}await Promise.all(i)}drainQueue=()=>{if(this._queuedDrain=void 0,!(this.initialized!==!0||this.queuedTasks.length===0)){for(let e=0;e<this.queuedTasks.length;){const t=this.queuedTasks[e];if(this.hasActiveRequest(t)){e++;continue}const i=F(t),s=this.getAvailableWorker(i);if(s==null)break;this.queuedTasks.splice(e,1),this.assignWorkerToTask(t,s),this.resolveLanguagesAndExecuteTask(s,t,i)}this.queueBroadcastStateChanges()}};highlightFileAST(e,t){const i=this.getFileResultCache(t);C(t)||i!=null&&k(i.options,this.getFileRenderOptions())||this.hasMatchingFileInstanceTask(e,t)||this.submitTask(e,{type:"file",file:t})}primeFileHighlightCache(e){if(e.cacheKey==null){console.warn(`WorkerPoolManager.primeFileHighlightCache: priming highlight cache requires file.cacheKey; skipping "${e.name}".`);return}const t=this.getFileResultCache(e),i=this.getFileHighlightKey(e);if(i==null||C(e)||t!=null&&k(t.options,this.getFileRenderOptions()))return;const s=this.getTaskByHighlightKey(i);s!=null?s.primeCache=!0:this.submitCacheTask({type:"file",file:e},i)}getPlainFileAST(e,t,i,s){if(this.highlighter==null){this.queueInitialization();return}return N(e,this.highlighter,this.renderOptions,{forcePlainText:!0,startingLine:t,totalLines:i,lines:s})}highlightDiffAST(e,t){const i=this.getDiffResultCache(t);I(t)||i!=null&&g(i.options,this.getDiffRenderOptions())||this.hasMatchingDiffInstanceTask(e,t)||this.submitTask(e,{type:"diff",diff:t})}primeDiffHighlightCache(e){if(e.cacheKey==null){console.warn(`WorkerPoolManager.primeDiffHighlightCache: priming highlight cache requires diff.cacheKey; skipping "${e.prevName??e.name}" -> "${e.name}".`);return}const t=this.getDiffResultCache(e),i=this.getDiffHighlightKey(e);if(i==null||I(e)||t!=null&&g(t.options,this.getDiffRenderOptions()))return;const s=this.getTaskByHighlightKey(i);s!=null?s.primeCache=!0:this.submitCacheTask({type:"diff",diff:e},i)}getPlainDiffAST(e,t,i,s,r){return this.highlighter!=null?$(e,this.highlighter,this.renderOptions,{forcePlainText:!0,startingLine:t,totalLines:i,expandedHunks:s,collapsedContextThreshold:r}):void 0}terminate(){this.lifecycleGeneration++,this.cancelActiveWorkerTasks(),this.terminateWorkers(),this.fileCache.clear(),this.diffCache.clear(),this.activeRequestByInstance.clear(),this.queuedTasks.length=0,this.queuedTaskByInstance.clear(),this.taskByHighlightKey.clear(),this.activeTaskById.clear(),this.highlighter=void 0,this.initialized=!1,this.workersFailed=!1,this.queueBroadcastStateChanges()}isCurrentLifecycle(e){return this.lifecycleGeneration===e}queueInitialization(e){this.initialize(e).catch(t=>{console.error(t)})}cancelActiveWorkerTasks(){const e=new T;for(const t of this.activeTaskById.values())"reject"in t&&t.reject(e)}terminateWorkers(){for(const e of this.workers)e.worker.terminate();this.workers.length=0}getStats(){return{managerState:this.initialized===!1?"waiting":this.initialized!==!0?"initializing":"initialized",totalWorkers:this.workers.length,workersFailed:this.workersFailed,busyWorkers:this.workers.filter(e=>e.requestId!=null||e.pendingSetupRequestId!=null).length,queuedTasks:this.queuedTasks.length,activeTasks:this.activeTaskById.size,themeSubscribers:this.themeSubscribers.size,fileCacheSize:this.fileCache.size,diffCacheSize:this.diffCache.size}}submitTask(e,t){this.initialized===!1&&this.queueInitialization();const i=this.getHighlightKeyForRequest(t),s=i!=null?this.getTaskByHighlightKey(i):void 0;if(s!=null){this.detachInstanceFromQueuedTasks(e,s),this.addInstanceToTask(s,e),this.queueBroadcastStateChanges();return}this.detachInstanceFromQueuedTasks(e);const r=this.generateRequestId(),n=Date.now(),{renderOptionsVersion:a}=this,h=(()=>{switch(t.type){case"file":return{type:"file",id:r,request:{...t,id:r},instances:new Set([e]),primeCache:!1,highlightKey:i,renderOptionsVersion:a,requestStart:n};case"diff":return{type:"diff",id:r,request:{...t,id:r},instances:new Set([e]),primeCache:!1,highlightKey:i,renderOptionsVersion:a,requestStart:n}}})();this.enqueueRenderTask(h,e)}submitCacheTask(e,t){this.initialized===!1&&this.queueInitialization();const i=this.generateRequestId(),s=Date.now(),{renderOptionsVersion:r}=this,n=(()=>{switch(e.type){case"file":return{type:"file",id:i,request:{...e,id:i},instances:new Set,primeCache:!0,highlightKey:t,renderOptionsVersion:r,requestStart:s};case"diff":return{type:"diff",id:i,request:{...e,id:i},instances:new Set,primeCache:!0,highlightKey:t,renderOptionsVersion:r,requestStart:s}}})();this.enqueueRenderTask(n)}enqueueRenderTask(e,t){this.queuedTasks.push(e),t!=null&&this.queuedTaskByInstance.set(t,e),e.highlightKey!=null&&this.taskByHighlightKey.set(e.highlightKey,e),this.queueDrain()}async resolveLanguagesAndExecuteTask(e,t,i){try{const s=i.filter(r=>!e.langs.has(r));if(s.length>0&&(O(s)?t.request.resolvedLanguages=B(s):t.request.resolvedLanguages=await b(s)),!this.activeTaskById.has(t.id)){e.requestId===t.id&&(this.cleanWorkerAndTask(e,t),this.queueBroadcastStateChanges(),this.queuedTasks.length>0&&this.queueDrain());return}this.executeTask(e,t)}catch{this.cleanWorkerAndTask(e,t),this.queueBroadcastStateChanges(),this.queuedTasks.length>0&&this.queueDrain()}}handleWorkerMessage(e,t){const i=this.activeTaskById.get(t.id);try{if(i==null)throw p;if(t.type==="error"){const s=new Error(t.error);if(t.stack&&(s.stack=t.stack),"reject"in i)i.reject(s);else if(c(i))this.notifyHighlightError(i,s);else throw new Error("handleWorkerMessage: unknown task type");throw s}else switch(t.requestType){case"initialize":if(i.type!=="initialize")throw new Error("handleWorkerMessage: task/response dont match");this.syncCustomExtensionVersion(e,i.request),i.resolve();break;case"set-render-options":if(i.type!=="set-render-options")throw new Error("handleWorkerMessage: task/response dont match");i.resolve();break;case"file":{if(i.type!=="file")throw new Error("handleWorkerMessage: task/response dont match");const{result:s,options:r}=t;if(!this.isCurrentRenderTask(i)||!k(r,this.getFileRenderOptions()))throw p;const{request:n}=i;this.syncCustomExtensionVersion(e,n),n.file.cacheKey!=null&&this.fileCache.set(n.file.cacheKey,{result:s,options:r}),this.notifyFileInstances(i,s,r);break}case"diff":{if(i.type!=="diff")throw new Error("handleWorkerMessage: task/response dont match");const{result:s,options:r}=t;if(!this.isCurrentRenderTask(i)||!g(r,this.getDiffRenderOptions()))throw p;const{request:n}=i;this.syncCustomExtensionVersion(e,n),n.diff.cacheKey!=null&&this.diffCache.set(n.diff.cacheKey,{result:s,options:r}),this.notifyDiffInstances(i,s,r);break}}}catch(s){s!==p&&console.error(s,i,t)}this.cleanWorkerAndTask(e,i,t.id),this.queueBroadcastStateChanges(),this.queuedTasks.length>0&&this.queueDrain()}_queuedDrain;queueDrain(){this._queuedDrain==null&&(this._queuedDrain=Promise.resolve().then(this.drainQueue),this.queueBroadcastStateChanges())}assignWorkerToTask(e,t){t.requestId=e.id,c(e)&&(this.clearQueuedInstanceRequests(e),this.trackInstanceRequests(e)),this.activeTaskById.set(e.id,e)}cleanWorkerAndTask(e,t,i=t?.id){e.requestId===i&&(e.requestId=void 0),e.pendingSetupRequestId===i&&(e.pendingSetupRequestId=void 0),t!=null&&(c(t)&&(this.clearInstanceRequests(t),this.clearHighlightKey(t)),this.activeTaskById.delete(t.id))}executeTask(e,t){U(t.request)&&this.maybeAttachCustomExtensions(e,t.request),this.activeTaskById.has(t.id)||this.assignWorkerToTask(t,e);for(const i of F(t))e.langs.add(i);try{e.worker.postMessage(t.request)}catch(i){console.error("Failed to post message to worker:",i),c(t)?this.notifyHighlightError(t,i):"reject"in t&&t.reject(i),this.cleanWorkerAndTask(e,t),this.queuedTasks.length>0&&this.queueDrain()}this.queueBroadcastStateChanges()}maybeAttachCustomExtensions(e,t){if(t.customExtensionsVersion!=null)return;const i=Q();e.customExtensionsVersion>=i||(t.customExtensionsVersion=i,t.customExtensionMap=V())}syncCustomExtensionVersion(e,t){t.customExtensionsVersion!=null&&(e.customExtensionsVersion=t.customExtensionsVersion)}getAvailableWorker(e){let t;for(const i of this.workers){if(i.requestId!=null||i.pendingSetupRequestId!=null||!i.initialized)continue;if(t=i,e.length===0)break;let s=!0;for(const r of e)if(!i.langs.has(r)){s=!1;break}if(s)break}return t}getFileHighlightKey(e){if(e.cacheKey!=null)return`file:${e.cacheKey}:${this.renderOptionsVersion}`}getDiffHighlightKey(e){if(e.cacheKey!=null)return`diff:${e.cacheKey}:${this.renderOptionsVersion}`}getHighlightKeyForRequest(e){switch(e.type){case"file":return this.getFileHighlightKey(e.file);case"diff":return this.getDiffHighlightKey(e.diff)}}hasActiveRequest(e){for(const t of d(e))if(this.activeRequestByInstance.has(t))return!0;return!1}addInstanceToTask(e,t){e.type,e.instances.add(t),this.activeTaskById.has(e.id)?this.activeRequestByInstance.set(t,e.id):this.queuedTaskByInstance.set(t,e)}detachInstanceFromQueuedTasks(e,t){const i=this.queuedTaskByInstance.get(e);i==null||i===t||(this.queuedTaskByInstance.delete(e),this.detachInstanceFromRenderTask(i,e),!i.primeCache&&i.instances.size===0&&this.removeQueuedTask(i))}detachInstanceFromRenderTask(e,t){e.type,e.instances.delete(t)}removeQueuedTask(e){const t=this.queuedTasks.indexOf(e);t!==-1&&this.queuedTasks.splice(t,1),this.clearQueuedInstanceRequests(e),this.clearHighlightKey(e)}removeActiveTask(e){this.clearInstanceRequests(e),this.clearHighlightKey(e),this.activeTaskById.delete(e.id)}invalidateRenderTasks(){for(let e=this.queuedTasks.length-1;e>=0;e--){const t=this.queuedTasks[e];t.renderOptionsVersion!==this.renderOptionsVersion&&this.removeQueuedTask(t)}for(const e of Array.from(this.activeTaskById.values()))c(e)&&e.renderOptionsVersion!==this.renderOptionsVersion&&this.removeActiveTask(e)}clearQueuedInstanceRequests(e){for(const t of d(e))this.queuedTaskByInstance.get(t)===e&&this.queuedTaskByInstance.delete(t)}clearHighlightKey(e){e.highlightKey!=null&&this.taskByHighlightKey.get(e.highlightKey)===e&&this.taskByHighlightKey.delete(e.highlightKey)}trackInstanceRequests(e){for(const t of d(e))this.activeRequestByInstance.set(t,e.id)}clearInstanceRequests(e){for(const t of d(e))this.activeRequestByInstance.get(t)===e.id&&this.activeRequestByInstance.delete(t)}notifyFileInstances(e,t,i){for(const s of e.instances)this.activeRequestByInstance.get(s)===e.id&&s.onHighlightSuccess(e.request.file,t,i)}notifyDiffInstances(e,t,i){for(const s of e.instances)this.activeRequestByInstance.get(s)===e.id&&s.onHighlightSuccess(e.request.diff,t,i)}notifyHighlightError(e,t){for(const i of d(e))this.activeRequestByInstance.get(i)===e.id&&i.onHighlightError(t)}hasMatchingFileInstanceTask(e,t){for(const i of this.iterateRenderTasks())if(i.type==="file"&&this.isCurrentRenderTask(i)&&i.instances.has(e)&&_(t,i.request.file))return!0;return!1}hasMatchingDiffInstanceTask(e,t){for(const i of this.iterateRenderTasks())if(i.type==="diff"&&this.isCurrentRenderTask(i)&&i.instances.has(e)&&j(i.request.diff,t))return!0;return!1}getTaskByHighlightKey(e){const t=this.taskByHighlightKey.get(e);return t!=null&&this.isCurrentRenderTask(t)?t:void 0}isCurrentRenderTask(e){return e.renderOptionsVersion===this.renderOptionsVersion}*iterateRenderTasks(){for(const e of this.queuedTasks)yield e;for(const e of this.activeTaskById.values())c(e)&&(yield e)}generateRequestId(){return`req_${++this.nextRequestId}`}};function U(e){return e.type==="initialize"||e.type==="file"||e.type==="diff"}function F(e){const t=new Set;if(e.type==="initialize"||e.type==="set-render-options")return[];switch(e.type){case"file":t.add(e.request.file.lang??m(e.request.file.name));break;case"diff":t.add(e.request.diff.lang??m(e.request.diff.name)),t.add(e.request.diff.lang??m(e.request.diff.prevName??"-"));break}return t.delete("text"),Array.from(t)}function c(e){return e?.type==="file"||e?.type==="diff"}function d(e){return e.instances}let f;function Le({poolOptions:e,highlighterOptions:t}){return f??=new G(e,t),f}function De(){f!=null&&(f.terminate(),f=void 0)}export{G as WorkerPoolManager,Le as getOrCreateWorkerPoolSingleton,De as terminateWorkerPoolSingleton};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/renderElectronMiniChatApp-DSa3gYqR.js","assets/vendor-boot-DyL2td56.js","assets/vendor-react-DASdDPIk.js","assets/vendor-clsx-B-dksMZM.js","assets/index-6IO1AcJI.js","assets/vendor-zustand-CUi8eEds.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/index-BAmzAlNx.css","assets/pi-session-focus-preference-LDVCJ_YR.js","assets/useAppFontEffects-CG3_yteE.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/runtimeSurface-DW_Ia4q3.js","assets/vendor-katex-css-Cp579UoJ.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{_ as o}from"./vendor-vite-runtime-DD1OZmLC.js";import{c as t}from"./index-6IO1AcJI.js";/* empty css */import"./vendor-zustand-CUi8eEds.js";import"./vendor-react-DASdDPIk.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-tailwind-merge-CPcsbTWB.js";import"./vendor-fuse.js-Dw8P0qyA.js";window.__PICHAMBER_RUNTIME_APIS__=t();o(async()=>{const{renderElectronMiniChatApp:r}=await import("./renderElectronMiniChatApp-DSa3gYqR.js");return{renderElectronMiniChatApp:r}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13])).then(({renderElectronMiniChatApp:r})=>{r()});
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/renderMobileApp-CPE-3uMl.js","assets/vendor-boot-DyL2td56.js","assets/vendor-react-DASdDPIk.js","assets/vendor-clsx-B-dksMZM.js","assets/index-6IO1AcJI.js","assets/vendor-zustand-CUi8eEds.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/index-BAmzAlNx.css","assets/pi-session-focus-preference-LDVCJ_YR.js","assets/useAppFontEffects-CG3_yteE.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/runtimeSurface-DW_Ia4q3.js","assets/runtimeEndpointReset-CzJfovWI.js","assets/SessionUnreadDot-CELKNVIM.js","assets/permissionStore-B9Hkrqny.js","assets/runtimeEndpointReset-BV3KOtdA.css","assets/vendor-xterm-xterm-css-DDGTF8rc.css","assets/vendor-capacitor-core-B4EWRrHz.js","assets/vendor-aparajita-capacitor-secure-storage-5IShChL0.js","assets/SettingsView-CZvRRgJe.js","assets/vendor-qrcode-Dv4uniC1.js","assets/vendor-dijkstrajs-COg3n3zL.js","assets/collapsible-DhV9d4dT.js","assets/vendor-base-ui-DIkTOIJS.js","assets/useSwitcherItems-BmoCnS9W.js","assets/vendor-katex-css-Cp579UoJ.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{_ as t}from"./vendor-vite-runtime-DD1OZmLC.js";import{c as i}from"./index-6IO1AcJI.js";/* empty css */import"./vendor-zustand-CUi8eEds.js";import"./vendor-react-DASdDPIk.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-tailwind-merge-CPcsbTWB.js";import"./vendor-fuse.js-Dw8P0qyA.js";window.__PICHAMBER_RUNTIME_APIS__=i();t(async()=>{const{renderMobileApp:r}=await import("./renderMobileApp-CPE-3uMl.js").then(o=>o.r);return{renderMobileApp:r}},__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])).then(({renderMobileApp:r})=>{r()});
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/SessionSwitcherDropdown-cC9wVBH7.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-boot-DyL2td56.js","assets/vendor-react-DASdDPIk.js","assets/vendor-clsx-B-dksMZM.js","assets/useAppFontEffects-CG3_yteE.js","assets/index-6IO1AcJI.js","assets/vendor-zustand-CUi8eEds.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/index-BAmzAlNx.css","assets/runtimeSurface-DW_Ia4q3.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{j as e,aJ as ye}from"./vendor-boot-DyL2td56.js";import{R as c,a as me}from"./vendor-react-DASdDPIk.js";/* empty css */import{o as V,u as K,aD as ge,D as Z,t as ie,az as U,Q as we,U as ve,z as le,w as je,B as be}from"./index-6IO1AcJI.js";import{f as Se,u as Ie,a as Ce,s as Ne}from"./pi-session-focus-preference-LDVCJ_YR.js";import{bR as De,I as J,aY as Pe,a9 as Me,aa as ke,ac as Ee,bS as _e,bT as Le,f as j,b8 as Oe,a as ae,H as P,as as ce,bU as Te,p as Re,aD as Ae,bF as Be,bu as Fe,B as de,bJ as ze,bV as ue,bW as Ue,t as $e,g as We,R as He,E as Ge,T as Ve,U as Je,W as Ke,V as Ye,Y as Qe,Z as Xe,bX as Ze,bG as qe,a0 as et,a1 as tt,a2 as st,a3 as rt}from"./useAppFontEffects-CG3_yteE.js";import{_ as nt}from"./vendor-vite-runtime-DD1OZmLC.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-zustand-CUi8eEds.js";import"./vendor-tailwind-merge-CPcsbTWB.js";import"./vendor-fuse.js-Dw8P0qyA.js";import"./runtimeSurface-DW_Ia4q3.js";const ot=({mode:t,children:r})=>e.jsx(De.Provider,{value:t,children:r}),it=_e,at=Le,ct=({totalTokens:t,percentage:r,colorPercentage:n,contextLimit:a,outputLimit:o,size:u="default",isMobile:l=!1,hideIcon:D=!1,showPercentIcon:E=!1,className:p,valueClassName:f,percentIconClassName:_,onClick:M,pressed:O=!1,cacheRead:x,cacheWrite:C,cacheHitPercent:h})=>{const[b,i]=c.useState(!1),g=typeof n=="number"?n:r,m=it(r)??0,y=at(g),Y=y==="critical"?"var(--status-error)":y==="warn"?"var(--status-warning)":"var(--status-success)",w=I=>I>=1e6?`${(I/1e6).toFixed(1)}M`:I>=1e3?`${(I/1e3).toFixed(1)}K`:I.toFixed(1).replace(/\.0$/,""),N=I=>I>=90?"text-status-error":I>=75?"text-status-warning":"text-status-success",k=20,$=3,W=(k-$)/2,re=2*Math.PI*W,Q=re*(1-m/100),R=typeof o=="number"?Math.max(o,0):0,A=typeof x=="number"&&typeof C=="number",q=A?Math.max(0,x):0,B=A?Math.max(0,C):0,L=typeof h=="number"&&Number.isFinite(h),T=[`Used tokens: ${w(t)}`,`Context limit: ${w(a)}`,`Output limit: ${w(R)}`,...A?[`Cache read: ${w(q)}`,`Cache write: ${w(B)}`]:[],...L?[`Cache hit: ${h.toFixed(1)}%`]:[],`${Math.min(r,999).toFixed(1)}% used`],F=!l&&typeof M=="function",v=e.jsxs(e.Fragment,{children:[!l&&!D&&e.jsx(J,{name:"donut-chart",className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:V("font-medium inline-flex items-center gap-1.5",f),children:E?e.jsxs(e.Fragment,{children:[e.jsxs("svg",{viewBox:`0 0 ${k} ${k}`,className:V("h-3.5 w-3.5 -rotate-90",_),role:"progressbar","aria-valuenow":Math.round(m),"aria-valuemin":0,"aria-valuemax":100,children:[e.jsx("circle",{cx:k/2,cy:k/2,r:W,fill:"none",stroke:"var(--interactive-border)",strokeWidth:$}),e.jsx("circle",{cx:k/2,cy:k/2,r:W,fill:"none",stroke:Y,strokeWidth:$,strokeLinecap:"round",strokeDasharray:re,strokeDashoffset:Q,className:"transition-[stroke-dashoffset,stroke] duration-300"})]}),e.jsxs("span",{className:"text-foreground",children:[Math.min(r,999).toFixed(1),"%"]})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:N(g),children:Math.min(r,999).toFixed(1)}),"%"]})})]}),S=V("app-region-no-drag flex items-center gap-1.5 select-none",u==="compact"?"typography-micro":"typography-meta",F?V("rounded-md px-2 py-1.5 text-foreground transition-colors","hover:bg-interactive-hover","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"):"text-muted-foreground/60",p),H=F?e.jsx("button",{type:"button",className:S,"aria-label":"Context usage","aria-pressed":O,onClick:M,children:v}):e.jsx("div",{className:S,"aria-label":"Context usage",onClick:l?()=>i(!0):void 0,children:v});return l?e.jsxs(e.Fragment,{children:[H,e.jsx(Pe,{open:b,onClose:()=>i(!1),title:"Context Usage",children:e.jsx("div",{className:"flex flex-col gap-1.5",children:e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-3 py-2 space-y-1",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Used tokens"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:w(t)})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Context limit"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:w(a)})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Output limit"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:w(R)})]}),A?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Cache read"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:w(q)})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Cache write"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:w(B)})]})]}):null,L?e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Cache hit"}),e.jsxs("span",{className:"typography-meta text-foreground font-medium",children:[h.toFixed(1),"%"]})]}):null,e.jsxs("div",{className:"flex justify-between items-center pt-1 border-t border-border/40",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Usage"}),e.jsxs("span",{className:V("typography-meta font-semibold",N(g)),children:[Math.min(r,999).toFixed(1),"%"]})]})]})})})]}):e.jsxs(Me,{children:[e.jsx(ke,{asChild:!0,children:H}),e.jsx(Ee,{children:e.jsx("div",{className:"space-y-0.5",children:T.map(I=>e.jsx("p",{className:"typography-micro leading-tight",children:I},I))})})]})},lt=c.lazy(()=>nt(()=>import("./SessionSwitcherDropdown-cC9wVBH7.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])).then(t=>({default:t.SessionSwitcherDropdown}))),dt=t=>{const r=typeof t=="string"?t.trim():"";if(!r)return"";const n=typeof window<"u"?window.__PICHAMBER_HOME__:"";if(n&&r===n)return"~";if(n&&r.startsWith(`${n}/`))return`~/${r.slice(n.length+1)}`;const a=r.split("/").filter(Boolean);return a.length<=3?r:`.../${a.slice(-3).join("/")}`},se=t=>{const r=typeof t=="string"?t.trim():"";if(!r)return"";const n=r.replace(/\\/g,"/");return n==="/"?"/":n.replace(/\/+$/,"")},ut=({mode:t})=>{const r=j(s=>s.currentSessionId),n=j(s=>!!s.newSessionDraft?.open),a=j(s=>s.newSessionDraft?.selectedProjectId??null),o=K(s=>s.currentDirectory),u=ae(s=>s.projects),l=ae(s=>s.getActiveProject()),D=P(s=>s.getCurrentModel),E=P(s=>s.providers),p=ce(),f=Te(r??""),_=Re(),M=Ae(s=>s.ensureStatus),O=j(s=>s.newSessionDraft?.open?se(s.newSessionDraft.directoryOverride??""):""),[x,C]=c.useState(!1),h=typeof window<"u"?window.__PICHAMBER_MACOS_MAJOR__??0:0,b=Number.isFinite(h)&&h>0,i=Be(),g=b?h>=26?"h-12":h<=15?"h-14":"":"",m=c.useMemo(()=>r?p.find(s=>s.id===r)??null:null,[r,p]);c.useEffect(()=>{ge()&&Z("desktop_get_window_pinned").then(s=>{typeof s?.pinned=="boolean"&&C(s.pinned)})},[]);const y=m?.title?.trim()||(n||t==="draft"?"New session":"Session"),Y=se(m?.directory??null),w=se(o),N=Y||O||w,k=dt(N);c.useEffect(()=>{N&&M(N,_.git).catch(()=>{})},[M,N,_.git]);const $=c.useMemo(()=>{const s=N;return s?u.map(d=>({...d,normalizedPath:se(d.path)})).filter(d=>d.normalizedPath&&(d.normalizedPath===s||s.startsWith(`${d.normalizedPath}/`))).sort((d,G)=>G.path.length-d.path.length)[0]??null:null},[N,u]),W=c.useMemo(()=>{const s=$??l;if(!s)return k||"PiChamber";const d=s.label?.trim();return d||(s.path.split(/[\\/]/).filter(Boolean).at(-1)??s.path)},[l,k,$]),Q=Fe(N||null),R=Q&&Q!=="HEAD"?Q:null,A=D(),q=c.useMemo(()=>{for(let s=f.length-1;s>=0;s-=1){const d=f[s];if(d.role!=="assistant"||typeof d.providerID!="string"||typeof d.modelID!="string")continue;const te=E.find(X=>X.id===d.providerID)?.models.find(X=>X.id===d.modelID);if(te)return te}},[f,E]),B=A?.limit?A:q,L=B&&typeof B.limit=="object"&&B.limit!==null?B.limit:null,T=L&&typeof L.context=="number"?L.context:0,F=L&&typeof L.output=="number"?L.output:0,v=c.useMemo(()=>{if(!r||f.length===0)return null;let s,d;for(let ne=f.length-1;ne>=0;ne-=1){const oe=f[ne];if(oe.role!=="assistant")continue;const z=oe.tokens;if(!z)continue;if(z.input+z.output+z.reasoning+(z.cache?.read??0)+(z.cache?.write??0)>0){s=z,d=oe.id;break}}if(!s)return null;const G=s.input+s.output+s.reasoning+(s.cache?.read??0)+(s.cache?.write??0),te=T>0?T:2e5,X=T>0?Math.round(G/T*100):0,xe=F>0?Math.round(s.output/F*100):void 0;return{totalTokens:G,percentage:X,contextLimit:T||0,outputLimit:F||void 0,normalizedOutput:xe,thresholdLimit:te,lastMessageId:d}},[T,r,f,F]),[S,H]=c.useState(null),I={WebkitAppRegion:"drag"},ee={WebkitAppRegion:"no-drag"};c.useEffect(()=>{if(!r){H(s=>s===null?s:null);return}if(v&&v.totalTokens>0){H(s=>s&&s.totalTokens===v.totalTokens&&s.percentage===v.percentage&&s.contextLimit===v.contextLimit&&(s.outputLimit??0)===(v.outputLimit??0)&&(s.normalizedOutput??0)===(v.normalizedOutput??0)&&s.thresholdLimit===v.thresholdLimit&&s.lastMessageId===v.lastMessageId?s:v);return}H(s=>s===null?s:null)},[v,r]);const fe=S&&S.contextLimit>0?Math.min(999,S.totalTokens/S.contextLimit*100):0,pe=c.useCallback(()=>{const s=!x;C(s),Z("desktop_set_window_pinned",{pinned:s}).catch(()=>{C(!s)})},[x]),he=c.useCallback(()=>{const s=r?{sessionId:r,directory:m?.directory??o??""}:{mode:"draft",directory:N||o||"",projectId:a};Z("desktop_focus_main_window",s).then(d=>d?.focused===!0?Z("desktop_close_current_window"):null)},[o,r,a,N,m]);return e.jsxs("header",{className:V("flex items-center gap-3 bg-background pr-3",b?"pl-[5.5rem]":"pl-3",i?"h-12":g||"min-h-14"),style:I,children:[e.jsx(me.Suspense,{fallback:e.jsxs("button",{type:"button","aria-label":"Open session switcher",style:ee,className:"flex min-w-0 max-w-full flex-col items-start rounded-md px-1 py-0.5 text-left transition-colors hover:bg-interactive-hover/60 focus-visible:outline-none focus-visible:bg-interactive-hover/60",children:[e.jsx("span",{className:"truncate typography-ui-label text-[14px] font-normal leading-tight text-foreground max-w-full",children:y}),e.jsxs("span",{className:"flex min-w-0 max-w-full items-center gap-1.5 truncate typography-micro text-[10.5px] font-normal leading-tight text-muted-foreground/75",children:[e.jsx("span",{className:"truncate",children:W}),R?e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[e.jsx(J,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),e.jsx("span",{className:"truncate",children:R})]}):null]})]}),children:e.jsx(lt,{children:e.jsxs("button",{type:"button","aria-label":"Open session switcher",style:ee,className:"flex min-w-0 max-w-full flex-col items-start rounded-md px-1 py-0.5 text-left transition-colors hover:bg-interactive-hover/60 focus-visible:outline-none focus-visible:bg-interactive-hover/60",children:[e.jsx("span",{className:"truncate typography-ui-label text-[14px] font-normal leading-tight text-foreground max-w-full",children:y}),e.jsxs("span",{className:"flex min-w-0 max-w-full items-center gap-1.5 truncate typography-micro text-[10.5px] font-normal leading-tight text-muted-foreground/75",children:[e.jsx("span",{className:"truncate",children:W}),R?e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[e.jsx(J,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),e.jsx("span",{className:"truncate",children:R})]}):null]})]})})}),e.jsx("div",{className:"min-w-0 flex-1"}),S&&S.totalTokens>0?e.jsx(ct,{totalTokens:S.totalTokens,percentage:fe,colorPercentage:S.percentage,contextLimit:S.contextLimit,outputLimit:S.outputLimit??0,className:"h-9 shrink-0 pl-1 pr-1 typography-ui-label",valueClassName:"font-semibold leading-none",hideIcon:!0,showPercentIcon:!0,percentIconClassName:"h-4.5 w-4.5"}):null,e.jsx(de,{type:"button",variant:"ghost",size:"icon",onClick:pe,"aria-label":x?"Unpin Mini Chat window":"Pin Mini Chat window",title:x?"Unpin window":"Pin above other windows",style:ee,children:x?e.jsx(J,{name:"pushpin-2-fill",className:"h-4 w-4"}):e.jsx(J,{name:"pushpin-2",className:"h-4 w-4"})}),e.jsx(de,{type:"button",variant:"ghost",size:"icon",onClick:he,"aria-label":"Open session in main window",title:"Open in main window",style:ee,children:e.jsx(J,{name:"external-link",className:"h-4 w-4"})}),e.jsx(ze,{visible:i})]})},mt=({mode:t,autoOpenDraft:r=!1,unavailable:n=!1})=>{const a=j(o=>o.currentSessionId);return e.jsxs("div",{className:"flex h-full min-h-0 flex-col bg-background text-foreground",children:[e.jsx(ut,{mode:t}),e.jsx("main",{className:"min-h-0 flex-1",children:n?e.jsx("div",{className:"flex h-full items-center justify-center px-6 text-center typography-ui-label text-muted-foreground",children:e.jsxs("div",{className:"max-w-sm rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-4 py-3",children:[e.jsx("div",{className:"font-medium text-foreground",children:"Session unavailable"}),e.jsx("div",{className:"mt-1 typography-small text-muted-foreground",children:"This session could not be loaded. It may have been deleted, archived, or opened from a different project context."})]})}):e.jsx(ot,{mode:"mini-chat",children:e.jsx(Oe,{autoOpenDraft:r},a??"no-session")})})]})},ft=()=>{const t=ie(o=>o.shortcutOverrides),r=K(o=>o.currentDirectory),n=ae(o=>o.getActiveProject()),a=j(o=>o.openNewSessionDraft);c.useEffect(()=>{const o=l=>ve(l,t),u=l=>{if(U(l,o("focus_input"))){l.preventDefault(),ue();return}if(we()&&U(l,o("new_mini_chat"))){l.preventDefault(),Z("desktop_open_draft_mini_chat_window",{directory:r||n?.path||"",projectId:n?.id??null})?.catch(p=>{console.warn("[mini-chat-shortcuts] failed to open draft mini chat window",p)});return}if(U(l,o("new_chat"))){l.preventDefault(),a({selectedProjectId:n?.id??null,directoryOverride:r||n?.path||null,preserveDirectoryOverride:!!(r||n?.path)}),ue();return}if(U(l,o("open_model_selector"))){l.preventDefault();const{isModelSelectorOpen:p,setModelSelectorOpen:f}=ie.getState();f(!p);return}if(U(l,o("cycle_thinking_variant"))){if(P.getState().getCurrentModelVariants().length===0)return;l.preventDefault(),Ue(1).catch(()=>{$e.error("Couldn't update thinking")});return}const D=U(l,o("cycle_favorite_model_forward")),E=U(l,o("cycle_favorite_model_backward"));if(D||E){const{favoriteModels:p,addRecentModel:f}=ie.getState();if(p.length===0)return;l.preventDefault();const{currentProviderId:_,currentModelId:M,setProvider:O,setModel:x}=P.getState(),C=p.findIndex(i=>i.providerID===_&&i.modelID===M),b=p[(C+(D?1:-1)+p.length)%p.length];O(b.providerID),x(b.modelID),f(b.providerID,b.modelID)}};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[n?.id,n?.path,r,a,t])},pt="pichamber:mini-chat-presence",ht=()=>{const t=typeof window<"u"?new URLSearchParams(window.location.search):new URLSearchParams,r=t.get("mode")==="session"?"session":"draft",n=t.get("sessionId")?.trim()||null,a=t.get("directory")?.trim()||null,o=t.get("projectId")?.trim()||null;return{mode:r,sessionId:n,directory:a,projectId:o}},xt=({config:t})=>{const r=ce(),n=K(i=>i.currentDirectory),a=K(i=>i.setDirectory),o=j(i=>i.currentSessionId),u=j(i=>!!i.newSessionDraft?.open),l=j(i=>i.newSessionDraft?.open?i.newSessionDraft.bootstrapPendingDirectory??i.newSessionDraft.directoryOverride??"":""),D=j(i=>i.setCurrentSession),E=j(i=>i.openNewSessionDraft),p=P(i=>i.initializeApp),f=P(i=>i.isInitialized),_=P(i=>i.isConnected),M=P(i=>i.loadProviders),O=P(i=>i.providers.length),x=qe();c.useEffect(()=>{p()},[p]),c.useEffect(()=>{if(f)return;let i=!0,g=0;const m=window.setInterval(()=>{if(i){if(g+=1,g>10){window.clearInterval(m);return}P.getState().isInitialized||P.getState().initializeApp()}},1e3);return()=>{i=!1,window.clearInterval(m)}},[f]);const C=c.useRef(!1);c.useEffect(()=>{if(!C.current&&t.mode==="session"&&t.directory){if(n===t.directory){C.current=!0;return}a(t.directory,{showOverlay:!1}),C.current=!0}},[t.directory,t.mode,n,a]),c.useEffect(()=>{t.mode!=="draft"||!u||o||!l||n===l||a(l,{showOverlay:!1})},[t.mode,n,o,l,u,a]),c.useEffect(()=>{_&&O===0&&M({source:"electronMiniChat:recovery"})},[_,M,O]);const h=c.useRef(!1);c.useEffect(()=>{if(h.current||t.mode!=="session"||!t.sessionId)return;if(o===t.sessionId){h.current=!0;return}if(o){h.current=!0;return}const i=r.find(m=>m.id===t.sessionId);if(!i){x.ensureSessionRenderable(t.sessionId);return}const g=i.directory??t.directory;D(t.sessionId,g),h.current=!0},[t,o,r,D,x]),c.useEffect(()=>{const i=g=>{const m=g.detail,y=typeof m?.sessionId=="string"?m.sessionId.trim():"";if(!y||j.getState().currentSessionId===y)return;const Y=typeof m?.directory=="string"&&m.directory.trim().length>0?m.directory.trim():r.find(w=>w.id===y)?.directory??null;x.ensureSessionRenderable(y),D(y,Y),h.current=!0};return window.addEventListener("pichamber:open-session",i),()=>window.removeEventListener("pichamber:open-session",i)},[r,D,x]),c.useEffect(()=>{t.mode!=="draft"||u||o||E({selectedProjectId:t.projectId,directoryOverride:t.directory,preserveDirectoryOverride:!!t.directory})},[t,o,u,E]);const b=c.useRef(!1);return c.useEffect(()=>{if(b.current||!f)return;const i=()=>{if(b.current)return;b.current=!0;const y=typeof document<"u"?document.getElementById("initial-loading"):null;y&&(y.classList.add("fade-out"),window.setTimeout(()=>y.remove(),300))},g=t.mode==="session"?o===t.sessionId:u,m=window.setTimeout(i,g?100:1500);return()=>window.clearTimeout(m)},[f,t.mode,t.sessionId,o,u]),null},yt=()=>{const t=j(n=>n.currentSessionId),r=K(n=>n.currentDirectory);return c.useEffect(()=>{if(!t||!r||typeof BroadcastChannel>"u")return;const n=new BroadcastChannel(pt),a=l=>{n.postMessage({type:"mini-chat-session-presence",sessionId:t,directory:r,viewed:l})};a(!0);const o=window.setInterval(()=>a(!0),5e3),u=()=>a(!1);return window.addEventListener("beforeunload",u),()=>{window.clearInterval(o),window.removeEventListener("beforeunload",u),a(!1),n.close()}},[r,t]),null},gt=t=>{const r=ce(),n=j(u=>u.currentSessionId),[a,o]=c.useState(!1);return c.useEffect(()=>{if(t.mode!=="session"||!t.sessionId||n===t.sessionId){o(!1);return}if(r.some(l=>l.id===t.sessionId)){o(!1);return}const u=window.setTimeout(()=>o(!0),5e3);return()=>window.clearTimeout(u)},[t.mode,t.sessionId,n,r]),a};function wt({apis:t}){const r=c.useMemo(()=>ht(),[]),n=K(a=>a.currentDirectory);return c.useEffect(()=>{const a=n||r.directory;if(!a)return;const o=r.mode==="session"?{sessionId:r.sessionId,directory:r.directory}:null;We().focusProject(a,Se(a,o))},[r.directory,r.mode,r.sessionId,n]),c.useEffect(()=>(le(t),()=>le(null)),[t]),He(),ft(),Ie({enabled:!0}),e.jsx(Ge,{children:e.jsx(Ve,{directory:n||r.directory,children:e.jsxs(Je,{apis:t,children:[e.jsx(Ke,{}),e.jsx(Ye,{delayDuration:300,skipDelayDuration:150,children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(vt,{config:r}),e.jsx(Qe,{}),e.jsx(Xe,{})]})})]})})})}const vt=({config:t})=>{const r=gt(t);return e.jsxs(e.Fragment,{children:[e.jsx(xt,{config:t}),e.jsx(yt,{}),e.jsx(Ze,{embeddedBackgroundWorkEnabled:!0}),e.jsx(mt,{mode:t.mode,autoOpenDraft:t.mode==="draft",unavailable:r})]})},jt=()=>{(async()=>{try{await Promise.all([be(),Ce()])}catch(t){console.error("[mini-chat-main] settings init failed:",t)}st(),rt(),Ne()})()};function Tt(t){const r=t??je();if(!r)throw new Error("Runtime APIs not registered");jt();const n=document.getElementById("root");if(!n)throw new Error("Root element not found");ye.createRoot(n).render(e.jsx(me.StrictMode,{children:e.jsx(et,{children:e.jsx(tt,{children:e.jsx(wt,{apis:r})})})}))}export{Tt as renderElectronMiniChatApp};
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/FilesView-qP1ypN9J.js","assets/vendor-boot-DyL2td56.js","assets/vendor-react-DASdDPIk.js","assets/vendor-clsx-B-dksMZM.js","assets/index-6IO1AcJI.js","assets/vendor-zustand-CUi8eEds.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/index-BAmzAlNx.css","assets/useAppFontEffects-CG3_yteE.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/runtimeSurface-DW_Ia4q3.js","assets/vendor-codemirror-lang-javascript-DpTUrvx8.js","assets/vendor-lezer-javascript-oje4tdp_.js","assets/vendor-lezer-lr-BU2qmu_5.js","assets/vendor-codemirror-autocomplete-DsFn4GLp.js","assets/vendor-codemirror-lang-json-CLGxdOCz.js","assets/vendor-lezer-json-BRXb_bDX.js","assets/vendor-codemirror-lang-css-Dwf2XpnZ.js","assets/vendor-lezer-css-DNU_fzPI.js","assets/vendor-codemirror-lang-html-DcKqyeGk.js","assets/vendor-lezer-html-DDGRhRUz.js","assets/vendor-codemirror-lang-markdown-DmFP9s6x.js","assets/vendor-lezer-markdown-CicYv7V9.js","assets/vendor-codemirror-language-data-DglcKYWT.js","assets/vendor-codemirror-lang-python-yuxIkjit.js","assets/vendor-lezer-python-Cuvm9X9Y.js","assets/shell-CjFT_Tl9.js","assets/appThemeRegistry-gegrE2dq.js","assets/registerCustomTheme-DmolaWWZ.js","assets/themeResolver-yJ9XpNMI.js","assets/vendor-pierre-theming-Dgp7B_O4.js","assets/vendor-shikijs-core-CGM_jqPK.js","assets/vendor-shikijs-types-CPSbSeK6.js","assets/vendor-shikijs-vscode-textmate-BgLrS_2D.js","assets/vendor-hast-util-to-html-BKBhbTDb.js","assets/vendor-html-void-elements-CkdplsNl.js","assets/vendor-property-information-rJCbAzvX.js","assets/vendor-zwitch-C2o2j-tx.js","assets/vendor-stringify-entities-CsH1VEn9.js","assets/vendor-character-entities-legacy-BpoLgcEt.js","assets/vendor-character-entities-html4-D7taRCQ7.js","assets/vendor-ccount-c2V3InAJ.js","assets/vendor-comma-separated-tokens-D8TqSuIK.js","assets/vendor-space-separated-tokens-DD3iYX1K.js","assets/vendor-hast-util-whitespace-D4Wp6AEg.js","assets/FileSaveConflictDialog-u5L4k_5k.js","assets/vendor-react-drawio-Duu5LgQA.js","assets/runtimeEndpointReset-CzJfovWI.js","assets/SessionUnreadDot-CELKNVIM.js","assets/permissionStore-B9Hkrqny.js","assets/runtimeEndpointReset-BV3KOtdA.css","assets/vendor-xterm-xterm-css-DDGTF8rc.css","assets/useFilesViewSearch-C_LzYIgD.js","assets/JsonTreeView-DSuC4naV.js","assets/web-components-CH3-XV-n.js","assets/computeVirtualFileMetrics-CeMpF2xC.js","assets/vendor-shiki-Bbf2GEcE.js","assets/vendor-shikijs-engine-oniguruma-DPWuIF1G.js","assets/vendor-shikijs-engine-javascript-Cme4830A.js","assets/vendor-oniguruma-to-es-DLBnFDCE.js","assets/vendor-oniguruma-parser-C0D4_9rT.js","assets/vendor-regex-BBWcyTkg.js","assets/vendor-regex-utilities-2BQyy0xI.js","assets/vendor-regex-recursion-JU4mF-dD.js","assets/vendor-shikijs-transformers-CZWsLLKm.js","assets/Virtualizer-wpC51ZBQ.js","assets/renderFileWithHighlighter-TpKRyfCY.js","assets/vendor-codemirror-search-DaE6R5gH.js","assets/vendor-replit-codemirror-vim-CZy3BUVv.js","assets/GitView-y2k2i4gR.js","assets/gitStatusPredicates-DEBSqUNE.js","assets/GitHubDetailScaffold-zCKCy5OJ.js","assets/vendor-dompurify-r8glNMJW.js","assets/collapsible-DhV9d4dT.js","assets/vendor-base-ui-DIkTOIJS.js","assets/PierreDiffViewer-DQKujzLb.js","assets/VirtualizedFileDiff-D6KbvKc6.js","assets/renderDiffWithHighlighter-CDsgOnkH.js","assets/vendor-diff-C3JhlQdm.js","assets/PullRequestsSurface-Cfb1wSvC.js","assets/useGitHubRemoteSearch-DsxWOzKZ.js","assets/GitHubListPrimitives-Ck3zllel.js","assets/IssuesSurface-HWgR87N3.js","assets/githubLink-DT7i2NlH.js","assets/vendor-capacitor-app-BrDJj9I_.js","assets/vendor-capacitor-core-B4EWRrHz.js","assets/vendor-capacitor-push-notifications-KNe1zSBF.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{j as n,aH as Ke,aI as bt,aJ as ds}from"./vendor-boot-DyL2td56.js";import{a as Ct,R as a}from"./vendor-react-DASdDPIk.js";/* empty css */import{a as fe,b as Rn,d as Xt,e as it,i as ee,f as Ye,h as ae,s as Ne,j as fs,k as Qe,r as ps,l as Tn,m as Nn,p as hs,n as ms,o as K,u as In,q as ys,t as Ie,v as bs,w as Et,x as gs,y as xs,z as qt,A as vs,B as Pn,C as ws}from"./index-6IO1AcJI.js";import{f as ks,u as Ss,a as js,s as Cs}from"./pi-session-focus-preference-LDVCJ_YR.js";import{u as Es,M as Rs,a as Ts,i as Ns,D as Jt,b as Yt,c as Qt,g as Is,d as Zt,e as Ps,s as As,S as _s,f as Ds,T as Ms,h as en,j as tn,k as Ls,r as Os,l as zs,m as Us,n as Bs,H as $s,A as Ks,C as Ws,o as Hs,p as Fs,q as Vs,F as Gs,t as Xs,v as qs,W as Js,w as Ys}from"./runtimeEndpointReset-CzJfovWI.js";import{g as Ge,l as Qs,u as Zs,a as An,b as er,c as tr,r as _n,d as nr,e as Be,t as gt,o as sr,I as F,B as le,P as Se,f as me,h as rr,i as ar,j as ir,k as or,E as de,C as st,m as Dn,n as lr,p as cr,q as nn,s as ur,v as dr,w as fr,x as pr,y as hr,z as mr,A as yr,D as br,F as gr,G as xr,H as ke,J as vr,K as ve,L as wr,M as kr,N as Sr,O as jr,Q as Cr,R as Er,S as Rr,T as Tr,U as Nr,W as Ir,V as Pr,X as Ar,Y as _r,Z as Dr,_ as Mr,$ as Lr,a0 as Or,a1 as zr,a2 as Ur,a3 as Br}from"./useAppFontEffects-CG3_yteE.js";import{Capacitor as $r}from"./vendor-capacitor-core-B4EWRrHz.js";import{p as Kr}from"./vendor-aparajita-capacitor-secure-storage-5IShChL0.js";import{_ as Ce}from"./vendor-vite-runtime-DD1OZmLC.js";import{S as Wr,A as Hr}from"./SettingsView-CZvRRgJe.js";import{f as Fr,S as Vr,a as Gr,g as Mn}from"./SessionUnreadDot-CELKNVIM.js";import{u as Xr}from"./useSwitcherItems-BmoCnS9W.js";let Ln=null,sn=!1;const qr=new Promise(e=>{Ln=e});function Jr(){sn||(sn=!0,Ln?.())}const Yr=6,Qr=e=>e.parentID??null,rn=e=>{const t=e.replace(/\/+$/,"");return t.slice(t.lastIndexOf("/")+1)||t},Zr=e=>e.replace(/\\/g,"/").replace(/\/+$/,""),ea=(e,t)=>{if(!e)return"";let r=null,s=-1;for(const o of t){const i=Zr(o.path);(e===i||e.startsWith(`${i}/`))&&i.length>s&&(r=o,s=i.length)}return r?r.label?.trim()||rn(r.path):rn(e)},ta=()=>{const e=Ge().getState().catalog,t=[];for(const d of e.byId.values())d.archived||t.push(Qs(d));const r=Zs.getState().index.session.unseenCount,s=An.getState().projects,o=er.getState().ids,i=tr.getState().rankById;let l=0;const c=[];for(const d of t){const p=Qr(d)!==null,S=(r[d.id]??0)>0;S&&(l+=1),p||c.push({session:d,unread:S,project:ea(_n(d),s)})}c.sort(nr(o,i,d=>d.session));const u=c.slice(0,Yr).map(({session:d,unread:p,project:m})=>({id:d.id,title:d.title??"",unread:p,project:m}));return{runtimeKey:fe(),attentionCount:l,recentSessions:u}},na="__PICHAMBER_WIDGET_SNAPSHOT__",sa=()=>{typeof window>"u"||(window[na]=()=>{try{return JSON.stringify(ta())}catch{return null}})},xt="mobile-app-update-available",an="mobile-app-update-toast-dismissed-version",ra=()=>{const e=Be(i=>i.available),t=Be(i=>i.runtimeType),r=Be(i=>i.info?.version),s=Be(i=>i.info?.downloadUrl),o=Ct.useRef(new Set);return Ct.useEffect(()=>{if(Rn()!=="android"||t!=="mobile"||!e||!r||!s){gt.dismiss(xt);return}Xt().getItem(an)!==r&&(o.current.has(r)||(o.current.add(r),gt.info("PiChamber update available",{id:xt,description:`Version ${r} is ready for Android.`,duration:1/0,icon:n.jsx(F,{name:"download",className:"h-4 w-4 text-muted-foreground"}),action:{label:"Download",onClick:()=>{sr(s)}},cancel:{label:"Dismiss",onClick:()=>{Xt().setItem(an,r),gt.dismiss(xt)}}})))},[e,s,t,r]),null},aa=e=>{const{persisted:t,persistedDirectory:r,stale:s,ready:o,catalog:i,runtimeKey:l,capturedRuntimeKey:c,storeIdentityMatches:u,generationMatches:d}=e;if(!t||!r)return{action:"wait"};if(s||l!==c||!u||!d)return{action:"wait"};if(!o||!i)return{action:"wait"};const p=i.byId.get(t.sessionId);return!p||p.archived?{action:"clear"}:{action:"select",sessionId:p.id,directory:p.directory??r}},ot="pichamber.mobile.connections.v1",ia="pichamber.mobile.",on="pichamber.mobile.deviceId",On=12,oa=8e3,la=2500,ca=3e3,lt=2500,We=15e3,ua=1500,da=5e3,fa=()=>{try{const e=window.localStorage.getItem(on);if(e&&e.trim())return e.trim();const t=it();return window.localStorage.setItem(on,t),t}catch{return it()}},ln=()=>`mobile:${fa()}`,cn=()=>{try{const e=$r.getPlatform();return e==="ios"||e==="android"?e:void 0}catch{return}},zn=()=>{let e=0;return{begin:()=>(e+=1,e),cancel:()=>{e+=1},isCurrent:t=>t===e}},Oe=e=>{const t=e.trim();if(!t)return"";const r=/^https?:\/\//i.test(t)?t:`http://${t}`,s=new URL(r);return s.hash="",s.search="",s.pathname=s.pathname.replace(/\/+$/,""),s.toString().replace(/\/+$/,"")},Je=e=>{try{return new URL(e).host}catch{return e}},He=e=>{try{return Oe(e)}catch{return e.trim().replace(/\/+$/g,"")}},Pt=(e,t)=>He(e)===He(t),At=e=>`relay:${e.serverId}@${e.relayUrl.trim()}`,pa=e=>`relay://${e.serverId}`,ft=e=>e.candidates.filter(t=>t.kind==="direct"),Me=e=>{const t=e.candidates.find(r=>r.kind==="relay");return t&&t.kind==="relay"?t.relay:null},xe=e=>{const t=ft(e)[0];if(t)return t.url;const r=Me(e);return r?pa(r):""},q=e=>{const t=Me(e);if(t)return At(t);const r=ft(e)[0];return r?He(r.url):""},ct=(e,t)=>{const r=e.find(i=>i.kind==="relay"),s=r&&r.kind==="relay"?r.relay.serverId:null,o=new Set(e.filter(i=>i.kind==="direct").map(i=>He(i.url)));return t.some(i=>i.kind==="relay"?s!==null&&i.relay.serverId===s:o.has(He(i.url)))},_t=e=>{const t=(()=>{try{return Oe(e)}catch{return""}})();return t?[{kind:"direct",url:t}]:[]},un=e=>{if(e.candidates&&e.candidates.length>0)return e.candidates;const t=[];return typeof e.url=="string"&&e.url.trim()&&!/^relay:\/\//i.test(e.url.trim())&&t.push(..._t(e.url)),e.relay&&t.push({kind:"relay",relay:e.relay}),t},Dt=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;if(typeof t.relayUrl!="string"||!t.relayUrl.trim()||typeof t.serverId!="string"||!t.serverId.trim())return null;const r=t.hostEncPubJwk;if(!r||typeof r!="object"||Array.isArray(r))return null;const s=r;return s.kty!=="EC"||s.crv!=="P-256"||typeof s.x!="string"||!s.x||typeof s.y!="string"||!s.y?null:{relayUrl:t.relayUrl,serverId:t.serverId,hostEncPubJwk:{kty:"EC",crv:"P-256",x:s.x,y:s.y}}},ha=e=>{if(!e||typeof e!="object")return null;const t=e;if(t.kind==="direct")return typeof t.url=="string"&&t.url.trim()?{kind:"direct",url:t.url}:null;if(t.kind==="relay"){const r=Dt(t.relay);return r?{kind:"relay",relay:r}:null}return null},ma=e=>{if(e.mode==="relay"){const t=Dt(e.relay);return t?[{kind:"relay",relay:t}]:[]}return typeof e.url=="string"?_t(e.url):[]},Ze=e=>e.kind==="relay"?{kind:"relay",relay:{relayUrl:e.relay.relayUrl,serverId:e.relay.serverId,hostEncPubJwk:e.relay.hostEncPubJwk}}:{kind:"direct",url:e.url},ze=()=>{if(typeof window>"u")return[];let e;try{e=JSON.parse(window.localStorage.getItem(ot)||"[]")}catch{return[]}if(!Array.isArray(e))return[];const t=ee();return e.flatMap(r=>{if(!r||typeof r!="object")return[];const s=r;if(typeof s.id!="string")return[];const o=Array.isArray(s.candidates)?s.candidates.map(ha).filter(u=>!!u):ma(s);if(o.length===0)return[];const i=typeof s.clientToken=="string"&&s.clientToken.trim()?s.clientToken:void 0,l=typeof s.label=="string"&&s.label.trim()?s.label:Je(xe({candidates:o})),c={id:s.id,label:l,candidates:o,lastUsedAt:typeof s.lastUsedAt=="number"?s.lastUsedAt:0};return t?[{...c,hasToken:!!s.hasToken||!!i}]:[{...c,clientToken:i,hasToken:!!i}]}).sort((r,s)=>s.lastUsedAt-r.lastUsedAt)},Mt=e=>{if(typeof window>"u")return;const t=ee(),r=e.slice(0,On).map(s=>{const o={id:s.id,label:s.label,candidates:s.candidates.map(Ze),lastUsedAt:s.lastUsedAt};return t?{...o,hasToken:!!(s.hasToken||s.clientToken)}:{...o,clientToken:s.clientToken}});try{window.localStorage.setItem(ot,JSON.stringify(r))}catch(s){console.warn("[mobile-storage] failed to persist connection metadata",s)}},Un=(e,t)=>{const r=e.find(i=>t.id&&i.id===t.id||ct(i.candidates,t.candidates)),s=ee(),o={id:t.id||r?.id||it(),label:t.label,candidates:t.candidates,lastUsedAt:Date.now(),...s?{hasToken:t.hasToken??(!!t.clientToken||r?.hasToken||!1)}:{clientToken:t.clientToken??r?.clientToken,hasToken:!!(t.clientToken??r?.clientToken)}};return[o,...e.filter(i=>i.id!==o.id&&!ct(i.candidates,t.candidates))].slice(0,On)},Lt=Kr,ya=0,Ot=e=>`${ia}token.${encodeURIComponent(e)}`,ba=async(e,t)=>{let r;const s=new Promise(o=>{r=window.setTimeout(()=>o(t),ca)});try{return await Promise.race([e.catch(()=>t),s])}finally{r!==void 0&&window.clearTimeout(r)}},zt=async(e,t,r)=>ee()?ba(t().catch(s=>(console.warn(`[mobile-storage] ${e} failed`,s),r)),r):r,et=async e=>{const t=await zt("secure:read",async()=>(await Lt.internalGetItem({prefixedKey:Ot(e),sync:!1})).data,null);return typeof t=="string"&&t.trim()?t:void 0},Pe=async(e,t)=>zt("secure:write",async()=>(await Lt.internalSetItem({prefixedKey:Ot(e),data:t,sync:!1,access:ya}),!0),!1),ga=async e=>{await zt("secure:delete",async()=>(await Lt.internalRemoveItem({prefixedKey:Ot(e),sync:!1}),!0),!1)},Bn=async(e,t)=>{let r=0,s=0;return{records:await Promise.all(e.map(async i=>{if(!i||typeof i!="object")return i;const l=i,c=typeof l.url=="string"?l.url:null,u=typeof l.clientToken=="string"?l.clientToken.trim():"";if(!c||!u)return i;if(!await t(c,u))return s+=1,i;r+=1;const{clientToken:d,...p}=l;return{...p,hasToken:!0}})),migrated:r,failed:s}},$n=async()=>{if(typeof window>"u"||!ee())return;let e;try{e=JSON.parse(window.localStorage.getItem(ot)||"[]")}catch{return}if(!Array.isArray(e)||e.filter(s=>!!s&&typeof s=="object"&&typeof s.url=="string"&&typeof s.clientToken=="string"&&!!s.clientToken.trim()).length===0)return;const r=await Bn(e,async(s,o)=>{const i=He(s);return await Pe(i,o)?await et(i)===o:!1});if(r.migrated>0)try{window.localStorage.setItem(ot,JSON.stringify(r.records))}catch(s){console.warn("[mobile-storage] failed to finalize secure token migration",s)}},Kn=async()=>(await $n(),ze()),tt=async e=>{const t=Un(ze(),e);return Mt(t),ee()&&e.clientToken&&await Pe(q({candidates:e.candidates}),e.clientToken),t},Wn=async e=>{const t=ze(),r=t.find(o=>o.id===e)??null,s=t.filter(o=>o.id!==e);return Mt(s),r&&ee()&&await ga(q(r)),s},Ut=e=>{try{return JSON.stringify(e)}catch{return String(e)}},Q=(e,t={})=>{console.info("[mobile-connect]",e,Ut(t)),ps("connect",{code:e,status:typeof t.status=="number"?t.status:void 0,detail:typeof t.reason=="string"?t.reason:typeof t.result=="string"?t.result:void 0})},xa=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}},va=e=>{if(typeof e!="string")return e??void 0;try{return JSON.parse(e)}catch{return e}},wa=async(e,t)=>{if(!ee())return null;try{const{CapacitorHttp:r}=await Ce(async()=>{const{CapacitorHttp:i}=await import("./vendor-capacitor-core-B4EWRrHz.js");return{CapacitorHttp:i}},[]),s=Object.fromEntries(new Headers(t?.headers).entries()),o=await r.request({url:e,method:t?.method||"GET",headers:s,data:va(t?.body)});return{ok:o.status>=200&&o.status<300,status:o.status,source:"native-http",json:async()=>xa(o.data)}}catch(r){return console.warn("[mobile-connect]","native-http failed",Ut({url:e,error:r instanceof Error?r.message:String(r)})),null}},ka=async(e,t)=>{const r=await fetch(e,t).catch(s=>(console.warn("[mobile-connect]","browser-fetch failed",Ut({url:e,error:s instanceof Error?s.message:String(s)})),null));return r?{ok:r.ok,status:r.status,source:"browser-fetch",json:()=>r.json()}:null},Ee=async(e,t,r)=>{let s;const o=new Promise(i=>{s=window.setTimeout(()=>{r?.(),i(null)},e)});try{return await Promise.race([t,o])}catch{return null}finally{s!==void 0&&window.clearTimeout(s)}},Le=async(e,t,r)=>{const s=r?.totalTimeoutMs??oa,o=Date.now(),i=await Ee(Math.min(la,s),wa(e,t));if(i)return i;const l=new AbortController,c=Math.max(500,s-(Date.now()-o));return Ee(c,ka(e,{...t,signal:l.signal}),()=>l.abort())},pt=async e=>{if(!e)return null;const t=await e.json().catch(()=>null);if(!t||typeof t!="object")return null;const r=t;return{authenticated:typeof r.authenticated=="boolean"?r.authenticated:void 0,disabled:typeof r.disabled=="boolean"?r.disabled:void 0,scope:typeof r.scope=="string"?r.scope:void 0}},Sa=async(e,t,r,s=We,o)=>{if(o?.shouldAbort?.())return{outcome:"unreachable"};const i=Tn({relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk}),l=c=>c==="ok"&&o?.keepTunnel?{outcome:c,tunnel:i}:(i.close(),{outcome:c});try{const c=t?{Authorization:`Bearer ${t}`}:void 0,u=await Ee(s,i.fetch("/auth/session",{headers:c}).catch(()=>null));if(Q("relay:session",{ok:u?.ok===!0,status:u?.status??null,hasToken:!!t}),!u)return l("unreachable");if(u.status===401)return l(t?"auth-failed":"needs-login");if(!u.ok&&u.status!==404)return l("auth-failed");const d=await pt(u);return d&&d.disabled!==!0&&d.authenticated===!1?l(t?"auth-failed":"needs-login"):l("ok")}catch(c){throw i.close(),c}},ja=(e,t,r,s,o)=>{const i=typeof window<"u"?window.location.origin:"",l={relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk,...r?{grant:r}:{}};o&&fs(l,o),Ne({apiBaseUrl:i,clientToken:t,runtimeKey:s??At(e),relay:l})},ut=async(e,t,r)=>{const s=r?.shouldAbort,o=r?.fast?{totalTimeoutMs:lt}:void 0,i=Me({candidates:e})?.serverId??null,l=e.find(p=>p.kind==="relay")??null,c=e.filter(p=>p.kind==="direct"),u=async()=>{for(const p of c){if(s?.())return{status:"unreachable"};const m=Oe(p.url)||p.url,S=t?{Authorization:`Bearer ${t}`}:void 0,k=await Le(`${m}/health`,{method:"GET"},o);if(s?.())return{status:"unreachable"};if(!k?.ok)continue;if(i){const I=await k.json().catch(()=>null),P=I&&typeof I=="object"?I.serverId:null;if(typeof P=="string"&&P&&P!==i){Q("probe:server-id-mismatch",{url:m});continue}}const w=await Le(`${m}/auth/session`,{method:"GET",credentials:t?"omit":"include",headers:S},o);if(s?.())return{status:"unreachable"};if(w?.status===401)return{status:"needs-login"};if(!w||!w.ok&&w.status!==404)continue;const E=await pt(w);if(E&&E.disabled!==!0&&E.authenticated===!1)return{status:"needs-login"};const _=E?.disabled===!0;return!t&&ee()&&!_&&E?.scope!=="client"?{status:"needs-login"}:{status:"ok",transport:{kind:"direct",url:m}}}return{status:"unreachable"}},d=async()=>{if(!l)return{status:"unreachable"};if(s?.())return{status:"unreachable"};const{outcome:p,tunnel:m}=await Sa(l.relay,t,void 0,r?.fast?lt:void 0,{keepTunnel:!0,...s?{shouldAbort:s}:{}});return s?.()?(m?.close(),{status:"unreachable"}):p==="ok"?{status:"ok",transport:{kind:"relay",relay:l.relay,tunnel:m}}:p==="needs-login"||p==="auth-failed"?{status:"needs-login"}:{status:"unreachable"}};return l?c.length===0?d():new Promise(p=>{let m=!1,S=!1,k,w=null,E=null;const _=h=>{h?.status==="ok"&&h.transport.kind==="relay"&&h.transport.tunnel?.close()},I=h=>{m||(m=!0,p(h))},P=()=>{S||m||s?.()||(k!==void 0&&(window.clearTimeout(k),k=void 0),d().then(h=>{if(E=h,m||S){_(h);return}if(h.status==="ok"||h.status==="needs-login"){I(h);return}w&&I(w)}))};u().then(h=>{if(w=h,!m){if(h.status==="ok"||h.status==="needs-login"){S=!0,k!==void 0&&window.clearTimeout(k),_(E),I(h);return}if(E){I(E);return}P()}}),k=window.setTimeout(P,ua)}):u()},_e=(e,t,r)=>{e.kind==="relay"?ja(e.relay,t,r?.grant,r?.runtimeKey,e.tunnel):Ne({apiBaseUrl:e.url,clientToken:t,runtimeKey:r?.runtimeKey}),Xn()},Ae=()=>{const e=ze()[0];return e?.label?.trim()?e.label:null},at=async()=>{const e=Ye(),t=`${fe()}|${ae()}`,r=()=>Ye()!==e||`${fe()}|${ae()}`!==t;if(await $n(),r())return{status:"no-candidate"};const s=ze()[0];if(!s)return{status:"no-candidate"};let o;if(ee()){if(!s.hasToken)return{status:"no-candidate"};if(o=await et(q(s)),!o)return{status:"no-candidate"}}else if(o=s.clientToken,!o)return{status:"no-candidate"};const i=await ut(s.candidates,o,{fast:!0});return r()?(Tt(i),{status:"no-candidate"}):i.status==="needs-login"?{status:"needs-login",label:s.label}:i.status!=="ok"?{status:"unreachable",label:s.label}:(await tt({id:s.id,label:s.label,candidates:s.candidates}),r()?(dt(i.transport),{status:"no-candidate"}):(_e(i.transport,o,{runtimeKey:q(s)}),{status:"connected"}))},Hn=async(e,t)=>{let r="";try{r=Oe(e.url)}catch{return!1}if(!r)return!1;const s=e.clientToken?.trim()||void 0,o=s?{Authorization:`Bearer ${s}`}:void 0,i=t?.fast?{totalTimeoutMs:lt}:void 0;if(!(await Le(`${r}/health`,{method:"GET",headers:o},i))?.ok)return!1;const c=await Le(`${r}/auth/session`,{method:"GET",credentials:s?"omit":"include",headers:o},i);if(!c||!c.ok&&c.status!==404)return!1;const u=await pt(c);return!(u&&u.disabled!==!0&&u.authenticated===!1)},dn=async e=>{const t=Me({candidates:e})?.serverId??null;for(const r of e){if(r.kind==="relay"){const i=Tn(r.relay),l=await Ee(We,i.fetch("/health").catch(()=>null));if(Q("establish:relay:health",{ok:l?.ok===!0,status:l?.status??null}),l?.ok)return{kind:"relay",relay:r.relay,tunnel:i};i.close();continue}const s=Oe(r.url)||r.url,o=await Le(`${s}/health`,{method:"GET"});if(Q("establish:direct:health",{ok:o?.ok===!0,status:o?.status??null}),!!o?.ok){if(t){const i=await o.json().catch(()=>null),l=i&&typeof i=="object"?i.serverId:null;if(typeof l=="string"&&l&&l!==t){Q("establish:server-id-mismatch",{url:s});continue}}return{kind:"direct",url:s}}}return null},Ca=e=>[...e].sort((t,r)=>{const s=(t.priority??100)-(r.priority??100);if(s!==0)return s;const o=i=>i.type==="relay"?2:i.url.startsWith("https://")?0:1;return o(t)-o(r)}).flatMap(t=>{if(t.type==="relay"){const r=Dt({relayUrl:t.relayUrl,serverId:t.serverId,hostEncPubJwk:t.hostEncPubJwk});return r?[{kind:"relay",relay:r}]:[]}return _t(t.url)}),Fn=async(e,t)=>{if(!Qe())return Hn(e,t);const r=await Ee(t?.fast?lt:We,Nn("/auth/session").then(o=>o).catch(()=>null));if(!r)return!0;if(r.status===401)return!1;if(!r.ok&&r.status!==404)return!0;const s=await pt(r);return!(s&&s.disabled!==!0&&s.authenticated===!1)},Ea=e=>e.kind==="relay"?Qe():!Qe()&&Pt(e.url,ae()),ht=()=>{const e=fe();return e?ze().find(t=>q(t)===e)??null:null},Rt=e=>{const t=fe();return!!t&&q(e)===t},Bt=e=>({generation:Ye(),runtimeKey:fe(),apiBaseUrl:ae(),connectionId:e.id,secureKey:q(e),candidatesJson:JSON.stringify(e.candidates.map(Ze))}),Vn=e=>{if(Ye()!==e.generation||fe()!==e.runtimeKey||ae()!==e.apiBaseUrl)return!0;const t=ht();if(!t||t.id!==e.connectionId||q(t)!==e.secureKey)return!0;try{if(JSON.stringify(t.candidates.map(Ze))!==e.candidatesJson)return!0}catch{return!0}return!1},dt=e=>{try{e?.kind==="relay"&&e.tunnel?.close()}catch{}},Tt=e=>{e.status==="ok"&&dt(e.transport)},Ra=e=>e?`${e.generation}|${e.runtimeKey}|${e.apiBaseUrl}|${e.connectionId}|${e.secureKey}|${e.candidatesJson}`:`noselection|${Ye()}|${fe()}`;let De=null,Nt="";const fn=(e,t)=>{const r=t.finally(()=>{De===r&&(De=null,Nt="")});return De=r,Nt=e,r},$t=()=>{const e=ht(),t=e?Bt(e):null,r=Ra(t);if(De&&Nt===r)return De;if(De){const o=De.then(()=>vt(),()=>vt());return fn(r,o)}return fn(r,vt())},vt=async()=>{const e=ht();if(!e)return"no-connection";const t=Bt(e),r=()=>Vn(t);let s;if(ee()){if(s=e.hasToken?await et(q(e)):void 0,r())return"no-connection"}else s=e.clientToken;if(!s)return"unreachable";if(r())return"no-connection";const o=e.candidates.findIndex(d=>Ea(d.kind==="relay"?{kind:"relay",relay:d.relay}:{kind:"direct",url:d.url})),i=o>=0?e.candidates.slice(0,o):e.candidates,l=await ut(i,s,{fast:!0,shouldAbort:r});if(r())return Tt(l),"no-connection";if(l.status==="ok")return await tt({id:e.id,label:e.label,candidates:e.candidates}),r()?(dt(l.transport),"no-connection"):(_e(l.transport,s,{runtimeKey:q(e)}),"switched");if(l.status==="needs-login")return"needs-login";if(o>=0){if(r())return"no-connection";const d=await Fn({url:t.apiBaseUrl,clientToken:s},{fast:!0});if(r())return"no-connection";if(d)return Xn(),"unchanged"}const c=o>=0?e.candidates.slice(o+1):[];if(c.length===0)return"unreachable";const u=await ut(c,s,{fast:!0,shouldAbort:r});return r()?(Tt(u),"no-connection"):u.status==="ok"?(await tt({id:e.id,label:e.label,candidates:e.candidates}),r()?(dt(u.transport),"no-connection"):(_e(u.transport,s,{runtimeKey:q(e)}),"switched")):u.status==="needs-login"?"needs-login":"unreachable"};let wt=!1;const Gn=async()=>{if(wt)return"skipped";const e=ht();if(!e)return Q("candidates:refresh-skip",{reason:"no-active-connection"}),"skipped";const t=Me(e);if(!t)return Q("candidates:refresh-skip",{reason:"no-relay-candidate"}),"skipped";const r=Bt(e),s=()=>Vn(r);wt=!0;try{const o=await Ee(We,Nn("/api/client-auth/connection/candidates").then(m=>m).catch(()=>null));if(!o?.ok)return Q("candidates:refresh-skip",{reason:"fetch-failed",status:o?.status??null}),"skipped";if(s())return Q("candidates:refresh-skip",{reason:"selection-changed"}),"skipped";const i=await o.json().catch(()=>null);if(!i||i.serverId!==t.serverId)return Q("candidates:refresh-skip",{reason:"server-id-mismatch"}),"skipped";const l=Array.isArray(i.candidates)?i.candidates:[],c=[];for(const m of l){if(!m||typeof m!="object")continue;const S=m;if(!(S.type!=="lan"||typeof S.url!="string"))try{const k=Oe(S.url);k&&!c.includes(k)&&c.push(k)}catch{}}if(c.length===0)return Q("candidates:refresh-skip",{reason:"no-lan-reported"}),"skipped";const u=ft(e).filter(m=>m.url.startsWith("https://")),d=[...c.map(m=>({kind:"direct",url:m})),...u,{kind:"relay",relay:t}];return JSON.stringify(e.candidates.map(Ze))===JSON.stringify(d.map(Ze))?"unchanged":s()?(Q("candidates:refresh-skip",{reason:"selection-changed"}),"skipped"):(Q("candidates:refreshed",{lanCount:c.length}),await tt({id:e.id,label:e.label,candidates:d}),"updated")}finally{wt=!1}},Xn=()=>{typeof window>"u"||window.setTimeout(()=>{(async()=>{const e=await Gn().catch(()=>"skipped");Q("candidates:refresh-result",{result:e}),e==="updated"&&Qe()&&await $t().catch(()=>null)})()},da)},Kt=e=>{const[t,r]=a.useState(()=>ze()),[s,o]=a.useState(null),[i,l]=a.useState(null),[c,u]=a.useState(null),d=a.useRef(t),p=a.useRef(null),m=a.useRef(zn()),S=a.useCallback(x=>{d.current=x,r(x)},[]),k=a.useCallback(x=>{p.current=x,o(x)},[]),w=a.useCallback(x=>{p.current===x&&(p.current=null,o(null))},[]);a.useEffect(()=>{let x=!1;return Kn().then(j=>{x||S(j)}),()=>{x=!0}},[S]);const E=a.useCallback(x=>{const j=Un(d.current,x);return S(j),Mt(j),j},[S]),_=a.useCallback(async x=>{l(null),k("connect");try{const j=un(x);if(j.length===0){l("Enter a server URL.");return}const C=x.id?d.current.find(M=>M.id===x.id):d.current.find(M=>ct(M.candidates,j)),L=x.label?.trim()||C?.label||Je(xe({candidates:j})),z=x.relayGrant;let A=x.clientToken?.trim()||void 0;const f=!!A;A||(ee()?C?.hasToken&&(A=await et(q({candidates:j}))):A=C?.clientToken),Q("connect:start",{candidates:j.map(M=>M.kind),hasToken:!!A});const D=await ut(j,A);if(Q("connect:probe",{status:D.status}),D.status==="unreachable"){l("Could not reach that PiChamber server.");return}if(D.status==="needs-login"){E({id:C?.id,label:L,candidates:j}),u({id:C?.id??it(),label:L,candidates:j,relay:Me({candidates:j})??void 0,relayGrant:z});return}A&&f&&ee()&&await Pe(q({candidates:j}),A),E({id:C?.id,label:L,candidates:j,clientToken:A}),_e(D.transport,A??null,{runtimeKey:q({candidates:j}),grant:z}),e()}catch(j){console.warn("[mobile-connect] connect threw",j),l("That server URL is not valid.")}finally{w("connect")}},[k,w,e,E]),I=a.useCallback(async x=>{if(p.current==="pairing")return;l(null),k("pairing");const j=Ca(x.candidates);let C=null,L=!1;try{if(C=await dn(j),!C){l("Could not reach that PiChamber server.");return}const z=JSON.stringify({pairingId:x.pairingId,secret:x.secret,clientLabel:"PiChamber Mobile",clientKind:"mobile",deviceName:"PiChamber Mobile",devicePlatform:cn(),dedupeKey:ln()}),A={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:z},f=C.kind==="relay"?await Ee(We,C.tunnel.fetch("/api/client-auth/pairing/redeem",A).catch(()=>null)):await Le(`${C.url}/api/client-auth/pairing/redeem`,A);if(!f?.ok){l("This server needs a password or client token.");return}const D=await f.json().catch(()=>null),M=typeof D?.clientToken=="string"?D.clientToken.trim():"";if(!M){l("This server needs a password or client token.");return}const v=typeof D?.server?.label=="string"?D.server.label:"",N=x.label||v||Je(xe({candidates:j}));if(ee()&&!await Pe(q({candidates:j}),M)){l("This server needs a password or client token.");return}E({label:N,candidates:j,clientToken:M}),_e(C.kind==="relay"?{kind:"relay",relay:C.relay,tunnel:C.tunnel}:{kind:"direct",url:C.url},M,{runtimeKey:q({candidates:j})}),L=C.kind==="relay",e()}catch(z){console.warn("[mobile-connect] pairing threw",z),l("This server needs a password or client token.")}finally{!L&&C?.kind==="relay"&&C.tunnel.close(),w("pairing")}},[k,w,e,E]),P=a.useCallback(async x=>{if(!c||!x.trim()||p.current==="password")return;l(null),k("password");const j=m.current.begin(),C=()=>m.current.isCurrent(j),{id:L,label:z,candidates:A}=c;let f=null,D=!1;try{if(f=await dn(A),!C())return;if(!f){l("Could not reach that PiChamber server.");return}const M={method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:x,trustDevice:!0,issueClientToken:!0,clientLabel:"PiChamber Mobile",clientKind:"mobile",devicePlatform:cn(),dedupeKey:ln()})};Q("password:start",{transport:f.kind});const v=f.kind==="relay"?await Ee(We,f.tunnel.fetch("/auth/session",M).catch(()=>null)):await Le(`${f.url}/auth/session`,M);if(!C())return;if(Q("password:done",{ok:v?.ok===!0,status:v?.status??null}),!v?.ok){l("Could not unlock that server. Check the password.");return}const N=await v.json().catch(()=>null);if(!C())return;const J=typeof N?.clientToken=="string"?N.clientToken.trim():"";if(Q("password:token",{issued:!!J}),!J){if(f.kind==="direct"&&!ee()){E({id:L,label:z,candidates:A}),u(null),_e({kind:"direct",url:f.url},null,{runtimeKey:q({candidates:A})}),e();return}l("This server needs a password or client token.");return}if(ee()&&(!C()||(await Pe(q({candidates:A}),J),!C()))||!C()||(E({id:L,label:z,candidates:A,clientToken:J}),u(null),_e(f.kind==="relay"?{kind:"relay",relay:f.relay,tunnel:f.tunnel}:{kind:"direct",url:f.url},J,{runtimeKey:q({candidates:A})}),D=f.kind==="relay",!C()))return;e()}catch(M){if(!C())return;console.warn("[mobile-connect] password threw",M),l("Could not unlock that server. Check the password.")}finally{!D&&f?.kind==="relay"&&f.tunnel.close(),C()&&w("password")}},[k,w,e,c,E]),h=a.useCallback(()=>{m.current.cancel(),w("password"),u(null),l(null)},[w]),y=a.useCallback(async x=>{l(null);let j=un(x);const C=x.id?d.current.find(f=>f.id===x.id)??null:null;if(C){const f=j.filter(v=>v.kind==="direct"),D=ft(C).filter(v=>v.url.startsWith("https://")&&!f.some(N=>Pt(N.url,v.url))),M=Me(C);j=[...f,...D,...M?[{kind:"relay",relay:M}]:[]]}if(j.length===0)return l("Enter a server URL."),null;const L=x.clientToken?.trim()||void 0,z=x.label?.trim()||Je(xe({candidates:j}));if(ee()){const f=q({candidates:j});if(L)await Pe(f,L);else if(C?.hasToken){const D=q(C);if(D&&f&&D!==f){const M=await et(D);M&&await Pe(f,M)}}}return E({id:x.id,label:z,candidates:j,clientToken:L}).find(f=>ct(f.candidates,j))??null},[E]),U=a.useCallback(async x=>{const j=d.current.find(L=>L.id===x)??null,C=await Wn(x);return S(C),j},[S]);return{connections:t,isBusy:s!==null,isPasswordBusy:s==="password",error:i,pendingConnection:c,connect:_,redeemPairingConnection:I,submitPassword:P,cancelPassword:h,saveConnection:y,removeConnection:U,setError:l}},Ni=Object.freeze(Object.defineProperty({__proto__:null,autoConnectLastInstance:at,connectionDisplayUrl:xe,createMobilePasswordOperationTracker:zn,deleteMobileConnection:Wn,getAutoConnectTargetLabel:Ae,getConnectionLabel:Je,isActiveRuntimeConnection:Rt,isSameConnectionUrl:Pt,loadMobileConnections:Kn,migrateLegacyInlineTokenRecords:Bn,normalizeConnectionUrl:Oe,refreshActiveConnectionCandidates:Gn,relayConnectionRuntimeKey:At,reprobeActiveConnection:$t,upsertMobileConnection:tt,useMobileConnection:Kt,validateActiveRuntimeSession:Fn,validateMobileConnectionSession:Hn},Symbol.toStringTag,{value:"Module"})),qn=()=>{if(typeof window>"u")return null;const t=window.Capacitor?.Plugins?.BarcodeScanner;return t&&(typeof t.scan=="function"||typeof t.startScan=="function")?t:null},Ta=()=>window.Capacitor?.getPlatform?.()==="android",Jn=e=>{const t=e.trim();if(!t)return null;if(/^pichamber:\/\//i.test(t)){const r=hs(t);return r?{pairing:r}:null}return/^https?:\/\//i.test(t)?{url:t}:null},Yn=(e,t)=>{const r=Jn(e);if(!r&&t?.pairingStringFallback){const s=ms(e);if(s)return{status:"pairing",pairing:s}}return r?"pairing"in r?{status:"pairing",...r}:{status:"ok",...r}:{status:"invalid"}},Na=async(e,t)=>{if(!e.startScan||!e.stopScan||!e.addListener)return{status:"unsupported"};if(t?.aborted)return{status:"cancelled"};let r,s,o=!1,i=()=>{};const l=new Promise(d=>{i=d}),c=d=>{o||(o=!0,i(d))},u=()=>c({status:"cancelled"});t?.addEventListener("abort",u,{once:!0});try{return(await Promise.allSettled([Promise.resolve(e.addListener("barcodesScanned",({barcodes:p})=>{const m=p?.[0],S=(m?.rawValue??m?.displayValue??"").trim();S&&c(Yn(S,{pairingStringFallback:!0}))})).then(p=>{r=p}),Promise.resolve(e.addListener("scanError",()=>c({status:"failed"}))).then(p=>{s=p})])).some(({status:p})=>p==="rejected")?c({status:"failed"}):o||e.startScan({formats:["QR_CODE"]}).catch(()=>c({status:"failed"})),await l}finally{t?.removeEventListener("abort",u),await Promise.allSettled([Promise.resolve(r?.remove()),Promise.resolve(s?.remove()),e.stopScan()])}},It=()=>qn()!==null,Qn=async e=>{const t=qn();if(!t)return{status:"unsupported"};try{if(t.requestPermissions){const l=(await t.requestPermissions())?.camera;if(l&&l!=="granted"&&l!=="limited")return{status:"permission-denied"}}if(e?.signal?.aborted)return{status:"cancelled"};if(Ta())return Na(t,e?.signal);if(!t.scan)return{status:"unsupported"};const s=(await t.scan({formats:["QR_CODE"]}))?.barcodes?.[0],o=(s?.rawValue??s?.displayValue??"").trim();return o?Yn(o):{status:"cancelled"}}catch{return{status:"failed"}}},$e={autoComplete:"off",autoCorrect:"off",spellCheck:!1},Xe="h-12 w-full rounded-[16px] border border-border/70 bg-surface-elevated px-4 text-[16px] text-foreground outline-none transition-colors placeholder:text-muted-foreground focus:border-primary focus:ring-2 focus:ring-primary/20",Zn=({onCancel:e})=>{const t=a.useRef(null);return a.useLayoutEffect(()=>{const r={value:document.documentElement.style.getPropertyValue("background-color"),priority:document.documentElement.style.getPropertyPriority("background-color")},s={value:document.body.style.getPropertyValue("background-color"),priority:document.body.style.getPropertyPriority("background-color")};document.documentElement.style.setProperty("background-color","rgba(0, 0, 0, 0)","important"),document.body.style.setProperty("background-color","rgba(0, 0, 0, 0)","important");const o=new Map,i=c=>{!(c instanceof HTMLElement)||c===t.current||o.has(c)||(o.set(c,{opacity:c.style.opacity,pointerEvents:c.style.pointerEvents}),c.style.setProperty("opacity","0"),c.style.setProperty("pointer-events","none"))};Array.from(document.body.children).forEach(i);const l=new MutationObserver(c=>{c.forEach(u=>u.addedNodes.forEach(i))});return l.observe(document.body,{childList:!0}),()=>{l.disconnect(),o.forEach((c,u)=>{u.style.opacity=c.opacity,u.style.pointerEvents=c.pointerEvents}),r.value?document.documentElement.style.setProperty("background-color",r.value,r.priority):document.documentElement.style.removeProperty("background-color"),s.value?document.body.style.setProperty("background-color",s.value,s.priority):document.body.style.removeProperty("background-color")}},[]),a.useEffect(()=>{const r=()=>{document.visibilityState==="hidden"&&e()};return document.addEventListener("visibilitychange",r),()=>document.removeEventListener("visibilitychange",r)},[e]),Ke.createPortal(n.jsxs("div",{ref:t,role:"dialog","aria-modal":"true","aria-label":"Scan QR code",className:"fixed inset-0 z-[1000] flex flex-col bg-transparent px-6 pb-[calc(var(--safe-area-inset-bottom,env(safe-area-inset-bottom,0px))+24px)] pt-[calc(var(--safe-area-inset-top,env(safe-area-inset-top,0px))+24px)] text-foreground",children:[n.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-6",children:[n.jsx("div",{className:"aspect-square w-full max-w-72 rounded-[28px] border-2 border-foreground/90 shadow-[0_0_0_9999px_color-mix(in_srgb,var(--surface-background)_18%,transparent)]","aria-hidden":!0}),n.jsx("p",{className:"max-w-sm rounded-[16px] border border-border/60 bg-background px-4 py-3 text-center typography-body text-foreground shadow-sm",children:"On your computer, open «Add a device» to show a QR code, then scan it here."})]}),n.jsxs(le,{type:"button",variant:"outline",size:"lg",className:"mx-auto min-h-12 w-full max-w-sm bg-background",onClick:e,children:[n.jsx(F,{name:"close",className:"size-[18px]"}),"Cancel"]})]}),document.body)},es=()=>Ke.createPortal(n.jsxs("div",{role:"status",className:"fixed inset-0 z-[1000] flex flex-col items-center justify-center gap-5 bg-background px-6 text-foreground",children:[n.jsx(Se,{width:96,height:96,isAnimated:!0}),n.jsxs("div",{className:"flex items-center gap-2 typography-ui-label text-muted-foreground",children:[n.jsx(F,{name:"loader-4",className:"size-[18px] animate-spin"}),n.jsx("span",{children:"Connecting..."})]})]}),document.body),Ia=({onConnected:e,notice:t=null})=>{const r=Kt(e),{connections:s,isBusy:o,isPasswordBusy:i,error:l,pendingConnection:c}=r,[u,d]=a.useState(""),[p,m]=a.useState(""),[S,k]=a.useState(""),[w,E]=a.useState(!1),[_,I]=a.useState(!1),P=a.useRef(null),h=a.useMemo(()=>It(),[]),[y,U]=a.useState(()=>!It()),[x,j]=a.useState(null),[C,L]=a.useState(""),z=a.useCallback(v=>{v.preventDefault(),r.connect({url:u,clientToken:S,label:p})},[S,r,p,u]),A=a.useCallback(v=>{if(/^pichamber:\/\//i.test(v.trim())){const N=Jn(v);if(N){if("pairing"in N){r.redeemPairingConnection(N.pairing);return}d(N.url),N.label&&m(N.label),N.clientToken&&k(N.clientToken);return}}d(v)},[r]),f=a.useCallback(async()=>{if(P.current||o)return;r.setError(null),E(!0);const v=new AbortController;P.current=v;try{const N=await Qn({signal:v.signal});switch(P.current===v&&(P.current=null,E(!1)),N.status){case"ok":I(!0),d(N.url),N.label&&m(N.label),N.clientToken&&k(N.clientToken),await r.connect({url:N.url,clientToken:N.clientToken,label:N.label});break;case"pairing":I(!0),await r.redeemPairingConnection(N.pairing);break;case"permission-denied":r.setError("Camera access is off. Enable it in Settings to scan a QR code.");break;case"invalid":r.setError("That QR code is not an PiChamber connection code.");break;case"unsupported":r.setError("QR scanning is only available in the installed mobile app.");break;case"failed":r.setError("Could not scan that QR code. Try again or enter the URL manually.");break;default:break}}finally{I(!1),P.current===v&&(P.current=null,E(!1))}},[r,o]);a.useEffect(()=>()=>P.current?.abort(),[]);const D=a.useCallback(v=>{v.preventDefault(),r.submitPassword(C)},[r,C]),M=a.useCallback(()=>{L(""),r.cancelPassword()},[r]);return n.jsxs(n.Fragment,{children:[w?n.jsx(Zn,{onCancel:()=>P.current?.abort()}):null,_?n.jsx(es,{}):null,n.jsx("main",{className:"oc-keyboard-fill-screen flex min-h-dvh flex-col overflow-y-auto bg-background px-6 pb-[calc(var(--safe-area-inset-bottom,env(safe-area-inset-bottom,0px))+28px)] pt-[calc(var(--safe-area-inset-top,env(safe-area-inset-top,0px))+28px)] text-foreground",children:n.jsxs("div",{className:"m-auto flex w-full max-w-[360px] shrink-0 flex-col items-center gap-9 py-8",children:[n.jsxs("div",{className:"flex flex-col items-center gap-5 text-center",children:[n.jsx(Se,{width:72,height:72,className:"size-[72px]"}),n.jsx("h1",{className:"typography-h2 text-foreground",children:"Connect to PiChamber"})]}),t?n.jsxs("div",{role:"status",className:"flex w-full items-center gap-3 rounded-[18px] border border-[color-mix(in_srgb,var(--status-warning)_35%,transparent)] bg-[color-mix(in_srgb,var(--status-warning)_10%,transparent)] px-3.5 py-3",children:[n.jsx("span",{className:"flex size-9 shrink-0 items-center justify-center rounded-[12px] bg-[color-mix(in_srgb,var(--status-warning)_16%,transparent)] text-[var(--status-warning)]",children:n.jsx(F,{name:t.kind==="auth-expired"?"lock":"cloud-off",className:"size-[18px]"})}),n.jsx("p",{className:"min-w-0 flex-1 typography-small text-foreground",children:t.kind==="auth-expired"?`Access to ${t.label} has expired or was revoked. Sign in again.`:`Couldn't reach ${t.label}. Check that the server is running.`})]}):null,c?n.jsxs("form",{className:"flex w-full flex-col gap-3",onSubmit:D,children:[n.jsxs("div",{className:"flex items-center gap-3 rounded-[18px] border border-border/70 bg-surface-elevated px-3.5 py-3",children:[n.jsx("span",{className:"flex size-9 shrink-0 items-center justify-center rounded-[12px] bg-interactive-hover text-foreground",children:n.jsx(F,{name:"lock",className:"size-[18px]"})}),n.jsxs("div",{className:"min-w-0 text-left",children:[n.jsx("p",{className:"truncate typography-ui-label text-foreground",children:c.label}),n.jsx("p",{className:"truncate typography-small text-muted-foreground",children:c.candidates.some(v=>v.kind==="direct")?xe(c):"via PiChamber Relay"})]})]}),n.jsx("input",{...$e,value:C,onChange:v=>L(v.target.value),placeholder:"PiChamber password","aria-label":"Password",type:"password",autoFocus:!0,className:Xe}),l?n.jsx("p",{className:"px-1 text-center typography-small text-[var(--status-error)]",children:l}):null,n.jsx(le,{type:"submit",size:"lg",className:"mt-1 h-12 w-full",disabled:i||!C.trim(),children:i?"Connecting...":"Unlock and connect"}),n.jsx(le,{type:"button",variant:"ghost",size:"sm",className:"w-full",onClick:M,children:"Use another server"})]}):n.jsxs("div",{className:"flex w-full flex-col gap-6",children:[h?n.jsxs("div",{className:"flex w-full flex-col gap-2",children:[n.jsxs(le,{type:"button",size:"lg",className:"h-12 w-full",onClick:()=>{f()},disabled:w||o,children:[n.jsx(F,{name:"scan-2",className:K("size-[18px]",w&&"animate-pulse")}),o?"Connecting...":"Scan QR code"]}),n.jsx("p",{className:"px-2 text-center typography-small text-muted-foreground",children:"On your computer, open «Add a device» to show a QR code, then scan it here."})]}):null,l&&!y?n.jsx("p",{className:"px-1 text-center typography-small text-[var(--status-error)]",children:l}):null,s.length>0?n.jsxs("section",{className:"flex w-full flex-col gap-2.5",children:[n.jsx("h2",{className:"text-center typography-micro uppercase tracking-[0.14em] text-muted-foreground",children:"Saved connections"}),n.jsx("div",{className:"overflow-hidden rounded-[18px] border border-border/70 bg-surface-elevated",children:s.map(v=>{const N=x===v.id;return n.jsxs("button",{type:"button",disabled:o,className:"flex min-h-14 w-full items-center gap-3 border-b border-border/70 px-3.5 py-2.5 text-left last:border-b-0 hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary disabled:opacity-70",onClick:()=>{j(v.id),r.connect({id:v.id,candidates:v.candidates,clientToken:v.clientToken,label:v.label}).finally(()=>j(null))},children:[n.jsx("span",{className:"flex size-9 shrink-0 items-center justify-center rounded-[12px] bg-interactive-hover text-foreground",children:n.jsx(F,{name:"server",className:"size-[18px]"})}),n.jsxs("span",{className:"min-w-0 flex-1",children:[n.jsx("span",{className:"block truncate typography-ui-label text-foreground",children:v.label}),n.jsx("span",{className:K("block truncate typography-small",N?"text-foreground":"text-muted-foreground"),children:N?"Connecting...":v.candidates.some(J=>J.kind==="direct")?xe(v):"via PiChamber Relay"})]}),N?n.jsx(F,{name:"loader-4",className:"size-5 animate-spin text-muted-foreground"}):n.jsx(F,{name:"arrow-right-s",className:"size-5 text-muted-foreground"})]},v.id)})})]}):null,n.jsxs("div",{className:"flex w-full flex-col",children:[h?n.jsxs("button",{type:"button",onClick:()=>U(v=>!v),"aria-expanded":y,className:"mx-auto flex items-center gap-1 rounded-full px-2 py-1 typography-small text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:[n.jsx("span",{children:"Connect by address"}),n.jsx(F,{name:"arrow-down-s",className:K("size-4 transition-transform duration-200",y&&"rotate-180")})]}):null,n.jsx("div",{className:"grid transition-[grid-template-rows] duration-200 ease-out",style:{gridTemplateRows:y?"1fr":"0fr"},children:n.jsx("div",{className:"min-h-0 overflow-hidden",children:n.jsxs("form",{className:"flex w-full flex-col gap-3 pt-3",onSubmit:z,children:[n.jsx("input",{...$e,value:u,onChange:v=>A(v.target.value),placeholder:"http://192.168.1.74:2606","aria-label":"Server URL",type:"url",inputMode:"url",autoCapitalize:"none",tabIndex:y?void 0:-1,className:K(Xe,"text-center")}),n.jsx("input",{value:p,onChange:v=>m(v.target.value),placeholder:"Optional display name","aria-label":"Name",autoComplete:"off",autoCapitalize:"words",autoCorrect:"off",spellCheck:!1,tabIndex:y?void 0:-1,className:K(Xe,"text-center")}),n.jsx("input",{...$e,value:S,onChange:v=>k(v.target.value),placeholder:"Paste access token","aria-label":"Client token",tabIndex:y?void 0:-1,autoCapitalize:"none",className:K(Xe,"text-center")}),n.jsx("p",{className:"px-1 text-center typography-micro text-muted-foreground",children:"Only needed if your server requires a token instead of a password."}),l?n.jsx("p",{className:"px-1 text-center typography-small text-[var(--status-error)]",children:l}):null,n.jsx(le,{type:"submit",variant:h?"outline":"default",size:"lg",className:"h-12 w-full",disabled:o||w||!u.trim(),children:o?"Connecting...":"Connect"})]})})})]})]})]})})]})},Pa=10,Aa=(e,t)=>Mn(e,t),_a=({session:e,meta:t,active:r,onSelect:s})=>{const o=rr(e.id),i=ar(e.id),l=o?.type??"idle",c=l==="busy"||l==="retry",u=!c&&i>0&&!r,d=ir(e.id,c),p=c&&d,m=Fr(e.time?.updated??e.time?.created??0);return n.jsxs("button",{type:"button",className:K("flex w-full items-center gap-3 rounded-xl px-2.5 py-2 text-left transition-colors active:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary",r&&"bg-[color-mix(in_srgb,var(--primary)_10%,transparent)]"),onClick:s,style:{touchAction:"manipulation"},children:[n.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[n.jsx("span",{className:K("block truncate typography-ui-label",r?"text-primary":"text-foreground"),children:Aa(e,"Untitled Session")}),t?n.jsx("span",{className:"block truncate typography-micro text-muted-foreground",children:t}):null]}),c?n.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-primary","aria-hidden":!0}):u?n.jsx(Vr,{label:"Session complete"}):null,p?n.jsx(Gr,{sessionId:e.id,running:c,className:"typography-micro"}):u?null:m?n.jsx("span",{className:"shrink-0 typography-micro text-muted-foreground tabular-nums",children:m}):null]})},Da=({open:e,onClose:t,anchorRef:r})=>{const{panelRef:s,wrapperRef:o,shouldRender:i,isExiting:l,anchorLeft:c,isPopover:u}=Es({open:e,onClose:t,anchorRef:r}),d=me(w=>w.currentSessionId),p=me(w=>w.setCurrentSession),m=An(w=>w.setActiveProjectIdOnly),S=Xr(e||i,{maxParents:Pa}),k=a.useCallback(w=>{p(w.id,_n(w)),t()},[t,p]);return i?n.jsxs("div",{ref:o,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:s,role:"dialog","aria-label":"Open session switcher",className:K("flex flex-col overflow-hidden rounded-[20px] border border-border/70 bg-[var(--surface-elevated)] p-2 shadow-[0_12px_32px_rgb(0_0_0_/_0.2)] will-change-transform",u?"absolute origin-top-left":"mx-3 mt-2",l?"pointer-events-none":"pointer-events-auto"),style:{animation:`${l?"session-switcher-out":"session-switcher-in"} ${l?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:c??8,width:`min(${Rs}px, calc(100% - 16px))`}:null},children:n.jsx("div",{className:"oc-hide-scrollbar min-h-0 flex-1 space-y-0.5 overflow-y-auto overscroll-contain",children:S.length===0?n.jsx("p",{className:"px-3 py-6 text-center typography-small text-muted-foreground",children:"No recent sessions"}):S.map(w=>{const E=w.node.session,_=[w.secondaryMeta?.projectLabel,w.secondaryMeta?.branchLabel].filter(Boolean).join(" · ");return n.jsx(_a,{session:E,meta:_,active:E.id===d,onSelect:()=>{w.projectId&&m(w.projectId),k(E)}},E.id)})})}),n.jsx("style",{children:`
|
|
3
|
-
@keyframes session-switcher-in {
|
|
4
|
-
from { opacity: 0; transform: translateY(-8px) scale(0.985); }
|
|
5
|
-
to { opacity: 1; transform: translateY(0) scale(1); }
|
|
6
|
-
}
|
|
7
|
-
@keyframes session-switcher-out {
|
|
8
|
-
from { opacity: 1; transform: translateY(0) scale(1); }
|
|
9
|
-
to { opacity: 0; transform: translateY(-6px) scale(0.985); }
|
|
10
|
-
}
|
|
11
|
-
`})]}):null},Ma=({onOpenSessions:e,onOpenWorkspace:t,compactTitle:r=!1})=>{const[s,o]=a.useState(!1),[i,l]=a.useState(!1),c=a.useRef(null),u=In(h=>h.currentDirectory),d=me(h=>h.currentSessionId),m=me(a.useCallback(h=>d?h.getDirectoryForSession(d):null,[d]))||u,S=or(d),k=me(h=>!!h.newSessionDraft?.open),E=S?.title?.trim()||(d?Mn(S,"Untitled session"):"New session");a.useEffect(()=>{o(!1),l(!1)},[d,m]);const _=a.useCallback(()=>{o(!1),l(!1),e()},[e]),I=a.useCallback(h=>{o(y=>{const U=typeof h=="function"?h(y):h;return U&&l(!1),U})},[]),P=a.useCallback(()=>{l(h=>{const y=!h;return y&&o(!1),y})},[]);return n.jsxs(n.Fragment,{children:[n.jsx("header",{className:"oc-mobile-header relative z-30 flex shrink-0 items-center gap-1 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80",style:{paddingTop:"var(--oc-safe-area-top, 0px)"},children:n.jsxs("div",{className:"flex h-[var(--oc-header-height,56px)] w-full items-center gap-1 px-2",children:[n.jsx("button",{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":"Open sessions and projects",onClick:_,style:{touchAction:"manipulation"},children:n.jsx(F,{name:"list-unordered",className:"size-5"})}),n.jsx("button",{ref:c,type:"button",className:K("flex h-10 min-w-0 items-center rounded-lg px-2 py-1.5 text-left transition-colors active:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",r?"shrink":"flex-1"),"aria-label":"Open session switcher","aria-haspopup":"dialog","aria-expanded":i,onClick:P,style:{touchAction:"manipulation"},children:n.jsxs("span",{className:"flex min-w-0 items-center gap-1",children:[n.jsx("span",{className:"block min-w-0 truncate typography-ui-label text-foreground",children:E}),n.jsx(F,{name:"arrow-down-s",className:K("size-4 shrink-0 text-muted-foreground transition-transform duration-150",i&&"rotate-180")})]})}),r?n.jsx("div",{className:"min-w-0 flex-1"}):null,n.jsx(Ts,{open:s,onOpenChange:I,currentSessionId:d,effectiveDirectory:m,isNewSessionDraftOpen:k}),n.jsx("button",{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":"Open workspace panel",onClick:()=>{o(!1),l(!1),t()},style:{touchAction:"manipulation"},children:n.jsx(F,{name:"layout-right",className:"size-5"})})]})}),n.jsx(Da,{open:i,onClose:()=>l(!1),anchorRef:c})]})},La=({onActiveConnectionDeleted:e,onConnect:t})=>{const r=Kt(t),{connections:s,isBusy:o,isPasswordBusy:i,error:l,pendingConnection:c,connect:u,submitPassword:d,cancelPassword:p,saveConnection:m,removeConnection:S,setError:k}=r,[w,E]=a.useState(null),_=w?s.find(T=>T.id===w)??null:null,[I,P]=a.useState(null),[h,y]=a.useState(""),[U,x]=a.useState(""),[j,C]=a.useState(""),[L,z]=a.useState(""),[A,f]=a.useState(!1),[D,M]=a.useState(!1),[v,N]=a.useState(!1),[J,X]=a.useState(null),V=a.useRef(null),ne=a.useMemo(()=>It(),[]),[R,W]=a.useState(!1),[te,Te]=a.useState(null),ye=a.useCallback(()=>{E(null),y(""),x(""),C(""),k(null),W(!1)},[k]),pe=a.useCallback(T=>{T.preventDefault(),m({id:w??void 0,url:h,label:U,clientToken:j}).then($=>{$&&ye()})},[j,w,U,ye,m,h]),ce=a.useCallback(async()=>{if(V.current)return;k(null),f(!0);const T=new AbortController;V.current=T;try{const $=await Qn({signal:T.signal});switch(V.current===T&&(V.current=null,f(!1)),$.status){case"ok":y($.url),$.label&&x($.label),$.clientToken&&C($.clientToken),W(!0);break;case"pairing":M(!0),await r.redeemPairingConnection($.pairing);break;case"permission-denied":k("Camera access is off. Enable it in Settings to scan a QR code.");break;case"invalid":k("That QR code is not an PiChamber connection code.");break;case"unsupported":k("QR scanning is only available in the installed mobile app.");break;case"failed":k("Could not scan that QR code. Try again or enter the URL manually.");break;default:break}}finally{M(!1),V.current===T&&(V.current=null,f(!1))}},[r,k]);a.useEffect(()=>()=>V.current?.abort(),[]);const b=a.useCallback(T=>{T.preventDefault(),d(L)},[L,d]),B=a.useCallback(()=>{z(""),p()},[p]),G=a.useCallback(async()=>{if(!v){X(null),N(!0);try{const T=await ys();X(T==="copied"?"Diagnostics copied to the clipboard.":T==="downloaded"?"Diagnostics downloaded.":"Diagnostics ready to share.")}catch{X("Diagnostics export was cancelled or unavailable.")}finally{N(!1)}}},[v]),O=a.useCallback(T=>{P($=>$===T?null:T)},[]),H=a.useCallback(T=>{P(null),w===T&&ye();const $=s.length===1;S(T).then(Y=>{Y&&($||Rt(Y))&&e()})},[s.length,w,e,S,ye]),se=Xe;return c?n.jsx("div",{className:"flex h-full flex-col overflow-hidden",children:n.jsx("form",{className:"flex-1 overflow-y-auto px-5 py-4",onSubmit:b,children:n.jsxs("div",{className:"flex flex-col gap-3",children:[n.jsxs("div",{className:"flex items-center gap-3 rounded-[18px] border border-border/70 bg-surface-elevated px-3.5 py-3",children:[n.jsx("span",{className:"flex size-9 shrink-0 items-center justify-center rounded-[12px] bg-interactive-hover text-foreground",children:n.jsx(F,{name:"lock",className:"size-[18px]"})}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("p",{className:"truncate typography-ui-label text-foreground",children:c.label}),n.jsx("p",{className:"truncate typography-small text-muted-foreground",children:c.candidates.some(T=>T.kind==="direct")?xe(c):"via PiChamber Relay"})]})]}),n.jsx("input",{...$e,value:L,onChange:T=>z(T.target.value),placeholder:"PiChamber password","aria-label":"Password",type:"password",autoFocus:!0,className:se}),l?n.jsx("p",{className:"px-1 typography-small text-[var(--status-error)]",children:l}):null,n.jsx(le,{type:"submit",size:"lg",className:"mt-1 h-12 w-full",disabled:i||!L.trim(),children:i?"Connecting...":"Unlock and connect"}),n.jsx(le,{type:"button",variant:"ghost",size:"sm",className:"w-full",onClick:B,children:"Use another server"})]})})}):n.jsxs(n.Fragment,{children:[A?n.jsx(Zn,{onCancel:()=>V.current?.abort()}):null,D?n.jsx(es,{}):null,n.jsx("div",{className:"flex h-full flex-col overflow-hidden",children:n.jsx("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:n.jsxs("div",{className:"space-y-6",children:[s.length>0?n.jsx("div",{className:"overflow-hidden rounded-[18px] border border-border/70 bg-surface-elevated",children:s.map(T=>{const $=I===T.id,Y=Rt(T),Z=te===T.id,be=Z?"Connecting...":Y?Qe()?"Connected · Private relay":"Connected · Local network":T.candidates.some(he=>he.kind==="direct")?xe(T):"via PiChamber Relay";return n.jsxs("div",{className:K("flex items-center border-b border-border/70 transition-colors last:border-b-0",$&&"bg-[color-mix(in_srgb,var(--destructive)_8%,transparent)]"),children:[n.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 items-center gap-3 px-3.5 py-3 text-left transition-colors active:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary disabled:opacity-60",onClick:()=>{Y||(Te(T.id),u({id:T.id,candidates:T.candidates,clientToken:T.clientToken,label:T.label}).finally(()=>Te(null)))},disabled:o&&!Z||$,children:[n.jsxs("span",{className:"relative flex size-9 shrink-0 items-center justify-center rounded-[12px] bg-interactive-hover text-foreground",children:[n.jsx(F,{name:"server",className:"size-[18px]"}),Y?n.jsx("span",{className:"absolute -right-0.5 -top-0.5 size-2.5 rounded-full border-2 border-[var(--surface-elevated)] bg-[var(--status-success)]","aria-hidden":!0}):null]}),n.jsxs("span",{className:"min-w-0 flex-1",children:[n.jsx("span",{className:"block truncate typography-ui-label text-foreground",children:T.label}),n.jsx("span",{className:K("block truncate typography-small",Y&&!Z?"text-[var(--status-success)]":"text-muted-foreground"),children:be})]}),Z?n.jsx(F,{name:"loader-4",className:"size-5 shrink-0 animate-spin text-muted-foreground"}):null]}),n.jsxs("div",{className:"flex items-center gap-0.5 pr-2",children:[$?n.jsxs("button",{type:"button","aria-label":`Confirm deleting ${T.label}`,className:"flex h-9 shrink-0 items-center gap-1.5 rounded-full bg-destructive px-3 text-destructive-foreground transition-opacity active:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive",onClick:()=>H(T.id),style:{touchAction:"manipulation"},children:[n.jsx(F,{name:"delete-bin",className:"size-[18px]"}),n.jsx("span",{className:"typography-ui-label",children:"Delete"})]}):T.candidates.some(he=>he.kind==="direct")?n.jsx("button",{type:"button","aria-label":"Edit",className:"flex size-9 items-center justify-center rounded-full text-muted-foreground transition-colors active:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",onClick:()=>{E(T.id),y(xe(T)),x(T.label),C(T.clientToken||""),k(null)},style:{touchAction:"manipulation"},children:n.jsx(F,{name:"edit",className:"size-[18px]"})}):null,n.jsx("button",{type:"button","aria-label":$?`Keep ${T.label}`:`Delete ${T.label}`,className:"flex size-9 items-center justify-center rounded-full text-muted-foreground transition-colors active:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",onClick:()=>O(T.id),style:{touchAction:"manipulation"},children:n.jsx(F,{name:$?"close":"delete-bin",className:"size-[18px]"})})]})]},T.id)})}):n.jsx("p",{className:"rounded-[18px] border border-dashed border-border/70 px-4 py-6 text-center typography-small text-muted-foreground",children:"No saved connections yet."}),n.jsxs("div",{className:"space-y-2",children:[n.jsxs(le,{type:"button",variant:"outline",size:"lg",className:"h-12 w-full",onClick:()=>{G()},disabled:v,children:[n.jsx(F,{name:"download",className:"size-[18px]"}),v?"Preparing diagnostics…":"Export diagnostics"]}),J?n.jsx("p",{className:"px-1 text-center typography-small text-muted-foreground",children:J}):null]}),!R&&!_?n.jsxs("div",{className:"space-y-2",children:[ne?n.jsxs(le,{type:"button",size:"lg",className:"h-12 w-full",onClick:()=>{ce()},disabled:A,children:[n.jsx(F,{name:"scan-2",className:K("size-[18px]",A&&"animate-pulse")}),"Scan QR code"]}):null,n.jsxs(le,{type:"button",variant:ne?"ghost":"outline",size:"lg",className:"h-12 w-full",onClick:()=>{k(null),W(!0)},children:[n.jsx(F,{name:"add",className:"size-[18px]"}),"Add by address"]}),l?n.jsx("p",{className:"px-1 text-center typography-small text-[var(--status-error)]",children:l}):null]}):n.jsxs("form",{className:"space-y-3",onSubmit:pe,children:[n.jsxs("div",{className:"flex h-8 items-center justify-between gap-3 px-1",children:[n.jsx("h3",{className:"typography-ui-label text-foreground",children:_?"Edit instance":"Add instance"}),n.jsx(le,{type:"button",variant:"ghost",size:"xs",onClick:ye,children:"Cancel"})]}),n.jsxs("label",{className:"block space-y-1.5",children:[n.jsx("span",{className:"block px-1 typography-ui-label text-foreground",children:"Server URL"}),n.jsx("input",{...$e,value:h,onChange:T=>y(T.target.value),placeholder:"http://192.168.1.74:2606",type:"url",inputMode:"url",autoCapitalize:"none",className:se})]}),n.jsxs("label",{className:"block space-y-1.5",children:[n.jsx("span",{className:"block px-1 typography-ui-label text-foreground",children:"Name"}),n.jsx("input",{value:U,onChange:T=>x(T.target.value),placeholder:"Optional display name",autoComplete:"off",autoCapitalize:"words",autoCorrect:"off",spellCheck:!1,className:se})]}),n.jsxs("label",{className:"block space-y-1.5",children:[n.jsx("span",{className:"block px-1 typography-ui-label text-foreground",children:"Client token"}),n.jsx("input",{...$e,value:j,onChange:T=>C(T.target.value),placeholder:"Paste access token",autoCapitalize:"none",className:se}),n.jsx("p",{className:"px-1 typography-micro text-muted-foreground",children:"Only needed if your server requires a token instead of a password."})]}),l?n.jsx("p",{className:"px-1 typography-small text-[var(--status-error)]",children:l}):null,n.jsx(le,{type:"submit",size:"lg",className:"mt-1 h-12 w-full",children:_?"Save changes":"Save instance"})]})]})})})]})},Fe=320,Re="cubic-bezier(0.22, 1, 0.36, 1)",ts=({side:e,enabled:t,open:r,drawerRef:s,scrimRef:o,onClose:i,widthRatio:l,prefersReducedMotion:c})=>{a.useEffect(()=>{if(!t||!r)return;const u=s.current,d=o.current;if(!u||!d)return;let p=!1,m=!1,S=!1,k=0,w=0,E=0,_=0;const I=c?0:Fe,P=e==="left"?"translateX(-100%)":"translateX(100%)",h=()=>({drawer:I?`transform ${I}ms ${Re}`:"none",scrim:I?`opacity ${I}ms ${Re}`:"none"}),y=()=>{const f=h();u.style.transition=f.drawer,d.style.transition=f.scrim,u.style.transform="none",d.style.opacity="1",d.style.pointerEvents="auto"},U=()=>{p=!1,m=!1,S=!1},x=()=>{if(!(p||m)){U();return}y(),U()},j=f=>{if(f.touches.length!==1){(p||m)&&x();return}if(Ns(f.target,u,{excludeInteractive:!1}))return;u.style.transition&&u.style.transition!=="none"&&(u.style.transition="none",d.style.transition="none");const D=f.touches[0];k=D.clientX,w=D.clientY,E=Date.now(),_=u.offsetWidth||window.innerWidth*l,_<10&&(_=window.innerWidth*l),p=!0,m=!1,S=!1},C=f=>{if(!p)return;if(f.touches.length!==1){x();return}const D=f.touches[0],M=D.clientX-k,v=D.clientY-w;if(!S){if(Math.abs(M)<Jt&&Math.abs(v)<Jt)return;if(Math.abs(v)>Math.abs(M)*Yt||!Qt(e,M)){p=!1;return}S=!0,m=!0,u.style.transition="none",d.style.transition="none"}if(!m)return;f.cancelable&&f.preventDefault();const N=Zt(e,M,_);u.style.transform=Is(e,N),d.style.opacity=String(N)},L=(f,D,M)=>{if(!p)return;const v=f-k,N=D-w,J=Math.max(1,Date.now()-E),X=Zt(e,v,_),V=As({side:e,dx:v,dy:N,dt:J,progress:X,isDragging:m}),ne=h();u.style.transition=ne.drawer,d.style.transition=ne.scrim,u.style.transform=V?P:"none",d.style.opacity=V?"0":"1",d.style.pointerEvents=V?"none":"auto",U(),V&&i()},z=f=>{const D=f.changedTouches[0];if(!D){x();return}const M=D.clientX-k,v=D.clientY-w,N=Math.abs(M)>=Ps&&Math.abs(v)<=Math.abs(M)*Yt&&Qt(e,M);p&&(m||N)&&f.cancelable&&f.preventDefault(),L(D.clientX,D.clientY)},A=()=>{x()};return u.addEventListener("touchstart",j,{passive:!0}),u.addEventListener("touchmove",C,{passive:!1}),u.addEventListener("touchend",z,{passive:!1}),u.addEventListener("touchcancel",A,{passive:!0}),()=>{try{x()}catch{}u.removeEventListener("touchstart",j),u.removeEventListener("touchmove",C),u.removeEventListener("touchend",z),u.removeEventListener("touchcancel",A)}},[s,t,i,r,c,o,e,l])},Oa=16,pn=a.memo(function({open:t,onOpenChange:r,variant:s="drawer",drawerRefExternal:o,scrimRefExternal:i,rootRefExternal:l}){const c=a.useRef(null),u=a.useCallback(()=>{const y=typeof document<"u"?document.activeElement:null;y instanceof HTMLElement&&c.current?.contains(y)&&y.blur(),r(!1)},[r]),[d,p]=a.useState(!1),m=a.useRef(null),S=a.useRef(null),k=o??m,w=i??S,E=a.useCallback(y=>{c.current=y,l&&(l.current=y)},[l]),_=a.useMemo(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches,[]);a.useEffect(()=>{const y=c.current;if(!y||t)return;const U=document.activeElement;U&&y.contains(U)&&U.blur()},[t]),a.useEffect(()=>{if(s!=="sidebar"){if(t){const y=window.setTimeout(()=>p(!0),_?0:Oa);return()=>window.clearTimeout(y)}p(!1)}},[t,_,s]),a.useEffect(()=>{if(s==="sidebar"||!t)return;const y=document.body.style.overflow;document.body.style.overflow="hidden";const U=x=>{x.key==="Escape"&&u()};return document.addEventListener("keydown",U),()=>{document.body.style.overflow=y,document.removeEventListener("keydown",U)}},[u,t,s]);const I=s==="sidebar",P=n.jsx(_s,{mobileVariant:!I,isVisible:t,allowReselect:!0,onSessionSelected:I?void 0:u,onNavigateAway:I?void 0:u});if(ts({side:"left",enabled:s==="drawer",open:t,drawerRef:k,scrimRef:w,onClose:u,widthRatio:.72,prefersReducedMotion:_}),s==="sidebar")return n.jsx("aside",{className:"relative flex h-full w-full flex-col bg-sidebar",children:P});if(typeof document>"u")return null;const h=_?0:Fe;return Ke.createPortal(n.jsxs("div",{ref:E,className:"fixed inset-0 z-50",inert:!t,style:{pointerEvents:t?"auto":"none"},"data-mobile-sessions-root":"true",children:[n.jsx("button",{ref:w,type:"button",className:"absolute inset-0 cursor-default bg-black/70","aria-label":"Close sessions",onClick:u,tabIndex:t?0:-1,style:{opacity:d?1:0,transition:`opacity ${h}ms ${Re}`},"data-mobile-sessions-scrim":"true"}),n.jsx("div",{ref:k,className:K("relative z-10 flex h-full w-[72%] max-w-[72%] flex-col bg-sidebar"),style:{paddingTop:"var(--oc-safe-area-top, 0px)",transform:d?"none":"translateX(-100%)",transition:h?`transform ${h}ms ${Re}`:"none",touchAction:"pan-x pan-y"},"data-mobile-sessions-drawer":"true",children:P})]}),document.body)}),hn="mobile-surface-root",kt=16,rt=200,za=()=>{if(typeof document>"u")return null;let e=document.getElementById(hn);return e||(e=document.createElement("div"),e.id=hn,document.body.appendChild(e)),e},St=({open:e,onClose:t,title:r,subtitle:s,trailing:o,disableEscapeDismiss:i=!1,headerless:l=!1,noHeaderBorder:c=!1,ariaLabel:u,variant:d="fullscreen",dialogAlign:p="chat",children:m})=>{const S=a.useRef(null),[k,w]=a.useState(!1),[E,_]=a.useState(!1),I=a.useRef(null),P=a.useRef(null),h=a.useRef(t);if(a.useEffect(()=>{h.current=t},[t]),typeof document<"u"&&!S.current&&(S.current=za()),a.useEffect(()=>{if(!e){w(!1);return}const x=window.setTimeout(()=>w(!0),kt);return()=>window.clearTimeout(x)},[e]),a.useEffect(()=>{if(!e){_(!1);return}const x=window.setTimeout(()=>_(!0),kt+rt+80);return()=>window.clearTimeout(x)},[e]),a.useEffect(()=>{if(!e)return;const x=document.body.style.overflow;P.current=document.activeElement instanceof HTMLElement?document.activeElement:null,document.body.style.overflow="hidden";const j=()=>{const z=I.current;if(!z)return;(z.querySelector('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')??z).focus({preventScroll:!0})},C=window.setTimeout(j,kt),L=z=>{if(z.key==="Escape"&&!i){h.current();return}if(z.key!=="Tab")return;const A=I.current;if(!A)return;const f=Array.from(A.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')).filter(N=>!N.hasAttribute("disabled")&&N.getAttribute("aria-hidden")!=="true");if(f.length===0){z.preventDefault(),A.focus({preventScroll:!0});return}const D=f[0],M=f[f.length-1],v=document.activeElement;z.shiftKey&&v===D?(z.preventDefault(),M.focus({preventScroll:!0})):!z.shiftKey&&v===M&&(z.preventDefault(),D.focus({preventScroll:!0}))};return document.addEventListener("keydown",L),()=>{window.clearTimeout(C),document.body.style.overflow=x,document.removeEventListener("keydown",L),P.current?.focus?.({preventScroll:!0}),P.current=null}},[i,e]),!e||!S.current)return null;const y=d==="dialog",U=n.jsxs("section",{ref:I,role:"dialog","aria-modal":"true","aria-label":u,tabIndex:-1,className:K("flex flex-col bg-background text-foreground",y?"h-[min(88dvh,860px)] w-full max-w-[720px] overflow-hidden rounded-2xl border border-border/70 shadow-[0_24px_64px_rgb(0_0_0_/_0.32)]":"oc-keyboard-inset-surface fixed inset-0 z-50"),style:y?{opacity:k?1:0,transform:k?"none":"scale(0.97)",transition:`opacity ${rt}ms ease-out, transform ${rt}ms cubic-bezier(0.32, 0.72, 0, 1)`}:{paddingTop:"var(--oc-safe-area-top, 0px)",transform:k?"none":"translateX(100%)",transition:`transform ${rt}ms cubic-bezier(0.32, 0.72, 0, 1)`},onTransitionEnd:x=>{k&&x.target===x.currentTarget&&x.propertyName==="transform"&&_(!0)},children:[l?null:n.jsxs("header",{className:K("flex h-[var(--oc-header-height,56px)] shrink-0 items-center gap-2 px-3",!c&&"border-b border-border/70"),children:[n.jsx("button",{type:"button",className:"-ml-1 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":"Close",onClick:t,style:{touchAction:"manipulation"},children:n.jsx(F,{name:"close",className:"size-5"})}),n.jsxs("div",{className:"min-w-0 flex-1 px-1",children:[r?typeof r=="string"?n.jsx("h2",{className:"truncate typography-ui-label text-foreground",children:r}):r:null,s?typeof s=="string"?n.jsx("p",{className:"truncate typography-micro text-muted-foreground",children:s}):s:null]}),o?n.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:o}):null]}),n.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:E?n.jsx("div",{className:"h-full",style:{animation:"oc-surface-content-in 200ms ease-out"},children:m}):null}),n.jsx("style",{children:"@keyframes oc-surface-content-in { from { opacity: 0 } to { opacity: 1 } }"})]});return y?Ke.createPortal(n.jsx("div",{className:"oc-keyboard-inset-surface fixed inset-0 z-50 flex items-center justify-center p-4 transition-opacity duration-200 ease-out",style:{background:"rgb(0 0 0 / 0.45)",opacity:k?1:0,paddingLeft:p==="chat"?"max(1rem, var(--oc-chat-inset-left, 0px))":"1rem",paddingRight:p==="chat"?"max(1rem, var(--oc-chat-inset-right, 0px))":"1rem",paddingTop:"max(1rem, var(--oc-safe-area-top, 0px))"},onClick:t,children:n.jsx("div",{className:"flex w-full max-w-[720px] justify-center",onClick:x=>x.stopPropagation(),children:U})}),S.current):Ke.createPortal(U,S.current)},Ua=a.lazy(()=>Ce(()=>import("./FilesView-qP1ypN9J.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,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69])).then(e=>({default:e.FilesView}))),Ba=a.lazy(()=>Ce(()=>import("./GitView-y2k2i4gR.js"),__vite__mapDeps([70,10,1,2,3,9,4,5,6,7,8,11,48,49,50,51,52,71,72,73,74,75,76,55,56,57,32,33,34,35,36,37,38,39,40,41,42,43,44,45,58,30,31,59,60,61,62,63,64,65,77,78,79,28,29])).then(e=>({default:e.GitView}))),$a=a.lazy(()=>Ce(()=>import("./PullRequestsSurface-Cfb1wSvC.js"),__vite__mapDeps([80,10,1,2,3,81,4,5,6,7,8,9,11,48,49,50,51,52,82,72,73,76,55,56,57,32,33,34,35,36,37,38,39,40,41,42,43,44,45,58,30,31,59,60,61,62,63,64,65,77,78,79,28,29])).then(e=>({default:e.PullRequestsSurface}))),Ka=a.lazy(()=>Ce(()=>import("./IssuesSurface-HWgR87N3.js"),__vite__mapDeps([83,1,2,3,81,4,5,6,7,8,9,10,11,48,49,50,51,52,82,72,73,84])).then(e=>({default:e.IssuesSurface}))),mn="mobile-surface-root",Wa=16,yn=a.memo(function({open:t,onClose:r,tab:s,onTabChange:o,pendingChangesDiff:i,variant:l="drawer",drawerRefExternal:c,scrimRefExternal:u,rootRefExternal:d,githubTabsAvailable:p=!1}){const m=a.useRef(null),S=a.useRef(null),k=a.useRef(null),w=a.useRef(null),E=c??S,_=u??k,I=d??w,P=a.useCallback(R=>{w.current=R,d&&(d.current=R)},[d]),h=a.useCallback(()=>{const R=typeof document<"u"?document.activeElement:null;R instanceof HTMLElement&&I.current?.contains(R)&&R.blur(),r()},[r]),[y,U]=a.useState(!1),[x,j]=a.useState(t),C=`mobile-workspace-tab-${a.useId()}`,L=a.useMemo(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches,[]),[z,A]=a.useState(()=>new Set),[f,D]=a.useState(null),[M,v]=a.useState(null);if(a.useEffect(()=>{t&&A(R=>{if(R.has(s))return R;const W=new Set(R);return W.add(s),W})},[t,s]),typeof document<"u"&&!m.current){let R=document.getElementById(mn);R||(R=document.createElement("div"),R.id=mn,document.body.appendChild(R)),m.current=R}if(a.useEffect(()=>{if(t){j(!0);const W=window.setTimeout(()=>U(!0),L?0:Wa);return()=>window.clearTimeout(W)}U(!1);const R=window.setTimeout(()=>j(!1),Fe+40);return()=>window.clearTimeout(R)},[t,L]),a.useEffect(()=>{if(!t)return;const R=document.body.style.overflow;l==="drawer"&&(document.body.style.overflow="hidden");const W=te=>{te.key==="Escape"&&s!=="terminal"&&h()};return document.addEventListener("keydown",W),()=>{l==="drawer"&&(document.body.style.overflow=R),document.removeEventListener("keydown",W)}},[h,t,s,l]),a.useEffect(()=>{const R=I.current;if(!R||t||l!=="drawer")return;const W=document.activeElement;W&&R.contains(W)&&W.blur()},[t,l]),ts({side:"right",enabled:l==="drawer",open:t,drawerRef:E,scrimRef:_,onClose:h,widthRatio:1,prefersReducedMotion:L}),l==="drawer"&&!m.current)return null;const N=L?0:Fe,J=Ds(p),X=L?{duration:0}:{type:"spring",stiffness:520,damping:40,mass:.8},V=n.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-0.5 py-1 overflow-x-auto overflow-y-hidden scrollbar-none",role:"tablist","aria-label":"Workspace","data-no-drawer-swipe":"true",children:J.map(R=>{const W=s===R.id;return n.jsxs(bt.button,{layout:"position",transition:X,type:"button",role:"tab","aria-selected":W,"aria-label":R.label,onClick:()=>o(R.id),className:K("relative flex min-h-[44px] items-center justify-center gap-1 rounded-lg py-2 typography-ui-label transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",W?"min-w-0 shrink px-2.5 text-foreground":"size-11 shrink-0 text-muted-foreground hover:bg-interactive-hover hover:text-foreground"),children:[W?n.jsx(bt.span,{layoutId:C,transition:X,className:"absolute inset-0 bg-interactive-selection",style:{borderRadius:8},"aria-hidden":"true"}):null,n.jsx(F,{name:R.icon,className:"relative size-5 shrink-0"}),W?n.jsx(bt.span,{initial:L?!1:{opacity:0,x:-4},animate:{opacity:1,x:0},transition:X,className:"relative truncate",children:R.label},R.id):null]},R.id)})}),ne=n.jsxs(n.Fragment,{children:[l==="panel"?null:n.jsxs("div",{className:"flex h-[var(--oc-header-height,56px)] shrink-0 items-center gap-1 px-2",children:[V,n.jsx("button",{type:"button",onClick:h,"aria-label":"Close workspace panel",className:"flex size-11 shrink-0 items-center justify-center rounded-full text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:n.jsx(F,{name:"close",className:"size-5"})})]}),n.jsxs("div",{className:"min-h-0 flex-1 overflow-hidden",children:[z.has("changes")?n.jsx("div",{className:K("h-full",s!=="changes"&&"hidden"),children:n.jsx(de,{children:n.jsx(a.Suspense,{fallback:null,children:n.jsx(Ba,{isActive:t&&s==="changes",chrome:"mobile",initialDiffPath:i?.path??null,initialDiffStaged:i?.staged===!0})})})},i?`changes:${i.path}:${i.staged}`:"changes"):null,z.has("files")?n.jsx("div",{className:K("h-full",s!=="files"&&"hidden"),children:n.jsx(de,{children:n.jsx(a.Suspense,{fallback:null,children:n.jsx(Ua,{chrome:"mobile",mode:"editor-only",isVisible:t&&s==="files"})})})}):null,z.has("terminal")?n.jsx("div",{className:K("h-full",s!=="terminal"&&"hidden"),children:n.jsx(de,{children:n.jsx(Ms,{visible:t&&s==="terminal"})})}):null,z.has("pull-requests")?n.jsx("div",{className:K("h-full",s!=="pull-requests"&&"hidden"),children:n.jsxs("div",{className:"flex h-full min-h-0 flex-col bg-background",children:[n.jsx(en,{icon:st.find(R=>R.id==="pull-requests")?.icon,title:st.find(R=>R.id==="pull-requests")?.label??"Pull requests",actions:n.jsx("div",{ref:R=>{D(R)},className:"flex items-center gap-1"})}),n.jsx("div",{className:"min-h-0 flex-1",children:n.jsx(de,{children:n.jsx(a.Suspense,{fallback:null,children:n.jsx($a,{hideFilesTab:!0,headerActionsSlot:t&&s==="pull-requests"?f:null,headerActionsPresentation:"drawer"})})})})]})}):null,z.has("issues")?n.jsx("div",{className:K("h-full",s!=="issues"&&"hidden"),children:n.jsxs("div",{className:"flex h-full min-h-0 flex-col bg-background",children:[n.jsx(en,{icon:st.find(R=>R.id==="issues")?.icon,title:st.find(R=>R.id==="issues")?.label??"Issues",actions:n.jsx("div",{ref:R=>{v(R)},className:"flex items-center gap-1"})}),n.jsx("div",{className:"min-h-0 flex-1",children:n.jsx(de,{children:n.jsx(a.Suspense,{fallback:null,children:n.jsx(Ka,{headerActionsSlot:t&&s==="issues"?M:null,headerActionsPresentation:"drawer"})})})})]})}):null]})]});return l==="panel"?n.jsx("div",{className:"flex h-full min-h-0 flex-col bg-sidebar",children:ne}):Ke.createPortal(n.jsxs("div",{ref:P,className:"fixed inset-0 z-50",inert:!t,style:{pointerEvents:t?"auto":"none",visibility:x?"visible":"hidden"},"data-mobile-workspace-root":"true",children:[n.jsx("button",{ref:_,type:"button",className:"absolute inset-0 cursor-default bg-black/70","aria-label":"Close workspace panel",onClick:h,tabIndex:t?0:-1,style:{opacity:y?1:0,transition:N?`opacity ${N}ms ${Re}`:"none"},"data-mobile-workspace-scrim":"true"}),n.jsx("section",{ref:E,role:"dialog","aria-modal":"true","aria-label":"Open workspace panel",className:"oc-keyboard-inset-surface absolute inset-y-0 right-0 z-10 flex h-full w-full flex-col bg-sidebar",style:{paddingTop:"var(--oc-safe-area-top, 0px)",transform:y?"none":"translateX(100%)",transition:N?`transform ${N}ms ${Re}`:"none",touchAction:"pan-x pan-y"},"data-mobile-workspace-drawer":"true",children:ne})]}),m.current)}),Ha="pichamber",Fa=e=>e.replace(/^\/+|\/+$/g,""),Va=e=>{const t=Fa(e.pathname).split("/").filter(Boolean);return e.host?[e.host,...t]:t};function Ga(e){if(typeof e!="string"||e.length===0)return null;let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`${Ha}:`)return null;const r=Va(t),s=(r[0]??"").toLowerCase(),o=r.slice(1),i=t.searchParams;switch(s){case"session":{const l=o[0]||i.get("id")||"";return l?{type:"session",sessionId:l,directory:i.get("dir")??void 0}:null}case"new":case"new-session":return{type:"new-session",directory:i.get("dir")??void 0,projectId:i.get("project")??void 0,agent:i.get("agent")??void 0,model:i.get("model")??void 0};case"sessions":{const l=i.get("filter");return{type:"sessions",filter:l==="attention"||l==="recent"||l==="all"?l:void 0}}case"status":return{type:"status"};case"settings":return{type:"settings",section:o[0]||i.get("section")||void 0};case"changes":return{type:"changes",path:o.join("/")||i.get("path")||void 0,staged:i.get("staged")==="true"};case"view":{const l=(o[0]||"").toLowerCase();return l==="changes"?{type:"changes"}:l==="files"||l==="mcp"||l==="instances"||l==="update"?{type:"view",target:l}:null}default:return null}}let oe={},ns=!1,qe=null;const Xa=e=>{switch(e.type){case"session":return me.getState().setCurrentSession(e.sessionId,e.directory??null),!0;case"new-session":{const t=me.getState();return t.openNewSessionDraft(),(e.directory||e.projectId)&&t.setNewSessionDraftTarget({directoryOverride:e.directory??null,projectId:e.projectId??null,selectedProjectId:e.projectId??null}),!0}case"sessions":return oe.openSessions?(oe.openSessions(e.filter),!0):!1;case"status":return oe.openSessions?(oe.openSessions(),!0):!1;case"view":return oe.openView?(oe.openView(e.target),!0):!1;case"changes":return oe.openChanges?(oe.openChanges({path:e.path,staged:e.staged}),!0):!1;case"settings":return oe.openSettings?(oe.openSettings(e.section),!0):!1}},Wt=()=>{if(!ns||!qe)return;const e=qe;qe=null,Xa(e)||(qe=e)},ss=e=>{qe=e,Wt()},bn=e=>{const t=Ga(e);t&&ss(t)},qa=e=>{ns=e,Wt()},Ja=e=>{a.useEffect(()=>(oe=e,Wt(),()=>{oe===e&&(oe={})}),[e])},Ya=e=>{const{ready:t}=e;a.useEffect(()=>{qa(t)},[t]),a.useEffect(()=>{if(!ee())return;let r=!1;const s=[];return Ce(()=>import("./vendor-capacitor-app-BrDJj9I_.js"),__vite__mapDeps([85,10,86])).then(async({App:o})=>{if(r)return;const i=await o.addListener("appUrlOpen",l=>{bn(l?.url)});if(r){i.remove();return}s.push(()=>{i.remove()})}).catch(()=>{}),Ce(()=>import("./vendor-capacitor-push-notifications-KNe1zSBF.js"),__vite__mapDeps([87,86])).then(async({PushNotifications:o})=>{if(r)return;const i=await o.addListener("pushNotificationActionPerformed",l=>{const c=l?.notification?.data,u=typeof c?.url=="string"?c.url:typeof c?.deeplink=="string"?c.deeplink:void 0;if(u){bn(u);return}const d=typeof c?.sessionId=="string"?c.sessionId:void 0;d&&ss({type:"session",sessionId:d})});if(r){i.remove();return}s.push(()=>{i.remove()})}).catch(()=>{}),()=>{r=!0,s.forEach(o=>o())}},[])},gn=e=>{const t=e.drawer.current,r=e.scrim.current,s=e.root.current;s&&(s.style.pointerEvents="auto",s.style.visibility="visible"),t&&(t.style.transition="none"),r&&(r.style.transition="none")},xn=(e,t,r)=>{const s=e.drawer.current,o=e.scrim.current;if(s&&(s.style.transform=r>=.999?"none":`translateX(${(t==="left"?r-1:1-r)*100}%)`),o){o.style.opacity=String(r);const i=r>.01?"auto":"none";o.style.pointerEvents!==i&&(o.style.pointerEvents=i)}},vn=(e,t,r)=>{const s=r.drawer.current,o=r.scrim.current,i=r.root.current;s&&(s.style.transition=`transform ${Fe}ms ${Re}`,s.style.transform=t?"none":e==="left"?"translateX(-100%)":"translateX(100%)"),o&&(o.style.transition=`opacity ${Fe}ms ${Re}`,o.style.opacity=t?"1":"0",o.style.pointerEvents=t?"auto":"none"),i&&(i.style.pointerEvents=t?"auto":"none",i.style.visibility=t?"visible":"")},wn=e=>{const t=e.shell.current,r=e.inner.current;t&&(t.style.overflow="visible"),r&&(r.style.transition="none")},kn=(e,t,r,s)=>{const o=e.inner.current;if(!o)return;const i=s==="left"?(t-1)*r:(1-t)*r;o.style.transform=t>=.999?"translateX(0)":`translateX(${i}px)`},Sn=(e,t,r,s,o)=>{const i=e.shell.current,l=e.inner.current;return!i||!l?void 0:(l.style.transition="transform 200ms cubic-bezier(0.22, 1, 0.36, 1)",l.style.transform=t?"translateX(0)":`translateX(${s==="left"?-r:r}px)`,window.setTimeout(()=>{l.style.transition="",l.style.transform="",i.style.overflow=""},220))},jn=({side:e,isResizing:t,ariaLabel:r,handleProps:s})=>n.jsx("div",{className:K("absolute inset-y-0 z-50 w-6 cursor-col-resize touch-none",e==="left"?"right-0":"left-0"),role:"separator","aria-orientation":"vertical","aria-label":r,...s,children:n.jsx("div",{className:K("absolute inset-y-0 w-[3px] transition-colors",e==="left"?"right-0":"left-0",t&&"bg-[var(--interactive-border)]")})}),Qa=320,Za=380,Cn=280,ei=560,ti=900;function En(e,t,r,s=ei){const o=a.useRef(null),[i,l]=a.useState(()=>{if(typeof window>"u")return r;const h=Number.parseInt(window.localStorage.getItem(t)??"",10);return Number.isFinite(h)?Math.min(s,Math.max(Cn,h)):r}),[c,u]=a.useState(!1),d=a.useRef(0),p=a.useRef(i),m=a.useRef(null),S=a.useRef(null),k=a.useCallback(h=>Math.min(s,Math.max(Cn,Math.round(h))),[s]),w=a.useCallback(h=>{const y=o.current;y&&(y.style.width=`${h}px`,y.style.minWidth=`${h}px`,y.style.maxWidth=`${h}px`,y.style.setProperty("--oc-ipad-sidebar-width",`${h}px`))},[]),E=a.useCallback(h=>{try{h.currentTarget.setPointerCapture(h.pointerId)}catch{}S.current=h.pointerId,d.current=h.clientX,p.current=i,m.current=i,u(!0),h.preventDefault()},[i]),_=a.useCallback(h=>{if(S.current!==h.pointerId)return;const y=h.clientX-d.current,U=k(p.current+(e==="left"?y:-y));m.current!==U&&(m.current=U,w(U))},[w,k,e]),I=a.useCallback(h=>{if(S.current!==h.pointerId)return;try{h.currentTarget.releasePointerCapture(h.pointerId)}catch{}const y=k(m.current??p.current);S.current=null,m.current=null,u(!1),l(y);try{window.localStorage.setItem(t,String(y))}catch{}},[k,t]),P=a.useMemo(()=>({onPointerDown:E,onPointerMove:_,onPointerUp:I,onPointerCancel:I}),[E,I,_]);return{asideRef:o,width:i,isResizing:c,handleProps:P}}const ni=a.memo(Ws),si=({onActiveConnectionDeleted:e})=>{const[t,r]=a.useState(!1),[s,o]=a.useState(null),[i,l]=a.useState(!1),[c,u]=a.useState("changes"),d=a.useCallback(g=>{u(tn(g))},[]),p=c,[m,S]=a.useState("nav"),[k,w]=a.useState(null),E=a.useRef([]),_=a.useCallback(()=>{E.current.forEach(g=>window.clearTimeout(g)),E.current=[]},[]);a.useEffect(()=>()=>_(),[_]);const I=a.useRef(null),P=a.useRef(null),h=a.useRef(null),y=a.useRef(null),U=a.useRef(null),x=a.useRef(null),j=a.useRef(null),C=a.useRef(null),L=a.useRef(0),z=a.useRef(0),A=a.useCallback(g=>{_(),r(g)},[_]),f=a.useCallback(g=>{_(),l(g)},[_]),D=Ie(g=>g.setSettingsPage),M=Ie(g=>g.isArchivePageOpen),v=Ie(g=>g.setArchivePageOpen),N=Be(g=>g.available),J=Be(g=>g.runtimeType),X=a.useMemo(()=>Dn(),[]),V=!X&&N&&(J==="desktop"||J==="web"),ne=lr()??"",R=ne?bs(ne):"",W=cr().github??null,te=nn(g=>g.ensureScope);a.useEffect(()=>{!R||!W||te(R,W)},[R,W,te]);const Te=nn(g=>R?g.entriesByDirectory[R]??null:null),ye=a.useMemo(()=>ur(Te),[Te]),pe=dr(ye);a.useEffect(()=>{!pe&&Ls(c)&&u(Os(c))},[pe,c]);const ce=a.useCallback(()=>{o(null)},[]),b=a.useCallback(g=>{o(g)},[]),B=a.useCallback(()=>{f(!1)},[f]),G=a.useCallback(g=>{S(g),b("settings")},[b]),{enabled:O,roomyForPanels:H}=fr(),T=pr()==="portrait",$=hr(),Y=Ie(g=>g.setSidebarOpen),Z=Ie(g=>g.isSidebarOpen),be=a.useRef(!1);a.useLayoutEffect(()=>{O&&!be.current&&Y(mr().roomyForPanels),!O&&be.current&&Y(!1),be.current=O},[O,Y]);const he=a.useCallback(()=>{w(null),d("files"),f(!0)},[d,f]),nt=a.useCallback((g=null)=>{w(g),d("changes"),f(!0)},[d,f]),ie=En("left","pichamber.ipad.leftSidebarWidth",Qa),ue=En("right","pichamber.ipad.rightSidebarWidth",Za,ti),Ht=H,ge=Ht&&i?ue.width:0,rs=zs(O&&Z),Ve=O&&Z?ie.width:0,as=a.useCallback(g=>{const re=tn(g);i&&p===re?f(!1):(d(re),f(!0))},[i,p,d,f]),is=a.useCallback(()=>{f(!i)},[i,f]),os=a.useCallback(g=>{!g&&!H&&Y(!1)},[H,Y]);a.useEffect(()=>{if(typeof document>"u")return;const g=document.documentElement;return g.style.setProperty("--oc-chat-inset-left",`${Ve}px`),g.style.setProperty("--oc-chat-inset-right",`${ge}px`),()=>{g.style.removeProperty("--oc-chat-inset-left"),g.style.removeProperty("--oc-chat-inset-right")}},[Ve,ge]),a.useEffect(()=>{if(typeof document>"u")return;const g=O&&(T||$),re=document.documentElement;return re.classList.toggle("oc-keep-draft-starters",g),()=>re.classList.remove("oc-keep-draft-starters")},[$,O,T]);const Ft=a.useCallback(()=>{A(!1),f(!1)},[A,f]),ls=a.useMemo(()=>({openChanges:({diffPath:g,staged:re}={})=>{nt(g?{path:g,staged:re===!0}:null)},openFiles:()=>he(),openSettings:g=>{g&&D(g),G(g?"page-content":"nav")},openInstances:X?()=>b("instances"):void 0,instanceLabel:X?Ae():null,openUpdate:V?()=>b("update"):void 0,closeDrawers:Ft}),[Ft,nt,he,G,b,D,X,V]),cs=a.useMemo(()=>({openSessions:()=>{O?Y(!0):A(!0)},openView:g=>{if(g==="files"){he();return}(g==="instances"||g==="update"||g==="mcp")&&b(g)},openChanges:({path:g,staged:re}={})=>{nt(g?{path:g,staged:re===!0}:null)},openSettings:g=>{g&&D(g),G(g?"page-content":"nav")}}),[O,nt,he,G,b,D,A,Y]);Ja(cs);const Vt=a.useRef(null);Us(Vt,{leftOpen:O?Z:t,rightOpen:i,leftWidth:()=>O?ie.width:I.current?.offsetWidth||window.innerWidth*.72,rightWidth:()=>O?ue.width:y.current?.offsetWidth||window.innerWidth,onLeftProgress:g=>{if(L.current=g,O){kn({inner:j},g,ie.width,"left");return}xn({drawer:I,scrim:P},"left",g)},onRightProgress:g=>{if(z.current=g,O&&H){kn({inner:C},g,ue.width,"right");return}xn({drawer:y,scrim:U},"right",g)},onLeftOpen:()=>{O?Y(!0):A(!0)},onLeftClose:()=>{O?Y(!1):A(!1)},onRightOpen:()=>f(!0),onRightClose:()=>f(!1),onDragStart:g=>{if(_(),g==="left"){L.current=O?Z?1:0:t?1:0,O?wn({shell:ie.asideRef,inner:j}):gn({drawer:I,scrim:P,root:h});return}z.current=i?1:0,O&&H?wn({shell:ue.asideRef,inner:C}):gn({drawer:y,scrim:U,root:x})},onDragEnd:(g,re)=>{if(g==="left"){const Ue=typeof re=="boolean"?re:L.current>.5;if(L.current=Ue?1:0,O){const Gt=Sn({shell:ie.asideRef,inner:j},Ue,ie.width,"left");Gt!==void 0&&E.current.push(Gt)}else vn("left",Ue,{drawer:I,scrim:P,root:h});return}const yt=typeof re=="boolean"?re:z.current>.5;if(z.current=yt?1:0,O&&H){const Ue=Sn({shell:ue.asideRef,inner:C},yt,ue.width,"right");Ue!==void 0&&E.current.push(Ue)}else vn("right",yt,{drawer:y,scrim:U,root:x})}});const us=a.useCallback(()=>M?(v(!1),!0):s?(ce(),!0):i?(B(),!0):t?(A(!1),!0):!1,[s,ce,B,M,t,v,A,i]);yr(us);const mt=O?"dialog":"fullscreen";return n.jsx(br,{actions:ls,children:n.jsxs("div",{className:"oc-mobile-app-shell main-content-safe-area relative flex h-[100dvh] flex-row bg-background text-foreground","data-page-scroll-lock":"true",children:[O?n.jsxs("aside",{ref:ie.asideRef,className:K("relative flex h-full shrink-0 flex-col overflow-hidden border-r border-border/70 bg-sidebar motion-reduce:transition-none",!Z&&"border-r-0"),style:{width:Ve,minWidth:Ve,maxWidth:Ve,"--oc-ipad-sidebar-width":`${ie.width}px`,overflowX:"clip",paddingTop:"var(--oc-safe-area-top, 0px)"},inert:!Z,"data-page-scroll-lock":"true",children:[n.jsx("div",{ref:j,className:K("flex h-full shrink-0 flex-col",ie.isResizing&&"pointer-events-none",!Z&&"pointer-events-none select-none"),style:{width:"var(--oc-ipad-sidebar-width)",overflowX:"hidden",transform:ie.isResizing||rs.slidIn?"translateX(0)":"translateX(-100%)",transition:ie.isResizing?"none":"transform 200ms cubic-bezier(0.22, 1, 0.36, 1)"},children:n.jsx(de,{children:n.jsx(pn,{open:Z,variant:"sidebar",onOpenChange:os})})}),Z?n.jsx(jn,{side:"left",isResizing:ie.isResizing,ariaLabel:"Resize left panel",handleProps:ie.handleProps}):null]}):null,n.jsxs("div",{className:"relative flex h-full min-w-0 flex-1 flex-col","data-page-scroll-lock":"true",children:[O?n.jsxs(n.Fragment,{children:[n.jsx(Bs,{}),n.jsx($s,{onToggleRightDrawer:is,rightDrawerOpen:i,tabletWorkspaceTab:p,onSelectTabletWorkspaceTab:as,tabletGitHubTabsAvailable:pe})]}):n.jsx(Ma,{onOpenSessions:()=>A(!0),onOpenWorkspace:()=>f(!0)}),n.jsx("main",{ref:Vt,className:"relative min-h-0 flex-1 overflow-hidden","data-page-scroll-lock":"true",style:{touchAction:"pan-x pan-y"},children:n.jsx("div",{className:"h-full w-full",children:n.jsx(de,{children:n.jsx(ni,{})})})})]}),O?null:n.jsx(pn,{open:t,onOpenChange:A,drawerRefExternal:I,scrimRefExternal:P,rootRefExternal:h}),O?n.jsxs("aside",{ref:ue.asideRef,className:K("relative flex h-full shrink-0 flex-col overflow-hidden border-l border-border/70 bg-background motion-reduce:transition-none",!ge&&"border-l-0"),style:{width:ge,minWidth:ge,maxWidth:ge,"--oc-ipad-sidebar-width":`${ue.width}px`,overflowX:"clip",paddingTop:"var(--oc-safe-area-top, 0px)"},inert:!ge,"data-page-scroll-lock":"true",children:[n.jsx("div",{ref:C,className:K("flex h-full min-h-0 shrink-0 flex-col transition-opacity duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",ue.isResizing&&"pointer-events-none",!ge&&"pointer-events-none select-none opacity-0"),style:{width:"var(--oc-ipad-sidebar-width)",overflowX:"hidden",transform:ge?"translateX(0)":"translateX(100%)",transition:ue.isResizing?"none":"transform 200ms cubic-bezier(0.22, 1, 0.36, 1), opacity 200ms cubic-bezier(0.22, 1, 0.36, 1)"},children:n.jsx(de,{children:n.jsx(yn,{open:i,onClose:B,tab:p,onTabChange:d,pendingChangesDiff:k,variant:Ht?"panel":"drawer",githubTabsAvailable:pe,drawerRefExternal:y,scrimRefExternal:U,rootRefExternal:x})})}),ge?n.jsx(jn,{side:"right",isResizing:ue.isResizing,ariaLabel:"Resize right panel",handleProps:ue.handleProps}):null]}):n.jsx(yn,{open:i,onClose:B,tab:p,onTabChange:d,pendingChangesDiff:k,githubTabsAvailable:pe,drawerRefExternal:y,scrimRefExternal:U,rootRefExternal:x}),s==="instances"&&X?n.jsx(St,{open:!0,variant:mt,dialogAlign:"app",onClose:ce,ariaLabel:"Instances",title:"Instances",children:n.jsx(La,{onConnect:ce,onActiveConnectionDeleted:e})}):null,s==="settings"?n.jsx(St,{open:!0,variant:mt,dialogAlign:"app",onClose:ce,ariaLabel:"Settings",headerless:!0,children:n.jsx(de,{children:n.jsx(Wr,{forceMobile:!O,isWindowed:!0,initialMobileStage:m,onClose:ce})})}):null,s==="update"?n.jsx(St,{open:!0,variant:mt,dialogAlign:"app",onClose:ce,ariaLabel:"Update",title:"Update",children:n.jsx(de,{children:n.jsx("div",{className:"h-full overflow-auto px-5 py-4",children:n.jsx(Hr,{initialUpdateDialogOpen:!0})})})}):null,n.jsx(de,{children:n.jsx(Ks,{})})]})})},ri=8,ai=6e4,jt=[1e3,2e3,4e3,8e3,15e3,3e4,3e4,3e4],ii=(e,t)=>{if(t?.offline||t?.hidden)return ai;if(e<=0)return jt[0];const r=Math.min(e-1,jt.length-1);return jt[r]??3e4},je=()=>typeof navigator<"u"&&typeof navigator.onLine=="boolean"?!navigator.onLine:!1,we=()=>typeof document<"u"&&typeof document.visibilityState=="string"?document.visibilityState==="hidden":!1;class oi{constructor(t,r,s=()=>""){this.probe=t,this.callbacks=r,this.getRuntimeIdentity=s}generation=0;attempt=0;timer=null;wakeCleanup=null;running=!1;exhausted=!1;probingGeneration=null;get currentGeneration(){return this.generation}get currentAttempt(){return this.attempt}get isRunning(){return this.running&&!this.exhausted}start(){this.startCycle(!1)}startCycle(t){this.clearTimer(),this.generation+=1,this.attempt=0,this.exhausted=!1,this.running=!0,t?this.runAttempt(this.generation):this.scheduleNext(this.generation)}retryNow(){if(this.exhausted){if(je()||we())return;this.startCycle(!0);return}this.running&&(this.clearTimer(),this.runAttempt(this.generation))}cancel(){this.generation+=1,this.running=!1,this.exhausted=!1,this.attempt=0,this.probingGeneration=null,this.clearTimer()}async probeOnce(){if(this.running||this.exhausted||this.probingGeneration!==null||je()||we())return null;const t=this.generation;this.probingGeneration=t;const r=this.getRuntimeIdentity();let s;try{s=await this.probe()}catch{s="unreachable"}finally{this.probingGeneration===t&&(this.probingGeneration=null)}return t!==this.generation||this.getRuntimeIdentity()!==r?null:s}clearTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.wakeCleanup&&(this.wakeCleanup(),this.wakeCleanup=null)}scheduleNext(t){if(t!==this.generation||!this.running||this.exhausted)return;if(this.attempt>=ri){this.exhausted=!0,this.running=!1,this.callbacks.onExhausted();return}const r=this.attempt+1,s=ii(r,{offline:je(),hidden:we()});this.callbacks.onAttempt?.(r,s);const o=()=>{je()||we()||t===this.generation&&(this.clearTimer(),this.runAttempt(t))},i=()=>o(),l=()=>{typeof document<"u"&&document.visibilityState==="visible"&&o()};typeof window<"u"&&window.addEventListener("online",i),typeof document<"u"&&document.addEventListener("visibilitychange",l),this.wakeCleanup=()=>{typeof window<"u"&&window.removeEventListener("online",i),typeof document<"u"&&document.removeEventListener("visibilitychange",l)},this.timer=setTimeout(()=>{if(this.timer=null,this.wakeCleanup?.(),this.wakeCleanup=null,!(t!==this.generation||!this.running||this.exhausted)){if(je()||we()){this.scheduleNext(t);return}this.runAttempt(t)}},s)}async runAttempt(t){if(t!==this.generation||!this.running||this.exhausted||this.probingGeneration===t)return;if(je()||we()){this.scheduleNext(t);return}this.probingGeneration=t;const r=this.getRuntimeIdentity();let s;try{s=await this.probe()}catch{s="unreachable"}finally{this.probingGeneration===t&&(this.probingGeneration=null)}if(t===this.generation&&this.getRuntimeIdentity()===r){if(s==="switched"||s==="unchanged"){this.running=!1,this.clearTimer(),this.callbacks.onHealthy(s);return}if(s==="needs-login"){this.running=!1,this.clearTimer(),this.callbacks.onAuthExpired();return}if(s==="no-connection"){this.running=!1,this.clearTimer(),this.callbacks.onNoConnection();return}this.attempt+=1,this.scheduleNext(t)}}}function li(e=2500){const{uiFont:t}=gr(),[r,s]=a.useState(!1);return a.useEffect(()=>{let o=!1;const i=()=>{o||s(!0)},l=()=>{requestAnimationFrame(()=>requestAnimationFrame(i))},c=Promise.all([xr(t).catch(()=>{}),document.fonts?.ready?.then(()=>{}).catch(()=>{})??Promise.resolve(),qr.catch(()=>{})]).then(()=>{}),u=new Promise(d=>{window.setTimeout(d,e)});return Promise.race([c,u]).then(l),()=>{o=!0}},[t,e]),r}const ci=()=>{if(typeof window>"u")return;const e=window.__PICHAMBER_APNS_ENV__;if(e==="development")return"sandbox";if(e==="production")return"production"},ui=()=>{if(typeof window>"u")return!1;const t=window.Capacitor?.getPlatform?.();return t==="ios"||t==="android"},di=e=>{const{enabled:t}=e,r=Ie(o=>o.nativeNotificationsEnabled),s=a.useRef(null);a.useEffect(()=>{if(!t||!r||!ui())return;let o=!1;const i=[];return Ce(()=>import("./vendor-capacitor-push-notifications-KNe1zSBF.js"),__vite__mapDeps([87,86])).then(async({PushNotifications:l})=>{if(o)return;let c=await l.checkPermissions().catch(()=>null);if(c?.receive!=="granted"&&(c=await l.requestPermissions().catch(()=>null)),c?.receive!=="granted")return;const u=await l.addListener("registration",p=>{s.current=p.value,Et()?.push?.registerApnsToken?.({token:p.value,platform:Rn(),environment:ci()})}),d=await l.addListener("registrationError",p=>{console.warn("[Push] Native registration error:",p)});if(await l.register().catch(()=>{}),o){u.remove(),d.remove();return}i.push(()=>{u.remove()},()=>{d.remove()})}).catch(()=>{}),()=>{o=!0,i.forEach(l=>l())}},[t,r]),a.useEffect(()=>{if(r)return;const o=s.current;if(!o)return;s.current=null,Et()?.push?.unregisterApnsToken?.({token:o})},[r])},fi=1e3;function pi({apis:e}){const t=ke(b=>b.initializeApp),r=ke(b=>b.isInitialized),s=ke(b=>b.isConnected),o=ke(b=>b.connectionPhase),i=ke(b=>b.providers.length),l=ke(b=>b.loadProviders),c=In(b=>b.currentDirectory),u=me(b=>b.error),d=me(b=>b.clearError),p=Ie(b=>b.setIsMobile),[m,S]=a.useState(0),[k,w]=a.useState(0),[E,_]=a.useState(!1),[I,P]=a.useState("idle"),h=vr(),y=a.useRef(null),U=a.useRef(I);U.current=I;const[x,j]=a.useState("pending"),[C,L]=a.useState(null),z=a.useMemo(()=>Ae(),[]),[,A]=a.useReducer(b=>b+1,0),f=a.useMemo(()=>Dn(),[]),D=a.useRef(0),M=a.useRef(0),v=a.useRef(!1);a.useEffect(()=>{const b=new oi(()=>$t(),{onHealthy:B=>{if(P("idle"),ve(!1),B==="unchanged"){ke.getState().initializeApp();const G=ke.getState();G.providers.length===0&&G.loadProviders({source:"mobileApp:recovery"})}},onAuthExpired:()=>{P("idle"),ve(!1),L({kind:"auth-expired",label:Ae()??""}),Ne({apiBaseUrl:"",clientToken:null,runtimeKey:"mobile-disconnected"}),S(B=>B+1)},onNoConnection:()=>{P("idle"),ve(!1),Ne({apiBaseUrl:"",clientToken:null,runtimeKey:"mobile-disconnected"}),S(B=>B+1)},onExhausted:()=>{P("exhausted")}},()=>`${fe()}|${ae()}`);return y.current=b,()=>{b.cancel(),y.current=null}},[]);const N=a.useCallback(()=>{if(!f||!ae())return;const b=y.current;if(b){if(b.isRunning){b.retryNow();return}P("recovering"),ve(!0),b.start()}},[f]),J=a.useCallback(()=>{y.current?.cancel(),P("idle"),ve(!1)},[]),X=a.useCallback(b=>{y.current?.cancel(),P("idle"),ve(!1),b&&L(b),Ne({apiBaseUrl:"",clientToken:null,runtimeKey:"mobile-disconnected"}),S(B=>B+1)},[]),V=a.useCallback(()=>{const b=Date.now();b-D.current>=fi&&(D.current=b,window.dispatchEvent(new Event("pichamber:system-resume")))},[]),ne=a.useCallback(()=>{const b=ae(),B=M.current+1;if(M.current=B,!b){if(v.current)return;v.current=!0,at().catch(()=>{}).finally(()=>{v.current=!1});return}if(y.current?.isRunning){y.current.retryNow(),V();return}if(U.current==="exhausted"){if(je()||we())return;P("recovering"),ve(!0),y.current?.start(),V();return}if(je()||we()){N();return}const G=()=>{t(),i===0&&l({source:"mobileApp:nativeResume"})},O=y.current;O&&(O.probeOnce().then(H=>{if(H!==null&&M.current===B){if(H==="no-connection"){X(null);return}if(H==="needs-login"){X({kind:"auth-expired",label:Ae()??""});return}if(H==="unreachable"){N();return}H!=="switched"&&G()}}),V())},[X,V,t,l,i,N]);wr(),kr(ne),a.useEffect(()=>gs(),[]),a.useEffect(()=>{if(!f)return;let b;const B=()=>{if(y.current?.isRunning){y.current.retryNow();return}if(U.current==="exhausted"){if(we())return;P("recovering"),ve(!0),y.current?.start();return}window.clearTimeout(b),b=window.setTimeout(()=>ne(),1500)};return window.addEventListener("online",B),()=>{window.removeEventListener("online",B),window.clearTimeout(b)}},[f,ne]),a.useEffect(()=>{if(f)return xs(()=>{ae()&&X({kind:"auth-expired",label:Ae()??""})})},[X,f]),a.useEffect(()=>(qt(e),()=>qt(null)),[e]),a.useEffect(()=>vs(b=>{if(!!b.runtimeKey&&b.runtimeKey===b.previousRuntimeKey){Hs(),A();return}y.current?.cancel(),P("idle"),ve(!1),Fs(b),w(G=>G+1),S(G=>G+1)}),[]),a.useEffect(()=>{Pn()},[k]),a.useEffect(()=>{if(!f||s||ae()){j("done");return}let b=!1;return j("attempting"),at().catch(()=>({status:"no-candidate"})).then(B=>{b||(B.status==="unreachable"?L({kind:"unreachable",label:B.label}):B.status==="needs-login"&&L({kind:"auth-expired",label:B.label}),j("done"))}),()=>{b=!0}},[]),a.useEffect(()=>{if(!f||!ae())return;let b=!1;const B=O=>{O&&L(O),Ne({apiBaseUrl:"",clientToken:null,runtimeKey:"mobile-disconnected"}),S(H=>H+1)},G=y.current;if(G)return G.probeOnce().then(async O=>{if(b||O===null||O==="switched"||O==="unchanged")return;const H=Ae();if(O==="needs-login"){B({kind:"auth-expired",label:H??""});return}if(O==="unreachable"){B(H?{kind:"unreachable",label:H}:null);return}const se=await at().catch(()=>({status:"no-candidate"}));b||se.status==="connected"||(se.status==="needs-login"?B({kind:"auth-expired",label:se.label}):se.status==="unreachable"?B({kind:"unreachable",label:se.label}):B(null))}),()=>{b=!0}},[]),a.useEffect(()=>{p(!0)},[p]),a.useEffect(()=>{f&&!ae()||t()},[m,t,f]),a.useEffect(()=>{s&&i===0&&l({source:"mobileApp:recovery"})},[s,l,i]);const R=a.useRef(!1),[W,te]=a.useState(f);a.useEffect(()=>{if(!f||!s||R.current)return;if(me.getState().currentSessionId){R.current=!0,te(!1);return}const b=fe(),B=Sr(b);if(!B){R.current=!0,te(!1);return}const G=ws(B.directory??null);if(!G){R.current=!0,te(!1);return}const O=Ge();let H=0;try{H=O.getRuntimeGeneration()}catch{H=0}let se=!1;const T=window.setTimeout(()=>te(!1),6e3);return(async()=>{let $=null;try{$=await jr([G])}catch{$=null}if(se)return;if(!$){te(!1);return}const Y=Ge();let Z=H;try{Z=Y.getRuntimeGeneration()}catch{Z=H}const be=aa({persisted:B,persistedDirectory:G,stale:$.stale,ready:$.readyDirectories.has(G),catalog:$.catalog,runtimeKey:fe(),capturedRuntimeKey:b,storeIdentityMatches:Y===O,generationMatches:Z===H});if(be.action==="wait"){te(!1);return}if(R.current=!0,be.action==="clear"){Cr(b),te(!1);return}const he=me.getState();if(fe()!==b||Ge()!==O){te(!1);return}he.currentSessionId||he.setCurrentSession(be.sessionId,be.directory),te(!1)})(),()=>{se=!0,window.clearTimeout(T)}},[m,s,f]),a.useEffect(()=>{s&&Ge().focusProject(c,ks(c))},[c,s]),a.useEffect(()=>{if(!u)return;const b=window.setTimeout(()=>d(),5e3);return()=>window.clearTimeout(b)},[d,u]),a.useEffect(()=>{if(f&&I!=="idle"){_(!1);return}if(!(!s&&(f?!!ae():!0))){_(!1);return}const B=window.setTimeout(()=>{_(!0)},f?4e3:8e3);return()=>window.clearTimeout(B)},[s,f,m,I,k]),Er(),Ss({enabled:!0}),Vs(),di({enabled:f&&s}),Ya({ready:f&&s&&r});const Te=li(),ye=!s&&o==="reconnecting",pe=!!ae(),ce=f&&pe&&I!=="idle";return Te?f&&!ce&&(!pe||!s&&!ye)?pe?n.jsx("main",{className:"flex min-h-dvh items-center justify-center bg-background px-6 text-center text-foreground",children:n.jsxs("div",{className:"flex max-w-sm flex-col items-center gap-4",children:[n.jsx(Se,{width:120,height:120,isAnimated:!E}),E?n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"space-y-2",children:[n.jsx("h1",{className:"typography-h3 text-foreground",children:"Unable to reach server"}),n.jsx("p",{className:"typography-body text-muted-foreground",children:"Could not connect to the saved server. Check that it is running, or pick another instance."})]}),n.jsx(le,{type:"button",variant:"outline",onClick:()=>{X(null)},children:"Use another server"})]}):null]})}):x!=="done"?n.jsxs("main",{className:"relative flex min-h-dvh items-center justify-center bg-background text-foreground",children:[n.jsx(Se,{width:120,height:120,isAnimated:!0}),z?n.jsxs("div",{className:"absolute inset-x-0 top-[calc(50%+84px)] flex flex-col items-center gap-0.5 px-6 text-center",children:[n.jsx("p",{className:"typography-small text-muted-foreground",children:"Connecting to device:"}),n.jsx("div",{className:"flex justify-center",children:n.jsx(Rr,{text:z,showElapsed:!1})})]}):null]}):n.jsx(n.Fragment,{children:n.jsx(Ia,{onConnected:()=>S(b=>b+1),notice:C})}):!s&&!ye?E?n.jsx("main",{className:"flex min-h-dvh items-center justify-center bg-background px-6 text-center text-foreground",children:n.jsxs("div",{className:"max-w-sm space-y-3",children:[n.jsx("h1",{className:"typography-h3 text-foreground",children:"Unable to reach server"}),n.jsx("p",{className:"typography-body text-muted-foreground",children:"We could not verify the UI session. If you're opening PiChamber from another device on your local network, make sure Desktop Network Access is enabled on the desktop app and use the LAN address shown in Settings."})]})}):n.jsx("main",{className:"flex min-h-dvh items-center justify-center bg-background text-foreground",children:n.jsx(Se,{width:120,height:120,isAnimated:!0})}):n.jsx(de,{children:n.jsx(Tr,{children:n.jsxs(Nr,{apis:e,children:[n.jsx(Ir,{}),n.jsx(Pr,{delayDuration:300,skipDelayDuration:150,children:n.jsxs(Gs,{children:[n.jsx(Xs,{}),n.jsxs("div",{className:"h-full bg-background text-foreground",children:[f&&W?n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-background",children:n.jsx(Se,{width:120,height:120,isAnimated:!0})}):null,n.jsx(Ar,{embeddedBackgroundWorkEnabled:r&&!h}),ce?n.jsxs("div",{role:"status","aria-live":"polite",className:"pointer-events-none fixed inset-x-0 top-[calc(var(--oc-safe-area-top,0px)+var(--oc-header-height,56px)+10px)] z-40 flex justify-center",children:[n.jsx("span",{className:"flex size-11 items-center justify-center rounded-full border border-border/70 bg-[var(--surface-elevated)] text-[var(--surface-elevated-foreground)] shadow-sm",children:n.jsx(Se,{width:24,height:24,isAnimated:!0})}),n.jsx("span",{className:"sr-only",children:I==="exhausted"?"Server unreachable":"Reconnecting…"})]}):null,n.jsx(ra,{}),n.jsx(si,{onActiveConnectionDeleted:()=>{J(),Ne({apiBaseUrl:"",clientToken:null,runtimeKey:"mobile-disconnected"}),S(b=>b+1)}}),n.jsx(qs,{}),n.jsx(Js,{}),n.jsx(_r,{position:"top-center",offset:"calc(var(--oc-safe-area-top, 0px) + 16px)"}),n.jsx(Dr,{})]})]})})]})},k)}):n.jsx("main",{className:"flex min-h-dvh items-center justify-center bg-background text-foreground",children:n.jsx(Se,{width:120,height:120,isAnimated:!0})})}const hi=()=>{(async()=>{try{await Promise.all([Pn(),js()])}catch(e){console.error("[mobile-main] settings init failed:",e)}Ur(),Br(),Cs()})().finally(()=>{Jr()})};function mi(e){window.__PICHAMBER_SURFACE__="mobile",Mr(),hi(),sa(),Lr();const t=document.getElementById("root");if(!t)throw new Error("Root element not found");const s=window.Capacitor?.isNativePlatform?.()===!0||window.location.protocol==="capacitor:",o=e??Et();if(!o)throw new Error("Runtime APIs not registered");const i=s?{...o,notifications:{notify:async()=>!1,canNotify:()=>!1}}:o,l=n.jsx(pi,{apis:i});ds.createRoot(t).render(n.jsx(Ct.StrictMode,{children:n.jsx(Or,{children:n.jsx(Ys,{children:s?l:n.jsx(zr,{children:l})})})}))}const Ii=Object.freeze(Object.defineProperty({__proto__:null,renderMobileApp:mi},Symbol.toStringTag,{value:"Module"}));export{Ni as m,Ii as r};
|