@yuriai/web 0.2.0-beta.8 → 0.2.0

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.
Files changed (163) hide show
  1. package/README.md +4 -0
  2. package/dist/assets/{AgentAvatar-CMpCBSy_.js → AgentAvatar-BeM4lXfE.js} +1 -1
  3. package/dist/assets/{AssistantView-BlPMro6O.js → AssistantView-C67p8xuJ.js} +3 -3
  4. package/dist/assets/DiagramView-DPcsLliB.js +1 -0
  5. package/dist/assets/{FadeInOnReveal-ANDXEIE7.js → FadeInOnReveal-B8BCjwPb.js} +1 -1
  6. package/dist/assets/GuiPluginLoadingNotice-DjO_uy_0.js +1 -0
  7. package/dist/assets/GuiPluginSurface-DYQotofG.js +1 -0
  8. package/dist/assets/GuiPluginWindow-jUuZl9JF.js +1 -0
  9. package/dist/assets/{Icon-DgrlwLKs.js → Icon-DofI60x2.js} +1 -1
  10. package/dist/assets/{ImageLoadingPlaceholder-1ACRI1jC.js → ImageLoadingPlaceholder-7jM-y96Q.js} +1 -1
  11. package/dist/assets/{LoadingImage-CVpLgSVp.js → LoadingImage-DV6Neoja.js} +1 -1
  12. package/dist/assets/MarkdownRenderer-Qqpr2mPH.js +2 -0
  13. package/dist/assets/{MarkdownRendererImpl-TDDDij0i.js → MarkdownRendererImpl-NsSkRpGi.js} +2 -2
  14. package/dist/assets/{MarkstreamRendererImpl-C6-UfI7p.js → MarkstreamRendererImpl-DQpFxOfX.js} +1 -1
  15. package/dist/assets/{MobileDetailNavigation-BdEfSCm4.js → MobileDetailNavigation-BaXXR9xC.js} +1 -1
  16. package/dist/assets/MobileResizableSheet-CuRgnS-k.js +1 -0
  17. package/dist/assets/MobileShareBridge-CbmVqEAx.js +4 -0
  18. package/dist/assets/MobileTabPageHeader-BIAkmiCb.js +2 -0
  19. package/dist/assets/{MultiRunWindow-v4oq9X77.js → MultiRunWindow-B_ptQuKi.js} +1 -1
  20. package/dist/assets/OnboardingScreen-hvLlaoKt.js +1 -0
  21. package/dist/assets/{OverlayScrollbar-bByT588g.js → OverlayScrollbar-Bi17Olmj.js} +1 -1
  22. package/dist/assets/SettingsView-BbzGMK_z.js +26 -0
  23. package/dist/assets/{SettingsWindow-C7EEBdGt.js → SettingsWindow-h25-n1wB.js} +1 -1
  24. package/dist/assets/TerminalView-DCQATs7S.js +8 -0
  25. package/dist/assets/{ToolOutputDialog-zF7xpkS8.js → ToolOutputDialog-Bm2kSYCn.js} +3 -3
  26. package/dist/assets/{YuriLogo-Qr_mhaKp.js → YuriLogo-D9cfwLdW.js} +1 -1
  27. package/dist/assets/appThemeRegistry-DNb0Emjp.js +1 -0
  28. package/dist/assets/{assistant-attachment-cache-DWMcn4cE.js → assistant-attachment-cache-Ul88TuFO.js} +1 -1
  29. package/dist/assets/button-CT7WL0lp.js +1 -0
  30. package/dist/assets/{capgoAdapter-Bh3XnAlW.js → capgoAdapter-vYSlprFh.js} +1 -1
  31. package/dist/assets/clipboard-Bj6jZiuP.js +1 -0
  32. package/dist/assets/{collapsible-CwLF0o1c.js → collapsible-UDWFNcbF.js} +1 -1
  33. package/dist/assets/desktop-CfMDfs6c.js +1 -0
  34. package/dist/assets/{desktopHosts-CjH4TGh8.js → desktopHosts-BEzVZGiW.js} +1 -1
  35. package/dist/assets/{desktopRelayRestore-BLJo3sm7.js → desktopRelayRestore-aNSNYVEB.js} +1 -1
  36. package/dist/assets/device-BDrEmxBm.js +2 -0
  37. package/dist/assets/{diagram-BIYywJNf.js → diagram-BxF_wECt.js} +1 -1
  38. package/dist/assets/dialog-BpsbJk8Y.js +1 -0
  39. package/dist/assets/download-progress-MobTWf23.js +1 -0
  40. package/dist/assets/dropdown-menu.styles-MkqoyFTv.js +1 -0
  41. package/dist/assets/{es-BIEtnCM1.js → es-iuy57SFI.js} +1 -1
  42. package/dist/assets/{fileMentionTouchSelection-B9osqnyB.js → fileMentionTouchSelection-BkCvPXYn.js} +1 -1
  43. package/dist/assets/{fileQueries-DbUx7NwP.js → fileQueries-voABZL1r.js} +1 -1
  44. package/dist/assets/{fileReferenceActions-DuYvTiGf.js → fileReferenceActions-CgsqIeIM.js} +1 -1
  45. package/dist/assets/{fr-CYbm8LUE.js → fr-LyrJa2Qb.js} +1 -1
  46. package/dist/assets/gitApi-DdK0IlIM.js +10 -0
  47. package/dist/assets/gitApiHttp-BhcxUxqo.js +7 -0
  48. package/dist/assets/gui-CTKa6rbU.js +1 -0
  49. package/dist/assets/host-1RDqqL9w.js +1 -0
  50. package/dist/assets/{image-loading-Ctpxfqla.js → image-loading-Bqi69xpy.js} +1 -1
  51. package/dist/assets/{input-BVgNVYou.js → input-D86Oqf3B.js} +1 -1
  52. package/dist/assets/insertionBoundaries-B28Dk8Dp.js +1 -0
  53. package/dist/assets/{ja-DJq4-rL4.js → ja-QqNYiTeY.js} +1 -1
  54. package/dist/assets/{ko-DUjfbG7o.js → ko-CL-s2hwZ.js} +1 -1
  55. package/dist/assets/main-BqrjAS06.js +169 -0
  56. package/dist/assets/main-hwetTT7m.js +2 -0
  57. package/dist/assets/{markdownHeightCache-BceTKVDK.js → markdownHeightCache-DB_NzPGt.js} +1 -1
  58. package/dist/assets/mcpQueries-DTbwg6z6.js +1 -0
  59. package/dist/assets/miniChat-BMNB2ztD.js +2 -0
  60. package/dist/assets/mobile-BdQMBg5f.js +2 -0
  61. package/dist/assets/{mobileBackNavigation-BXe_06C5.js → mobileBackNavigation-CaxJVILv.js} +1 -1
  62. package/dist/assets/multirun-CpWGs_sU.js +3 -0
  63. package/dist/assets/native-BMAEg2E6.js +1 -0
  64. package/dist/assets/native-config-BfIzLvxi.js +1 -0
  65. package/dist/assets/native-errors-06if6eu-.js +1 -0
  66. package/dist/assets/{persistence-D-W3L37Z.js → persistence-Ck0wskDR.js} +1 -1
  67. package/dist/assets/{pl-CBlSVV3-.js → pl-AKGY_sFU.js} +1 -1
  68. package/dist/assets/platform-kv0OsX45.js +1 -0
  69. package/dist/assets/{projectMeta-B_eftQTB.js → projectMeta-DZFuF8rn.js} +1 -1
  70. package/dist/assets/{pt-BR-CY8I_bEt.js → pt-BR-BFRFGU_b.js} +1 -1
  71. package/dist/assets/{queryRuntime-BuRnpVtK.js → queryRuntime-CpsVmMzy.js} +1 -1
  72. package/dist/assets/readiness-CdLdF_Pp.js +1 -0
  73. package/dist/assets/reasoning-projection-client-BEhVknv9.js +1 -0
  74. package/dist/assets/renderElectronMiniChatApp-C_MTyWYO.js +2 -0
  75. package/dist/assets/renderMobileApp-B-tmvQxg.js +28 -0
  76. package/dist/assets/runtime-fetch-BclMrQHc.js +1 -0
  77. package/dist/assets/{runtime-file-download-CwP-HoXN.js → runtime-file-download-J_Vcm3tT.js} +1 -1
  78. package/dist/assets/{runtime-file-resource-h3yIw4HU.js → runtime-file-resource-Disaet9c.js} +1 -1
  79. package/dist/assets/runtime-switch-WzPG6NMR.js +1 -0
  80. package/dist/assets/runtimeConfig-BA2rxwwc.js +2 -0
  81. package/dist/assets/runtimeEndpointReset-BxlxF5X2.js +149 -0
  82. package/dist/assets/{scheduledTaskNavigation-DFa4lhwN.js → scheduledTaskNavigation-C6FKpwPD.js} +1 -1
  83. package/dist/assets/scheduling-DCTDfxV-.js +1 -0
  84. package/dist/assets/{sessionChangeSummary-D9-zyniS.js → sessionChangeSummary-2Bt21ayX.js} +1 -1
  85. package/dist/assets/sessionLookup-C1nNfbh0.js +1 -0
  86. package/dist/assets/{sortable-tabs-strip-DTWwlndW.js → sortable-tabs-strip-CSXgXPyP.js} +1 -1
  87. package/dist/assets/speechSettingsQueries-B6_7YC3O.js +4 -0
  88. package/dist/assets/src-D3pZqEZM.css +2 -0
  89. package/dist/assets/{store-BhjP3zxz.js → store-CGMD02tA.js} +2 -2
  90. package/dist/assets/terminalApi-B_oHorrS.js +1 -0
  91. package/dist/assets/{textarea-BLvbQAIG.js → textarea-CMvxcQhR.js} +1 -1
  92. package/dist/assets/{tooltip-jf98dFQe.js → tooltip-CnIKZ6bg.js} +1 -1
  93. package/dist/assets/types-CfsdaRmC.js +2 -0
  94. package/dist/assets/{uk-DZVrg2WI.js → uk-C21_nQhw.js} +1 -1
  95. package/dist/assets/{useAppFontEffects-EC1-6ksC.js → useAppFontEffects-dB996j53.js} +51 -51
  96. package/dist/assets/{useAssistantUIStore-D7JZlg_Q.js → useAssistantUIStore-4a569vpy.js} +1 -1
  97. package/dist/assets/useDesktopWindowControlsLayout-DyTyv6Rk.js +1 -0
  98. package/dist/assets/useEffectiveDirectory-Cxkuxd4u.js +1 -0
  99. package/dist/assets/{useFontPreferences-qIHM7E9c.js → useFontPreferences-BPTEYhfn.js} +1 -1
  100. package/dist/assets/useMobileNavigationStore-M61L6rKt.js +417 -0
  101. package/dist/assets/useUIStore-DqtgX2FB.js +1 -0
  102. package/dist/assets/{useWorkerHighlightedLines-Bfa_CBGR.js → useWorkerHighlightedLines-BjUDrhqD.js} +1 -1
  103. package/dist/assets/{vendor-effect-DXlObQuU.js → vendor-effect-DV9F8PTZ.js} +1 -1
  104. package/dist/assets/vendor-opencode-client-fxfj4IA_.js +12 -0
  105. package/dist/assets/{vendor-opencode-plugin-BglYYlJt.js → vendor-opencode-plugin-CQ5ogY33.js} +1 -1
  106. package/dist/assets/{vendor-solid-js-B2FO7pdm.js → vendor-solid-js-Dmt4_-Zk.js} +1 -1
  107. package/dist/assets/yuri-mark-black-DxEnMyCE.svg +1 -0
  108. package/dist/assets/{zh-CN-b17bGCPK.js → zh-CN-C7PVNr9_.js} +1 -1
  109. package/dist/assets/{zh-TW-DN-AMZ3b.js → zh-TW-DLLoB3-e.js} +1 -1
  110. package/dist/index.html +25 -24
  111. package/dist/mini-chat.html +28 -35
  112. package/dist/mobile.html +31 -24
  113. package/package.json +1 -1
  114. package/server/index.d.ts +2 -0
  115. package/server/index.js +8 -1
  116. package/server/lib/opencode/DOCUMENTATION.md +1 -0
  117. package/server/lib/opencode/gui-plugin-source.js +14 -0
  118. package/server/lib/opencode/gui-plugin-source.test.js +28 -0
  119. package/dist/assets/DiagramView-BKXzTCL8.js +0 -1
  120. package/dist/assets/GuiPluginSurface-BNly6Xlz.js +0 -1
  121. package/dist/assets/GuiPluginWindow-Cfi0SMUy.js +0 -1
  122. package/dist/assets/MarkdownRenderer-CgvK6Tz9.js +0 -2
  123. package/dist/assets/MobileResizableSheet-xE71zG4E.js +0 -1
  124. package/dist/assets/MobileShareBridge-B5WB1WKT.js +0 -4
  125. package/dist/assets/MobileTabPageHeader-BBNJMFBw.js +0 -2
  126. package/dist/assets/OnboardingScreen-BH__JnO0.js +0 -1
  127. package/dist/assets/SettingsView-CvS8W9-A.js +0 -26
  128. package/dist/assets/TerminalView-f9li4Dcm.js +0 -8
  129. package/dist/assets/appThemeRegistry-BKP8vwhk.js +0 -1
  130. package/dist/assets/button-BuhP8T0R.js +0 -1
  131. package/dist/assets/desktop-DpAcrF1h.js +0 -1
  132. package/dist/assets/device-D_NngvEq.js +0 -2
  133. package/dist/assets/dialog-BUEUatKm.js +0 -1
  134. package/dist/assets/dropdown-menu.styles-LCAyXnEk.js +0 -1
  135. package/dist/assets/gitApi-B4bdEdqD.js +0 -10
  136. package/dist/assets/gui-DZ723-fy.js +0 -1
  137. package/dist/assets/host-Bs4ljApp.js +0 -1
  138. package/dist/assets/insertionBoundaries-BY22eMtE.js +0 -1
  139. package/dist/assets/main-AMwJi-py.js +0 -2
  140. package/dist/assets/main-C7jIE2Fj.js +0 -169
  141. package/dist/assets/mcpQueries-BUMvgK26.js +0 -1
  142. package/dist/assets/miniChat-RvuopuxS.js +0 -2
  143. package/dist/assets/mobile-DIHyvbDs.js +0 -2
  144. package/dist/assets/multirun-CQx2I3IZ.js +0 -3
  145. package/dist/assets/native-config-3PInpl5r.js +0 -1
  146. package/dist/assets/platform-BND-ZKbF.js +0 -7
  147. package/dist/assets/readiness-CerJYd9R.js +0 -1
  148. package/dist/assets/renderElectronMiniChatApp-CPBlGAhU.js +0 -2
  149. package/dist/assets/renderMobileApp-CrP_LwLi.js +0 -28
  150. package/dist/assets/runtime-fetch-BAN5Gnnp.js +0 -1
  151. package/dist/assets/runtime-switch-CAZiOV2G.js +0 -1
  152. package/dist/assets/runtimeConfig-fwwvQvAp.js +0 -2
  153. package/dist/assets/runtimeEndpointReset-CEwt353V.js +0 -149
  154. package/dist/assets/sessionLookup-pq3vdPGh.js +0 -1
  155. package/dist/assets/speechSettingsQueries-CCFpfJtJ.js +0 -4
  156. package/dist/assets/src-r07HspQy.css +0 -2
  157. package/dist/assets/terminalApi-rE93RnSc.js +0 -1
  158. package/dist/assets/types-BG8ZDWn4.js +0 -2
  159. package/dist/assets/useDesktopWindowControlsLayout-Cz30O7Tu.js +0 -1
  160. package/dist/assets/useEffectiveDirectory-C8VRrWsr.js +0 -1
  161. package/dist/assets/useMobileNavigationStore-YGHA7SiM.js +0 -417
  162. package/dist/assets/useUIStore-NMQx_cnG.js +0 -1
  163. package/dist/assets/vendor-opencode-client-BcpAhe9I.js +0 -12
@@ -1,8 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{n as t}from"./runtime-fetch-BAN5Gnnp.js";import{_ as n}from"./desktop-DpAcrF1h.js";import{it as r,nt as i,rt as a}from"./vendor-base-ui-CdzJ6My_.js";import{c as o,l as s,n as c}from"./useUIStore-NMQx_cnG.js";import{u as l}from"./fileQueries-DbUx7NwP.js";import{o as u}from"./terminalApi-rE93RnSc.js";import{n as d,r as f,t as p}from"./vendor-ghostty-web-DbBrwBII.js";import{d as m,f as h,r as g,t as _}from"./button-BuhP8T0R.js";import{d as v}from"./useMobileNavigationStore-YGHA7SiM.js";import{n as y}from"./useThemeSystem-8jhE4Zyk.js";import{n as b}from"./Icon-DgrlwLKs.js";import{r as ee}from"./device-D_NngvEq.js";import{t as x}from"./OverlayScrollbar-bByT588g.js";import{n as S}from"./useEffectiveDirectory-C8VRrWsr.js";import{t as C}from"./sortable-tabs-strip-DTWwlndW.js";import{n as w,t as T}from"./useFontPreferences-qIHM7E9c.js";import{r as E}from"./projectActions-BX0cjZoq.js";var D=e(r(),1);function te(e){let{colors:t}=e,n=t.syntax.base;return{background:t.surface.background,foreground:n.foreground,cursor:t.interactive.cursor,cursorAccent:t.surface.background,selectionBackground:t.interactive.selection,selectionForeground:t.interactive.selectionForeground,selectionInactiveBackground:t.interactive.selection+`50`,black:t.surface.muted,red:t.status.error,green:t.status.success,yellow:t.status.warning,blue:n.function,magenta:n.keyword,cyan:n.type,white:n.foreground,brightBlack:n.comment,brightRed:t.status.error,brightGreen:t.status.success,brightYellow:t.status.warning,brightBlue:n.function,brightMagenta:n.keyword,brightCyan:n.type,brightWhite:t.surface.elevatedForeground}}function ne(e,t,n,r,i=!1){return{cursorBlink:!1,cursorStyle:`bar`,fontSize:t,lineHeight:1.15,fontFamily:`${e}, "JetBrainsMonoNL Nerd Font", "FiraCode Nerd Font", "Cascadia Code PL", "Fira Code", "JetBrains Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", "Courier New", monospace`,allowTransparency:!1,theme:{background:n.background,foreground:n.foreground,cursor:n.cursor,cursorAccent:n.cursorAccent,selectionBackground:n.selectionBackground,selectionForeground:n.selectionForeground,black:n.black,red:n.red,green:n.green,yellow:n.yellow,blue:n.blue,magenta:n.magenta,cyan:n.cyan,white:n.white,brightBlack:n.brightBlack,brightRed:n.brightRed,brightGreen:n.brightGreen,brightYellow:n.brightYellow,brightBlue:n.brightBlue,brightMagenta:n.brightMagenta,brightCyan:n.brightCyan,brightWhite:n.brightWhite},scrollback:1e4,ghostty:r,disableStdin:i}}var re=e(i(),1),O=a(),k=null;function A(){return k||=f.load(),k}function ie(e){if(typeof window>`u`)return null;let t=[e,...Array.from(e.querySelectorAll(`*`))],n=null;for(let e of t){let t=window.getComputedStyle(e).overflowY;if(t===`auto`||t===`scroll`){if(e.scrollHeight-e.clientHeight>2)return e;n||=e}}return n}var ae=D.forwardRef(({sessionKey:e,chunks:t,onInput:n,onResize:r,theme:i,fontFamily:a,fontSize:o,className:s,enableTouchScroll:c,autoFocus:l=!0,isVisible:u=!0},f)=>{let{t:_}=h(),v=D.useRef(null),y=D.useRef(null),b=D.useRef(null),ee=D.useRef(null),S=D.useRef(n),C=D.useRef(r),w=D.useRef(null),T=D.useRef(``),E=D.useRef(null),te=D.useRef(!1),k=D.useRef(null),ae=D.useRef(!0),j=D.useRef(null),M=D.useRef(null),oe=D.useRef(0),se=D.useRef(null),N=D.useRef(null),P=D.useRef(!1),F=D.useRef(!1),ce=D.useRef(null),le=D.useRef(null),ue=D.useRef(null),I=D.useRef(``),de=D.useRef(null),fe=D.useRef(!c),pe=D.useRef(u),[,me]=D.useReducer(e=>e+1,0),[he,ge]=D.useReducer(e=>e+1,0);S.current=n,C.current=r;let _e=typeof navigator<`u`&&(/Android/i.test(navigator.userAgent)||navigator.userAgentData?.platform===`Android`),L=!!c;D.useEffect(()=>{if(!c){fe.current=!0,pe.current=u;return}!pe.current&&u&&(fe.current=!1),pe.current=u},[c,u]);let ve=D.useCallback(()=>{if(!L)return;let e=v.current,t=se.current;if(!e)return;let n=[];e.getAttribute(`contenteditable`)===`true`&&n.push(e),n.push(...Array.from(e.querySelectorAll(`[contenteditable="true"]`))),n.forEach(e=>{e.setAttribute(`data-terminal-disabled-contenteditable`,`true`),e.setAttribute(`contenteditable`,`false`),e.setAttribute(`aria-hidden`,`true`),e.tabIndex=-1,e.style.setProperty(`caret-color`,`transparent`),e.style.color=`transparent`,e.style.setProperty(`-webkit-text-fill-color`,`transparent`),e.style.background=`transparent`,e.style.outline=`none`,e.style.boxShadow=`none`,e.style.textShadow=`none`,e.style.setProperty(`user-select`,`none`),e.style.setProperty(`-webkit-user-select`,`none`)}),e.tabIndex=-1,e.removeAttribute(`role`),e.removeAttribute(`aria-multiline`),Array.from(e.querySelectorAll(`textarea`)).forEach(e=>{e.style.setProperty(`caret-color`,`transparent`),e.style.color=`transparent`,e.style.setProperty(`-webkit-text-fill-color`,`transparent`),e.style.background=`transparent`,e.style.border=`0`,e.style.outline=`none`,e.style.boxShadow=`none`,e.style.textShadow=`none`,e.style.fontSize=`0`,e.style.lineHeight=`0`,e!==t&&e.getAttribute(`data-terminal-disabled-input`)!==`true`&&(e.setAttribute(`data-terminal-disabled-input`,`true`),e.setAttribute(`aria-hidden`,`true`),e.tabIndex=-1,e.disabled=!0,e.style.position=`absolute`,e.style.opacity=`0`,e.style.width=`0px`,e.style.height=`0px`,e.style.pointerEvents=`none`,e.style.zIndex=`-1`)})},[L]),R=D.useCallback(e=>{if(de.current===e)return;let t=b.current;if(t)try{if(typeof t.setOption==`function`){t.setOption(`cursorBlink`,e),de.current=e;return}t.options&&(t.options.cursorBlink=e,de.current=e)}catch{}},[]),z=L&&_e,B=D.useCallback((e,t)=>{let n=z?N.current:se.current,r=v.current;if(!n||!r)return;let i=r.getBoundingClientRect(),a=typeof window<`u`?window.innerWidth:i.width,o=typeof window<`u`?window.innerHeight:i.height,s=i.left+i.width/2,c=i.top+i.height-12,l=typeof e==`number`?e:s,u=typeof t==`number`?t:c,d=Math.max(8,Math.min(a-8,l)),f=Math.max(8,Math.min(o-8,u));n.style.left=`${d}px`,n.style.top=`${f}px`,n.style.bottom=``,(n instanceof HTMLTextAreaElement||n instanceof HTMLInputElement)&&(n.disabled=!1,n.readOnly=!1,n.removeAttribute(`disabled`),n.removeAttribute(`readonly`));try{n.focus({preventScroll:!0})}catch{try{n.focus()}catch{}}},[z]),V=D.useCallback(()=>{if(L){B(),R(!0);return}b.current?.focus(),R(!0)},[B,R,L]),H=D.useCallback(e=>e instanceof HTMLTextAreaElement||e instanceof HTMLInputElement?e.value:e.textContent??``,[]),U=D.useCallback(e=>{if(e instanceof HTMLTextAreaElement||e instanceof HTMLInputElement){e.value=``;return}e.textContent=``},[]),ye=D.useCallback(e=>{if(typeof window>`u`||z)return;ue.current!==null&&(window.clearTimeout(ue.current),ue.current=null);let t=0,n=()=>{ue.current=window.setTimeout(()=>{ue.current=null;let r=H(e);if(!r){if(t+=1,t<3){n();return}return}let i=I.current;I.current=r;let a=r.startsWith(i)?r.slice(i.length):r;a&&S.current(a.replace(/\r\n|\r|\n/g,`\r`)),U(e),I.current=``},t===0?0:24)};n()},[U,H,z]);D.useEffect(()=>{let e=v.current;if(!L||!e||c)return;let t=t=>{let n=t.target;if(n&&n.getAttribute(`data-terminal-hidden-input`)!==`true`&&e.contains(n)){try{n.blur()}catch{}B()}};return e.addEventListener(`focusin`,t,!0),()=>{e.removeEventListener(`focusin`,t,!0)}},[c,L,B]);let W=D.useCallback(()=>{let e=b.current;if(!e||typeof e.getSelection!=`function`)return``;let t=e.getSelection();return typeof t==`string`?t:``},[]),be=D.useCallback(()=>{if(typeof window>`u`)return``;let e=window.getSelection();if(!e)return``;let t=e.toString();if(!t.trim())return``;let n=v.current;if(!n)return``;let r=e.anchorNode,i=e.focusNode;return r&&!n.contains(r)||i&&!n.contains(i)?``:t},[]),xe=D.useCallback(async()=>{if(typeof document>`u`)return;let e=W()||be();e.trim()&&await m(e)},[be,W]),Se=D.useCallback(()=>W().trim()?!0:!!be().trim(),[be,W]);D.useEffect(()=>{if(typeof window>`u`)return;let e=e=>{Se()&&(e.preventDefault(),xe())};return window.addEventListener(`yuri:copy`,e),()=>{window.removeEventListener(`yuri:copy`,e)}},[xe,Se]);let G=D.useCallback(()=>{T.current=``,E.current!==null&&typeof window<`u`&&window.cancelAnimationFrame(E.current),E.current=null,te.current=!1,k.current=null},[]),K=D.useCallback(()=>{let e=ee.current,t=b.current,n=v.current;if(!e||!t||!n)return;let r=n.getBoundingClientRect();if(!(r.width<24||r.height<24))try{e.fit();let n={cols:t.cols,rows:t.rows},r=w.current;(!r||r.cols!==n.cols||r.rows!==n.rows)&&(w.current=n,C.current(n.cols,n.rows))}catch{}},[]),q=D.useCallback(()=>{if(te.current)return;let e=b.current;if(!e){G();return}if(!T.current)return;let t=T.current;T.current=``,te.current=!0,e.write(t,()=>{te.current=!1,T.current&&(typeof window<`u`?E.current=window.requestAnimationFrame(()=>{E.current=null,q()}):q())})},[G]),Ce=D.useCallback(()=>{E.current===null&&(typeof window<`u`?E.current=window.requestAnimationFrame(()=>{E.current=null,q()}):q())},[q]),J=D.useCallback(e=>{e&&(T.current+=e,Ce())},[Ce]),we=D.useCallback(()=>{if(j.current?.(),j.current=null,M.current!==null&&typeof window<`u`&&(window.clearTimeout(M.current),M.current=null),!c){oe.current=0;return}let e=v.current;if(!e)return;let t=b.current;if(!t)return;oe.current=0;let n=2.2,r=2.8,i=.25,a=.05,s=.015,l={lastY:null,lastTime:null,velocity:0,rafId:null,startX:null,startY:null,didMove:!1},u=()=>typeof performance<`u`?performance.now():Date.now(),d=Math.max(12,Math.round(o*1.35)),f=0,p=e=>{if(!e)return!1;let n=t.getViewportY(),r=f+e,i=Math.trunc(r/d);return f=r-i*d,i!==0&&t.scrollLines(i),t.getViewportY()!==n},m=()=>{l.rafId!==null&&typeof window<`u`&&window.cancelAnimationFrame(l.rafId),l.rafId=null},h={passive:!1,capture:!1};if(typeof window<`u`&&`PointerEvent`in window){let t=Object.assign(l,{pointerId:null,startX:null,startY:null,moved:!1}),o=n=>{if(n.pointerType===`touch`){m(),t.pointerId=n.pointerId,t.startX=n.clientX,t.startY=n.clientY,t.moved=!1,t.lastY=n.clientY,t.lastTime=u(),t.velocity=0;try{e.setPointerCapture(n.pointerId)}catch{}}},d=e=>{if(e.pointerType!==`touch`||t.pointerId!==e.pointerId)return;if(t.startX!==null&&t.startY!==null&&!t.moved){let n=e.clientX-t.startX,r=e.clientY-t.startY;Math.hypot(n,r)>=6&&(t.moved=!0)}if(t.lastY===null){t.lastY=e.clientY,t.lastTime=u();return}let a=t.lastY,o=t.lastTime??u(),s=u();t.lastY=e.clientY,t.lastTime=s;let c=a-e.clientY;if(Math.abs(c)<1)return;let l=Math.max(s-o,8),d=c*(n+Math.min(r,Math.abs(c)/25)),f=d/l;t.velocity=t.velocity*.75+f*i,t.velocity>8?t.velocity=8:t.velocity<-8&&(t.velocity=-8),t.moved&&(e.cancelable&&e.preventDefault(),e.stopPropagation()),p(d)},f=n=>{if(n.pointerType!==`touch`||t.pointerId!==n.pointerId)return;let r=!t.moved;t.pointerId=null,t.startX=null,t.startY=null,t.moved=!1,t.lastY=null,t.lastTime=null;try{e.releasePointerCapture(n.pointerId)}catch{}if(r){L?B(n.clientX,n.clientY):c&&!fe.current&&(fe.current=!0,b.current?.focus());return}if(typeof window>`u`)return;if(Math.abs(t.velocity)<a){t.velocity=0;return}let i=u(),o=()=>{let e=u(),n=Math.max(e-i,8);i=e;let r=p(t.velocity*n)??!1,c=Math.sign(t.velocity),l=Math.max(0,Math.abs(t.velocity)-s*n);if(t.velocity=l*c,!r||l<=a){m(),t.velocity=0;return}t.rafId=window.requestAnimationFrame(o)};t.rafId=window.requestAnimationFrame(o)};e.addEventListener(`pointerdown`,o,h),e.addEventListener(`pointermove`,d,h),e.addEventListener(`pointerup`,f,h),e.addEventListener(`pointercancel`,f,h);let g=e.style.touchAction,_=e.style.overscrollBehaviorY;e.style.touchAction=`none`,e.style.overscrollBehaviorY=`contain`,j.current=()=>{m(),M.current!==null&&typeof window<`u`&&(window.clearTimeout(M.current),M.current=null),oe.current=0,e.removeEventListener(`pointerdown`,o,h),e.removeEventListener(`pointermove`,d,h),e.removeEventListener(`pointerup`,f,h),e.removeEventListener(`pointercancel`,f,h),e.style.touchAction=g,e.style.overscrollBehaviorY=_};return}let g=e=>{e.touches.length===1&&(m(),l.lastY=e.touches[0].clientY,l.lastTime=u(),l.velocity=0,l.startX=e.touches[0].clientX,l.startY=e.touches[0].clientY,l.didMove=!1)},_=e=>{if(e.touches.length!==1){l.lastY=null,l.lastTime=null,l.velocity=0,l.startX=null,l.startY=null,l.didMove=!1,m();return}let t=e.touches[0].clientX,a=e.touches[0].clientY;if(l.startX!==null&&l.startY!==null&&!l.didMove){let e=t-l.startX,n=a-l.startY;Math.hypot(e,n)>=6&&(l.didMove=!0)}if(l.lastY===null){l.lastY=a,l.lastTime=u();return}let o=l.lastY,s=l.lastTime??u(),c=u();l.lastY=a,l.lastTime=c;let d=o-a;if(Math.abs(d)<1)return;let f=Math.max(c-s,8),h=d*(n+Math.min(r,Math.abs(d)/25)),g=h/f;l.velocity=l.velocity*.75+g*i,l.velocity>8?l.velocity=8:l.velocity<-8&&(l.velocity=-8),l.didMove&&(e.preventDefault(),e.stopPropagation()),p(h)},y=e=>{let t=!l.didMove;l.lastY=null,l.lastTime=null;let n=l.velocity;if(l.startX=null,l.startY=null,l.didMove=!1,t){let t=e.changedTouches?.[0];L?B(t?.clientX,t?.clientY):c&&!fe.current&&(fe.current=!0,b.current?.focus());return}if(typeof window>`u`)return;if(Math.abs(n)<a){l.velocity=0;return}let r=u(),i=()=>{let e=u(),t=Math.max(e-r,8);r=e;let n=p(l.velocity*t)??!1,o=Math.sign(l.velocity),c=Math.max(0,Math.abs(l.velocity)-s*t);if(l.velocity=c*o,!n||c<=a){m(),l.velocity=0;return}l.rafId=window.requestAnimationFrame(i)};l.rafId=window.requestAnimationFrame(i)};e.addEventListener(`touchstart`,g,h),e.addEventListener(`touchmove`,_,h),e.addEventListener(`touchend`,y,h),e.addEventListener(`touchcancel`,y,h);let ee=e.style.touchAction,x=e.style.overscrollBehaviorY;e.style.touchAction=`none`,e.style.overscrollBehaviorY=`contain`,j.current=()=>{m(),M.current!==null&&typeof window<`u`&&(window.clearTimeout(M.current),M.current=null),oe.current=0,e.removeEventListener(`touchstart`,g,h),e.removeEventListener(`touchmove`,_,h),e.removeEventListener(`touchend`,y,h),e.removeEventListener(`touchcancel`,y,h),e.style.touchAction=ee,e.style.overscrollBehaviorY=x}},[c,L,B,o]);D.useEffect(()=>{let e=!1,t=null,n=null,r=null,s=[],l=null,u=null,f=null,m=v.current;if(!m)return;if(m.tabIndex=L?-1:0,L){let e=m.focus.bind(m),t=m;t.focus=((...e)=>{B()}),f=()=>{t.focus=e}}let h=()=>{R(!0)},g=()=>{R(!1)},_=e=>{let t=e.target;if(t&&m.contains(t)){if(L&&t instanceof HTMLElement){window.setTimeout(()=>{t.blur(),B()},0),R(!1);return}if(c&&!fe.current&&t instanceof HTMLElement){window.setTimeout(()=>{t.blur()},0),R(!1);return}R(!0);return}R(!1)},x=()=>{R(!1)},C=null;return(async()=>{try{let f=await A();if(e)return;let _=ne(a,o,i,f,!1),v=new d(_);ae.current=!0,L&&(v.focus=()=>{});let x=v;if(typeof x.scrollToBottom==`function`){let e=x.scrollToBottom.bind(x);x.scrollToBottom=()=>{ae.current&&e()},l=()=>{x.scrollToBottom=e}}let w=new p;if(t=v,b.current=v,ee.current=w,v.loadAddon(w),v.open(m),c){let e=v.renderer;if(e&&typeof e.renderScrollbar==`function`){let t=e.renderScrollbar.bind(e);e.renderScrollbar=()=>{},u=()=>{e.renderScrollbar=t}}}ge(),de.current=!1,C=v.textarea??m.querySelector(`textarea`),C&&(C.addEventListener(`focus`,h),C.addEventListener(`blur`,g)),ve(),typeof MutationObserver<`u`&&(r=new MutationObserver(()=>{ve()}),r.observe(m,{childList:!0,subtree:!0,attributes:!0,attributeFilter:[`contenteditable`,`role`,`tabindex`,`aria-label`]}));let T=ie(m);T?(T.classList.add(`overlay-scrollbar-target`,`overlay-scrollbar-container`),y.current=T,me()):y.current=null,K();let E=w;typeof E.observeResize==`function`&&E.observeResize(),we(),s=[v.onData(e=>{S.current(e)}),v.onScroll(e=>{if(typeof e==`number`&&Number.isFinite(e)){let t=typeof v.hasSelection==`function`&&v.hasSelection();ae.current=!t&&e<=.5}}),v.onSelectionChange(()=>{if(typeof v.hasSelection==`function`&&v.hasSelection()){ae.current=!1;return}let e=typeof v.getViewportY==`function`?v.getViewportY():0;ae.current=e<=.5})],n=new ResizeObserver(()=>{K()}),n.observe(m),typeof window<`u`&&window.setTimeout(()=>{K()},0)}catch{}})(),document.addEventListener(`focusin`,_,!0),window.addEventListener(`blur`,x),()=>{e=!0,j.current?.(),j.current=null,document.removeEventListener(`focusin`,_,!0),window.removeEventListener(`blur`,x),s.forEach(e=>e.dispose()),l?.(),l=null,u?.(),u=null,C&&(C.removeEventListener(`focus`,h),C.removeEventListener(`blur`,g)),n?.disconnect(),r?.disconnect(),f?.(),t?.dispose(),b.current=null,ee.current=null,y.current=null,w.current=null,de.current=null,G()}},[ve,c,K,B,a,o,we,i,G,R,L]),D.useEffect(()=>{let e=b.current;e&&(e.reset(),G(),w.current=null,K())},[e,he,K,G]),D.useEffect(()=>{l&&b.current&&V()},[l,V,e,he]),D.useEffect(()=>(we(),()=>{j.current?.(),j.current=null}),[we,e]),D.useEffect(()=>{let e=b.current;if(!e)return;if(t.length===0){k.current!==null&&(e.reset(),G(),K());return}let n=k.current,r;if(n===null)r=t;else{let e=t.findIndex(e=>e.id===n);r=e>=0?t.slice(e+1):t}r.length>0&&J(r.map(e=>e.data).join(``)),k.current=t[t.length-1].id},[t,he,J,K,G]),D.useImperativeHandle(f,()=>({focus:()=>{V()},clear:()=>{let e=b.current;e&&(e.reset(),G(),K())},fit:()=>{K()}}),[V,K,G]);let Y=D.useCallback(e=>{if(!L)return;let t=v.current,n=e.relatedTarget,r=n?.tagName;r===`INPUT`||r===`TEXTAREA`||n?.isContentEditable,n?.getAttribute(`data-terminal-hidden-input`),n&&t?.contains(n)},[L]),X=D.useCallback(e=>{let t=e.nativeEvent,n=t?.inputType??``,r=typeof t?.data==`string`?t.data:``;if(le.current=typeof performance<`u`?performance.now():Date.now(),n===`insertCompositionText`){P.current=!0;return}if(!n&&r){if(P.current)return;e.preventDefault(),S.current(r),ce.current={type:`insertText`,at:typeof performance<`u`?performance.now():Date.now()},F.current=!0;return}if(n===`insertText`&&r){if(P.current)return;e.preventDefault(),S.current(r),ce.current={type:n,at:typeof performance<`u`?performance.now():Date.now()},F.current=!0;return}if(n===`insertLineBreak`){if(P.current)return;e.preventDefault(),S.current(`\r`),ce.current={type:n,at:typeof performance<`u`?performance.now():Date.now()},F.current=!0;return}if(n===`deleteContentBackward`){if(P.current)return;e.preventDefault(),S.current(``),ce.current={type:n,at:typeof performance<`u`?performance.now():Date.now()},F.current=!0}},[]),Z=D.useCallback(e=>{let t=e.currentTarget;if(le.current=typeof performance<`u`?performance.now():Date.now(),P.current)return;if(F.current){let e=ce.current,n=typeof performance<`u`?performance.now():Date.now();if(e&&n-e.at<50){F.current=!1,U(t);return}F.current=!1}let n=H(t);if(!n)return;I.current=n;let r=n.replace(/\r\n|\r|\n/g,`\r`);S.current(r),U(t),I.current=``},[U,H]),Te=D.useCallback(e=>{e.stopPropagation();let t=e.key.toLowerCase(),n=e.metaKey&&!e.ctrlKey&&!e.altKey&&t===`c`,r=e.ctrlKey&&e.shiftKey&&!e.metaKey&&!e.altKey&&t===`c`;if((n||r)&&Se()){e.preventDefault(),xe();return}if(e.ctrlKey&&!e.metaKey&&!e.altKey&&e.key.length===1){let t=e.key.toUpperCase();if(t>=`A`&&t<=`Z`){e.preventDefault(),e.nativeEvent?.stopImmediatePropagation(),S.current(String.fromCharCode(t.charCodeAt(0)-64)),U(e.currentTarget);return}}if(e.altKey&&!e.ctrlKey&&!e.metaKey&&e.key.length===1){e.preventDefault(),e.nativeEvent?.stopImmediatePropagation(),S.current(`\x1B`+e.key),U(e.currentTarget);return}let i={ArrowUp:`\x1B[A`,ArrowDown:`\x1B[B`,ArrowRight:`\x1B[C`,ArrowLeft:`\x1B[D`,Escape:`\x1B`,Tab:` `,Delete:`\x1B[3~`,Home:`\x1B[H`,End:`\x1B[F`}[e.key];if(i){e.preventDefault(),S.current(i),U(e.currentTarget);return}let a=e.currentTarget;if(e.nativeEvent?.isComposing)return;let o=ce.current,s=typeof performance<`u`?performance.now():Date.now(),c=!!(o&&s-o.at<50);if(e.key===`Enter`){if(c&&o?.type===`insertLineBreak`)return;e.preventDefault(),S.current(`\r`),U(a);return}if(e.key===`Backspace`){if(e.preventDefault(),c&&o?.type===`deleteContentBackward`)return;H(a)||S.current(``)}if(e.key.length===1&&!e.ctrlKey&&!e.metaKey&&!e.altKey){let t=le.current;t&&s-t<50||(e.preventDefault(),S.current(e.key),F.current=!0,ce.current={type:`keydown-text`,at:s})}ye(a)},[U,xe,Se,H,ye]),Ee=D.useCallback(e=>{e.stopPropagation();let t=e.currentTarget;e.nativeEvent?.isComposing||ye(t)},[ye]),De=D.useCallback(e=>{let t=e.currentTarget;P.current=!1;let n=e.data||H(t);if(le.current=typeof performance<`u`?performance.now():Date.now(),!n)return;let r=n.replace(/\r\n|\r|\n/g,`\r`);S.current(r),U(t),ce.current={type:`compositionend`,at:typeof performance<`u`?performance.now():Date.now()},F.current=!0},[U,H]),Oe=D.useCallback(e=>{e.stopPropagation();let t=e.clipboardData?.getData(`text`)??``;if(!t)return;e.preventDefault();let n=b.current?.hasBracketedPaste?.()?`\x1b[200~${t}\x1b[201~`:t;S.current(n)},[]),ke={position:`fixed`,left:0,top:0,width:1,height:1,opacity:0,zIndex:-1,background:`transparent`,color:`transparent`,WebkitTextFillColor:`transparent`,caretColor:`transparent`,textShadow:`none`,WebkitAppearance:`none`,appearance:`none`,resize:`none`,overflow:`hidden`,whiteSpace:`nowrap`,border:`0`,padding:0,margin:0,outline:`none`,outlineOffset:0,fontSize:16,fontWeight:400,pointerEvents:`none`,WebkitUserSelect:`none`,userSelect:`none`};return(0,O.jsxs)(`div`,{ref:v,className:g(`relative h-full w-full terminal-viewport-container`,s),"data-hidden-input-overlay-active":L?`true`:void 0,style:{backgroundColor:i.background},onTouchStart:e=>{if(!(!L||c)&&!Se()){let t=e.touches?.[0];B(t?.clientX,t?.clientY)}},onClick:e=>{if(!c)if(L){if(Se())return;B(e.clientX,e.clientY)}else b.current?.focus()},onMouseUp:()=>{!c&&Se()&&xe()},onTouchEnd:()=>{!c&&Se()&&xe()},children:[L&&typeof document<`u`?(0,re.createPortal)((0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(`input`,{ref:N,type:`text`,inputMode:`text`,autoCapitalize:`off`,autoComplete:`off`,autoCorrect:`off`,spellCheck:!1,tabIndex:-1,enterKeyHint:`send`,"data-terminal-hidden-input":`true`,"aria-label":_(`terminalView.viewport.inputAria`),"aria-hidden":`true`,style:{...ke,display:z?`block`:`none`},onBlur:Y,onBeforeInput:X,onCompositionStart:()=>{P.current=!0},onInput:Z,onKeyDown:Te,onKeyUp:Ee,onCompositionEnd:De,onPaste:Oe}),(0,O.jsx)(`textarea`,{ref:se,inputMode:`text`,autoCapitalize:`off`,autoComplete:`off`,autoCorrect:`off`,spellCheck:!1,tabIndex:-1,enterKeyHint:`send`,"data-terminal-hidden-input":`true`,"aria-label":_(`terminalView.viewport.inputAria`),"aria-hidden":`true`,style:{...ke,display:z?`none`:`block`},onBlur:Y,onBeforeInput:X,onCompositionStart:()=>{P.current=!0},onInput:Z,onKeyDown:Te,onKeyUp:Ee,onCompositionEnd:De,onPaste:Oe})]}),document.body):null,y.current&&!c?(0,O.jsx)(x,{containerRef:y,disableHorizontal:!0,className:`overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero`}):null]})});ae.displayName=`TerminalViewport`;var j=RegExp(`\x1B\\[[0-9;?]*[ -/]*[@-~]`,`g`),M=/(https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[(?:::1|::)\])(?::\d{2,5})?(?:\/[^\s<>'"`]*)?)/gi,oe=/(?:➜\s*(?:Local|Network):)|\b(?:local|network|loopback|serving|listening|available|ready|started|running|server|vite|webpack|next\.js|astro|sveltekit|nuxt)\b/i,se=/Serving HTTP on .*? port (\d{2,5})/i,N=new Set([`.`,`,`,`;`,`:`,`!`,`?`]),P=e=>{let t=e;for(;t.length>0;){let e=t[t.length-1];if(e===`)`||e===`]`||e===`}`||e===`>`){let n=e===`)`?`(`:e===`]`?`[`:e===`}`?`{`:`<`,r=t.slice(0,-1);if((r.match(RegExp(`\\${n}`,`g`))||[]).length>(r.match(RegExp(`\\${e}`,`g`))||[]).length)break;t=r;continue}if(N.has(e)){t=t.slice(0,-1);continue}break}return t},F=e=>{let t=P(e);return t=t.replace(`0.0.0.0`,`127.0.0.1`),t=t.replace(`[::1]`,`127.0.0.1`),t=t.replace(`[::]`,`127.0.0.1`),t},ce=e=>{if(!e)return null;let t=e.replace(j,``),n=t.match(se);if(n?.[1]){let e=Number.parseInt(n[1],10);if(Number.isFinite(e)&&e>0&&e<=65535)return`http://127.0.0.1:${e}/`}let r=t.split(`
2
- `);for(let e of r){if(!oe.test(e))continue;let t=Array.from(e.matchAll(M));if(t.length!==0)return F((t.find(e=>{try{return!!new URL(F(e[1])).port}catch{return!1}})??t[0])[1])}return null},le=async(e,n=1500)=>{if(!e||typeof window>`u`)return!1;let r;try{r=new URL(e)}catch{return!1}if(r.protocol!==`http:`&&r.protocol!==`https:`)return!1;let i=r.hostname.toLowerCase();if(i!==`localhost`&&i!==`127.0.0.1`&&i!==`0.0.0.0`&&i!==`::1`&&i!==`::`)return!1;let a=new AbortController,o=window.setTimeout(()=>a.abort(),n);try{let e=await t(`/api/system/probe-url`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({url:r.toString()}),cache:`no-store`,signal:a.signal});return e.ok?(await e.json().catch(()=>null))?.ok===!0:!1}catch{return!1}finally{window.clearTimeout(o)}},ue={esc:`\x1B`,tab:` `,enter:`\r`,"arrow-up":`\x1B[A`,"arrow-down":`\x1B[B`,"arrow-left":`\x1B[D`,"arrow-right":`\x1B[C`},I={ctrl:`5`,cmd:`3`},de={retry:{maxRetries:3,initialDelayMs:500,maxDelayMs:8e3},connectionTimeoutMs:1e4},fe={retry:{maxRetries:8,initialDelayMs:400,maxDelayMs:8e3},connectionTimeoutMs:15e3},pe=(e,t)=>{if(t)switch(e){case`arrow-up`:return`\u001b[1;${I[t]}A`;case`arrow-down`:return`\u001b[1;${I[t]}B`;case`arrow-right`:return`\u001b[1;${I[t]}C`;case`arrow-left`:return`\u001b[1;${I[t]}D`}return ue[e]??null},me=()=>{let{t:e}=h(),{terminal:t,runtime:r}=l(),{currentTheme:i}=y(),{monoFont:a}=T(),d=c(e=>e.terminalFontSize),f=c(e=>e.bottomTerminalHeight),p=c(e=>e.isBottomTerminalExpanded),{isMobile:m,isTablet:x,hasTouchOnlyPointer:ne}=ee(),re=m||x,k=(re||ne)&&r.platform===`web`,A=r.platform!==`vscode`,ie=c(e=>e.showTerminalQuickKeysOnDesktop),j=!n()&&(re||ie),M=v(e=>e.currentSessionId),oe=v(e=>e.newSessionDraft),se=M!==null||oe?.open===!0,N=S()??null,P=w(e=>e.sessions),F=w(e=>e.hasHydrated),ue=w(e=>e.ensureDirectory),I=w(e=>e.createTab),me=w(e=>e.setActiveTab),he=w(e=>e.closeTab),ge=w(e=>e.setTabSessionId),_e=w(e=>e.setTabLifecycle),L=w(e=>e.setConnecting),ve=w(e=>e.appendToBuffer),R=w(e=>e.setTabPreviewUrl),z=w(e=>e.clearBuffer),B=c(e=>e.openContextPreview),V=D.useMemo(()=>{if(N)return P.get(N)},[P,N]),H=D.useMemo(()=>V?A?V.activeTabId??V.tabs[0]?.id??null:V.tabs[0]?.id??null:null,[V,A]),U=D.useMemo(()=>{if(V)return H?V.tabs.find(e=>e.id===H)??V.tabs[0]:V.tabs[0]},[V,H]),ye=D.useMemo(()=>(V?.tabs??[]).map(t=>({icon:(()=>{let e=t.iconKey?E[t.iconKey]??`terminal`:`terminal`;return(0,O.jsx)(b,{name:e,className:`h-4 w-4`})})(),id:t.id,label:t.label,title:t.label,closeLabel:e(`terminalView.tabs.closeTabTitle`)})),[V?.tabs,e]),W=U?.terminalSessionId??null,be=U?.lifecycle??`idle`,xe=U?.bufferChunks??[],Se=U?.isConnecting??!1,G=U?.previewUrl??null,[K,q]=D.useState(null),[Ce,J]=D.useState(!1),[we,Y]=D.useState(!1),[X,Z]=D.useState(null),[Te,Ee]=D.useState(!1),[De,Oe]=D.useState(0),ke=D.useRef(null),Ae=D.useRef(null),je=D.useRef(H),Me=D.useRef(W),Ne=D.useRef(N),Pe=D.useRef(null),Fe=D.useRef(null),Ie=D.useRef(!1),Le=D.useRef(!1),Re=D.useRef(null),ze=D.useRef(null),Be=D.useRef(new Set),Ve=D.useRef(!1),He=D.useRef(``),Ue=D.useRef(new Set),We=D.useRef(0),Ge=D.useCallback(()=>{He.current=``,Ue.current.clear(),We.current+=1},[]),Ke=D.useCallback(()=>{k||typeof document<`u`&&!document.hasFocus()||Pe.current?.focus()},[k]),qe=D.useCallback(()=>{k||Pe.current?.focus()},[k]);D.useEffect(()=>{if(!F||Ve.current)return;Ve.current=!0;let e=new Set;for(let[,t]of w.getState().sessions.entries())for(let n of t.tabs)n.terminalSessionId&&e.add(n.terminalSessionId);Be.current=e},[F]);let Je=c(e=>e.activeMainTab),Ye=c(e=>e.isBottomTerminalOpen),Xe=c(e=>e.setBottomTerminalOpen),Ze=c(e=>e.setBottomTerminalExpanded),Qe=Je===`terminal`,Q=Qe||Ye,[$e,et]=D.useState(Q);D.useEffect(()=>{!Q||r.platform===`vscode`||u()},[Q,r.platform]),D.useEffect(()=>{Q&&et(!0)},[Q]),D.useEffect(()=>{Le.current=Q},[Q]),D.useEffect(()=>{Me.current=W},[W]),D.useEffect(()=>{je.current=H,Ge()},[H,Ge]),D.useEffect(()=>{Ne.current=N},[N]),D.useEffect(()=>{!j&&X!==null&&Z(null)},[j,X,Z]),D.useEffect(()=>{!W&&X!==null&&Z(null)},[W,X,Z]);let $=D.useCallback(()=>{ke.current?.(),ke.current=null,Ae.current=null,Re.current=null,Y(!1)},[]);D.useEffect(()=>()=>{$(),Me.current=null},[$]);let tt=D.useCallback((e,t,n)=>{if(!n)return;let r=`${He.current}${n}`.replace(/\r\n|\r/g,`
3
- `),i=r.split(`
4
- `),a=r.endsWith(`
5
- `)?i.join(`
6
- `):i.slice(0,-1).join(`
7
- `);if(He.current=r.endsWith(`
8
- `)?``:(i[i.length-1]??``).slice(-1024),!a)return;let o=ce(a);if(!o||Ue.current.has(o))return;let s=We.current;Ue.current.add(o),le(o).then(n=>{if(Ue.current.delete(o),!n||We.current!==s)return;let r=w.getState().getDirectoryState(e)?.tabs.find(e=>e.id===t);!r||r.previewUrlLocked||r.previewUrl===o||R(e,t,o,{locked:!1,autoOpened:!1})})},[R]),nt=D.useCallback((n,r,i,a=de,o=!1)=>{if(Ae.current===i)return;$(),Ae.current=i;let s=t.connect(i,{onEvent:a=>{if(Ae.current===i)switch(a.type){case`connected`:Re.current=i,L(n,r,!1),q(null),J(!1),Y(!1),Ke(),ze.current===i&&(ze.current=null,t.sendInput(i,`\r`).catch(()=>{}));break;case`reconnecting`:q(null),J(!1),Y(!0);break;case`data`:a.data&&(ve(n,r,a.data),tt(n,r,a.data));break;case`exit`:{let t=typeof a.exitCode==`number`?a.exitCode:null,i=typeof a.signal==`number`?a.signal:null,o=!!(w.getState().getDirectoryState(n)?.tabs.find(e=>e.id===r))?.label?.startsWith(`Action:`);ve(n,r,e(`terminalView.stream.processExitedMessage`,{exitCodeSegment:t===null?``:e(`terminalView.stream.processExitedWithCode`,{exitCode:t}),signalSegment:i===null?``:e(`terminalView.stream.processExitedWithSignal`,{signal:i})})),_e(n,r,`exited`),ge(n,r,null),L(n,r,!1),q(o?null:e(`terminalView.error.sessionEnded`)),J(!1),Y(!1),$();break}}},onError:(t,a)=>{if(Ae.current===i){if(!a){q(null),J(!1);return}if(/session not found/i.test(t.message)||o){Y(!1),q(null),J(!1),L(n,r,!0),z(n,r),_e(n,r,`idle`),ge(n,r,null),$();return}Y(!1),q(e(`terminalView.error.connectionFailed`,{message:t.message})),J(!0),L(n,r,!1),z(n,r),_e(n,r,`exited`),ge(n,r,null),$()}}},a);ke.current=()=>{s.close(),Ae.current=null}},[ve,z,$,Ke,tt,L,_e,ge,e,t]);D.useEffect(()=>{let n=!1;if(!(!F||!$e)){if(!N){q(e(se?`terminalView.empty.noWorkingDirectory`:`terminalView.empty.selectSession`));return}return(async()=>{let r=N;if(!Ne.current||Ne.current!==r)return;ue(r);let i=w.getState().getDirectoryState(r);if(!i||i.tabs.length===0)return;let a=A?i.activeTabId??i.tabs[0]?.id??null:i.tabs[0]?.id??null;if(!a)return;let o=i.tabs.find(e=>e.id===a)??i.tabs[0],s=o?.terminalSessionId??null,c=o?.lifecycle??`idle`,l=!!o?.label?.startsWith(`Action:`),u=(o?.bufferLength??0)>0||(o?.bufferChunks?.length??0)>0;if(s)return;if(c===`exited`){L(r,a,!1);return}if(l&&u){L(r,a,!1);return}let d=Fe.current;if(!(!d&&Le.current)){q(null),J(!1),Y(!1),L(r,a,!0);try{let e=await t.createSession({cwd:r,cols:d?.cols,rows:d?.rows});if(!(!n&&Ne.current===r&&je.current===a)){try{await t.close(e.sessionId)}catch{}return}if(w.getState().getDirectoryState(r)?.tabs.find(e=>e.id===a)?.terminalSessionId){try{await t.close(e.sessionId)}catch{}return}ge(r,a,e.sessionId)}catch(t){n||(q(t instanceof Error?t.message:e(`terminalView.error.startSessionFailed`)),J(!0),Y(!1),L(r,a,!1))}}})(),()=>{n=!0}}},[se,N,W,be,H,$e,De,A,F,ue,L,ge,e,t]);let rt=D.useRef(nt);rt.current=nt;let it=D.useRef($);it.current=$,D.useEffect(()=>{if(!F||!$e)return;if(!N){it.current();return}let e=N,t=w.getState().getDirectoryState(e);if(!t||t.tabs.length===0){it.current();return}let n=A?t.activeTabId??t.tabs[0]?.id??null:t.tabs[0]?.id??null;if(!n){it.current();return}let r=t.tabs.find(e=>e.id===n)??t.tabs[0],i=r?.terminalSessionId??null;if(!i){it.current(),Me.current=null;return}if(Ae.current===i&&ke.current){Me.current=i;return}Me.current=i;let a=Be.current.has(i),o=a&&(r?.bufferLength??0)===0&&(r?.bufferChunks?.length??0)===0;a&&Be.current.delete(i),o&&(ze.current=i),rt.current(e,n,i,a?fe:de,a)},[N,W,H,A,$e,F]),D.useEffect(()=>{if(!Q||k)return;if(typeof window>`u`){Ke();return}let e=window.requestAnimationFrame(()=>{Ke()});return()=>{window.cancelAnimationFrame(e)}},[H,Ke,Q,k]);let at=D.useCallback(async()=>{if(!N||Te)return;let t=w.getState().getDirectoryState(N),n=A?H??t?.activeTabId??t?.tabs[0]?.id??null:t?.tabs[0]?.id??null;if(n){Ee(!0),q(null),J(!1),Y(!1),$(),z(N,n),Ge();try{await he(N,n)}catch(t){q(t instanceof Error?t.message:e(`terminalView.error.restartFailed`)),J(!0),Y(!1)}finally{Ee(!1)}}},[H,z,he,$,N,A,Te,Ge,e]),ot=D.useCallback(async()=>{await at()},[at]),st=D.useCallback(()=>{if(!N)return;let e=I(N);me(N,e),q(null),J(!1),Y(!1),$()},[I,$,N,me]),ct=D.useCallback(e=>{N&&(me(N,e),q(null),J(!1),Y(!1),$())},[$,N,me]),lt=D.useCallback(e=>{N&&(e===H&&$(),q(null),J(!1),Y(!1),he(N,e))},[H,he,$,N]),ut=D.useCallback(n=>{if(!n||we)return;let r=n,i=!1;if(X&&n.length>0){let e=n[0];if(e.length===1&&/[a-zA-Z]/.test(e)){let t=e.toUpperCase();(X===`ctrl`||X===`cmd`)&&(r=String.fromCharCode(t.charCodeAt(0)&31),i=!0)}i||=!0}let a=Me.current;!a||Re.current!==a||(t.sendInput(a,r).catch(t=>{we||q(t instanceof Error?t.message:e(`terminalView.error.sendInputFailed`))}),i&&(Z(null),qe()))},[X,qe,we,Z,e,t]),dt=D.useCallback((e,n)=>{let r=Fe.current;if((!r||r.cols!==e||r.rows!==n)&&(Fe.current={cols:e,rows:n}),Ie.current||(Ie.current=!0,Oe(e=>e+1)),!Le.current)return;let i=Me.current;!i||Re.current!==i||t.resize({sessionId:i,cols:e,rows:n}).catch(()=>{})},[t]),ft=D.useCallback(e=>{Z(t=>t===e?null:e),qe()},[qe,Z]),pt=D.useCallback(e=>{let t=pe(e,X);t&&(ut(t),Z(null),qe())},[X,qe,ut,Z]);D.useEffect(()=>{if(!j||!X||!W)return;let e=e=>{if(e.repeat)return;let t=e.key;if(!t||t===`Control`||t===`Meta`||t===`Alt`||t===`Shift`)return;let n=t.length===1?t.toLowerCase():t,r=e.code??``,i=r.startsWith(`Key`)&&r.length===4?r.slice(3).toUpperCase():null,a=t.length===1&&/[a-zA-Z]/.test(t)?t.toUpperCase():i,o={Tab:`tab`,Enter:`enter`,ArrowUp:`arrow-up`,ArrowDown:`arrow-down`,ArrowLeft:`arrow-left`,ArrowRight:`arrow-right`,Escape:`esc`,tab:`tab`,enter:`enter`,arrowup:`arrow-up`,arrowdown:`arrow-down`,arrowleft:`arrow-left`,arrowright:`arrow-right`,escape:`esc`};if(n in o){e.preventDefault(),e.stopPropagation(),pt(o[n]);return}if(X===`ctrl`&&a&&a.length===1&&a>=`A`&&a<=`Z`){let t=String.fromCharCode(a.charCodeAt(0)&31);e.preventDefault(),e.stopPropagation(),ut(t),Z(null),qe()}};return window.addEventListener(`keydown`,e),()=>{window.removeEventListener(`keydown`,e)}},[X,pt,ut,qe,j,Z,W]);let mt=D.useMemo(()=>{let e=o[s].stack;if(typeof window>`u`)return(o[a]??o[`system-mono`]).stack;let t=window.getComputedStyle(document.documentElement).getPropertyValue(`--font-family-mono`);return t&&t.trim().length>0?t.trim():(o[a]??o[`system-mono`]).stack??e},[a]),ht=D.useMemo(()=>te(i),[i]),gt=D.useMemo(()=>`${N??`no-dir`}::${H??`no-tab`}`,[N,H]);if(D.useEffect(()=>{if(!Q||k)return;let e=Pe.current;if(!e)return;let t=()=>{e.fit()};if(typeof window<`u`){let e=window.requestAnimationFrame(()=>{t(),Ke()}),n=[220,400].map(e=>window.setTimeout(t,e));return()=>{window.cancelAnimationFrame(e),n.forEach(e=>window.clearTimeout(e))}}t()},[Ke,Q,k,gt,W]),D.useEffect(()=>{if(k||!Q||!Ye)return;let e=Pe.current;if(!e)return;let t=()=>{e.fit()};if(typeof window<`u`){let e=window.requestAnimationFrame(()=>{t()}),n=[0,80,180,320].map(e=>window.setTimeout(t,e));return()=>{window.cancelAnimationFrame(e),n.forEach(e=>window.clearTimeout(e))}}t()},[f,p,Ye,Q,k]),!se)return(0,O.jsx)(`div`,{className:`flex h-full items-center justify-center p-4 text-center text-sm text-muted-foreground`,children:e(`terminalView.empty.selectSession`)});if(!N)return(0,O.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-2 p-4 text-center text-sm text-muted-foreground`,children:[(0,O.jsx)(`p`,{children:e(`terminalView.empty.noWorkingDirectoryForSession`)}),(0,O.jsx)(_,{onClick:at,size:`sm`,children:e(`terminalView.actions.retry`)})]});let _t=!W||Se||Te||we,vt=$e,yt=!re&&Ye&&!Qe,bt=(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(_,{type:`button`,size:`sm`,variant:`outline`,className:`h-6 px-2 text-xs`,onClick:()=>pt(`esc`),disabled:_t,children:e(`terminalView.quickKeys.escape`)}),(0,O.jsxs)(_,{type:`button`,size:`sm`,variant:`outline`,className:`h-6 w-9 p-0`,onClick:()=>pt(`tab`),disabled:_t,children:[(0,O.jsx)(b,{name:`arrow-right`,className:`h-4 w-4`}),(0,O.jsx)(`span`,{className:`sr-only`,children:e(`terminalView.quickKeys.tabAria`)})]}),(0,O.jsxs)(_,{type:`button`,size:`sm`,variant:`chip`,"aria-pressed":X===`ctrl`,className:`h-6 w-9 p-0`,onClick:()=>ft(`ctrl`),disabled:_t,children:[(0,O.jsx)(`span`,{className:`text-xs font-medium`,children:e(`terminalView.quickKeys.controlLabel`)}),(0,O.jsx)(`span`,{className:`sr-only`,children:e(`terminalView.quickKeys.controlModifierAria`)})]}),(0,O.jsxs)(_,{type:`button`,size:`sm`,variant:`chip`,"aria-pressed":X===`cmd`,className:`h-6 w-9 p-0`,onClick:()=>ft(`cmd`),disabled:_t,children:[(0,O.jsx)(b,{name:`command`}),(0,O.jsx)(`span`,{className:`sr-only`,children:e(`terminalView.quickKeys.commandModifierAria`)})]}),(0,O.jsxs)(_,{type:`button`,size:`sm`,variant:`outline`,className:`h-6 w-9 p-0`,onClick:()=>pt(`arrow-up`),disabled:_t,children:[(0,O.jsx)(b,{name:`arrow-up`}),(0,O.jsx)(`span`,{className:`sr-only`,children:e(`terminalView.quickKeys.arrowUpAria`)})]}),(0,O.jsxs)(_,{type:`button`,size:`sm`,variant:`outline`,className:`h-6 w-9 p-0`,onClick:()=>pt(`arrow-left`),disabled:_t,children:[(0,O.jsx)(b,{name:`arrow-left`}),(0,O.jsx)(`span`,{className:`sr-only`,children:e(`terminalView.quickKeys.arrowLeftAria`)})]}),(0,O.jsxs)(_,{type:`button`,size:`sm`,variant:`outline`,className:`h-6 w-9 p-0`,onClick:()=>pt(`arrow-down`),disabled:_t,children:[(0,O.jsx)(b,{name:`arrow-down`}),(0,O.jsx)(`span`,{className:`sr-only`,children:e(`terminalView.quickKeys.arrowDownAria`)})]}),(0,O.jsxs)(_,{type:`button`,size:`sm`,variant:`outline`,className:`h-6 w-9 p-0`,onClick:()=>pt(`arrow-right`),disabled:_t,children:[(0,O.jsx)(b,{name:`arrow-right`}),(0,O.jsx)(`span`,{className:`sr-only`,children:e(`terminalView.quickKeys.arrowRightAria`)})]}),(0,O.jsxs)(_,{type:`button`,size:`sm`,variant:`outline`,className:`h-6 w-9 p-0`,onClick:()=>pt(`enter`),disabled:_t,children:[(0,O.jsx)(b,{name:`arrow-go-back`}),(0,O.jsx)(`span`,{className:`sr-only`,children:e(`terminalView.quickKeys.enterAria`)})]})]});return(0,O.jsxs)(`div`,{"data-terminal-view":`true`,className:`flex h-full flex-col overflow-hidden bg-[var(--surface-background)]`,children:[(0,O.jsxs)(`div`,{className:g(`app-region-no-drag sticky top-0 z-20 shrink-0 bg-[var(--surface-background)] text-xs`,re?`px-3 py-1.5`:`pl-3 pr-1.5 py-1`),children:[A&&V?(0,O.jsxs)(`div`,{className:`flex items-center gap-2 pl-1 pr-1`,children:[(0,O.jsx)(`div`,{className:g(`min-w-0 flex-1`,re?`h-8`:`h-7`),children:(0,O.jsx)(C,{items:ye,activeId:H,onSelect:ct,onClose:lt,layoutMode:`scrollable`,variant:`default`,className:`h-full bg-transparent`})}),(0,O.jsx)(_,{type:`button`,size:`xs`,variant:`ghost`,className:g(`shrink-0`,re?`h-8 w-8 p-0`:`h-7 w-7 p-0`),onClick:st,title:e(`terminalView.tabs.newTabTitle`),children:(0,O.jsx)(b,{name:`add`,className:`${re?`h-[18px] w-[18px]`:`h-4 w-4`}`})}),(0,O.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 overflow-visible`,children:[G?(0,O.jsxs)(_,{type:`button`,size:`xs`,variant:`outline`,className:`h-6 shrink-0 gap-1 px-2`,onClick:()=>{N&&B(N,G)},title:e(`terminalView.preview.openTitle`),children:[(0,O.jsx)(b,{name:`global`,className:`h-3.5 w-3.5 shrink-0`}),(0,O.jsx)(`span`,{className:`whitespace-nowrap`,children:e(`terminalView.preview.open`)})]}):null,yt?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(_,{type:`button`,size:`xs`,variant:`ghost`,onClick:()=>Ze(!p),className:g(`shrink-0 p-0`,m?`h-8 w-8`:`h-7 w-7`),title:e(p?`terminalView.bottomDock.restoreTitle`:`terminalView.bottomDock.expandTitle`),"aria-label":e(p?`terminalView.bottomDock.restoreAria`:`terminalView.bottomDock.expandAria`),children:p?(0,O.jsx)(b,{name:`fullscreen-exit`,className:`h-4 w-4`}):(0,O.jsx)(b,{name:`fullscreen`,className:`h-4 w-4`})}),(0,O.jsx)(_,{type:`button`,size:`xs`,variant:`ghost`,onClick:()=>Xe(!1),className:g(`shrink-0 p-0`,m?`h-8 w-8`:`h-7 w-7`),title:e(`terminalView.bottomDock.closeTitle`),"aria-label":e(`terminalView.bottomDock.closeAria`),children:(0,O.jsx)(b,{name:`close`,className:`h-4 w-4`})})]}):null]})]}):null,!m&&j&&A&&V?(0,O.jsx)(`div`,{className:`mt-2 flex flex-wrap items-center gap-1 pl-1 pr-1`,children:bt}):null,j&&(m||!A||!V)?(0,O.jsx)(`div`,{className:`mt-2 flex flex-wrap items-center gap-1`,children:bt}):null]}),(0,O.jsxs)(`div`,{className:`relative flex-1 overflow-hidden`,style:{backgroundColor:ht.background},children:[(0,O.jsx)(`div`,{className:`h-full w-full box-border pl-4 pr-1.5 pt-3 pb-4`,children:vt?(0,O.jsx)(ae,{ref:e=>{Pe.current=e},sessionKey:gt,chunks:xe,onInput:ut,onResize:dt,theme:ht,fontFamily:mt,fontSize:d,enableTouchScroll:k,autoFocus:!k&&Q,isVisible:Q},gt):null}),!we&&K&&(0,O.jsxs)(`div`,{className:`absolute inset-x-0 bottom-0 bg-[var(--status-error-background)] px-3 py-2 text-xs text-[var(--status-error-foreground)] flex items-center justify-between gap-2`,children:[(0,O.jsx)(`span`,{children:K}),Ce&&m&&(0,O.jsx)(_,{size:`sm`,variant:`secondary`,className:`h-6 px-2 py-0 text-xs`,onClick:ot,disabled:Te,title:e(`terminalView.actions.hardRestartTitle`),type:`button`,children:e(`terminalView.actions.hardRestart`)})]})]})]})};export{me as TerminalView};
@@ -1 +0,0 @@
1
- import{a as e}from"./vendor-zustand-o69pgTEK.js";import{n as t,t as n}from"./platform-BND-ZKbF.js";import"./brand-storage-bootstrap-D4BW3w-M.js";import{a as r,n as i}from"./vendor-aparajita-capacitor-secure-storage-xol_6BsB.js";import{r as a}from"./vendor-pierre-diffs-DPBtNDJ5.js";import{o}from"./useMobileNavigationStore-YGHA7SiM.js";import{t as s}from"./agentColors-DWSbQXy2.js";import{t as c}from"./rasterizePng-056Poix7.js";var l=`yuri.iosNativeUi`,u=()=>{if(typeof window>`u`)return!1;try{return window.localStorage.getItem(l)===`1`}catch{return!1}},d=e=>{if(!(typeof window>`u`))try{e?window.localStorage.setItem(l,`1`):window.localStorage.removeItem(l)}catch{}},f=e(e=>({enabled:u(),setEnabled:t=>{d(t),e({enabled:t})}})),p=()=>f.getState().enabled,m=()=>f(te),ee=()=>t()&&n()===`ios`;function te(e){return e.enabled}var h=5,g=Math.ceil(h/2);function _(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return t>>>0}function ne(e){let t=Array.from({length:h},()=>Array.from({length:h},()=>!1));if(!e)return t;let n=_(e);for(let e=0;e<h;e++)for(let r=0;r<g;r++){let i=(n&1)==1;n>>>=1,t[e][r]=i,t[e][4-r]=i}return t}var re=`yuri-native-ios-composer`,v=`--yuri-native-composer-height`,y=`--yuri-native-composer-accessory`,b=33554432,x=`YuriComposer`,S=`#22c55e`,C=32,w=()=>({open:!1,highlightedIndex:0,query:``,highlightColor:``,rows:[]}),T=()=>({text:``,placeholder:``,modelLabel:``,modelVariantLabel:``,modelIcon:``,canSend:!1,canAbort:!1,attachmentCount:0,attachmentPreviews:[],citationRanges:[],chipRanges:[],appearance:`dark`,attachAria:``,attachTitle:``,attachPhotosLabel:``,attachFilesLabel:``,attachCancelLabel:``,sendAria:``,queueAria:``,stopAria:``,modelAria:``,agentAria:``,agentLabel:``,agentColor:S,agentIdenticon:Array.from({length:25},()=>0),agentIcon:``,suppressed:!0,showScrollToBottom:!1,scrollAria:``,autocomplete:w()}),ie=r(x),ae=e=>e.isCapacitor&&e.platform===`ios`&&e.pluginAvailable&&e.isMobile&&e.nativeUiEnabled!==!1;function oe(e){return typeof window>`u`?!1:ae({isCapacitor:t(),platform:n(),pluginAvailable:i.isPluginAvailable(x),isMobile:e,nativeUiEnabled:p()})}var se=e=>e.classList.contains(`dark`)?`dark`:`light`,ce=e=>{let t=e?.height;return typeof t!=`number`||!Number.isFinite(t)||t<0?0:t},le=(e,t)=>{if(!(t>0)){e.style.removeProperty(v);return}e.style.setProperty(v,`${Math.round(t)}px`)},ue=(e,t)=>{if(!(t>0)){e.style.removeProperty(y);return}e.style.setProperty(y,`${Math.round(t)}px`)},E=(e,t)=>{e.classList.toggle(re,t),t||(e.style.removeProperty(v),e.style.removeProperty(y))},de=e=>ne(e).flat().map(e=>+!!e),D=new Map,O=null,k=e=>{let t=D.get(e);if(t!==void 0)return t;if(typeof document>`u`||typeof getComputedStyle>`u`)return S;!O&&typeof MutationObserver<`u`&&(O=new MutationObserver(()=>{D.clear()}),O.observe(document.documentElement,{attributes:!0,attributeFilter:[`class`,`style`]}));let n=getComputedStyle(document.documentElement).getPropertyValue(e).trim(),r=document.createElement(`span`);r.style.color=n||`var(${e})`,document.documentElement.appendChild(r);let i=getComputedStyle(r).color;r.remove();let a=/rgba?\(\s*([\d.]+)(?:\s*,\s*|\s+)([\d.]+)(?:\s*,\s*|\s+)([\d.]+)/.exec(i);if(!a)return D.set(e,S),S;let o=e=>Math.max(0,Math.min(255,Math.round(Number(e)))).toString(16).padStart(2,`0`),s=`#${o(a[1])}${o(a[2])}${o(a[3])}`;return D.set(e,s),s},fe=e=>k(s(e).var),A=(e,t)=>e.text===t.text&&e.placeholder===t.placeholder&&e.modelLabel===t.modelLabel&&e.modelVariantLabel===t.modelVariantLabel&&e.modelIcon===t.modelIcon&&e.canSend===t.canSend&&e.canAbort===t.canAbort&&e.attachmentCount===t.attachmentCount&&M(e.attachmentPreviews,t.attachmentPreviews)&&N(e.citationRanges,t.citationRanges)&&P(e.chipRanges,t.chipRanges)&&e.appearance===t.appearance&&e.attachAria===t.attachAria&&e.attachTitle===t.attachTitle&&e.attachPhotosLabel===t.attachPhotosLabel&&e.attachFilesLabel===t.attachFilesLabel&&e.attachCancelLabel===t.attachCancelLabel&&e.sendAria===t.sendAria&&e.queueAria===t.queueAria&&e.stopAria===t.stopAria&&e.modelAria===t.modelAria&&e.agentAria===t.agentAria&&e.agentLabel===t.agentLabel&&e.agentColor===t.agentColor&&e.agentIdenticon.join(``)===t.agentIdenticon.join(``)&&e.agentIcon===t.agentIcon&&e.suppressed===t.suppressed&&e.showScrollToBottom===t.showScrollToBottom&&e.scrollAria===t.scrollAria&&j(e.autocomplete,t.autocomplete),j=(e,t)=>e.open===t.open&&e.highlightedIndex===t.highlightedIndex&&e.query===t.query&&e.highlightColor===t.highlightColor&&e.rows.length===t.rows.length&&e.rows.every((e,n)=>{let r=t.rows[n];return!!(r&&e.id===r.id&&e.title===r.title&&e.subtitle===r.subtitle&&e.badge===r.badge&&e.iconBase64===r.iconBase64)}),M=(e,t)=>e.length===t.length&&e.every((e,n)=>{let r=t[n];return!!(r&&e.id===r.id&&e.filename===r.filename&&e.mime===r.mime&&e.thumbnailBase64===r.thumbnailBase64&&e.removeAria===r.removeAria)}),N=(e,t)=>e.length===t.length&&e.every((e,n)=>e.start===t[n]?.start&&e.end===t[n]?.end),P=(e,t)=>e.length===t.length&&e.every((e,n)=>{let r=t[n];return!!(r&&e.start===r.start&&e.end===r.end&&e.triggerLength===r.triggerLength&&e.color===r.color)}),F=(e,t)=>{if(!e||!t||t.length===0)return[];let n=[],r=0;for(let e of t){let t=r;r+=e.text.length;let i=e.visual;if(!i)continue;let a=i.trigger.length;a<1||t+a>r||i.icon&&n.push({start:t,end:r,triggerLength:a,iconName:i.icon})}return n},I=(e,t)=>e.map(e=>({start:e.start,end:e.end,triggerLength:e.triggerLength,color:t})),L=e=>e.map(e=>`${e.id}:${e.filename}:${e.mimeType}:${e.dataUrl?.length??0}`).join(`|`),R=e=>{let t=e?.id;return typeof t==`string`&&t.trim()?t:``},z=e=>{if(typeof e==`number`&&Number.isFinite(e)&&e>=0)return Math.floor(e);if(typeof e==`string`&&e.trim()){let t=Number(e);if(Number.isFinite(t)&&t>=0)return Math.floor(t)}return null},B=e=>{let t=z(e?.selectionStart);if(t===null)return null;let n=z(e?.selectionEnd);return{start:t,end:n!==null&&n>=t?n:t}},V=e=>z(e?.index)??0,pe=(e,t)=>{let n=Math.max(0,e);return typeof t!=`number`||!Number.isFinite(t)?n:Math.max(0,Math.min(Math.floor(t),n))},me=e=>e.nextText===e.nativeOwnedText?{omitText:!0,forceText:!1}:e.nextText.length===0&&e.nativeOwnedText.length>0||e.preset?{omitText:!1,forceText:!0}:e.echoingNative?{omitText:!0,forceText:!1}:{omitText:!1,forceText:!0},he=e=>e.replacedText!==null&&e.incoming===e.replacedText,ge=e=>setTimeout(e,0),_e=e=>{e.applyDocument(e.text),ge(e.submit)},H=(e,t)=>e===t,ve=(e,t,n,r)=>{if(n.omitText&&e&&A(e,t))return null;let i={};if(n.omitText||(i.text=t.text,n.forceText&&(i.forceText=!0),n.forceText&&typeof r?.caret==`number`&&Number.isFinite(r.caret)&&(i.caret=Math.max(0,Math.floor(r.caret)))),!e){let{text:e,...n}=t;return Object.assign(i,n),i}let a=(n,r)=>{r(e[n],t[n])||(i[n]=t[n])};return a(`placeholder`,H),a(`modelLabel`,H),a(`modelVariantLabel`,H),a(`modelIcon`,H),a(`canSend`,H),a(`canAbort`,H),a(`attachmentCount`,H),a(`attachmentPreviews`,M),a(`citationRanges`,N),a(`chipRanges`,P),a(`appearance`,H),a(`attachAria`,H),a(`attachTitle`,H),a(`attachPhotosLabel`,H),a(`attachFilesLabel`,H),a(`attachCancelLabel`,H),a(`sendAria`,H),a(`queueAria`,H),a(`stopAria`,H),a(`modelAria`,H),a(`agentAria`,H),a(`agentLabel`,H),a(`agentColor`,H),a(`agentIdenticon`,(e,t)=>e.join(``)===t.join(``)),a(`agentIcon`,H),a(`suppressed`,H),a(`showScrollToBottom`,H),a(`scrollAria`,H),a(`autocomplete`,j),Object.keys(i).length===0?null:i},ye=e=>{let t=Array.isArray(e?.skipped)?e.skipped:[],n=[];for(let e of t){if(!e||typeof e!=`object`)continue;let t=e.name;typeof t==`string`&&t.trim()&&n.push(t)}return n},be=e=>{try{let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}catch{return null}},xe=(e,t=b)=>{let n=Array.isArray(e?.files)?e.files:[],r=[];for(let e of n){if(!e||typeof e!=`object`)continue;let n=e;if(typeof n.dataBase64!=`string`||n.dataBase64.length===0)continue;let i=be(n.dataBase64);if(!i||i.byteLength===0||i.byteLength>t)continue;let a=typeof n.name==`string`&&n.name.trim()?n.name:`file`,o=typeof n.mime==`string`&&n.mime.trim()?n.mime:`application/octet-stream`;r.push(new File([new Uint8Array(i)],a,{type:o}))}return r},U=80,Se=e=>typeof document>`u`||!e||!e.startsWith(`data:image/`)?Promise.resolve(null):new Promise(t=>{let n=new Image;n.decoding=`async`,n.onload=()=>{try{let e=document.createElement(`canvas`);e.width=U,e.height=U;let r=e.getContext(`2d`);if(!r){t(null);return}r.clearRect(0,0,U,U),r.drawImage(n,0,0,U,U);let i=e.toDataURL(`image/jpeg`,.72),a=i.indexOf(`,`);t(a>=0?i.slice(a+1):null)}catch{t(null)}},n.onerror=()=>t(null),n.src=e}),Ce=e=>c(e,C),W=()=>ie,G=((e=W)=>{let t=0,n=null,r=[],i=null,a=``,o=!1,s=!1,c=()=>{n!==null&&(clearTimeout(n),n=null)},l=(e,...t)=>{let n=i;n&&n[e](...t)},u=async()=>{if(r.length>0)return;let t=e(),n=await Promise.all([t.addListener(`textChanged`,e=>{let t=typeof e.text==`string`?e.text:``;a=t,l(`onText`,t,e.composing===!0,B(e))}),t.addListener(`send`,e=>{let t=typeof e.text==`string`?e.text:a;a=t,l(`onSend`,t)}),t.addListener(`abort`,()=>{l(`onAbort`)}),t.addListener(`attach`,()=>{l(`onAttach`)}),t.addListener(`filesPicked`,t=>{l(`onFiles`,xe(t),ye(t)),e().focus()}),t.addListener(`removeAttachment`,e=>{let t=R(e);t&&l(`onRemoveAttachment`,t)}),t.addListener(`openModel`,()=>{l(`onOpenModel`)}),t.addListener(`cycleAgent`,()=>{l(`onCycleAgent`)}),t.addListener(`openAgent`,()=>{l(`onOpenAgent`)}),t.addListener(`heightChanged`,e=>{l(`onHeight`,ce(e))}),t.addListener(`scrollToBottom`,()=>{l(`onScrollToBottom`)}),t.addListener(`autocompleteAccept`,e=>{l(`onAutocompleteAccept`,V(e))}),t.addListener(`autocompleteDismiss`,()=>{l(`onAutocompleteDismiss`)})]);if(r.length>0){for(let e of n)e.remove();return}r=n},d=n=>{t>0||(i=null,o=!1,E(n,!1),e().dismiss())};return{bind(e){i=e},rememberText(e){a=e},rememberState(e){a=e.text},conceal(){o||t===0||(o=!0,e().hide())},reveal(){!o||t===0||(o=!1,e().show())},async warm(){s||t>0||(s=!0,await e().present(T()))},async retain(n,i){c(),t+=1,o=!1,s=!0,a=i.text,E(n,!0),r.length===0&&await u(),await e().present(i)},release(e){t=Math.max(0,t-1),!(t>0)&&(c(),n=setTimeout(()=>{n=null,d(e)},0))},shutdown(n=document.documentElement){c();let r=s||t>0;t=0,s=!1,o=!1,i=null,E(n,!1),r&&e().dismiss()},snapshot(){return{retainCount:t,listenerCount:r.length,hidePending:n!==null,concealed:o,warmed:s}}}})(),we=()=>r(`YuriNavigation`),K=e=>e?.kind===`chat`||e?.kind===`draft`,q=e=>e?e.kind===`draft`||e.kind===`chat`&&e.routes.length<=1:!1,Te=(e,t)=>K(e)&&!K(t),Ee=(e=G)=>{q(o.getState().secondary)&&e.conceal()},De=(e=G)=>{let t=o.subscribe((t,n)=>{Te(n.secondary,t.secondary)&&e.conceal()}),n=[],r=!1;return i.getPlatform()===`ios`&&(async()=>{let t=we(),i=await t.addListener(`backStarted`,()=>{q(o.getState().secondary)&&e.conceal()}),a=await t.addListener(`backCancelled`,()=>{e.reveal()});if(r){i.remove(),a.remove();return}n=[i,a]})(),()=>{r=!0,t();for(let e of n)e.remove();n=[]}},Oe=e=>/^#[0-9a-fA-F]{6}$/.test(e),ke=e=>/^#[0-9a-fA-F]{8}$/.test(e),Ae=(e,t)=>/^[0-9a-fA-F]{2}$/.test(t)?Oe(e)?`${e}${t}`:ke(e)?`${e.slice(0,7)}${t}`:e:e,J=(e,t)=>typeof e==`string`&&e.trim().length>0?e:t,je=e=>{let t=e.colors.syntax.base,n=e.colors.syntax.tokens??{},r=(e,t)=>J(n[e],t);return[{name:`plain`,scope:[`source`,`support.type.property-name.css`],settings:{foreground:t.foreground}},{name:`classes`,scope:[`entity.name.type.class`],settings:{foreground:r(`className`,r(`class`,t.function))}},{name:`interfaces`,scope:[`entity.name.type.interface`,`entity.name.type`],settings:{foreground:r(`interface`,t.type)}},{name:`structs`,scope:[`entity.name.type.struct`],settings:{foreground:r(`struct`,t.function)}},{name:`enums`,scope:[`entity.name.type.enum`],settings:{foreground:r(`enum`,t.function)}},{name:`keys`,scope:[`meta.object-literal.key`,`support.type.property-name`],settings:{foreground:r(`key`,t.function)}},{name:`methods`,scope:[`entity.name.function.method`,`meta.function.method`],settings:{foreground:r(`method`,e.colors.status.success)}},{name:`functions`,scope:[`entity.name.function`,`support.function`,`meta.function-call.generic`],settings:{foreground:t.function,fontStyle:`bold`}},{name:`variables`,scope:[`variable`,`meta.variable`,`variable.other.object.property`],settings:{foreground:t.variable}},{name:`variablesOther`,scope:[`variable.other.object`,`variable.other.readwrite.alias`],settings:{foreground:r(`variableOther`,r(`method`,e.colors.status.success))}},{name:`globalVariables`,scope:[`variable.other.global`,`variable.language.this`],settings:{foreground:r(`variableGlobal`,t.number)}},{name:`localVariables`,scope:[`variable.other.local`],settings:{foreground:r(`variableLocal`,e.colors.surface.elevated)}},{name:`parameters`,scope:[`variable.parameter`,`meta.parameter`],settings:{foreground:r(`parameter`,t.foreground)}},{name:`properties`,scope:[`variable.other.property`,`meta.property`],settings:{foreground:r(`variableProperty`,e.colors.status.info)}},{name:`strings`,scope:[`string`,`string.other.link`,`markup.inline.raw.string.markdown`],settings:{foreground:t.string}},{name:`stringEscapeSequences`,scope:[`constant.character.escape`,`constant.other.placeholder`],settings:{foreground:r(`stringEscape`,t.foreground)}},{name:`keywords`,scope:[`keyword`],settings:{foreground:t.keyword}},{name:`keywordsControl`,scope:[`keyword.control.import`,`keyword.control.from`,`keyword.import`],settings:{foreground:r(`keywordImport`,t.operator)}},{name:`storageModifiers`,scope:[`storage.modifier`,`keyword.modifier`,`storage.type`],settings:{foreground:r(`storageModifier`,t.keyword)}},{name:`comments`,scope:[`comment`,`punctuation.definition.comment`],settings:{foreground:t.comment}},{name:`docComments`,scope:[`comment.documentation`,`comment.line.documentation`],settings:{foreground:r(`commentDoc`,e.colors.surface.mutedForeground)}},{name:`numbers`,scope:[`constant.numeric`],settings:{foreground:t.number}},{name:`booleans`,scope:[`constant.language`],settings:{foreground:r(`boolean`,t.type)}},{name:`operators`,scope:[`keyword.operator`],settings:{foreground:t.operator}},{name:`macros`,scope:[`entity.name.function.preprocessor`,`meta.preprocessor`],settings:{foreground:r(`macro`,t.keyword)}},{name:`preprocessor`,scope:[`meta.preprocessor`],settings:{foreground:r(`preprocessor`,r(`label`,t.number))}},{name:`urls`,scope:[`markup.underline.link`],settings:{foreground:r(`url`,e.colors.status.info)}},{name:`tags`,scope:[`entity.name.tag`],settings:{foreground:r(`tag`,t.keyword)}},{name:`jsxTags`,scope:[`support.class.component`],settings:{foreground:r(`jsxTag`,r(`label`,t.number))}},{name:`attributes`,scope:[`entity.other.attribute-name`,`meta.attribute`],settings:{foreground:r(`tagAttribute`,t.type)}},{name:`types`,scope:[`support.type`],settings:{foreground:t.type}},{name:`constants`,scope:[`variable.other.constant`,`variable.readonly`],settings:{foreground:r(`constant`,t.foreground)}},{name:`labels`,scope:[`entity.name.label`,`punctuation.definition.label`],settings:{foreground:r(`label`,r(`variableGlobal`,t.number))}},{name:`namespaces`,scope:[`entity.name.namespace`,`storage.modifier.namespace`,`markup.bold.markdown`],settings:{foreground:r(`namespace`,t.type)}},{name:`modules`,scope:[`entity.name.module`,`storage.modifier.module`],settings:{foreground:r(`module`,t.operator)}},{name:`typeParameters`,scope:[`variable.type.parameter`,`variable.parameter.type`],settings:{foreground:r(`typeParameter`,t.function)}},{name:`exceptions`,scope:[`keyword.control.exception`,`keyword.control.trycatch`],settings:{foreground:r(`exception`,r(`label`,t.number))}},{name:`decorators`,scope:[`meta.decorator`,`punctuation.decorator`,`entity.name.function.decorator`],settings:{foreground:r(`decorator`,t.type)}},{name:`calls`,scope:[`variable.function`],settings:{foreground:t.foreground}},{name:`punctuation`,scope:[`punctuation`,`punctuation.terminator`,`punctuation.definition.tag`,`punctuation.separator`,`punctuation.definition.string`,`punctuation.section.block`],settings:{foreground:r(`punctuation`,t.comment)}},{name:`yellow`,scope:[`storage.type.numeric.go`,`storage.type.byte.go`,`storage.type.boolean.go`,`storage.type.string.go`,`storage.type.uintptr.go`,`storage.type.error.go`,`storage.type.rune.go`,`constant.language.go`,`support.class.dart`,`keyword.other.documentation`,`storage.modifier.import.java`,`punctuation.definition.list.begin.markdown`,`punctuation.definition.quote.begin.markdown`,`meta.separator.markdown`,`entity.name.section.markdown`],settings:{foreground:t.type}},{name:`green`,scope:[],settings:{foreground:r(`method`,e.colors.status.success)}},{name:`cyan`,scope:[`markup.italic.markdown`,`support.type.python`,`variable.legacy.builtin.python`,`support.constant.property-value.css`,`storage.modifier.attribute.swift`],settings:{foreground:t.string}},{name:`blue`,scope:[],settings:{foreground:t.keyword}},{name:`purple`,scope:[`keyword.channel.go`,`keyword.other.platform.os.swift`],settings:{foreground:t.number}},{name:`magenta`,scope:[`punctuation.definition.heading.markdown`],settings:{foreground:r(`label`,r(`variableGlobal`,t.number))}},{name:`red`,scope:[],settings:{foreground:t.operator}},{name:`orange`,scope:[],settings:{foreground:t.function}}]},Y=e=>{let t=e.colors.surface,n=e.colors.interactive,r=e.colors.status,i=e.colors.syntax.base,a=e.colors.syntax.highlights??{},o=J(a.diffAddedBackground,r.successBackground),s=J(a.diffRemovedBackground,r.errorBackground);return{"editor.background":t.background,"editor.foreground":t.foreground,"editor.hoverHighlightBackground":J(n.hover,t.subtle),"editor.lineHighlightBackground":t.muted,"editor.selectionBackground":n.selection,"editor.selectionHighlightBackground":n.selection,"editor.findMatchBackground":i.type,"editor.findMatchHighlightBackground":Ae(i.type,`cc`),"editor.findRangeHighlightBackground":t.muted,"editor.inactiveSelectionBackground":t.elevated,"editor.lineHighlightBorder":t.elevated,"editor.rangeHighlightBackground":J(n.active,n.borderHover),"notifications.background":t.elevated,"editorInlayHint.typeBackground":t.subtle,"editorInlayHint.typeForeground":t.foreground,"editorWhitespace.foreground":n.borderHover,"editorIndentGuide.background1":t.subtle,"editorHoverWidget.background":t.elevated,"editorLineNumber.activeForeground":J(a.lineNumberActive,t.foreground),"editorLineNumber.foreground":J(a.lineNumber,t.mutedForeground),"editorGutter.background":t.background,"editorGutter.modifiedBackground":r.info,"editorGutter.addedBackground":r.success,"editorGutter.deletedBackground":r.error,"editorBracketMatch.background":t.elevated,"editorBracketMatch.border":t.subtle,"editorError.foreground":r.error,"editorWarning.foreground":r.warning,"editorInfo.foreground":r.info,"diffEditor.insertedTextBackground":o,"diffEditor.removedTextBackground":s,"editorGroupHeader.tabsBackground":t.background,"editorGroup.border":n.border,"tab.activeBackground":t.background,"tab.inactiveBackground":t.muted,"tab.inactiveForeground":t.mutedForeground,"tab.activeForeground":t.foreground,"tab.hoverBackground":t.subtle,"tab.unfocusedHoverBackground":t.subtle,"tab.border":n.border,"tab.activeModifiedBorder":i.type,"tab.inactiveModifiedBorder":r.info,"tab.unfocusedActiveModifiedBorder":i.type,"tab.unfocusedInactiveModifiedBorder":r.info,"editorWidget.background":t.muted,"editorWidget.border":n.border,"editorSuggestWidget.background":t.background,"editorSuggestWidget.border":n.border,"editorSuggestWidget.foreground":t.foreground,"editorSuggestWidget.highlightForeground":t.mutedForeground,"editorSuggestWidget.selectedBackground":t.subtle,"peekView.border":n.border,"peekViewEditor.background":t.background,"peekViewEditor.matchHighlightBackground":t.subtle,"peekViewResult.background":t.muted,"peekViewResult.fileForeground":t.foreground,"peekViewResult.lineForeground":t.mutedForeground,"peekViewResult.matchHighlightBackground":t.subtle,"peekViewResult.selectionBackground":t.elevated,"peekViewResult.selectionForeground":t.mutedForeground,"peekViewTitle.background":t.subtle,"peekViewTitleDescription.foreground":t.mutedForeground,"peekViewTitleLabel.foreground":t.foreground,"merge.currentHeaderBackground":r.success,"merge.currentContentBackground":J(a.diffAdded,r.success),"merge.incomingHeaderBackground":r.info,"merge.incomingContentBackground":J(a.diffModified,r.info),"merge.border":n.border,"merge.commonContentBackground":t.subtle,"merge.commonHeaderBackground":t.muted,"panel.background":t.background,"panel.border":n.border,"panelTitle.activeBorder":n.borderHover,"panelTitle.activeForeground":t.foreground,"panelTitle.inactiveForeground":t.mutedForeground,"statusBar.background":t.background,"statusBar.foreground":t.foreground,"statusBar.border":n.border,"statusBar.debuggingBackground":r.error,"statusBar.debuggingForeground":r.errorForeground,"statusBar.noFolderBackground":t.subtle,"statusBar.noFolderForeground":t.mutedForeground,"titleBar.activeBackground":t.background,"titleBar.activeForeground":t.foreground,"titleBar.inactiveBackground":t.muted,"titleBar.inactiveForeground":t.mutedForeground,"titleBar.border":n.border,"menu.foreground":t.foreground,"menu.background":t.background,"menu.selectionForeground":t.foreground,"menu.selectionBackground":t.subtle,"menu.border":n.border,"editorInlayHint.foreground":t.mutedForeground,"editorInlayHint.background":t.subtle,"terminal.foreground":t.foreground,"terminal.background":t.background,"terminalCursor.foreground":t.foreground,"terminalCursor.background":t.background,"terminal.ansiRed":J(a.diffRemoved,r.error),"terminal.ansiGreen":J(a.diffAdded,r.success),"terminal.ansiYellow":r.warning,"terminal.ansiBlue":J(a.diffModified,r.info),"terminal.ansiMagenta":i.keyword,"terminal.ansiCyan":i.type,"activityBar.background":t.background,"activityBar.foreground":t.foreground,"activityBar.inactiveForeground":t.mutedForeground,"activityBar.activeBorder":t.foreground,"activityBar.border":n.border,"sideBar.background":t.background,"sideBar.foreground":t.foreground,"sideBar.border":n.border,"sideBarTitle.foreground":t.foreground,"sideBarSectionHeader.background":t.muted,"sideBarSectionHeader.foreground":t.foreground,"sideBarSectionHeader.border":n.border,"sideBar.activeBackground":t.subtle,"sideBar.activeForeground":t.foreground,"sideBar.hoverBackground":t.muted,"sideBar.hoverForeground":t.foreground,"list.warningForeground":r.warning,"list.errorForeground":r.error,"list.inactiveSelectionBackground":t.subtle,"list.activeSelectionBackground":t.elevated,"list.inactiveSelectionForeground":t.foreground,"list.activeSelectionForeground":t.foreground,"list.hoverForeground":t.foreground,"list.hoverBackground":t.muted,"input.background":t.muted,"input.foreground":t.foreground,"input.border":n.border,"input.placeholderForeground":t.mutedForeground,"inputOption.activeBorder":n.border,"inputOption.activeBackground":t.elevated,"inputOption.activeForeground":t.foreground,"inputValidation.infoBackground":r.infoBackground,"inputValidation.infoBorder":r.infoBorder,"inputValidation.warningBackground":r.warningBackground,"inputValidation.warningBorder":r.warningBorder,"inputValidation.errorBackground":r.errorBackground,"inputValidation.errorBorder":r.errorBorder,"dropdown.background":t.muted,"dropdown.foreground":t.foreground,"dropdown.border":n.border,"dropdown.listBackground":t.background,"badge.background":e.colors.primary.base,"activityBarBadge.background":e.colors.primary.base,"button.background":e.colors.primary.base,"button.foreground":J(e.colors.primary.foreground,t.background),"badge.foreground":J(e.colors.primary.foreground,t.background),"activityBarBadge.foreground":J(e.colors.primary.foreground,t.background)}};function Me(e){return{name:e.metadata.name,type:e.metadata.variant,colors:Y(e),tokenColors:je(e)}}var Ne=e=>/^#[0-9a-fA-F]{8}$/.test(e),X=e=>Ne(e)?e.slice(0,7):e;function Pe(e,t){return Object.defineProperty(e,"toString",{value:()=>t,enumerable:!1,configurable:!0}),Object.defineProperty(e,Symbol.toPrimitive,{value:()=>t,enumerable:!1,configurable:!0}),e}var Z=new Map,Q=new Set,Fe=(e,t)=>{let n=e.colors?.[`editor.background`],r=e.colors?.[`editor.foreground`],i=n?X(n):void 0,a=r?X(r):void 0;if(!i||!a)throw Error(`Theme "${t}" is missing editor.background/editor.foreground`);let o=e.tokenColors??[];return Pe({...e,name:t,fg:a,bg:i,settings:o},t)},Ie=e=>Me(e),$=e=>{let t=Z.get(e.metadata.id);if(t)return t;let n=Fe(Ie(e),e.metadata.id);return Z.set(e.metadata.id,n),n},Le=e=>{let t=e.metadata.id;if(Q.has(t))return;let n=$(e);a(t,async()=>n),Q.add(t)};export{p as A,Ce as C,E as D,me as E,f as M,he as O,Se as S,k as T,F as _,G as a,se as b,le as c,ve as d,oe as f,j as g,_e as h,Ee as i,m as j,ee as k,L as l,W as m,$ as n,v as o,w as p,De as r,ue as s,Le as t,I as u,A as v,pe as w,de as x,fe as y};
@@ -1 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{_ as t,m as n,p as r}from"./desktop-DpAcrF1h.js";import{it as i,rt as a}from"./vendor-base-ui-CdzJ6My_.js";import{n as o}from"./vendor-react-BP2cRVqX.js";import{a as s,i as c,o as l,t as u}from"./store-BhjP3zxz.js";import{n as d,t as f}from"./vendor-class-variance-authority-BLUaYARZ.js";import{t as p}from"./vendor-tailwind-merge-BicNWLTg.js";var m=e(i(),1),h=o(),g=async(e,t)=>{if(!r())throw Error(`Desktop runtime is not available`);return n(e,t)},_=async()=>{if(t())try{await g(`desktop_start_window_drag`)}catch{}},v=async e=>{if(t())try{await g(`desktop_set_window_title`,{title:e})}catch{}},y=async(e,n)=>{if(t())try{await g(`desktop_set_window_theme`,{themeMode:e,themeVariant:n})}catch{}},ee=async e=>{if(t())try{await g(`desktop_set_menu_locale`,{locale:e})}catch{}},b=async()=>{if(!t())return null;try{let e=await g(`desktop_get_app_version`);return typeof e==`string`&&e.trim().length>0?e:null}catch{return null}},x=m.createContext(null),S=a(),C=e=>{let t=(0,h.c)(19),{children:n}=e,r=c(w),i=c(te),a=c(T),o=c(ne),d,f;t[0]===r?(d=t[1],f=t[2]):(d=()=>{typeof document>`u`||(document.documentElement.lang=r)},f=[r],t[0]=r,t[1]=d,t[2]=f),m.useEffect(d,f);let p,g;t[3]!==a||t[4]!==r?(p=()=>{a===null&&ee(r)},g=[r,a],t[3]=a,t[4]=r,t[5]=p,t[6]=g):(p=t[5],g=t[6]),m.useEffect(p,g);let _;t[7]===i?_=t[8]:(_=(e,t)=>u(i,e,t),t[7]=i,t[8]=_);let v=_,y;t[9]===v?y=t[10]:(y=e=>v(l[e]),t[9]=v,t[10]=y);let b;t[11]!==r||t[12]!==o||t[13]!==v||t[14]!==y?(b={locale:r,locales:s,setLocale:o,label:y,t:v},t[11]=r,t[12]=o,t[13]=v,t[14]=y,t[15]=b):b=t[15];let C=b,E;return t[16]!==n||t[17]!==C?(E=(0,S.jsx)(x.Provider,{value:C,children:n}),t[16]=n,t[17]=C,t[18]=E):E=t[18],E};function w(e){return e.locale}function te(e){return e.dictionary}function T(e){return e.loadingLocale}function ne(e){return e.setLocale}var E={startingApi:`Starting OpenCode API…`,initializing:`Initializing…`,connecting:`Connecting…`,connected:`Connected!`,connectionError:`Connection error`,disconnected:`Disconnected`,reconnecting:`Reconnecting…`,initialDataLoadFailed:`OpenCode connected, but initial data load failed.`,cliNotFound:`OpenCode CLI not found. Please install it first.`,providersReady:`✓ Providers`,providersLoading:`… Providers`,agentsReady:`✓ Agents`,agentsLoading:`… Agents`,startingDevServer:e=>`Starting webview dev server (${e})...`,waitingDevServer:(e,t)=>`Waiting for webview dev server (${e})... attempt ${t}`,loadingData:(e,t)=>`Loading data (${e}, ${t})…`},re={startingApi:`Démarrage de l’API OpenCode…`,initializing:`Initialisation…`,connecting:`Connexion…`,connected:`Connecté !`,connectionError:`Erreur de connexion`,disconnected:`Déconnecté`,reconnecting:`Reconnexion…`,initialDataLoadFailed:`OpenCode est connecté, mais le chargement initial des données a échoué.`,cliNotFound:`L’interface en ligne de commande OpenCode est introuvable. Veuillez l’installer d’abord.`,providersReady:`✓ Fournisseurs`,providersLoading:`… Fournisseurs`,agentsReady:`✓ Agents`,agentsLoading:`… Agents`,startingDevServer:e=>`Démarrage du serveur de développement de la webview (${e})...`,waitingDevServer:(e,t)=>`En attente du serveur de développement de la webview (${e})... tentative ${t}`,loadingData:(e,t)=>`Chargement des données (${e}, ${t})…`},D={startingApi:`正在启动 OpenCode API…`,initializing:`正在初始化…`,connecting:`正在连接…`,connected:`已连接!`,connectionError:`连接错误`,disconnected:`已断开连接`,reconnecting:`正在重新连接…`,initialDataLoadFailed:`OpenCode 已连接,但初始数据加载失败。`,cliNotFound:`未找到 OpenCode CLI。请先安装它。`,providersReady:`✓ 提供商`,providersLoading:`… 提供商`,agentsReady:`✓ Agent`,agentsLoading:`… Agent`,startingDevServer:e=>`正在启动 webview 开发服务器 (${e})...`,waitingDevServer:(e,t)=>`正在等待 webview 开发服务器 (${e})... 第 ${t} 次尝试`,loadingData:(e,t)=>`正在加载数据 (${e}, ${t})…`},O={startingApi:`正在啟動 OpenCode API…`,initializing:`正在初始化…`,connecting:`正在連線…`,connected:`已連線!`,connectionError:`連線錯誤`,disconnected:`已中斷連線`,reconnecting:`正在重新連線…`,initialDataLoadFailed:`OpenCode 已連線,但初始資料載入失敗。`,cliNotFound:`找不到 OpenCode CLI。請先安裝。`,providersReady:`✓ 提供者`,providersLoading:`… 提供者`,agentsReady:`✓ 代理`,agentsLoading:`… 代理`,startingDevServer:e=>`正在啟動 webview 開發伺服器 (${e})...`,waitingDevServer:(e,t)=>`正在等待 webview 開發伺服器 (${e})... 第 ${t} 次嘗試`,loadingData:(e,t)=>`正在載入資料 (${e}, ${t})…`},k={startingApi:`Запуск OpenCode API…`,initializing:`Ініціалізація…`,connecting:`Підключення…`,connected:`Підключено!`,connectionError:`Помилка підключення`,disconnected:`Відключено`,reconnecting:`Повторне підключення…`,initialDataLoadFailed:`OpenCode підключено, але початкове завантаження даних не вдалося.`,cliNotFound:`OpenCode CLI не знайдено. Спершу встановіть його.`,providersReady:`✓ Провайдери`,providersLoading:`… Провайдери`,agentsReady:`✓ Агенти`,agentsLoading:`… Агенти`,startingDevServer:e=>`Запуск dev-сервера webview (${e})...`,waitingDevServer:(e,t)=>`Очікування dev-сервера webview (${e})... спроба ${t}`,loadingData:(e,t)=>`Завантаження даних (${e}, ${t})…`},A={startingApi:`Iniciando la API de OpenCode…`,initializing:`Inicializando…`,connecting:`Conectando…`,connected:`¡Conectado!`,connectionError:`Error de conexión`,disconnected:`Desconectado`,reconnecting:`Reconectando…`,initialDataLoadFailed:`OpenCode se conectó, pero falló la carga inicial de datos.`,cliNotFound:`No se encontró OpenCode CLI. Instálalo primero.`,providersReady:`✓ Proveedores`,providersLoading:`… Proveedores`,agentsReady:`✓ Agentes`,agentsLoading:`… Agentes`,startingDevServer:e=>`Iniciando el servidor de desarrollo de webview (${e})...`,waitingDevServer:(e,t)=>`Esperando el servidor de desarrollo de webview (${e})... intento ${t}`,loadingData:(e,t)=>`Cargando datos (${e}, ${t})…`},j={startingApi:`Iniciando a API do OpenCode…`,initializing:`Inicializando…`,connecting:`Conectando…`,connected:`Conectado!`,connectionError:`Erro de conexão`,disconnected:`Desconectado`,reconnecting:`Reconectando…`,initialDataLoadFailed:`OpenCode conectado, mas o carregamento inicial dos dados falhou.`,cliNotFound:`OpenCode CLI não encontrado. Instale-o primeiro.`,providersReady:`✓ Provedores`,providersLoading:`… Provedores`,agentsReady:`✓ Agentes`,agentsLoading:`… Agentes`,startingDevServer:e=>`Iniciando o servidor de desenvolvimento da webview (${e})...`,waitingDevServer:(e,t)=>`Aguardando o servidor de desenvolvimento da webview (${e})... tentativa ${t}`,loadingData:(e,t)=>`Carregando dados (${e}, ${t})…`},M={startingApi:`OpenCode API 시작 중…`,initializing:`초기화 중…`,connecting:`연결 중…`,connected:`연결됨!`,connectionError:`연결 오류`,disconnected:`연결 끊김`,reconnecting:`다시 연결 중…`,initialDataLoadFailed:`OpenCode에 연결되었지만 초기 데이터 로드에 실패했습니다.`,cliNotFound:`OpenCode CLI를 찾을 수 없습니다. 먼저 설치하세요.`,providersReady:`✓ 공급자`,providersLoading:`… 공급자`,agentsReady:`✓ 에이전트`,agentsLoading:`… 에이전트`,startingDevServer:e=>`webview 개발 서버 시작 중 (${e})...`,waitingDevServer:(e,t)=>`webview 개발 서버 대기 중 (${e})... ${t}번째 시도`,loadingData:(e,t)=>`데이터 로드 중 (${e}, ${t})…`},N={startingApi:`Uruchamianie API OpenCode…`,initializing:`Inicjalizacja…`,connecting:`Łączenie…`,connected:`Połączono!`,connectionError:`Błąd połączenia`,disconnected:`Rozłączono`,reconnecting:`Ponowne łączenie…`,initialDataLoadFailed:`OpenCode połączony, ale początkowe ładowanie danych nie powiodło się.`,cliNotFound:`Nie znaleziono OpenCode CLI. Najpierw go zainstaluj.`,providersReady:`✓ Dostawcy`,providersLoading:`… Dostawcy`,agentsReady:`✓ Agenci`,agentsLoading:`… Agenci`,startingDevServer:e=>`Uruchamianie serwera deweloperskiego webview (${e})...`,waitingDevServer:(e,t)=>`Oczekiwanie na serwer deweloperski webview (${e})... próba ${t}`,loadingData:(e,t)=>`Ładowanie danych (${e}, ${t})…`},P={startingApi:`OpenCode API を起動中…`,initializing:`初期化中…`,connecting:`接続中…`,connected:`接続完了!`,connectionError:`接続エラー`,disconnected:`切断されました`,reconnecting:`再接続中…`,initialDataLoadFailed:`OpenCode に接続しましたが、初期データの読み込みに失敗しました。`,cliNotFound:`OpenCode CLI が見つかりません。先にインストールしてください。`,providersReady:`✓ プロバイダ`,providersLoading:`… プロバイダ`,agentsReady:`✓ エージェント`,agentsLoading:`… エージェント`,startingDevServer:e=>`Webview 開発サーバーを起動中 (${e})...`,waitingDevServer:(e,t)=>`Webview 開発サーバーを待機中 (${e})... 試行 ${t}`,loadingData:(e,t)=>`データを読み込み中 (${e}, ${t})…`},F=e=>I[e],I={en:E,fr:re,"zh-CN":D,"zh-TW":O,uk:k,es:A,"pt-BR":j,ko:M,pl:N,ja:P},L={en:`en-US`,fr:`fr-FR`,"zh-CN":`zh-CN`,"zh-TW":`zh-TW`,uk:`uk-UA`,es:`es-ES`,"pt-BR":`pt-BR`,ko:`ko-KR`,pl:`pl-PL`,ja:`ja-JP`},R=e=>L[e]??`en-US`,z=()=>R(c.getState().locale);function B(){let e=m.useContext(x);if(!e)throw Error(`useI18n must be used within I18nProvider`);return e}async function V(e){let t=null;if(typeof navigator<`u`&&navigator.clipboard?.writeText)try{return await navigator.clipboard.writeText(e),{ok:!0,method:`clipboard`}}catch(e){t=e instanceof Error?e.message:String(e)}if(typeof document<`u`&&document.body){let t=document.createElement(`textarea`);t.value=e,t.setAttribute(`readonly`,``),t.style.position=`fixed`,t.style.top=`-1000px`,t.style.left=`-1000px`,document.body.appendChild(t),t.select(),t.setSelectionRange(0,t.value.length);let n=document.execCommand(`copy`);if(document.body.removeChild(t),n)return{ok:!0,method:`execCommand`}}return{ok:!1,error:t??`Clipboard access denied in current context`}}function H(...e){return p(d(e))}var U=()=>typeof navigator>`u`?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||``),W=()=>typeof navigator>`u`?!1:/Windows/.test(navigator.userAgent||``),G=()=>U()?`common.revealPath.finder`:W()?`common.revealPath.fileExplorer`:`common.revealPath.fileManager`,K=e=>U()&&t()?e.metaKey:e.ctrlKey,q=()=>U()&&t()?`⌘`:`Ctrl`,J=(e,t)=>{let n=e??``,r=Math.max(16,t?.maxLength??45);if(n.length<=r)return n;let i=n.split(`/`);if(i.length<=1)return n;let a=i.pop()??``;if(!a)return n;let o=Math.max(0,r-(a.length+2));if(o<=0)return`…/${a}`;let s=``;for(let e of i){if(!e)continue;let t=s?`${s}/${e}`:e;if(t.length>o)break;s=t}if(!s){let e=i[0]??``;s=e?e.slice(0,o):``}return s?`${s}…/${a}`:`…/${a}`},Y=e=>e?e===`/`?`/`:e.replace(/\/+$/,``):``;function X(e,t){if(!e)return``;let n=Y(e);if(n===`/`)return`/`;let r=t?Y(t):void 0;if(r&&r!==`/`){if(n===r)return`~`;if(n.startsWith(`${r}/`)){let e=n.slice(r.length+1);return e?`~/${e}`:`~`}}return n}function ie(e,t){if(!e)return`/`;let n=Y(e);if(!n||n===`/`)return`/`;let r=t?Y(t):void 0;return r&&r!==`/`&&n===r?`~`:n.split(`/`).pop()||n||`/`}function ae(e,t){let n=(0,h.c)(3),r;return n[0]!==e||n[1]!==t?(r=n=>{for(let r of[e,t])r&&(typeof r==`function`?r(n):r.current=n)},n[0]=e,n[1]=t,n[2]=r):r=n[2],r}function oe(e,t){let n={...t};for(let r in e){let i=t[r],a=e[r];n[r]=/^on[A-Z]/.test(r)&&typeof i==`function`&&typeof a==`function`?(...e)=>{a(...e),i(...e)}:r===`className`&&typeof i==`string`&&typeof a==`string`?`${a} ${i}`:r===`style`&&typeof i==`object`&&typeof a==`object`?{...a,...i}:a}return n}var Z=m.forwardRef(function(e,t){let n=(0,h.c)(3),{children:r,...i}=e,a=m.isValidElement(r)?r:null,o=ae(t,a?a.ref:void 0);if(!a)return null;let s=oe(a.props,i),c;return n[0]!==o||n[1]!==s?(c={...s,ref:o},n[0]=o,n[1]=s,n[2]=c):c=n[2],m.cloneElement(a,c)}),Q=[`bg-[var(--surface-muted)] text-foreground border-0 shadow-none`,`hover:bg-[color-mix(in_srgb,var(--foreground)_6%,var(--surface-muted))]`,`active:bg-[color-mix(in_srgb,var(--foreground)_12%,var(--surface-muted))]`,`focus-visible:border-transparent focus-visible:ring-foreground/20`].join(` `),$=[`bg-[color-mix(in_srgb,var(--status-error)_7%,var(--background))]`,`text-[var(--status-error)]`,`border border-[color-mix(in_srgb,var(--status-error)_9%,transparent)]`,`hover:bg-[color-mix(in_srgb,var(--status-error)_11%,var(--background))]`,`active:bg-[color-mix(in_srgb,var(--status-error)_16%,var(--background))]`,`dark:bg-[color-mix(in_srgb,var(--status-error)_9%,transparent)]`,`dark:border-[color-mix(in_srgb,var(--status-error)_14%,transparent)]`,`dark:hover:bg-[color-mix(in_srgb,var(--status-error)_14%,transparent)]`,`dark:active:bg-[color-mix(in_srgb,var(--status-error)_20%,transparent)]`].join(` `),se=f([`group relative inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] typography-ui-label font-medium tracking-[0.01em] shrink-0 select-none`,`transition-[background-color,border-color,color,opacity,filter,transform] duration-150 ease-out outline-none`,`focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]`,`aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive`,`disabled:pointer-events-none disabled:opacity-50`,`[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4`],{variants:{variant:{default:Q,destructive:H($,`focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40`),neutral:Q,outline:Q,mobileGlass:`yuri-mobile-floating-action text-foreground hover:brightness-105 active:bg-interactive-active focus-visible:border-transparent focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]`,chip:H(Q,`aria-pressed:bg-[color-mix(in_srgb,var(--foreground)_6%,var(--surface-muted))]`,`aria-pressed:hover:bg-[color-mix(in_srgb,var(--foreground)_8%,var(--surface-muted))]`,`aria-pressed:active:bg-[color-mix(in_srgb,var(--foreground)_10%,var(--surface-muted))]`),secondary:`bg-interactive-hover text-foreground hover:bg-interactive-active`,ghost:`text-foreground hover:bg-interactive-hover hover:text-foreground active:bg-interactive-active`,link:`text-primary underline-offset-4 hover:underline`},size:{default:`h-9 px-3.5 has-[>svg]:px-3`,sm:`h-8 gap-1.5 px-2.5 has-[>svg]:px-2 rounded-[9px] supports-[corner-shape:squircle]:rounded-[50px]`,xs:`h-6 gap-1 px-2 typography-micro has-[>svg]:px-1.5 rounded-[7px] supports-[corner-shape:squircle]:rounded-[50px]`,lg:`h-10 px-4 has-[>svg]:px-3.5 rounded-[12px] supports-[corner-shape:squircle]:rounded-[50px]`,icon:`size-9`,mobileIcon:`size-10 min-h-10 min-w-10 rounded-full`}},defaultVariants:{variant:`default`,size:`default`}}),ce=new Set([`icon`,`mobileIcon`,`xs`]);function le(e){let t=(0,h.c)(20),n,r,i,a,o,s;t[0]===e?(n=t[1],r=t[2],i=t[3],a=t[4],o=t[5],s=t[6]):({className:n,variant:s,size:i,asChild:a,type:o,...r}=e,t[0]=e,t[1]=n,t[2]=r,t[3]=i,t[4]=a,t[5]=o,t[6]=s);let c=a!==void 0&&a,l=c?Z:`button`,u;t[7]!==c||t[8]!==o?(u=c?o===void 0?{}:{type:o}:{type:o??`button`},t[7]=c,t[8]=o,t[9]=u):u=t[9];let d=u,f=i!=null&&ce.has(i)?`compact`:void 0,p;t[10]!==n||t[11]!==i||t[12]!==s?(p=H(se({variant:s,size:i,className:n})),t[10]=n,t[11]=i,t[12]=s,t[13]=p):p=t[13];let m;return t[14]!==l||t[15]!==f||t[16]!==r||t[17]!==p||t[18]!==d?(m=(0,S.jsx)(l,{"data-slot":`button`,"data-mobile-press-feedback":f,className:p,...d,...r}),t[14]=l,t[15]=f,t[16]=r,t[17]=p,t[18]=d,t[19]=m):m=t[19],m}export{g as _,X as a,_ as b,K as c,V as d,B as f,b as g,C as h,ie as i,U as l,F as m,Z as n,q as o,z as p,H as r,G as s,le as t,J as u,y as v,v as y};
@@ -1 +0,0 @@
1
- import{w as e}from"./runtime-auth-ef9W7A43.js";import{r as t,t as n}from"./runtime-switch-CAZiOV2G.js";import{t as r}from"./runtimeAPIRegistry-C2VogTny.js";var i=[`local`,`remote`,null],a=[`ok`,`not-configured`,`unreachable`,`incompatible`,`wrong-service`,`missing`];function o(e){if(!e||typeof e!=`object`)return{valid:!1};let t=e,n=t.target,r=t.status;if(n!==null&&(typeof n!=`string`||!i.includes(n))||typeof r!=`string`||!a.includes(r))return{valid:!1};if(n===`remote`||n===`local`){if(r===`ok`&&n===`local`)return{valid:!0,outcome:{target:`local`,status:`ok`}};if(r===`ok`&&n===`remote`)return typeof t.hostId!=`string`||typeof t.url!=`string`?{valid:!1}:{valid:!0,outcome:{target:`remote`,status:`ok`,hostId:t.hostId,url:t.url}};if(r===`unreachable`)return n===`local`?{valid:!0,outcome:{target:`local`,status:`unreachable`}}:typeof t.hostId!=`string`||typeof t.url!=`string`?{valid:!1}:{valid:!0,outcome:{target:`remote`,status:`unreachable`,hostId:t.hostId,url:t.url}};if(r===`incompatible`||r===`wrong-service`)return n!==`remote`||typeof t.hostId!=`string`||typeof t.url!=`string`?{valid:!1}:{valid:!0,outcome:{target:`remote`,status:r,hostId:t.hostId,url:t.url}};if(r===`missing`)return n!==`remote`||typeof t.hostId!=`string`?{valid:!1}:{valid:!0,outcome:{target:`remote`,status:`missing`,hostId:t.hostId}}}if(n===null){if(r===`not-configured`)return{valid:!0,outcome:{target:null,status:`not-configured`}};if(r===`missing`)return{valid:!1}}return{valid:!1}}function s(e){if(!e.isDesktopShell)return null;let t=e.bootOutcome;if(!t)return null;if(t.status===`ok`){if(t.target===`local`)return{screen:`main`};if(t.target===`remote`)return{screen:`main`,hostId:t.hostId,url:t.url}}if(t.target===null&&t.status===`not-configured`)return{screen:`chooser`};if(t.target===`local`&&t.status===`unreachable`)return{screen:`recovery`,variant:`local-unavailable`};if(t.target===`remote`){if(t.status===`unreachable`)return{screen:`recovery`,variant:`remote-unreachable`,hostId:t.hostId,url:t.url};if(t.status===`incompatible`)return{screen:`recovery`,variant:`remote-incompatible`,hostId:t.hostId,url:t.url};if(t.status===`wrong-service`)return{screen:`recovery`,variant:`remote-wrong-service`,hostId:t.hostId,url:t.url};if(t.status===`missing`)return{screen:`recovery`,variant:`remote-missing`,hostId:t.hostId}}return null}function c(e){return e.isDesktopShell?e.bootOutcomeKnown?e.bootViewIsMain===!1||e.isInitialized:!1:e.isInitialized}function l(e){return e.isDesktopShell&&!e.isDesktopLocalOriginActive}function u(){if(f()!==`valid`)return null;let e=o(d());return e.valid?e.outcome:null}var d=()=>{if(typeof window>`u`)return;let e=window.__YURI_DESKTOP_BOOT_OUTCOME__;if(e!=null)return e;let t=window.__YURI_DESKTOP_BOOT__;if(t&&typeof t.getOutcome==`function`)try{return t.getOutcome()}catch{return}return e};function f(){if(typeof window>`u`)return`not-injected`;let e=d();return e==null?`not-injected`:o(e).valid?`valid`:`malformed`}var p=()=>typeof window>`u`?null:window.__YURI_ELECTRON__??null,m=()=>typeof window>`u`?null:window.__YURI_DESKTOP__??null,h=()=>p()?.runtime===`electron`,g=()=>h()&&p()?.packaged===!0,_=e=>{if(!h())return null;let t=m()?.getPathForFile?.(e);return typeof t==`string`&&t.trim()?t:null},v=()=>{if(typeof window>`u`)return null;let e=window.__YURI_PLATFORM__;return typeof e==`string`?e:null},y=()=>{if(!h())return!1;let e=v();return e===`win32`||e===`linux`},b=(e=v())=>e===`linux`?`left`:`right`,x=(e,t=v())=>e===`left`||e===`right`?e:b(t),S=()=>typeof m()?.invoke==`function`,C=()=>h()&&S(),w=async(e,t)=>{let n=m();return typeof n?.invoke==`function`?n.invoke(e,t??{}):null},T=async()=>{if(!C()||!P())return null;try{let e=await w(`desktop_get_launch_at_login`);return!e||typeof e.supported!=`boolean`||typeof e.enabled!=`boolean`?null:e}catch(e){return console.warn(`Failed to get launch at login status`,e),null}},E=async e=>{if(!C()||!P())return null;try{let t=await w(`desktop_set_launch_at_login`,{enabled:e});return!t||typeof t.supported!=`boolean`||typeof t.enabled!=`boolean`?null:t}catch(e){return console.warn(`Failed to set launch at login status`,e),null}},D=async()=>{if(!C()||!P())return null;try{let e=await w(`desktop_get_minimize_to_tray`);return!e||typeof e.supported!=`boolean`||typeof e.enabled!=`boolean`?null:e}catch(e){return console.warn(`Failed to get minimize to tray status`,e),null}},O=async e=>{if(!C()||!P())return null;try{let t=await w(`desktop_set_minimize_to_tray`,{enabled:e});return!t||typeof t.supported!=`boolean`||typeof t.enabled!=`boolean`?null:t}catch(e){return console.warn(`Failed to set minimize to tray status`,e),null}},ee=async()=>{if(!C()||!P())return null;try{let e=await w(`desktop_get_keep_awake`);return!e||typeof e.supported!=`boolean`||typeof e.enabled!=`boolean`||typeof e.active!=`boolean`?null:e}catch(e){return console.warn(`Failed to get keep awake status`,e),null}},k=async e=>{if(!C()||!P())return null;try{let t=await w(`desktop_set_keep_awake`,{enabled:e});return!t||typeof t.supported!=`boolean`||typeof t.enabled!=`boolean`||typeof t.active!=`boolean`?null:t}catch(e){return console.warn(`Failed to set keep awake status`,e),null}},A=e=>{let t=e.trim();if(!t)return null;try{return new URL(t).origin}catch{try{return new URL(t.endsWith(`/`)?t:`${t}/`).origin}catch{return null}}},j=e=>{let t=e.trim();if(!t)return null;try{return new URL(t)}catch{try{return new URL(t.endsWith(`/`)?t:`${t}/`)}catch{return null}}},M=e=>e.replace(/^\[|\]$/g,``).toLowerCase(),N=e=>{let t=M(e);return t===`localhost`||t===`127.0.0.1`||t===`::1`},P=()=>{if(typeof window>`u`||!F()||e())return!1;let r=t();if(r.startsWith(`host:`))return!1;if(r===`local`)return!0;let i=typeof window.__YURI_LOCAL_ORIGIN__==`string`?window.__YURI_LOCAL_ORIGIN__:``,a=j(i),o=j(n());if(!o&&a&&u()?.target===`local`)return!0;if(a&&o){if(a.origin===o.origin)return!0;let e=a.port||(a.protocol===`https:`?`443`:`80`),t=o.port||(o.protocol===`https:`?`443`:`80`);return a.protocol===o.protocol&&e===t&&N(a.hostname)&&N(o.hostname)}let s=j(window.location.origin);if(a&&s){if(a.origin===s.origin)return!0;let e=a.port||(a.protocol===`https:`?`443`:`80`),t=s.port||(s.protocol===`https:`?`443`:`80`);return a.protocol===s.protocol&&e===t&&N(a.hostname)&&N(s.hostname)}let c=A(i),l=A(window.location.origin)||window.location.origin;return c&&l&&c===l?!0:!!(s&&N(s.hostname))},F=()=>typeof window>`u`?!1:h(),I=async()=>{if(!F())return!1;try{return await w(`desktop_start_window_drag`),!0}catch{return!1}},L=()=>r()?.runtime?.isVSCode===!0,R=()=>{let e=r()?.runtime?.platform;return e===`web`?!0:e===`desktop`||e===`vscode`?!1:!L()},z=async()=>{if(typeof window<`u`){let e=window.__YURI_HOME__;if(e&&e.length>0)return e}return null},B=async e=>{if(S()&&P())try{let e=await m()?.openDialog?.({directory:!0,multiple:!1,title:`Select Working Directory`});return!e||typeof e!=`string`?{success:!1,error:`Directory selection cancelled`}:{success:!0,path:e}}catch(e){return console.warn(`Failed to request directory access`,e),{success:!1,error:e instanceof Error?e.message:String(e)}}return{success:!0,path:e}},V=e=>typeof e==`object`&&!!e&&!Array.isArray(e),H=async e=>{if(S()&&P())try{let t=await m()?.openDialog?.({directory:!1,multiple:!1,title:`Select File`,returnGrant:!0,...e?.filters?{filters:e.filters}:{},...e?.defaultPath?{defaultPath:e.defaultPath}:{}});if(!t)return{success:!1,error:`File selection cancelled`};if(typeof t==`string`)return{success:!0,path:t};if(!V(t))return{success:!1,error:`File selection cancelled`};let n=typeof t.path==`string`?t.path:``;return n?{success:!0,path:n,outsideFileGrant:typeof t.outsideFileGrant==`string`?t.outsideFileGrant:void 0}:{success:!1,error:`File selection cancelled`}}catch(e){return console.warn(`Failed to request file access`,e),{success:!1,error:e instanceof Error?e.message:String(e)}}return{success:!1,error:`Native file picker not available`}},U=async e=>{let t=typeof e==`string`?e.trim():``;if(!t)return{success:!1,error:`Path is required`};if(!S()||!P())return{success:!1,error:`Native file access not available`};try{let e=await m()?.grantFileAccess?.(t);if(!V(e))return{success:!1,error:`File access was not granted`};let n=typeof e.path==`string`?e.path:``,r=typeof e.outsideFileGrant==`string`?e.outsideFileGrant:``;return!n||!r?{success:!1,error:`File access was not granted`}:{success:!0,path:n,outsideFileGrant:r}}catch(e){return console.warn(`Failed to request existing file access`,e),{success:!1,error:e instanceof Error?e.message:String(e)}}},W=async e=>({success:!0}),te=async e=>({success:!0}),G=async e=>{if(!S())throw Error(`Desktop update checker is unavailable`);let t=await w(`desktop_check_for_updates`,{channelOverride:e});if(!t)throw Error(`Desktop update checker returned no result`);return t},K=async e=>{S()&&await w(`desktop_ota_ready`,{version:e})},q=()=>w(`desktop_get_app_version`),J=async e=>{let t=m();return typeof t?.listen==`function`?t.listen(`yuri:update-progress`,t=>{let n=t?.payload;if(!n||typeof n!=`object`)return;let r=n;e({event:typeof r.event==`string`?r.event:void 0,data:r.data&&typeof r.data==`object`?r.data:void 0})}):null},Y=async e=>{let t=m();return typeof t?.listen==`function`?t.listen(`yuri:update-ready`,t=>{let n=t?.payload;if(!n||typeof n!=`object`)return;let r=n;e({version:typeof r.version==`string`?r.version:null,downloaded:r.downloaded===!0})}):null},X=async e=>{if(!S())return!1;let t=m(),n=null,r=0,i;try{return typeof e==`function`&&t?.listen&&(n=await t.listen(`yuri:update-progress`,t=>{let n=t?.payload;if(!n||typeof n!=`object`)return;let a=n,o=typeof a.event==`string`?a.event:null,s=a.data&&typeof a.data==`object`?a.data:null;if(o===`Started`){r=0,i=typeof s?.contentLength==`number`?s.contentLength:void 0,e({downloaded:r,total:i});return}if(o===`Progress`){let t=s?.downloaded,n=s?.total;typeof t==`number`&&(r=t),typeof n==`number`&&(i=n),e({downloaded:r,total:i});return}o===`Finished`&&e({downloaded:r,total:i})})),await w(`desktop_download_and_install_update`),!0}catch(e){throw e instanceof Error?e:Error(String(e))}finally{if(n)try{let e=n();e instanceof Promise&&await e}catch{}}},Z=async()=>S()?Q({applyUpdate:!0}):!1,Q=async({applyUpdate:e=!1}={})=>{if(!S())return!1;try{return await w(`desktop_restart`,e?{applyUpdate:!0}:void 0),!0}catch(e){return console.warn(`Failed to restart desktop app`,e),!1}},ne=async()=>{if(!S()||!P())return null;try{let e=await w(`desktop_get_lan_address`);return typeof e==`string`&&e.trim().length>0?e.trim():null}catch(e){return console.warn(`Failed to get desktop LAN address`,e),null}},$=async(e,t)=>{if(!S()||!P())return!1;let n=e?.trim();if(!n)return!1;try{return await w(`desktop_open_path`,{path:n,app:typeof t==`string`&&t.trim().length>0?t.trim():void 0}),!0}catch(e){return console.warn(`Failed to open path`,e),!1}},re=async e=>{if(!S()||!P())return null;let t=e?.trim();if(!t)return null;try{let e=await w(`desktop_is_binary_path`,{path:t});return typeof e==`boolean`?e:null}catch{return null}},ie=async e=>{if(!S()||!P())return!1;let t=e?.trim();if(!t)return!1;try{return await w(`desktop_reveal_path`,{path:t}),!0}catch{return $(t)}},ae=async(e,t)=>{if(!S()||!P())return null;let n=e?.trim();if(!n)return null;try{let e=await w(`desktop_save_markdown_file`,{defaultFileName:n,content:t});return typeof e==`string`&&e.trim().length>0?e:null}catch(e){return console.warn(`Failed to save markdown file`,e),null}},oe=async(e,n,r,i)=>{if(!S()||!i&&!P())return!1;if(i)return t()===`host:${i}`&&(await w(`desktop_open_ssh_in_app`,{projectPath:e,appId:n,hostId:i}),!0);let a=e?.trim(),o=n?.trim(),s=r?.trim();if(!a||!o||!s)return!1;try{return await w(`desktop_open_in_app`,{projectPath:a,appId:o,appName:s}),!0}catch(e){return console.warn(`Failed to open project in app`,e),!1}},se=async(e,t,n)=>{if(!S()||!P())return!1;let r=e?.trim(),i=t?.trim(),a=n?.trim();if(!r||!i||!a)return!1;try{return await w(`desktop_open_file_in_app`,{filePath:r,appId:i,appName:a}),!0}catch(e){return console.warn(`Failed to open file in app`,e),!1}},ce=async(e,t)=>{if(!S())return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};if(v()===`linux`)return{apps:[],success:!0,hasCache:!1,isCacheStale:!1};let n=Array.isArray(e)?e.filter(e=>typeof e==`string`):[];if(n.length===0)return{apps:[],success:!0,hasCache:!1,isCacheStale:!1};try{let e=await w(`desktop_get_installed_apps`,{apps:n,force:t===!0||void 0});if(!e||typeof e!=`object`)return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};let r=e;return r.supported===!1?{apps:[],success:!0,hasCache:!1,isCacheStale:!1}:Array.isArray(r.apps)?{apps:r.apps.filter(e=>e&&typeof e==`object`).map(e=>{let t=e;return{name:typeof t.name==`string`?t.name:``,iconDataUrl:typeof t.iconDataUrl==`string`?t.iconDataUrl:null}}).filter(e=>e.name.length>0),success:!0,hasCache:r.hasCache===!0,isCacheStale:r.isCacheStale===!0}:{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}catch(e){return console.warn(`Failed to fetch installed apps`,e),{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}};export{H as A,I as B,Y as C,oe as D,$ as E,ae as F,u as G,y as H,k as I,s as K,E as L,Q as M,Z as N,B as O,ie as P,O as R,J as S,se as T,c as U,te as V,f as W,F as _,q as a,L as b,ne as c,_ as d,v as f,P as g,re as h,ce as i,x as j,U as k,T as l,w as m,G as n,z as o,S as p,l as q,X as r,ee as s,C as t,D as u,h as v,K as w,R as x,g as y,W as z};
@@ -1,2 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-aparajita-capacitor-secure-storage-xol_6BsB.js","assets/rolldown-runtime-hePW80VL.js"])))=>i.map(i=>d[i]);
2
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{_ as t,b as n}from"./desktop-DpAcrF1h.js";import{it as r}from"./vendor-base-ui-CdzJ6My_.js";import{n as i}from"./platform-BND-ZKbF.js";import"./brand-storage-bootstrap-D4BW3w-M.js";import{n as a}from"./vendor-react-BP2cRVqX.js";import{o}from"./vendor-aparajita-capacitor-secure-storage-xol_6BsB.js";var s=e(r(),1),c=a(),l=.85,u=1.2,d=10/9,f=.9,p=.98,m=p/f,h=`yuri.designPtScale.v8`;function g(e){return!Number.isFinite(e)||e<=0?1:Math.min(u,Math.max(l,e))}function _(e){if(!e)return p;let t=e.density,n=(e.xdpi+e.ydpi)/2;if(!(t>0)||!(n>=50)||n>800)return p;let r=g(n/t/163);return Math.min(p,r*m)}function v(){if(typeof window>`u`)return 1;try{let e=Number.parseFloat(window.localStorage.getItem(`yuri.designPtScale.v8`)??``),t=window.Capacitor?.getPlatform?.();return t===`android`?Math.min(p,g(e)):t===`ios`?d:g(e)}catch{return 1}}function y(e){if(!(typeof window>`u`))try{window.localStorage.setItem(h,String(e))}catch{}}function b(e,t=document.documentElement){let n=g(e);t.style.setProperty(`--dpt`,`${n}px`),t.style.setProperty(`--dpt-n`,String(n))}async function x(){if(typeof document>`u`)return 1;b(v());let{Capacitor:e,registerPlugin:t}=await o(async()=>{let{Capacitor:e,registerPlugin:t}=await import(`./vendor-aparajita-capacitor-secure-storage-xol_6BsB.js`).then(e=>e.i);return{Capacitor:e,registerPlugin:t}},__vite__mapDeps([0,1]));if(!e.isNativePlatform())return b(1),1;if(e.getPlatform()===`ios`)return b(d),y(d),d;if(e.getPlatform()!==`android`)return b(1),1;if(!e.isPluginAvailable(`YuriPhysicalScale`))return b(p),y(p),p;try{let e=_(await t(`YuriPhysicalScale`).getMetrics());return y(e),b(e),e}catch{return b(p),y(p),p}}var S={xs:0,sm:640,md:768,lg:1024,xl:1280,"2xl":1536},C={isMobile:!1,isTablet:!1,isDesktop:!0,deviceType:`desktop`,screenWidth:1024,breakpoint:`lg`,hasTouchInput:!1,hasTouchOnlyPointer:!1},w=()=>typeof window>`u`?!1:new URLSearchParams(window.location.search).get(`surface`)===`desktop`,T=e=>{if(typeof navigator>`u`)return{isExplicitTablet:!1};let t=navigator.userAgent||``,n=navigator.platform||``,r=/iPad/i.test(t)||(/Macintosh|MacIntel/i.test(t)||/MacIntel/i.test(n))&&e>1,i=/Android/i.test(t)&&!/Mobile/i.test(t),a=/Tablet/i.test(t);return{isExplicitTablet:r||i||a}},E=(e,t,n)=>{if(typeof window>`u`)return;let r=document.documentElement,i=t===`mobile`,a=t===`tablet`;r.classList.remove(`device-mobile`,`device-tablet`,`device-desktop`),r.classList.add(t===`mobile`?`device-mobile`:t===`tablet`?`device-tablet`:`device-desktop`),e?(r.classList.add(`desktop-runtime`),r.style.setProperty(`--is-mobile`,`0`),r.style.setProperty(`--device-type`,`desktop`),r.style.setProperty(`--font-scale`,`1`),r.style.setProperty(`--has-coarse-pointer`,`0`),r.style.setProperty(`--has-touch-input`,`0`),r.classList.remove(`mobile-pointer`)):(r.classList.remove(`desktop-runtime`),r.style.setProperty(`--is-mobile`,i?`1`:`0`),r.style.setProperty(`--device-type`,t),r.style.setProperty(`--font-scale`,i?`0.9`:a?`0.95`:`1`),r.style.setProperty(`--has-coarse-pointer`,n?`1`:`0`),r.style.setProperty(`--has-touch-input`,n?`1`:`0`),n?r.classList.add(`mobile-pointer`):r.classList.remove(`mobile-pointer`)),b(e?1:v(),r)};function D(){let e=window.innerWidth,r=typeof window.matchMedia==`function`,a=r?window.matchMedia(`(pointer: coarse)`):null,o=r?window.matchMedia(`(hover: none)`):null,s=a?.matches??!1,c=o?.matches??!1,l=typeof navigator<`u`?navigator.maxTouchPoints??0:0,u=t()||n()||w(),{isExplicitTablet:d}=T(l),f=s||c||l>0,p=s||c,m=e>S.md&&e<=S.lg,h=e<=S.md,g=f&&h,_=f&&!g&&(m||d),v=!f||!_&&e>S.lg,y=`desktop`;u?(g=!1,_=!1,v=!0,y=`desktop`):i()?(g=!0,_=!1,v=!1,y=`mobile`):g?y=`mobile`:_?y=`tablet`:(v=!0,y=`desktop`),E(u,y,f);let b=`xs`;for(let[t,n]of Object.entries(S))e>=n&&(b=t);return{isMobile:g,isTablet:_,isDesktop:v,deviceType:y,screenWidth:e,breakpoint:b,hasTouchInput:f,hasTouchOnlyPointer:p}}var O=(e,t)=>e.isMobile===t.isMobile&&e.isTablet===t.isTablet&&e.isDesktop===t.isDesktop&&e.deviceType===t.deviceType&&e.screenWidth===t.screenWidth&&e.breakpoint===t.breakpoint&&e.hasTouchInput===t.hasTouchInput&&e.hasTouchOnlyPointer===t.hasTouchOnlyPointer,k=new Set,A=null,j,M=null,N=()=>typeof window>`u`?C:(A||=D(),A),P=()=>{for(let e of k)e()},F=()=>{j=void 0;let e=D();A&&O(A,e)||(A=e,P())},I=()=>{typeof window>`u`||j!==void 0||(j=window.requestAnimationFrame(F))},L=(e,t)=>e?typeof e.addEventListener==`function`?(e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)):typeof e.addListener==`function`?(e.addListener(t),()=>e.removeListener(t)):()=>{}:()=>{},R=()=>{if(typeof window>`u`)return()=>{};A=D(),window.addEventListener(`resize`,I);let e=typeof window.matchMedia==`function`?window.matchMedia(`(pointer: coarse)`):null,t=typeof window.matchMedia==`function`?window.matchMedia(`(hover: none)`):null,n=L(e,I),r=L(t,I);return()=>{window.removeEventListener(`resize`,I),n(),r(),j!==void 0&&(window.cancelAnimationFrame(j),j=void 0)}},z=e=>typeof window>`u`?()=>{}:(k.add(e),M||=R(),()=>{k.delete(e),k.size===0&&M&&(M(),M=null,A=null)});function B(){if(typeof window>`u`||typeof window<`u`&&t())return!1;let e=document.documentElement,n=e.style.getPropertyValue(`--is-mobile`)||getComputedStyle(e).getPropertyValue(`--is-mobile`);return n===`1`||n===`true`}var V=()=>typeof window>`u`?!1:!!(navigator.standalone===!0||window.matchMedia?.(`(display-mode: standalone)`)?.matches||window.matchMedia?.(`(display-mode: fullscreen)`)?.matches),H=()=>{if(typeof window>`u`||t())return!1;let e=typeof navigator<`u`?navigator.maxTouchPoints??0:0;return V()&&e>0&&window.innerWidth>S.md};function U(){let e=(0,c.c)(2),[t,n]=s.useState(W),r,i;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=()=>{if(typeof window>`u`)return;let e=()=>n(H()),t=window.matchMedia?.(`(display-mode: standalone)`),r=window.matchMedia?.(`(display-mode: fullscreen)`);e(),window.addEventListener(`resize`,e),window.addEventListener(`focus`,e);let i=t=>{t&&(typeof t.addEventListener==`function`?t.addEventListener(`change`,e):typeof t.addListener==`function`&&t.addListener(e))},a=t=>{t&&(typeof t.removeEventListener==`function`?t.removeEventListener(`change`,e):typeof t.removeListener==`function`&&t.removeListener(e))};return i(t),i(r),()=>{window.removeEventListener(`resize`,e),window.removeEventListener(`focus`,e),a(t),a(r)}},i=[],e[0]=r,e[1]=i):(r=e[0],i=e[1]),s.useEffect(r,i),t}function W(){return H()}var G=()=>typeof window>`u`?`portrait`:window.matchMedia?.(`(orientation: landscape)`)?.matches?`landscape`:`portrait`;function K(){let e=(0,c.c)(2),[t,n]=s.useState(G),r,i;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(`(orientation: landscape)`),t=()=>n(e.matches?`landscape`:`portrait`);return t(),L(e,t)},i=[],e[0]=r,e[1]=i):(r=e[0],i=e[1]),s.useEffect(r,i),t}function q(){return s.useSyncExternalStore(z,N,J)}function J(){return C}export{U as a,K as i,B as n,x as o,q as r,D as t};
@@ -1 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{$ as t,J as n,Q as r,X as i,Y as a,Z as o,et as s,it as c,q as l,rt as u}from"./vendor-base-ui-CdzJ6My_.js";import{n as d}from"./vendor-react-BP2cRVqX.js";import{f,r as p}from"./button-BuhP8T0R.js";import{n as m}from"./Icon-DgrlwLKs.js";var h=d(),g=e(c(),1),_=u(),v=0;function y(e,t){return e&&g.isValidElement(t)?{render:t}:{children:t}}function b(e){let t=(0,h.c)(4),n;t[0]===e?n=t[1]:({...n}=e,t[0]=e,t[1]=n);let r;return t[2]===n?r=t[3]:(r=(0,_.jsx)(a,{...n}),t[2]=n,t[3]=r),r}function x(e){let t=(0,h.c)(10),n,r,i;t[0]===e?(n=t[1],r=t[2],i=t[3]):({asChild:n,children:r,...i}=e,t[0]=e,t[1]=n,t[2]=r,t[3]=i);let a;t[4]!==n||t[5]!==r?(a=y(n,r),t[4]=n,t[5]=r,t[6]=a):a=t[6];let o=a,s;return t[7]!==i||t[8]!==o?(s=(0,_.jsx)(l,{"data-slot":`dialog-trigger`,...i,...o}),t[7]=i,t[8]=o,t[9]=s):s=t[9],s}function S(e){let t=(0,h.c)(4),n;t[0]===e?n=t[1]:({...n}=e,t[0]=e,t[1]=n);let r;return t[2]===n?r=t[3]:(r=(0,_.jsx)(i,{...n}),t[2]=n,t[3]=r),r}var C=g.forwardRef((e,t)=>{let n=(0,h.c)(10),r,i;n[0]===e?(r=n[1],i=n[2]):({className:r,...i}=e,n[0]=e,n[1]=r,n[2]=i);let a;n[3]===Symbol.for(`react.memo_cache_sentinel`)?(a=[],n[3]=a):a=n[3],g.useEffect(A,a);let o=t,c;n[4]===r?c=n[5]:(c=p(`app-region-no-drag fixed inset-0 z-50 bg-black/50 dark:bg-black/75`,`transition-opacity duration-150 ease-out`,`data-[starting-style]:opacity-0 data-[ending-style]:opacity-0`,r),n[4]=r,n[5]=c);let l;return n[6]!==i||n[7]!==o||n[8]!==c?(l=(0,_.jsx)(s,{ref:o,"data-slot":`dialog-overlay`,className:c,...i}),n[6]=i,n[7]=o,n[8]=c,n[9]=l):l=n[9],l});C.displayName=`DialogOverlay`;function w(e){let n=(0,h.c)(29),r,i,a,s,c,l;n[0]===e?(r=n[1],i=n[2],a=n[3],s=n[4],c=n[5],l=n[6]):({className:i,overlayClassName:s,containerClassName:a,children:r,showCloseButton:l,...c}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a,n[4]=s,n[5]=c,n[6]=l);let u=l===void 0||l,{t:d}=f(),g;n[7]===s?g=n[8]:(g=p(`rounded-none`,s),n[7]=s,n[8]=g);let v;n[9]===g?v=n[10]:(v=(0,_.jsx)(C,{className:g}),n[9]=g,n[10]=v);let y=a??`items-center p-4`,b;n[11]===y?b=n[12]:(b=p(`fixed inset-0 z-50 flex justify-center pointer-events-none`,y),n[11]=y,n[12]=b);let x;n[13]===i?x=n[14]:(x=p(`app-region-no-drag relative pointer-events-auto bg-background text-foreground flex flex-col w-full max-w-lg max-h-full gap-4 rounded-xl border p-6 shadow-none overflow-y-auto pwa-dialog-content origin-center`,`transition-all duration-150 ease-out`,`data-[starting-style]:opacity-0 data-[starting-style]:scale-[0.98]`,`data-[ending-style]:opacity-0 data-[ending-style]:scale-[0.98]`,`data-[nested-dialog-open]:brightness-[0.55] dark:data-[nested-dialog-open]:brightness-[0.4]`,i),n[13]=i,n[14]=x);let w;n[15]!==u||n[16]!==d?(w=u&&(0,_.jsxs)(t,{"data-slot":`dialog-close`,className:`ring-offset-background focus:ring-ring data-[open]:bg-interactive-active data-[open]:text-foreground absolute top-2 right-2 rounded-lg opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none text-muted-foreground hover:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4`,children:[(0,_.jsx)(m,{name:`close`}),(0,_.jsx)(`span`,{className:`sr-only`,children:d(`dialog.common.actions.close`)})]}),n[15]=u,n[16]=d,n[17]=w):w=n[17];let T;n[18]!==r||n[19]!==c||n[20]!==x||n[21]!==w?(T=(0,_.jsxs)(o,{"data-slot":`dialog-content`,"data-state-slot":`dialog`,className:x,...c,children:[r,w]}),n[18]=r,n[19]=c,n[20]=x,n[21]=w,n[22]=T):T=n[22];let E;n[23]!==b||n[24]!==T?(E=(0,_.jsx)(`div`,{className:b,children:T}),n[23]=b,n[24]=T,n[25]=E):E=n[25];let D;return n[26]!==v||n[27]!==E?(D=(0,_.jsxs)(S,{children:[v,E]}),n[26]=v,n[27]=E,n[28]=D):D=n[28],D}function T(e){let t=(0,h.c)(8),n,r;t[0]===e?(n=t[1],r=t[2]):({className:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i;t[3]===n?i=t[4]:(i=p(`flex flex-col gap-2 text-center sm:text-left`,n),t[3]=n,t[4]=i);let a;return t[5]!==r||t[6]!==i?(a=(0,_.jsx)(`div`,{"data-slot":`dialog-header`,className:i,...r}),t[5]=r,t[6]=i,t[7]=a):a=t[7],a}function E(e){let t=(0,h.c)(8),n,r;t[0]===e?(n=t[1],r=t[2]):({className:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i;t[3]===n?i=t[4]:(i=p(`flex flex-col-reverse gap-2 bottom-safe-area sm:flex-row sm:justify-end`,n),t[3]=n,t[4]=i);let a;return t[5]!==r||t[6]!==i?(a=(0,_.jsx)(`div`,{"data-slot":`dialog-footer`,className:i,...r}),t[5]=r,t[6]=i,t[7]=a):a=t[7],a}function D(e){let t=(0,h.c)(8),r,i;t[0]===e?(r=t[1],i=t[2]):({className:r,...i}=e,t[0]=e,t[1]=r,t[2]=i);let a;t[3]===r?a=t[4]:(a=p(`typography-markdown leading-none font-semibold text-foreground`,r),t[3]=r,t[4]=a);let o;return t[5]!==i||t[6]!==a?(o=(0,_.jsx)(n,{"data-slot":`dialog-title`,className:a,...i}),t[5]=i,t[6]=a,t[7]=o):o=t[7],o}function O(e){let t=(0,h.c)(8),n,i;t[0]===e?(n=t[1],i=t[2]):({className:n,...i}=e,t[0]=e,t[1]=n,t[2]=i);let a;t[3]===n?a=t[4]:(a=p(`text-muted-foreground typography-ui-label`,n),t[3]=n,t[4]=a);let o;return t[5]!==i||t[6]!==a?(o=(0,_.jsx)(r,{"data-slot":`dialog-description`,className:a,...i}),t[5]=i,t[6]=a,t[7]=o):o=t[7],o}function k(){v=Math.max(0,v-1),v===0&&document.documentElement.classList.remove(`yuri-dialog-open`)}function A(){return v+=1,document.documentElement.classList.add(`yuri-dialog-open`),k}export{T as a,E as i,w as n,D as o,O as r,x as s,b as t};
@@ -1 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{p as t}from"./runtime-auth-ef9W7A43.js";import{c as n,f as r,i}from"./runtime-switch-CAZiOV2G.js";import{n as a}from"./runtime-fetch-BAN5Gnnp.js";import{it as o}from"./vendor-base-ui-CdzJ6My_.js";import{St as s}from"./platform-BND-ZKbF.js";import{n as c}from"./vendor-react-BP2cRVqX.js";import{n as l}from"./vendor-reactuses-core-BpfIZ1tg.js";import{f as u}from"./button-BuhP8T0R.js";var d=`yuri:close-embedded-session-chat`,f=`yuri:embedded-visibility`,p=`yuri:embedded-visibility-request`,m=e=>new URLSearchParams(e).get(`yuriPanel`)===`session-chat`,h=(e,t,n)=>JSON.stringify({sessionID:e,directory:t||``,readOnly:n===!0}),g=(e,t,n,r)=>{if(typeof window>`u`)return``;let i=new URL(window.location.pathname,window.location.origin);return i.searchParams.set(`yuriPanel`,`session-chat`),i.searchParams.set(`surface`,`desktop`),i.searchParams.set(`sessionId`,e),n?i.searchParams.set(`readOnly`,`1`):i.searchParams.delete(`readOnly`),t&&t.trim().length>0?i.searchParams.set(`directory`,t):i.searchParams.delete(`directory`),i.searchParams.set(`themeMode`,r.mode),i.searchParams.set(`lightThemeId`,r.lightThemeId),i.searchParams.set(`darkThemeId`,r.darkThemeId),i.searchParams.set(`themeVariant`,r.currentTheme.metadata.variant===`dark`?`dark`:`light`),i.searchParams.set(`currentTheme`,JSON.stringify(r.currentTheme)),i.hash=``,i.toString()},_=(e,t,n,r,i,a)=>{let o=h(n,r,i),s=e.get(t);if(s?.signature===o)return s.src;let c=g(n,r,i,a);return e.set(t,{signature:o,src:c}),c},v=null,y=()=>{if(v!==null)return v;if(typeof window>`u`)return v=!1,!1;try{return v=new URLSearchParams(window.location.search).get(`yuriPanel`)===`session-chat`,v}catch{return v=!1,!1}},b=()=>{if(!y())return null;try{let e=new URLSearchParams(window.location.search).get(`sessionId`);return e&&e.trim().length>0?e.trim():null}catch{return null}},x=e(o(),1);async function S(e,t){let n=i(),r=await a(`/api/voice/session`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({kind:e}),signal:AbortSignal.any([t,AbortSignal.timeout(2e4)])});if(t.throwIfAborted(),n!==i())throw Error(`Speech runtime changed`);if(r.status===404||r.ok&&r.headers.get(`content-type`)?.includes(`text/html`))return await r.body?.cancel(),null;if(!r.ok)throw await r.body?.cancel(),Error(`Unable to create speech session`);let o=await r.json();if(t.throwIfAborted(),n!==i())throw Error(`Speech runtime changed`);if(o?.transport===`host`)return null;if(o?.transport!==`volcengine-direct`||typeof o.token!=`string`||o.token.length>16384||!/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(o.token)||typeof o.appId!=`string`||!/^[A-Za-z0-9_-]{1,128}$/.test(o.appId)||typeof o.resourceId!=`string`||!/^[A-Za-z0-9._-]{1,128}$/.test(o.resourceId)||!Number.isFinite(o.expiresAt)||o.expiresAt<=Date.now()+5e3||o.expiresAt>Date.now()+36e4||e===`tts`&&(typeof o.voice!=`string`||!/^[A-Za-z0-9_-]{1,200}$/.test(o.voice)||!Number.isFinite(o.speed)||o.speed<.5||o.speed>2||!Number.isFinite(o.pitch)||o.pitch<.5||o.pitch>2||!Number.isFinite(o.volume)||o.volume<0||o.volume>1)||e===`asr`&&o.asrContext!==void 0&&(typeof o.asrContext!=`string`||o.asrContext.length>2e3||/\0/.test(o.asrContext)))throw Error(`Invalid speech session`);return o}function C(e,t){let n=new URL(t===`asr`?`wss://openspeech.bytedance.com/api/v3/sauc/bigmodel_async`:`wss://openspeech.bytedance.com/api/v3/tts/bidirection`);return n.search=new URLSearchParams({api_app_key:e.appId,api_access_key:`Jwt; ${e.token}`,api_resource_id:e.resourceId}).toString(),n.toString()}var w=new TextEncoder,T=new TextDecoder,E=1048576;function D(e,t=!1,n=!1){let r=new Uint8Array(8+e.length);return r.set([17,(t?2:1)<<4|(n?2:0),t?0:16,0]),new DataView(r.buffer).setUint32(4,e.length),r.set(e,8),r}function O(e,t=``,n={}){let r=w.encode(t),i=w.encode(JSON.stringify(n)),a=new Uint8Array(12+i.length+(t?4+r.length:0));a.set([17,20,16,0]);let o=new DataView(a.buffer);o.setInt32(4,e);let s=8;return t&&(o.setUint32(s,r.length),a.set(r,s+4),s+=4+r.length),o.setUint32(s,i.length),a.set(i,s+4),a}async function k(e,t){if(e.byteLength<8||e.byteLength>E)throw Error(`Invalid speech frame size`);let n=new Uint8Array(e),r=new DataView(e),i=n[1]>>4,a=n[1]&15,o=n[2]&15,s=(n[0]&15)*4;if(n[0]>>4!=1||s<4||s>n.length-4)throw Error(`Invalid speech frame`);let c=()=>{if(s+4>n.length)throw Error(`Truncated speech frame`);let e=r.getUint32(s);return s+=4,e};if(i===15)throw Error(`Speech provider failed (code ${c()})`);if(i!==9&&(t!==`tts`||i!==11))throw Error(`Unexpected speech frame`);a&1&&c();let l=0,u=``;if(a&4&&(l=c(),t===`tts`)){let e=c();if(e>256||s+e>n.length)throw Error(`Invalid speech session ID`);u=T.decode(n.subarray(s,s+e)),s+=e}let d=c();if(s+d!==n.length)throw Error(`Truncated speech payload`);let f=n.slice(s);if(o===1){let e=new Blob([f]).stream().pipeThrough(new DecompressionStream(`gzip`)).getReader(),t=[],n=0;try{for(;;){let r=await e.read();if(r.done)break;if(n+=r.value.length,n>E)throw Error(`Speech payload exceeds size limit`);t.push(r.value)}}finally{await e.cancel().catch(()=>void 0),e.releaseLock()}f=new Uint8Array(n);let r=0;for(let e of t)f.set(e,r),r+=e.length}else if(o!==0)throw Error(`Unsupported speech compression`);return{type:i,event:l,sessionId:u,final:!!(a&2),payload:f}}function A(e){let t=JSON.parse(T.decode(e));if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`Invalid speech response`);return t}async function j(e,t){t.throwIfAborted();let n=new WebSocket(e);n.binaryType=`arraybuffer`;let r=[],i=0,a=null,o=null,s=null,c=(e=!0)=>{t.removeEventListener(`abort`,u),n.onmessage=null,n.onclose=null,n.onerror=null,n.onopen=null,e&&(r.length=0,i=0),n.close(),o?.()},l=(e,t=!0)=>{a??=e,s?.(a),c(t)},u=()=>l(new DOMException(`Speech cancelled`,`AbortError`));t.addEventListener(`abort`,u,{once:!0}),n.onmessage=e=>{if(!(e.data instanceof ArrayBuffer)||e.data.byteLength>E){l(Error(`Invalid speech message`));return}if(i+=e.data.byteLength,i>33554432||r.length>=4096){l(Error(`Speech receive buffer exceeded`));return}r.push(e.data),o?.()},n.onerror=()=>l(Error(`Speech connection failed`)),n.onclose=()=>l(Error(`Speech connection ended before completion`),!1);let d=setTimeout(()=>l(Error(`Speech connection timed out`)),1e4);try{await new Promise((e,t)=>{s=t,n.onopen=()=>e()})}finally{clearTimeout(d),s=null}return{send(e){if(t.throwIfAborted(),a)throw a;if(n.readyState!==WebSocket.OPEN||n.bufferedAmount+e.length>E)throw Error(`Speech send buffer exceeded`);n.send(e)},async read(){let e=setTimeout(()=>l(Error(`Speech response timed out`)),6e4);try{for(;!r.length&&!a;)await new Promise(e=>{o=e});if(t.throwIfAborted(),!r.length&&a)throw a;let e=r.shift();return i-=e.byteLength,e}finally{clearTimeout(e),o=null}},close(){a??=new DOMException(`Speech closed`,`AbortError`),c()}}}var M=class{abort;partial;disconnected;socket=null;failure=null;completion=null;text=``;final=!1;finishing=!1;sequence=0;constructor(e,t,n){this.abort=e,this.partial=t,this.disconnected=n}get connected(){return this.socket!==null&&!this.failure&&!this.abort.signal.aborted}async start(e,t){if(t!==`audio/pcm;rate=16000;bits=16`)throw Error(`Direct speech requires 16 kHz PCM16 audio`);let n=await j(C(e,`asr`),this.abort.signal);this.socket=n;try{n.send(D(new TextEncoder().encode(JSON.stringify({user:{uid:`yuri`},audio:{format:`pcm`,codec:`raw`,rate:16e3,bits:16,channel:1},request:{model_name:`bigmodel`,result_type:`full`,enable_itn:!0,enable_punc:!0,enable_nonstream:!0,show_utterances:!0,...e.asrContext?.trim()?{corpus:{context:JSON.stringify({context_type:`dialog_ctx`,context_data:[{text:e.asrContext.trim()}]})}}:{}}}))))}catch(e){throw n.close(),e}this.completion=this.receive().catch(e=>{this.failure=e instanceof Error?e:Error(`Speech recognition failed`),n.close(),!this.abort.signal.aborted&&!this.finishing&&this.disconnected()})}send(e,t){if(!this.connected||this.finishing||this.final||e!==this.sequence)return!1;try{if(t.length>128e3)throw Error(`Speech audio chunk exceeds size limit`);let e=atob(t);if(e.length%2)throw Error(`Invalid PCM audio`);let n=Uint8Array.from(e,e=>e.charCodeAt(0));return this.socket.send(D(n,!0)),this.sequence++,!0}catch{return this.failure=Error(`Unable to send speech audio`),this.socket?.close(),!1}}async finish(e){if(this.failure)throw this.failure;if(!this.socket||e!==this.sequence-1)throw Error(`Incomplete speech audio`);this.finishing=!0,this.socket.send(D(new Uint8Array,!0,!0));let t=setTimeout(()=>{this.failure=Error(`Speech finalization timed out`),this.socket?.close()},3e4);try{if(await this.completion,this.abort.signal.throwIfAborted(),this.failure)throw this.failure;if(!this.final)throw Error(`Incomplete speech recognition`);return{text:this.text}}finally{clearTimeout(t),this.socket.close()}}cancel(){this.abort.abort(),this.socket?.close()}async receive(){for(;;){let e=await k(await this.socket.read(),`asr`);this.abort.signal.throwIfAborted();let t=A(e.payload);if(t.code!==void 0&&![0,1e3,2e7].includes(Number(t.code)))throw Error(`Speech recognition failed`);let n=t.result;if(n!==void 0&&(!n||typeof n!=`object`||Array.isArray(n)))throw Error(`Invalid speech transcript`);if(n&&typeof n==`object`&&`text`in n){if(typeof n.text!=`string`)throw Error(`Invalid speech transcript`);this.text=n.text,e.final||this.partial(this.text)}if(e.final){if(!this.finishing)throw Error(`Speech recognition ended unexpectedly`);this.final=!0;return}}}},N=(e,t,n)=>{let r=Error(e);return r.name=`DictationStreamError`,r.retryable=t,n&&(r.reasonCode=n),r},P=1e4,F=15e3,I=3e4,L=3e4,R=new class{socket=null;connectPromise=null;idleCloseTimer=null;pendingStarts=new Map;pendingFinishes=new Map;connectionListeners=new Set;partialListeners=new Set;activeDictations=0;directStarts=new Map;directSessions=new Map;get isConnected(){if(this.socket?.readyState===WebSocket.OPEN)return!0;for(let e of this.directSessions.values())if(e.connected)return!0;return!1}subscribeConnectionStatus(e){return this.connectionListeners.add(e),()=>{this.connectionListeners.delete(e)}}onPartial(e){return this.partialListeners.add(e),()=>{this.partialListeners.delete(e)}}async ensureConnected(){if(this.socket?.readyState!==WebSocket.OPEN){if(this.connectPromise){await this.connectPromise;return}try{await t()}catch{}this.connectPromise=new Promise((e,t)=>{let n=!1,i;try{let e=r().websocket(`/api/dictation/ws`);i=s(e)}catch(e){this.connectPromise=null,t(e instanceof Error?e:Error(String(e)));return}let a=setTimeout(()=>{if(!n){n=!0,this.connectPromise=null;try{i.close()}catch{}t(Error(`Dictation connection timed out`))}},P);i.onopen=()=>{},i.onmessage=t=>{let r;try{r=JSON.parse(String(t.data))}catch{return}if(!n&&r.type===`ready`){n=!0,clearTimeout(a),this.socket=i,this.connectPromise=null,this.notifyConnection(!0),e();return}this.handleMessage(r)},i.onerror=()=>{window.setTimeout(()=>{n||(n=!0,clearTimeout(a),this.connectPromise=null,t(Error(`Dictation connection failed`)))},250)},i.onclose=e=>{if(!n){n=!0,clearTimeout(a),this.connectPromise=null;let r=e?.reason?`: ${e.reason}`:``;t(Error(`Dictation connection failed${r}`));return}this.socket===i&&(this.socket=null,this.rejectAllPending(Error(`Dictation connection lost`)),this.notifyConnection(!1))}}),await this.connectPromise}}async startDictationStream(e,t){let n=new AbortController;this.directStarts.set(e,n);try{let r=await S(`asr`,n.signal);if(n.signal.throwIfAborted(),r){let i=new M(n,t=>{for(let n of this.partialListeners)n(e,t)},()=>{this.directSessions.delete(e),i.cancel(),this.notifyConnection(!1)});this.directSessions.set(e,i),await i.start(r,t),n.signal.throwIfAborted(),this.notifyConnection(!0);return}await this.ensureConnected(),n.signal.throwIfAborted()}catch(t){throw this.directSessions.get(e)?.cancel(),this.directSessions.delete(e),t}finally{this.directStarts.delete(e)}return this.activeDictations+=1,this.clearIdleCloseTimer(),new Promise((n,r)=>{let i=setTimeout(()=>{this.pendingStarts.delete(e),this.releaseDictation(),r(Error(`Dictation start timed out`))},F);this.pendingStarts.set(e,{resolve:()=>{clearTimeout(i),n()},reject:e=>{clearTimeout(i),this.releaseDictation(),r(e)},timeout:i}),this.send({type:`start`,dictationId:e,format:t})||(clearTimeout(i),this.pendingStarts.delete(e),this.releaseDictation(),r(Error(`Dictation connection lost`)))})}sendDictationStreamChunk(e,t,n){let r=this.directSessions.get(e);return r?r.send(t,n):this.send({type:`chunk`,dictationId:e,seq:t,audio:n})}finishDictationStream(e,t){let n=this.directSessions.get(e);return n?n.finish(t).finally(()=>{n.cancel(),this.directSessions.delete(e)}):new Promise((n,r)=>{let i={resolve:e=>{i.timeout&&clearTimeout(i.timeout),this.releaseDictation(),n(e)},reject:e=>{i.timeout&&clearTimeout(i.timeout),this.releaseDictation(),r(e)},timeout:null};i.timeout=setTimeout(()=>{this.pendingFinishes.delete(e),this.releaseDictation(),r(Error(`Timed out waiting for transcription`))},L),this.pendingFinishes.set(e,i),this.send({type:`finish`,dictationId:e,finalSeq:t})||(this.pendingFinishes.delete(e),i.reject(Error(`Dictation connection lost`)))})}cancelDictationStream(e){this.directStarts.get(e)?.abort(),this.directStarts.delete(e);let t=this.directSessions.get(e);if(t){t.cancel(),this.directSessions.delete(e);return}this.send({type:`cancel`,dictationId:e});let n=this.pendingStarts.get(e);n&&(this.pendingStarts.delete(e),n.reject(Error(`Dictation cancelled`)));let r=this.pendingFinishes.get(e);r&&(this.pendingFinishes.delete(e),r.reject(Error(`Dictation cancelled`))),this.releaseDictation(),this.scheduleIdleCloseIfReady()}handleMessage(e){let t=e.dictationId;if(t)switch(e.type){case`ack`:{let e=this.pendingStarts.get(t);e&&(this.pendingStarts.delete(t),e.resolve());return}case`partial`:for(let n of this.partialListeners)n(t,e.text??``);return;case`finish_accepted`:{let n=this.pendingFinishes.get(t);n&&typeof e.timeoutMs==`number`&&(n.timeout&&clearTimeout(n.timeout),n.timeout=setTimeout(()=>{this.pendingFinishes.delete(t),n.reject(Error(`Timed out waiting for transcription`))},e.timeoutMs+5e3));return}case`final`:{let n=this.pendingFinishes.get(t);n&&(this.pendingFinishes.delete(t),n.resolve({text:e.text??``})),this.scheduleIdleCloseIfReady();return}case`error`:{let n=N(e.error||`Dictation failed`,e.retryable!==!1,e.reasonCode),r=this.pendingStarts.get(t);r&&(this.pendingStarts.delete(t),r.reject(n));let i=this.pendingFinishes.get(t);i&&(this.pendingFinishes.delete(t),i.reject(n)),this.scheduleIdleCloseIfReady();return}}}send(e){if(!this.isConnected||!this.socket)return!1;try{return this.socket.send(JSON.stringify(e)),!0}catch{return!1}}notifyConnection(e){for(let t of this.connectionListeners)t(e)}rejectAllPending(e){for(let[t,n]of this.pendingStarts)this.pendingStarts.delete(t),n.reject(e);for(let[t,n]of this.pendingFinishes)this.pendingFinishes.delete(t),n.reject(e);this.activeDictations=0}releaseDictation(){this.activeDictations=Math.max(0,this.activeDictations-1),this.scheduleIdleCloseIfReady()}scheduleIdleCloseIfReady(){this.activeDictations>0||this.pendingFinishes.size>0||this.pendingStarts.size>0||(this.clearIdleCloseTimer(),this.idleCloseTimer=setTimeout(()=>{if(this.activeDictations===0&&this.pendingFinishes.size===0&&this.pendingStarts.size===0){let e=this.socket;if(this.socket=null,e){try{e.close(1e3,`idle`)}catch{}this.notifyConnection(!1)}}},I))}cancelAllForRuntimeSwitch(){for(let e of this.directStarts.values())e.abort();this.directStarts.clear();for(let e of this.directSessions.values())e.cancel();this.directSessions.clear(),this.clearIdleCloseTimer();let e=this.socket;if(this.socket=null,this.connectPromise=null,this.rejectAllPending(Error(`Runtime changed`)),e){try{e.close(1e3,`runtime switch`)}catch{}this.notifyConnection(!1)}}clearIdleCloseTimer(){this.idleCloseTimer&&=(clearTimeout(this.idleCloseTimer),null)}};typeof window<`u`&&window.addEventListener(`yuri:runtime-endpoint-changed`,()=>{R.cancelAllForRuntimeSwitch()});var z=128,B=`audio/pcm;rate=16000;bits=16`,V=()=>new Promise(e=>setTimeout(e,0)),H=()=>{let e=Math.random().toString(36).slice(2,10);return`dic_${Date.now().toString(16)}${e}`},ee=class{client;format;createDictationId;dictationId=null;sendSeq=0;segments=[];streamReady=!1;flushTimer=null;drainWaiters=[];startGeneration=0;startPromise=null;constructor(e){this.client=e.client,this.format=e.format??B,this.createDictationId=e.createDictationId??H}getDictationId(){return this.dictationId}getFinalSeq(){return this.segments.length-1}hasSegments(){return this.segments.length>0}clearAll(){this.dictationId&&this.client.cancelDictationStream(this.dictationId),this.clearScheduledFlush(),this.dictationId=null,this.sendSeq=0,this.segments=[],this.streamReady=!1,this.startPromise=null,this.startGeneration+=1}resetStreamForReplay(){this.dictationId&&this.client.cancelDictationStream(this.dictationId),this.clearScheduledFlush(),this.dictationId=null,this.sendSeq=0,this.streamReady=!1,this.startPromise=null,this.startGeneration+=1}enqueueSegment(e){if(this.segments.push(e),this.client.isConnected){if(!this.dictationId){this.startPromise||this.restartStream().catch(()=>{});return}this.flush()}}flush(){let e=this.dictationId;if(!this.client.isConnected||!e||!this.streamReady)return 0;let t=0;for(;this.sendSeq<this.segments.length&&t<z;){let n=this.sendSeq,r=this.segments[n];if(!this.client.sendDictationStreamChunk(e,n,r))break;this.sendSeq=n+1,t+=1}return this.hasPendingSegments()?this.scheduleFlush():this.resolveDrainWaiters(),t}async restartStream(){this.startGeneration+=1;let e=this.startGeneration,t=this.createDictationId();this.dictationId=t,this.sendSeq=0,this.streamReady=!1;let n=(async()=>{await this.client.startDictationStream(t,this.format),this.startGeneration===e&&this.dictationId===t&&(this.streamReady=!0,this.flush())})().catch(n=>{throw this.startGeneration===e&&this.dictationId===t&&(this.dictationId=null,this.streamReady=!1),n}).finally(()=>{this.startPromise===n&&(this.startPromise=null)});this.startPromise=n,await n}async finish(e){this.dictationId||await this.restartStream(),this.startPromise&&await this.startPromise;let t=this.dictationId;if(!t||!this.streamReady)throw Error(`Failed to start dictation stream`);return this.flush(),await this.waitForFlushDrain(),{dictationId:t,text:(await this.client.finishDictationStream(t,e)).text}}cancel(){this.resetStreamForReplay()}hasPendingSegments(){return this.sendSeq<this.segments.length}scheduleFlush(){this.flushTimer||=setTimeout(()=>{this.flushTimer=null,this.flush()},0)}clearScheduledFlush(){this.resolveDrainWaiters(),this.flushTimer&&=(clearTimeout(this.flushTimer),null)}async waitForFlushDrain(){for(;this.hasPendingSegments();){if(!this.client.isConnected||!this.dictationId||!this.streamReady)throw Error(`Failed to flush dictation stream`);await new Promise(e=>{this.drainWaiters.push(e)}),await V()}}resolveDrainWaiters(){let e=this.drainWaiters;this.drainWaiters=[];for(let t of e)t()}},U=c(),W=new Set;function G(e){return W.add(e),()=>{W.delete(e)}}function K(){for(let e of W)e();if(typeof window<`u`&&window.speechSynthesis?.cancel(),typeof navigator>`u`)return;let e=navigator.audioSession;if(e)try{e.type=`play-and-record`}catch{}}function te(){if(typeof navigator>`u`)return;let e=navigator.audioSession;if(e)try{e.type!==`playback`&&(e.type=`playback`)}catch{}}var q=16e3,J=q/5,Y=()=>{if(typeof window>`u`)return null;let e=window;return e.AudioContext||e.webkitAudioContext||null},X=e=>{let t=Math.max(-1,Math.min(1,e));return Math.round(t<0?t*32768:t*32767)},ne=(e,t,n)=>{if(e.length===0)return new Int16Array;if(t===n){let t=new Int16Array(e.length);for(let n=0;n<e.length;n++)t[n]=X(e[n]);return t}let r=t/n,i=Math.max(1,Math.round(e.length/r)),a=new Int16Array(i);for(let t=0;t<i;t++){let n=t*r,i=Math.floor(n),o=Math.min(e.length-1,i+1),s=n-i;a[t]=X(e[i]*(1-s)+e[o]*s)}return a},re=(e,t)=>{if(e.length===0)return t;if(t.length===0)return e;let n=new Int16Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n},Z=e=>{let t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n=``;for(let e=0;e<t.length;e++)n+=String.fromCharCode(t[e]);return btoa(n)},Q=()=>({stream:null,context:null,source:null,processor:null,gain:null,pending:new Int16Array,started:!1}),$=e=>{if(e)try{e.disconnect()}catch{}},ie=()=>typeof navigator>`u`||typeof window>`u`||!navigator.mediaDevices||typeof navigator.mediaDevices.getUserMedia!=`function`?!1:Y()!==null;function ae(e){let t=(0,U.c)(16),[n,r]=(0,x.useState)(0),i=(0,x.useRef)(e.onPcmSegment),a=(0,x.useRef)(e.onError),o,s;t[0]!==e.onError||t[1]!==e.onPcmSegment?(o=()=>{i.current=e.onPcmSegment,a.current=e.onError},s=[e.onPcmSegment,e.onError],t[0]=e.onError,t[1]=e.onPcmSegment,t[2]=o,t[3]=s):(o=t[2],s=t[3]),(0,x.useEffect)(o,s);let c;t[4]===Symbol.for(`react.memo_cache_sentinel`)?(c=Q(),t[4]=c):c=t[4];let u=(0,x.useRef)(c),d=(0,x.useRef)(0),f;t[5]===Symbol.for(`react.memo_cache_sentinel`)?(f=async()=>{if(u.current.started)return;if(typeof navigator>`u`||!navigator.mediaDevices||typeof navigator.mediaDevices.getUserMedia!=`function`)throw Error(`Microphone capture is not supported in this environment`);let e=Y();if(!e)throw Error(`AudioContext unavailable`);let t=d.current+=1;K();let n=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,noiseSuppression:!0,echoCancellation:!0,autoGainControl:!0}});if(t!==d.current){n.getTracks().forEach(ue);return}let a=new e;try{if(a.state===`suspended`&&await a.resume().catch(le),t!==d.current){n.getTracks().forEach(ce),await a.close();return}let e=a.createMediaStreamSource(n),o=a.createScriptProcessor(4096,1,1),s=a.createGain();s.gain.value=0,u.current={stream:n,context:a,source:e,processor:o,gain:s,pending:new Int16Array,started:!0},o.onaudioprocess=e=>{let t=u.current;if(!t.started)return;let n=e.inputBuffer.getChannelData(0),o=0;for(let e=0;e<n.length;e++)o+=n[e]*n[e];let s=Math.sqrt(o/Math.max(1,n.length));r(Math.min(1,Math.max(0,s*2)));let c=ne(n,a.sampleRate,q);for(t.pending=re(t.pending,c);t.pending.length>=J;){let e=t.pending.slice(0,J);t.pending=t.pending.slice(J),i.current(Z(e))}},e.connect(o),o.connect(s),s.connect(a.destination)}catch(e){let t=e;n.getTracks().forEach(se);try{await a.close()}catch{}throw u.current=Q(),t instanceof Error?t:Error(String(t))}},t[5]=f):f=t[5];let p=l(f),m;t[6]===Symbol.for(`react.memo_cache_sentinel`)?(m=async()=>{d.current+=1;let e=u.current;if(e.started=!1,r(0),e.processor)try{e.processor.onaudioprocess=null}catch{}$(e.processor),$(e.source),$(e.gain),e.stream&&e.stream.getTracks().forEach(oe);let t=e.pending;if(e.pending=new Int16Array,t.length>0&&i.current(Z(t)),e.context)try{await e.context.close()}catch{}u.current===e&&(u.current=Q())},t[6]=m):m=t[6];let h=l(m),g,_;t[7]===h?(g=t[8],_=t[9]):(g=()=>()=>{h().catch(e=>{a.current?.(e instanceof Error?e:Error(String(e)))})},_=[h],t[7]=h,t[8]=g,t[9]=_),(0,x.useEffect)(g,_);let v;t[10]===p?v=t[11]:(v=async()=>{try{await p()}catch(e){let t=e,n=t instanceof Error?t:Error(String(t));throw a.current?.(n),n}},t[10]=p,t[11]=v);let y;return t[12]!==h||t[13]!==v||t[14]!==n?(y={start:v,stop:h,volume:n},t[12]=h,t[13]=v,t[14]=n,t[15]=y):y=t[15],y}function oe(e){try{e.stop()}catch{}}function se(e){try{e.stop()}catch{}}function ce(e){return e.stop()}function le(){}function ue(e){return e.stop()}var de=1e3,fe=e=>e instanceof Error?e:Error(String(e));function pe(e={}){let{t}=u(),{onTranscript:r,onError:i,canStart:a}=e,[o,s]=(0,x.useState)(`idle`),[c,d]=(0,x.useState)(!1),[f,p]=(0,x.useState)(``),[m,h]=(0,x.useState)(0),[g,_]=(0,x.useState)(null),[v,y]=(0,x.useState)(null),b=(0,x.useRef)(o);(0,x.useEffect)(()=>{b.current=o},[o]);let S=(0,x.useRef)(``),C=(0,x.useRef)(null),w=(0,x.useRef)({starting:!1,confirming:!1,cancelling:!1}),T=(0,x.useRef)(0),E=(0,x.useRef)(r),D=(0,x.useRef)(i);(0,x.useEffect)(()=>{E.current=r,D.current=i},[r,i]);let O=(0,x.useRef)(null);O.current||=new ee({client:R});let k=l(()=>{C.current&&=(clearInterval(C.current),null)}),A=l(()=>{C.current||=setInterval(()=>{h(e=>e+1)},de)}),j=l(e=>{let n=fe(e),r=n.name===`NotFoundError`||n.name===`DevicesNotFoundError`?Error(t(`chat.dictation.error.microphoneNotFound`),{cause:n}):n;_(r.message);let i=n.reasonCode;y(typeof i==`string`?i:null),D.current?.(r)}),M=l(()=>{_(null),y(null)}),N=l(()=>{O.current?.clearAll(),S.current=``,p(``)}),P=l(t=>e.onPartialTranscript?.(t));(0,x.useEffect)(()=>R.onPartial((e,t)=>{let n=O.current?.getDictationId();!n||e!==n||(S.current=t,p(t),P(t))}),[P]),(0,x.useEffect)(()=>R.subscribeConnectionStatus(e=>{if(!e){b.current===`recording`&&O.current?.resetStreamForReplay();return}if(b.current!==`recording`||O.current?.getDictationId())return;let t=T.current;O.current?.restartStream().catch(e=>{T.current===t&&j(e)})}),[j]);let F=ae({onPcmSegment:e=>{b.current===`recording`&&O.current?.enqueueSegment(e)},onError:e=>{D.current?.(e)}}),I=(0,x.useRef)(F.stop);(0,x.useEffect)(()=>{I.current=F.stop},[F.stop]);let L=l(e=>{h(0),s(`idle`),b.current=`idle`;let t=e.trim();return N(),t?(E.current?.(t),t):null}),z=l(e=>{O.current?.hasSegments()?(s(`failed`),b.current=`failed`):(s(`idle`),b.current=`idle`),j(e)}),B=l(async()=>{let e=w.current;if(e.starting||e.confirming||e.cancelling||b.current!==`idle`||a&&!a())return;e.starting=!0,d(!0);let t=++T.current;M(),p(``),h(0),s(`recording`),b.current=`recording`,N();try{if(await F.start(),T.current!==t||b.current!==`recording`)return;d(!1),A(),await O.current?.restartStream().catch(e=>{T.current===t&&j(e)})}catch(e){if(T.current!==t)return;await F.stop().catch(()=>void 0),k(),s(`idle`),b.current=`idle`,j(e)}finally{T.current===t&&d(!1),e.starting=!1}}),V=l(async()=>{let e=w.current;if(!e.cancelling&&(b.current===`recording`||b.current===`uploading`)){e.cancelling=!0,d(!1),T.current+=1,k(),h(0),M(),s(`idle`),b.current=`idle`;try{O.current?.cancel()}catch{}N();try{await F.stop()}catch{}finally{e.cancelling=!1}}}),H=l(async()=>{let e=w.current;if(e.confirming||b.current!==`recording`)return null;e.confirming=!0,d(!1);let t=++T.current;M(),k();try{if(await F.stop(),T.current!==t)return null;s(`uploading`),b.current=`uploading`;let e=O.current?.getFinalSeq()??-1;if(e<0)return O.current?.cancel(),L(``);let n=await O.current.finish(e);return T.current===t?L(n.text):null}catch(e){return T.current===t&&z(e),null}finally{e.confirming=!1}}),U=l(async()=>{if(b.current!==`failed`||!O.current?.hasSegments())return null;M();let e=++T.current;s(`uploading`),b.current=`uploading`;try{O.current.resetStreamForReplay();let t=O.current.getFinalSeq(),n=await O.current.finish(t);return T.current===e?L(n.text):null}catch(t){return T.current===e&&z(t),null}}),W=l(()=>{if(b.current!==`failed`)return null;let e=S.current.trim();h(0),s(`idle`),b.current=`idle`,M();try{O.current?.cancel()}catch{}return N(),e?(E.current?.(e),e):null}),G=l(()=>{h(0),s(`idle`),b.current=`idle`,M(),N()});return(0,x.useEffect)(()=>n(()=>{b.current===`failed`?(T.current+=1,G()):V()}),[V,G]),(0,x.useEffect)(()=>{if(o!==`recording`||v!==`model_download_in_progress`)return;let e=setInterval(()=>{b.current!==`recording`||O.current?.getDictationId()||O.current?.restartStream().then(()=>{M()}).catch(e=>{j(e)})},3e3);return()=>clearInterval(e)},[o,v,M,j]),(0,x.useEffect)(()=>()=>{T.current+=1,k(),I.current().catch(()=>void 0),O.current?.cancel()},[k]),{status:o,isRecording:o===`recording`,isStarting:c,isProcessing:o===`uploading`,partialTranscript:f,volume:F.volume,duration:m,error:g,errorReason:v,startDictation:B,confirmDictation:H,cancelDictation:V,retryFailedDictation:U,acceptPartialTranscript:W,discardFailedDictation:G}}var me=`app-region-no-drag transition-[opacity,transform] duration-150 ease-out data-[starting-style]:opacity-0 data-[starting-style]:scale-95 data-[ending-style]:opacity-0 data-[ending-style]:scale-95 z-50 max-h-[var(--available-height)] min-w-[8rem] origin-[var(--transform-origin)] overflow-visible rounded-xl p-1 shadow-[inset_0_1px_0_0_rgba(255,255,255,0.8),inset_0_0_0_1px_rgba(0,0,0,0.04),0_0_0_1px_rgba(0,0,0,0.10),0_1px_2px_-0.5px_rgba(0,0,0,0.08),0_4px_8px_-2px_rgba(0,0,0,0.08),0_12px_20px_-4px_rgba(0,0,0,0.08)] dark:shadow-[inset_0_1px_0_0_rgba(255,255,255,0.12),inset_0_0_0_1px_rgba(255,255,255,0.08),0_0_0_1px_rgba(0,0,0,0.36),0_1px_1px_-0.5px_rgba(0,0,0,0.22),0_3px_3px_-1.5px_rgba(0,0,0,0.20),0_6px_6px_-3px_rgba(0,0,0,0.16)]`,he=`data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover active:bg-interactive-active data-[variant=destructive]:text-destructive data-[variant=destructive]:hover:bg-destructive/10 dark:data-[variant=destructive]:hover:bg-destructive/20 data-[variant=destructive]:hover:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-pointer items-center gap-2 rounded-lg px-2 py-1 typography-ui-label outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5`,ge=`data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover active:bg-interactive-active [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-pointer items-center gap-2 rounded-lg px-2 py-1 typography-ui-label outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5`,_e=`bg-border -mx-1 my-0.5 h-px`;export{m as S,f as _,pe as a,_ as b,te as c,j as d,A as f,d as g,C as h,ge as i,G as l,S as m,me as n,ie as o,O as p,_e as r,K as s,he as t,k as u,p as v,y as x,b as y};
@@ -1,10 +0,0 @@
1
- import{n as e}from"./rolldown-runtime-hePW80VL.js";import{i as t,n}from"./runtime-switch-CAZiOV2G.js";import{n as r}from"./runtime-fetch-BAN5Gnnp.js";import{t as i}from"./runtimeAPIRegistry-C2VogTny.js";import{$ as a,A as o,C as s,F as c,G as l,J as u,K as d,L as f,M as p,N as m,Nt as ee,O as te,Q as ne,R as re,S as ie,T as ae,X as oe,Y as h,Z as se,_ as ce,at as le,b as ue,c as de,d as fe,gt as pe,h as me,ht as he,it as ge,lt as _e,m as ve,nt as ye,o as be,pt as xe,rt as Se,u as Ce,ut as we,v as Te,vt as Ee,w as De,x as Oe,xt as ke,yt as Ae,z as je}from"./platform-BND-ZKbF.js";import{d as g,ga as _,l as Me,wa as v}from"./useMobileNavigationStore-YGHA7SiM.js";var Ne=e({COMMIT_DIFF_FILE_LIMIT:()=>30,COMMIT_DIFF_TOTAL_CHAR_LIMIT:()=>j,SESSION_GENERATE_TIMEOUT_MS:()=>M,applyGitStash:()=>K,checkIsGitRepository:()=>x,checkoutCommit:()=>$e,cherryPick:()=>et,collectSelectedFileDiffs:()=>N,countGitStashFiles:()=>W,createBranch:()=>Y,createGitIdentity:()=>Q,createGitWorktree:()=>B,deleteGitIdentity:()=>Je,deleteGitWorktree:()=>V,deleteRemoteBranch:()=>A,discoverGitCredentials:()=>Ye,discoverGitRepositories:()=>S,dropGitStash:()=>J,generateCommitMessage:()=>F,getCommitFileDiff:()=>X,getConflictDetails:()=>$,getGitBranches:()=>k,getGitIdentities:()=>Z,getGitStatus:()=>C,getGitWorktreeBootstrapStatus:()=>R,getGlobalGitIdentity:()=>Xe,git:()=>H,listGitStashes:()=>U,listGitWorktrees:()=>I,merge:()=>Qe,popGitStash:()=>q,previewGitWorktree:()=>z,rebase:()=>Ze,resetToCommit:()=>nt,resolveGitPrimaryRoot:()=>w,resolveGitTopLevel:()=>T,revertCommit:()=>tt,stageGitFile:()=>E,stageGitFiles:()=>D,stashGitChanges:()=>G,unstageGitFile:()=>Pe,unstageGitFiles:()=>O,updateGitIdentity:()=>qe,validateGitWorktree:()=>L}),y=()=>i()?.git??null,b=e=>{let t=e.trim(),n=(t.match(/```(?:json)?\s*([\s\S]*?)```/i)?.[1]??t).trim(),r=[n.indexOf(`{`)].filter(e=>e>=0);for(let e of r)for(let t=n.length;t>e;--t)if(n[t-1]===`}`)try{let r=JSON.parse(n.slice(e,t));if(r&&typeof r==`object`&&!Array.isArray(r))return r}catch{}return null};async function x(e){let t=y();return t?t.checkIsGitRepository(e):de(e)}async function S(e){return De(e)}async function C(e,t){let n=y();return n?n.getGitStatus(e,t):f(e,t)}async function w(e){return(await Se(e)).root}async function T(e){return(await ge(e)).root}async function E(e,t){let n=y();return n?.stageGitFile?n.stageGitFile(e,t):_e(e,t)}async function D(e,t){let n=y();return n?.stageGitFiles?n.stageGitFiles(e,t):we(e,t)}async function Pe(e,t){let n=y();return n?.unstageGitFile?n.unstageGitFile(e,t):he(e,t)}async function O(e,t){let n=y();return n?.unstageGitFiles?n.unstageGitFiles(e,t):pe(e,t)}async function k(e,t){let n=y();if(t?.signal?.throwIfAborted(),n){let r=await n.getGitBranches(e,t);return t?.signal?.throwIfAborted(),r}return p(e,t)}async function A(e,t){let n=y();return n?n.deleteRemoteBranch(e,t):ie(e,t)}var j=12e4,M=9e4,Fe=[`This is an auxiliary structured generation request (git copy).`,`Use the active session context plus the materials below.`,`Answer with the required JSON only.`,`Do not call any tools and do not take any actions.`,`Model and instructions follow the session.generate session contract.`].join(` `),Ie=`Select an active session for generation. session.generate uses that session model contract and does not mutate chat history.`,Le=`No default provider or model configured. Please select a provider and model in settings first.`,Re=`Runtime changed during session.generate`,ze=`session.generate returned empty text`,Be=`session.generate returned invalid structured output`,Ve=e=>{let t=[`Diff budget: included ${e.includedFileCount} of ${e.selectedFileCount} selected files`,`fileLimit=${e.fileLimit}`,`charLimit=${e.charLimit}`,`truncatedByCharLimit=${e.truncatedByCharLimit?`yes`:`no`}`,`omittedFiles=${e.omittedFileCount}`],n=e.omittedFileCount>0||e.truncatedByCharLimit?` Materials are partial under this budget — do not invent diffs for omitted or truncated files; base the message only on provided material.`:` Materials cover the full selected set within the budget.`;return`${t.join(`; `)}.${n}`};async function N(e,t){let n=t.length,r=t.slice(0,30),i=await Promise.all(r.map(async t=>{try{let[n,r]=await Promise.all([m(e,{path:t,staged:!0}).catch(()=>null),m(e,{path:t,staged:!1}).catch(()=>null)]);return[n?.diff,r?.diff].filter(e=>typeof e==`string`&&e.trim().length>0).join(`
2
- `)||`--- ${t} (no textual diff available)`}catch{return`--- ${t} (diff unavailable)`}})),a=``,o=0,s=!1;for(let e of i){let t=a?`
3
-
4
- `:``;if(a.length+t.length+e.length>12e4){a+=`
5
- [remaining diffs truncated by char budget — not a full selected-set dump]`,s=!0;break}a+=t+e,o+=1}let c=Math.max(0,n-r.length),l=c+(s?Math.max(0,r.length-o):0);c>0&&(a+=`\n[${c} more selected files omitted by file budget — not included]`);let u={selectedFileCount:n,includedFileCount:o,omittedFileCount:l,truncatedByCharLimit:s,fileLimit:30,charLimit:j};return{...u,text:a,budgetNote:Ve(u)}}var P=e=>{let t=typeof e?.subject==`string`?e.subject.trim():``,n=Array.isArray(e?.highlights)?e.highlights.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean).slice(0,3):[];if(!t)throw Error(`Structured output missing subject`);return{subject:t,highlights:n}},He=(e,t)=>{if(t?.aborted)return!0;if(!e||typeof e!=`object`)return!1;let n=`name`in e?String(e.name??``):``;return n===`AbortError`||n===`TimeoutError`},Ue=e=>{let t=new AbortController,n=()=>{try{t.abort(e?.reason)}catch{t.abort()}};e&&(e.aborted?n():e.addEventListener(`abort`,n,{once:!0}));let r=setTimeout(()=>{let e=new DOMException(`session.generate timed out after ${M}ms`,`TimeoutError`);try{t.abort(e)}catch{t.abort()}},M);return{signal:t.signal,cleanup:()=>{clearTimeout(r),e&&e.removeEventListener(`abort`,n)}}};async function We(){let e=g.getState().currentSessionId;if(typeof e==`string`&&e.trim())return e.trim();if(!g.getState().newSessionDraft?.open)throw Error(Ie);let t=v.getState();if(!t.currentProviderId||!t.currentModelId)throw Error(Le);let n=await Me({providerID:t.currentProviderId,modelID:t.currentModelId,agent:t.currentAgentName||void 0,variant:t.currentVariant||void 0});if(n?.sessionId)return n.sessionId;let r=g.getState().currentSessionId;if(typeof r==`string`&&r.trim())return r.trim();throw Error(`Failed to create session for generation`)}async function Ge(e){let r={sessionId:await We(),directory:e.directory,kind:e.kind,runtimeGeneration:n(),runtimeTransport:t()},i=typeof e.prompt==`string`?e.prompt.trim():``;if(!i)throw Error(`Generation prompts are empty`);let{signal:a,cleanup:o}=Ue(e.signal),s=Date.now();r.kind,r.directory,r.sessionId,i.length;try{a.throwIfAborted();let e=await ee.generateSessionAside({sessionId:r.sessionId,directory:r.directory,prompt:i,signal:a});if(n()!==r.runtimeGeneration||t()!==r.runtimeTransport)throw Error(Re);let o=typeof e?.text==`string`?e.text.trim():``;if(!o)throw Error(ze);let c=b(o);if(!c)throw console.error(`[git-generation][browser] invalid JSON from session.generate`,{kind:r.kind,sessionId:r.sessionId,elapsedMs:Date.now()-s,textPreview:o.slice(0,400)}),Error(Be);return r.kind,r.sessionId,Date.now()-s,o.length,c}catch(e){if(He(e,a)){let e=a.reason instanceof Error?a.reason.message:typeof a.reason==`string`&&a.reason.trim()?a.reason:`session.generate cancelled`;throw new DOMException(e,a.reason instanceof DOMException?a.reason.name:`AbortError`)}throw e}finally{o()}}var Ke=(e,t)=>[Fe,typeof e==`string`?e.trim():``,typeof t==`string`?t.trim():``].filter(Boolean).join(`
6
-
7
- `);async function F(e,t,n){let i=Date.now(),a=n?.signal;n?.zenModel,n?.providerId,n?.modelId,t.length;let o=await _(`git.commit.generate.visible`),s=await _(`git.commit.generate.instructions`,{selected_files:t.map(e=>`- ${e}`).join(`
8
- `)});try{a?.throwIfAborted();let n=await N(e,t),c=[s,n.budgetNote,`Diffs of the selected files (budget-aligned; see note above):`,n.text].join(`
9
-
10
- `),{currentProviderId:l,currentModelId:u}=v.getState(),d=await r(`/api/small-model/generate`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({purpose:`commit`,system:o,prompt:c,directory:e,...l?{preferredProviderID:l}:{},...u?{preferredModelID:u}:{}}),...a?{signal:a}:{}});if(d.status===404){t.length,n.includedFileCount,n.omittedFileCount,n.truncatedByCharLimit,c.length;let r={message:P(await Ge({directory:e,prompt:Ke(o,c),kind:`commit`,signal:a}))};return Date.now()-i,r.message.subject.length,r.message.highlights.length,n.includedFileCount,n.omittedFileCount,n.truncatedByCharLimit,r}let f=await d.json().catch(()=>null);if(!d.ok||typeof f?.text!=`string`){let e=typeof f?.error==`string`?f.error:`HTTP ${d.status}`;throw Error(e)}let p={message:P(b(f.text))};return Date.now()-i,p.message.subject.length,p.message.highlights.length,n.includedFileCount,n.omittedFileCount,n.truncatedByCharLimit,p}catch(e){throw console.error(`[git-generation][browser] failed`,{transport:`small-model|session.generate`,kind:`commit`,elapsedMs:Date.now()-i,message:e instanceof Error?e.message:String(e),error:e}),e}}async function I(e){let t=y();if(!t)return h(e);let n=t.worktree?.list??t.listGitWorktrees;if(d(n))return h(e);let r=t.worktree?.list?t.worktree.list.bind(t.worktree):t.listGitWorktrees.bind(t);return ke(()=>r(e))}async function L(e,t){let n=y();return n?.worktree?.validate?n.worktree.validate(e,t):n?.validateGitWorktree?n.validateGitWorktree(e,t):Ae(e,t)}async function R(e){let t=y();return t?.worktree?.bootstrapStatus?t.worktree.bootstrapStatus(e):t?.getGitWorktreeBootstrapStatus?t.getGitWorktreeBootstrapStatus(e):re(e)}async function z(e,t){let n=y();return n?.worktree?.preview?n.worktree.preview(e,t):n?.previewGitWorktree?n.previewGitWorktree(e,t):ne(e,t)}async function B(e,t){let n=y(),r;return r=n?.worktree?.create?await n.worktree.create(e,t):n?.createGitWorktree?await n.createGitWorktree(e,t):await Te(e,t),l(e),r}async function V(e,t){let n=y(),r;return r=n?.worktree?.remove?await n.worktree.remove(e,t):n?.deleteGitWorktree?await n.deleteGitWorktree(e,t):await Oe(e,t),l(e),r}var H={worktree:{list:I,validate:L,create:B,remove:V}};async function U(e){let t=y();return t?t.listGitStashes(e):u(e)}async function W(e,t){let n=y();return n?n.countGitStashFiles(e,t):ve(e,t)}async function G(e,t={}){let n=y();return n?n.stashGitChanges(e,t):xe(e,t)}async function K(e,t){let n=y();return n?n.applyGitStash(e,t):be(e,t)}async function q(e,t){let n=y();return n?n.popGitStash(e,t):se(e,t)}async function J(e,t){let n=y();return n?n.dropGitStash(e,t):ae(e,t)}async function Y(e,t,n){let r=y();return r?r.createBranch(e,t,n):me(e,t,n)}async function X(e,t,n,r){let i=y();return i?.getCommitFileDiff?i.getCommitFileDiff(e,t,n,r):te(e,t,n,r)}async function Z(){let e=y();return e?e.getGitIdentities():c()}async function Q(e){let t=y();return t?t.createGitIdentity(e):ce(e)}async function qe(e,t){let n=y();return n?n.updateGitIdentity(e,t):Ee(e,t)}async function Je(e){let t=y();return t?t.deleteGitIdentity(e):ue(e)}async function Ye(){let e=y();return e?.discoverGitCredentials?e.discoverGitCredentials():s()}async function Xe(){let e=y();return e?.getGlobalGitIdentity?e.getGlobalGitIdentity():je()}async function Ze(e,t){let n=y();return n?n.rebase(e,t):a(e,t)}async function Qe(e,t){let n=y();return n?n.merge(e,t):oe(e,t)}async function $e(e,t){let n=y();return n?n.checkoutCommit(e,t):Ce(e,t)}async function et(e,t){let n=y();return n?n.cherryPick(e,t):fe(e,t)}async function tt(e,t){let n=y();return n?n.revertCommit(e,t):le(e,t)}async function nt(e,t,n,r){let i=y();return i?i.resetToCommit(e,t,n,r):ye(e,t,n,r)}async function $(e){let t=y();return t?.getConflictDetails?t.getConflictDetails(e):o(e)}export{T as A,U as C,Ze as D,z as E,Pe as F,O as I,qe as L,E as M,D as N,nt as O,G as P,Ne as S,q as T,Z as _,W as a,Xe as b,Je as c,S as d,J as f,k as g,$ as h,et as i,tt as j,w as k,A as l,X as m,x as n,Y as o,F as p,$e as r,Q as s,K as t,Ye as u,C as v,Qe as w,H as x,R as y};
@@ -1 +0,0 @@
1
- import{c as e,f as t,i as n,n as r,r as i}from"./runtime-switch-CAZiOV2G.js";import{n as a}from"./runtime-fetch-BAN5Gnnp.js";import{L as o}from"./vendor-opencode-client-BcpAhe9I.js";import{t as s}from"./runtime-file-store-BVRgEtI-.js";var c=(e,t)=>JSON.stringify([`gui-code-v1`,`2.2`,e,t]),l=(e,t)=>JSON.stringify([`gui-code`,e,t]),u=e=>typeof e==`string`&&/^[a-f0-9]{64}$/.test(e),d={async read(e,t,n){try{let r=await s.read(c(e,t),n);if(!r)return null;let i=JSON.parse(await r.text());if(!i||typeof i!=`object`||Array.isArray(i))return null;let a=i;return Object.keys(a).length!==2||typeof a.code!=`string`||!a.code||!u(a.token)?null:{code:a.code,token:a.token}}catch{return null}},async write(e,t,n,r){try{await s.write(c(e,t),new Blob([JSON.stringify({code:n.code,token:n.token})],{type:`application/json`}),r,void 0,l(e,t))}catch{}}},f=e=>!!e&&typeof e==`object`&&!Array.isArray(e);function p(s){let c=n(),l=r(),p=i(),m=()=>c===n()&&l===r()&&p===i();return o.make({baseUrl:new URL(t().api(`/`),window.location.href).href,fetch:async(n,r)=>{if(s.aborted||!m())throw new DOMException(`Plugin runtime ended`,`AbortError`);let i=new URL(n instanceof Request?n.url:n.toString()),o=new URL(t().api(`${i.pathname}${i.search}`),window.location.href),c=new Request(o,n instanceof Request?n:r),l={...r,signal:AbortSignal.any([s,c.signal,...r?.signal?[r.signal]:[]])},h=i.searchParams.get(`id`);if((r?.method??c.method).toUpperCase()!==`GET`||i.pathname!==`/api/plugin/gui`||!h)return a(c,l);let g=new AbortController,_=e(()=>{m()||g.abort()}),v=AbortSignal.any([l.signal,g.signal]),y=()=>{if(v.throwIfAborted(),!m())throw new DOMException(`Plugin runtime ended`,`AbortError`)};try{let e=await d.read(p,h,v);y();let t=async e=>{y();let t=new Headers(r?.headers??c.headers);return t.delete(`X-Yuri-Gui-Revision`),t.delete(`If-None-Match`),e&&t.set(`X-Yuri-Gui-Revision`,e),a(c,{...l,signal:v,headers:t,cache:`no-store`})},n=await t(e?.token),i=!!e;if(y(),n.headers.get(`X-Yuri-Gui-Code`)===`cached`&&(!e||n.headers.get(`X-Yuri-Gui-Revision`)!==e.token)&&(await n.body?.cancel(),i=!1,n=await t(),y()),n.status!==200)return n;let o=await n.clone().json();if(y(),!f(o)||!f(o.data)||typeof o.data.code!=`string`||typeof o.data.revision!=`string`||!f(o.data.options))throw Error(`Invalid GUI bundle response`);let s=n.headers.get(`X-Yuri-Gui-Revision`);if(n.headers.get(`X-Yuri-Gui-Code`)===`cached`){if(!i||!e||s!==e.token||o.data.code!==``)throw Error(`Invalid GUI code cache response`);o.data.code=e.code;let t=new Headers(n.headers);t.delete(`content-length`),t.delete(`content-encoding`),n=Response.json(o,{status:200,headers:t})}else u(s)&&o.data.code&&(y(),await d.write(p,h,{code:o.data.code,token:s},v));return y(),n}finally{_()}}})}export{p as createGuiClient};
@@ -1 +0,0 @@
1
- import{A as e,C as t,E as n,F as r,I as i,M as a,P as o,S as s,T as c,_ as l,a as u,b as d,g as f,h as p,i as m,k as h,n as g,o as _,r as v,t as y,x as b}from"./vendor-opencode-client-BcpAhe9I.js";import{i as x}from"./vendor-tanstack-query-core-BWz0ose6.js";import{n as S,r as ee}from"./fileQueries-DbUx7NwP.js";import{o as te}from"./path-utils-jGozTg9d.js";import{n as ne}from"./pathNormalization-ewtPqJWn.js";import{i as re,o as ie}from"./fileReferenceParser-1HHDBUum.js";import{n as ae,t as oe}from"./vendor-solid-js-B2FO7pdm.js";import{a as se,c as ce,d as C,f as w,h as le,i as T,l as E,m as D,n as ue,o as O,p as de,r as fe,s as pe,t as k,u as A}from"./vendor-opencode-plugin-BglYYlJt.js";import{ft as j,pt as M,wt as N,y as P}from"./vendor-effect-DXlObQuU.js";var F={"@opencode/plugin/gui":O,"@opencode/plugin/gui/main":O,"@opencode/plugin/gui/file":se,"@opencode/plugin/gui/review":T,"@opencode/plugin/gui/browser":fe,"@opencode/plugin/rpc":k,"@opencode/schema/rpc":ue,"@opencode/client":i,"@opencode/client/effect":g,"@opencode/client/solid":y,effect:P,"solid-js":a,"solid-js/web":ae,"solid-js/store":u},I=new Set(`assert assert/strict async_hooks buffer child_process cluster console constants crypto dgram diagnostics_channel dns dns/promises domain events fs fs/promises http http2 https inspector inspector/promises module net os path path/posix path/win32 perf_hooks process punycode querystring readline readline/promises repl stream stream/consumers stream/promises stream/web string_decoder sys timers timers/promises tls trace_events tty url util util/types v8 vm wasi worker_threads zlib`.split(` `));function L(){let e=new Proxy(function(){},{get:(t,n)=>n===`then`?void 0:n===Symbol.hasInstance?()=>!1:n===Symbol.toPrimitive||n===`toString`?()=>`[main-only module]`:e,apply:()=>e,construct:()=>e,set:()=>!0});return e}function R(e){if(e.length>16777216)throw Error(`GUI bundle exceeds 16 MiB`);let t={exports:{}};Function(`require`,`module`,`exports`,e)(e=>{if(Object.hasOwn(F,e))return F[e];if(e===`electron`||e.startsWith(`node:`)||I.has(e))return L();throw Error(`Unsupported GUI shared module: ${e}`)},t,t.exports);let n=t.exports,r=n&&typeof n==`object`&&`default`in n?n.default:n;if(!r||typeof r!=`object`)throw Error(`GUI bundle must default-export Plugin.define`);if(!(`setup`in r)||typeof r.setup!=`function`)throw Error(`This host requires a window setup; main-only plugins are unsupported`);if(`os`in r&&r.os!==void 0)throw Error(`OS-restricted plugins require the native GUI host`);if(`main`in r&&r.main!==void 0&&typeof r.main!=`function`)throw Error(`Invalid GUI main entry`);if(`stores`in r&&r.stores!==void 0){if(!r.stores||typeof r.stores!=`object`||Array.isArray(r.stores))throw Error(`Invalid GUI stores`);for(let e of Object.values(r.stores))if(!e||typeof e!=`object`||!(`schema`in e)||!N(e.schema)||!(`scope`in e)||![`global`,`session`].includes(String(e.scope))||!(`initial`in e))throw Error(`Invalid GUI store declaration`)}if(`i18n`in r&&r.i18n!==void 0){if(!r.i18n||typeof r.i18n!=`object`||Array.isArray(r.i18n))throw Error(`Invalid GUI locale catalog`);for(let e of Object.values(r.i18n))if(!e||typeof e!=`object`||Array.isArray(e)||Object.values(e).some(e=>typeof e!=`string`))throw Error(`GUI locales must be inline string dictionaries`)}return r}function z(e){let t=e;if(/^file:/i.test(t)){let e=new URL(t);t=`${e.hostname&&e.hostname!==`localhost`?`//${e.hostname}`:``}${decodeURIComponent(e.pathname)}`,/^\/[a-z]:\//i.test(t)&&(t=t.slice(1))}let n=ne(t)??``;return n===`.`?``:n}var B=e=>/^(?:\/|[a-z]:\/)/i.test(e),V=()=>{throw Error(`Unsupported GUI file API: tree`)},H=class extends Error{},U=e=>new TextEncoder().encode(e).byteLength,me=class{files;query;transport;root;api;ended=!1;states=new Map;inflight=new Map;watches=new Map;apiLeases=new Map;registeredOwners=new WeakSet;endedOwners=new WeakSet;leaseCount=0;rerun=new Set;selections=new Map;scrolls=new Map;subscriptions=new Map;constructor(e,t,r,i){this.files=e,this.query=t,this.transport=r,this.root=i,this.root=z(i),this.api={root:this.root,ready:()=>!this.ended,resolve:e=>this.resolve(e),absolute:B,get:e=>{let t=this.track(e,`file`);return this.states.get(t)},missing:e=>{let t=this.track(e,`missing`);return this.states.get(t)?.notFound===!0},sync:(e,t)=>{let r=n();return this.ended||r&&this.endedOwners.has(r)?Promise.resolve():(this.acquireApiLease(e),this.sync(e,t?.force))},unwatch:e=>this.releaseApiLease(n(),this.resolve(e)),exists:async e=>{try{if(this.files.statFile)return(await this.query.fetchQuery(this.statOptions(e))).isFile;let t=this.full(e);return(await this.files.listDirectory(t.slice(0,t.lastIndexOf(`/`)))).entries.some(e=>!e.isDirectory&&z(e.path)===t)}catch{return!1}},search:async(e,t)=>{if(t?.kind===`any`)throw Error(`Unsupported GUI file search: directories`);t?.signal?.throwIfAborted();let n=await this.query.fetchQuery({queryKey:[`gui-plugin-files`,r,this.root,`search`,e,t?.limit],gcTime:3e4,queryFn:async({signal:n})=>(n.throwIfAborted(),this.files.search({directory:this.root,query:e,maxResults:t?.limit??100}))});if(t?.signal?.throwIfAborted(),this.ended)throw new DOMException(`GUI file model was disposed`,`AbortError`);return n.map(e=>this.resolve(e.path))},selection:{get:e=>this.selections.get(this.track(e,`selection`)),set:(e,t)=>{let n=this.resolve(e),r=this.selections.get(n);r===t||r&&t&&r.start===t.start&&r.end===t.end&&r.side===t.side&&r.endSide===t.endSide||(this.selections.set(n,t),this.trim(this.selections,`selection`),this.changed(n,`selection`))}},scroll:{get:e=>this.scrolls.get(this.track(e,`scroll`))??{},set:(e,t)=>{let n=this.resolve(e),r=this.scrolls.get(n),i={...r,...t};(r?.top!==i.top||r?.left!==i.left)&&(this.scrolls.set(n,i),this.trim(this.scrolls,`scroll`),this.changed(n,`scroll`))}},tree:{list:V,state:V,sync:V,expand:V,collapse:V}}}resolve(e){let t=z(e);if(!B(t))return t;if(t===this.root)return``;let n=this.root.endsWith(`/`)?this.root:`${this.root}/`;return t.startsWith(n)?t.slice(n.length):t}full(e){let t=this.resolve(e);return B(t)?t:z(`${this.root}/${t}`)}input(e){return{scopeDirectory:this.root,path:this.full(e),options:{directory:this.root}}}statOptions(e){return{...ee(this.files,this.input(e),this.transport),gcTime:3e4}}track(n,r){let i=this.resolve(n),a=c();if(!a||this.ended)return i;let o=`${r}:${i}`,s=this.subscriptions.get(o);s||(s={revision:t(0),listeners:new Set},this.subscriptions.set(o,s));let l=s;return l.listeners.has(a)||(l.listeners.add(a),e(a,()=>h(()=>{l.listeners.delete(a),!l.listeners.size&&this.subscriptions.get(o)===l&&this.subscriptions.delete(o)}))),l.revision[0](),i}changed(e,t){this.ended||this.subscriptions.get(`${t}:${e}`)?.revision[1](e=>e+1)}trim(e,t){for(;e.size>64;){let n=e.keys().next().value;e.delete(n),this.changed(n,t)}}setState(e,t){let n=this.states.get(e);n?.content?.content===t.content?.content&&n?.content?.type===t.content?.type&&(t.content=n?.content),!(n&&n.loaded===t.loaded&&n.loading===t.loading&&n.error===t.error&&n.notFound===t.notFound&&n.content===t.content)&&(this.states.set(e,t),p(()=>{this.changed(e,`file`),n?.notFound===!0!=(t.notFound===!0)&&this.changed(e,`missing`)}))}acquireApiLease(e){let t=n();if(this.ended||t&&this.endedOwners.has(t)||!this.files.statFile)return;let r=this.resolve(e),i=this.apiLeases.get(t);if(i?.has(r))return;if(this.leaseCount>=256)throw Error(`GUI file consumer limit exceeded`);let a=this.watch(r);i||(i=new Map,this.apiLeases.set(t,i)),i.set(r,a),this.leaseCount++,t&&!this.registeredOwners.has(t)&&(this.registeredOwners.add(t),h(()=>{`fn`in t||this.endedOwners.add(t),this.registeredOwners.delete(t);for(let e of[...this.apiLeases.get(t)?.keys()??[]])this.releaseApiLease(t,e)}))}releaseApiLease(e,t){let n=this.apiLeases.get(e),r=n?.get(t);r&&(n.delete(t),this.leaseCount--,n.size||this.apiLeases.delete(e),r())}reserve(e){if(!this.states.has(e)){if(this.states.size>=64){let e=[...this.states.keys()].find(e=>!this.watches.has(e)&&!this.inflight.has(e));if(!e)throw Error(`GUI file cache limit exceeded`);let t=this.states.get(e)?.notFound===!0;this.states.delete(e),p(()=>{this.changed(e,`file`),t&&this.changed(e,`missing`)})}this.states.set(e,{path:e,name:e.split(`/`).at(-1)??e})}}async sync(e,t=!1){if(this.ended)return;let n=this.resolve(e);if(this.inflight.has(n))return t&&this.rerun.add(n),this.inflight.get(n);if(!t&&this.states.get(n)?.loaded&&!this.states.get(n)?.error)return;this.reserve(n);let r=this.states.get(n);this.setState(n,{...r,path:n,name:n.split(`/`).at(-1)??n,loading:!r?.loaded&&!this.watches.get(n)?.failed});let i=(async()=>{try{do{this.rerun.delete(n);let e=this.watches.get(n),r=e?.epoch;try{let i=S(this.files,this.input(n),this.transport),a=await this.query.fetchQuery({...i,gcTime:3e4,staleTime:t?0:3e4,queryFn:async()=>{if(!this.files.readFile)throw Error(`File content reads are unavailable in this runtime`);let e=await this.files.readFile(this.full(n),{directory:this.root});if(e.exists===!1)throw new H(`File does not exist`);let t=e.content;if(U(t)>131072)throw Error(`GUI file preview exceeds 128 KiB`);return t}});if(this.ended)return;if(U(a)>131072)throw Error(`GUI file preview exceeds 128 KiB`);(!e||e.epoch===r&&!e.failed)&&this.setState(n,{path:n,name:n.split(`/`).at(-1)??n,loaded:!0,loading:!1,content:{type:`text`,content:a}})}catch(t){if(this.ended)return;if((!e||e.epoch===r&&!e.failed)&&this.setState(n,{...this.states.get(n),loading:!1,...t instanceof H?{notFound:!0}:{},error:String(t)}),!this.rerun.has(n))throw t}t=!0}while(!this.ended&&this.rerun.has(n))}finally{this.inflight.delete(n),this.rerun.delete(n)}})();return this.inflight.set(n,i),i}watch(e){if(this.ended||!this.files.statFile)return()=>{};let t=this.resolve(e),n=this.watches.get(t);if(!n){if(this.watches.size>=64)throw Error(`GUI file watch limit exceeded`);this.reserve(t),n={count:0,epoch:0,failed:!1,stop:()=>{}};let e=n;this.watches.set(t,e);let r,i=new x(this.query,{...this.statOptions(t),refetchInterval:2e3,refetchIntervalInBackground:!1}),a=i.subscribe(n=>{if(this.ended||this.watches.get(t)!==e||n.isFetching)return;if(n.isError||n.isSuccess&&!n.data.isFile){e.failed=!0,e.epoch++,this.setState(t,{...this.states.get(t),loading:!1,notFound:n.isSuccess?!0:this.states.get(t)?.notFound,error:n.isError?String(n.error):`File does not exist`});return}if(!n.data||!n.isSuccess)return;let i=`${n.data.size}:${n.data.mtimeMs??``}`,a=e.failed||r!==void 0&&i!==r;e.failed=!1,r=i,a&&(e.epoch++,this.sync(t,!0).catch(()=>{}))});e.stop=()=>{a(),i.destroy()}}n.count++;let r=!0;return()=>{r&&(r=!1,--n.count===0&&this.watches.get(t)===n&&this.stopWatch(t))}}stopWatch(e){this.watches.get(e)?.stop(),this.watches.delete(e)}dispose(){this.ended=!0;for(let e of this.watches.values())e.stop();this.watches.clear(),this.apiLeases.clear(),this.leaseCount=0,this.rerun.clear(),this.states.clear(),this.inflight.clear(),this.selections.clear(),this.scrolls.clear(),this.subscriptions.clear()}},W=256,G=2097152,K=e=>structuredClone(_(e)),he=class{backend;transport;memory=new Map;resets=new Map;constructor(e,t){this.backend=e,this.transport=t}forPlugin(e,n){let r=(t,n=`global`)=>{if(typeof n==`object`&&`session`in n&&!n.session.location)throw Error(`Unsupported GUI storage: session location is unknown`);let r=n===`global`?n:`session`in n?[n.session.server.id,n.session.id,n.session.location]:[n.server,n.directory];return`yuri.gui-plugin.${JSON.stringify([this.transport,e,r,t])}`},i=e=>{if(n.aborted)throw Error(`GUI plugin has been disposed`);if(e!==void 0)throw Error(`Unsupported GUI storage migration: from`)},a=new Map;return{store:(e,o)=>{i(o.from);let s=r(e,o.scope),c=a.get(s);if(c)return c;if(a.size>=W)throw Error(`GUI plugin store limit exceeded`);let l=j(o.schema),u=M(o.schema),d=l(u(K(o.initial)));if(JSON.stringify(u(d)).length>G)throw Error(`GUI plugin store exceeds 2 MiB`);let f=d,p=this.backend.getItem(s);if(p!==null&&p.length<=G)try{f=l(JSON.parse(p))}catch{f=d}let[m,h]=t(f),g=e=>{i();let t=JSON.stringify(u(K(e)));if(t.length>G)throw Error(`GUI plugin store exceeds 2 MiB`);let n=l(JSON.parse(t));this.backend.setItem(s,t),h(()=>n)},_={get value(){return m()},ready:()=>!0,set:g,update:e=>{let t=K(m());if(e(t)!==void 0)throw Error(`Store update must not return a replacement`);g(t)}},v=()=>h(()=>K(d)),y=this.resets.get(s)??new Set;return y.add(v),this.resets.set(s,y),n.addEventListener(`abort`,()=>{y.delete(v),y.size||this.resets.delete(s),a.clear()},{once:!0}),a.set(s,_),_},memory:(e,t)=>{i();let n=r(e),a=this.memory.get(n);if(a)return[a[0],e=>{i(),a[1](e)}];if(this.memory.size>=W)throw Error(`GUI plugin memory store limit exceeded`);if(JSON.stringify(t.initial).length>G)throw Error(`GUI plugin memory exceeds 2 MiB`);let[o,s]=v(K(t.initial)),c=[o,e=>{i();let t=K(_(o));if(e(t)!==void 0)throw Error(`Memory update must not return a replacement`);if(JSON.stringify(t).length>G)throw Error(`GUI plugin memory exceeds 2 MiB`);s(m(t))}];return this.memory.set(n,[o,e=>{let t=K(_(o));if(e(t)!==void 0)throw Error(`Memory update must not return a replacement`);if(JSON.stringify(t).length>G)throw Error(`GUI plugin memory exceeds 2 MiB`);s(m(t))}]),c},remove:(e,t)=>{i(t?.from);let n=r(e,t?.scope);this.backend.removeItem(n);for(let e of this.resets.get(n)??[])e()}}}dispose(){this.memory.clear(),this.resets.clear()}},ge=`yuri.file-icon`,q=`http://www.w3.org/2000/svg`,_e=new Set([`svg`,`g`,`path`,`rect`,`circle`,`ellipse`,`line`,`polyline`,`polygon`,`defs`,`linearGradient`,`radialGradient`,`stop`,`clipPath`,`mask`,`use`,`title`,`desc`]),J=e=>e.trim().replace(/^\./,``).toLowerCase();function Y(e,t){if(typeof e!=`string`)throw Error(`GUI file icon requires SVG text`);let n=t.get(e);if(n)return n;if(e.length>16384)throw Error(`GUI file icon SVG exceeds 16 KiB`);let r=new TextEncoder().encode(e).byteLength;if(r>16384)throw Error(`GUI file icon SVG exceeds 16 KiB`);if(!/^\s*<svg[\s>]/.test(e)||/<!|<\?/.test(e))throw Error(`Invalid GUI file icon SVG`);let i=new DOMParser().parseFromString(e,`image/svg+xml`),a=i.documentElement;if(a?.localName!==`svg`||a.namespaceURI!==q||i.querySelector(`parsererror`))throw Error(`Invalid GUI file icon SVG`);for(let e of[a,...a.querySelectorAll(`*`)]){if(e.namespaceURI!==q||!_e.has(e.localName))throw Error(`Unsupported GUI file icon SVG element`);for(let t of e.attributes){let e=t.name.toLowerCase(),n=t.value.trim();if(e.startsWith(`on`)||e===`style`||e===`xml:base`||n.includes(`\\`)||Array.from(n).some(e=>e.charCodeAt(0)<32)||(e===`href`||e.endsWith(`:href`))&&!/^#[\w.-]+$/.test(n)||/url\s*\(/i.test(n)&&!/^url\(\s*#[\w.-]+\s*\)$/.test(n))throw Error(`Unsupported GUI file icon SVG reference or attribute`)}}let o={source:e,bytes:r,uri:`data:image/svg+xml,${encodeURIComponent(e)}`};return t.set(e,o),o}var ve=class{plugins=new Map;index=new Map;listeners=new Set;subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});get(e,t){if(t?.isDirectory)return;let n=e.split(/[\\/]/).at(-1)??``,r=t?.extension??(n.includes(`.`)?n.slice(n.lastIndexOf(`.`)+1):``),i=this.index.get(J(r));return t?.themeVariant===`light`?i?.light.uri:i?.dark.uri}replace(e,t){if(t.length>64)throw Error(`GUI file icon per-plugin limit exceeded`);if(!t.length){this.remove(e);return}let n=new Map;for(let t of this.plugins.get(e)??[])for(let e of[t.dark,t.light])n.set(e.source,e);let r=new Set,i=t.map(e=>{if(!e||typeof e!=`object`||!(`id`in e)||typeof e.id!=`string`||!e.id.trim()||e.id.length>128||r.has(e.id))throw Error(`Invalid or duplicate GUI file icon id`);if(r.add(e.id),!(`extensions`in e)||!Array.isArray(e.extensions)||!e.extensions.length||e.extensions.length>64)throw Error(`GUI file icon requires 1–64 extensions`);let t=e.extensions.map(e=>{if(typeof e!=`string`)throw Error(`Invalid GUI file icon extension`);let t=J(e);if(!/^[a-z0-9][a-z0-9_+-]{0,63}$/.test(t))throw Error(`Invalid GUI file icon extension`);return t}),i=Y(`svg`in e?e.svg:void 0,n),a=`lightSvg`in e&&e.lightSvg!==void 0?Y(e.lightSvg,n):i;return{id:e.id,extensions:[...new Set(t)],dark:i,light:a}}),a=i.length,o=i.reduce((e,t)=>e+t.dark.bytes+t.light.bytes,0);for(let[t,n]of this.plugins)t!==e&&(a+=n.length,o+=n.reduce((e,t)=>e+t.dark.bytes+t.light.bytes,0));if(a>512||o>8388608)throw Error(`GUI file icon total limit exceeded`);this.plugins.set(e,i),this.publish()}remove(e){this.plugins.delete(e)&&this.publish()}dispose(){this.plugins.clear(),this.publish(),this.listeners.clear()}publish(){let e=new Map;for(let t of this.plugins.values())for(let n of t)for(let t of n.extensions)e.set(t,n);let t=e.size!==this.index.size||[...e].some(([e,t])=>{let n=this.index.get(e);return n?.dark.uri!==t.dark.uri||n?.light.uri!==t.light.uri});if(this.index=e,t)for(let e of this.listeners)e()}},X=e=>{throw Error(`Unsupported GUI host API: ${e}`)};function Z(e,t){return new Proxy(t,{get:(t,n)=>n in t?Reflect.get(t,n):X(`${e}.${String(n)}`)})}var Q=e=>Object.freeze(e.map(e=>Object.freeze(e)));function $(e,t){if(e){for(let n of e.owned??[])$(n,t);e.cleanups&&=e.cleanups.map(e=>()=>{try{Promise.resolve(e()).catch(t)}catch(e){t(e)}})}}var ye=class{options;fileIcons=new ve;instances=new Map;listeners=new Set;panelMounts=new Set;fileViews=new Map;changes=t(0);views=t(0);session=t();appearance;layouts=new Map;files;storage;ended=!1;contracts=new Map;snapshot=Object.freeze({plugins:Object.freeze([]),commands:Object.freeze([]),panels:Object.freeze([]),settings:Object.freeze([]),menuItems:Object.freeze([]),activePanel:null});screen;constructor(e){this.options=e,this.appearance=t({locale:e.locale,mode:e.mode,narrow:e.narrow}),this.storage=new he(e.storage,e.transport);let n=()=>(this.session[0](),this.files?.api??X(`screen.file without a session`));this.screen=Z(`screen`,{get file(){return n()}})}subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});getSnapshot=()=>this.snapshot;changed(){this.changes[1](e=>e+1)}setSession(e){if(this.ended)return;let t=this.session[0]();if(t?.id===e?.id&&t?.directory===e?.directory)return;if(!e)for(let e of[...this.panelMounts])e();this.files?.dispose(),this.files=e?new me(this.options.files,this.options.queryClient,this.options.transport,e.directory):void 0;let n=Z(`session.server`,{id:this.options.transport,name:this.options.transport,client:this.options.client}),r=e?Object.freeze(Z(`session`,{id:e.id,directory:e.directory,key:`${this.options.transport}\n${e.id}`,tab:e.id,server:n,pending:!1,visit:{},location:{directory:e.directory}})):void 0;this.session[1](r),this.publish()}setAppearance(e){if(this.ended)return;let t=this.appearance[0]();(t.locale!==e.locale||t.mode!==e.mode||t.narrow!==e.narrow)&&this.appearance[1]({...e})}install(r,i){let a=this.instances.get(r);if(this.ended||a?.status===`active`&&a.revision===i.revision)return;a&&(this.instances.delete(r),this.release(a));let c={id:r,revision:i.revision,controller:new AbortController,status:`active`,cleanups:new Set,contributions:new Set,iconChanges:t(0),commands:[],panels:[],settings:[],menus:[]};this.instances.set(r,c);try{let t=R(i.code);s(r=>{c.dispose=r,c.root=n(),f(()=>l(D.Provider,{value:c.context=this.context(c,t,i.options),get children(){c.owner=n();let e=o(()=>t.setup(c.context));if(typeof e==`function`)c.cleanups.add(()=>{Promise.resolve(e()).catch(e=>{c.error=String(e)})});else if(e!==void 0)throw e&&typeof e==`object`&&`then`in e&&Promise.resolve(e).catch(()=>{}),Error(`GUI setup must be synchronous and return only cleanup`);return null}}),e=>this.fail(c,e)),c.controller.signal.aborted||e(c.owner,()=>b(()=>{if(c.iconChanges[0](),!c.controller.signal.aborted)try{let e=[...c.contributions].filter(e=>e.registry===ge).map(e=>e.read()).filter(e=>e!==void 0);this.fileIcons.replace(c.id,e),c.iconError!==void 0&&o(()=>{c.iconError=void 0,this.publish()})}catch(e){o(()=>{this.fileIcons.remove(c.id),c.iconError=e instanceof Error?e.message:String(e),this.publish()})}})),c.controller.signal.aborted||e(c.owner,()=>b(()=>{this.changes[0](),this.session[0](),this.appearance[0]();try{this.derive(c)}catch(e){o(()=>this.fail(c,e))}o(()=>this.publish())}))})}catch(e){this.fail(c,e)}this.changed(),this.publish()}release(e){e.controller.abort();for(let t of[...e.cleanups])try{t()}catch(t){e.error??=String(t)}e.cleanups.clear(),$(e.root,t=>{e.error??=String(t)});try{e.dispose?.()}catch(t){e.error??=String(t)}e.contributions.clear(),e.commands=[],e.panels=[],e.settings=[],e.menus=[],this.fileIcons.remove(e.id);for(let t of this.contracts.values())t.provider===e&&(t.provider=void 0,t.live[1]({status:`inactive`,reason:e.status===`failed`?`failed`:`disabled`}))}fail(e,t){e.status!==`failed`&&this.instances.get(e.id)===e&&(e.status=`failed`,e.error=t instanceof Error?t.message:String(t),this.release(e),this.publish())}uninstall(e){let t=this.instances.get(e);if(t){this.instances.delete(e),this.release(t);for(let t of this.layouts.values())t.open=t.open.filter(t=>!t.startsWith(`${e}:`)),t.active?.startsWith(`${e}:`)&&(t.active=null);this.changed(),this.publish()}}dispose(){this.ended||(this.ended=!0,p(()=>{for(let e of[...this.instances.keys()])this.uninstall(e)}),this.files?.dispose(),this.fileIcons.dispose(),this.storage.dispose(),this.layouts.clear(),this.fileViews.clear(),this.contracts.clear(),this.listeners.clear())}own(e,t){let i=!0,a=()=>{i&&(i=!1,e.cleanups.delete(a),t())};return e.controller.signal.aborted||r(w)?.ended?(a(),a):(e.cleanups.add(a),n()&&h(a),a)}list(e){this.changes[0]();let t=[];for(let n of this.instances.values())if(n.status===`active`){for(let r of n.contributions)if(r.registry===e.id){let e=r.read();e!==void 0&&t.push(e)}}return t}context(e,t,i){let a=this.storage.forPlugin(e.id,e.controller.signal),c=Object.fromEntries(Object.entries(t.stores??{}).map(([e,t])=>[e,t.scope===`global`?a.store(e,{...t,scope:`global`}):n=>a.store(e,{...t,scope:{session:n}})])),l=(e,n)=>{let r=this.appearance[0]().locale;return(t.i18n?.[r]?.[e]??t.i18n?.[r.split(`-`)[0]]?.[e]??t.i18n?.en?.[e]??e).replace(/\{\{(\w+)\}\}/g,(e,t)=>String(n?.[t]??e))},u=Z(`layout`,{narrow:()=>this.appearance[0]().narrow,ready:()=>!!this.session[0](),open:(t,n,r)=>{e.controller.signal.aborted||this.openPanel(t,n,r)},close:(t,n)=>{e.controller.signal.aborted||this.closeFor(t,n)},toggle:(e,t)=>u.state(e,t)===`visible`?u.close(e,t):u.open(e,t),hide:(t,n)=>{if(e.controller.signal.aborted)return;let r=this.layout(n);r.active===t&&r.shown&&(r.shown=!1,this.changed())},state:(e,t)=>{this.changes[0]();let n=this.layout(t);return n.active===e?n.shown?`visible`:`active`:n.open.includes(e)?`open`:`closed`},stored:t=>(this.changes[0](),this.layout(t).open.filter(t=>t.startsWith(`${e.id}:`)).map(t=>t.slice(e.id.length+1))),side:{opened:e=>(this.changes[0](),this.layout(e).shown),toggle:t=>{if(e.controller.signal.aborted)return;let n=this.layout(t);n.shown=!n.shown,this.changed()},menu:()=>this.list(E).filter(e=>e.menu===`session.panel`).sort((e,t)=>(e.order??0)-(t.order??0))},scroll:{get:(e,t)=>(this.changes[0](),this.layout(e).scroll.get(t)),set:(t,n,r)=>{if(e.controller.signal.aborted)return;let i=this.layout(t).scroll;if(!i.has(n)&&i.size>=128)throw Error(`GUI layout scroll limit exceeded`);i.set(n,{...r}),this.changed()}}});return Z(`ctx`,{id:e.id,options:i,signal:e.controller.signal,client:this.options.client,storage:a,stores:c,app:{name:`yuri`,version:``,channel:`local`,platform:`web`,packaged:!1},desktop:void 0,t:l,plural:(e,t,n)=>{let r=`${e}.${new Intl.PluralRules(this.appearance[0]().locale).select(t)}`;return l(r,{...n,count:t})===r?l(`${e}.other`,{...n,count:t}):l(r,{...n,count:t})},add:(t,i)=>{if(e.controller.signal.aborted||r(w)?.ended)return()=>{};if([`server`,`titlebar-item`,`composer-pill`,`slot`,`file.viewer`,`menubar-item`].includes(t.id)&&X(`registry.${t.id}`),e.contributions.size>=256)throw Error(`GUI contribution limit exceeded`);let a=()=>{},c,l=s(e=>{a=e,c=n();let r=()=>typeof i==`function`?i():i,o;if(t.id===`yuri.file-icon`){let e=d(()=>{try{return{ok:!0,value:r()}}catch(e){return{ok:!1,error:e}}});o=()=>{let t=e();if(!t.ok)throw t.error;return t.value}}else o=d(r);if(t.id===`style`){let e=document.createElement(`style`);document.head.append(e),h(()=>e.remove()),b(()=>{let t=o();e.textContent=t===void 0?``:String(t)})}return{registry:t.id,read:o}},n()??e.owner);e.contributions.add(l);let u=()=>{t.id===`yuri.file-icon`&&e.iconChanges[1](e=>e+1)};return o(u),o(()=>this.changed()),this.own(e,()=>{$(c,t=>{e.error??=String(t)}),a(),e.contributions.delete(l),o(u),o(()=>this.changed())})},list:e=>this.list(e),provide:(t,n)=>{if(e.controller.signal.aborted||r(w)?.ended)return()=>{};if(t.kind!==`contract`||!(t.id===e.id||t.id.startsWith(`${e.id}.`)))throw Error(`Contract must belong to the providing plugin`);let i=this.contract(t.id);if(i.provider)throw Error(`Contract already provided: ${t.id}`);return i.provider=e,i.live[1]({status:`active`,value:n,generation:++i.generation}),this.own(e,()=>{i.provider===e&&(i.provider=void 0,i.live[1]({status:`inactive`,reason:e.status===`failed`?`failed`:`disabled`}))})},use:e=>this.contract(e.id,e.kind===`ipc`).live[0],main:t=>{if(!(t.id===e.id||t.id.startsWith(`${e.id}.`)))throw Error(`IPC must belong to the plugin`);return new Proxy({state:()=>void 0},{get:(e,t)=>t===`state`?e.state:t===`on`?()=>X(`native IPC events`):()=>Promise.reject(Error(`Unsupported GUI host API: native IPC`))})},sessions:{current:this.session[0],list:()=>{let e=this.session[0]();return e?[e]:[]}},screen:{current:()=>this.session[0]()?this.screen:void 0},layout:u,appearance:{mode:()=>this.appearance[0]().mode,font:()=>getComputedStyle(document.documentElement).getPropertyValue(`--font-mono`).trim()||`monospace`},locale:{locale:()=>this.appearance[0]().locale,direction:()=>/^(ar|fa|he|ur)(-|$)/i.test(this.appearance[0]().locale)?`rtl`:`ltr`},system:{copy:e=>navigator.clipboard.writeText(e),openExternal:e=>{let t=new URL(e);[`https:`,`http:`,`mailto:`].includes(t.protocol)||X(`system.openExternal protocol`),window.open(e,`_blank`,`noopener,noreferrer`)},save:async e=>{let t=URL.createObjectURL(new Blob([e.content],{type:`text/plain`}));try{let n=document.createElement(`a`);return n.href=t,n.download=e.name,n.click(),!0}finally{setTimeout(()=>URL.revokeObjectURL(t),0)}}},commands:{run:t=>e.controller.signal.aborted||!this.command(t)?!1:(this.runCommand(t),!0)},links:{open:t=>!e.controller.signal.aborted&&this.navigateLink(e,t),exists:t=>o(()=>{if(e.controller.signal.aborted)return!1;let n=this.linkHandler(t);try{return Promise.resolve(n?.value.exists?.(t)??!1).catch(()=>!1)}catch{return!1}})}})}contract(e,n=!1){let r=this.contracts.get(e);if(!r){if(this.contracts.size>=256)throw Error(`GUI contract limit exceeded`);let n=t({status:`inactive`,reason:`disabled`});r={live:[le(n[0]),n[1]],generation:0},this.contracts.set(e,r)}return n&&r.provider&&X(`IPC contract collision`),r}derive(e){if(e.status!==`active`)return;let t=[],n=[],r=[],i=[],a=this.session[0]();for(let o of e.contributions){if(o.registry===`yuri.file-icon`)continue;let s=o.read();if(s!==void 0){if(o.registry===pe.id){let n=s;n.enabled!==!1&&t.push({key:`${e.id}.${n.id}`,title:n.title,description:n.description,bind:n.bind,hidden:n.hidden,run:()=>this.invoke(e,()=>n.run())})}else if(o.registry===A.id&&a){let t=s,r=`${e.id}:`,i=this.layout(a).open.filter(e=>e.startsWith(r)).map(e=>e.slice(r.length));for(let r of t.list({session:a,screen:this.screen,open:i}))n.push({plugin:e,panel:t,tab:r})}else if(o.registry===C.id){let e=s;(e.page||e.section)&&X(`SettingsPage host sections`),e.title,r.push(e)}else if(o.registry===E.id){let e=s;e.menu===`session.panel`?(e.title,i.push(e)):X(`MenuItem.${e.menu}`)}}}for(let e of n)e.tab.title;e.commands=t,e.panels=n,e.settings=r,e.menus=i,o(()=>this.views[1](e=>e+1))}publish(){let e=o(this.session[0]),t=e?this.layouts.get(e.key):void 0,n=[...this.instances.values()],r=n.filter(e=>e.status===`active`),i=r.flatMap(e=>e.panels.map(({tab:n})=>{let r=n.file?this.filePath(n.file):void 0;return{key:`${e.id}:${n.id}`,pluginId:e.id,title:n.title,file:r,inline:!!(r&&this.fileViews.has(r)),active:t?.shown===!0&&t.active===`${e.id}:${n.id}`}}));this.snapshot=Object.freeze({plugins:Q(n.map(({id:e,revision:t,status:n,error:r,iconError:i})=>({id:e,revision:t,status:n,error:r??i}))),commands:Q(r.flatMap(e=>e.commands.filter(e=>!e.hidden))),panels:Q(i),settings:Q(r.flatMap(e=>e.settings.map(t=>({key:`${e.id}:${t.id}`,pluginId:e.id,title:t.title})))),menuItems:Q(r.flatMap(e=>e.menus.map(t=>({key:`${e.id}:${t.id}`,title:t.title,description:t.description,run:()=>{this.invoke(e,()=>t.run())}})))),activePanel:t?.shown&&i.some(e=>e.key===t.active)?t.active:null,sessionKey:e?.key});for(let e of this.listeners)e()}invoke(t,n){if(!t.controller.signal.aborted)try{let r=e(t.owner??null,n);if(r instanceof Promise)return r.catch(e=>this.fail(t,e))}catch(e){this.fail(t,e)}}command(e){return[...this.instances.values()].flatMap(e=>e.commands).find(t=>t.key===e)}runCommand(e){return this.command(e)?.run()}linkHandler(e){let t=[];for(let e of this.instances.values())for(let n of e.contributions)if(n.registry===ce.id){let r=n.read();r&&t.push({instance:e,value:r})}for(let n of t.sort((e,t)=>(t.value.priority??0)-(e.value.priority??0)))try{if(n.value.match(e))return n}catch(e){this.fail(n.instance,e)}}navigateLink(e,t){if(this.ended)return!1;let n=ie(t.href);if(!n||!re(n.path))return this.openLink(t);let r=this.session[0]();if(!r||t.session&&(t.session.key!==r.key||t.session.server.id!==r.server.id))return!1;if(!this.options.focusFile)return this.openLink(t);let i=te(t.base??r.directory,n.path),a=n.line===void 0?``:`:${n.line}${n.column===void 0?``:`:${n.column}`}`;return this.invoke(e,()=>this.options.focusFile(i+a,r.directory)),!0}openLink(e){if(this.ended)return!1;let t={...e,session:e.session??this.session[0]()},n=this.linkHandler(t);return n?(this.invoke(n.instance,()=>n.value.open(t)),!0):!1}filePath(e,t=this.session[0]()?.directory){let n=z(e);return/^(?:\/|[a-z]:\/)/i.test(n)||!t?n:z(`${t}/${n}`)}registerFileView(e,t){if(this.ended)return()=>{};let n=this.filePath(e,t),r=this.fileViews.get(n)??0;this.fileViews.set(n,r+1),r===0&&(this.changed(),this.publish());let i=!1;return()=>{if(i||this.ended)return;i=!0;let e=(this.fileViews.get(n)??1)-1;if(e){this.fileViews.set(n,e);return}{let e=this.session[0](),t=e&&this.layouts.get(e.key);t?.active&&this.snapshot.panels.some(e=>e.key===t.active&&e.file===n)&&(t.shown=!1),this.fileViews.delete(n)}this.changed(),this.publish()}}filePanel(e,t){let n=this.filePath(e,t);return this.snapshot.panels.find(e=>e.file===n&&e.inline)}panelVisible(e){let t=this.session[0]();if(!t)return!1;let n=this.panel(e)?.tab.file;if(n&&this.fileViews.has(this.filePath(n)))return!0;let r=this.layouts.get(t.key);return!!(r?.shown&&r.active===e)}layout(e){let t=this.layouts.get(e.key);if(!t){if(this.layouts.size>=128)throw Error(`GUI session layout limit exceeded`);t={open:[],active:null,shown:!1,scroll:new Map},this.layouts.set(e.key,t)}return t}openPanel(e,t,n){if(this.ended)return;let r=this.layout(t),i=r.active,a=r.shown,o=r.open.length;if(!r.open.includes(e)){if(r.open.length>=64)throw Error(`GUI panel tab limit exceeded`);r.open=[...r.open,e]}n?.tab!==`append`&&(r.active=e,r.shown=!(this.appearance[0]().narrow&&n?.background)),(i!==r.active||a!==r.shown||o!==r.open.length)&&(this.changed(),this.publish());let s=this.panel(e);t.key===this.session[0]()?.key&&s&&n?.tab!==`append`&&this.invoke(s.plugin,()=>s.panel.focus?.({...this.props(e),restored:!1}))}selectPanel(e){let t=this.session[0]();t&&this.openPanel(e,t)}closeFor(e,t){let n=this.layout(t),r=t.key===this.session[0]()?.key?this.panel(e):void 0;if(!n.open.includes(e)||r?.tab.pinned||r?.tab.closable===!1)return;let i=this.session[0](),a=r&&i?{tab:r.tab,session:i,screen:this.screen}:void 0;n.open=n.open.filter(t=>t!==e),n.active===e&&(n.active=n.open.at(-1)??null),this.changed(),this.publish(),r&&a&&this.invoke(r.plugin,()=>r.panel.close?.(a))}closePanel(e){let t=this.session[0]();t&&this.closeFor(e,t)}hidePanel(){let e=this.session[0]();if(!e)return;let t=this.layout(e);t.shown&&(t.shown=!1,this.changed(),this.publish())}panel(e){return[...this.instances.values()].flatMap(e=>e.panels).find(t=>`${t.plugin.id}:${t.tab.id}`===e)}props(e){let t=this.panel(e)?.tab,n=()=>(this.views[0](),this.panel(e)?.tab??t??X(`panel no longer listed`)),r=()=>this.session[0]()??X(`panel without session`);return{get tab(){return n()},get session(){return r()},screen:this.screen}}mountPanel(e,t){let n=this.panel(e);if(!n)return()=>{};let r=()=>{let t=d(()=>{this.session[0](),this.changes[0](),this.views[0]();let t=this.panel(e)?.tab.file;return t&&this.files&&this.panelVisible(e)?{model:this.files,file:t}:void 0},void 0,{equals:(e,t)=>e?.model===t?.model&&e?.file===t?.file});return b(()=>{let e=t();e&&(h(e.model.watch(e.file)),e.model.sync(e.file).catch(()=>{}))}),o(()=>n.panel.render(this.props(e)))},i=this.mount(n.plugin,t,()=>l(de.Provider,{value:{visible:()=>(this.changes[0](),this.panelVisible(e)),present:()=>(this.changes[0](),this.panelVisible(e)),placement:()=>this.appearance[0]().narrow?`mobile`:`side`,reserve:()=>!1,animate:()=>!1,sidebar:Z(`panel.sidebar`,{}),open:()=>{let e=this.session[0]();return e?n.plugin.context.layout.stored(e):[]}},get children(){return r()}})),a=()=>{this.panelMounts.delete(a),i()};return this.panelMounts.add(a),this.own(n.plugin,a)}mountSettings(e,t){for(let n of this.instances.values()){let r=n.settings.find(t=>`${n.id}:${t.id}`===e);if(r)return this.mount(n,t,()=>r.render({}))}return()=>{}}mount(e,t,r){if(e.controller.signal.aborted)return()=>{};let i=()=>{},a,s=t=>{queueMicrotask(()=>this.fail(e,t))};try{i=oe(()=>l(D.Provider,{value:e.context,get children(){return a=n(),f(()=>o(r),s)}}),t)}catch(t){this.fail(e,t)}return this.own(e,()=>{$(a,t=>{e.error??=String(t)}),i(),t.replaceChildren()})}};export{ye as GuiPluginHost};