@openchambery/web 1.18.2-beta.21 → 1.18.2-beta.23

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 (47) hide show
  1. package/dist/assets/{AssistantView-C00aiEHK.js → AssistantView-BwOGfQdf.js} +1 -1
  2. package/dist/assets/{ChatContainer-BDFeDKu-.js → ChatContainer-BhuJ17NV.js} +5 -5
  3. package/dist/assets/{DiagramView-CUfSFI3e.js → DiagramView-BZDrlrBa.js} +1 -1
  4. package/dist/assets/{MarkdownRendererImpl-Cen6E9Lj.js → MarkdownRendererImpl-_B10-P_d.js} +1 -1
  5. package/dist/assets/{MobileDetailNavigation-DILi0tN7.js → MobileDetailNavigation-B4ou1pP8.js} +1 -1
  6. package/dist/assets/{MobileShareBridge-PZMRiieI.js → MobileShareBridge-BFvNHNJt.js} +1 -1
  7. package/dist/assets/{MobileSurface-BLYcR0tO.js → MobileSurface-DWSNe5Oc.js} +1 -1
  8. package/dist/assets/{MultiRunWindow-D_2mWZyv.js → MultiRunWindow-C_n1QW0Q.js} +1 -1
  9. package/dist/assets/{OverlayScrollbar-BgMLtMIq.js → OverlayScrollbar-Mi_WH4jv.js} +1 -1
  10. package/dist/assets/{SettingsView-CbDBfQp1.js → SettingsView-BXzpHbAd.js} +1 -1
  11. package/dist/assets/{SettingsWindow-Br7XLcSd.js → SettingsWindow-ChZzPrmx.js} +1 -1
  12. package/dist/assets/{TerminalView-CM5jRKlj.js → TerminalView-DHnpuSPa.js} +1 -1
  13. package/dist/assets/{ToolOutputDialog-D3U6aTZ4.js → ToolOutputDialog-C1R-GCPB.js} +1 -1
  14. package/dist/assets/{appThemeRegistry-CDxBJNNB.js → appThemeRegistry-Ck9e8eEr.js} +2 -2
  15. package/dist/assets/assistant-guide-hero-wide-DiFIThB0.jpg +0 -0
  16. package/dist/assets/{context-menu-DBOMervd.js → context-menu-CjVxtovr.js} +1 -1
  17. package/dist/assets/{gitApi-BQT3QXD2.js → gitApi-Ctgr4Y9i.js} +1 -1
  18. package/dist/assets/{insertionBoundaries-9a0RuIDc.js → insertionBoundaries-BEvkmerk.js} +1 -1
  19. package/dist/assets/{main-CEqSDnE2.js → main-DakgzbmV.js} +2 -2
  20. package/dist/assets/{main-BGfX81Y9.js → main-mPlXr40-.js} +4 -4
  21. package/dist/assets/{miniChat-CKucSAhg.js → miniChat-BvWaAk95.js} +2 -2
  22. package/dist/assets/{mobile-C4bTWKry.js → mobile-BBcoCHM3.js} +2 -2
  23. package/dist/assets/{multirun-DeNtSkgb.js → multirun-Dc_oCEXn.js} +1 -1
  24. package/dist/assets/{projectMeta-BunN9pH5.js → projectMeta-BbjPDSpU.js} +2 -2
  25. package/dist/assets/radio-CQrbmLB7.js +1 -0
  26. package/dist/assets/{renderElectronMiniChatApp-D8-FDgWE.js → renderElectronMiniChatApp-C7FdCciX.js} +2 -2
  27. package/dist/assets/{renderMobileApp-CdU0aJ-e.js → renderMobileApp-Bhv28XIT.js} +5 -5
  28. package/dist/assets/{runtimeEndpointReset-CK1GhIsm.js → runtimeEndpointReset-DhSRMf7G.js} +1 -1
  29. package/dist/assets/{sortable-tabs-strip-pWlBorwQ.js → sortable-tabs-strip-yvKEEQEL.js} +1 -1
  30. package/dist/assets/{src-8kQFmtjw.css → src-7UHu0sNZ.css} +1 -1
  31. package/dist/assets/{useAppFontEffects-IEUQDvE8.js → useAppFontEffects-BiZhEY4g.js} +2 -2
  32. package/dist/assets/{useDesktopWindowControlsLayout-MlqJX89k.js → useDesktopWindowControlsLayout-D3lc4TXT.js} +1 -1
  33. package/dist/assets/{useEffectiveDirectory-GbhkdO6m.js → useEffectiveDirectory-DD7JGLuB.js} +1 -1
  34. package/dist/assets/{useMobileNavigationStore-DQHF_ETu.js → useMobileNavigationStore-DEUCakMd.js} +1 -1
  35. package/dist/assets/{useSessionAutoCleanup-BuU_S_Sh.js → useSessionAutoCleanup-X6napv6d.js} +1 -1
  36. package/dist/assets/{useWorkerHighlightedLines-Ca6OgNHF.js → useWorkerHighlightedLines-B6gvEO9K.js} +1 -1
  37. package/dist/index.html +2 -2
  38. package/dist/mini-chat.html +2 -2
  39. package/dist/mobile.html +2 -2
  40. package/package.json +1 -1
  41. package/server/lib/assistants/DOCUMENTATION.md +2 -2
  42. package/server/lib/assistants/history-state.js +23 -0
  43. package/server/lib/assistants/history-state.test.js +51 -0
  44. package/server/lib/assistants/service.js +37 -11
  45. package/server/lib/assistants/service.test.js +106 -2
  46. package/dist/assets/assistant-guide-hero-BeUHQcxE.jpg +0 -0
  47. package/dist/assets/radio-Bziafaje.js +0 -1
@@ -1,7 +1,7 @@
1
1
  const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-capacitor-app-PzT84wSx.js","assets/rolldown-runtime-C0FnF6B9.js","assets/vendor-aparajita-capacitor-secure-storage-CjQdwfjS.js"])))=>i.map(i=>d[i]);
2
- import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{D as t,E as n,F as r,H as i,M as a,T as o,d as s,h as c,j as l,k as u,m as d,s as f,t as p,v as m,w as h}from"./useUIStore-5agS8bsW.js";import{$ as g,$t as _,Ft as v,Mt as y,Xt as b,Yt as x,Zt as S,c as C,en as w,g as T,h as E,kn as D,m as O,n as ee,qt as k,r as A,t as j,u as M,xn as N}from"./persistence-D1lIuyqO.js";import{c as P,d as F,f as I,h as L,i as te,l as R,m as ne,n as z,o as B,p as V,r as H,s as re,v as ie}from"./desktopHosts-ZK_vkdzL.js";import{i as U}from"./desktopRelayRestore-CewM6-g5.js";import{a as ae,i as oe}from"./vendor-zustand-B4dlGEM2.js";import{nt as W,rt as se,tt as G}from"./vendor-base-ui-CnHfUmDN.js";import{kt as ce,wt as le,yt as ue}from"./gitApiHttp-BxGAFLTf.js";import{o as de}from"./vendor-aparajita-capacitor-secure-storage-CjQdwfjS.js";import{n as fe}from"./vendor-react-DLPElpoQ.js";import{c as pe}from"./vendor-tanstack-react-query-D7pys_c9.js";import{t as me}from"./vendor-sonner-DVzioF3d.js";import{a as he,n as ge}from"./vendor-reactuses-core-DDoDDyM9.js";import{c as _e,n as ve,r as ye,s as be,t as xe}from"./clipboard-BnElHSnO.js";import{i as Se,t as Ce}from"./store-CUWqzRt7.js";import{Ao as we,Fa as Te,Fr as Ee,Ft as De,H as Oe,I as ke,Ji as Ae,Qi as je,R as Me,Ra as Ne,St as Pe,Tn as Fe,V as Ie,W as Le,Xi as K,Xr as Re,_t as ze,bn as Be,bt as Ve,ea as He,ei as Ue,go as We,gt as Ge,hr as Ke,jo as qe,ko as Je,l as q,mr as Ye,mt as Xe,na as Ze,pt as Qe,ta as $e,un as et,vr as tt,vt as nt,xt as rt,z as it}from"./useMobileNavigationStore-DQHF_ETu.js";import{t as at}from"./utils-BxJEIWv5.js";import{n as J}from"./Icon-DiIuWOuC.js";import{a as ot,n as st,o as ct,r as lt,t as ut}from"./dialog-COrLBm9O.js";import{t as dt}from"./button-DaAoVF4X.js";import{n as ft}from"./gitApi-BQT3QXD2.js";import{a as pt}from"./vendor-simplewebauthn-browser-Dwhcdg_5.js";import{N as mt,c as ht}from"./projectMeta-BunN9pH5.js";import{t as gt}from"./input-XiL2-2gG.js";import{i as _t,n as vt,t as yt}from"./tooltip-BLugzWq-.js";import{A as bt,B as xt,I as St,J as Ct,K as wt,P as Tt,T as Et,b as Dt,n as Ot,q as kt,t as At,v as jt,w as Mt,x as Nt,y as Pt}from"./useSessionAutoCleanup-BuU_S_Sh.js";import{n as Ft,r as It}from"./useThemeSystem-DMzWVJaW.js";import{B as Lt,Q as Rt,U as zt,W as Bt,Y as Vt,z as Y}from"./radio-Bziafaje.js";import{i as Ht}from"./OverlayScrollbar-BgMLtMIq.js";import{C as Ut,S as Wt,b as Gt,x as Kt,y as qt}from"./markdownTheme-D-aLQZaM.js";import{D as Jt,J as Yt,X as Xt,Y as Zt,_ as Qt,et as $t,g as en,q as tn,s as nn,tt as rn,v as an}from"./ChatContainer-BDFeDKu-.js";import{r as on}from"./useRuntimeAPIs-DSLXJybW.js";import{t as sn}from"./useEffectiveDirectory-GbhkdO6m.js";import{n as cn,t as ln}from"./useFontPreferences-92Qg-98H.js";typeof window<`u`&&(window.__opencodeDebug={getLastAssistantMessage(){let e=q.getState().currentSessionId;if(!e)return null;let t=He(e);if(!t||t.length===0)return null;for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role===`assistant`){let e=($e(n.id)||[]).map(e=>{let t={id:e.id,type:e.type};return e.type===`text`?(t.text=e.text,t.textLength=e.text?.length||0):e.type===`tool`?(t.tool=e.tool,t.state=e.state?.status):(e.type===`step-start`||e.type===`step-finish`)&&(t.isStepMarker=!0),t}),t=e.some(e=>e.type===`text`&&e.text&&e.text.trim().length>0),r=e.some(e=>e.type===`tool`),i=e.some(e=>e.type===`step-start`||e.type===`step-finish`),a=e.length===0,o=!t&&!r&&(!a||i),s={messageId:n.id,role:n.role,timestamp:n.time?.created||0,partsCount:e.length,parts:e,isEmpty:a,isEmptyResponse:o,raw:n};return s.messageId,s.partsCount,s.isEmpty,s.isEmptyResponse,s.isEmpty&&console.warn(`[WARNING] Message has NO parts!`),s.isEmptyResponse&&(console.warn(`[WARNING] Message has parts but NO meaningful content (empty text, no tools)!`),i&&!t&&!r&&console.warn(`[CRITICAL] CLAUDE EMPTY RESPONSE BUG: Only step-start/step-finish markers, no actual content!`)),s}}return null},truncateString(e,t=80){return!e||typeof e!=`string`||e.length<=t?e:e.substring(0,t)+`…`},truncateMessages(e){return e.map(e=>({...e,parts:($e(e.id)||[]).map(e=>{let t={...e};return`text`in e&&(t.text=this.truncateString(e.text)),`textPreview`in e&&(t.textPreview=this.truncateString(e.textPreview)),e.state&&(t.state={...e.state},`output`in e.state&&(t.state.output=this.truncateString(e.state.output)),`error`in e.state&&(t.state.error=this.truncateString(e.state.error)),e.state.metadata&&`preview`in e.state.metadata&&(t.state.metadata={...e.state.metadata,preview:this.truncateString(e.state.metadata.preview)})),t})}))},getAllMessages(e=!1){let t=q.getState().currentSessionId;if(!t)return[];let n=He(t);return`${n.length}`,n.forEach((e,t)=>{let n=$e(e.id)||[];`${t}${e.role}${e.id}${n.length}`}),e?this.truncateMessages(n):n},async getAppStatus(){let e=ue.getState(),t=q.getState(),n=We.getState(),r=e.currentDirectory||null,i=ce.getDirectory()??null,a=Ze(),o=new Set,s={};a.forEach(e=>{let t=e.directory;typeof t==`string`&&t.trim().length>0?(o.add(t),s[t]=(s[t]??0)+1):s[`(none)`]=(s[`(none)`]??0)+1});let c=(()=>{if(typeof window>`u`)return{available:!1};try{return{available:!0,lastDirectory:window.localStorage.getItem(`lastDirectory`),homeDirectory:window.localStorage.getItem(`homeDirectory`)}}catch(e){return{available:!1,error:e instanceof Error?e.message:String(e)}}})(),l=N(),u=typeof window<`u`&&!!window.__OPENCHAMBER_ELECTRON__,d=async e=>{try{return await e.json()}catch{return null}},f=async e=>{try{return await e.text()}catch{return null}},p=async e=>{try{let t=await D(e);return t.ok?await d(t):{status:t.status}}catch(e){return{error:e instanceof Error?e.message:String(e)}}},m=null,h=null,g=null,_=null;try{let e=await ce.getSdkClient().path.get(r?{directory:r}:void 0);m=e.error?{error:e.error}:e.data}catch(e){m={error:e instanceof Error?e.message:String(e)}}try{let e=await ce.getSdkClient().project.current(r?{directory:r}:void 0);h=e.error?{error:e.error}:e.data}catch(e){h={error:e instanceof Error?e.message:String(e)}}g=await p(`/api/config/settings`);try{let e=await D(`/api/health`),t=e.headers.get(`content-type`)||``,n=await f(e),r=t.toLowerCase().includes(`application/json`),i=null;if(r&&n)try{let e=JSON.parse(n);e&&typeof e==`object`&&!Array.isArray(e)&&(i=e)}catch{i=null}_={status:e.status,ok:e.ok,contentType:t,type:r?`json`:`html`,openCodePort:i?.openCodePort??null,openCodeRunning:i?.openCodeRunning??null,openCodeSecureConnection:i?.openCodeSecureConnection??null,openCodeAuthSource:i?.openCodeAuthSource??null,isOpenCodeReady:i?.isOpenCodeReady??null,lastOpenCodeError:i?.lastOpenCodeError??null,preview:n?n.slice(0,120):null}}catch(e){_={error:e instanceof Error?e.message:String(e)}}let v={isGitRepo:null};if(r)try{v.isGitRepo=await ft(r)}catch(e){v={isGitRepo:null,error:e instanceof Error?e.message:String(e)}}let y=n.projects.map(e=>({id:e.id,path:e.path,label:e.label}));return{runtime:{platform:l?.runtime?.platform??null,isDesktop:u,isVSCode:!!l?.runtime?.isVSCode,hasRuntimeApis:!!l,desktopServerOrigin:null},location:typeof window<`u`?{href:window.location?.href??null,origin:window.location?.origin??null}:null,directories:{currentDirectory:r,opencodeDirectory:m?.directory||m?.worktree||i,homeDirectory:e.homeDirectory||null,isHomeReady:e.isHomeReady,hasPersistedDirectory:e.hasPersistedDirectory,isSwitchingDirectory:e.isSwitchingDirectory},projects:{total:n.projects.length,activeProjectId:n.activeProjectId,samples:y},sessions:{total:a.length,currentSessionId:t.currentSessionId,lastLoadedDirectory:t.lastLoadedDirectory,uniqueDirectories:o.size,directorySamples:Array.from(o).slice(0,5),directoryCounts:s},worktrees:{available:t.availableWorktrees.length,metadataEntries:t.worktreeMetadata.size},git:v,localStorage:c,opencode:{pathInfo:m,projectInfo:h,health:_},openchamber:{settingsInfo:g}}},async buildDiagnosticsReport(){let e=await this.getAppStatus();return JSON.stringify(e,null,2)},async copyTextToClipboard(e){return xe(e)},async copyDiagnosticsReport(){let e=await this.buildDiagnosticsReport();return{...await this.copyTextToClipboard(e),report:e}},checkLastMessage(){let e=this.getLastAssistantMessage();if(!e)return!1;let t=e.isEmpty||e.isEmptyResponse;return t&&(console.error(`[ALERT] PROBLEMATIC MESSAGE DETECTED!`),e.messageId,e.isEmpty,e.isEmptyResponse,e.partsCount,e.parts.length>0&&e.parts),t},getStreamingState(){let e=q.getState(),t=Be.getState(),n=e.currentSessionId?t.streamingMessageIds.get(e.currentSessionId)??null:null;return Array.from(t.streamingMessageIds.entries()),Array.from(t.messageStreamStates.entries()),{streamingMessageId:n,streamingMessageIds:t.streamingMessageIds,streamStates:t.messageStreamStates}},findEmptyMessages(){let e=q.getState().currentSessionId;if(!e)return[];let t=He(e).filter(e=>e.role===`assistant`).filter(e=>{let t=$e(e.id)||[],n=t.some(e=>e.type===`text`&&e.text&&e.text.trim().length>0),r=t.some(e=>e.type===`tool`);return t.length===0||!n&&!r});return`${t.length}`,t.forEach((e,t)=>{let n=$e(e.id)||[];`${t}`,e.id,n.length,e.providerID,e.modelID,e.time?.created}),t},showRetryHelp(){},analyzeMessageCompletionConsistency(e={}){let{includeNonAssistant:t=!1,verbose:n=!0,maxTableRows:r=25}=e,i=q.getState().currentSessionId;if(!i)return{summary:null,rows:[]};let a=He(i),o=t?a:a.filter(e=>e.role===`assistant`),s={totalMessages:a.length,analyzedMessages:o.length,completedMissing:0,completedBeforeTool:0,completedBeforeReasoning:0,runningToolsWhenCompleted:0,reasoningOpenWhenCompleted:0,withTools:0,withReasoning:0},c=e=>typeof e==`number`&&Number.isFinite(e)?e:null,l=e=>{let t=e.filter(e=>typeof e==`number`);return t.length>0?Math.max(...t):null},u=o.map((e,t)=>{let n=e,r=$e(e.id)||[],i=n.time??{},a=c(i.completed),o=a!==null,u=r.filter(e=>e.type===`tool`),d=r.filter(e=>e.type===`reasoning`),f=l(u.map(e=>c(e.state?.time?.end??e.state?.time?.start))),p=l(d.map(e=>c(e.time?.end??e.time?.start))),m=l([f,p].filter(e=>e!==null)),h=u.some(e=>[`pending`,`running`,`started`].includes(e.state?.status)),g=d.some(e=>typeof e.time?.end!=`number`);u.length>0&&(s.withTools+=1),d.length>0&&(s.withReasoning+=1),o||(s.completedMissing+=1);let _=!!(o&&typeof f==`number`&&a<f);_&&(s.completedBeforeTool+=1);let v=!!(o&&typeof p==`number`&&a<p);return v&&(s.completedBeforeReasoning+=1),o&&h&&(s.runningToolsWhenCompleted+=1),o&&g&&(s.reasoningOpenWhenCompleted+=1),{index:t,messageId:n.id,role:n.role,completedAt:a,latestToolTimestamp:f,latestReasoningTimestamp:p,latestPartTimestamp:m,completed_missing:!o,completed_before_tool:_,completed_before_reasoning:v,running_tools_when_completed:!!(o&&h),reasoning_open_when_completed:!!(o&&g),has_tools:u.length>0,has_reasoning:d.length>0}});return n&&(console.table(u.slice(0,r)),u.length>r&&`${r}${u.length}`),{summary:s,rows:u}},checkCompletionStatus(){let e=q.getState().currentSessionId;if(!e)return null;let t=He(e).filter(e=>e.role===`assistant`);if(t.length===0)return null;let n=t[t.length-1],r=($e(n.id)||[]).filter(e=>e.type===`step-finish`),i=n.finish===`stop`,a=n.time?.completed,o=n.status,s=typeof a==`number`&&a>0||o===`completed`,c=!!(s&&i),l=Be.getState();n.sessionID&&l.streamingMessageIds.get(n.sessionID);let u=l.messageStreamStates.get(n.id);return n.id,n.id,u?.phase,{messageId:n.id,completed:a,status:o,hasCompletedFlag:s,hasStopReason:i,messageIsComplete:c,stepFinishParts:r,raw:n}}},le(),window.addEventListener(`error`,e=>{try{let t=e.message||``,n=e.filename||``;typeof t==`string`&&t.includes(`this._renderer.value.dimensions`)&&/xterm/i.test(String(n))&&e.preventDefault()}catch{}}));var X=e(se(),1),Z=fe(),un=async()=>{if(typeof window>`u`)return;let e=null;try{e=y(`lastDirectory`)}catch(e){console.warn(`Failed to read saved directory preferences:`,e)}e&&!_()&&ue.getState().setDirectory(e,{showOverlay:!1})},dn=new Map,fn=e=>dn.get(e)??null,pn=({runtimeKey:e,initializeAppearance:t,syncSettings:n,applyDirectory:r,onError:i},a={})=>{let o=dn.get(e);if(o&&!a.force)return o;let s=(async()=>{o&&await o;try{await t()}catch(e){return i(`appearance`,e),!1}try{await Promise.all([n(),r()])}catch(e){i(`secondary`,e)}return!0})();return dn.set(e,s),s},mn=async({runtimeKey:e,initializeAppearance:t,syncSettings:n,applyDirectory:r,startWatchers:i,onError:a})=>{await pn({runtimeKey:e,initializeAppearance:t,syncSettings:n,applyDirectory:r,onError:a})&&i()},hn=(e,t=50)=>{let n=null,r;return{schedule:i=>{r=i,n&&clearTimeout(n),n=setTimeout(()=>{n=null;let t=r;r=void 0,t!==void 0&&e(t)},t)},cancel:()=>{n&&clearTimeout(n),n=null,r=void 0}}};function gn(e){return!e||e===`idle`?null:e===`ready`?`ok`:e===`error`?`unreachable`:`auth`}function _n(e,t){let n=e.via===`relay`;return t?n:!n}function vn(e){let{isActive:t,isSsh:n,runtimeIsConnected:r,runtimeConnectionPhase:i,currentTransportIsRelay:a,probe:o,sshPhase:s}=e,c;c=t?r&&i===`connected`?`ok`:`checking`:n?gn(s):o?.status??`checking`;let l=t?a:o?.via===`relay`,u=null;return!n&&c===`ok`&&o?.status===`ok`&&typeof o.latencyMs==`number`&&(!t||_n(o,a))&&(u=Math.max(0,Math.round(o.latencyMs))),{statusKind:c,showViaRelay:l,latencyMs:u}}var Q=W(),$=`local`,yn=9e4,bn=`SSH connection cancelled`,xn=e=>U(e),Sn={},Cn=e=>{let t=V(e);if(!t)return e.trim();try{let e=new URL(t);return e.pathname.endsWith(`/`)||(e.pathname=`${e.pathname}/`),e.toString()}catch{return t}},wn=()=>typeof window>`u`?``:window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,Tn=async()=>S()?B().catch(()=>``):``,En=e=>e===`ok`?`bg-status-success`:e===`auth`||e===`update-recommended`?`bg-status-warning`:e===`incompatible`||e===`wrong-service`||e===`unreachable`?`bg-status-error`:e===`checking`?`bg-status-info`:`bg-muted-foreground/40`,Dn=e=>e===`ok`?`text-[var(--status-success)]`:e===`auth`||e===`update-recommended`?`text-[var(--status-warning)]`:e===`incompatible`||e===`wrong-service`||e===`unreachable`?`text-[var(--status-error)]`:`text-muted-foreground`,On=e=>e===`unreachable`||e===`wrong-service`||e===`incompatible`,kn=e=>e===`unreachable`||e===`wrong-service`||e===`incompatible`,An=e=>e===`ok`?`desktopHostSwitcher.status.connected`:e===`auth`?`desktopHostSwitcher.status.authRequired`:e===`checking`?`desktopHostSwitcher.status.checking`:e===`update-recommended`?`desktopHostSwitcher.status.updateRecommended`:e===`incompatible`?`desktopHostSwitcher.status.incompatible`:e===`wrong-service`?`desktopHostSwitcher.status.wrongService`:e===`unreachable`?`desktopHostSwitcher.status.unreachable`:`desktopHostSwitcher.status.unknown`,jn=e=>new Promise(t=>window.setTimeout(t,e)),Mn=e=>{switch(e){case`ready`:return`desktopHostSwitcher.sshPhase.ready`;case`error`:return`desktopHostSwitcher.sshPhase.error`;case`degraded`:return`desktopHostSwitcher.sshPhase.reconnecting`;case`config_resolved`:return`desktopHostSwitcher.sshPhase.resolvingConfig`;case`auth_check`:return`desktopHostSwitcher.sshPhase.checkingAuth`;case`master_connecting`:return`desktopHostSwitcher.sshPhase.connectingSsh`;case`remote_probe`:return`desktopHostSwitcher.sshPhase.probingRemote`;case`installing`:return`desktopHostSwitcher.sshPhase.installing`;case`updating`:return`desktopHostSwitcher.sshPhase.updating`;case`server_detecting`:return`desktopHostSwitcher.sshPhase.detectingServer`;case`server_starting`:return`desktopHostSwitcher.sshPhase.startingServer`;case`forwarding`:return`desktopHostSwitcher.sshPhase.forwardingPorts`;default:return`desktopHostSwitcher.sshPhase.idle`}},Nn=async()=>{let e=await xt().catch(()=>[]),t={};for(let n of e)t[n.id]=n;return t},Pn=async(e,t,n,r)=>{let i=Date.now()+t;for(;Date.now()<i;){if(r?.())throw Error(bn);let t=(await xt(e).catch(()=>[])).find(t=>t.id===e);if(t){if(n(t),t.phase===`ready`)return t;if(t.phase===`error`)throw Error(t.detail||`SSH connection failed`)}await jn(700)}throw r?.()?Error(bn):Error(`Timed out waiting for SSH connection`)},Fn=e=>({id:$,label:`Local`,url:e||wn()}),In=e=>{let t=typeof window>`u`?``:window.location.href,r=e.find(e=>e.id===$)?.url||wn(),i=h(),a=V(r)||r,o=V(t)||t,s=n(),c=e.find(e=>e.relay&&xn(e)===s);if(c)return{id:c.id,label:c.label,url:c.url};if(i&&I(i,r))return{id:$,label:`Local`,url:a};let l=e.find(e=>i?I(i,R(e)):!1);if(l)return{id:l.id,label:l.label,url:V(R(l))||R(l)};if(t&&I(t,r))return{id:$,label:`Local`,url:a};let u=e.find(e=>t?I(t,e.url):!1);return u?{id:u.id,label:u.label,url:V(u.url)||u.url}:t.startsWith(`openchamber-ui://`)?{id:$,label:`Local`,url:a}:{id:`custom`,label:L(o||`Instance`),url:o}};function Ln({open:e,onOpenChange:r,embedded:i=!1,onHostSwitched:a}){let{t:o}=ve(),s=p(e=>e.setSettingsDialogOpen),c=p(e=>e.setSettingsPage),u=K(e=>e.isConnected),d=K(e=>e.connectionPhase),[f,m]=X.useState([]),[h,g]=X.useState(null),[_,v]=X.useState(()=>({...Sn}));X.useEffect(()=>{Object.assign(Sn,_)},[_]);let[y,x]=X.useState(!1),[C,w]=X.useState(!1),[T,E]=X.useState(!1),D=kt(),O=Ct(),[ee,k]=X.useState(null),A=ee||O,[j,M]=X.useState({}),[N,I]=X.useState({}),[B,U]=X.useState({open:!1,hostId:null,hostLabel:``,phase:`idle`,detail:null,error:null}),[ae,oe]=X.useState(``),[W,se]=X.useState(()=>wn()),[G,ce]=X.useState(null),[le,ue]=X.useState(``),[de,fe]=X.useState(``),[pe,me]=X.useState(0),he=X.useRef(0),_e=X.useMemo(()=>[Fn(W),...f.map(e=>({...e,url:V(e.url)||e.url}))],[f,W]),ye=X.useMemo(()=>new Set(Object.keys(j)),[j]),be=X.useMemo(()=>_e.filter(e=>e.id===$||F(e,ye)),[_e,ye]);X.useEffect(()=>l(()=>me(e=>e+1)),[]);let xe=X.useMemo(()=>In(_e),[_e,pe]),Se=X.useMemo(()=>t().startsWith(`relay:`),[pe]),Ce=X.useMemo(()=>{let e=h||$;return _e.find(t=>t.id===e)?.label||o(`desktopHostSwitcher.instance.local`)},[_e,h,o]),we=X.useCallback(async(e,t)=>{if(b()){E(!0),oe(``);try{let n=e.filter(e=>e.id!==$);await te({hosts:n,defaultHostId:t}),m(n),g(t)}catch(e){oe(e instanceof Error?e.message:o(`desktopHostSwitcher.error.failedToSave`))}finally{E(!1)}}},[o]),Te=X.useCallback(()=>{c(`remote-instances`),s(!0),r(!1)},[r,s,c]),Ee=X.useCallback(async()=>{if(b()){x(!0),oe(``);try{let[e,t,n]=await Promise.all([H(),St().catch(()=>({instances:[]})),Nn()]);e.localOrigin&&se(e.localOrigin);let r={};for(let e of t.instances)r[e.id]=!0;m(e.hosts||[]),g(e.defaultHostId??null),M(r),I(n)}catch(e){oe(e instanceof Error?e.message:o(`desktopHostSwitcher.error.failedToLoad`)),m([]),g(null),M({}),I({})}finally{x(!1)}}},[o]),De=X.useCallback(async e=>{if(b()){w(!0);try{let t=await Tn(),n=await Promise.all(e.map(async e=>{let n=async()=>{let t=await ne(e.relay,{sshTarget:e.sshTarget}).catch(()=>({status:`unreachable`,latencyMs:0}));return{status:t.status,latencyMs:t.latencyMs,...t.status===`ok`?{via:`relay`}:{}}};if(e.relay&&!e.apiUrl)return[e.id,await n()];let r=V(S()?R(e):e.url);if(!r)return[e.id,{status:`unreachable`,latencyMs:0}];let i=e.id===$?t:e.clientToken||``,a=await z(r,{clientToken:i||null,requestHeaders:e.requestHeaders||null}).catch(()=>({status:`unreachable`,latencyMs:0}));if(On(a.status)&&e.relay){let t=await n();if(t.status===`ok`)return[e.id,t]}return[e.id,{status:a.status,latencyMs:a.latencyMs}]})),r={};for(let[e,t]of n)r[e]=t;v(r)}finally{w(!1)}}},[]);X.useEffect(()=>{if(!e){ce(null),ue(``),fe(``),k(null),U({open:!1,hostId:null,hostLabel:``,phase:`idle`,detail:null,error:null}),oe(``);return}Ee()},[e,Ee]),X.useEffect(()=>{e&&De(be)},[e,be,De]),X.useEffect(()=>{if(!e||!b())return;let t=!1,n=async()=>{let e=await Nn();t||I(e)};n();let r=window.setInterval(()=>{typeof document<`u`&&document.visibilityState!==`visible`||n()},1500);return()=>{t=!0,window.clearInterval(r)}},[e]);let Oe=ge(async e=>{let t=e.id===$?W:V(e.url)||``,r=e.id===$?W:V(R(e))||``,i=!!e.relay&&!e.apiUrl&&e.id!==$;if(e.viaSshRelay&&Se){if(D)return;if(n()===xn(e)){a?.();return}let t=await wt({host:e});v(n=>({...n,[e.id]:t.status})),t.ok&&a?.();return}if(!t&&!i)return;if(S()){if(!r&&!e.relay||D)return;let t=e.id===$?await Tn():null,n=await wt({host:e,cachedProbe:_[e.id]||null,...e.id===$?{localApiOrigin:r,localClientToken:t}:{}});v(t=>({...t,[e.id]:n.status})),n.ok&&a?.();return}let s=!!j[e.id];if(e.id!==$&&s&&b()){let n=N[e.id],r=await xt(e.id).then(t=>t.find(t=>t.id===e.id)||null).catch(()=>null);r&&(n=r,I(t=>({...t,[e.id]:r})));let i=V(n?.localUrl||e.url||``);if(n?.phase===`ready`&&i){let e=Cn(i);a?.(),window.location.assign(e);return}k(e.id);let s=he.current+1;he.current=s,U({open:!0,hostId:e.id,hostLabel:L(e.label),phase:`master_connecting`,detail:null,error:null});try{if(await bt(e.id),s!==he.current)return;let n=await Pn(e.id,yn,e=>{I(t=>({...t,[e.id]:e})),U(t=>({...t,phase:e.phase,detail:e.detail||null}))},()=>s!==he.current);if(s!==he.current)return;let r=Cn(V(n.localUrl||``)||t);a?.(),window.location.assign(r);return}catch(t){if(s!==he.current)return;let n=t instanceof Error?t.message:String(t);if(n===bn)return;U(e=>({...e,error:n})),tt.error(o(`desktopHostSwitcher.toast.sshFailedToConnect`,{host:L(e.label)}),{description:n});return}finally{s===he.current&&k(null)}}if(e.id!==$&&b()){k(e.id);let n=await z(t,{clientToken:e.clientToken||null,requestHeaders:e.requestHeaders||null}).catch(()=>({status:`unreachable`,latencyMs:0}));if(v(t=>({...t,[e.id]:{status:n.status,latencyMs:n.latencyMs}})),On(n.status)){tt.error(o(`desktopHostSwitcher.toast.instanceUnreachable`,{host:L(e.label)})),k(null);return}}let c=Cn(t);a?.();try{window.location.assign(c)}catch{window.location.href=c}}),ke=X.useCallback(()=>{ce(null),ue(``),fe(``)},[]),Ae=X.useCallback(e=>{e.stopPropagation()},[]),je=X.useCallback(async()=>{if(!G)return;if(G===$){ke();return}let e=ie(de);if(!e){oe(o(`desktopHostSwitcher.error.invalidUrl`));return}let t=e.persistedUrl,n=(le||L(t)).trim(),r=f.map(e=>e.id===G?{...e,label:n,url:t,apiUrl:t}:e);await we(r,h),ke(),e.redeemUrl&&window.location.assign(e.redeemUrl)},[ke,f,h,le,de,G,we,o]),Me=X.useCallback(async e=>{await we(f,e===$?$:e)},[f,we]),Ne=X.useCallback(e=>{let t=e=>{tt.error(o(`desktopHostSwitcher.error.failedToOpenNewWindow`),{description:e instanceof Error?e.message:String(e)})};if(e.relay&&e.id!==$){P(e.id).catch(t);return}let n=e.id===$?W:R(e);if(!n)return;let r=Cn(n);re(r,{clientToken:e.clientToken||null,requestHeaders:e.requestHeaders||null}).catch(t)},[W,o]),Pe=ge(async()=>{he.current+=1,k(null),U(e=>({...e,open:!1,hostId:null,error:null,detail:null,phase:`idle`}));let e=Cn(W);if(S()){if(D)return;let e=await Tn();(await wt({host:Fn(W),localApiOrigin:W,localClientToken:e})).ok&&a?.();return}a?.(),window.location.assign(e)}),Fe=X.useCallback(async()=>{let e=B.hostId||A;he.current+=1,k(null),U({open:!1,hostId:null,hostLabel:``,phase:`idle`,detail:null,error:null}),!(!e||e===$||!b())&&await Tt(e).catch(()=>{})},[B.hostId,A]),Ie=X.useCallback(()=>{let e=B.hostId;if(!e)return;let t=_e.find(t=>t.id===e);t&&Oe(t)},[_e,Oe,B.hostId]),Le=X.useCallback(async e=>{if(b()){k(e.id);try{await bt(e.id),(await Pn(e.id,yn,e=>{I(t=>({...t,[e.id]:e}))})).phase===`ready`&&tt.success(o(`desktopHostSwitcher.toast.sshConnected`,{host:L(e.label)}))}catch(t){let n=t instanceof Error?t.message:String(t);n!==bn&&tt.error(o(`desktopHostSwitcher.toast.sshFailedToConnect`,{host:L(e.label)}),{description:n})}finally{k(null)}}},[o]);if(!b())return null;let Re=b(),ze=(0,Q.jsxs)(Q.Fragment,{children:[i?(0,Q.jsx)(`div`,{className:`flex-shrink-0 border-b border-[var(--interactive-border)] px-3 py-2`,children:(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,Q.jsxs)(`div`,{className:`min-w-0 flex items-baseline gap-1.5 typography-ui-label`,children:[(0,Q.jsx)(`span`,{className:`font-medium text-foreground`,children:o(`desktopHostSwitcher.header.current`)}),(0,Q.jsx)(`span`,{className:`max-w-[9rem] truncate text-muted-foreground`,children:L(xe.label)}),(0,Q.jsx)(`span`,{className:`text-muted-foreground/50`,children:`•`}),(0,Q.jsx)(`span`,{className:`font-medium text-foreground`,children:o(`desktopHostSwitcher.header.default`)}),(0,Q.jsx)(`span`,{className:`max-w-[9rem] truncate text-muted-foreground`,children:L(Ce)})]}),(0,Q.jsx)(`button`,{type:`button`,className:at(`inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors`,`hover:text-foreground hover:bg-interactive-hover`,`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary`),onClick:()=>void De(be),disabled:!Re||y||C,"aria-label":o(`desktopHostSwitcher.actions.refreshInstancesAria`),children:(0,Q.jsx)(J,{name:`refresh`,className:at(`h-4 w-4`,C&&`animate-spin`)})})]})}):(0,Q.jsxs)(ot,{className:`flex-shrink-0`,children:[(0,Q.jsxs)(ct,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(J,{name:`server`,className:`h-5 w-5`}),o(`desktopHostSwitcher.title`)]}),(0,Q.jsx)(lt,{children:o(`desktopHostSwitcher.description`)})]}),!i&&(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-2 flex-shrink-0`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 min-w-0`,children:[(0,Q.jsx)(`span`,{className:`typography-meta text-muted-foreground`,children:o(`desktopHostSwitcher.header.currentColon`)}),(0,Q.jsx)(`span`,{className:`typography-ui-label text-foreground truncate`,children:L(xe.label)}),(0,Q.jsx)(`span`,{className:`typography-meta text-muted-foreground`,children:o(`desktopHostSwitcher.header.currentDefaultColon`)}),(0,Q.jsx)(`span`,{className:`typography-ui-label text-foreground truncate`,children:L(Ce)})]}),(0,Q.jsx)(`div`,{className:`flex items-center gap-1`,children:(0,Q.jsxs)(dt,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>void De(be),disabled:!Re||y||C,children:[(0,Q.jsx)(J,{name:`refresh`,className:at(`h-4 w-4`,C&&`animate-spin`)}),o(`desktopHostSwitcher.actions.refresh`)]})})]}),!Re&&(0,Q.jsx)(`div`,{className:`flex-shrink-0 rounded-lg border border-border/50 bg-muted/20 p-3`,children:(0,Q.jsx)(`div`,{className:`typography-meta text-muted-foreground`,children:o(`desktopHostSwitcher.state.limitedOnPage`)})}),(0,Q.jsx)(`div`,{className:`flex-1 min-h-0 overflow-y-auto`,children:(0,Q.jsx)(`div`,{className:at(`space-y-1`,i&&`space-y-1.5 px-3 py-1`),children:y?(0,Q.jsx)(`div`,{className:`px-2 py-2 text-muted-foreground text-sm`,children:o(`desktopHostSwitcher.state.loading`)}):be.map(e=>{let t=e.id===$,n=!!j[e.id],r=e.id===xe.id,a=(h||$)===e.id,s=_[e.id]||null,c=N[e.id]||null,l=vn({isActive:r,isSsh:n,runtimeIsConnected:u,runtimeConnectionPhase:d,currentTransportIsRelay:Se,probe:s,sshPhase:c?.phase}),f=l.statusKind,p=l.showViaRelay,m=G===e.id,g=t?W:V(e.url)||e.url,v=e.id===$?o(`desktopHostSwitcher.instance.local`):L(e.label),y=e.relay&&!e.apiUrl?o(`mobile.connect.relay.badge`):L(g);return(0,Q.jsxs)(`div`,{className:at(`group flex items-center gap-2 px-2.5 py-2 rounded-md overflow-hidden`,i&&`rounded-xl bg-[var(--surface-muted)] px-3 py-2.5`,i&&r&&`bg-[var(--interactive-selection)]/25`,m?`bg-interactive-hover/20`:`hover:bg-interactive-hover/30`),children:[(0,Q.jsxs)(`button`,{type:`button`,className:at(`flex items-center gap-2 flex-1 min-w-0 text-left`,m&&`pointer-events-none opacity-70`),onClick:()=>void Oe(e),disabled:A===e.id,"aria-label":o(`desktopHostSwitcher.actions.switchToAria`,{instance:v}),children:[(0,Q.jsx)(`span`,{className:at(`h-2 w-2 rounded-full flex-shrink-0`,En(f))}),(0,Q.jsxs)(`div`,{className:`flex-1 min-w-0 space-y-0.5`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 items-center gap-1.5`,children:[(0,Q.jsx)(`span`,{className:`typography-ui-label font-medium truncate text-foreground`,children:v}),r&&(0,Q.jsx)(`span`,{className:`typography-micro flex-shrink-0 text-muted-foreground bg-muted px-1 rounded leading-none pb-px border border-border/50`,children:o(`desktopHostSwitcher.header.current`)}),n&&(0,Q.jsx)(`span`,{className:`typography-micro flex-shrink-0 px-1 rounded leading-none pb-px text-[var(--status-info)] bg-[var(--status-info)]/10`,children:`SSH`})]}),(0,Q.jsxs)(`div`,{className:at(`typography-micro truncate`,Dn(f)),children:[o(n&&!r?Mn(c?.phase):An(f)),l.latencyMs==null?``:o(`desktopHostSwitcher.status.ping`,{ms:l.latencyMs}),p?` · ${o(`settings.remoteInstances.clientAuth.state.viaRelay`)}`:``]}),(0,Q.jsx)(`div`,{className:`typography-micro text-muted-foreground/70 truncate font-mono`,children:y})]})]}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 flex-shrink-0`,children:[n&&!t&&(c?.phase===`idle`||!c?.phase?(0,Q.jsxs)(dt,{type:`button`,variant:`outline`,size:`sm`,className:`h-8 px-2.5`,disabled:A===e.id,onClick:t=>{t.stopPropagation(),Le(e)},children:[A===e.id?(0,Q.jsx)(J,{name:`loader-4`,className:`h-3.5 w-3.5 animate-spin`}):(0,Q.jsx)(J,{name:`plug-2`,className:`h-3.5 w-3.5`}),o(`desktopHostSwitcher.actions.connect`)]}):(0,Q.jsx)(`div`,{className:`h-8 w-8 opacity-0 pointer-events-none`,"aria-hidden":`true`})),(0,Q.jsxs)(yt,{children:[(0,Q.jsx)(_t,{asChild:!0,children:(0,Q.jsx)(`button`,{type:`button`,className:at(`h-8 w-8 rounded-md inline-flex items-center justify-center hover:bg-interactive-hover transition-colors`,a?`text-primary hover:text-primary/80`:`text-muted-foreground/60 hover:text-primary/80`),onClick:()=>void Me(e.id),"aria-label":o(a?`desktopHostSwitcher.actions.defaultInstanceAria`:`desktopHostSwitcher.actions.setAsDefaultAria`),disabled:T||!a&&kn(f),children:a?(0,Q.jsx)(J,{name:`star-fill`,className:`h-4 w-4`}):(0,Q.jsx)(J,{name:`star`,className:`h-4 w-4`})})}),(0,Q.jsx)(vt,{sideOffset:6,children:o(a?`desktopHostSwitcher.header.default`:`desktopHostSwitcher.actions.setAsDefault`)})]}),(0,Q.jsxs)(yt,{children:[(0,Q.jsx)(_t,{asChild:!0,children:(0,Q.jsx)(`button`,{type:`button`,className:at(`h-8 w-8 rounded-md inline-flex items-center justify-center hover:bg-interactive-hover transition-colors`,kn(f)?`text-muted-foreground/30 cursor-not-allowed`:`text-muted-foreground/60 hover:text-foreground`),onClick:t=>{t.stopPropagation(),Ne(e)},disabled:kn(f),"aria-label":o(`desktopHostSwitcher.actions.openInNewWindowAria`),children:(0,Q.jsx)(J,{name:`window`,className:`h-4 w-4`})})}),(0,Q.jsx)(vt,{sideOffset:6,children:kn(f)?o(`desktopHostSwitcher.state.instanceUnreachable`):o(`desktopHostSwitcher.actions.openInNewWindow`)})]})]})]},e.id)})})}),Re&&G&&G!==$&&(0,Q.jsxs)(`div`,{className:`flex-shrink-0 rounded-lg border border-border/50 bg-muted/20 p-3`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Q.jsx)(`div`,{className:`typography-ui-label font-medium text-foreground`,children:o(`desktopHostSwitcher.edit.title`)}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(dt,{type:`button`,variant:`outline`,size:`sm`,onClick:ke,disabled:T,children:o(`desktopHostSwitcher.actions.cancel`)}),(0,Q.jsxs)(dt,{type:`button`,size:`sm`,onClick:()=>void je(),disabled:T,children:[T?(0,Q.jsx)(J,{name:`loader-4`,className:`h-4 w-4 animate-spin`}):null,o(`desktopHostSwitcher.actions.save`)]})]})]}),(0,Q.jsxs)(`div`,{className:`mt-2 grid grid-cols-1 gap-2 sm:grid-cols-2`,children:[(0,Q.jsx)(gt,{value:le,onChange:e=>ue(e.target.value),onKeyDown:Ae,placeholder:o(`desktopHostSwitcher.field.labelPlaceholder`),disabled:T}),(0,Q.jsx)(gt,{value:de,onChange:e=>fe(e.target.value),onKeyDown:Ae,placeholder:o(`desktopHostSwitcher.field.urlPlaceholder`),disabled:T})]})]}),(0,Q.jsx)(`div`,{className:`flex-shrink-0 border-t border-[var(--interactive-border)]`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`w-full flex items-center gap-2 px-2 py-2 text-left text-muted-foreground hover:text-foreground hover:bg-interactive-hover/30 transition-colors`,onClick:Te,children:[(0,Q.jsx)(J,{name:`add`,className:`h-4 w-4`}),(0,Q.jsx)(`span`,{className:`typography-ui-label`,children:o(`desktopHostSwitcher.actions.addInstance`)})]})}),ae&&(0,Q.jsx)(`div`,{className:`flex-shrink-0 typography-meta text-status-error`,children:ae})]}),Be=(0,Q.jsx)(ut,{open:B.open,onOpenChange:e=>{if(!e&&A){Fe();return}U(t=>({...t,open:e,...e?{}:{hostId:null,error:null,detail:null,phase:`idle`}}))},children:(0,Q.jsxs)(st,{className:`w-[min(28rem,calc(100vw-2rem))] max-w-none`,children:[(0,Q.jsxs)(ot,{children:[(0,Q.jsxs)(ct,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(J,{name:`loader-4`,className:at(`h-4 w-4`,!B.error&&`animate-spin`)}),o(`desktopHostSwitcher.ssh.connectingTo`,{host:B.hostLabel||o(`desktopHostSwitcher.ssh.instanceFallback`)})]}),(0,Q.jsx)(lt,{children:B.error?B.error:B.detail||o(Mn(B.phase))})]}),B.error?(0,Q.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Q.jsx)(dt,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>void Pe(),children:o(`desktopHostSwitcher.actions.switchToLocal`)}),(0,Q.jsx)(dt,{type:`button`,size:`sm`,onClick:Ie,disabled:!B.hostId,children:o(`desktopHostSwitcher.actions.retry`)})]}):null]})});return i?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`w-full max-h-[70vh] flex flex-col overflow-hidden gap-2`,children:ze}),Be]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(ut,{open:e,onOpenChange:r,children:(0,Q.jsx)(st,{className:`w-[min(42rem,calc(100vw-2rem))] max-w-none max-h-[70vh] flex flex-col overflow-hidden gap-3`,children:ze})}),Be]})}function Rn(){let e=(0,Z.c)(11),[t,n]=X.useState(!1),{t:r}=ve();if(!b())return null;let i,a;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(i=()=>n(!0),a=(0,Q.jsx)(J,{name:`server`,className:`h-4 w-4`}),e[0]=i,e[1]=a):(i=e[0],a=e[1]);let o;e[2]===r?o=e[3]:(o=r(`desktopHostSwitcher.actions.switchInstance`),e[2]=r,e[3]=o);let s;e[4]===o?s=e[5]:(s=(0,Q.jsxs)(dt,{type:`button`,variant:`ghost`,size:`sm`,"data-oc-host-switcher":!0,className:`w-full justify-center`,onClick:i,children:[a,o]}),e[4]=o,e[5]=s);let c;e[6]===t?c=e[7]:(c=(0,Q.jsx)(Ln,{open:t,onOpenChange:n}),e[6]=t,e[7]=c);let l;return e[8]!==s||e[9]!==c?(l=(0,Q.jsxs)(Q.Fragment,{children:[s,c]}),e[8]=s,e[9]=c,e[10]=l):l=e[10],l}var zn=e=>e.shouldUseDesktopShellPasswordLogin?`locked`:`error`,Bn=`/auth/session`,Vn=4,Hn=1500,Un=`openchamber.uiAuth.trustDevice`,Wn=`desktop-local`,Gn=`desktop-local`,Kn=()=>{if(typeof window>`u`)return``;let e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof e==`string`?e.trim():``},qn=(e,t)=>{let n=V(e),r=V(t);if(!n||!r)return!1;try{return new URL(n).origin===new URL(r).origin}catch{return!1}},Jn=()=>b(),Yn=e=>{let t=e.replace(/^\[|\]$/g,``);return t===`localhost`||t===`127.0.0.1`||t===`::1`},Xn=()=>{if(!b())return!1;let e=Kn();if(!e)return!1;let t=h()||(typeof window<`u`?window.location.origin:``);if(qn(e,t))return!0;try{let e=V(t);return!!(e&&Yn(new URL(e).hostname))}catch{return!1}},Zn=()=>Xn()?{clientKind:Wn,dedupeKey:Gn}:{},Qn=async()=>await D(Bn,{method:`GET`,credentials:`include`,headers:{Accept:`application/json`}}),$n=()=>typeof window>`u`?!1:window.localStorage.getItem(Un)===`true`,er=async(e,t)=>{let n=Jn();return await D(Bn,{method:`POST`,credentials:`include`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({password:e,trustDevice:t,issueClientToken:n,clientLabel:`OpenChamber Desktop`,...Zn()})})},tr=async()=>{if(!b())return``;let e=await D(`/api/client-auth/clients`,{method:`POST`,credentials:`include`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({label:`OpenChamber Desktop`,...Zn()})}).catch(()=>null);if(!e?.ok)return``;let t=await e.json().catch(()=>null);return typeof t?.token==`string`?t.token.trim():``},nr=()=>b()&&!Xn(),rr=async(e,t)=>{if(!b()||typeof window>`u`)return null;let n=await k(`desktop_remote_password_login`,{url:h(),password:e,trustDevice:t,requestHeaders:i()}).catch(()=>null);if(!n||typeof n!=`object`)return null;let r=n.token,a=n.status;return{token:typeof r==`string`?r.trim():``,...typeof a==`number`?{status:a}:{}}},ir=async(e,t)=>{if(!b()||!t)return;let n=await H().catch(()=>null);if(!n)return;if(n.localOrigin&&qn(n.localOrigin,e)){await te({hosts:n.hosts,defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted,localClientToken:t}).catch(()=>void 0);return}let r=!1,i=n.hosts.map(n=>!qn(R(n),e)||n.clientToken===t?n:(r=!0,{...n,clientToken:t}));r&&await te({hosts:i,defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted}).catch(()=>void 0)},ar=async e=>{if(!e)return;let t=h(),n=i();await ir(t,e),a({apiBaseUrl:t,clientToken:e,requestHeaders:Object.keys(n).length>0?n:null})},or=e=>{let t=(0,Z.c)(7),{children:n}=e,r;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(r={height:`var(--oc-wco-titlebar-height, 0px)`,right:`var(--oc-wco-right-inset, 0px)`},t[0]=r):r=t[0];let i=r,a,o;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(a={fontFamily:`"Inter", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", sans-serif`},o=(0,Q.jsx)(`div`,{className:`app-region-drag fixed left-0 top-0 z-20`,style:i,"aria-hidden":!0}),t[1]=a,t[2]=o):(a=t[1],o=t[2]);let s;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(s=(0,Q.jsx)(`div`,{className:`pointer-events-none absolute inset-0 opacity-55`,style:{background:`radial-gradient(120% 140% at 50% -20%, var(--surface-overlay) 0%, transparent 68%)`}}),t[3]=s):s=t[3];let c;t[4]===Symbol.for(`react.memo_cache_sentinel`)?(c=(0,Q.jsx)(`div`,{className:`pointer-events-none absolute inset-0`,style:{backgroundColor:`var(--surface-subtle)`,opacity:.22}}),t[4]=c):c=t[4];let l;return t[5]===n?l=t[6]:(l=(0,Q.jsxs)(`div`,{className:`relative flex min-h-screen items-center justify-center overflow-hidden bg-background text-foreground`,style:a,children:[o,s,c,(0,Q.jsx)(`div`,{className:`app-region-no-drag relative z-10 flex w-full justify-center px-4 py-12 sm:px-6`,children:n})]}),t[5]=n,t[6]=l),l},sr=()=>{let e=(0,Z.c)(1),t;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,Q.jsx)(`div`,{className:`flex min-h-screen items-center justify-center bg-background text-foreground`,children:(0,Q.jsx)(Rt,{width:120,height:120})}),e[0]=t):t=e[0],t},cr=e=>{let t=(0,Z.c)(23),{onRetry:n,errorType:r,retryAfter:i,children:a}=e,o=r===void 0?`network`:r,{t:s}=ve(),c=o===`rate-limit`,l=i?Math.ceil(i/60):1,u;t[0]!==c||t[1]!==s?(u=s(c?`sessionAuth.error.rateLimitTitle`:`sessionAuth.error.networkTitle`),t[0]=c,t[1]=s,t[2]=u):u=t[2];let d;t[3]===u?d=t[4]:(d=(0,Q.jsx)(`h1`,{className:`typography-ui-header font-semibold text-destructive`,children:u}),t[3]=u,t[4]=d);let f;t[5]!==c||t[6]!==l||t[7]!==s?(f=c?s(l>1?`sessionAuth.error.rateLimitDescriptionPlural`:`sessionAuth.error.rateLimitDescriptionSingle`,{minutes:l}):s(`sessionAuth.error.networkDescription`),t[5]=c,t[6]=l,t[7]=s,t[8]=f):f=t[8];let p;t[9]===f?p=t[10]:(p=(0,Q.jsx)(`p`,{className:`typography-meta text-muted-foreground max-w-xs`,children:f}),t[9]=f,t[10]=p);let m;t[11]!==d||t[12]!==p?(m=(0,Q.jsxs)(`div`,{className:`space-y-2`,children:[d,p]}),t[11]=d,t[12]=p,t[13]=m):m=t[13];let h;t[14]===s?h=t[15]:(h=s(`sessionAuth.error.retry`),t[14]=s,t[15]=h);let g;t[16]!==n||t[17]!==h?(g=(0,Q.jsx)(dt,{type:`button`,onClick:n,className:`w-full max-w-xs`,children:h}),t[16]=n,t[17]=h,t[18]=g):g=t[18];let _;return t[19]!==a||t[20]!==m||t[21]!==g?(_=(0,Q.jsx)(or,{children:(0,Q.jsxs)(`div`,{className:`flex flex-col items-center gap-6 text-center`,children:[m,g,a]})}),t[19]=a,t[20]=m,t[21]=g,t[22]=_):_=t[22],_},lr=({children:e})=>{let{t}=ve(),r=X.useMemo(()=>_(),[]),i=r,a=X.useMemo(()=>b()&&!r,[r]),[o,s]=X.useState(()=>i?`authenticated`:`pending`),[c,d]=X.useState(``),[f,p]=X.useState(!1),[m,h]=X.useState(``),[g,v]=X.useState(void 0),[y,x]=X.useState(!1),[S,C]=X.useState(Dt),[w,T]=X.useState(!1),[E,D]=X.useState(!1),[O,k]=X.useState(()=>$n()),[A,M]=X.useState(null),[N,P]=X.useState(i),F=X.useRef(null),I=X.useRef(i);X.useEffect(()=>{typeof window>`u`||window.localStorage.setItem(Un,O?`true`:`false`)},[O]);let L=X.useCallback(async()=>{if(i)return Dt;try{let e=await Nt();return C(e),e}catch{return C(Dt),Dt}},[i]);X.useEffect(()=>{let e=!1;if(!i)return(async()=>{try{if(!window.isSecureContext||!pt()){e||T(!1);return}e||T(!0)}catch{e||T(!1)}})(),()=>{e=!0}},[i]);let te=X.useRef(0),R=X.useRef(null),ne=X.useRef(null),z=X.useCallback(()=>{R.current!==null&&(window.clearTimeout(R.current),R.current=null)},[]),B=X.useCallback(()=>{te.current=0,z()},[z]),V=X.useCallback(()=>te.current>=Vn?!1:(te.current+=1,z(),R.current=window.setTimeout(()=>{R.current=null,ne.current?.()},Hn*te.current),!0),[z]);X.useEffect(()=>z,[z]);let H=X.useCallback(async()=>{if(i){s(`authenticated`);return}s(e=>e===`authenticated`?e:`pending`);try{let[e,t]=await Promise.all([Qn(),L()]),n=await e.text();if(e.ok){B(),s(`authenticated`),x(!1),h(``),v(void 0);return}if(e.status===401){let e={};try{e=JSON.parse(n)}catch{e={}}B(),x(e.tunnelLocked===!0),C(t),s(`locked`),v(void 0);return}if(e.status===429){let e={};try{e=JSON.parse(n)}catch{e={}}B(),v(e.retryAfter),x(!1),s(`rate-limited`);return}if(V())return;s(`error`),x(!1)}catch(e){if(console.warn(`Failed to check session status:`,e),zn({shouldUseDesktopShellPasswordLogin:nr()})===`locked`){s(`locked`),v(void 0),x(!1);return}if(V())return;s(`error`),x(!1)}},[L,B,V,i]);X.useEffect(()=>{ne.current=H},[H]),X.useEffect(()=>{i||H()},[H,i]),X.useEffect(()=>{if(o===`pending`||o===`authenticated`||typeof document>`u`)return;let e=document.getElementById(`initial-loading`);if(!e)return;e.classList.add(`fade-out`);let t=window.setTimeout(()=>{e.remove()},300);return()=>{window.clearTimeout(t)}},[o]),X.useEffect(()=>{if(i)return;let e=hn(e=>{u(e)&&(d(``),h(``),v(void 0),x(!1),B(),P(!1),I.current=!1,s(`pending`),H())}),t=l(t=>e.schedule(t));return()=>{t(),e.cancel()}},[H,B,i]),X.useEffect(()=>{!i&&o===`locked`&&(I.current=!1,P(!1))},[i,o]),X.useEffect(()=>{o===`locked`&&F.current&&(F.current.focus(),F.current.select())},[o]),X.useEffect(()=>{if(!i&&o===`authenticated`&&!I.current){I.current=!0;let e=!1;return pn({runtimeKey:n(),initializeAppearance:j,syncSettings:ee,applyDirectory:un,onError:(e,t)=>{console.error(`[SessionAuthGate] ${e} settings hydration failed:`,t)}},{force:!0}).then(()=>{e||P(!0)}),()=>{e=!0}}},[i,o]);let re=async e=>{e.preventDefault(),await ae(!1)},ie=X.useCallback(async()=>{M(`register`),D(!0);try{await Et()}finally{M(null),D(!1)}await L()},[L]),U=X.useCallback(()=>{Pt(),M(null),D(!1)},[]),ae=X.useCallback(async e=>{if(!y&&!(!c||f)){E&&U(),p(!0),h(``);try{if(nr()){let e=await rr(c,O);if(e?.token){d(``),x(!1),await ar(e.token),s(`authenticated`);return}if(e?.status===401){h(t(`sessionAuth.error.incorrectPassword`)),x(!1),s(`locked`);return}if(e?.status===429){v(void 0),x(!1),s(`rate-limited`);return}}let n=await er(c,O);if(n.ok){let r=await n.json().catch(()=>null),i=Jn(),a=``;if(i&&(a=typeof r?.clientToken==`string`&&r.clientToken.trim()?r.clientToken.trim():``,a||=(await rr(c,O))?.token||await tr()),d(``),x(!1),a&&await ar(a),e&&w)try{await ie(),tt.success(t(`sessionAuth.toast.passkeyAdded`)),s(`authenticated`);return}catch(e){if(Mt(e))tt.message(t(`sessionAuth.toast.passkeySetupCanceled`));else{let n=e instanceof Error?e.message:t(`sessionAuth.error.passkeySetupFailed`);tt.error(n)}s(`authenticated`);return}s(`authenticated`);return}if(n.status===401){h(t(`sessionAuth.error.incorrectPassword`)),x(!1),s(`locked`);return}if(n.status===429){let e=await n.json().catch(()=>({}));v(e.retryAfter),x(!1),s(`rate-limited`);return}h(t(`sessionAuth.error.unexpectedResponse`)),x(!1),s(`error`)}catch(e){console.warn(`Failed to submit UI password:`,e);let n=nr()?await rr(c,O):null;if(n?.token){d(``),x(!1),await ar(n.token),s(`authenticated`);return}if(n?.status===401){h(t(`sessionAuth.error.incorrectPassword`)),x(!1),s(`locked`);return}if(n?.status===429){v(void 0),x(!1),s(`rate-limited`);return}h(t(`sessionAuth.error.networkRetry`)),x(!1),s(`error`)}finally{p(!1)}}},[U,E,f,y,c,ie,w,t,O]),oe=X.useCallback(async()=>{if(!(f||!w)){if(E){U();return}D(!0),M(`auth`),h(``);try{let e=await jt(O,{issueClientToken:Jn(),clientLabel:`OpenChamber Desktop`,...Zn()}),t=Jn()&&typeof e?.clientToken==`string`&&e.clientToken.trim()?e.clientToken.trim():``;t&&await ar(t),d(``),s(`authenticated`)}catch(e){if(Mt(e))h(``);else{let n=e instanceof Error?e.message:t(`sessionAuth.error.passkeySignInCanceled`);h(n)}}finally{M(null),D(!1)}}},[U,E,f,w,t,O]),W=X.useCallback(async()=>{if(!(f||y||!w)){if(E){U();return}if(o!==`authenticated`){if(!c){h(t(`sessionAuth.error.enterPasswordForPasskey`));return}await ae(!0);return}h(``);try{await ie(),tt.success(t(`sessionAuth.toast.passkeyAdded`))}catch(e){if(Mt(e)){tt.message(t(`sessionAuth.toast.passkeySetupCanceled`));return}let n=e instanceof Error?e.message:t(`sessionAuth.error.passkeySetupFailed`);tt.error(n)}}},[U,ae,E,f,y,c,ie,o,w,t]),se=w&&S.enabled,G=se&&S.hasPasskeys;return o===`pending`||o===`authenticated`&&!N?(0,Q.jsx)(sr,{}):o===`error`?(0,Q.jsx)(cr,{onRetry:()=>{B(),H()},errorType:`network`,children:a&&(0,Q.jsxs)(`div`,{className:`w-full max-w-xs`,children:[(0,Q.jsx)(Rn,{}),(0,Q.jsx)(`p`,{className:`mt-1 text-center typography-micro text-muted-foreground`,children:t(`sessionAuth.locked.hostSwitcherHint`)})]})}):o===`rate-limited`?(0,Q.jsx)(cr,{onRetry:()=>void H(),errorType:`rate-limit`,retryAfter:g}):o===`locked`?(0,Q.jsx)(or,{children:(0,Q.jsxs)(`div`,{className:`flex flex-col items-center gap-6 w-full max-w-xs`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-col items-center gap-1 text-center`,children:[(0,Q.jsx)(`h1`,{className:`text-xl font-semibold text-foreground`,children:t(y?`sessionAuth.locked.tunnelTitle`:`sessionAuth.locked.unlockTitle`)}),(0,Q.jsx)(`p`,{className:`typography-meta text-muted-foreground`,children:t(y?`sessionAuth.locked.tunnelDescription`:`sessionAuth.locked.passwordDescription`)})]}),!y&&(0,Q.jsxs)(`form`,{onSubmit:re,className:`w-full space-y-2`,children:[G&&(0,Q.jsxs)(dt,{type:`button`,variant:`outline`,className:`w-full`,onClick:()=>void oe(),disabled:f||E&&A!==`auth`,children:[E?(0,Q.jsx)(J,{name:`loader-4`,className:`h-4 w-4 animate-spin`}):(0,Q.jsx)(J,{name:`lock-unlock`,className:`h-4 w-4`}),(0,Q.jsx)(`span`,{children:t(E&&A===`auth`?`sessionAuth.actions.cancelPasskey`:`sessionAuth.actions.usePasskey`)})]}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsxs)(`div`,{className:`relative flex-1`,children:[(0,Q.jsx)(J,{name:`lock`,className:`absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground/60`}),(0,Q.jsx)(gt,{id:`openchamber-ui-password`,ref:F,type:`password`,autoComplete:`current-password`,placeholder:t(`sessionAuth.password.placeholder`),value:c,onChange:e=>{d(e.target.value),m&&h(``)},className:`pl-10`,"aria-invalid":!!m||void 0,"aria-describedby":m?`oc-ui-auth-error`:void 0,disabled:f})]}),(0,Q.jsx)(dt,{type:`submit`,size:`icon`,disabled:!c||f,"aria-label":t(f?`sessionAuth.actions.unlockingAria`:`sessionAuth.actions.unlockAria`),children:f?(0,Q.jsx)(J,{name:`loader-4`,className:`h-4 w-4 animate-spin`}):(0,Q.jsx)(J,{name:`lock-unlock`,className:`h-4 w-4`})})]}),se?(0,Q.jsxs)(`div`,{className:`flex items-center justify-between pt-1`,children:[(0,Q.jsxs)(`label`,{className:`flex items-center gap-2 text-center typography-micro text-muted-foreground`,children:[(0,Q.jsx)(mt,{checked:O,onChange:k,disabled:f,ariaLabel:t(`sessionAuth.actions.trustDeviceAria`),className:`size-4`,iconClassName:`size-4`}),(0,Q.jsx)(`span`,{children:t(`sessionAuth.actions.trustDevice`)})]}),(0,Q.jsx)(dt,{type:`button`,variant:`ghost`,size:`sm`,className:`text-muted-foreground hover:text-foreground`,onClick:()=>void W(),disabled:f,children:t(E&&A===`register`?`sessionAuth.actions.cancelPasskeySetup`:`sessionAuth.actions.addPasskey`)})]}):(0,Q.jsxs)(`label`,{className:`flex items-center justify-center gap-2 pt-1 text-center typography-micro text-muted-foreground`,children:[(0,Q.jsx)(mt,{checked:O,onChange:k,disabled:f,ariaLabel:t(`sessionAuth.actions.trustDeviceAria`),className:`size-4`,iconClassName:`size-4`}),(0,Q.jsx)(`span`,{children:t(`sessionAuth.actions.trustDevice`)})]}),m&&(0,Q.jsx)(`p`,{id:`oc-ui-auth-error`,className:`typography-meta text-destructive`,children:m})]}),a&&(0,Q.jsxs)(`div`,{className:`w-full`,children:[(0,Q.jsx)(Rn,{}),(0,Q.jsx)(`p`,{className:`mt-1 text-center typography-micro text-muted-foreground`,children:t(`sessionAuth.locked.hostSwitcherHint`)})]})]})}):(0,Q.jsx)(Q.Fragment,{children:e})},ur=e=>{let t=(0,Z.c)(14),{children:n}=e,r=p(dr),i=p(fr),a=p(pr),o=p(mr),s=p(hr),{deviceType:c,hasTouchInput:l}=Ht(),u;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(u=typeof document<`u`&&m(),t[0]=u):u=t[0];let d=u,f;t[1]!==s||t[2]!==a?(f=()=>{a(),s()},t[1]=s,t[2]=a,t[3]=f):f=t[3];let h;t[4]!==s||t[5]!==a||t[6]!==i||t[7]!==c||t[8]!==r||t[9]!==l||t[10]!==o?(h=[r,i,a,o,s,c,l,d],t[4]=s,t[5]=a,t[6]=i,t[7]=c,t[8]=r,t[9]=l,t[10]=o,t[11]=h):h=t[11],X.useLayoutEffect(f,h);let g;return t[12]===n?g=t[13]:(g=(0,Q.jsx)(Q.Fragment,{children:n}),t[12]=n,t[13]=g),g};function dr(e){return e.fontSize}function fr(e){return e.codeFontSize}function pr(e){return e.applyTypography}function mr(e){return e.padding}function hr(e){return e.applyPadding}var gr=e(G(),1),_r=e=>{if(!e||typeof e!=`string`)return null;let t=e.trim();if(!t.startsWith(`#`))return null;let n=t.slice(1);if((n.length===3||n.length===4)&&(n=n.split(``).map(e=>e+e).join(``)),n.length===8&&(n=n.slice(0,6)),n.length!==6)return null;let r=Number.parseInt(n,16);return Number.isNaN(r)?null:`${r>>16&255} ${r>>8&255} ${r&255}`},vr=class{inheritanceMap=new Map;constructor(){this.initializeInheritanceMap()}generate(e){let t=[];return t.push(...this.generateTailwindVariables(e)),t.push(...this.generatePrimaryColors(e.colors.primary)),t.push(...this.generateSurfaceColors(e.colors.surface)),t.push(...this.generateInteractiveColors(e.colors.interactive)),t.push(...this.generateStatusColors(e.colors.status)),t.push(...this.generatePullRequestColors(e)),t.push(...this.generateSyntaxColors(e.colors.syntax)),t.push(...this.generateComponentColors(e.colors,e)),t.push(...this.generateTypographyVariables()),e.config&&t.push(...this.generateConfigVariables(e.config)),t.join(`
2
+ import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{D as t,E as n,F as r,H as i,M as a,T as o,d as s,h as c,j as l,k as u,m as d,s as f,t as p,v as m,w as h}from"./useUIStore-5agS8bsW.js";import{$ as g,$t as _,Ft as v,Mt as y,Xt as b,Yt as x,Zt as S,c as C,en as w,g as T,h as E,kn as D,m as O,n as ee,qt as k,r as A,t as j,u as M,xn as N}from"./persistence-D1lIuyqO.js";import{c as P,d as F,f as I,h as L,i as te,l as R,m as ne,n as z,o as B,p as V,r as H,s as re,v as ie}from"./desktopHosts-ZK_vkdzL.js";import{i as U}from"./desktopRelayRestore-CewM6-g5.js";import{a as ae,i as oe}from"./vendor-zustand-B4dlGEM2.js";import{nt as W,rt as se,tt as G}from"./vendor-base-ui-CnHfUmDN.js";import{kt as ce,wt as le,yt as ue}from"./gitApiHttp-BxGAFLTf.js";import{o as de}from"./vendor-aparajita-capacitor-secure-storage-CjQdwfjS.js";import{n as fe}from"./vendor-react-DLPElpoQ.js";import{c as pe}from"./vendor-tanstack-react-query-D7pys_c9.js";import{t as me}from"./vendor-sonner-DVzioF3d.js";import{a as he,n as ge}from"./vendor-reactuses-core-DDoDDyM9.js";import{c as _e,n as ve,r as ye,s as be,t as xe}from"./clipboard-BnElHSnO.js";import{i as Se,t as Ce}from"./store-CUWqzRt7.js";import{Ao as we,Fa as Te,Fr as Ee,Ft as De,H as Oe,I as ke,Ji as Ae,Qi as je,R as Me,Ra as Ne,St as Pe,Tn as Fe,V as Ie,W as Le,Xi as K,Xr as Re,_t as ze,bn as Be,bt as Ve,ea as He,ei as Ue,go as We,gt as Ge,hr as Ke,jo as qe,ko as Je,l as q,mr as Ye,mt as Xe,na as Ze,pt as Qe,ta as $e,un as et,vr as tt,vt as nt,xt as rt,z as it}from"./useMobileNavigationStore-DEUCakMd.js";import{t as at}from"./utils-BxJEIWv5.js";import{n as J}from"./Icon-DiIuWOuC.js";import{a as ot,n as st,o as ct,r as lt,t as ut}from"./dialog-COrLBm9O.js";import{t as dt}from"./button-DaAoVF4X.js";import{n as ft}from"./gitApi-Ctgr4Y9i.js";import{a as pt}from"./vendor-simplewebauthn-browser-Dwhcdg_5.js";import{N as mt,c as ht}from"./projectMeta-BbjPDSpU.js";import{t as gt}from"./input-XiL2-2gG.js";import{i as _t,n as vt,t as yt}from"./tooltip-BLugzWq-.js";import{A as bt,B as xt,I as St,J as Ct,K as wt,P as Tt,T as Et,b as Dt,n as Ot,q as kt,t as At,v as jt,w as Mt,x as Nt,y as Pt}from"./useSessionAutoCleanup-X6napv6d.js";import{n as Ft,r as It}from"./useThemeSystem-DMzWVJaW.js";import{B as Lt,Q as Rt,U as zt,W as Bt,Y as Vt,z as Y}from"./radio-CQrbmLB7.js";import{i as Ht}from"./OverlayScrollbar-Mi_WH4jv.js";import{C as Ut,S as Wt,b as Gt,x as Kt,y as qt}from"./markdownTheme-D-aLQZaM.js";import{D as Jt,J as Yt,X as Xt,Y as Zt,_ as Qt,et as $t,g as en,q as tn,s as nn,tt as rn,v as an}from"./ChatContainer-BhuJ17NV.js";import{r as on}from"./useRuntimeAPIs-DSLXJybW.js";import{t as sn}from"./useEffectiveDirectory-DD7JGLuB.js";import{n as cn,t as ln}from"./useFontPreferences-92Qg-98H.js";typeof window<`u`&&(window.__opencodeDebug={getLastAssistantMessage(){let e=q.getState().currentSessionId;if(!e)return null;let t=He(e);if(!t||t.length===0)return null;for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role===`assistant`){let e=($e(n.id)||[]).map(e=>{let t={id:e.id,type:e.type};return e.type===`text`?(t.text=e.text,t.textLength=e.text?.length||0):e.type===`tool`?(t.tool=e.tool,t.state=e.state?.status):(e.type===`step-start`||e.type===`step-finish`)&&(t.isStepMarker=!0),t}),t=e.some(e=>e.type===`text`&&e.text&&e.text.trim().length>0),r=e.some(e=>e.type===`tool`),i=e.some(e=>e.type===`step-start`||e.type===`step-finish`),a=e.length===0,o=!t&&!r&&(!a||i),s={messageId:n.id,role:n.role,timestamp:n.time?.created||0,partsCount:e.length,parts:e,isEmpty:a,isEmptyResponse:o,raw:n};return s.messageId,s.partsCount,s.isEmpty,s.isEmptyResponse,s.isEmpty&&console.warn(`[WARNING] Message has NO parts!`),s.isEmptyResponse&&(console.warn(`[WARNING] Message has parts but NO meaningful content (empty text, no tools)!`),i&&!t&&!r&&console.warn(`[CRITICAL] CLAUDE EMPTY RESPONSE BUG: Only step-start/step-finish markers, no actual content!`)),s}}return null},truncateString(e,t=80){return!e||typeof e!=`string`||e.length<=t?e:e.substring(0,t)+`…`},truncateMessages(e){return e.map(e=>({...e,parts:($e(e.id)||[]).map(e=>{let t={...e};return`text`in e&&(t.text=this.truncateString(e.text)),`textPreview`in e&&(t.textPreview=this.truncateString(e.textPreview)),e.state&&(t.state={...e.state},`output`in e.state&&(t.state.output=this.truncateString(e.state.output)),`error`in e.state&&(t.state.error=this.truncateString(e.state.error)),e.state.metadata&&`preview`in e.state.metadata&&(t.state.metadata={...e.state.metadata,preview:this.truncateString(e.state.metadata.preview)})),t})}))},getAllMessages(e=!1){let t=q.getState().currentSessionId;if(!t)return[];let n=He(t);return`${n.length}`,n.forEach((e,t)=>{let n=$e(e.id)||[];`${t}${e.role}${e.id}${n.length}`}),e?this.truncateMessages(n):n},async getAppStatus(){let e=ue.getState(),t=q.getState(),n=We.getState(),r=e.currentDirectory||null,i=ce.getDirectory()??null,a=Ze(),o=new Set,s={};a.forEach(e=>{let t=e.directory;typeof t==`string`&&t.trim().length>0?(o.add(t),s[t]=(s[t]??0)+1):s[`(none)`]=(s[`(none)`]??0)+1});let c=(()=>{if(typeof window>`u`)return{available:!1};try{return{available:!0,lastDirectory:window.localStorage.getItem(`lastDirectory`),homeDirectory:window.localStorage.getItem(`homeDirectory`)}}catch(e){return{available:!1,error:e instanceof Error?e.message:String(e)}}})(),l=N(),u=typeof window<`u`&&!!window.__OPENCHAMBER_ELECTRON__,d=async e=>{try{return await e.json()}catch{return null}},f=async e=>{try{return await e.text()}catch{return null}},p=async e=>{try{let t=await D(e);return t.ok?await d(t):{status:t.status}}catch(e){return{error:e instanceof Error?e.message:String(e)}}},m=null,h=null,g=null,_=null;try{let e=await ce.getSdkClient().path.get(r?{directory:r}:void 0);m=e.error?{error:e.error}:e.data}catch(e){m={error:e instanceof Error?e.message:String(e)}}try{let e=await ce.getSdkClient().project.current(r?{directory:r}:void 0);h=e.error?{error:e.error}:e.data}catch(e){h={error:e instanceof Error?e.message:String(e)}}g=await p(`/api/config/settings`);try{let e=await D(`/api/health`),t=e.headers.get(`content-type`)||``,n=await f(e),r=t.toLowerCase().includes(`application/json`),i=null;if(r&&n)try{let e=JSON.parse(n);e&&typeof e==`object`&&!Array.isArray(e)&&(i=e)}catch{i=null}_={status:e.status,ok:e.ok,contentType:t,type:r?`json`:`html`,openCodePort:i?.openCodePort??null,openCodeRunning:i?.openCodeRunning??null,openCodeSecureConnection:i?.openCodeSecureConnection??null,openCodeAuthSource:i?.openCodeAuthSource??null,isOpenCodeReady:i?.isOpenCodeReady??null,lastOpenCodeError:i?.lastOpenCodeError??null,preview:n?n.slice(0,120):null}}catch(e){_={error:e instanceof Error?e.message:String(e)}}let v={isGitRepo:null};if(r)try{v.isGitRepo=await ft(r)}catch(e){v={isGitRepo:null,error:e instanceof Error?e.message:String(e)}}let y=n.projects.map(e=>({id:e.id,path:e.path,label:e.label}));return{runtime:{platform:l?.runtime?.platform??null,isDesktop:u,isVSCode:!!l?.runtime?.isVSCode,hasRuntimeApis:!!l,desktopServerOrigin:null},location:typeof window<`u`?{href:window.location?.href??null,origin:window.location?.origin??null}:null,directories:{currentDirectory:r,opencodeDirectory:m?.directory||m?.worktree||i,homeDirectory:e.homeDirectory||null,isHomeReady:e.isHomeReady,hasPersistedDirectory:e.hasPersistedDirectory,isSwitchingDirectory:e.isSwitchingDirectory},projects:{total:n.projects.length,activeProjectId:n.activeProjectId,samples:y},sessions:{total:a.length,currentSessionId:t.currentSessionId,lastLoadedDirectory:t.lastLoadedDirectory,uniqueDirectories:o.size,directorySamples:Array.from(o).slice(0,5),directoryCounts:s},worktrees:{available:t.availableWorktrees.length,metadataEntries:t.worktreeMetadata.size},git:v,localStorage:c,opencode:{pathInfo:m,projectInfo:h,health:_},openchamber:{settingsInfo:g}}},async buildDiagnosticsReport(){let e=await this.getAppStatus();return JSON.stringify(e,null,2)},async copyTextToClipboard(e){return xe(e)},async copyDiagnosticsReport(){let e=await this.buildDiagnosticsReport();return{...await this.copyTextToClipboard(e),report:e}},checkLastMessage(){let e=this.getLastAssistantMessage();if(!e)return!1;let t=e.isEmpty||e.isEmptyResponse;return t&&(console.error(`[ALERT] PROBLEMATIC MESSAGE DETECTED!`),e.messageId,e.isEmpty,e.isEmptyResponse,e.partsCount,e.parts.length>0&&e.parts),t},getStreamingState(){let e=q.getState(),t=Be.getState(),n=e.currentSessionId?t.streamingMessageIds.get(e.currentSessionId)??null:null;return Array.from(t.streamingMessageIds.entries()),Array.from(t.messageStreamStates.entries()),{streamingMessageId:n,streamingMessageIds:t.streamingMessageIds,streamStates:t.messageStreamStates}},findEmptyMessages(){let e=q.getState().currentSessionId;if(!e)return[];let t=He(e).filter(e=>e.role===`assistant`).filter(e=>{let t=$e(e.id)||[],n=t.some(e=>e.type===`text`&&e.text&&e.text.trim().length>0),r=t.some(e=>e.type===`tool`);return t.length===0||!n&&!r});return`${t.length}`,t.forEach((e,t)=>{let n=$e(e.id)||[];`${t}`,e.id,n.length,e.providerID,e.modelID,e.time?.created}),t},showRetryHelp(){},analyzeMessageCompletionConsistency(e={}){let{includeNonAssistant:t=!1,verbose:n=!0,maxTableRows:r=25}=e,i=q.getState().currentSessionId;if(!i)return{summary:null,rows:[]};let a=He(i),o=t?a:a.filter(e=>e.role===`assistant`),s={totalMessages:a.length,analyzedMessages:o.length,completedMissing:0,completedBeforeTool:0,completedBeforeReasoning:0,runningToolsWhenCompleted:0,reasoningOpenWhenCompleted:0,withTools:0,withReasoning:0},c=e=>typeof e==`number`&&Number.isFinite(e)?e:null,l=e=>{let t=e.filter(e=>typeof e==`number`);return t.length>0?Math.max(...t):null},u=o.map((e,t)=>{let n=e,r=$e(e.id)||[],i=n.time??{},a=c(i.completed),o=a!==null,u=r.filter(e=>e.type===`tool`),d=r.filter(e=>e.type===`reasoning`),f=l(u.map(e=>c(e.state?.time?.end??e.state?.time?.start))),p=l(d.map(e=>c(e.time?.end??e.time?.start))),m=l([f,p].filter(e=>e!==null)),h=u.some(e=>[`pending`,`running`,`started`].includes(e.state?.status)),g=d.some(e=>typeof e.time?.end!=`number`);u.length>0&&(s.withTools+=1),d.length>0&&(s.withReasoning+=1),o||(s.completedMissing+=1);let _=!!(o&&typeof f==`number`&&a<f);_&&(s.completedBeforeTool+=1);let v=!!(o&&typeof p==`number`&&a<p);return v&&(s.completedBeforeReasoning+=1),o&&h&&(s.runningToolsWhenCompleted+=1),o&&g&&(s.reasoningOpenWhenCompleted+=1),{index:t,messageId:n.id,role:n.role,completedAt:a,latestToolTimestamp:f,latestReasoningTimestamp:p,latestPartTimestamp:m,completed_missing:!o,completed_before_tool:_,completed_before_reasoning:v,running_tools_when_completed:!!(o&&h),reasoning_open_when_completed:!!(o&&g),has_tools:u.length>0,has_reasoning:d.length>0}});return n&&(console.table(u.slice(0,r)),u.length>r&&`${r}${u.length}`),{summary:s,rows:u}},checkCompletionStatus(){let e=q.getState().currentSessionId;if(!e)return null;let t=He(e).filter(e=>e.role===`assistant`);if(t.length===0)return null;let n=t[t.length-1],r=($e(n.id)||[]).filter(e=>e.type===`step-finish`),i=n.finish===`stop`,a=n.time?.completed,o=n.status,s=typeof a==`number`&&a>0||o===`completed`,c=!!(s&&i),l=Be.getState();n.sessionID&&l.streamingMessageIds.get(n.sessionID);let u=l.messageStreamStates.get(n.id);return n.id,n.id,u?.phase,{messageId:n.id,completed:a,status:o,hasCompletedFlag:s,hasStopReason:i,messageIsComplete:c,stepFinishParts:r,raw:n}}},le(),window.addEventListener(`error`,e=>{try{let t=e.message||``,n=e.filename||``;typeof t==`string`&&t.includes(`this._renderer.value.dimensions`)&&/xterm/i.test(String(n))&&e.preventDefault()}catch{}}));var X=e(se(),1),Z=fe(),un=async()=>{if(typeof window>`u`)return;let e=null;try{e=y(`lastDirectory`)}catch(e){console.warn(`Failed to read saved directory preferences:`,e)}e&&!_()&&ue.getState().setDirectory(e,{showOverlay:!1})},dn=new Map,fn=e=>dn.get(e)??null,pn=({runtimeKey:e,initializeAppearance:t,syncSettings:n,applyDirectory:r,onError:i},a={})=>{let o=dn.get(e);if(o&&!a.force)return o;let s=(async()=>{o&&await o;try{await t()}catch(e){return i(`appearance`,e),!1}try{await Promise.all([n(),r()])}catch(e){i(`secondary`,e)}return!0})();return dn.set(e,s),s},mn=async({runtimeKey:e,initializeAppearance:t,syncSettings:n,applyDirectory:r,startWatchers:i,onError:a})=>{await pn({runtimeKey:e,initializeAppearance:t,syncSettings:n,applyDirectory:r,onError:a})&&i()},hn=(e,t=50)=>{let n=null,r;return{schedule:i=>{r=i,n&&clearTimeout(n),n=setTimeout(()=>{n=null;let t=r;r=void 0,t!==void 0&&e(t)},t)},cancel:()=>{n&&clearTimeout(n),n=null,r=void 0}}};function gn(e){return!e||e===`idle`?null:e===`ready`?`ok`:e===`error`?`unreachable`:`auth`}function _n(e,t){let n=e.via===`relay`;return t?n:!n}function vn(e){let{isActive:t,isSsh:n,runtimeIsConnected:r,runtimeConnectionPhase:i,currentTransportIsRelay:a,probe:o,sshPhase:s}=e,c;c=t?r&&i===`connected`?`ok`:`checking`:n?gn(s):o?.status??`checking`;let l=t?a:o?.via===`relay`,u=null;return!n&&c===`ok`&&o?.status===`ok`&&typeof o.latencyMs==`number`&&(!t||_n(o,a))&&(u=Math.max(0,Math.round(o.latencyMs))),{statusKind:c,showViaRelay:l,latencyMs:u}}var Q=W(),$=`local`,yn=9e4,bn=`SSH connection cancelled`,xn=e=>U(e),Sn={},Cn=e=>{let t=V(e);if(!t)return e.trim();try{let e=new URL(t);return e.pathname.endsWith(`/`)||(e.pathname=`${e.pathname}/`),e.toString()}catch{return t}},wn=()=>typeof window>`u`?``:window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,Tn=async()=>S()?B().catch(()=>``):``,En=e=>e===`ok`?`bg-status-success`:e===`auth`||e===`update-recommended`?`bg-status-warning`:e===`incompatible`||e===`wrong-service`||e===`unreachable`?`bg-status-error`:e===`checking`?`bg-status-info`:`bg-muted-foreground/40`,Dn=e=>e===`ok`?`text-[var(--status-success)]`:e===`auth`||e===`update-recommended`?`text-[var(--status-warning)]`:e===`incompatible`||e===`wrong-service`||e===`unreachable`?`text-[var(--status-error)]`:`text-muted-foreground`,On=e=>e===`unreachable`||e===`wrong-service`||e===`incompatible`,kn=e=>e===`unreachable`||e===`wrong-service`||e===`incompatible`,An=e=>e===`ok`?`desktopHostSwitcher.status.connected`:e===`auth`?`desktopHostSwitcher.status.authRequired`:e===`checking`?`desktopHostSwitcher.status.checking`:e===`update-recommended`?`desktopHostSwitcher.status.updateRecommended`:e===`incompatible`?`desktopHostSwitcher.status.incompatible`:e===`wrong-service`?`desktopHostSwitcher.status.wrongService`:e===`unreachable`?`desktopHostSwitcher.status.unreachable`:`desktopHostSwitcher.status.unknown`,jn=e=>new Promise(t=>window.setTimeout(t,e)),Mn=e=>{switch(e){case`ready`:return`desktopHostSwitcher.sshPhase.ready`;case`error`:return`desktopHostSwitcher.sshPhase.error`;case`degraded`:return`desktopHostSwitcher.sshPhase.reconnecting`;case`config_resolved`:return`desktopHostSwitcher.sshPhase.resolvingConfig`;case`auth_check`:return`desktopHostSwitcher.sshPhase.checkingAuth`;case`master_connecting`:return`desktopHostSwitcher.sshPhase.connectingSsh`;case`remote_probe`:return`desktopHostSwitcher.sshPhase.probingRemote`;case`installing`:return`desktopHostSwitcher.sshPhase.installing`;case`updating`:return`desktopHostSwitcher.sshPhase.updating`;case`server_detecting`:return`desktopHostSwitcher.sshPhase.detectingServer`;case`server_starting`:return`desktopHostSwitcher.sshPhase.startingServer`;case`forwarding`:return`desktopHostSwitcher.sshPhase.forwardingPorts`;default:return`desktopHostSwitcher.sshPhase.idle`}},Nn=async()=>{let e=await xt().catch(()=>[]),t={};for(let n of e)t[n.id]=n;return t},Pn=async(e,t,n,r)=>{let i=Date.now()+t;for(;Date.now()<i;){if(r?.())throw Error(bn);let t=(await xt(e).catch(()=>[])).find(t=>t.id===e);if(t){if(n(t),t.phase===`ready`)return t;if(t.phase===`error`)throw Error(t.detail||`SSH connection failed`)}await jn(700)}throw r?.()?Error(bn):Error(`Timed out waiting for SSH connection`)},Fn=e=>({id:$,label:`Local`,url:e||wn()}),In=e=>{let t=typeof window>`u`?``:window.location.href,r=e.find(e=>e.id===$)?.url||wn(),i=h(),a=V(r)||r,o=V(t)||t,s=n(),c=e.find(e=>e.relay&&xn(e)===s);if(c)return{id:c.id,label:c.label,url:c.url};if(i&&I(i,r))return{id:$,label:`Local`,url:a};let l=e.find(e=>i?I(i,R(e)):!1);if(l)return{id:l.id,label:l.label,url:V(R(l))||R(l)};if(t&&I(t,r))return{id:$,label:`Local`,url:a};let u=e.find(e=>t?I(t,e.url):!1);return u?{id:u.id,label:u.label,url:V(u.url)||u.url}:t.startsWith(`openchamber-ui://`)?{id:$,label:`Local`,url:a}:{id:`custom`,label:L(o||`Instance`),url:o}};function Ln({open:e,onOpenChange:r,embedded:i=!1,onHostSwitched:a}){let{t:o}=ve(),s=p(e=>e.setSettingsDialogOpen),c=p(e=>e.setSettingsPage),u=K(e=>e.isConnected),d=K(e=>e.connectionPhase),[f,m]=X.useState([]),[h,g]=X.useState(null),[_,v]=X.useState(()=>({...Sn}));X.useEffect(()=>{Object.assign(Sn,_)},[_]);let[y,x]=X.useState(!1),[C,w]=X.useState(!1),[T,E]=X.useState(!1),D=kt(),O=Ct(),[ee,k]=X.useState(null),A=ee||O,[j,M]=X.useState({}),[N,I]=X.useState({}),[B,U]=X.useState({open:!1,hostId:null,hostLabel:``,phase:`idle`,detail:null,error:null}),[ae,oe]=X.useState(``),[W,se]=X.useState(()=>wn()),[G,ce]=X.useState(null),[le,ue]=X.useState(``),[de,fe]=X.useState(``),[pe,me]=X.useState(0),he=X.useRef(0),_e=X.useMemo(()=>[Fn(W),...f.map(e=>({...e,url:V(e.url)||e.url}))],[f,W]),ye=X.useMemo(()=>new Set(Object.keys(j)),[j]),be=X.useMemo(()=>_e.filter(e=>e.id===$||F(e,ye)),[_e,ye]);X.useEffect(()=>l(()=>me(e=>e+1)),[]);let xe=X.useMemo(()=>In(_e),[_e,pe]),Se=X.useMemo(()=>t().startsWith(`relay:`),[pe]),Ce=X.useMemo(()=>{let e=h||$;return _e.find(t=>t.id===e)?.label||o(`desktopHostSwitcher.instance.local`)},[_e,h,o]),we=X.useCallback(async(e,t)=>{if(b()){E(!0),oe(``);try{let n=e.filter(e=>e.id!==$);await te({hosts:n,defaultHostId:t}),m(n),g(t)}catch(e){oe(e instanceof Error?e.message:o(`desktopHostSwitcher.error.failedToSave`))}finally{E(!1)}}},[o]),Te=X.useCallback(()=>{c(`remote-instances`),s(!0),r(!1)},[r,s,c]),Ee=X.useCallback(async()=>{if(b()){x(!0),oe(``);try{let[e,t,n]=await Promise.all([H(),St().catch(()=>({instances:[]})),Nn()]);e.localOrigin&&se(e.localOrigin);let r={};for(let e of t.instances)r[e.id]=!0;m(e.hosts||[]),g(e.defaultHostId??null),M(r),I(n)}catch(e){oe(e instanceof Error?e.message:o(`desktopHostSwitcher.error.failedToLoad`)),m([]),g(null),M({}),I({})}finally{x(!1)}}},[o]),De=X.useCallback(async e=>{if(b()){w(!0);try{let t=await Tn(),n=await Promise.all(e.map(async e=>{let n=async()=>{let t=await ne(e.relay,{sshTarget:e.sshTarget}).catch(()=>({status:`unreachable`,latencyMs:0}));return{status:t.status,latencyMs:t.latencyMs,...t.status===`ok`?{via:`relay`}:{}}};if(e.relay&&!e.apiUrl)return[e.id,await n()];let r=V(S()?R(e):e.url);if(!r)return[e.id,{status:`unreachable`,latencyMs:0}];let i=e.id===$?t:e.clientToken||``,a=await z(r,{clientToken:i||null,requestHeaders:e.requestHeaders||null}).catch(()=>({status:`unreachable`,latencyMs:0}));if(On(a.status)&&e.relay){let t=await n();if(t.status===`ok`)return[e.id,t]}return[e.id,{status:a.status,latencyMs:a.latencyMs}]})),r={};for(let[e,t]of n)r[e]=t;v(r)}finally{w(!1)}}},[]);X.useEffect(()=>{if(!e){ce(null),ue(``),fe(``),k(null),U({open:!1,hostId:null,hostLabel:``,phase:`idle`,detail:null,error:null}),oe(``);return}Ee()},[e,Ee]),X.useEffect(()=>{e&&De(be)},[e,be,De]),X.useEffect(()=>{if(!e||!b())return;let t=!1,n=async()=>{let e=await Nn();t||I(e)};n();let r=window.setInterval(()=>{typeof document<`u`&&document.visibilityState!==`visible`||n()},1500);return()=>{t=!0,window.clearInterval(r)}},[e]);let Oe=ge(async e=>{let t=e.id===$?W:V(e.url)||``,r=e.id===$?W:V(R(e))||``,i=!!e.relay&&!e.apiUrl&&e.id!==$;if(e.viaSshRelay&&Se){if(D)return;if(n()===xn(e)){a?.();return}let t=await wt({host:e});v(n=>({...n,[e.id]:t.status})),t.ok&&a?.();return}if(!t&&!i)return;if(S()){if(!r&&!e.relay||D)return;let t=e.id===$?await Tn():null,n=await wt({host:e,cachedProbe:_[e.id]||null,...e.id===$?{localApiOrigin:r,localClientToken:t}:{}});v(t=>({...t,[e.id]:n.status})),n.ok&&a?.();return}let s=!!j[e.id];if(e.id!==$&&s&&b()){let n=N[e.id],r=await xt(e.id).then(t=>t.find(t=>t.id===e.id)||null).catch(()=>null);r&&(n=r,I(t=>({...t,[e.id]:r})));let i=V(n?.localUrl||e.url||``);if(n?.phase===`ready`&&i){let e=Cn(i);a?.(),window.location.assign(e);return}k(e.id);let s=he.current+1;he.current=s,U({open:!0,hostId:e.id,hostLabel:L(e.label),phase:`master_connecting`,detail:null,error:null});try{if(await bt(e.id),s!==he.current)return;let n=await Pn(e.id,yn,e=>{I(t=>({...t,[e.id]:e})),U(t=>({...t,phase:e.phase,detail:e.detail||null}))},()=>s!==he.current);if(s!==he.current)return;let r=Cn(V(n.localUrl||``)||t);a?.(),window.location.assign(r);return}catch(t){if(s!==he.current)return;let n=t instanceof Error?t.message:String(t);if(n===bn)return;U(e=>({...e,error:n})),tt.error(o(`desktopHostSwitcher.toast.sshFailedToConnect`,{host:L(e.label)}),{description:n});return}finally{s===he.current&&k(null)}}if(e.id!==$&&b()){k(e.id);let n=await z(t,{clientToken:e.clientToken||null,requestHeaders:e.requestHeaders||null}).catch(()=>({status:`unreachable`,latencyMs:0}));if(v(t=>({...t,[e.id]:{status:n.status,latencyMs:n.latencyMs}})),On(n.status)){tt.error(o(`desktopHostSwitcher.toast.instanceUnreachable`,{host:L(e.label)})),k(null);return}}let c=Cn(t);a?.();try{window.location.assign(c)}catch{window.location.href=c}}),ke=X.useCallback(()=>{ce(null),ue(``),fe(``)},[]),Ae=X.useCallback(e=>{e.stopPropagation()},[]),je=X.useCallback(async()=>{if(!G)return;if(G===$){ke();return}let e=ie(de);if(!e){oe(o(`desktopHostSwitcher.error.invalidUrl`));return}let t=e.persistedUrl,n=(le||L(t)).trim(),r=f.map(e=>e.id===G?{...e,label:n,url:t,apiUrl:t}:e);await we(r,h),ke(),e.redeemUrl&&window.location.assign(e.redeemUrl)},[ke,f,h,le,de,G,we,o]),Me=X.useCallback(async e=>{await we(f,e===$?$:e)},[f,we]),Ne=X.useCallback(e=>{let t=e=>{tt.error(o(`desktopHostSwitcher.error.failedToOpenNewWindow`),{description:e instanceof Error?e.message:String(e)})};if(e.relay&&e.id!==$){P(e.id).catch(t);return}let n=e.id===$?W:R(e);if(!n)return;let r=Cn(n);re(r,{clientToken:e.clientToken||null,requestHeaders:e.requestHeaders||null}).catch(t)},[W,o]),Pe=ge(async()=>{he.current+=1,k(null),U(e=>({...e,open:!1,hostId:null,error:null,detail:null,phase:`idle`}));let e=Cn(W);if(S()){if(D)return;let e=await Tn();(await wt({host:Fn(W),localApiOrigin:W,localClientToken:e})).ok&&a?.();return}a?.(),window.location.assign(e)}),Fe=X.useCallback(async()=>{let e=B.hostId||A;he.current+=1,k(null),U({open:!1,hostId:null,hostLabel:``,phase:`idle`,detail:null,error:null}),!(!e||e===$||!b())&&await Tt(e).catch(()=>{})},[B.hostId,A]),Ie=X.useCallback(()=>{let e=B.hostId;if(!e)return;let t=_e.find(t=>t.id===e);t&&Oe(t)},[_e,Oe,B.hostId]),Le=X.useCallback(async e=>{if(b()){k(e.id);try{await bt(e.id),(await Pn(e.id,yn,e=>{I(t=>({...t,[e.id]:e}))})).phase===`ready`&&tt.success(o(`desktopHostSwitcher.toast.sshConnected`,{host:L(e.label)}))}catch(t){let n=t instanceof Error?t.message:String(t);n!==bn&&tt.error(o(`desktopHostSwitcher.toast.sshFailedToConnect`,{host:L(e.label)}),{description:n})}finally{k(null)}}},[o]);if(!b())return null;let Re=b(),ze=(0,Q.jsxs)(Q.Fragment,{children:[i?(0,Q.jsx)(`div`,{className:`flex-shrink-0 border-b border-[var(--interactive-border)] px-3 py-2`,children:(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,Q.jsxs)(`div`,{className:`min-w-0 flex items-baseline gap-1.5 typography-ui-label`,children:[(0,Q.jsx)(`span`,{className:`font-medium text-foreground`,children:o(`desktopHostSwitcher.header.current`)}),(0,Q.jsx)(`span`,{className:`max-w-[9rem] truncate text-muted-foreground`,children:L(xe.label)}),(0,Q.jsx)(`span`,{className:`text-muted-foreground/50`,children:`•`}),(0,Q.jsx)(`span`,{className:`font-medium text-foreground`,children:o(`desktopHostSwitcher.header.default`)}),(0,Q.jsx)(`span`,{className:`max-w-[9rem] truncate text-muted-foreground`,children:L(Ce)})]}),(0,Q.jsx)(`button`,{type:`button`,className:at(`inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors`,`hover:text-foreground hover:bg-interactive-hover`,`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary`),onClick:()=>void De(be),disabled:!Re||y||C,"aria-label":o(`desktopHostSwitcher.actions.refreshInstancesAria`),children:(0,Q.jsx)(J,{name:`refresh`,className:at(`h-4 w-4`,C&&`animate-spin`)})})]})}):(0,Q.jsxs)(ot,{className:`flex-shrink-0`,children:[(0,Q.jsxs)(ct,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(J,{name:`server`,className:`h-5 w-5`}),o(`desktopHostSwitcher.title`)]}),(0,Q.jsx)(lt,{children:o(`desktopHostSwitcher.description`)})]}),!i&&(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-2 flex-shrink-0`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 min-w-0`,children:[(0,Q.jsx)(`span`,{className:`typography-meta text-muted-foreground`,children:o(`desktopHostSwitcher.header.currentColon`)}),(0,Q.jsx)(`span`,{className:`typography-ui-label text-foreground truncate`,children:L(xe.label)}),(0,Q.jsx)(`span`,{className:`typography-meta text-muted-foreground`,children:o(`desktopHostSwitcher.header.currentDefaultColon`)}),(0,Q.jsx)(`span`,{className:`typography-ui-label text-foreground truncate`,children:L(Ce)})]}),(0,Q.jsx)(`div`,{className:`flex items-center gap-1`,children:(0,Q.jsxs)(dt,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>void De(be),disabled:!Re||y||C,children:[(0,Q.jsx)(J,{name:`refresh`,className:at(`h-4 w-4`,C&&`animate-spin`)}),o(`desktopHostSwitcher.actions.refresh`)]})})]}),!Re&&(0,Q.jsx)(`div`,{className:`flex-shrink-0 rounded-lg border border-border/50 bg-muted/20 p-3`,children:(0,Q.jsx)(`div`,{className:`typography-meta text-muted-foreground`,children:o(`desktopHostSwitcher.state.limitedOnPage`)})}),(0,Q.jsx)(`div`,{className:`flex-1 min-h-0 overflow-y-auto`,children:(0,Q.jsx)(`div`,{className:at(`space-y-1`,i&&`space-y-1.5 px-3 py-1`),children:y?(0,Q.jsx)(`div`,{className:`px-2 py-2 text-muted-foreground text-sm`,children:o(`desktopHostSwitcher.state.loading`)}):be.map(e=>{let t=e.id===$,n=!!j[e.id],r=e.id===xe.id,a=(h||$)===e.id,s=_[e.id]||null,c=N[e.id]||null,l=vn({isActive:r,isSsh:n,runtimeIsConnected:u,runtimeConnectionPhase:d,currentTransportIsRelay:Se,probe:s,sshPhase:c?.phase}),f=l.statusKind,p=l.showViaRelay,m=G===e.id,g=t?W:V(e.url)||e.url,v=e.id===$?o(`desktopHostSwitcher.instance.local`):L(e.label),y=e.relay&&!e.apiUrl?o(`mobile.connect.relay.badge`):L(g);return(0,Q.jsxs)(`div`,{className:at(`group flex items-center gap-2 px-2.5 py-2 rounded-md overflow-hidden`,i&&`rounded-xl bg-[var(--surface-muted)] px-3 py-2.5`,i&&r&&`bg-[var(--interactive-selection)]/25`,m?`bg-interactive-hover/20`:`hover:bg-interactive-hover/30`),children:[(0,Q.jsxs)(`button`,{type:`button`,className:at(`flex items-center gap-2 flex-1 min-w-0 text-left`,m&&`pointer-events-none opacity-70`),onClick:()=>void Oe(e),disabled:A===e.id,"aria-label":o(`desktopHostSwitcher.actions.switchToAria`,{instance:v}),children:[(0,Q.jsx)(`span`,{className:at(`h-2 w-2 rounded-full flex-shrink-0`,En(f))}),(0,Q.jsxs)(`div`,{className:`flex-1 min-w-0 space-y-0.5`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 items-center gap-1.5`,children:[(0,Q.jsx)(`span`,{className:`typography-ui-label font-medium truncate text-foreground`,children:v}),r&&(0,Q.jsx)(`span`,{className:`typography-micro flex-shrink-0 text-muted-foreground bg-muted px-1 rounded leading-none pb-px border border-border/50`,children:o(`desktopHostSwitcher.header.current`)}),n&&(0,Q.jsx)(`span`,{className:`typography-micro flex-shrink-0 px-1 rounded leading-none pb-px text-[var(--status-info)] bg-[var(--status-info)]/10`,children:`SSH`})]}),(0,Q.jsxs)(`div`,{className:at(`typography-micro truncate`,Dn(f)),children:[o(n&&!r?Mn(c?.phase):An(f)),l.latencyMs==null?``:o(`desktopHostSwitcher.status.ping`,{ms:l.latencyMs}),p?` · ${o(`settings.remoteInstances.clientAuth.state.viaRelay`)}`:``]}),(0,Q.jsx)(`div`,{className:`typography-micro text-muted-foreground/70 truncate font-mono`,children:y})]})]}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 flex-shrink-0`,children:[n&&!t&&(c?.phase===`idle`||!c?.phase?(0,Q.jsxs)(dt,{type:`button`,variant:`outline`,size:`sm`,className:`h-8 px-2.5`,disabled:A===e.id,onClick:t=>{t.stopPropagation(),Le(e)},children:[A===e.id?(0,Q.jsx)(J,{name:`loader-4`,className:`h-3.5 w-3.5 animate-spin`}):(0,Q.jsx)(J,{name:`plug-2`,className:`h-3.5 w-3.5`}),o(`desktopHostSwitcher.actions.connect`)]}):(0,Q.jsx)(`div`,{className:`h-8 w-8 opacity-0 pointer-events-none`,"aria-hidden":`true`})),(0,Q.jsxs)(yt,{children:[(0,Q.jsx)(_t,{asChild:!0,children:(0,Q.jsx)(`button`,{type:`button`,className:at(`h-8 w-8 rounded-md inline-flex items-center justify-center hover:bg-interactive-hover transition-colors`,a?`text-primary hover:text-primary/80`:`text-muted-foreground/60 hover:text-primary/80`),onClick:()=>void Me(e.id),"aria-label":o(a?`desktopHostSwitcher.actions.defaultInstanceAria`:`desktopHostSwitcher.actions.setAsDefaultAria`),disabled:T||!a&&kn(f),children:a?(0,Q.jsx)(J,{name:`star-fill`,className:`h-4 w-4`}):(0,Q.jsx)(J,{name:`star`,className:`h-4 w-4`})})}),(0,Q.jsx)(vt,{sideOffset:6,children:o(a?`desktopHostSwitcher.header.default`:`desktopHostSwitcher.actions.setAsDefault`)})]}),(0,Q.jsxs)(yt,{children:[(0,Q.jsx)(_t,{asChild:!0,children:(0,Q.jsx)(`button`,{type:`button`,className:at(`h-8 w-8 rounded-md inline-flex items-center justify-center hover:bg-interactive-hover transition-colors`,kn(f)?`text-muted-foreground/30 cursor-not-allowed`:`text-muted-foreground/60 hover:text-foreground`),onClick:t=>{t.stopPropagation(),Ne(e)},disabled:kn(f),"aria-label":o(`desktopHostSwitcher.actions.openInNewWindowAria`),children:(0,Q.jsx)(J,{name:`window`,className:`h-4 w-4`})})}),(0,Q.jsx)(vt,{sideOffset:6,children:kn(f)?o(`desktopHostSwitcher.state.instanceUnreachable`):o(`desktopHostSwitcher.actions.openInNewWindow`)})]})]})]},e.id)})})}),Re&&G&&G!==$&&(0,Q.jsxs)(`div`,{className:`flex-shrink-0 rounded-lg border border-border/50 bg-muted/20 p-3`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Q.jsx)(`div`,{className:`typography-ui-label font-medium text-foreground`,children:o(`desktopHostSwitcher.edit.title`)}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(dt,{type:`button`,variant:`outline`,size:`sm`,onClick:ke,disabled:T,children:o(`desktopHostSwitcher.actions.cancel`)}),(0,Q.jsxs)(dt,{type:`button`,size:`sm`,onClick:()=>void je(),disabled:T,children:[T?(0,Q.jsx)(J,{name:`loader-4`,className:`h-4 w-4 animate-spin`}):null,o(`desktopHostSwitcher.actions.save`)]})]})]}),(0,Q.jsxs)(`div`,{className:`mt-2 grid grid-cols-1 gap-2 sm:grid-cols-2`,children:[(0,Q.jsx)(gt,{value:le,onChange:e=>ue(e.target.value),onKeyDown:Ae,placeholder:o(`desktopHostSwitcher.field.labelPlaceholder`),disabled:T}),(0,Q.jsx)(gt,{value:de,onChange:e=>fe(e.target.value),onKeyDown:Ae,placeholder:o(`desktopHostSwitcher.field.urlPlaceholder`),disabled:T})]})]}),(0,Q.jsx)(`div`,{className:`flex-shrink-0 border-t border-[var(--interactive-border)]`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`w-full flex items-center gap-2 px-2 py-2 text-left text-muted-foreground hover:text-foreground hover:bg-interactive-hover/30 transition-colors`,onClick:Te,children:[(0,Q.jsx)(J,{name:`add`,className:`h-4 w-4`}),(0,Q.jsx)(`span`,{className:`typography-ui-label`,children:o(`desktopHostSwitcher.actions.addInstance`)})]})}),ae&&(0,Q.jsx)(`div`,{className:`flex-shrink-0 typography-meta text-status-error`,children:ae})]}),Be=(0,Q.jsx)(ut,{open:B.open,onOpenChange:e=>{if(!e&&A){Fe();return}U(t=>({...t,open:e,...e?{}:{hostId:null,error:null,detail:null,phase:`idle`}}))},children:(0,Q.jsxs)(st,{className:`w-[min(28rem,calc(100vw-2rem))] max-w-none`,children:[(0,Q.jsxs)(ot,{children:[(0,Q.jsxs)(ct,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(J,{name:`loader-4`,className:at(`h-4 w-4`,!B.error&&`animate-spin`)}),o(`desktopHostSwitcher.ssh.connectingTo`,{host:B.hostLabel||o(`desktopHostSwitcher.ssh.instanceFallback`)})]}),(0,Q.jsx)(lt,{children:B.error?B.error:B.detail||o(Mn(B.phase))})]}),B.error?(0,Q.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Q.jsx)(dt,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>void Pe(),children:o(`desktopHostSwitcher.actions.switchToLocal`)}),(0,Q.jsx)(dt,{type:`button`,size:`sm`,onClick:Ie,disabled:!B.hostId,children:o(`desktopHostSwitcher.actions.retry`)})]}):null]})});return i?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`w-full max-h-[70vh] flex flex-col overflow-hidden gap-2`,children:ze}),Be]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(ut,{open:e,onOpenChange:r,children:(0,Q.jsx)(st,{className:`w-[min(42rem,calc(100vw-2rem))] max-w-none max-h-[70vh] flex flex-col overflow-hidden gap-3`,children:ze})}),Be]})}function Rn(){let e=(0,Z.c)(11),[t,n]=X.useState(!1),{t:r}=ve();if(!b())return null;let i,a;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(i=()=>n(!0),a=(0,Q.jsx)(J,{name:`server`,className:`h-4 w-4`}),e[0]=i,e[1]=a):(i=e[0],a=e[1]);let o;e[2]===r?o=e[3]:(o=r(`desktopHostSwitcher.actions.switchInstance`),e[2]=r,e[3]=o);let s;e[4]===o?s=e[5]:(s=(0,Q.jsxs)(dt,{type:`button`,variant:`ghost`,size:`sm`,"data-oc-host-switcher":!0,className:`w-full justify-center`,onClick:i,children:[a,o]}),e[4]=o,e[5]=s);let c;e[6]===t?c=e[7]:(c=(0,Q.jsx)(Ln,{open:t,onOpenChange:n}),e[6]=t,e[7]=c);let l;return e[8]!==s||e[9]!==c?(l=(0,Q.jsxs)(Q.Fragment,{children:[s,c]}),e[8]=s,e[9]=c,e[10]=l):l=e[10],l}var zn=e=>e.shouldUseDesktopShellPasswordLogin?`locked`:`error`,Bn=`/auth/session`,Vn=4,Hn=1500,Un=`openchamber.uiAuth.trustDevice`,Wn=`desktop-local`,Gn=`desktop-local`,Kn=()=>{if(typeof window>`u`)return``;let e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof e==`string`?e.trim():``},qn=(e,t)=>{let n=V(e),r=V(t);if(!n||!r)return!1;try{return new URL(n).origin===new URL(r).origin}catch{return!1}},Jn=()=>b(),Yn=e=>{let t=e.replace(/^\[|\]$/g,``);return t===`localhost`||t===`127.0.0.1`||t===`::1`},Xn=()=>{if(!b())return!1;let e=Kn();if(!e)return!1;let t=h()||(typeof window<`u`?window.location.origin:``);if(qn(e,t))return!0;try{let e=V(t);return!!(e&&Yn(new URL(e).hostname))}catch{return!1}},Zn=()=>Xn()?{clientKind:Wn,dedupeKey:Gn}:{},Qn=async()=>await D(Bn,{method:`GET`,credentials:`include`,headers:{Accept:`application/json`}}),$n=()=>typeof window>`u`?!1:window.localStorage.getItem(Un)===`true`,er=async(e,t)=>{let n=Jn();return await D(Bn,{method:`POST`,credentials:`include`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({password:e,trustDevice:t,issueClientToken:n,clientLabel:`OpenChamber Desktop`,...Zn()})})},tr=async()=>{if(!b())return``;let e=await D(`/api/client-auth/clients`,{method:`POST`,credentials:`include`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({label:`OpenChamber Desktop`,...Zn()})}).catch(()=>null);if(!e?.ok)return``;let t=await e.json().catch(()=>null);return typeof t?.token==`string`?t.token.trim():``},nr=()=>b()&&!Xn(),rr=async(e,t)=>{if(!b()||typeof window>`u`)return null;let n=await k(`desktop_remote_password_login`,{url:h(),password:e,trustDevice:t,requestHeaders:i()}).catch(()=>null);if(!n||typeof n!=`object`)return null;let r=n.token,a=n.status;return{token:typeof r==`string`?r.trim():``,...typeof a==`number`?{status:a}:{}}},ir=async(e,t)=>{if(!b()||!t)return;let n=await H().catch(()=>null);if(!n)return;if(n.localOrigin&&qn(n.localOrigin,e)){await te({hosts:n.hosts,defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted,localClientToken:t}).catch(()=>void 0);return}let r=!1,i=n.hosts.map(n=>!qn(R(n),e)||n.clientToken===t?n:(r=!0,{...n,clientToken:t}));r&&await te({hosts:i,defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted}).catch(()=>void 0)},ar=async e=>{if(!e)return;let t=h(),n=i();await ir(t,e),a({apiBaseUrl:t,clientToken:e,requestHeaders:Object.keys(n).length>0?n:null})},or=e=>{let t=(0,Z.c)(7),{children:n}=e,r;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(r={height:`var(--oc-wco-titlebar-height, 0px)`,right:`var(--oc-wco-right-inset, 0px)`},t[0]=r):r=t[0];let i=r,a,o;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(a={fontFamily:`"Inter", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", sans-serif`},o=(0,Q.jsx)(`div`,{className:`app-region-drag fixed left-0 top-0 z-20`,style:i,"aria-hidden":!0}),t[1]=a,t[2]=o):(a=t[1],o=t[2]);let s;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(s=(0,Q.jsx)(`div`,{className:`pointer-events-none absolute inset-0 opacity-55`,style:{background:`radial-gradient(120% 140% at 50% -20%, var(--surface-overlay) 0%, transparent 68%)`}}),t[3]=s):s=t[3];let c;t[4]===Symbol.for(`react.memo_cache_sentinel`)?(c=(0,Q.jsx)(`div`,{className:`pointer-events-none absolute inset-0`,style:{backgroundColor:`var(--surface-subtle)`,opacity:.22}}),t[4]=c):c=t[4];let l;return t[5]===n?l=t[6]:(l=(0,Q.jsxs)(`div`,{className:`relative flex min-h-screen items-center justify-center overflow-hidden bg-background text-foreground`,style:a,children:[o,s,c,(0,Q.jsx)(`div`,{className:`app-region-no-drag relative z-10 flex w-full justify-center px-4 py-12 sm:px-6`,children:n})]}),t[5]=n,t[6]=l),l},sr=()=>{let e=(0,Z.c)(1),t;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,Q.jsx)(`div`,{className:`flex min-h-screen items-center justify-center bg-background text-foreground`,children:(0,Q.jsx)(Rt,{width:120,height:120})}),e[0]=t):t=e[0],t},cr=e=>{let t=(0,Z.c)(23),{onRetry:n,errorType:r,retryAfter:i,children:a}=e,o=r===void 0?`network`:r,{t:s}=ve(),c=o===`rate-limit`,l=i?Math.ceil(i/60):1,u;t[0]!==c||t[1]!==s?(u=s(c?`sessionAuth.error.rateLimitTitle`:`sessionAuth.error.networkTitle`),t[0]=c,t[1]=s,t[2]=u):u=t[2];let d;t[3]===u?d=t[4]:(d=(0,Q.jsx)(`h1`,{className:`typography-ui-header font-semibold text-destructive`,children:u}),t[3]=u,t[4]=d);let f;t[5]!==c||t[6]!==l||t[7]!==s?(f=c?s(l>1?`sessionAuth.error.rateLimitDescriptionPlural`:`sessionAuth.error.rateLimitDescriptionSingle`,{minutes:l}):s(`sessionAuth.error.networkDescription`),t[5]=c,t[6]=l,t[7]=s,t[8]=f):f=t[8];let p;t[9]===f?p=t[10]:(p=(0,Q.jsx)(`p`,{className:`typography-meta text-muted-foreground max-w-xs`,children:f}),t[9]=f,t[10]=p);let m;t[11]!==d||t[12]!==p?(m=(0,Q.jsxs)(`div`,{className:`space-y-2`,children:[d,p]}),t[11]=d,t[12]=p,t[13]=m):m=t[13];let h;t[14]===s?h=t[15]:(h=s(`sessionAuth.error.retry`),t[14]=s,t[15]=h);let g;t[16]!==n||t[17]!==h?(g=(0,Q.jsx)(dt,{type:`button`,onClick:n,className:`w-full max-w-xs`,children:h}),t[16]=n,t[17]=h,t[18]=g):g=t[18];let _;return t[19]!==a||t[20]!==m||t[21]!==g?(_=(0,Q.jsx)(or,{children:(0,Q.jsxs)(`div`,{className:`flex flex-col items-center gap-6 text-center`,children:[m,g,a]})}),t[19]=a,t[20]=m,t[21]=g,t[22]=_):_=t[22],_},lr=({children:e})=>{let{t}=ve(),r=X.useMemo(()=>_(),[]),i=r,a=X.useMemo(()=>b()&&!r,[r]),[o,s]=X.useState(()=>i?`authenticated`:`pending`),[c,d]=X.useState(``),[f,p]=X.useState(!1),[m,h]=X.useState(``),[g,v]=X.useState(void 0),[y,x]=X.useState(!1),[S,C]=X.useState(Dt),[w,T]=X.useState(!1),[E,D]=X.useState(!1),[O,k]=X.useState(()=>$n()),[A,M]=X.useState(null),[N,P]=X.useState(i),F=X.useRef(null),I=X.useRef(i);X.useEffect(()=>{typeof window>`u`||window.localStorage.setItem(Un,O?`true`:`false`)},[O]);let L=X.useCallback(async()=>{if(i)return Dt;try{let e=await Nt();return C(e),e}catch{return C(Dt),Dt}},[i]);X.useEffect(()=>{let e=!1;if(!i)return(async()=>{try{if(!window.isSecureContext||!pt()){e||T(!1);return}e||T(!0)}catch{e||T(!1)}})(),()=>{e=!0}},[i]);let te=X.useRef(0),R=X.useRef(null),ne=X.useRef(null),z=X.useCallback(()=>{R.current!==null&&(window.clearTimeout(R.current),R.current=null)},[]),B=X.useCallback(()=>{te.current=0,z()},[z]),V=X.useCallback(()=>te.current>=Vn?!1:(te.current+=1,z(),R.current=window.setTimeout(()=>{R.current=null,ne.current?.()},Hn*te.current),!0),[z]);X.useEffect(()=>z,[z]);let H=X.useCallback(async()=>{if(i){s(`authenticated`);return}s(e=>e===`authenticated`?e:`pending`);try{let[e,t]=await Promise.all([Qn(),L()]),n=await e.text();if(e.ok){B(),s(`authenticated`),x(!1),h(``),v(void 0);return}if(e.status===401){let e={};try{e=JSON.parse(n)}catch{e={}}B(),x(e.tunnelLocked===!0),C(t),s(`locked`),v(void 0);return}if(e.status===429){let e={};try{e=JSON.parse(n)}catch{e={}}B(),v(e.retryAfter),x(!1),s(`rate-limited`);return}if(V())return;s(`error`),x(!1)}catch(e){if(console.warn(`Failed to check session status:`,e),zn({shouldUseDesktopShellPasswordLogin:nr()})===`locked`){s(`locked`),v(void 0),x(!1);return}if(V())return;s(`error`),x(!1)}},[L,B,V,i]);X.useEffect(()=>{ne.current=H},[H]),X.useEffect(()=>{i||H()},[H,i]),X.useEffect(()=>{if(o===`pending`||o===`authenticated`||typeof document>`u`)return;let e=document.getElementById(`initial-loading`);if(!e)return;e.classList.add(`fade-out`);let t=window.setTimeout(()=>{e.remove()},300);return()=>{window.clearTimeout(t)}},[o]),X.useEffect(()=>{if(i)return;let e=hn(e=>{u(e)&&(d(``),h(``),v(void 0),x(!1),B(),P(!1),I.current=!1,s(`pending`),H())}),t=l(t=>e.schedule(t));return()=>{t(),e.cancel()}},[H,B,i]),X.useEffect(()=>{!i&&o===`locked`&&(I.current=!1,P(!1))},[i,o]),X.useEffect(()=>{o===`locked`&&F.current&&(F.current.focus(),F.current.select())},[o]),X.useEffect(()=>{if(!i&&o===`authenticated`&&!I.current){I.current=!0;let e=!1;return pn({runtimeKey:n(),initializeAppearance:j,syncSettings:ee,applyDirectory:un,onError:(e,t)=>{console.error(`[SessionAuthGate] ${e} settings hydration failed:`,t)}},{force:!0}).then(()=>{e||P(!0)}),()=>{e=!0}}},[i,o]);let re=async e=>{e.preventDefault(),await ae(!1)},ie=X.useCallback(async()=>{M(`register`),D(!0);try{await Et()}finally{M(null),D(!1)}await L()},[L]),U=X.useCallback(()=>{Pt(),M(null),D(!1)},[]),ae=X.useCallback(async e=>{if(!y&&!(!c||f)){E&&U(),p(!0),h(``);try{if(nr()){let e=await rr(c,O);if(e?.token){d(``),x(!1),await ar(e.token),s(`authenticated`);return}if(e?.status===401){h(t(`sessionAuth.error.incorrectPassword`)),x(!1),s(`locked`);return}if(e?.status===429){v(void 0),x(!1),s(`rate-limited`);return}}let n=await er(c,O);if(n.ok){let r=await n.json().catch(()=>null),i=Jn(),a=``;if(i&&(a=typeof r?.clientToken==`string`&&r.clientToken.trim()?r.clientToken.trim():``,a||=(await rr(c,O))?.token||await tr()),d(``),x(!1),a&&await ar(a),e&&w)try{await ie(),tt.success(t(`sessionAuth.toast.passkeyAdded`)),s(`authenticated`);return}catch(e){if(Mt(e))tt.message(t(`sessionAuth.toast.passkeySetupCanceled`));else{let n=e instanceof Error?e.message:t(`sessionAuth.error.passkeySetupFailed`);tt.error(n)}s(`authenticated`);return}s(`authenticated`);return}if(n.status===401){h(t(`sessionAuth.error.incorrectPassword`)),x(!1),s(`locked`);return}if(n.status===429){let e=await n.json().catch(()=>({}));v(e.retryAfter),x(!1),s(`rate-limited`);return}h(t(`sessionAuth.error.unexpectedResponse`)),x(!1),s(`error`)}catch(e){console.warn(`Failed to submit UI password:`,e);let n=nr()?await rr(c,O):null;if(n?.token){d(``),x(!1),await ar(n.token),s(`authenticated`);return}if(n?.status===401){h(t(`sessionAuth.error.incorrectPassword`)),x(!1),s(`locked`);return}if(n?.status===429){v(void 0),x(!1),s(`rate-limited`);return}h(t(`sessionAuth.error.networkRetry`)),x(!1),s(`error`)}finally{p(!1)}}},[U,E,f,y,c,ie,w,t,O]),oe=X.useCallback(async()=>{if(!(f||!w)){if(E){U();return}D(!0),M(`auth`),h(``);try{let e=await jt(O,{issueClientToken:Jn(),clientLabel:`OpenChamber Desktop`,...Zn()}),t=Jn()&&typeof e?.clientToken==`string`&&e.clientToken.trim()?e.clientToken.trim():``;t&&await ar(t),d(``),s(`authenticated`)}catch(e){if(Mt(e))h(``);else{let n=e instanceof Error?e.message:t(`sessionAuth.error.passkeySignInCanceled`);h(n)}}finally{M(null),D(!1)}}},[U,E,f,w,t,O]),W=X.useCallback(async()=>{if(!(f||y||!w)){if(E){U();return}if(o!==`authenticated`){if(!c){h(t(`sessionAuth.error.enterPasswordForPasskey`));return}await ae(!0);return}h(``);try{await ie(),tt.success(t(`sessionAuth.toast.passkeyAdded`))}catch(e){if(Mt(e)){tt.message(t(`sessionAuth.toast.passkeySetupCanceled`));return}let n=e instanceof Error?e.message:t(`sessionAuth.error.passkeySetupFailed`);tt.error(n)}}},[U,ae,E,f,y,c,ie,o,w,t]),se=w&&S.enabled,G=se&&S.hasPasskeys;return o===`pending`||o===`authenticated`&&!N?(0,Q.jsx)(sr,{}):o===`error`?(0,Q.jsx)(cr,{onRetry:()=>{B(),H()},errorType:`network`,children:a&&(0,Q.jsxs)(`div`,{className:`w-full max-w-xs`,children:[(0,Q.jsx)(Rn,{}),(0,Q.jsx)(`p`,{className:`mt-1 text-center typography-micro text-muted-foreground`,children:t(`sessionAuth.locked.hostSwitcherHint`)})]})}):o===`rate-limited`?(0,Q.jsx)(cr,{onRetry:()=>void H(),errorType:`rate-limit`,retryAfter:g}):o===`locked`?(0,Q.jsx)(or,{children:(0,Q.jsxs)(`div`,{className:`flex flex-col items-center gap-6 w-full max-w-xs`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-col items-center gap-1 text-center`,children:[(0,Q.jsx)(`h1`,{className:`text-xl font-semibold text-foreground`,children:t(y?`sessionAuth.locked.tunnelTitle`:`sessionAuth.locked.unlockTitle`)}),(0,Q.jsx)(`p`,{className:`typography-meta text-muted-foreground`,children:t(y?`sessionAuth.locked.tunnelDescription`:`sessionAuth.locked.passwordDescription`)})]}),!y&&(0,Q.jsxs)(`form`,{onSubmit:re,className:`w-full space-y-2`,children:[G&&(0,Q.jsxs)(dt,{type:`button`,variant:`outline`,className:`w-full`,onClick:()=>void oe(),disabled:f||E&&A!==`auth`,children:[E?(0,Q.jsx)(J,{name:`loader-4`,className:`h-4 w-4 animate-spin`}):(0,Q.jsx)(J,{name:`lock-unlock`,className:`h-4 w-4`}),(0,Q.jsx)(`span`,{children:t(E&&A===`auth`?`sessionAuth.actions.cancelPasskey`:`sessionAuth.actions.usePasskey`)})]}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsxs)(`div`,{className:`relative flex-1`,children:[(0,Q.jsx)(J,{name:`lock`,className:`absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground/60`}),(0,Q.jsx)(gt,{id:`openchamber-ui-password`,ref:F,type:`password`,autoComplete:`current-password`,placeholder:t(`sessionAuth.password.placeholder`),value:c,onChange:e=>{d(e.target.value),m&&h(``)},className:`pl-10`,"aria-invalid":!!m||void 0,"aria-describedby":m?`oc-ui-auth-error`:void 0,disabled:f})]}),(0,Q.jsx)(dt,{type:`submit`,size:`icon`,disabled:!c||f,"aria-label":t(f?`sessionAuth.actions.unlockingAria`:`sessionAuth.actions.unlockAria`),children:f?(0,Q.jsx)(J,{name:`loader-4`,className:`h-4 w-4 animate-spin`}):(0,Q.jsx)(J,{name:`lock-unlock`,className:`h-4 w-4`})})]}),se?(0,Q.jsxs)(`div`,{className:`flex items-center justify-between pt-1`,children:[(0,Q.jsxs)(`label`,{className:`flex items-center gap-2 text-center typography-micro text-muted-foreground`,children:[(0,Q.jsx)(mt,{checked:O,onChange:k,disabled:f,ariaLabel:t(`sessionAuth.actions.trustDeviceAria`),className:`size-4`,iconClassName:`size-4`}),(0,Q.jsx)(`span`,{children:t(`sessionAuth.actions.trustDevice`)})]}),(0,Q.jsx)(dt,{type:`button`,variant:`ghost`,size:`sm`,className:`text-muted-foreground hover:text-foreground`,onClick:()=>void W(),disabled:f,children:t(E&&A===`register`?`sessionAuth.actions.cancelPasskeySetup`:`sessionAuth.actions.addPasskey`)})]}):(0,Q.jsxs)(`label`,{className:`flex items-center justify-center gap-2 pt-1 text-center typography-micro text-muted-foreground`,children:[(0,Q.jsx)(mt,{checked:O,onChange:k,disabled:f,ariaLabel:t(`sessionAuth.actions.trustDeviceAria`),className:`size-4`,iconClassName:`size-4`}),(0,Q.jsx)(`span`,{children:t(`sessionAuth.actions.trustDevice`)})]}),m&&(0,Q.jsx)(`p`,{id:`oc-ui-auth-error`,className:`typography-meta text-destructive`,children:m})]}),a&&(0,Q.jsxs)(`div`,{className:`w-full`,children:[(0,Q.jsx)(Rn,{}),(0,Q.jsx)(`p`,{className:`mt-1 text-center typography-micro text-muted-foreground`,children:t(`sessionAuth.locked.hostSwitcherHint`)})]})]})}):(0,Q.jsx)(Q.Fragment,{children:e})},ur=e=>{let t=(0,Z.c)(14),{children:n}=e,r=p(dr),i=p(fr),a=p(pr),o=p(mr),s=p(hr),{deviceType:c,hasTouchInput:l}=Ht(),u;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(u=typeof document<`u`&&m(),t[0]=u):u=t[0];let d=u,f;t[1]!==s||t[2]!==a?(f=()=>{a(),s()},t[1]=s,t[2]=a,t[3]=f):f=t[3];let h;t[4]!==s||t[5]!==a||t[6]!==i||t[7]!==c||t[8]!==r||t[9]!==l||t[10]!==o?(h=[r,i,a,o,s,c,l,d],t[4]=s,t[5]=a,t[6]=i,t[7]=c,t[8]=r,t[9]=l,t[10]=o,t[11]=h):h=t[11],X.useLayoutEffect(f,h);let g;return t[12]===n?g=t[13]:(g=(0,Q.jsx)(Q.Fragment,{children:n}),t[12]=n,t[13]=g),g};function dr(e){return e.fontSize}function fr(e){return e.codeFontSize}function pr(e){return e.applyTypography}function mr(e){return e.padding}function hr(e){return e.applyPadding}var gr=e(G(),1),_r=e=>{if(!e||typeof e!=`string`)return null;let t=e.trim();if(!t.startsWith(`#`))return null;let n=t.slice(1);if((n.length===3||n.length===4)&&(n=n.split(``).map(e=>e+e).join(``)),n.length===8&&(n=n.slice(0,6)),n.length!==6)return null;let r=Number.parseInt(n,16);return Number.isNaN(r)?null:`${r>>16&255} ${r>>8&255} ${r&255}`},vr=class{inheritanceMap=new Map;constructor(){this.initializeInheritanceMap()}generate(e){let t=[];return t.push(...this.generateTailwindVariables(e)),t.push(...this.generatePrimaryColors(e.colors.primary)),t.push(...this.generateSurfaceColors(e.colors.surface)),t.push(...this.generateInteractiveColors(e.colors.interactive)),t.push(...this.generateStatusColors(e.colors.status)),t.push(...this.generatePullRequestColors(e)),t.push(...this.generateSyntaxColors(e.colors.syntax)),t.push(...this.generateComponentColors(e.colors,e)),t.push(...this.generateTypographyVariables()),e.config&&t.push(...this.generateConfigVariables(e.config)),t.join(`
3
3
  `)}generateTailwindVariables(e){let t=[];t.push(` --background: ${e.colors.surface.background} !important;`),t.push(` --foreground: ${e.colors.surface.foreground} !important;`),t.push(` --muted: ${e.colors.surface.muted} !important;`),t.push(` --muted-foreground: ${e.colors.surface.mutedForeground} !important;`),t.push(` --card: ${e.colors.surface.elevated} !important;`),t.push(` --card-foreground: ${e.colors.surface.elevatedForeground} !important;`),t.push(` --popover: ${e.colors.surface.elevated} !important;`),t.push(` --popover-foreground: ${e.colors.surface.elevatedForeground} !important;`),t.push(` --border: ${e.colors.interactive.border} !important;`),t.push(` --input: ${e.colors.interactive.border} !important;`),t.push(` --primary: ${e.colors.primary.base} !important;`),t.push(` --primary-foreground: ${e.colors.primary.foreground} !important;`),t.push(` --secondary: ${e.colors.surface.muted} !important;`),t.push(` --secondary-foreground: ${e.colors.surface.mutedForeground} !important;`),t.push(` --accent: ${e.colors.surface.subtle} !important;`),t.push(` --accent-foreground: ${e.colors.surface.foreground} !important;`),t.push(` --destructive: ${e.colors.status.error} !important;`),t.push(` --destructive-foreground: ${e.colors.status.errorForeground} !important;`),t.push(` --ring: ${e.colors.interactive.focusRing} !important;`);let n=_r(e.colors.surface.muted),r=_r(e.colors.surface.subtle),i=_r(e.colors.interactive.border);t.push(` --sidebar-base: ${e.colors.surface.muted} !important;`),n&&t.push(` --sidebar-base-rgb: ${n} !important;`),t.push(` --sidebar: var(--sidebar-base) !important;`),t.push(` --sidebar-foreground: ${e.colors.surface.mutedForeground} !important;`),t.push(` --sidebar-primary: ${e.colors.primary.base} !important;`),t.push(` --sidebar-primary-foreground: ${e.colors.primary.foreground} !important;`),t.push(` --sidebar-accent-base: ${e.colors.surface.subtle} !important;`),r&&t.push(` --sidebar-accent-base-rgb: ${r} !important;`),t.push(` --sidebar-accent: var(--sidebar-accent-base) !important;`),t.push(` --sidebar-accent-foreground: ${e.colors.surface.foreground} !important;`),t.push(` --sidebar-border: ${e.colors.interactive.border} !important;`),i&&t.push(` --sidebar-border-rgb: ${i} !important;`),t.push(` --sidebar-ring: ${e.colors.interactive.focusRing} !important;`);let a=e.metadata.variant===`dark`,o=a?.15:.5,s=a?.1:.3,c=a?.42:.52;if(n)t.push(` --sidebar-overlay-strong: rgb(${n} / ${o}) !important;`),t.push(` --sidebar-overlay-soft: rgb(${n} / ${s}) !important;`),t.push(` --sidebar-vibrancy-overlay: rgb(${n} / ${c}) !important;`);else{let n=e.colors.surface.muted;t.push(` --sidebar-overlay-strong: ${this.opacity(n,o)} !important;`),t.push(` --sidebar-overlay-soft: ${this.opacity(n,s)} !important;`),t.push(` --sidebar-vibrancy-overlay: ${this.opacity(n,c)} !important;`)}return e.colors.charts?.series&&Array.isArray(e.colors.charts.series)&&e.colors.charts.series.forEach((e,n)=>{t.push(` --chart-${n+1}: ${e};`)}),e.colors.loading?(t.push(` --loading-spinner: ${e.colors.loading.spinner||e.colors.primary.base};`),t.push(` --loading-spinner-track: ${e.colors.loading.spinnerTrack||e.colors.surface.muted};`)):(t.push(` --loading-spinner: ${e.colors.primary.base};`),t.push(` --loading-spinner-track: ${e.colors.surface.muted};`)),t}apply(e){let t=this.generate(e),n=document.createElement(`style`);n.id=`opencode-theme-variables`;let r=``;e.metadata.variant===`dark`?(r=`:root {\n${t}\n}\n\n.dark {\n${t}\n}`,document.documentElement.classList.add(`dark`),document.documentElement.classList.remove(`light`)):(r=`:root {\n${t}\n}\n\n:root:not(.dark) {\n${t}\n}`,document.documentElement.classList.remove(`dark`),document.documentElement.classList.add(`light`)),n.textContent=r;let i=document.getElementById(`opencode-theme-variables`);i&&i.remove(),document.head.appendChild(n),document.documentElement.setAttribute(`data-theme`,e.metadata.variant);let a=typeof window<`u`&&window.__OPENCHAMBER_ELECTRON__?.runtime===`electron`&&window.__OPENCHAMBER_ELECTRON__?.macVibrancy===!0;document.documentElement.toggleAttribute(`data-oc-vibrancy`,a),a&&document.documentElement.toggleAttribute(`data-oc-vibrancy-ready`,!0)}generatePrimaryColors(e){let t=[];return t.push(` --primary-base: ${e.base};`),t.push(` --primary-hover: ${e.hover||this.darken(e.base,10)};`),t.push(` --primary-active: ${e.active||this.darken(e.base,20)};`),t.push(` --primary-foreground: ${e.foreground||`#ffffff`};`),t.push(` --primary-muted: ${e.muted||this.opacity(e.base,.5)};`),t.push(` --primary-emphasis: ${e.emphasis||this.lighten(e.base,10)};`),t}generateSurfaceColors(e){let t=[];return t.push(` --surface-background: ${e.background};`),t.push(` --surface-foreground: ${e.foreground};`),t.push(` --surface-muted: ${e.muted};`),t.push(` --surface-muted-foreground: ${e.mutedForeground};`),t.push(` --surface-elevated: ${e.elevated};`),t.push(` --surface-elevated-foreground: ${e.elevatedForeground};`),t.push(` --surface-overlay: ${e.overlay};`),t.push(` --surface-subtle: ${e.subtle};`),t}generateInteractiveColors(e){let t=[];return t.push(` --interactive-border: ${e.border};`),t.push(` --interactive-border-hover: ${e.borderHover};`),t.push(` --interactive-border-focus: ${e.borderFocus};`),t.push(` --interactive-selection: ${e.selection};`),t.push(` --interactive-selection-foreground: ${e.selectionForeground};`),t.push(` --interactive-focus: ${e.focus};`),t.push(` --interactive-focus-ring: ${e.focusRing};`),t.push(` --interactive-cursor: ${e.cursor};`),t.push(` --interactive-hover: ${e.hover};`),t.push(` --interactive-active: ${e.active};`),t}generateStatusColors(e){let t=[];return t.push(` --status-error: ${e.error};`),t.push(` --status-error-foreground: ${e.errorForeground};`),t.push(` --status-error-background: ${e.errorBackground};`),t.push(` --status-error-border: ${e.errorBorder};`),t.push(` --status-warning: ${e.warning};`),t.push(` --status-warning-foreground: ${e.warningForeground};`),t.push(` --status-warning-background: ${e.warningBackground};`),t.push(` --status-warning-border: ${e.warningBorder};`),t.push(` --status-success: ${e.success};`),t.push(` --status-success-foreground: ${e.successForeground};`),t.push(` --status-success-background: ${e.successBackground};`),t.push(` --status-success-border: ${e.successBorder};`),t.push(` --status-info: ${e.info};`),t.push(` --status-info-foreground: ${e.infoForeground};`),t.push(` --status-info-background: ${e.infoBackground};`),t.push(` --status-info-border: ${e.infoBorder};`),t}generatePullRequestColors(e){let t=[],n=e.colors.pr;return t.push(` --pr-open: ${n?.open||e.colors.status.success};`),t.push(` --pr-draft: ${n?.draft||e.colors.surface.mutedForeground};`),t.push(` --pr-blocked: ${n?.blocked||e.colors.status.warning};`),t.push(` --pr-merged: ${n?.merged||(e.metadata.variant===`dark`?`#8957e5`:`#8250df`)};`),t.push(` --pr-closed: ${n?.closed||e.colors.status.error};`),t}generateSyntaxColors(e){let t=[];t.push(` --syntax-background: ${e.base.background};`),t.push(` --syntax-foreground: ${e.base.foreground};`),t.push(` --syntax-comment: ${e.base.comment};`),t.push(` --syntax-keyword: ${e.base.keyword};`),t.push(` --syntax-string: ${e.base.string};`),t.push(` --syntax-number: ${e.base.number};`),t.push(` --syntax-function: ${e.base.function};`),t.push(` --syntax-variable: ${e.base.variable};`),t.push(` --syntax-type: ${e.base.type};`),t.push(` --syntax-operator: ${e.base.operator};`);let n=this.generateSyntaxTokens(e);for(let[e,r]of Object.entries(n))t.push(` --syntax-${this.kebabCase(e)}: ${r};`);return t}generateSyntaxTokens(e){let t=e.base,n=e.tokens||{};return{commentDoc:n.commentDoc||this.lighten(t.comment,10),stringEscape:n.stringEscape||this.darken(t.string,20),stringInterpolation:n.stringInterpolation||t.variable,stringRegex:n.stringRegex||this.adjustHue(t.string,15),keywordControl:n.keywordControl||t.keyword,keywordOperator:n.keywordOperator||t.operator,keywordImport:n.keywordImport||this.lighten(t.keyword,10),keywordReturn:n.keywordReturn||this.emphasize(t.keyword),functionCall:n.functionCall||this.lighten(t.function,5),functionBuiltin:n.functionBuiltin||this.darken(t.function,10),method:n.method||t.function,methodCall:n.methodCall||this.lighten(t.function,5),variableBuiltin:n.variableBuiltin||this.emphasize(t.variable),variableProperty:n.variableProperty||this.lighten(t.variable,10),variableReadonly:n.variableReadonly||t.number,parameter:n.parameter||t.variable,typePrimitive:n.typePrimitive||this.darken(t.type,10),typeInterface:n.typeInterface||t.type,className:n.className||this.emphasize(t.type),enum:n.enum||t.type,boolean:n.boolean||t.number,null:n.null||this.opacity(t.number,.7),constant:n.constant||t.number,punctuation:n.punctuation||this.opacity(t.foreground,.7),delimiter:n.delimiter||this.opacity(t.foreground,.8),bracket:n.bracket||t.foreground,tag:n.tag||t.keyword,tagAttribute:n.tagAttribute||t.variable,tagAttributeValue:n.tagAttributeValue||t.string,tagBracket:n.tagBracket||this.opacity(t.foreground,.8),decorator:n.decorator||t.function,annotation:n.annotation||t.function,namespace:n.namespace||this.opacity(t.type,.8),module:n.module||this.opacity(t.type,.8),...n}}generateComponentColors(e,t){let n=[];return e.markdown?n.push(...this.generateMarkdownColors(e.markdown,t)):n.push(...this.generateDefaultMarkdownColors(t)),e.chat?n.push(...this.generateChatColors(e.chat,t)):n.push(...this.generateDefaultChatColors(t)),e.tools?n.push(...this.generateToolColors(e.tools,t)):n.push(...this.generateDefaultToolColors(t)),n}generateMarkdownColors(e,t){let n=[],r=t.colors.primary.base,i=t.colors.chat?.background||t.colors.surface.background;return n.push(` --markdown-heading1: ${e.heading1||r};`),n.push(` --markdown-heading2: ${e.heading2||this.opacity(r,.9)};`),n.push(` --markdown-heading3: ${e.heading3||this.opacity(r,.8)};`),n.push(` --markdown-heading4: ${e.heading4||t.colors.surface.foreground};`),n.push(` --markdown-link: ${e.link||r};`),n.push(` --markdown-link-hover: ${e.linkHover||t.colors.primary.hover||this.darken(r,10)};`),n.push(` --markdown-inline-code: ${e.inlineCode||t.colors.syntax.base.string};`),n.push(` --markdown-inline-code-bg: ${e.inlineCodeBackground||i};`),n.push(` --markdown-blockquote: ${e.blockquote||t.colors.surface.mutedForeground};`),n.push(` --markdown-blockquote-border: ${e.blockquoteBorder||t.colors.interactive.border};`),n.push(` --markdown-list-marker: ${r};`),n.push(` --markdown-bold: ${e.bold||t.colors.surface.foreground};`),n.push(` --markdown-italic: ${e.italic||this.opacity(t.colors.surface.foreground,.9)};`),n.push(` --markdown-strikethrough: ${e.strikethrough||t.colors.surface.mutedForeground};`),n.push(` --markdown-hr: ${e.hr||t.colors.interactive.border};`),n}generateDefaultMarkdownColors(e){let t=[],n=e.colors.primary.base,r=e.colors.chat?.background||e.colors.surface.background;return t.push(` --markdown-heading1: ${n};`),t.push(` --markdown-heading2: ${this.opacity(n,.9)};`),t.push(` --markdown-heading3: ${this.opacity(n,.8)};`),t.push(` --markdown-heading4: ${e.colors.surface.foreground};`),t.push(` --markdown-link: ${n};`),t.push(` --markdown-link-hover: ${e.colors.primary.hover||this.darken(n,10)};`),t.push(` --markdown-inline-code: ${e.colors.syntax.base.string};`),t.push(` --markdown-inline-code-bg: ${r};`),t.push(` --markdown-blockquote: ${e.colors.surface.mutedForeground};`),t.push(` --markdown-blockquote-border: ${e.colors.interactive.border};`),t.push(` --markdown-list-marker: ${n};`),t.push(` --markdown-bold: ${e.colors.surface.foreground};`),t.push(` --markdown-italic: ${this.opacity(e.colors.surface.foreground,.9)};`),t.push(` --markdown-strikethrough: ${e.colors.surface.mutedForeground};`),t.push(` --markdown-hr: ${e.colors.interactive.border};`),t}generateChatColors(e,t){let n=[],r=e.background||t.colors.surface.background,i=e.composerSkill||this.getDefaultComposerSkillColor(t);return n.push(` --chat-background: ${r};`),n.push(` --chat-user-message: ${e.userMessage||t.colors.surface.foreground};`),n.push(` --chat-user-message-bg: ${e.userMessageBackground||t.colors.surface.elevated};`),n.push(` --chat-assistant-message: ${e.assistantMessage||t.colors.surface.foreground};`),n.push(` --chat-assistant-message-bg: ${e.assistantMessageBackground||t.colors.surface.muted};`),n.push(` --chat-timestamp: ${e.timestamp||t.colors.surface.mutedForeground};`),n.push(` --chat-divider: ${e.divider||t.colors.interactive.border};`),n.push(` --chat-typing: ${e.typing||t.colors.surface.mutedForeground};`),n.push(` --chat-composer-skill: ${i};`),n}generateDefaultChatColors(e){let t=[];return t.push(` --chat-background: ${e.colors.surface.background};`),t.push(` --chat-user-message: ${e.colors.surface.foreground};`),t.push(` --chat-user-message-bg: ${e.colors.surface.elevated};`),t.push(` --chat-assistant-message: ${e.colors.surface.foreground};`),t.push(` --chat-assistant-message-bg: ${e.colors.surface.muted};`),t.push(` --chat-timestamp: ${e.colors.surface.mutedForeground};`),t.push(` --chat-divider: ${e.colors.interactive.border};`),t.push(` --chat-typing: ${e.colors.surface.mutedForeground};`),t.push(` --chat-composer-skill: ${this.getDefaultComposerSkillColor(e)};`),t}getDefaultComposerSkillColor(e){return e.metadata.variant===`dark`?this.lighten(e.colors.status.warning,25):e.colors.status.warning}generateToolColors(e,t){let n=[];return n.push(` --tools-background: ${e?.background||this.opacity(t.colors.surface.muted,.2)};`),n.push(` --tools-border: ${e?.border||this.opacity(t.colors.interactive.border,.3)};`),n.push(` --tools-header-hover: ${e?.headerHover||this.opacity(t.colors.surface.muted,.3)};`),n.push(` --tools-icon: ${e?.icon||t.colors.surface.mutedForeground};`),n.push(` --tools-title: ${e?.title||t.colors.surface.foreground};`),n.push(` --tools-description: ${e?.description||this.opacity(t.colors.surface.mutedForeground,.6)};`),e?.edit?(n.push(` --tools-edit-added: ${e.edit.added||t.colors.status.success};`),n.push(` --tools-edit-added-bg: ${e.edit.addedBackground||t.colors.status.successBackground};`),n.push(` --tools-edit-removed: ${e.edit.removed||t.colors.status.error};`),n.push(` --tools-edit-removed-bg: ${e.edit.removedBackground||t.colors.status.errorBackground};`),n.push(` --tools-edit-modified: ${e.edit.modified||t.colors.status.info};`),n.push(` --tools-edit-modified-bg: ${e.edit.modifiedBackground||t.colors.status.infoBackground};`),n.push(` --tools-edit-line-number: ${e.edit.lineNumber||this.opacity(t.colors.surface.mutedForeground,.6)};`)):(n.push(` --tools-edit-added: ${t.colors.status.success};`),n.push(` --tools-edit-added-bg: ${t.colors.status.successBackground};`),n.push(` --tools-edit-removed: ${t.colors.status.error};`),n.push(` --tools-edit-removed-bg: ${t.colors.status.errorBackground};`),n.push(` --tools-edit-modified: ${t.colors.status.info};`),n.push(` --tools-edit-modified-bg: ${t.colors.status.infoBackground};`),n.push(` --tools-edit-line-number: ${this.opacity(t.colors.surface.mutedForeground,.6)};`)),n}generateDefaultToolColors(e){let t=[];return t.push(` --tools-background: ${this.opacity(e.colors.surface.muted,.2)};`),t.push(` --tools-border: ${this.opacity(e.colors.interactive.border,.3)};`),t.push(` --tools-header-hover: ${this.opacity(e.colors.surface.muted,.3)};`),t.push(` --tools-icon: ${e.colors.surface.mutedForeground};`),t.push(` --tools-title: ${e.colors.surface.foreground};`),t.push(` --tools-description: ${this.opacity(e.colors.surface.mutedForeground,.6)};`),t.push(` --tools-edit-added: ${e.colors.status.success};`),t.push(` --tools-edit-added-bg: ${this.addTransparency(this.removeTransparency(e.colors.status.successBackground),.15)};`),t.push(` --tools-edit-removed: ${e.colors.status.error};`),t.push(` --tools-edit-removed-bg: ${this.addTransparency(this.removeTransparency(e.colors.status.errorBackground),.15)};`),t.push(` --tools-edit-modified: ${e.colors.status.info};`),t.push(` --tools-edit-modified-bg: ${this.addTransparency(this.removeTransparency(e.colors.status.infoBackground),.15)};`),t.push(` --tools-edit-line-number: ${this.opacity(e.colors.surface.mutedForeground,.6)};`),t}generateConfigVariables(e){let t=[];return e?(e.fonts&&(e.fonts.sans&&(t.push(` --font-sans: ${e.fonts.sans};`),t.push(` --font-family-sans: ${e.fonts.sans};`)),e.fonts.mono&&(t.push(` --font-mono: ${e.fonts.mono};`),t.push(` --font-family-mono: ${e.fonts.mono};`)),e.fonts.heading&&t.push(` --font-heading: ${e.fonts.heading};`)),e.transitions&&(e.transitions.fast&&t.push(` --transition-fast: ${e.transitions.fast};`),e.transitions.normal&&t.push(` --transition-normal: ${e.transitions.normal};`),e.transitions.slow&&t.push(` --transition-slow: ${e.transitions.slow};`)),t):t}generateTypographyVariables(){let e=[],t=_()?c:d;return e.push(` /* Semantic Typography Variables */`),e.push(` --ui-regular-font-weight: 400;`),e.push(` /* Markdown content - all markdown elements use same size */`),e.push(` --text-markdown: ${t.markdown};`),e.push(` /* Code content - all code elements use same size */`),e.push(` --text-code: ${t.code};`),e.push(` /* UI headers - dialog titles, panel headers */`),e.push(` --text-ui-header: ${t.uiHeader};`),e.push(` /* UI labels - buttons, menus, navigation */`),e.push(` --text-ui-label: ${t.uiLabel};`),e.push(` /* Metadata - timestamps, status, helper text */`),e.push(` --text-meta: ${t.meta};`),e.push(` /* Micro text - badges, shortcuts, indicators */`),e.push(` --text-micro: ${t.micro};`),e.push(` /* Heading line height and letter spacing */`),e.push(` --h1-line-height: 1.25rem;`),e.push(` --h2-line-height: 1.25rem;`),e.push(` --h3-line-height: 1.5rem;`),e.push(` --h4-line-height: 1.5rem;`),e.push(` --h5-line-height: 1.5rem;`),e.push(` --h6-line-height: 1.5rem;`),e.push(` --h1-letter-spacing: -0.025em;`),e.push(` --h2-letter-spacing: -0.02em;`),e.push(` --h3-letter-spacing: -0.015em;`),e.push(` --h4-letter-spacing: -0.01em;`),e.push(` --h5-letter-spacing: 0;`),e.push(` --h6-letter-spacing: 0.01em;`),e.push(` /* UI element line height and letter spacing */`),e.push(` --ui-button-line-height: 1.375rem;`),e.push(` --ui-button-letter-spacing: 0.02em;`),e.push(` --ui-button-font-weight: 500;`),e.push(` --ui-label-line-height: 1rem;`),e.push(` --ui-label-letter-spacing: 0.03em;`),e.push(` --ui-label-font-weight: 500;`),e.push(` --ui-caption-line-height: 1rem;`),e.push(` --ui-caption-letter-spacing: 0.025em;`),e.push(` --ui-caption-font-weight: var(--ui-regular-font-weight, 400);`),e.push(` /* Markdown line height and letter spacing */`),e.push(` --markdown-body-line-height: 1.625;`),e.push(` --markdown-body-letter-spacing: 0;`),e.push(` --markdown-body-font-weight: var(--ui-regular-font-weight, 400);`),e.push(` --markdown-h1-line-height: 1.25rem;`),e.push(` --markdown-h1-letter-spacing: -0.025em;`),e.push(` --markdown-h2-line-height: 1.25rem;`),e.push(` --markdown-h2-letter-spacing: -0.02em;`),e.push(` --markdown-h3-line-height: 1.5rem;`),e.push(` --markdown-h3-letter-spacing: -0.015em;`),e.push(` --markdown-h4-line-height: 1.5rem;`),e.push(` --markdown-h4-letter-spacing: -0.01em;`),e.push(` --markdown-h5-line-height: 1.5rem;`),e.push(` --markdown-h5-letter-spacing: 0;`),e.push(` --markdown-h6-line-height: 1.5rem;`),e.push(` --markdown-h6-letter-spacing: 0.01em;`),e.push(` --markdown-list-line-height: 1.625;`),e.push(` --markdown-code-block-line-height: 1rem;`),e.push(` --ui-button-small-line-height: 1.25rem;`),e.push(` --ui-button-small-letter-spacing: 0.02em;`),e.push(` --ui-button-small-font-weight: 500;`),e.push(` --markdown-body-small-line-height: 1.5;`),e.push(` --markdown-body-small-letter-spacing: 0;`),e.push(` --markdown-body-small-font-weight: var(--ui-regular-font-weight, 400);`),e.push(` --ui-button-large-line-height: 1.5rem;`),e.push(` --ui-button-large-letter-spacing: 0.02em;`),e.push(` --ui-button-large-font-weight: 500;`),e.push(` --markdown-body-large-line-height: 1.625;`),e.push(` --markdown-body-large-letter-spacing: 0;`),e.push(` --markdown-body-large-font-weight: var(--ui-regular-font-weight, 400);`),e.push(` /* Code line height and letter spacing */`),e.push(` --code-inline-line-height: 1rem;`),e.push(` --code-inline-letter-spacing: 0;`),e.push(` --code-inline-font-weight: 400;`),e.push(` --code-block-line-height: 1.4rem;`),e.push(` --code-block-letter-spacing: 0;`),e.push(` --code-block-font-weight: 400;`),e.push(` --code-line-numbers-line-height: 1.25rem;`),e.push(` --code-line-numbers-letter-spacing: 0;`),e.push(` --code-line-numbers-font-weight: 400;`),e.push(` /* Additional UI element line height and letter spacing */`),e.push(` --ui-badge-line-height: 1rem;`),e.push(` --ui-badge-letter-spacing: 0.025em;`),e.push(` --ui-badge-font-weight: 500;`),e.push(` --ui-tooltip-line-height: 1rem;`),e.push(` --ui-tooltip-letter-spacing: 0.025em;`),e.push(` --ui-tooltip-font-weight: var(--ui-regular-font-weight, 400);`),e.push(` --ui-input-line-height: 1.375rem;`),e.push(` --ui-input-letter-spacing: 0.02em;`),e.push(` --ui-input-font-weight: var(--ui-regular-font-weight, 400);`),e.push(` --ui-helper-text-line-height: 1rem;`),e.push(` --ui-helper-text-letter-spacing: 0.025em;`),e.push(` --ui-helper-text-font-weight: var(--ui-regular-font-weight, 400);`),e.push(` /* Additional markdown line height and letter spacing */`),e.push(` --markdown-blockquote-line-height: 1.625;`),e.push(` --markdown-blockquote-letter-spacing: 0;`),e.push(` --markdown-blockquote-font-weight: var(--ui-regular-font-weight, 400);`),e.push(` --markdown-list-letter-spacing: 0;`),e.push(` --markdown-list-font-weight: var(--ui-regular-font-weight, 400);`),e.push(` --markdown-link-line-height: 1.625;`),e.push(` --markdown-link-letter-spacing: 0;`),e.push(` --markdown-link-font-weight: var(--ui-regular-font-weight, 400);`),e.push(` --markdown-code-line-height: 1.35;`),e.push(` --markdown-code-letter-spacing: 0;`),e.push(` --markdown-code-font-weight: 400;`),e.push(` --markdown-code-block-letter-spacing: 0;`),e.push(` --markdown-code-block-font-weight: 400;`),e}initializeInheritanceMap(){this.inheritanceMap.set(`header.background`,`surface.background`),this.inheritanceMap.set(`header.foreground`,`surface.foreground`),this.inheritanceMap.set(`header.logoTint`,`primary.base`),this.inheritanceMap.set(`header.divider`,`interactive.border`),this.inheritanceMap.set(`sidebar.background`,`surface.muted`),this.inheritanceMap.set(`sidebar.foreground`,`surface.mutedForeground`),this.inheritanceMap.set(`sidebar.hover`,`interactive.hover`),this.inheritanceMap.set(`sidebar.active`,`primary.base`),this.inheritanceMap.set(`sidebar.activeForeground`,`primary.foreground`)}opacity(e,t){return e.startsWith(`#`)?`${e}${Math.round(t*255).toString(16).padStart(2,`0`)}`:e.startsWith(`rgb`)?e.replace(`rgb`,`rgba`).replace(`)`,`, ${t})`):e}removeTransparency(e){return e.startsWith(`#`)?e.length===9?e.slice(0,7):e.length===5?e.slice(0,4):e:e.startsWith(`rgba`)?e.replace(`rgba`,`rgb`).replace(/,\s*[\d.]+\)$/,`)`):e}addTransparency(e,t){if(e.startsWith(`#`)){let n=e.slice(1);if(n.length===3)return`rgba(${parseInt(n[0]+n[0],16)}, ${parseInt(n[1]+n[1],16)}, ${parseInt(n[2]+n[2],16)}, ${t})`;if(n.length===6)return`rgba(${parseInt(n.slice(0,2),16)}, ${parseInt(n.slice(2,4),16)}, ${parseInt(n.slice(4,6),16)}, ${t})`}return e.startsWith(`rgb`)?e.replace(`rgb`,`rgba`).replace(`)`,`, ${t})`):e}darken(e,t){if(e.startsWith(`#`)){let n=parseInt(e.slice(1),16),r=Math.round(2.55*t),i=(n>>16)-r,a=(n>>8&255)-r,o=(n&255)-r;return`#`+(16777216+(i<255?i<0?0:i:255)*65536+(a<255?a<0?0:a:255)*256+(o<255?o<0?0:o:255)).toString(16).slice(1)}return e}lighten(e,t){if(e.startsWith(`#`)){let n=parseInt(e.slice(1),16),r=Math.round(2.55*t),i=(n>>16)+r,a=(n>>8&255)+r,o=(n&255)+r;return`#`+(16777216+(i<255?i<0?0:i:255)*65536+(a<255?a<0?0:a:255)*256+(o<255?o<0?0:o:255)).toString(16).slice(1)}return e}adjustHue(e,t){return this.lighten(e,t/10)}emphasize(e){return this.lighten(e,15)}kebabCase(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).toLowerCase()}},yr=()=>$t()?new URLSearchParams(window.location.search):null,br=()=>typeof window>`u`||window.matchMedia(`(prefers-color-scheme: dark)`).matches,xr=()=>{let e=yr()?.get(`themeVariant`);return e===`dark`||e===`light`?e===`dark`:br()},Sr=(e,t)=>t.reduce((e,t)=>e&&typeof e==`object`?e[t]:void 0,e),Cr=e=>typeof e==`string`&&e.trim().length>0,wr=e=>{if(!e||typeof e!=`object`)return!1;for(let t of[[`metadata`,`id`],[`metadata`,`name`],[`metadata`,`variant`],[`colors`,`primary`,`base`],[`colors`,`primary`,`foreground`],[`colors`,`surface`,`background`],[`colors`,`surface`,`foreground`],[`colors`,`surface`,`muted`],[`colors`,`surface`,`mutedForeground`],[`colors`,`surface`,`elevated`],[`colors`,`surface`,`elevatedForeground`],[`colors`,`surface`,`subtle`],[`colors`,`interactive`,`border`],[`colors`,`interactive`,`selection`],[`colors`,`interactive`,`selectionForeground`],[`colors`,`interactive`,`focusRing`],[`colors`,`interactive`,`hover`],[`colors`,`status`,`error`],[`colors`,`status`,`errorForeground`],[`colors`,`status`,`errorBackground`],[`colors`,`status`,`errorBorder`],[`colors`,`status`,`warning`],[`colors`,`status`,`warningForeground`],[`colors`,`status`,`warningBackground`],[`colors`,`status`,`warningBorder`],[`colors`,`status`,`success`],[`colors`,`status`,`successForeground`],[`colors`,`status`,`successBackground`],[`colors`,`status`,`successBorder`],[`colors`,`status`,`info`],[`colors`,`status`,`infoForeground`],[`colors`,`status`,`infoBackground`],[`colors`,`status`,`infoBorder`],[`colors`,`syntax`,`base`,`background`],[`colors`,`syntax`,`base`,`foreground`],[`colors`,`syntax`,`base`,`keyword`],[`colors`,`syntax`,`base`,`string`],[`colors`,`syntax`,`base`,`number`],[`colors`,`syntax`,`base`,`function`],[`colors`,`syntax`,`base`,`variable`],[`colors`,`syntax`,`base`,`type`],[`colors`,`syntax`,`base`,`comment`],[`colors`,`syntax`,`base`,`operator`],[`colors`,`syntax`,`highlights`,`diffAdded`],[`colors`,`syntax`,`highlights`,`diffRemoved`],[`colors`,`syntax`,`highlights`,`lineNumber`]])if(!Cr(Sr(e,t)))return!1;let t=Sr(e,[`metadata`,`variant`]);return t===`light`||t===`dark`},Tr=e=>wr(e.currentTheme)?e.currentTheme:null,Er=e=>Tr(e)?.metadata.variant??null,Dr=Gt,Or=qt,kr=()=>{let e=yr()?.get(`currentTheme`);if(!e)return null;try{let t=JSON.parse(e);return wr(t)?t:null}catch{return null}},Ar=e=>Kt(e===`dark`),jr=typeof window<`u`?X.useLayoutEffect:X.useEffect,Mr=()=>{if(typeof document>`u`)return;let e=document.documentElement;e.classList.add(`oc-theme-switching`);let t=window.requestAnimationFrame(()=>{window.requestAnimationFrame(()=>{e.classList.remove(`oc-theme-switching`)})});return()=>{window.cancelAnimationFrame(t),e.classList.remove(`oc-theme-switching`)}},Nr=e=>{let t=Dr,n=Or,r=`system`;if(typeof window<`u`){let e=yr(),i=e?.get(`themeMode`),a=e?.get(`lightThemeId`),o=e?.get(`darkThemeId`),s=E(`themeMode`),c=E(`lightThemeId`),l=E(`darkThemeId`),u=E(`useSystemTheme`),d=E(`selectedThemeId`),f=E(`selectedThemeVariant`);if(i===`light`||i===`dark`||i===`system`)r=i;else if(s===`light`||s===`dark`||s===`system`)r=s;else if(u!==null){if(u===`true`)r=`system`;else if(d){let e=Wt(d);e&&(r=e.metadata.variant===`dark`?`dark`:`light`,e.metadata.variant===`dark`?n=e.metadata.id:t=e.metadata.id)}}else(f===`light`||f===`dark`)&&(r=f);typeof a==`string`&&a.trim().length>0?t=a.trim():typeof c==`string`&&c.trim().length>0&&(t=c.trim()),typeof o==`string`&&o.trim().length>0?n=o.trim():typeof l==`string`&&l.trim().length>0&&(n=l.trim())}if(e){let r=Wt(e);r&&(r.metadata.variant===`light`?t=r.metadata.id:n=r.metadata.id)}return{themeMode:r,lightThemeId:t,darkThemeId:n}};function Pr({children:e,defaultThemeId:t}){let n=(0,X.useMemo)(()=>new vr,[]),[r,i]=(0,X.useState)(()=>Nr(t)),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(()=>xr()),[d,f]=(0,X.useState)([]),[p]=(0,X.useState)(()=>kr()),[m,h]=(0,X.useState)(null),[g,v]=(0,X.useState)(!1),[y,S]=(0,X.useState)(()=>typeof window>`u`||!_()?null:window.__OPENCHAMBER_VSCODE_THEME__||null),C=(0,X.useMemo)(()=>_(),[]),w=(0,X.useMemo)(()=>x(),[]),ee=(0,X.useMemo)(()=>b(),[]),k=(0,X.useMemo)(()=>typeof window>`u`?!1:yr()!==null,[]),j=(0,X.useMemo)(()=>{let e=[],t=new Set,n=n=>{let r=n.metadata.id;t.has(r)||(t.add(r),e.push(n))};return C&&y&&n(y),m&&n(m),p&&n(p),d.forEach(n),Ut.forEach(n),e},[d,p,m,C,y]),M=(0,X.useMemo)(()=>e=>j.find(t=>t.metadata.id===e),[j]),N=(0,X.useMemo)(()=>(e,t)=>{let n=M(e);return n&&n.metadata.variant===t?n:j.find(e=>e.metadata.variant===t)??Ar(t)},[j,M]),P=(0,X.useMemo)(()=>C&&y?y:r.themeMode===`light`?N(r.lightThemeId,`light`):r.themeMode===`dark`||s?N(r.darkThemeId,`dark`):N(r.lightThemeId,`light`),[N,C,r,s,y]),F=ge(async()=>{if(!(typeof window>`u`||C)){v(!0);try{let e=await D(`/api/config/themes`,{method:`GET`,credentials:w?`omit`:`include`,headers:{Accept:`application/json`}});if(e.status===401||!e.ok)return;let t=await e.json(),n=(Array.isArray(t?.themes)?t.themes:[]).filter(wr);f(n)}catch{}finally{v(!1)}}});(0,X.useEffect)(()=>{F()},[F]),(0,X.useEffect)(()=>{if(!C)return;let e=e=>{S(e)},t=t=>{let n=t.detail;n?.theme&&e(n.theme)},n=window.__OPENCHAMBER_VSCODE_THEME__;return n&&e(n),window.addEventListener(`openchamber:vscode-theme`,t),()=>window.removeEventListener(`openchamber:vscode-theme`,t)},[C]);let I=ge(e=>{if(typeof document>`u`)return;let t=document.documentElement.hasAttribute(`data-oc-vibrancy`)||window.__OPENCHAMBER_ELECTRON__?.macVibrancy===!0?`transparent`:e.colors.surface.background;document.body.style.backgroundColor=t;let n=document.querySelector(`meta[name="theme-color"]`);n||(n=document.createElement(`meta`),n.setAttribute(`name`,`theme-color`),document.head.appendChild(n)),n.setAttribute(`content`,t);let r=e.metadata.variant===`dark`?`(prefers-color-scheme: dark)`:`(prefers-color-scheme: light)`,i=document.querySelector(`meta[name="theme-color"][media="${r}"]`);i||(i=document.createElement(`meta`),i.setAttribute(`name`,`theme-color`),i.setAttribute(`media`,r),document.head.appendChild(i)),i.setAttribute(`content`,t)}),L=ge(e=>{typeof document>`u`||document.documentElement.classList.toggle(`vscode-runtime`,e)});jr(()=>{if(typeof window>`u`)return;let e=Mr();n.apply(P),L(C),I(P);let t=document.documentElement;return t.classList.remove(`light`,`dark`),t.classList.add(P.metadata.variant),e},[L,n,P,C,I]),(0,X.useEffect)(()=>{if(r.themeMode!==`system`||typeof window>`u`||k)return;let e=window.matchMedia(`(prefers-color-scheme: dark)`),t=e=>{c(e.matches)};return c(e.matches),e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[r.themeMode,k]),(0,X.useEffect)(()=>{if(k||typeof window>`u`)return;T(`themeMode`,r.themeMode),T(`lightThemeId`,r.lightThemeId),T(`darkThemeId`,r.darkThemeId),T(`useSystemTheme`,String(r.themeMode===`system`)),T(`selectedThemeId`,P.metadata.id),T(`selectedThemeVariant`,P.metadata.variant===`light`?`light`:`dark`);let e=N(r.lightThemeId,`light`),t=N(r.darkThemeId,`dark`);T(`splashBgLight`,e.colors.surface.background),T(`splashFgLight`,e.colors.surface.foreground),T(`splashBgDark`,t.colors.surface.background),T(`splashFgDark`,t.colors.surface.foreground),w&&(localStorage.setItem(`themeMode`,r.themeMode),localStorage.setItem(`useSystemTheme`,String(r.themeMode===`system`)),localStorage.setItem(`splashBgLight`,e.colors.surface.background),localStorage.setItem(`splashFgLight`,e.colors.surface.foreground),localStorage.setItem(`splashBgDark`,t.colors.surface.background),localStorage.setItem(`splashFgDark`,t.colors.surface.foreground))},[r,P,N,w,k]),(0,X.useEffect)(()=>{if(typeof window>`u`||k)return;let e=e=>{e.storageArea===window.localStorage&&(O(e.key,`themeMode`)||O(e.key,`lightThemeId`)||O(e.key,`darkThemeId`))&&i(e=>{let t=E(`themeMode`),n=t===`light`||t===`dark`||t===`system`?t:e.themeMode,r=E(`lightThemeId`),i=typeof r==`string`&&r.trim().length>0?r.trim():e.lightThemeId,a=E(`darkThemeId`),o=typeof a==`string`&&a.trim().length>0?a.trim():e.darkThemeId;return n===e.themeMode&&i===e.lightThemeId&&o===e.darkThemeId?e:{themeMode:n,lightThemeId:i,darkThemeId:o}})};return window.addEventListener(`storage`,e),()=>window.removeEventListener(`storage`,e)},[k]);let te=ge(e=>{let t=e.themeMode,n=e.lightThemeId,r=e.darkThemeId,a=Er(e),o=Tr(e);if(t!==`light`&&t!==`dark`&&t!==`system`||typeof n!=`string`||typeof r!=`string`)return;let s=n.trim(),l=r.trim();!s||!l||(Mr(),(0,gr.flushSync)(()=>{k&&o&&h(o),t===`system`&&a&&c(a===`dark`),i(e=>e.themeMode===t&&e.lightThemeId===s&&e.darkThemeId===l?e:{themeMode:t,lightThemeId:s,darkThemeId:l})}))});(0,X.useEffect)(()=>{if(typeof window>`u`)return;let e=window;return e.__openchamberApplyThemeSync=te,()=>{e.__openchamberApplyThemeSync===te&&delete e.__openchamberApplyThemeSync}},[te]),(0,X.useEffect)(()=>{if(typeof window>`u`)return;let e=e=>{if(e.origin!==window.location.origin)return;let t=e.data;t?.type!==`openchamber:theme-sync`||!t.payload||te(t.payload)};return window.addEventListener(`message`,e),()=>window.removeEventListener(`message`,e)},[te]),(0,X.useEffect)(()=>{if(k||!a)return;let e=N(r.lightThemeId,`light`),t=N(r.darkThemeId,`dark`);A({themeId:P.metadata.id,themeVariant:P.metadata.variant===`light`?`light`:`dark`,useSystemTheme:r.themeMode===`system`,lightThemeId:r.lightThemeId,darkThemeId:r.darkThemeId,splashBgLight:e.colors.surface.background,splashFgLight:e.colors.surface.foreground,splashBgDark:t.colors.surface.background,splashFgDark:t.colors.surface.foreground})},[P.metadata.id,P.metadata.variant,N,r.themeMode,r.lightThemeId,r.darkThemeId,k,a]),(0,X.useEffect)(()=>{k||!ee||(async()=>{await be(r.themeMode,P.metadata.variant)})()},[P.metadata.variant,ee,r.themeMode,k]),(0,X.useEffect)(()=>{if(typeof window>`u`)return;let e=e=>{let t=e.detail;t&&(i(e=>{let n=e.themeMode;t.useSystemTheme===!0?n=`system`:t.useSystemTheme===!1&&(t.themeVariant===`dark`||t.themeVariant===`light`)&&(n=t.themeVariant);let r=e.lightThemeId;typeof t.lightThemeId==`string`&&t.lightThemeId.length>0&&(r=t.lightThemeId.trim());let i=e.darkThemeId;return typeof t.darkThemeId==`string`&&t.darkThemeId.length>0&&(i=t.darkThemeId.trim()),n===e.themeMode&&r===e.lightThemeId&&i===e.darkThemeId?e:{themeMode:n,lightThemeId:r,darkThemeId:i}}),o(!0))};return window.addEventListener(`openchamber:settings-synced`,e),()=>window.removeEventListener(`openchamber:settings-synced`,e)},[]),(0,X.useEffect)(()=>{if(!(k||typeof window>`u`))return l(e=>{u(e)&&(i(e=>{let t=E(`themeMode`),n=t===`light`||t===`dark`||t===`system`?t:e.themeMode,r=E(`lightThemeId`),i=typeof r==`string`&&r.trim().length>0?r.trim():e.lightThemeId,a=E(`darkThemeId`),o=typeof a==`string`&&a.trim().length>0?a.trim():e.darkThemeId;return n===e.themeMode&&i===e.lightThemeId&&o===e.darkThemeId?e:{themeMode:n,lightThemeId:i,darkThemeId:o}}),o(!1))})},[k]);let R=ge(e=>{let t=j.find(t=>t.metadata.id===e);t&&i(e=>t.metadata.variant===`dark`?e.darkThemeId===t.metadata.id&&e.themeMode===`dark`?e:{...e,darkThemeId:t.metadata.id,themeMode:`dark`}:e.lightThemeId===t.metadata.id&&e.themeMode===`light`?e:{...e,lightThemeId:t.metadata.id,themeMode:`light`})}),ne=ge(e=>{i(t=>t.themeMode===e?t:{...t,themeMode:e})}),z=ge(e=>{if(e){i(e=>e.themeMode===`system`?e:{...e,themeMode:`system`});return}let t=P.metadata.variant===`dark`?`dark`:`light`;i(e=>e.themeMode===t?e:{...e,themeMode:t})}),B=ge(e=>{let t=j.find(t=>t.metadata.id===e&&t.metadata.variant===`light`);t&&i(e=>e.lightThemeId===t.metadata.id?e:{...e,lightThemeId:t.metadata.id})}),V=ge(e=>{let t=j.find(t=>t.metadata.id===e&&t.metadata.variant===`dark`);t&&i(e=>e.darkThemeId===t.metadata.id?e:{...e,darkThemeId:t.metadata.id})}),H=(0,X.useMemo)(()=>({currentTheme:P,availableThemes:j,setTheme:R,customThemesLoading:g,reloadCustomThemes:F,isSystemPreference:r.themeMode===`system`,setSystemPreference:z,themeMode:r.themeMode,setThemeMode:ne,lightThemeId:r.lightThemeId,darkThemeId:r.darkThemeId,setLightThemePreference:B,setDarkThemePreference:V}),[j,P,g,r.darkThemeId,r.lightThemeId,r.themeMode,F,V,B,z,R,ne]);return(0,Q.jsx)(It.Provider,{value:H,children:e})}var Fr=!1,Ir=()=>{if(Fr||typeof window>`u`)return;Fr=!0;let e={showReasoningTraces:p.getState().showReasoningTraces,sessionRecapEnabled:p.getState().sessionRecapEnabled,sessionTitleRefreshEnabled:p.getState().sessionTitleRefreshEnabled,sessionGoalEnabled:p.getState().sessionGoalEnabled,sessionGoalDefaultBudgetEnabled:p.getState().sessionGoalDefaultBudgetEnabled,sessionGoalDefaultBudget:p.getState().sessionGoalDefaultBudget,collapsibleThinkingBlocks:p.getState().collapsibleThinkingBlocks,showDeletionDialog:p.getState().showDeletionDialog,nativeNotificationsEnabled:p.getState().nativeNotificationsEnabled,notificationMode:p.getState().notificationMode,notifyOnSubtasks:p.getState().notifyOnSubtasks,notifyOnCompletion:p.getState().notifyOnCompletion,notifyOnError:p.getState().notifyOnError,notifyOnQuestion:p.getState().notifyOnQuestion,notificationTemplates:p.getState().notificationTemplates,summarizeLastMessage:p.getState().summarizeLastMessage,summaryThreshold:p.getState().summaryThreshold,summaryLength:p.getState().summaryLength,maxLastMessageLength:p.getState().maxLastMessageLength,autoDeleteEnabled:p.getState().autoDeleteEnabled,autoDeleteAfterDays:p.getState().autoDeleteAfterDays,sessionRetentionAction:p.getState().sessionRetentionAction,fontSize:p.getState().fontSize,terminalFontSize:p.getState().terminalFontSize,editorFontSize:p.getState().editorFontSize,uiFont:p.getState().uiFont,monoFont:p.getState().monoFont,padding:p.getState().padding,cornerRadius:p.getState().cornerRadius,inputBarOffset:p.getState().inputBarOffset,mobileKeyboardMode:p.getState().mobileKeyboardMode,diffLayoutPreference:p.getState().diffLayoutPreference,gitChangesViewMode:p.getState().gitChangesViewMode},t=null,n=null,r=()=>{let e=t;t=null,n=null,e&&Object.keys(e).length>0&&A(e)},i=e=>{t={...t??{},...e},!n&&(n=setTimeout(r,150))};p.subscribe(t=>{let n={showReasoningTraces:t.showReasoningTraces,sessionRecapEnabled:t.sessionRecapEnabled,sessionTitleRefreshEnabled:t.sessionTitleRefreshEnabled,sessionGoalEnabled:t.sessionGoalEnabled,sessionGoalDefaultBudgetEnabled:t.sessionGoalDefaultBudgetEnabled,sessionGoalDefaultBudget:t.sessionGoalDefaultBudget,collapsibleThinkingBlocks:t.collapsibleThinkingBlocks,showDeletionDialog:t.showDeletionDialog,nativeNotificationsEnabled:t.nativeNotificationsEnabled,notificationMode:t.notificationMode,notifyOnSubtasks:t.notifyOnSubtasks,notifyOnCompletion:t.notifyOnCompletion,notifyOnError:t.notifyOnError,notifyOnQuestion:t.notifyOnQuestion,notificationTemplates:t.notificationTemplates,summarizeLastMessage:t.summarizeLastMessage,summaryThreshold:t.summaryThreshold,summaryLength:t.summaryLength,maxLastMessageLength:t.maxLastMessageLength,autoDeleteEnabled:t.autoDeleteEnabled,autoDeleteAfterDays:t.autoDeleteAfterDays,sessionRetentionAction:t.sessionRetentionAction,fontSize:t.fontSize,terminalFontSize:t.terminalFontSize,editorFontSize:t.editorFontSize,uiFont:t.uiFont,monoFont:t.monoFont,padding:t.padding,cornerRadius:t.cornerRadius,inputBarOffset:t.inputBarOffset,mobileKeyboardMode:t.mobileKeyboardMode,diffLayoutPreference:t.diffLayoutPreference,gitChangesViewMode:t.gitChangesViewMode},r={};n.showReasoningTraces!==e.showReasoningTraces&&(r.showReasoningTraces=n.showReasoningTraces),n.sessionRecapEnabled!==e.sessionRecapEnabled&&(r.sessionRecapEnabled=n.sessionRecapEnabled),n.sessionTitleRefreshEnabled!==e.sessionTitleRefreshEnabled&&(r.sessionTitleRefreshEnabled=n.sessionTitleRefreshEnabled),n.sessionGoalEnabled!==e.sessionGoalEnabled&&(r.sessionGoalEnabled=n.sessionGoalEnabled),n.sessionGoalDefaultBudgetEnabled!==e.sessionGoalDefaultBudgetEnabled&&(r.sessionGoalDefaultBudgetEnabled=n.sessionGoalDefaultBudgetEnabled),n.sessionGoalDefaultBudget!==e.sessionGoalDefaultBudget&&(r.sessionGoalDefaultBudget=n.sessionGoalDefaultBudget),n.collapsibleThinkingBlocks!==e.collapsibleThinkingBlocks&&(r.collapsibleThinkingBlocks=n.collapsibleThinkingBlocks),n.showDeletionDialog!==e.showDeletionDialog&&(r.showDeletionDialog=n.showDeletionDialog),n.nativeNotificationsEnabled!==e.nativeNotificationsEnabled&&(r.nativeNotificationsEnabled=n.nativeNotificationsEnabled),n.notificationMode!==e.notificationMode&&(r.notificationMode=n.notificationMode),n.notifyOnSubtasks!==e.notifyOnSubtasks&&(r.notifyOnSubtasks=n.notifyOnSubtasks),n.notifyOnCompletion!==e.notifyOnCompletion&&(r.notifyOnCompletion=n.notifyOnCompletion),n.notifyOnError!==e.notifyOnError&&(r.notifyOnError=n.notifyOnError),n.notifyOnQuestion!==e.notifyOnQuestion&&(r.notifyOnQuestion=n.notifyOnQuestion),JSON.stringify(n.notificationTemplates)!==JSON.stringify(e.notificationTemplates)&&(r.notificationTemplates=n.notificationTemplates),n.summarizeLastMessage!==e.summarizeLastMessage&&(r.summarizeLastMessage=n.summarizeLastMessage),n.summaryThreshold!==e.summaryThreshold&&(r.summaryThreshold=n.summaryThreshold),n.summaryLength!==e.summaryLength&&(r.summaryLength=n.summaryLength),n.maxLastMessageLength!==e.maxLastMessageLength&&(r.maxLastMessageLength=n.maxLastMessageLength),n.autoDeleteEnabled!==e.autoDeleteEnabled&&(r.autoDeleteEnabled=n.autoDeleteEnabled),n.autoDeleteAfterDays!==e.autoDeleteAfterDays&&(r.autoDeleteAfterDays=n.autoDeleteAfterDays),n.sessionRetentionAction!==e.sessionRetentionAction&&(r.sessionRetentionAction=n.sessionRetentionAction),n.fontSize!==e.fontSize&&(r.fontSize=n.fontSize),n.terminalFontSize!==e.terminalFontSize&&(r.terminalFontSize=n.terminalFontSize),n.editorFontSize!==e.editorFontSize&&(r.editorFontSize=n.editorFontSize),n.uiFont!==e.uiFont&&(r.uiFont=n.uiFont),n.monoFont!==e.monoFont&&(r.monoFont=n.monoFont),n.padding!==e.padding&&(r.padding=n.padding),n.cornerRadius!==e.cornerRadius&&(r.cornerRadius=n.cornerRadius),n.inputBarOffset!==e.inputBarOffset&&(r.inputBarOffset=n.inputBarOffset),n.mobileKeyboardMode!==e.mobileKeyboardMode&&(r.mobileKeyboardMode=n.mobileKeyboardMode),n.diffLayoutPreference!==e.diffLayoutPreference&&(r.diffLayoutPreference=n.diffLayoutPreference),n.gitChangesViewMode!==e.gitChangesViewMode&&(r.gitChangesViewMode=n.gitChangesViewMode),e=n,Object.keys(r).length>0&&i(r)})},Lr=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]?.providerID!==t[n]?.providerID||e[n]?.modelID!==t[n]?.modelID)return!1;return!0},Rr=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0},zr=(e,t)=>{if(e===t)return!0;let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Array.isArray(t[n])&&Rr(e[n],t[n]))},Br=()=>{let e=p.getState();return{favoriteModels:e.favoriteModels,hiddenModels:e.hiddenModels,collapsedModelProviders:e.collapsedModelProviders,recentModels:e.recentModels,recentAgents:e.recentAgents,recentEfforts:e.recentEfforts}},Vr=(e,t)=>Lr(e.favoriteModels,t.favoriteModels)&&Lr(e.hiddenModels,t.hiddenModels)&&Rr(e.collapsedModelProviders,t.collapsedModelProviders)&&Lr(e.recentModels,t.recentModels)&&Rr(e.recentAgents,t.recentAgents)&&zr(e.recentEfforts,t.recentEfforts),Hr=e=>({favoriteModels:e.favoriteModels.slice(),hiddenModels:e.hiddenModels.slice(),collapsedModelProviders:e.collapsedModelProviders.slice(),recentModels:e.recentModels.slice(),recentAgents:e.recentAgents.slice(),recentEfforts:Object.fromEntries(Object.entries(e.recentEfforts).map(([e,t])=>[e,t.slice()]))}),Ur=()=>{if(typeof window>`u`)return()=>{};let e=null,t=null,n=!1,r=()=>{e=null;let n=Br();t&&Vr(t,n)||(t=Hr(n),A(n).catch(()=>{}))},i=()=>{if(!n){n=!0;return}e!==null&&window.clearTimeout(e),e=window.setTimeout(r,1200)},a=p.subscribe((e,t)=>{Vr({favoriteModels:e.favoriteModels,hiddenModels:e.hiddenModels,collapsedModelProviders:e.collapsedModelProviders,recentModels:e.recentModels,recentAgents:e.recentAgents,recentEfforts:e.recentEfforts},{favoriteModels:t.favoriteModels,hiddenModels:t.hiddenModels,collapsedModelProviders:t.collapsedModelProviders,recentModels:t.recentModels,recentAgents:t.recentAgents,recentEfforts:t.recentEfforts})||i()});return()=>{a(),e!==null&&window.clearTimeout(e)}},Wr=!1,Gr=`openchamber-typography-base`,Kr=()=>{if(typeof document>`u`)return;let e=`:root {\n${Object.entries(d).map(([e,t])=>` --text-${e.replace(/([A-Z])/g,`-$1`).toLowerCase()}: ${t};`).join(`
4
- `)}\n}\n`,t=document.getElementById(Gr);if(t){t.textContent=e;return}let n=document.createElement(`style`);n.id=Gr,n.textContent=e,document.head.appendChild(n)},qr=()=>{Wr||typeof window>`u`||(Wr=!0,Kr())};function Jr(e){let t=(0,Z.c)(3),{children:n}=e,r;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=[],t[0]=r):r=t[0],(0,X.useEffect)(Yr,r);let i;return t[1]===n?i=t[2]:(i=(0,Q.jsx)(pe,{client:M,children:n}),t[1]=n,t[2]=i),i}function Yr(){return C(M)}var Xr=15,Zr=2e3,Qr=e=>{let t=K(e=>e.isConnected),n=K(e=>e.providers.length),r=K(e=>e.agents.length),i=K(e=>e.activeDirectoryKey),a=K(e=>e.refreshMissingCatalogs),o=e.enabled&&t&&(n===0||r===0),s=X.useRef(0),c=X.useRef(!1),[l,u]=X.useState(!1),d=e.source,f=ge(async()=>{if(!o||c.current)return;if(s.current>=Xr){u(!0);return}let e=K.getState();if(!(e.providers.length>0&&e.agents.length>0)){c.current=!0,s.current+=1;try{await a({source:d})}catch{}finally{c.current=!1}}});X.useEffect(()=>{s.current=0,c.current=!1,u(!1),o&&f()},[o,i]),he(f,o&&!l?Zr:null)},$r=40,ei=20971520,ti=new Map,ni=0;function ri(e){return e.length*2}function ii(e,t){let n=ti.get(e);n!==void 0&&(ni-=n),ti.delete(e),ti.set(e,t),ni+=t}function ai(e,t){let n=ti.get(e);(n!==void 0||t!==void 0)&&ii(e,t??n??0)}function oi(e){let t=ti.get(e);t!==void 0&&(ti.delete(e),ni-=t)}function si(e,t){let n=e??new Set;for(;ti.size>$r||ni>ei;){let e=ti.keys().next().value;if(!e)return;if(n.has(e)){if(ai(e),ti.size<=n.size)return;continue}oi(e),t(e)}}function ci(e,t){ii(e,t)}function li(e){oi(e)}function ui(e,t){ai(e,t)}function di(e){let t=new Map,n=e=>{t.delete(e),li(e)},r=e=>{let r=e.endsWith(`/`)?e:`${e}/`;for(let i of t.keys())(i===e||i.startsWith(r))&&n(i)},i=(e,t)=>t.isFile?e.mtimeMs!==void 0&&t.mtimeMs!==void 0?e.mtimeMs===t.mtimeMs&&e.size===t.size:e.size===t.size:!1,a=(e,n,r)=>{let i=ri(n.content);return t.set(e,{...n,size:r?.isFile?r.size:void 0,mtimeMs:r?.isFile?r.mtimeMs:void 0}),ci(e,i),si(new Set,e=>{t.delete(e)}),n},o=async(t,n)=>{let r=await e.statFile?.(t,n).catch(()=>null),i=await e.readFile(t,n),o=await e.statFile?.(t,n).catch(()=>null);if(r&&o&&r.isFile&&o.isFile){if(r.size===o.size&&r.mtimeMs===o.mtimeMs)return a(t,i,o);let s=await e.statFile?.(t,n).catch(()=>null),c=await e.readFile(t,n),l=await e.statFile?.(t,n).catch(()=>null);return s&&l&&s.isFile&&l.isFile&&s.size===l.size&&(s.mtimeMs,l.mtimeMs),a(t,c,l)}return a(t,i,o??r)},s=e.readFile?async(r,a)=>{if(a?.allowOutsideWorkspace)return o(r,a);let s=t.get(r);if(s){if(e.statFile){let t=await e.statFile(r,a).catch(()=>(n(r),null));if(!t||!i(s,t))return n(r),o(r,a)}return ui(r),{content:s.content,path:s.path}}return o(r,a)}:void 0,c=e.writeFile?async(t,r)=>(n(t),e.writeFile(t,r)):void 0,l=e.delete?async t=>(r(t),e.delete(t)):void 0,u=e.rename?async(t,n)=>(r(t),r(n),e.rename(t,n)):void 0;return{...e,readFile:s,writeFile:c,delete:l,rename:u}}function fi(e){let t=(0,Z.c)(8),{apis:n,children:r}=e,i;t[0]===n.files?i=t[1]:(i=di(n.files),t[0]=n.files,t[1]=i);let a;t[2]!==n||t[3]!==i?(a={...n,files:i},t[2]=n,t[3]=i,t[4]=a):a=t[4];let o=a,s;return t[5]!==o||t[6]!==r?(s=(0,Q.jsx)(on.Provider,{value:o,children:r}),t[5]=o,t[6]=r,t[7]=s):s=t[7],s}var pi=`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)`,mi=`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)`;function hi(){let e=(0,Z.c)(2),t=gi,[n,r]=X.useState(t),i,a;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(i=()=>{let e=()=>r(t()),n=new MutationObserver(e);return n.observe(document.documentElement,{attributes:!0,attributeFilter:[`class`]}),e(),()=>n.disconnect()},a=[],e[0]=i,e[1]=a):(i=e[0],a=e[1]),X.useEffect(i,a),n}function gi(){return typeof document<`u`&&document.documentElement.classList.contains(`dark`)}function _i(e){let t=(0,Z.c)(3),n,r;t[0]===e?(n=t[1],r=t[2]):(n=()=>{if(typeof document>`u`)return;let t=t=>{t.style.setProperty(`box-shadow`,e,`important`),t.style.setProperty(`outline`,`none`,`important`),t.getAttribute(`tabindex`)===`0`&&t.setAttribute(`tabindex`,`-1`)},n=()=>{document.querySelectorAll(`[data-sonner-toast]`).forEach(t)};n();let r=new MutationObserver(e=>{for(let n of e)n.addedNodes.forEach(e=>{e instanceof HTMLElement&&(e.matches?.(`[data-sonner-toast]`)&&t(e),e.querySelectorAll?.(`[data-sonner-toast]`).forEach(t))});n()});return r.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:[`style`,`tabindex`,`data-expanded`,`data-swiping`]}),()=>r.disconnect()},r=[e],t[0]=e,t[1]=n,t[2]=r),X.useEffect(n,r)}var vi=e=>{let t=(0,Z.c)(7),n;t[0]===e?n=t[1]:({...n}=e,t[0]=e,t[1]=n);let r=hi();_i(r?pi:mi);let i=r?`dark`:`light`,a,o;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(a={classNames:{toast:`group/toast toast !flex !min-w-[min(var(--width),calc(100vw-2rem))] !max-w-[calc(100vw-2rem)] !items-center !rounded-[var(--radius-xl)] !border-0 !px-3.5 !py-3 !gap-2.5 !text-foreground`,content:`!min-w-0 !flex-1 !text-left`,title:`typography-ui-label !font-medium !text-foreground`,description:`typography-meta !text-muted-foreground !mt-0.5`,actionButton:`!ms-0 !me-0 !shrink-0 !rounded-[var(--radius-md)] !bg-[var(--primary-base)] !text-[var(--primary-foreground)] hover:!opacity-85 !px-2 !py-1 typography-meta !font-medium transition-opacity`,cancelButton:`!ms-0 !me-0 !shrink-0 !rounded-[var(--radius-md)] !bg-[var(--interactive-hover)] !text-foreground hover:!bg-[var(--interactive-active)] !px-2 !py-1 typography-meta !font-medium transition-colors`,closeButton:`!rounded-[var(--radius-md)] !bg-[var(--interactive-hover)] !text-foreground hover:!bg-[var(--interactive-active)]`,icon:`!shrink-0 !text-muted-foreground`,success:`[&_[data-icon]]:!text-[var(--status-success)]`,error:`[&_[data-icon]]:!text-[var(--status-error)]`,warning:`[&_[data-icon]]:!text-[var(--status-warning)]`,info:`[&_[data-icon]]:!text-[var(--status-info)]`},style:{borderRadius:`var(--radius-xl)`,backgroundColor:`var(--surface-elevated)`}},o={"--normal-bg":`var(--surface-elevated)`,"--normal-text":`var(--foreground)`,"--normal-border":`transparent`,"--error-bg":`var(--surface-elevated)`,"--error-text":`var(--foreground)`,"--error-border":`transparent`,"--success-bg":`var(--surface-elevated)`,"--success-text":`var(--foreground)`,"--success-border":`transparent`,"--warning-bg":`var(--surface-elevated)`,"--warning-text":`var(--foreground)`,"--warning-border":`transparent`,"--info-bg":`var(--surface-elevated)`,"--info-text":`var(--foreground)`,"--info-border":`transparent`},t[2]=a,t[3]=o):(a=t[2],o=t[3]);let s;return t[4]!==n||t[5]!==i?(s=(0,Q.jsx)(me,{theme:i,className:`toaster group`,closeButton:!1,toastOptions:a,style:o,...n}),t[4]=n,t[5]=i,t[6]=s):s=t[6],s},yi=(e,t)=>Ce(Se.getState().dictionary,e,t),bi=e=>{let t=new Date(e),n=new Date,r=(e,t)=>e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate(),i=new Date(n);return i.setDate(n.getDate()-1),r(t,n)?yi(`common.date.today`):r(t,i)?yi(`common.date.yesterday`):t.toLocaleDateString(ye(),{month:`short`,day:`numeric`,year:`numeric`}).replace(`,`,``)},xi=e=>{let t=new Date;if(((e,t)=>e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate())(new Date(e),t)){let t=Date.now()-e;return t<6e4?yi(`common.relative.justNow`):t<36e5?yi(`common.relative.minutesAgoShort`,{count:Math.floor(t/6e4)}):yi(`common.relative.hoursAgoShort`,{count:Math.floor(t/36e5)})}return bi(e)},Si=e=>{let t=Math.max(0,Date.now()-e),n=6e4,r=60*n,i=24*r,a=7*i,o=365*i;return t<r?yi(`common.relative.minutesAgoCompact`,{count:Math.max(1,Math.floor(t/n))}):t<i?yi(`common.relative.hoursAgoCompact`,{count:Math.floor(t/r)}):t<a?yi(`common.relative.daysAgoCompact`,{count:Math.floor(t/i)}):t<5*a?yi(`common.relative.weeksAgoCompact`,{count:Math.floor(t/a)}):t<o?yi(`common.relative.monthsAgoCompact`,{count:Math.floor(t/2592e6)}):yi(`common.relative.yearsAgoCompact`,{count:Math.floor(t/o)})},Ci=(e,t)=>wi(g(e),g(t)),wi=(e,t)=>!e||!t?!1:e===t?!0:t===`/`?e.startsWith(`/`):e.startsWith(`${t}/`),Ti=e=>e.toLowerCase().replace(/^opencode[/-]?/i,``).replace(/[-_]/g,``).trim(),Ei=(e,t)=>e?Ti(e)!==Ti(t):!1,Di=e=>{if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&e.trim().length>0){let t=Number(e);if(Number.isFinite(t))return t}},Oi=e=>Di(e.time?.created)??0,ki=(e,t,n)=>{let r=n.has(e.id),i=n.has(t.id);return r===i?r&&i?Oi(t)-Oi(e):Ae(t)-Ae(e):r?-1:1},Ai=e=>{let t=new Map;return e.forEach(e=>{t.set(e.id,e)}),Array.from(t.values())},ji=e=>`__archived__:${e}`,Mi=(e,t)=>{let n=g(e.directory??null),r=g(e.project?.worktree??null),i=n??r;if(!i)return`unassigned`;if(t&&i===t)return`project root`;let a=(t&&i.startsWith(`${t}/`)?i.slice(t.length+1):i).split(`/`).filter(Boolean);return a[a.length-1]??`unassigned`},Ni=`box-border w-full px-2 py-1.5 text-left typography-micro text-muted-foreground/70 select-none`,Pi=`bg-[color-mix(in_srgb,var(--surface-foreground)_6%,transparent)] dark:bg-[color-mix(in_srgb,var(--surface-foreground)_11%,transparent)]`,Fi=`hover:bg-[color-mix(in_srgb,var(--surface-foreground)_3.5%,transparent)] dark:hover:bg-[color-mix(in_srgb,var(--surface-foreground)_8%,transparent)]`,Ii=e=>{let t=Math.max(0,e);return t===0?8:30+(t-1)*14},Li=(e,t)=>{if(!t)return e;let n=e.toLowerCase(),r=t.toLowerCase(),i=r.length;if(i===0)return e;let a=[],o=0,s=n.indexOf(r,o);for(;s!==-1;){s>o&&a.push(e.slice(o,s));let t=e.slice(s,s+i);a.push((0,Q.jsx)(`mark`,{className:`bg-primary text-primary-foreground ring-1 ring-primary/90`,children:t},`${s}-${t}`)),o=s+i,s=n.indexOf(r,o)}return o<e.length&&a.push(e.slice(o)),a.length>0?a:e},Ri=2e4,zi=()=>typeof document>`u`||document.visibilityState===`visible`&&document.hasFocus()?`visible`:`hidden`,Bi=e=>{if(!w()&&!qe())return;let t=N();t?.push?.setVisibility&&t.push.setVisibility({visible:e,platform:we()})},Vi=e=>{let t=e?.enabled??!0;X.useEffect(()=>{if(!t||!w()&&!qe()||typeof window>`u`)return;if(qe()){let e=!0,t=!1,n=null,r=()=>Bi(e);de(async()=>{let{App:e}=await import(`./vendor-capacitor-app-PzT84wSx.js`).then(e=>e.t);return{App:e}},__vite__mapDeps([0,1,2])).then(async({App:i})=>{if(t)return;let a=await i.getState().catch(()=>null);a&&(e=a.isActive===!0),r();let o=await i.addListener(`appStateChange`,({isActive:t})=>{e=t===!0,r()});if(t){o.remove();return}n=()=>void o.remove()}).catch(()=>void 0);let i=window.setInterval(()=>{e&&Bi(!0)},Ri);return()=>{t=!0,window.clearInterval(i),n?.()}}if(typeof document>`u`)return;let e=()=>{Bi(zi()===`visible`)},n=()=>{zi()===`visible`&&Bi(!0)},r=()=>{Bi(!1)};e();let i=window.setInterval(n,Ri);return document.addEventListener(`visibilitychange`,e),window.addEventListener(`pagehide`,r),window.addEventListener(`pageshow`,e),window.addEventListener(`focus`,e),window.addEventListener(`blur`,e),()=>{window.clearInterval(i),document.removeEventListener(`visibilitychange`,e),window.removeEventListener(`pagehide`,r),window.removeEventListener(`pageshow`,e),window.removeEventListener(`focus`,e),window.removeEventListener(`blur`,e)}},[t])},Hi=`OpenChamber`,Ui=e=>{let t=e.replace(/\\/g,`/`).replace(/\/+$/,``).split(`/`).filter(Boolean);return t[t.length-1]??``},Wi=(e,t)=>[e,t,Hi].filter(e=>typeof e==`string`&&e.trim().length>0).join(` | `),Gi=()=>{let e=We(e=>e.activeProjectId?e.projects.find(t=>t.id===e.activeProjectId)??null:null),t=X.useMemo(()=>e&&Ui(e.path)||null,[e]),[n,r]=X.useState(null);X.useEffect(()=>{if(typeof window>`u`||!b()){r(null);return}let e=!1,t=async()=>{try{if(x()){e||r(null);return}let t=window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,n=h();if(n&&I(n,t)){e||r(null);return}let i=(await H()).hosts.find(e=>n?I(n,R(e)):!1),a=i?.label?.trim()?L(i.label.trim()):`Instance`;e||r(a)}catch{e||r(`Instance`)}};t();let n=()=>{t()};return window.addEventListener(`focus`,n),()=>{e=!0,window.removeEventListener(`focus`,n)}},[]);let i=X.useMemo(()=>Wi(t,n),[t,n]);X.useEffect(()=>{typeof document<`u`&&(document.title=i),b()&&(async()=>{try{if(typeof navigator<`u`&&/Macintosh|Mac OS X/.test(navigator.userAgent||``))return;await _e(i)}catch{return}})()},[i])},Ki=()=>{let e=q.getState().currentSessionId;if(!e)return``;let t=Ze().find(t=>t.id===e);return typeof t?.directory==`string`?t.directory:``},qi=async(e,t=6e3)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),t),i=Date.now();try{let t=await D(e,{method:`GET`,headers:{Accept:`application/json`},signal:n.signal}),r=Date.now()-i,a=t.headers.get(`content-type`)||``,o=a.toLowerCase(),s=o.includes(`json`)&&!o.includes(`text/html`),c=``;if(s){let e=await t.json().catch(()=>null);if(Array.isArray(e))c=`json[array] len=${e.length}`;else if(e&&typeof e==`object`){let t=Object.keys(e).slice(0,8);c=`json[object] keys=${t.join(`,`)}${Object.keys(e).length>t.length?`,…`:``}`}else c=`json[${typeof e}]`}else c=a?`content-type=${a}`:`no content-type`;return{ok:t.ok&&s,status:t.status,elapsedMs:r,summary:c}}catch(e){return{ok:!1,status:0,elapsedMs:Date.now()-i,summary:`error=${n.signal.aborted||e instanceof Error&&(e.name===`AbortError`||e.message.toLowerCase().includes(`aborted`))?`timeout after ${t}ms`:e instanceof Error?e.message:String(e)}`}}finally{clearTimeout(r)}},Ji=e=>{if(!e||!Number.isFinite(e))return`(n/a)`;try{return new Date(e).toISOString()}catch{return`(invalid)`}},Yi=e=>{if(typeof e==`number`&&Number.isFinite(e)&&e>0)return Math.trunc(e);if(typeof e==`string`){let t=Number.parseInt(e,10);if(Number.isFinite(t)&&t>0)return t}return null},Xi=e=>!!e&&typeof e==`object`&&!Array.isArray(e),Zi=(e,t=`(n/a)`)=>typeof e==`string`?e.trim()||t:typeof e==`number`&&Number.isFinite(e)?String(e):typeof e==`boolean`?e?`true`:`false`:t,Qi=(e,t,n)=>e===`node-shebang`||e===`node-launcher`?t?`node (${t})`:`node`:e===`bun-shebang`?n?`bun (${n})`:`bun`:e||`direct executable`,$i=async()=>{let e=new Date,t=typeof navigator<`u`?navigator.userAgent:`(no navigator)`,n=Ki(),i=p.getState().eventStreamStatus,a=typeof window<`u`?window.location.origin:``,o=r(),s=o.health(),c=o.api(`/api/`),l=await(async()=>{if(!s)return null;let e=new AbortController,t=setTimeout(()=>e.abort(),5e3);try{let t=await D(s,{method:`GET`,headers:{Accept:`application/json`},signal:e.signal});if(!t.ok)return null;let n=await t.json().catch(()=>null);return!n||typeof n!=`object`||Array.isArray(n)?null:n}catch{return null}finally{clearTimeout(t)}})(),u=await(async()=>{if(!c)return null;let e=new AbortController,t=setTimeout(()=>e.abort(),7e3);try{let t=await D(o.api(`/api/config/opencode-resolution`),{method:`GET`,headers:{Accept:`application/json`},signal:e.signal}),n=t.headers.get(`content-type`)||`(none)`;if(!t.ok)return{data:null,status:t.status,error:`http ${t.status} content-type=${n}`};let r=await t.text(),i=null;try{i=JSON.parse(r)}catch{let e=r.replace(/\s+/g,` `).slice(0,120);return{data:null,status:t.status,error:`invalid json content-type=${n} body=${e||`(empty)`}`}}return!i||typeof i!=`object`||Array.isArray(i)?{data:null,status:t.status,error:`invalid json-shape content-type=${n}`}:{data:i,status:t.status,error:null}}catch(e){return{data:null,status:null,error:e instanceof Error?e.message:String(e)}}finally{clearTimeout(t)}})()||{data:null,status:null,error:null},d=(e,t=!0)=>{if(!c)return null;let r=new URL(e.replace(/^\/+/,``),c);return t&&n&&r.searchParams.set(`directory`,n),r.toString()},f=c?await Promise.all([{label:`health`,path:`/health`,includeDirectory:!1},{label:`config`,path:`/config`,includeDirectory:!0},{label:`providers`,path:`/config/providers`,includeDirectory:!0},{label:`agents`,path:`/agent`,includeDirectory:!0,timeoutMs:12e3},{label:`commands`,path:`/command`,includeDirectory:!0,timeoutMs:1e4},{label:`project`,path:`/project/current`,includeDirectory:!0},{label:`path`,path:`/path`,includeDirectory:!0},{label:`sessions`,path:`/session`,includeDirectory:!0,timeoutMs:12e3},{label:`sessionStatus`,path:`/session/status`,includeDirectory:!0}].map(async e=>{let t=d(e.path,e.includeDirectory!==!1);if(!t)return{label:e.label,url:`(none)`,result:null};let n=await qi(t,typeof e.timeoutMs==`number`?e.timeoutMs:void 0);return{label:e.label,url:t,result:n}})):[],m=[];m.push(`Time: ${e.toISOString()}`),m.push(`OpenChamber version: 1.18.2-beta.21`),m.push(`Runtime: ${a||`(unknown)`} (api=${c||`(unknown)`})`),m.push(`OpenCode SDK base: ${ce.getBaseUrl()}`),m.push(`Event stream: ${i}`),m.push(`Directory: ${n||`(none)`}`),m.push(`Platform: ${t}`);let h=Yi(l?.openCodePort);if(m.push(`OpenCode runtime port: ${h??`(unknown)`}`),typeof l?.openCodeRunning==`boolean`&&m.push(`OpenCode runtime running: ${l.openCodeRunning?`yes`:`no`}`),typeof l?.openCodeSecureConnection==`boolean`&&m.push(`Secure OpenCode connection: ${l.openCodeSecureConnection?`true`:`false`}`),typeof l?.openCodeAuthSource==`string`&&l.openCodeAuthSource.trim()&&m.push(`OpenCode auth source: ${l.openCodeAuthSource}`),typeof window<`u`){let e=window.__OPENCHAMBER_MACOS_MAJOR__;typeof e==`number`&&Number.isFinite(e)&&e>0&&m.push(`macOS major: ${e}`)}if(/Mac OS X|Macintosh/.test(t)){m.push(``),m.push(`OpenCode CLI resolution:`);let e=Xi(l?.lastOpenCodeLaunchDiagnostics)?l.lastOpenCodeLaunchDiagnostics:null,t=e&&Array.isArray(e.args)?e.args.filter(e=>typeof e==`string`):[],n=u.data,r=n&&typeof n.configured==`string`?n.configured:null,i=n&&typeof n.resolved==`string`?n.resolved:l&&typeof l.opencodeBinaryResolved==`string`?l.opencodeBinaryResolved:``,a=n&&typeof n.resolvedDir==`string`?n.resolvedDir:``,o=n&&typeof n.source==`string`?n.source:l&&typeof l.opencodeBinarySource==`string`?l.opencodeBinarySource:``,s=n&&typeof n.launchBinary==`string`?n.launchBinary:l&&typeof l.opencodeLaunchBinary==`string`?l.opencodeLaunchBinary:``,c=n&&typeof n.launchWrapperType==`string`?n.launchWrapperType:l&&typeof l.opencodeLaunchWrapperType==`string`?l.opencodeLaunchWrapperType:``,d=n&&Array.isArray(n.launchArgs)?n.launchArgs.filter(e=>typeof e==`string`):l&&Array.isArray(l.opencodeLaunchArgs)?l.opencodeLaunchArgs.filter(e=>typeof e==`string`):[],f=n&&typeof n.node==`string`?n.node:l&&typeof l.nodeBinaryResolved==`string`?l.nodeBinaryResolved:``,p=n&&typeof n.bun==`string`?n.bun:l&&typeof l.bunBinaryResolved==`string`?l.bunBinaryResolved:``,h=n&&typeof n.detectedNow==`string`?n.detectedNow:``,g=n&&typeof n.detectedSourceNow==`string`?n.detectedSourceNow:``;if(r!==null&&m.push(`- configured: ${r.trim().length===0?`(cleared)`:r}`),i){let e=a||(i.includes(`/`)?i.split(`/`).slice(0,-1).join(`/`)||`/`:``);m.push(`- opencode: ${i}${e?` (dir=${e})`:``}`)}else m.push(`- opencode: (n/a)`);m.push(`- source: ${o||`(n/a)`}`),h&&(m.push(`- detected-now: ${h}`),m.push(`- detected-source: ${g||`(n/a)`}`)),e?(m.push(`- launched-at: ${Zi(e.launchedAt)}`),m.push(`- launch: ${Zi(e.binary)} ${t.join(` `)}`.trim()),m.push(`- cwd: ${Zi(e.cwd)}`),m.push(`- wrapper: ${Zi(e.wrapperType)}`),m.push(`- runtime: ${Qi(Zi(e.wrapperType,``),f,p)}`),m.push(`- PATH entries: ${Zi(e.pathEntryCount,`(unknown)`)}`),m.push(`- shell env: ${Zi(e.hasShellEnv,`(unknown)`)} (${Zi(e.shellEnvKeysCount,`?`)} keys)`)):(m.push(`- launch-binary: ${s||`(n/a)`}`),m.push(`- launch-wrapper: ${c||`(n/a)`}`),m.push(`- launch-args: ${d.length?d.join(` `):`(none)`}`),m.push(`- runtime: ${Qi(c||``,f,p)}`)),!n&&u.error&&m.push(`- resolution-endpoint: ${u.error}`)}if(m.push(``),f.length){m.push(`OpenCode API probes:`);for(let e of f){if(!e.result){m.push(`- ${e.label}: (no url)`);continue}let{ok:t,status:n,elapsedMs:r,summary:i}=e.result,a=t?``:` url=${e.url}`;m.push(`- ${e.label}: ${t?`ok`:`fail`} status=${n} time=${r}ms ${i}${a}`)}}else m.push(`OpenCode API probes: (skipped)`);return m.push(``),m.push(`Generated: ${Ji(Date.now())}`),m.join(`
4
+ `)}\n}\n`,t=document.getElementById(Gr);if(t){t.textContent=e;return}let n=document.createElement(`style`);n.id=Gr,n.textContent=e,document.head.appendChild(n)},qr=()=>{Wr||typeof window>`u`||(Wr=!0,Kr())};function Jr(e){let t=(0,Z.c)(3),{children:n}=e,r;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=[],t[0]=r):r=t[0],(0,X.useEffect)(Yr,r);let i;return t[1]===n?i=t[2]:(i=(0,Q.jsx)(pe,{client:M,children:n}),t[1]=n,t[2]=i),i}function Yr(){return C(M)}var Xr=15,Zr=2e3,Qr=e=>{let t=K(e=>e.isConnected),n=K(e=>e.providers.length),r=K(e=>e.agents.length),i=K(e=>e.activeDirectoryKey),a=K(e=>e.refreshMissingCatalogs),o=e.enabled&&t&&(n===0||r===0),s=X.useRef(0),c=X.useRef(!1),[l,u]=X.useState(!1),d=e.source,f=ge(async()=>{if(!o||c.current)return;if(s.current>=Xr){u(!0);return}let e=K.getState();if(!(e.providers.length>0&&e.agents.length>0)){c.current=!0,s.current+=1;try{await a({source:d})}catch{}finally{c.current=!1}}});X.useEffect(()=>{s.current=0,c.current=!1,u(!1),o&&f()},[o,i]),he(f,o&&!l?Zr:null)},$r=40,ei=20971520,ti=new Map,ni=0;function ri(e){return e.length*2}function ii(e,t){let n=ti.get(e);n!==void 0&&(ni-=n),ti.delete(e),ti.set(e,t),ni+=t}function ai(e,t){let n=ti.get(e);(n!==void 0||t!==void 0)&&ii(e,t??n??0)}function oi(e){let t=ti.get(e);t!==void 0&&(ti.delete(e),ni-=t)}function si(e,t){let n=e??new Set;for(;ti.size>$r||ni>ei;){let e=ti.keys().next().value;if(!e)return;if(n.has(e)){if(ai(e),ti.size<=n.size)return;continue}oi(e),t(e)}}function ci(e,t){ii(e,t)}function li(e){oi(e)}function ui(e,t){ai(e,t)}function di(e){let t=new Map,n=e=>{t.delete(e),li(e)},r=e=>{let r=e.endsWith(`/`)?e:`${e}/`;for(let i of t.keys())(i===e||i.startsWith(r))&&n(i)},i=(e,t)=>t.isFile?e.mtimeMs!==void 0&&t.mtimeMs!==void 0?e.mtimeMs===t.mtimeMs&&e.size===t.size:e.size===t.size:!1,a=(e,n,r)=>{let i=ri(n.content);return t.set(e,{...n,size:r?.isFile?r.size:void 0,mtimeMs:r?.isFile?r.mtimeMs:void 0}),ci(e,i),si(new Set,e=>{t.delete(e)}),n},o=async(t,n)=>{let r=await e.statFile?.(t,n).catch(()=>null),i=await e.readFile(t,n),o=await e.statFile?.(t,n).catch(()=>null);if(r&&o&&r.isFile&&o.isFile){if(r.size===o.size&&r.mtimeMs===o.mtimeMs)return a(t,i,o);let s=await e.statFile?.(t,n).catch(()=>null),c=await e.readFile(t,n),l=await e.statFile?.(t,n).catch(()=>null);return s&&l&&s.isFile&&l.isFile&&s.size===l.size&&(s.mtimeMs,l.mtimeMs),a(t,c,l)}return a(t,i,o??r)},s=e.readFile?async(r,a)=>{if(a?.allowOutsideWorkspace)return o(r,a);let s=t.get(r);if(s){if(e.statFile){let t=await e.statFile(r,a).catch(()=>(n(r),null));if(!t||!i(s,t))return n(r),o(r,a)}return ui(r),{content:s.content,path:s.path}}return o(r,a)}:void 0,c=e.writeFile?async(t,r)=>(n(t),e.writeFile(t,r)):void 0,l=e.delete?async t=>(r(t),e.delete(t)):void 0,u=e.rename?async(t,n)=>(r(t),r(n),e.rename(t,n)):void 0;return{...e,readFile:s,writeFile:c,delete:l,rename:u}}function fi(e){let t=(0,Z.c)(8),{apis:n,children:r}=e,i;t[0]===n.files?i=t[1]:(i=di(n.files),t[0]=n.files,t[1]=i);let a;t[2]!==n||t[3]!==i?(a={...n,files:i},t[2]=n,t[3]=i,t[4]=a):a=t[4];let o=a,s;return t[5]!==o||t[6]!==r?(s=(0,Q.jsx)(on.Provider,{value:o,children:r}),t[5]=o,t[6]=r,t[7]=s):s=t[7],s}var pi=`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)`,mi=`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)`;function hi(){let e=(0,Z.c)(2),t=gi,[n,r]=X.useState(t),i,a;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(i=()=>{let e=()=>r(t()),n=new MutationObserver(e);return n.observe(document.documentElement,{attributes:!0,attributeFilter:[`class`]}),e(),()=>n.disconnect()},a=[],e[0]=i,e[1]=a):(i=e[0],a=e[1]),X.useEffect(i,a),n}function gi(){return typeof document<`u`&&document.documentElement.classList.contains(`dark`)}function _i(e){let t=(0,Z.c)(3),n,r;t[0]===e?(n=t[1],r=t[2]):(n=()=>{if(typeof document>`u`)return;let t=t=>{t.style.setProperty(`box-shadow`,e,`important`),t.style.setProperty(`outline`,`none`,`important`),t.getAttribute(`tabindex`)===`0`&&t.setAttribute(`tabindex`,`-1`)},n=()=>{document.querySelectorAll(`[data-sonner-toast]`).forEach(t)};n();let r=new MutationObserver(e=>{for(let n of e)n.addedNodes.forEach(e=>{e instanceof HTMLElement&&(e.matches?.(`[data-sonner-toast]`)&&t(e),e.querySelectorAll?.(`[data-sonner-toast]`).forEach(t))});n()});return r.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:[`style`,`tabindex`,`data-expanded`,`data-swiping`]}),()=>r.disconnect()},r=[e],t[0]=e,t[1]=n,t[2]=r),X.useEffect(n,r)}var vi=e=>{let t=(0,Z.c)(7),n;t[0]===e?n=t[1]:({...n}=e,t[0]=e,t[1]=n);let r=hi();_i(r?pi:mi);let i=r?`dark`:`light`,a,o;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(a={classNames:{toast:`group/toast toast !flex !min-w-[min(var(--width),calc(100vw-2rem))] !max-w-[calc(100vw-2rem)] !items-center !rounded-[var(--radius-xl)] !border-0 !px-3.5 !py-3 !gap-2.5 !text-foreground`,content:`!min-w-0 !flex-1 !text-left`,title:`typography-ui-label !font-medium !text-foreground`,description:`typography-meta !text-muted-foreground !mt-0.5`,actionButton:`!ms-0 !me-0 !shrink-0 !rounded-[var(--radius-md)] !bg-[var(--primary-base)] !text-[var(--primary-foreground)] hover:!opacity-85 !px-2 !py-1 typography-meta !font-medium transition-opacity`,cancelButton:`!ms-0 !me-0 !shrink-0 !rounded-[var(--radius-md)] !bg-[var(--interactive-hover)] !text-foreground hover:!bg-[var(--interactive-active)] !px-2 !py-1 typography-meta !font-medium transition-colors`,closeButton:`!rounded-[var(--radius-md)] !bg-[var(--interactive-hover)] !text-foreground hover:!bg-[var(--interactive-active)]`,icon:`!shrink-0 !text-muted-foreground`,success:`[&_[data-icon]]:!text-[var(--status-success)]`,error:`[&_[data-icon]]:!text-[var(--status-error)]`,warning:`[&_[data-icon]]:!text-[var(--status-warning)]`,info:`[&_[data-icon]]:!text-[var(--status-info)]`},style:{borderRadius:`var(--radius-xl)`,backgroundColor:`var(--surface-elevated)`}},o={"--normal-bg":`var(--surface-elevated)`,"--normal-text":`var(--foreground)`,"--normal-border":`transparent`,"--error-bg":`var(--surface-elevated)`,"--error-text":`var(--foreground)`,"--error-border":`transparent`,"--success-bg":`var(--surface-elevated)`,"--success-text":`var(--foreground)`,"--success-border":`transparent`,"--warning-bg":`var(--surface-elevated)`,"--warning-text":`var(--foreground)`,"--warning-border":`transparent`,"--info-bg":`var(--surface-elevated)`,"--info-text":`var(--foreground)`,"--info-border":`transparent`},t[2]=a,t[3]=o):(a=t[2],o=t[3]);let s;return t[4]!==n||t[5]!==i?(s=(0,Q.jsx)(me,{theme:i,className:`toaster group`,closeButton:!1,toastOptions:a,style:o,...n}),t[4]=n,t[5]=i,t[6]=s):s=t[6],s},yi=(e,t)=>Ce(Se.getState().dictionary,e,t),bi=e=>{let t=new Date(e),n=new Date,r=(e,t)=>e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate(),i=new Date(n);return i.setDate(n.getDate()-1),r(t,n)?yi(`common.date.today`):r(t,i)?yi(`common.date.yesterday`):t.toLocaleDateString(ye(),{month:`short`,day:`numeric`,year:`numeric`}).replace(`,`,``)},xi=e=>{let t=new Date;if(((e,t)=>e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate())(new Date(e),t)){let t=Date.now()-e;return t<6e4?yi(`common.relative.justNow`):t<36e5?yi(`common.relative.minutesAgoShort`,{count:Math.floor(t/6e4)}):yi(`common.relative.hoursAgoShort`,{count:Math.floor(t/36e5)})}return bi(e)},Si=e=>{let t=Math.max(0,Date.now()-e),n=6e4,r=60*n,i=24*r,a=7*i,o=365*i;return t<r?yi(`common.relative.minutesAgoCompact`,{count:Math.max(1,Math.floor(t/n))}):t<i?yi(`common.relative.hoursAgoCompact`,{count:Math.floor(t/r)}):t<a?yi(`common.relative.daysAgoCompact`,{count:Math.floor(t/i)}):t<5*a?yi(`common.relative.weeksAgoCompact`,{count:Math.floor(t/a)}):t<o?yi(`common.relative.monthsAgoCompact`,{count:Math.floor(t/2592e6)}):yi(`common.relative.yearsAgoCompact`,{count:Math.floor(t/o)})},Ci=(e,t)=>wi(g(e),g(t)),wi=(e,t)=>!e||!t?!1:e===t?!0:t===`/`?e.startsWith(`/`):e.startsWith(`${t}/`),Ti=e=>e.toLowerCase().replace(/^opencode[/-]?/i,``).replace(/[-_]/g,``).trim(),Ei=(e,t)=>e?Ti(e)!==Ti(t):!1,Di=e=>{if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&e.trim().length>0){let t=Number(e);if(Number.isFinite(t))return t}},Oi=e=>Di(e.time?.created)??0,ki=(e,t,n)=>{let r=n.has(e.id),i=n.has(t.id);return r===i?r&&i?Oi(t)-Oi(e):Ae(t)-Ae(e):r?-1:1},Ai=e=>{let t=new Map;return e.forEach(e=>{t.set(e.id,e)}),Array.from(t.values())},ji=e=>`__archived__:${e}`,Mi=(e,t)=>{let n=g(e.directory??null),r=g(e.project?.worktree??null),i=n??r;if(!i)return`unassigned`;if(t&&i===t)return`project root`;let a=(t&&i.startsWith(`${t}/`)?i.slice(t.length+1):i).split(`/`).filter(Boolean);return a[a.length-1]??`unassigned`},Ni=`box-border w-full px-2 py-1.5 text-left typography-micro text-muted-foreground/70 select-none`,Pi=`bg-[color-mix(in_srgb,var(--surface-foreground)_6%,transparent)] dark:bg-[color-mix(in_srgb,var(--surface-foreground)_11%,transparent)]`,Fi=`hover:bg-[color-mix(in_srgb,var(--surface-foreground)_3.5%,transparent)] dark:hover:bg-[color-mix(in_srgb,var(--surface-foreground)_8%,transparent)]`,Ii=e=>{let t=Math.max(0,e);return t===0?8:30+(t-1)*14},Li=(e,t)=>{if(!t)return e;let n=e.toLowerCase(),r=t.toLowerCase(),i=r.length;if(i===0)return e;let a=[],o=0,s=n.indexOf(r,o);for(;s!==-1;){s>o&&a.push(e.slice(o,s));let t=e.slice(s,s+i);a.push((0,Q.jsx)(`mark`,{className:`bg-primary text-primary-foreground ring-1 ring-primary/90`,children:t},`${s}-${t}`)),o=s+i,s=n.indexOf(r,o)}return o<e.length&&a.push(e.slice(o)),a.length>0?a:e},Ri=2e4,zi=()=>typeof document>`u`||document.visibilityState===`visible`&&document.hasFocus()?`visible`:`hidden`,Bi=e=>{if(!w()&&!qe())return;let t=N();t?.push?.setVisibility&&t.push.setVisibility({visible:e,platform:we()})},Vi=e=>{let t=e?.enabled??!0;X.useEffect(()=>{if(!t||!w()&&!qe()||typeof window>`u`)return;if(qe()){let e=!0,t=!1,n=null,r=()=>Bi(e);de(async()=>{let{App:e}=await import(`./vendor-capacitor-app-PzT84wSx.js`).then(e=>e.t);return{App:e}},__vite__mapDeps([0,1,2])).then(async({App:i})=>{if(t)return;let a=await i.getState().catch(()=>null);a&&(e=a.isActive===!0),r();let o=await i.addListener(`appStateChange`,({isActive:t})=>{e=t===!0,r()});if(t){o.remove();return}n=()=>void o.remove()}).catch(()=>void 0);let i=window.setInterval(()=>{e&&Bi(!0)},Ri);return()=>{t=!0,window.clearInterval(i),n?.()}}if(typeof document>`u`)return;let e=()=>{Bi(zi()===`visible`)},n=()=>{zi()===`visible`&&Bi(!0)},r=()=>{Bi(!1)};e();let i=window.setInterval(n,Ri);return document.addEventListener(`visibilitychange`,e),window.addEventListener(`pagehide`,r),window.addEventListener(`pageshow`,e),window.addEventListener(`focus`,e),window.addEventListener(`blur`,e),()=>{window.clearInterval(i),document.removeEventListener(`visibilitychange`,e),window.removeEventListener(`pagehide`,r),window.removeEventListener(`pageshow`,e),window.removeEventListener(`focus`,e),window.removeEventListener(`blur`,e)}},[t])},Hi=`OpenChamber`,Ui=e=>{let t=e.replace(/\\/g,`/`).replace(/\/+$/,``).split(`/`).filter(Boolean);return t[t.length-1]??``},Wi=(e,t)=>[e,t,Hi].filter(e=>typeof e==`string`&&e.trim().length>0).join(` | `),Gi=()=>{let e=We(e=>e.activeProjectId?e.projects.find(t=>t.id===e.activeProjectId)??null:null),t=X.useMemo(()=>e&&Ui(e.path)||null,[e]),[n,r]=X.useState(null);X.useEffect(()=>{if(typeof window>`u`||!b()){r(null);return}let e=!1,t=async()=>{try{if(x()){e||r(null);return}let t=window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,n=h();if(n&&I(n,t)){e||r(null);return}let i=(await H()).hosts.find(e=>n?I(n,R(e)):!1),a=i?.label?.trim()?L(i.label.trim()):`Instance`;e||r(a)}catch{e||r(`Instance`)}};t();let n=()=>{t()};return window.addEventListener(`focus`,n),()=>{e=!0,window.removeEventListener(`focus`,n)}},[]);let i=X.useMemo(()=>Wi(t,n),[t,n]);X.useEffect(()=>{typeof document<`u`&&(document.title=i),b()&&(async()=>{try{if(typeof navigator<`u`&&/Macintosh|Mac OS X/.test(navigator.userAgent||``))return;await _e(i)}catch{return}})()},[i])},Ki=()=>{let e=q.getState().currentSessionId;if(!e)return``;let t=Ze().find(t=>t.id===e);return typeof t?.directory==`string`?t.directory:``},qi=async(e,t=6e3)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),t),i=Date.now();try{let t=await D(e,{method:`GET`,headers:{Accept:`application/json`},signal:n.signal}),r=Date.now()-i,a=t.headers.get(`content-type`)||``,o=a.toLowerCase(),s=o.includes(`json`)&&!o.includes(`text/html`),c=``;if(s){let e=await t.json().catch(()=>null);if(Array.isArray(e))c=`json[array] len=${e.length}`;else if(e&&typeof e==`object`){let t=Object.keys(e).slice(0,8);c=`json[object] keys=${t.join(`,`)}${Object.keys(e).length>t.length?`,…`:``}`}else c=`json[${typeof e}]`}else c=a?`content-type=${a}`:`no content-type`;return{ok:t.ok&&s,status:t.status,elapsedMs:r,summary:c}}catch(e){return{ok:!1,status:0,elapsedMs:Date.now()-i,summary:`error=${n.signal.aborted||e instanceof Error&&(e.name===`AbortError`||e.message.toLowerCase().includes(`aborted`))?`timeout after ${t}ms`:e instanceof Error?e.message:String(e)}`}}finally{clearTimeout(r)}},Ji=e=>{if(!e||!Number.isFinite(e))return`(n/a)`;try{return new Date(e).toISOString()}catch{return`(invalid)`}},Yi=e=>{if(typeof e==`number`&&Number.isFinite(e)&&e>0)return Math.trunc(e);if(typeof e==`string`){let t=Number.parseInt(e,10);if(Number.isFinite(t)&&t>0)return t}return null},Xi=e=>!!e&&typeof e==`object`&&!Array.isArray(e),Zi=(e,t=`(n/a)`)=>typeof e==`string`?e.trim()||t:typeof e==`number`&&Number.isFinite(e)?String(e):typeof e==`boolean`?e?`true`:`false`:t,Qi=(e,t,n)=>e===`node-shebang`||e===`node-launcher`?t?`node (${t})`:`node`:e===`bun-shebang`?n?`bun (${n})`:`bun`:e||`direct executable`,$i=async()=>{let e=new Date,t=typeof navigator<`u`?navigator.userAgent:`(no navigator)`,n=Ki(),i=p.getState().eventStreamStatus,a=typeof window<`u`?window.location.origin:``,o=r(),s=o.health(),c=o.api(`/api/`),l=await(async()=>{if(!s)return null;let e=new AbortController,t=setTimeout(()=>e.abort(),5e3);try{let t=await D(s,{method:`GET`,headers:{Accept:`application/json`},signal:e.signal});if(!t.ok)return null;let n=await t.json().catch(()=>null);return!n||typeof n!=`object`||Array.isArray(n)?null:n}catch{return null}finally{clearTimeout(t)}})(),u=await(async()=>{if(!c)return null;let e=new AbortController,t=setTimeout(()=>e.abort(),7e3);try{let t=await D(o.api(`/api/config/opencode-resolution`),{method:`GET`,headers:{Accept:`application/json`},signal:e.signal}),n=t.headers.get(`content-type`)||`(none)`;if(!t.ok)return{data:null,status:t.status,error:`http ${t.status} content-type=${n}`};let r=await t.text(),i=null;try{i=JSON.parse(r)}catch{let e=r.replace(/\s+/g,` `).slice(0,120);return{data:null,status:t.status,error:`invalid json content-type=${n} body=${e||`(empty)`}`}}return!i||typeof i!=`object`||Array.isArray(i)?{data:null,status:t.status,error:`invalid json-shape content-type=${n}`}:{data:i,status:t.status,error:null}}catch(e){return{data:null,status:null,error:e instanceof Error?e.message:String(e)}}finally{clearTimeout(t)}})()||{data:null,status:null,error:null},d=(e,t=!0)=>{if(!c)return null;let r=new URL(e.replace(/^\/+/,``),c);return t&&n&&r.searchParams.set(`directory`,n),r.toString()},f=c?await Promise.all([{label:`health`,path:`/health`,includeDirectory:!1},{label:`config`,path:`/config`,includeDirectory:!0},{label:`providers`,path:`/config/providers`,includeDirectory:!0},{label:`agents`,path:`/agent`,includeDirectory:!0,timeoutMs:12e3},{label:`commands`,path:`/command`,includeDirectory:!0,timeoutMs:1e4},{label:`project`,path:`/project/current`,includeDirectory:!0},{label:`path`,path:`/path`,includeDirectory:!0},{label:`sessions`,path:`/session`,includeDirectory:!0,timeoutMs:12e3},{label:`sessionStatus`,path:`/session/status`,includeDirectory:!0}].map(async e=>{let t=d(e.path,e.includeDirectory!==!1);if(!t)return{label:e.label,url:`(none)`,result:null};let n=await qi(t,typeof e.timeoutMs==`number`?e.timeoutMs:void 0);return{label:e.label,url:t,result:n}})):[],m=[];m.push(`Time: ${e.toISOString()}`),m.push(`OpenChamber version: 1.18.2-beta.23`),m.push(`Runtime: ${a||`(unknown)`} (api=${c||`(unknown)`})`),m.push(`OpenCode SDK base: ${ce.getBaseUrl()}`),m.push(`Event stream: ${i}`),m.push(`Directory: ${n||`(none)`}`),m.push(`Platform: ${t}`);let h=Yi(l?.openCodePort);if(m.push(`OpenCode runtime port: ${h??`(unknown)`}`),typeof l?.openCodeRunning==`boolean`&&m.push(`OpenCode runtime running: ${l.openCodeRunning?`yes`:`no`}`),typeof l?.openCodeSecureConnection==`boolean`&&m.push(`Secure OpenCode connection: ${l.openCodeSecureConnection?`true`:`false`}`),typeof l?.openCodeAuthSource==`string`&&l.openCodeAuthSource.trim()&&m.push(`OpenCode auth source: ${l.openCodeAuthSource}`),typeof window<`u`){let e=window.__OPENCHAMBER_MACOS_MAJOR__;typeof e==`number`&&Number.isFinite(e)&&e>0&&m.push(`macOS major: ${e}`)}if(/Mac OS X|Macintosh/.test(t)){m.push(``),m.push(`OpenCode CLI resolution:`);let e=Xi(l?.lastOpenCodeLaunchDiagnostics)?l.lastOpenCodeLaunchDiagnostics:null,t=e&&Array.isArray(e.args)?e.args.filter(e=>typeof e==`string`):[],n=u.data,r=n&&typeof n.configured==`string`?n.configured:null,i=n&&typeof n.resolved==`string`?n.resolved:l&&typeof l.opencodeBinaryResolved==`string`?l.opencodeBinaryResolved:``,a=n&&typeof n.resolvedDir==`string`?n.resolvedDir:``,o=n&&typeof n.source==`string`?n.source:l&&typeof l.opencodeBinarySource==`string`?l.opencodeBinarySource:``,s=n&&typeof n.launchBinary==`string`?n.launchBinary:l&&typeof l.opencodeLaunchBinary==`string`?l.opencodeLaunchBinary:``,c=n&&typeof n.launchWrapperType==`string`?n.launchWrapperType:l&&typeof l.opencodeLaunchWrapperType==`string`?l.opencodeLaunchWrapperType:``,d=n&&Array.isArray(n.launchArgs)?n.launchArgs.filter(e=>typeof e==`string`):l&&Array.isArray(l.opencodeLaunchArgs)?l.opencodeLaunchArgs.filter(e=>typeof e==`string`):[],f=n&&typeof n.node==`string`?n.node:l&&typeof l.nodeBinaryResolved==`string`?l.nodeBinaryResolved:``,p=n&&typeof n.bun==`string`?n.bun:l&&typeof l.bunBinaryResolved==`string`?l.bunBinaryResolved:``,h=n&&typeof n.detectedNow==`string`?n.detectedNow:``,g=n&&typeof n.detectedSourceNow==`string`?n.detectedSourceNow:``;if(r!==null&&m.push(`- configured: ${r.trim().length===0?`(cleared)`:r}`),i){let e=a||(i.includes(`/`)?i.split(`/`).slice(0,-1).join(`/`)||`/`:``);m.push(`- opencode: ${i}${e?` (dir=${e})`:``}`)}else m.push(`- opencode: (n/a)`);m.push(`- source: ${o||`(n/a)`}`),h&&(m.push(`- detected-now: ${h}`),m.push(`- detected-source: ${g||`(n/a)`}`)),e?(m.push(`- launched-at: ${Zi(e.launchedAt)}`),m.push(`- launch: ${Zi(e.binary)} ${t.join(` `)}`.trim()),m.push(`- cwd: ${Zi(e.cwd)}`),m.push(`- wrapper: ${Zi(e.wrapperType)}`),m.push(`- runtime: ${Qi(Zi(e.wrapperType,``),f,p)}`),m.push(`- PATH entries: ${Zi(e.pathEntryCount,`(unknown)`)}`),m.push(`- shell env: ${Zi(e.hasShellEnv,`(unknown)`)} (${Zi(e.shellEnvKeysCount,`?`)} keys)`)):(m.push(`- launch-binary: ${s||`(n/a)`}`),m.push(`- launch-wrapper: ${c||`(n/a)`}`),m.push(`- launch-args: ${d.length?d.join(` `):`(none)`}`),m.push(`- runtime: ${Qi(c||``,f,p)}`)),!n&&u.error&&m.push(`- resolution-endpoint: ${u.error}`)}if(m.push(``),f.length){m.push(`OpenCode API probes:`);for(let e of f){if(!e.result){m.push(`- ${e.label}: (no url)`);continue}let{ok:t,status:n,elapsedMs:r,summary:i}=e.result,a=t?``:` url=${e.url}`;m.push(`- ${e.label}: ${t?`ok`:`fail`} status=${n} time=${r}ms ${i}${a}`)}}else m.push(`OpenCode API probes: (skipped)`);return m.push(``),m.push(`Generated: ${Ji(Date.now())}`),m.join(`
5
5
  `)},ea=async()=>{let e=await $i(),t=p.getState();t.setOpenCodeStatusText(e),t.setOpenCodeStatusDialogOpen(!0)},ta=(e,t)=>e===t?!0:!e||!t?!1:e.scope===t.scope&&e.sessionId===t.sessionId&&e.projectId===t.projectId,na=e=>e?`${e.scope}:${e.projectId??``}:${e.sessionId}`:null,ra=e=>({scope:`project`,sessionId:e,projectId:null}),ia=ae()(e=>({focus:null,setFocus:t=>e(e=>ta(e.focus,t)?e:{focus:t})})),aa=null,oa=0,sa=(e,t)=>{let n=new Set,r=[];for(let i of t){if(!i.sessionId)continue;let t=e===`pinned`?i.sessionId:`${i.projectId??``}:${i.sessionId}`;n.has(t)||(n.add(t),r.push(i.scope===e?i:{...i,scope:e}))}return r},ca=e=>{let t=++oa;return aa={pinned:sa(`pinned`,e.pinned),project:sa(`project`,e.project)},()=>{oa===t&&(aa=null)}},la=()=>aa,ua=e=>!!e.parentID,da=(e,t)=>{if(!e)return null;let n=new Map(t.map(e=>[e.id,e])),r=n.get(e);if(!r)return e;for(;r&&ua(r);){let e=r.parentID;if(!e)break;let t=n.get(e);if(!t)return e;r=t}return r?.id??e},fa=()=>{let e=Ke.getState().activeSessions;if(e.length>0)return e;let t=je();return t.length>0?t:Ze()},pa=(e,t,n)=>{if(!t)return-1;if(n?.projectId){let r=e.findIndex(e=>e.sessionId===t&&e.projectId===n.projectId);if(r>=0)return r}return e.findIndex(e=>e.sessionId===t)},ma=(e,t,n,r)=>{if(e.length===0)return null;let i=pa(e,n,r);return i<0?t>0?e[0]??null:e[e.length-1]??null:e[(i+t+e.length)%e.length]??null},ha=(e,t,n=ia.getState().focus)=>{let r=da(t,fa()),i=n?.sessionId===t?n:null,a=i?.scope??`project`,o=la();return o?ma(a===`pinned`?o.pinned:o.project,e,r,i)||(a===`pinned`?ma(o.project,e,r,i):null):null},ga=(e,t,n=e=>{q.getState().setCurrentSession(e.sessionId,e.directory)})=>{let r=ha(e,t);return r?(ia.getState().setFocus({scope:r.scope,sessionId:r.sessionId,projectId:r.projectId}),n(r),r):null},_a=.5,va=.1,ya=`oc.webviewZoomFactor`,ba=e=>Number.isFinite(e)?Math.min(3,Math.max(_a,Math.round(e*100)/100)):1,xa=()=>{if(typeof window>`u`)return 1;try{let e=window.localStorage.getItem(ya);return e?ba(Number.parseFloat(e)):1}catch{return 1}},Sa=e=>{if(!(typeof window>`u`))try{window.localStorage.setItem(ya,String(e))}catch{}},Ca=e=>{let t=ba(e);return typeof document<`u`&&(document.documentElement.style.zoom=t===1?``:String(t)),Sa(t),t},wa=()=>{if(typeof document>`u`)return 1;let e=document.documentElement.style.zoom;if(!e)return xa();let t=Number.parseFloat(e);return Number.isFinite(t)&&t>0?ba(t):xa()},Ta=()=>{if(v())return;let e=xa();e!==1&&Ca(e)},Ea=async()=>{if(v())try{let e=await k(`desktop_zoom_in`);if(typeof e==`number`&&Number.isFinite(e))return ba(e)}catch(e){console.warn(`[webview-zoom] desktop_zoom_in failed, using CSS zoom`,e)}return Ca(wa()+va)},Da=async()=>{if(v())try{let e=await k(`desktop_zoom_out`);if(typeof e==`number`&&Number.isFinite(e))return ba(e)}catch(e){console.warn(`[webview-zoom] desktop_zoom_out failed, using CSS zoom`,e)}return Ca(wa()-va)},Oa=async()=>{if(v())try{let e=await k(`desktop_zoom_reset`);if(typeof e==`number`&&Number.isFinite(e))return ba(e)}catch(e){console.warn(`[webview-zoom] desktop_zoom_reset failed, using CSS zoom`,e)}return Ca(1)},ka=9,Aa=null,ja=0,Ma=({pinnedTargets:e,projectTargets:t})=>[...e,...t].slice(0,ka),Na=(e,t)=>{let n=e.findIndex(e=>e.scope===t.scope&&e.sessionId===t.sessionId&&(e.projectId??null)===(t.projectId??null));return n>=0?n+1:null},Pa=e=>{let t=++ja;return Aa={targets:e.targets.slice(0,ka),activate:e.activate},()=>{ja===t&&(Aa=null)}},Fa=e=>{if(!Number.isInteger(e)||e<1||e>ka)return!1;let t=Aa,n=t?.targets[e-1];return!t||!n?!1:(t.activate(n),!0)},Ia=e=>{let t=e.trim();if(!t)return null;let n=cn.getState(),r=n.createTab(t);return!r||r===`tab-invalid`?null:(n.setActiveTab(t,r),r)},La=e=>{let t=e.trim();if(!t)return null;let n=p.getState();return!n.isBottomTerminalOpen&&n.activeMainTab!==`terminal`&&n.setBottomTerminalOpen(!0),Ia(t)},Ra=(e,t)=>{let n=e.trim();if(!n)return!1;let r=cn.getState(),i=r.getDirectoryState(n);if(!i||i.tabs.length<2)return!1;let a=i.tabs.findIndex(e=>e.id===i.activeTabId),o=((a>=0?a:0)+t+i.tabs.length)%i.tabs.length,s=i.tabs[o]?.id;return!s||s===i.activeTabId?!1:(r.setActiveTab(n,s),!0)},za=e=>{let t=e.trim();if(!t)return{closed:!1,wasLastTab:!1};let n=cn.getState(),r=n.getDirectoryState(t),i=r?.activeTabId??null;if(!r||!i)return{closed:!1,wasLastTab:!1};let a=r.tabs.length===1;return n.closeTab(t,i),{closed:!0,wasLastTab:a}},Ba=()=>typeof window>`u`||window.parent===window||!rn(window.location.search)?!1:(window.parent.postMessage({type:Xt},window.location.origin),!0),Va=()=>{let{isMobile:e,closeActiveContextPanelTab:t}=p.getState();if(e)return!1;let n=sn();return n&&t(n)?!0:v()?(k(`desktop_close_current_window`).catch(e=>{console.warn(`[keyboard-shortcuts] failed to close current window`,e)}),!0):!1},Ha=({sessionId:e,surfaceKind:t,wiringCanAbort:n,primaryCanAbort:r})=>e?n?!0:t===`primary`&&r:!1,Ua=async({sessionId:e,currentProviderId:t,currentModelId:n,waitForConnectionOrThrow:r,getAuthoritativeDirectoryForSession:i,summarizeSession:a,onCompactFailed:o})=>{try{await r();let s=i(e);if(!s){o();return}await a(e,t,n,s)}catch(e){o(e)}},Wa=()=>{let e=(0,Z.c)(70),{t}=ve(),n=q(Ga),r=q(Ka),i=q(qa),a=q(Ja),o=Ee,s=p(Ya),c=p(Xa),l=p(Za),u=p(Qa),d=p($a),f=p(eo),m=p(to),h=p(no),g=p(ro),y=p(io),b=p(ao),x=p(oo),S=p(so),C=p(co),w=p(lo),T=p(uo),E=p(fo),D=p(po),O=p(mo),ee=ue(ho),A=We(go),{themeMode:j,setThemeMode:M}=Ft(),{working:N}=nn(),P=X.useRef(null),F=X.useRef(null),I=X.useRef(null),L=X.useRef(!1),te=X.useRef(j),R,ne;e[0]===j?(R=e[1],ne=e[2]):(R=()=>{te.current=j},ne=[j],e[0]=j,e[1]=R,e[2]=ne),X.useEffect(R,ne);let z;e[3]===i?z=e[4]:(z=()=>{F.current&&=(clearTimeout(F.current),null),P.current=null,i()},e[3]=i,e[4]=z);let B=z,V;e[5]===Symbol.for(`react.memo_cache_sentinel`)?(V=()=>{I.current&&=(clearTimeout(I.current),null),Zt.getState().clear()},e[5]=V):V=e[5];let H=V,re;e[6]===Symbol.for(`react.memo_cache_sentinel`)?(re=()=>{I.current&&=(clearTimeout(I.current),null);let e=Zt.getState().arm(Yt);I.current=setTimeout(()=>{let{expiresAt:e}=Zt.getState();e&&Date.now()>=e&&Zt.getState().clear(),I.current=null},Math.max(0,e-Date.now()))},e[6]=re):re=e[6];let ie=re,U;e[7]!==A?.id||e[8]!==A?.path||e[9]!==r||e[10]!==ee||e[11]!==a||e[12]!==g||e[13]!==n||e[14]!==B||e[15]!==b||e[16]!==C||e[17]!==h||e[18]!==S||e[19]!==E||e[20]!==d||e[21]!==f||e[22]!==y||e[23]!==x||e[24]!==M||e[25]!==w||e[26]!==O||e[27]!==t||e[28]!==m||e[29]!==s||e[30]!==D||e[31]!==c||e[32]!==T||e[33]!==u||e[34]!==l||e[35]!==N?(U=()=>{let e=e=>zt(e,O),i=e=>Bt(e,O),j=_o,I=[`[data-slot="dropdown-menu-content"]`,`[data-slot="select-content"]`,`[role="combobox"]`,`[role="listbox"]`,`[role="menu"]`,`[role="menuitem"]`,`[role="option"]`,`[data-radix-popper-content-wrapper]`].join(`,`),R=e=>e instanceof Element&&!!e.closest(I),ne=yo,z=xo,V=So,re=async()=>{let e=Qt(),n=e?en(e):null;if(n&&e){try{await n.compact({providerID:e.selection.value.providerID,modelID:e.selection.value.modelID,agent:e.selection.value.agent,variant:e.selection.value.variant})}catch(e){let n=e;tt.error(n instanceof Error?n.message:t(`chat.chatInput.toast.compactFailed`))}return}let r=q.getState().currentSessionId;if(!r)return;let{currentProviderId:i,currentModelId:a}=K.getState();await Ua({sessionId:r,currentProviderId:i,currentModelId:a,waitForConnectionOrThrow:Ue,getAuthoritativeDirectoryForSession:q.getState().getAuthoritativeDirectoryForSession,summarizeSession:Co,onCompactFailed:e=>{tt.error(e instanceof Error?e.message:t(`chat.chatInput.toast.compactFailed`))}})},U=t=>{let r=Zt.getState().pending;if(t.repeat||t.isComposing&&!r||t.defaultPrevented&&!r||j(t.target)&&!r)return;let i=e(`leader_key`);if(r){let e=()=>{L.current=!0,window.setTimeout(()=>{L.current=!1},0)};if(i&&Y(t,i)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),ie();return}let r=t.key.toLowerCase();if(r===`escape`){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),H();return}if(t.key===`Control`||t.key===`Shift`||t.key===`Alt`||t.key===`Meta`)return;if(t.metaKey||t.ctrlKey||t.altKey){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),e(),H();return}let{activeMainTab:a,isModelSelectorOpen:o,isAgentSelectorOpen:s}=p.getState(),c=an(a)&&!V();if(r===`m`&&c){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),e(),H(),window.requestAnimationFrame(()=>{S(!o,{instant:!0})});return}if(r===`a`&&c){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),e(),H(),C(!s,{instant:!0});return}if(r===`n`&&c){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),e(),H();let r=Qt(),i=r?en(r):null;i?i.shortcut(`new`):(b(`chat`),y(!1),n());return}if(r===`c`&&c){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),e(),H(),re(),z();return}t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),e(),H(),z();return}if(!i||!Y(t,i)||V())return;let{activeMainTab:a}=p.getState();an(a)&&(t.preventDefault(),t.stopPropagation(),ie())},ae=()=>Zt.getState().pending||L.current,oe=e=>{ae()&&e.preventDefault()},W=e=>{ae()&&(e.preventDefault(),e.stopPropagation())},se=t=>{if(j(t.target)){if(!_()&&Y(t,e(`new_terminal_tab`))){let e=sn();if(!e||!Ia(e))return;t.preventDefault(),t.stopPropagation();return}if(!_()&&Y(t,e(`previous_terminal_tab`))){let e=sn();if(!e||!Ra(e,-1))return;t.preventDefault(),t.stopPropagation();return}if(!_()&&Y(t,e(`next_terminal_tab`))){let e=sn();if(!e||!Ra(e,1))return;t.preventDefault(),t.stopPropagation();return}if(Y(t,e(`close_context_panel_tab`))){let e=sn();if(!e)return;let{closed:n,wasLastTab:r}=za(e);if(!n)return;if(t.preventDefault(),t.stopPropagation(),r){let e=p.getState();e.setBottomTerminalOpen(!1),e.activeMainTab===`terminal`&&e.setActiveMainTab(`chat`)}return}if(Y(t,e(`toggle_terminal`))){let{isMobile:e}=p.getState();if(e)return;t.preventDefault(),t.stopPropagation(),m();return}if(Y(t,e(`toggle_bottom_panel`))){let{isMobile:e}=p.getState();if(e)return;t.preventDefault(),t.stopPropagation(),m();return}if(Y(t,e(`toggle_terminal_expanded`))){let{isMobile:e,isBottomTerminalExpanded:n}=p.getState();if(e)return;t.preventDefault(),t.stopPropagation(),h(!n);return}}},G=wo,ce=t=>{if(t.defaultPrevented)return;if(Y(t,e(`close_context_panel_tab`))){(Ba()||Va())&&(t.preventDefault(),t.stopPropagation());return}if(j(t.target))return;let C=To;if(C(t.target)&&t.ctrlKey&&!t.metaKey&&!t.shiftKey&&!t.altKey&&t.key.toLowerCase()===`t`){t.preventDefault(),G();return}if(Y(t,e(`open_command_palette`))){t.preventDefault(),s();return}if(Y(t,e(`open_timeline_dialog`))){t.preventDefault(),w(!0);return}if(Y(t,e(`toggle_prompt_navigator`))){let{activeMainTab:e,promptNavigatorEnabled:n,isSettingsDialogOpen:r,isCommandPaletteOpen:i,isHelpDialogOpen:a,isSessionSwitcherOpen:o,isAboutDialogOpen:s,isTimelineDialogOpen:c,isMultiRunLauncherOpen:l,isImagePreviewOpen:u}=p.getState();if(!n||g||_()||e!==`chat`||r||i||a||o||s||c||l||u)return;t.preventDefault(),T();return}if(Y(t,e(`open_status`))){t.preventDefault(),ea();return}if(Y(t,e(`open_help`))){t.preventDefault(),c();return}if(v()&&Y(t,e(`new_mini_chat`))){t.preventDefault(),k(`desktop_open_draft_mini_chat_window`,{directory:ee||A?.path||``,projectId:A?.id??null}).catch(Eo);return}let O=Y(t,e(`new_chat`)),I=Y(t,e(`new_chat_worktree`));if(O||I){if(t.preventDefault(),b(`chat`),y(!1),!_()&&I){Jt();return}n();return}if(Y(t,e(`cycle_theme`))){if(t.preventDefault(),yr()!==null&&window.parent&&window.parent!==window){window.parent.postMessage({type:`openchamber:cycle-theme-request`},window.location.origin);return}let e=[`light`,`dark`,`system`],n=document.activeElement,r=(e.indexOf(te.current)+1)%e.length;M(e[r]),requestAnimationFrame(()=>{typeof document>`u`||typeof window>`u`||(document.hasFocus()||window.focus(),n&&document.contains(n)&&n.focus({preventScroll:!0}))});return}if(Lt(t,`in`,e(`zoom_in`))){t.preventDefault(),Ea();return}if(Lt(t,`out`,e(`zoom_out`))){t.preventDefault(),Da();return}if(Y(t,e(`zoom_reset`))){t.preventDefault(),Oa();return}if(Y(t,e(`open_settings`))){t.preventDefault();let{isSettingsDialogOpen:e}=p.getState();x(!e);return}if(Y(t,e(`toggle_sidebar`))){t.preventDefault();let{isMobile:e,isSessionSwitcherOpen:n}=p.getState();e?y(!n):l();return}if(Y(t,e(`focus_input`))){t.preventDefault(),document.querySelector(`textarea[data-chat-input="true"]`)?.focus();return}let L=e(`cycle_agent`),z=L&&!L.includes(`shift`)?Vt(`shift+${L}`):``,V=z&&Y(t,z)?-1:+!!Y(t,L);if(V!==0){let{isSettingsDialogOpen:e,isCommandPaletteOpen:n,isHelpDialogOpen:r,isSessionSwitcherOpen:i,isAboutDialogOpen:a,activeMainTab:o}=p.getState();if(e||n||r||i||a||!an(o)||!C(t.target))return;let s=Qt(),c=s?en(s):null;if(c){t.preventDefault(),c.shortcut(`cycle`,V);return}let l=K.getState(),u=Ne(l.getVisibleAgents(),l.currentAgentName,V);if(!u)return;t.preventDefault(),l.setAgent(u),p.getState().addRecentAgent(u);let d=q.getState().currentSessionId;d&&Te.getState().saveSessionAgentSelection(d,u);return}if(i(`toggle_right_sidebar`).some(e=>Y(t,e))){let{isMobile:e}=p.getState();if(e)return;t.preventDefault(),u();return}if(Y(t,e(`open_right_sidebar_git`))){let{isMobile:e}=p.getState();if(e)return;t.preventDefault(),d(!0),f(`git`);return}if(Y(t,e(`open_right_sidebar_files`))){let{isMobile:e}=p.getState();if(e)return;t.preventDefault(),d(!0),f(`files`);return}if(Y(t,e(`cycle_right_sidebar_tab`))){let{isMobile:e,rightSidebarTab:n}=p.getState();if(e)return;let r=[`git`,`files`,`context`],i=r[(r.indexOf(n)+1)%r.length];t.preventDefault(),d(!0),f(i);return}let H=e=>ga(e,q.getState().currentSessionId,e=>{b(`chat`),y(!1),q.getState().setCurrentSession(e.sessionId,e.directory)});if(i(`previous_session`).some(e=>Y(t,e))){t.preventDefault(),H(-1);return}if(i(`next_session`).some(e=>Y(t,e))){t.preventDefault(),H(1);return}for(let n=1;n<=9;n+=1)if(Y(t,e(`switch_tab_${n}`))){Fa(n)&&t.preventDefault();return}if(Y(t,e(`toggle_terminal`))){let{isMobile:e}=p.getState();if(e)return;t.preventDefault(),m();return}if(Y(t,e(`open_new_terminal`))){let{isMobile:e}=p.getState();if(e||_())return;let n=sn();if(!n||!La(n))return;t.preventDefault();return}if(Y(t,e(`toggle_bottom_panel`))){let{isMobile:e}=p.getState();if(e)return;t.preventDefault(),m();return}if(Y(t,e(`toggle_terminal_expanded`))){let{isMobile:e,isBottomTerminalExpanded:n}=p.getState();if(e)return;t.preventDefault(),h(!n);return}if(Y(t,e(`open_model_selector`))){let{isSettingsDialogOpen:e,isCommandPaletteOpen:n,isHelpDialogOpen:r,isSessionSwitcherOpen:i,isAboutDialogOpen:a,activeMainTab:o,isModelSelectorOpen:s}=p.getState();if(e)return;let c=n||r||i||a,l=an(o);if(c||!l)return;t.preventDefault(),S(!s,{instant:!0});return}if(Y(t,e(`cycle_thinking_variant`))){G()&&t.preventDefault();return}if(Y(t,e(`cycle_favorite_model_forward`))||Y(t,e(`cycle_favorite_model_backward`))){let{isSettingsDialogOpen:n,isCommandPaletteOpen:r,isHelpDialogOpen:i,isSessionSwitcherOpen:a,isAboutDialogOpen:o,activeMainTab:s,favoriteModels:c,addRecentModel:l}=p.getState();if(n)return;let u=r||i||a||o,d=an(s);if(u||!d||c.length===0)return;t.preventDefault();let f=c.length,m=Y(t,e(`cycle_favorite_model_forward`))?1:-1,h=Qt();if(h?.selection.change){let e=h.selection.value.providerID,t=h.selection.value.modelID,n=c[(c.findIndex(n=>n.providerID===e&&n.modelID===t)+m+f)%f];h.selection.change({...h.selection.value,providerID:n.providerID,modelID:n.modelID,variant:void 0}),l(n.providerID,n.modelID);return}let{currentProviderId:g,currentModelId:_,setProvider:v,setModel:y}=K.getState(),b=c[(c.findIndex(e=>e.providerID===g&&e.modelID===_)+m+f)%f];v(b.providerID),y(b.modelID),l(b.providerID,b.modelID);return}if(Y(t,e(`expand_input`))){if(g)return;t.preventDefault(),D();return}if(Y(t,e(`toggle_dictation`))){let{activeMainTab:e,isCommandPaletteOpen:n,isHelpDialogOpen:r,isSessionSwitcherOpen:i,isSettingsDialogOpen:a}=p.getState();if(!an(e)||n||r||i||a)return;t.preventDefault(),window.dispatchEvent(new CustomEvent(`openchamber:dictation-toggle`));return}if(t.key===`Escape`){let e=t.target,n=!!e?.closest(`[role="dialog"]`),i=!!document.querySelector(`[data-settings-view="true"]`),s=!!(e?.closest(`.terminal-viewport-container`)||e?.getAttribute(`data-terminal-hidden-input`)===`true`),c=R(e)||ne(),{isSettingsDialogOpen:l,isCommandPaletteOpen:u,isHelpDialogOpen:d,isSessionSwitcherOpen:f,isAboutDialogOpen:m,isMultiRunLauncherOpen:h,isImagePreviewOpen:g,activeMainTab:_,isPromptNavigatorPanelOpen:v}=p.getState();if(n||s||c){B();return}if(v){t.preventDefault(),E(!1),B();return}if(l){t.preventDefault(),x(!1),B();return}if(i){B();return}let y=u||d||f||m||h||g,b=an(_);if(y||!b){B();return}let S=Qt(),C=S?en(S):null,w=S?.sessionID??a;if(!Ha({sessionId:w,surfaceKind:S?.kind,wiringCanAbort:C?.canAbort,primaryCanAbort:N.canAbort})){B();return}let T=Date.now(),D=P.current;if(D&&T<D){t.preventDefault(),B(),C?C.abort():(w&&ke(w),o(w??``));return}t.preventDefault();let O=S?.kind===`secondary`?T+3e3:r(3e3)??T+3e3;P.current=O,F.current&&clearTimeout(F.current);let ee=Math.max(O-T,0);F.current=setTimeout(()=>{P.current&&Date.now()>=P.current&&B()},ee||0);return}};return window.addEventListener(`keydown`,U,!0),window.addEventListener(`beforeinput`,oe,!0),window.addEventListener(`compositionstart`,W,!0),window.addEventListener(`compositionupdate`,W,!0),window.addEventListener(`compositionend`,W,!0),window.addEventListener(`keydown`,se,!0),window.addEventListener(`keydown`,ce),()=>{window.removeEventListener(`keydown`,U,!0),window.removeEventListener(`beforeinput`,oe,!0),window.removeEventListener(`compositionstart`,W,!0),window.removeEventListener(`compositionupdate`,W,!0),window.removeEventListener(`compositionend`,W,!0),window.removeEventListener(`keydown`,se,!0),window.removeEventListener(`keydown`,ce)}},e[7]=A?.id,e[8]=A?.path,e[9]=r,e[10]=ee,e[11]=a,e[12]=g,e[13]=n,e[14]=B,e[15]=b,e[16]=C,e[17]=h,e[18]=S,e[19]=E,e[20]=d,e[21]=f,e[22]=y,e[23]=x,e[24]=M,e[25]=w,e[26]=O,e[27]=t,e[28]=m,e[29]=s,e[30]=D,e[31]=c,e[32]=T,e[33]=u,e[34]=l,e[35]=N,e[36]=U):U=e[36];let ae=A?.id,oe=A?.path,W;e[37]!==r||e[38]!==ee||e[39]!==a||e[40]!==g||e[41]!==n||e[42]!==B||e[43]!==b||e[44]!==C||e[45]!==h||e[46]!==S||e[47]!==E||e[48]!==d||e[49]!==f||e[50]!==y||e[51]!==x||e[52]!==M||e[53]!==w||e[54]!==O||e[55]!==t||e[56]!==ae||e[57]!==oe||e[58]!==m||e[59]!==s||e[60]!==D||e[61]!==c||e[62]!==T||e[63]!==u||e[64]!==l||e[65]!==N?(W=[n,o,s,c,l,u,d,f,m,h,g,y,b,x,S,C,w,T,E,D,M,N,r,B,ie,H,a,ee,ae,oe,O,t],e[37]=r,e[38]=ee,e[39]=a,e[40]=g,e[41]=n,e[42]=B,e[43]=b,e[44]=C,e[45]=h,e[46]=S,e[47]=E,e[48]=d,e[49]=f,e[50]=y,e[51]=x,e[52]=M,e[53]=w,e[54]=O,e[55]=t,e[56]=ae,e[57]=oe,e[58]=m,e[59]=s,e[60]=D,e[61]=c,e[62]=T,e[63]=u,e[64]=l,e[65]=N,e[66]=W):W=e[66],X.useEffect(U,W);let se,G;e[67]===B?(se=e[68],G=e[69]):(G=()=>()=>{B(),H()},se=[B,H],e[67]=B,e[68]=se,e[69]=G),X.useEffect(G,se)};function Ga(e){return e.openNewSessionDraft}function Ka(e){return e.armAbortPrompt}function qa(e){return e.clearAbortPrompt}function Ja(e){return e.currentSessionId}function Ya(e){return e.toggleCommandPalette}function Xa(e){return e.toggleHelpDialog}function Za(e){return e.toggleSidebar}function Qa(e){return e.toggleRightSidebar}function $a(e){return e.setRightSidebarOpen}function eo(e){return e.setRightSidebarTab}function to(e){return e.toggleBottomTerminal}function no(e){return e.setBottomTerminalExpanded}function ro(e){return e.isMobile}function io(e){return e.setSessionSwitcherOpen}function ao(e){return e.setActiveMainTab}function oo(e){return e.setSettingsDialogOpen}function so(e){return e.setModelSelectorOpen}function co(e){return e.setAgentSelectorOpen}function lo(e){return e.setTimelineDialogOpen}function uo(e){return e.togglePromptNavigatorPanel}function fo(e){return e.setPromptNavigatorPanelOpen}function po(e){return e.toggleExpandedInput}function mo(e){return e.shortcutOverrides}function ho(e){return e.currentDirectory}function go(e){return e.getActiveProject()}function _o(e){return e instanceof Element&&!!(e.closest(`[data-terminal-view="true"]`)||e.closest(`.terminal-viewport-container`)||e.getAttribute(`data-terminal-hidden-input`)===`true`)}function vo(e){return e.getClientRects().length>0}function yo(){let e=document.querySelectorAll(`[data-slot="dropdown-menu-content"], [data-slot="select-content"], [role="listbox"], [role="menu"], [data-radix-popper-content-wrapper]`);return Array.from(e).some(vo)}function bo(){document.querySelector(`textarea[data-chat-input="true"]`)?.focus({preventScroll:!0})}function xo(){window.requestAnimationFrame(bo)}function So(){let{isSettingsDialogOpen:e,isCommandPaletteOpen:t,isHelpDialogOpen:n,isSessionSwitcherOpen:r,isAboutDialogOpen:i}=p.getState();return e||t||n||r||i}function Co(e,t,n,r){return ce.summarizeSession(e,t,n,r)}function wo(){let{isSettingsDialogOpen:e,isCommandPaletteOpen:t,isHelpDialogOpen:n,isSessionSwitcherOpen:r,isAboutDialogOpen:i,activeMainTab:a}=p.getState();if(e||t||n||r||i||!an(a))return!1;let o=Qt();if(o?.selection.change){let e=o.selection.catalog?.variants??[];if(e.length===0)return!1;let t=o.selection.value.variant,n=e[((t?e.indexOf(t):-1)+1)%e.length];return o.selection.change({...o.selection.value,variant:n}),!0}let s=K.getState();if(s.getCurrentModelVariants().length===0)return!1;s.cycleCurrentVariant();let c=K.getState().currentVariant,l=q.getState().currentSessionId,u=K.getState().currentAgentName,d=K.getState().currentProviderId,f=K.getState().currentModelId;return l&&u&&d&&f&&Te.getState().saveAgentModelVariantForSession(l,u,d,f,c),u&&d&&f&&K.getState().saveAgentModelSelection(u,d,f,c),!0}function To(e){return e instanceof HTMLTextAreaElement&&e.getAttribute(`data-chat-input`)===`true`}function Eo(e){console.warn(`[keyboard-shortcuts] failed to open draft mini chat window`,e)}var Do=3,Oo=(e,t)=>{if(typeof e!=`string`)return t;let n=e.trim().replace(/\s+/g,` `);return n?n.slice(0,48):t},ko=(e,t)=>{let n=t?[...e.filter(e=>e.id===t),...e.filter(e=>e.id!==t)]:e,r=[],i=new Set;for(let e of n){let t=typeof e.id==`string`?e.id.trim():``;if(!(!t||i.has(t))&&(i.add(t),r.push({sessionId:t,title:Oo(e.title,`Session ${r.length+1}`)}),r.length>=Do))break}return r},Ao=()=>{let e=(0,Z.c)(9),t=et(),n=q(jo),r;e[0]!==n||e[1]!==t?(r=ko(t,n),e[0]=n,e[1]=t,e[2]=r):r=e[2];let i=r,a;e[3]===i?a=e[4]:(a=JSON.stringify(i),e[3]=i,e[4]=a);let o=a,s,c;e[5]!==i||e[6]!==o?(s=()=>{if(!(typeof window>`u`||!w())){try{i.length===0?localStorage.removeItem(Ot):localStorage.setItem(Ot,o)}catch{return}window.__OPENCHAMBER_UPDATE_PWA_MANIFEST__?.()}},c=[i,o],e[5]=i,e[6]=o,e[7]=s,e[8]=c):(s=e[7],c=e[8]),X.useEffect(s,c)};function jo(e){return e.currentSessionId}var Mo=e=>Number.isFinite(e)?`${Math.max(0,Math.round(e))}px`:`0px`,No=(e,t,n,r)=>{e.style.setProperty(`--oc-wco-left-inset`,Mo(t)),e.style.setProperty(`--oc-wco-right-inset`,Mo(n)),e.style.setProperty(`--oc-wco-titlebar-height`,Mo(r))},Po=()=>{let e=(0,Z.c)(1),t;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=[],e[0]=t):t=e[0],X.useEffect(Fo,t)};function Fo(){if(typeof window>`u`||!w())return;let e=document.documentElement,t=typeof window.matchMedia==`function`?window.matchMedia(`(display-mode: window-controls-overlay)`):null,n=window.navigator.windowControlsOverlay,r=()=>{if(!n||!t?.matches||!n.visible){No(e,0,0,0);return}let r=n.getTitlebarAreaRect(),i=Math.max(0,Number(r.x)||0),a=Math.max(0,Number(r.width)||0),o=Math.max(0,Number(r.height)||0),s=Math.max(0,window.innerWidth-(i+a));No(e,i,s,o)},i=()=>{r()};return r(),window.addEventListener(`resize`,r),window.addEventListener(`focus`,r),t&&(typeof t.addEventListener==`function`?t.addEventListener(`change`,i):typeof t.addListener==`function`&&t.addListener(i)),n&&typeof n.addEventListener==`function`&&n.addEventListener(`geometrychange`,r),()=>{window.removeEventListener(`resize`,r),window.removeEventListener(`focus`,r),t&&(typeof t.removeEventListener==`function`?t.removeEventListener(`change`,i):typeof t.removeListener==`function`&&t.removeListener(i)),n&&typeof n.removeEventListener==`function`&&n.removeEventListener(`geometrychange`,r),No(e,0,0,0)}}var Io=null,Lo=e=>{let t=Io;return Io=e,()=>{Io===e&&(Io=t)}},Ro=()=>({orderByProject:{},pendingProjectIDs:{}}),zo=(e,t)=>!!(e&&e.length===t.length&&e.every((e,n)=>e===t[n])),Bo=t(),Vo=ae()(oe((e,t)=>({runtimeIdentity:Bo,...Ro(),serverRevisionByProject:{},deferredServerOrderByProject:{},runtimeOrdersByIdentity:{[Bo]:Ro()},activateWorktreeOrderRuntime:t=>e(e=>{if(e.runtimeIdentity===t)return e;let n=e.runtimeOrdersByIdentity[t]??Ro();return{runtimeIdentity:t,orderByProject:n.orderByProject,pendingProjectIDs:n.pendingProjectIDs,serverRevisionByProject:{},deferredServerOrderByProject:{},runtimeOrdersByIdentity:e.runtimeOrdersByIdentity[t]?e.runtimeOrdersByIdentity:{...e.runtimeOrdersByIdentity,[t]:n}}}),setWorktreeOrder:(t,n,r)=>{let i=!1;e(e=>{let n=zo(e.orderByProject[t],r),a=e.pendingProjectIDs[t]?e.pendingProjectIDs:{...e.pendingProjectIDs,[t]:!0};if(i=!n||a!==e.pendingProjectIDs,!i)return e;let o=n?e.orderByProject:{...e.orderByProject,[t]:r},s={orderByProject:o,pendingProjectIDs:a};return{orderByProject:o,pendingProjectIDs:a,runtimeOrdersByIdentity:{...e.runtimeOrdersByIdentity,[e.runtimeIdentity]:s}}}),i&&Io?.(t,n,r)},markPendingWorktreeOrder:t=>e(e=>{if(e.pendingProjectIDs[t])return e;let n={...e.pendingProjectIDs,[t]:!0};return{pendingProjectIDs:n,runtimeOrdersByIdentity:{...e.runtimeOrdersByIdentity,[e.runtimeIdentity]:{orderByProject:e.orderByProject,pendingProjectIDs:n}}}}),applyServerWorktreeOrder:(t,n,r)=>e(e=>{let i=e.serverRevisionByProject[t];if(i!==void 0&&r<=i)return e;let a={...e.serverRevisionByProject,[t]:r};if(e.pendingProjectIDs[t])return{serverRevisionByProject:a,deferredServerOrderByProject:{...e.deferredServerOrderByProject,[t]:{orderedPaths:n,revision:r}}};if(zo(e.orderByProject[t],n))return{serverRevisionByProject:a};let o={...e.orderByProject,[t]:n};return{orderByProject:o,serverRevisionByProject:a,runtimeOrdersByIdentity:{...e.runtimeOrdersByIdentity,[e.runtimeIdentity]:{orderByProject:o,pendingProjectIDs:e.pendingProjectIDs}}}}),setServerRevision:(t,n)=>e(e=>{let r=e.serverRevisionByProject[t];return r!==void 0&&n<=r?e:{serverRevisionByProject:{...e.serverRevisionByProject,[t]:n}}}),resolvePendingWorktreeOrder:(t,n)=>e(e=>{let r=e.serverRevisionByProject[t],i=e.deferredServerOrderByProject[t],a=Math.max(r??0,n,i?.revision??0),o=r===a?e.serverRevisionByProject:{...e.serverRevisionByProject,[t]:a},s=i?(()=>{let n={...e.deferredServerOrderByProject};return delete n[t],n})():e.deferredServerOrderByProject;if(!e.pendingProjectIDs[t])return o===e.serverRevisionByProject&&s===e.deferredServerOrderByProject?e:{serverRevisionByProject:o,deferredServerOrderByProject:s};let c={...e.pendingProjectIDs};delete c[t];let l=i&&i.revision>n&&!zo(e.orderByProject[t],i.orderedPaths)?{...e.orderByProject,[t]:i.orderedPaths}:e.orderByProject;return{pendingProjectIDs:c,orderByProject:l,serverRevisionByProject:o,deferredServerOrderByProject:s,runtimeOrdersByIdentity:{...e.runtimeOrdersByIdentity,[e.runtimeIdentity]:{orderByProject:l,pendingProjectIDs:c}}}}),resetServerWorktreeOrders:()=>e(e=>Object.keys(e.serverRevisionByProject).length===0&&Object.keys(e.deferredServerOrderByProject).length===0?e:{serverRevisionByProject:{},deferredServerOrderByProject:{}}),hasPendingWorktreeOrder:e=>!!t().pendingProjectIDs[e]}),{name:`mobile-worktree-order`,version:2,partialize:e=>({runtimeOrdersByIdentity:e.runtimeOrdersByIdentity}),migrate:e=>{let t=e;return t.runtimeOrdersByIdentity?{runtimeOrdersByIdentity:t.runtimeOrdersByIdentity}:{runtimeOrdersByIdentity:{[Bo]:{orderByProject:t.orderByProject??{},pendingProjectIDs:t.pendingProjectIDs??{}}}}},merge:(e,t)=>{let n=e.runtimeOrdersByIdentity??t.runtimeOrdersByIdentity,r=n[t.runtimeIdentity]??Ro();return{...t,runtimeOrdersByIdentity:n,orderByProject:r.orderByProject,pendingProjectIDs:r.pendingProjectIDs}}})),Ho=e=>e.replace(/\\/g,`/`).replace(/\/+$/,``),Uo=(e,t)=>{if(!e||e.length===0)return t;let n=new Map(e.map((e,t)=>[Ho(e),t]));return t.map((e,t)=>({worktree:e,index:t})).sort((e,t)=>(n.get(Ho(e.worktree.path))??2**53-1)-(n.get(Ho(t.worktree.path))??2**53-1)||e.index-t.index).map(e=>e.worktree)},Wo=3e4,Go=e=>e.replace(/\\/g,`/`).replace(/\/+$/,``)||`/`,Ko=e=>e instanceof nt?e.status===501?`unsupported`:e.status>=400&&e.status<500&&e.status!==408&&e.status!==429&&e.code!==`revision_conflict`?`permanent`:`retry`:`retry`,qo=(e,t)=>new Promise((n,r)=>{let i=()=>{clearTimeout(a),t.removeEventListener(`abort`,i),r(new DOMException(`Aborted`,`AbortError`))},a=setTimeout(()=>{t.removeEventListener(`abort`,i),n()},e);t.aborted?i():t.addEventListener(`abort`,i,{once:!0})}),Jo=(e,t)=>e.then(e=>{if(t?.aborted)throw new DOMException(`Aborted`,`AbortError`);return e}),Yo={fetchSnapshot:e=>Jo(Ge(M),e),refreshSnapshot:e=>Jo(ze(M),e),fetchOrder:Ve,setOrder:rt,waitInvalidation:Pe,captureRuntime:()=>({transportIdentity:t(),generation:o()}),isCurrent:e=>e.transportIdentity===t()&&e.generation===o(),sleep:qo,createRequestID:()=>typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID():`worktree-order-${Date.now()}-${Math.random().toString(36).slice(2)}`},Xo=new Map,Zo=()=>{for(let e of Xo.values())e.controller.abort();Xo.clear()},Qo=(e,t,n,r=Yo)=>{Xo.get(e)?.controller.abort();let i={projectDirectory:Go(t),orderedPaths:[...n],capture:r.captureRuntime(),controller:new AbortController,backoffMs:500,running:!1};Xo.set(e,i),$o(e,r)},$o=async(e,t=Yo)=>{let n=Xo.get(e);if(!(!n||n.running)){n.running=!0;try{for(;;){let n=Xo.get(e);if(!n||!t.isCurrent(n.capture)||n.controller.signal.aborted)return;let r=Vo.getState().serverRevisionByProject[e]??0;n.expectedRevision!==r&&(n.expectedRevision=r,n.requestID=t.createRequestID());try{let i=await t.setOrder({requestID:n.requestID,projectDirectory:n.projectDirectory,expectedRevision:r,orderedPaths:n.orderedPaths,signal:n.controller.signal});if(!t.isCurrent(n.capture)||Xo.get(e)!==n)return;let a=i.worktreeOrder??{projectDirectory:n.projectDirectory,orderedPaths:n.orderedPaths,revision:i.revision};Vo.getState().setServerRevision(e,a.revision),Vo.getState().resolvePendingWorktreeOrder(e,a.revision),Xo.delete(e);return}catch(r){if(n.controller.signal.aborted||!t.isCurrent(n.capture)||Xo.get(e)!==n)return;if(r instanceof nt&&r.code===`revision_conflict`)try{let r=await t.fetchOrder(n.projectDirectory,n.controller.signal);if(Xo.get(e)!==n||!t.isCurrent(n.capture))return;Vo.getState().applyServerWorktreeOrder(e,r.orderedPaths,r.revision),n.expectedRevision=void 0,n.requestID=void 0,n.backoffMs=500;continue}catch(e){if(Ko(e)!==`retry`)return}else if(Ko(r)!==`retry`)return;if(await t.sleep(n.backoffMs,n.controller.signal).catch(()=>{}),n.backoffMs=Math.min(n.backoffMs*2,Wo),n.controller.signal.aborted)return}}}finally{Xo.get(e)===n&&(!t.isCurrent(n.capture)||n.controller.signal.aborted)&&Xo.delete(e),Xo.get(e)===n&&(n.running=!1)}}},es=(e,t,n,r)=>{let i=new Map(t.map(e=>[Go(e.path),e.id]));for(let t of e){let e=i.get(Go(t.projectDirectory));e&&r.isCurrent(n)&&Vo.getState().applyServerWorktreeOrder(e,t.orderedPaths,t.revision)}},ts=(e,t=Yo)=>{let n=null,r=()=>n?.abort();return{start:()=>{r(),n=new AbortController;let i=n.signal,a=t.captureRuntime();(async()=>{let n=0,r=500;for(;!i.aborted&&t.isCurrent(a);)try{let r=await t.fetchSnapshot(i);if(i.aborted||!t.isCurrent(a))return;n=r.revision;let o=e();es(r.worktreeOrders,o,a,t);let s=new Set(r.worktreeOrders.map(e=>Go(e.projectDirectory)));for(let e of o){let n=Vo.getState(),r=n.orderByProject[e.id];n.pendingProjectIDs[e.id]?Qo(e.id,e.path,r??[],t):r?.length&&!s.has(Go(e.path))&&(n.markPendingWorktreeOrder(e.id),Qo(e.id,e.path,r,t))}break}catch(e){if(Ko(e)!==`retry`)return;await t.sleep(r,i).catch(()=>{}),r=Math.min(r*2,Wo)}for(;!i.aborted&&t.isCurrent(a);)try{let o=await t.waitInvalidation(n,{signal:i});if(i.aborted||!t.isCurrent(a)||o===`aborted`)return;let s=await(t.refreshSnapshot??t.fetchSnapshot)(i);if(i.aborted||!t.isCurrent(a))return;n=s.revision,es(s.worktreeOrders,e(),a,t),r=500}catch(e){if(Ko(e)!==`retry`)return;await t.sleep(r,i).catch(()=>{}),r=Math.min(r*2,Wo)}})()},stop:r}},ns=()=>{let e=(0,Z.c)(2),t=We(is),n;e[0]===t?n=e[1]:(n=[t],e[0]=t,e[1]=n),X.useEffect(ss,n)};function rs(e){return[e.id,Go(e.path)]}function is(e){return JSON.stringify(e.projects.map(rs))}function as(e,t,n){return Qo(e,t,n)}function os(){return We.getState().projects}function ss(){let e=t();Vo.getState().activateWorktreeOrderRuntime(e);let n=Lo(as),r=ts(os);r.start();let i=l(e=>{u(e)&&(Zo(),Vo.getState().activateWorktreeOrderRuntime(t()),r.start())});return()=>{n(),i(),r.stop(),Zo()}}var cs=e=>e.replace(/\\/g,`/`).replace(/\/+$/,``)||`/`,ls=e=>{let t=!1,n=0,r=0,i=0,a=new Map,o=new Map,s=new Set,c=new Set,l=new Map,u=new Set,d=new Set,f=new Set,p=``,m=[],h=t=>{let n=cs(t);return e.getProjects().find(e=>cs(e.path)===n)},g=(n,i=150)=>{let s=cs(n.path),c=o.get(s);c&&e.clearTimer(c.timer);let l=r,u=e.setTimer(()=>{!t||l!==r||(o.delete(s),a.set(s,n),_(l))},i);o.set(s,{timer:u,epoch:l})},_=(n=r)=>{if(!(!t||n!==r))for(;i<2&&a.size>0;){let[n,o]=a.entries().next().value;a.delete(n),i+=1;let s=e.generation(),c=r;e.refresh(o,{isCurrent:()=>t&&c===r&&s===e.generation()}).then(i=>{if(!(!t||c!==r||s!==e.generation())){f.add(n);for(let e of i.addedDirectories)u.add(cs(e));if(e.needsSessionSync)for(let t of i.worktrees){let n=cs(t.path);e.needsSessionSync(n)&&u.add(n)}v(c,s),y()}}).then(()=>{t&&c===r&&s===e.generation()&&l.delete(n)}).catch(()=>{if(!t||c!==r||s!==e.generation())return;let i=(l.get(n)??0)+1;l.set(n,i),t&&c===r&&g(o,[1e3,2e3,5e3,15e3,3e4][Math.min(i-1,4)])}).finally(()=>{c===r&&(--i,_(c))})}},v=(n,i)=>{if(u.size===0)return;let a=[...u];u.clear(),e.syncAdded(a).catch(()=>{if(t&&n===r&&i===e.generation()){for(let e of a)u.add(e);let o=e.setTimer(()=>{s.delete(o),t&&n===r&&v(n,i)},1e3);s.add(o)}})},y=()=>{if(f.size!==e.getProjects().length)return;let t=e.getCatalog();for(let e of d){let n=e.slice(e.indexOf(`:`)+1);[...t.entries()].some(([e,t])=>cs(e)===n||t.some(e=>cs(e.path)===n))||c.add(e)}},b=()=>{f.clear();for(let t of e.getProjects())g(t,0)},x=()=>{let t=e.getCatalog(),r=e.getProjects(),i=new Set;for(let t of e.getActiveDirectories())t.trim()&&i.add(cs(t));for(let e of[...d]){let t=e.slice(e.indexOf(`:`)+1);i.has(t)||d.delete(e)}for(let e of[...c]){let t=e.slice(e.indexOf(`:`)+1);i.has(t)||c.delete(e)}for(let e of i)if(!r.find(n=>{let r=cs(n.path),i=t.get(r)?.some(t=>cs(t.path)===e);return e===r||i})){let t=`${n}:${e}`;!c.has(t)&&!d.has(t)&&(d.add(t),b())}},S=()=>{r+=1,c.clear(),d.clear(),l.clear(),u.clear(),f.clear();for(let t of o.values())e.clearTimer(t.timer);o.clear();for(let t of s)e.clearTimer(t);s.clear(),a.clear(),i=0};return{start:()=>{t||e.isVSCode()||(t=!0,m.push(e.subscribeEvents(e=>{if(e.type===`event-stream-ready`&&(n+=1,S(),b()),e.type===`worktree-topology-changed`&&e.projectDirectory){let t=h(e.projectDirectory);t&&g(t)}})),p=e.getProjects().map(e=>`${e.id}\u0000${cs(e.path)}`).sort().join(`
6
6
  `),m.push(e.subscribeProjects(()=>{let t=e.getProjects().map(e=>`${e.id}\u0000${cs(e.path)}`).sort().join(`
7
7
  `);t!==p&&(p=t,S(),b(),x())})),m.push(e.subscribeCatalog(x)),m.push(e.subscribeSessions(x)),m.push(e.subscribeRuntime(e=>{e&&(n+=1,S(),b())})),b(),x())},stop:()=>{t=!1,S();for(let{timer:t}of o.values())e.clearTimer(t);for(o.clear(),a.clear(),i=0;m.length;)m.pop()?.()},reconcileAll:b}},us=null,ds=0,fs=()=>(us||=ls({isVSCode:_,getProjects:()=>We.getState().projects,getCatalog:()=>q.getState().availableWorktreesByProject,getActiveDirectories:()=>{let e=Ke.getState(),t=[];for(let n of e.activeSessions)typeof n.directory==`string`&&t.push(n.directory);for(let n of e.cachedDirectories)t.push(n);return t},needsSessionSync:e=>!Ke.getState().loadedDirectories.has(cs(e)),refresh:ht,syncAdded:e=>Ye(e,Ke.getState().activeSessions),subscribeProjects:e=>We.subscribe(e),subscribeCatalog:e=>q.subscribe((t,n)=>{t.availableWorktreesByProject!==n.availableWorktreesByProject&&e()}),subscribeSessions:e=>Ke.subscribe((t,n)=>{(t.activeSessions!==n.activeSessions||t.cachedDirectories!==n.cachedDirectories)&&e()}),subscribeEvents:Je,subscribeRuntime:e=>l(t=>e(u(t))),generation:o,setTimer:(e,t)=>globalThis.setTimeout(e,t),clearTimer:e=>globalThis.clearTimeout(e)}),ds+=1,us.start(),()=>{ds=Math.max(0,ds-1),ds===0&&us?.stop()}),ps=`openchamber:mini-chat-presence`,ms=()=>{let e=tn(),t=X.useRef(e.optimistic.add),n=X.useRef(e.optimistic.remove),r=X.useRef(e.optimistic.confirm);return t.current=e.optimistic.add,n.current=e.optimistic.remove,r.current=e.optimistic.confirm,X.useEffect(()=>{Re(e=>t.current(e),e=>n.current(e),e=>r.current(e))},[]),X.useEffect(()=>fs(),[]),null},hs=()=>{let e=(0,Z.c)(1),t;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=[],e[0]=t):t=e[0],X.useEffect(xs,t),null};function gs(e){let t=(0,Z.c)(4),{embeddedBackgroundWorkEnabled:n}=e,r;t[0]===n?r=t[1]:(r={enabled:n,autoRun:!1},t[0]=n,t[1]=r),At(r);let i=X.useSyncExternalStore(Oe,Ie,Ie);Le(n&&i===`legacy-enabled`),Me();let a;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(a=[],t[2]=a):a=t[2],X.useEffect(_s,a);let o;return t[3]===Symbol.for(`react.memo_cache_sentinel`)?(o=(0,Q.jsx)(ms,{}),t[3]=o):o=t[3],o}function _s(){let e=Qe(),t=it();e.start(),t.start();let n=Xe(e);return()=>{n(),t.stop(),e.stop()}}function vs(e){let t=(0,Z.c)(6),{embeddedBackgroundWorkEnabled:n}=e;Ao(),Po(),Wa(),ns();let r;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=[],t[0]=r):r=t[0],X.useEffect(ys,r);let i;t[1]===n?i=t[2]:(i=(0,Q.jsx)(gs,{embeddedBackgroundWorkEnabled:n}),t[1]=n,t[2]=i);let a;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(a=(0,Q.jsx)(hs,{}),t[3]=a):a=t[3];let o;return t[4]===i?o=t[5]:(o=(0,Q.jsxs)(Q.Fragment,{children:[i,a]}),t[4]=i,t[5]=o),o}function ys(){Ta()}function bs(e){let t=e.data;if(t?.type!==`mini-chat-session-presence`||!t.sessionId||!t.directory)return;let n=t.viewed!==!1;De(t.directory,t.sessionId,n),n&&Fe(t.sessionId)}function xs(){if(typeof BroadcastChannel>`u`)return;let e=new BroadcastChannel(ps);return e.onmessage=bs,()=>e.close()}var Ss=new Set,Cs=new Map,ws=(e,t)=>`https://cdn.jsdelivr.net/npm/${encodeURIComponent(e.packageName).replace(`%40`,`@`).replace(`%2F`,`/`)}/files/${e.filePrefix}-latin-${t}-normal.woff2`,Ts=(e,t)=>{let n=`${e.family}:${t}`;if(Ss.has(n))return Promise.resolve();let r=Cs.get(n);if(r)return r;if(typeof document>`u`||typeof FontFace>`u`||!document.fonts)return Promise.resolve();let i=new FontFace(e.family,`url(${ws(e,t)}) format('woff2')`,{style:`normal`,weight:String(t),display:`swap`});document.fonts.add(i);let a=i.load().then(()=>{Ss.add(n)}).catch(n=>{document.fonts.delete(i),console.warn(`Failed to load font: ${e.family} ${t}`,n)}).finally(()=>{Cs.delete(n)});return Cs.set(n,a),a},Es=e=>e?Promise.all(e.weights.map(t=>Ts(e,t))).then(()=>void 0):Promise.resolve(),Ds=e=>Es(s[e]?.source),Os=e=>Es(f[e]?.source),ks={family:`Syne`,packageName:`@fontsource/syne`,filePrefix:`syne`,weights:[700]},As=()=>Es(ks);function js(){let e=(0,Z.c)(4),{uiFont:t,monoFont:n}=ln(),r,i;e[0]!==n||e[1]!==t?(r=()=>{if(typeof document>`u`)return;let e=document.documentElement,r=s[t]?.stack??s.system.stack,i=f[n]?.stack??f[`system-mono`].stack;Ds(t),Os(n),e.style.setProperty(`--font-sans`,r),e.style.setProperty(`--font-heading`,r),e.style.setProperty(`--font-family-sans`,r),e.style.setProperty(`--font-mono`,i),e.style.setProperty(`--font-family-mono`,i),e.style.setProperty(`--ui-regular-font-weight`,`400`),document.body&&(document.body.style.fontFamily=r)},i=[t,n],e[0]=n,e[1]=t,e[2]=r,e[3]=i):(r=e[2],i=e[3]),X.useEffect(r,i)}export{xi as A,Qr as B,Vi as C,ki as D,Fi as E,Ti as F,Pr as G,qr as H,Li as I,Ln as J,ur as K,Mi as L,Ii as M,Ei as N,Ai as O,Ci as P,un as Q,vi as R,Gi as S,Pi as T,Ur as U,Jr as V,Ir as W,fn as X,hn as Y,mn as Z,ra as _,gs as a,ia as b,La as c,Pa as d,Oa as f,ca as g,ga as h,vs as i,ji as j,Si as k,Ma as l,Da as m,As as n,Uo as o,Ea as p,lr as q,Ds as r,Vo as s,js as t,Na as u,na as v,Ni as w,ea as x,ta as y,fi as z};