@openchambery/web 2.1.10-beta.8 → 2.1.10

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 (147) hide show
  1. package/dist/assets/{AgentAvatar-CSTBp5FT.js → AgentAvatar-VWQTTR4M.js} +1 -1
  2. package/dist/assets/AssistantView-pFHs1mFy.js +3 -0
  3. package/dist/assets/DiagramView-DvtLUBju.js +1 -0
  4. package/dist/assets/{FadeInOnReveal-C-zbv53H.js → FadeInOnReveal-fsguD-xX.js} +1 -1
  5. package/dist/assets/Icon-CEQUcqTJ.js +1 -0
  6. package/dist/assets/{ImageLoadingPlaceholder-CN33uB-A.js → ImageLoadingPlaceholder-Bel8eqgg.js} +1 -1
  7. package/dist/assets/{LoadingImage-BR82n0vB.js → LoadingImage-DjkSZxMq.js} +1 -1
  8. package/dist/assets/MarkdownRenderer-DMk_HgEW.js +2 -0
  9. package/dist/assets/MarkdownRendererImpl-BD3MLIXK.js +10 -0
  10. package/dist/assets/MarkstreamRendererImpl-Bmq_rlW8.js +3 -0
  11. package/dist/assets/MobileDetailNavigation-BEKXW98F.js +1 -0
  12. package/dist/assets/MobileShareBridge-7uwkwoDd.js +4 -0
  13. package/dist/assets/MobileTabPageHeader-Bv5dbFRY.js +2 -0
  14. package/dist/assets/{MultiRunWindow-Dl6X54iv.js → MultiRunWindow-YPpInxnV.js} +1 -1
  15. package/dist/assets/OnboardingScreen-CQuSd1SL.js +1 -0
  16. package/dist/assets/{OverlayScrollbar-BY5HaNrb.js → OverlayScrollbar-DI271QYq.js} +1 -1
  17. package/dist/assets/{SettingsView-DJZEQaSF.js → SettingsView-rMvVrvoc.js} +11 -11
  18. package/dist/assets/{SettingsWindow-TvlhBd6w.js → SettingsWindow-Bu0pJmO4.js} +1 -1
  19. package/dist/assets/TerminalView-B7wbbWmJ.js +8 -0
  20. package/dist/assets/ToolOutputDialog-C7usOU7_.css +1 -0
  21. package/dist/assets/ToolOutputDialog-kGRZ3zBv.js +10 -0
  22. package/dist/assets/{appThemeRegistry-Du5KFmTd.js → appThemeRegistry-COjSA5s9.js} +1 -1
  23. package/dist/assets/assistant-attachment-cache-BWe8KqRS.js +1 -0
  24. package/dist/assets/{button-CWSs9Baz.js → button-9V3jJ3gG.js} +1 -1
  25. package/dist/assets/{collapsible-ngtoKADo.js → collapsible-Cx3lMy_W.js} +1 -1
  26. package/dist/assets/{desktopHosts-C0e7Nes2.js → desktopHosts-C4ejHJ9p.js} +1 -1
  27. package/dist/assets/desktopRelayRestore-UTCV51RC.js +1 -0
  28. package/dist/assets/{diagram-DmlTCkmV.js → diagram-Bpt5dSrL.js} +1 -1
  29. package/dist/assets/{dialog-BMa16qrs.js → dialog-Yxau54Tq.js} +1 -1
  30. package/dist/assets/dropdown-menu.styles-CtzReuqO.js +1 -0
  31. package/dist/assets/{es-ChfgOskU.js → es-DsJ_HQyU.js} +1 -1
  32. package/dist/assets/{fileMentionTouchSelection-DZvVbBP-.js → fileMentionTouchSelection-Hibjg1ml.js} +1 -1
  33. package/dist/assets/{fr-DnKqN4E3.js → fr-Dfkjku77.js} +1 -1
  34. package/dist/assets/{gitApi-DdM2FGUu.js → gitApi-HQKLs8JU.js} +3 -3
  35. package/dist/assets/image-loading-ClZBSNMo.js +1 -0
  36. package/dist/assets/{input-CALwaZEB.js → input-BqE6rFfR.js} +1 -1
  37. package/dist/assets/insertionBoundaries-I_znkRIX.js +1 -0
  38. package/dist/assets/{ja-DH-a_ThB.js → ja-C71g0jYh.js} +1 -1
  39. package/dist/assets/{ko-BXABOKd9.js → ko-32s8rv0M.js} +1 -1
  40. package/dist/assets/main-BwNzKZuT.js +169 -0
  41. package/dist/assets/main-DfS2IaSq.js +2 -0
  42. package/dist/assets/{markdownHeightCache-DXM_5jTe.js → markdownHeightCache-lTJfaoDe.js} +1 -1
  43. package/dist/assets/mcpQueries-MXNO55dw.js +1 -0
  44. package/dist/assets/miniChat-CMt8PqCU.js +2 -0
  45. package/dist/assets/mobile-BaUwTAK3.js +2 -0
  46. package/dist/assets/{mobileBackNavigation-DYaEgNKl.js → mobileBackNavigation-DgrGA2Qw.js} +1 -1
  47. package/dist/assets/multirun-DN46tuiy.js +3 -0
  48. package/dist/assets/persistence-CAKBi4bp.js +3 -0
  49. package/dist/assets/{pl-D-KNROrB.js → pl-eAbyJFO9.js} +1 -1
  50. package/dist/assets/platform-C5jNCIbB.js +7 -0
  51. package/dist/assets/projectMeta-BV2S2dYM.js +1 -0
  52. package/dist/assets/{pt-BR-UDs5YUzv.js → pt-BR-nVxduPt0.js} +1 -1
  53. package/dist/assets/queryRuntime-DRiRiAgZ.js +1 -0
  54. package/dist/assets/renderElectronMiniChatApp-BOMvMWpo.js +2 -0
  55. package/dist/assets/renderMobileApp-BGP-Q03v.css +1 -0
  56. package/dist/assets/renderMobileApp-DX0VWU7B.js +28 -0
  57. package/dist/assets/runtime-file-download-CEzr1Pfg.js +1 -0
  58. package/dist/assets/runtime-file-resource-BUFMRmIF.js +2 -0
  59. package/dist/assets/runtimeConfig-BTc8J1kY.js +2 -0
  60. package/dist/assets/runtimeEndpointReset-BiSu_pxJ.js +149 -0
  61. package/dist/assets/{scheduledTaskNavigation-DQcLqQ52.js → scheduledTaskNavigation-j6F6n0ym.js} +1 -1
  62. package/dist/assets/sessionChangeSummary-Bz22Q8e1.js +1 -0
  63. package/dist/assets/{sessionLookup-Dayma9hk.js → sessionLookup-5rpUSv3O.js} +1 -1
  64. package/dist/assets/{sortable-tabs-strip-CscHgCaq.js → sortable-tabs-strip-DFi-Mck5.js} +1 -1
  65. package/dist/assets/speechSettingsQueries-C8efV361.js +4 -0
  66. package/dist/assets/src-DzBIReeh.css +2 -0
  67. package/dist/assets/{store-CG7Ytsg9.js → store-D4rR0svj.js} +2 -2
  68. package/dist/assets/terminalApi-B8arordk.js +1 -0
  69. package/dist/assets/{textarea-CAOC2ViF.js → textarea-DoWm-pRV.js} +1 -1
  70. package/dist/assets/{tooltip-CV6dvLBp.js → tooltip-DWlA7PRY.js} +1 -1
  71. package/dist/assets/{uk-CkliYeRs.js → uk-DOvCFanR.js} +1 -1
  72. package/dist/assets/{url-nBOUbtV_.js → url-BD7mCWgV.js} +1 -1
  73. package/dist/assets/{useAppFontEffects-Cf-BIyAh.js → useAppFontEffects-DAI7VfQG.js} +51 -51
  74. package/dist/assets/{useDesktopWindowControlsLayout-BgLopOdv.js → useDesktopWindowControlsLayout-BjvIMnxi.js} +1 -1
  75. package/dist/assets/{useEffectiveDirectory-BljJHzlP.js → useEffectiveDirectory-CuXlnig5.js} +1 -1
  76. package/dist/assets/{useFontPreferences-DqEIKMEW.js → useFontPreferences-Ctm4A_2D.js} +1 -1
  77. package/dist/assets/useMobileNavigationStore-D47T6Oi2.js +417 -0
  78. package/dist/assets/{useWorkerHighlightedLines-r5Bij0Em.js → useWorkerHighlightedLines-m2onDaI2.js} +1 -1
  79. package/dist/assets/{zh-CN-BH4APVTu.js → zh-CN-CuYFLeS4.js} +2 -2
  80. package/dist/assets/{zh-TW-BEi6Yf50.js → zh-TW-DKJIyd5A.js} +2 -2
  81. package/dist/index.html +13 -10
  82. package/dist/mini-chat.html +13 -10
  83. package/dist/mobile.html +13 -10
  84. package/package.json +1 -1
  85. package/server/lib/content-search/DOCUMENTATION.md +5 -1
  86. package/server/lib/content-search/runtime.test.js +6 -2
  87. package/server/lib/content-search/service.js +7 -2
  88. package/server/lib/content-search/service.test.js +20 -0
  89. package/server/lib/fs/DOCUMENTATION.md +4 -1
  90. package/server/lib/fs/image-fingerprint.d.ts +2 -0
  91. package/server/lib/fs/image-fingerprint.js +43 -0
  92. package/server/lib/fs/image-fingerprint.test.js +54 -0
  93. package/server/lib/fs/raw-video.test.js +34 -0
  94. package/server/lib/fs/routes.js +16 -6
  95. package/server/lib/opencode/proxy.js +2 -1
  96. package/server/lib/opencode/proxy.test.js +13 -0
  97. package/server/lib/quota/DOCUMENTATION.md +2 -0
  98. package/server/lib/quota/magpie.js +3 -0
  99. package/server/lib/quota/magpie.test.js +14 -0
  100. package/server/lib/relay/relay-server.e2e.test.ts +8 -0
  101. package/server/lib/session-turn-pages/DOCUMENTATION.md +8 -0
  102. package/server/lib/session-turn-pages/native-payload.d.ts +2 -0
  103. package/server/lib/session-turn-pages/native-payload.js +38 -0
  104. package/server/lib/session-turn-pages/native-payload.test.js +34 -0
  105. package/server/lib/session-turn-pages/routes.js +2 -1
  106. package/server/lib/session-turn-pages/routes.test.js +18 -0
  107. package/dist/assets/AssistantView-sg_gJwXp.js +0 -3
  108. package/dist/assets/DiagramView-BW-3spOQ.js +0 -1
  109. package/dist/assets/Icon-BCFeHDWx.js +0 -1
  110. package/dist/assets/MarkdownRenderer-LEXHIyuj.js +0 -2
  111. package/dist/assets/MarkdownRendererImpl-Xs4gJB0s.js +0 -10
  112. package/dist/assets/MarkstreamRendererImpl-RXTIFS1c.js +0 -3
  113. package/dist/assets/MobileDetailNavigation-Bx1Vbirv.js +0 -1
  114. package/dist/assets/MobileShareBridge-DKsBX4J6.js +0 -4
  115. package/dist/assets/MobileTabPageHeader-BIbvqv8n.js +0 -2
  116. package/dist/assets/OnboardingScreen-CqcZEptL.js +0 -1
  117. package/dist/assets/TerminalView-By3D_hLv.js +0 -8
  118. package/dist/assets/ToolOutputDialog-DesCcdFD.css +0 -1
  119. package/dist/assets/ToolOutputDialog-Dt49fiUz.js +0 -10
  120. package/dist/assets/assistant-attachment-cache-CecNXB7z.js +0 -1
  121. package/dist/assets/desktopRelayRestore-DckkHKsi.js +0 -1
  122. package/dist/assets/dropdown-menu.styles-BNwZmBRp.js +0 -1
  123. package/dist/assets/fileQueries-DVpZC5ha.js +0 -1
  124. package/dist/assets/image-loading-DImQz00b.js +0 -1
  125. package/dist/assets/insertionBoundaries-D5hR7Bnk.js +0 -1
  126. package/dist/assets/main-C4f3ftkw.js +0 -2
  127. package/dist/assets/main-M6NuXmS9.js +0 -169
  128. package/dist/assets/mcpQueries-BJQRGKlF.js +0 -1
  129. package/dist/assets/miniChat-haVuHJtE.js +0 -2
  130. package/dist/assets/mobile-AgEB6KUi.js +0 -2
  131. package/dist/assets/multirun-CLywRk_h.js +0 -3
  132. package/dist/assets/persistence-BKszKaoQ.js +0 -3
  133. package/dist/assets/platform-CgwxwfA4.js +0 -7
  134. package/dist/assets/projectMeta-CmY-ALGU.js +0 -1
  135. package/dist/assets/relay-image-stream-CqgxIcA5.js +0 -2
  136. package/dist/assets/renderElectronMiniChatApp-G3oei-lb.js +0 -2
  137. package/dist/assets/renderMobileApp-CLKJYLRa.js +0 -28
  138. package/dist/assets/runtime-fetch-WgH0pROs.js +0 -1
  139. package/dist/assets/runtimeConfig-wXAjg8Wj.js +0 -2
  140. package/dist/assets/runtimeEndpointReset-BcpbVtkr.js +0 -149
  141. package/dist/assets/sessionChangeSummary-DIIJkyzk.js +0 -1
  142. package/dist/assets/speechSettingsQueries-F67f52-o.js +0 -4
  143. package/dist/assets/src-azLZheh6.css +0 -2
  144. package/dist/assets/terminalApi-rxsMWL0o.js +0 -1
  145. package/dist/assets/useMobileNavigationStore-Bc3q1mPg.js +0 -417
  146. package/dist/assets/useRuntimeAPIs-Cx8S1HLz.js +0 -1
  147. package/dist/assets/vendor-legendapp-list-CNxU_ALy.js +0 -1
@@ -1,10 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{c as t,i as n}from"./runtime-switch-CMiMO5Yj.js";import{n as r}from"./runtime-fetch-WgH0pROs.js";import{Mn as i,ln as a}from"./persistence-BKszKaoQ.js";import{it as o,nt as s,rt as c}from"./vendor-base-ui-CdzJ6My_.js";import{n as l}from"./platform-CgwxwfA4.js";import{_ as u}from"./useUIStore-CEqU9Ujv.js";import{n as d}from"./vendor-react-BP2cRVqX.js";import{a as f,n as p}from"./vendor-aparajita-capacitor-secure-storage-xol_6BsB.js";import{s as m}from"./vendor-tanstack-react-query-CdqCAt40.js";import{a as h,i as g}from"./vendor-pierre-diffs-DPBtNDJ5.js";import{n as _}from"./vendor-reactuses-core-BpfIZ1tg.js";import{f as v,r as y,t as b}from"./button-CWSs9Baz.js";import{n as x,t as S}from"./useThemeSystem-8jhE4Zyk.js";import{n as C}from"./Icon-BCFeHDWx.js";import{n as w,t as T}from"./dialog-BMa16qrs.js";import{i as E,l as D,o as O,s as k,v as A}from"./image-loading-DImQz00b.js";import{t as j}from"./MobileWindowStack-DGLdgoGr.js";import{t as M}from"./appThemeRegistry-Du5KFmTd.js";import{n as N,o as P}from"./MarkdownRenderer-LEXHIyuj.js";import{l as ee}from"./markdown-worker-DFNZ3KJ_.js";import{n as te}from"./useEffectiveDirectory-BljJHzlP.js";import{r as ne}from"./relay-image-stream-CqgxIcA5.js";import{t as F}from"./ImageLoadingPlaceholder-CN33uB-A.js";import{d as I,f as L,g as R,h as z,l as B,m as V,n as H,p as U,r as re,s as W,t as ie,u as ae}from"./useWorkerHighlightedLines-r5Bij0Em.js";import{t as G}from"./vendor-tanstack-react-virtual-B_EO--9t.js";import{n as oe}from"./markdownTheme-BUfvCGAn.js";import{n as K}from"./mobileBackNavigation-DYaEgNKl.js";var q=d(),J=e(o(),1),Y=c(),X=80,Z=20,se=J.memo(e=>{let t=(0,q.c)(26),{lines:n,language:r,maxHeight:i,showLineNumbers:a,lineStyles:o}=e,s=i===void 0?`60vh`:i,c=a===void 0||a,{currentTheme:l}=x(),u;t[0]===l?u=t[1]:(u=oe(l),t[0]=l,t[1]=u);let d=u,f;t[2]===n?f=t[3]:(f=n.map(ue).join(`
2
- `),t[2]=n,t[3]=f);let p=ie(f,r);if(!(n.length>X)){let e=d,r;t[4]!==s||t[5]!==e?(r={...e,maxHeight:s,overflow:`auto`},t[4]=s,t[5]=e,t[6]=r):r=t[6];let i;if(t[7]!==p||t[8]!==o||t[9]!==n||t[10]!==c){let e;t[12]!==p||t[13]!==o||t[14]!==c?(e=(e,t)=>(0,Y.jsx)(le,{line:e,html:p?.[t],showLineNumbers:c,style:o?.(e)},t),t[12]=p,t[13]=o,t[14]=c,t[15]=e):e=t[15],i=n.map(e),t[7]=p,t[8]=o,t[9]=n,t[10]=c,t[11]=i}else i=t[11];let a;return t[16]!==r||t[17]!==i?(a=(0,Y.jsx)(`div`,{className:`typography-code font-mono w-full min-w-0`,style:r,children:i}),t[16]=r,t[17]=i,t[18]=a):a=t[18],a}let m;return t[19]!==p||t[20]!==o||t[21]!==n||t[22]!==s||t[23]!==c||t[24]!==d?(m=(0,Y.jsx)(ce,{lines:n,highlighted:p,syntaxVars:d,maxHeight:s,showLineNumbers:c,lineStyles:o}),t[19]=p,t[20]=o,t[21]=n,t[22]=s,t[23]=c,t[24]=d,t[25]=m):m=t[25],m});se.displayName=`VirtualizedCodeBlock`;var ce=J.memo(({lines:e,highlighted:t,syntaxVars:n,maxHeight:r,showLineNumbers:i,lineStyles:a})=>{let o=J.useRef(null),s=`min(${e.length*Z}px, ${r})`,c=G({count:e.length,getScrollElement:()=>o.current,estimateSize:()=>Z,overscan:20}),l=c.getVirtualItems();return(0,Y.jsx)(`div`,{ref:o,className:`typography-code font-mono w-full min-w-0`,style:{...n,height:s,maxHeight:r,overflow:`auto`},children:(0,Y.jsx)(`div`,{style:{height:c.getTotalSize(),position:`relative`},children:l.map(n=>{let r=e[n.index];return r?(0,Y.jsx)(`div`,{"data-index":n.index,ref:c.measureElement,style:{position:`absolute`,top:0,left:0,width:`100%`,transform:`translateY(${n.start}px)`},children:(0,Y.jsx)(le,{line:r,html:t?.[n.index],showLineNumbers:i,style:a?.(r)})},n.index):null})})})});ce.displayName=`VirtualizedRows`;var le=J.memo(e=>{let t=(0,q.c)(12),{line:n,html:r,showLineNumbers:i,style:a}=e,o;t[0]!==n.isInfo||t[1]!==n.lineNumber||t[2]!==i?(o=i&&(0,Y.jsx)(`span`,{className:`w-10 flex-shrink-0 text-right pr-3 select-none border-r mr-3 -my-0.5 py-0.5`,style:{color:`var(--tools-edit-line-number)`,borderColor:`var(--tools-border)`},children:!n.isInfo&&n.lineNumber!=null?n.lineNumber:``}),t[0]=n.isInfo,t[1]=n.lineNumber,t[2]=i,t[3]=o):o=t[3];let s;t[4]!==r||t[5]!==n.isInfo||t[6]!==n.text?(s=(0,Y.jsx)(`div`,{className:`flex-1 min-w-0`,children:n.isInfo?(0,Y.jsx)(`div`,{className:`whitespace-pre-wrap break-words text-muted-foreground/70 italic`,children:n.text}):r===void 0?(0,Y.jsx)(`div`,{className:`whitespace-pre`,children:n.text}):(0,Y.jsx)(`div`,{className:`whitespace-pre`,dangerouslySetInnerHTML:{__html:r}})}),t[4]=r,t[5]=n.isInfo,t[6]=n.text,t[7]=s):s=t[7];let c;return t[8]!==a||t[9]!==o||t[10]!==s?(c=(0,Y.jsxs)(`div`,{className:`typography-code font-mono flex w-full min-w-0`,style:a,children:[o,s]}),t[8]=a,t[9]=o,t[10]=s,t[11]=c):c=t[11],c});le.displayName=`VirtualizedCodeBlock.Row`;function ue(e){return e.text}var de=J.memo(function({jsonString:e,className:t,maxHeight:n=`100%`,initiallyExpandedDepth:r=2}){let{t:i}=v(),a=J.useRef(null),[o,s]=J.useState(null),c=J.useMemo(()=>{try{let t=e.trim();if(!t)return s(i(`jsonTreeView.error.emptyJson`)),null;let n=JSON.parse(t);return s(null),n}catch(e){return s(e instanceof Error?e.message:i(`jsonTreeView.error.invalidJson`)),null}},[e,i]),l=J.useCallback(()=>{a.current?.expandAll()},[]),u=J.useCallback(()=>{a.current?.collapseAll()},[]);return o?(0,Y.jsx)(`div`,{className:t,children:(0,Y.jsxs)(`div`,{className:`rounded-md border border-[var(--interactive-border)] bg-[var(--syntax-base-background)] p-4`,children:[(0,Y.jsx)(`div`,{className:`mb-1 font-medium text-[var(--surface-foreground)]`,children:i(`jsonTreeView.error.invalidJsonTitle`)}),(0,Y.jsx)(`div`,{className:`font-mono text-xs text-[var(--surface-mutedForeground)]`,children:o})]})}):c===null?null:(0,Y.jsxs)(`div`,{className:t,children:[(0,Y.jsxs)(`div`,{className:`flex items-center gap-1 border-b border-[var(--interactive-border)] px-2 py-1`,children:[(0,Y.jsxs)(b,{variant:`ghost`,size:`xs`,onClick:l,className:`gap-1 text-xs text-muted-foreground`,children:[(0,Y.jsx)(C,{name:`arrow-down-s`,className:`h-3 w-3`}),i(`jsonTreeView.actions.expandAll`)]}),(0,Y.jsxs)(b,{variant:`ghost`,size:`xs`,onClick:u,className:`gap-1 text-xs text-muted-foreground`,children:[(0,Y.jsx)(C,{name:`arrow-up-s`,className:`h-3 w-3`}),i(`jsonTreeView.actions.collapseAll`)]})]}),(0,Y.jsx)(`div`,{className:`bg-[var(--syntax-base-background)] py-1`,style:{maxHeight:n,overflow:`auto`},children:(0,Y.jsx)(re,{ref:a,data:c,maxHeight:n,initiallyExpandedDepth:r})})]})}),fe=class extends Error{key;params;constructor(e,t){super(e),this.name=`MermaidLoadFailure`,this.key=e,this.params=t}},pe=(e,t)=>new fe(e,t),me=e=>e instanceof fe,he=e=>e+1,ge=(e,t)=>e===t,Q=e=>{let t=e.indexOf(`,`);if(t<0)throw pe(`chat.toolOutputDialog.mermaid.dataUrlMalformed`);let n=e.slice(0,t).toLowerCase(),r=e.slice(t+1);return n.includes(`;base64`)?atob(r):decodeURIComponent(r)},_e=e=>Promise.resolve().then(()=>Q(e)),ve=1,ye=56,be=(e,t,n)=>Math.min(n,Math.max(t,e)),xe=({isMobile:e,pointerType:t,cancelled:n,moved:r,suppressTap:i,targetWasCanvas:a,start:o,end:s,startScale:c,hasMultipleImages:l})=>{if(n||i)return`none`;let u={x:s.x-o.x,y:s.y-o.y},d=Math.hypot(u.x,u.y),f=t!==`mouse`;if(e&&f&&c<=1.01&&Math.abs(u.x)>=ye&&Math.abs(u.x)>Math.abs(u.y)*1.2)return l?u.x<0?`next`:`previous`:`none`;let p=!r&&d<=10;return e&&f&&p||!e&&t===`mouse`&&p&&a?`close`:`none`},Se=(e,t)=>{if(e.width<=0||e.height<=0||t.width<=0||t.height<=0)return{width:1,height:1};let n=Math.min(t.width/e.width,t.height/e.height);return{width:Math.max(1,e.width*n),height:Math.max(1,e.height*n)}},Ce=(e,t)=>{let n=t.minScale??ve,r=t.maxScale??5,i=be(e.scale,n,r),a=Math.max(0,(t.image.width*i-t.viewport.width)/2),o=Math.max(0,(t.image.height*i-t.viewport.height)/2);return{scale:i,x:be(e.x,-a,a),y:be(e.y,-o,o)}},we=(e,t,n,r,i)=>{let a=be(t,i.minScale??ve,i.maxScale??5),o=a/e.scale;return Ce({scale:a,x:n.x-r.x-(n.x-r.x-e.x)*o,y:n.y-r.y-(n.y-r.y-e.y)*o},i)},Te=(e,t,n)=>Ce({...e,x:e.x+t.x,y:e.y+t.y},n),Ee=(e,t,n,r,i,a)=>{let o=be(r,a.minScale??ve,a.maxScale??5),s=o/e.scale;return Ce({scale:o,x:n.x-i.x-(t.x-i.x-e.x)*s,y:n.y-i.y-(t.y-i.y-e.y)*s},a)},De=500,Oe=24,ke=(e,t={})=>{let n=t.target??(typeof document>`u`?null:document);if(!n)return()=>{};let r=t.durationMs??De,i=t.maxDistance??Oe,a=!0,o,s=()=>{a&&(a=!1,n.removeEventListener(`click`,c,!0),o!==void 0&&globalThis.clearTimeout(o))},c=t=>{let n=t;typeof n.clientX==`number`&&typeof n.clientY==`number`&&(Math.hypot(n.clientX-e.x,n.clientY-e.y)>i||(s(),t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation()))};return n.addEventListener(`click`,c,!0),o=globalThis.setTimeout(s,r),s},Ae=(e,t,n={})=>{ke(e,n),t()},je=e(s(),1);function Me(e,t,n,r,i){let a=e instanceof HTMLImageElement?e:e.querySelector(`img`);if(!a||!t.complete||!t.naturalWidth||!t.animate)return;let o=t.getBoundingClientRect(),s=a.getBoundingClientRect();if(!o.width||!o.height||!s.width||!s.height)return;let c=getComputedStyle(a),l=t.naturalWidth/t.naturalHeight,u=c.objectFit===`cover`?Math.max(s.width,s.height*l):Math.min(s.width,s.height*l),d=u/l,f=c.objectPosition.split(` `);if(!f.every(e=>e.endsWith(`%`)))return;let p=(s.width-u)*parseFloat(f[0])/100,m=(s.height-d)*parseFloat(f[1]??f[0])/100,h=s.left,g=s.top,_=s.right,v=s.bottom,y=c.borderRadius;for(let e=a.parentElement;e;e=e.parentElement){let t=getComputedStyle(e),n=e.getBoundingClientRect();[`hidden`,`clip`,`auto`,`scroll`].includes(t.overflowX)&&(h=Math.max(h,n.left),_=Math.min(_,n.right)),[`hidden`,`clip`,`auto`,`scroll`].includes(t.overflowY)&&(g=Math.max(g,n.top),v=Math.min(v,n.bottom)),n.width===s.width&&n.height===s.height&&t.borderRadius!==`0px`&&(y=t.borderRadius)}if(_<=h||v<=g)return;let b=document.createElement(`div`);b.dataset.mediaCropAnimation=``,b.setAttribute(`aria-hidden`,`true`),Object.assign(b.style,{position:`fixed`,left:`0`,top:`0`,overflow:`hidden`,pointerEvents:`none`,zIndex:`51`,contain:`paint`});let x=document.createElement(`img`);x.src=t.currentSrc||t.src,x.alt=``,Object.assign(x.style,{display:`block`,width:`${o.width}px`,height:`${o.height}px`,maxWidth:`none`,transformOrigin:`0 0`}),b.append(x),document.body.append(b);let S={transform:`translate(${o.left}px, ${o.top}px)`,width:`${o.width}px`,height:`${o.height}px`,borderRadius:`0px`},C={transform:`translate(${h}px, ${g}px)`,width:`${_-h}px`,height:`${v-g}px`,borderRadius:y},w={transform:`translate(0px, 0px) scale(1)`},T={transform:`translate(${s.left+p-h}px, ${s.top+m-g}px) scale(${u/o.width})`},E={duration:280,easing:`cubic-bezier(0.2, 0, 0, 1)`,fill:`both`},D=t.style.visibility;t.style.visibility=`hidden`;let O=[b.animate(r?[S,C]:[C,S],E),x.animate(r?[w,T]:[T,w],E),n.animate({opacity:r?[1,0]:[0,1]},E)],k=!1,A=(e=!1)=>{b.remove(),t.style.visibility=D,O.forEach((t,n)=>{(!e||n!==2)&&t.cancel()})};return Promise.all(O.map(e=>e.finished)).then(()=>{k||(A(r),i())},()=>{k||(A(),i())}),()=>{k=!0,A()}}function Ne(e,t,n,r,i=()=>{}){let a=e?.getBoundingClientRect(),o=window.matchMedia(`(prefers-reduced-motion: reduce)`).matches;if(!o&&e?.isConnected&&t instanceof HTMLImageElement&&n&&a?.width&&a.height&&a.bottom>0&&a.top<window.innerHeight&&a.right>0&&a.left<window.innerWidth){let a=Me(e,t,n,r,i);if(a)return a}if(!document.startViewTransition||o||!e?.isConnected||!t||!n||!a?.width||!a.height||a.bottom<=0||a.top>=window.innerHeight||a.right<=0||a.left>=window.innerWidth){if(!n?.animate||o)return i(),()=>{};let e=n.animate({opacity:r?[1,0]:[0,1]},{duration:150,fill:`forwards`}),t=!1;return e.finished.then(()=>{t||i()},()=>{}),()=>{t=!0,e.cancel()}}let s=e.style.viewTransitionName,c=t.style.viewTransitionName,l=n.style.visibility,u=!1,d=`oc-media-preview`;e.style.viewTransitionName=r?`none`:d,t.style.viewTransitionName=r?d:`none`,r||(n.style.visibility=`hidden`);let f=document.startViewTransition(()=>{u||(e.style.viewTransitionName=r?d:`none`,t.style.viewTransitionName=r?`none`:d,n.style.visibility=r?`hidden`:l)}),p=()=>{e.style.viewTransitionName=s,t.style.viewTransitionName=c,n.style.visibility=l};f.ready.catch(()=>{});let m=()=>{u||(p(),i())};return f.finished.then(m,m),()=>{u=!0,f.skipTransition(),p()}}function Pe(e){let t=(0,q.c)(12),{onClose:n,isMobile:r,size:i}=e,{t:a}=v(),o;t[0]!==r||t[1]!==i?(o=r?{top:`calc(var(--oc-safe-area-top, 0px) + 0.5rem)`,right:`calc(var(--oc-safe-area-right, 0px) + 0.75rem)`}:{top:i?`calc(50% - ${i.height/2}px + 0.5rem)`:`0.5rem`,right:i?`calc(50% - ${i.width/2}px + 0.5rem)`:`0.5rem`},t[0]=r,t[1]=i,t[2]=o):o=t[2];let s;t[3]===a?s=t[4]:(s=a(`dialog.common.actions.close`),t[3]=a,t[4]=s);let c;t[5]===Symbol.for(`react.memo_cache_sentinel`)?(c=(0,Y.jsx)(C,{name:`close`,className:`size-5`}),t[5]=c):c=t[5];let l;t[6]!==n||t[7]!==s?(l=(0,Y.jsx)(b,{variant:`mobileGlass`,size:`mobileIcon`,"aria-label":s,onClick:n,children:c}),t[6]=n,t[7]=s,t[8]=l):l=t[8];let u;return t[9]!==o||t[10]!==l?(u=(0,Y.jsx)(`div`,{className:`absolute right-3 z-20`,style:o,children:l}),t[9]=o,t[10]=l,t[11]=u):u=t[11],u}function Fe(e){let t=(0,q.c)(3),{children:n}=e,r;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(r={bottom:`calc(var(--oc-safe-area-bottom, 0px) + 0.5rem)`},t[0]=r):r=t[0];let i;return t[1]===n?i=t[2]:(i=(0,Y.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 z-20 flex justify-center px-2`,style:r,children:(0,Y.jsx)(`div`,{"data-media-preview-toolbar":``,className:`pointer-events-auto flex h-10 items-center gap-0.5 rounded-full border border-[color-mix(in_srgb,var(--oc-media-preview-foreground)_15%,transparent)] bg-[color-mix(in_srgb,var(--oc-media-preview-foreground)_10%,transparent)] px-1 text-[var(--oc-media-preview-foreground)] shadow-lg backdrop-blur-xl`,onPointerDown:Le,onDoubleClick:Ie,children:n})}),t[1]=n,t[2]=i),i}function Ie(e){return e.stopPropagation()}function Le(e){return e.stopPropagation()}function Re(e){let t=(0,q.c)(28),{open:n,title:r,kind:i,source:a,isMobile:o,onOpenChange:s,children:c}=e,l=J.useRef(null),u=J.useId(),d=J.useRef(null),f=J.useRef(!1),[p,m]=J.useState(!1),h;t[0]!==s||t[1]!==a?(h=()=>{if(f.current)return;f.current=!0,d.current?.();let e=l.current?.querySelector(`[data-preview-transition-target]`)??null;d.current=Ne(e?.dataset.previewReturn===`false`?void 0:a,e,l.current,!0,()=>{m(!0),s(!1)})},t[0]=s,t[1]=a,t[2]=h):h=t[2];let g=_(h),v=`${i}-preview`,y=n&&!p&&o,b;t[3]!==g||t[4]!==v||t[5]!==y?(b={id:v,active:y,layer:`overlay`,onBack:g,surfaceRef:l},t[3]=g,t[4]=v,t[5]=y,t[6]=b):b=t[6],K(b);let x,S;if(t[7]!==g||t[8]!==p||t[9]!==o||t[10]!==u||t[11]!==n||t[12]!==a?(x=()=>{if(!n){m(!1),f.current=!1;return}if(p)return;let e=l.current,t=document.activeElement instanceof HTMLElement?document.activeElement:null,r=o?j.add({id:u,onClose:g},document.body):void 0;return e?.querySelector(`button`)?.focus({preventScroll:!0}),d.current=Ne(a,e?.querySelector(`[data-preview-transition-target]`)??null,e,!1),()=>{d.current?.(),d.current=null,f.current=!1,r?.(),t?.isConnected&&t.focus({preventScroll:!0})}},S=[p,n,a,o,u,g],t[7]=g,t[8]=p,t[9]=o,t[10]=u,t[11]=n,t[12]=a,t[13]=x,t[14]=S):(x=t[13],S=t[14]),J.useLayoutEffect(x,S),!n||p||typeof document>`u`)return null;let C=o?`var(--oc-media-preview-background)`:`color-mix(in srgb, var(--oc-media-preview-background) ${i===`mermaid`?90:70}%, transparent)`,w;t[15]===C?w=t[16]:(w={backgroundColor:C,color:`var(--oc-media-preview-foreground)`},t[15]=C,t[16]=w);let T;t[17]===g?T=t[18]:(T=e=>{if(!e.currentTarget.contains(e.target)||(e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),g()),e.key!==`Tab`))return;let t=Array.from(e.currentTarget.querySelectorAll(`button:not([disabled]), a[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex="0"]`)),n=t[0],r=t.at(-1);e.shiftKey&&document.activeElement===n?(e.preventDefault(),r?.focus()):!e.shiftKey&&document.activeElement===r&&(e.preventDefault(),n?.focus())},t[17]=g,t[18]=T);let E;t[19]!==c||t[20]!==g?(E=c(g),t[19]=c,t[20]=g,t[21]=E):E=t[21];let D;return t[22]!==i||t[23]!==E||t[24]!==w||t[25]!==T||t[26]!==r?(D=(0,je.createPortal)((0,Y.jsx)(`div`,{ref:l,role:`dialog`,"aria-modal":`true`,"aria-label":r,"data-media-preview":i,"data-page-scroll-lock":`true`,tabIndex:-1,className:`fixed inset-0 z-[80] overflow-hidden select-none [-webkit-touch-callout:none]`,style:w,onClick:ze,onKeyDown:T,children:E}),document.body),t[22]=i,t[23]=E,t[24]=w,t[25]=T,t[26]=r,t[27]=D):D=t[27],D}function ze(e){e.stopPropagation()}var Be=1048576,$=f(`OpenChamberVideo`),Ve=e=>{let t=/^bytes=(\d*)-(\d*)$/.exec(e||`bytes=0-1048575`);if(!t||!t[1]&&!t[2])throw Error(`Invalid media range`);if(!t[1]){let e=Number(t[2]);if(!Number.isSafeInteger(e)||e<=0)throw Error(`Invalid media range`);return`bytes=-${Math.min(e,Be)}`}let n=Number(t[1]),r=t[2]?Number(t[2]):n+Be-1;if(!Number.isSafeInteger(n)||!Number.isSafeInteger(r)||r<n)throw Error(`Invalid media range`);return`bytes=${n}-${Math.min(r,n+Be-1)}`},He=e=>{let t=``;for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t)};async function Ue(e,i,a){if(!p.isNativePlatform()||p.getPlatform()!==`ios`||!p.isPluginAvailable(`OpenChamberVideo`))return null;let o=n(),s=crypto.randomUUID(),c=new Map,l=!1,u=()=>{},d=async()=>{if(!l){l=!0,u(),a.removeEventListener(`abort`,f);for(let e of c.values())e.abort();c.clear(),await Promise.allSettled([h?.remove(),$.release({assetId:s})])}},f=()=>{d()},m=async t=>{if(t.assetId!==s||l)return;if(t.cancelled){c.get(t.requestId)?.abort();return}if(c.has(t.requestId))return;let u=new AbortController;c.set(t.requestId,u);let d;try{if(o!==n()||a.aborted)throw Error(`Video runtime changed`);let s=t.method===`HEAD`?`bytes=0-0`:Ve(t.range);d=await r(e,{...i,headers:{Range:s},signal:u.signal});let c=d.headers.get(`content-range`)||``;if(d.status===416&&/^bytes \*\/\d+$/.test(c)){await $.respond({requestId:t.requestId,status:416,contentRange:c,dataBase64:``});return}let f=/^bytes (\d+)-(\d+)\/(\d+)$/.exec(c);if(d.status!==206||!f)throw Error(`Host does not support video ranges`);let[p,m,h]=f.slice(1).map(Number),g=m-p+1;if(![p,m,h].every(Number.isSafeInteger)||g<=0||g>1048576||m>=h)throw Error(`Invalid video range response`);let _=d.body?.getReader();if(!_)throw Error(`Missing video response body`);let v=new Uint8Array(g),y=0;try{for(;;){let{done:e,value:t}=await _.read();if(e)break;if(y+t.length>g)throw Error(`Oversized video range`);v.set(t,y),y+=t.length}}finally{await _.cancel().catch(()=>{}),_.releaseLock()}if(y!==g)throw Error(`Truncated video range`);if(l||u.signal.aborted||o!==n())return;let b=d.headers.get(`content-type`)?.split(`;`)[0]||`application/octet-stream`;await $.respond({requestId:t.requestId,status:t.method===`HEAD`?200:206,contentType:b,contentRange:t.method===`HEAD`?void 0:c,contentLength:t.method===`HEAD`?h:g,dataBase64:t.method===`HEAD`?``:He(v)})}catch{!l&&!u.signal.aborted&&await $.respond({requestId:t.requestId,status:502,dataBase64:``}).catch(()=>{})}finally{d?.body&&!d.body.locked&&await d.body.cancel().catch(()=>{}),c.delete(t.requestId)}},h=await $.addListener(`request`,e=>{m(e)});a.addEventListener(`abort`,f,{once:!0}),u=t(f);try{a.throwIfAborted();let{url:e}=await $.create({assetId:s});if(l||a.aborted)throw await $.release({assetId:s}),new DOMException(`Aborted`,`AbortError`);return{url:e,release:d}}catch(e){throw await d(),e}}var We=`image/png`,Ge=f(`OpenChamberMedia`),Ke=e=>{let t=e.toLowerCase().split(`;`)[0]?.trim()||We;if(t===`image/jpeg`||t===`image/jpg`)return`jpg`;if(t===`image/webp`)return`webp`;if(t===`image/gif`)return`gif`;if(t===`image/svg+xml`)return`svg`;if(t===`image/png`)return`png`;if(t===`video/quicktime`)return`mov`;let n=t.split(`/`)[1];return n&&/^[a-z0-9.+-]+$/i.test(n)?n:`png`},qe=(e,t)=>{let n=`${t.startsWith(`video/`)?`video`:`image`}.${Ke(t)}`,r=(((e||``).trim()||n).split(/[\\/]/).pop()||n).replace(/[^\w.\- ()[\]]+/g,`_`).replace(/^\.+/,``);return r?/\.[a-z0-9]{1,8}$/i.test(r)?r:`${r}.${Ke(t)}`:n},Je=e=>new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{if(typeof r.result==`string`){t(r.result);return}n(Error(`Failed to encode image`))},r.onerror=()=>n(r.error??Error(`Failed to encode image`)),r.readAsDataURL(e)}),Ye=async e=>{let t=await Je(e),n=t.indexOf(`,`);return n>=0?t.slice(n+1):t},Xe=(e,t)=>{let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,document.body.appendChild(r),r.click(),document.body.removeChild(r),window.setTimeout(()=>URL.revokeObjectURL(n),1e3)},Ze=async(e,t)=>{if(e.startsWith(`openchamber-asset:`)){let n=await ne(e,t);if(n)return n;if(l())throw Error(`Image display stream is no longer available`)}let n=await(/^\/api(?=\/|[?#]|$)/.test(e)?r(e,{signal:t,cache:`no-store`}):fetch(e,{signal:t,cache:`no-store`}));if(!n.ok)throw Error(`Image fetch failed (${n.status})`);return n.blob()},Qe=async(e,t)=>{let n=await r(`/api/fs/raw`,{query:{path:e},signal:t});if(!n.ok)throw Error(`Image source request failed (${n.status})`);return n.blob()},$e=async(e,t)=>{let n=e.effectiveDirectory??``,r=null;e.prefetchedBlob&&e.prefetchedBlob.size>0&&(r=e.prefetchedBlob);let i=e.displayUrl?.trim();if(!r&&i)try{r=await Ze(i,t)}catch{t?.throwIfAborted(),r=null}if(!r){let i=e.sourceUrl.trim();if(!i)throw Error(`Image source is empty`);if(/^(?:data|blob):/i.test(i)||/^https?:/i.test(i)||/^\/api(?=\/|[?#]|$)/.test(i))r=await Ze(i,t);else{let e=O(i,n);r=E(e)?await Qe(e.path,t):await Ze(e.source,t)}}if(!r||r.size<=0)throw Error(`Image is empty`);let a=(e.mimeType||(r.type&&/^(image|video)\//.test(r.type)?r.type:``)||(e.kind===`video`?`video/mp4`:``)||We).split(`;`)[0].trim()||We;return{blob:r,filename:qe(e.filename,a),mimeType:a}},et=()=>!l()||p===void 0?!1:p.isPluginAvailable(`OpenChamberMedia`),tt=async(e,t)=>{let{blob:n,filename:r,mimeType:o}=await $e(e,t);if(t?.throwIfAborted(),et()){let i=await Ye(n);if(t?.throwIfAborted(),e.kind===`video`){if((await Ge.saveFile({dataBase64:i,mimeType:o,filename:r}))?.cancelled)throw new DOMException(`Save cancelled`,`AbortError`);return`saved`}return await Ge.saveImage({dataBase64:i,mimeType:o,filename:r}),`saved`}if(a()){if(e.kind===`video`){let t=O(e.sourceUrl,e.effectiveDirectory??``),n=i()?.files;if(E(t)&&n?.downloadFile)return await n.downloadFile(t.path),`saved`;throw Error(`Video download is unavailable for this source in VS Code`)}let t=i()?.vscode;if(t?.saveImage){let e=await Je(n);return await t.saveImage({fileName:r,dataUrl:e}),`saved`}}return Xe(n,r),`downloaded`};function nt(e){let t=(0,q.c)(29),{target:n}=e,{t:r}=v(),[i,a]=J.useState(`idle`),o=J.useRef(null),s,c;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(s=()=>()=>o.current?.abort(),c=[],t[0]=s,t[1]=c):(s=t[0],c=t[1]),J.useEffect(s,c);let l;t[2]===n?l=t[3]:(l=async()=>{if(o.current)return;let e=new AbortController;o.current=e,a(`saving`);try{await tt(n,e.signal),e.signal.aborted||a(`saved`)}catch(t){let n=t;if(e.signal.aborted)return;o.current=null,a(n instanceof DOMException&&n.name===`AbortError`?`idle`:`error`)}},t[2]=n,t[3]=l);let u=_(l),d=i===`saving`,f=i===`saved`,p;t[4]!==f||t[5]!==d||t[6]!==r||t[7]!==n?(p=r(d?`chat.image.actions.saving`:f?`filesView.editor.saved`:n.kind===`video`?`filesView.editor.saveFile`:`chat.image.actions.saveImage`),t[4]=f,t[5]=d,t[6]=r,t[7]=n,t[8]=p):p=t[8];let m=p,h=d||f,g=d?`loader-4`:f?`check`:`download`,y=d?`size-4 motion-safe:animate-spin`:`size-4`,x;t[9]!==g||t[10]!==y?(x=(0,Y.jsx)(C,{name:g,className:y}),t[9]=g,t[10]=y,t[11]=x):x=t[11];let S;t[12]!==m||t[13]!==u||t[14]!==d||t[15]!==i||t[16]!==h||t[17]!==x?(S=(0,Y.jsx)(b,{variant:`ghost`,size:`icon`,"data-media-save":i,className:`size-8 rounded-full [corner-shape:round] text-[var(--oc-media-preview-foreground)] hover:text-[var(--oc-media-preview-foreground)] hover:bg-[color-mix(in_srgb,var(--oc-media-preview-foreground)_12%,transparent)] disabled:opacity-100`,"aria-label":m,"aria-busy":d,disabled:h,onClick:u,children:x}),t[12]=m,t[13]=u,t[14]=d,t[15]=i,t[16]=h,t[17]=x,t[18]=S):S=t[18];let w;t[19]!==m||t[20]!==i||t[21]!==r||t[22]!==n?(w=i===`error`?r(n.kind===`video`?`filesView.toast.saveFailed`:`chat.image.actions.saveFailed`):i===`idle`?``:m,t[19]=m,t[20]=i,t[21]=r,t[22]=n,t[23]=w):w=t[23];let T;t[24]===w?T=t[25]:(T=(0,Y.jsx)(`span`,{className:`sr-only`,role:`status`,"aria-live":`polite`,children:w}),t[24]=w,t[25]=T);let E;return t[26]!==T||t[27]!==S?(E=(0,Y.jsxs)(Y.Fragment,{children:[S,T]}),t[26]=T,t[27]=S,t[28]=E):E=t[28],E}function rt(e){let t=(0,q.c)(53),{video:n,onClose:i,isMobile:a}=e,{t:o}=v(),s=te()??``,c=D(),l,u;t[0]!==s||t[1]!==n.url?(l=O(n.url,s),u=E(l)?l.path:``,t[0]=s,t[1]=n.url,t[2]=l,t[3]=u):(l=t[2],u=t[3]);let d=u,f=/^\/api(?=\/|[?#]|$)/.test(n.url)?n.url:``,p=!!(d||f),h=`${c}\n${s}\n${n.url}`,[g,_]=J.useState(),y,b;t[4]!==p||t[5]!==d||t[6]!==f||t[7]!==h?(y=()=>{if(!p)return;let e=new AbortController,t;return Ue(f||`/api/fs/raw`,{query:d?{path:d}:void 0},e.signal).then(async n=>{if(e.signal.aborted){await n?.release();return}t=n?.release,_({key:h,url:n?.url,unsupported:!n})}).catch(()=>{e.signal.aborted||_({key:h,error:!0})}),()=>{e.abort(),t?.()}},b=[p,d,f,h],t[4]=p,t[5]=d,t[6]=f,t[7]=h,t[8]=y,t[9]=b):(y=t[8],b=t[9]),J.useEffect(y,b);let x=g?.key===h?g:void 0,S;t[10]!==s||t[11]!==c||t[12]!==n.url?(S=[`video-preview`,c,s,n.url],t[10]=s,t[11]=c,t[12]=n.url,t[13]=S):S=t[13];let C=p&&x?.unsupported===!0,w;t[14]!==d||t[15]!==f?(w=async e=>{let{signal:t}=e,n=await r(f||`/api/fs/raw`,{query:d?{path:d}:void 0,signal:t});if(!n.ok)throw Error(`Video request failed (${n.status})`);return n.blob()},t[14]=d,t[15]=f,t[16]=w):w=t[16];let T;t[17]!==S||t[18]!==C||t[19]!==w?(T={queryKey:S,enabled:C,gcTime:0,staleTime:1/0,retry:!1,queryFn:w},t[17]=S,t[18]=C,t[19]=w,t[20]=T):T=t[20];let k=m(T),[A,j]=J.useState(null),M,N;t[21]===k.data?(M=t[22],N=t[23]):(M=()=>{if(!k.data)return;let e=URL.createObjectURL(k.data);return j({blob:k.data,url:e}),()=>URL.revokeObjectURL(e)},N=[k.data],t[21]=k.data,t[22]=M,t[23]=N),J.useEffect(M,N);let P=p?x?.url||(A?.blob===k.data?A?.url:``):l.source,[ee,ne]=J.useState(),F=x?.error||k.isError||!!(P&&ee===P),I;t[24]!==a||t[25]!==i?(I=(0,Y.jsx)(Pe,{onClose:i,isMobile:a}),t[24]=a,t[25]=i,t[26]=I):I=t[26];let L;t[27]!==F||t[28]!==P||t[29]!==o?(L=!P&&!F&&(0,Y.jsx)(`p`,{role:`status`,children:o(`common.loading`)}),t[27]=F,t[28]=P,t[29]=o,t[30]=L):L=t[30];let R;t[31]!==F||t[32]!==o?(R=F&&(0,Y.jsx)(`p`,{role:`alert`,children:o(`filesView.error.readFileFailed`)}),t[31]=F,t[32]=o,t[33]=R):R=t[33];let z;t[34]!==P||t[35]!==n.filename?(z=P&&(0,Y.jsx)(`video`,{src:P,controls:!0,playsInline:!0,preload:`metadata`,"aria-label":n.filename,className:`max-h-[80dvh] w-full max-w-5xl object-contain`,onError:()=>ne(P),controlsList:`nodownload`,onContextMenu:it},P),t[34]=P,t[35]=n.filename,t[36]=z):z=t[36];let B=x?.url?void 0:P,V;t[37]!==s||t[38]!==k.data||t[39]!==B||t[40]!==n.filename||t[41]!==n.mimeType||t[42]!==n.url?(V={kind:`video`,sourceUrl:n.url,displayUrl:B,filename:n.filename,mimeType:n.mimeType,effectiveDirectory:s,prefetchedBlob:k.data},t[37]=s,t[38]=k.data,t[39]=B,t[40]=n.filename,t[41]=n.mimeType,t[42]=n.url,t[43]=V):V=t[43];let H;t[44]!==h||t[45]!==V?(H=(0,Y.jsx)(Fe,{children:(0,Y.jsx)(nt,{target:V},h)}),t[44]=h,t[45]=V,t[46]=H):H=t[46];let U;return t[47]!==I||t[48]!==L||t[49]!==R||t[50]!==z||t[51]!==H?(U=(0,Y.jsxs)(`div`,{className:`absolute inset-0 flex flex-col items-center justify-center gap-3 p-4`,children:[I,L,R,z,H]}),t[47]=I,t[48]=L,t[49]=R,t[50]=z,t[51]=H,t[52]=U):U=t[52],U}function it(e){return e.preventDefault()}var at=400,ot=(e,t)=>new fe(e,t),st=e=>{let t=`h-3.5 w-3.5 flex-shrink-0`,n=e.toLowerCase();return n===`reasoning`?(0,Y.jsx)(C,{name:`brain-ai-3`,className:t}):n===`image-preview`?(0,Y.jsx)(C,{name:`file-image`,className:t}):n===`mermaid-preview`?(0,Y.jsx)(C,{name:`file-list-2`,className:t}):n===`edit`||n===`multiedit`||n===`apply_patch`||n===`str_replace`||n===`str_replace_based_edit_tool`?(0,Y.jsx)(C,{name:`pencil-ai`,className:t}):n===`write`||n===`create`||n===`file_write`||n===`read`||n===`view`||n===`file_read`||n===`cat`?(0,Y.jsx)(C,{name:`file-pdf`,className:t}):n===`bash`||n===`shell`||n===`cmd`||n===`terminal`?(0,Y.jsx)(C,{name:`terminal-box`,className:t}):n===`list`||n===`ls`||n===`dir`||n===`list_files`?(0,Y.jsx)(C,{name:`folder-6`,className:t}):n===`search`||n===`grep`||n===`find`||n===`ripgrep`?(0,Y.jsx)(C,{name:`search`,className:t}):n===`glob`?(0,Y.jsx)(C,{name:`file-search`,className:t}):n===`fetch`||n===`curl`||n===`wget`||n===`webfetch`?(0,Y.jsx)(C,{name:`global`,className:t}):n===`web-search`||n===`websearch`||n===`search_web`||n===`google`||n===`bing`||n===`duckduckgo`?(0,Y.jsx)(C,{name:`search`,className:t}):n===`todowrite`||n===`todoread`?(0,Y.jsx)(C,{name:`list-check-3`,className:t}):n.startsWith(`git`)?(0,Y.jsx)(C,{name:`git-branch`,className:t}):(0,Y.jsx)(C,{name:`tools`,className:t})},ct={style:{background:`transparent`,backgroundColor:`transparent`,fontSize:`inherit`}},lt={download:!1,copy:!1,showPanZoomControls:!0},ut=`
3
- [data-diff-header],
4
- [data-diff] {
5
- [data-separator] {
6
- height: 24px !important;
7
- }
8
- }
9
- `,dt={hunkLineCount:50,lineHeight:24,diffHeaderHeight:44,hunkSeparatorHeight:24,spacing:0},ft=()=>{let e=(0,q.c)(22),t=S(),n;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(n=A(!1),e[0]=n):n=e[0];let r=n,i;e[1]===Symbol.for(`react.memo_cache_sentinel`)?(i=A(!0),e[1]=i):i=e[1];let a=i,o;e[2]===t?.availableThemes?o=e[3]:(o=()=>t?.availableThemes??[r,a],e[2]=t?.availableThemes,e[3]=o),t?.availableThemes;let s;e[4]===o?s=e[5]:(s=o(),e[4]=o,e[5]=s);let c=s,l=t?.lightThemeId??r.metadata.id,u=t?.darkThemeId??a.metadata.id,d;e[6]!==c||e[7]!==l?(d=c.find(e=>e.metadata.id===l)??r,e[6]=c,e[7]=l,e[8]=d):d=e[8];let f=d,p;e[9]!==c||e[10]!==u?(p=c.find(e=>e.metadata.id===u)??a,e[9]=c,e[10]=u,e[11]=p):p=e[11];let m=p,h,g;e[12]!==m||e[13]!==f?(h=()=>{M(f),M(m)},g=[m,f],e[12]=m,e[13]=f,e[14]=h,e[15]=g):(h=e[14],g=e[15]),J.useEffect(h,g);let _=t?.currentTheme.metadata.variant??`light`,v;e[16]!==m.metadata.id||e[17]!==f.metadata.id?(v={light:f.metadata.id,dark:m.metadata.id},e[16]=m.metadata.id,e[17]=f.metadata.id,e[18]=v):v=e[18];let y=_===`dark`?`dark`:`light`,b;return e[19]!==v||e[20]!==y?(b={theme:v,themeType:y},e[19]=v,e[20]=y,e[21]=b):b=e[21],b},pt=()=>({width:typeof window<`u`?window.innerWidth:0,height:typeof window<`u`?window.innerHeight:0}),mt=e=>{let t=(0,q.c)(3),[n,r]=J.useState(pt),i,a;return t[0]===e?(i=t[1],a=t[2]):(i=()=>{if(!e||typeof window>`u`)return;let t=()=>{r(pt())};return t(),window.addEventListener(`resize`,t),()=>{window.removeEventListener(`resize`,t)}},a=[e],t[0]=e,t[1]=i,t[2]=a),J.useEffect(i,a),n},ht=({popup:e,onOpenChange:t,isMobile:n})=>{let{t:r}=v(),i=S(),a=te()??``,o=J.useMemo(()=>{let t=e.image;if(!t)return[];let n=Array.isArray(t.gallery)?t.gallery.filter(e=>!!e?.url):[];return n.length>0?n:[{url:t.url,mimeType:t.mimeType,filename:t.filename,size:t.size}]},[e.image]),[s,c]=J.useState(()=>{let t=e.image?.index??o.findIndex(t=>t.url===e.image?.url);return t>=0&&t<o.length?t:0}),l=e.previewSource instanceof HTMLImageElement?e.previewSource:void 0,u=l?.naturalWidth&&l.naturalHeight?{width:l.naturalWidth,height:l.naturalHeight}:null,[d,f]=J.useState(u),[p,m]=J.useState(!!u),h=e.open,g=mt(e.open),x=J.useRef(null),w=J.useRef(null),T=J.useRef(null),E=J.useRef(null),D=J.useRef({scale:1,x:0,y:0}),O=J.useRef({image:{width:1,height:1},viewport:{width:1,height:1},maxScale:5}),A=J.useRef(new Map),j=J.useRef(null),M=J.useRef(null),N=J.useRef(null),P=J.useRef(null),ee=J.useRef(0);J.useEffect(()=>{e.open&&(ee.current=typeof performance<`u`?performance.now():Date.now())},[e.open]);let ne=_(()=>(typeof performance<`u`?performance.now():Date.now())-ee.current<at);J.useEffect(()=>{if(!e.open||o.length===0)return;let t=typeof e.image?.index==`number`?e.image.index:-1;if(t>=0&&t<o.length){c(t);return}let n=e.image?.url?o.findIndex(t=>t.url===e.image?.url):-1;c(n>=0?n:0)},[o,e.image?.index,e.image?.url,e.open]);let I=o[s]??o[0]??e.image,L=k(I?.url??``,a,`preview`),R=L.source||(I?.url===e.image?.url?l?.currentSrc:``)||``,z=`${L.key}\n${R}`,[B,V]=J.useState(``),H=!!(L.error||B===z),U=_(()=>V(z)),re=I?.filename||e.title,W=o.length>1,ie=_(()=>{o.length<=1||c(e=>(e-1+o.length)%o.length)}),ae=_(()=>{o.length<=1||c(e=>(e+1)%o.length)}),G=J.useMemo(()=>{let e={width:Math.max(1,g.width*(n?1:.8)),height:Math.max(1,g.height*(n?1:.95))};return d?Se(d,e):e},[d,n,g.height,g.width]),oe=J.useMemo(()=>({image:G,viewport:{width:Math.max(1,g.width),height:Math.max(1,g.height)},maxScale:5}),[G,g.height,g.width]),K=_((e,t=!1)=>{let n=Ce(e,O.current);D.current=n,P.current={transform:n,animate:t},!(N.current!==null||typeof window>`u`)&&(N.current=window.requestAnimationFrame(()=>{N.current=null;let e=P.current;P.current=null,e&&(T.current&&(T.current.style.transition=e.animate?`transform 180ms cubic-bezier(0.22, 1, 0.36, 1)`:`none`,T.current.style.transform=`translate3d(${e.transform.x}px, ${e.transform.y}px, 0) scale(${e.transform.scale})`),E.current&&(E.current.textContent=`${Math.round(e.transform.scale*100)}%`),x.current&&(x.current.style.cursor=e.transform.scale>1?`grab`:`zoom-in`))}))}),q=_((e=!0)=>{K({scale:1,x:0,y:0},e)}),X=_(()=>({x:O.current.viewport.width/2,y:O.current.viewport.height/2})),Z=_((e,t,n=!1)=>{K(we(D.current,e,t,X(),O.current),n)}),se=_(e=>{if(D.current.scale>1.01){q(!0);return}Z(2,e,!0)}),ce=_(e=>{if(!(n||e.defaultPrevented)){if(e.key===`+`||e.key===`=`){e.preventDefault(),Z(D.current.scale*1.4,X(),!0);return}if(e.key===`-`||e.key===`_`){e.preventDefault(),Z(D.current.scale/1.4,X(),!0);return}if(e.key===`0`){e.preventDefault(),q(!0);return}if(e.key===`ArrowLeft`&&W){e.preventDefault(),ie();return}e.key===`ArrowRight`&&W&&(e.preventDefault(),ae())}});J.useEffect(()=>{if(e.open)return window.addEventListener(`keydown`,ce),()=>{window.removeEventListener(`keydown`,ce)}},[e.open]),J.useEffect(()=>{N.current!==null&&window.cancelAnimationFrame(N.current),N.current=null,P.current=null;let t=I?.url===e.image?.url?l:void 0;f(t?.naturalWidth&&t.naturalHeight?{width:t.naturalWidth,height:t.naturalHeight}:null),m(!!t?.naturalWidth),D.current={scale:1,x:0,y:0},A.current.clear(),j.current=null,M.current=null,T.current&&(T.current.style.transform=`translate3d(0, 0, 0) scale(1)`),E.current&&(E.current.textContent=`100%`)},[I?.url,R,e.image?.url,l]),J.useLayoutEffect(()=>{O.current=oe;let e=Ce(D.current,O.current);D.current=e,T.current&&(T.current.style.transition=`none`,T.current.style.transform=`translate3d(${e.x}px, ${e.y}px, 0) scale(${e.scale})`)},[oe]),J.useEffect(()=>()=>{N.current!==null&&window.cancelAnimationFrame(N.current),N.current=null,P.current=null},[]);let le=_(e=>{if(n)return;e.preventDefault();let t={x:e.clientX,y:e.clientY},r=Math.exp(-e.deltaY*.002);Z(D.current.scale*r,t)});J.useEffect(()=>{let e=x.current;if(!(!h||n||!e))return e.addEventListener(`wheel`,le,{passive:!1}),()=>e.removeEventListener(`wheel`,le)},[n,h]);let ue=_(e=>{n||(e.preventDefault(),se({x:e.clientX,y:e.clientY}))}),de=_(e=>{e.preventDefault(),e.stopPropagation()}),fe=_(e=>{e.pointerType!==`mouse`&&e.preventDefault(),e.currentTarget.setPointerCapture(e.pointerId);let t={x:e.clientX,y:e.clientY};if(A.current.set(e.pointerId,{point:t,pointerType:e.pointerType}),A.current.size===1){j.current={pointerId:e.pointerId,pointerType:e.pointerType,start:t,transform:D.current,moved:!1,targetWasCanvas:e.target===e.currentTarget,suppressTap:!1},x.current&&D.current.scale>1&&(x.current.style.cursor=`grabbing`);return}j.current&&(j.current.suppressTap=!0);let n=Array.from(A.current.values()).slice(0,2).map(e=>e.point),r=n[1].x-n[0].x,i=n[1].y-n[0].y;M.current={distance:Math.max(1,Math.hypot(r,i)),midpoint:{x:(n[0].x+n[1].x)/2,y:(n[0].y+n[1].y)/2},transform:D.current},j.current&&(j.current.suppressTap=!0)}),pe=_(e=>{if(!A.current.has(e.pointerId))return;e.preventDefault();let t={x:e.clientX,y:e.clientY};if(A.current.set(e.pointerId,{point:t,pointerType:e.pointerType}),A.current.size>=2&&M.current){let e=Array.from(A.current.values()).slice(0,2).map(e=>e.point),t=e[1].x-e[0].x,n=e[1].y-e[0].y,r={x:(e[0].x+e[1].x)/2,y:(e[0].y+e[1].y)/2},i=M.current.transform.scale*Math.hypot(t,n)/M.current.distance;K(Ee(M.current.transform,M.current.midpoint,r,i,X(),O.current));return}let n=j.current;if(!n||n.pointerId!==e.pointerId)return;let r={x:t.x-n.start.x,y:t.y-n.start.y};Math.hypot(r.x,r.y)>10&&(n.moved=!0),n.transform.scale>1.01&&K(Te(n.transform,r,O.current))}),me=_((e,r)=>{let i=j.current,a=A.current.get(e.pointerId)?{x:e.clientX,y:e.clientY}:void 0;if(A.current.delete(e.pointerId),i?.pointerId===e.pointerId&&a){let e=xe({isMobile:n,pointerType:i.pointerType,cancelled:r,moved:i.moved||Math.hypot(a.x-i.start.x,a.y-i.start.y)>10,suppressTap:i.suppressTap,targetWasCanvas:i.targetWasCanvas,start:i.start,end:a,startScale:i.transform.scale,hasMultipleImages:W});if(e===`next`&&ae(),e===`previous`&&ie(),e===`close`){if(ne())return;if(n&&i.pointerType!==`mouse`){Ae(a,()=>t(!1));return}t(!1)}}if(A.current.size===1){let[e,t]=Array.from(A.current.entries())[0];j.current={pointerId:e,pointerType:t.pointerType,start:t.point,transform:D.current,moved:!1,targetWasCanvas:!1,suppressTap:!0},M.current=null}else A.current.size===0&&(j.current=null,M.current=null,x.current&&(x.current.style.cursor=D.current.scale>1?`grab`:`zoom-in`));e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId)}),he=_(e=>{e.preventDefault(),e.stopPropagation(),j.current&&(j.current.suppressTap=!0)}),ge=_(e=>{let t=e.currentTarget;t.naturalWidth>0&&t.naturalHeight>0&&f(e=>e?.width===t.naturalWidth&&e.height===t.naturalHeight?e:{width:t.naturalWidth,height:t.naturalHeight}),m(!0)});if(!h||!I||typeof document>`u`)return null;let Q=i?.currentTheme.metadata.variant===`dark`?`text-foreground hover:bg-foreground/15 hover:text-foreground`:`text-background hover:bg-background/15 hover:text-background`;return(0,Y.jsxs)(`div`,{ref:w,className:`absolute inset-0 overflow-hidden select-none`,tabIndex:-1,onClick:de,children:[(0,Y.jsx)(Pe,{onClose:()=>t(!1),isMobile:n,size:G}),(0,Y.jsxs)(`div`,{ref:x,className:`absolute inset-0 flex items-center justify-center overflow-hidden touch-none [overscroll-behavior:none]`,onDoubleClick:n?void 0:ue,onContextMenu:he,onPointerDown:fe,onPointerMove:pe,onPointerUp:e=>me(e,!1),onPointerCancel:e=>me(e,!0),onLostPointerCapture:e=>me(e,!0),children:[!p&&!H&&(0,Y.jsx)(`div`,{className:`pointer-events-none absolute inset-0 flex items-center justify-center`,role:`status`,children:(0,Y.jsx)(F,{className:`aspect-square w-64 max-w-[80vw] rounded-xl`})}),H?(0,Y.jsx)(`p`,{role:`status`,className:`px-6 text-center typography-ui-label`,children:r(`filesView.error.readFileFailed`)}):(0,Y.jsx)(`img`,{ref:T,"data-preview-transition-target":``,"data-preview-return":I?.url===e.image?.url,src:R||void 0,alt:re??``,className:y(`block max-w-none object-contain will-change-transform`,p?`opacity-100`:`opacity-0`),style:{width:`${G.width}px`,height:`${G.height}px`},loading:`lazy`,draggable:!1,onLoad:ge,onError:U})]}),(0,Y.jsxs)(Fe,{children:[W&&(0,Y.jsx)(b,{variant:`ghost`,size:`icon`,className:y(`size-8 rounded-full`,Q),onClick:ie,"aria-label":r(`chat.toolOutputDialog.image.previousAria`),title:r(`chat.toolOutputDialog.image.previousAria`),children:(0,Y.jsx)(C,{name:`arrow-left-s`,className:`size-5`})}),W&&(0,Y.jsxs)(`span`,{className:`min-w-10 px-1 text-center typography-micro tabular-nums opacity-80`,children:[s+1,` / `,o.length]}),W&&(0,Y.jsx)(b,{variant:`ghost`,size:`icon`,className:y(`size-8 rounded-full`,Q),onClick:ae,"aria-label":r(`chat.toolOutputDialog.image.nextAria`),title:r(`chat.toolOutputDialog.image.nextAria`),children:(0,Y.jsx)(C,{name:`arrow-right-s`,className:`size-5`})}),W&&(0,Y.jsx)(`span`,{className:`mx-0.5 h-4 w-px bg-current opacity-15`,"aria-hidden":`true`}),(0,Y.jsx)(b,{variant:`ghost`,size:`icon`,className:y(`size-8 rounded-full`,Q),onClick:()=>Z(D.current.scale/1.4,X(),!0),"aria-label":r(`chat.toolOutputDialog.image.zoomOutAria`),title:r(`chat.toolOutputDialog.image.zoomOutAria`),children:(0,Y.jsx)(C,{name:`subtract`,className:`size-4`})}),(0,Y.jsxs)(b,{variant:`ghost`,size:`sm`,className:y(`h-8 min-w-14 rounded-full px-2 tabular-nums`,Q),onClick:()=>q(!0),"aria-label":r(`chat.toolOutputDialog.image.resetZoomAria`),title:r(`chat.toolOutputDialog.image.resetZoomAria`),children:[(0,Y.jsx)(C,{name:`restart`,className:`size-3.5`}),(0,Y.jsx)(`span`,{ref:E,children:`100%`})]}),(0,Y.jsx)(b,{variant:`ghost`,size:`icon`,className:y(`size-8 rounded-full`,Q),onClick:()=>Z(D.current.scale*1.4,X(),!0),"aria-label":r(`chat.toolOutputDialog.image.zoomInAria`),title:r(`chat.toolOutputDialog.image.zoomInAria`),children:(0,Y.jsx)(C,{name:`add`,className:`size-4`})}),(0,Y.jsx)(nt,{target:{sourceUrl:I.url||R,displayUrl:R||void 0,filename:I.filename||e.image?.filename||e.title,mimeType:I.mimeType||e.image?.mimeType,effectiveDirectory:a}},L.key)]})]})},gt=J.memo(e=>{let t=(0,q.c)(7),{popup:n,diffViewMode:r,pierreThemeConfig:i}=e,a=n.content||``,o=r===`unified`?`unified`:`split`,s;t[0]!==i.theme||t[1]!==i.themeType||t[2]!==o?(s={diffStyle:o,diffIndicators:`none`,hunkSeparators:`line-info-basic`,lineDiffType:`none`,disableFileHeader:!0,maxLineDiffLength:1e3,expansionLineCount:20,overflow:`wrap`,theme:i.theme,themeType:i.themeType,unsafeCSS:ut},t[0]=i.theme,t[1]=i.themeType,t[2]=o,t[3]=s):s=t[3];let c;return t[4]!==a||t[5]!==s?(c=(0,Y.jsx)(`div`,{className:`typography-code`,children:(0,Y.jsx)(g,{patch:a,metrics:dt,options:s,className:`block w-full`})}),t[4]=a,t[5]=s,t[6]=c):c=t[6],c});gt.displayName=`DialogUnifiedDiff`;var _t=J.memo(e=>{let t=(0,q.c)(29),{popup:n,pierreThemeConfig:r}=e,i;t[0]===n.content?i=t[1]:(i=B(n.content),t[0]=n.content,t[1]=i);let a=i,o=n.metadata?.input,s;t[2]===o?s=t[3]:(s=typeof o==`object`&&o?o:{},t[2]=o,t[3]=s);let c=s,l=typeof c.offset==`number`?c.offset:0,u=typeof c.file_path==`string`?c.file_path:typeof c.filePath==`string`?c.filePath:typeof c.path==`string`?c.path:`read-output`,d;t[4]===a.lines?d=t[5]:(d=a.lines.map(bt).join(`
10
- `),t[4]=a.lines,t[5]=d);let f=d,p;t[6]!==u||t[7]!==n.language?(p=n.language||ee(u)||`text`,t[6]=u,t[7]=n.language,t[8]=p):p=t[8];let m=p,g;t[9]===a.lines?g=t[10]:(g=a.lines.some(xt),t[9]=a.lines,t[10]=g);let _=g,v;if(t[11]!==_||t[12]!==l||t[13]!==a.lines||t[14]!==a.type){v=[];let e=l;for(let t of a.lines){t.lineNumber!==null&&(e=t.lineNumber);let n=a.type===`file`&&!_&&t.lineNumber===null&&!t.isInfo,r=t.lineNumber??(n?e+1:null);typeof r==`number`&&(e=r),v.push({text:t.text,lineNumber:r,isInfo:t.isInfo})}t[11]=_,t[12]=l,t[13]=a.lines,t[14]=a.type,t[15]=v}else v=t[15];let y=v;if(a.type===`file`){let e=m||void 0,n;t[16]!==f||t[17]!==u||t[18]!==e?(n={name:u,contents:f,lang:e},t[16]=f,t[17]=u,t[18]=e,t[19]=n):n=t[19];let i;t[20]!==r.theme||t[21]!==r.themeType?(i={disableFileHeader:!0,overflow:`wrap`,theme:r.theme,themeType:r.themeType},t[20]=r.theme,t[21]=r.themeType,t[22]=i):i=t[22];let a;return t[23]!==n||t[24]!==i?(a=(0,Y.jsx)(h,{file:n,options:i,className:`block w-full`}),t[23]=n,t[24]=i,t[25]=a):a=t[25],a}let b;return t[26]!==y||t[27]!==m?(b=(0,Y.jsx)(se,{lines:y,language:m,maxHeight:`70vh`}),t[26]=y,t[27]=m,t[28]=b):b=t[28],b});_t.displayName=`DialogReadContent`;var vt=({popup:e,onOpenChange:t,isMobile:n})=>{let{t:i}=v(),a=S(),o=J.useMemo(()=>a?.currentTheme.metadata.variant===`dark`?a.currentTheme:a?.availableThemes.find(e=>e.metadata.id===a.darkThemeId&&e.metadata.variant===`dark`)??A(!0),[a?.currentTheme,a?.availableThemes,a?.darkThemeId]),[s,c]=J.useState(e.mermaid?.source||``),[l,u]=J.useState(e.mermaid?.source?`ready`:`idle`),[d,f]=J.useState(``),p=J.useRef(0),m=J.useCallback(e=>{let t=e.trim();if(!t.toLowerCase().startsWith(`file://`))return null;let n=e=>{if(!e||/[\0\r\n]/.test(e))return!1;let t=e.replace(/\\/g,`/`);return t.split(`/`).filter(Boolean).includes(`..`)?!1:t.startsWith(`/`)?!0:/^[A-Za-z]:\//.test(t)},r=e=>e.replace(/%([0-9A-Fa-f]{2})/g,(e,t)=>{let n=Number.parseInt(t,16);return Number.isFinite(n)?String.fromCharCode(n):`%${t}`});if(typeof URL.canParse==`function`&&URL.canParse(t)){let e=r(new URL(t).pathname||``);return/^\/[A-Za-z]:\//.test(e)&&(e=e.slice(1)),n(e)?e:null}let i=t.replace(/^file:\/\//i,``),a=r(i);return n(a)?a:n(i)?i:null},[]),h=J.useCallback(async()=>{let t=e.mermaid,n=he(p.current);if(p.current=n,!t?.url){u(`error`),f(i(`chat.toolOutputDialog.mermaid.missingSource`));return}if(t.source){c(t.source),u(`ready`),f(``);return}u(`loading`),f(``);let a;if(t.url.startsWith(`data:`))a=_e(t.url);else if(t.url.toLowerCase().startsWith(`file://`)){let e=m(t.url);a=e?r(`/api/fs/raw`,{query:{path:e}}).then(e=>e.ok?e.text():Promise.reject(ot(`chat.toolOutputDialog.mermaid.readFileFailedWithStatus`,{status:e.status}))):Promise.reject(ot(`chat.toolOutputDialog.mermaid.invalidLocalPath`))}else{let e=typeof URL.canParse==`function`&&URL.canParse(t.url,window.location.origin)?new URL(t.url,window.location.origin):null;a=!e||e.protocol!==`http:`&&e.protocol!==`https:`?Promise.reject(ot(`chat.toolOutputDialog.mermaid.unsupportedUrlProtocol`)):fetch(e.toString()).then(e=>e.ok?e.text():Promise.reject(ot(`chat.toolOutputDialog.mermaid.loadFailedWithStatus`,{status:e.status})))}await a.then(e=>{ge(p.current,n)&&(c(e),u(`ready`))}).catch(e=>{ge(p.current,n)&&(u(`error`),f(me(e)?i(e.key,e.params):i(`chat.toolOutputDialog.mermaid.loadFailed`)))})},[m,e.mermaid,i]);J.useEffect(()=>{!e.open||!e.mermaid||h()},[h,e.mermaid,e.open]);let g=`\`\`\`mermaid\n${s}\n\`\`\``;return!e.open||typeof document>`u`?null:(0,Y.jsx)(`div`,{className:`absolute inset-0 flex items-center justify-center`,onClick:e=>{e.target===e.currentTarget&&t(!1)},children:(0,Y.jsxs)(`div`,{"data-mermaid-preview":`true`,"data-preview-transition-target":``,className:`relative flex min-h-0 flex-col overflow-hidden`,style:{width:n?`100%`:`80%`,height:n?`100%`:`95%`},onMouseDown:e=>e.stopPropagation(),children:[(0,Y.jsx)(Pe,{onClose:()=>t(!1),isMobile:n}),(0,Y.jsx)(`div`,{className:`relative min-h-0 flex-1 overflow-hidden`,children:(0,Y.jsxs)(`div`,{className:`h-full overflow-hidden`,children:[l===`loading`&&(0,Y.jsxs)(`div`,{className:`h-full min-h-28 flex items-center justify-center gap-2 text-muted-foreground typography-meta`,children:[(0,Y.jsx)(C,{name:`loader-4`,className:`h-4 w-4 animate-spin`}),(0,Y.jsx)(`span`,{children:i(`chat.toolOutputDialog.mermaid.loading`)})]}),l===`error`&&(0,Y.jsxs)(`div`,{className:`rounded-xl border p-3 space-y-3`,style:{backgroundColor:`var(--status-error-background)`,borderColor:`var(--status-error-border)`},children:[(0,Y.jsx)(`p`,{className:`typography-markdown`,style:{color:`var(--status-error)`},children:d||i(`chat.toolOutputDialog.mermaid.renderFailed`)}),(0,Y.jsx)(`button`,{type:`button`,onClick:()=>{h()},className:`px-3 py-1.5 rounded-lg typography-meta border transition-colors hover:bg-[var(--interactive-hover)]`,style:{borderColor:`var(--interactive-border)`,color:`var(--surface-foreground)`},children:i(`chat.toolOutputDialog.mermaid.retry`)})]}),l===`ready`&&(0,Y.jsx)(`div`,{className:`h-full`,children:(0,Y.jsx)(N,{content:g,variant:`tool`,allowMermaidWheelEvents:!0,className:`markdown-mermaid-fullscreen h-full`,mermaidControls:lt,mermaidTheme:o,enableFileReferences:!1})})]})})]})})},yt=e=>{let t=(0,q.c)(52),{popup:n,onOpenChange:r,isMobile:i}=e,{t:a}=v(),[o,s]=J.useState(`unified`),c=ft(),l;t[0]===n.open?l=t[1]:(l=()=>{n.open&&s(`unified`)},t[0]=n.open,t[1]=l);let d;t[2]!==n.open||t[3]!==n.title?(d=[n.open,n.title],t[2]=n.open,t[3]=n.title,t[4]=d):d=t[4],J.useEffect(l,d);let f=n.video??(n.image&&P(n.image.url,n.image.mimeType)?n.image:void 0);if(n.image||n.mermaid||f){let e=f?`video`:n.image?`image`:`mermaid`,a;t[5]!==i||t[6]!==n||t[7]!==f?(a=e=>(0,Y.jsx)(Y.Fragment,{children:f?(0,Y.jsx)(rt,{video:f,onClose:e,isMobile:i}):n.image?(0,Y.jsx)(ht,{popup:n,onOpenChange:e,isMobile:i}):(0,Y.jsx)(vt,{popup:n,onOpenChange:e,isMobile:i})}),t[5]=i,t[6]=n,t[7]=f,t[8]=a):a=t[8];let o;return t[9]!==i||t[10]!==r||t[11]!==n.open||t[12]!==n.previewSource||t[13]!==n.title||t[14]!==e||t[15]!==a?(o=(0,Y.jsx)(Re,{open:n.open,title:n.title,kind:e,source:n.previewSource,isMobile:i,onOpenChange:r,children:a}),t[9]=i,t[10]=r,t[11]=n.open,t[12]=n.previewSource,t[13]=n.title,t[14]=e,t[15]=a,t[16]=o):o=t[16],o}let p=n.open,m=i?`w-[95vw] max-w-[95vw]`:`max-w-5xl`,g=i?`[&>button]:right-1`:`[&>button]:top-2.5 [&>button]:right-4`,_;t[17]!==m||t[18]!==g?(_=y(`overflow-hidden flex flex-col min-h-0 pt-3 pb-4 px-4 gap-1`,`[&>button]:top-1.5`,m,g),t[17]=m,t[18]=g,t[19]=_):_=t[19];let b;t[20]===Symbol.for(`react.memo_cache_sentinel`)?(b={maxHeight:`90vh`},t[20]=b):b=t[20];let x;t[21]===n.metadata?x=t[22]:(x=n.metadata?.tool?st(n.metadata.tool):(0,Y.jsx)(C,{name:`tools`,className:`h-3.5 w-3.5 text-foreground flex-shrink-0`}),t[21]=n.metadata,t[22]=x);let S;t[23]===n.title?S=t[24]:(S=(0,Y.jsx)(`span`,{className:`break-words flex-1 leading-tight`,children:n.title}),t[23]=n.title,t[24]=S);let E;t[25]!==o||t[26]!==n.isDiff?(E=n.isDiff&&(0,Y.jsx)(H,{mode:o,onModeChange:s,className:`mr-8 flex-shrink-0`}),t[25]=o,t[26]=n.isDiff,t[27]=E):E=t[27];let D;t[28]!==E||t[29]!==x||t[30]!==S?(D=(0,Y.jsx)(`div`,{className:`flex-shrink-0 pb-1`,children:(0,Y.jsxs)(`div`,{className:`flex items-start gap-2 text-foreground typography-ui-header font-semibold`,children:[x,S,E]})}),t[28]=E,t[29]=x,t[30]=S,t[31]=D):D=t[31];let O;t[32]!==c||t[33]!==n.metadata?(O=n.metadata?.input&&typeof n.metadata.input==`object`&&Object.keys(n.metadata.input).length>0&&n.metadata?.tool!==`todowrite`&&n.metadata?.tool!==`todoread`&&n.metadata?.tool!==`apply_patch`?(()=>{let e=n.metadata,t=e.input,r=e=>{let n=t[e];return typeof n==`string`?n:typeof n==`number`?String(n):null};return(0,Y.jsxs)(`div`,{className:`border-b border-border/20 p-4 -mx-3`,children:[(0,Y.jsx)(`div`,{className:`typography-markdown font-medium text-muted-foreground mb-2 px-3`,children:e.tool===`bash`||e.tool===`shell`?`Command:`:e.tool===`task`||e.tool===`subagent`?`Task Details:`:`Input:`}),(e.tool===`bash`||e.tool===`shell`)&&r(`command`)?(0,Y.jsx)(`div`,{className:`tool-input-surface bg-transparent rounded-xl border border-border/20 mx-3`,children:(0,Y.jsx)(R,{language:`bash`,code:r(`command`),style:u.getPopupStyles(),codeStyle:ct.style,wrap:!0})}):(e.tool===`task`||e.tool===`subagent`)&&r(`prompt`)?(0,Y.jsxs)(`div`,{className:`tool-input-surface bg-transparent rounded-xl border border-border/20 font-mono whitespace-pre-wrap text-foreground/90 mx-3`,style:u.getPopupStyles(),children:[r(`description`)?`Task: ${r(`description`)}\n`:``,r(`subagent_type`)||r(`agent`)?`Agent Type: ${r(`subagent_type`)||r(`agent`)}\n`:``,`Instructions:\n${r(`prompt`)}`]}):e.tool===`write`&&r(`content`)?(0,Y.jsx)(`div`,{className:`tool-input-surface bg-transparent rounded-xl border border-border/20 mx-3`,children:(0,Y.jsx)(h,{file:{name:r(`filePath`)||r(`file_path`)||`new-file`,contents:r(`content`),lang:ee(r(`filePath`)||r(`file_path`)||``)||void 0},options:{disableFileHeader:!0,overflow:`wrap`,theme:c.theme,themeType:c.themeType},className:`block w-full`})}):(0,Y.jsx)(`div`,{className:`tool-input-surface bg-transparent rounded-xl border border-border/20 font-mono whitespace-pre-wrap text-foreground/90 mx-3`,style:u.getPopupStyles(),children:W(t,e.tool)})]})})():null,t[32]=c,t[33]=n.metadata,t[34]=O):O=t[34];let k;t[35]!==o||t[36]!==i||t[37]!==c||t[38]!==n||t[39]!==a?(k=n.isDiff?(0,Y.jsx)(gt,{popup:n,diffViewMode:o,pierreThemeConfig:c}):n.content?(0,Y.jsx)(`div`,{className:`p-4`,children:(()=>{let e=n.metadata?.tool;return e===`todowrite`||e===`todoread`?U(n.content)||(0,Y.jsx)(R,{language:`json`,code:n.content,style:u.getPopupContainerStyles(),codeStyle:ct.style,wrap:!0}):e===`list`?L(n.content)||(0,Y.jsx)(`pre`,{className:`typography-markdown bg-muted/30 p-2 rounded-xl border border-border/20 font-mono whitespace-pre-wrap`,children:n.content}):e===`grep`?I(n.content,i)||(0,Y.jsx)(`pre`,{className:`typography-code bg-muted/30 p-2 rounded-xl border border-border/20 font-mono whitespace-pre-wrap`,children:n.content}):e===`glob`?ae(n.content,i)||(0,Y.jsx)(`pre`,{className:`typography-code bg-muted/30 p-2 rounded-xl border border-border/20 font-mono whitespace-pre-wrap`,children:n.content}):e===`task`||e===`subagent`||e===`reasoning`?(0,Y.jsx)(`div`,{className:e===`reasoning`?`text-muted-foreground/70`:``,children:(0,Y.jsx)(N,{content:n.content,variant:`tool`})}):e===`web-search`||e===`websearch`||e===`search_web`?V(n.content)||(0,Y.jsx)(R,{language:`text`,code:n.content,style:u.getPopupContainerStyles(),codeStyle:ct.style,wrap:!0}):e===`read`?(0,Y.jsx)(_t,{popup:n,pierreThemeConfig:c}):(n.content?z(n.content):{data:null,isJson:!1}).isJson?(0,Y.jsx)(de,{jsonString:n.content,initiallyExpandedDepth:3,maxHeight:`70vh`}):(0,Y.jsx)(R,{language:n.language||`text`,code:n.content,style:u.getPopupContainerStyles(),codeStyle:ct.style,wrap:!0})})()}):(0,Y.jsxs)(`div`,{className:`p-8 text-muted-foreground typography-ui-header`,children:[(0,Y.jsx)(`div`,{className:`mb-2`,children:a(`chat.toolOutputDialog.commandCompleted`)}),(0,Y.jsx)(`div`,{className:`typography-meta`,children:a(`chat.toolOutputDialog.noOutputProduced`)})]}),t[35]=o,t[36]=i,t[37]=c,t[38]=n,t[39]=a,t[40]=k):k=t[40];let A;t[41]!==O||t[42]!==k?(A=(0,Y.jsx)(`div`,{className:`flex-1 min-h-0 rounded-xl border border-border/30 bg-muted/10 overflow-hidden`,children:(0,Y.jsxs)(`div`,{className:`tool-output-surface h-full max-h-[75vh] overflow-y-auto px-3 pr-4`,children:[O,k]})}),t[41]=O,t[42]=k,t[43]=A):A=t[43];let j;t[44]!==D||t[45]!==A||t[46]!==_?(j=(0,Y.jsxs)(w,{className:_,style:b,children:[D,A]}),t[44]=D,t[45]=A,t[46]=_,t[47]=j):j=t[47];let M;return t[48]!==r||t[49]!==n.open||t[50]!==j?(M=(0,Y.jsx)(T,{open:p,onOpenChange:r,children:j}),t[48]=r,t[49]=n.open,t[50]=j,t[51]=M):M=t[51],M};function bt(e){return e.text}function xt(e){return e.lineNumber!==null}export{yt as default};
@@ -1 +0,0 @@
1
- import{n as e}from"./rolldown-runtime-hePW80VL.js";import{_ as t,c as n,d as r,s as i}from"./runtime-auth-BpCQ-dPr.js";import{c as a,i as o}from"./runtime-switch-CMiMO5Yj.js";import{n as s}from"./runtime-fetch-WgH0pROs.js";import{t as c}from"./dualLimitLru-D8Sphgua.js";import{a as l,c as u,i as d,n as f,o as p,t as m}from"./relay-image-stream-CqgxIcA5.js";var h=26214400,g=class extends Error{status;code;constructor(e,t,n=`Failed to upload assistant attachment`){super(n),this.name=`AssistantAttachmentUploadError`,this.status=e,this.code=t}},_=e=>typeof e==`object`&&!!e&&!Array.isArray(e),v=e=>[...new Uint8Array(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``),y=async e=>{let t;if(e instanceof ArrayBuffer)t=e;else if(ArrayBuffer.isView(e)){let n=e;t=n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)}else t=await e.arrayBuffer();return v(await crypto.subtle.digest(`SHA-256`,t))},b=e=>typeof e==`string`?e.split(`;`)[0]?.trim().toLowerCase():``,x=e=>{if(!Number.isSafeInteger(e)||e<0)throw new g(0,`rejected`,`Invalid attachment size`);if(e>26214400)throw new g(413,`too-large`)},ee=(e,t,n={})=>{if(!_(e))throw new g(0,`integrity`,`Attachment response was not a JSON object`);if(e.type!==`file`)throw new g(0,`integrity`,`Attachment response type must be file`);let r=typeof e.attachmentID==`string`?e.attachmentID.trim():``,i=typeof e.sha256==`string`?e.sha256.trim().toLowerCase():``,a=typeof e.size==`number`&&Number.isSafeInteger(e.size)?e.size:NaN,o=b(typeof e.mime==`string`?e.mime:``),s=typeof e.filename==`string`&&e.filename.trim()?e.filename.trim():void 0;if(!r)throw new g(0,`integrity`,`Attachment response missing attachmentID`);if(!/^[a-f0-9]{64}$/i.test(i))throw new g(0,`integrity`,`Attachment response missing sha256`);if(!Number.isSafeInteger(a)||a<0)throw new g(0,`integrity`,`Attachment response missing size`);if(!o)throw new g(0,`integrity`,`Attachment response missing mime`);if((n.enforceUploadLimit===!0||t)&&x(a),t){if(i!==t.sha256.toLowerCase())throw new g(0,`integrity`,`Attachment SHA-256 mismatch`);if(a!==t.size)throw new g(0,`integrity`,`Attachment size mismatch`);if(o!==t.mime)throw new g(0,`integrity`,`Attachment mime mismatch`)}return{type:`file`,attachmentID:r,sha256:i,size:a,mime:o,...s?{filename:s}:{}}},te=async(e,t,n,r)=>{let i=typeof e==`string`?e.trim():``,a=typeof n==`string`?n.trim():``;if(!i||!a)throw new g(0,`rejected`,`assistantID and uploadID are required`);if(!(t instanceof Blob))throw new g(0,`rejected`,`file must be a File or Blob`);let o=b(t.type||t.type)||`application/octet-stream`,c=t.type===o?t:new Blob([t],{type:o});x(c.size);let l=await y(c),u=typeof t.name==`string`&&t.name.trim()?t.name.trim():void 0,d;try{d=await s(`/api/openchamber/assistants/${encodeURIComponent(i)}/contact/attachments/${encodeURIComponent(a)}`,{method:`PUT`,headers:{"Content-Type":o,"X-Content-SHA256":l,"X-Content-Size":String(c.size),...u?{"X-Attachment-Filename":encodeURIComponent(u)}:{}},body:c,signal:r})}catch{throw new g(0,`unavailable`)}if(d.status===204||d.status===205)throw new g(d.status,`integrity`,`Attachment upload returned empty status`);if(d.status===413)throw new g(413,`too-large`);if(!d.ok)throw new g(d.status,d.status>=500||d.status===0?`unavailable`:`rejected`);let f=d.headers.get(`content-type`)?.toLowerCase()??``;if(f.includes(`text/html`)||f.includes(`text/plain`))throw new g(d.status,`integrity`,`Attachment upload returned non-JSON body`);let p;try{let e=await d.text();if(!e.trim())throw new g(d.status,`integrity`,`Attachment upload returned empty body`);if(!f.includes(`application/json`)&&!e.trim().startsWith(`{`))throw new g(d.status,`integrity`,`Attachment upload returned non-JSON body`);p=JSON.parse(e)}catch(e){throw e instanceof g?e:new g(d.status,`integrity`,`Attachment upload response was not valid JSON`)}return ee(p,{sha256:l,size:c.size,mime:o})},ne=e=>{try{return ee(e,void 0,{enforceUploadLimit:!1}),!0}catch{return!1}},re=e({ASSISTANT_ATTACHMENT_CACHE_MAX_BYTES:()=>S,ASSISTANT_ATTACHMENT_CACHE_MAX_ENTRIES:()=>200,ASSISTANT_ATTACHMENT_DISPLAY_MAX_BYTES:()=>C,AssistantAttachmentCacheError:()=>E,clearAssistantAttachmentCacheAll:()=>Te,clearAssistantAttachmentCacheForBearer:()=>we,clearAssistantAttachmentCacheScope:()=>Ce,getAssistantAttachmentBlob:()=>Oe,getAssistantAttachmentDisplay:()=>$,resolveAssistantAttachmentCacheScope:()=>R}),S=104857600,C=m,ie=`openchamber-assistant-attachments`,ae=2,w=`meta`,T=`data`,E=class extends Error{status;code;constructor(e,t,n=`Assistant attachment cache error`){super(n),this.name=`AssistantAttachmentCacheError`,this.status=e,this.code=t}},D=new c({maxEntries:200,maxBytes:S}),O=new Map,k=new Map,A=new Map,oe=null,se=null,j=0,M=null,N=!1,ce=Promise.resolve(),le=e=>[...new Uint8Array(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``),P=async e=>{let t=new TextEncoder().encode(e);return le(await crypto.subtle.digest(`SHA-256`,t))},F=async e=>{let t=ce,n;ce=new Promise(e=>{n=e}),await t.catch(()=>void 0);try{return await e()}finally{n()}},I=()=>(j+=1,j),ue=(e,t)=>e.transportIdentity===t.transportIdentity&&e.authScope===t.authScope&&e.authScopeKind===t.authScopeKind,L=(e,t)=>{if(e!==j)throw new E(0,`stale`,`Attachment cache epoch changed`)},R=async(e={})=>{let t=e.transportIdentity??o(),r=e.authGeneration??i(),a=(e.bearer??n()).trim();return a?{transportIdentity:t,authScope:`b:${await P(a)}`,authScopeKind:`bearer-hash`,authGeneration:r}:{transportIdentity:t,authScope:`m:${r}`,authScopeKind:`memory-ephemeral`,authGeneration:r}},z=(e,t,n)=>[e.transportIdentity,e.authScope,t.trim(),n.attachmentID.trim(),n.sha256.toLowerCase()].join(`\0`),de=(e,t)=>{let n={...t,lastAccess:Date.now()};return D.set(e,n,n.size),n},fe=()=>{try{if(typeof globalThis<`u`&&globalThis.indexedDB)return globalThis.indexedDB}catch{}return null},B=()=>N?Promise.resolve(null):M||(M=new Promise(e=>{let t=fe();if(!t){N=!0,e(null);return}try{let n=t.open(ie,ae);n.onerror=()=>{N=!0,M=null,e(null)},n.onupgradeneeded=()=>{let e=n.result;if(e.objectStoreNames.contains(`blobs`)&&e.deleteObjectStore(`blobs`),!e.objectStoreNames.contains(w)){let t=e.createObjectStore(w,{keyPath:`key`});t.createIndex(`lastAccess`,`lastAccess`),t.createIndex(`authScope`,`authScope`),t.createIndex(`transportIdentity`,`transportIdentity`)}e.objectStoreNames.contains(T)||e.createObjectStore(T,{keyPath:`key`})},n.onsuccess=()=>{let t=n.result;t.onversionchange=()=>{try{t.close()}catch{}M=null},e(t)}}catch{N=!0,M=null,e(null)}}),M),V=e=>new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error??Error(`idb-request-failed`))}),H=e=>new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error??Error(`idb-tx-failed`)),e.onabort=()=>n(e.error??Error(`idb-tx-aborted`))}),pe=async e=>{let t=await B();if(!t)return null;try{return await V(t.transaction(w,`readonly`).objectStore(w).get(e))??null}catch{return null}},me=async e=>{let t=await B();if(!t)return null;try{return await V(t.transaction(T,`readonly`).objectStore(T).get(e))??null}catch{return null}},U=async(e,t)=>{await F(async()=>{let n=await B();if(n)try{let r=n.transaction(w,`readwrite`),i=r.objectStore(w),a=await V(i.get(e));if(!a)return;i.put({...a,lastAccess:t}),await H(r)}catch{}})},W=async(e,t)=>{let n=e.transaction([w,T],`readwrite`),r=n.objectStore(w),i=n.objectStore(T),a=r.index(`lastAccess`),o=[];await new Promise((e,t)=>{let n=a.openCursor();n.onerror=()=>t(n.error??Error(`idb-cursor-failed`)),n.onsuccess=()=>{let t=n.result;if(!t){e();return}o.push(t.value),t.continue()}});let s=o.reduce((e,t)=>e+(t.size||0),0),c=o.length,l=Math.max(0,t.needBytes??0),u=Math.max(0,t.maxBytes-l);for(let e of o){if(c<=t.maxEntries&&s<=u)break;r.delete(e.key),i.delete(e.key),s-=e.size||0,--c}await H(n)},he=async(e,t,n,r)=>{if(n!==j)return!1;let i=await R();return n!==j||i.authScope!==r.authScope||i.transportIdentity!==r.transportIdentity?!1:F(async()=>{if(n!==j)return!1;let r=await B();if(!r)return!1;let i=async()=>{if(n!==j||(await W(r,{maxEntries:199,maxBytes:S,needBytes:e.size}),n!==j))return!1;let i=r.transaction([w,T],`readwrite`);return i.objectStore(w).put(e),i.objectStore(T).put({key:e.key,bytes:t}),await H(i),!0};try{return await i()}catch(t){if(!(t instanceof DOMException&&t.name===`QuotaExceededError`))return!1;try{return await W(r,{maxEntries:199,maxBytes:S,needBytes:e.size}),n===j&&await i()}catch{return!1}}})},G=async e=>{await F(async()=>{let t=await B();if(t)try{let n=t.transaction([w,T],`readwrite`),r=n.objectStore(w),i=n.objectStore(T),a=await V(r.getAllKeys());for(let t of a){if(typeof t!=`string`)continue;let n=await V(r.get(t));n&&e(n)&&(r.delete(t),i.delete(t))}await H(n)}catch{}})},K=async(e,t,n,r,i)=>{if(i!==j)return;let a={blob:t,sha256:n.sha256,size:n.size,mime:n.mime,lastAccess:Date.now()};if(D.set(e,a,a.size),r.authScopeKind!==`bearer-hash`||i!==j)return;let o=await t.arrayBuffer();i===j&&await he({key:e,sha256:n.sha256,size:n.size,mime:n.mime,lastAccess:a.lastAccess,transportIdentity:r.transportIdentity,authScope:r.authScope},o,i,r)},q=async(e,t,n,r)=>{L(r,n);let i=D.get(e);if(i&&i.sha256===t&&i.blob.size===i.size)return de(e,i),n.authScopeKind===`bearer-hash`&&U(e,Date.now()),i.blob;if(n.authScopeKind!==`bearer-hash`)return null;let a=await pe(e);if(L(r,n),!a||a.sha256!==t||a.size<=0||a.authScope!==n.authScope||a.transportIdentity!==n.transportIdentity)return null;let o=await me(e);if(L(r,n),!o||!(o.bytes instanceof ArrayBuffer)||o.bytes.byteLength!==a.size)return null;let s=await y(o.bytes);if(L(r,n),s!==t)return G(t=>t.key===e),null;let c={blob:new Blob([o.bytes],{type:a.mime||`application/octet-stream`}),sha256:a.sha256,size:a.size,mime:a.mime,lastAccess:Date.now()};return D.set(e,c,c.size),U(e,c.lastAccess),c.blob},J=e=>{if(e?.aborted)throw e.reason instanceof Error?e.reason:new E(0,`aborted`,`aborted`)},ge=(e,t)=>`/api/openchamber/assistants/${encodeURIComponent(e)}/contact/attachments/${encodeURIComponent(t)}`,_e=async(e,t,n,a,o,c)=>{J(n),L(o,a);let l;try{l=await s(ge(e,t.attachmentID),{method:`GET`,cache:`no-store`,signal:n})}catch(e){throw n.aborted?e instanceof Error?e:new E(0,`aborted`):new E(0,`unavailable`)}if(L(o,a),l.status===401||l.status===403)throw await Ce(a,`unauthorized`),i()===a.authGeneration&&r(),new E(l.status,`unauthorized`);if(l.status===413)throw new E(413,`too-large`);if(!l.ok)throw new E(l.status,l.status>=500?`unavailable`:`rejected`);let u=l.headers.get(`content-type`)?.split(`;`)[0]?.trim().toLowerCase()||t.mime||`application/octet-stream`,d=l.body,f=async(e,t)=>{try{await t?.cancel(e.message)}catch{}throw n.aborted,e};if(!d||typeof d.getReader!=`function`){let e=await l.blob();if(J(n),L(o,a),e.size>c)throw new E(413,`too-large`);if(e.size!==t.size)throw new E(0,`integrity`,`Attachment size failed verification`);let r=await y(e);if(L(o,a),r!==t.sha256.toLowerCase())throw new E(0,`integrity`,`Attachment SHA-256 mismatch`);return e.type===u?e:new Blob([e],{type:u})}let p=d.getReader(),m=[],h=0;try{for(;;){J(n),L(o,a);let{done:e,value:r}=await p.read();if(e)break;!r||r.byteLength===0||(h+=r.byteLength,h>c&&await f(new E(413,`too-large`),p),h>t.size&&await f(new E(0,`integrity`,`Attachment exceeded declared size`),p),m.push(r))}}catch(e){try{await p.cancel(e instanceof Error?e.message:`aborted`)}catch{}throw e}finally{try{p.releaseLock()}catch{}}if(L(o,a),h!==t.size)throw new E(0,`integrity`,`Attachment size mismatch`);let g=new Uint8Array(h),_=0;for(let e of m)g.set(e,_),_+=e.byteLength;let v=await y(g);if(L(o,a),v!==t.sha256.toLowerCase())throw new E(0,`integrity`,`Attachment SHA-256 mismatch`);return new Blob([g],{type:u})},Y=(e,t,n,r,i,a,o)=>{let s=O.get(e);if(!s||s.epoch!==i||!ue(s.scope,r)){let o=new AbortController;s={promise:_e(t,n,o.signal,r,i,a).finally(()=>{O.get(e)?.controller===o&&O.delete(e)}),controller:o,subscribers:0,scope:r,epoch:i},O.set(e,s)}return s.subscribers+=1,new Promise((t,n)=>{let r=!1,i=t=>{r||(r=!0,s.subscribers=Math.max(0,s.subscribers-1),t&&s.subscribers===0&&O.get(e)===s&&(s.controller.abort(o?.reason??Error(`aborted`)),O.delete(e)))},a=()=>{i(!0),n(o?.reason instanceof Error?o.reason:new E(0,`aborted`))};if(o?.aborted){a();return}o?.addEventListener(`abort`,a,{once:!0}),s.promise.then(e=>{o?.removeEventListener(`abort`,a),!r&&(r=!0,s.subscribers=Math.max(0,s.subscribers-1),t(e))},e=>{o?.removeEventListener(`abort`,a),!r&&(r=!0,s.subscribers=Math.max(0,s.subscribers-1),n(e))})})},ve=e=>{D.clear()},ye=(e,t)=>{for(let[n,r]of[...O.entries()])e(r,n)&&(r.controller.abort(Error(t)),O.delete(n))},be=e=>{for(let[t,n]of[...k.entries()])e(n,t)&&(d(n.url),l(n.url),k.delete(t));for(let[t]of[...A.entries()])e({url:``,refs:0,cacheKey:t,epoch:0},t)&&A.delete(t)},xe=()=>{for(let e of k.values())d(e.url),l(e.url);k.clear(),A.clear()},Se=e=>{for(let t of O.values())t.controller.abort(Error(e));O.clear()},Ce=async(e,t=`scope-cleared`)=>{let n=typeof e==`object`&&e?e:await R(),r=typeof e==`string`?e:t;I(),ye(e=>e.scope.authScope===n.authScope&&e.scope.transportIdentity===n.transportIdentity,r),be(e=>{let t=e.cacheKey.split(`\0`);return t[0]===n.transportIdentity&&t[1]===n.authScope}),ve(()=>!0),await G(e=>e.authScope===n.authScope&&e.transportIdentity===n.transportIdentity)},we=async(e,t=`forget-bearer`)=>{let n=e.trim();if(!n)return;let r=`b:${await P(n)}`;I(),ye(e=>e.scope.authScope===r,t),be(e=>e.cacheKey.split(`\0`)[1]===r),ve(()=>!0),await G(e=>e.authScope===r)},Te=async(e=`cleared`)=>{I(),Se(e),xe(),D.clear(),await F(async()=>{let e=await B();if(e)try{let t=e.transaction([w,T],`readwrite`);t.objectStore(w).clear(),t.objectStore(T).clear(),await H(t)}catch{}})},X=e=>{I(),Se(e),xe(),D.clear()},Ee=e=>{if(e.reason===`endpoint-switch`){X(`endpoint-switch`);return}if(X(e.reason===`invalidate`?`auth-invalidate`:`auth-credential`),e.previousBearerDigest){let t=`b:${e.previousBearerDigest}`;G(e=>e.authScope===t);return}let t=o();G(e=>e.transportIdentity===t)},De=()=>{typeof window>`u`||(oe||=a(()=>{X(`transport-changed`)}),se||=t(e=>{Ee(e)}))},Z=(e,t)=>{if(!ne(e))throw new E(0,`rejected`,`Invalid attachment descriptor`);if(e.size>t)throw new E(413,`too-large`);return{...e,sha256:e.sha256.toLowerCase()}},Oe=async(e,t,n={})=>{De(),J(n.signal);let r=typeof e==`string`?e.trim():``;if(!r)throw new E(0,`rejected`,`assistantID is required`);let i=Z(t,h),a=j,o=await R();L(a,o);let s=z(o,r,i),c=await q(s,i.sha256,o,a);if(c)return J(n.signal),L(a,o),c;let l=await Y(s,r,i,o,a,h,n.signal);return J(n.signal),L(a,o),await K(s,l,{sha256:i.sha256,size:i.size,mime:i.mime||l.type},o,a),L(a,o),l},ke=(e,t,n)=>{if(!f(t)||!p(t))throw l(t),new E(0,`unavailable`,`Display URL is not live`);let r=k.get(e);(!r||r.url!==t||r.epoch!==n)&&(r&&r.url!==t&&l(r.url),r={url:t,refs:0,cacheKey:e,epoch:n},k.set(e,r)),r.refs+=1;let i=!1;return{url:t,release:()=>{if(i)return;i=!0;let n=k.get(e);if(d(t),!n||n.url!==t){l(t);return}--n.refs,n.refs<=0&&(k.delete(e),l(n.url))}}},Ae=async(e,t,n,r,i,a)=>{let o=k.get(e);if(o&&o.epoch===i&&f(o.url))return o.url;let s=Z(n,C),c=z(a,t.trim(),s),l=await q(c,s.sha256,a,i);J(r),L(i,a),l||(l=await Y(c,t.trim(),s,a,i,s.size>26214400?C:h,r),L(i,a),J(r),s.size>26214400?D.set(c,{blob:l,sha256:s.sha256,size:s.size,mime:s.mime||l.type,lastAccess:Date.now()},s.size):(await K(c,l,{sha256:s.sha256,size:s.size,mime:s.mime||l.type},a,i),L(i,a))),J(r),L(i,a);let d=await u(l,r,{mimeType:s.mime||l.type});return J(r),L(i,a),d},Q=(e,t)=>{e.releasedOrphan||e.subscribers>0||(e.releasedOrphan=!0,e.url&&=(l(e.url),null),A.get(t)===e&&A.delete(t))},$=async(e,t,n={})=>{De(),J(n.signal);let r=typeof e==`string`?e.trim():``;if(!r)throw new E(0,`rejected`,`assistantID is required`);let i=Z(t,C),a=j,o=await R();L(a,o);let s=z(o,r,i),c=A.get(s);if(!c||c.epoch!==a){c&&c.epoch!==a&&(c.controller.abort(Error(`stale-epoch`)),Q(c,s));let e=new AbortController,t={promise:Promise.resolve(``),controller:e,subscribers:0,epoch:a,url:null,releasedOrphan:!1};t.promise=Ae(s,r,i,e.signal,a,o).then(e=>{if(t.url=e,t.subscribers===0||t.epoch!==j||t.releasedOrphan)throw l(e),t.url=null,t.releasedOrphan=!0,A.get(s)===t&&A.delete(s),new E(0,`stale`,`Display URL orphaned before lease`);return e}).catch(e=>{throw A.get(s)===t&&A.delete(s),t.url&&=(l(t.url),null),t.releasedOrphan=!0,e}).finally(()=>{A.get(s)===t&&t.subscribers===0&&Q(t,s)}),c=t,A.set(s,c)}return c.subscribers+=1,new Promise((e,t)=>{let r=!1,i=e=>{c.subscribers=Math.max(0,c.subscribers-1),c.subscribers===0&&(e&&c.controller.abort(n.signal?.reason??Error(`aborted`)),Q(c,s),A.get(s)===c&&A.delete(s))},o=()=>{r||(r=!0,i(!0),t(n.signal?.reason instanceof Error?n.signal.reason:new E(0,`aborted`)))};if(n.signal?.aborted){o();return}n.signal?.addEventListener(`abort`,o,{once:!0}),c.promise.then(i=>{if(n.signal?.removeEventListener(`abort`,o),!r){r=!0,c.subscribers=Math.max(0,c.subscribers-1),c.subscribers===0&&A.get(s)===c&&A.delete(s);try{if(c.epoch!==j)throw l(i),new E(0,`stale`,`Display epoch changed`);e(ke(s,i,a))}catch(e){t(e)}}},e=>{n.signal?.removeEventListener(`abort`,o),!r&&(r=!0,i(!1),t(e))})})};export{te as i,Oe as n,$ as r,re as t};
@@ -1 +0,0 @@
1
- import{b as e}from"./runtime-auth-BpCQ-dPr.js";import{l as t,n,r}from"./runtime-switch-CMiMO5Yj.js";import{n as i}from"./runtime-fetch-WgH0pROs.js";import{sn as a}from"./persistence-BKszKaoQ.js";import{i as o,l as s,m as c,n as l,p as u,r as d}from"./desktopHosts-C0e7Nes2.js";var f=e=>e!==`ok`&&e!==`update-recommended`,p=e=>e.id===`local`?`local`:`host:${e.id}`,m=e=>r()===p(e),h=async(n,r)=>{if(!a())return{ok:!1,status:{status:`unreachable`,latencyMs:0},reason:`unsupported`};let i=u(s(n))||``;if(!i&&!n.relay)return{ok:!1,status:{status:`unreachable`,latencyMs:0},reason:`unreachable`};let o=(r,i)=>{i&&e({relayUrl:r.relayUrl,serverId:r.serverId,hostEncPubJwk:r.hostEncPubJwk},i),t({apiBaseUrl:S(),clientToken:n.clientToken||null,runtimeKey:p(n),relay:r}),w(n.id)},d=e=>{t({apiBaseUrl:e,clientToken:n.clientToken||null,requestHeaders:n.requestHeaders||null,runtimeKey:p(n)})},m={status:`unreachable`,latencyMs:0},h=null,g;if(i){let e=await l(i,{clientToken:n.clientToken||null,requestHeaders:n.requestHeaders||null,expectedServerId:n.relay?.serverId||null}).catch(()=>({status:`unreachable`,latencyMs:0}));m={status:e.status,latencyMs:e.latencyMs},f(e.status)||(h=`direct`)}if(!h&&n.relay){let e=await c(n.relay,{keepTunnel:!0,clientToken:n.clientToken||null}).catch(()=>({status:`unreachable`,latencyMs:0}));e.status===`ok`?(m={status:e.status,latencyMs:e.latencyMs,via:`relay`},h=`relay`,g=`tunnel`in e?e.tunnel:void 0):(!i||e.status===`auth`)&&(m={status:e.status,latencyMs:e.latencyMs})}return h?h===`relay`&&n.relay?(o(n.relay,g),{ok:!0,via:`relay`,status:m}):(d(i),{ok:!0,via:`direct`,status:m}):{ok:!1,status:m,reason:`unreachable`}},g=5e3,_=1500,v=e=>e===`ok`||e===`update-recommended`,y=!1,b=()=>{if(typeof window>`u`)return``;let e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof e==`string`?e.trim():``},x=e=>{if(!e||e===`null`)return!1;try{let t=new URL(e);return(t.protocol===`http:`||t.protocol===`https:`)&&t.origin!==`null`}catch{return!1}},S=()=>{if(typeof window>`u`)return``;let e=window.location.origin;if(x(e))return e;let t=b();return x(t)?t:``},C=async e=>{if(!a()||y)return;let s=`host:${e}`;if(r()!==s)return;let c=n(),f=()=>r()===s&&n()===c;y=!0;try{let n=await d().catch(()=>null);if(!f())return;let r=n?.hosts.find(t=>t.id===e);if(!n||!r?.relay)return;let a=r.apiUrl?u(r.apiUrl):null;if(a&&a.startsWith(`https://`))return;let c=await i(`/api/client-auth/connection/candidates`).catch(()=>null);if(!c?.ok)return;let p=await c.json().catch(()=>null);if(!f()||!p||p.serverId!==r.relay.serverId)return;let m=Array.isArray(p.candidates)?p.candidates:[],h=[];for(let e of m){if(!e||typeof e!=`object`)continue;let t=e;if(t.type!==`lan`||typeof t.url!=`string`)continue;let n=u(t.url);n&&!h.includes(n)&&h.push(n)}if(h.length===0)return;let g=a&&h.includes(a)?a:h[0];if(g!==a&&await o({hosts:n.hosts.map(t=>t.id===e?{...t,apiUrl:g}:t),defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted}).catch(()=>void 0),!f()||!v((await l(g,{clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,expectedServerId:r.relay.serverId}).catch(()=>({status:`unreachable`,latencyMs:0}))).status)||!f())return;t({apiBaseUrl:g,clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,runtimeKey:s})}finally{y=!1}},w=e=>{typeof window>`u`||window.setTimeout(()=>{C(e).catch(()=>void 0)},g)},T=async e=>{if(!a())return;let i=r(),o=n(),c=()=>r()===i&&n()===o,f=await d().catch(()=>null);if(!f||!c())return;let m=e||(f.defaultHostId===`local`?null:f.defaultHostId);if(!m)return;let h=f.hosts.find(e=>e.id===m);if(!h?.relay)return;let g=p(h);if(r()===g)return;let y=e=>{t({apiBaseUrl:e,clientToken:h.clientToken||null,requestHeaders:h.requestHeaders||null,runtimeKey:g})},b=()=>{t({apiBaseUrl:S(),clientToken:h.clientToken||null,runtimeKey:g,relay:h.relay??void 0}),w(h.id)},x=h.apiUrl?u(s(h)):null;if(!x){b();return}let C=e=>v(e.status),T=l(x,{clientToken:h.clientToken||null,requestHeaders:h.requestHeaders||null,expectedServerId:h.relay.serverId}).catch(()=>({status:`unreachable`,latencyMs:0})),E=await Promise.race([T,new Promise(e=>setTimeout(()=>e(null),_))]);if(c()){if(E){if(C(E)){y(x);return}b();return}b()}};export{h as i,m as n,p as r,T as t};
@@ -1 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{p as t}from"./runtime-auth-BpCQ-dPr.js";import{c as n,f as r,i}from"./runtime-switch-CMiMO5Yj.js";import{n as a}from"./runtime-fetch-WgH0pROs.js";import{it as o}from"./vendor-base-ui-CdzJ6My_.js";import{St as s}from"./platform-CgwxwfA4.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-CWSs9Baz.js";var d=`openchamber:close-embedded-session-chat`,f=`openchamber:embedded-visibility`,p=`openchamber:embedded-visibility-request`,m=e=>new URLSearchParams(e).get(`ocPanel`)===`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(`ocPanel`,`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(`ocPanel`)===`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:`openchamber`},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(`openchamber: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 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{i as t}from"./runtime-switch-CMiMO5Yj.js";import{h as n,m as r}from"./persistence-BKszKaoQ.js";import{it as i}from"./vendor-base-ui-CdzJ6My_.js";import{n as a}from"./vendor-react-BP2cRVqX.js";import{s as o}from"./vendor-tanstack-react-query-CdqCAt40.js";import{n as s}from"./useRuntimeAPIs-Cx8S1HLz.js";var c=a(),l=e(i(),1),u=e=>e,d=(e,r=t())=>n.files.content(e.scopeDirectory,e.path,u(e.options),r),f=(e,r,i=t())=>({queryKey:n.files.directory(r.scopeDirectory,r.directory,r.respectGitignore,i),queryFn:async()=>{if(!r.directory)throw Error(`A directory is required to list files`);return r.respectGitignore===void 0?e.listDirectory(r.directory):e.listDirectory(r.directory,{respectGitignore:r.respectGitignore})}}),p=(e,r,i=t())=>({queryKey:n.files.search(r.directory,r.query,r.maxResults,r.includeHidden,r.respectGitignore,i),queryFn:async()=>{if(!r.directory)throw Error(`A directory is required to search files`);let t={directory:r.directory,query:r.query.trim(),maxResults:r.maxResults,...r.includeHidden===void 0?{}:{includeHidden:r.includeHidden},...r.respectGitignore===void 0?{}:{respectGitignore:r.respectGitignore}};return e.search(t)}}),m=(e,n,r=t())=>({queryKey:d(n,r),queryFn:async()=>{if(!n.path)throw Error(`A file path is required to read file content`);if(!e.readFile)throw Error(`File content reads are unavailable in this runtime`);return(await(n.options===void 0?e.readFile(n.path):e.readFile(n.path,n.options))).content}}),h=(e,t,n,r)=>{e.setQueryData(d(t,n),r)},g=(e,r,i=t())=>({queryKey:n.files.stat(r.scopeDirectory,r.path,u(r.options),i),queryFn:async()=>{if(!r.path)throw Error(`A file path is required to read file status`);if(!e.statFile)throw Error(`File status reads are unavailable in this runtime`);return r.options===void 0?e.statFile(r.path):e.statFile(r.path,r.options)}}),_=(e,n)=>{let r=(0,c.c)(9),i;r[0]===n?i=r[1]:(i=n===void 0?{}:n,r[0]=n,r[1]=i);let a=i,{files:l}=s(),u,d;if(r[2]!==l||r[3]!==e){let n=t();d=o,u=f(l,e,n),r[2]=l,r[3]=e,r[4]=u,r[5]=d}else u=r[4],d=r[5];let p;return r[6]!==a||r[7]!==u?(p={...u,...a},r[6]=a,r[7]=u,r[8]=p):p=r[8],d(p)},v=(e,n)=>{let r=(0,c.c)(9),i;r[0]===n?i=r[1]:(i=n===void 0?{}:n,r[0]=n,r[1]=i);let a=i,{files:l}=s(),u,d;if(r[2]!==l||r[3]!==e){let n=t();d=o,u=p(l,e,n),r[2]=l,r[3]=e,r[4]=u,r[5]=d}else u=r[4],d=r[5];let f;return r[6]!==a||r[7]!==u?(f={...u,...a},r[6]=a,r[7]=u,r[8]=f):f=r[8],d(f)},y=(e,n)=>{let r=(0,c.c)(9),i;r[0]===n?i=r[1]:(i=n===void 0?{}:n,r[0]=n,r[1]=i);let a=i,{files:l}=s(),u,d;if(r[2]!==l||r[3]!==e){let n=t();d=o,u=m(l,e,n),r[2]=l,r[3]=e,r[4]=u,r[5]=d}else u=r[4],d=r[5];let f;return r[6]!==a||r[7]!==u?(f={...u,...a},r[6]=a,r[7]=u,r[8]=f):f=r[8],d(f)},b=2e3,x=(e,n)=>{let i=(0,c.c)(19),a;i[0]===n?a=i[1]:(a=n===void 0?{}:n,i[0]=n,i[1]=a);let u=a,{files:f}=s(),p,m,h,_;i[2]!==f||i[3]!==e||i[4]!==u.enabled?(_=t(),p=!!(u.enabled&&e.path&&f.statFile),h=o,m=g(f,e,_),i[2]=f,i[3]=e,i[4]=u.enabled,i[5]=p,i[6]=m,i[7]=h,i[8]=_):(p=i[5],m=i[6],h=i[7],_=i[8]);let v=u.intervalMs??b,y;i[9]!==p||i[10]!==m||i[11]!==v?(y={...m,enabled:p,refetchInterval:v,refetchIntervalInBackground:!1,staleTime:0},i[9]=p,i[10]=m,i[11]=v,i[12]=y):y=i[12];let x=h(y),S=l.useRef(null),C=l.useRef(null),w;i[13]!==p||i[14]!==e||i[15]!==u.client||i[16]!==x||i[17]!==_?(w=()=>{let t=x.data;if(!p||!t)return;S.current!==e.path&&(S.current=e.path??null,C.current=null);let n=`${t.size}:${t.mtimeMs??``}`,i=C.current;C.current=n,i!==null&&i!==n&&(u.client??r).invalidateQueries({queryKey:d(e,_)})},i[13]=p,i[14]=e,i[15]=u.client,i[16]=x,i[17]=_,i[18]=w):w=i[18],l.useEffect(w)};export{_ as a,y as i,g as n,v as o,h as r,x as s,d as t};