9remote 3.0.7 → 3.0.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.cjs +26 -26
- package/dist/server.cjs +210 -209
- package/dist/ui/assets/index-Dis7ADvo.js +8 -0
- package/dist/ui/index.html +1 -1
- package/dist/web/404.html +1 -1
- package/dist/web/__next.__PAGE__.txt +2 -2
- package/dist/web/__next._full.txt +3 -3
- package/dist/web/__next._head.txt +1 -1
- package/dist/web/__next._index.txt +2 -2
- package/dist/web/__next._tree.txt +2 -2
- package/dist/web/_next/static/chunks/1750.0aa6aeecbaace8cb.js +1 -0
- package/dist/web/_next/static/chunks/5018-0af0eec430de34c7.js +86 -0
- package/dist/web/_next/static/chunks/6552-26435ba7e21d8241.js +1 -0
- package/dist/web/_next/static/chunks/774-72d0e3531439cf1c.js +1 -0
- package/dist/web/_next/static/chunks/8439-43c6c0f6514a09d9.js +1 -0
- package/dist/web/_next/static/chunks/9958-448e936357b2d620.js +1 -0
- package/dist/web/_next/static/chunks/app/admin/admins/{page-a83d0b3b92891389.js → page-55a5b7d9e2cce009.js} +1 -1
- package/dist/web/_next/static/chunks/app/admin/login/{page-944e8499d7b8bc17.js → page-0ee5816b25a58124.js} +1 -1
- package/dist/web/_next/static/chunks/app/admin/modes/{page-567e8f7d4213406b.js → page-4a42062c1aa3bdfe.js} +1 -1
- package/dist/web/_next/static/chunks/app/admin/ota/{page-8d387fa8da56b013.js → page-f933a80b41b1fa71.js} +1 -1
- package/dist/web/_next/static/chunks/app/admin/{page-c008b84f3d009af1.js → page-9af75732b2cda9b6.js} +1 -1
- package/dist/web/_next/static/chunks/app/admin/turn/{page-4410571db9d99337.js → page-fbb8e50d077e6051.js} +1 -1
- package/dist/web/_next/static/chunks/app/dev/question/page-c28a92f80ec9e5a7.js +1 -0
- package/dist/web/_next/static/chunks/app/login/page-1db3e14c6da784f1.js +1 -0
- package/dist/web/_next/static/chunks/app/page-7f6a2a71b53981dc.js +22 -0
- package/dist/web/_next/static/chunks/app/workspace/layout-1ca3e32492ef60bc.js +14 -0
- package/dist/web/_next/static/chunks/{webpack-210219beafaa52a1.js → webpack-d869f11e68050bab.js} +1 -1
- package/dist/web/_next/static/css/98e745d5833fdea2.css +1 -0
- package/dist/web/_not-found/__next._full.txt +2 -2
- package/dist/web/_not-found/__next._head.txt +1 -1
- package/dist/web/_not-found/__next._index.txt +2 -2
- package/dist/web/_not-found/__next._not-found.__PAGE__.txt +1 -1
- package/dist/web/_not-found/__next._not-found.txt +1 -1
- package/dist/web/_not-found/__next._tree.txt +2 -2
- package/dist/web/_not-found.html +1 -1
- package/dist/web/_not-found.txt +2 -2
- package/dist/web/admin/__next._full.txt +3 -3
- package/dist/web/admin/__next._head.txt +1 -1
- package/dist/web/admin/__next._index.txt +2 -2
- package/dist/web/admin/__next._tree.txt +2 -2
- package/dist/web/admin/__next.admin.__PAGE__.txt +2 -2
- package/dist/web/admin/__next.admin.txt +1 -1
- package/dist/web/admin/admins/__next._full.txt +3 -3
- package/dist/web/admin/admins/__next._head.txt +1 -1
- package/dist/web/admin/admins/__next._index.txt +2 -2
- package/dist/web/admin/admins/__next._tree.txt +2 -2
- package/dist/web/admin/admins/__next.admin.admins.__PAGE__.txt +2 -2
- package/dist/web/admin/admins/__next.admin.admins.txt +1 -1
- package/dist/web/admin/admins/__next.admin.txt +1 -1
- package/dist/web/admin/admins.html +1 -1
- package/dist/web/admin/admins.txt +3 -3
- package/dist/web/admin/login/__next._full.txt +3 -3
- package/dist/web/admin/login/__next._head.txt +1 -1
- package/dist/web/admin/login/__next._index.txt +2 -2
- package/dist/web/admin/login/__next._tree.txt +2 -2
- package/dist/web/admin/login/__next.admin.login.__PAGE__.txt +2 -2
- package/dist/web/admin/login/__next.admin.login.txt +1 -1
- package/dist/web/admin/login/__next.admin.txt +1 -1
- package/dist/web/admin/login.html +1 -1
- package/dist/web/admin/login.txt +3 -3
- package/dist/web/admin/modes/__next._full.txt +3 -3
- package/dist/web/admin/modes/__next._head.txt +1 -1
- package/dist/web/admin/modes/__next._index.txt +2 -2
- package/dist/web/admin/modes/__next._tree.txt +2 -2
- package/dist/web/admin/modes/__next.admin.modes.__PAGE__.txt +2 -2
- package/dist/web/admin/modes/__next.admin.modes.txt +1 -1
- package/dist/web/admin/modes/__next.admin.txt +1 -1
- package/dist/web/admin/modes.html +1 -1
- package/dist/web/admin/modes.txt +3 -3
- package/dist/web/admin/ota/__next._full.txt +3 -3
- package/dist/web/admin/ota/__next._head.txt +1 -1
- package/dist/web/admin/ota/__next._index.txt +2 -2
- package/dist/web/admin/ota/__next._tree.txt +2 -2
- package/dist/web/admin/ota/__next.admin.ota.__PAGE__.txt +2 -2
- package/dist/web/admin/ota/__next.admin.ota.txt +1 -1
- package/dist/web/admin/ota/__next.admin.txt +1 -1
- package/dist/web/admin/ota.html +1 -1
- package/dist/web/admin/ota.txt +3 -3
- package/dist/web/admin/turn/__next._full.txt +3 -3
- package/dist/web/admin/turn/__next._head.txt +1 -1
- package/dist/web/admin/turn/__next._index.txt +2 -2
- package/dist/web/admin/turn/__next._tree.txt +2 -2
- package/dist/web/admin/turn/__next.admin.turn.__PAGE__.txt +2 -2
- package/dist/web/admin/turn/__next.admin.turn.txt +1 -1
- package/dist/web/admin/turn/__next.admin.txt +1 -1
- package/dist/web/admin/turn.html +1 -1
- package/dist/web/admin/turn.txt +3 -3
- package/dist/web/admin.html +1 -1
- package/dist/web/admin.txt +3 -3
- package/dist/web/agent-icons/hermes-ui.png +0 -0
- package/dist/web/dev/question/__next._full.txt +3 -3
- package/dist/web/dev/question/__next._head.txt +1 -1
- package/dist/web/dev/question/__next._index.txt +2 -2
- package/dist/web/dev/question/__next._tree.txt +2 -2
- package/dist/web/dev/question/__next.dev.question.__PAGE__.txt +2 -2
- package/dist/web/dev/question/__next.dev.question.txt +1 -1
- package/dist/web/dev/question/__next.dev.txt +1 -1
- package/dist/web/dev/question.html +1 -1
- package/dist/web/dev/question.txt +3 -3
- package/dist/web/index.html +1 -1
- package/dist/web/index.txt +3 -3
- package/dist/web/login/__next._full.txt +3 -3
- package/dist/web/login/__next._head.txt +1 -1
- package/dist/web/login/__next._index.txt +2 -2
- package/dist/web/login/__next._tree.txt +2 -2
- package/dist/web/login/__next.login.__PAGE__.txt +2 -2
- package/dist/web/login/__next.login.txt +1 -1
- package/dist/web/login.html +1 -1
- package/dist/web/login.txt +3 -3
- package/dist/web/workspace/__next._full.txt +3 -3
- package/dist/web/workspace/__next._head.txt +1 -1
- package/dist/web/workspace/__next._index.txt +2 -2
- package/dist/web/workspace/__next._tree.txt +2 -2
- package/dist/web/workspace/__next.workspace.__PAGE__.txt +1 -1
- package/dist/web/workspace/__next.workspace.txt +2 -2
- package/dist/web/workspace/browse/__next._full.txt +3 -3
- package/dist/web/workspace/browse/__next._head.txt +1 -1
- package/dist/web/workspace/browse/__next._index.txt +2 -2
- package/dist/web/workspace/browse/__next._tree.txt +2 -2
- package/dist/web/workspace/browse/__next.workspace.browse.__PAGE__.txt +1 -1
- package/dist/web/workspace/browse/__next.workspace.browse.txt +1 -1
- package/dist/web/workspace/browse/__next.workspace.txt +2 -2
- package/dist/web/workspace/browse.html +1 -1
- package/dist/web/workspace/browse.txt +3 -3
- package/dist/web/workspace/editor/__next._full.txt +3 -3
- package/dist/web/workspace/editor/__next._head.txt +1 -1
- package/dist/web/workspace/editor/__next._index.txt +2 -2
- package/dist/web/workspace/editor/__next._tree.txt +2 -2
- package/dist/web/workspace/editor/__next.workspace.editor.__PAGE__.txt +1 -1
- package/dist/web/workspace/editor/__next.workspace.editor.txt +1 -1
- package/dist/web/workspace/editor/__next.workspace.txt +2 -2
- package/dist/web/workspace/editor.html +1 -1
- package/dist/web/workspace/editor.txt +3 -3
- package/dist/web/workspace/files/__next._full.txt +3 -3
- package/dist/web/workspace/files/__next._head.txt +1 -1
- package/dist/web/workspace/files/__next._index.txt +2 -2
- package/dist/web/workspace/files/__next._tree.txt +2 -2
- package/dist/web/workspace/files/__next.workspace.files.__PAGE__.txt +1 -1
- package/dist/web/workspace/files/__next.workspace.files.txt +1 -1
- package/dist/web/workspace/files/__next.workspace.txt +2 -2
- package/dist/web/workspace/files.html +1 -1
- package/dist/web/workspace/files.txt +3 -3
- package/dist/web/workspace/git/__next._full.txt +3 -3
- package/dist/web/workspace/git/__next._head.txt +1 -1
- package/dist/web/workspace/git/__next._index.txt +2 -2
- package/dist/web/workspace/git/__next._tree.txt +2 -2
- package/dist/web/workspace/git/__next.workspace.git.__PAGE__.txt +1 -1
- package/dist/web/workspace/git/__next.workspace.git.txt +1 -1
- package/dist/web/workspace/git/__next.workspace.txt +2 -2
- package/dist/web/workspace/git.html +1 -1
- package/dist/web/workspace/git.txt +3 -3
- package/dist/web/workspace/mobile/__next._full.txt +3 -3
- package/dist/web/workspace/mobile/__next._head.txt +1 -1
- package/dist/web/workspace/mobile/__next._index.txt +2 -2
- package/dist/web/workspace/mobile/__next._tree.txt +2 -2
- package/dist/web/workspace/mobile/__next.workspace.mobile.__PAGE__.txt +1 -1
- package/dist/web/workspace/mobile/__next.workspace.mobile.txt +1 -1
- package/dist/web/workspace/mobile/__next.workspace.txt +2 -2
- package/dist/web/workspace/mobile.html +1 -1
- package/dist/web/workspace/mobile.txt +3 -3
- package/dist/web/workspace/remote/__next._full.txt +3 -3
- package/dist/web/workspace/remote/__next._head.txt +1 -1
- package/dist/web/workspace/remote/__next._index.txt +2 -2
- package/dist/web/workspace/remote/__next._tree.txt +2 -2
- package/dist/web/workspace/remote/__next.workspace.remote.__PAGE__.txt +1 -1
- package/dist/web/workspace/remote/__next.workspace.remote.txt +1 -1
- package/dist/web/workspace/remote/__next.workspace.txt +2 -2
- package/dist/web/workspace/remote.html +1 -1
- package/dist/web/workspace/remote.txt +3 -3
- package/dist/web/workspace/terminal/default/__next._full.txt +3 -3
- package/dist/web/workspace/terminal/default/__next._head.txt +1 -1
- package/dist/web/workspace/terminal/default/__next._index.txt +2 -2
- package/dist/web/workspace/terminal/default/__next._tree.txt +2 -2
- package/dist/web/workspace/terminal/default/__next.workspace.terminal.$d$sessionId.__PAGE__.txt +1 -1
- package/dist/web/workspace/terminal/default/__next.workspace.terminal.$d$sessionId.txt +1 -1
- package/dist/web/workspace/terminal/default/__next.workspace.terminal.txt +1 -1
- package/dist/web/workspace/terminal/default/__next.workspace.txt +2 -2
- package/dist/web/workspace/terminal/default.html +1 -1
- package/dist/web/workspace/terminal/default.txt +3 -3
- package/dist/web/workspace/workspaces/__next._full.txt +3 -3
- package/dist/web/workspace/workspaces/__next._head.txt +1 -1
- package/dist/web/workspace/workspaces/__next._index.txt +2 -2
- package/dist/web/workspace/workspaces/__next._tree.txt +2 -2
- package/dist/web/workspace/workspaces/__next.workspace.txt +2 -2
- package/dist/web/workspace/workspaces/__next.workspace.workspaces.__PAGE__.txt +1 -1
- package/dist/web/workspace/workspaces/__next.workspace.workspaces.txt +1 -1
- package/dist/web/workspace/workspaces.html +1 -1
- package/dist/web/workspace/workspaces.txt +3 -3
- package/dist/web/workspace.html +1 -1
- package/dist/web/workspace.txt +3 -3
- package/package.json +1 -1
- package/dist/ui/assets/index-BjdVz7mh.js +0 -8
- package/dist/web/_next/static/chunks/161-ccde05f90997adf7.js +0 -1
- package/dist/web/_next/static/chunks/1750.a35b00a05b21d196.js +0 -1
- package/dist/web/_next/static/chunks/3973-919fa2e493564fcf.js +0 -1
- package/dist/web/_next/static/chunks/6552-09e2e0d864ebbc44.js +0 -1
- package/dist/web/_next/static/chunks/8516-b3694c9156666b12.js +0 -152
- package/dist/web/_next/static/chunks/9958-ccfdf26ae6776021.js +0 -1
- package/dist/web/_next/static/chunks/app/dev/question/page-344ec1e850f0d8a2.js +0 -1
- package/dist/web/_next/static/chunks/app/login/page-c9eba50fbf9af8b9.js +0 -1
- package/dist/web/_next/static/chunks/app/page-863e9695cfd65f93.js +0 -22
- package/dist/web/_next/static/chunks/app/workspace/layout-08b1abf6c42c1416.js +0 -14
- package/dist/web/_next/static/css/48ee7d57614b1421.css +0 -1
- /package/dist/web/_next/static/{YOawNeLZwNQHJ4nLya6K3 → LzU93v-WhDilDnQQPclsp}/_buildManifest.js +0 -0
- /package/dist/web/_next/static/{YOawNeLZwNQHJ4nLya6K3 → LzU93v-WhDilDnQQPclsp}/_ssgManifest.js +0 -0
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[1807,3977],{27520:(e,t,s)=>{"use strict";s.d(t,{FQ:()=>o,Lq:()=>p,UX:()=>i,k_:()=>d,yO:()=>c});var n=s(2805);let r=[],a=new Set,l=location.hostname.startsWith("dev.")||"localhost"===location.hostname&&!(0,n.XS)()||"1"===localStorage.getItem("9remote:termLog");function i(){return l}function o(){return r}function c(e){return a.add(e),()=>a.delete(e)}function d(){for(let e of(r.length=0,a))try{e(null)}catch(e){}}function u(e){if(null==e)return"";if(e instanceof Uint8Array||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)return`<${e.byteLength}b>`;if("string"==typeof e)return e.length>120?`${e.slice(0,60)}…${e.length}b`:e;if("object"==typeof e)try{return JSON.stringify(e)}catch(e){}return String(e)}let m=new Set(["recv"]),x=null;function p(e,...t){if(!l)return;let s=Date.now(),n=t.map(u).join(" ");if(x&&x.category===e&&x.baseMsg===n&&s-x.ts<3e3||m.has(e)&&x&&x.category===e&&s-x.ts<300){x.count=(x.count||1)+1,x.ts=s,x.msg=`${n} \xd7${x.count}`,queueMicrotask(()=>{for(let e of a)try{e(x)}catch(e){}});return}let i={ts:s,category:e,msg:n,baseMsg:n,count:1};x=i,r.push(i),r.length>800&&r.shift();try{console.log(`[termLog ${e}] ${n}`)}catch{}queueMicrotask(()=>{for(let e of a)try{e(i)}catch(e){}})}},36416:(e,t,s)=>{Promise.resolve().then(s.bind(s,69620))},48310:(e,t,s)=>{"use strict";s.d(t,{w:()=>l});var n=s(1521),r=s(38415);let a="9remote_github_stars";function l(){let[e,t]=(0,n.useState)(null);return(0,n.useEffect)(()=>{try{let e=localStorage.getItem(a);if(e){let{count:s,timestamp:n}=JSON.parse(e);if("number"==typeof s&&t(s),Date.now()-n<36e5)return}}catch{}let e=!0;return fetch(r.O8).then(e=>e.ok?e.json():null).then(s=>{if(!e||"number"!=typeof s?.stargazers_count)return;let n=s.stargazers_count;t(n);try{localStorage.setItem(a,JSON.stringify({count:n,timestamp:Date.now()}))}catch{}}).catch(()=>{}),()=>{e=!1}},[]),{stars:e,formattedStars:null==e?"":e>=1e3?(e/1e3).toFixed(1).replace(/\.0$/,"")+"k":String(e)}}},63977:(e,t,s)=>{"use strict";s.d(t,{freshAuth:()=>a});var n=s(90084),r=s(86251);async function a(e={},t){let s={...e,connectionMode:t},l=(0,n.lz)(e.apiKey),i=e.tempKey?(0,n.lz)(e.tempKey):null,o=l?.tail?l:i?.tail?i:l||i,c=o?.tail;if(delete s.keyTail,delete s.keyTailSealed,!c)return s;if(o?.hostSealKey){let e=await (0,r.Y)(c,o.hostSealKey);if(e)return s.keyTailSealed=e,s}return s.keyTail=c,s}},69620:(e,t,s)=>{"use strict";s.r(t),s.d(t,{default:()=>mk});var n=s(73365),r=s(1521),a=s(29717),l=s(97711);let i="9remote_deviceId";var o=s(86129);class c{static{this.id="base"}static{this.capabilities={control:!1,binary:!1,signaling:"none"}}static{this.priority={control:0,binary:0}}constructor(){this._listeners=new Map,this._state=o.Of.idle}get state(){return this._state}get ready(){return this._state===o.Of.open}supports(e){return!!this.constructor.capabilities[e]}getPriority(e){return this.constructor.priority[e]??0}on(e,t){this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(t)}off(e,t){this._listeners.get(e)?.delete(t)}_emit(e,...t){let s=this._listeners.get(e);if(s)for(let e of s)e(...t)}_setState(e){this._state!==e&&(this._state=e,this._emit("stateChange",e))}connect(e){throw Error("Not implemented: connect")}disconnect(){throw Error("Not implemented: disconnect")}send(e,t){throw Error("Not implemented: send")}}var d=s(48193),u=s(63977);let m={transports:["websocket"],reconnection:!1,reconnectionDelay:1e3,reconnectionDelayMax:5e3};class x{constructor({tunnelUrl:e,namespace:t="",socketOptions:s={}}){this._tunnelUrl=e,this._namespace=t,this._socketOptions=s}connect({onSocket:e,onFail:t}){let s=this._namespace?`${this._tunnelUrl}${this._namespace}`:this._tunnelUrl,n=this._tunnelUrl===window.location.origin?"local":"tunnel",r=(0,d.io)(s,{...m,...this._socketOptions,path:"/socket.io",auth:e=>{(0,u.freshAuth)(this._socketOptions.auth,n).then(e)}}),a=!1;r.once("connect",()=>{a||(a=!0,e(r,n))}),r.once("connect_error",()=>{a||(a=!0,t?.())})}}let p={transports:["websocket"],reconnection:!1};class h{constructor({tunnelUrl:e,localIp:t,namespace:s="",socketOptions:n={}}){this._tunnelUrl=e,this._localIp=t,this._namespace=s,this._socketOptions=n}connect({onSocket:e,onFail:t}){let s=!1,n=(t,n)=>{if(s){try{t.disconnect()}catch{}return}s=!0,e(t,n)},r=e=>this._namespace?`${e}${this._namespace}`:e,a=e=>({...p,...this._socketOptions,path:"/socket.io",auth:t=>{(0,u.freshAuth)(this._socketOptions.auth,e).then(t)}}),l=()=>{let e=this._tunnelUrl===window.location.origin?"local":"tunnel",l=(0,d.io)(r(this._tunnelUrl),a(e));l.once("connect",()=>n(l,e)),l.once("connect_error",()=>void(!s&&(s=!0,t?.())))};if(!this._localIp||"https:"===window.location.protocol)return void l();let i=(0,d.io)(r(`http://${this._localIp}`),a("local"));i.once("connect",()=>n(i,"local")),i.once("connect_error",()=>{s||(i.disconnect(),l())})}}var f=s(90076);let b=3;var g=s(52159),v=s(27520);let y=2e3,w=15,k=15,j=15,N=45;class S extends c{static{this.id="ws"}static{this.capabilities={control:!0,binary:!0,file:!0,signaling:"ws"}}static{this.priority={control:100,binary:10,file:10}}constructor(){super(),this._socket=null,this._connectionMode="local",this._retryTimer=null,this._retryAttempt=0,this._retryScheduled=!1,this._retryNowTimer=null,this._destroyed=!1,this._blocked=!1,this._updating=!1,this._connecting=!1,this._visibilityHandler=null,this._lastInboundAt=Date.now(),this._lastMsgAt=0,this._retrySeq=0}get lastInboundAt(){return this._lastInboundAt}get lastMsgAt(){return this._lastMsgAt}get socket(){return this._socket}get connectionMode(){return this._connectionMode}get blocked(){return this._blocked}setUpdating(e){this._updating=e,e&&(this._maxAttempts=N,this._retryAttempt=0,(0,g.c)("transport",`[ws] updating=true maxAttempts=${this._maxAttempts}`))}forceReconnect(){this._destroyed||this._forceReconnect()}retryNow(e="?"){if(this._blocked)return void(0,v.Lq)("switch",`ws retryNow SKIP by=${e} (blocked)`);let t=Date.now(),s=t-(this._lastRetryNowAt||0);if(s<3e3){this._retryNowTimer||(this._retryNowTimer=setTimeout(()=>{this._retryNowTimer=null,this.retryNow(`${e}-deferred`)},3e3-s)),(0,g.c)("transport","[ws] retryNow throttled → deferred"),(0,v.Lq)("switch",`ws retryNow DEFER by=${e} (${3e3-s}ms left)`);return}(0,v.Lq)("switch",`ws retryNow GO by=${e} (drops attempt ${this._retryAttempt})`),this._retrySeq++,this._lastRetryNowAt=t,clearTimeout(this._retryNowTimer),this._retryNowTimer=null,clearTimeout(this._retryTimer),clearTimeout(this._connectingTimer),this._retryTimer=null,this._retryScheduled=!1,this._retryAttempt=0,this._connecting=!1,this._destroyed=!0,this._detachSocketEvents(),this._socket?.disconnect(),this._socket=null,this._destroyed=!1,this._ctx?.onRetryStatus?.({isRetrying:!0,attempt:1,maxAttempts:this._maxAttempts,failed:!1}),this._setState(o.Of.connecting),this._connectInternal()}setBlocked(e){this._blocked=e,(0,g.c)("transport",`[ws] blocked=${e}`),e?(this._cancelRetry(),this._socket?.disconnect()):this._socket?.connected||this._destroyed||this._connectInternal()}connect(e){this._ctx=e,this._auth=e.auth,this._maxAttempts=this._auth.tempKey?w:k,this._reconnectMaxAttempts=j,this._destroyed=!1,this._attachNetworkListeners(),this._setState(o.Of.connecting),this._connectInternal()}disconnect(){this._destroyed=!0,this._retrySeq++,this._cancelRetry(),this._removeNetworkListeners(),this._detachSocketEvents(),this._socket?.disconnect(),this._socket=null,this._setState(o.Of.closed)}send(e,t){if(!this._socket?.connected)return!1;if(e===o.l_.control){let{event:e,args:s=[],cb:n}=t;return n?this._socket.emit(e,...s,n):this._socket.emit(e,...s),!0}return e===o.l_.binary?(this._socket.emit("tiles-bin-v2",t),!0):e===o.l_.file&&(this._socket.emit("file-bin",t),!0)}_connectInternal(){if(this._connecting||this._socket?.connected||this._destroyed)return;if(!this._auth.tunnelUrl&&!this._auth.localIp){(0,g.c)("transport","[ws] connect HOLD (no tunnelUrl/localIp yet) → retry"),(0,v.Lq)("switch","ws connect HOLD (no url yet) → fetch on retry"),this._setState(o.Of.degraded),this._scheduleRetry();return}this._connecting=!0,clearTimeout(this._connectingTimer),this._connectingTimer=setTimeout(()=>{this._connecting=!1},y);let e={tunnelUrl:this._auth.tunnelUrl,namespace:this._auth.namespace||"",socketOptions:this._auth.socketOptions||{}};(0,g.c)("transport",`[ws] connect: tunnelUrl=${this._auth.tunnelUrl} localIp=${this._auth.localIp||"none"}`),new x(e).connect({onSocket:(e,t)=>{if(this._connecting=!1,clearTimeout(this._connectingTimer),this._socket?.connected&&this._socket!==e){try{e.disconnect()}catch{}return}this._connectionMode=t,this._socket=e,this._retryAttempt=0,this._updating=!1,this._maxAttempts=this._reconnectMaxAttempts,this._cancelRetry(),this._attachSocketEvents(e),(0,g.c)("transport",`[ws] connect mode=${t}`),(0,v.Lq)("switch",`ws open mode=${t}`),this._setState(o.Of.open)},onFail:()=>{this._connecting=!1,clearTimeout(this._connectingTimer),(0,g.c)("transport","[ws] connect FAIL → schedule retry"),this._scheduleRetry()}})}_attachSocketEvents(e){e.on("disconnect",e=>{(0,g.c)("transport",`[ws] disconnect reason=${e}`),(0,v.Lq)("switch",`ws disconnect reason=${e}`),this._setState(o.Of.degraded),this._destroyed||this._forceReconnect()}),e.on("connect_error",e=>{(0,g.c)("transport",`[ws] connect_error ${e?.message||e}`),this._setState(o.Of.degraded),this._forceReconnect()}),e.io?.on?.("pong",()=>{this._lastInboundAt=Date.now()}),e.on("connect",()=>{this._lastInboundAt=Date.now()}),e.onAny((e,t)=>{this._lastMsgAt=Date.now(),this._emit("message",{event:e,data:t,source:"ws"})})}_attachNetworkListeners(){this._visibilityHandler||(this._visibilityHandler=()=>{"visible"!==document.visibilityState||this._socket?.connected||this._connecting||this.retryNow("visible")},this._offlineHandler=()=>{(0,v.Lq)("switch","ws offline event → drop socket, degraded"),this._socket?.disconnect(),this._socket=null,this._setState(o.Of.degraded)},this._onlineHandler=()=>{this._socket?.connected||this._connecting?(0,v.Lq)("switch",`ws online event → skip (${this._connecting?"handshaking":"already up"})`):this.retryNow("online")},this._pagehideHandler=()=>{try{this._socket?.disconnect()}catch{}},window.addEventListener("pagehide",this._pagehideHandler),document.addEventListener("visibilitychange",this._visibilityHandler),window.addEventListener("offline",this._offlineHandler),window.addEventListener("online",this._onlineHandler))}_detachSocketEvents(){if(this._socket)try{this._socket.offAny()}catch{}}_removeNetworkListeners(){this._pagehideHandler&&(window.removeEventListener("pagehide",this._pagehideHandler),this._pagehideHandler=null),this._visibilityHandler&&(document.removeEventListener("visibilitychange",this._visibilityHandler),this._visibilityHandler=null),this._offlineHandler&&(window.removeEventListener("offline",this._offlineHandler),this._offlineHandler=null),this._onlineHandler&&(window.removeEventListener("online",this._onlineHandler),this._onlineHandler=null)}_forceReconnect(){if(!this._destroyed&&!this._blocked&&!this._retryScheduled&&!this._connecting){if(this._retrySeq++,this._retryAttempt++,this._retryAttempt>b){this._retryAttempt=0,this._scheduleRetry();return}this._socket?.disconnect(),this._socket=null,this._connectInternal()}}_scheduleRetry(){this._retryScheduled||this._destroyed||this._blocked||(this._retryScheduled=!0,this._retryTimer=setTimeout(()=>this._doRetry(),y))}async _doRetry(){if(this._destroyed)return;if("u">typeof document&&"hidden"===document.visibilityState){(0,v.Lq)("switch",`ws retry HOLD (hidden, still at ${this._retryAttempt}/${this._maxAttempts})`),this._retryScheduled=!1,this._scheduleRetry();return}this._retryAttempt++;let e=this._retryAttempt,t=this._retrySeq;if(e>this._maxAttempts){this._retryScheduled=!1,(0,v.Lq)("switch",`ws GAVE UP after ${this._maxAttempts} attempts → closed`),this._ctx?.onRetryStatus?.({isRetrying:!1,attempt:e,maxAttempts:this._maxAttempts,failed:!0}),this._setState(o.Of.closed);return}(0,g.c)("transport",`[ws] retry attempt=${e}/${this._maxAttempts}`),(0,v.Lq)("switch",`ws retry ${e}/${this._maxAttempts}`),this._ctx?.onRetryStatus?.({isRetrying:!0,attempt:e,maxAttempts:this._maxAttempts,failed:!1});try{let e=await fetch(f.Sn.connect,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:this._auth.apiKey})});if(!e.ok)throw Error("Failed");let{tunnelUrl:s,localIp:n}=await e.json();if(t!==this._retrySeq)return void(0,v.Lq)("switch","ws retry ABORT (superseded mid-fetch)");this._auth.tunnelUrl=s,this._auth.localIp=n||null,this._connectionMode="local",this._ctx?.onUrlUpdate?.({tunnelUrl:s,localIp:n}),this._socket?.disconnect(),this._retryScheduled=!1,this._connectInternal()}catch{if(t!==this._retrySeq)return;this._retryScheduled=!1,this._scheduleRetry()}}_cancelRetry(){clearTimeout(this._retryTimer),this._retryTimer=null,clearTimeout(this._retryNowTimer),this._retryNowTimer=null,this._retrySeq++,this._retryAttempt=0,this._retryScheduled=!1,this._ctx?.onRetryStatus?.({isRetrying:!1,attempt:0,maxAttempts:this._maxAttempts,failed:!1})}}function C(e,t){if(t instanceof Uint8Array){let e="";for(let s=0;s<t.length;s++)e+=String.fromCharCode(t[s]);return{__b:btoa(e)}}return t}function T(e,t){if(t&&"object"==typeof t&&"string"==typeof t.__b){let e=atob(t.__b),s=new Uint8Array(e.length);for(let t=0;t<e.length;t++)s[t]=e.charCodeAt(t);return s}return t}function R(e){return JSON.stringify(e,C)}function E(e,t=null){let s=[],n={event:e.event,args:function e(t,s){if(t instanceof ArrayBuffer)return s.push(new Uint8Array(t)),{__B:s.length-1};if(ArrayBuffer.isView(t))return s.push(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),{__B:s.length-1};if(Array.isArray(t))return t.map(t=>e(t,s));if(t&&"object"==typeof t){let n={};for(let r of Object.keys(t))n[r]=e(t[r],s);return n}return t}(e.args||[],s),ackId:e.ackId??null,lens:s.map(e=>e.length)};t&&(n.frag=t.id,n.part=t.part,n.parts=t.parts);let r=new TextEncoder().encode(JSON.stringify(n)),a=new Uint8Array(4+r.length+s.reduce((e,t)=>e+t.length,0));new DataView(a.buffer).setUint32(0,r.length,!0),a.set(r,4);let l=4+r.length;for(let e of s)a.set(e,l),l+=e.length;return a}function _(e){let t=e instanceof Uint8Array?e:new Uint8Array(e);if(t.length<4)throw Error("frame too short");let s=4+new DataView(t.buffer,t.byteOffset,t.byteLength).getUint32(0,!0);if(s>t.length)throw Error("frame header truncated");let n=JSON.parse(new TextDecoder().decode(t.subarray(4,s))),r=[],a=s;for(let e of n.lens||[]){if(a+e>t.length)throw Error("frame part truncated");r.push(t.subarray(a,a+e)),a+=e}return{event:n.event,args:function e(t,s){if(Array.isArray(t))return t.map(t=>e(t,s));if(t&&"object"==typeof t){if("number"==typeof t.__B)return s[t.__B]??null;let n={};for(let r of Object.keys(t))n[r]=e(t[r],s);return n}return t}(n.args||[],r),ackId:n.ackId??null,frag:n.frag,part:n.part,parts:n.parts}}function $(){let e=new Map;return{push(t){let{frag:s,part:n,parts:r}=t;if(null==s)return t;if(!Number.isInteger(n)||!Number.isInteger(r)||n<0||r<1||n>=r||r>4096)return null;let a=e.get(s);a||(e.size>=4&&e.delete(e.keys().next().value),a={slices:Array(r),got:0},e.set(s,a));let l=t.args?.[0];if(null==l||(!a.slices[n]&&(a.slices[n]=l,a.got++),a.got<r))return null;e.delete(s);let i=new Uint8Array(a.slices.reduce((e,t)=>e+t.byteLength,0)),o=0;for(let e of a.slices)i.set(e,o),o+=e.byteLength;return _(i)}}}var M=s(90084),P=s(7938);let A=null,z=0,I=new Map,L=0;async function D(e,t){let s=`9remote_turn_cache_${t?.slice(0,12)||"anon"}`;try{let e="u">typeof localStorage?localStorage.getItem(s):null;if(e){let t=JSON.parse(e);if(t?.expiresAt>Date.now()&&Array.isArray(t.iceServers)&&t.iceServers.length)return t.iceServers}}catch{}try{let n=await fetch(e,{headers:{"X-API-Key":t},signal:AbortSignal.timeout(4e3)});if(n.ok){let e=await n.json();if(e?.iceServers?.length){try{"u">typeof localStorage&&localStorage.setItem(s,JSON.stringify({iceServers:e.iceServers,expiresAt:Date.now()+828e5}))}catch{}return e.iceServers}}}catch(e){console.warn("[WebRtcProtocol] TURN fetch failed:",e.message)}return null}class F extends c{static{this.id="rtc"}static{this.capabilities={control:!0,binary:!0,file:!0,signaling:"external"}}static{this.priority={control:50,binary:100,file:100}}constructor(){super(),this._pc=null,this._dcControl=null,this._dcBinary=null,this._dcFile=null,this._typeDetail="dc-stun",this._localCandidateTypes=new Set,this._answerApplied=!1,this._pendingCandidates=[],this._iceReachedChecking=!1,this._everOpened=!1,this._isLoopback=!1,this._pendingEmit=null,this._flushTimer=null,this._latestTileTs=new Map,this._hbTimer=null,this._hbLastPing=0,this._peerEnv2=!1,this._peerFragCtl=!1,this._v2Announced=!1,this._v2RxSeen=!1,this._fragSeq=0,this._reassemble=$(),this._lastInboundAt=0,this._signalingHandlers={},this._signaling=null,this._useTurn=!1}get lastInboundAt(){return this._lastInboundAt}getPriority(e){return"dc-turn"===this._typeDetail?5:150}async connect(e){this._ctx=e,this._cleanupPeer(),this._peerEpoch=(this._peerEpoch??0)+1,this._localCandidateTypes=new Set,this._answerApplied=!1,this._pendingCandidates=[],this._iceReachedChecking=!1,this._everOpened=!1,this._isLoopback=!1,this._typeDetail="dc-stun",this._lastMid=null,this._remoteGatheringDone=!1,this._setState(o.Of.connecting),this.connectingSince=Date.now(),this.connectDeadline=this.connectingSince+o.AC,clearTimeout(this._connectTimer),this._connectTimer=setTimeout(()=>{this._state!==o.Of.open&&((0,g.c)("transport",`[rtc] connect timeout (${o.AC}ms, state=${this._state}) → close + retry`),this._closePeer(`connect-timeout (state=${this._state})`))},o.AC);let t=[{urls:["stun:stun.l.google.com:19302","stun:stun1.l.google.com:19302","stun:stun2.l.google.com:19302","stun:stun3.l.google.com:19302","stun:stun4.l.google.com:19302"]},{urls:"stun:global.stun.twilio.com:3478"},{urls:"stun:stun.cloudflare.com:3478"}];if(this._useTurn=!!(e.useTurn||e.profile?.rtc?.enableTurn),e.iceServers?.length)t=e.iceServers;else if(this._useTurn){let s=await D(f.Sn.turnCredentials,e.auth?.apiKey);s?.length&&(t=s)}let s=new RTCPeerConnection({iceServers:t,iceCandidatePoolSize:4,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});this._pc=s;let n=e.profile?.rtc?.dcControl?.ordered??!0,r=s.createDataChannel("control",{ordered:n}),a=s.createDataChannel("binary",{ordered:!1,maxPacketLifeTime:500}),l=s.createDataChannel("file",{ordered:!0});a.binaryType="arraybuffer",r.binaryType="arraybuffer",l.binaryType="arraybuffer",this._dcControl=r,this._dcBinary=a,this._dcFile=l;let i=async()=>{if("open"!==r.readyState||"open"!==a.readyState)return;let e="";try{let t=await s.getStats();t.forEach(s=>{if("candidate-pair"===s.type&&"succeeded"===s.state){let n=[...t.values()].find(e=>e.id===s.localCandidateId),r=[...t.values()].find(e=>e.id===s.remoteCandidateId);(n?.candidateType==="relay"||r?.candidateType==="relay")&&(this._typeDetail="dc-turn");let a=n?.address||n?.ip||"",l=r?.address||r?.ip||"";("127.0.0.1"===a||"::1"===a||"127.0.0.1"===l||"::1"===l)&&(this._isLoopback=!0),e=`local=${n?.candidateType}/${n?.protocol} remote=${r?.candidateType}/${r?.protocol}`}})}catch{}this.send(o.l_.control,{event:"rtc:linkType",args:[this._typeDetail]}),(0,g.c)("transport",`[rtc] dc OPEN type=${this._typeDetail} ${e}`),(0,v.Lq)("switch",`rtc dc OPEN (${this._typeDetail} ${e})`),clearTimeout(this._connectTimer),this._connectTimer=null,this._everOpened=!0,this._lastInboundAt=Date.now(),this._setState(o.Of.open)};r.onopen=i,a.onopen=i;let c=()=>{let e=!this._dcControl||"closed"===this._dcControl.readyState,t=!this._dcBinary||"closed"===this._dcBinary.readyState;(0,v.Lq)("switch",`rtc dc-close (ctrl=${this._dcControl?.readyState} bin=${this._dcBinary?.readyState})`),e&&t?this._setState(o.Of.closed):this._setState(o.Of.degraded)};r.onclose=c,a.onclose=c,l.onclose=()=>{this._dcFile=null},r.onerror=e=>{let t=e.error?.message??"unknown";t.includes("User-Initiated")||console.error("[rtc] dcControl ERROR:",t)},a.onerror=e=>{let t=e.error?.message??"unknown";t.includes("User-Initiated")||console.error("[rtc] dcBinary ERROR:",t)},l.onerror=e=>{let t=e.error?.message??"unknown";t.includes("User-Initiated")||console.error("[rtc] dcFile ERROR:",t)},r.onmessage=({data:e})=>{let t;this._lastInboundAt=Date.now();try{let s;if("string"==typeof e)s=JSON.parse("string"==typeof e?e:new TextDecoder().decode(e),T);else s=_(e),this._v2RxSeen||(this._v2RxSeen=!0,(0,v.Lq)("switch","env2: first v2 binary frame DECODED from agent (mutual upgrade confirmed)"));t=this._reassemble.push(s)}catch(e){console.error("[rtc] control parse error:",e.message);return}if(t){if("__ping"===t.event){this._hbTimer||this._startHeartbeatWatch(),this._hbLastPing=Date.now();try{r.send(R({event:"__pong",args:t.args||[]}))}catch{}return}this._emit("message",{event:t.event,data:t,source:"rtc"})}},a.onmessage=({data:e})=>{this._lastInboundAt=Date.now(),e instanceof ArrayBuffer&&this._receiveTile(e)},l.onmessage=({data:e})=>{this._lastInboundAt=Date.now(),e instanceof ArrayBuffer&&this._emit("binary",{channel:"file",buffer:e,source:"rtc"})},s.onicecandidate=({candidate:e})=>{var t;if(!e)return void this._sendSignaling({type:"ice",candidate:"",mid:this._lastMid||"0"});this._lastMid=e.sdpMid;let s=/typ (host|srflx|relay|prflx)/.exec(e.candidate||"");s&&this._localCandidateTypes.add(s[1]);let n=(t=e.candidate)&&t.includes("typ srflx")&&t.split(" ")[4]||null;n&&this._emit("netFingerprint",n),this._sendSignaling({type:"ice",candidate:e.candidate,mid:e.sdpMid})},s.oniceconnectionstatechange=()=>{(0,g.c)("transport",`[rtc] iceState=${s.iceConnectionState}`),(0,v.Lq)("switch",`rtc ice=${s.iceConnectionState} types=[${[...this._localCandidateTypes].join(",")}]`),"checking"===s.iceConnectionState&&(this._iceReachedChecking=!0),"disconnected"===s.iceConnectionState?this._setState(o.Of.degraded):"failed"===s.iceConnectionState?this._closePeer("ice-failed"):"connected"===s.iceConnectionState&&this._dcControl?.readyState==="open"&&this._dcBinary?.readyState==="open"&&this._setState(o.Of.open)},this._signaling=e.signaling,this._signaling?.on?.(e=>this._handleSignal(e));try{let e=await s.createOffer();await s.setLocalDescription(e),(0,g.c)("transport","[rtc] offer sent"),(0,v.Lq)("switch","rtc offer sent"),this._sendSignaling({type:"offer",sdp:e.sdp,useTurn:this._useTurn})}catch(e){console.error("[rtc] createOffer error:",e.message),this._closePeer(`create-offer:${e.message}`)}}disconnect(e="?"){this._closePeer(`manual-disconnect by=${e} state=${this._state}`),this._signaling?.off?.(),this._signaling=null}send(e,t){if(e===o.l_.control){if(this._dcControl?.readyState!=="open")return!1;let e={event:t.event,args:t.args||[],ackId:t.ackId||null};if(this._peerEnv2)return!!this._sendFramed(e)&&(this._v2Announced||(this._v2Announced=!0,(0,v.Lq)("switch","env2: client→agent control now SENT as v2 binary frames")),!0);try{return this._dcControl.send(R(e)),!0}catch(e){return!1}}if(e===o.l_.binary){if(this._dcBinary?.readyState!=="open")return!1;try{return this._dcBinary.send(t),!0}catch(e){return console.error("[rtc] send binary error:",e.message),!1}}if(e===o.l_.file){if(this._dcFile?.readyState!=="open")return!1;try{if(this._dcFile.bufferedAmount>o.HE.dcBufferThreshold)return!1;return this._dcFile.send(t),!0}catch(e){console.error("[rtc] send file error:",e.message)}}return!1}get typeDetail(){return this._typeDetail}get isLoopback(){return this._isLoopback}_closePeer(e){(0,v.Lq)("switch",`rtc→closed reason=${e}`),this._cleanupPeer(),this._setState(o.Of.closed)}setPeerCaps(e){this._peerEnv2=!!e?.env2,this._peerFragCtl=!!e?.fragCtl}get maxControlBytes(){return this._pc?.sctp?.maxMessageSize||o.dT}_sendFramed(e){var t;let s,n,r=this._peerFragCtl?this.maxControlBytes:1/0,a=(t=++this._fragSeq,(n=function(e,t){if(e.byteLength<=t)return[e];let s=t-192;if(s<=0)return null;let n=Math.ceil(e.byteLength/s);if(n>4096)return null;let r=[];for(let t=0;t<n;t++)r.push(e.subarray(t*s,Math.min((t+1)*s,e.byteLength)));return r}(s=E(e),r))?1===n.length?[s]:n.map((s,r)=>E({event:e.event,args:[s]},{id:t,part:r,parts:n.length})):null);if(!a)return!1;try{for(let e of a)this._dcControl.send(e);return!0}catch(e){return(0,g.c)("transport",`[rtc] control send refused: ${e.message}`),!1}}_startHeartbeatWatch(){this._hbTimer&&(clearInterval(this._hbTimer),this._hbTimer=null),this._hbLastPing=Date.now(),this._hbTimer=setInterval(()=>{if(this._state!==o.Of.open){clearInterval(this._hbTimer),this._hbTimer=null;return}let e=Date.now()-this._hbLastPing;e>o.An&&((0,g.c)("transport",`[rtc] heartbeat: no ping for ${e}ms → closing stalled peer`),this._closePeer(`heartbeat-stale (${e}ms)`))},o.KF)}async _addRemoteCandidate({candidate:e,mid:t}){e||(this._remoteGatheringDone=!0),await this._pc.addIceCandidate(new RTCIceCandidate(e?{candidate:e,sdpMid:t}:{candidate:"",sdpMid:t||"0"})).catch(()=>{})}_startDeadPathWatch(){clearInterval(this._deadPathTimer),this._deadPathTimer=setInterval(async()=>{if(this._state===o.Of.open||!this._pc)return this._stopDeadPathWatch();if(!this._remoteGatheringDone||"complete"!==this._pc.iceGatheringState)return;let e=0,t=0;try{(await this._pc.getStats()).forEach(s=>{"candidate-pair"===s.type&&(e++,"failed"===s.state&&t++)})}catch{return}e&&!(t<e)&&(this._stopDeadPathWatch(),this._closePeer(`dead-path (${t} pair(s) failed)`))},o.QS)}_stopDeadPathWatch(){clearInterval(this._deadPathTimer),this._deadPathTimer=null}_sendSignaling(e){this._signaling?.send?.(e)}async _handleSignal(e){if((0,g.c)("transport",`[rtc] signal: ${e.type}`),(0,v.Lq)("switch",`rtc signal recv=${e.type}`),this._pc)try{if("answer"===e.type){if(this._answerApplied||"stable"===this._pc.signalingState){(0,g.c)("transport","[rtc] duplicate answer ignored"),(0,v.Lq)("switch","rtc duplicate answer ignored");return}if(e.pub&&e.sig&&!await this._verifyHostAnswer(e)){console.error("[rtc] host key verification FAILED — relayed answer rejected"),this._closePeer("host-key-rejected");return}await this._pc.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e.sdp})),this._answerApplied=!0,(0,g.c)("transport","[rtc] answer set"),(0,v.Lq)("switch","rtc answer applied");let t=this._pendingCandidates;for(let e of(this._pendingCandidates=[],t))await this._addRemoteCandidate(e);clearTimeout(this._connectTimer),this.connectDeadline=Date.now()+o.HJ,this._startDeadPathWatch(),this._connectTimer=setTimeout(async()=>{if(this._state!==o.Of.open){try{let e=await this._pc.getStats();e.forEach(t=>{if("candidate-pair"!==t.type)return;let s=e.get(t.localCandidateId),n=e.get(t.remoteCandidateId),r=(s?.address||s?.ip||"?").split(":")[0].slice(-12),a=n?.address||n?.ip||"?";(0,v.Lq)("switch",`pair ${t.state} ${s?.candidateType}:${r}→${n?.candidateType}:${a}`)})}catch{}this._closePeer(`ice-timeout (state=${this._state})`)}},o.HJ)}else if("ice"===e.type){if(!this._answerApplied)return void this._pendingCandidates.push(e);await this._addRemoteCandidate(e)}else"error"===e.type&&((0,g.c)("transport",`[rtc] server error: ${e.message}`),this._closePeer(`server-error:${e.message}`))}catch(e){console.error("[rtc] signal handle error:",e.message)}}async _verifyHostAnswer(e){let t=this._ctx?.auth?.apiKey;if(!t)return!0;let s=(0,M.lz)(t),n=s?.hostPubKey?s:null,r=!!s?.hostSealKey;if((0,g.c)("auth","[seal] verify answer:",{agentSentXpub:!!e.xpub,pinned:!!n,stalePin:!!(s?.hostPubKey&&!r),pendingFp2:(0,M.e1)()}),n){if(n.hostPubKey!==e.pub){let s=(0,M.e1)();return s&&await (0,M.t8)(e.pub,e.xpub)===s?((0,M.LG)(t,{hostPubKey:e.pub,hostSealKey:e.xpub,fp2:s}),(0,g.c)("transport","[rtc] host key re-pinned via fresh pairing fp2"),!0):((0,g.c)("auth","[seal] REJECT answer — pinned pub differs (host key rotated?) and no fresh fp2 to re-pin"),!1)}let s=await (0,M.D5)(e.pub,e.sdp,e.sig);if(!1===s)return(0,g.c)("auth","[seal] REJECT answer — signature invalid (relay tampering?)"),!1;if(null===s){if(!r)return(0,g.c)("auth","[seal] REJECT answer — no Ed25519 in browser and pinned fp2 predates sealing"),!1;let t=await (0,M.t8)(e.pub,e.xpub)===n.fp2;return t||(0,g.c)("auth","[seal] REJECT answer — fp2 fallback mismatch vs pinned",n.fp2),t}return!0}let a=(0,M.e1)();if(a){let s=await (0,M.t8)(e.pub,e.xpub);if(s!==a)return(0,g.c)("auth","[seal] REJECTED — fp2",s,"!= code",a,e.xpub?"":"(agent sent no sealing key — needs the source build)"),(0,M.HY)(),!1;(0,M.LG)(t,{hostPubKey:e.pub,hostSealKey:e.xpub,fp2:s}),(0,g.c)("auth","[seal] pinned via RTC — fp2",s,"sealing key stored"),(0,g.c)("transport","[rtc] host key pinned via pairing fp2")}return!0}natVerdict(){let e=this._localCandidateTypes;return this._everOpened||e.has("relay")?"ok":0===e.size||e.has("srflx")&&(!this._answerApplied||this._iceReachedChecking)?"unknown":"hard"}_cleanupPeer(){for(let e of(clearTimeout(this._connectTimer),this._connectTimer=null,this._stopDeadPathWatch(),this._hbTimer&&(clearInterval(this._hbTimer),this._hbTimer=null),[this._dcControl,this._dcBinary,this._dcFile]))if(e){e.onopen=null,e.onclose=null,e.onerror=null,e.onmessage=null;try{e.close()}catch{}}if(this._dcControl=null,this._dcBinary=null,this._dcFile=null,this._isLoopback=!1,this._typeDetail="dc-stun",this._pc){this._pc.onicecandidate=null,this._pc.oniceconnectionstatechange=null;try{this._pc.close()}catch{}this._pc=null}this._pendingEmit=null,this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=null),this._latestTileTs.clear(),this._reassemble=$()}_receiveTile(e){let t=++z,n=e.byteLength;new Promise(n=>{let r=setTimeout(()=>{I.has(t)&&(I.delete(t),n(null))},8e3),a=P.eR.decodeQueueCap;for(;I.size>=a;){let e=I.keys().next().value,t=I.get(e);if(!t)break;clearTimeout(t.timer),I.delete(e),t.resolve(null)}let l=function(){if(!1===A)return null;if(A)return A;try{A=new Worker(s.tu(new URL(s.p+s.u(3692),s.b)))}catch{return A=!1,null}return A.onmessage=({data:{tiles:e,timestamp:t,id:s,hasBitmap:n,error:r}})=>{L=0;let a=I.get(s);if(!a){if(e)for(let t of e)t.bitmap?.close?.();return}clearTimeout(a.timer),I.delete(s),a.resolve(r?null:{tiles:e,timestamp:t,hasBitmap:n})},A.onerror=e=>{console.error("[Worker] tileDecoder:",e.message),function(){if(A)try{A.terminate()}catch{}for(let{resolve:e}of(A=null,I.values()))try{e(null)}catch{}I.clear()}(),++L>=3&&(A=!1)},A}();if(!l){clearTimeout(r),I.delete(t),n(null);return}I.set(t,{resolve:n,timer:r}),l.postMessage({buffer:e,id:t,v:2},[e])}).then(e=>{if(!e)return;let{tiles:t,timestamp:s,hasBitmap:r}=e;for(let e of(this._pendingEmit||(this._pendingEmit={tiles:new Map,timestamp:s,hasBitmap:r,bytes:0}),this._pendingEmit.bytes+=n,t))s>=(this._latestTileTs.get(e.tileIndex)??0)?(this._latestTileTs.set(e.tileIndex,s),this._pendingEmit.tiles.get(e.tileIndex)?.bitmap?.close?.(),this._pendingEmit.tiles.set(e.tileIndex,e),s>this._pendingEmit.timestamp&&(this._pendingEmit.timestamp=s)):e.bitmap?.close?.();this._flushTimer&&clearTimeout(this._flushTimer),this._flushTimer=setTimeout(()=>{if(this._flushTimer=null,!this._pendingEmit)return;let{tiles:e,timestamp:t,hasBitmap:s,bytes:n}=this._pendingEmit;this._pendingEmit=null;let r=[...e.values()];r.length&&this._emit("message",{event:"tiles-data",data:{tiles:r,timestamp:t,hasBitmap:s,bytes:n,transport:this._typeDetail},source:"rtc"})},0)})}}let O=new Map;function B(e){if(!e?.id)throw Error("Adapter missing static id");O.set(e.id,e)}function W({urls:e,timeoutMs:t,PeerConnection:s}={}){let n=s||("u">typeof RTCPeerConnection?RTCPeerConnection:null);if(!n)return Promise.resolve(null);let r=[{urls:e||o.cx.urls}];return new Promise(e=>{let s,a,l=!1,i=t=>{if(!l){l=!0,clearTimeout(a);try{s.onicecandidate=null,s.close()}catch{}e(t)}};try{s=new n({iceServers:r,iceCandidatePoolSize:0})}catch{return e(null)}a=setTimeout(()=>i(null),t??o.cx.timeoutMs),s.onicecandidate=({candidate:e})=>{var t;if(!e)return i(null);let s=(t=e.candidate)&&t.includes("typ srflx")&&t.split(" ")[4]||null;s&&i(s)};try{s.createDataChannel("probe"),s.createOffer().then(e=>s.setLocalDescription(e)).catch(()=>i(null))}catch{i(null)}})}let K="no-public-ip";function H(e){let t=0,s=!1;for(let n of e.values())"candidate-pair"===n.type&&(n.nominated||n.selected)&&(s=!0,t+=(n.bytesReceived??0)+(n.responsesReceived??0));return s?t:null}function U(e,t){let s=e._adapters.get("rtc"),n=s?._pc;if(!n||"failed"===n.connectionState)return void e._forceRestartRtc(`${t}-pc-failed`);if(e._probeLive?.rtc===s)return void(0,v.Lq)("switch",`${t} probe shared (already measuring this peer)`);clearTimeout(e._resumeProbeTimer);let r=++e._probeToken;e._probeLive={rtc:s,token:r},(async()=>{let t=H(await n.getStats());return null==t||(await new Promise(t=>{e._resumeProbeTimer=setTimeout(t,o.UT)}),r!==e._probeToken)?null:H(await n.getStats())-t})().then(n=>{if(r!==e._probeToken)return;let a=s?.lastInboundAt&&Date.now()-s.lastInboundAt<o.An;null!=n&&n>0||a?(0,v.Lq)("switch",`${t} probe alive (Δ=${n}, recent=${!!a})`):((0,v.Lq)("switch",`${t} probe DEAD (Δ=${n}) → forceRestartRtc`),e._forceRestartRtc(`${t}-probe-dead`))}).catch(()=>{r!==e._probeToken||(s?.lastInboundAt&&Date.now()-s.lastInboundAt<o.An?(0,v.Lq)("switch",`${t} probe error ignored (rtc recently active)`):((0,v.Lq)("switch",`${t} probe error → forceRestartRtc`),e._forceRestartRtc(`${t}-probe-error`)))}).finally(()=>{e._probeLive?.token===r&&(e._probeLive=null)})}function q(e,t){if(t?.type!=="error")return!1;let s=t.message===o.bg.pending?"pending":t.message===o.bg.rejected?"rejected":null;return!!s&&((0,g.c)("transport",`[pm] device ${s} → approval UI`),e._awaitingApproval=!0,e._wsCallbacks.onApproval?.(s),!0)}function V(e){if((0,v.Lq)("switch","signaling ready"),G(e),e._awaitingApproval)return;let t=e._adapters.get("rtc");if(!t){(0,v.Lq)("switch","sig-ready → start rtc (was deferred)"),e._startSecondaryAdapters();return}t.state===o.Of.closed&&((0,v.Lq)("switch","sig-ready → restartRtc (rtc was closed)"),e._restartRtc("sig-ready"))}function X(e,t){!(e._sig?.ready&&e._sig.send(t))&&("offer"===t.type&&(e._sigBuffer=e._sigBuffer.filter(e=>"offer"!==e.type&&"ice"!==e.type)),e._sigBuffer.push(t),e._sigBuffer.length>32&&e._sigBuffer.shift())}function G(e){if(!e._sigBuffer.length)return;let t=e._sigBuffer;for(let s of(e._sigBuffer=[],t))X(e,s)}async function J(e){if(e._auth.tunnelUrl!==window.location.origin)try{(0,g.c)("transport",`[pm] refreshTunnelUrl: fetching from ${f.O}/api/connect`);let t=await fetch(`${f.O}/api/connect`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e._auth.apiKey})});if(!t.ok)return void(0,g.c)("transport",`[pm] refreshTunnelUrl: HTTP ${t.status}`);let s=await t.json();(0,g.c)("transport",`[pm] refreshTunnelUrl: got ${s.tunnelUrl} (was ${e._auth.tunnelUrl})`),s.tunnelUrl&&s.tunnelUrl!==e._auth.tunnelUrl&&(e._auth.tunnelUrl=s.tunnelUrl)}catch(e){(0,g.c)("transport",`[pm] refreshTunnelUrl: error ${e.message}`)}}B(S),B(F);class Y{constructor(e,t){const{profile:s,auth:n,wsCallbacks:r,rtcCallbacks:a,peerId:l}=function(e,t){let s=t?.enableWebRTC?"remoteDesktop":"clientApp",n={...o.j3[s]};t?.enableWebRTC||(n.enabled=["ws"]),t?.enableTurn&&(n.rtc={...n.rtc,enableTurn:!0});let r={tunnelUrl:e.tunnelUrl,localIp:e.localIp,apiKey:e.apiKey,tempKey:e.tempKey,deviceId:e.deviceId,namespace:e.namespace,socketOptions:e.socketOptions},a={onConnect:e.onConnect,onDisconnect:e.onDisconnect,onRetryStatus:e.onRetryStatus,onUrlUpdate:e.onUrlUpdate,onApproval:e.onApproval},l=t?{onUpgrade:t.onUpgrade,onFallback:t.onFallback,onTransportChange:t.onTransportChange}:{},i=`${e.deviceId}:${Math.random().toString(36).slice(2,10)}`;return r.socketOptions?.auth&&(r.socketOptions.auth.peerId=i),{profile:n,auth:r,wsCallbacks:a,rtcCallbacks:l,peerId:i}}(e,t);for(const e of(this._profile=s,this._auth=n,this._wsCallbacks=r,this._rtcCallbacks=a,this._peerId=l,Object.assign(this,{_adapters:new Map,_buffer:[],_pendingAcks:new Map,_ackTimers:new Map,_ackSeq:0,_rtcRestartAttempts:0,_rtcRestartTimer:null,_rtcRestartDueAt:0,_probeAttempts:0,_rtcGivenUp:!1,_giveUpIp:null,_lastStunProbeAt:0,_rejoinDebounceTimer:null,_netFingerprint:null,_awaitingApproval:!1,_ackTimeoutMs:o.QZ.ackTimeoutMs,_hiddenAt:null,_resumeProbeTimer:null,_probeToken:0,_probeLive:null,_connected:!1,_type:"ws",_connectionMode:"tunnel",_lastWsState:null,_rawSocket:null,_onConnectFired:!1,_rtcSignalingHandler:null,_sig:null,_sigDestroyed:!1,_sigBuffer:[],_wsFallbackTimer:null}),this._bus=function(e){let t=new Map,s=(e,s)=>{t.has(e)||t.set(e,[]),t.get(e).push(s)},n=(e,s)=>{let n=t.get(e);if(!n)return;let r=n.findIndex(e=>e===s||e._original===s);-1!==r&&n.splice(r,1)};return{_listeners:t,get connected(){return e._anyAdapterReady()},get id(){return e._rawSocket?.id||null},emit(t,...s){e._sendControl(t,s)},on(e,t){s(e,t)},off(e,t){n(e,t)},once(e,t){let r=(...s)=>{n(e,r),t(...s)};r._original=t,s(e,r)},listeners:e=>[...t.get(e)||[]],dispatch(e,s=[]){let n=t.get(e);if(n?.length){for(let e of[...n])if(n.includes(e))try{e(...s)}catch{}}},clear(){t.clear()},disconnect(){e._rawSocket?.disconnect()}}}(this),this.busRef={current:this._bus},M.IU))this._bus.on(e,t=>(0,M.lu)(this,e,t));this._watchers=function(e){let t=()=>{let t;if((0,v.Lq)("switch",`visibility=${document.visibilityState}`),"visible"!==document.visibilityState)return;let s=e._adapters.get("ws"),n=e._adapters.get("rtc");(0,v.Lq)("switch",`resume check: ws=${s?.ready?"ready":s?.state} rtc=${n?.ready?"ready":n?.state}`);let r=Math.max(s?.lastInboundAt??0,s?.lastMsgAt??0),a=s?.ready&&function({ready:e=!0,lastInboundAt:t=0,now:s}={}){return!!e&&(!t||s-t>=o.Rh)}({ready:!0,lastInboundAt:r,now:Date.now()});if(s){let e=s.lastInboundAt??0,t=s.lastMsgAt??0,n=Date.now();(0,v.Lq)("switch",`zombie check: verdict=${!!a} ready=${!!s.ready} lastPong=${e?`${n-e}ms`:"never"} lastMsg=${t?`${n-t}ms`:"never"}`)}if(a){(0,g.c)("transport","[pm] ws zombie on resume → force reconnect");try{s.forceReconnect?.()}catch{}}if(e._awaitingApproval)return;if(e._rtcGivenUp)return void e._maybeRearmRtc();if(t=e._rtcRestartTimer?Math.max(e._rtcRestartDueAt-Date.now(),0):-1,(0,v.Lq)("switch",`RESET attempts (was ${e._rtcRestartAttempts}) reason=resume pendingIn=${t}ms`),e._rtcRestartAttempts=0,e._probeAttempts=0,t<=o.QZ.backoffMs[0]||((0,v.Lq)("switch",`resume: pending rung was ${t}ms out → re-arm fast`),e._disarmRestart(),e._scheduleRtcRestart("resume-rearm")),!e._canSignal())return void e._sig?.retryNow("resume-no-carrier");let l=n?.state;n&&l!==o.Of.closed&&l!==o.Of.degraded?function(e){let t=e._adapters.get("rtc");if(!t?.ready)return e._restartRtc("resume-not-ready");let s=e._hiddenAt?Date.now()-e._hiddenAt:0;if("function"==typeof matchMedia&&matchMedia("(pointer: coarse)").matches&&s>o.Tr){(0,v.Lq)("switch",`resume: hidden ${Math.round(s/1e3)}s on touch → skip probe, force restart`),(0,g.c)("transport",`[pm] resume: hidden ${Math.round(s/1e3)}s → immediate restart`),e._forceRestartRtc("resume-hidden-touch");return}U(e,"resume")}(e):((0,v.Lq)("switch",`visibility → restartRtc (rtc=${l||"absent"})`),e._restartRtc("resume-dead-rtc"))},s=()=>{if("hidden"===document.visibilityState){e._hiddenAt=Date.now();return}clearTimeout(e._resumeCoalesceTimer),e._resumeCoalesceTimer=setTimeout(t,150)};document.addEventListener("visibilitychange",s);let n=()=>{"visible"===document.visibilityState&&s()},r=()=>{e._hiddenAt=Date.now()};document.addEventListener("resume",n),document.addEventListener("freeze",r);let a=()=>{clearTimeout(e._netDebounceTimer),e._netDebounceTimer=setTimeout(()=>{!1===navigator.onLine?(0,v.Lq)("switch","net-change: still offline → wait"):((0,g.c)("transport","[pm] network change → probe rtc"),(0,v.Lq)("switch",`net-change: online=${navigator.onLine} → kick sig + ws + rtc`),e._sig?.retryNow("net-change"),e.retryNow("net-change"),(0,v.Lq)("switch",`RESET attempts (was ${e._rtcRestartAttempts}) givenUp=${e._rtcGivenUp} reason=net-change`),e._rtcRestartAttempts=0,e._probeAttempts=0,e._rtcGivenUp=!1,e._giveUpIp=null,e._shouldRenegotiate()&&e._restartRtc("net-change"))},o.o_.debounceMs)};return window.addEventListener("online",a),navigator.connection?.addEventListener?.("change",a),{visibilityHandler:s,detach(){document.removeEventListener("visibilitychange",s),document.removeEventListener("resume",n),document.removeEventListener("freeze",r),window.removeEventListener("online",a),navigator.connection?.removeEventListener?.("change",a),clearTimeout(e._netDebounceTimer),e._netDebounceTimer=null,clearTimeout(e._resumeCoalesceTimer),e._resumeCoalesceTimer=null}}}(this)}get type(){return this._type}get connected(){return this._connected}get connectionMode(){return this._connectionMode}get wsBlocked(){return this._adapters.get("ws")?.blocked||!1}setWsBlocked(e){this._adapters.get("ws")?.setBlocked(e)}setUpdating(e){this._adapters.get("ws")?.setUpdating(e)}retryNow(e="user"){let t=this._adapters.get("ws");t?t.retryNow?.(e):((0,v.Lq)("switch",`retryNow by=${e}: no ws adapter → full connect()`),this.connect())}emit(e,...t){this._sendControl(e,t)}sendBinary(e,t){let s=this._pickAdapter(e);return!!s&&s.send(e,t)}connect(){this._sigDestroyed=!1;let e=this._profile.enabled.includes("rtc");e&&this._initSignalingClient(),e&&(this._canSignal()?this._startSecondaryAdapters():((0,v.Lq)("switch","rtc deferred — waiting for signaling relay"),clearTimeout(this._rtcDeferTimer),this._rtcDeferTimer=setTimeout(()=>{this._sigDestroyed||this._adapters.has("rtc")||((0,v.Lq)("switch","rtc defer expired → start anyway"),this._startSecondaryAdapters())},o.BF))),this._startWsFallback(),(0,g.c)("transport","[pm] connect: RTC + WS parallel (RTC preferred, WS warm standby)."),(0,v.Lq)("switch","connect: RTC + WS parallel")}async _startWsFallback(){if(!(this._adapters.has("ws")||this._sigDestroyed||this._adapters.get("rtc")?.isLoopback)){if((0,v.Lq)("switch","ws-fallback: start (refresh url)"),await this._refreshTunnelUrl(),this._adapters.has("ws")||this._sigDestroyed||this._adapters.get("rtc")?.isLoopback)return void(0,v.Lq)("switch","ws-fallback: aborted (destroyed, loopback or already attached)");(0,v.Lq)("switch","ws-fallback: connecting"),this._instantiate("ws"),this._adapters.get("ws")?.connect(this._buildCtx("ws"))}}async _refreshTunnelUrl(){return J(this)}_initSignalingClient(){!function(e){if(!o.gI.enabled||e._sig||e._sigDestroyed||!e._auth.deviceId||!e._auth.apiKey)return;let t=f.O.replace(/^http/,"ws")+"/signaling";s.e(6739).then(s.bind(s,46739)).then(({SignalingClient:s})=>{e._sig||e._sigDestroyed||(e._sig=new s({url:t,role:"client",roomId:e._auth.apiKey,apiKey:e._auth.apiKey,from:e._peerId,onReady:()=>V(e),pingMs:o.gI.pingMs}),e._sig.on(t=>{if("error"===t.type&&"rtc-disabled"===t.message){e._rtcTestDisabled=!0,(0,v.Lq)("switch","rtc-disabled by agent → stop RTC retry (use WS)");return}q(e,t)||e._rtcSignalingHandler?.(t)}),e._sig.connect())}).catch(e=>(0,g.c)("transport",`[pm] SignalingClient load failed: ${e?.message||e}`))}(this)}_instantiate(e){if(this._adapters.has(e))return;let t=O.get(e);if(!t)return;let s=new t;s.on("stateChange",t=>this._onAdapterStateChange(e,t)),s.on("message",({event:e,data:t,source:s})=>this._dispatch(e,t,s)),s.on("binary",e=>this._onBinary(e)),"rtc"===e&&(s.on("netFingerprint",e=>this._onNetFingerprint(e)),this._srvCaps&&s.setPeerCaps?.(this._srvCaps)),this._adapters.set(e,s)}_onNetFingerprint(e){if(!e||e===this._netFingerprint)return;let t=this._netFingerprint;this._netFingerprint=e,t&&(0,g.c)("transport",`[pm] net fingerprint ${t}→${e} (same network — no backoff reset)`)}_maybeRearmRtc(){if(!this._rtcGivenUp)return;let e=Date.now();e-this._lastStunProbeAt<o.cx.minIntervalMs||(this._lastStunProbeAt=e,W().then(e=>{var t;if(this._sigDestroyed||!this._rtcGivenUp)return;let s=e||(this._giveUpIp===K?K:null);(t=this._giveUpIp,s&&(!t||s!==t))?((0,v.Lq)("switch",`rearm check: ip ${this._giveUpIp||"unknown"}→${s} changed → re-arm RTC`),(0,g.c)("transport","[pm] public ip changed → re-arm rtc"),this._rtcGivenUp=!1,this._giveUpIp=null,this._probeAttempts=0,this._rtcRestartAttempts=0,this._netFingerprint=e,this._canSignal())?this._shouldRenegotiate()&&this._restartRtc("stun-rearm"):this._sig?.retryNow("stun-rearm"):(0,v.Lq)("switch",`rearm check: ip=${s||"unknown"} same as give-up → stay WS-only`)}).catch(()=>{}))}_startSecondaryAdapters(){for(let e of((0,g.c)("transport",`[pm] startSecondary enabled=${this._profile.enabled}`),(0,g.c)("transport",`[pm] startSecondary rtcTestDisabled=${!!this._rtcTestDisabled}`),this._profile.enabled))"ws"!==e&&("rtc"!==e||!this._rtcTestDisabled)&&(this._adapters.has(e)||((0,g.c)("transport",`[pm] start adapter ${e}`),this._instantiate(e),this._adapters.get(e)?.connect(this._buildCtx(e))))}_handleApprovalSignal(e){return q(this,e)}_onSignalingReady(){V(this)}_canSignal(){return!!this._sig?.ready}_shouldRenegotiate(){return!this._awaitingApproval&&this._canSignal()}_restartRtc(e="?"){(0,v.Lq)("switch",`restartRtc CALLED by=${e} attempts=${this._rtcRestartAttempts}`);let t=this._adapters.get("rtc"),s=function({testDisabled:e,givenUp:t,rtcState:s,hasRtc:n}){return e?"skip-test-disabled":t?"skip-given-up":n&&(s===o.Of.connecting||s===o.Of.open)?"skip-in-flight":n?"restart":"start-fresh"}({testDisabled:!!this._rtcTestDisabled,givenUp:this._rtcGivenUp,rtcState:t?.state,hasRtc:!!t});if("skip-test-disabled"===s)return void(0,v.Lq)("switch","restartRtc skipped (rtcTestDisabled)");if("skip-given-up"===s)return void(0,v.Lq)("switch","restartRtc skipped (hard NAT → WS-only)");if("skip-in-flight"===s)return void(0,v.Lq)("switch",`restartRtc skipped (rtc=${t.state})`);if("start-fresh"===s){(0,v.Lq)("switch","restartRtc: no rtc → startSecondary"),this._startSecondaryAdapters();return}(0,v.Lq)("switch","restartRtc: tear down + renegotiate"),(0,g.c)("transport","[pm] ws reconnected → restart rtc");try{t.disconnect(`restart:${e}`)}catch{}this._adapters.delete("rtc"),this._rtcSignalingHandler=null,this._startSecondaryAdapters()}_forceRestartRtc(e="?"){(0,v.Lq)("switch",`forceRestartRtc CALLED by=${e}`);let t=this._adapters.get("rtc");if(t){try{t.disconnect(`force:${e}`)}catch{}this._adapters.delete("rtc"),this._rtcSignalingHandler=null}this._rtcGivenUp?(0,v.Lq)("switch","forceRestartRtc: torn down, no renegotiate (hard NAT)"):this._startSecondaryAdapters()}disconnect(){this._watchers?.detach(),this._watchers=null,clearTimeout(this._resumeProbeTimer),this._resumeProbeTimer=null,clearTimeout(this._rtcDeferTimer),this._rtcDeferTimer=null,this._probeToken++;try{this._sig?.disconnect()}catch{}for(let e of(this._sig=null,this._sigDestroyed=!0,this._sigBuffer=[],clearTimeout(this._wsFallbackTimer),clearTimeout(this._rejoinDebounceTimer),this._rejoinDebounceTimer=null,this._adapters.values()))try{e.disconnect("pm-disconnect")}catch{}for(let e of(this._adapters.clear(),this._bus.clear(),this._buffer=[],this._connected=!1,this._rawSocket=null,this._disarmRestart(),(0,v.Lq)("switch",`RESET attempts (was ${this._rtcRestartAttempts}) reason=pm-disconnect`),this._rtcRestartAttempts=0,this._probeAttempts=0,this._rtcGivenUp=!1,this._giveUpIp=null,this._lastStunProbeAt=0,this._ackTimers.values()))clearTimeout(e);this._ackTimers.clear()}_buildCtx(e,t){let s={auth:this._auth,profile:this._profile};return"ws"===e&&(s.onRetryStatus=this._wsCallbacks.onRetryStatus,s.onUrlUpdate=e=>{e.tunnelUrl&&(this._auth.tunnelUrl=e.tunnelUrl),void 0!==e.localIp&&(this._auth.localIp=e.localIp),this._wsCallbacks.onUrlUpdate?.(e)}),"rtc"===e&&(s.signaling={send:e=>this._sendSignaling(e),on:e=>{this._rtcSignalingHandler=e},off:()=>{this._rtcSignalingHandler=null}}),s}_onAdapterStateChange(e,t){(0,g.c)("transport",`[pm] ${e} state=${t}`),("rtc"!==e||t!==o.Of.closed)&&(0,v.Lq)("switch",`${e}→${t}`),"ws"===e&&function(e,t){let s=e._adapters.get("ws");if(t===o.Of.open){let t=e._lastWsState===o.Of.degraded;e._connected=!0,e._connectionMode=s?.connectionMode||"tunnel",e._rawSocket=s?.socket||null,t&&e._maybeFireRejoin("ws","ws reconnect while rtc ready"),e._lastWsState!==o.Of.open&&(e._onConnectFired?e._wsCallbacks.onUrlUpdate?.({}):(e._onConnectFired=!0,(0,v.Lq)("switch",`onConnect FIRE (ws, mode=${e._connectionMode})`),e._wsCallbacks.onConnect?.(e._bus,e._connectionMode)))}else e._rawSocket=null,e._lastWsState===o.Of.open&&((0,v.Lq)("switch","ws down"),e._anyAdapterReady()&&(0,v.Lq)("switch","ws down but rtc alive → skip onDisconnect"));e._lastWsState=t}(this,t),"rtc"===e&&function(e,t){if(t===o.Of.open){let t=e._onConnectFired;clearTimeout(e._wsFallbackTimer),e._rtcCallbacks.onUpgrade?.(e._adapters.get("rtc")?.typeDetail||"dc-stun"),e._onConnectFired||(e._onConnectFired=!0,e._connected=!0,e._connectionMode="webrtc",(0,v.Lq)("switch","onConnect FIRE (rtc, mode=webrtc)"),e._wsCallbacks.onConnect?.(e._bus,e._connectionMode)),(0,v.Lq)("switch",`RESET attempts (was ${e._rtcRestartAttempts}) reason=rtc-open`),e._rtcRestartAttempts=0,e._probeAttempts=0,e._rtcGivenUp=!1,e._giveUpIp=null,e._disarmRestart(),clearTimeout(e._rejoinDebounceTimer),e._rejoinDebounceTimer=null;let s=e._adapters.get("rtc");if(s?.isLoopback){(0,v.Lq)("switch","rtc loopback detected (same machine) → drop ws standby");let t=e._adapters.get("ws");if(t){try{t.disconnect()}catch{}e._adapters.delete("ws")}}t&&e._maybeFireRejoin("rtc","rtc reconnect while ws ready")}if(t===o.Of.closed){for(let t of(e._rtcCallbacks.onFallback?.("ws"),(0,v.Lq)("switch","rtc closed → startWsFallback + scheduleRtcRestart"),e._startWsFallback(),clearTimeout(e._wsFallbackTimer),e._pendingAcks.values()))try{t({error:"rtc-closed"})}catch{}for(let t of(e._pendingAcks.clear(),e._ackTimers.values()))clearTimeout(t);e._ackTimers.clear(),e._scheduleRtcRestart("rtc-closed")}}(this,t),"rtc"===e&&t===o.Of.open&&((0,g.c)("auth","[seal] rtc OPEN → sending proof"),(0,M.pV)(this)),this._recomputeType();let s=this._anyAdapterReady();s!==this._connected&&(this._connected=s,s||(this._onConnectFired=!1,(0,v.Lq)("switch",`onDisconnect FIRE (last carrier gone: ${e}→${t})`),this._wsCallbacks.onDisconnect?.(`${e}-${t}`))),this._flushBuffer()}_maybeFireRejoin(e,t){let s="ws"===e?this._adapters.get("rtc"):this._adapters.get("ws");if(s?.ready){(0,g.c)("transport",`[pm] ${t} → skip rejoin (other ready)`),(0,v.Lq)("switch",`${t} → skip rejoin (other ready)`);return}if("ws"===e&&s&&s.state===o.Of.connecting){(0,g.c)("transport",`[pm] ${t} → debounce rejoin (rtc connecting)`),(0,v.Lq)("switch",`${t} → debounce rejoin ${o.ZN}ms (rtc connecting)`),clearTimeout(this._rejoinDebounceTimer),this._rejoinDebounceTimer=setTimeout(()=>{this._rejoinDebounceTimer=null;let e=this._adapters.get("rtc");e?.ready?(0,v.Lq)("switch","debounce: rtc opened → skip rejoin"):((0,v.Lq)("switch",`debounce expired → FIRE rejoin (rtc=${e?.state||"absent"})`),this._bus.dispatch("connect",[]))},o.ZN);return}(0,v.Lq)("switch",`${t} → FIRE rejoin`),this._bus.dispatch("connect",[])}_recomputeType(){let e=this._pickAdapter(o.l_.binary)||this._pickAdapter(o.l_.control),t=e&&"rtc"===e.constructor.id?e.typeDetail||"dc-stun":"ws";t!==this._type&&(this._type=t,this._rtcCallbacks.onTransportChange?.(t))}_anyAdapterReady(){for(let e of this._adapters.values())if(e.ready)return!0;return!1}_pickAdapter(e){return function(e,t,s){let n=t.channels[s];if(!n)return null;let r=[...e.values()].filter(e=>e.supports(s)&&e.ready);return r.length?(r.sort((e,t)=>{let r=t.getPriority?t.getPriority(s):t.constructor.priority[s]??0,a=e.getPriority?e.getPriority(s):e.constructor.priority[s]??0;if(r!==a)return r-a;if(n.prefer){if(t.constructor.id===n.prefer)return 1;if(e.constructor.id===n.prefer)return -1}return 0}),r[0]||null):null}(this._adapters,this._profile,e)}_sendControl(e,t){!function(e,t,s){let n="function"==typeof s[s.length-1]?s.pop():null,r=e._pickAdapter(o.l_.control);if(!r){(0,g.c)("transport",`[pm] buffer event=${t} (no adapter ready)`),(0,v.Lq)("switch",`buffer "${t}" (no adapter)`),e._buffer.push({event:t,args:s,cb:n});return}if((0,g.c)("transport",`[pm] send control event=${t} via=${r.constructor.id}`),"rtc"===r.constructor.id){let a=null;if(n&&(a=`c_${++e._ackSeq}`,e._pendingAcks.set(a,n),e._scheduleAckTimeout(a,{event:t,args:s})),!r.send(o.l_.control,{event:t,args:s,ackId:a})){let l=e._pickAdapter(o.l_.control);if(l&&l!==r&&l.send(o.l_.control,n?{event:t,args:s,ackId:a,cb:n}:{event:t,args:s,ackId:a}))return;(0,g.c)("transport",`[pm] rtc refused event=${t} → buffered`),e._buffer.push({event:t,args:s,cb:n})}}else r.send(o.l_.control,{event:t,args:s,cb:n})}(this,e,t)}_flushBuffer(){!function(e){if(!e._buffer.length)return;let t=e._pickAdapter(o.l_.control);if(!t)return;let s=e._buffer.splice(0);for(let{event:n,args:r,cb:a}of((0,g.c)("transport",`[pm] flush ${s.length} buffered via=${t.constructor.id}`),s))e._sendControl(n,a?[...r,a]:r)}(this)}_dispatch(e,t,s){!function(e,t,s,n){if("srvCaps"===t){let t="rtc"===n?s?.args?.[0]:s;(0,g.c)("transport",`[pm] srvCaps from agent via ${n}: ${JSON.stringify(t)}`),e._srvCaps=t||{},e._adapters.get("rtc")?.setPeerCaps?.(e._srvCaps)}if("__ack"===t){let{ackId:t,args:n}=s||{},r=e._pendingAcks.get(t);if(r){e._pendingAcks.delete(t);let s=e._ackTimers.get(t);s&&(clearTimeout(s),e._ackTimers.delete(t)),r(...n||[])}return}if("device:approved"===t){e._awaitingApproval=!1;let t=e._adapters.get("rtc");e._canSignal()&&(!t||t.state===o.Of.closed)&&e._restartRtc("device-approved")}if("rtc:enabled"===t){e._rtcTestDisabled&&(e._rtcTestDisabled=!1,(0,v.Lq)("switch","rtc:enabled by agent → clear flag + restart RTC"),e._restartRtc("rtc-enabled"));return}if("tunnel:updated"===t){let t="rtc"===n?s?.args?.[0]:s;if(t){let{tunnelUrl:s,localIp:n,status:r}=t;if(e._auth.tunnelUrl===window.location?.origin)return(0,v.Lq)("switch",`tunnel:updated ignored (carrier is the page origin; got url=${s||"none"})`);if((0,v.Lq)("switch",`tunnel:updated recv (status=${r} url=${s||"none"})`),"ready"===r&&s){let t=e._auth.tunnelUrl!==s;e._auth.tunnelUrl=s,n&&(e._auth.localIp=n),e._wsCallbacks.onUrlUpdate?.({tunnelUrl:s,localIp:n});let r=e._adapters.get("ws");if(r&&(!r.ready||t)){(0,v.Lq)("switch",`tunnel:updated → ${t?"url changed":"ws not ready"} → retry ws with new URL`);try{r.retryNow("tunnel-updated")}catch{}}}else"down"===r&&(e._auth.tunnelUrl="",e._wsCallbacks.onUrlUpdate?.({tunnelUrl:"",localIp:n}))}return}let r="rtc"===n&&Array.isArray(s?.args)?s.args:[s];e._bus?.dispatch(t,r)}(this,e,t,s)}_onBinary(e){e&&"file"===e.channel&&this._bus?.dispatch("file-bin",[e.buffer])}_scheduleAckTimeout(e){var t;let s;t=this,s=setTimeout(()=>{t._ackTimers.delete(e),(0,g.c)("transport",`[pm] ack timeout ackId=${e} event=undefined → suspect zombie RTC`);let s=t._pendingAcks.get(e),n=t._adapters.get("rtc");t._adapters.get("ws");let r=Date.now(),a=n?.lastInboundAt||0;n?.ready&&a&&r-a<o.An?(0,v.Lq)("switch",`ack-timeout ? ignored (rtc active, lastInbound=${r-a}ms ago)`):n?.state===o.Of.open?U(t,"ack-timeout:?"):t._scheduleRtcRestart("ack-timeout")},t._ackTimeoutMs),t._ackTimers.set(e,s)}_armRestart(e,t){clearTimeout(this._rtcRestartTimer),this._rtcRestartDueAt=Date.now()+t,this._rtcRestartTimer=setTimeout(e,t)}_disarmRestart(){let e=this._rtcRestartTimer?Math.max(this._rtcRestartDueAt-Date.now(),0):-1;return clearTimeout(this._rtcRestartTimer),this._rtcRestartTimer=null,this._rtcRestartDueAt=0,e}_scheduleRtcRestart(e="?"){if((0,v.Lq)("switch",`rtcRestart REQ by=${e} attempts=${this._rtcRestartAttempts} probe=${this._probeAttempts} givenUp=${this._rtcGivenUp} pending=${!!this._rtcRestartTimer}`),this._rtcRestartTimer){let t=Math.max(this._rtcRestartDueAt-Date.now(),0);(0,v.Lq)("switch",`rtcRestart SKIP by=${e} (pending rung ${this._rtcRestartAttempts} fires in ${t}ms)`);return}if(this._rtcGivenUp){(0,v.Lq)("switch","scheduleRtcRestart skipped (hard NAT → WS-only)"),(0,g.c)("transport","[pm] rtc probe skipped (given up — hard NAT)");return}let t=function({attempts:e,probeAttempts:t,verdict:s}){let n,r,a=e>=o.QZ.maxAttempts,l=t;if(a){if(n=o.QZ.probeBackoffMs[t]??o.QZ.probeBackoffMs.at(-1),(l=t+1)>=o.QZ.classifyAfterProbes){if("hard"===(r=s?.()??"unknown"))return{giveUp:!0,verdict:r,probeAttempts:l};l=0}}else n=o.QZ.backoffMs[e]??o.QZ.backoffMs.at(-1);return{delay:n,isProbe:a,attempts:e+1,probeAttempts:l,verdict:r}}({attempts:this._rtcRestartAttempts,probeAttempts:this._probeAttempts,verdict:()=>this._adapters.get("rtc")?.natVerdict?.()??"unknown"});if(void 0!==t.verdict&&((0,v.Lq)("switch",`scheduleRtcRestart natVerdict=${t.verdict} probeAttempts=${t.probeAttempts}`),(0,g.c)("transport",`[pm] rtc nat verdict=${t.verdict} after ${t.probeAttempts} probes`)),t.giveUp){this._probeAttempts=t.probeAttempts,this._rtcGivenUp=!0,this._giveUpIp=this._netFingerprint,this._giveUpIp||W().then(e=>{this._rtcGivenUp&&!this._giveUpIp&&(this._giveUpIp=e||K,(0,v.Lq)("switch",`give-up baseline from probe: ip=${this._giveUpIp}`))}).catch(()=>{}),(0,v.Lq)("switch",`RTC give-up: hard NAT → WS-only (ip=${this._giveUpIp||"pending"})`);return}let{delay:s,isProbe:n}=t;this._probeAttempts=t.probeAttempts,this._rtcRestartAttempts=t.attempts,(0,v.Lq)("switch",`rtcRestart ARM by=${e} rung=${this._rtcRestartAttempts} delay=${s}ms probe=${n}`),(0,g.c)("transport",`[pm] schedule rtc ${n?"probe":"restart"} #${this._rtcRestartAttempts} in ${s}ms`);let r=()=>{if(this._disarmRestart(),this._awaitingApproval||!this._sig?.ready)return;let e=this._adapters.get("rtc");if(e){let t=function({state:e,connectingSince:t,connectDeadline:s,now:n,connectTimeoutMs:r}){return e!==o.Of.connecting?"restart":n<function({connectingSince:e,connectDeadline:t,connectTimeoutMs:s}){return t??(e??0)+s}({connectingSince:t,connectDeadline:s,connectTimeoutMs:r})?"wait":"teardown"}({state:e.state,connectingSince:e.connectingSince,connectDeadline:e.connectDeadline,now:Date.now(),connectTimeoutMs:o.AC});if("wait"===t){let t=Math.max(function({connectingSince:e,connectDeadline:t,connectTimeoutMs:s}){return t??(e??0)+s}({connectingSince:e.connectingSince,connectDeadline:e.connectDeadline,connectTimeoutMs:o.AC})-Date.now(),s);(0,v.Lq)("switch",`restart tick: peer still young (rung ${this._rtcRestartAttempts}) → re-arm in ${t}ms, no rung spent`),this._armRestart(r,t);return}if("teardown"===t){try{e.disconnect(`rung-${this._rtcRestartAttempts}-teardown`)}catch{}this._adapters.delete("rtc"),this._rtcSignalingHandler=null}}this._restartRtc(`rung-${this._rtcRestartAttempts}`)};this._armRestart(r,s)}_sendSignaling(e){X(this,e)}_flushSigBuffer(){G(this)}}var Z=s(2074);let Q=(0,Z.v)(e=>({bus:null,busRef:{current:null},protocolRef:{current:null},connected:!1,connectionMode:"tunnel",carrier:"ws",endpoint:null,retryStatus:{isRetrying:!1,attempt:0,maxAttempts:10,failed:!1},setConnection:t=>e(e=>({...e,...t})),setConnected:t=>e({connected:t}),setCarrier:t=>e({carrier:t}),setConnectionMode:t=>e({connectionMode:t}),setRetryStatus:t=>e({retryStatus:t}),reset:()=>e({bus:null,connected:!1,connectionMode:"tunnel",carrier:"ws",endpoint:null,retryStatus:{isRetrying:!1,attempt:0,maxAttempts:10,failed:!1}})}));var ee=s(2805),et=s(11155),es=s(11472);let en=["git status","git add .",'git commit -m ""',"git push","git pull","git fetch","git diff","git log --oneline","git branch","git checkout","git checkout -b","git switch","git stash","git stash pop","git merge","git rebase","git clone","git remote -v","git restore","npm install","npm ci","npm run dev","npm run build","npm run test","npm run lint","npm outdated","pnpm install","pnpm dev","yarn dev","bun install","cd ..","cd ~","cd -","ls -la","ll","mkdir -p","cp -r","find . -name","du -sh","chmod +x","ln -s","grep -rn","grep -i","wc -l","tail -f","ps aux","df -h","free -h","lsof -i","netstat -tlnp","docker ps","docker ps -a","docker images","docker logs -f","docker exec -it","docker compose up -d","docker compose down","docker build -t","code .","claude","claude --continue","claude --resume","claude --dangerously-skip-permissions","claude mcp","codex","codex --full-auto"],er={min:400,max:1/0},ea={default:190,min:180,max:1/0},el={default:190,min:190,max:1/0},ei={default:420,min:280,max:1/0},eo=[{id:"remote",labelKey:"menu.remoteDesktop",group:"header"},{id:"mobile",labelKey:"mobile.androidDevice",group:"header"},{id:"sites",labelKey:"menu.sites",group:"header"},{id:"notifications",labelKey:"menu.notificationsButton",group:"header"},{id:"folder",labelKey:"menu.showFolder",group:"pane",storeKey:"showFolderButton",setterKey:"setShowFolderButton"},{id:"note",labelKey:"menu.showNote",group:"pane",storeKey:"showNoteButton",setterKey:"setShowNoteButton"}],ec=[{group:"header",titleKey:"menu.headerButtons"},{group:"pane",titleKey:"menu.showButtons"}],ed={default:300,min:240,max:1/0},eu=300,em=240,ex=900,ep=620,eh=320,ef={Escape:{data:"\x1b"},c:{ctrl:!0,data:"\x03",requireNoSelection:!0},d:{ctrl:!0,data:"\x04"},z:{ctrl:!0,data:"\x1a"},l:{ctrl:!0,data:"\f"}},eb=["check again","continue","summarize"],eg="terminal:noteSync",ev="terminal:openSession",ey={cursorBlink:!0,fontSize:12,fontSizeMobile:12,fontFamily:'ui-monospace, "SF Mono", "Cascadia Code", "Roboto Mono", "Noto Sans Mono", Menlo, Monaco, "Courier New", monospace',scrollback:15e3,convertEol:!0,allowProposedApi:!0,scrollOnUserInput:!0,fastScrollModifier:"none",smoothScrollDuration:0,rescaleOverlappingGlyphs:!0,minimumContrastRatio:4.5,macOptionIsMeta:!0};function ew(e){return null!=e?e:window.innerWidth<768?ey.fontSizeMobile:ey.fontSize}let ek="16,16,20",ej="116,120,136",eN={min:.3,max:.95,step:.01},eS={none:{label:"None"},art1:{label:"Anime 1",src:"/backgrounds/bg9.jpg"},art2:{label:"Anime 2",src:"/backgrounds/bg2.jpg"},art3:{label:"Anime 3",src:"/backgrounds/bg3.jpg"},art4:{label:"Anime 4",src:"/backgrounds/bg4.jpg"},art5:{label:"Anime 5",src:"/backgrounds/bg5.jpg"},art7:{label:"Anime 7",src:"/backgrounds/bg7.jpg"},art8:{label:"Anime 8",src:"/backgrounds/bg8.jpg"},art9:{label:"Anime 9",src:"/backgrounds/bg10.jpg"},art10:{label:"Anime 10",src:"/backgrounds/bg11.jpg"},art11:{label:"Anime 11",src:"/backgrounds/bg12.jpg"},art12:{label:"Anime 12",src:"/backgrounds/bg13.jpg"}};function eC(e,t){return e&&t&&"none"!==t&&(eS[t]||String(t).startsWith("custom"))?{...e,background:"#10101400"}:e}function eT(e){return"custom"===e?"custom":"string"==typeof e&&e.startsWith("custom:")?e.slice(7):null}function eR(e,t=[]){let s=eT(e);return s?t.find(e=>e?.id===s)?.dataUrl||null:eS[e]?.src||null}function eE(e){return eS[e]?.label||(eT(e)?"Custom":eS.none.label)}function e_(e,t=[]){return Array.isArray(e)?e.filter(e=>{let s=eT(e);return s?t.some(e=>e?.id===s):"none"===e||!!eS[e]}):[]}function e$(e,t,s=[],n=0){var r;return e_([e],s)[0]||(r=e_(t,s),Array.isArray(r)&&0!==r.length&&r[n%r.length]||"none")}let eM=/[A-Za-z0-9._\-/~:@]/,eP={verbs:["cd","ls","ll","cat","less","more","head","tail","vim","nvim","nano","bat","code","code-insiders","rm","cp","mv","mkdir","touch","chmod","open","grep"],ttlMs:3e5,debounceMs:120,maxDirs:20,maxResults:8},eA=[{id:"ctrl",label:"Ctrl",key:"Ctrl",type:"modifier"},{id:"opt",label:"Opt",key:"Alt",type:"modifier"},{id:"shift",label:"Shift",key:"Shift",type:"modifier"},{id:"meta",label:"⌘",key:"Meta",type:"modifier"},{id:"esc",label:"Esc",key:"Escape",type:"key"},{id:"tab",label:"Tab",key:"Tab",type:"key"},{id:"enter",label:"↵",key:"Enter",type:"key"},{id:"backspace",label:"⌫",key:"Backspace",type:"key"},{id:"up",label:"↑",key:"ArrowUp",type:"arrow"},{id:"down",label:"↓",key:"ArrowDown",type:"arrow"},{id:"left",label:"←",key:"ArrowLeft",type:"arrow"},{id:"right",label:"→",key:"ArrowRight",type:"arrow"},{id:"home",label:"Home",key:"Home",type:"key"},{id:"end",label:"End",key:"End",type:"key"},{id:"pgup",label:"PgUp",key:"PageUp",type:"key"},{id:"pgdn",label:"PgDn",key:"PageDown",type:"key"},{id:"del",label:"Del",key:"Delete",type:"key"},{id:"ins",label:"Ins",key:"Insert",type:"key"},{id:"ctrlA",label:"^A",key:"a",type:"ctrl"},{id:"ctrlC",label:"^C",key:"c",type:"ctrl"},{id:"ctrlD",label:"^D",key:"d",type:"ctrl"},{id:"ctrlE",label:"^E",key:"e",type:"ctrl"},{id:"ctrlK",label:"^K",key:"k",type:"ctrl"},{id:"ctrlL",label:"^L",key:"l",type:"ctrl"},{id:"ctrlN",label:"^N",key:"n",type:"ctrl"},{id:"ctrlP",label:"^P",key:"p",type:"ctrl"},{id:"ctrlR",label:"^R",key:"r",type:"ctrl"},{id:"ctrlT",label:"^T",key:"t",type:"ctrl"},{id:"ctrlU",label:"^U",key:"u",type:"ctrl"},{id:"ctrlW",label:"^W",key:"w",type:"ctrl"},{id:"ctrlX",label:"^X",key:"x",type:"ctrl"},{id:"ctrlY",label:"^Y",key:"y",type:"ctrl"},{id:"ctrlZ",label:"^Z",key:"z",type:"ctrl"},{id:"f1",label:"F1",key:"F1",type:"key"},{id:"f2",label:"F2",key:"F2",type:"key"},{id:"f3",label:"F3",key:"F3",type:"key"},{id:"f4",label:"F4",key:"F4",type:"key"},{id:"f5",label:"F5",key:"F5",type:"key"},{id:"f6",label:"F6",key:"F6",type:"key"},{id:"f7",label:"F7",key:"F7",type:"key"},{id:"f8",label:"F8",key:"F8",type:"key"},{id:"f9",label:"F9",key:"F9",type:"key"},{id:"f10",label:"F10",key:"F10",type:"key"},{id:"f11",label:"F11",key:"F11",type:"key"},{id:"f12",label:"F12",key:"F12",type:"key"},{id:"pipe",label:"|",key:"|",type:"key"},{id:"tilde",label:"~",key:"~",type:"key"},{id:"slash",label:"/",key:"/",type:"key"},{id:"backslash",label:"\\",key:"\\",type:"key"},{id:"dash",label:"-",key:"-",type:"key"},{id:"underscore",label:"_",key:"_",type:"key"}],ez=["esc","up","down","ctrlC","ctrl","opt","shift","tab","slash"],eI="enter",eL=[["left","right","home","end","pgup","pgdn","del"],["ctrlZ","ctrlR","ctrlL","ctrlA","ctrlE","ctrlW","ctrlD"],["f1","f2","f3","f4","f5","f10","f11"]],eD="bg-brand-500 text-white shadow-sm",eF="bg-brand-500/15 hover:bg-brand-500/25 text-brand-400",eO={minWidth:"34px",height:"32px",paddingLeft:"6px",paddingRight:"6px"},eB={minWidth:"38px",height:"32px",paddingLeft:"8px",paddingRight:"8px"},eW=["main","master"],eK={DELAY_MS:400,GAP_PX:6,EDGE_PX:8,MAX_WIDTH_PX:320,EST_HEIGHT_PX:48,SLACK_PX:.5},eH="/workspace",eU={list:()=>eH,terminal:e=>`${eH}/terminal/${encodeURIComponent(e.sessionId||"")}`,files:e=>eX(`${eH}/files`,{ws:e.workspace,p:e.currentPath}),editor:e=>eX(`${eH}/editor`,{path:e.path,line:e.line,col:e.column}),git:e=>eX(`${eH}/git`,{ws:e.workspace}),remote:()=>`${eH}/remote`,mobile:()=>`${eH}/mobile`,workspaces:()=>`${eH}/workspaces`,browse:e=>eX(`${eH}/browse`,{path:e.path})},eq=["site"],eV={"":"list",terminal:"terminal",files:"files",editor:"editor",git:"git",remote:"remote",mobile:"mobile",workspaces:"workspaces",browse:"browse"};function eX(e,t){let s=Object.entries(t).filter(([,e])=>null!=e&&""!==e).map(([e,t])=>`${e}=${encodeURIComponent(t)}`).join("&");return s?`${e}?${s}`:e}function eG(e,t){if(!e?.startsWith(eH))return null;let[s,n]=e.slice(eH.length).replace(/^\//,"").split("/"),r=eV[s||""];if(!r)return null;let a=e=>t?.get(e)||void 0;switch(r){case"terminal":return{type:r,sessionId:n?decodeURIComponent(n):void 0};case"files":return{type:r,workspace:a("ws"),currentPath:a("p")};case"editor":return{type:r,path:a("path"),line:eY(a("line")),column:eY(a("col"))};case"git":return{type:r,workspace:a("ws")};case"browse":return{type:r,path:a("path")};default:return{type:r}}}function eJ(e){return(eU[e?.type]||eU.list)(e)}function eY(e){let t=Number(e);return Number.isFinite(t)?t:void 0}let eZ="__ungrouped__",eQ=e=>e?.workspaceId??e?.groupId??null;function e0({container:e,pane:t}){if(!e||!t||t.offsetWidth<=0)return null;let s=t.getBoundingClientRect().left-e.getBoundingClientRect().left;return Math.max(0,Math.min(e.scrollLeft+s-(e.clientWidth-t.offsetWidth)/2,e.scrollWidth-e.clientWidth))}let e1=(e,{min:t,max:s})=>Math.max(t,Math.min(s,Math.round(e))),e2=e=>"string"==typeof e?e.replace(/\\/g,"/"):e,e5=new Set(["path","currentPath","parentPath","dirPath","filePath","repoPath","oldPath","newPath","fullPath","relativePath"]),e3=[".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svg",".avif",".apng",".tif",".tiff",".heic",".heif"],e4=[".mp4",".m4v",".webm",".ogv",".mov",".mkv",".avi",".3gp"],e6=[".mp3",".wav",".ogg",".oga",".flac",".m4a",".aac",".opus"],e8=[".pdf"],e9=[".docx"],e7=[".xlsx",".xls",".csv",".tsv"],te=[".html",".htm",".xhtml"],tt=[".mmd",".mermaid"],ts=[".md",".markdown",".mdx"];function tn(e,t){if(!e)return!1;let s=e.toLowerCase();return t.some(e=>s.endsWith(e))}function tr(e){return e?tn(e,te)?"html":tn(e,ts)?"markdown":tn(e,tt)?"mermaid":null:null}let ta={".js":"javascript",".jsx":"javascript",".ts":"javascript",".tsx":"javascript",".mjs":"javascript",".cjs":"javascript",".html":"html",".htm":"html",".xhtml":"html",".css":"css",".scss":"css",".sass":"css",".less":"css",".styl":"css",".json":"json",".json5":"json",".jsonc":"json",".md":"markdown",".markdown":"markdown",".mdx":"markdown",".py":"python",".pyw":"python",".rb":"ruby",".php":"php",".go":"go",".rs":"rust",".java":"java",".kt":"kotlin",".kts":"kotlin",".swift":"swift",".scala":"scala",".clj":"clojure",".cljs":"clojure",".ex":"elixir",".exs":"elixir",".erl":"erlang",".hs":"haskell",".ml":"ocaml",".mli":"ocaml",".jl":"julia",".pl":"perl",".pm":"perl",".tcl":"tcl",".lua":"lua",".r":"r",".dart":"dart",".groovy":"groovy",".gradle":"groovy",".c":"c",".h":"c",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".hpp":"cpp",".hh":"cpp",".cs":"csharp",".m":"objectivec",".sh":"shell",".bash":"shell",".zsh":"shell",".fish":"shell",".ps1":"powershell",".bat":"batch",".cmd":"batch",".yml":"yaml",".yaml":"yaml",".toml":"toml",".ini":"ini",".cfg":"ini",".conf":"ini",".properties":"ini",".xml":"xml",".sql":"sql",".graphql":"graphql",".gql":"graphql",".proto":"protobuf",".vue":"vue",".svelte":"svelte",".csv":"csv",".tsv":"csv",".log":"log",".diff":"diff",".patch":"diff",".dockerfile":"dockerfile",".makefile":"makefile",".mk":"makefile",".env":"env",".gitignore":"gitignore"},tl={M:"text-git-modified",A:"text-git-added",D:"text-git-deleted","?":"text-git-untracked",U:"text-git-modified"},ti={indentBase:12,indentStep:12,icon:16,chevron:14,text:"text-[15px] sm:text-sm",padY:"py-1 sm:py-0.5"},to={indentBase:8,indentStep:8,icon:14,chevron:12,text:"text-[13px] sm:text-[12px]",padY:"py-0.5 sm:py-[1px]"},tc="git-diff:",td=(e,t)=>`${tc}${e}:${t}`,tu=e=>"string"==typeof e&&e.startsWith(tc),tm=e=>{let t=e.slice(tc.length),s=t.indexOf(":");return{status:t.slice(0,s),absPath:t.slice(s+1)}},tx=e=>{let{status:t,absPath:s}=tm(e),n=s.indexOf("\0");return -1===n?{status:t,repoPath:null,filePath:s}:{status:t,repoPath:s.slice(0,n),filePath:s.slice(n+1)}},tp="fileExplorer:gitRefresh",th="fileExplorer.editorFontSize",tf="fileExplorer.wordWrap",tb="fileExplorer.expandedFolders",tg="fileExplorer.showHidden",tv="explorer",ty="search",tw="settings",tk={name:null,value:null},tj=null,tN=()=>{if(tj&&(clearTimeout(tj),tj=null),null===tk.name)return;let{name:e,value:t}=tk;tk.name=null,tk.value=null;try{localStorage.setItem(e,JSON.stringify(t))}catch{}};window.addEventListener("pagehide",tN),document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&tN()});let tS=(0,Z.v)((0,es.Zr)((e,t,s)=>({...{viewStack:[{type:"list"}],openedSessions:[],activeWorkspaceId:null,setActiveWorkspaceId:t=>e(e=>({activeWorkspaceId:t,fullMode:!!e.fullModes?.[t??eZ]})),livePanes:[],touchLivePane:t=>e(e=>{let s=Array.isArray(t)?t:[t];return{livePanes:[...e.livePanes.filter(e=>!s.includes(e)),...s].slice(-12)}}),mountedWorkspaces:{},markWorkspaceMounted:t=>e(e=>{let s=t??eZ;return e.mountedWorkspaces[s]?e:{mountedWorkspaces:{...e.mountedWorkspaces,[s]:!0}}}),isWorkspaceMounted:e=>{let s=e??eZ;return!!t().mountedWorkspaces[s]},drafts:{},setDraft:(t,s)=>e(e=>({drafts:{...e.drafts,[t]:s}})),collapsedWorkspaces:{},toggleWorkspace:t=>e(e=>({collapsedWorkspaces:{...e.collapsedWorkspaces,[t]:!e.collapsedWorkspaces[t]}})),cwdBySession:{},setCwd:(t,s)=>{if(!t||!s)return;let n=e2(s);e(e=>e.cwdBySession[t]===n?e:{cwdBySession:{...e.cwdBySession,[t]:n}})},pushView:t=>e(e=>{let s=Array.isArray(e.viewStack)?e.viewStack:[];return{viewStack:[...eq.includes(t?.type)?s:s.filter((e,t)=>!(eq.includes(e?.type)&&t===s.length-1)),t]}}),popView:()=>e(e=>{let t=Array.isArray(e.viewStack)?e.viewStack:[];return{viewStack:t.length>1?t.slice(0,-1):[{type:"list"}]}}),setViewStack:t=>e({viewStack:t}),addOpenedSession:t=>e(e=>({openedSessions:e.openedSessions.includes(t)?e.openedSessions:[...e.openedSessions,t]})),removeOpenedSession:t=>e(e=>{let{[t]:s,...n}=e.drafts,{[t]:r,...a}=e.pendingStartup,{[t]:l,...i}=e.artifactsBySession;return{artifactsBySession:i,openedSessions:e.openedSessions.filter(e=>e!==t),livePanes:e.livePanes.filter(e=>e!==t),hiddenPaneSessionIds:e.hiddenPaneSessionIds?e.hiddenPaneSessionIds.filter(e=>e!==t):[],drafts:n,pendingStartup:a}}),replaceOpenedSession:(t,s)=>e(e=>{if(!s||t===s)return e;let n=e=>e===t?s:e;return{openedSessions:!t||e.openedSessions.includes(t)?e.openedSessions.map(n):e.openedSessions.includes(s)?e.openedSessions:[...e.openedSessions,s],livePanes:e.livePanes.map(n)}}),clearOpenedSessions:()=>e({openedSessions:[],livePanes:[]}),reorderOpenedSessions:t=>e(e=>{let s=new Set(t),n=t.filter(t=>e.openedSessions.includes(t));if(n.length<2)return{};let r=0;return{openedSessions:e.openedSessions.map(e=>s.has(e)?n[r++]:e)}}),closeSession:t=>e(e=>{let{[t]:s,...n}=e.drafts,{[t]:r,...a}=e.pendingStartup,{[t]:l,...i}=e.agentBySession,o=((e,t)=>{let s={};for(let[n,r]of Object.entries(e))s[n]={at:0,sessions:t?r.sessions.map(t):r.sessions};return s})(e.agentHistory,e=>e.openSessionId===t?{...e,openSessionId:null}:e);return{openedSessions:e.openedSessions.filter(e=>e!==t),livePanes:e.livePanes.filter(e=>e!==t),drafts:n,pendingStartup:a,agentBySession:i,agentHistory:o}}),getCurrentView:()=>{let{viewStack:e}=t();return e[e.length-1]},getSelectedSession:()=>{let{viewStack:e}=t();for(let t=e.length-1;t>=0;t--)if("terminal"===e[t].type)return e[t].sessionId;return null},reset:()=>e({viewStack:[{type:"list"}],openedSessions:[],livePanes:[],activeWorkspaceId:null})},...{sidebarCollapsed:!1,toggleSidebar:()=>e(e=>({sidebarCollapsed:!e.sidebarCollapsed})),setSidebarCollapsed:t=>e({sidebarCollapsed:!!t}),sidebarWidth:ea.default,setSidebarWidth:t=>e({sidebarWidth:e1(t,ea)}),fullModes:{},fullMode:!1,toggleFullMode:t=>e(e=>{let s=t??e.activeWorkspaceId??eZ,n=!e.fullModes[s];return{fullModes:{...e.fullModes,[s]:n},fullMode:s===(e.activeWorkspaceId??eZ)?n:e.fullMode}}),setFullMode:(t,s)=>e(e=>{let n="boolean"==typeof t?e.activeWorkspaceId??eZ:t??e.activeWorkspaceId??eZ,r="boolean"==typeof t?t:!!s;return{fullModes:{...e.fullModes,[n]:r},fullMode:n===(e.activeWorkspaceId??eZ)?r:e.fullMode}}),hiddenPaneSessionIds:[],toggleHidePane:t=>e(e=>({hiddenPaneSessionIds:e.hiddenPaneSessionIds.includes(t)?e.hiddenPaneSessionIds.filter(e=>e!==t):[...e.hiddenPaneSessionIds,t]})),unhidePane:t=>e(e=>({hiddenPaneSessionIds:e.hiddenPaneSessionIds.filter(e=>e!==t)})),paneWidths:{},setPaneWidth:(t,s)=>e(e=>({paneWidths:{...e.paneWidths,[t]:null==s?null:e1(s,er)}})),autoPaneWidths:{},setAutoPaneWidth:(t,s)=>e(e=>({autoPaneWidths:{...e.autoPaneWidths,[t]:null==s?null:Math.round(s)}})),rightPanelOpen:window.innerWidth>=760,rightPanelTabs:{},rightPanelWidth:el.default,toggleRightPanel:()=>e(e=>({rightPanelOpen:!e.rightPanelOpen,rightPanelWasOpen:null})),closeRightPanel:()=>e({rightPanelOpen:!1,rightPanelWasOpen:null}),openRightPanel:()=>e({rightPanelOpen:!0,rightPanelWasOpen:null}),setRightPanelTab:(t,s)=>e(e=>({rightPanelOpen:!0,rightPanelWasOpen:null,...null!=s?{rightPanelTabs:{...e.rightPanelTabs,[s]:t}}:{}})),rightPanelRoots:{},setRightPanelRoot:(t,s)=>e(e=>{if(null==t)return e;let n=e.rightPanelRoots[t],r=s&&s!==t?s:void 0;if(n===r)return e;let a={...e.rightPanelRoots};return r?a[t]=r:delete a[t],{rightPanelRoots:a}}),setRightPanelWidth:t=>e({rightPanelWidth:e1(t,el)}),editorFilePath:null,editorPanelWidth:ei.default,setEditorPanelWidth:t=>e({editorPanelWidth:e1(t,ei)}),editorPreviewSeq:0,artifactTitle:null,rightPanelWasOpen:null,artifactSessionId:null,openEditorFile:(t,s={})=>e(e=>({editorFilePath:t,editorPreviewSeq:s.preview?e.editorPreviewSeq+1:0,artifactTitle:s.artifactTitle||null,artifactSessionId:s.artifactSessionId||null,...s.artifactTitle?{rightPanelWasOpen:e.rightPanelWasOpen??e.rightPanelOpen,rightPanelOpen:!1}:{}})),closeEditorFile:()=>e(e=>({editorFilePath:null,editorPreviewSeq:0,artifactTitle:null,artifactSessionId:null,rightPanelWasOpen:null,...e.rightPanelWasOpen?{rightPanelOpen:!0}:{},...e.artifactSessionId&&e.editorFilePath?{artifactsBySession:((e,t,s)=>{let n=e[t];if(!n)return e;let r=n.filter(e=>e.path!==s);if(r.length===n.length)return e;let{[t]:a,...l}=e;return r.length?{...l,[t]:r}:l})(e.artifactsBySession,e.artifactSessionId,e.editorFilePath)}:{}})),hiddenHeaderButtons:["mobile"],hiddenHeaderButtonsMigrated:!1,toggleHeaderButton:t=>e(e=>({hiddenHeaderButtons:e.hiddenHeaderButtons.includes(t)?e.hiddenHeaderButtons.filter(e=>e!==t):[...e.hiddenHeaderButtons,t]})),mobileLowPower:!1,setMobileLowPower:t=>e({mobileLowPower:!!t}),mobileDeviceCount:0,setMobileDeviceCount:t=>e({mobileDeviceCount:Number(t)||0}),mobileAvailable:!1,setMobileAvailable:t=>e({mobileAvailable:!!t}),mobileOpen:!1,mobileMode:"float",mobilePanelWidth:ed.default,mobileFloatRect:null,setMobileOpen:t=>e({mobileOpen:!!t}),setMobileMode:t=>e({mobileMode:t,mobileOpen:!0}),setMobilePanelWidth:t=>e({mobilePanelWidth:e1(t,ed)}),setMobileFloatRect:t=>e({mobileFloatRect:t}),mobileSession:null,setMobileSession:t=>e(e=>({mobileSession:"function"==typeof t?t(e.mobileSession):t}))},...{webglEnabled:!0,setWebglEnabled:t=>e({webglEnabled:!!t}),fontSize:null,setFontSize:t=>e({fontSize:t?Math.max(10,Math.min(18,Math.round(t))):null}),terminalTheme:"default",setTerminalTheme:t=>e({terminalTheme:t||"default"}),terminalBackgrounds:["art8"],setTerminalBackgrounds:t=>e({terminalBackgrounds:Array.isArray(t)?t.filter(Boolean):[]}),terminalBackgroundOpacity:null,setTerminalBackgroundOpacity:t=>e({terminalBackgroundOpacity:null==t?.8:Number(Math.max(eN.min,Math.min(eN.max,Math.round(t/eN.step)*eN.step)).toFixed(2))}),customBackgrounds:[],setCustomBackgrounds:t=>e({customBackgrounds:Array.isArray(t)?t.filter(e=>e?.id&&e?.dataUrl):[]}),backgroundBySession:{},setSessionBackground:(t,s)=>e(e=>{let n={...e.backgroundBySession};return s?n[t]=s:delete n[t],{backgroundBySession:n}}),showFolderButton:!0,showNoteButton:!1,setShowFolderButton:t=>e({showFolderButton:!!t}),setShowNoteButton:t=>e({showNoteButton:!!t}),noteChips:[],addNoteChip:t=>e(e=>({noteChips:[...e.noteChips,t]})),removeNoteChip:t=>e(e=>({noteChips:e.noteChips.filter(e=>e!==t)})),pinnedNotes:{},setNotePinned:(t,s)=>e(e=>{let n={...e.pinnedNotes};return s?n[t]=!0:delete n[t],{pinnedNotes:n}})},...{agentCaps:{},setAgentCaps:t=>e({agentCaps:t||{}}),artifactEnabled:!1,setArtifactEnabled:t=>e({artifactEnabled:!!t}),mcpClients:[],setMcpClients:t=>e({mcpClients:Array.isArray(t)?t:[]}),agentClisBy:{},setAgentClis:(t,s)=>e(e=>({agentClisBy:{...e.agentClisBy,[t]:{list:Array.isArray(s)?s:[],at:Date.now()}}})),agentHistory:{},setAgentHistory:(t,s)=>e(e=>({agentHistory:{...e.agentHistory,[t]:{at:Date.now(),sessions:Array.isArray(s)?s:[]}}})),invalidateAgentHistory:()=>e(e=>({agentHistory:(e=>{let t={};for(let[s,n]of Object.entries(e))t[s]={at:0,sessions:n.sessions};return t})(e.agentHistory)})),agentBySession:{},setSessionAgent:(t,s)=>e(e=>e.agentBySession[t]===s?e:{agentBySession:{...e.agentBySession,[t]:s}}),pendingStartup:{},queueStartup:(t,s)=>e(e=>({pendingStartup:{...e.pendingStartup,[t]:s}})),consumeStartup:s=>{let n=t().pendingStartup[s];return void 0===n?null:(e(e=>{let{[s]:t,...n}=e.pendingStartup;return{pendingStartup:n}}),n)},artifactsBySession:{},pushArtifact:(t,s)=>e(e=>{if(!t||!s?.path)return{};let n=(e.artifactsBySession[t]||[]).filter(e=>e.path!==s.path);return{artifactsBySession:{...e.artifactsBySession,[t]:[s,...n].slice(0,20)}}}),removeArtifact:(t,s)=>e(e=>({artifactsBySession:((e,t,s)=>{let n=e[t];if(!n)return e;let r=n.filter(e=>e.path!==s);if(r.length===n.length)return e;let{[t]:a,...l}=e;return r.length?{...l,[t]:r}:l})(e.artifactsBySession,t,s)}))}}),{name:"terminal-ui-state",partialize:e=>({viewStack:e.viewStack,openedSessions:e.openedSessions,agentBySession:e.agentBySession,activeWorkspaceId:e.activeWorkspaceId,collapsedWorkspaces:e.collapsedWorkspaces,webglEnabled:e.webglEnabled,fontSize:e.fontSize,terminalTheme:e.terminalTheme,terminalBackgrounds:e.terminalBackgrounds,terminalBackgroundOpacity:e.terminalBackgroundOpacity,backgroundBySession:e.backgroundBySession,showFolderButton:e.showFolderButton,showNoteButton:e.showNoteButton,noteChips:e.noteChips,pinnedNotes:e.pinnedNotes,sidebarCollapsed:e.sidebarCollapsed,sidebarWidth:e.sidebarWidth,fullModes:e.fullModes||{},fullMode:e.fullMode,hiddenPaneSessionIds:e.hiddenPaneSessionIds||[],paneWidths:e.paneWidths,rightPanelOpen:e.rightPanelOpen,rightPanelTabs:e.rightPanelTabs,rightPanelWidth:e.rightPanelWidth,editorPanelWidth:e.editorPanelWidth,hiddenHeaderButtons:e.hiddenHeaderButtons,hiddenHeaderButtonsMigrated:e.hiddenHeaderButtonsMigrated,mobileLowPower:e.mobileLowPower,mobileMode:e.mobileMode,mobilePanelWidth:e.mobilePanelWidth,mobileFloatRect:e.mobileFloatRect,artifactsBySession:e.artifactsBySession}),storage:{getItem:e=>{try{let t=localStorage.getItem(e);if(!t)return null;let s=JSON.parse(t);return s&&!Array.isArray(s.viewStack)&&(s.viewStack=[{type:"list"}]),s}catch{return null}},setItem:(e,t)=>{tk.name=e,tk.value=t,tj||(tj=setTimeout(tN,250))},removeItem:e=>{tk.name===e&&(tk.name=null,tk.value=null),localStorage.removeItem(e)}},onRehydrateStorage:()=>e=>{e&&(Array.isArray(e.viewStack)&&0!==e.viewStack.length||(e.viewStack=[{type:"list"}]),e.viewStack=e.viewStack.filter(e=>!eq.includes(e?.type)),0===e.viewStack.length&&(e.viewStack=[{type:"list"}]),Array.isArray(e.terminalBackgrounds)||(e.terminalBackgrounds=[]),e.terminalBackground&&"none"!==e.terminalBackground&&0===e.terminalBackgrounds.length&&(e.terminalBackgrounds=[e.terminalBackground]),e.agentBySession&&"object"==typeof e.agentBySession||(e.agentBySession={}),window.innerWidth<760&&(e.rightPanelOpen=!1),!e.hiddenHeaderButtonsMigrated&&(e.hiddenHeaderButtonsMigrated=!0,Array.isArray(e.hiddenHeaderButtons)?e.hiddenHeaderButtons.includes("mobile")||(e.hiddenHeaderButtons=[...e.hiddenHeaderButtons,"mobile"]):e.hiddenHeaderButtons=["mobile"]))}})),tC="https://openrouter.ai/api/v1",tT={enabled:"voiceEnabled",mode:"voiceMode",endpoint:"voiceEndpoint",apiKey:"voiceApiKey",model:"voiceModel",preset:"voicePreset",geminiKeys:"voiceGeminiKeys",openrouterKey:"voiceOpenrouterKey",customEndpoint:"voiceCustomEndpoint",customModel:"voiceCustomModel",customKey:"voiceCustomKey"},tR={gemini:{label:"Gemini",endpoint:"https://generativelanguage.googleapis.com/v1beta/openai",model:"gemini-3.1-flash-lite",note:"Free tier \xb7 quota per project (AI Studio)"},openrouter:{label:"OpenRouter",endpoint:tC,model:"google/gemini-3.5-flash-lite",note:"$0.30/1M in \xb7 $2.50/1M out"},custom:{label:"Custom"}};async function tE(e,t){let s=new AbortController,n=setTimeout(()=>s.abort(),15e3);try{if(!e.apiKey?.trim())throw Error("No API key set");let n=(e.endpoint?.trim()||tC).replace(/\/+$/,""),r=await fetch(`${n}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},body:JSON.stringify({stream:!1,...t}),signal:s.signal}),a=await r.json().catch(()=>({}));if(!r.ok)throw Error(a?.error?.message||`HTTP ${r.status}`);return a}finally{clearTimeout(n)}}let t_=e=>e?.name==="AbortError"?"Timed out":e?.message==="Failed to fetch"?"Network/CORS error":e?.message||"Failed";async function t$(e=3e3){let t=await navigator.mediaDevices.getUserMedia({audio:!0}),s=new MediaRecorder(t),n=[];s.ondataavailable=e=>{e.data.size&&n.push(e.data)};let r=new Promise(e=>{s.onstop=e});return s.start(),await new Promise(t=>setTimeout(t,e)),s.stop(),await r,t.getTracks().forEach(e=>e.stop()),new Blob(n,{type:s.mimeType||"audio/webm"})}async function tM(e){let t=new OfflineAudioContext(1,1,16e3),s=await t.decodeAudioData(await e.arrayBuffer()),n=new OfflineAudioContext(1,Math.ceil(16e3*s.duration),16e3),r=n.createBufferSource();return r.buffer=s,r.connect(n.destination),r.start(),function(e){let t=new ArrayBuffer(44+2*e.length),s=new DataView(t),n=(e,t)=>{for(let n=0;n<t.length;n++)s.setUint8(e+n,t.charCodeAt(n))};n(0,"RIFF"),s.setUint32(4,36+2*e.length,!0),n(8,"WAVE"),n(12,"fmt "),s.setUint32(16,16,!0),s.setUint16(20,1,!0),s.setUint16(22,1,!0),s.setUint32(24,16e3,!0),s.setUint32(28,32e3,!0),s.setUint16(32,2,!0),s.setUint16(34,16,!0),n(36,"data"),s.setUint32(40,2*e.length,!0);let r=44;for(let t=0;t<e.length;t++,r+=2){let n=Math.max(-1,Math.min(1,e[t]));s.setInt16(r,n<0?32768*n:32767*n,!0)}return new Blob([t],{type:"audio/wav"})}((await n.startRendering()).getChannelData(0))}let tP=0;function tA(e){if("gemini"===e.preset||"openrouter"===e.preset){let t=tR[e.preset],s=e[`${e.preset}Model`]?.trim()||t.model;if("gemini"===e.preset){let n=e.geminiKeys.map(e=>e.trim()).filter(Boolean);return{endpoint:t.endpoint,model:s,apiKey:n.length?n[tP++%n.length]:""}}return{endpoint:t.endpoint,model:s,apiKey:e.openrouterKey}}return{endpoint:e.customEndpoint,model:e.customModel,apiKey:e.customKey}}async function tz(e,t){var s;let n=tA(e),r=await tE(n,{model:n.model,messages:[{role:"user",content:[{type:"text",text:`Transcribe this audio accurately for a developer coding & terminal context.
|
|
2
|
+
- Auto-detect spoken language; do NOT translate.
|
|
3
|
+
- Keep English tech terms, code, and CLI commands in English (e.g. git, npm, docker, API, bug, log, deploy).
|
|
4
|
+
- Add natural punctuation. Omit filler sounds.
|
|
5
|
+
- Output ONLY the transcribed text.`},{type:"input_audio",input_audio:{data:await (s=await tM(t),new Promise(e=>{let t=new FileReader;t.onload=()=>e(String(t.result).split(",")[1]),t.readAsDataURL(s)})),format:"wav"}}]}]});return r?.choices?.[0]?.message?.content?.trim()||""}let tI=(e,t)=>{try{let s=Array.isArray(t)?JSON.stringify(t):"boolean"==typeof t?t?"1":"0":t;localStorage.setItem(tT[e],s)}catch{}};function tL(e){try{let t=Q.getState().bus;if(!t||"function"!=typeof t.emit)return;t.emit("setVoiceConfig",{voiceConfig:{enabled:e.enabled,mode:e.mode,preset:e.preset,geminiKeys:e.geminiKeys,geminiModel:e.geminiModel,openrouterKey:e.openrouterKey,openrouterModel:e.openrouterModel,customEndpoint:e.customEndpoint,customModel:e.customModel,customKey:e.customKey}})}catch{}}let tD=(0,Z.v)((e,t)=>({enabled:!0,mode:"browser",preset:"gemini",geminiKeys:[],geminiModel:"",openrouterKey:"",openrouterModel:"",customEndpoint:"",customModel:"",customKey:"",setEnabled:s=>{tI("enabled",s),e({enabled:s}),tL(t())},setMode:s=>{tI("mode",s),e({mode:s}),tL(t())},setPreset:s=>{tI("preset",s),e({preset:s}),tL(t())},setField:(s,n)=>{tI(s,n),e({[s]:n}),tL(t())},syncFromAgent:t=>{t&&"object"==typeof t&&e(e=>{let s={...e};return"boolean"==typeof t.enabled&&(s.enabled=t.enabled,tI("enabled",s.enabled)),t.mode&&(s.mode=t.mode,tI("mode",s.mode)),t.preset&&(s.preset=t.preset,tI("preset",s.preset)),Array.isArray(t.geminiKeys)&&(s.geminiKeys=t.geminiKeys,tI("geminiKeys",s.geminiKeys)),"string"==typeof t.geminiModel&&(s.geminiModel=t.geminiModel,tI("geminiModel",s.geminiModel)),"string"==typeof t.openrouterKey&&(s.openrouterKey=t.openrouterKey,tI("openrouterKey",s.openrouterKey)),"string"==typeof t.openrouterModel&&(s.openrouterModel=t.openrouterModel,tI("openrouterModel",s.openrouterModel)),"string"==typeof t.customEndpoint&&(s.customEndpoint=t.customEndpoint,tI("customEndpoint",s.customEndpoint)),"string"==typeof t.customModel&&(s.customModel=t.customModel,tI("customModel",s.customModel)),"string"==typeof t.customKey&&(s.customKey=t.customKey,tI("customKey",s.customKey)),s})},pushToAgent:()=>tL(t())}));try{let e=e=>localStorage.getItem(tT[e]),t={enabled:"0"!==e("enabled"),mode:"ai"===e("mode")?"ai":"browser",preset:["gemini","openrouter","custom"].includes(e("preset"))?e("preset"):null,geminiKeys:(e=>{try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}})(e("geminiKeys")),geminiModel:e("geminiModel")||"",openrouterKey:e("openrouterKey")||"",openrouterModel:e("openrouterModel")||"",customEndpoint:e("customEndpoint")||"",customModel:e("customModel")||"",customKey:e("customKey")||""};if(!t.preset){let s=e("endpoint")||"",n=e("apiKey")||"",r=e("model")||"";s.includes("generativelanguage")?(t.preset="gemini",n&&(t.geminiKeys=[n])):s&&s!==tC?(t.preset="custom",t.customEndpoint=s,t.customKey=n,t.customModel=r):n||r?(t.preset="openrouter",t.openrouterKey=n):t.preset="gemini",tI("preset",t.preset),r&&"custom"!==t.preset&&(t[`${t.preset}Model`]=r),t.geminiModel&&tI("geminiModel",t.geminiModel),t.openrouterModel&&tI("openrouterModel",t.openrouterModel),t.geminiKeys.length&&tI("geminiKeys",t.geminiKeys),t.openrouterKey&&tI("openrouterKey",t.openrouterKey),t.customEndpoint&&tI("customEndpoint",t.customEndpoint),t.customModel&&tI("customModel",t.customModel),t.customKey&&tI("customKey",t.customKey)}tD.setState(t)}catch{}function tF(e,t){if(e===t)return!0;if(!e||!t||"object"!=typeof e||"object"!=typeof t)return!1;let s=Object.keys(e);if(s.length!==Object.keys(t).length)return!1;for(let n of s)if(!(n in t)||e[n]!==t[n])return!1;return!0}function tO(e,t){if(e===t)return!0;if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;for(let s=0;s<e.length;s++)if(!tF(e[s],t[s]))return!1;return!0}function tB(e,t){if(e===t)return!0;if(!e||!t)return!1;let s=Object.keys(e);if(s.length!==Object.keys(t).length)return!1;for(let n of s)if(!(n in t)||!tF(e[n],t[n]))return!1;return!0}var tW=s(87670);let tK=(0,Z.v)(e=>({isKeyboardOpen:!1,setKeyboardOpen:t=>{e({isKeyboardOpen:t}),"u">typeof document&&document.body.classList.toggle("keyboard-open",t)}}));function tH(e){let t=e instanceof ArrayBuffer?new Uint8Array(e):e,s=new DataView(t.buffer,t.byteOffset,t.byteLength);return{uploadId:s.getUint32(0,!0),offset:s.getUint32(4,!0),payload:t.slice(8)}}let tU={balanced:{bitsPerPixel:.16,maxFps:30,edgeScale:.55,maxBitRate:4e6},quality:{bitsPerPixel:.2,maxFps:30,edgeScale:.8,maxBitRate:8e6},saver:{bitsPerPixel:.14,maxFps:24,edgeScale:.4,maxBitRate:2e6}},tq="balanced",tV=["V","D","I","W","E","F"],tX={V:"text-text-muted",D:"text-text-muted",I:"text-text",W:"text-amber-400",E:"text-red-400",F:"text-red-500 font-semibold"};function tG(e,t,s){return new Promise(n=>{e?e.emit(t,s,e=>n(e||{success:!1,error:"No response"})):n({success:!1,error:"Not connected"})})}class tJ{constructor(e){this.totalSize=e,this._contiguous=0,this._gaps=new Map,this.watermark=0}mark(e,t){if(0===this.totalSize||e<this._contiguous)return null;for(this._gaps.set(e,t);this._gaps.has(this._contiguous);){let e=this._gaps.get(this._contiguous);this._gaps.delete(this._contiguous),this._contiguous+=e}return this._contiguous>this.watermark?(this.watermark=this._contiguous,this.watermark):null}isComplete(){return this.watermark>=this.totalSize}}class tY{constructor(){this.skipAll=!1,this.replaceAll=!1}resolve(e){return e?this.replaceAll?"replace":this.skipAll?"skip":"ask":"write"}record(e){"skipAll"===e?this.skipAll=!0:"replaceAll"===e&&(this.replaceAll=!0)}}async function tZ({bus:e,protocolRef:t,targetDir:s,items:n,callbacks:r}){let{onConflict:a,onProgress:l,onFileDone:i,onError:o}=r||{},c=new tY;for(let{file:r,relativePath:d}of n)try{let n=await tQ(e,t,s,r,d,c,a,l);i?.(r,n.status)}catch(e){o?.(r,e)}}async function tQ(e,t,s,n,r,a,l,i){var c,d,u,m,x;let p=await tG(e,"upload:start",{targetDir:s,relativePath:r,size:n.size,mtime:n.lastModified||0});if(!p.success)throw Error(p.error);let{uploadId:h,exists:f}=p;if(f){let t=a.resolve(!0);if("ask"===t){let e=await l?.(n,r);a.record(e),t=a.resolve(!0)}if("skip"===t)return e.emit("upload:cancel",{uploadId:h}),{status:"skipped"}}return await (c=e,d=t,u=h,m=n,x=i,new Promise(async(e,t)=>{let s,n=m.size,r=o.HE.chunkSize,a=r*o.HE.windowSize;try{s=new Uint8Array(await m.arrayBuffer())}catch(e){t(e);return}let l=function(e,t){if(e<=0)return[];let s=[],n=0;for(;n<e;){let r=Math.min(t,e-n);s.push({offset:n,length:r}),n+=r}return s}(n,r),i=0,p=0,h=0,f=!1,b=({uploadId:e,offset:t})=>{e===u&&(t>h&&(h=t,x?.(m,n?h/n:1)),h>=n&&!f?(f=!0,c.emit("upload:end",{uploadId:u})):k())},g=({uploadId:e,error:s})=>{e===u&&(y(),t(Error(s)))},v=({uploadId:t})=>{t===u&&(y(),e())};function y(){c.off("upload:ack",b),c.off("upload:error",g),c.off("upload:done",v)}c.on("upload:ack",b),c.on("upload:error",g),c.on("upload:done",v);let w=e=>{let t=d?.current;return t?.sendBinary?t.sendBinary(o.l_.file,e):(c.emit("file-bin",e),!0)};function k(){for(;i<l.length&&p-h<a;){let e=l[i];if(!w(function(e,t,s){let n=s instanceof ArrayBuffer?new Uint8Array(s):s,r=new Uint8Array(8+n.byteLength),a=new DataView(r.buffer);return a.setUint32(0,e>>>0,!0),a.setUint32(4,t>>>0,!0),r.set(n,8),r}(u,e.offset,s.subarray(e.offset,e.offset+e.length))))break;i++,p=e.offset+e.length}if(h>=n&&!f){f=!0,c.emit("upload:end",{uploadId:u});return}i<l.length&&p-h<a&&setTimeout(k,50)}k()})),{status:"done"}}let t0=e=>t=>{e(function e(t){let s;if(!t||"object"!=typeof t)return t;if(Array.isArray(t)){let s=!1,n=t.map(t=>{let n=e(t);return n!==t&&(s=!0),n});return s?n:t}for(let n of Object.keys(t)){let r=t[n];if(e5.has(n)&&"string"==typeof r&&r.includes("\\"))(s||={...t})[n]=e2(r);else if(r&&"object"==typeof r){let a=e(r);a!==r&&((s||={...t})[n]=a)}}return s||t}(t))},t1=()=>{let e=Q.getState();return e.connected?e.busRef?.current||e.bus:null},t2=(0,Z.v)(()=>({getSystemInfo:()=>new Promise(e=>{let t=t1();if(!t)return e({success:!1,error:"Not connected"});t.emit("getSystemInfo",e)}),getFiles:(e,t=!1)=>new Promise(s=>{let n=t1();if(!n)return s({success:!1,error:"Not connected"});n.emit("getFiles",{dirPath:e,showHidden:t},t0(s))}),readFile:e=>new Promise(t=>{let s=t1();if(!s)return t({success:!1,error:"Not connected"});s.emit("readFile",{filePath:e},t)}),readImage:e=>new Promise(t=>{let s=t1();if(!s)return t({success:!1,error:"Not connected"});s.emit("readImage",{filePath:e},t)}),readMedia:e=>new Promise(t=>{let s=t1();if(!s)return t({success:!1,error:"Not connected"});s.emit("readMedia",{filePath:e},t)}),writeFile:(e,t)=>new Promise(s=>{let n=t1();if(!n)return s({success:!1,error:"Not connected"});n.emit("writeFile",{filePath:e,content:t},s)}),createItem:(e,t)=>new Promise(s=>{let n=t1();if(!n)return s({success:!1,error:"Not connected"});n.emit("createItem",{itemPath:e,type:t},s)}),deleteItem:e=>new Promise(t=>{let s=t1();if(!s)return t({success:!1,error:"Not connected"});s.emit("deleteItem",{itemPath:e},t)}),renameItem:(e,t)=>new Promise(s=>{let n=t1();if(!n)return s({success:!1,error:"Not connected"});n.emit("renameItem",{oldPath:e,newPath:t},s)}),copyItem:(e,t)=>new Promise(s=>{let n=t1();if(!n)return s({success:!1,error:"Not connected"});n.emit("copyItem",{srcPath:e,destPath:t},s)}),gitStatus:e=>new Promise(t=>{let s=t1();if(!s)return t({success:!1,error:"Not connected"});s.emit("gitStatus",{repoPath:e},t0(t))}),gitChangedCount:e=>new Promise(t=>{let s=t1();if(!s)return t({success:!1,error:"Not connected"});s.emit("gitChangedCount",{repoPath:e},t)}),gitFileStatus:(e,t)=>new Promise(s=>{let n=t1();if(!n)return s({success:!1,error:"Not connected"});n.emit("gitFileStatus",{repoPath:e,filePath:t},t0(s))}),gitDiff:(e,t,s)=>new Promise(n=>{let r=t1();if(!r)return n({success:!1,error:"Not connected"});r.emit("gitDiff",{repoPath:e,file:t,status:s},n)}),gitShowMedia:(e,t,s="HEAD")=>new Promise(n=>{let r=t1();if(!r)return n({success:!1,error:"Not connected"});r.emit("gitShowMedia",{repoPath:e,file:t,ref:s},n)}),searchFiles:(e,t)=>new Promise(s=>{let n=t1();if(!n)return s({success:!1,error:"Not connected"});n.emit("searchFiles",{workspace:e,query:t},t0(s))}),gitDiscard:(e,t,s)=>new Promise(n=>{let r=t1();if(!r)return n({success:!1,error:"Not connected"});r.emit("gitDiscard",{repoPath:e,file:t,status:s},n)}),searchInFiles:(e,t,s={})=>new Promise(n=>{let r=t1();if(!r)return n({success:!1,error:"Not connected"});let{caseSensitive:a=!1,regex:l=!1,includeGlob:i="",excludeGlob:o=""}=s;r.emit("searchInFiles",{workspace:e,query:t,caseSensitive:a,regex:l,includeGlob:i,excludeGlob:o},t0(n))}),replaceInFiles:(e,t,s,n={},r=[])=>new Promise(a=>{let l=t1();if(!l)return a({success:!1,error:"Not connected"});let{caseSensitive:i=!1,regex:o=!1,includeGlob:c="",excludeGlob:d=""}=n;l.emit("replaceInFiles",{workspace:e,query:t,replacement:s,caseSensitive:i,regex:o,includeGlob:c,excludeGlob:d,files:r},a)}),watchDir:e=>new Promise(t=>{let s=t1();if(!s)return t({success:!1,error:"Not connected"});s.emit("watchDir",{dirPath:e},t)}),unwatchDir:e=>new Promise(t=>{let s=t1();if(!s)return t({success:!1,error:"Not connected"});s.emit("unwatchDir",{dirPath:e},t)}),onFileChange:e=>{let t=Q.getState(),s=t.busRef?.current||t.bus;return s?(s.on("fileChange",e),()=>s.off("fileChange",e)):()=>{}},revealInOS:e=>new Promise(t=>{let s=t1();if(!s)return t({success:!1,error:"Not connected"});s.emit("revealInOS",{filePath:e},t)}),openInTerminal:e=>new Promise(t=>{let s=t1();if(!s)return t({success:!1,error:"Not connected"});s.emit("openInTerminal",{dirPath:e},t)}),getFileTree:(e,t=1,s=!1)=>new Promise(n=>{let r=t1();if(!r)return n({success:!1,error:"Not connected"});r.emit("getFileTree",{dirPath:e,depth:t,showHidden:s},t0(n))}),gitBranch:e=>new Promise(t=>{let s=t1();if(!s)return t({success:!1,error:"Not connected"});s.emit("gitBranch",{repoPath:e},t)}),gitScanRepos:(e,t)=>new Promise(s=>{let n=t1();if(!n)return s({success:!1,error:"Not connected"});n.emit("gitScanRepos",{rootPath:e,maxDepth:t},s)}),gitWorkspaceChangedCount:(e,t)=>new Promise(s=>{let n=t1();if(!n)return s({success:!1,error:"Not connected"});n.emit("gitWorkspaceChangedCount",{rootPath:e,maxDepth:t},s)}),gitRefreshRepos:e=>new Promise(t=>{let s=t1();if(!s)return t({success:!1,error:"Not connected"});s.emit("gitRefreshRepos",{rootPath:e},t)}),gitWorktreeList:e=>new Promise(t=>{let s=t1();if(!s)return t({success:!1,error:"Not connected"});s.emit("gitWorktreeList",{repoPath:e},t)}),gitWorktreeAdd:(e,t,s,n)=>new Promise(r=>{let a=t1();if(!a)return r({success:!1,error:"Not connected"});a.emit("gitWorktreeAdd",{repoPath:e,worktreePath:t,branch:s,newBranch:n},r)}),gitWorktreeRemove:(e,t,s={})=>new Promise(n=>{let r=t1();if(!r)return n({success:!1,error:"Not connected"});r.emit("gitWorktreeRemove",{repoPath:e,worktreePath:t,...s},n)}),gitBranchList:e=>new Promise(t=>{let s=t1();if(!s)return t({success:!1,error:"Not connected"});s.emit("gitBranchList",{repoPath:e},t)}),gitBranchCheckout:(e,t,s)=>new Promise(n=>{let r=t1();if(!r)return n({success:!1,error:"Not connected"});r.emit("gitBranchCheckout",{repoPath:e,branch:t,create:s},n)}),gitAdd:(e,t)=>new Promise(s=>{let n=t1();if(!n)return s({success:!1,error:"Not connected"});n.emit("gitAdd",{repoPath:e,files:t},s)}),gitReset:(e,t)=>new Promise(s=>{let n=t1();if(!n)return s({success:!1,error:"Not connected"});n.emit("gitReset",{repoPath:e,files:t},s)}),gitCommit:(e,t)=>new Promise(s=>{let n=t1();if(!n)return s({success:!1,error:"Not connected"});n.emit("gitCommit",{repoPath:e,message:t},s)}),gitPush:e=>new Promise(t=>{let s=t1();if(!s)return t({success:!1,error:"Not connected"});s.emit("gitPush",{repoPath:e},t)}),gitPull:e=>new Promise(t=>{let s=t1();if(!s)return t({success:!1,error:"Not connected"});s.emit("gitPull",{repoPath:e},t)}),gitLog:(e,t=50)=>new Promise(s=>{let n=t1();if(!n)return s({success:!1,error:"Not connected"});n.emit("gitLog",{repoPath:e,limit:t},t0(s))}),uploadFiles:(e,t,s)=>{let n=t1();return n?tZ({bus:n,protocolRef:Q.getState().protocolRef,targetDir:e,items:t,callbacks:s}):(s?.onError?.(null,Error("Not connected")),Promise.resolve())},downloadFile:(e,t)=>{let s=t1();return s?function({bus:e,protocolRef:t,filePath:s,onSave:n,onProgress:r,onError:a}){let l=null,i=null,o=null,c=null,d=null,u=e=>{let t;try{t=tH(e)}catch{return}t.uploadId===l&&(d.set(t.offset,t.payload),c&&(c.mark(t.offset,t.payload.byteLength),r&&i&&r(c.watermark/i)))},m=({downloadId:e})=>{if(e===l&&(!c||c.isComplete())){let e;p(),e=[...d.entries()].sort((e,t)=>e[0]-t[0]).map(([,e])=>e),n?.(new Blob(e),{size:i,fileName:o})}},x=({downloadId:e,error:t})=>{e===l&&(p(),a?.(Error(t)))};function p(){e.off("file-bin",u),e.off("download:done",m),e.off("download:error",x)}tG(e,"download:start",{filePath:s}).then(t=>{t.success?(l=t.downloadId,i=t.size,o=t.fileName,c=null!=i?new tJ(i):null,d=new Map,e.on("file-bin",u),e.on("download:done",m),e.on("download:error",x)):a?.(Error(t.error))}).catch(e=>a?.(e))}({bus:s,protocolRef:Q.getState().protocolRef,filePath:e,...t}):(t?.onError?.(Error("Not connected")),Promise.resolve())},streamMedia:(e,t)=>{let s=t1();return s?function({bus:e,filePath:t,onMeta:s,onChunk:n,onDone:r,onError:a}){let l=null,i=new Map,o=0,c=()=>{for(;i.has(o);){let e=i.get(o);i.delete(o),n?.(e),o+=e.byteLength}},d=e=>{let t;if(null!=l){try{t=tH(e)}catch{return}t.uploadId===l&&(i.set(t.offset,t.payload),c())}},u=({downloadId:e})=>{e===l&&(x(),r?.())},m=({downloadId:e,error:t})=>{e===l&&(x(),a?.(Error(t)))};function x(){e.off("file-bin",d),e.off("download:done",u),e.off("download:error",m)}return e.on("file-bin",d),e.on("download:done",u),e.on("download:error",m),tG(e,"streamMedia:start",{filePath:t}).then(e=>{if(!e.success){x(),a?.(Error(e.error));return}l=e.streamId,s?.({mime:e.mime,size:e.size,width:e.width,height:e.height,scaled:e.scaled,originalWidth:e.originalWidth,originalHeight:e.originalHeight}),c()}).catch(e=>{x(),a?.(e)}),()=>{x(),null!=l&&e.emit("download:cancel",{downloadId:l})}}({bus:s,filePath:e,...t}):(t?.onError?.(Error("Not connected")),{cancel:()=>{}})},previewStart:e=>new Promise(t=>{let s=t1();if(!s)return t({success:!1,error:"Not connected"});s.emit("preview:start",{filePath:e},t)}),previewEnd:e=>new Promise(t=>{let s=t1();if(!s)return t({success:!1});s.emit("preview:end",{sessionId:e},t)})}));function t5(){return t2.getState()}var t3=s(64683);let t4={recv:"text-green-400",join:"text-blue-400",reconnect:"text-yellow-400",switch:"text-purple-400",resize:"text-cyan-400",send:"text-orange-400","ai-hydrate":"text-pink-400","ai-page":"text-amber-400","ai-gate":"text-red-400"};function t6(e){let t=new Date(e);return`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}:${String(t.getSeconds()).padStart(2,"0")}.${String(t.getMilliseconds()).padStart(3,"0")}`}function t8(){let[e,t]=(0,r.useState)(!1),[s,a]=(0,r.useState)(()=>(0,v.FQ)()),[l,i]=(0,r.useState)(!1),[o,c]=(0,r.useState)(""),d=(0,r.useRef)(null),[u,m]=(0,r.useState)(()=>{try{let e=JSON.parse(localStorage.getItem("9remote:termLogBtn")||"null");if(e&&Number.isFinite(e.x)&&Number.isFinite(e.y))return e}catch{}return{x:8,y:8}}),x=(0,r.useRef)({dragging:!1,startX:0,startY:0,origX:0,origY:0,moved:!1}),p=e=>{let s=x.current;if(s.dragging){s.dragging=!1;try{e.currentTarget.releasePointerCapture(e.pointerId)}catch{}if(s.moved)try{localStorage.setItem("9remote:termLogBtn",JSON.stringify(u))}catch{}else t(e=>!e)}};if((0,r.useEffect)(()=>{let e=()=>{x.current.dragging&&(x.current.dragging=!1)};return window.addEventListener("blur",e),()=>window.removeEventListener("blur",e)},[]),(0,r.useEffect)(()=>{if((0,v.UX)())return(0,v.yO)(()=>{l||a([...(0,v.FQ)()])})},[l]),(0,r.useEffect)(()=>{e&&d.current&&(d.current.scrollTop=d.current.scrollHeight)},[s,e]),!(0,v.UX)())return null;let h=o?s.filter(e=>e.category.includes(o)||e.msg.includes(o)):s,f=async()=>{let e=h.map(e=>`${t6(e.ts)} ${e.category} ${e.msg}`).join("\n");try{await navigator.clipboard?.writeText(e)}catch{}};return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{style:{left:u.x,top:u.y},onPointerDown:e=>{x.current={dragging:!0,startX:e.clientX,startY:e.clientY,origX:u.x,origY:u.y,moved:!1};try{e.currentTarget.setPointerCapture(e.pointerId)}catch{}},onPointerMove:e=>{let t=x.current;if(!t.dragging)return;if("mouse"===e.pointerType&&0===e.buttons)return void p(e);let s=e.clientX-t.startX,n=e.clientY-t.startY;(Math.abs(s)>4||Math.abs(n)>4)&&(t.moved=!0);let r=window.innerWidth,a=window.innerHeight;m({x:Math.max(4,Math.min(r-44,t.origX+s)),y:Math.max(4,Math.min(a-44,t.origY+n))})},onPointerUp:p,onPointerCancel:p,className:"fixed z-[80] px-1.5 py-1 rounded-full bg-surface-2/90 backdrop-blur-sm shadow-md text-text border border-border-subtle touch-none select-none cursor-grab active:cursor-grabbing",title:"Dev log (drag to move)",children:(0,n.jsx)("span",{className:"text-[10px] font-bold leading-none",children:s.length})}),e&&(0,n.jsx)("div",{className:"fixed inset-x-0 bottom-0 z-[79] flex flex-col pb-safe",style:{height:"55vh"},children:(0,n.jsxs)("div",{className:"bg-surface-2/95 backdrop-blur-sm border-t border-border-subtle rounded-t-xl shadow-2xl flex flex-col h-full overflow-hidden",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-border-subtle flex-shrink-0",children:[(0,n.jsx)("span",{className:"text-xs font-semibold text-text",children:"termLog"}),(0,n.jsxs)("span",{className:"text-[10px] text-text-muted",children:["(",h.length,"/",s.length,")"]}),(0,n.jsx)("input",{value:o,onChange:e=>c(e.target.value),placeholder:"filter…",className:"flex-1 min-w-0 text-[11px] bg-surface px-2 py-0.5 rounded border border-border-subtle text-text"}),(0,n.jsx)("button",{onClick:()=>i(e=>!e),className:"p-1 text-text-muted hover:text-text text-[10px]",title:l?"Resume":"Pause",children:l?"▶":"⏸"}),(0,n.jsx)("button",{onClick:f,className:"p-1 text-text-muted hover:text-text",title:`Copy ${h.length} rows`,children:(0,n.jsx)(t3.QR,{size:13})}),(0,n.jsx)("button",{onClick:()=>{(0,v.k_)(),a([])},className:"p-1 text-text-muted hover:text-text",title:"Clear",children:(0,n.jsx)(t3.TB,{size:13})}),(0,n.jsx)("button",{onClick:()=>t(!1),className:"p-1 text-text-muted hover:text-text",title:"Close",children:(0,n.jsx)(t3.X,{size:14})})]}),(0,n.jsx)("div",{ref:d,className:"flex-1 overflow-y-auto overflow-x-auto px-2 py-1 font-mono text-[10px] leading-tight",children:0===h.length?(0,n.jsx)("p",{className:"text-text-muted text-center py-4",children:"No logs yet"}):h.map((e,t)=>(0,n.jsxs)("div",{className:"flex gap-1.5 py-0.5 hover:bg-surface rounded px-1",children:[(0,n.jsx)("span",{className:"text-text-muted flex-shrink-0",children:t6(e.ts)}),(0,n.jsx)("span",{className:`flex-shrink-0 font-bold ${t4[e.category]||"text-text"}`,children:e.category}),(0,n.jsx)("span",{className:"text-text break-all whitespace-pre-wrap",children:e.msg})]},t))})]})})]})}var t9=s(42174),t7=s(8910),se=s(78762);let st="recentWorkspaces",ss=e=>{if(!e)return e;let t={...e};return"string"==typeof t.path&&(t.path=e2(t.path)),"string"==typeof t.lastPath&&(t.lastPath=e2(t.lastPath)),Array.isArray(t.openedFiles)&&(t.openedFiles=t.openedFiles.map(e=>e&&"object"==typeof e?{...e,path:e2(e.path)}:e)),"string"==typeof t.activeFile&&(t.activeFile=e2(t.activeFile)),t};function sn(){try{return JSON.parse(localStorage.getItem(st)||"[]").map(ss)}catch{return[]}}function sr(e){let t=e2(e),s=sn(),n=s.find(e=>e.path===t),r=s.filter(e=>e.path!==t);r.unshift({path:t,lastOpened:Date.now(),lastPath:n?.lastPath,name:n?.name,pinned:n?.pinned||!1,openedFiles:n?.openedFiles||[]});let a=r.filter(e=>e.pinned),l=r.filter(e=>!e.pinned).slice(0,20);localStorage.setItem(st,JSON.stringify([...a,...l]))}function sa({onSelect:e,onBrowse:t,onBack:s,isCodespaces:a,systemInfo:l}){let{t:i}=(0,se.s)(),[o,c]=(0,r.useState)([]),[d,u]=(0,r.useState)({isOpen:!1,path:null,name:""});return(0,r.useEffect)(()=>{c(sn())},[]),(0,n.jsxs)("div",{className:"h-full bg-bg flex flex-col",children:[(0,n.jsxs)("div",{className:"bg-surface px-4 py-3 flex items-center gap-3 flex-shrink-0",children:[(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),s()},className:"p-2 bg-surface-2 hover:bg-surface-3 text-text rounded-brand transition-all duration-150 ease-out active:scale-[0.96]",children:(0,n.jsx)("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,n.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}),(0,n.jsx)("h1",{className:"text-text text-lg font-semibold",children:i("files.selectWorkspace")})]}),(0,n.jsxs)("div",{className:"flex-1 p-4 overflow-auto modal-scrollable",children:[o.length>0&&(0,n.jsxs)("div",{className:"mb-6",children:[(0,n.jsx)("h2",{className:"text-text-muted text-sm font-medium mb-3",children:i("files.recentWorkspaces")}),(0,n.jsx)("div",{className:"space-y-2",children:o.map(t=>{var s;let r,a,l,o,c;return(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),e(t.path)},className:"w-full bg-surface hover:bg-surface-2 rounded-brand-lg p-4 flex items-center gap-3 transition-all duration-150 ease-out active:scale-[0.99] text-left",children:[(0,n.jsx)(t3.vd,{size:24,className:"text-orange-500/70 flex-shrink-0"}),(0,n.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,n.jsx)("div",{className:"text-text font-medium truncate",children:(r=t.path).split("/").pop()||r}),(0,n.jsx)("div",{className:"text-text-muted text-sm truncate",title:t.path,children:t.path.replace(/^\/Users\/[^/]+/,"~")}),(0,n.jsx)("div",{className:"text-text-muted text-xs mt-1",children:(s=t.lastOpened,l=Math.floor((a=Date.now()-s)/6e4),o=Math.floor(a/36e5),c=Math.floor(a/864e5),l<60?i("common.minutesAgo",{n:l}):o<24?i("common.hoursAgo",{n:o}):i("common.daysAgo",{n:c}))})]}),(0,n.jsx)("div",{onClick:e=>{(0,t7.e)(),e.stopPropagation(),u({isOpen:!0,path:t.path,name:t.path.split("/").pop()||t.path})},className:"p-2 text-text-muted hover:text-red-400 hover:bg-surface-2 rounded-brand transition-all duration-200 flex-shrink-0",title:i("files.removeRecent"),children:(0,n.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,n.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})})}),(0,n.jsx)("svg",{className:"w-5 h-5 text-text-muted flex-shrink-0",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,n.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]},t.path)})})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("h2",{className:"text-text-muted text-sm font-medium mb-3",children:i("files.selectWorkspace")}),(0,n.jsxs)("div",{className:"space-y-2",children:[l?.isWindows?(0,n.jsx)(n.Fragment,{children:l.drives?.map(e=>(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),t(e.path)},className:"w-full bg-surface hover:bg-surface-2 rounded-brand-lg p-4 flex items-center gap-3 transition-all duration-150 ease-out active:scale-[0.99] text-left",children:[(0,n.jsx)(t3.ak,{size:24,className:"text-blue-500/70"}),(0,n.jsxs)("div",{className:"flex-1",children:[(0,n.jsx)("div",{className:"text-text font-medium",children:i("files.drive",{letter:e.letter})}),(0,n.jsx)("div",{className:"text-text-muted text-sm",children:e.path})]}),(0,n.jsx)("svg",{className:"w-5 h-5 text-text-muted",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,n.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]},e.letter))}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),t("~")},className:"w-full bg-surface hover:bg-surface-2 rounded-brand-lg p-4 flex items-center gap-3 transition-all duration-150 ease-out active:scale-[0.99] text-left",children:[(0,n.jsx)(t3.ww,{size:24,className:"text-blue-500/70"}),(0,n.jsxs)("div",{className:"flex-1",children:[(0,n.jsx)("div",{className:"text-text font-medium",children:i("files.home")}),(0,n.jsx)("div",{className:"text-text-muted text-sm",children:"~/"})]}),(0,n.jsx)("svg",{className:"w-5 h-5 text-text-muted",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,n.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]}),(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),t("/")},className:"w-full bg-surface hover:bg-surface-2 rounded-brand-lg p-4 flex items-center gap-3 transition-all duration-150 ease-out active:scale-[0.99] text-left",children:[(0,n.jsx)(t3.ak,{size:24,className:"text-text-subtle"}),(0,n.jsxs)("div",{className:"flex-1",children:[(0,n.jsx)("div",{className:"text-text font-medium",children:i("files.root")}),(0,n.jsx)("div",{className:"text-text-muted text-sm",children:"/"})]}),(0,n.jsx)("svg",{className:"w-5 h-5 text-text-muted",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,n.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]})]}),a&&(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),t("/workspaces")},className:"w-full bg-purple-500/15 hover:bg-purple-500/25 rounded-brand-lg p-4 flex items-center gap-3 transition-all duration-150 ease-out active:scale-[0.99] text-left",children:[(0,n.jsx)(t3.sU,{size:24,className:"text-purple-400"}),(0,n.jsxs)("div",{className:"flex-1",children:[(0,n.jsx)("div",{className:"text-text font-medium",children:i("files.codespaces")}),(0,n.jsx)("div",{className:"text-purple-400 text-sm",children:"/workspaces"})]}),(0,n.jsx)("svg",{className:"w-5 h-5 text-purple-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,n.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]})]})]})]}),(0,n.jsx)(t9.A,{isOpen:d.isOpen,onClose:()=>u({isOpen:!1,path:null,name:""}),onConfirm:()=>{if(d.path){let e,t;e=e2(d.path),t=sn().filter(t=>t.path!==e),localStorage.setItem(st,JSON.stringify(t)),c(sn())}u({isOpen:!1,path:null,name:""})},title:i("files.removeTitle"),message:i("files.removeMessage",{name:d.name})})]})}let sl=(e,t)=>{if(Object.is(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;let s=Object.keys(e),n=Object.keys(t);if(s.length!==n.length)return!1;for(let n of s)if(e[n]!==t[n])return!1;return!0},si=(0,Z.v)((e,t)=>({isOpen:!1,activePanel:"menu",context:{connected:!1,remoteAvailable:!1,codespaceInfo:null,showTheme:!1,theme:"default",busRef:null,tunnelUrl:null,apiKey:null,hideActions:[],connectionMode:"tunnel",agentVersion:null,transport:"ws"},callbacks:{onRemote:null,onFiles:null,onCodespace:null,onLogout:null,onThemeChange:null,onStopCodespace:null,onUpdate:null,onRestart:null},cachedSites:[],currentSites:[],loadingSites:!1,open:(t="menu")=>e({isOpen:!0,activePanel:t}),close:()=>e({isOpen:!1,activePanel:"menu"}),setActivePanel:t=>e({activePanel:t}),setContext:t=>e(e=>{let s={...e.context,...t},n=!1;for(let t of Object.keys(s))if(!sl(e.context[t],s[t])){n=!0;break}return n?{context:s}:e}),setCallbacks:s=>{let n=t().callbacks,r=!1;for(let e of Object.keys(s))!!n[e]!=!!s[e]&&(r=!0),n[e]=s[e];r&&e({callbacks:{...n}})},setCachedSites:t=>e({cachedSites:t}),setCurrentSites:t=>e({currentSites:t}),setLoadingSites:t=>e({loadingSites:t}),openPwa:()=>e({isOpen:!0,activePanel:"pwa"}),openCodespace:()=>e({isOpen:!0,activePanel:"codespace"}),openMenu:()=>e({isOpen:!0,activePanel:"menu"})})),so=(e,t)=>{let{[t]:s,...n}=e;return n},sc=(0,Z.v)((e,t)=>({notifications:{},sessionStatus:{},handleStatusState:t=>e(e=>{let s=t||{};return tB(e.sessionStatus,s)?e:{sessionStatus:s}}),handleStatusChange:({sessionId:t,state:s,tool:n,since:r,conversationId:a})=>{t&&e(e=>{let l=e.sessionStatus[t],i={state:s,tool:void 0!==n?n:l?.tool,since:r,...a||l?.conversationId?{conversationId:a||l?.conversationId}:{}},o={...e.sessionStatus,[t]:i},c="done"===s||"blocked"===s,d=e.notifications;if(c){let a={sessionId:t,type:s,tool:n,timestamp:r};tF(e.notifications[t],a)||(d={...e.notifications,[t]:a})}else t in e.notifications&&(d=so(e.notifications,t));return{sessionStatus:o,notifications:d}})},handleStatusCleared:t=>{t&&e(e=>{let s=e.sessionStatus[t];return s?{sessionStatus:{...e.sessionStatus,[t]:{state:"idle",tool:s.tool,since:s.since}}}:e})},handleNotificationState:t=>e(e=>{let s=t||{};return tB(e.notifications,s)?e:{notifications:s}}),clearNotification:s=>{if(!s)return;let{notifications:n,sessionStatus:r}=t(),a=r[s]?.state;if("blocked"===a||!n[s]&&"done"!==a)return;e(e=>{let t=e.sessionStatus[s];return{notifications:s in e.notifications?so(e.notifications,s):e.notifications,sessionStatus:t?.state==="done"?{...e.sessionStatus,[s]:{state:"idle",tool:t.tool,since:t.since}}:e.sessionStatus}});let l=Q.getState().busRef?.current||Q.getState().bus;l?.emit("clearStatus",s)},reset:()=>e({notifications:{},sessionStatus:{}})})),sd={working:0,blocked:1,done:2,idle:3};function su(e={},t=[]){return(t.length?t.map(t=>{let s=e[t.id];return{id:t.id,state:s?.state||"idle",tool:s?.tool,since:s?.since}}):Object.entries(e).map(([e,t])=>({id:e,...t}))).sort((e,t)=>{let s=(sd[e.state]??9)-(sd[t.state]??9);return 0!==s?s:(t.since||0)-(e.since||0)})}function sm(e={},t=[]){let s=su(e,t),n=s.filter(e=>"blocked"===e.state),r=s.filter(e=>"done"===e.state);return{blocked:n.length,done:r.length,total:n.length+r.length,targetId:n[0]?.id||r[0]?.id||null}}let sx="9remote:push:userDisabled",sp="9Remote",sh="9Remote • ",sf=null,sb=0,sg=0,sv=null,sy=null;function sw(){!sy&&"u">typeof MutationObserver&&(sy=new MutationObserver(()=>{sv&&document.title!==sv&&sk(sv)})).observe(document.head,{childList:!0,subtree:!0,characterData:!0})}function sk(e){sv=e;let t=sy;t&&t.disconnect(),document.title=e;try{window.__TAURI__?.window?.getCurrentWindow?.().setTitle(e)?.catch?.(()=>{})}catch{}t&&t.observe(document.head,{childList:!0,subtree:!0,characterData:!0})}function sj(){let e=sh.slice(sb)+sh.slice(0,sb);sk(`(${sg}) 🔔 ${e}`),sb=(sb+1)%sh.length}function sN(e,t){sg=e,e>0?(sw(),sf||(sb=0,sj(),sf=setInterval(sj,400))):(sf&&(clearInterval(sf),sf=null),sb=0,t?(sw(),sk(`${t} • ${sp}`)):(sy&&(sy.disconnect(),sy=null),sv=null,document.title=sp))}function sS(e,{startWidth:t,axis:s=1,onWidth:n,onEnd:r}){e.preventDefault();let a=e.clientX,l=a,i=null,o=()=>{i=null,n((({startWidth:e,startX:t,x:s,axis:n=1})=>e+n*(s-t))({startWidth:t,startX:a,x:l,axis:s}))},c=e=>{0===e.buttons?d():(l=e.clientX,null===i&&(i=requestAnimationFrame(o)))},d=()=>{document.removeEventListener("pointermove",c),document.removeEventListener("pointerup",d),document.removeEventListener("pointercancel",d),window.removeEventListener("blur",d),document.body.style.cursor="",document.body.style.userSelect="",null!==i&&(cancelAnimationFrame(i),o()),r?.()};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("pointermove",c),document.addEventListener("pointerup",d),document.addEventListener("pointercancel",d),window.addEventListener("blur",d)}let sC=null,sT=(0,Z.v)((e,t)=>({canInstall:!1,isInstalled:!1,setDeferredPrompt:t=>{sC=t,e({canInstall:!!t})},setIsInstalled:t=>e({isInstalled:t}),install:async()=>{if(!sC)return null;sC.prompt();let t=await sC.userChoice;return sC=null,e({canInstall:!1}),t?.outcome??null}})),sR=!1,sE=new Set(["codex","aider","pi","omp"]),s_="rounded-[3px]";function s$(e){if(!e||"null"===e||"undefined"===e)return null;let t=e.replace(/-ui$/,"");return`/agent-icons/${t}.${sE.has(t)?"svg":"png"}`}function sM(e){return!!(e?.yolo||e?.yoloEnv)}function sP(e,t=!1){if(!e?.cmd)return null;if(!t)return e.cmd;if(e.yolo)return`${e.cmd} ${e.yolo}`;if(e.yoloEnv){let t=Object.entries(e.yoloEnv).map(([e,t])=>`${e}=${t}`).join(" ");return`${t} ${e.cmd}`}return e.cmd}let sA="9remote.terminal.shellPref",sz="9remote.terminal.agentPref",sI="9remote.terminal.yoloPref2";function sL(e){try{return localStorage.getItem(e)||null}catch{return null}}function sD(e,t){try{localStorage.setItem(e,t)}catch{}}function sF(){return{agentId:sL(sz)||"",shellId:sL(sA),yolo:"0"!==sL(sI)}}let sO=(e,t)=>"string"==typeof e&&e.startsWith(`${t}:`)?e.slice(t.length+1):null;function sB(e,t){return e.filter(e=>t&&e.key!==t).sort((e,t)=>("offline"===e.status)-("offline"===t.status)||(e.label||"").localeCompare(t.label||""))}let sW="9remote_fleet_cache",sK="9remote_fleet_focus",sH=new Map,sU=null;function sq(e){return e&&sH.get(e)?.busRef?.current||null}let sV=e=>({key:e,full:null,label:"",status:"offline",sessions:[],workspaces:[],statusMap:{},platform:null,version:null,lastSeenAt:null}),sX=(0,Z.v)((e,t)=>({hosts:{},currentKey:null,focus:function(){try{let e=localStorage.getItem(sK);return null===e?null:e}catch{return null}}(),overlayOpen:!1,sync(s,n){let r=n||"",a=new Map;for(let e of s){let t=(0,et.Uo)(e.key);t&&!a.has(t)&&a.set(t,{full:e.key,label:e.label||""})}r&&!a.has(r)&&a.set(r,{full:null,label:""});let l=[...a.keys()].filter(e=>e!==r).slice(0,8),i=new Set(l);for(let[e,t]of sH)i.has(e)||(t.disconnect(),sH.delete(e));let o=function(){try{return JSON.parse(localStorage.getItem(sW)||"{}")}catch{return{}}}();e(e=>{let t={};for(let[s,n]of a){let a=e.hosts[s]||{...sV(s),...o[s]||{}};t[s]={...a,key:s,full:n.full,label:n.label||a.label,status:s===r?"full":i.has(s)&&("online"===a.status||"connecting"===a.status)?a.status:"offline"}}return{hosts:t,currentKey:r}}),l.length&&fetch("/api/host-status",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({heads:l})}).then(e=>e.ok?e.json():null).then(e=>{for(let s of l){let n=e?.hosts?.[s];if(!n)continue;let r=t().hosts[s];r&&"connecting"!==r.status&&"full"!==r.status&&t()._patchHost(s,{status:n.online?"online":"offline"})}}).catch(()=>{})},_openHost(e){if(sH.has(e))return;let s=t().hosts[e],n=function(){try{return localStorage.getItem("9remote_deviceId")}catch{return null}}();if(!s||!n)return;let r=(0,et.Cj)(s.full);r&&(0,M.LG)(e,{tail:r});let a=s=>t()._patchHost(e,s),l=!1,i=null,o=e=>{e?.emit("getSessions",e=>{Array.isArray(e)&&a({sessions:e})}),e?.emit("getWorkspaces",e=>{Array.isArray(e)&&a({workspaces:e})}),e?.emit("getStatusState")},c=new Y({tunnelUrl:null,localIp:null,namespace:"",socketOptions:{auth:{apiKey:e,tempKey:null,deviceId:n}},apiKey:e,deviceId:n,tempKey:null,onConnect:s=>{clearTimeout(i),a({status:"online",lastSeenAt:Date.now()}),l||(l=!0,s.on("connect",()=>{s.emit("device:clientReady"),o(s)}),s.on("serverInfo",e=>a({platform:e?.platform||null,version:e?.version||null})),s.on("statusState",e=>a({statusMap:e||{}})),s.on("statusChange",({sessionId:s,state:n,tool:r,since:l}={})=>{s&&a({statusMap:{...t().hosts[e]?.statusMap||{},[s]:{state:n,tool:r,since:l}}})}),s.on("statusCleared",s=>{let n=t().hosts[e]?.statusMap;n?.[s]&&a({statusMap:{...n,[s]:{...n[s],state:"idle"}}})}),s.on("sessionsChanged",()=>o(s)),s.on("workspacesChanged",()=>o(s)),s.on("session-renamed",()=>o(s)),s.on("sessionClosed",()=>o(s)),s.on("device:rejected",()=>t()._closeHost(e)),s.on("device:tailRejected",()=>t()._closeHost(e)),s.emit("device:clientReady")),o(s)},onDisconnect:()=>t()._patchHost(e,{status:"offline",lastSeenAt:Date.now()})},{enableWebRTC:P.eR.enableWebRTC,enableTurn:P.eR.enableTurn,apiKey:e});sH.set(e,c),a({status:"connecting"}),i=setTimeout(()=>{t().hosts[e]?.status==="connecting"&&t()._patchHost(e,{status:"offline"})},15e3),c.connect()},_patchHost(s,n){e(e=>{let t=e.hosts[s];return t?{hosts:{...e.hosts,[s]:{...t,...n}}}:e}),clearTimeout(sU),sU=setTimeout(()=>{sU=null;let e={};for(let[s,n]of Object.entries(t().hosts))e[s]={label:n.label,platform:n.platform,version:n.version,sessions:n.sessions,workspaces:n.workspaces,statusMap:n.statusMap,lastSeenAt:n.lastSeenAt};try{localStorage.setItem(sW,JSON.stringify(e))}catch{}},1e3)},_closeHost(e){let s=sH.get(e);s&&(s.disconnect(),sH.delete(e)),t()._patchHost(e,{status:"offline",lastSeenAt:Date.now()})},setFocus(t){try{localStorage.setItem(sK,t)}catch{}e({focus:t})},ensureHost(e){e===t().currentKey||sH.has(e)||t()._openHost(e)},retryHost(e){let s=sH.get(e);s&&(s.disconnect(),sH.delete(e)),t()._openHost(e)},disconnectHost(e){t()._closeHost(e)},clearFocus(){try{localStorage.setItem(sK,"")}catch{}e({focus:""})},closeAll(){for(let e of sH.values())e.disconnect();sH.clear(),e({overlayOpen:!1})},openOverlay(){e({overlayOpen:!0})},closeOverlay(){e({overlayOpen:!1})}}));function sG(e,{onSelectSession:t=null}={}){let s=t=>{let s=sX.getState(),n=s.hosts[e.key]?.sessions||[];s._patchHost(e.key,{sessions:t(n)})};return{selectSession:s=>{sX.getState().ensureHost(e.key),t?.(s)},createSession:(n,r,a,l,i,o,c,d)=>{let u="string"==typeof i?i:i?.id||null,m=sq(e.key);m?m.emit("createSession",{name:n,shellId:a,workspaceId:r,cwd:l,nameIsAuto:c,agent:u},e=>{e?.success&&e.sessionId&&(s(t=>t.some(t=>t.id===e.sessionId)?t:[...t,{id:e.sessionId,name:e.name||n||"",createdAt:Date.now(),cwd:e.cwd||l||null,workspaceId:r||null,shellId:e.shellId||a||null,agent:u}]),t?.(e.sessionId)),d?.(e)}):sX.getState().ensureHost(e.key)},renameSession:(t,n)=>{sq(e.key)?.emit("renameSession",{sessionId:t,name:n},()=>{}),s(e=>e.map(e=>e.id===t?{...e,name:n}:e))},deleteSession:t=>{sq(e.key)?.emit("deleteSession",t,()=>{}),s(e=>e.filter(e=>e.id!==t))},reorderSession:t=>{sq(e.key)?.emit("reorderSession",{orderedIds:t},()=>{});let n=new Map(t.map((e,t)=>[e,t]));s(e=>[...e].sort((e,t)=>(n.get(e.id)??1/0)-(n.get(t.id)??1/0)))},renameWorkspace:(t,s)=>{sq(e.key)?.emit("renameWorkspace",{workspaceId:t,name:s},()=>{})},deleteWorkspace:t=>{sq(e.key)?.emit("deleteWorkspace",{workspaceId:t},()=>{})}}}let sJ=[{id:"sessionPrev",key:"ArrowLeft",label:"Previous terminal",mac:"⌥←",pc:"Ctrl+Shift+←"},{id:"sessionNext",key:"ArrowRight",label:"Next terminal",mac:"⌥→",pc:"Ctrl+Shift+→"},{id:"workspacePrev",key:"ArrowUp",label:"Previous workspace",mac:"⌥↑",pc:"Ctrl+Shift+↑"},{id:"workspaceNext",key:"ArrowDown",label:"Next workspace",mac:"⌥↓",pc:"Ctrl+Shift+↓"},{id:"closeTerminal",code:"KeyW",label:"Close terminal",mac:"⌥W",pc:"Alt+W"},{id:"fitPanes",key:"=",code:"Equal",label:"Auto-fit panes",mac:"⌥=",pc:"Ctrl+Shift+="},{id:"toggleFocus",code:"Backquote",label:"Toggle terminal / input focus",mac:"⌃`",pc:"Ctrl+`"},{id:"newTerminal",key:"Enter",label:"New terminal",mac:"⌥⇧↵",pc:"Ctrl+Shift+Enter"},{id:"palette",code:"KeyP",label:"Search files",mac:"⌥⇧P",pc:"Ctrl+Shift+P"},{id:"toggleSidebar",code:"KeyB",label:"Toggle sidebar",mac:"⌥⇧B",pc:"Ctrl+Shift+B"},{id:"toggleRightPanel",code:"KeyJ",label:"Toggle side panel",mac:"⌥⇧J",pc:"Ctrl+Shift+J"},{id:"help",code:"Slash",label:"Keyboard shortcuts",mac:"⌥⇧/",pc:"Ctrl+Shift+/"}],sY={id:"sessionIndex",label:"Go to terminal 1–9",mac:"⌥1…9",pc:"Ctrl+Shift+1…9"},sZ=[{id:"switchTerminal",label:"Switch terminal",mac:"⌥← / →",pc:"Ctrl+Shift+← / →"},sY,{id:"switchWorkspace",label:"Switch workspace",mac:"⌥↑ / ↓",pc:"Ctrl+Shift+↑ / ↓"},sJ.find(e=>"newTerminal"===e.id),sJ.find(e=>"closeTerminal"===e.id),sJ.find(e=>"fitPanes"===e.id),sJ.find(e=>"toggleFocus"===e.id),sJ.find(e=>"toggleSidebar"===e.id),sJ.find(e=>"toggleRightPanel"===e.id),sJ.find(e=>"palette"===e.id),sJ.find(e=>"help"===e.id)].filter(Boolean),sQ=/^Digit([1-9])$/,s0=null,s1=()=>{if(null!==s0)return s0;if("u"<typeof navigator)return!1;let e=navigator.userAgentData?.platform;return s0=e?"macOS"===e:/Mac/.test(navigator.platform||"")&&navigator.maxTouchPoints<=1},s2=e=>s1()?e.mac:e.pc,s5="inline-flex h-6 min-w-6 items-center justify-center px-1.5 font-mono text-xs font-medium text-text leading-none select-none bg-surface-2 border border-border border-b-2 rounded-md shadow-[inset_0_-1px_0_rgba(0,0,0,0.08)] whitespace-nowrap",s3=new Set(["⌘","⌥","⇧","⌃"]);function s4(e){let t=s2(e);if(t.includes("+"))return t.split("+");let s=[],n=t;n.startsWith("Opt ")&&(s.push("Opt"),n=n.slice(4));let r=0;for(;r<n.length&&s3.has(n[r]);)s.push(n[r]),r++;return r<n.length&&s.push(n.slice(r)),s}let s6=e=>!!e&&"function"==typeof e.closest&&!!(e.closest("[role=dialog]")||e.closest(".modal-overlay")||e.closest(".card-elev")),s8=e=>!(!e||"function"!=typeof e.closest||e.closest(".xterm"))&&(e.isContentEditable||"INPUT"===e.tagName||"TEXTAREA"===e.tagName);function s9(e,t){let s=sJ.find(e=>e.id===t);return s?`${e} \xb7 ${s2(s)}`:e}let s7=(0,Z.v)(e=>({isOpen:!1,open:()=>e({isOpen:!0}),close:()=>e({isOpen:!1}),toggle:()=>e(e=>({isOpen:!e.isOpen}))}));function ne(e,t="main"){let s=tS(e=>e.agentClisBy[t]?.list),n=sX(e=>e.hosts[t]?.status||null);return(0,r.useEffect)(()=>{let s=tS.getState().agentClisBy[t];s&&Date.now()-s.at<6e4||e?.current?.emit("getAgentClis",e=>{let s=Array.isArray(e?.agents)?e.agents:Array.isArray(e)?e:null;s&&tS.getState().setAgentClis(t,s)})},[e,t,n]),s}var nt=s(39096);let ns=(e,t=[])=>{let s=e.trim().split(/\s+/).filter(Boolean).map(e=>e[0]).join("").toLowerCase().replace(/[^a-z0-9]/g,"");if(!s)return"";let n=s,r=2;for(;t.includes(n);)n=`${s}${r++}`;return n},nn=e=>(0,Z.v)((0,es.Zr)((e,t)=>({history:[],pinned:[],addCommand:t=>e(e=>{let s=t.trim();return!s||s.length>500||e.history[0]===s?e:{history:[s,...e.history.filter(e=>e!==s)].slice(0,100)}}),removeCommand:t=>e(e=>({history:e.history.filter(e=>e!==t)})),togglePin:t=>e(e=>{let s=t.trim();if(!s)return e;if(e.pinned.some(e=>e.cmd===s))return{pinned:e.pinned.filter(e=>e.cmd!==s)};let n=ns(s,e.pinned.map(e=>e.alias));return{pinned:[{cmd:s,alias:n},...e.pinned]}}),setSnippet:(t,s)=>e(e=>({pinned:e.pinned.map(e=>e.cmd===t?{cmd:(s.cmd??e.cmd).trim(),alias:(s.alias??e.alias).trim()}:e)})),resolveAlias:e=>{let s=e.trim(),n=t().pinned.find(e=>e.alias&&e.alias===s);return n?n.cmd:e},clearHistory:()=>e({history:[]})}),{name:e,version:1,migrate:(e,t)=>{if(t<1&&e?.pinned){let t=[];e.pinned=e.pinned.map(e=>{let s=ns(e,t);return t.push(s),{cmd:e,alias:s}})}return e},storage:{getItem:e=>{try{let t=localStorage.getItem(e);return t?JSON.parse(t):null}catch{return null}},setItem:(e,t)=>{try{localStorage.setItem(e,JSON.stringify(t))}catch{}},removeItem:e=>{localStorage.removeItem(e)}}})),nr=nn("terminal-command-history"),na=nn("remote-input-history"),nl=nn("ai-command-history");function ni({snippet:e,onSave:t,onClose:s}){let{t:a}=(0,se.s)(),[l,i]=(0,r.useState)(e?.alias??""),[o,c]=(0,r.useState)(e?.cmd??""),d=(0,r.useRef)(null);if((0,r.useEffect)(()=>{let e=e=>{"Escape"===e.key&&s()};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[s]),!e)return null;let u=o.trim().length>0;return(0,n.jsxs)("div",{className:"fixed inset-0 z-[70] flex items-center justify-center p-4",children:[(0,n.jsx)("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-[2px] animate-in fade-in duration-200",onClick:s}),(0,n.jsxs)("div",{className:"relative card-elev max-w-md w-full flex flex-col animate-in zoom-in-95 duration-200",children:[(0,n.jsxs)("div",{className:"px-5 py-4 flex items-center justify-between flex-shrink-0",children:[(0,n.jsx)("h3",{className:"text-lg font-semibold text-text",children:a("history.editSnippet")}),(0,n.jsx)("button",{onClick:s,className:"p-2 text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-all duration-150 ease-out","aria-label":a("common.close"),children:(0,n.jsx)(t3.X,{size:20})})]}),(0,n.jsxs)("div",{className:"px-5 pb-5 flex flex-col gap-4",children:[(0,n.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,n.jsx)("label",{className:"text-xs font-semibold uppercase tracking-wide text-text-muted",children:a("history.aliasLabel")}),(0,n.jsx)("input",{type:"text",value:l,onChange:e=>i(e.target.value),placeholder:a("history.aliasPlaceholder"),autoCapitalize:"off",autoCorrect:"off",spellCheck:!1,className:"w-full px-3 py-2 bg-surface-2 text-text font-mono text-sm rounded-brand outline-none focus:ring-1 focus:ring-brand-500"}),(0,n.jsx)("span",{className:"text-xs text-text-subtle",children:a("history.aliasHint")})]}),(0,n.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,n.jsx)("label",{className:"text-xs font-semibold uppercase tracking-wide text-text-muted",children:a("history.commandLabel")}),(0,n.jsx)("textarea",{ref:d,value:o,onChange:e=>c(e.target.value),rows:3,autoCapitalize:"off",autoCorrect:"off",spellCheck:!1,className:"w-full px-3 py-2 bg-surface-2 text-text font-mono text-sm rounded-brand outline-none focus:ring-1 focus:ring-brand-500 resize-y min-h-[60px] max-h-[240px]"})]}),(0,n.jsxs)("div",{className:"flex items-center justify-end gap-2",children:[(0,n.jsx)("button",{onClick:s,className:"px-4 py-2 text-sm bg-surface-3 hover:bg-surface text-text rounded-brand transition-colors",children:a("common.cancel")}),(0,n.jsxs)("button",{onClick:()=>{u&&((0,t7.e)(),t({cmd:o.trim(),alias:l.trim()}),s())},disabled:!u,className:"px-4 py-2 text-sm bg-brand-500 hover:bg-brand-500/80 text-white rounded-brand transition-colors flex items-center gap-1.5 disabled:opacity-40 disabled:cursor-not-allowed",children:[(0,n.jsx)(t3.aJ,{size:16}),a("common.save")]})]})]})]})]})}function no({isOpen:e,onSelect:t,onClose:s,store:a=nr}){let{t:l}=(0,se.s)(),i=a(e=>e.history),o=a(e=>e.pinned),c=a(e=>e.removeCommand),d=a(e=>e.clearHistory),u=a(e=>e.togglePin),m=a(e=>e.setSnippet),[x,p]=(0,r.useState)(null);if((0,r.useEffect)(()=>{if(!e)return;document.activeElement?.blur?.();let t=e=>{"Escape"!==e.key||x||s()};return window.addEventListener("keydown",t),()=>window.removeEventListener("keydown",t)},[e,s,x]),!e)return null;let h=e=>{(0,t7.e)(),t(e),s()};return(0,n.jsxs)("div",{className:"fixed inset-0 z-[60] flex items-center justify-center p-4",children:[(0,n.jsx)("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-[2px] animate-in fade-in duration-200 touch-none",onClick:s}),(0,n.jsxs)("div",{className:"relative card-elev max-w-lg w-full max-h-[90dvh] flex flex-col animate-in zoom-in-95 duration-200",children:[(0,n.jsxs)("div",{className:"px-5 py-4 flex items-center justify-between flex-shrink-0",children:[(0,n.jsx)("h3",{className:"text-lg font-semibold text-text",children:l("history.title")}),(0,n.jsxs)("div",{className:"flex items-center gap-1",children:[i.length>0&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),d()},className:"p-2 text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-all duration-150 ease-out","aria-label":l("history.clearAll"),title:l("history.clearAll"),children:(0,n.jsx)(t3.TB,{size:18})}),(0,n.jsx)("button",{onClick:s,className:"p-2 text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-all duration-150 ease-out","aria-label":l("common.close"),children:(0,n.jsx)(t3.X,{size:20})})]})]}),(0,n.jsx)("div",{className:"flex-1 overflow-y-auto modal-scrollable p-3",children:0===o.length&&0===i.length?(0,n.jsxs)("div",{className:"flex flex-col items-center justify-center gap-2 py-12 text-text-muted",children:[(0,n.jsx)(t3.BZ,{size:32,className:"opacity-50"}),(0,n.jsx)("span",{className:"text-sm",children:l("history.empty")})]}):(0,n.jsxs)("div",{className:"flex flex-col gap-0",children:[o.length>0&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"px-3 pt-1 pb-0.5 text-xs font-semibold uppercase tracking-wide text-text-muted",children:l("history.snippets")}),o.map(e=>(0,n.jsxs)("div",{className:"group flex items-center gap-2 rounded-brand hover:bg-surface-2 transition-all duration-150 ease-out",children:[(0,n.jsxs)("button",{onClick:()=>h(e.cmd),className:"flex-1 min-w-0 px-3 py-1 text-left flex items-center gap-2",children:[e.alias&&(0,n.jsx)("span",{className:"flex-shrink-0 px-1.5 py-0.5 text-xs font-mono font-semibold text-brand-500 bg-brand-500/10 rounded",children:e.alias}),(0,n.jsx)("span",{className:"min-w-0 text-sm text-text font-mono truncate",title:e.cmd,children:e.cmd})]}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),p(e)},className:"flex-shrink-0 p-2 text-text-muted hover:text-text rounded-brand transition-colors","aria-label":l("history.editSnippet"),children:(0,n.jsx)(t3.gH,{size:16})}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),u(e.cmd)},className:"flex-shrink-0 p-2 mr-1 text-brand-500 hover:text-brand-400 rounded-brand transition-colors","aria-label":l("history.unpin"),children:(0,n.jsx)(t3.yU,{size:16,fill:"currentColor"})})]},`p-${e.cmd}`)),(0,n.jsx)("div",{className:"h-px bg-border/40 my-1"})]}),i.length>0&&(0,n.jsxs)(n.Fragment,{children:[o.length>0&&(0,n.jsx)("div",{className:"px-3 pt-0.5 pb-0.5 text-xs font-semibold uppercase tracking-wide text-text-muted",children:l("history.history")}),i.map(e=>{let t=o.some(t=>t.cmd===e);return(0,n.jsxs)("div",{className:"group flex items-center gap-2 rounded-brand hover:bg-surface-2 transition-all duration-150 ease-out",children:[(0,n.jsx)("button",{onClick:()=>h(e),className:"flex-1 min-w-0 px-3 py-1 text-left text-sm text-text font-mono truncate",title:e,children:e}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),u(e)},className:`flex-shrink-0 p-2 rounded-brand transition-colors ${t?"text-brand-500 hover:text-brand-400":"text-text-muted hover:text-text"}`,"aria-label":t?l("history.unpin"):l("history.pin"),children:(0,n.jsx)(t3.yU,{size:16,fill:t?"currentColor":"none"})}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),c(e)},className:"flex-shrink-0 p-2 mr-1 text-text-muted hover:text-text rounded-brand transition-colors","aria-label":l("common.delete"),children:(0,n.jsx)(t3.X,{size:16})})]},e)})]})]})})]}),x&&(0,n.jsx)(ni,{snippet:x,onSave:e=>m(x.cmd,e),onClose:()=>p(null)})]})}let nc={pinned:2,history:4,common:4,total:8},nd={pinned:1,history:2,common:2,total:4},nu=(e,t)=>{let s=e.indexOf(t);return s<0?null:1e3*(0!==s)+s+.1*e.length};function nm(e,t,s,n,r){let a=e.trim().toLowerCase();if(!a)return[];let l=new Set,i=(e,t,s)=>{let n=[];for(let r of e){let e=s(r),i=e.toLowerCase();if(!e||i===a||l.has(i))continue;let o=nu(i,a);null!==o&&(l.add(i),n.push({cmd:e,type:t,score:o}))}return n.sort((e,t)=>e.score-t.score)},o={pinned:i(s,"pinned",e=>e.cmd),history:i(t,"history",e=>e),common:i(n,"common",e=>e)},c=r?nd:nc,d=[...o.pinned.slice(0,c.pinned),...o.history.slice(0,c.history),...o.common.slice(0,c.common)];if(d.length<c.total){let e=new Set(d.map(e=>e.cmd)),t=[...o.pinned,...o.history,...o.common].filter(t=>!e.has(t.cmd)).sort((e,t)=>e.score-t.score).slice(0,c.total-d.length);d.push(...t)}return d.slice(0,c.total)}function nx({value:e,store:t,commonCommands:s=[],onSelect:a,isMobile:l=!1,disabled:i=!1,activeIndex:o=-1}){let c=t(e=>e.history),d=t(e=>e.pinned),[u,m]=(0,r.useState)(""),x=(0,r.useMemo)(()=>i?[]:nm(e,c,d,s,l),[e,c,d,s,l,i]),p=(0,r.useRef)(null);return((0,r.useEffect)(()=>{let e=p.current;if(!e||o<0)return;let t=e.children[o];t&&t.scrollIntoView({block:"nearest"})},[o]),0===x.length||u===e)?null:(0,n.jsxs)("div",{className:"absolute bottom-full left-0 right-0 mb-1 z-40 rounded-brand overflow-hidden bg-surface/95 backdrop-blur-xl shadow-xl ring-1 ring-border touch-none",children:[(0,n.jsx)("button",{type:"button",onMouseDown:e=>e.preventDefault(),onClick:()=>m(e),className:"absolute right-1 top-1 z-10 w-5 h-5 flex items-center justify-center rounded-full bg-surface-2/80 text-text-muted hover:text-text transition-colors","aria-label":"Close",children:(0,n.jsx)(t3.X,{size:12})}),(0,n.jsx)("div",{ref:p,className:"flex flex-col max-h-[25vh] overflow-y-auto modal-scrollable",children:x.map((e,t)=>{let s;return(0,n.jsxs)("button",{onMouseDown:e=>e.preventDefault(),onClick:()=>{(0,t7.e)(),a(e.cmd)},className:`flex items-center gap-2 px-3 py-1.5 text-left hover:bg-surface-2 transition-colors touch-none ${t===o?"bg-brand-500/15":""}`,children:[(0,n.jsx)("span",{className:"flex-shrink-0",children:"pinned"===(s=e.type)?(0,n.jsx)(t3.yU,{size:13,className:"text-brand-500",fill:"currentColor"}):"common"===s?(0,n.jsx)(t3.BK,{size:13,className:"text-text-muted"}):(0,n.jsx)(t3.BZ,{size:13,className:"text-text-muted"})}),(0,n.jsx)("span",{className:"min-w-0 text-sm text-text font-mono truncate",title:e.cmd,children:e.cmd})]},`${e.type}-${e.cmd}`)})})]})}let np={en:"en-US",vi:"vi-VN",zh:"zh-CN",ja:"ja-JP",ko:"ko-KR",es:"es-ES",fr:"fr-FR",de:"de-DE",pt:"pt-BR",ru:"ru-RU",ar:"ar-SA",hi:"hi-IN",id:"id-ID",th:"th-TH",tr:"tr-TR",it:"it-IT",nl:"nl-NL",pl:"pl-PL",uk:"uk-UA",fa:"fa-IR",ms:"ms-MY",sv:"sv-SE",he:"he-IL"},nh=e=>np[e]||e||"en-US",nf="voiceLang";function nb(e){let[t,s]=(0,r.useState)(e);return(0,r.useEffect)(()=>{let e=localStorage.getItem(nf);e&&np[e]&&s(e)},[]),[t,(0,r.useCallback)(e=>{s(e);try{localStorage.setItem(nf,e)}catch{}},[])]}let ng=new Set(["not-allowed","service-not-allowed","audio-capture","language-not-supported"]);function nv(){return window.SpeechRecognition||window.webkitSpeechRecognition||null}function ny({lang:e="en-US",onText:t,onError:s,onFinish:n}={}){let a=tD(e=>e.mode),l=tD(e=>e.enabled),[i,o]=(0,r.useState)(!1),[c,d]=(0,r.useState)(!1),[u,m]=(0,r.useState)(0),[x,p]=(0,r.useState)(null),h=(0,r.useRef)(n);(0,r.useEffect)(()=>{h.current=n},[n]);let f=(0,r.useRef)(s);(0,r.useEffect)(()=>{f.current=s},[s]);let b=(0,r.useRef)(t);(0,r.useEffect)(()=>{b.current=t},[t]);let g=(0,r.useRef)(!1),v=(0,r.useRef)(e);(0,r.useEffect)(()=>{if(v.current=e,g.current)try{y.current?.stop()}catch{}},[e]);let y=(0,r.useRef)(null),w=(0,r.useRef)(null),k=(0,r.useRef)(""),j=!!window.ReactNativeWebView||/9Remote-Mobile/i.test(navigator.userAgent),N="ai"===a?!!(navigator.mediaDevices?.getUserMedia&&window.MediaRecorder):!j&&!!nv(),S=(0,r.useCallback)(async()=>{g.current=!1;let e=w.current;if(w.current=null,!e){o(!1),d(!1),m(0);return}clearInterval(e.timer),m(0),d(!0);try{"inactive"!==e.rec.state&&e.rec.stop()}catch{}await e.stopped,e.stream.getTracks().forEach(e=>e.stop());try{e.ctx.close()}catch{}try{let t=new Blob(e.chunks,{type:e.rec.mimeType||"audio/webm"}),s=await tz(tD.getState(),t,v.current),n=`${k.current}${s}`.replace(/\s+/g," ").trimStart();b.current?.(n),s?.trim()&&h.current?.(n)}catch(e){p("network"),f.current?.("network")}finally{o(!1),d(!1),m(0)}},[]),C=(0,r.useCallback)(async(e="")=>{k.current=e?e.replace(/\s*$/,"")+" ":"",p(null),g.current=!0,m(0),d(!1);try{let e=await navigator.mediaDevices.getUserMedia({audio:!0}),t=new MediaRecorder(e),s=[];t.ondataavailable=e=>{e.data.size&&s.push(e.data)};let n=new Promise(e=>{t.onstop=e}),r=new AudioContext;try{await r.resume()}catch{}let a=r.createAnalyser();a.fftSize=512,r.createMediaStreamSource(e).connect(a);let l=new Uint8Array(a.fftSize),i=setInterval(()=>{a.getByteTimeDomainData(l);let e=0;for(let t=0;t<l.length;t++)e+=Math.abs(l[t]-128);let t=e/l.length;m(Math.min(1,Math.max(0,(t-2)/20)))},80);w.current={stream:e,rec:t,chunks:s,stopped:n,ctx:r,timer:i},t.start(),o(!0)}catch(t){g.current=!1;let e=t?.name==="NotAllowedError"||t?.name==="SecurityError"?"not-allowed":"audio-capture";p(e),f.current?.(e)}},[]),T=(0,r.useCallback)(()=>{g.current=!1;let e=w.current;if(w.current=null,e){clearInterval(e.timer);try{"inactive"!==e.rec.state&&e.rec.stop()}catch{}e.stream.getTracks().forEach(e=>e.stop());try{e.ctx.close()}catch{}}try{y.current?.abort()}catch{}o(!1),d(!1),m(0)},[]),R=(0,r.useCallback)(()=>{if(g.current=!1,"ai"===a)return void S();try{y.current?.stop()}catch{}},[a,S]),E=(0,r.useCallback)(function e(){let t=nv();if(!t)return;let s=new t;s.lang=v.current,s.continuous=!0,s.interimResults=!0,s.onresult=e=>{if(!g.current)return;let t="",s="";for(let n=e.resultIndex;n<e.results.length;n++){let r=e.results[n][0].transcript;e.results[n].isFinal?t+=r:s+=r}t&&(k.current=`${k.current}${t} `.replace(/\s+/g," "));let n=`${k.current}${s}`.replace(/\s+/g," ").trimStart();b.current?.(n)},s.onend=()=>{if(y.current=null,g.current)try{e()}catch{o(!1)}else{o(!1),m(0);let e=k.current.trim();e&&h.current?.(e)}},s.onerror=e=>{let t=e?.error||"error";"no-speech"!==t&&"aborted"!==t&&(p(t),f.current?.(t),ng.has(t)&&(g.current=!1,o(!1)))},y.current=s;try{s.start(),o(!0)}catch(e){console.warn("[voice] start failed:",e),y.current||(o(!1),g.current=!1)}},[]),_=(0,r.useCallback)((e="")=>{"ai"===a?C(e):!j&&nv()&&(k.current=e?e.replace(/\s*$/,"")+" ":"",p(null),g.current=!0,E())},[j,a,C,E]),$=(0,r.useCallback)((e="")=>{i?R():_(e)},[i,_,R]);return(0,r.useEffect)(()=>()=>{g.current=!1;try{y.current?.abort()}catch{}let e=w.current;if(e){w.current=null,clearInterval(e.timer);try{"inactive"!==e.rec.state&&e.rec.stop()}catch{}e.stream.getTracks().forEach(e=>e.stop());try{e.ctx.close()}catch{}}},[]),{supported:N,active:l&&N,listening:i,transcribing:c,volume:u,error:x,start:_,stop:R,cancel:T,toggle:$}}let nw="(pointer: fine) and (hover: hover)";function nk(){let[e,t]=(0,r.useState)(()=>window.matchMedia(nw).matches?"mouse":"touch");return(0,r.useEffect)(()=>{let e=window.matchMedia(nw),s=()=>{t(e.matches?"mouse":"touch")};return s(),e.addEventListener?e.addEventListener("change",s):e.addListener(s),()=>{e.removeEventListener?e.removeEventListener("change",s):e.removeListener(s)}},[]),e}function nj(e,t){let[s,n]=(0,r.useState)(t),a=(0,r.useRef)(!0),l=(0,r.useRef)(e);(0,r.useEffect)(()=>{l.current!==e&&(l.current=e,a.current=!0);try{let t=window.localStorage.getItem(e);null!==t&&n(JSON.parse(t))}catch(t){console.warn(`usePersistedState: failed to read "${e}"`,t)}},[e]),(0,r.useEffect)(()=>{if(a.current){a.current=!1;return}try{window.localStorage.setItem(e,JSON.stringify(s))}catch(t){console.warn(`usePersistedState: failed to write "${e}"`,t)}},[e,s]);let i=(0,r.useCallback)(()=>n(t),[t]);return[s,n,i]}function nN(e,t,s,n="flat",a=[]){let[l,i,o]=nj(e,s),c=(0,r.useMemo)(()=>new Map(t.map(e=>[e.id,e])),[t]),d="grid"===n?l?.flat?.():l,u=(e,t)=>Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((e,s)=>e===t[s]),m=d&&a.some(e=>"grid"===n?u(e.flat(),d):u(e,d)),x=m?s:l,p=(0,r.useCallback)(e=>e.map(e=>c.get(e)).filter(Boolean),[c]),h="grid"===n&&Array.isArray(s)?s.length:1,f=(0,r.useMemo)(()=>"grid"===n?Array.isArray(x)&&x.length===h&&x.every(Array.isArray)?x:s:[Array.isArray(x)?x:[]],[x,n,s,h]),b=(0,r.useMemo)(()=>p(f.flat()),[f,p]),g=(0,r.useMemo)(()=>{let e=new Set(b.map(e=>e.id));return t.filter(t=>!e.has(t.id))},[b,t]),v=(0,r.useCallback)(e=>"grid"===n?x[e]||[]:x,[x,n]);(0,r.useEffect)(()=>{m&&i(s)},[m,s,i]);let y=(0,r.useCallback)(e=>{i(t=>"grid"===n?e(Array.isArray(t)&&t.length===h&&t.every(Array.isArray)?t.map(e=>[...e]):s.map(e=>[...e])):e([[...Array.isArray(t)?t:[]]])[0])},[i,n,s,h]),w=(0,r.useCallback)((e,t=0)=>{y(s=>(s[t]||(s[t]=[]),s.flat().includes(e)||(s[t]=[...s[t],e]),s))},[y]),k=(0,r.useCallback)((e,t)=>{y(s=>(s[e]&&(s[e]=s[e].filter((e,s)=>s!==t)),s))},[y]);return{mode:n,rows:f,keys:b,available:g,getRow:v,add:w,removeAt:k,replaceAt:(0,r.useCallback)((e,t,s)=>{y(n=>{if(n[e]||(n[e]=[]),n.flat().indexOf(s)>=0)for(let e of n){let t=e.indexOf(s);t>=0&&e.splice(t,1)}return t>=n[e].length?n[e].push(s):n[e][t]=s,n})},[y]),swap:(0,r.useCallback)((e,t)=>{y(s=>{let n=s[e.row],r=s[t.row];if(!n||!r)return s;let a=n[e.col];return n[e.col]=r[t.col],r[t.col]=a,s})},[y]),reset:o}}let nS="min-w-[38px] h-9 px-2 flex items-center justify-center rounded-brand text-xs font-semibold select-none shrink-0 whitespace-nowrap transition-all duration-150 ease-out active:scale-[0.96]",nC="bg-brand-500 text-white";function nT({label:e,selected:t,onClick:s}){return(0,n.jsx)("button",{type:"button",onClick:()=>{(0,t7.e)(),s()},className:`${nS} ${t?nC:"bg-surface-2 hover:bg-surface-3 text-text"}`,children:e})}function nR({selected:e,onClick:t}){return(0,n.jsx)("button",{type:"button",onClick:()=>{(0,t7.e)(),t()},className:`${nS} ${e?nC:"border border-dashed border-border text-text-subtle hover:text-text hover:bg-surface-2"}`,title:"Select this slot, then pick a key below",children:(0,n.jsx)(t3.FW,{size:16})})}function nE({isOpen:e,onClose:t,title:s="Customize Keys",tabs:a}){let[l,i]=(0,r.useState)(a?.[0]?.id),[o,c]=(0,r.useState)(null);if((0,r.useEffect)(()=>{e&&c(null)},[e]),(0,r.useEffect)(()=>{if(!e)return;let s=e=>{"Escape"===e.key&&t()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e,t]),(0,r.useEffect)(()=>{c(null)},[l]),!e)return null;let d=a.find(e=>e.id===l)||a[0],{rows:u,available:m,replaceAt:x,swap:p,removeAt:h,reset:f}=d.hook,b=d.excludeIds||[],g=u.map(e=>e.map((e,t)=>({id:e,rawCol:t})).filter(e=>!b.includes(e.id))),v=g.map(e=>e.map(e=>e.id)),y=b.length?m.filter(e=>!b.includes(e.id)):m,w=(e,t)=>{let s=g[e]||[];return t>=s.length?(u[e]||[]).length:s[t].rawCol},k=(e,t)=>o&&o.row===e&&o.col===t,j=(e,t,s)=>{if(!s&&k(e,t))return void c(null);if(o&&!s&&!(o.col>=v[o.row].length)){p({row:o.row,col:w(o.row,o.col)},{row:e,col:w(e,t)}),c(null);return}c({row:e,col:t})},N=new Map;d.hook.keys?.forEach(e=>N.set(e.id,e)),y.forEach(e=>N.set(e.id,e));let S=o&&v[o.row]&&o.col<v[o.row].length;return(0,n.jsxs)("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",children:[(0,n.jsx)("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-[2px]",onClick:t}),(0,n.jsxs)("div",{className:"relative card-elev w-full max-w-2xl max-h-[85dvh] flex flex-col",children:[(0,n.jsxs)("div",{className:"px-5 py-3 flex items-center justify-between",children:[(0,n.jsx)("h3",{className:"text-base font-semibold text-text",children:s}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),t()},className:"text-text-muted hover:text-text",children:(0,n.jsx)(t3.X,{size:18})})]}),a.length>1&&(0,n.jsx)("div",{className:"px-5 pt-1 flex gap-2 border-b border-border-subtle",children:a.map(e=>(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),i(e.id)},className:`px-3 py-2 -mb-px text-xs font-semibold border-b-2 transition-colors duration-150 ${l===e.id?"text-brand-400 border-brand-500":"text-text-muted border-transparent hover:text-text"}`,children:e.label},e.id))}),(0,n.jsxs)("div",{className:"flex-1 overflow-y-auto p-5 space-y-4",children:[(0,n.jsxs)("div",{children:[(0,n.jsxs)("div",{className:"flex items-center justify-between mb-2",children:[(0,n.jsx)("div",{className:"text-xs text-text-muted",children:o?"Click another to swap, or Remove below":"Click to select"}),S&&(0,n.jsxs)("button",{onClick:()=>{if(!o)return;let e=v[o.row]||[];o.col<e.length&&h(o.row,w(o.row,o.col)),c(null)},className:"flex items-center gap-1 px-2 py-1 text-xs text-red-400 hover:text-red-300",children:[(0,n.jsx)(t3.TB,{size:14})," Remove"]})]}),(0,n.jsx)("div",{className:"space-y-1.5 p-2 rounded-brand bg-surface-2",children:v.map((e,t)=>(0,n.jsxs)("div",{className:"modal-scrollable flex items-center gap-1.5 overflow-x-auto pb-1",children:[e.map((e,s)=>{let r=N.get(e);return(0,n.jsx)(nT,{label:r?.label||e,selected:k(t,s),onClick:()=>j(t,s,!1)},e+s)}),(0,n.jsx)(nR,{selected:k(t,e.length),onClick:()=>j(t,e.length,!0)})]},t))})]}),(0,n.jsxs)("div",{children:[(0,n.jsxs)("div",{className:"text-xs text-text-muted mb-2",children:["Available — click to ",o?S?"replace selected":"add to slot":"add"]}),(0,n.jsxs)("div",{className:"flex flex-wrap gap-1.5 p-2 rounded-brand bg-surface-2",children:[0===y.length&&(0,n.jsx)("div",{className:"text-xs text-text-muted italic",children:"All keys added."}),y.map(e=>(0,n.jsx)(nT,{label:e.label,onClick:()=>(e=>{if(o)x(o.row,w(o.row,o.col),e);else{let t=v.length>0?v.length-1:0;x(t,(u[t]||[]).length,e)}c(null)})(e.id)},e.id))]})]})]}),(0,n.jsxs)("div",{className:"px-5 py-3 flex items-center justify-between",children:[(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),f(),c(null)},className:"px-3 py-1.5 text-xs text-text-muted hover:text-text transition-colors",children:"↺ Reset to default"}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),t()},className:"px-4 py-1.5 bg-brand-500 hover:bg-brand-600 text-white text-sm font-semibold rounded-brand transition-all duration-150 ease-out active:scale-[0.97]",children:"Done"})]})]})]})}function n_({bus:e,sessionId:t}){let{t:s}=(0,se.s)(),[n,a]=(0,r.useState)([]),l=(0,r.useRef)(0),i=(0,r.useCallback)(e=>new Promise(t=>{if(e.size>5242880)return alert(s("mobileKeyboard.fileTooLarge")),t(null);let n=new FileReader;n.onload=()=>{let s=n.result.split(",")[1],r=e.type.startsWith("image/"),a=e.name||`paste_${l.current}.${r?e.type.split("/")[1]||"png":"bin"}`;t({id:++l.current,name:a,type:e.type,size:e.size,content:s,isImage:r})},n.onerror=()=>{alert(s("mobileKeyboard.readFileFailed")),t(null)},n.readAsDataURL(e)}),[s]),o=(0,r.useCallback)(async e=>{let t=5-n.length;if(t<=0)return;let s=Array.from(e).slice(0,t),r=(await Promise.all(s.map(i))).filter(Boolean);r.length&&((0,t7.e)(),a(e=>[...e,...r]))},[n.length,i]),c=(0,r.useCallback)(e=>{a(t=>t.filter(t=>t.id!==e))},[]),d=(0,r.useCallback)(s=>new Promise(n=>{let r=!1,a=()=>{r||(r=!0,n())};e.emit("clipboard-attach",{sessionId:t,filename:s.name,type:s.type,content:s.content},a),setTimeout(a,3e3)}),[e,t]),u=(0,r.useCallback)(async e=>{(0,t7.e)();let t=e.target.files;t?.length&&await o(t),e.target.value=""},[o]),m=(0,r.useCallback)(e=>{let t=e.clipboardData?.items;if(!t)return;let s=[];for(let e of t)if("file"===e.kind){let t=e.getAsFile();t&&s.push(t)}s.length&&(e.preventDefault(),o(s))},[o]);return{attachments:n,setAttachments:a,addFiles:o,removeAttachment:c,sendOneAttachment:d,handleFileUpload:u,handleAttachPaste:m}}let n$={ArrowUp:"\x1b[A",ArrowDown:"\x1b[B",ArrowRight:"\x1b[C",ArrowLeft:"\x1b[D",Escape:"\x1b",Tab:" ",Enter:"\r",Backspace:"",Delete:"\x1b[3~",Home:"\x1b[H",End:"\x1b[F",PageUp:"\x1b[5~",PageDown:"\x1b[6~",Insert:"\x1b[2~",F1:"\x1bOP",F2:"\x1bOQ",F3:"\x1bOR",F4:"\x1bOS",F5:"\x1b[15~",F6:"\x1b[17~",F7:"\x1b[18~",F8:"\x1b[19~",F9:"\x1b[20~",F10:"\x1b[21~",F11:"\x1b[23~",F12:"\x1b[24~"},nM={ArrowUp:"\x1b[1;5A",ArrowDown:"\x1b[1;5B",ArrowRight:"\x1b[1;5C",ArrowLeft:"\x1b[1;5D"},nP={ArrowUp:"\x1b[1;2A",ArrowDown:"\x1b[1;2B",ArrowRight:"\x1b[1;2C",ArrowLeft:"\x1b[1;2D"},nA={"[":"\x1b","]":"\x1d","\\":"\x1c","@":"\0","?":""};var nz=s(70362),nI=s(50068);function nL({items:e,onSelect:t,activeIndex:s=-1}){let a=(0,r.useRef)(null);return((0,r.useEffect)(()=>{let e=a.current;if(!e||s<0)return;let t=e.children[s];t&&t.scrollIntoView({block:"nearest"})},[s]),e?.length)?(0,n.jsx)("div",{className:"absolute bottom-full left-0 right-0 mb-1 z-40 rounded-brand overflow-hidden bg-surface/95 backdrop-blur-xl shadow-xl ring-1 ring-border touch-none",children:(0,n.jsx)("div",{ref:a,className:"flex flex-col max-h-[25dvh] overflow-y-auto modal-scrollable",children:e.map((e,r)=>(0,n.jsxs)("button",{onMouseDown:e=>e.preventDefault(),onClick:()=>{(0,t7.e)(),t(e.full)},className:`flex items-center gap-2 px-3 py-1.5 text-left hover:bg-surface-2 transition-colors touch-none ${r===s?"bg-brand-500/15":""}`,children:[(0,n.jsx)("span",{className:"flex-shrink-0",children:"folder"===e.type?(0,n.jsx)(nz.A,{size:13,className:"text-brand-500",fill:"currentColor"}):(0,n.jsx)(nI.A,{size:13,className:"text-text-muted"})}),(0,n.jsx)("span",{className:"min-w-0 text-xs text-text font-mono",style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",direction:"rtl",unicodeBidi:"plaintext"},title:e.full,children:e.label})]},`${e.type}-${e.name}`))})}):null}let nD=[.3,.6,.85,1,.75,.9,1,.65,.35],nF=[.4,.8,1,.7,.9,.5,.85,.35],nO=(0,r.memo)(function({voice:e,onDone:t,onCancel:s,className:r=""}){return e?.listening?(0,n.jsx)("div",{className:`w-fit mx-auto flex items-center gap-2 px-2.5 py-1 rounded-full bg-surface-2/95 border border-border-subtle shadow-md backdrop-blur-md text-xs animate-in fade-in slide-in-from-bottom-1 duration-150 pointer-events-auto ${r}`,children:e.transcribing?(0,n.jsxs)("div",{className:"flex items-center gap-2 px-1 py-0.5",children:[(0,n.jsx)("span",{className:"w-2 h-2 rounded-full bg-brand-500 animate-ping shrink-0"}),(0,n.jsx)("div",{className:"flex items-center gap-[3px] h-3.5",children:nF.map((e,t)=>(0,n.jsx)("span",{className:"w-[2.5px] rounded-full bg-brand-500/85 animate-pulse transition-all",style:{height:`${Math.round(13*e)}px`,animationDelay:`${100*t}ms`,animationDuration:"800ms"}},t))})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",onClick:()=>{s?s():e.cancel()},className:"text-text-muted hover:text-text p-1 rounded-full hover:bg-surface-3 transition-colors cursor-pointer shrink-0",title:"Cancel","aria-label":"Cancel",children:(0,n.jsx)(t3.X,{size:12})}),(0,n.jsx)("div",{className:"h-3 w-px bg-border-subtle shrink-0"}),(0,n.jsxs)("span",{className:"relative flex h-2 w-2 shrink-0",children:[(0,n.jsx)("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-red-400 opacity-75"}),(0,n.jsx)("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-red-500"})]}),(0,n.jsx)("div",{className:"flex items-center gap-[2.5px] h-3.5 shrink-0 px-0.5",children:nD.map((t,s)=>{let r=Math.max(3,Math.round(3+t*(e.volume||.1)*11));return(0,n.jsx)("span",{className:"w-[2px] rounded-full bg-brand-500 transition-all duration-75",style:{height:`${r}px`}},s)})}),(0,n.jsx)("div",{className:"h-3 w-px bg-border-subtle shrink-0"}),(0,n.jsx)("button",{type:"button",onClick:()=>{(0,t7.e)(),t?t():e.stop()},className:"p-1 rounded-full bg-brand-500 hover:bg-brand-600 text-white transition-colors cursor-pointer shadow-xs flex items-center justify-center shrink-0",title:"Done","aria-label":"Done",children:(0,n.jsx)(t3.aJ,{size:11})})]})}):null}),nB=RegExp(`^\\s*(${eP.verbs.join("|")})\\s+(\\S*)$`,"i"),nW=r.memo(({bus:e,sessionId:t,onExpandChange:s,onRefocus:a,onRegisterTextApi:l,platform:i,onInput:o,onSwitchSession:c,onSwitchToIndex:d,onInputFocusChange:u,statusStrip:m=null,isDesktop:x=!1})=>{let p,{t:h,locale:f}=(0,se.s)(),[b,g]=(0,r.useState)(!1),[v,y]=(0,r.useState)(!1);(0,r.useEffect)(()=>{let e=window.visualViewport;if(!e)return;let t=()=>y(window.innerHeight-e.height>150);return e.addEventListener("resize",t),t(),()=>e.removeEventListener("resize",t)},[]);let w=tS(e=>e.drafts[t]??""),k=tS(e=>e.setDraft),j=(0,r.useCallback)(e=>{k(t,"function"==typeof e?e(tS.getState().drafts[t]??""):e)},[k,t]),[N,S]=(0,r.useState)(!1),[C,T]=(0,r.useState)(!1),[R,E]=(0,r.useState)(!1),[_,$]=(0,r.useState)(!1),M=nr(e=>e.addCommand),P=nr(e=>e.resolveAlias),A=nr(e=>e.history),z=nr(e=>e.pinned),I=(0,r.useRef)(null),L=(0,r.useRef)(null),D=(0,r.useRef)(!1),F=(0,r.useRef)(-1);(0,r.useRef)("");let O=tS(e=>e.cwdBySession[t]),[B,W]=(0,r.useState)([]),[K,H]=(0,r.useState)(-1),[U,q]=(0,r.useState)(-1),V=(0,r.useMemo)(()=>B.length>0?[]:nm(w,A,z,en,N),[w,A,z,N,B]),X=(e,t)=>e<0||!t?-1:(e%t+t)%t,G=X(K,B.length),J=X(U,V.length),Y=(0,r.useRef)(null);null==Y.current&&(Y.current=function({ttlMs:e,maxDirs:t}=eP){let s=new Map;return{get(e,t){let n=s.get(e);return n?n.expireAt<t?(s.delete(e),null):(s.delete(e),s.set(e,s.get(e)),n.entries):null},set(n,r,a){s.size>=t&&!s.has(n)&&s.delete(s.keys().next().value),s.set(n,{entries:r,expireAt:a+e})},clear(){s.clear()}}}());let Z=(0,r.useRef)(e);(0,r.useEffect)(()=>{Z.current=e},[e]);let Q=t5(Z),{attachments:ee,setAttachments:et,addFiles:es,removeAttachment:er,sendOneAttachment:ea,handleFileUpload:el,handleAttachPaste:ei}=n_({bus:e,sessionId:t}),[eo]=nb(f),ec=ny({lang:nh(eo),onText:e=>{j(e);let t=I.current;t&&requestAnimationFrame(()=>{try{t.selectionStart=t.selectionEnd=t.value.length}catch{}t.scrollTop=t.scrollHeight})}}),ed="mouse"===nk();(0,r.useEffect)(()=>{let e=I.current;if(!e)return;e.style.height="auto";let t=ed?200:101;e.style.height=`${Math.min(e.scrollHeight,t)}px`},[w,ed]);let eu=(0,r.useRef)(0);(0,r.useEffect)(()=>{let e=function(e,t){var s,n;let r=nB.exec(e);if(!r)return null;let a=r[1],l=r[2]||"",i=l.lastIndexOf("/");if(i<0)return{verb:a,dir:t||"",prefix:l,partial:l};let o=l.slice(0,i);return o?{verb:a,dir:(s=t,(n=o)?n.startsWith("/")||n.startsWith("~")||!s?n:s.replace(/\/+$/,"")+"/"+n:s||""),prefix:l.slice(i+1),partial:l}:{verb:a,dir:l.startsWith("~")?"~":"/",prefix:l.slice(i+1),partial:l}}(w,O),t=++eu.current,s=setTimeout(async()=>{if(t!==eu.current)return;if(!e)return void W([]);let s=Date.now(),n=Y.current.get(e.dir,s);if(null==n){let r=await Q.getFiles(e.dir,!1);if(t!==eu.current)return;if(!r?.success)return void W([]);n=r.files,Y.current.set(e.dir,n,s)}W(function(e,t,{partial:s,verb:n}={}){if(!e?.length)return[];let r=t.toLowerCase(),a=s&&s.includes("/")?s.slice(0,s.lastIndexOf("/")+1):"";return e.filter(e=>e.name.toLowerCase().startsWith(r)).map(e=>({name:e.name,type:e.type,arg:a+e.name+("folder"===e.type?"/":""),label:e.name+("folder"===e.type?"/":""),full:`${n} ${a}${e.name}${"folder"===e.type?"/":""}`})).sort((e,t)=>{let s=+("folder"!==e.type),n=+("folder"!==t.type);return s!==n?s-n:e.name.localeCompare(t.name)}).slice(0,eP.maxResults||8)}(n,e.prefix,e))},eP.debounceMs);return()=>clearTimeout(s)},[w,O,Q]),(0,r.useEffect)(()=>{let e=setTimeout(()=>{Y.current?.clear(),W([])},0);return()=>clearTimeout(e)},[t]);let[em,ex]=(0,r.useState)(!1),[ep,eh]=(0,r.useState)(!1),[eb,eg]=(0,r.useState)(!1),[ev,ey]=(0,r.useState)(!1),ew=nN("terminal.basicKeys",eA,ez,"flat",[["esc","up","down","ctrlC","ctrl","opt","shift","tab"]]),ek=nN("terminal.extraKeys",eA,eL,"grid"),ej=(0,r.useCallback)((e,t={})=>(function(e,{ctrl:t=!1,alt:s=!1,shift:n=!1}={}){if(t&&1===e.length){let t=e.toUpperCase().charCodeAt(0);return t>=65&&t<=90?String.fromCharCode(t-64):nA[e]??e}return s?n$[e]?"\x1b"+n$[e]:1===e.length?"\x1b"+e:n$[e]||e:t&&n$[e]?e.startsWith("Arrow")?nM[e]||n$[e]:"Home"===e?"\x1b[1;5H":"End"===e?"\x1b[1;5F":n$[e]:n&&n$[e]?"Tab"===e?"\x1b[Z":e.startsWith("Arrow")&&nP[e]||n$[e]:n&&1===e.length?e.toUpperCase():n$[e]||e})(e,{ctrl:t.ctrl||em,alt:t.alt||eb,shift:t.shift||ev}),[em,eb,ev]);(0,r.useEffect)(()=>{let e=()=>{S(window.innerWidth<768||"ontouchstart"in window||navigator.maxTouchPoints>0)};return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),(0,r.useEffect)(()=>{s&&s(!0)},[ed]),(0,r.useEffect)(()=>{if(l)return l({openTextPanel:()=>{setTimeout(()=>I.current?.focus(),100)},focus:()=>{I.current?.focus({preventScroll:!0})}}),()=>l(null)},[l]);let eN=(0,r.useCallback)(()=>{T(!0),setTimeout(()=>L.current?.focus(),100)},[]);if((0,r.useEffect)(()=>{if(!N||!e||!t||!(em||ep||eb||ev))return;let s=async s=>{if(!em&&!ep&&!eb&&!ev||["Control","Alt","Shift","Meta"].includes(s.key))return;s.preventDefault(),s.stopPropagation();let n=s.key;if((em||ep)&&"v"===n.toLowerCase()){eN(),ex(!1),eh(!1),eg(!1),ey(!1);return}"Backspace"===n?n="Backspace":"Enter"===n?n="Enter":"Tab"===n?n="Tab":"Escape"===n?n="Escape":"Delete"===n?n="Delete":n.startsWith("Arrow")?n=s.key:n.startsWith("F")&&n.length<=3&&(n=s.key);let r=ej(n,{ctrl:em,alt:eb,shift:ev,meta:ep});o?.(t),e.emit("input",{sessionId:t,data:r}),ex(!1),eh(!1),eg(!1),ey(!1)};return document.addEventListener("keydown",s,!0),()=>document.removeEventListener("keydown",s,!0)},[N,e,t,em,ep,eb,ev,ej,eN]),!N&&!ed||!e||!t)return null;let eS=async(s,n={})=>{(0,t7.e)();let r=n.ctrl||em,a=n.meta||ep;if((r||a)&&"v"===s.toLowerCase()){eN(),ex(!1),eh(!1),eg(!1),ey(!1);return}let l=ej(s,n);o?.(t),e.emit("input",{sessionId:t,data:l}),"Ctrl"!==s&&"Meta"!==s&&"Alt"!==s&&"Shift"!==s&&(ex(!1),eh(!1),eg(!1),ey(!1))},eC=async()=>{if(D.current)return;if(D.current=!0,(0,t7.e)(15),ec.listening&&ec.stop(),!e||!t){D.current=!1;return}let s=document.activeElement===I.current;s&&I.current?.blur();let n=I.current?.value??w;I.current&&(I.current.value=""),j(""),F.current=-1;let r=P(n);for(let e of(o?.(t),ee.length&&et([]),ee))await ea(e),await new Promise(e=>setTimeout(e,150));""===r?ee.length||e.emit("input",{sessionId:t,data:"\r"}):(e.emit("input",{sessionId:t,data:r}),setTimeout(()=>e.emit("input",{sessionId:t,data:"\r"}),100),M(r)),s&&I.current?.focus(),setTimeout(()=>{D.current=!1},150)},eT="flex items-center justify-center rounded-brand font-semibold transition-all duration-150 ease-out active:scale-[0.94]",eR=`${eT} bg-surface-2 hover:bg-surface-3 text-text`,eE=`${eT} bg-surface-2 hover:bg-surface-3 text-text text-sm`,e_=(e,t,s=!1,r=!1)=>{let a,l="modifier"===e.type&&("ctrl"===(a=e.id)&&em||"meta"===a&&ep||"opt"===a&&eb||"shift"===a&&ev)?`${eT} ${eD}`:r?`${eT} ${eF}`:"arrow"===e.type?eE:eR,i="ctrl"===e.type?"text-brand-400":"",o=e.label.length>1?"text-[11px]":"text-xs";return(0,n.jsx)("button",{onMouseDown:e=>e.preventDefault(),onClick:()=>{if("modifier"===e.type){var t;t=e.key,(0,t7.e)(),"Ctrl"===t?ex(!em):"Meta"===t?eh(!ep):"Alt"===t||"Opt"===t?eg(!eb):"Shift"===t&&ey(!ev)}else"ctrl"===e.type?eS(e.key,{ctrl:!0}):eS(e.key)},className:`${l} ${i} ${o} whitespace-nowrap`,style:s?eB:eO,children:e.label},e.id+t)},e$=!!m&&!b&&!v&&!ed;return(0,n.jsxs)("div",{className:"flex flex-col w-full",children:[C&&(0,n.jsx)("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-[60]",onClick:()=>T(!1),children:(0,n.jsx)("input",{ref:L,placeholder:h("mobileKeyboard.pasteHere"),onPaste:s=>{s.preventDefault();let n=s.clipboardData?.getData("text");n&&e&&(o?.(t),e.emit("input",{sessionId:t,data:n}),(0,t7.e)()),T(!1)},onClick:e=>e.stopPropagation(),className:"px-6 py-3 bg-surface-2 text-text rounded-brand focus:ring-2 focus:ring-brand-500/40 font-medium transition-all duration-150 ease-out outline-none text-center w-64"})}),(0,n.jsx)("div",{className:`transition-all duration-300 overflow-hidden bg-bg ${b&&!ed?"max-h-64 opacity-100":"max-h-0 opacity-0"}`,children:(0,n.jsx)("div",{className:"p-2 max-w-2xl mx-auto",children:(0,n.jsx)("div",{className:"space-y-1",children:ek.rows.map((e,t)=>(0,n.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,n.jsx)("div",{className:"flex-1 min-w-0 flex gap-1.5 overflow-x-auto scroll-thin-x pr-3 rounded-lg",children:e.map((e,s)=>{let n=eA.find(t=>t.id===e);return n?e_(n,100*t+s,!0):null})}),0===t&&(0,n.jsx)("button",{onMouseDown:e=>e.preventDefault(),onClick:()=>{(0,t7.e)(),E(!0)},className:"shrink-0 h-8 w-8 flex items-center justify-center text-text-muted hover:text-text bg-surface-2 hover:bg-surface-3 rounded-brand transition-all duration-150 ease-out",title:h("remote.customizeKeys"),children:(0,n.jsx)(t3.wB,{size:16})})]},t))})})}),e$&&m,(0,n.jsxs)("div",{className:"relative transition-all duration-300 overflow-visible opacity-100 flex-shrink-0",children:[(0,n.jsx)(nO,{voice:ec,className:`absolute left-1/2 -translate-x-1/2 z-30 ${e$?"bottom-[calc(100%+36px)]":"bottom-[calc(100%+18px)]"}`}),(0,n.jsxs)("div",{className:x?"flex w-full items-stretch":`${e$?"pt-0.5":"pt-2"} px-2 pb-2 flex gap-2 items-end`,children:[(0,n.jsxs)("div",{className:`relative flex-1 bg-surface-2 transition-all duration-150 ease-out input-focus-glow border-border-subtle ${x?"rounded-none border-0 border-r":"rounded-xl border"}`,children:[(0,n.jsx)(nL,{items:B,activeIndex:G,onSelect:e=>{j(e),I.current?.focus()}}),(0,n.jsx)(nx,{value:w,store:nr,commonCommands:en,isMobile:N,disabled:B.length>0,activeIndex:J,onSelect:e=>{j(e),I.current?.focus()}}),ee.length>0&&(0,n.jsx)("div",{className:"flex gap-2 px-2 pt-2 overflow-x-auto scroll-thin-x",children:ee.map(e=>(0,n.jsxs)("div",{className:"relative flex-shrink-0 group",children:[e.isImage?(0,n.jsx)("img",{src:`data:${e.type};base64,${e.content}`,alt:e.name,className:"w-10 h-10 object-cover rounded border border-border"}):(0,n.jsxs)("div",{className:"w-10 h-10 flex flex-col items-center justify-center rounded border border-border bg-surface-3 px-1",children:[(0,n.jsx)(t3.xv,{size:14,className:"text-text-muted"}),(0,n.jsx)("span",{className:"text-[9px] text-text-muted truncate w-full text-center",children:e.name})]}),(0,n.jsx)("button",{onMouseDown:e=>e.preventDefault(),onClick:()=>er(e.id),className:"absolute -top-1.5 -right-1.5 w-4 h-4 flex items-center justify-center bg-surface-3 rounded-full text-text-muted hover:text-text border border-border",children:(0,n.jsx)(t3.X,{size:10})})]},e.id))}),(0,n.jsxs)("label",{className:"absolute left-1.5 top-1/2 -translate-y-1/2 w-6 h-6 flex items-center justify-center cursor-pointer text-orange-500/70 hover:text-orange-500 transition-colors touch-none",children:[(0,n.jsx)(t3.xv,{size:16}),(0,n.jsx)("input",{type:"file",multiple:!0,onChange:el,className:"hidden",accept:"*/*"})]}),(0,n.jsx)("textarea",{ref:I,value:w,onChange:e=>{j(e.target.value),F.current=-1},onFocus:e=>{let t=e.target.value.length;e.target.selectionStart=e.target.selectionEnd=t,u?.(!0)},onBlur:()=>u?.(!1),onPaste:ei,onKeyDown:s=>{if(ed&&"Tab"===s.key){if(!s.ctrlKey&&!s.altKey&&!s.metaKey){if(B.length>0){s.preventDefault();let e=s.shiftKey?-1:1;H(t=>B.length?((t+e)%B.length+B.length)%B.length:-1);return}if(V.length>0){s.preventDefault();let e=s.shiftKey?-1:1;q(t=>V.length?((t+e)%V.length+V.length)%V.length:-1);return}}s.preventDefault();let n=ej("Tab",{ctrl:s.ctrlKey,alt:s.altKey,shift:s.shiftKey,meta:s.metaKey});o?.(t),e.emit("input",{sessionId:t,data:n});return}let n=/^Digit([1-9])$/.exec(s.code)||/^[1-9]$/.exec(s.key);if(ed&&(s1()?s.altKey&&!s.ctrlKey&&!s.metaKey:s.ctrlKey||s.metaKey)&&n){s.preventDefault(),d?.(Number(n[1])-1);return}if(ed&&"Enter"===s.key&&!s.shiftKey){if(s.nativeEvent?.isComposing||s.isComposing||229===s.keyCode)return;if(B.length>0&&G>=0){s.preventDefault(),j(B[G].full),H(-1),I.current?.focus();return}if(V.length>0&&J>=0){s.preventDefault(),j(V[J].cmd),q(-1),I.current?.focus();return}s.preventDefault(),eC();return}if(ed&&("ArrowUp"===s.key||"ArrowDown"===s.key)&&!s.shiftKey&&!s.ctrlKey&&!s.metaKey&&!s.altKey&&!w){s.preventDefault(),o?.(t),e.emit("input",{sessionId:t,data:"ArrowUp"===s.key?"\x1b[A":"\x1b[B"});return}let r=ef[s.key];if(r&&(!r.ctrl||s.ctrlKey)&&!s.metaKey&&!s.altKey){let n=s.target;if(r.requireNoSelection&&n.selectionStart!==n.selectionEnd)return;s.preventDefault(),o?.(t),e.emit("input",{sessionId:t,data:r.data})}},placeholder:ed?s1()?"Opt ←/→ \xb7 Opt 1…9 to switch tab":"Ctrl+Shift+←/→ \xb7 1…9 to switch tab":h("mobileKeyboard.typeCommand"),rows:1,className:"block w-full pl-9 pr-16 py-2 bg-transparent text-text text-sm placeholder-text-muted placeholder:text-[11px] placeholder:leading-[20px] focus:outline-none resize-none overflow-y-auto touch-none"}),w?(0,n.jsx)("button",{onMouseDown:e=>e.preventDefault(),onClick:()=>{j(""),I.current?.focus()},title:h("voice.clear"),className:"absolute right-10 top-1/2 -translate-y-1/2 w-5 h-5 flex items-center justify-center text-text-muted hover:text-text transition-colors touch-none",children:(0,n.jsx)(t3.X,{size:14})}):(0,n.jsx)("button",{onMouseDown:e=>e.preventDefault(),onClick:()=>$(!0),title:h("history.title"),className:"absolute right-10 top-1/2 -translate-y-1/2 w-5 h-5 flex items-center justify-center text-text-muted hover:text-text transition-colors touch-none",children:(0,n.jsx)(t3.BZ,{size:14})}),ec.active&&(0,n.jsx)("button",{onMouseDown:e=>e.preventDefault(),onClick:()=>{ec.listening?ec.stop():(document.activeElement?.blur(),ec.start(w))},title:"not-allowed"===ec.error||"service-not-allowed"===ec.error?h("voice.denied"):h("voice.dictate"),className:`absolute right-1.5 top-1/2 -translate-y-1/2 w-7 h-7 flex items-center justify-center rounded-full transition-all duration-200 touch-none ${ec.listening?"bg-red-500/90 text-white animate-pulse":ec.error?"text-red-400":"text-text-muted hover:text-text"}`,children:ec.listening?(0,n.jsx)(t3.jj,{size:16}):(0,n.jsx)(t3.GO,{size:16})})]}),(0,n.jsx)("button",{onMouseDown:e=>e.preventDefault(),onClick:eC,disabled:!1,className:x?"px-4 py-2 bg-brand-500 hover:bg-brand-600 text-white text-sm font-medium rounded-none transition-colors flex-shrink-0 flex items-center justify-center select-none":"px-3 py-2 bg-brand-500 hover:bg-brand-600 text-white text-sm font-medium rounded-xl transition-all duration-200 shadow-lg shadow-brand-500/20 flex-shrink-0 min-w-[56px] flex items-center justify-center",children:w.trim()||ee.length?h("mobileKeyboard.send"):(0,n.jsx)(t3.Lt,{size:16,strokeWidth:2.5})})]})]}),!ed&&(0,n.jsx)("div",{className:"overflow-x-auto overflow-y-hidden touch-pan-x px-1.5 pb-1.5 safe-area-bottom bg-bg",children:(0,n.jsxs)("div",{className:"flex items-center gap-1 max-w-4xl mx-auto",children:[(0,n.jsx)("div",{className:"flex gap-1 flex-1 overflow-x-auto scroll-thin-x touch-pan-x pr-2 rounded-lg",children:ew.keys.filter(e=>e.id!==eI).map((e,t)=>e_(e,t))}),(p=eA.find(e=>e.id===eI))?(0,n.jsx)("div",{className:"flex-shrink-0",children:e_(p,"pinned",!1,!0)}):null,(0,n.jsx)("button",{onMouseDown:e=>e.preventDefault(),onClick:()=>{(0,t7.e)();let e=!b;g(e),e&&document.activeElement?.blur(),s&&setTimeout(()=>s(e),320)},className:`${eT} ${b?eD:eF} flex-shrink-0`,style:eO,title:h("mobileKeyboard.toggleExtraKeys"),children:b?(0,n.jsx)(t3.X,{size:16}):(0,n.jsx)(t3.a4,{size:16})})]})}),(0,n.jsx)(nE,{isOpen:R,onClose:()=>E(!1),title:h("mobileKeyboard.customizeTerminalKeys"),tabs:[{id:"basic",label:h("mobileKeyboard.mainBar"),hook:ew,excludeIds:[eI]},{id:"extra",label:h("mobileKeyboard.extraPanel"),hook:ek}]}),(0,n.jsx)(no,{isOpen:_,onSelect:e=>{j(e),I.current?.focus()},onClose:()=>$(!1)})]})}),nK={idle:{dot:"#22c55e",cls:"st-idle",label:"common.statusIdle"},working:{dot:"#3b82f6",cls:"st-working",pulse:"soft",glow:"rgba(59,130,246,0.30)",label:"common.statusWorking"},blocked:{dot:"#ef4444",cls:"st-blocked",pulse:"strong",glow:"rgba(239,68,68,0.32)",label:"common.statusBlocked"},done:{dot:"#f59e0b",cls:"st-done",glow:"rgba(245,158,11,0.22)",label:"common.statusDone"}},nH=e=>nK[e]||nK.idle,nU=e=>{let t=nH(e);return`term-dot ${t.cls}${t.pulse?` pulse-${t.pulse}`:""}`},nq={claude:"Claude",codex:"Codex",opencode:"OpenCode",grok:"Grok",cursor:"Cursor",antigravity:"Antigravity",kiro:"Kiro",copilot:"Copilot",codebuddy:"CodeBuddy",factory:"Factory",qoder:"Qoder",rovodev:"Rovo Dev",hermes:"Hermes",amp:"Amp",pi:"Pi","qwen-code":"Qwen",droid:"Droid",crush:"Crush"},nV=new Proxy({},{get:(e,t)=>"string"==typeof t&&t&&s$(t)||void 0});function nX({sessions:e=[],allSessions:t=[],sessionStatus:s,onSwitchSession:a,workspaces:l=[]}){let{t:i}=(0,se.s)(),[o,c]=(0,r.useState)(!1),d=(0,r.useRef)(null),u=sc(e=>e.sessionStatus),m=s||u,x=su(m,t),{total:p}=sm(m,t),h=s=>t.find(e=>e.id===s)?.name||e.find(e=>e.id===s)?.name||s.slice(0,8),f=e=>t.find(t=>t.id===e)?.workspaceId??null,b=new Map(t.map((e,t)=>[e.id,t])),g=(()=>{let e=new Map;for(let t of x){let s=f(t.id);e.has(s)||e.set(s,[]),e.get(s).push(t)}let t=e=>[...e].sort((e,t)=>(b.has(e.id)?b.get(e.id):Number.MAX_SAFE_INTEGER)-(b.has(t.id)?b.get(t.id):Number.MAX_SAFE_INTEGER)),s=[];for(let n of l){let r=e.get(n.id);r?.length&&s.push({id:n.id,name:n.name,items:t(r)})}let n=e.get(null);return n?.length&&s.push({id:null,name:i("workspaces.unassigned"),items:t(n)}),s})();(0,r.useEffect)(()=>{if(!o)return;let e=e=>{d.current&&!d.current.contains(e.target)&&c(!1)},t=e=>{"Escape"===e.key&&c(!1)};return document.addEventListener("mousedown",e),document.addEventListener("touchstart",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("mousedown",e),document.removeEventListener("touchstart",e),document.removeEventListener("keydown",t)}},[o]);let v=(0,r.useRef)(null),y=()=>{v.current&&(clearTimeout(v.current),v.current=null)};return(0,r.useEffect)(()=>()=>y(),[]),(0,n.jsxs)("div",{ref:d,className:"relative hidden sm:flex flex-shrink-0",onMouseEnter:()=>{y(),c(!0)},onMouseLeave:()=>{y(),v.current=setTimeout(()=>c(!1),150)},children:[(0,n.jsxs)("button",{onClick:()=>c(e=>!e),className:"relative p-1.5 text-text hover:bg-surface-2 hover:text-text rounded-brand transition-all duration-150 ease-out active:scale-[0.94]",title:i("notifications.title"),children:[(0,n.jsx)(t3.Ir,{size:16}),p>0&&(0,n.jsx)("span",{className:"absolute top-0 -right-1 min-w-[16px] h-4 px-1 rounded-full bg-brand-500 text-white text-[10px] font-bold flex items-center justify-center",children:p>9?"9+":p})]}),o&&(0,n.jsx)("div",{className:"absolute right-0 top-full pt-2 z-[70] flex flex-col",children:(0,n.jsxs)("div",{className:"bg-surface-2 border border-border-subtle rounded-brand-lg shadow-lg w-72 max-h-[60vh] overflow-y-auto flex flex-col",children:[(0,n.jsxs)("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border-subtle flex-shrink-0",children:[(0,n.jsx)("span",{className:"text-sm font-semibold",children:i("notifications.title")}),(0,n.jsx)("button",{onClick:()=>c(!1),className:"p-1 text-text-muted hover:text-text rounded transition-colors",title:i("common.close"),children:(0,n.jsx)(t3.X,{size:14})})]}),x.length?(0,n.jsx)("div",{className:"flex flex-col",children:g.map(e=>(0,n.jsxs)("div",{className:"flex flex-col",children:[(0,n.jsxs)("div",{className:"px-3 pt-2 pb-1 text-[11px] font-semibold uppercase tracking-wider text-text-muted flex items-center gap-1.5",children:[(0,n.jsx)("span",{className:"w-1 h-1 rounded-full bg-text-muted"}),(0,n.jsx)("span",{className:"truncate",title:e.name,children:e.name})]}),e.items.map(e=>{let t="idle"===e.state,s=nH(e.state),r=i(s.label);return(0,n.jsxs)("button",{onClick:()=>{var t;return t=e.id,void(c(!1),a?.(t))},className:`w-full flex items-center gap-2 px-3 py-1 hover:bg-surface-3 text-left transition-colors ${t?"opacity-50":""}`,title:h(e.id),children:[t?(0,n.jsx)("span",{className:"w-2 h-2 rounded-full flex-shrink-0 border border-text-muted/60"}):(0,n.jsx)("span",{className:`w-2 h-2 rounded-full flex-shrink-0 term-dot ${s.cls}${s.pulse?` pulse-${s.pulse}`:""}`,style:{background:s.dot}}),nV[e.tool]&&!t?(0,n.jsx)("img",{src:nV[e.tool],alt:e.tool,className:`w-5 h-5 flex-shrink-0 ${s_}`}):(0,n.jsx)(t3.BK,{size:18,className:"text-text-muted flex-shrink-0"}),(0,n.jsxs)("span",{className:"flex-1 min-w-0 flex flex-col",children:[(0,n.jsx)("span",{className:"text-sm font-medium truncate",title:h(e.id),children:h(e.id)}),(0,n.jsxs)("span",{className:"text-xs text-text-muted truncate",children:[nq[e.tool]||i("notifications.agent")," \xb7 ",r]})]}),(0,n.jsx)("span",{className:"text-[11px] text-text-muted flex-shrink-0",children:(e=>{if(!e||!Number.isFinite(e))return"";let t=Math.max(0,Math.floor((Date.now()-e)/1e3));return t<60?"now":t<3600?`${Math.floor(t/60)}m`:t<86400?`${Math.floor(t/3600)}h`:`${Math.floor(t/86400)}d`})(e.since)})]},e.id)})]},e.id??"unassigned"))}):(0,n.jsx)("p",{className:"px-3 py-6 text-center text-sm text-text-muted",children:i("notifications.empty")})]})})]})}function nG({sessionStatus:e,allSessions:t=[],onSwitchSession:s}){let{t:r}=(0,se.s)(),a=sc(e=>e.sessionStatus),{blocked:l,done:i,total:o,targetId:c}=sm(e||a,t);if(!o)return null;let d=[{key:"blocked",count:l,state:"blocked"},{key:"done",count:i,state:"done"}].filter(e=>e.count>0);return(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),c&&s?.(c)},className:"sm:hidden flex items-center gap-1.5 px-2 py-1.5 rounded-brand bg-surface-2 text-text transition-all duration-150 ease-out active:scale-[0.94] flex-shrink-0",title:r("notifications.badgeTitle",{blocked:l,done:i}),children:d.map(({key:e,count:t,state:s})=>{let r=nH(s);return(0,n.jsxs)("span",{className:"flex items-center gap-1",children:[(0,n.jsx)("span",{className:`w-2 h-2 rounded-full term-dot ${r.cls}${r.pulse?` pulse-${r.pulse}`:""}`,style:{background:r.dot}}),(0,n.jsx)("span",{className:"text-xs font-semibold tabular-nums",children:t>9?"9+":t})]},e)})})}let nJ="custom_ports",nY="site_labels";function nZ(e,t){try{let s=localStorage.getItem(e);return s?JSON.parse(s):t}catch{return t}}function nQ(e,t){localStorage.setItem(e,JSON.stringify(t))}let n0=()=>nZ(nJ,[]),n1=()=>nZ(nY,{});async function n2(e,t){if(!e)return null;let s=await fetch(`${e}/api/local-sites`,{headers:{Authorization:`Bearer ${t}`}}).catch(()=>null);return s?.ok?s.json():null}function n5(e,t){return t&&"https:"!==window.location.protocol?`http://${t}`:e||null}async function n3(e,{busRef:t,base:s,apiKey:n,port:r}){let a=t?.current;if(a?.connected){if("start"!==e)return a.emit("endProxySession",r),!0;let t=await new Promise(e=>{let t=setTimeout(()=>e(null),5e3);a.emit("startProxySession",r,s=>{clearTimeout(t),e(s?.sessionId||null)})});if(t)return t}if(!s)return!1;let l=await fetch(`${s}/api/proxy/${e}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({port:r})}).catch(()=>null);if(!l?.ok)return!1;if("start"!==e)return!0;let i=await l.json().catch(()=>null);return i?.sessionId||String(r)}function n4({tunnelUrl:e,apiKey:t,busRef:s,onSelectSite:a,isOpen:i,onClose:o}){let{t:c}=(0,se.s)(),d=tS(e=>e.pushView),{getAuth:u}=(0,l.F)(),[m,x]=(0,r.useState)([]),[p,h]=(0,r.useState)(!1),[f,b]=(0,r.useState)({}),[g,v]=(0,r.useState)(""),[y,w]=(0,r.useState)({isOpen:!1}),[k,j]=(0,r.useState)({}),[N,S]=(0,r.useState)(null),[C,T]=(0,r.useState)(""),R=(0,r.useRef)({}),E=si(e=>e.cachedSites),_=si(e=>e.currentSites),$=si(e=>e.loadingSites),M=si(e=>e.setCachedSites),P=si(e=>e.setCurrentSites),A=si(e=>e.setLoadingSites),z=void 0!==i?i:p,I=o||(()=>h(!1)),L=async()=>{_&&0!==_.length||A(!0);try{let n,r=await (n=s?.current,!n?.connected?Promise.resolve(null):new Promise(e=>{let t=setTimeout(()=>e(null),8e3);n.emit("getLocalSites",s=>{clearTimeout(t),e(Array.isArray(s?.sites)?s.sites:null)})}))??await n2(e,t);if(!r)return void console.error("[SitesList] unable to load local sites (no bus, tunnel unreachable)");P(r),M(r)}catch(e){console.error("Failed to load local sites:",e)}finally{A(!1)}},D=async()=>{let n=Object.keys(f);if(n.forEach(e=>{let t=R.current[e];t&&(clearInterval(t),delete R.current[e]);let s=f[e];s&&!s.closed&&s.close()}),0===n.length)return;b({});let r=n5(e,u()?.localIp);await Promise.all(n.map(e=>n3("end",{busRef:s,base:r,apiKey:t,port:Number(e)}).catch(()=>{})))};(0,r.useEffect)(()=>{z?(x(n0()),j(n1()),(!_||0===_.length)&&E&&E.length>0&&(P(E),A(!1)),L()):D()},[z]);let F=async n=>{let{port:r}=n;if(window.location.pathname.startsWith("/workspace")&&s?.current?.connected){s.current.emit("startProxySession",r),d({type:"site",port:r,path:"/"}),a?.(n),I();return}let l=n5(e,u()?.localIp);if(!l)return void alert(c("sites.startProxyFailed",{name:n.name}));if(f[r]&&!f[r].closed)return void f[r].focus();let i=window.open("about:blank",`_proxy_${r}`);if(!i)return void alert(c("sites.popupBlocked"));b(e=>({...e,[r]:i}));let o=await n3("start",{busRef:s,base:l,apiKey:t,port:r}).catch(()=>!1);if(!o){console.error("[SitesList] Failed to start proxy session for port",r),alert(c("sites.startProxyFailed",{name:n.name})),i.close(),b(e=>{let t={...e};return delete t[r],t});return}i.location.href=`${l}/proxy/${o}/`,a?.(n),R.current[r]=setInterval(async()=>{i.closed&&(clearInterval(R.current[r]),delete R.current[r],b(e=>{let t={...e};return delete t[r],t}),await n3("end",{busRef:s,base:l,apiKey:t,port:r}).catch(e=>console.error(`[SitesList] Cleanup failed for port ${r}:`,e)))},1e3)},O=()=>{I(),v("")};(0,r.useEffect)(()=>{if(!z)return;let e=e=>{"Escape"===e.key&&null===N&&(e.preventDefault(),e.stopPropagation(),o?o():h(!1),v(""))};return window.addEventListener("keydown",e,!0),()=>window.removeEventListener("keydown",e,!0)},[z,N,o]);let B=()=>{let e=parseInt(g,10);if(isNaN(e)||e<1||e>65535)return;let t=_.some(t=>t.port===e),s=m.includes(e);if(t||s){F({port:e,name:`Port ${e}`,protocol:"http",isCustom:!0}),v("");return}let n=[...m,e];x(n),nQ(nJ,n),v(""),F({port:e,name:`Port ${e}`,protocol:"http",isCustom:!0})},W=(e,t)=>{S(e),T(t||"")},K=()=>{if(null==N)return;let e=C.trim(),t={...k};e?t[N]=e:delete t[N],j(t),nQ(nY,t),S(null),T("")},H=()=>{S(null),T("")};return(0,r.useEffect)(()=>()=>{Object.values(R.current).forEach(e=>{clearInterval(e)})},[]),(0,n.jsxs)(n.Fragment,{children:[void 0===i&&(0,n.jsxs)("button",{onClick:()=>h(!0),className:"px-3 sm:px-4 py-2 bg-surface-2 hover:bg-surface-3 text-text text-sm font-medium rounded-brand transition-all duration-150 ease-out active:scale-[0.97] flex items-center gap-2",children:[(0,n.jsx)(t3.qz,{className:"text-brand-500",size:16}),(0,n.jsx)("span",{className:"hidden sm:inline",children:c("sites.title")})]}),z&&(0,n.jsx)("div",{className:"fixed inset-0 bg-black/60 backdrop-blur-[2px] z-[60] flex items-center justify-center p-4 animate-in fade-in duration-200 modal-overlay",onClick:O,children:(0,n.jsxs)("div",{className:"card-elev w-full max-w-md max-h-[85vh] flex flex-col animate-in zoom-in-95 slide-in-from-bottom-4 duration-300",onClick:e=>e.stopPropagation(),children:[(0,n.jsxs)("div",{className:"flex items-center justify-between px-5 py-4 shrink-0",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("h2",{className:"text-lg font-semibold text-orange-400",children:c("sites.localSites")}),(0,n.jsx)("p",{className:"text-sm text-text-muted mt-0.5",children:c("sites.selectSitePreview")})]}),(0,n.jsx)("button",{onClick:O,className:"p-2 text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-colors",children:(0,n.jsx)(t3.X,{size:20})})]}),(0,n.jsx)("div",{className:"px-4 py-3 border-b border-border shrink-0",children:(0,n.jsxs)("div",{className:"flex gap-2 items-center",children:[(0,n.jsx)("span",{className:"text-text-muted text-sm whitespace-nowrap",children:"http://localhost:"}),(0,n.jsx)("input",{type:"number",value:g,onChange:e=>v(e.target.value),onKeyDown:e=>"Enter"===e.key&&B(),placeholder:c("sites.portPlaceholder"),min:"1",max:"65535",className:"flex-1 px-3 py-2 bg-surface-2 rounded-brand text-text placeholder-text-muted focus:outline-none focus:ring-2 focus:ring-brand-500/40 text-sm min-w-0 transition-all duration-150 ease-out"}),(0,n.jsx)("button",{onClick:B,disabled:!g,className:"px-4 py-2 bg-brand-500 hover:bg-brand-600 disabled:bg-surface-2 disabled:cursor-not-allowed text-text text-sm font-medium rounded-brand transition-all duration-200 shadow-lg shadow-brand-500/20",children:c("sites.open")})]})}),(0,n.jsx)("div",{className:"p-4 modal-scrollable overflow-y-auto",style:{maxHeight:"40vh"},children:$?(0,n.jsx)("div",{className:"flex items-center justify-center py-8",children:(0,n.jsxs)("div",{className:"flex items-center gap-3 text-brand-500",children:[(0,n.jsx)(t3.kr,{className:"animate-spin",size:20}),(0,n.jsx)("span",{children:c("sites.loadingSites")})]})}):0===_.length?(0,n.jsxs)("div",{className:"text-center py-8",children:[(0,n.jsx)("div",{className:"w-12 h-12 mx-auto mb-3 rounded-brand-lg bg-surface-2 flex items-center justify-center",children:(0,n.jsx)(t3.qz,{className:"text-text-muted",size:24})}),(0,n.jsx)("p",{className:"text-text font-medium",children:c("sites.noSitesFound")}),(0,n.jsx)("p",{className:"text-text-muted text-sm mt-1",children:c("sites.startServerHint")})]}):(0,n.jsxs)("div",{className:"space-y-2",children:[m.filter(e=>!_.some(t=>t.port===e)).map(e=>{let t=N===e,s=k[e]||c("common.new");return(0,n.jsxs)("div",{className:"w-full px-4 py-3 bg-surface-2 hover:bg-surface-3 rounded-brand-lg transition-all duration-150 ease-out active:scale-[0.99] group flex items-center justify-between gap-2",children:[(0,n.jsxs)("button",{onClick:()=>!t&&F({port:e,name:s,protocol:"http",isCustom:!0}),className:"flex-1 flex items-center gap-3 text-left min-w-0",children:[(0,n.jsx)("div",{className:"w-2.5 h-2.5 rounded-full bg-surface-2 shrink-0"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[t?(0,n.jsx)("input",{type:"text",value:C,onChange:e=>T(e.target.value),onKeyDown:e=>{"Enter"===e.key&&K(),"Escape"===e.key&&H()},onClick:e=>e.stopPropagation(),autoFocus:!0,placeholder:c("sites.siteNamePlaceholder"),className:"w-full px-2 py-1 bg-surface ring-2 ring-brand-500/40 rounded-brand text-text text-sm focus:outline-none transition-all duration-150"}):(0,n.jsx)("div",{className:"text-text font-medium group-hover:text-brand-500 transition-colors truncate",title:s,children:s}),(0,n.jsxs)("div",{className:"text-xs text-text-muted mt-0.5 flex items-center gap-2",children:[(0,n.jsx)("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-medium uppercase bg-surface-2 text-text-muted",children:"http"}),(0,n.jsxs)("span",{children:["Port ",e]})]})]})]}),t?(0,n.jsx)("button",{onClick:e=>{e.stopPropagation(),K()},className:"p-2 text-brand-500 hover:text-text hover:bg-surface-2 rounded-brand transition-colors shrink-0",title:c("sites.saveTitle"),children:(0,n.jsx)(t3.aJ,{size:16})}):(0,n.jsx)("button",{onClick:t=>{t.stopPropagation(),W(e,k[e])},className:"p-2 text-text-muted hover:text-brand-500 hover:bg-surface-2 rounded-brand transition-colors shrink-0",title:c("sites.editNameTitle"),children:(0,n.jsx)(t3.gH,{size:16})}),(0,n.jsx)("button",{onClick:t=>{t.stopPropagation(),w({isOpen:!0,title:c("sites.removePortTitle"),message:c("sites.removePortMessage",{port:e}),onConfirm:()=>{let t=m.filter(t=>t!==e);x(t),nQ(nJ,t)}})},className:"p-2 text-text-muted hover:text-red-400 hover:bg-surface-2 rounded-brand transition-colors shrink-0",title:c("sites.removeTitle"),children:(0,n.jsx)(t3.TB,{size:16})}),!t&&(0,n.jsx)(t3.c_,{className:"text-text-muted group-hover:text-brand-500 transition-colors shrink-0",size:20})]},`custom-${e}`)}),_.map(e=>{let t=N===e.port,s=k[e.port]||e.name;return(0,n.jsxs)("div",{className:"w-full px-4 py-3 bg-surface-2 hover:bg-surface-3 rounded-brand-lg transition-all duration-150 ease-out active:scale-[0.99] group flex items-center justify-between gap-2",children:[(0,n.jsxs)("button",{onClick:()=>!t&&F({...e,name:s}),className:"flex-1 flex items-center gap-3 text-left min-w-0",children:[(0,n.jsx)("div",{className:"w-2.5 h-2.5 rounded-full bg-green-500 animate-pulse shrink-0"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[t?(0,n.jsx)("input",{type:"text",value:C,onChange:e=>T(e.target.value),onKeyDown:e=>{"Enter"===e.key&&K(),"Escape"===e.key&&H()},onClick:e=>e.stopPropagation(),autoFocus:!0,placeholder:e.name,className:"w-full px-2 py-1 bg-surface ring-2 ring-brand-500/40 rounded-brand text-text text-sm focus:outline-none transition-all duration-150"}):(0,n.jsx)("div",{className:"text-text font-medium group-hover:text-brand-500 transition-colors truncate",title:s,children:s}),(0,n.jsxs)("div",{className:"text-xs text-text-muted mt-0.5 flex items-center gap-2",children:[(0,n.jsx)("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-medium uppercase ${"https"===e.protocol?"bg-green-500/20 text-green-400":"bg-blue-500/20 text-blue-400"}`,children:e.protocol}),(0,n.jsxs)("span",{children:["Port ",e.port]})]})]})]}),t?(0,n.jsx)("button",{onClick:e=>{e.stopPropagation(),K()},className:"p-2 text-brand-500 hover:text-text hover:bg-surface-2 rounded-brand transition-colors shrink-0",title:c("sites.saveTitle"),children:(0,n.jsx)(t3.aJ,{size:16})}):(0,n.jsx)("button",{onClick:t=>{t.stopPropagation(),W(e.port,k[e.port])},className:"p-2 text-text-muted hover:text-brand-500 hover:bg-surface-2 rounded-brand transition-colors shrink-0",title:c("sites.editNameTitle"),children:(0,n.jsx)(t3.gH,{size:16})}),!t&&(0,n.jsx)(t3.c_,{className:"text-text-muted group-hover:text-brand-500 transition-colors shrink-0",size:20})]},`auto-${e.port}`)})]})}),(0,n.jsxs)("div",{className:"px-5 py-3 border-t border-border flex items-center justify-between shrink-0",children:[(0,n.jsx)("span",{className:"text-xs text-text-muted",children:_.length>0?c("sites.foundCount",{n:_.length,suffix:_.length>1?"s":""}):""}),(0,n.jsxs)("button",{onClick:L,disabled:$,className:"flex items-center gap-2 px-3 py-1.5 text-sm text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-colors disabled:opacity-50",children:[(0,n.jsx)(t3.e9,{className:$?"animate-spin text-brand-500":"",size:16}),c("sites.refresh")]})]})]})}),(0,n.jsx)(t9.A,{isOpen:y.isOpen,onClose:()=>w({isOpen:!1}),onConfirm:y.onConfirm,title:y.title,message:y.message})]})}let n6=(0,Z.v)(e=>({isOpen:!1,open:()=>e({isOpen:!0}),close:()=>e({isOpen:!1})}));function n8(e,t){let s=e.split(".").map(Number),n=t.split(".").map(Number);for(let e=0;e<3;e++)if((s[e]||0)!==(n[e]||0))return(s[e]||0)<(n[e]||0);return!1}function n9(e,t){return!!e&&!!t&&n8(e,t)}function n7(e,t){return!!e&&!!t&&n8(t,e)}function re({agentVersion:e,webVersion:t,updateAvailable:s=null,canSelfUpdate:a=!1,onUpdate:l,className:i=""}){let{t:o}=(0,se.s)(),[c,d]=(0,r.useState)(!1),u=(0,r.useCallback)(()=>{(0,t7.e)(),d(!0),l?.()},[l]),m=(0,r.useCallback)(()=>{(0,t7.e)(),d(!0),setTimeout(()=>window.location.reload(),400)},[]),x=n9(e,t)||!!s,p=n7(e,t);if(x&&!a)return(0,n.jsxs)("div",{className:`px-3 py-2 bg-brand-500/10 border border-brand-500/30 rounded-brand-lg flex items-center gap-2.5 ${i}`,children:[(0,n.jsx)(t3.f5,{size:16,className:"text-brand-500 shrink-0"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"text-xs font-medium text-text",children:o("menu.updateAvailableTitle")}),s?.version&&(0,n.jsxs)("span",{className:"text-xs text-text-muted ml-1.5",children:["v",s.version]}),(0,n.jsx)("div",{className:"text-xs text-text-muted mt-0.5",children:o("menu.versionMismatchHint")})]}),(0,n.jsx)("code",{className:"shrink-0 px-2 py-1 bg-surface-2 border border-border text-text text-xs rounded font-mono",children:"npm i -g 9remote@latest"})]});let h=!!(x&&l),f=h&&s?.version||e,b=o(h?"menu.updateAvailableTitle":"menu.webReloadTitle"),g=o(h?"menu.updateNow":"menu.reloadWeb"),v=h?t3.f5:t3.e9;return x||p?(0,n.jsxs)("div",{className:`px-3 py-2 bg-brand-500/10 border border-brand-500/30 rounded-brand-lg flex items-center gap-2.5 ${i}`,children:[(0,n.jsx)(v,{size:16,className:"text-brand-500 shrink-0"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"text-xs font-medium text-text",children:b}),f&&(0,n.jsxs)("span",{className:"text-xs text-text-muted ml-1.5",children:["v",f]})]}),(0,n.jsxs)("button",{onClick:h?u:m,disabled:c,className:"shrink-0 px-3 py-1 bg-brand-500 hover:bg-brand-600 disabled:opacity-60 text-white text-xs font-medium rounded-brand flex items-center gap-1.5 transition-colors",type:"button",children:[(0,n.jsx)(v,{size:13,className:c?"animate-spin":""}),g]})]}):null}var rt=s(62004);function rs(e,t){if(!e)return"";if(!t)return e;if(e===t)return"~";let s=t.endsWith("/")?t:`${t}/`;return e.startsWith(s)?`~/${e.slice(s.length)}`:e}function rn(e){return e?.path?e.path:e?.items?.find(e=>e.workspacePath)?.workspacePath||null}function rr(e,t){if(!e)return"";let s=e.slice(0,e.lastIndexOf("/"))||"/",n=t.replace(/[^\w.-]+/g,"-");return`${s}/${e.split("/").pop()}-${n}`}function ra({workspacePath:e,workspaceName:t,fileBus:s,homeDir:a,value:l,onChange:i,onBrowse:o}){let{t:c}=(0,se.s)(),[d,u]=(0,r.useState)(!1),[m,x]=(0,r.useState)(null),[p,h]=(0,r.useState)(!1),[f,b]=(0,r.useState)(!1),[g,v]=(0,r.useState)(""),[y,w]=(0,r.useState)(null),[k,j]=(0,r.useState)(!1),[N,S]=(0,r.useState)(null),C=(0,r.useRef)(null),T=(0,r.useRef)(null),R=(0,r.useCallback)(async()=>{if(!e||!s?.gitScanRepos)return x([]);h(!0);let n=await s.gitScanRepos(e),r=n?.success&&n.repos||[],a=await Promise.all(r.map(async e=>{let t=await s.gitWorktreeList?.(e.path),n=t?.success&&t.worktrees||[],r=n.length?n.map(e=>({path:e.path,branch:e.branch,detached:e.detached})):[{path:e.path,branch:e.branch,detached:!1}];return{repoPath:e.path,name:e.name,branch:e.branch,isRoot:!e.relPath,isRepo:!0,entries:r}}));a.some(e=>e.isRoot)||a.unshift({repoPath:e,name:t||c("terminal.workspaceRoot"),isRoot:!0,isRepo:!1,entries:[{path:e,branch:null,detached:!1}]}),x(a),h(!1)},[e,t,s,c]);(0,r.useEffect)(()=>{if(!d)return;let e=e=>{C.current?.contains(e.target)||u(!1)},t=e=>{"Escape"===e.key&&(e.stopPropagation(),f?(b(!1),S(null)):u(!1))};return document.addEventListener("mousedown",e),document.addEventListener("keydown",t,!0),()=>{document.removeEventListener("mousedown",e),document.removeEventListener("keydown",t,!0)}},[d,f]);let E=e=>{(0,t7.e)(),b(!1),i?.(e),u(!1)};(0,r.useEffect)(()=>{f&&window.matchMedia("(pointer: fine)").matches&&requestAnimationFrame(()=>T.current?.focus())},[f]);let _=(m||[]).filter(e=>e.isRepo),$=(0,rt.A)(g.trim()).replace(/[^\w.-]+/g,"-").replace(/^-+|-+$/g,""),M=async()=>{if(!y||!$||k||!s?.gitWorktreeAdd)return;let e=rr(y,$);j(!0),S(null);let t=await s.gitWorktreeAdd(y,e,$,!0);if(!t?.success)return j(!1),S(t?.error||"Failed to create worktree");await R(),E(t.path||e)},P=(m?.length||0)>1,A=l?(m||[]).flatMap(e=>e.entries).find(e=>e.path===l):null,z=A?.branch||(l||e||"").split("/").filter(Boolean).pop()||t||c("terminal.workspaceRoot");return(0,n.jsxs)("div",{ref:C,className:"relative",children:[(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),null===m&&R(),u(e=>!e)},"aria-haspopup":"listbox","aria-expanded":d,title:l||e||void 0,className:"w-full flex items-center gap-2 px-2.5 py-1.5 rounded-brand text-left bg-surface-2 hover:bg-surface-3 transition-colors",children:[(0,n.jsx)(t3.Zr,{size:14,className:"text-text-muted shrink-0"}),(0,n.jsxs)("span",{className:"flex-1 min-w-0 flex flex-col",children:[(0,n.jsx)("span",{className:"text-xs text-text truncate leading-tight",children:z}),(0,n.jsx)("span",{className:"text-[10px] text-text-subtle truncate leading-tight",children:"Pick a branch or worktree"})]}),(0,n.jsx)(t3.yQ,{size:14,className:`text-text-muted shrink-0 transition-transform ${d?"rotate-180":""}`})]}),d&&(0,n.jsxs)("div",{role:"listbox",className:"absolute z-10 left-0 right-0 top-full mt-1 max-h-72 flex flex-col bg-surface-3 rounded-brand border border-border shadow-xl",children:[(0,n.jsxs)("div",{className:"min-h-0 flex-1 overflow-y-auto scrollbar-thin py-1",children:[!f&&p&&(0,n.jsx)("div",{className:"flex items-center justify-center py-4 text-text-muted",children:(0,n.jsx)(t3.kr,{size:15,className:"animate-spin"})}),!f&&!p&&m?.map(e=>(0,n.jsxs)("div",{children:[P&&(0,n.jsx)("p",{className:"px-3 pt-1.5 pb-0.5 text-[10px] font-medium uppercase tracking-wider text-text-subtle truncate",children:e.name}),e.entries.map(t=>{let s=l===t.path;return(0,n.jsxs)("button",{type:"button",role:"option","aria-selected":s,onClick:()=>E(t.path),className:`w-full flex items-start gap-2 px-3 py-1.5 text-left transition-colors ${s?"bg-brand-500/15":"hover:bg-text/[0.06]"}`,children:[t.branch||t.detached?(0,n.jsx)(t3.Zr,{size:12,className:"mt-[3px] shrink-0 text-text-subtle"}):(0,n.jsx)(t3.vd,{size:12,className:"mt-[3px] shrink-0 text-text-subtle"}),(0,n.jsxs)("span",{className:"flex-1 min-w-0 flex flex-col",children:[(0,n.jsxs)("span",{className:"flex items-center gap-1 min-w-0",children:[(0,n.jsx)("span",{className:`truncate text-xs ${s?"text-text font-medium":"text-text"}`,title:t.branch||e.name,children:t.branch||(t.detached?c("terminal.detachedHead"):e.name)}),s&&(0,n.jsx)(t3.aJ,{size:12,className:"text-brand-400 shrink-0"})]}),(0,n.jsx)("span",{className:"truncate text-[10px] text-text-subtle leading-tight",title:t.path,children:t.path.split("/").filter(Boolean).pop()||t.path})]})]},t.path)})]},e.repoPath)),f&&(0,n.jsxs)("div",{"data-wt-form":!0,className:"px-2 py-1.5",children:[(0,n.jsxs)("div",{className:"flex items-center gap-1.5 px-1 pb-1.5 text-[10px] font-medium uppercase tracking-wider text-text-subtle",children:[(0,n.jsx)(t3.dx,{size:11}),c("workspaces.newWorktree")]}),_.length>1&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("p",{className:"px-1 pb-1 flex items-center gap-1 text-[10px] text-text-subtle",children:[(0,n.jsx)(t3.Zr,{size:10,className:"shrink-0"}),c("workspaces.worktreeRepoLabel")]}),(0,n.jsx)("select",{value:y||"",onChange:e=>w(e.target.value),disabled:k,className:"w-full mb-1 px-2 py-1 rounded-brand bg-surface-2 text-xs text-text border border-border-subtle focus:outline-none",children:_.map(e=>(0,n.jsxs)("option",{value:e.repoPath,children:[e.name,e.branch?` \xb7 ${e.branch}`:""]},e.repoPath))})]}),(0,n.jsx)("input",{type:"text",ref:T,value:g,disabled:k,onChange:e=>v(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),M())},placeholder:c("workspaces.worktreeName"),className:"w-full px-2 py-1.5 rounded-brand bg-surface-2 text-xs text-text placeholder-text-subtle border border-border-subtle focus:outline-none"}),g.trim()&&!$&&(0,n.jsx)("p",{className:"px-1 pt-1 text-[10px] text-red-500 leading-tight",children:c("workspaces.worktreeNameAscii")}),(0,n.jsx)("p",{className:"px-1 pt-1 truncate text-[10px] text-text-subtle leading-tight",title:rr(y,$||"…"),children:rs(rr(y,$||"…"),a)}),N&&(0,n.jsx)("p",{className:"px-1 pt-1 text-[10px] text-red-500 break-words",children:N}),(0,n.jsxs)("div",{className:"flex items-center justify-end gap-1.5 pt-1.5",children:[(0,n.jsx)("button",{type:"button",onClick:()=>{(0,t7.e)(),b(!1),S(null)},className:"px-2 py-1 text-xs text-text-muted hover:text-text transition-colors",children:c("common.cancel")}),(0,n.jsx)("button",{type:"button",onClick:()=>{(0,t7.e)(),M()},disabled:!$||k||!y,className:"px-2.5 py-1 rounded-brand bg-brand-500 hover:bg-brand-600 text-white text-xs font-medium transition-colors disabled:opacity-50 disabled:pointer-events-none",children:k?(0,n.jsx)(t3.kr,{size:12,className:"animate-spin"}):c("common.create")})]})]})]}),!f&&(_.length>0||o)&&(0,n.jsxs)("div",{className:"shrink-0 border-t border-border-subtle flex items-center gap-1 px-2 py-1.5",children:[_.length>0&&s?.gitWorktreeAdd&&(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),w(e=>e||_.find(e=>e.isRoot)?.repoPath||_[0]?.repoPath||null),v(""),S(null),j(!1),b(!0)},className:"flex-1 min-w-0 flex items-center justify-center gap-1.5 px-2 py-1 rounded-brand text-xs text-brand-500 hover:bg-brand-500/10 transition-colors",children:[(0,n.jsx)(t3.dx,{size:12,className:"shrink-0"}),(0,n.jsx)("span",{className:"truncate",children:c("workspaces.newWorktree")})]}),o&&(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),u(!1),o()},className:"flex-1 min-w-0 flex items-center justify-center gap-1.5 px-2 py-1 rounded-brand text-xs text-text-muted hover:bg-text/[0.06] hover:text-text transition-colors",children:[(0,n.jsx)(t3.Bm,{size:12,className:"shrink-0 opacity-70"}),(0,n.jsx)("span",{className:"truncate",children:c("terminal.browseFolders")})]})]})]})]})}function rl(e,t,{fireOnReturn:s=!0}={}){let n=null,r=()=>{n||!("u"<typeof document)&&document.hidden||(n=setInterval(e,t))},a=()=>{n&&(clearInterval(n),n=null)},l=()=>{document.hidden?a():(s&&e(),r())};return"u">typeof document&&document.addEventListener("visibilitychange",l),r(),()=>{a(),"u">typeof document&&document.removeEventListener("visibilitychange",l)}}let ri=new Map;function ro({isOpen:e,onClose:t,busRef:s,cwd:a,onResume:l,onSelectSession:i,liveSessionIds:o,activeSessionId:c,connected:d=!0}){let{t:u}=(0,se.s)(),[m,x]=(0,r.useState)(""),[p,h]=(0,r.useState)("all"),[f,b]=(0,r.useState)(null),g=tS(e=>a?e.agentHistory[a]?.sessions:null),v=(0,r.useMemo)(()=>g||[],[g]);(0,r.useEffect)(()=>{if(!e)return;document.activeElement?.blur?.();let s=e=>{"Escape"!==e.key||f||t()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e,t,f]);let y=(0,r.useMemo)(()=>{let e=new Set;for(let t of v)t.agent&&e.add(t.agent);return Array.from(e)},[v]),w=(0,r.useMemo)(()=>{let e=m.trim().toLowerCase();return v.filter(t=>{if("all"!==p&&t.agent!==p)return!1;if(!e)return!0;let s=(t.title||"").toLowerCase(),n=(t.sessionId||"").toLowerCase(),r=(t.agent||"").toLowerCase();return s.includes(e)||n.includes(e)||r.includes(e)})},[v,m,p]);if(!e)return null;let k=(e,s)=>{(0,t7.e)(),s?i?.(s):l?.(e),t()};return(0,n.jsxs)("div",{className:"fixed inset-0 z-[60] flex items-center justify-center p-4",children:[(0,n.jsx)("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-[2px] animate-in fade-in duration-200 touch-none",onClick:t}),(0,n.jsxs)("div",{className:"relative card-elev max-w-xl w-full max-h-[85vh] flex flex-col animate-in zoom-in-95 duration-200 bg-surface border border-border rounded-brand-lg overflow-hidden shadow-2xl",children:[(0,n.jsxs)("div",{className:"px-5 py-3.5 border-b border-border-subtle flex items-center justify-between flex-shrink-0",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)(t3.BZ,{size:17,className:"text-text-muted"}),(0,n.jsx)("h3",{className:"text-base font-semibold text-text",children:u("agentHistory.title")}),(0,n.jsx)("span",{className:"px-2 py-0.5 text-xs rounded-full bg-surface-2 text-text-subtle font-mono",children:v.length})]}),(0,n.jsx)("button",{onClick:t,className:"p-1.5 text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-colors","aria-label":u("common.close"),children:(0,n.jsx)(t3.X,{size:18})})]}),(0,n.jsxs)("div",{className:"p-3 border-b border-border-subtle flex flex-col gap-2 bg-surface-1/50 flex-shrink-0",children:[(0,n.jsxs)("div",{className:"relative flex items-center",children:[(0,n.jsx)(t3.vj,{size:15,className:"absolute left-3 text-text-muted pointer-events-none"}),(0,n.jsx)("input",{type:"text",value:m,onChange:e=>x(e.target.value),placeholder:u("agentHistory.searchPlaceholder"),className:"w-full pl-9 pr-8 py-1.5 text-xs bg-surface-2 border border-border-subtle rounded-brand text-text placeholder-text-muted outline-none focus:border-text-muted/40 focus:ring-1 focus:ring-text-muted/20 transition-all"}),m&&(0,n.jsx)("button",{onClick:()=>x(""),className:"absolute right-2.5 p-0.5 text-text-muted hover:text-text rounded transition-colors",children:(0,n.jsx)(t3.X,{size:13})})]}),y.length>1&&(0,n.jsxs)("div",{className:"flex items-center gap-1.5 overflow-x-auto pb-0.5 scrollbar-none",children:[(0,n.jsx)("button",{onClick:()=>h("all"),className:`px-2.5 py-1 text-xs rounded-brand transition-colors whitespace-nowrap ${"all"===p?"bg-surface-3 text-text font-medium border border-border-subtle shadow-sm":"bg-surface-2 text-text-muted hover:text-text"}`,children:u("agentHistory.allAgents")}),y.map(e=>(0,n.jsxs)("button",{onClick:()=>h(e),className:`px-2.5 py-1 text-xs rounded-brand transition-colors flex items-center gap-1.5 whitespace-nowrap capitalize ${p===e?"bg-surface-3 text-text font-medium border border-border-subtle shadow-sm":"bg-surface-2 text-text-muted hover:text-text"}`,children:[(0,n.jsx)("img",{src:s$(e),alt:"",className:`w-3.5 h-3.5 ${s_}`}),(0,n.jsx)("span",{children:e})]},e))]})]}),(0,n.jsx)("div",{className:"flex-1 min-h-0 overflow-y-auto modal-scrollable p-2 space-y-1",children:0===w.length?(0,n.jsxs)("div",{className:"flex flex-col items-center justify-center py-14 text-text-muted text-sm gap-2",children:[(0,n.jsx)(t3.BZ,{size:32,className:"opacity-40"}),(0,n.jsx)("span",{children:m?u("agentHistory.noResults"):u("agentHistory.empty")})]}):w.map(e=>{var t;let s=e.openSessionId&&o?.has(e.openSessionId)?e.openSessionId:null,r=!!s&&s===c,a=e.title||u("agentHistory.untitled");return(0,n.jsxs)("div",{className:`group flex items-center gap-2.5 px-3 py-2 rounded-brand transition-colors ${r?"bg-surface-2 border border-border-subtle":"hover:bg-surface-2"}`,children:[(0,n.jsx)("img",{src:s$(e.agent),alt:e.agent,className:`w-5 h-5 flex-shrink-0 object-contain ${s_}`}),(0,n.jsxs)("div",{onClick:()=>k(e,s),className:"flex-1 min-w-0 cursor-pointer",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("span",{className:`text-xs truncate font-medium ${s?"text-emerald-400":"text-text"}`,children:a}),s&&(0,n.jsx)("span",{className:"px-1.5 py-0.2 text-[10px] rounded bg-emerald-500/15 text-emerald-400 border border-emerald-500/30 flex-shrink-0",children:u("agentHistory.openNow")})]}),(0,n.jsxs)("div",{className:"flex items-center gap-2 mt-0.5 text-[11px] text-text-subtle",children:[(0,n.jsx)("span",{className:"capitalize",children:e.agent}),(0,n.jsx)("span",{children:"•"}),(0,n.jsx)("span",{className:"tabular-nums",children:function(e,t){let s=Math.round((Date.now()-e)/6e4);if(s<60)return t("agentHistory.minutesAgo",{n:Math.max(1,s)});let n=Math.round(s/60);return n<24?t("agentHistory.hoursAgo",{n:n}):t("agentHistory.daysAgo",{n:Math.round(n/24)})}(e.updatedAt,u)}),e.size>0&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{children:"•"}),(0,n.jsx)("span",{className:"tabular-nums font-mono text-[10px] opacity-75",children:(t=e.size)&&!(t<=0)?t<1024?`${t} B`:t<1048576?`${(t/1024).toFixed(0)} KB`:`${(t/1048576).toFixed(1)} MB`:""})]})]})]}),(0,n.jsxs)("div",{className:"flex items-center gap-1 flex-shrink-0",children:[(0,n.jsx)("button",{onClick:()=>k(e,s),disabled:!d,className:"p-1.5 text-text-muted hover:text-text hover:bg-surface-3 rounded-brand transition-colors",title:s?u("agentHistory.openNow"):u("common.confirm"),children:(0,n.jsx)(t3.jG,{size:14})}),(0,n.jsx)("button",{onClick:()=>b(e),disabled:!d||!!s,className:"p-1.5 text-text-muted hover:text-red-400 hover:bg-red-500/10 rounded-brand transition-colors disabled:opacity-30 disabled:hover:text-text-muted disabled:hover:bg-transparent",title:s?u("agentHistory.openNow"):u("agentHistory.delete"),children:(0,n.jsx)(t3.TB,{size:14})})]})]},`${e.agent}:${e.sessionId}`)})})]}),f&&(0,n.jsx)(t9.A,{isOpen:!0,onClose:()=>b(null),onConfirm:()=>{if(!f)return;let{agent:e,sessionId:t}=f;(0,t7.e)();let n=v.filter(s=>s.agent!==e||s.sessionId!==t);tS.getState().setAgentHistory(a,n),s?.current?.emit("deleteAgentSession",{agent:e,sessionId:t,cwd:a},e=>{e?.success||s?.current?.emit("getAgentSessions",{cwd:a},e=>{Array.isArray(e?.sessions)&&tS.getState().setAgentHistory(a,e.sessions)})}),b(null)},title:u("agentHistory.deleteTitle"),message:u("agentHistory.deleteMessage",{title:f.title||u("agentHistory.untitled")})})]})}function rc({busRef:e,cwd:t,onResume:s,onSelectSession:a,liveSessionIds:l,activeSessionId:i,connected:o=!0,variant:c="section"}){let d,u,{t:m}=(0,se.s)(),[x,p]=(0,r.useState)(!1),[h,f]=(0,r.useState)(!1),[b,g]=(0,r.useState)(null),v=(d=tS(e=>t?e.agentHistory[t]:null),u=d?.at??0,(0,r.useEffect)(()=>{if(!t)return;let s=function(e,t){let s=ri.get(t);if(s)return s.count+=1,s;let n=!1,r=()=>{n||(n=!0,e?.current?.emit("getAgentSessions",{cwd:t},e=>{n=!1,Array.isArray(e?.sessions)&&tS.getState().setAgentHistory(t,e.sessions)}))},a={count:1,fetchNow:r,stop:rl(r,3e4)};return ri.set(t,a),a}(e,t),n=tS.getState().agentHistory[t];return(!n||Date.now()-n.at>=3e4)&&s.fetchNow(),()=>{let e;!(e=ri.get(t))||(e.count-=1,!(e.count>0)&&(e.stop(),ri.delete(t)))}},[e,t,u]),d?.sessions||null),y="list"===c;if(!t)return null;if(!v?.length)return y?(0,n.jsx)("div",{className:"flex-1 min-h-0 flex items-center justify-center px-6 py-10 text-center text-sm text-text-muted",children:m("agentHistory.empty")}):null;let w=y?v:v.slice(0,40),k=!y&&v.length>40;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:y?"flex-1 min-h-0 flex flex-col":"flex-shrink-0 border-t border-border-subtle pt-1 flex flex-col",style:y?void 0:{maxHeight:x?void 0:"28%"},children:[!y&&(0,n.jsxs)("div",{className:"w-full pl-1 pr-1 py-0.5 flex items-center justify-between text-text-subtle",children:[(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),p(e=>!e)},className:"flex items-center gap-1 hover:text-text transition-colors flex-1 min-w-0",children:[(0,n.jsx)(t3.c_,{size:12,className:`flex-shrink-0 transition-transform duration-150 ${x?"":"rotate-90"}`}),(0,n.jsx)(t3.BZ,{size:11,className:"flex-shrink-0"}),(0,n.jsx)("span",{className:"text-[11px] font-medium uppercase truncate",children:m("agentHistory.title")}),(0,n.jsxs)("span",{className:"ml-1 text-[10px] tabular-nums opacity-60",children:["(",v.length,")"]})]}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),f(!0)},className:"p-1 hover:text-text hover:bg-surface-2 rounded transition-colors text-text-subtle",title:m("agentHistory.manageHistory"),"aria-label":m("agentHistory.manageHistory"),children:(0,n.jsx)(t3.Gr,{size:12})})]}),(y||!x)&&(0,n.jsxs)("div",{className:`overflow-y-auto modal-scrollable min-h-0 ${y?"flex-1 px-1.5 pb-2":""}`,children:[w.map(e=>{let t=e.openSessionId&&l?.has(e.openSessionId)?e.openSessionId:null,r=!!t&&t===i,c=e.title||m("agentHistory.untitled");return(0,n.jsxs)("div",{className:`group relative w-full flex items-center gap-1 text-left transition-colors rounded-brand hover:bg-text/5 ${y?"gap-2 px-2.5 py-1.5":"pl-3 pr-1 py-px"} ${r?"bg-text/8":""}`,children:[(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),t?a?.(t):s?.(e)},disabled:!o,className:`flex items-center gap-1.5 flex-1 min-w-0 text-left transition-colors disabled:opacity-40 hover:text-text ${y?"gap-2.5":""} ${t?"text-text font-medium":"text-text-muted"}`,title:`${c} \xb7 ${e.agent}${t?` \xb7 ${m("agentHistory.openNow")}`:""}`,children:[(0,n.jsx)("img",{src:s$("ui"===e.mode?`${e.agent}-ui`:e.agent),alt:e.agent,className:`flex-shrink-0 ${s_} ${y?"w-4 h-4":"w-2.5 h-2.5"} ${t?"":"opacity-70"}`}),(0,n.jsx)("span",{className:`truncate flex-1 min-w-0 ${y?"text-sm":"text-[11px]"}`,"data-tip":c,children:c}),(0,n.jsx)("span",{className:`text-[10px] text-text-subtle flex-shrink-0 opacity-70 tabular-nums whitespace-nowrap ${y?"mr-1":""}`,children:function(e,t){let s=Math.round((Date.now()-e)/6e4);if(s<60)return t("agentHistory.minutesAgo",{n:Math.max(1,s)});let n=Math.round(s/60);return n<24?t("agentHistory.hoursAgo",{n:n}):t("agentHistory.daysAgo",{n:Math.round(n/24)})}(e.updatedAt,m)})]}),y?(0,n.jsx)("button",{onClick:t=>{t.stopPropagation(),g(e)},disabled:!o||!!t,className:`flex-shrink-0 p-1 rounded-[4px] text-text-subtle transition-colors hover:bg-red-500/15 hover:text-red-400 opacity-60 hover:opacity-100 ${t?"invisible":""}`,title:t?m("agentHistory.openNow"):m("agentHistory.delete"),"aria-label":m("agentHistory.delete"),children:(0,n.jsx)(t3.TB,{size:14})}):(0,n.jsx)("button",{onClick:t=>{t.stopPropagation(),g(e)},disabled:!o||!!t,className:`absolute right-1 top-1/2 -translate-y-1/2 pl-1.5 pr-0.5 rounded-[4px] bg-surface-2 text-text-subtle group-hover:text-red-400 hover:bg-red-500/15 transition-colors opacity-0 group-hover:opacity-100 ${t?"invisible":""}`,title:t?m("agentHistory.openNow"):m("agentHistory.delete"),"aria-label":m("agentHistory.delete"),children:(0,n.jsx)(t3.TB,{size:13})})]},`${e.agent}:${e.sessionId}`)}),k&&(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),f(!0)},className:"w-full py-1.5 px-2 mt-1 mb-0.5 flex items-center justify-center gap-1.5 text-[10px] font-medium text-text-subtle hover:text-text bg-surface-2/50 hover:bg-surface-2 border border-border-subtle/50 rounded transition-all",children:[(0,n.jsx)(t3.BZ,{size:11,className:"opacity-60"}),(0,n.jsxs)("span",{children:[m("agentHistory.showAll")," (",v.length,")"]})]})]})]}),h&&(0,n.jsx)(ro,{isOpen:h,onClose:()=>f(!1),busRef:e,cwd:t,onResume:s,onSelectSession:a,liveSessionIds:l,activeSessionId:i,connected:o}),b&&(0,n.jsx)(t9.A,{isOpen:!0,onClose:()=>g(null),onConfirm:()=>{if(!b)return;let{agent:s,sessionId:n}=b;(0,t7.e)();let r=(v||[]).filter(e=>e.agent!==s||e.sessionId!==n);tS.getState().setAgentHistory(t,r),e?.current?.emit("deleteAgentSession",{agent:s,sessionId:n,cwd:t},s=>{s?.success||e?.current?.emit("getAgentSessions",{cwd:t},e=>{Array.isArray(e?.sessions)&&tS.getState().setAgentHistory(t,e.sessions)})}),g(null)},title:m("agentHistory.deleteTitle"),message:m("agentHistory.deleteMessage",{title:b.title||m("agentHistory.untitled")})})]})}let rd=null,ru=e=>{rd=null==e?null:e2(e)},rm=/^[A-Za-z]:\/?$/,rx=/^[A-Za-z]:\//,rp=e=>{if(!e||"/"===e||rm.test(e))return null;let t=e.lastIndexOf("/");if(t<=0)return"/";let s=e.slice(0,t);return/^[A-Za-z]:$/.test(s)?`${s}/`:s},rh=e=>e&&"/"!==e?e.split("/").filter(Boolean).pop()??null:null,rf=e=>{let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return -1===t?"":e.slice(0,t+1)},rb=(e,t)=>"drive"===e.kind?t<0?e.driveRoot:`${e.driveRoot}${e.segments.slice(0,t+1).join("/")}`:`/${e.segments.slice(0,t+1).join("/")}`;function rg(e,t){let s=t.trim().toLowerCase();return s?e.filter(e=>e.name.toLowerCase().includes(s)):e}let rv=e=>e.includes("/")||e.includes("\\")||/^[A-Za-z]:$/.test(e)||"~"===e||"."===e||".."===e;function ry(e){let t,s,n;if(!rv(e))return{mode:"filter",filter:e};let r=e.replace(/\\/g,"/");if("~"===r)return{mode:"path",base:"home",committedSegments:[],trailingFilter:""};if("."===r)return{mode:"path",base:"cwd",committedSegments:[],trailingFilter:""};if(".."===r)return{mode:"path",base:"cwd",committedSegments:[".."],trailingFilter:""};if(/^[A-Za-z]:$/.test(r))return{mode:"path",base:"drive",driveRoot:`${r[0].toUpperCase()}:/`,committedSegments:[],trailingFilter:""};if(rx.test(r)?(t="drive",s=`${r[0].toUpperCase()}:/`,n=r.slice(3)):r.startsWith("/")?(t="root",n=r.slice(1)):r.startsWith("~/")?(t="home",n=r.slice(2)):(t="cwd",n=r),n.includes("//")||/[\x00-\x1F]/.test(n))return{mode:"path",base:t,driveRoot:s,committedSegments:[],trailingFilter:"",invalid:!0};let a=""===n?[""]:n.split("/");return{mode:"path",base:t,driveRoot:s,committedSegments:a.slice(0,-1),trailingFilter:a[a.length-1]}}function rw({fileBus:e,initialPath:t,onSelect:s,onClose:a}){let{t:l}=(0,se.s)(),[i]=(0,r.useState)(()=>t||rd||null),[o,c]=(0,r.useState)(i),[d,u]=(0,r.useState)([]),[m,x]=(0,r.useState)(!!i),[p,h]=(0,r.useState)(null),[f,b]=(0,r.useState)(""),[g,v]=(0,r.useState)(0),[y,w]=(0,r.useState)(null),[k,j]=(0,r.useState)(null),[N]=(0,r.useState)(()=>sn()),S=(0,r.useRef)(null),C=(0,r.useRef)(!1),T=(0,r.useRef)(0),R=(0,r.useRef)(0),E=(0,r.useRef)(null),_=(0,r.useRef)(null),$=(0,r.useRef)(null),M=(0,r.useRef)(null),P=(0,r.useRef)(null),A=(0,r.useRef)(new Map),z=(0,r.useRef)(null),I=(0,r.useRef)(""),L=(0,r.useRef)(!1),D=(0,r.useCallback)(async t=>{let s=A.current.get(t);if(s)return s;let n=await e.getFiles(t,!1);if(!n?.success)throw Error(n?.error||l("workspaces.pathNotFolder"));let r={resolvedPath:e2(n.currentPath)||t,entries:(n.files||[]).filter(e=>"folder"===e.type)};return A.current.set(r.resolvedPath,r),t!==r.resolvedPath&&A.current.set(t,r),r},[e,l]),F=(0,r.useCallback)(async e=>{if(null==e){T.current++,c(null),u([]),x(!1),h(null);return}let t=++T.current;x(!0),h(null);try{let s=await D(e);if(t!==T.current)return;c(s.resolvedPath),u(s.entries),"~"===e&&(z.current=s.resolvedPath)}catch(e){if(t!==T.current)return;h(e.message||String(e)),u([])}finally{t===T.current&&x(!1)}},[D]);(0,r.useEffect)(()=>{if(!i)return;let e=setTimeout(()=>void F(i),0);return()=>clearTimeout(e)},[i,F]),(0,r.useEffect)(()=>{let t=!1;return e?.getSystemInfo?.().then(e=>{if(t||!e?.success)return;j(e);let s=e2(e.homedir);s&&(z.current=s,i||L.current||(L.current=!0,F(s)))}),()=>{t=!0}},[e,i,F]);let O=(0,r.useCallback)(e=>{(0,t7.e)(),ru(e),b(""),w(null),v(0),R.current++,I.current="",E.current&&(clearTimeout(E.current),E.current=null),F(e)},[F]),B=(0,r.useCallback)(()=>{o&&O(rp(o))},[o,O]),W=(0,r.useCallback)(async e=>{let t,s=ry(e);if("path"!==s.mode)return;let n=++R.current;if(s.invalid)return void w({resolvedPath:o??"/",entries:[],filter:"",error:l("workspaces.invalidPath"),loading:!1});if("root"===s.base)t="/";else if("drive"===s.base)t=s.driveRoot;else if("home"===s.base){if(!z.current){w({resolvedPath:o??"/",entries:[],filter:"",error:null,loading:!0});try{let e=await D("~");if(n!==R.current)return;z.current=e.resolvedPath}catch(e){if(n!==R.current)return;w({resolvedPath:o??"/",entries:[],filter:"",error:e.message,loading:!1});return}}t=z.current}else t=o||"/";w(e=>e&&e.loading?e:{resolvedPath:t,entries:[],filter:"",error:null,loading:!0});let r=t;try{for(let e of s.committedSegments){let t=await D(r);if(n!==R.current)return;let s=function(e,t){if("."===e||".."===e)return{type:"stay",up:".."===e};let s=t.find(t=>t.name===e)||t.find(t=>t.name.toLowerCase()===e.toLowerCase());if(s)return"folder"===s.type?{type:"descend",path:s.path}:{type:"error",multiple:!1};let n=e.toLowerCase(),r=t.filter(e=>"folder"===e.type&&e.name.toLowerCase().startsWith(n));return 1===r.length?{type:"descend",path:r[0].path}:{type:"error",multiple:r.length>1}}(e,t.entries);if("error"===s.type){let n=rs(r,k?.homedir);w({resolvedPath:r,entries:t.entries,filter:"",error:s.multiple?l("workspaces.multipleDirMatches",{name:e,dir:n}):l("workspaces.notADirectory",{name:e,dir:n}),loading:!1});return}if("stay"===s.type){s.up&&(r=rp(r)||"/");continue}r=s.path}let t=await D(r);if(n!==R.current)return;I.current=rf(e),w({resolvedPath:t.resolvedPath,entries:t.entries,filter:s.trailingFilter,error:null,loading:!1})}catch(e){if(n!==R.current)return;w({resolvedPath:r,entries:[],filter:"",error:e.message,loading:!1})}},[o,D,k,l]),K=(0,r.useCallback)(e=>{if(b(e),v(0),e.length>2048||!rv(e)){y&&(w(null),R.current++),E.current&&(clearTimeout(E.current),E.current=null);return}let t=ry(e);"path"!==t.mode||!y||y.error||t.invalid||rf(e)!==I.current?(E.current&&clearTimeout(E.current),E.current=setTimeout(()=>{E.current=null,W(e)},300)):w({...y,filter:t.trailingFilter})},[y,W]);(0,r.useEffect)(()=>()=>{for(let e of(T.current++,R.current++,[E,_,$]))e.current&&clearTimeout(e.current),e.current=null},[]);let H=(0,r.useMemo)(()=>rg(d,f),[d,f]),U=(0,r.useMemo)(()=>y?rg(y.entries,y.filter):[],[y]),q=y?U:H;(0,r.useEffect)(()=>{C.current=window.matchMedia("(min-width: 640px)").matches,C.current&&S.current?.focus()},[]),(0,r.useEffect)(()=>{let e=e=>{"Escape"!==e.key||f||a()};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[f,a]);let V=(0,r.useMemo)(()=>(function(e){if(!e)return{kind:"posix",segments:[]};let t=/^([A-Za-z]:)(\/.*)?$/.exec(e);return t?{kind:"drive",driveRoot:`${t[1]}/`,segments:(t[2]||"").split("/").filter(Boolean)}:{kind:"posix",segments:e.split("/").filter(Boolean)}})(o),[o]);(0,r.useEffect)(()=>{M.current&&(M.current.scrollLeft=M.current.scrollWidth)},[o]);let X=rh(o),G=k?e2(k.homedir):null,J=!!k?.isWindows,Y=m||!!y&&""!==f;return(0,n.jsx)("div",{className:"fixed inset-0 z-[80] flex items-center justify-center p-3 sm:p-4 bg-black/70 backdrop-blur-[2px]",onClick:a,children:(0,n.jsxs)("div",{ref:P,role:"dialog","aria-modal":"true","aria-label":l("workspaces.newWorkspace"),onKeyDown:e=>{if("Tab"!==e.key)return;let t=P.current?.querySelectorAll("button:not([disabled]), input");if(!t?.length)return;let s=t[0],n=t[t.length-1];e.shiftKey&&document.activeElement===s?(e.preventDefault(),n.focus()):e.shiftKey||document.activeElement!==n||(e.preventDefault(),s.focus())},className:"bg-surface w-full sm:w-[560px] sm:max-w-full h-[min(85%,calc(var(--app-height,85vh)-2rem))] sm:h-[70vh] sm:max-h-[560px] my-auto rounded-[3px] flex flex-col shadow-elev overflow-hidden",onClick:e=>e.stopPropagation(),children:[(0,n.jsxs)("div",{className:"px-4 h-11 flex items-center gap-2 border-b border-border-subtle flex-shrink-0",children:[(0,n.jsx)("h3",{className:"text-sm font-semibold text-text flex-1",children:l("workspaces.newWorkspace")}),(0,n.jsx)("button",{onClick:a,className:"p-1 text-text-muted hover:text-text rounded-[3px] hover:bg-surface-2",children:(0,n.jsx)(t3.X,{size:16})})]}),(0,n.jsxs)("div",{ref:M,className:"px-3 pt-2 flex items-center gap-0.5 min-h-[28px] overflow-x-auto flex-shrink-0",children:[(0,n.jsx)("button",{onClick:B,disabled:m||!o||"/"===o,className:"shrink-0 p-1.5 text-text-muted hover:text-text hover:bg-surface-2 rounded-[3px] disabled:opacity-30 transition-colors",title:l("workspaces.parentFolder"),children:(0,n.jsx)(t3.Do,{size:14})}),(0,n.jsx)("button",{onClick:()=>O(G||"/"),disabled:m,className:"shrink-0 p-1.5 text-text-muted hover:text-text hover:bg-surface-2 rounded-[3px] transition-colors",title:l("workspaces.homeFolder"),children:(0,n.jsx)(t3.ww,{size:14})}),(0,n.jsxs)("div",{className:"flex items-center gap-0 text-[11px] text-text-muted ml-1 min-w-0",children:[J?(0,n.jsx)("button",{type:"button",onClick:()=>O(null),className:"shrink-0 px-0.5 hover:text-text transition-colors",title:l("workspaces.drives"),children:(0,n.jsx)(t3.ak,{size:12})}):(0,n.jsx)("button",{type:"button",onClick:()=>O("/"),className:"shrink-0 px-0.5 hover:text-text transition-colors",children:"/"}),"drive"===V.kind&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(t3.c_,{size:11,className:"shrink-0 text-text-subtle"}),(0,n.jsx)("button",{type:"button",onClick:()=>O(V.driveRoot),className:`truncate max-w-[120px] px-0.5 hover:text-text transition-colors ${0===V.segments.length?"text-text font-medium":""}`,children:V.driveRoot.replace(/\/$/,"")})]}),V.segments.map((e,t)=>(0,n.jsxs)("div",{className:"flex items-center gap-0 min-w-0",children:[(0,n.jsx)(t3.c_,{size:11,className:"shrink-0 text-text-subtle"}),(0,n.jsx)("button",{type:"button",onClick:()=>O(rb(V,t)),className:`truncate max-w-[120px] px-0.5 hover:text-text transition-colors ${t===V.segments.length-1?"text-text font-medium":""}`,children:e})]},rb(V,t)))]})]}),(0,n.jsxs)("div",{className:"px-3 py-2 flex-shrink-0",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2 bg-surface-2 rounded-[3px] px-2 py-1.5 border border-border-subtle focus-within:border-brand-500 transition-colors",children:[(0,n.jsx)(t3.vj,{size:13,className:"text-text-subtle flex-shrink-0"}),(0,n.jsx)("input",{ref:S,value:f,onChange:e=>K(e.target.value),onPaste:e=>{e.defaultPrevented||e.clipboardData.getData("text/plain").length>2048||(_.current&&clearTimeout(_.current),_.current=setTimeout(()=>{_.current=null,E.current&&(clearTimeout(E.current),E.current=null);let e=S.current?.value??"";e.length<=2048&&rv(e)&&W(e)},0))},onKeyDown:e=>{if("Enter"===e.key){if(y){if(y.error||y.loading)return void e.preventDefault();let t=ry(f);if("path"===t.mode&&""===t.trailingFilter){e.preventDefault(),O(y.resolvedPath);return}return void(1===U.length?(e.preventDefault(),O(U[0].path)):e.preventDefault())}let t=1===H.length?H[0]:H[g];return void(t&&(e.preventDefault(),O(t.path)))}"ArrowDown"===e.key?(e.preventDefault(),v(e=>Math.min(e+1,Math.max(q.length-1,0)))):"ArrowUp"===e.key?(e.preventDefault(),v(e=>Math.max(e-1,0))):"Escape"===e.key&&f?(e.stopPropagation(),b(""),w(null),R.current++,E.current&&(clearTimeout(E.current),E.current=null)):"Backspace"!==e.key||""!==f||y||(e.preventDefault(),B())},placeholder:l("workspaces.filterOrPath"),"aria-invalid":!!y?.error,className:"flex-1 min-w-0 bg-transparent text-sm text-text outline-none placeholder:text-text-subtle"}),y?.loading&&(0,n.jsx)(t3.kr,{size:13,className:"animate-spin text-text-subtle flex-shrink-0"}),!!f&&!y?.loading&&(0,n.jsx)("span",{className:"text-[10px] text-text-subtle tabular-nums flex-shrink-0",children:q.length})]}),y?.error&&(0,n.jsx)("p",{className:"pt-1 px-0.5 text-[11px] text-red-500",children:y.error})]}),(0,n.jsxs)("div",{className:"flex-1 min-h-0 overflow-y-auto modal-scrollable",children:[!f&&!y&&!!N.length&&(0,n.jsxs)("div",{className:"p-2 pb-1",children:[(0,n.jsx)("p",{className:"px-1 pb-1.5 text-[10px] uppercase tracking-wider text-text-subtle",children:l("workspaces.recentFolders")}),(0,n.jsx)("div",{className:"flex gap-1.5 overflow-x-auto pb-0.5",children:N.slice(0,8).map(e=>{let t=e2(e.path);return(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),ru(t),s(t)},className:"flex items-center gap-1.5 px-2 py-1.5 bg-surface-2 hover:bg-surface-3 rounded-[4px] border border-border-subtle text-left transition-colors w-[150px] shrink-0",title:t,children:[(0,n.jsx)(t3.Bm,{size:13,className:"text-brand-500 flex-shrink-0"}),(0,n.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"block text-xs text-text truncate",children:rh(t)||t}),(0,n.jsx)("span",{className:"block text-[10px] text-text-subtle truncate",children:rs(t,G)})]})]},e.path)})})]}),!f&&!y&&!o&&(0,n.jsx)("div",{className:"p-2 space-y-1",children:J?k?.drives?.map(e=>(0,n.jsx)(rk,{icon:(0,n.jsx)(t3.ak,{size:15,className:"text-blue-500/70"}),label:e2(e.path),onClick:()=>O(e2(e.path))},e.letter)):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(rk,{icon:(0,n.jsx)(t3.ww,{size:15,className:"text-blue-500/70"}),label:G||"/",onClick:()=>O(G||"/")}),(0,n.jsx)(rk,{icon:(0,n.jsx)(t3.ak,{size:15,className:"text-text-subtle"}),label:"/",onClick:()=>O("/")})]})}),m&&(0,n.jsx)("div",{className:"p-6 flex justify-center text-text-muted",children:(0,n.jsx)(t3.kr,{size:18,className:"animate-spin"})}),!m&&p&&(0,n.jsx)("p",{className:"p-4 text-xs text-red-500",children:p}),!m&&!p&&(o||y)&&(0,n.jsxs)("div",{className:"p-1",children:[q.map((e,t)=>(0,n.jsxs)("button",{onClick:()=>{!y?.loading&&($.current&&clearTimeout($.current),$.current=setTimeout(()=>{$.current=null,O(e.path)},220))},onDoubleClick:()=>{!y?.loading&&($.current&&(clearTimeout($.current),$.current=null),ru(e.path),s(e.path))},onMouseDown:e=>{C.current&&(e.preventDefault(),S.current?.focus())},className:`group w-full flex items-center gap-2 pl-3 pr-2 py-2 text-sm text-text rounded-[3px] hover:bg-surface-2 active:bg-surface-2 transition-colors ${(f||y)&&t===g?"bg-surface-2 ring-1 ring-brand-500/40":""}`,children:[(0,n.jsx)(t3.vd,{size:16,className:"text-orange-500/70 flex-shrink-0"}),(0,n.jsx)("span",{className:"flex-1 min-w-0 truncate text-left",title:e.name,children:e.name}),(0,n.jsx)(t3.c_,{size:14,className:"text-text-subtle flex-shrink-0 opacity-0 group-hover:opacity-100"})]},e.path)),!q.length&&(0,n.jsx)("p",{className:"px-3 py-4 text-xs text-text-subtle italic",children:(y?y.entries.length:d.length)?l("common.noResults"):l("files.emptyFolder")})]})]}),(0,n.jsxs)("div",{className:"px-3 pt-2 pb-3 border-t border-border-subtle flex-shrink-0",children:[(0,n.jsx)("p",{className:"pb-2 text-[10px] text-text-subtle truncate",title:y?y.resolvedPath:o||"",children:y?rs(y.resolvedPath,G):o?rs(o,G):l("workspaces.drives")}),(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("button",{onClick:a,className:"px-4 py-2 text-sm text-text-muted hover:text-text bg-surface-2 hover:bg-surface-3 rounded-[3px] transition-colors",children:l("common.cancel")}),(0,n.jsx)("button",{onClick:()=>{o&&(ru(o),(0,t7.e)(),s(o))},disabled:!o||Y,className:"flex-1 py-2 text-sm font-semibold text-white bg-brand-500 hover:bg-brand-600 rounded-[3px] transition-colors disabled:opacity-40 disabled:cursor-not-allowed truncate",title:o||"",children:X?l("workspaces.selectNamed",{name:X}):l("workspaces.selectFolder")})]})]})]})})}function rk({icon:e,label:t,onClick:s}){return(0,n.jsxs)("button",{onClick:s,className:"w-full flex items-center gap-2 px-2 py-1.5 text-xs text-text-muted hover:text-text hover:bg-surface-2 rounded-[3px] transition-colors text-left",children:[(0,n.jsx)("span",{className:"flex-shrink-0",children:e}),(0,n.jsx)("span",{className:"truncate",children:t})]})}let rj=["⌥","⇧","↵"],rN=["Ctrl","⇧","↵"],rS=[{id:"new",icon:t3.BK,labelKey:"terminal.newTerminal"},{id:"history",icon:t3.BZ,labelKey:"agentHistory.title"}];function rC({agent:e}){let[t,s]=(0,r.useState)(!1);return e?t?(0,n.jsx)(t3.cC,{size:16,className:"text-text-muted"}):(0,n.jsx)("img",{src:s$(e.id),alt:"",width:16,height:16,onError:()=>s(!0),className:`w-4 h-4 object-contain ${s_}`}):(0,n.jsx)(t3.BK,{size:16,className:"text-text-muted"})}function rT({onClose:e,onCreate:t,shells:s=[],suggestName:a="",busRef:l=null,workspacePath:i=null,workspaceName:o="",fileBus:c=null,homeDir:d=null,onResumeAgentSession:u=null,liveSessionIds:m=null,activeSessionId:x=null,onSelectSession:p=null,connected:h=!0,hostKey:f="main"}){let{t:b}=(0,se.s)(),g=ne(l,f),[v,y]=(0,r.useState)(()=>sF().agentId),[w,k]=(0,r.useState)(""),[j,N]=(0,r.useState)(null),[S,C]=(0,r.useState)(!1),[T,R]=(0,r.useState)(()=>sF().yolo),[E,_]=(0,r.useState)(()=>{let e=sL(sA);return e&&s.some(t=>t.id===e)?e:s[0]?.id||""}),[$,M]=(0,r.useState)("new"),P=(0,r.useRef)(null),A=(0,r.useRef)(null),z=(0,r.useRef)(!1);(0,r.useEffect)(()=>{window.matchMedia("(pointer: fine)").matches&&requestAnimationFrame(()=>P.current?.focus())},[]);let I=s1()?rj:rN;(0,r.useEffect)(()=>{!z.current&&g?.length&&v&&(z.current=!0,A.current?.querySelector("[data-picked=true]")?.scrollIntoView({block:"nearest"}))},[g,v]);let L=nt.H8,D=(g||[]).flatMap(e=>{let t=L.find(t=>t.aiEngine===e.id);return t?[e,t]:[e]}),F=new Map(L.map(e=>[e.aiEngine,e])),O=new Set(F.keys()),B=D.find(e=>"claude"===e.id),W=D.find(e=>"claude-ui"===e.id),K=[],H=new Set(["claude"]);for(let e of D){let t=e.isAiUi?e.aiEngine:e.id;if(H.has(t)||!O.has(t))continue;H.add(t);let s=D.find(e=>!e.isAiUi&&e.id===t),n=F.get(t);s&&K.push(s),n&&K.push(n)}let U=D.filter(e=>!e.isAiUi&&!O.has(e.id)&&"claude"!==e.id),q=v&&D.find(e=>e.id===v)||null,V=[null,{empty:!0},...B?[B]:[],...W?[W]:[],...K,...U],X=!q?.isAiUi&&sM(q),G=q?.yolo||(q?.yoloEnv?Object.entries(q.yoloEnv).map(([e,t])=>`${e}=${t}`).join(" "):null),J=e=>{(0,t7.e)(),y(e?.id||"")},Y=a.match(/\d+$/)?.[0],Z=q?`${q.short||q.label}${Y?` ${Y}`:""}`:a||b("terminal.defaultName"),Q=j||i,ee=!!u&&!!Q,et=ee&&"history"===$,es=(s=q)=>{(0,t7.e)(),!s&&E&&sD(sA,E),sD(sz,s?.id||""),sD(sI,T?"1":"0");let n=T&&sM(s),r=Y?` ${Y}`:"",a=w.trim(),l=a||(s?`${s.short||s.label}${r}`:null);t?.(l,!s&&E||null,s,n,j,!a),e?.()},en=(0,r.useRef)(es);return(0,r.useEffect)(()=>{en.current=es}),(0,r.useEffect)(()=>{let t=t=>{if(!S&&!t.target?.closest?.("[data-wt-form]")){if("Escape"===t.key)t.preventDefault(),t.stopPropagation(),e?.();else if("Enter"===t.key&&"new"===$){if(t.target?.tagName==="BUTTON"){t.target?.getAttribute("role")==="radio"&&(t.preventDefault(),t.stopPropagation(),en.current());return}if(t.target?.tagName==="SELECT")return;t.preventDefault(),t.stopPropagation(),en.current()}}};return window.addEventListener("keydown",t,!0),()=>window.removeEventListener("keydown",t,!0)},[S,$,e]),(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"fixed inset-0 z-[60] flex items-center justify-center px-4 bg-black/50 backdrop-blur-[4px] animate-in fade-in duration-150",style:{paddingTop:"max(1rem, env(safe-area-inset-top))",paddingBottom:"max(1rem, env(safe-area-inset-bottom))"},onClick:e,children:(0,n.jsxs)("div",{role:"dialog","aria-modal":"true","aria-labelledby":"newTerminalTitle",className:"card-elev w-[26rem] max-w-full overflow-hidden flex flex-col my-auto max-h-[min(85%,calc(var(--app-height,85vh)-2rem))] animate-in zoom-in-95 duration-150",onClick:e=>e.stopPropagation(),children:[(0,n.jsxs)("div",{className:`px-4 pt-4 space-y-2.5 ${et?"pb-0":"pb-3"}`,children:[(0,n.jsxs)("div",{className:`flex gap-2 ${ee?"items-stretch -mx-4 px-4 border-b border-border-subtle":"items-center"}`,children:[ee?(0,n.jsx)("div",{role:"tablist",className:"flex-1 min-w-0 flex items-stretch gap-3",children:rS.map(({id:e,icon:t,labelKey:s})=>(0,n.jsxs)("button",{role:"tab","aria-selected":$===e,onClick:()=>{(0,t7.e)(),M(e)},className:`pb-2 -mb-px flex items-center gap-1.5 text-sm font-semibold border-b-2 transition-colors ${$===e?"text-text border-brand-500":"text-text-muted border-transparent hover:text-text"}`,children:[(0,n.jsx)(t,{size:14,className:"shrink-0"}),(0,n.jsx)("span",{className:"truncate",children:b(s)})]},e))}):(0,n.jsx)("h2",{id:"newTerminalTitle",className:"flex-1 text-sm font-semibold text-text",children:b("terminal.newTerminal")}),(0,n.jsx)("button",{onClick:e,"aria-label":b("common.cancel"),className:"text-text-muted hover:text-text shrink-0 self-center",children:(0,n.jsx)(t3.X,{size:18})})]}),i&&!et&&(0,n.jsx)(ra,{workspacePath:i,workspaceName:o,fileBus:c,homeDir:d,value:j,onChange:N,onBrowse:()=>C(!0)})]}),et?(0,n.jsx)(rc,{variant:"list",busRef:l,cwd:Q,onResume:t=>{u?.(t),e?.()},onSelectSession:t=>{p?.(t),e?.()},liveSessionIds:m,activeSessionId:x,connected:h}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{ref:A,role:"radiogroup","aria-label":b("terminal.newTerminal"),className:"flex-1 min-h-0 overflow-y-auto scrollbar-thin px-3 pb-1 grid grid-cols-2 gap-1.5 content-start",children:V.map((e,t)=>{if(e?.empty)return(0,n.jsx)("div",{"aria-hidden":"true",className:"pointer-events-none select-none"},"__empty_spacer");let s=(e?.id||"")===(q?.id||"");return(0,n.jsxs)("button",{type:"button",role:"radio","aria-checked":s,tabIndex:s?0:-1,onClick:()=>J(e),onDoubleClick:()=>es(e),onKeyDown:e=>((e,t)=>{let s={ArrowRight:1,ArrowLeft:-1,ArrowDown:2,ArrowUp:-2}[e.key];if(void 0===s)return;e.preventDefault();let n=t+s;V[n]?.empty&&(n+=s>0?1:-1),n=Math.max(0,Math.min(V.length-1,n)),V[n]?.empty||(J(V[n]),A.current?.querySelector(`[data-index="${n}"]`)?.focus())})(e,t),"data-picked":s,"data-index":t,className:`flex items-center gap-2 px-2.5 py-2 rounded-brand text-left transition-colors min-w-0 outline-none focus:outline-none focus:ring-0 ${s?"bg-brand-500/15 text-text":"text-text-muted hover:bg-surface-2 hover:text-text"}`,children:[(0,n.jsx)(rC,{agent:e}),(0,n.jsx)("span",{className:"flex-1 text-sm font-medium truncate",children:e?e.label:b("terminal.plainShell")}),s&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"hidden sm:inline-flex items-center gap-0.5 shrink-0 select-none",children:I.map(e=>(0,n.jsx)("kbd",{className:"inline-flex items-center justify-center px-1 py-0.5 text-[13px] font-medium leading-none rounded bg-surface-2 border border-border-subtle text-text",children:e},e))}),(0,n.jsx)(t3.aJ,{size:14,className:"text-brand-400 shrink-0 sm:hidden"})]})]},e?.id||"__plain")})}),(0,n.jsxs)("div",{className:"px-4 pt-3 pb-4 border-t border-border/60 space-y-3",children:[!q&&s.length>0&&(0,n.jsx)("select",{value:E,onChange:e=>_(e.target.value),"aria-label":b("terminal.shell"),className:"w-full px-3 py-2 bg-surface-2 rounded-brand text-sm text-text focus:outline-none focus:ring-2 focus:ring-brand-500/40",children:s.map(e=>(0,n.jsx)("option",{value:e.id,children:e.label},e.id))}),(0,n.jsxs)("label",{className:`flex items-center gap-2 px-0.5 select-none ${X?"cursor-pointer":"opacity-50 cursor-not-allowed"}`,children:[(0,n.jsx)("input",{type:"checkbox",checked:X&&T,disabled:!X,onChange:e=>R(e.target.checked),className:"w-4 h-4 accent-brand-500 cursor-pointer disabled:cursor-not-allowed"}),G?(0,n.jsx)("code",{className:"min-w-0 text-xs font-mono text-text-muted truncate",children:G}):(0,n.jsx)("span",{className:"text-xs text-text-muted",children:b("terminal.skipPermissions")})]}),(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)("label",{htmlFor:"newTerminalName",className:"block text-[11px] font-medium text-text-muted px-0.5",children:b("terminal.nameLabel")}),(0,n.jsx)("input",{id:"newTerminalName",type:"text",ref:P,value:w,placeholder:Z,onInput:e=>k(e.target.value),onKeyDown:e=>{"ArrowUp"===e.key&&(e.preventDefault(),A.current?.querySelector("[data-picked=true]")?.focus())},className:"w-full px-3 py-2 bg-surface-2 rounded-brand text-sm text-text placeholder-text-muted focus:outline-none focus:ring-2 focus:ring-brand-500/40"})]}),(0,n.jsxs)("div",{className:"flex gap-2",children:[(0,n.jsxs)("button",{onClick:e,className:"flex-1 py-2 text-sm text-text-muted bg-surface-2 hover:bg-surface-3 rounded-brand transition-colors flex items-center justify-center gap-1.5",children:[(0,n.jsx)("span",{children:b("common.cancel")}),(0,n.jsx)("kbd",{className:"hidden sm:inline-flex items-center text-[10px] font-mono px-1 py-0.5 rounded bg-surface-3 text-text-muted leading-none",children:"Esc"})]}),(0,n.jsxs)("button",{onClick:()=>es(),className:"flex-1 py-2 text-sm font-semibold text-white bg-brand-500 hover:bg-brand-600 rounded-brand transition-colors flex items-center justify-center gap-1.5",children:[(0,n.jsx)("span",{children:b("common.create")}),(0,n.jsx)("kbd",{className:"hidden sm:inline-flex items-center justify-center w-4 h-4 rounded bg-white/20 text-white",children:(0,n.jsx)(t3.Lt,{size:10,strokeWidth:2.5})})]})]})]})]})]})}),S&&(0,n.jsx)(rw,{fileBus:c,initialPath:j||i,onSelect:e=>{C(!1),e&&N(e)},onClose:()=>C(!1)})]})}function rR({title:e,value:t,onChange:s,onSubmit:a,onClose:l,confirmLabel:i,cancelLabel:o,placeholder:c}){let{t:d}=(0,se.s)();return(0,r.useEffect)(()=>{let e=e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),l?.())};return window.addEventListener("keydown",e,!0),()=>window.removeEventListener("keydown",e,!0)},[l]),(0,n.jsxs)("div",{className:"fixed inset-0 z-[85] flex items-center justify-center px-4",style:{paddingTop:"max(1rem, env(safe-area-inset-top))",paddingBottom:"max(1rem, env(safe-area-inset-bottom))"},onClick:l,children:[(0,n.jsx)("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-[4px] animate-in fade-in duration-150"}),(0,n.jsxs)("div",{role:"dialog","aria-modal":"true",className:"relative card-elev w-full max-w-xs p-5 my-auto max-h-[min(85%,calc(var(--app-height,85vh)-2rem))] overflow-y-auto animate-in zoom-in-95 duration-150",onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:[(0,n.jsx)("h3",{className:"text-[14px] font-semibold text-text mb-3",children:e}),(0,n.jsx)("input",{autoFocus:!0,value:t,placeholder:c,onChange:e=>s(e.target.value),onKeyDown:e=>{"Enter"===e.key&&a(),"Escape"===e.key&&l()},className:"w-full bg-surface-2 border border-border-subtle rounded-brand px-3 py-2 text-sm text-text outline-none focus:border-brand-500"}),(0,n.jsxs)("div",{className:"flex gap-2 mt-4",children:[(0,n.jsxs)("button",{onClick:a,disabled:!t?.trim(),className:"flex-1 py-2 text-sm font-semibold text-white bg-brand-500 rounded-brand disabled:opacity-40 flex items-center justify-center gap-1.5",children:[(0,n.jsx)("span",{children:i??d("common.confirm")}),(0,n.jsx)("kbd",{className:"hidden sm:inline-flex items-center justify-center w-4 h-4 rounded bg-white/20 text-white",children:(0,n.jsx)(t3.Lt,{size:10,strokeWidth:2.5})})]}),(0,n.jsxs)("button",{onClick:l,className:"flex-1 py-2 text-sm text-text-muted bg-surface-2 rounded-brand flex items-center justify-center gap-1.5",children:[(0,n.jsx)("span",{children:o??d("common.cancel")}),(0,n.jsx)("kbd",{className:"hidden sm:inline-flex items-center text-[10px] font-mono px-1 py-0.5 rounded bg-surface-3 text-text-muted leading-none",children:"Esc"})]})]})]})]})}function rE(e,t,s,n=8){let a=(e,t)=>{if(0===e&&0===t)return{left:e,top:t};let s=window.innerWidth,r=window.innerHeight;return{left:e+160>s-n?Math.max(n,e-160):e,top:t+120>r-n?Math.max(n,t-120):t}},[l,i]=(0,r.useState)(()=>a(t,s)),[o,c]=(0,r.useState)({x:t,y:s});return(o.x!==t||o.y!==s)&&(c({x:t,y:s}),i(a(t,s))),(0,r.useEffect)(()=>{let r=e?.current;if(!r||0===t&&0===s)return;let{width:a,height:l}=r.getBoundingClientRect(),o=window.innerWidth,c=window.innerHeight;i({left:t+a>o-n?Math.max(n,t-a):t,top:s+l>c-n?Math.max(n,s-l):s})},[e,t,s,n]),l}var r_=s(98196);async function r$(e,t=1600,s=.8){let n=await createImageBitmap(e),r=Math.min(1,t/Math.max(n.width,n.height)),a=document.createElement("canvas");return a.width=Math.max(1,Math.round(n.width*r)),a.height=Math.max(1,Math.round(n.height*r)),a.getContext("2d").drawImage(n,0,0,a.width,a.height),n.close(),a.toDataURL("image/jpeg",s)}function rM(e){let{t}=(0,se.s)(),[s,a]=(0,r.useState)(!1),[l,i]=(0,r.useState)(""),o=(0,r.useRef)(null),c=async n=>{let r=n.target.files?.[0];if(n.target.value="",r&&!s)try{(s=>{let n=e?.current;if(!n?.emit)return i(t("menu.bgSaveFailed"));a(!0),i("");let r=!1,l=e=>{r||(r=!0,clearTimeout(o),a(!1),e())},o=setTimeout(()=>l(()=>i(t("menu.bgSaveFailed"))),2e4);n.emit("bg:save",{dataUrl:s},e=>{l(()=>{if(e?.success&&e.id&&e.dataUrl){let t=`custom:${e.id}`,{customBackgrounds:s,setCustomBackgrounds:n,terminalBackgrounds:r,setTerminalBackgrounds:a}=tS.getState();n([...s,{id:e.id,dataUrl:e.dataUrl}]),r.includes(t)||a([...r,t]),(0,t7.e)()}else i(e?.error||t("menu.bgSaveFailed"))})})})(await r$(r))}catch{i(t("menu.bgSaveFailed"))}};return{saving:s,error:l,setError:i,fileInput:(0,n.jsx)("input",{ref:o,type:"file",accept:"image/*",className:"hidden",onChange:c}),openPicker:()=>{(0,t7.e)(),s||o.current?.click()}}}let rP="none";function rA({sessionId:e,title:t,onClose:s,busRef:a}){let{t:l}=(0,se.s)(),i=tS(t=>t.backgroundBySession[e]),o=tS(e=>e.setSessionBackground),c=tS(e=>e.customBackgrounds),d=tS(e=>e.terminalBackgrounds),u=tS(e=>e.setTerminalBackgrounds),m=tS(e=>e.setTerminalBackgroundOpacity),x=tS(e=>e.terminalBackgroundOpacity)??.8,[p,h]=(0,r.useState)(!1),{saving:f,error:b,fileInput:g,openPicker:v}=rM(a);if("u"<typeof document)return null;let y=e_(d,c),w=i??null,k=[{key:rP,label:eS.none.label},...c.map(e=>({key:`custom:${e.id}`,label:l("menu.bgCustomLabel"),src:e.dataUrl})),...Object.entries(eS).filter(([e])=>e!==rP).map(([e,t])=>({key:e,label:t.label,src:t.src}))];return(0,r_.createPortal)((0,n.jsxs)("div",{className:"fixed inset-0 z-[70] flex items-center justify-center p-4",children:[(0,n.jsx)("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-[2px] animate-in fade-in duration-200",onClick:s}),(0,n.jsxs)("div",{className:"relative w-full max-w-lg max-h-[80vh] rounded-brand-lg border border-border-subtle bg-surface shadow-2xl flex flex-col overflow-hidden animate-in zoom-in-95 duration-200",children:[(0,n.jsxs)("div",{className:"px-5 py-3 flex items-center justify-between flex-shrink-0 border-b border-border-subtle",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2 min-w-0",children:[(0,n.jsx)("span",{className:"w-6 h-6 rounded-full flex items-center justify-center flex-shrink-0 bg-brand-500/15 text-brand-500",children:(0,n.jsx)(t3.P6,{size:13})}),(0,n.jsxs)("div",{className:"min-w-0",children:[(0,n.jsx)("h2",{className:"text-sm font-semibold text-text truncate",children:l("menu.terminalBackground")}),t&&(0,n.jsx)("p",{className:"text-[11px] text-text-muted truncate",children:t})]})]}),(0,n.jsx)("button",{type:"button",onClick:s,className:"p-1 rounded-brand text-text-muted hover:text-text hover:bg-surface-2 transition-colors flex-shrink-0","aria-label":l("common.close"),children:(0,n.jsx)(t3.X,{size:16})})]}),(0,n.jsx)("div",{className:"flex-1 min-h-0 overflow-y-auto modal-scrollable px-4 py-4",children:(0,n.jsx)("div",{className:"grid grid-cols-3 gap-3",children:k.map(({key:t,label:r,src:a})=>{let l=t===rP,i=l?-1:y.indexOf(t),c=p?l?0===y.length:-1!==i:w===t;return(0,n.jsxs)("button",{type:"button",onClick:()=>(t=>{if(!p){o(e,t),s?.();return}t===rP?u([]):u(y.includes(t)?y.filter(e=>e!==t):[...y,t])})(t),className:`relative block w-full aspect-[9/16] rounded-2xl overflow-hidden transition-transform duration-200 ease-out active:scale-[0.97] ${c?"":"hover:-translate-y-0.5"}`,children:[a?(0,n.jsx)("img",{src:a,alt:r,className:"absolute inset-0 h-full w-full object-cover",loading:"lazy"}):(0,n.jsxs)("span",{className:"absolute inset-0 flex flex-col items-center justify-center gap-2 bg-surface-2 text-text-muted",children:[(0,n.jsx)(t3.P6,{size:22,strokeWidth:1.75}),(0,n.jsx)("span",{className:"text-[11px] font-medium",children:l?eS.none.label:r})]}),a&&(0,n.jsx)("span",{className:"pointer-events-none absolute inset-0",style:{background:"rgba(0,0,0,0.25)"}}),a&&(0,n.jsx)("span",{className:"absolute inset-x-0 bottom-0 h-1/3 bg-gradient-to-t from-black/70 to-transparent"}),a&&(0,n.jsx)("span",{className:"absolute bottom-1.5 inset-x-0 px-2 text-[11px] font-medium text-white truncate text-center",children:r}),(0,n.jsx)("span",{className:`pointer-events-none absolute inset-0 rounded-2xl ${c?"ring-1 ring-inset ring-brand-500":"ring-1 ring-inset ring-white/15"}`}),p&&c&&!l&&(0,n.jsx)("span",{className:"absolute top-1.5 right-1.5 flex items-center justify-center w-5 h-5 rounded-full bg-brand-500 text-white text-[11px] font-semibold shadow-lg",children:i+1})]},t??"global")})})}),(0,n.jsxs)("div",{className:"flex-shrink-0 border-t border-border-subtle px-4 py-3 flex items-center gap-3",children:[(0,n.jsx)("span",{className:"text-xs text-text flex-shrink-0",children:l("menu.bgDim")}),(0,n.jsx)("input",{type:"range",min:eN.min,max:eN.max,step:eN.step,value:x,onChange:e=>m(Number(e.target.value)),className:"brand-range flex-1 min-w-0",style:{"--pct":`${(x-eN.min)/(eN.max-eN.min)*100}%`},"aria-label":l("menu.bgDim")}),(0,n.jsxs)("span",{className:"text-xs text-text-muted tabular-nums flex-shrink-0",children:[Math.round(100*x),"%"]})]}),(0,n.jsxs)("div",{className:"flex-shrink-0 border-t border-border-subtle px-4 py-2.5 flex items-center gap-3",children:[(0,n.jsxs)("label",{className:"flex items-center gap-2.5 cursor-pointer min-w-0",children:[(0,n.jsx)("input",{type:"checkbox",checked:p,onChange:e=>h(e.target.checked),className:"accent-brand-500 w-3.5 h-3.5 flex-shrink-0"}),(0,n.jsx)("span",{className:"text-xs text-text truncate",children:l("menu.bgApplyAll")})]}),(0,n.jsx)("div",{className:"flex-1"}),(0,n.jsxs)("button",{type:"button",onClick:v,disabled:f,className:"flex items-center gap-1.5 px-2.5 py-1.5 rounded-brand border border-border-subtle text-xs text-text-muted hover:text-brand-500 hover:border-brand-500 transition-colors disabled:opacity-40 flex-shrink-0",children:[f?(0,n.jsx)(t3.kr,{size:13,className:"animate-spin"}):(0,n.jsx)(t3.FW,{size:13}),l("menu.bgAdd")]})]}),b&&(0,n.jsx)("div",{className:"flex-shrink-0 px-4 pb-3",children:(0,n.jsx)("div",{className:"px-3 py-2 rounded-brand bg-red-500/10 border border-red-500/30 text-red-500 text-xs break-all",children:b})})]}),g]}),document.body)}let rz={y:{pos:"clientY",start:"top",size:"height"},x:{pos:"clientX",start:"left",size:"width"}};function rI({axis:e="y",threshold:t=3,onCommit:s}){let[n,a]=(0,r.useState)(null),l=(0,r.useRef)(new Map),i=(0,r.useRef)(!1),o=(0,r.useRef)(null),c=(0,r.useRef)(null),d=(0,r.useCallback)(e=>t=>{t?l.current.set(e,t):l.current.delete(e)},[]),u=(0,r.useCallback)(()=>{let e=i.current;return i.current=!1,o.current&&(clearTimeout(o.current),o.current=null),e},[]);return{dragId:n,registerEl:d,startDrag:(0,r.useCallback)((n,r,d)=>{if("mouse"===n.pointerType&&0!==n.button||(c.current?.(!1),i.current=!1,o.current&&(clearTimeout(o.current),o.current=null),!d||d.length<2))return;let u=d.indexOf(r);if(u<0)return;let m=rz[e],x=d.map(e=>{let t=l.current.get(e)?.getBoundingClientRect();return t?{start:t[m.start],size:t[m.size]}:null});if(x.some(e=>!e))return;i.current=!1,o.current&&(clearTimeout(o.current),o.current=null);let p=x[u],h=n[m.pos],f=u,b=null,g=s=>{if("mouse"===s.pointerType&&0===s.buttons)return void y();let n=s[m.pos]-h;if(!i.current){if(Math.abs(n)<t)return;i.current=!0,(0,t7.e)(),a(r)}let o=p.start+p.size/2+n,c=0;for(let e=0;e<x.length;e++)o>=x[e].start&&(c=e);f=c,b||(b=requestAnimationFrame(()=>{let t;return b=null,void((t=l.current.get(r))&&(t.style.transform=`translate${e.toUpperCase()}(${n}px)`),d.forEach((t,s)=>{if(t===r)return;let n=l.current.get(t);if(!n)return;let a=0;u<f&&s>u&&s<=f?a=-p.size:u>f&&s>=f&&s<u&&(a=p.size),n.style.transform=a?`translate${e.toUpperCase()}(${a}px)`:""}))}))},v=e=>{for(let e of(window.removeEventListener("pointermove",g),window.removeEventListener("pointerup",y),window.removeEventListener("pointercancel",y),window.removeEventListener("blur",y),c.current=null,b&&(cancelAnimationFrame(b),b=null),l.current.values()))e&&(e.style.transform="");if(a(null),!e||!i.current||(o.current=setTimeout(()=>{o.current=null,i.current=!1},0),f===u))return;let t=[...d];t.splice(f,0,t.splice(u,1)[0]),(0,t7.e)(),s?.(t)},y=()=>v(!0);c.current=v,window.addEventListener("pointermove",g,{passive:!1}),window.addEventListener("pointerup",y),window.addEventListener("pointercancel",y),window.addEventListener("blur",y)},[e,t,s]),consumeClick:u}}var rL=s(48310),rD=s(38415);let rF="sm:h-8",rO=(0,r.memo)(function({bus:e}){let[t,s]=(0,r.useState)([]),[a,l]=(0,r.useState)(""),[i,o]=(0,r.useState)(!1),c=(0,r.useRef)(null);(0,r.useEffect)(()=>{if(!e?.emit)return;e.emit("jarvis:chatHistory",{},e=>{e?.ok&&s(function(e=[]){let t=[];for(let s of e)for(let e of s?.parts||[])"string"==typeof e?.text&&e.text?t.push({type:"user"===s.role?"user":"assistant",text:e.text}):e?.functionCall?t.push({type:"tool",name:e.functionCall.name,args:e.functionCall.args||{}}):e?.functionResponse&&t.push({type:"toolResult",name:e.functionResponse.name,text:JSON.stringify(e.functionResponse.response||{}).slice(0,300)});return t.slice(-80)}(e.history))});let t=e=>{e?.type==="assistant"&&o(!1),e?.type&&"user"!==e.type&&s(t=>[...t.slice(-160),e])};return e.on?.("jarvis:chat:event",t),()=>e.off?.("jarvis:chat:event",t)},[e]),(0,r.useEffect)(()=>{c.current?.scrollTo?.({top:c.current.scrollHeight})},[t]);let d=()=>{let t=a.trim();t&&!i&&e?.emit&&((0,t7.e)(),l(""),o(!0),e.emit("jarvis:chat",{text:t},e=>{o(!1),e?.error&&s(t=>[...t,{type:"error",text:e.error}])}))};return(0,n.jsxs)("div",{className:"h-full flex flex-col min-h-0",children:[(0,n.jsxs)("div",{ref:c,className:"flex-1 min-h-0 overflow-y-auto modal-scrollable px-3 py-3 flex flex-col gap-2.5",children:[0===t.length&&(0,n.jsxs)("div",{className:"flex-1 flex flex-col items-center justify-center gap-2 text-text-muted p-4",children:[(0,n.jsx)(t3.cC,{size:28,className:"opacity-50"}),(0,n.jsx)("span",{className:"text-xs text-center leading-relaxed",children:"Chat to coordinate — e.g. “create a demo task in 9router”, “who is free?”, “what is that worker doing?”"})]}),t.map((e,t)=>"user"===e.type?(0,n.jsx)("div",{className:"self-end max-w-[85%] px-3 py-1.5 rounded-brand-lg rounded-br-sm bg-brand-500/15 text-sm text-text whitespace-pre-wrap break-words",children:e.text},t):"assistant"===e.type?(0,n.jsx)("div",{className:"self-start max-w-[85%] px-3 py-1.5 rounded-brand-lg rounded-bl-sm bg-surface-2 text-sm text-text whitespace-pre-wrap break-words",children:e.text},t):"error"===e.type?(0,n.jsx)("div",{className:"self-start max-w-[85%] px-3 py-1.5 rounded-brand bg-red-500/10 text-xs text-red-400 break-words",children:e.text},t):(0,n.jsxs)("div",{className:"self-start max-w-[85%] px-2 py-1 rounded-brand bg-surface-2/50 border border-border-subtle/60 text-[10px] font-mono text-text-muted break-words",children:[(0,n.jsx)("span",{className:"text-brand-400",children:e.name}),"tool"===e.type?`(${JSON.stringify(e.args).slice(0,120)})`:` → ${String(e.text||"").slice(0,200)}`]},t)),i&&(0,n.jsx)("div",{className:"self-start px-3 text-[11px] text-text-muted animate-pulse",children:"Jarvis is thinking…"})]}),(0,n.jsxs)("div",{className:"flex-shrink-0 border-t border-border-subtle p-2 flex items-end gap-2",children:[(0,n.jsx)("textarea",{value:a,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),d())},rows:1,placeholder:"Delegate to Jarvis…",className:"flex-1 resize-none max-h-32 px-3 py-2 rounded-brand bg-surface-2/40 border border-border-subtle text-sm text-text placeholder:text-text-muted/60 outline-none focus:border-brand-500/60 transition-colors"}),(0,n.jsx)("button",{type:"button",onClick:d,disabled:i||!a.trim(),className:"p-2 rounded-brand bg-brand-500/15 text-brand-400 hover:bg-brand-500/25 disabled:opacity-40 disabled:cursor-not-allowed transition-colors","aria-label":"Send",children:i?(0,n.jsx)(t3.M6,{size:14}):(0,n.jsx)(t3.Vn,{size:14})})]})]})}),rB=["todo","in_progress","needs_input","done"],rW={enabled:!0,llmProvider:"gemini",llmBaseUrl:"",llmKey:"",agentModel:"gemini-3.8-flash",boardScope:"workspace",wakeOnDone:!0,liveKey:"",liveModel:"gemini-3.8-live",liveVoice:"Puck"},rK=[{id:"gemini",label:"Google Gemini",baseUrlHint:"https://generativelanguage.googleapis.com (default)",models:["gemini-3.8-flash","gemini-2.5-flash","gemini-2.5-pro"]},{id:"openai",label:"OpenAI-compatible",baseUrlHint:"https://openrouter.ai/api/v1 (default)",models:["openai/gpt-5","anthropic/claude-sonnet-5","google/gemini-3.8-flash"]},{id:"anthropic",label:"Anthropic",baseUrlHint:"https://api.anthropic.com (default)",models:["claude-sonnet-5","claude-haiku-4-5"]}],rH="jarvisSettings",rU=["Puck","Charon","Kore","Fenrir","Aoede","Leda"],rq={tasks:{}},rV=(0,Z.v)((e,t)=>({board:rq,sink:null,applyBoard:t=>e({board:t?.tasks?t:rq}),setSink:t=>e({sink:"function"==typeof t?t:null}),moveTask:(s,n)=>{let r=t().board.tasks[s];r&&rB.includes(n)&&(e({board:{tasks:{...t().board.tasks,[s]:{...r,status:n,updatedAt:Date.now()}}}}),t().sink?.({type:"move",taskId:s,status:n}))},deleteTask:s=>{if(!t().board.tasks[s])return;let n={...t().board.tasks};delete n[s],e({board:{tasks:n}}),t().sink?.({type:"delete",taskId:s})}})),rX=(0,Z.v)((e,t)=>({open:!1,settings:{...rW},setOpen:t=>e({open:!!t}),toggle:()=>e(e=>({open:!e.open})),hydrateSettings:()=>{let t;return e({settings:(!(t={...rW,...(()=>{try{let e=JSON.parse(localStorage.getItem(rH));return e&&"object"==typeof e?e:{}}catch{return{}}})()}).llmKey&&t.liveKey&&(t.llmKey=t.liveKey),t)})},setSettings:s=>{let n={...t().settings,...s&&"object"==typeof s?s:{}};try{localStorage.setItem(rH,JSON.stringify(n))}catch{}e({settings:n})}}));rX.getState().hydrateSettings();let rG={todo:{label:"Todo",cls:"text-text-muted",dot:"bg-text-muted/60"},in_progress:{label:"In Progress",cls:"text-sky-400",dot:"bg-sky-400"},needs_input:{label:"Needs Input",cls:"text-amber-400",dot:"bg-amber-400"},done:{label:"Done",cls:"text-emerald-400",dot:"bg-emerald-400"}},rJ={needs_input:"border-amber-500/60 animate-pulse",done:"border-border-subtle/60 opacity-70"};function rY({task:e,prev:t,next:s,showWorkspace:r}){let a=rV(e=>e.moveTask),l=rV(e=>e.deleteTask),i=r&&e.workspace?String(e.workspace).split("/").filter(Boolean).pop():"";return(0,n.jsxs)("div",{className:`group relative p-2 rounded-brand border border-border-subtle/80 bg-surface-2/80 text-xs shadow-sm
|
|
6
|
+
transition-all duration-150 ease-out hover:bg-surface-3/60 hover:border-border/80 hover:-translate-y-px
|
|
7
|
+
animate-in fade-in slide-in-from-bottom-1 duration-150 ${rJ[e.status]||""}`,children:[(0,n.jsx)("div",{className:"pr-4 font-medium text-text break-words",children:e.title}),(e.engine||e.branch||i)&&(0,n.jsxs)("div",{className:"mt-1 flex items-center gap-1.5 flex-wrap text-[10px] text-text-muted",children:[i&&(0,n.jsx)("span",{className:"px-1.5 py-0.5 rounded bg-brand-500/10 text-brand-400 truncate max-w-[110px]",title:e.workspace,children:i}),e.engine&&(0,n.jsx)("span",{className:"px-1.5 py-0.5 rounded bg-surface-3/60 font-mono truncate max-w-[110px]",children:e.engine}),e.branch&&(0,n.jsxs)("span",{className:"inline-flex items-center gap-0.5 min-w-0",children:[(0,n.jsx)(t3.Zr,{size:9,className:"shrink-0"}),(0,n.jsx)("span",{className:"truncate",children:e.branch})]})]}),e.sessionId&&!e.auto&&(0,n.jsx)("div",{className:"mt-1 text-[9px] font-mono text-text-muted/70 truncate",children:e.sessionId}),e.question&&(0,n.jsx)("div",{className:"mt-1 text-[10px] leading-relaxed text-amber-400/90 line-clamp-3",children:e.question}),e.summary&&(0,n.jsx)("div",{className:"mt-1 text-[10px] leading-relaxed text-text-muted line-clamp-3",children:e.summary}),!e.auto&&(0,n.jsxs)("div",{className:"absolute top-1 right-1 flex items-center gap-0.5 opacity-100 sm:opacity-0 sm:group-hover:opacity-100 sm:focus-within:opacity-100 transition-opacity",children:[t&&(0,n.jsx)("button",{type:"button",onClick:()=>{(0,t7.e)(),a(e.id,t)},"aria-label":"Move left",className:"p-0.5 rounded text-text-muted hover:text-text hover:bg-surface-3",children:(0,n.jsx)(t3.JG,{size:12})}),s&&(0,n.jsx)("button",{type:"button",onClick:()=>{(0,t7.e)(),a(e.id,s)},"aria-label":"Move right",className:"p-0.5 rounded text-text-muted hover:text-text hover:bg-surface-3",children:(0,n.jsx)(t3.c_,{size:12})}),(0,n.jsx)("button",{type:"button",onClick:()=>{(0,t7.e)(),l(e.id)},"aria-label":"Delete task",className:"p-0.5 rounded text-text-muted hover:text-red-400 hover:bg-surface-3",children:(0,n.jsx)(t3.X,{size:12})})]})]})}let rZ=(0,r.memo)(function({workspacePath:e=""}){let t=rV(e=>e.board.tasks),s=rX(e=>e.settings.boardScope),a=rX(e=>e.setSettings),l="all"===s,i=(0,r.useMemo)(()=>l?t:((e={},t="")=>{let s={};for(let[n,r]of Object.entries(e))r?.workspace&&r.workspace!==t||(s[n]=r);return s})(t,e),[t,e,l]),o=(0,r.useMemo)(()=>((e={})=>{let t=Object.fromEntries(rB.map(e=>[e,[]]));for(let s of Object.values(e))(t[s.status]||t.todo).push(s);return t})(i),[i]),c=Object.keys(i).length;return(0,n.jsxs)("div",{className:"h-full flex flex-col min-h-0",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2 px-2 pt-2 pb-1 flex-shrink-0",children:[(0,n.jsxs)("span",{className:"text-[10px] font-mono uppercase tracking-wider text-text-muted",children:[c," cards"]}),(0,n.jsx)("button",{type:"button",onClick:()=>{(0,t7.e)(),a({boardScope:l?"workspace":"all"})},className:`ml-auto text-[10px] px-2 py-0.5 rounded-full border transition-colors ${l?"border-brand-500/50 text-brand-400 bg-brand-500/10":"border-border-subtle text-text-muted hover:text-text"}`,title:l?"Showing cards from every workspace":"Showing cards from this workspace only",children:l?"All workspaces":"This workspace"})]}),!l&&Object.keys(t).length>c&&(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),a({boardScope:"all"})},className:"mx-2 mb-1 text-left text-[10px] text-text-muted/80 hover:text-text-muted flex-shrink-0",children:["+",Object.keys(t).length-c," cards in other workspaces — tap to show all"]}),c?(0,n.jsx)("div",{className:"flex-1 min-h-0 overflow-x-auto overflow-y-auto custom-scrollbar p-2 pt-1",children:(0,n.jsx)("div",{className:"min-w-[560px] h-full grid gap-2",style:{gridTemplateColumns:`repeat(${rB.length}, minmax(0, 1fr))`},children:rB.map(e=>{let t=rG[e]||{label:e,cls:"text-text-muted",dot:"bg-text-muted/60"},s=o[e]||[],r=rB.indexOf(e),a=rB[Math.max(0,r-1)],i=rB[Math.min(rB.length-1,r+1)];return(0,n.jsxs)("section",{className:"min-w-0 flex flex-col gap-1.5 bg-surface-2/30 rounded-brand-lg p-1.5","aria-label":`${t.label} column`,children:[(0,n.jsxs)("h4",{className:`flex items-center gap-1.5 px-1 pt-0.5 text-[10px] font-semibold uppercase tracking-wider ${t.cls}`,children:[(0,n.jsx)("span",{className:`w-1.5 h-1.5 rounded-full flex-shrink-0 ${t.dot}`}),(0,n.jsx)("span",{className:"truncate",children:t.label}),(0,n.jsx)("span",{className:"ml-auto px-1.5 py-px rounded-full bg-surface-3/60 text-[9px] font-mono text-text-muted",children:s.length})]}),(0,n.jsx)("div",{className:"flex-1 flex flex-col gap-1.5",children:s.map(t=>(0,n.jsx)(rY,{task:t,showWorkspace:l,prev:"todo"===e?null:a,next:"done"===e?null:i},t.id))})]},e)})})}):(0,n.jsxs)("div",{className:"flex-1 flex flex-col items-center justify-center gap-2 text-text-muted p-6",children:[(0,n.jsx)(t3.y8,{size:32,className:"opacity-50"}),(0,n.jsx)("span",{className:"text-sm",children:"Nothing on the board."}),(0,n.jsx)("span",{className:"text-xs text-center leading-relaxed",children:"Open sessions land here automatically; ask Jarvis — “create 2 tasks: API login and UI login” — to add work."})]})]})}),rQ=(0,r.memo)(function({icon:e,iconClass:t="bg-brand-500/15 text-brand-500",title:s,subtitle:a,maxWidth:l="max-w-lg",onClose:i,children:o,footer:c=null}){let d=(0,r.useRef)(null);return(0,r.useEffect)(()=>{d.current?.contains(document.activeElement)||d.current?.focus()},[]),(0,r.useEffect)(()=>{let e=e=>{"Escape"===e.key&&(e.stopPropagation(),i?.())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[i]),(0,n.jsx)("div",{className:"fixed inset-x-0 top-0 h-[var(--app-height,100dvh)] bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4 select-none",onClick:e=>{e.target===e.currentTarget&&i?.()},children:(0,n.jsxs)("div",{ref:d,tabIndex:-1,className:`card-elev w-full ${l} overflow-hidden flex flex-col max-h-[80%] animate-in fade-in zoom-in-95 duration-150 outline-none`,role:"dialog","aria-modal":"true",children:[(0,n.jsxs)("div",{className:"px-4 py-3 border-b border-border-subtle flex items-center justify-between shrink-0",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2 min-w-0",children:[(0,n.jsx)("div",{className:`w-6 h-6 rounded-full flex items-center justify-center shrink-0 ${t}`,children:e}),(0,n.jsxs)("div",{className:"min-w-0",children:[(0,n.jsx)("h2",{className:"text-sm font-semibold text-text truncate",children:s}),a&&(0,n.jsx)("p",{className:"text-[11px] text-text-muted truncate",children:a})]})]}),(0,n.jsx)("button",{type:"button",onClick:i,className:"p-1 rounded-brand text-text-muted hover:text-text hover:bg-surface-2 transition-colors shrink-0",children:(0,n.jsx)(t3.X,{size:16})})]}),o,c]})})}),r0="w-full px-3 py-2 rounded-brand bg-surface-2/40 border border-border-subtle text-sm text-text placeholder:text-text-muted/60 outline-none focus:border-brand-500 transition-colors",r1="text-[11px] text-text-muted px-1";function r2({title:e,summary:t,ok:s,open:r,onToggle:a,children:l}){return(0,n.jsxs)("div",{className:`rounded-brand border overflow-hidden transition-colors ${r?"border-brand-500/40":"border-border-subtle"} bg-surface-2/20`,children:[(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),a()},className:"w-full px-3 py-2.5 flex items-center gap-2 text-left",children:[(0,n.jsx)("span",{className:`w-1.5 h-1.5 rounded-full flex-shrink-0 ${s?"bg-emerald-400":"bg-text-muted/40"}`}),(0,n.jsx)("span",{className:"text-sm text-text flex-1 min-w-0 truncate",children:e}),(0,n.jsx)("span",{className:"text-[11px] text-text-muted truncate max-w-[45%]",children:t}),(0,n.jsx)(t3.yQ,{size:14,className:`text-text-muted flex-shrink-0 transition-transform ${r?"rotate-180":""}`})]}),r&&(0,n.jsx)("div",{className:"px-2.5 pb-2.5 pt-2 border-t border-border-subtle/60 flex flex-col gap-1.5",children:l})]})}function r5({label:e,hint:t,value:s,onChange:r}){return(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),r(!s)},className:"w-full px-3 py-2 rounded-brand text-left flex items-center gap-2.5 text-sm text-text hover:bg-surface-2 transition-colors",children:[(0,n.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,n.jsx)("span",{className:"block truncate",children:e}),(0,n.jsx)("span",{className:"block text-xs text-text-muted truncate",children:t})]}),(0,n.jsx)("span",{className:`shrink-0 relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${s?"bg-brand-500":"bg-surface-2"}`,children:(0,n.jsx)("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${s?"translate-x-4":"translate-x-0.5"}`})})]})}let r3=(0,r.memo)(function({busRef:e}){let t=rX(e=>e.settings),s=rX(e=>e.setSettings),[a,l]=(0,r.useState)(""),i=rK.find(e=>e.id===t.llmProvider)||rK[0],o=n=>{s(n);let r={...t,...n};e?.current?.emit?.("jarvis:agentConfig",{provider:r.llmProvider,baseUrl:r.llmBaseUrl,apiKey:r.llmKey,model:r.agentModel,wake:r.wakeOnDone})};return(0,n.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,n.jsxs)(r2,{title:"Chat LLM",summary:`${i.label} \xb7 ${t.agentModel||""}`,ok:!!t.llmKey,open:"llm"===a,onToggle:()=>l("llm"===a?"":"llm"),children:[(0,n.jsx)("span",{className:r1,children:"Endpoint"}),(0,n.jsx)("input",{type:"text",value:t.llmBaseUrl||"",onChange:e=>o({llmBaseUrl:e.target.value}),placeholder:i.baseUrlHint,autoComplete:"off",spellCheck:!1,className:r0}),(0,n.jsx)("span",{className:r1,children:"API key"}),(0,n.jsx)("input",{type:"password",value:t.llmKey||"",onChange:e=>o({llmKey:e.target.value}),placeholder:"sk-…",autoComplete:"off",spellCheck:!1,className:r0}),(0,n.jsx)("span",{className:r1,children:"Model"}),(0,n.jsx)("input",{type:"text",value:t.agentModel||"",onChange:e=>o({agentModel:e.target.value}),placeholder:i.models[0],autoComplete:"off",spellCheck:!1,className:r0}),(0,n.jsx)("span",{className:r1,children:"Format — must match the endpoint above"}),(0,n.jsx)("select",{value:t.llmProvider,onChange:e=>{var s;(0,t7.e)(),(s=e.target.value)!==t.llmProvider&&o({llmProvider:s})},className:"w-full px-3 py-2 rounded-brand bg-surface-2/40 border border-border-subtle text-sm text-text outline-none focus:border-brand-500",children:rK.map(e=>(0,n.jsx)("option",{value:e.id,children:e.label},e.id))})]}),(0,n.jsxs)(r2,{title:"Live voice",summary:t.liveKey?`${t.liveModel||"gemini-3.8-live"} \xb7 ${t.liveVoice||"Puck"}`:"no key",ok:!!t.liveKey,open:"live"===a,onToggle:()=>l("live"===a?"":"live"),children:[(0,n.jsx)("input",{type:"password",value:t.liveKey||"",onChange:e=>s({liveKey:e.target.value}),placeholder:"Google AI API key",autoComplete:"off",spellCheck:!1,className:r0}),(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("input",{type:"text",value:t.liveModel||"",onChange:e=>s({liveModel:e.target.value}),placeholder:"gemini-3.8-live",autoComplete:"off",spellCheck:!1,className:`${r0} flex-1 min-w-0`}),(0,n.jsx)("select",{value:t.liveVoice||"Puck",onChange:e=>s({liveVoice:e.target.value}),className:"w-24 shrink-0 px-2 py-2 rounded-brand bg-surface-2/40 border border-border-subtle text-sm text-text outline-none focus:border-brand-500",children:rU.map(e=>(0,n.jsx)("option",{value:e,children:e},e))})]}),(0,n.jsx)("p",{className:"text-[11px] leading-relaxed text-text-muted px-1",children:"Talk to delegate work — billed per minute of audio."})]}),(0,n.jsx)(r5,{label:"Wake on worker done",hint:"Jarvis checks the fleet and updates the board",value:t.wakeOnDone,onChange:e=>o({wakeOnDone:e})})]})}),r4=(0,r.memo)(function({busRef:e,onClose:t}){return(0,n.jsx)(rQ,{icon:(0,n.jsx)(t3.wB,{size:14}),iconClass:"bg-surface-3 text-text-muted",title:"Jarvis Settings",subtitle:"Coordinator harness and behavior",maxWidth:"max-w-sm",onClose:t,children:(0,n.jsx)("div",{className:"p-3",children:(0,n.jsx)(r3,{busRef:e})})})});function r6({busRef:e,fileBus:t=null,workspacePath:a="",onClose:l}){let i=rX(e=>e.settings),o=rV(e=>e.applyBoard),c=rV(e=>e.setSink),[d,u]=(0,r.useState)(!1),[m,x]=(0,r.useState)(!0),[p,h]=(0,r.useState)(null);(0,r.useEffect)(()=>{h(e?.current??null)},[e]);let f=function({busRef:e,apiKey:t,voice:n,model:a}){let[l,i]=(0,r.useState)("idle"),[o,c]=(0,r.useState)(""),[d,u]=(0,r.useState)([]),[m,x]=(0,r.useState)(0),p=(0,r.useCallback)((e,t)=>{t&&u(s=>[...s.slice(-40),{who:e,text:String(t).slice(0,400)}])},[]),h=(0,r.useRef)({}),f=(0,r.useCallback)(()=>{let e=h.current;h.current={},e?.levelProbe&&clearTimeout(e.levelProbe);try{e.session?.close?.()}catch{}for(let t of e.playing||[])try{t.stop()}catch{}e.processor?.disconnect?.(),e.mute?.disconnect?.(),e.stream?.getTracks?.().forEach(e=>e.stop());try{e.inCtx?.close()}catch{}try{e.outCtx?.close()}catch{}i("idle")},[]);(0,r.useEffect)(()=>f,[f]);let b=(0,r.useCallback)(async()=>{if(!t){c("Add a Google AI key in Jarvis settings first"),i("error");return}f(),c(""),u([]),x(0),i("connecting");let r=(t,s)=>new Promise(n=>{let r=!1,a=e=>{r||(r=!0,n(e))},l=setTimeout(()=>a({ok:!1,error:"agent timeout — restart the agent?"}),5e3);try{e.current?.emit?.(t,s,e=>{clearTimeout(l),a(e)})}catch(e){clearTimeout(l),a({ok:!1,error:e?.message||"bus unavailable"})}});try{let[{GoogleGenAI:e,Modality:o},d]=await Promise.all([Promise.all([s.e(1226),s.e(2847)]).then(s.bind(s,10913)),r("jarvis:tools",{})]),u=function(e=[]){return e.filter(e=>e?.name&&e?.description).map(({name:e,description:t,inputSchema:s})=>({name:e,description:t,...s?{parameters:function e(t){if(Array.isArray(t))return t.map(e);if(t&&"object"==typeof t){let s={};for(let[n,r]of Object.entries(t))s[n]="type"===n&&"string"==typeof r?r.toUpperCase():e(r);return s}return t}(s)}:{}}))}(d?.tools||[]);u.length||p("tool",`no coordinator tools (${d?.error||"empty manifest"}) — voice only; restart the agent to get tools`);let m=await navigator.mediaDevices.getUserMedia({audio:!0}),b=new AudioContext({sampleRate:16e3});await b.resume?.().catch?.(()=>{});let g=b.createMediaStreamSource(m),v=b.createScriptProcessor(1024,1,1),y=b.createGain();y.gain.value=0,g.connect(v),v.connect(y),y.connect(b.destination);let w=h.current;w.stream=m,w.inCtx=b,w.processor=v,w.mute=y,w.playing=[],w.maxLevel=0,w.levelProbe=setTimeout(()=>{h.current===w&&!w.speechSeen&&(0===w.maxLevel?p("tool","no mic signal — check microphone permission"):w.maxLevel<.03&&p("tool",`mic very quiet (peak ${w.maxLevel.toFixed(3)} < threshold 0.03) — speak up or move closer`))},3e3),w.levelProbe.unref?.();let k=new e({apiKey:t}),j=await k.live.connect({model:a||"gemini-3.8-live",callbacks:{onmessage:e=>(function(e){let t=h.current,s=e?.usageMetadata?.totalTokenCount;for(let t of(s>0&&x(e=>Math.max(e,s)),e?.serverContent?.modelTurn?.parts||[])){let s=t?.inlineData?.data;s&&(e.serverContent.interrupted||function(e){let t=h.current;t.outCtx||(t.outCtx=new AudioContext({sampleRate:24e3}));let s=t.outCtx,n=atob(e),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);let a=new Int16Array(r.buffer),l=new Float32Array(a.length);for(let e=0;e<a.length;e++)l[e]=a[e]/32768;let i=s.createBuffer(1,l.length,24e3);i.copyToChannel(l,0);let o=s.createBufferSource();o.buffer=i;let c=Math.max(s.currentTime+.02,t.nextAt||0);t.nextAt=c+i.duration,o.onended=()=>{t.playing=(t.playing||[]).filter(e=>e!==o)},o.connect(s.destination),o.start(c),t.playing.push(o)}(s))}if(e.serverContent?.interrupted){for(let e of t.playing||[])try{e.stop()}catch{}t.playing=[]}let n=e?.serverContent?.inputTranscription?.text,r=e?.serverContent?.outputTranscription?.text;n&&p("user",n),r&&p("jarvis",r);let a=e?.toolCall?.functionCalls;a?.length&&h.current.session&&Promise.all(a.map(e=>({fc:e,p:l(e)})).map(({fc:e,p:t})=>t.then(t=>({id:e.id,name:e.name,response:{result:t?.ok?t.result||"ok":`error: ${t?.error||"no answer"}`}})))).then(e=>{try{h.current.session?.sendToolResponse({functionResponses:e})}catch{}})})(e),onerror:e=>{c(e?.message||"live connection error"),i("error")},onclose:()=>i(e=>"idle"===e?e:"idle")},config:{responseModalities:[o.AUDIO],systemInstruction:"You are Jarvis, the conductor coordinating AI agents (claude, codex, opencode) on the user's machine. The user talks to you to delegate work and ask about status. Rules: call list_fleet before delegating to see which session is free; delegate with dispatch_prompt to an existing session, or create_session to open a new one (pass the workspace taken from list_fleet's workspacePath); record every job on the board with manage_kanban; when an agent asks or requests permission, use resolve_gate per the user's intent; to see what a worker printed, read_terminal. Reply BRIEFLY in the user's language, natural spoken style — never read out raw JSON.",speechConfig:{voiceConfig:{prebuiltVoiceConfig:{voiceName:n||"Puck"}}},tools:[{functionDeclarations:u}],contextWindowCompression:{triggerTokens:12e3,slidingWindow:{targetTokens:6e3}},inputAudioTranscription:{},outputAudioTranscription:{}}});if(w.session=j,!h.current.session)return f();let N=function({sendChunk:e,sendStreamEnd:t,now:s=()=>Date.now()}){let n=[],r=!1,a=0,l=!0;return{onChunk(i,o){let c=s(),d=o>=.03;if(d&&(a=c),d&&!r)for(let t of(r=!0,l=!1,n))e(t);if(n.push(i),n.length>5&&n.shift(),r){if(c-a>=1e3){r=!1;return}if(!l&&c-a>=500){l=!0;try{t()}catch{}}e(i)}}}}({sendChunk:e=>{try{j.sendRealtimeInput({media:new Blob([e],{type:"audio/pcm;rate=16000"})})}catch{}},sendStreamEnd:()=>j.sendRealtimeInput({audioStreamEnd:!0})});v.onaudioprocess=e=>{if(h.current.session!==j)return;let t=e.inputBuffer.getChannelData(0),s=0,n=new Int16Array(t.length);for(let e=0;e<t.length;e++){let r=Math.max(-1,Math.min(1,t[e]));s+=Math.abs(r),n[e]=r<0?32768*r:32767*r}let r=s/t.length;r>(w.maxLevel||0)&&(w.maxLevel=r),r>=.03&&(w.speechSeen=!0),N.onChunk(n,r)},i("live")}catch(e){f(),c(e?.message||String(e)),i("error")}async function l(e){p("tool",`${e.name}(${JSON.stringify(e.args||{})})`);let t=await r("jarvis:tool",{name:e.name,args:e.args||{}});return p("tool",`${e.name} → ${t?.ok?String(t.result).slice(0,200):t?.error}`),t}},[t,n,a,f,p,e]);return{status:l,error:o,entries:d,tokens:m,start:b,stop:f}}({busRef:e,apiKey:i.liveKey,voice:i.liveVoice,model:i.liveModel});return(0,r.useEffect)(()=>{let t=e?.current;if(!t?.emit||!t?.on)return;let s=()=>t.emit("jarvis:getState",{},e=>{e?.ok&&o(e.board)});s();let n=setInterval(s,5e3),r=e=>o(e);return t.on("jarvis:kanban",r),c(e=>t.emit("jarvis:kanban",{action:e})),()=>{clearInterval(n),t.off?.("jarvis:kanban",r),c(null)}},[e,o,c]),(0,r.useEffect)(()=>{p?.emit?.("jarvis:agentConfig",{provider:i.llmProvider,baseUrl:i.llmBaseUrl,apiKey:i.llmKey,model:i.agentModel,wake:i.wakeOnDone})},[p,i.llmProvider,i.llmBaseUrl,i.llmKey,i.agentModel,i.wakeOnDone]),(0,r.useEffect)(()=>{let e=e=>{"Escape"!==e.key||d||(e.preventDefault(),l?.())};return window.addEventListener("keydown",e,!0),()=>window.removeEventListener("keydown",e,!0)},[l,d]),(0,n.jsxs)("div",{className:"fixed inset-0 z-50 bg-bg/95 backdrop-blur-sm flex flex-col animate-in fade-in duration-150",children:[(0,n.jsxs)("header",{className:"h-12 px-3 flex items-center gap-2 border-b border-border-subtle flex-shrink-0 bg-bg/80 backdrop-blur-sm",children:[(0,n.jsx)(t3.cC,{size:18,className:"text-brand-500 shrink-0"}),(0,n.jsx)("h2",{className:"text-sm font-semibold text-text flex-1 min-w-0 truncate",children:"Jarvis Coordinator"}),i.liveKey&&(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),"idle"===f.status||"error"===f.status?f.start():f.stop()},className:`relative p-1.5 rounded-brand transition-colors ${"live"===f.status?"text-red-500":"text-text-muted"} hover:text-text hover:bg-surface-2`,"aria-label":"Live voice",title:"live"===f.status?"End live voice":"Live voice — talk to delegate work (Gemini 3.8 Live)",children:[(0,n.jsx)(t3.GO,{size:16}),"live"===f.status&&(0,n.jsx)("span",{className:"absolute top-0.5 right-0.5 w-1.5 h-1.5 rounded-full bg-red-500 animate-pulse"})]}),(0,n.jsx)("button",{type:"button",onClick:()=>{(0,t7.e)(),x(e=>!e)},className:`p-1.5 rounded-brand transition-colors ${m?"text-text":"text-text-muted"} hover:text-text hover:bg-surface-2`,"aria-label":m?"Hide board":"Show board",title:m?"Hide board":"Show board",children:m?(0,n.jsx)(t3.ue,{size:16}):(0,n.jsx)(t3.e6,{size:16})}),(0,n.jsx)("button",{type:"button",onClick:()=>{(0,t7.e)(),u(!0)},className:"p-1.5 text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-colors","aria-label":"Jarvis settings",title:"Jarvis settings",children:(0,n.jsx)(t3.wB,{size:16})}),(0,n.jsx)("button",{type:"button",onClick:()=>{(0,t7.e)(),l?.()},className:"p-1.5 text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-colors","aria-label":"Close",children:(0,n.jsx)(t3.X,{size:18})})]}),(0,n.jsxs)("div",{className:"flex-1 min-h-0 flex flex-col lg:flex-row",children:[m&&(0,n.jsx)("div",{className:"lg:w-[58%] h-[42%] lg:h-full min-h-0 bg-bg border-b lg:border-b-0 lg:border-r border-border-subtle lg:shadow-[6px_0_12px_-6px_rgba(0,0,0,0.15)] lg:relative lg:z-10 animate-in fade-in slide-in-from-left duration-200",children:(0,n.jsx)(rZ,{workspacePath:a})}),(0,n.jsx)("div",{className:"flex-1 min-h-0",children:(0,n.jsx)(rO,{bus:p})})]}),d&&(0,n.jsx)(r4,{busRef:e,onClose:()=>u(!1)}),"idle"!==f.status&&(0,n.jsx)("div",{className:"absolute bottom-3 left-3 right-3 z-20 max-w-md ml-auto pointer-events-none",children:(0,n.jsxs)("div",{className:"pointer-events-auto rounded-brand-lg border border-border-subtle bg-surface/95 backdrop-blur-sm shadow-xl p-2.5 max-h-52 flex flex-col",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2 pb-1.5 mb-1 border-b border-border-subtle/60",children:[(0,n.jsx)("span",{className:`w-2 h-2 rounded-full ${"live"===f.status?"bg-red-500 animate-pulse":"bg-amber-400 animate-pulse"}`}),(0,n.jsxs)("span",{className:"text-xs font-medium text-text flex-1",children:["Live ","connecting"===f.status?"— connecting…":"— listening"]}),f.tokens>0&&(0,n.jsxs)("span",{className:"text-[10px] text-text-muted font-mono",title:"Context tokens — the number the bill compounds on",children:[(f.tokens/1e3).toFixed(1),"k tok"]}),(0,n.jsx)("button",{type:"button",onClick:()=>{(0,t7.e)(),f.stop()},className:"text-xs text-text-muted hover:text-text px-1.5 py-0.5 rounded-brand",children:"End"})]}),f.error&&(0,n.jsx)("p",{className:"text-[11px] text-red-400 px-0.5 pb-1",children:f.error}),(0,n.jsxs)("div",{className:"overflow-y-auto modal-scrollable flex flex-col gap-1 pr-0.5",children:[0===f.entries.length&&(0,n.jsx)("p",{className:"text-[11px] text-text-muted",children:"Speak to delegate — e.g. “which sessions are free?”"}),f.entries.map((e,t)=>(0,n.jsxs)("p",{className:`text-[11px] leading-relaxed ${"user"===e.who?"text-text":"jarvis"===e.who?"text-brand-400":"text-text-muted font-mono"}`,children:["user"===e.who?"> ":"jarvis"===e.who?"Jarvis: ":"",e.text]},t))]})]})})]})}let r8=new Set(["claude","codex","opencode","antigravity","omp","devin","hermes"]),r9=new Set(["idle","done"]),r7=e=>!!e&&r8.has(e.endsWith("-ui")?e.slice(0,-3):e),ae=(0,r.memo)(function({sessions:e=[],allSessions:t=[],activeSessionId:s,connected:a,notifications:l,sessionStatus:i,onSwitchSession:o,onCreateSession:c,onBack:d,onOpenRemote:u,onOpenMobile:m,onOpenFiles:x,onLogout:p,onStopCodespace:h,onUpdate:f,onRestart:b,codespaceInfo:g,tunnelUrl:v,apiKey:y,connectionMode:w,subscribeToPush:k,unsubscribeFromPush:j,agentVersion:N,busRef:S,carrier:C="ws",isActive:T=!0,shells:R=[],modalBusRef:E=null,modalHostKey:_="main",modalShells:$=null,workspaces:M=[],activeWorkspaceId:P=null,onRenameSession:A,onDeleteSession:z,onCreateNamedSession:I,onResumeAgentSession:L=null,onToggleSidebar:D=null,sidebarCollapsed:F=!1,onToggleRightPanel:O,onReorderSession:B,rightPanelOpen:W=!1,updateAvailable:K=null,canSelfUpdate:H=!1,fileBus:U=null,homeDir:q=null,isDesktop:V=!0}){let{t:X}=(0,se.s)(),G=tS(e=>e.agentBySession||{}),J=tS(e=>e.fullModes||{})[P??eZ]??!1,Y=tS(e=>e.toggleFullMode);sc(e=>e.notifications);let Z=sc(e=>e.sessionStatus),Q=i||Z,{formattedStars:et}=(0,rL.w)(),es="mouse"===nk(),en=(e,t)=>es?s9(e,t):e,er=(0,r.useRef)(null),ea=(0,r.useRef)(null),[el,ei]=(0,r.useState)({sessionId:null,x:0,y:0}),[eo,ec]=(0,r.useState)(null),ed=(0,r.useRef)(null),eu=rE(ed,el.x,el.y),em=G[el.sessionId]||Q[el.sessionId]?.tool||e.find(e=>e.id===el.sessionId)?.agent,ex=em?.endsWith("-ui"),ep=r7(em),eh=ep&&r9.has(Q[el.sessionId]?.state||"idle"),[ef,eb]=(0,r.useState)({isOpen:!1,sessionId:null,sessionName:""}),[eg,ev]=(0,r.useState)({sessionId:null,name:"",value:""}),[ey,ew]=(0,r.useState)(!1),ek=rX(e=>e.open),ej=rX(e=>e.toggle),eN=rX(e=>!1),eS=rV(e=>Object.values(e.board.tasks).some(e=>"needs_input"===e.status));(0,r.useEffect)(()=>{if(!T||!eN)return;let e=e=>{(e.metaKey||e.ctrlKey)&&"j"===e.key.toLowerCase()&&(e.preventDefault(),ej())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[T,eN,ej]);let{dragId:eC,registerEl:eT,startDrag:eR,consumeClick:eE}=rI({axis:"x",threshold:6,onCommit:B}),e_=(0,r.useMemo)(()=>new Set(t.map(e=>e.id)),[t]);(0,r.useEffect)(()=>{if(!T)return;let t=t=>{let n,r=document.activeElement;if(!r||"INPUT"!==r.tagName&&"TEXTAREA"!==r.tagName||!t.ctrlKey||t.altKey||t.metaKey||t.shiftKey||e.length<2)return;let a=e.findIndex(e=>e.id===s);if("ArrowRight"===t.key)n=e[(a+1)%e.length];else if("ArrowLeft"===t.key)n=e[(a-1+e.length)%e.length];else{if(!(t.key>="1")||!(t.key<="9"))return;n=e[Math.min(t.key-1,e.length-1)]}t.preventDefault(),n&&n.id!==s&&o?.(n.id),requestAnimationFrame(()=>requestAnimationFrame(()=>r.focus()))};return window.addEventListener("keydown",t),()=>window.removeEventListener("keydown",t)},[T,e,s,o]);let e$=si(e=>e.open),eM=n6(e=>e.isOpen),eP=n6(e=>e.open),eA=n6(e=>e.close),ez=tS(e=>e.hiddenHeaderButtons),eI=tS(e=>e.hiddenPaneSessionIds||[]),eL=tS(e=>e.toggleHidePane),eD=tS(e=>e.unhidePane),eF=tS(e=>e.setFullMode),eO=tS(e=>e.mobileDeviceCount),eB=si(e=>e.setContext),eW=si(e=>e.setCallbacks);(0,r.useEffect)(()=>{if(!T)return;let e=e=>{(e.metaKey||e.ctrlKey)&&e.altKey&&!e.shiftKey&&"t"===e.key.toLowerCase()&&(e.preventDefault(),ew(!0))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[T]),(0,r.useEffect)(()=>{if(!el.sessionId)return;let e=e=>{ed.current&&!ed.current.contains(e.target)&&ei({sessionId:null,x:0,y:0})},t=e=>{"Escape"===e.key&&ei({sessionId:null,x:0,y:0})};return document.addEventListener("mousedown",e),document.addEventListener("touchstart",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("mousedown",e),document.removeEventListener("touchstart",e),document.removeEventListener("keydown",t)}},[el.sessionId]);let eK=(0,r.useRef)(null),eH=()=>{eK.current&&(clearTimeout(eK.current),eK.current=null)},eU=e=>{eb({isOpen:!0,sessionId:e.id,sessionName:e?.name||X("terminal.defaultName")}),ei({sessionId:null,x:0,y:0})},eq=M.find(e=>e.id===P)||null;return(0,r.useEffect)(()=>{if(!ea.current||!er.current)return;let e=requestAnimationFrame(()=>{let e=er.current,t=ea.current;if(!e||!t)return;let s=t.getBoundingClientRect().left-e.getBoundingClientRect().left,n=e.scrollLeft+s-(e.clientWidth-t.offsetWidth)/2,r=e.scrollWidth-e.clientWidth;e.scrollTo({left:Math.max(0,Math.min(n,r)),behavior:"smooth"})});return()=>cancelAnimationFrame(e)},[s,e.length]),(0,r.useEffect)(()=>{T&&(eB({connected:a,remoteAvailable:!!u,codespaceInfo:g,showTheme:!1,busRef:S,tunnelUrl:v,apiKey:y,connectionMode:w,subscribeToPush:k,unsubscribeFromPush:j,agentVersion:N,carrier:C}),eW({onRemote:u,onFiles:x,onCodespace:null,onLogout:p,onStopCodespace:h,onUpdate:f,onRestart:b}))},[T,a,u,x,g,p,h,f,b,v,y,w,N,S,C,k,j,eB,eW]),(0,n.jsxs)("div",{className:`h-9 ${rF} px-2 sm:pl-0 sm:pr-2 flex items-stretch gap-0 flex-shrink-0 bg-bg border-b border-border-subtle`,children:[D&&F&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),D()},className:"p-1.5 text-text hover:bg-surface-2 hover:text-text rounded-brand transition duration-150 ease-out active:scale-[0.94] flex-shrink-0 self-center",title:en(X("common.open"),"toggleSidebar"),children:(0,n.jsx)(t3.e6,{size:16})}),d&&(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),d()},className:"p-1 pl-1.5 pr-3.5 sm:p-1.5 text-text hover:bg-surface-2 hover:text-text rounded-brand transition duration-150 ease-out active:scale-[0.94] flex-shrink-0 self-center",title:X("common.back"),children:[(0,n.jsx)(t3.JG,{size:20,className:"sm:hidden"}),(0,n.jsx)(t3.JG,{size:16,className:"hidden sm:block"})]}),(0,n.jsx)("div",{ref:er,className:"flex-1 overflow-auto overflow-x-auto overflow-y-hidden scrollbar-none h-full",children:(0,n.jsxs)("div",{className:"flex gap-0 min-w-max items-stretch h-full",children:[e.map(t=>{let r=t.id===s,l=eI.includes(t.id),i=Q[t.id]?.state||"idle",c=nH(i),d=t.name||X("terminal.defaultName"),u=s$(G[t.id])||s$(G[t.id]?.replace(/-ui$/,""));return(0,n.jsxs)("div",{role:"button",tabIndex:0,ref:e=>{eT(t.id)(e),r&&(ea.current=e)},onMouseDown:e=>e.preventDefault(),onPointerDown:s=>{"mouse"===s.pointerType&&B&&a&&(eH(),eR(s,t.id,e.map(e=>e.id)))},onClick:()=>{eE()||((0,t7.e)(),l&&eD(t.id),o?.(t.id))},onKeyDown:e=>{("Enter"===e.key||" "===e.key)&&(e.preventDefault(),l&&eD(t.id),o?.(t.id))},onContextMenu:e=>{e.preventDefault(),(0,t7.e)(),ei({sessionId:t.id,x:e.clientX,y:e.clientY})},onTouchStart:e=>{let s;return s=e.touches[0],void(eK.current=setTimeout(()=>{(0,t7.e)(),ei({sessionId:t.id,x:s.clientX,y:s.clientY})},500))},onTouchMove:eH,onTouchEnd:eH,className:`term-tab group relative px-1.5 sm:px-2.5 text-xs font-medium duration-150 ease-out flex items-center gap-1 sm:gap-2 whitespace-nowrap h-full cursor-pointer select-none ${r?"term-tab-active":""} ${l?"opacity-75 hover:opacity-100":""} ${eC===t.id?"z-20 opacity-90 shadow-lg":"transition"}`,children:[(0,n.jsxs)("div",{className:"w-3.5 h-3.5 flex items-center justify-center shrink-0",children:["idle"===i&&u?(0,n.jsx)("img",{src:u,alt:"",className:`w-3.5 h-3.5 object-contain ${s_} ${z?"sm:group-hover:hidden":""}`}):(0,n.jsx)("span",{className:`w-1.5 h-1.5 rounded-full term-dot ${c.cls}${c.pulse?` pulse-${c.pulse}`:""} ${z?"sm:group-hover:hidden":""}`,style:{background:c.dot},title:X(c.label)}),z&&(0,n.jsx)("button",{type:"button",tabIndex:-1,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),(0,t7.e)(),eU(t)},className:"hidden w-full h-full p-0.5 rounded text-text hover:bg-text/15 sm:group-hover:flex items-center justify-center transition-colors",title:en(X("sessions.deleteTitle"),"closeTerminal"),children:(0,n.jsx)(t3.X,{size:11,strokeWidth:2.4})})]}),(0,n.jsx)("span",{className:"truncate max-w-[90px] sm:max-w-[140px]","data-tip":d,children:d}),l&&(0,n.jsx)("button",{type:"button",tabIndex:-1,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),(0,t7.e)(),eD(t.id)},className:"p-0.5 rounded text-amber-400 hover:text-amber-300 hover:bg-amber-400/20 transition-colors flex items-center justify-center shrink-0",title:X("sessions.showPanel")||"Show panel",children:(0,n.jsx)(t3.X_,{size:13})})]},t.id)}),c&&(0,n.jsx)("div",{className:"sticky right-0 z-10 ml-1 pl-1 flex items-center flex-shrink-0 bg-bg",children:(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),ew(!0)},disabled:!a,className:"p-1.5 text-text hover:bg-surface-2 hover:text-brand-500 transition duration-150 ease-out active:scale-[0.94] disabled:opacity-40 disabled:cursor-not-allowed rounded-brand",title:en(X("terminal.newTerminal"),"newTerminal"),children:(0,n.jsx)(t3.FW,{size:17,strokeWidth:2.4})})})]})}),(0,n.jsxs)("div",{className:"flex items-center gap-2 flex-shrink-0 self-center",children:[a&&f&&H&&(n9(N,"3.0.11")||!!K)&&(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),f()},className:"hidden sm:flex px-2 sm:px-2.5 py-1 bg-brand-500 hover:bg-brand-600 text-white text-xs font-medium rounded-brand items-center gap-1.5 flex-shrink-0 transition duration-150 ease-out active:scale-[0.94]",title:X("menu.updateAvailableTitle"),children:[(0,n.jsx)(t3.f5,{size:13}),(0,n.jsx)("span",{children:"Update 9Remote"})]}),!ez.includes("remote")&&u&&!(0,ee.sP)()&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),u()},className:"hidden sm:block p-1.5 text-text hover:bg-surface-2 hover:text-text rounded-brand transition duration-150 ease-out active:scale-[0.94]",title:X("menu.remoteDesktop"),children:(0,n.jsx)(t3.VA,{size:16})}),!ez.includes("mobile")&&m&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),m()},className:`hidden sm:block p-1.5 hover:bg-surface-2 rounded-brand transition duration-150 ease-out active:scale-[0.94] ${eO>0?"text-green-400":"text-text hover:text-text"}`,title:eO>0?X("mobile.deviceRunning",{count:eO}):X("mobile.androidDevice"),children:(0,n.jsx)(t3.wO,{size:16})}),!ez.includes("sites")&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),eP()},disabled:!a,className:"hidden sm:block p-1.5 text-text hover:bg-surface-2 hover:text-text rounded-brand transition duration-150 ease-out active:scale-[0.94] disabled:opacity-40 disabled:cursor-not-allowed",title:X("menu.sites"),children:(0,n.jsx)(t3.qz,{size:16})}),eN&&(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),ej()},disabled:!a,className:`relative p-1.5 hover:bg-surface-2 rounded-brand transition duration-150 ease-out active:scale-[0.94] disabled:opacity-40 disabled:cursor-not-allowed ${eS?"text-amber-400":"text-text hover:text-text"}`,title:"Jarvis coordinator (⌘J / Ctrl+J)",children:[(0,n.jsx)(t3.cC,{size:16}),eS&&(0,n.jsx)("span",{className:"absolute top-0.5 right-0.5 w-1.5 h-1.5 rounded-full bg-amber-400 animate-pulse"})]}),!ez.includes("notifications")&&(0,n.jsx)(nG,{sessionStatus:Q,allSessions:t,onSwitchSession:o}),!ez.includes("notifications")&&(0,n.jsx)(nX,{sessions:e,allSessions:t,sessionStatus:Q,onSwitchSession:o,workspaces:M}),O&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),O()},className:`hidden sm:block p-1.5 rounded-brand transition duration-150 ease-out active:scale-[0.94] hover:bg-surface-2 ${W?"text-brand-500":"text-text hover:text-text"}`,title:en(X("workspaces.tabFiles"),"toggleRightPanel"),children:(0,n.jsx)(t3.jz,{size:16})}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),e$()},className:`p-1.5 text-text hover:bg-surface-2 hover:text-text rounded-brand transition duration-150 ease-out active:scale-[0.94] ${D?"sm:hidden":""}`,title:X("menu.title"),children:(0,n.jsx)(t3.wB,{size:16})})]}),el.sessionId&&(0,n.jsxs)("div",{ref:ed,className:"fixed z-[60] menu-popover p-1 min-w-[140px] animate-in fade-in zoom-in-95 duration-100",style:{left:eu.left,top:eu.top},children:[Q[el.sessionId]?.state==="done"&&(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),sc.getState().clearNotification(el.sessionId),ei({sessionId:null,x:0,y:0})},className:"w-full text-left px-2.5 py-1.5 text-xs text-amber-500 hover:bg-amber-500/10 rounded-[6px] flex items-center gap-2",children:[(0,n.jsx)(t3.aJ,{size:13})," ",X("sessions.markRead")]}),(0,n.jsxs)("button",{onClick:()=>{var t;ev({sessionId:(t=e.find(e=>e.id===el.sessionId)).id,name:t.name||"",value:t.name||""}),ei({sessionId:null,x:0,y:0})},className:"w-full text-left px-2.5 py-1.5 text-xs text-text hover:bg-surface-2/80 rounded-[6px] flex items-center gap-2",children:[(0,n.jsx)(t3.gH,{size:13})," ",X("sessions.editName")]}),V&&(0,n.jsxs)("div",{className:"relative group/split",children:[(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),!J&&el.sessionId&&el.sessionId!==s&&o?.(el.sessionId),Y(P),ei({sessionId:null,x:0,y:0})},className:"w-full text-left px-2.5 py-1.5 text-xs text-text hover:bg-surface-2/80 rounded-[6px] flex items-center justify-between",children:[(0,n.jsxs)("span",{className:"flex items-center gap-2",children:[(0,n.jsx)(t3.Wn,{size:13}),(0,n.jsx)("span",{children:X("sessions.split")||"Split"})]}),(0,n.jsx)(t3.c_,{size:12,className:"text-text-muted"})]}),(0,n.jsxs)("div",{className:`hidden group-hover/split:block absolute top-0 menu-popover p-1 min-w-[130px] shadow-xl z-20 ${eu.left>window.innerWidth-280?"right-full -mr-0.5":"left-full -ml-0.5"}`,children:[(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),!J&&el.sessionId&&el.sessionId!==s&&o?.(el.sessionId),Y(P),ei({sessionId:null,x:0,y:0})},className:"w-full text-left px-2 py-1.5 text-xs text-text hover:bg-surface-2/80 rounded-[6px] flex items-center justify-between",children:[(0,n.jsxs)("span",{className:"flex items-center gap-1.5",children:[J?(0,n.jsx)(t3.xq,{size:12}):(0,n.jsx)(t3.h1,{size:12}),(0,n.jsx)("span",{children:J?X("sessions.restoreSplit")||"Restore Split":X("sessions.maximize")||"Maximize"})]}),(0,n.jsx)("span",{className:"text-[10px] text-text-muted",children:"100%"})]}),(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),J&&eF(P,!1),window.dispatchEvent(new CustomEvent("terminal:splitPreset",{detail:{fraction:2}})),ei({sessionId:null,x:0,y:0})},className:"w-full text-left px-2 py-1.5 text-xs text-text hover:bg-surface-2/80 rounded-[6px] flex items-center justify-between",children:[(0,n.jsx)("span",{children:"1/2"}),(0,n.jsx)("span",{className:"text-[10px] text-text-muted",children:"50%"})]}),(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),J&&eF(P,!1),window.dispatchEvent(new CustomEvent("terminal:splitPreset",{detail:{fraction:3}})),ei({sessionId:null,x:0,y:0})},className:"w-full text-left px-2 py-1.5 text-xs text-text hover:bg-surface-2/80 rounded-[6px] flex items-center justify-between",children:[(0,n.jsx)("span",{children:"1/3"}),(0,n.jsx)("span",{className:"text-[10px] text-text-muted",children:"33%"})]}),(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),J&&eF(P,!1),window.dispatchEvent(new CustomEvent("terminal:splitPreset",{detail:{fraction:4}})),ei({sessionId:null,x:0,y:0})},className:"w-full text-left px-2 py-1.5 text-xs text-text hover:bg-surface-2/80 rounded-[6px] flex items-center justify-between",children:[(0,n.jsx)("span",{children:"1/4"}),(0,n.jsx)("span",{className:"text-[10px] text-text-muted",children:"25%"})]}),(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),J&&eF(P,!1),window.dispatchEvent(new CustomEvent("terminal:splitPreset",{detail:{fraction:"auto"}})),ei({sessionId:null,x:0,y:0})},className:"w-full text-left px-2 py-1.5 text-xs text-text hover:bg-surface-2/80 rounded-[6px] flex items-center justify-between",children:[(0,n.jsx)("span",{children:"Auto Fit"}),(0,n.jsx)("span",{className:"text-[10px] text-text-muted",children:"Auto"})]}),(0,n.jsx)("div",{className:"h-px bg-border-subtle my-1"}),(0,n.jsx)("button",{type:"button",onClick:()=>{(0,t7.e)(),eL(el.sessionId),ei({sessionId:null,x:0,y:0})},className:"w-full text-left px-2 py-1.5 text-xs text-text hover:bg-surface-2/80 rounded-[6px] flex items-center justify-between",children:(0,n.jsxs)("span",{className:"flex items-center gap-1.5",children:[eI.includes(el.sessionId)?(0,n.jsx)(t3.kU,{size:12}):(0,n.jsx)(t3.X_,{size:12}),(0,n.jsx)("span",{children:eI.includes(el.sessionId)?X("sessions.showPanel")||"Show":X("sessions.hidePanel")||"Hide"})]})})]})]}),(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),ec(el.sessionId),ei({sessionId:null,x:0,y:0})},className:"w-full text-left px-2.5 py-1.5 text-xs text-text hover:bg-surface-2/80 rounded-[6px] flex items-center gap-2",children:[(0,n.jsx)(t3._V,{size:13,className:"flex-shrink-0"})," ",X("menu.terminalBackground")]}),(G[el.sessionId]?.endsWith("-ui")||Q[el.sessionId]?.conversationId)&&(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)();let e=el.sessionId;G[e]?.endsWith("-ui")?S?.current?.emit("ai:restart",{sessionId:e}):S?.current?.emit("session-resume",{sessionId:e}),ei({sessionId:null,x:0,y:0})},className:"w-full text-left px-2.5 py-1.5 text-xs text-text hover:bg-surface-2/80 rounded-[6px] flex items-center gap-2",children:[(0,n.jsx)(t3.kt,{size:13})," ",G[el.sessionId]?.endsWith("-ui")?X("sessions.restartAi")||"Restart AI":X("sessions.resumeSession")]}),ep&&(0,n.jsxs)("button",{disabled:!eh,onClick:()=>{(0,t7.e)();let e=el.sessionId;S?.current?.emit("setSessionMode",{sessionId:e,mode:ex?"terminal":"ui"},e=>{e?.success||alert(e?.error||X("sessions.modeSwitchFailed"))}),ei({sessionId:null,x:0,y:0})},className:`w-full text-left px-2.5 py-1.5 text-xs rounded-[6px] flex items-center gap-2 ${eh?"text-text hover:bg-surface-2/80":"text-text-subtle cursor-not-allowed"}`,children:[(0,n.jsx)(t3.sU,{size:13})," ",ex?X("sessions.openAsTerminal"):X("sessions.openAsUi")]}),(0,n.jsxs)("button",{onClick:()=>eU(e.find(e=>e.id===el.sessionId)),className:"w-full text-left px-2.5 py-1.5 text-xs text-red-500 hover:bg-red-500/10 rounded-[6px] flex items-center gap-2",children:[(0,n.jsx)(t3.TB,{size:13})," ",X("sessions.deleteTitle")]})]}),eo&&(0,n.jsx)(rA,{sessionId:eo,title:e.find(e=>e.id===eo)?.name,busRef:S,onClose:()=>ec(null)}),eg.sessionId&&(0,n.jsx)(rR,{title:X("sessions.editName"),placeholder:eg.name,value:eg.value,onChange:e=>ev({...eg,value:e}),onSubmit:()=>{let e=eg.value.trim();eg.sessionId&&e&&A?.(eg.sessionId,e),ev({sessionId:null,name:"",value:""})},onClose:()=>ev({sessionId:null,name:"",value:""})}),ey&&(0,n.jsx)(rT,{onClose:()=>ew(!1),onCreate:(e,t,s,n,r,a)=>{I?I(e,P,t,r||null,s,n,a):c?.()},shells:$||R,busRef:E||S,hostKey:_,suggestName:`${X("terminal.defaultName")} ${e.filter(e=>eQ(e)===(P??null)).length+1}`,workspacePath:eq?.path||null,workspaceName:eq?.name||"",fileBus:U,homeDir:q,onResumeAgentSession:L,onSelectSession:o,liveSessionIds:e_,activeSessionId:s,connected:a}),(0,n.jsx)(t9.A,{isOpen:ef.isOpen,onClose:()=>eb({isOpen:!1,sessionId:null,sessionName:""}),onConfirm:()=>{ef.sessionId&&z?.(ef.sessionId)},title:X("sessions.deleteTitle"),message:X("sessions.deleteMessage",{name:ef.sessionName}),confirmText:X("common.delete")}),(0,n.jsx)(n4,{tunnelUrl:v,apiKey:y,busRef:S,isOpen:eM,onClose:eA}),ek&&(0,n.jsx)(r6,{busRef:S,fileBus:U,workspacePath:eq?.path||"",onClose:()=>rX.getState().setOpen(!1)})]})});s(12401);let at="js|jsx|ts|tsx|css|json|md|txt|html|xml|yaml|yml|sh|py|rb|go|java|c|cpp|h",as={WEB_HTTP:/https?:\/\/[^\s]+/g,WEB_LOCALHOST:/localhost:\d+[^\s]*/g,FILE_ABSOLUTE:RegExp(`\\/[^\\s:]+\\.(${at})\\b`,"g"),FILE_RELATIVE:RegExp(`(?:\\.{1,2}\\/)?[^\\s:/]+(?:\\/[^\\s:/]+)*\\.(${at})\\b`,"g"),FILE_WITH_LINE:RegExp(`[^\\s]+\\.(${at}):\\d+(?::\\d+)?`,"g"),GIT_MODIFIED:/modified:\s+[^\s]+/g};function an({text:e,position:t,onOpenUrl:s,onCopy:r,onAddToNote:a,onClose:l}){let{t:i}=(0,se.s)(),o=function(e){let t=e.trim(),s=t.match(as.WEB_HTTP);if(s)return{isUrl:!0,isFile:!1,match:s[0]};let n=t.match(as.WEB_LOCALHOST);if(n)return{isUrl:!0,isFile:!1,match:`http://${n[0]}`};let r=t.match(as.FILE_WITH_LINE);if(r)return{isUrl:!1,isFile:!0,match:r[0]};let a=t.match(as.FILE_ABSOLUTE);if(a)return{isUrl:!1,isFile:!0,match:a[0]};let l=t.match(as.FILE_RELATIVE);return l?{isUrl:!1,isFile:!0,match:l[0]}:{isUrl:!1,isFile:!1,match:t}}(e),c=t=>{if("openUrl"===t&&o.isUrl)s(o.match);else if("copy"===t)r(e);else if("addNote"===t&&a)return void a(e);l()};return(0,n.jsx)("div",{className:"fixed inset-0 bg-black/30 flex items-center justify-center z-[60]",onMouseDown:e=>{e.preventDefault(),l()},children:(0,n.jsxs)("div",{className:"card-elev overflow-hidden min-w-[200px]",onMouseDown:e=>{e.stopPropagation()},onClick:e=>e.stopPropagation(),children:[(0,n.jsx)("div",{className:"px-4 py-3 border-b border-border bg-surface",children:(0,n.jsxs)("div",{className:"text-text text-sm font-medium",children:["Selected: ",e.length>30?e.substring(0,30)+"...":e]})}),(0,n.jsxs)("div",{className:"p-2",children:[o.isUrl&&(0,n.jsxs)("button",{onClick:()=>c("openUrl"),className:"w-full px-4 py-3 flex items-center gap-3 hover:bg-surface-2 text-text text-left rounded-brand transition-colors mb-1",children:[(0,n.jsx)(t3.Gr,{size:20}),(0,n.jsx)("span",{children:"Open URL"})]}),(0,n.jsxs)("button",{onClick:()=>c("copy"),className:"w-full px-4 py-3 flex items-center gap-3 hover:bg-surface-2 text-text text-left rounded-brand transition-colors mb-1",children:[(0,n.jsx)(t3.QR,{size:20}),(0,n.jsx)("span",{children:"Copy"})]}),a&&(0,n.jsxs)("button",{onClick:()=>c("addNote"),className:"w-full px-4 py-3 flex items-center gap-3 hover:bg-surface-2 text-text text-left rounded-brand transition-colors mb-1",children:[(0,n.jsx)(t3.y8,{size:20}),(0,n.jsx)("span",{children:i("terminalPane.addToNote")})]}),(0,n.jsxs)("button",{onClick:l,className:"w-full px-4 py-3 flex items-center gap-3 hover:bg-surface-2 text-red-400 text-left rounded-brand transition-colors border-t border-border mt-2 pt-3",children:[(0,n.jsx)(t3.X,{size:20}),(0,n.jsx)("span",{children:"Close"})]})]})]})})}let ar=new Map;function aa(e,t){e.fileBus?.gitChangedCount(t).then(t=>{t?.success&&(e.count=t.count||0,e.subs.forEach(t=>t(e.count)))})}function al(e,t,{enabled:s=!0}={}){let[n,a]=(0,r.useState)(0),l=t||t2.getState();return(0,r.useEffect)(()=>{let t;if(!e||!l||!s)return;let n=((t=ar.get(e))||(t={count:0,stop:null,refs:0,subs:new Set,fileBus:l},ar.set(e,t),aa(t,e),t.stop=rl(()=>aa(t,e),1e4)),t.refs++,t);return a(n.count),n.subs.add(a),()=>{let t;n.subs.delete(a),(t=ar.get(e))&&(t.refs--,t.refs<=0&&(t.stop?.(),ar.delete(e)))}},[e,l,s]),n}var ai=s(42970),ao=s(36890),ac=s(5262),ad=s(36834),au=s(10358),am=s(69070),ax=s(79063);let ap={...ax.aC,default:ax.aC.dark};function ah({joinClaimed:e,joining:t,gapBusy:s}){return!!(e?.current||t?.current||s)}function af(e){return e instanceof ArrayBuffer||ArrayBuffer.isView(e)?e instanceof Uint8Array?e:new Uint8Array(e):"string"==typeof e?e:String(e)}let ab=e=>"string"==typeof e?function(e){if(!e)return 0;let t=0,s=e.length;for(let n=0;n<s;n++){let s=e.charCodeAt(n);s<=127?t+=1:s<=2047?t+=2:s>=55296&&s<=56319?(t+=4,n++):t+=3}return t}(e):e.byteLength;function ag(e,t,s,n,r){if(!e||e._core?._isDisposed)return;let a=af(t);r?r.write(a):e.write(a),s&&(s.current.push(a),n.current+=ab(a))}let av="stale",ay=()=>{if("u"<typeof navigator)return!1;let e=/Macintosh|Mac OS X/i.test(navigator.userAgent)||"MacIntel"===navigator.platform,t=/AppleWebKit/i.test(navigator.userAgent)&&!/Chrome|Chromium|Edg/i.test(navigator.userAgent);return e&&t},aw=/^- \[([ xX])\] ?/;function ak(e){return e.map(e=>`- [${e.done?"x":" "}] ${e.text}`).join("\n")}let aj=new Map,aN=e=>{try{navigator.clipboard?.writeText(e).catch(()=>{})}catch{}};function aS({bus:e,sessionId:t,appendOnOpen:s,onClose:a,variant:l="modal",pinned:i=!1,onPin:o,rightSlot:c=null}){let{t:d}=(0,se.s)(),u=tS(e=>e.noteChips),m=tS(e=>e.addNoteChip),x=tS(e=>e.removeNoteChip),[p,h]=(0,r.useState)(null),[f,b]=(0,r.useState)(""),[g,v]=(0,r.useState)(!1),[y,w]=(0,r.useState)(()=>new Set),[k,j]=(0,r.useState)(null),[N,S]=(0,r.useState)(""),[C,T]=(0,r.useState)(null),R=(0,r.useRef)(new Map),E=(0,r.useRef)(null),[_,$]=(0,r.useState)(!1),[M,P]=(0,r.useState)(""),A=(0,r.useRef)([]),z=(0,r.useRef)(null),I=(0,r.useRef)(0),L=(0,r.useRef)(null),D=(0,r.useRef)(s),[F]=(0,r.useState)(()=>Symbol("note")),O=(0,r.useRef)(o);(0,r.useEffect)(()=>{O.current=o});let B=e=>e.map(e=>({...e,id:++I.current})),W=()=>{let e=D.current;return(D.current=null,e)?e.split("\n").map(e=>e.trim()).filter(Boolean).map(e=>({done:!1,text:e})):[]},K=(0,r.useCallback)(s=>{e?.emit("saveNote",{sessionId:t,text:s},()=>{})},[e,t]),H=(0,r.useCallback)(e=>{let s=e(A.current||[]);A.current=s,aj.set(t,s),h(s),window.dispatchEvent(new CustomEvent(eg,{detail:{sessionId:t,items:s,from:F}})),L.current&&clearTimeout(L.current),L.current=setTimeout(()=>{L.current=null,K(ak(A.current))},500)},[K,t,F]);(0,r.useEffect)(()=>{if(!e||!t)return;let s=!1,n=aj.get(t),r=(e,s)=>{for(let t of e)t.id>I.current&&(I.current=t.id);A.current=e,aj.set(t,e),h(e),s&&K(ak(e))};if(n){let e=W();r(e.length?[...n,...B(e)]:n,e.length>0);return}return e.emit("getNote",{sessionId:t},e=>{if(s)return;let t=((e?.success?e.text:"")||"").split("\n").map(e=>e.trim()).filter(Boolean).map(e=>{let t=e.match(aw);return t?{done:" "!==t[1],text:e.slice(t[0].length)}:{done:!1,text:e}}),n=W();n.length&&!t.length&&O.current?.(!0),r(B([...t,...n]),n.length>0)}),()=>{s=!0}},[e,t,K]),(0,r.useEffect)(()=>{let e=e=>{let s=e.detail;if(s&&s.sessionId===t&&s.from!==F&&null==E.current){for(let e of(L.current&&(clearTimeout(L.current),L.current=null),s.items))e.id>I.current&&(I.current=e.id);A.current=s.items,aj.set(t,s.items),h(s.items)}};return window.addEventListener(eg,e),()=>window.removeEventListener(eg,e)},[t,F]),(0,r.useEffect)(()=>()=>{L.current&&(clearTimeout(L.current),L.current=null,K(ak(A.current)))},[K]),(0,r.useEffect)(()=>{let e=z.current;if(!e)return;let t=window.innerWidth>=760?200:101;e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,t)}px`},[f]);let U=e=>{e.preventDefault();let t=f.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);t.length&&((0,t7.e)(),b(""),A.current.length||o?.(!0),H(e=>[...e,...B(t.map(e=>({done:!1,text:e})))]),z.current?.focus())},q=e=>{(0,t7.e)(),H(t=>t.map(t=>t.id===e?{...t,done:!t.done}:t))},V=()=>{let e=N.trim();e&&null!=k&&H(t=>t.map(t=>t.id===k?{...t,text:e}:t)),j(null)},X=()=>{let e=M.trim();e&&!Z.includes(e)&&m(e),P(""),$(!1)},G=(p?.length||0)>0,J=p?.filter(e=>e.done).length||0,Y=(p?.length||0)-J,Z=[...eb,...Array.isArray(u)?u:[]];if("pinned"===l){if(!G)return null;let e=p.find(e=>!e.done)||null;return(0,n.jsxs)("div",{style:{height:26},className:"flex items-center gap-2 px-2 -mt-1.5 -mx-1.5 mb-1.5 flex-shrink-0 bg-surface border-b border-border-subtle text-[11px] text-text-muted select-none relative z-10",onMouseDown:e=>e.stopPropagation(),onTouchStart:e=>e.stopPropagation(),children:[e?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{onClick:()=>q(e.id),className:"w-3.5 h-3.5 flex-shrink-0 flex items-center justify-center rounded-[3px] border-2 border-border hover:border-brand-400 transition-colors",title:d("common.done")}),(0,n.jsx)("span",{className:"flex-1 min-w-0 truncate text-text",title:e.text,children:e.text})]}):(0,n.jsx)("span",{className:"flex-1 min-w-0 truncate",children:d("note.allDone")}),(0,n.jsxs)("span",{className:"flex-shrink-0 text-text-subtle",children:[J,"/",p.length]}),c]})}return(0,n.jsx)("div",{className:"fixed inset-0 bg-black/40 flex items-center justify-center z-[60] p-4",onMouseDown:e=>{e.preventDefault(),a()},children:(0,n.jsxs)("div",{className:"card-elev w-full max-w-lg h-[55dvh] min-h-[300px] flex flex-col overflow-hidden",onMouseDown:e=>{e.stopPropagation()},onClick:e=>e.stopPropagation(),children:[(0,n.jsxs)("div",{className:"flex items-center justify-between pl-4 pr-2 py-2 border-b border-border bg-surface flex-shrink-0",children:[(0,n.jsxs)("div",{className:"flex items-baseline gap-2 min-w-0",children:[(0,n.jsx)("span",{className:"text-text text-sm font-medium truncate",children:d("note.title")}),G&&(0,n.jsxs)("span",{className:"text-xs text-text-subtle flex-shrink-0",children:[J,"/",p.length]})]}),(0,n.jsxs)("div",{className:"flex items-center gap-1",children:[o&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),o(!i),i||a()},className:`p-2 hover:bg-surface-2 rounded-brand transition-colors ${i?"text-brand-500":"text-text"}`,title:i?d("note.unpin"):d("note.pin"),children:i?(0,n.jsx)(t3.Ze,{size:16}):(0,n.jsx)(t3.yU,{size:16})}),(0,n.jsx)("button",{onClick:()=>{let e=(p||[]).filter(e=>!e.done);e.length&&((0,t7.e)(),w(new Set(e.map(e=>e.id))),aN(e.map(e=>e.text).join("\n")),v(!0),setTimeout(()=>v(!1),1200))},disabled:!Y,className:"p-2 hover:bg-surface-2 text-text rounded-brand transition-colors disabled:opacity-40",title:d("note.copyTodo"),children:g?(0,n.jsx)(t3.aJ,{size:16,className:"text-green-400"}):(0,n.jsx)(t3.QR,{size:16})}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),H(e=>e.filter(e=>!e.done))},disabled:!J,className:"p-2 hover:bg-surface-2 text-red-400 rounded-brand transition-colors disabled:opacity-40",title:d("note.clearDone"),children:(0,n.jsx)(t3.TB,{size:16})}),(0,n.jsx)("button",{onClick:a,className:"p-2 hover:bg-surface-2 text-text rounded-brand transition-colors",title:"Close",children:(0,n.jsx)(t3.X,{size:16})})]})]}),(0,n.jsx)("div",{className:"flex-1 min-h-0 overflow-y-auto",children:null===p?null:G?(0,n.jsx)("ul",{className:"py-1",children:p.map(e=>(0,n.jsxs)("li",{ref:t=>{t?R.current.set(e.id,t):R.current.delete(e.id)},className:`flex items-center gap-1.5 px-3 py-1.5 ${C===e.id?"relative z-10 bg-surface-2 shadow-elev select-none":null!=C?"transition-transform duration-150 ease-out":""}`,children:[(0,n.jsx)("span",{onPointerDown:t=>((e,t)=>{if("mouse"===e.pointerType&&0!==e.button)return;e.preventDefault(),(0,t7.e)(),e.currentTarget.setPointerCapture?.(e.pointerId),E.current=t.id,T(t.id);let s=(A.current||[]).map(e=>e.id),n=s.indexOf(t.id),r=R.current.get(t.id),a=r?.getBoundingClientRect().height||0,l=e.clientY,i=n,o=null,c=e=>{if("mouse"===e.pointerType&&0===e.buttons)return void d();let c=e.clientY-l,u=a?Math.round(c/a):0;i=Math.max(0,Math.min(s.length-1,n+u)),o||(o=requestAnimationFrame(()=>{o=null,r&&(r.style.transform=`translateY(${c}px)`),s.forEach((e,s)=>{if(e===t.id)return;let r=R.current.get(e);if(!r)return;let l=0;n<i&&s>n&&s<=i?l=-a:n>i&&s>=i&&s<n&&(l=a),r.style.transform=l?`translateY(${l}px)`:""})}))},d=()=>{for(let e of(window.removeEventListener("pointermove",c),window.removeEventListener("pointerup",d),window.removeEventListener("pointercancel",d),window.removeEventListener("blur",d),o&&(cancelAnimationFrame(o),o=null),R.current.values()))e&&(e.style.transform="");E.current=null,T(null),i!==n&&H(e=>{let s=e.findIndex(e=>e.id===t.id);if(s<0)return e;let n=[...e];return n.splice(Math.min(i,n.length-1),0,n.splice(s,1)[0]),n})};window.addEventListener("pointermove",c),window.addEventListener("pointerup",d),window.addEventListener("pointercancel",d),window.addEventListener("blur",d)})(t,e),className:`p-1 -ml-1.5 flex-shrink-0 touch-none cursor-grab active:cursor-grabbing ${C===e.id?"text-brand-500":"text-text-subtle/60 hover:text-text-subtle"}`,title:d("note.drag"),children:(0,n.jsx)(t3.f2,{size:13})}),(0,n.jsx)("button",{onClick:()=>q(e.id),className:`w-5 h-5 flex-shrink-0 flex items-center justify-center rounded border-2 transition-colors ${e.done?"bg-brand-500 border-brand-500":"border-border hover:border-brand-400"}`,children:e.done&&(0,n.jsx)(t3.aJ,{size:13,className:"text-white"})}),k===e.id?(0,n.jsx)("input",{value:N,onChange:e=>S(e.target.value),onKeyDown:e=>{"Enter"===e.key&&V(),"Escape"===e.key&&j(null)},onBlur:V,autoFocus:!0,className:"flex-1 min-w-0 bg-surface-2 border border-brand-500 rounded-brand px-2 py-1 text-sm text-text outline-none"}):(0,n.jsx)("span",{onClick:()=>{(0,t7.e)(),j(e.id),S(e.text)},className:`flex-1 min-w-0 text-sm break-words cursor-text ${e.done?"text-text-subtle line-through":"text-text"}`,title:d("note.edit"),children:e.text}),(0,n.jsx)("button",{onClick:()=>{let t;return(0,t7.e)(),void((t=new Set(y)).has(e.id)?t.delete(e.id):t.add(e.id),w(t),aN((p||[]).filter(e=>t.has(e.id)).map(e=>e.text).join("\n")))},className:`p-1.5 rounded-brand transition-colors flex-shrink-0 ${y.has(e.id)?"text-brand-500 bg-brand-500/10":"text-text-subtle hover:text-text hover:bg-surface-2"}`,title:d("note.copyItem"),children:(0,n.jsx)(t3.QR,{size:13})}),(0,n.jsx)("button",{onClick:()=>{var t;return t=e.id,void((0,t7.e)(),H(e=>e.filter(e=>e.id!==t)))},className:"p-1.5 text-text-subtle hover:text-red-400 rounded-brand transition-colors flex-shrink-0",title:d("common.delete"),children:(0,n.jsx)(t3.X,{size:13})})]},e.id))}):(0,n.jsx)("p",{className:"text-text-subtle text-sm px-4 py-6 text-center",children:d("note.placeholder")})}),null!==p&&(0,n.jsxs)("div",{className:"flex items-center gap-1.5 px-3 py-2 border-t border-border flex-shrink-0 overflow-x-auto scrollbar-thin",children:[Z.map(s=>(0,n.jsxs)("div",{className:"flex items-center flex-shrink-0",children:[(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),e?.emit("input",{sessionId:t,data:`${s}
|
|
8
|
+
${ak(p||[])}`}),setTimeout(()=>e?.emit("input",{sessionId:t,data:"\r"}),100),a()},disabled:!G,className:"px-2 py-1 text-[11px] text-text-secondary bg-surface-2 hover:bg-surface-3 rounded-brand transition-colors disabled:opacity-40",title:d("note.sendHint"),children:s}),!eb.includes(s)&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),x(s)},className:"p-1 text-text-subtle hover:text-red-400 transition-colors",title:d("note.removeChip"),children:(0,n.jsx)(t3.X,{size:10})})]},s)),_?(0,n.jsx)("form",{onSubmit:e=>{e.preventDefault(),X()},className:"flex items-center flex-shrink-0",children:(0,n.jsx)("input",{value:M,onChange:e=>P(e.target.value),onKeyDown:e=>{"Escape"===e.key&&($(!1),P(""))},onBlur:X,placeholder:d("note.chipPlaceholder"),autoFocus:!0,className:"w-28 bg-surface-2 border border-border-subtle focus-within:border-brand-500 rounded-brand px-2 py-1 text-[11px] text-text outline-none placeholder:text-text-subtle"})}):(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),$(!0)},className:"p-1 text-text-subtle hover:text-text hover:bg-surface-2 rounded-brand transition-colors flex-shrink-0",title:d("note.addChip"),children:(0,n.jsx)(t3.FW,{size:14})})]}),null!==p&&(0,n.jsxs)("form",{onSubmit:U,className:"flex items-end gap-2 p-3 border-t border-border flex-shrink-0",children:[(0,n.jsx)("textarea",{ref:z,value:f,onChange:e=>b(e.target.value),onKeyDown:e=>{"Enter"===e.key&&!e.shiftKey&&window.innerWidth>=760&&U(e)},rows:1,placeholder:d("note.multilinePlaceholder"),className:"flex-1 min-w-0 resize-none bg-surface-2 border border-border-subtle focus-within:border-brand-500 rounded-brand px-3 py-2 text-sm text-text outline-none placeholder:text-text-subtle transition-colors"}),(0,n.jsx)("button",{type:"submit",disabled:!f.trim(),onMouseDown:e=>e.preventDefault(),className:"p-2 bg-brand-500 hover:bg-brand-600 text-white rounded-brand transition-colors disabled:opacity-40 flex-shrink-0",title:d("note.addLines"),children:(0,n.jsx)(t3.FW,{size:16})})]})]})})}function aC({onOpenRemote:e,onOpenMobile:t}){let{t:s}=(0,se.s)(),r=tS(e=>e.hiddenHeaderButtons),a=tS(e=>e.mobileDeviceCount),l=n6(e=>e.open),i="p-1.5 -my-1 text-text hover:bg-surface-2 hover:text-text rounded-brand transition-all duration-150 ease-out active:scale-[0.94] flex-shrink-0";return(0,n.jsxs)("div",{className:"flex items-center gap-2 flex-shrink-0",onMouseDown:e=>e.stopPropagation(),onTouchStart:e=>e.stopPropagation(),children:[!r.includes("remote")&&e&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),e()},className:i,title:s("menu.remoteDesktop"),children:(0,n.jsx)(t3.VA,{size:16})}),!r.includes("mobile")&&t&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),t()},className:`${i} ${a>0?"!text-green-400":""}`,title:a>0?s("mobile.deviceRunning",{count:a}):s("mobile.androidDevice"),children:(0,n.jsx)(t3.wO,{size:16})}),!r.includes("sites")&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),l()},className:i,title:s("menu.sites"),children:(0,n.jsx)(t3.qz,{size:16})})]})}var aT=s(44976);function aR({isFocused:e,onActivate:t}){let s=s=>(function(e,{isFocused:t,onActivate:s}){let n=e.target;if(n?.closest?.("button,a,label,select,[role='dialog'],[data-pane-control]")){e.preventDefault(),e.stopPropagation();return}"touchstart"!==e.type||n?.closest?.("input, textarea")||e.preventDefault(),t||s?.()})(s,{isFocused:e,onActivate:t});return{onMouseDown:s,onTouchStart:s}}let aE="p-2 sm:p-1.5 bg-surface-2/60 hover:bg-surface-3 text-text rounded-full shadow-md sm:shadow-sm transition-all duration-150 ease-out active:scale-[0.94]",a_="sm:w-3.5 sm:h-3.5",a$=(0,r.memo)(function({bus:e,workspacePath:t,connected:s,sessionId:a,sessionName:l,sessionState:i,isVisible:o,isFocused:c,mountDelay:d=0,onActivate:u,onRegisterApi:m,onPasteFallback:x,showFocusBorder:p=!1,fileBus:h,bgIndex:f=0,onOpenArtifact:b,onOpenRemote:g,onOpenMobile:y}){let{t:w}=(0,se.s)(),{theme:k}=(0,aT.D)(),j=sc(e=>a?e.sessionStatus[a]?.state:"idle"),N=i||j||"idle",S=(0,r.useRef)(null),C=(0,r.useRef)(null),T=(0,r.useRef)({width:0,height:null}),[R,E]=(0,r.useState)(null),[_,$]=(0,r.useState)(!1),[M,P]=(0,r.useState)(!1),[A,z]=(0,r.useState)(!1),[I,L]=(0,r.useState)(null),D=tS(e=>e.setRightPanelTab),F=tS(e=>e.openRightPanel),O=tS(e=>e.setRightPanelRoot),B=Q(e=>e.bus),W=e||B,K=tS(e=>e.cwdBySession[a]),H=tS(e=>e.terminalTheme),U=tS(e=>e.terminalBackgroundOpacity),q=tS(e=>e.customBackgrounds),V=tS(e=>e.terminalBackgrounds),X=e$(tS(e=>e.backgroundBySession[a]),V,q,f),G=tS(e=>e.showFolderButton),J=tS(e=>e.showNoteButton),Y=tS(e=>e.artifactsBySession[a]),Z=tS(e=>!!e.pinnedNotes?.[a]),ee=tS(e=>e.setNotePinned),et=Z&&J,es=(0,r.useRef)(a);(0,r.useEffect)(()=>{es.current=a},[a]);let[en,er]=(0,r.useState)(!1),[ea,el]=(0,r.useState)(null),ei=(0,r.useCallback)(()=>{sc.getState().clearNotification(a)},[a]),eo=eR(X,q),{termRef:ec,cwdRef:ed,cwd:eu,termReady:em,joining:ex,doResize:ep,reload:eh,focus:ef,stopMomentum:eb,historyFetching:eg}=function({bus:e,sessionId:t,theme:s,terminalTheme:n,isVisible:a,isFocused:l,containerRef:i,mountDelay:o=0,bgKey:c="none",onInput:d,onSelectionMade:u}){let m=Q(e=>e.bus),x=e||m,p=(0,r.useRef)(null),h=(0,r.useRef)(null),f=(0,r.useRef)(null),b=(0,r.useRef)(null),g=(0,r.useRef)(null),y=(0,r.useRef)(null),w=(0,r.useRef)(null),k=(0,r.useRef)(null),j=(0,r.useRef)(null),N=(0,r.useRef)(null),S=(0,r.useRef)(null),C=(0,r.useRef)(!1),T=(0,r.useRef)(!1),R=(0,r.useRef)(null),E=(0,r.useRef)(null),[_,$]=(0,r.useState)(null),M=tS(e=>e.webglEnabled),P=tS(e=>e.fontSize),A=(0,r.useRef)(u);(0,r.useEffect)(()=>{A.current=u},[u]);let z=(0,r.useRef)(!1),I=(0,r.useRef)(null),[L,D]=(0,r.useState)(!1),F=(0,r.useRef)(null),O=(0,r.useRef)([]),B=(0,r.useRef)(0),W=(0,r.useRef)(0),K=(0,r.useRef)(!1),H=(0,r.useRef)(0),U=(0,r.useRef)(0),q=(0,r.useRef)(null),V=(0,r.useRef)(null),X=(0,r.useRef)(!1),G=(0,r.useRef)(!1),J=(0,r.useRef)(null),[Y,Z]=(0,r.useState)(!1),ee=(0,r.useRef)([]),et=(0,r.useRef)(0),es=(0,r.useRef)(null),en=(0,r.useRef)(null),er=(0,r.useRef)(null),ea=(0,r.useRef)(a);(0,r.useEffect)(()=>{ea.current=a},[a]);let[el,ei]=(0,r.useState)(!1),eo=(0,r.useRef)(null),ec=(0,r.useRef)(!1),ed=(0,r.useRef)(null),eu=(0,r.useRef)(0),em=(0,r.useRef)(0),ex=(0,r.useCallback)(()=>{let e=p.current;if(!e||!x)return;let{cols:s,rows:n}=e;s<30||n<2||(F.current={cols:s,rows:n},x.emit("resize",{sessionId:t,cols:s,rows:n}))},[x,t]),ep=(0,r.useCallback)((e={})=>{let s=!0===e||e?.force===!0,n=!!e?.join;s&&(C.current=!0),n&&(T.current=!0),k.current&&clearTimeout(k.current),k.current=setTimeout(()=>{k.current=null;let e=p.current,s=h.current,n=i.current;if(!e||e._isDisposed||!s||!x||!n?.offsetWidth||!n?.offsetHeight)return;s.fit();let{cols:r,rows:a}=e;if(r<30||a<2)return;let l=F.current,o=C.current,c=T.current;if(C.current=!1,T.current=!1,!o&&l&&l.cols===r&&l.rows===a&&!c){G.current=!1;return}F.current={cols:r,rows:a},x.emit("resize",{sessionId:t,cols:r,rows:a}),c&&!S.current&&(G.current=!1),c&&S.current&&(G.current=!0,e.reset(),S.current(r,a))},100)},[x,t,i]);(0,r.useEffect)(()=>{j.current=ep},[ep]),(0,r.useEffect)(()=>{let e,r,a,l;if(!i.current||!x||!t||p.current)return;eu.current=0,V.current=null;let d=new ai.B({...ey,fontSize:ew(P),allowTransparency:!0,theme:eC((0,ax.In)(s,n)||ap.dark,"dark"===s?c:"none")}),u=new ao.Y;d.loadAddon(u),d.loadAddon(new ad.I),d.unicode.activeVersion="11",p.current=d,h.current=u,d.open(i.current);let m=function(e,t){if(!ay())return()=>{};let s=e?.textarea,n=e?._core,r=n?._compositionHelper;if(!s||!n)return()=>{};let a=r?._handleAnyTextareaChanges,l=r?._finalizeComposition,i=n._inputEvent,o=!1,c="",d="",u=/^[sfrxj12345]$/i;r&&(r._handleAnyTextareaChanges=()=>{},r._finalizeComposition=function(){this._compositionView?.classList.remove("active"),this._isComposing=!1,this._isSendingComposition=!1,d&&(this._coreService.triggerDataEvent(d,!0),d=""),this._textarea&&(this._textarea.value="")});let m=e=>{e.target===s&&(c=e.key||"",o=(229===e.keyCode||229===e.which||"Process"===e.key)&&!e.isComposing)},x=e=>{e.target===s&&(229===e.keyCode||229===e.which)&&setTimeout(()=>{o=!1},50)},p=()=>{o=!1,d=""},h=e=>{e.data&&(d=e.data)},f=e=>{o=!1,e.data&&(d=e.data)};return n._inputEvent=function(e){let t=(e.data||"").replace(/[- ]/g,""),s=o||t&&/[^\x00-\x7F]/.test(t)||"insertReplacementText"===e.inputType;return(o=!1,s&&t&&!r?._isComposing&&!this.optionsService.rawOptions.screenReaderMode)?(this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._keyDownSeen=!1,t.length>1&&!u.test(c)&&this.coreService.triggerDataEvent("",!0),this.coreService.triggerDataEvent(t,!0),this.cancel(e),this.textarea&&(this.textarea.value=""),!0):i.call(this,e)},s.addEventListener("keydown",m,{capture:!0}),s.addEventListener("keyup",x,{capture:!0}),s.addEventListener("compositionstart",p,{capture:!0}),s.addEventListener("compositionupdate",h,{capture:!0}),s.addEventListener("compositionend",f,{capture:!0}),t&&(t.addEventListener("compositionupdate",h,{capture:!0}),t.addEventListener("compositionend",f,{capture:!0})),()=>{n._inputEvent=i,r&&(a&&(r._handleAnyTextareaChanges=a),l&&(r._finalizeComposition=l)),s.removeEventListener("keydown",m,{capture:!0}),s.removeEventListener("keyup",x,{capture:!0}),s.removeEventListener("compositionstart",p,{capture:!0}),s.removeEventListener("compositionupdate",h,{capture:!0}),s.removeEventListener("compositionend",f,{capture:!0}),t&&(t.removeEventListener("compositionupdate",h,{capture:!0}),t.removeEventListener("compositionend",f,{capture:!0}))}}(d,i.current),C=function(e){if(!ay()||!e)return()=>{};let t=!1,s=e=>{0===e.button&&(t=!0)},n=e=>{0===e.button&&(t=!1)},r=e=>{if(!t||0!==e.buttons)return;t=!1,e.stopImmediatePropagation();let s=new MouseEvent("mouseup",{bubbles:!0,cancelable:!0,button:0,buttons:0,clientX:e.clientX,clientY:e.clientY,screenX:e.screenX,screenY:e.screenY,ctrlKey:e.ctrlKey,metaKey:e.metaKey,altKey:e.altKey,shiftKey:e.shiftKey});document.dispatchEvent(s)},a=()=>{if(t){t=!1;let e=new MouseEvent("mouseup",{bubbles:!0,cancelable:!0,button:0,buttons:0});document.dispatchEvent(e)}};return e.addEventListener("mousedown",s),e.addEventListener("mouseup",n),e.addEventListener("pointercancel",a),e.addEventListener("mouseleave",a),document.addEventListener("mousemove",r,!0),window.addEventListener("blur",a),()=>{e.removeEventListener("mousedown",s),e.removeEventListener("mouseup",n),e.removeEventListener("pointercancel",a),e.removeEventListener("mouseleave",a),document.removeEventListener("mousemove",r,!0),window.removeEventListener("blur",a)}}(i.current);e=[],r=0,a=null,f.current={write:t=>{let s=t instanceof Uint8Array||"string"==typeof t?t.length:String(t).length;s<=512&&0===r&&null===a?d.write(t instanceof Uint8Array||"string"==typeof t?t:String(t)):(e.push(t instanceof Uint8Array||"string"==typeof t?t:String(t)),r+=s,null===a&&(a=requestAnimationFrame(l)))},flush:l=()=>{if(a=null,e.length){if(1===e.length)d.write(e[0]);else if(e.every(e=>e instanceof Uint8Array)){let t=new Uint8Array(r),s=0;for(let n of e)t.set(n,s),s+=n.length;d.write(t)}else{let t="";for(let s of e)t+="string"==typeof s?s:new TextDecoder().decode(s);d.write(t)}e=[],r=0}},dispose:()=>{null!==a&&cancelAnimationFrame(a),a=null,e=[],r=0}},I.current=new au.n,d.loadAddon(I.current);let T=i.current,R=e=>{d.options.smoothScrollDuration=125*!!(0!==e.deltaMode||Math.abs(e.deltaY)>=50)};T.addEventListener("wheel",R,{passive:!0});let _=null,M=!1;g.current=()=>{if(!_&&!M)try{b.current=_=new ac.o,_.onContextLoss(()=>{_?.dispose(),_=null,b.current=null}),d.loadAddon(_),d.loadAddon(new am.W),u.fit()}catch(e){M=!0,_=null,console.warn("WebGL unavailable, using DOM renderer")}},y.current=()=>{b.current&&(b.current.dispose(),b.current=null,_=null,u.fit(),ex(),d.refresh(0,d.rows-1))};let A=0,L=()=>{A++;let e=i.current?.offsetWidth||0,t=i.current?.offsetHeight||0;A>50?D(!0):d.element&&e>=100&&t>=100?(u.fit(),ex(),D(!0)):setTimeout(L,50)};setTimeout(L,50);let F=new ResizeObserver(()=>j.current?.());F.observe(i.current);let Y=function({fetchOlder:e,isAtTop:t,max:s,delayMs:n}){let r=0,a=null,l=()=>{a&&(clearTimeout(a),a=null)};return{gesture(){l(),e(!1)&&(r=0)},settled(){if(!t()){r=0;return}r>=s||(r+=1,l(),a=setTimeout(()=>{a=null,e(!0)},n))},cancel:l}}({fetchOlder:(e=!1)=>{let s=d.buffer.active;if(0,K.current||"alternate"===s.type||W.current<=0||W.current-B.current<256)return!1;let n=Date.now();if(!e&&n-H.current<600)return!1;let r=s.viewportY<=5;return(!!e||!!ec.current)&&(r?!!Q.getState().connected&&(K.current=!0,H.current=n,U.current=B.current,ei(!0),x.emit("requestHistory",{sessionId:t,have:U.current},e=>{if(!e||!e.success){K.current=!1,ei(!1);return}e.prefixLen||(K.current=!1,ei(!1)),W.current=e.total||W.current}),!0):(e||(ec.current=!1),!1))},isAtTop:()=>(d.buffer.active.viewportY??0)<=5,max:3,delayMs:300});ed.current=()=>Y.settled();let el=()=>Y.gesture();es.current=d.onScroll(()=>{(d.buffer.active.viewportY??0)>5&&(ec.current=!1)}),d.textarea?.addEventListener("keyup",el),eo.current=el;let ep=null,eh=null,ef=!1,eb=0,eg=function({emit:e,writeChunk:t,flush:s,onGapChunk:n,onFallback:r,log:a,getFromSeq:l}){let i=null,o=e=>{clearTimeout(e.timer),e.timer=setTimeout(()=>d(e,"stalled"),3e3)},c=e=>{if(!e.settled&&i===e){for(let s of(e.settled=!0,clearTimeout(e.timer),e.timer=null,e.pending))t(s.data),null!=s.seq&&n(s.seq);s?.(),i=null,a(`gap recovered (${e.received}/${e.expected} chunks, ${e.pending.length} pending flushed)`)}},d=(e,t)=>{e.settled||i!==e||(e.settled=!0,clearTimeout(e.timer),e.timer=null,i=null,a(`gap ${t} (${e.fromSeq}..${e.toSeq}) → reset+rejoin`),r())};return{start:function(t,s=[]){if(i)return;let n=l();if(t<n)return;a(`seq gap (last=${n-1} → ${t+1}) → requestGap ${n}..${t}`);let r={pending:[...s],fromSeq:n,toSeq:t,settled:!1,timer:null,expected:null,received:0,seen:new Set};i=r,o(r),e({fromSeq:n,toSeq:t},e=>{if(!r.settled&&i===r){if(!e?.hit)return d(r,"miss");r.expected=e.count??0,r.received>=r.expected&&c(r)}})},queueLive:function(e,t){return!!i&&(i.pending.push({data:e,seq:t}),!0)},handleGapChunk:function(e,s){let r=i;return!!r&&null!=s&&!(s<r.fromSeq)&&!(s>r.toSeq)&&(!!r.seen.has(s)||(o(r),t(e),n(s),r.seen.add(s),r.received=r.seen.size,null!=r.expected&&r.received>=r.expected&&c(r),!0))},cancel:function(){i&&(clearTimeout(i.timer),i=null)},isBusy:()=>null!==i}}({emit:(e,s)=>x.emit("requestGap",{sessionId:t,...e},s),writeChunk:e=>{let t=f.current;ag(d,e,O,B,t),t?.flush()},flush:()=>f.current?.flush(),onGapChunk:e=>{V.current=e},onFallback:()=>J.current?.("gap fallback"),log:e=>(0,v.Lq)("reconnect",e),getFromSeq:()=>(V.current??0)+1}),ev=e=>{if(p.current){if(!Q.getState().connected){en.current=e;return}en.current=null,(0,v.Lq)("reconnect",`reset+rejoin (${e})`),G.current=!0,N.current?.(!0)}};J.current=ev;let ek=e=>{if(!ea.current||ef){en.current=e;return}ep&&clearTimeout(ep),ep=setTimeout(()=>(e=>{if(ep=null,!ea.current||!Q.getState().connected){en.current=e;return}if(ah({joinClaimed:G,joining:X,gapBusy:eg.isBusy()}))return;if(null==V.current)return ev(`${e}: no seq baseline`);let s=++eb;ef=!0,eh=setTimeout(()=>{eh=null,ef=!1,eb++,(0,v.Lq)("reconnect",`${e}: peekSeq timed out → retry`),en.current=en.current||e,ej()},4e3),x.emit("peekSeq",{sessionId:t},t=>{if(s!==eb)return;clearTimeout(eh),eh=null,ef=!1;let n=t?.seq;if(null==n)return ev(`${e}: agent has no seq`);let r=V.current??0;return n<r?ev(`${e}: seq rewound ${r} → ${n}`):n===r?((0,v.Lq)("reconnect",`${e}: nothing missed (seq ${r})`),ej()):ah({joinClaimed:G,joining:X,gapBusy:eg.isBusy()})?ej():void((0,v.Lq)("reconnect",`${e}: peekSeq ${r} → ${n} → gapFetch`),eg.start(n))})})(e),150)};function ej(){let e=en.current;e&&(en.current=null,ek(e))}er.current=ek;let{handleOutput:eN}=function({sessionId:e,term:t,writeBatcherRef:s,gapFetch:n,refs:r,setHistoryFetching:a}){let l=e=>{var s;let n,l=af(e),i=t.buffer.active.viewportY,o=t.buffer.active.baseY;l=function(e,{haveAtEmit:t,historyBytes:s}){let n=Math.max(0,t>0?s-t:0);if(n<=0)return e;let r=Math.max(0,ab(e)-n);return"string"!=typeof e&&(r=function(e,t){if(t<=0)return 0;if(t>=e.byteLength)return e.byteLength;for(let s=t;s>0&&t-s<512;s--)if(27===e[s])return s;return t}(e,r)),"string"==typeof e?e.slice(0,r):e.subarray(0,r)}(l,{haveAtEmit:r.historyHaveAtEmitRef.current,historyBytes:r.historyBytesRef.current}),r.historyHaveAtEmitRef.current=0;let c=ab(l);if(0===c){r.historyFetchingRef.current=!1,a(!1),r.onPrefixSettledRef?.current?.();return}r.historyMirrorRef.current.unshift(l),r.historyBytesRef.current+=c,t.reset(),t.write((s=r.historyMirrorRef.current,n=new TextDecoder,s.map(e=>"string"==typeof e?e:n.decode(e,{stream:!0})).join("")),()=>{requestAnimationFrame(()=>{let e=function({oldViewportY:e,baseYBefore:t,baseYAfter:s}){return Math.max(0,Math.min(e+Math.max(0,s-t),s))-s}({oldViewportY:i,baseYBefore:o,baseYAfter:t.buffer.active.baseY});e<0&&t.scrollLines(e),r.historyFetchingRef.current=!1,a(!1),r.onPrefixSettledRef?.current?.()})})};return{handleOutput:a=>{if(a.sessionId!==e)return;a.data instanceof ArrayBuffer&&(a={...a,data:new Uint8Array(a.data)}),r.lastOutputAtRef.current=Date.now();let i=a.data?.length||0;r.outputTotalRef.current+=i,(a.replay||a.isHistoryPrefix)&&(0,v.Lq)("recv",`len=${i} replay=${!!a.replay} prefix=${!!a.isHistoryPrefix} total=${r.outputTotalRef.current}`);let o=a.data;if("b64"===a.enc&&"string"==typeof o)if("function"==typeof Uint8Array.fromBase64)o=Uint8Array.fromBase64(o);else{let e=atob(o),t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);o=t}if(r.awaitingTuiOutputRef.current=!1,a.isHistoryPrefix){if(a.parts>1){let e=r.prefixFragsRef.current;if(0!==a.part&&e&&e.parts===a.parts||(e={parts:a.parts,chunks:[]},r.prefixFragsRef.current=e),e.chunks[a.part]=o,e.chunks.filter(Boolean).length<a.parts)return;r.prefixFragsRef.current=null,(0,v.Lq)("recv",`prefix reassembled from ${a.parts} parts (${e.chunks.reduce((e,t)=>e+t.length,0)}B)`);let t=new Uint8Array(e.chunks.reduce((e,t)=>e+t.length,0)),s=0;for(let n of e.chunks)t.set(n,s),s+=n.length;l(t);return}l(o);return}if(a.replay){let e=af(o);s.current?.write(e),s.current?.flush(),null!=a.seq&&(r.lastSeqRef.current=a.seq);return}if(a.gap)return void n.handleGapChunk(o,a.seq);if(r.joiningRef.current)return void r.joinQueueRef.current.push({data:o,seq:a.seq});if(!n.queueLive(o,a.seq)){if(null!=a.seq){var c,d;let e=(c=r.lastSeqRef.current,d=a.seq,null==c?"init":d===c+1?"none":d>c+1?"gap":av);if("gap"===e)return void n.start(a.seq-1,[{data:o,seq:a.seq}]);if(e===av)return;r.lastSeqRef.current=a.seq}r.userAtTopRef.current=!1,ag(t,o,r.historyMirrorRef,r.historyBytesRef,s.current)}},replayWithPrefix:l}}({sessionId:t,term:d,writeBatcherRef:f,gapFetch:eg,refs:{joiningRef:X,joinQueueRef:ee,lastSeqRef:V,lastOutputAtRef:eu,outputTotalRef:em,awaitingTuiOutputRef:z,userAtTopRef:ec,historyFetchingRef:K,historyHaveAtEmitRef:U,historyMirrorRef:O,historyBytesRef:B,prefixFragsRef:q,onPrefixSettledRef:ed},setHistoryFetching:ei});x.on("output",eN);let eS=e=>{e&&e.sessionId===t&&e.cwd&&(E.current=e.cwd,$(e.cwd),tS.getState().setCwd(t,e.cwd))};x.on("cwdChange",eS);let eT=function({bus:e,sessionId:t,term:s,fitAddon:n,writeBatcherRef:r,doResizeRef:a,fireJoinRef:l,refs:i,setCwd:o}){let c=null,d=(u=!1)=>{i.historyMirrorRef.current=[],i.historyBytesRef.current=0,i.historyTotalRef.current=0,i.historyFetchingRef.current=!1,i.userAtTopRef.current=!1,requestAnimationFrame(()=>a.current?.({join:!0})),l.current=(a,l)=>{let u=tS.getState().agentCaps?.joinSessionSize?{sessionId:t,cols:a,rows:l}:t;i.joiningRef.current=!0,i.setJoining(!0),i.joinQueueRef.current=[];let m=++i.joinGenRef.current;(0,v.Lq)("join",`emit gen=${m} sid=${String(t).slice(-8)} cols=${a} rows=${l}`),c&&clearTimeout(c),c=setTimeout(()=>{if(c=null,m!==i.joinGenRef.current)return;(0,v.Lq)("join",`ack timeout gen=${m} (8000ms) → clear spinner`),i.joiningRef.current=!1,i.joinClaimedRef.current=!1,i.setJoining(!1);let e=i.joinQueueRef.current;i.joinQueueRef.current=[];let t=r.current;for(let n of e)ag(s,n&&"object"==typeof n&&"data"in n?n.data:n,i.historyMirrorRef,i.historyBytesRef,t);t?.flush()},8e3),e.emit("joinSession",u,a=>{if(c&&(clearTimeout(c),c=null),m!==i.joinGenRef.current)return void(0,v.Lq)("join",`stale ack gen=${m} (current=${i.joinGenRef.current})`);let l=a||{};if((0,v.Lq)("join",`ack gen=${m} sid=${String(t).slice(-8)} success=${!!l.success} total=${l.total} replaySize=${l.replaySize}`),l.success){setTimeout(()=>{if(m!==i.joinGenRef.current||s._core?._isDisposed)return;let e=i.joinQueueRef.current;i.joinQueueRef.current=[];let t=r.current,n=null;for(let r of e){let e=r&&"object"==typeof r&&"data"in r?r.data:r;r?.seq!=null&&(n=r.seq),ag(s,e,i.historyMirrorRef,i.historyBytesRef,t)}let a=l.seq??null;(null!=a||null!=n)&&(i.lastSeqRef.current=Math.max(a??-1,n??-1)),t?.flush(),i.joiningRef.current=!1,i.joinClaimedRef.current=!1,i.setJoining(!1)},0),i.historyTotalRef.current=l.total||0,l.cwd&&(i.cwdRef.current=l.cwd,o(l.cwd),tS.getState().setCwd(t,l.cwd));let a=tS.getState().consumeStartup(t);a&&((0,v.Lq)("join",`startup cmd queued (${a})`),setTimeout(()=>e.emit("input",{sessionId:t,data:`${a}\r`}),400)),setTimeout(()=>n.fit(),200)}else{if("rtc-closed"===l.error){(0,v.Lq)("join","rtc-closed during join ack → retry via fallback carrier"),d(!0);return}i.joiningRef.current=!1,i.joinClaimedRef.current=!1,i.setJoining(!1),i.joinQueueRef.current=[],s.write(`\r
|
|
9
|
+
\x1b[1;31mError: ${l.error||"Failed to join session"}\x1b[0m\r
|
|
10
|
+
`)}})}};return d}({bus:x,sessionId:t,term:d,fitAddon:u,writeBatcherRef:f,doResizeRef:j,fireJoinRef:S,refs:{historyMirrorRef:O,historyBytesRef:B,historyTotalRef:W,historyFetchingRef:K,userAtTopRef:ec,joiningRef:X,joinClaimedRef:G,joinQueueRef:ee,joinGenRef:et,lastSeqRef:V,cwdRef:E,setJoining:Z},setCwd:$}),eR=o>0?setTimeout(eT,o):null;eR||eT(),N.current=eT;let eE=()=>{if(p.current){var e;(e={historyFetching:K,historyHaveAtEmit:U,awaitingTuiOutput:z,joining:X,joinClaimed:G,joinQueue:ee,prefixFrags:q}).historyFetching&&(e.historyFetching.current=!1),e.historyHaveAtEmit&&(e.historyHaveAtEmit.current=0),e.awaitingTuiOutput&&(e.awaitingTuiOutput.current=!1),e.joining&&(e.joining.current=!1),e.joinClaimed&&(e.joinClaimed.current=!1),e.joinQueue&&(e.joinQueue.current=[]),e.prefixFrags&&(e.prefixFrags.current=null),e.awaitingGap&&(e.awaitingGap.current?.timer&&clearTimeout(e.awaitingGap.current.timer),e.awaitingGap.current=null),eg.cancel(),Y.cancel(),clearTimeout(eh),eh=null,ef=!1,eb++,ei(!1),Z(!1),ek("reconnect")}};x.on("connect",eE);let e_=()=>setTimeout(()=>{let e=p.current,t=h.current;e&&!e._isDisposed&&t&&(t.fit(),t.fit(),j.current?.({force:!0}))},600);window.addEventListener("orientationchange",e_);let e$=()=>{!document.hidden&&p.current&&(p.current.refresh(0,p.current.rows-1),Q.getState().connected&&ek("visible"))};return document.addEventListener("visibilitychange",e$),()=>{window.removeEventListener("orientationchange",e_),document.removeEventListener("visibilitychange",e$),F.disconnect(),T.removeEventListener("wheel",R),x.off("connect",eE),x.off("output",eN),x.off("cwdChange",eS),es.current&&es.current.dispose(),ed.current=null,d.textarea?.removeEventListener("keyup",el),w.current&&w.current.dispose(),k.current&&clearTimeout(k.current),eg.cancel(),eR&&clearTimeout(eR),ep&&clearTimeout(ep),eh&&clearTimeout(eh),b.current&&b.current.dispose(),f.current&&f.current.dispose(),m(),C(),u.dispose(),d.dispose(),p.current=null,D(!1)}},[x,t]),(0,r.useEffect)(()=>{let e=p.current,s=h.current;e&&s&&x&&t&&(M?g.current?.():y.current?.())},[M,x,t]),(0,r.useEffect)(()=>{let e=p.current,s=h.current;e&&s&&x&&t&&null!=P&&(e.options.fontSize=P,s.fit(),ex(),e.refresh(0,e.rows-1))},[P,x,t,ex]),(0,r.useEffect)(()=>{p.current&&x&&t&&(w.current&&(w.current.dispose(),w.current=null),l&&(w.current=p.current.onData(e=>{!((X.current||K.current)&&"string"==typeof e&&(/^\x1b\[[?>=][0-9;]*c$/.test(e)||/^\x1b\[[0-9]+;[0-9]+R$/.test(e)||/^\x1b\[0n$/.test(e)||/^\x1b\]\d+;/.test(e)))&&(e&&27!==e.charCodeAt(0)&&d?.(t),x.emit("input",{sessionId:t,data:e}))})))},[l,x,t,d]),(0,r.useEffect)(()=>{if(!p.current||!x||!t||l)return;let e=p.current.onData(e=>{(e.startsWith("\x1b[<")||e.startsWith("\x1b[M"))&&x.emit("input",{sessionId:t,data:e})});return()=>e.dispose()},[l,x,t]),(0,r.useEffect)(()=>{if(!a||!h.current||!p.current)return;let e=setTimeout(()=>{if(en.current){let e=en.current;en.current=null,(0,v.Lq)("reconnect",`deferred recover → fire (pane now visible, ${e})`),er.current?.(e)}ep({force:!0}),requestAnimationFrame(()=>p.current?.refresh(0,p.current.rows-1))},100);return()=>clearTimeout(e)},[a,ep]),(0,r.useEffect)(()=>{if(!l)return;let e=window.innerWidth<760,t=setTimeout(()=>{ep(e?{force:!0}:void 0),requestAnimationFrame(()=>p.current?.refresh(0,p.current.rows-1))},100);return()=>clearTimeout(t)},[l,ep]),(0,r.useEffect)(()=>{let e=p.current;if(!e)return;let t="dark"===s?c:"none";e.options.theme=eC((0,ax.In)(s,n)||ap.dark,t),e.refresh(0,e.rows-1)},[s,n,c]),function({termRef:e,termReady:t,isVisible:s,bus:n,sessionId:a,onSelectionMadeRef:l,awaitingTuiOutputRef:i,maybeFetchHistoryRef:o,userAtTopRef:c,stopMomentumRef:d}){(0,r.useEffect)(()=>{if(!t||!e.current)return;let s=e.current.element?.querySelector(".xterm-screen");if(!s)return;let r=0,u=0,m=0,x=null,p=0,h=0,f=0,b=0,g=null,v=()=>{let t,s,r,l;if(g=null,!b)return;let o=e.current;if(!o){b=0;return}let c=Math.max(1,Math.ceil(o.cols/2)),d=Math.max(1,Math.ceil(o.rows/2)),u=b>0?(t=c,s=d,`\x1b[<65;${t};${s}M`):(r=c,l=d,`\x1b[<64;${r};${l}M`),m=Math.min(Math.abs(b),1);for(let e=0;e<m;e++)n.emit("input",{sessionId:a,data:u});b=0,f=performance.now(),i.current=!0},y=t=>{let s=e.current;if(s)if("alternate"===s.buffer.active.type){if(i.current&&performance.now()-f<120)return;b+=t;let e=performance.now()-f;e>=50?v():g||(g=setTimeout(v,50-e))}else s.scrollLines(Math.max(-3,Math.min(3,t))),t<0&&s.buffer.active.viewportY<=5&&(c.current=!0,o.current?.())},w=()=>{x&&(cancelAnimationFrame(x),x=null),m=0},k=()=>{if(!e.current||.3>Math.abs(m)){x=null;return}let t=e.current.buffer?.active?.type==="alternate",s=performance.now(),n=t&&i.current&&s-f<120,r=!t&&s-h>=33;if(!n&&(t||r)){m*=.95;let e=Math.trunc((p+=m)/18);0!==e&&(y(e),p-=18*e,h=performance.now())}x=requestAnimationFrame(k)},j=null,N=!1,S=null,C=0,T=0,R=0,E=0,_=!1,$=null,M=(t,n)=>{let r=e.current,a=$||s.getBoundingClientRect(),l=a.width/r.cols,i=a.height/r.rows,o=Math.max(0,Math.min(r.cols-1,Math.floor((t-a.left)/l))),c=Math.max(0,Math.min(r.rows-1,Math.floor((n-a.top)/i)));return{col:o,row:r.buffer.active.viewportY+c}},P=t=>{w();let n=t.touches[0];r=n.clientY,C=R=n.clientX,T=E=n.clientY,u=Date.now(),m=0,p=0,N=!1,_=!1,e.current?.clearSelection(),j=setTimeout(()=>{!_&&e.current&&(N=!0,(0,t7.e)(),$=s.getBoundingClientRect(),(({col:t,row:s})=>{let n=e.current,r=n.buffer.active.getLine(s);if(!r)return;let a=r.translateToString(!1),l=e=>e&&eM.test(e);if(!l(a[t]))return n.select(t,s,1);let i=t,o=t;for(;i>0&&l(a[i-1]);)i--;for(;o<a.length-1&&l(a[o+1]);)o++;n.select(i,s,o-i+1)})(S=M(C,T)))},450)},A=t=>{if(!e.current)return;let n=t.touches[0];if(R=n.clientX,E=n.clientY,!_&&Math.hypot(R-C,E-T)>10&&(_=!0,N||clearTimeout(j)),N){t.preventDefault();var a=M(R,E);let s=e.current;if(a.row===S.row){let e=Math.min(a.col,S.col);s.select(e,a.row,Math.abs(a.col-S.col)+1)}else s.selectLines(Math.min(a.row,S.row),Math.max(a.row,S.row));return}let l=n.clientY,i=Date.now(),o=r-l,c=i-u||1,d=s.closest(".terminal-scroll.is-scrollable");if(d&&d.scrollHeight>d.clientHeight+1){let e=d.scrollHeight-d.clientHeight,s=d.scrollTop<=.5,n=d.scrollTop>=e-.5;if(!(o<0&&s||o>0&&n)){0!==o&&(t.preventDefault(),d.scrollTop=Math.max(0,Math.min(e,d.scrollTop+o))),r=l,u=i,m=0,p=0;return}}let x=+o,h=Math.trunc((p+=x)/18);0!==h&&(t.preventDefault(),y(h),p-=18*h),m=Math.min(x/c*16,55),r=l,u=i},z=()=>{if(clearTimeout(j),$=null,N){N=!1;let t=e.current?.getSelection();t&&t.trim()&&l.current?.(t,{x:R,y:E});return}Math.abs(m)>.3&&(x=requestAnimationFrame(k))};d.current=w,s.addEventListener("touchstart",P,{passive:!0}),s.addEventListener("touchmove",A,{passive:!1}),s.addEventListener("touchend",z,{passive:!0});let I=t=>{let s=e.current;s&&t.deltaY<0&&s.buffer.active.viewportY<=5&&(c.current=!0,o.current?.())};return s.addEventListener("wheel",I,{passive:!0}),()=>{w(),d.current=null,clearTimeout(j),s.removeEventListener("touchstart",P),s.removeEventListener("touchmove",A),s.removeEventListener("touchend",z),s.removeEventListener("wheel",I)}},[t,s,e,n,a,l,i,o,c,d])}({termRef:p,termReady:L,isVisible:a,bus:x,sessionId:t,onSelectionMadeRef:A,awaitingTuiOutputRef:z,maybeFetchHistoryRef:eo,userAtTopRef:ec,stopMomentumRef:R});let eh=(0,r.useCallback)(()=>{let e=p.current;e&&x&&((0,v.Lq)("join","manual reload (user refetch)"),N.current?.(!0),M?(y.current?.(),g.current?.()):e.refresh(0,e.rows-1))},[x,M]);return{termRef:p,cwdRef:E,cwd:_,searchAddonRef:I,termReady:L,joining:Y,doResize:ep,reload:eh,focus:()=>p.current?.focus(),stopMomentum:()=>R.current?.(),historyFetching:el}}({bus:W,sessionId:a,theme:k,terminalTheme:H,isVisible:o,isFocused:c,containerRef:S,mountDelay:d,bgKey:eo?X:"none",onInput:ei,onSelectionMade:(e,t)=>L({text:e,x:t.x,y:t.y})}),ev=(0,r.useCallback)(()=>{let e=C.current,t=ec.current;if(!e||!t)return;let s=T.current.height;if(null==s||e.clientHeight>=s-1)return;let n=t.buffer.active,r=n.baseY+n.cursorY,a=t.element?.querySelector(".xterm-screen")?.getBoundingClientRect()?.height?t.element.querySelector(".xterm-screen").getBoundingClientRect().height/t.rows:0;if(a<=0){e.scrollTop=e.scrollHeight;return}let l=e.clientHeight;if((n.baseY+t.rows)*a<=s){e.scrollTop=0;return}let i=Math.max(0,Math.min(r*a-l+2*a,e.scrollHeight-e.clientHeight));e.scrollTop=i},[ec]);(0,r.useEffect)(()=>{let e=C.current;if(!e)return;let t=0,s=()=>{if(window.innerWidth>=760){T.current={width:0,height:null},t=0,E(null),$(!1);return}let s=e.clientWidth,n=e.clientHeight;if(n<=0)return;let r=T.current;s!==r.width||null==r.height||n>=r.height-2?(T.current={width:s,height:n},E(n),t=n,$(!1)):null!=r.height&&n<r.height&&n<t-8?(t=n,$(!0),requestAnimationFrame(ev)):t=n};s();let n=new ResizeObserver(s);return n.observe(e),window.addEventListener("orientationchange",s),()=>{n.disconnect(),window.removeEventListener("orientationchange",s)}},[ev]);let eN=(0,n.jsx)(aC,{onOpenRemote:g,onOpenMobile:y});(0,r.useEffect)(()=>{if(m)return m(a,{focus:ef,doResize:ep}),()=>m(a,null)},[a,ef,ep,m]);let eS=(0,ax.In)(k,H)||ap.dark;(0,r.useEffect)(()=>{if(!em||!ec.current||!o)return;let e=ec.current,t=()=>{let t=C.current,s=!!t?.classList.contains("is-scrollable")&&t.scrollHeight>t.clientHeight+1&&t.scrollHeight-t.clientHeight-t.scrollTop>5,n=e.buffer.active,r=n.baseY-n.viewportY>5;P(s||r)},s=null,n=()=>{s||(s=requestAnimationFrame(()=>{s=null,t()}))};t();let r=e.onScroll(n),a=()=>n();return C.current?.addEventListener("scroll",a,{passive:!0}),()=>{s&&cancelAnimationFrame(s),r.dispose(),C.current?.removeEventListener("scroll",a),P(!1)}},[ec,em,o]);let eT=al(eu,h,{enabled:o}),eE=aR({isFocused:c,onActivate:()=>u?.(a)}),e_=[p&&c?"terminal-focus-glow":""].filter(Boolean).join(" "),eP=`rgba(${ek},${U??.8})`,eA=`rgba(${ej},0.28)`;return(0,n.jsxs)("div",{className:`h-full w-full flex flex-col overflow-hidden relative touch-none px-1.5 py-1.5 ${e_}${eo?" terminal-has-bg":""}`,style:eo?{background:`linear-gradient(${eP},${eP}), linear-gradient(${eA},${eA}), center / cover no-repeat url("${eo}")`,backgroundBlendMode:"normal, screen, normal"}:{background:eS.background},onMouseDown:eE.onMouseDown,onTouchStart:eE.onTouchStart,children:[!et&&(0,n.jsxs)("div",{style:{height:26},className:"sm:hidden flex items-center gap-2 px-2 -mt-1.5 -mx-1.5 mb-1.5 flex-shrink-0 bg-surface border-b border-border-subtle text-[11px] select-none relative z-10",children:[(0,n.jsx)("span",{className:`w-1.5 h-1.5 rounded-full flex-shrink-0 ${nU(N)}`,style:{background:nH(N).dot}}),(0,n.jsx)("span",{className:"flex-1 min-w-0 truncate text-text",children:l||w("terminal.defaultName")}),eN]}),et&&(0,n.jsx)(aS,{bus:W,sessionId:a,variant:"pinned",rightSlot:eN}),(0,n.jsxs)("div",{ref:C,className:`terminal-wrapper terminal-scroll flex-1 min-h-0 relative ${_?" is-scrollable":""}`,children:[(0,n.jsx)("div",{ref:S,className:"xterm-screen w-full rounded-sm overflow-hidden",style:null!=R?{height:R,minHeight:R}:{height:"100%",minHeight:"100%"}}),(ex||!em)&&(0,n.jsx)("div",{className:"absolute inset-0 z-40 flex items-center justify-center pointer-events-none",children:(0,n.jsx)("span",{className:"w-6 h-6 border-2 border-brand-500 border-t-transparent rounded-full animate-spin"})}),eg&&(0,n.jsx)("div",{className:"absolute top-2 left-1/2 -translate-x-1/2 z-40 pointer-events-none",children:(0,n.jsxs)("div",{className:"flex items-center gap-2 px-3 py-1.5 rounded-full bg-surface-2/80 backdrop-blur-sm shadow-md text-xs text-text-secondary",children:[(0,n.jsx)("span",{className:"w-3 h-3 border-2 border-brand-500 border-t-transparent rounded-full animate-spin"}),"Loading history…"]})}),I&&(0,n.jsx)(an,{text:I.text,position:I,onOpenUrl:e=>window.open(e,"_blank"),onCopy:e=>{try{navigator.clipboard?.writeText(e)}catch{}},onAddToNote:e=>{L(null),el(e),er(!0)},onClose:()=>{ec.current?.clearSelection(),L(null)}})]}),M&&(0,n.jsx)("button",{onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onTouchStart:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>{let t;e.stopPropagation(),(0,t7.e)(),eb(),t=C.current,t?.classList.contains("is-scrollable")&&t.scrollHeight>t.clientHeight+1&&(t.scrollTop=t.scrollHeight),ec.current?.scrollToBottom()},className:"absolute bottom-3 right-5 z-10 p-2 bg-surface-2 hover:bg-surface-3 text-text rounded-full shadow-md transition-all duration-150 ease-out active:scale-[0.94] touch-none",title:w("terminalPane.scrollToBottom"),children:(0,n.jsx)(t3.yQ,{size:20})}),c&&(0,n.jsxs)("div",{className:`absolute right-2 z-10 flex flex-col items-end gap-2 pointer-events-auto touch-none ${et?"top-9":"top-9 sm:top-2"}`,children:[(0,n.jsxs)("div",{className:"flex flex-row gap-2",children:[J&&(0,n.jsx)("button",{onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onTouchStart:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>{e.stopPropagation(),(0,t7.e)(),el(null),er(!0)},className:aE,title:w("terminalPane.note"),children:(0,n.jsx)(t3.y8,{size:16,className:a_})}),(0,n.jsx)("button",{onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onTouchStart:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>{e.stopPropagation(),A||((0,t7.e)(),z(!0),eh(),setTimeout(()=>z(!1),700))},className:aE,title:w("terminalPane.refresh"),children:(0,n.jsx)(t3.e9,{size:16,className:`${a_} ${A?"animate-spin":""}`})})]}),G&&(eu||t)&&(0,n.jsxs)("button",{onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onTouchStart:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>{e.stopPropagation(),(0,t7.e)(),O(t,K||t),window.innerWidth>=760?D("files",t):F()},className:`relative ${aE}`,title:w("terminalPane.openFolderHere"),children:[(0,n.jsx)(t3.vd,{size:16,className:a_}),eT>0&&(0,n.jsx)("span",{className:"absolute -top-1 -right-1 min-w-[16px] h-4 px-1 flex items-center justify-center text-[10px] font-semibold text-white bg-brand-500 rounded-full",children:eT>999?"999+":eT})]}),b&&Y?.length>0&&(0,n.jsxs)("button",{onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onTouchStart:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>{e.stopPropagation(),(0,t7.e)(),b(a,Y[0])},className:`relative ${aE}`,title:w("terminalPane.artifacts"),children:[(0,n.jsx)(t3.sU,{size:16,className:a_}),(0,n.jsx)("span",{className:"absolute -top-1 -right-1 min-w-[16px] h-4 px-1 flex items-center justify-center text-[10px] font-semibold text-white bg-brand-500 rounded-full",children:Y.length})]})]}),en&&J&&(0,n.jsx)(aS,{bus:e,sessionId:a,appendOnOpen:ea,pinned:Z,onPin:e=>ee(a,e),onClose:()=>{er(!1),el(null)}})]})},(e,t)=>e.sessionId===t.sessionId&&e.isVisible===t.isVisible&&e.isFocused===t.isFocused&&e.bgIndex===t.bgIndex&&e.connected===t.connected&&e.showFocusBorder===t.showFocusBorder&&e.sessionName===t.sessionName&&e.sessionState===t.sessionState&&e.onOpenArtifact===t.onOpenArtifact);function aM({items:e,size:t=12,label:s="",revealCls:a="",className:l="",anchor:i=null,onClose:o}){let c=e.filter(Boolean),[d,u]=(0,r.useState)(null),m=i??d,x=null!==m,p=(0,r.useRef)(null),h=rE(p,m?.left??0,m?.top??0),f=(0,r.useCallback)(()=>{u(null),o?.()},[o]);return((0,r.useEffect)(()=>{if(!x)return;let e=e=>{"Escape"===e.key&&(e.stopPropagation(),f())};return document.addEventListener("keydown",e,!0),()=>document.removeEventListener("keydown",e,!0)},[x,f]),c.length)?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",onClick:e=>{if(e.stopPropagation(),(0,t7.e)(),x)return void f();let t=e.currentTarget.getBoundingClientRect();u({left:t.left,top:t.bottom+2})},className:`p-0.5 text-text-subtle hover:text-text rounded-[2px] hover:bg-surface-2 transition-colors ${a} ${l}`,title:s,"aria-label":s,"aria-haspopup":"menu",children:(0,n.jsx)(t3.a4,{size:t})}),x&&"u">typeof document&&(0,r_.createPortal)((0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"fixed inset-0 z-[69]",onPointerDown:e=>{e.stopPropagation(),f()},onClick:e=>{e.stopPropagation(),f()},onContextMenu:e=>{e.preventDefault(),e.stopPropagation(),f()}}),(0,n.jsx)("div",{ref:p,role:"menu",className:"fixed z-[70] menu-popover p-1 min-w-[160px] animate-in fade-in zoom-in-95 duration-100 shadow-xl",style:{left:h.left,top:h.top},children:c.map(({icon:e,label:t,danger:s,onClick:r})=>(0,n.jsxs)("button",{type:"button",onClick:e=>{e.stopPropagation(),(0,t7.e)(),f(),r?.()},className:`w-full text-left px-2.5 py-1.5 text-xs rounded-[6px] flex items-center gap-2 transition-colors ${s?"text-red-500 hover:bg-red-500/10":"text-text hover:bg-surface-2/80"}`,children:[e&&(0,n.jsx)(e,{size:13,className:"flex-shrink-0"}),(0,n.jsx)("span",{className:"truncate",children:t})]},t))})]}),document.body)]}):null}var aP=s(20464),aA=s(4018),az=s(75687);function aI({onClose:e}){let{t}=(0,se.s)(),{authenticateWithApiKey:s,authenticateWithToken:a}=(0,aP.As)(),{saveKey:l}=(0,aA.u)(),[i,o]=(0,r.useState)(""),[c,d]=(0,r.useState)(!0),[u,m]=(0,r.useState)(!1),[x,p]=(0,r.useState)(""),h=(0,r.useRef)(null);(0,r.useEffect)(()=>{window.matchMedia("(pointer: fine)").matches&&requestAnimationFrame(()=>h.current?.focus())},[]),(0,r.useEffect)(()=>{let t=t=>{"Escape"===t.key&&(t.preventDefault(),t.stopPropagation(),e?.())};return window.addEventListener("keydown",t,!0),()=>window.removeEventListener("keydown",t,!0)},[e]);let f=async e=>{e?.preventDefault();let n=i.trim();if(!n||u)return;if((0,et.PF)(n))return p(t("login.legacyKeyError"));(0,t7.e)(),m(!0),p("");let r=(0,az.k)(n);try{let e=r?.tempKey?await a(r.tempKey,!0,r.tail):await s(n);if(!e?.success)return void p(e?.error&&"wrong-key-tail"!==e.error?e.error:t("login.invalidKeyTail"));let i=r?.tempKey?e.apiKey:(0,et.Uo)(n),o=r?.tempKey?r.tail:(0,et.Cj)(n);o&&i&&(0,M.LG)(r?.tempKey||i,{tail:o}),c&&i&&l(r?.tempKey?e.apiKey:n,""),window.location.href="/workspace/"}catch(e){p(e?.message||t("login.invalidKeyTail"))}finally{m(!1)}};return(0,n.jsx)("div",{className:"fixed inset-0 z-[70] flex items-center justify-center px-4 bg-black/50 backdrop-blur-[4px] animate-in fade-in duration-150",style:{paddingTop:"max(1rem, env(safe-area-inset-top))",paddingBottom:"max(1rem, env(safe-area-inset-bottom))"},onClick:e,children:(0,n.jsxs)("form",{role:"dialog","aria-modal":"true","aria-label":t("hosts.addHost"),onSubmit:f,className:"card-elev w-[26rem] max-w-full overflow-hidden flex flex-col my-auto animate-in zoom-in-95 duration-150",onClick:e=>e.stopPropagation(),children:[(0,n.jsxs)("div",{className:"px-4 pt-4 pb-3 flex items-center gap-2.5 border-b border-border-subtle",children:[(0,n.jsx)("div",{className:"p-1.5 bg-brand-500/10 rounded-brand flex-shrink-0",children:(0,n.jsx)(t3.kV,{className:"text-brand-500 w-4 h-4"})}),(0,n.jsx)("h2",{className:"flex-1 text-sm font-semibold text-text truncate",children:t("hosts.addHost")}),(0,n.jsx)("button",{type:"button",onClick:e,"aria-label":t("common.cancel"),className:"text-text-muted hover:text-text shrink-0",children:(0,n.jsx)(t3.X,{size:18})})]}),(0,n.jsxs)("div",{className:"px-4 py-4 space-y-3",children:[(0,n.jsx)("input",{ref:h,type:"text",value:i,onChange:e=>{o(e.target.value),p("")},placeholder:t("login.placeholder"),spellCheck:!1,autoComplete:"off",className:"w-full px-3 py-2.5 bg-surface-2 border border-border-subtle rounded-[10px] font-mono text-sm text-text placeholder-text-subtle focus:outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-500/20 transition-all duration-150"}),(0,n.jsxs)("label",{className:"flex items-center gap-2 px-0.5 text-xs text-text-muted cursor-pointer select-none",children:[(0,n.jsx)("input",{type:"checkbox",checked:c,onChange:e=>d(e.target.checked),className:"w-4 h-4 accent-brand-500 cursor-pointer"}),t("login.rememberKey")]}),x&&(0,n.jsx)("p",{className:"text-xs text-red-400 px-0.5",children:x})]}),(0,n.jsxs)("div",{className:"px-4 pb-4 flex gap-2",children:[(0,n.jsx)("button",{type:"button",onClick:e,className:"flex-1 py-2 text-sm text-text-muted bg-surface-2 hover:bg-surface-3 rounded-brand transition-colors",children:t("common.cancel")}),(0,n.jsxs)("button",{type:"submit",disabled:!i.trim()||u,className:"flex-1 py-2 text-sm font-semibold text-white bg-brand-500 hover:bg-brand-600 rounded-brand transition-colors flex items-center justify-center gap-1.5 disabled:opacity-50 disabled:cursor-not-allowed",children:[u&&(0,n.jsx)(t3.kr,{size:14,className:"animate-spin"}),t("login.connect")]})]})]})})}function aL({hostKey:e=null,label:t="",connected:s=!0,collapsed:a=!1,onToggleCollapse:l=null,onRename:i=null,onDelete:o=null,onDisconnect:c=null,onAddWorkspace:d=null,meta:u=null,mutedOffline:m=!1,connecting:x=!1,onRetry:p=null,showAdd:h=!0,className:f=""}){let{t:b}=(0,se.s)(),[g,v]=(0,r.useState)(null),[y,w]=(0,r.useState)(!1),[k,j]=(0,r.useState)(!1),[N,S]=(0,r.useState)(!1),[C,T]=(0,r.useState)(null),R=t||b("sessions.headerTitle");return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:`relative pr-2 py-1.5 flex items-center gap-1 group group/host ${f}`,onContextMenu:e=>{e.preventDefault(),(0,t7.e)(),T({left:e.clientX,top:e.clientY})},children:[l?(0,n.jsx)("button",{onClick:e=>{e.stopPropagation(),(0,t7.e)(),l()},className:"p-1 text-text-subtle hover:text-text flex-shrink-0",tabIndex:-1,"aria-expanded":!a,"aria-label":R,children:(0,n.jsx)(t3.c_,{size:12,className:`transition-transform duration-150 ${a?"":"rotate-90"}`})}):(0,n.jsx)("span",{className:"p-1 flex-shrink-0 invisible","aria-hidden":"true",children:(0,n.jsx)(t3.c_,{size:12})}),(0,n.jsxs)("span",{className:"relative flex-shrink-0",children:[(0,n.jsx)(t3.VA,{size:16,className:"text-text-muted"}),(0,n.jsx)("span",{className:`absolute -bottom-0.5 -right-0.5 w-1.5 h-1.5 rounded-full ring-1 ring-surface ${x?"bg-amber-400 animate-pulse":s?"bg-green-500":m?"bg-text-subtle":"bg-red-500 animate-pulse"}`})]}),(0,n.jsx)("button",{type:"button",onClick:()=>{l&&((0,t7.e)(),l())},className:"flex-1 min-w-0 py-0.5 pr-1 text-left",children:(0,n.jsx)("span",{className:`block text-sm font-medium uppercase truncate ${s?"text-text":"text-text-muted"}`,"data-tip":R,children:R})}),u&&(0,n.jsx)("span",{className:"text-[10px] text-text-subtle truncate min-w-0 max-w-[45%] mr-1",children:u}),(0,n.jsxs)("div",{className:"absolute right-1 top-1/2 -translate-y-1/2 flex items-center gap-1 sm:gap-1.5 px-1 rounded-[3px] bg-surface-2 opacity-0 group-hover:opacity-100 [@media(hover:none)]:opacity-100 [@media(hover:none)]:bg-transparent [@media(hover:none)]:px-0 transition-opacity",children:[h&&(0,n.jsx)("button",{onClick:e=>{e.stopPropagation(),(0,t7.e)(),S(!0)},className:"p-0.5 text-text-subtle hover:text-text rounded-[2px] transition-colors",title:b("hosts.addHost"),children:(0,n.jsx)(t3.kV,{size:13.5})}),p&&!s&&!x&&(0,n.jsx)("button",{onClick:e=>{e.stopPropagation(),(0,t7.e)(),p()},className:"p-1.5 text-text-subtle hover:text-text rounded-[2px] transition-colors",title:b("common.retry"),children:(0,n.jsx)(t3.kt,{size:16})}),d&&(0,n.jsx)("button",{onClick:e=>{e.stopPropagation(),(0,t7.e)(),d()},className:"p-1.5 text-text-subtle hover:text-text rounded-[2px] transition-colors",title:b("workspaces.newWorkspace"),children:(0,n.jsx)(t3.vd,{size:18})}),(0,n.jsx)(aM,{size:18,label:b("sessions.sessionActions"),revealCls:"",anchor:C,onClose:()=>T(null),items:[i&&e&&{icon:t3.gH,label:b("sessions.editName"),onClick:()=>v(R)},o&&e&&{icon:t3.TB,label:b("hosts.removeHost"),danger:!0,onClick:()=>w(!0)},c&&{icon:t3.Mr,label:b("common.disconnect"),danger:!0,onClick:()=>j(!0)}]})]})]}),N&&(0,n.jsx)(aI,{onClose:()=>S(!1)}),null!==g&&(0,n.jsx)(rR,{title:b("sessions.editName"),placeholder:R,value:g,onChange:v,onSubmit:()=>{let t=g.trim();t&&e&&i?.(e,t),v(null)},onClose:()=>v(null)}),(0,n.jsx)(t9.A,{isOpen:y,onClose:()=>w(!1),onConfirm:()=>{w(!1),e&&o?.(e)},title:b("hosts.removeHost"),message:b("hosts.removeHostMessage",{name:R}),confirmText:b("common.delete")}),(0,n.jsx)(t9.A,{isOpen:k,onClose:()=>j(!1),onConfirm:()=>{j(!1),c?.()},title:b("common.disconnect"),message:b("hosts.disconnectMessage",{name:R}),confirmText:b("common.disconnect")})]})}let aD="9remote_tree_collapsed",aF="_root";function aO(){try{return JSON.parse(localStorage.getItem(aD))||{}}catch{return{}}}function aB(e=""){let[t,s]=(0,r.useState)(()=>new Set(aO()[e]||[])),n=(0,r.useCallback)(t=>{s(s=>{let n=new Set(s);n.has(t)?n.delete(t):n.add(t);let r=aO();r[e]=[...n];try{localStorage.setItem(aD,JSON.stringify(r))}catch{}return n})},[e]);return{isCollapsed:(0,r.useCallback)(e=>t.has(e),[t]),toggle:n}}let aW=new Map,aK={branch:null,dirty:!1,changedCount:0};async function aH(e,t){let[s,n]=await Promise.all([e.fileBus?.gitBranch?.(t),e.fileBus?.gitChangedCount?.(t)]),r=s?.success&&s.branch||null,a=n?.success&&n.count||0;(e.state.branch!==r||e.state.changedCount!==a)&&(e.state={branch:r,dirty:a>0,changedCount:a},e.subs.forEach(t=>t(e.state)))}function aU(e,t,{enabled:s=!0}={}){let[n,a]=(0,r.useState)(aK),l=t||t2.getState();return(0,r.useEffect)(()=>{let t;if(!e||!l||!s)return;let n=((t=aW.get(e))||(t={state:aK,stop:null,refs:0,subs:new Set,fileBus:l},aW.set(e,t),aH(t,e),t.stop=rl(()=>aH(t,e),1e4)),t.refs++,t);return n.subs.add(a),a(e=>e===n.state?e:n.state),()=>{let t;n.subs.delete(a),(t=aW.get(e))&&(t.refs--,t.refs>0||(t.stop?.(),aW.delete(e)))}},[e,l,s]),n}function aq({branch:e,dirty:t,size:s=10,className:r="",iconClassName:a=""}){return e?(0,n.jsxs)("span",{className:`inline-flex items-center gap-0.5 min-w-0 ${r}`,title:e,children:[(0,n.jsx)(t3.Zr,{size:s,className:`flex-shrink-0 ${a||"opacity-70"}`}),(0,n.jsxs)("span",{className:"truncate",children:[e,t?"*":""]})]}):null}function aV({workspace:e,isActive:t,connected:s,collapsed:r,fileBus:a,onToggleCollapse:l,onSelect:i,onNewTerminal:o,onDelete:c,onRename:d}){let{t:u}=(0,se.s)(),{branch:m,dirty:x}=aU(rn(e),a,{enabled:!!a});return(0,n.jsxs)("div",{onClick:i,className:`relative pr-2 py-1.5 flex items-center gap-1 group group/grp transition-colors ${i?"cursor-pointer hover:bg-text/[0.06]":""}`,children:[(0,n.jsx)("button",{onClick:e=>{e.stopPropagation(),(0,t7.e)(),l?.()},className:"p-1 text-text-subtle hover:text-text flex-shrink-0",tabIndex:-1,children:(0,n.jsx)(t3.c_,{size:12,className:`transition-transform duration-150 ${r?"":"rotate-90"}`})}),(0,n.jsx)(t3.vd,{size:13.5,className:"text-text-muted flex-shrink-0"}),(0,n.jsxs)("span",{className:"flex-1 min-w-0 flex flex-col",children:[(0,n.jsx)("span",{className:`text-[12px] font-medium uppercase truncate ${t?"text-text":"text-text-muted"}`,"data-tip":e.name,children:e.name}),m&&!eW.includes(m)&&m!==e.name&&(0,n.jsx)("span",{className:"text-[10px] text-text-subtle leading-tight flex items-center gap-1 min-w-0",children:(0,n.jsx)(aq,{branch:m,dirty:x,className:"truncate flex-shrink-0 max-w-[7rem]"})})]}),(0,n.jsxs)("div",{className:"absolute right-1 top-1/2 -translate-y-1/2 flex items-center gap-1.5 px-1 rounded-[3px] bg-surface-2 opacity-0 group-hover:opacity-100 [@media(hover:none)]:opacity-100 transition-opacity",children:[o&&(0,n.jsx)("button",{type:"button",onClick:e=>{e.stopPropagation(),(0,t7.e)(),o()},disabled:!s,className:"p-0.5 text-text-subtle hover:text-text rounded-[2px] transition-colors disabled:opacity-40",title:u("terminal.newTerminal"),children:(0,n.jsx)(t3.FW,{size:13.5})}),(0,n.jsx)(aM,{size:13.5,label:u("sessions.sessionActions"),revealCls:"",items:[d&&{icon:t3.gH,label:u("workspaces.rename"),onClick:()=>d()},c&&s&&{icon:t3.TB,label:u("workspaces.delete"),danger:!0,onClick:()=>c()}]})]})]})}function aX({agent:e=null,tool:t=null}){let s="string"==typeof e?e:e?.id||null;return s?.endsWith("-ui")?(0,n.jsx)("img",{src:s$(s),alt:"",className:`w-3.5 h-3.5 flex-shrink-0 object-contain ${s_}`}):nV[t]?(0,n.jsx)("img",{src:nV[t],alt:t,className:`w-3.5 h-3.5 flex-shrink-0 object-contain ${s_}`}):(0,n.jsx)(t3.BK,{size:13.5,className:"flex-shrink-0"})}let aG=function({fileBus:e,cwd:t,basePath:s,homeDir:r}){let a,{branch:l,dirty:i}=aU(t,e),o=!!l&&!eW.includes(l),c=o?null:t&&s&&t.startsWith(`${s}/`)?t.slice(s.length+1):t&&s&&t!==s?(a=rs(t,r)).split("/").length>2?`…/${a.split("/").slice(-2).join("/")}`:a:null;return o||c?(0,n.jsxs)("span",{className:"text-xs text-text-subtle truncate leading-tight flex items-center gap-1.5",children:[o&&(0,n.jsx)(aq,{branch:l,dirty:i,className:"truncate italic"}),c&&(0,n.jsx)("span",{className:"truncate opacity-70","data-tip":c,children:c})]}):null};function aJ({host:e,actions:t={},busRef:s=null,activeSessionId:a=null,activeWorkspaceId:l=null,connected:i=!0,fileBus:o=null,homeDir:c=null,hiddenPaneSessionIds:d=[],onUnhidePane:u=null,onAddWorkspace:m=null,menuAddWorkspace:x=null,onRowContextMenu:p=null,onRowTouch:h=null,onRowMenu:f=null,agentBySession:b=null,cwdBySession:g=null,treeCls:v="pl-3.5",rowCls:y="hover:bg-text/5 hover:text-text"}){let{t:w}=(0,se.s)(),{isCollapsed:k,toggle:j}=aB(e.key),N=!k(aF),[S,C]=(0,r.useState)(null),[T,R]=(0,r.useState)(null),[E,_]=(0,r.useState)(null),[$,M]=(0,r.useState)(null),[P,A]=(0,r.useState)(null),[z,I]=(0,r.useState)(null),[L,D]=(0,r.useState)([]),F=e.status||"full",O="connecting"===F,B="offline"!==F,W="connecting"!==F,K=(0,r.useMemo)(()=>({current:sq(e.key)}),[e.key]),H=s||K;(0,r.useEffect)(()=>{null!==S&&H?.current?.emit&&H.current.emit("getShells",e=>D(e?.shells||[]))},[S,H]);let{dragId:U,registerEl:q,startDrag:V,consumeClick:X}=rI({axis:"y",onCommit:e=>t.reorderSession?.(e)}),G=function(e=[],t=[]){let s=new Set(t.map(e=>e.id)),n=new Map;for(let t of e){let e=s.has(t.workspaceId)?t.workspaceId:null;n.has(e)||n.set(e,[]),n.get(e).push(t)}return[...t.filter(e=>n.has(e.id)).map(e=>({workspace:e,sessions:n.get(e.id)})),...n.has(null)?[{workspace:null,sessions:n.get(null)}]:[]]}(e.sessions,e.workspaces);return(0,n.jsxs)("div",{children:[(0,n.jsx)(aL,{hostKey:e.key,label:e.label,connected:B,connecting:O,mutedOffline:"full"!==F,collapsed:!N,meta:O?(0,n.jsx)(t3.kr,{size:12,className:"animate-spin text-text-subtle"}):null,onToggleCollapse:W?()=>{(0,t7.e)(),N||sX.getState().ensureHost(e.key),j(aF)}:null,onRetry:"offline"===F?()=>sX.getState().retryHost(e.key):null,onDisconnect:e.onDisconnect,onAddWorkspace:x,onRename:t.renameHost,onDelete:t.deleteHost,showAdd:!1}),N&&W&&(0,n.jsxs)("div",{className:v,children:[!G.length&&(0,n.jsx)("p",{className:"px-3 py-6 text-center text-xs text-text-muted",children:w("workspaces.emptyWorkspace")}),G.map(({workspace:s,sessions:r})=>{let m=s?.id??null,x=m??"ungrouped",v=l===m;return(0,n.jsxs)("div",{className:"flex flex-col mt-2 first:mt-0",children:[(0,n.jsx)(aV,{workspace:{id:m,name:s?.name||w("workspaces.ungrouped"),path:s?.path||null,items:r},isActive:v,connected:i&&B,fileBus:o,collapsed:k(x),onToggleCollapse:()=>j(x),onSelect:t.selectWorkspace?()=>{(0,t7.e)(),t.selectWorkspace(m)}:null,onNewTerminal:t.createSession?()=>C(x):null,onRename:t.renameWorkspace&&null!=m?()=>R({id:m,value:s.name}):null,onDelete:t.deleteWorkspace&&null!=m?()=>_({id:m,name:s.name}):null}),!k(x)&&r.map(l=>{let v=nH(e.statusMap?.[l.id]?.state||"idle"),k=a===l.id,j=U===l.id,N=d.includes(l.id),S=l.name||w("terminal.defaultName");return(0,n.jsxs)("div",{ref:q(l.id),"data-sid":l.id,className:`group flex items-center gap-1.5 pl-3.5 pr-2 py-1.5 ml-0.5 rounded-[3px] text-left relative cursor-pointer ${k?"bg-brand-500/15 text-text":`text-text-muted ${y}`} ${j?"z-20 opacity-90 shadow-lg ring-1 ring-brand-500":"transition-colors"}`,onClick:e=>{X()||((0,t7.e)(),t.selectSession?.(l.id))},onContextMenu:p?e=>p(e,l.id,S):void 0,onTouchStart:h?.start,onTouchMove:h?.move,onTouchEnd:h?.end,children:[i&&B&&(0,n.jsx)("button",{"data-gid":"ungrouped"===x?"":m,"data-sid":l.id,onPointerDown:e=>V(e,l.id,r.map(e=>e.id)),disabled:r.length<2,className:"absolute left-0 top-1/2 -translate-y-1/2 z-10 p-0.5 text-text-subtle opacity-0 group-hover:opacity-100 cursor-grab active:cursor-grabbing touch-none disabled:opacity-0 disabled:cursor-default",tabIndex:-1,children:(0,n.jsx)(t3.f2,{size:12})}),(0,n.jsx)("span",{className:`w-2 h-2 rounded-full flex-shrink-0 term-dot ${v.cls}${v.pulse?` pulse-${v.pulse}`:""}`,style:{background:v.dot}}),(0,n.jsxs)("span",{className:"flex-1 min-w-0 flex flex-col",children:[(0,n.jsxs)("span",{className:`flex items-center gap-1 min-w-0 ${k?"font-medium":""}`,children:[(0,n.jsx)(aX,{agent:b?.[l.id]??l.agent,tool:e.statusMap?.[l.id]?.tool}),(0,n.jsx)("span",{className:"text-[11px] truncate","data-tip":S,children:S}),N&&u&&(0,n.jsx)("button",{type:"button",tabIndex:-1,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),(0,t7.e)(),u(l.id)},className:"p-0.5 rounded text-amber-400 hover:text-amber-300 hover:bg-amber-400/20 transition-colors flex items-center justify-center shrink-0 ml-1",title:w("sessions.showPanel")||"Show panel",children:(0,n.jsx)(t3.X_,{size:12})})]}),(0,n.jsx)(aG,{fileBus:o,cwd:g?.[l.id]??l.cwd??l.workspacePath,basePath:rn({path:s?.path||null,items:r}),homeDir:c})]}),(0,n.jsx)("div",{className:"absolute right-1 top-1/2 -translate-y-1/2 flex items-center px-1 rounded-[3px] bg-surface-2 opacity-0 group-hover:opacity-100 [@media(hover:none)]:opacity-60 transition-opacity",children:f?(0,n.jsx)("button",{onClick:e=>{e.stopPropagation(),(0,t7.e)();let t=e.currentTarget.getBoundingClientRect();f(l.id,S,t)},className:"p-0.5 text-text-subtle hover:text-text rounded-[2px] transition-colors",title:w("sessions.sessionActions"),children:(0,n.jsx)(t3.a4,{size:13.5})}):(0,n.jsx)(aM,{size:13.5,label:w("sessions.sessionActions"),revealCls:"",items:[t.renameSession&&{label:w("sessions.editName"),onClick:()=>M({id:l.id,value:l.name||""})},t.deleteSession&&{label:w("sessions.deleteTitle"),danger:!0,onClick:()=>A({id:l.id,name:l.name||""})}]})})]},l.id)}),!k(x)&&0===r.length&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),C(x)},disabled:!i||!B,className:"pl-3.5 pr-2 py-1.5 text-left text-xs text-text-subtle hover:text-brand-500 italic transition-colors disabled:opacity-40",children:w("workspaces.emptyWorkspace")})]},x)}),(0,n.jsx)("div",{className:"px-2 pt-3 pb-1",children:(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),m?m():I("")},disabled:!i||!B,className:"mx-auto flex items-center gap-1.5 py-1.5 px-4 text-xs text-text-subtle hover:text-text border border-dashed border-border-subtle hover:border-text-muted/40 rounded-brand hover:bg-surface-2 transition-colors disabled:opacity-40",children:[(0,n.jsx)(t3.FW,{size:12,className:"flex-shrink-0"}),(0,n.jsx)("span",{children:w("workspaces.newWorkspace")})]})})]}),null!==S&&(0,n.jsx)(rT,{onClose:()=>C(null),onCreate:(e,s,n,r,a,l)=>{t.createSession?.(e,"ungrouped"===S?null:S,s,a,n,r,l),C(null)},shells:L,busRef:H,hostKey:e.key,liveSessionIds:null,connected:i&&B,workspacePath:e.workspaces?.find(e=>e.id===("ungrouped"===S?null:S))?.path||null,workspaceName:"ungrouped"===S?w("workspaces.ungrouped"):e.workspaces?.find(e=>e.id===S)?.name||"",suggestName:`${w("terminal.defaultName")} ${(e.sessions?.length||0)+1}`}),null!==z&&(0,n.jsx)(rR,{title:w("workspaces.newWorkspace"),placeholder:w("workspaces.workspaceNamePlaceholder"),value:z,onChange:I,onSubmit:()=>{let t=z.trim();t&&sq(e.key)?.emit("createWorkspace",{name:t,path:null},()=>{}),I(null)},onClose:()=>I(null)}),null!==T&&(0,n.jsx)(rR,{title:w("workspaces.rename"),value:T.value,onChange:e=>R({...T,value:e}),onSubmit:()=>{let e=T.value.trim();e&&t.renameWorkspace?.(T.id,e),R(null)},onClose:()=>R(null)}),null!==E&&(0,n.jsx)(t9.A,{isOpen:!0,onClose:()=>_(null),onConfirm:()=>{t.deleteWorkspace?.(E.id),_(null)},title:w("workspaces.deleteTitle"),message:w("workspaces.deleteMessage",{name:E.name}),confirmText:w("common.delete")}),null!==$&&(0,n.jsx)(rR,{title:w("sessions.editName"),value:$.value,onChange:e=>M({...$,value:e}),onSubmit:()=>{let e=$.value.trim();e&&t.renameSession?.($.id,e),M(null)},onClose:()=>M(null)}),null!==P&&(0,n.jsx)(t9.A,{isOpen:!0,onClose:()=>A(null),onConfirm:()=>{t.deleteSession?.(P.id),A(null)},title:w("sessions.deleteTitle"),message:w("sessions.deleteMessage",{name:P.name||""}),confirmText:w("common.delete")})]})}let aY=!!window.__TAURI__||(0,ee._r)()&&window.location.port===String(f._8),aZ=(0,r.memo)(function({allSessions:e=[],workspaces:t=[],activeSessionId:s,activeWorkspaceId:a,sessionStatus:l,notifications:i,onSelectSession:o,onSelectWorkspace:c,onCreateNamedSession:d,onDeleteWorkspace:u,shells:m=[],onRenameSession:x,onDeleteSession:p,onReorderSession:h,onAddWorkspace:f,onRenameWorkspace:b=null,onOpenSettings:g,onLogout:v=null,onRenameHost:y=null,onDeleteHost:w=null,busRef:k=null,fileBus:j,homeDir:N,cwdBySession:S={},connected:C=!0,width:T=ea.default,onResize:R,onCollapse:E,onResumeAgentSession:_}){let{t:$}=(0,se.s)(),M=tS(e=>e.agentBySession||{}),P=Object.values(sX(e=>e.hosts)),A=P.find(e=>"full"===e.status),[z,I]=(0,r.useState)(!1),L=sB(P,A?.key),D=tS(e=>e.fullModes||{});tS(e=>e.fullMode);let F=tS(e=>e.toggleFullMode),O=tS(e=>e.setFullMode),B=tS(e=>e.hiddenPaneSessionIds||[]),W=tS(e=>e.toggleHidePane),K=tS(e=>e.unhidePane),H=sc(e=>e.sessionStatus),U=l||H,q="mouse"===nk()?s9($("common.close"),"toggleSidebar"):$("common.close"),V=(0,r.useMemo)(()=>new Set(e.map(e=>e.id)),[e]),X=s?S[s]??e.find(e=>e.id===s)?.cwd??e.find(e=>e.id===s)?.workspacePath??null:null,G=sT(e=>e.canInstall),J=sT(e=>e.isInstalled),Y=sT(e=>e.install),Z=window.matchMedia("(display-mode: standalone)").matches||!!window.ReactNativeWebView,Q=G&&!Z&&!J&&!(0,ee.XS)(),[et,es]=(0,r.useState)(null),en=(0,r.useRef)(null),er=rE(en,et?.left??0,et?.top??0),[el,ei]=(0,r.useState)(null),eo=M[et?.sessionId]||U[et?.sessionId]?.tool||e.find(e=>e.id===et?.sessionId)?.agent,ec=eo?.endsWith("-ui");U[et?.sessionId]?.conversationId;let ed=r7(eo),eu=ed&&r9.has(U[et?.sessionId]?.state||"idle"),em=eQ(e.find(e=>e.id===et?.sessionId))??eZ,ex=D[em]??!1,[ep,eh]=(0,r.useState)({sessionId:null,name:"",value:""}),[ef,eb]=(0,r.useState)(null);(0,r.useEffect)(()=>{if(!et)return;let e=e=>{en.current&&!en.current.contains(e.target)&&es(null)},t=e=>{"Escape"===e.key&&es(null)};return document.addEventListener("mousedown",e),document.addEventListener("touchstart",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("mousedown",e),document.removeEventListener("touchstart",e),document.removeEventListener("keydown",t)}},[et]);let eg=t=>e.find(e=>e.id===t),ev=(0,r.useRef)(null),ey=()=>{ev.current&&(clearTimeout(ev.current),ev.current=null)};return(0,n.jsxs)("div",{className:"flex-shrink-0 h-full hidden sm:flex flex-col terminal-sidebar-bg border-r border-border-subtle relative",style:{width:T},children:[(0,n.jsxs)("div",{style:{height:32},className:"px-3 flex items-center justify-between flex-shrink-0 border-b border-border-subtle relative z-10",children:[(0,n.jsx)("div",{className:"flex items-center gap-2 min-w-0",children:aY?(0,n.jsxs)("button",{onClick:()=>{window.location.href="/"},className:"flex items-center gap-1.5 px-1.5 py-1 text-[12px] font-medium text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-colors flex-shrink-0",title:"Pair Device",children:[(0,n.jsx)(t3.JG,{size:14,className:"opacity-70"}),(0,n.jsx)(t3.vW,{size:13,className:"opacity-80"}),(0,n.jsx)("span",{className:"truncate",children:"Pair Device"})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("img",{src:"/icon-192.png",alt:"9Remote",className:"w-4 h-4 rounded-[4px] object-contain flex-shrink-0"}),(0,n.jsx)("span",{className:"text-[13px] font-semibold text-text truncate",children:"9Remote"})]})}),(0,n.jsxs)("div",{className:"flex items-center gap-0.5 flex-shrink-0",children:[(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),I(!0)},className:"p-1 text-text-muted hover:text-text rounded-[3px] hover:bg-surface-2 transition-colors",title:$("hosts.addHost"),children:(0,n.jsx)(t3.kV,{size:14})}),E&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),E()},className:"p-1 text-text-muted hover:text-text rounded-[3px] hover:bg-surface-2 transition-colors",title:q,children:(0,n.jsx)(t3.e6,{size:14})})]})]}),(0,n.jsxs)("div",{className:"flex-1 min-h-0 overflow-y-auto modal-scrollable pt-1.5 pl-3.5 relative z-10",children:[(0,n.jsx)("div",{className:"-ml-3.5",children:(0,n.jsx)(aJ,{host:{key:A?.key||"main",label:A?.label||"",status:"full",workspaces:t,sessions:e,statusMap:U,onDisconnect:v},busRef:k,actions:{selectSession:e=>{B.includes(e)&&K(e),o?.(e)},selectWorkspace:e=>{(0,t7.e)(),c?.(e)},createSession:d,renameSession:x,deleteSession:p,reorderSession:h,renameWorkspace:b,deleteWorkspace:u,renameHost:y,deleteHost:w},activeSessionId:s,activeWorkspaceId:a,connected:C,fileBus:j,homeDir:N,cwdBySession:S,agentBySession:M,hiddenPaneSessionIds:B,onUnhidePane:K,onAddWorkspace:f,menuAddWorkspace:f,onRowContextMenu:e=>{e.preventDefault(),e.stopPropagation();let t=e.currentTarget.dataset.sid,s=eg(t);es({sessionId:t,left:e.clientX,top:e.clientY,name:s?.name||""})},onRowTouch:{start:e=>{let t,s;t=e.currentTarget.dataset.sid,s=e.touches[0],ev.current=setTimeout(()=>{(0,t7.e)();let e=eg(t);es({sessionId:t,left:s.clientX,top:s.clientY,name:e?.name||""})},500)},move:ey,end:ey},onRowMenu:(e,t,s)=>es({sessionId:e,left:s.left,top:s.bottom+2,name:t}),treeCls:"pl-3.5"})}),L.length>0&&(0,n.jsx)("div",{className:"mt-1 -ml-3.5 border-t border-border-subtle pt-1",children:L.map(e=>(0,n.jsx)(aJ,{host:{...e,onDisconnect:()=>sX.getState().disconnectHost(e.key)},actions:{...sG(e,{onSelectSession:o}),renameHost:y,deleteHost:w},activeSessionId:s,activeWorkspaceId:function(e,t){let s=sO(e,t);if(null!==s)return"_"===s?null:s}(a,e.key),connected:C,hiddenPaneSessionIds:B,onUnhidePane:K,treeCls:"pl-3.5"},e.key))})]}),_&&(0,n.jsx)(rc,{busRef:k,cwd:X,onResume:_,onSelectSession:o,liveSessionIds:V,activeSessionId:s,connected:C}),(Q||g)&&(0,n.jsxs)("div",{className:"p-1.5 border-t border-border-subtle flex-shrink-0 relative z-10",children:[Q&&(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),Y()},className:"w-full flex items-center gap-2 px-2 py-1.5 text-xs text-text-muted hover:text-text hover:bg-surface-2 rounded-[3px] transition-colors",title:$("menu.installApp"),children:[(0,n.jsx)(t3.f5,{size:14}),(0,n.jsx)("span",{children:$("menu.installApp")})]}),g&&(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),g()},className:"w-full flex items-center gap-2 px-2 py-1.5 text-xs text-text-muted hover:text-text hover:bg-surface-2 rounded-[3px] transition-colors",title:$("menu.settings"),children:[(0,n.jsx)(t3.wB,{size:14}),(0,n.jsx)("span",{children:$("menu.settings")})]})]}),z&&(0,n.jsx)(aI,{onClose:()=>I(!1)}),(0,n.jsx)("div",{onPointerDown:e=>{e.stopPropagation(),sS(e,{startWidth:T,onWidth:e=>R?.(e)})},className:"absolute top-0 right-0 bottom-0 w-1 cursor-col-resize hover:bg-brand-500/40 transition-colors z-20"}),et&&(0,n.jsxs)("div",{ref:en,className:"fixed z-[70] menu-popover p-1 min-w-[160px] animate-in fade-in zoom-in-95 duration-100",style:{left:er.left,top:er.top},children:[U[et.sessionId]?.state==="done"&&(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),sc.getState().clearNotification(et.sessionId),es(null)},className:"w-full text-left px-2.5 py-1.5 text-xs text-amber-500 hover:bg-amber-500/10 rounded-[6px] flex items-center gap-2",children:[(0,n.jsx)(t3.aJ,{size:13})," ",$("sessions.markRead")]}),(0,n.jsxs)("button",{onClick:()=>{var e;let t;return e=et.sessionId,t=eg(e)?.name||"",void(eh({sessionId:e,name:t,value:t}),es(null))},className:"w-full text-left px-2.5 py-1.5 text-xs text-text hover:bg-surface-2/80 rounded-[6px] flex items-center gap-2",children:[(0,n.jsx)(t3.gH,{size:13})," ",$("sessions.editName")]}),(0,n.jsxs)("div",{className:"relative group/split",children:[(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)();let e=et.sessionId;!ex&&e&&e!==s&&o?.(e),F(em),es(null)},className:"w-full text-left px-2.5 py-1.5 text-xs text-text hover:bg-surface-2/80 rounded-[6px] flex items-center justify-between",children:[(0,n.jsxs)("span",{className:"flex items-center gap-2",children:[(0,n.jsx)(t3.Wn,{size:13}),(0,n.jsx)("span",{children:$("sessions.split")||"Split"})]}),(0,n.jsx)(t3.c_,{size:12,className:"text-text-muted"})]}),(0,n.jsxs)("div",{className:`hidden group-hover/split:block absolute top-0 menu-popover p-1 min-w-[130px] shadow-xl z-20 ${er.left>window.innerWidth-280?"right-full -mr-0.5":"left-full -ml-0.5"}`,children:[(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)();let e=et.sessionId;!ex&&e&&e!==s&&o?.(e),F(em),es(null)},className:"w-full text-left px-2 py-1.5 text-xs text-text hover:bg-surface-2/80 rounded-[6px] flex items-center justify-between",children:[(0,n.jsxs)("span",{className:"flex items-center gap-1.5",children:[ex?(0,n.jsx)(t3.xq,{size:12}):(0,n.jsx)(t3.h1,{size:12}),(0,n.jsx)("span",{children:ex?$("sessions.restoreSplit")||"Restore Split":$("sessions.maximize")||"Maximize"})]}),(0,n.jsx)("span",{className:"text-[10px] text-text-muted",children:"100%"})]}),(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),et.sessionId&&et.sessionId!==s&&o?.(et.sessionId),ex&&O(em,!1),window.dispatchEvent(new CustomEvent("terminal:splitPreset",{detail:{fraction:2}})),es(null)},className:"w-full text-left px-2 py-1.5 text-xs text-text hover:bg-surface-2/80 rounded-[6px] flex items-center justify-between",children:[(0,n.jsx)("span",{children:"1/2"}),(0,n.jsx)("span",{className:"text-[10px] text-text-muted",children:"50%"})]}),(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),et.sessionId&&et.sessionId!==s&&o?.(et.sessionId),ex&&O(em,!1),window.dispatchEvent(new CustomEvent("terminal:splitPreset",{detail:{fraction:3}})),es(null)},className:"w-full text-left px-2 py-1.5 text-xs text-text hover:bg-surface-2/80 rounded-[6px] flex items-center justify-between",children:[(0,n.jsx)("span",{children:"1/3"}),(0,n.jsx)("span",{className:"text-[10px] text-text-muted",children:"33%"})]}),(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),et.sessionId&&et.sessionId!==s&&o?.(et.sessionId),ex&&O(em,!1),window.dispatchEvent(new CustomEvent("terminal:splitPreset",{detail:{fraction:4}})),es(null)},className:"w-full text-left px-2 py-1.5 text-xs text-text hover:bg-surface-2/80 rounded-[6px] flex items-center justify-between",children:[(0,n.jsx)("span",{children:"1/4"}),(0,n.jsx)("span",{className:"text-[10px] text-text-muted",children:"25%"})]}),(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),et.sessionId&&et.sessionId!==s&&o?.(et.sessionId),ex&&O(em,!1),window.dispatchEvent(new CustomEvent("terminal:splitPreset",{detail:{fraction:"auto"}})),es(null)},className:"w-full text-left px-2 py-1.5 text-xs text-text hover:bg-surface-2/80 rounded-[6px] flex items-center justify-between",children:[(0,n.jsx)("span",{children:"Auto Fit"}),(0,n.jsx)("span",{className:"text-[10px] text-text-muted",children:"Auto"})]}),(0,n.jsx)("div",{className:"h-px bg-border-subtle my-1"}),(0,n.jsx)("button",{type:"button",onClick:()=>{(0,t7.e)(),W(et.sessionId),es(null)},className:"w-full text-left px-2 py-1.5 text-xs text-text hover:bg-surface-2/80 rounded-[6px] flex items-center justify-between",children:(0,n.jsxs)("span",{className:"flex items-center gap-1.5",children:[B.includes(et.sessionId)?(0,n.jsx)(t3.kU,{size:12}):(0,n.jsx)(t3.X_,{size:12}),(0,n.jsx)("span",{children:B.includes(et.sessionId)?$("sessions.showPanel")||"Show":$("sessions.hidePanel")||"Hide"})]})})]})]}),(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),ei(et.sessionId),es(null)},className:"w-full text-left px-2.5 py-1.5 text-xs text-text hover:bg-surface-2/80 rounded-[6px] flex items-center gap-2",children:[(0,n.jsx)(t3._V,{size:13,className:"flex-shrink-0"})," ",$("menu.terminalBackground")]}),(M[et.sessionId]?.endsWith("-ui")||U[et.sessionId]?.conversationId)&&(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)();let e=et.sessionId;M[e]?.endsWith("-ui")?k?.current?.emit("ai:restart",{sessionId:e}):k?.current?.emit("session-resume",{sessionId:e}),es(null)},className:"w-full text-left px-2.5 py-1.5 text-xs text-text hover:bg-surface-2/80 rounded-[6px] flex items-center gap-2",children:[(0,n.jsx)(t3.kt,{size:13})," ",M[et.sessionId]?.endsWith("-ui")?$("sessions.restartAi")||"Restart AI":$("sessions.resumeSession")]}),ed&&(0,n.jsxs)("button",{disabled:!eu,onClick:()=>{(0,t7.e)();let e=et.sessionId;k?.current?.emit("setSessionMode",{sessionId:e,mode:ec?"terminal":"ui"},e=>{e?.success||alert(e?.error||$("sessions.modeSwitchFailed"))}),es(null)},className:`w-full text-left px-2.5 py-1.5 text-xs rounded-[6px] flex items-center gap-2 ${eu?"text-text hover:bg-surface-2/80":"text-text-subtle cursor-not-allowed"}`,children:[(0,n.jsx)(t3.sU,{size:13})," ",ec?$("sessions.openAsTerminal"):$("sessions.openAsUi")]}),(0,n.jsx)("div",{className:"h-px bg-border-subtle my-1"}),(0,n.jsxs)("button",{onClick:()=>{eb({sessionId:et.sessionId,name:et.name}),es(null)},className:"w-full text-left px-2.5 py-1.5 text-xs text-red-500 hover:bg-red-500/10 rounded-[6px] flex items-center gap-2",children:[(0,n.jsx)(t3.TB,{size:13})," ",$("sessions.deleteTitle")]})]}),el&&(0,n.jsx)(rA,{sessionId:el,title:eg(el)?.name,busRef:k,onClose:()=>ei(null)}),ep.sessionId&&(0,n.jsx)(rR,{title:$("sessions.editName"),placeholder:ep.name,value:ep.value,onChange:e=>eh({...ep,value:e}),onSubmit:()=>{let e=ep.value.trim();ep.sessionId&&e&&x?.(ep.sessionId,e),eh({sessionId:null,name:"",value:""})},onClose:()=>eh({sessionId:null,name:"",value:""})}),(0,n.jsx)(t9.A,{isOpen:!!ef,onClose:()=>eb(null),onConfirm:()=>{ef?.sessionId&&p?.(ef.sessionId)},title:$("sessions.deleteTitle"),message:$("sessions.deleteMessage",{name:ef?.name||""}),confirmText:$("common.delete")})]})}),aQ={claude:"Claude",codex:"Codex",kimi:"Kimi",grok:"Grok"};function a0(e){return e<60?"bg-text-muted/40":e<80?"bg-yellow-500":"bg-red-500"}function a1(e,{enabled:t=!0}={}){let[s,n]=(0,r.useState)(null);return(0,r.useEffect)(()=>{if(!t||!e)return;let s=!1,r=()=>{e.current&&e.current.emit("quota:get",{},e=>{!s&&e?.success&&e.providers&&n(e)})};r();let a=rl(r,6e4);return()=>{s=!0,a()}},[e,t]),s}let a2=[["session","5h"],["weekly","wk"],["monthly","mo"]];function a5({usedPct:e}){return(0,n.jsx)("span",{className:"w-10 h-[5px] rounded-full bg-text-muted/20 overflow-hidden flex-shrink-0",children:(0,n.jsx)("span",{className:`block h-full rounded-full transition-all duration-300 ${a0(e)}`,style:{width:`${Math.min(100,Math.max(0,e))}%`}})})}function a3({provider:e}){let[t,s]=(0,r.useState)(!1);return t?(0,n.jsx)("span",{className:"text-text-subtle",children:aQ[e]||e}):(0,n.jsx)("img",{src:s$(e),alt:"",width:14,height:14,onError:()=>s(!0),className:`w-3.5 h-3.5 object-contain ${s_}`})}function a4({label:e,window:t}){return t?(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("span",{className:"w-16 truncate text-text-muted",children:e}),(0,n.jsxs)("span",{className:"w-9 text-right tabular-nums",children:[Math.round(t.usedPercent),"%"]}),(0,n.jsx)(a5,{usedPct:t.usedPercent}),t.resetsAt&&(0,n.jsx)("span",{className:"text-text-subtle whitespace-nowrap",children:function(e){if(!e)return"";let t=new Date(e),s=t.toDateString()===new Date().toDateString(),n=t.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"});return s?n:`${t.toLocaleDateString(void 0,{weekday:"short"})} ${n}`}(t.resetsAt)})]}):null}function a6({p:e,onClose:t}){let s=(0,r.useRef)(null),{t:a}=(0,se.s)();return(0,r.useEffect)(()=>{let e=e=>{s.current?.contains(e.target)||t()},n=e=>{"Escape"===e.key&&t()};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",n),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",n)}},[t]),(0,n.jsxs)("div",{ref:s,className:"absolute bottom-full right-0 mb-2 z-50 w-64 p-3 rounded-brand-lg bg-surface-2 border border-border shadow-lg text-[11px] flex flex-col gap-2",children:[(0,n.jsx)("div",{className:"font-medium",children:aQ[e.provider]||e.provider}),a2.map(([t,s])=>(0,n.jsx)(a4,{label:s,window:e[t]},t)),(e.buckets||[]).map(e=>(0,n.jsx)(a4,{label:e.name,window:e},e.name)),!e.session&&!e.weekly&&!e.monthly&&!(e.buckets||[]).length&&(0,n.jsx)("div",{className:"text-text-muted",children:e.error||a("terminal.quotaNoData")}),e.error&&(e.session||e.weekly||e.monthly)&&(0,n.jsx)("div",{className:"text-text-subtle border-t border-border-subtle pt-1.5",children:e.error})]})}function a8({quota:e}){let[t,s]=(0,r.useState)(null),{t:a}=(0,se.s)();if(!e?.providers)return null;let l=Object.values(e.providers).filter(e=>e&&"ok"===e.status&&(e.session||e.weekly||e.monthly||e.buckets?.length));return l.length?(0,n.jsx)("span",{className:"relative flex items-center gap-1 flex-shrink-0",children:l.map(e=>{let r=e.session||e.weekly||e.monthly||e.buckets[0];return(0,n.jsxs)("span",{className:"relative",children:[(0,n.jsxs)("button",{type:"button",className:"flex items-center gap-1.5 px-1.5 py-0.5 rounded-[2px] hover:bg-white/10 transition-colors",onClick:()=>s(t===e.provider?null:e.provider),title:`${aQ[e.provider]||e.provider} ${a("terminal.quotaUsageTitle")}`,children:[(0,n.jsx)(a3,{provider:e.provider}),(0,n.jsx)(a5,{usedPct:r.usedPercent}),(0,n.jsxs)("span",{className:"tabular-nums",children:[Math.round(r.usedPercent),"%"]})]}),t===e.provider&&(0,n.jsx)(a6,{p:e,onClose:()=>s(null)})]},e.provider)})}):null}function a9({left:e,right:t,className:s="flex"}){return(0,n.jsxs)("div",{style:{height:26},className:`items-center gap-3 px-3 flex-shrink-0 bg-surface border-t border-border-subtle text-[11px] text-text-muted select-none ${s}`,children:[(0,n.jsx)("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:e}),(0,n.jsx)("div",{className:"flex items-center gap-3 flex-shrink-0",children:t})]})}let a7="flex items-center gap-1.5 px-1.5 py-0.5 rounded-[2px] hover:bg-white/10 transition-colors cursor-pointer",le="flex items-center gap-1.5 px-1.5 py-0.5",lt={darwin:"mac",win32:"win",linux:"linux"};function ls({pages:e,activeKey:t}){return(0,n.jsx)("span",{className:"grid justify-items-end",children:e.map(({key:e,node:s})=>(0,n.jsx)("span",{"aria-hidden":e!==t,className:"[grid-area:1/1] flex items-center min-w-0 motion-reduce:transition-none",style:{opacity:+(e===t),transform:e===t?"translateY(0)":"translateY(2px)",pointerEvents:e===t?"auto":"none",transition:"opacity 250ms ease, transform 250ms ease"},children:s},e))})}let ln=(0,r.memo)(function({sessionId:e,fileBus:t,busRef:s,onReveal:a}){let l,i,o,c=tS(t=>t.cwdBySession[e])||"",{branch:d,changedCount:u}=aU(c,t,{enabled:!!c}),m=(i=a1(s,{enabled:!!(l=tS(t=>t.agentBySession[e])||"")}),(o=l?i?.providers?.[l]:null)&&"ok"===o.status&&o.session?{agentId:l,usedPct:o.session.usedPercent}:null),[x,p]=(0,r.useState)(!1),h=c?c.replace(/\\+|\/+$/g,"").split(/[\\/]/).filter(Boolean):[],f=h.length?h.slice(-2).join("/"):"";(0,r.useEffect)(()=>{if(!x)return;let e=setTimeout(()=>p(!1),5e3);return()=>clearTimeout(e)},[x]);let b=[];f&&b.push({key:"path",node:(0,n.jsxs)("button",{type:"button",onClick:a?()=>a(c):void 0,title:c,className:`flex items-center gap-1 min-w-0 font-mono ${a?"hover:text-text":""}`,children:[(0,n.jsx)(t3.vd,{size:10,className:"opacity-70 flex-shrink-0"}),(0,n.jsx)("span",{className:"truncate",children:f})]})}),m&&b.push({key:"quota",node:(0,n.jsxs)("button",{type:"button",onClick:()=>p(!0),className:"flex items-center gap-1.5 flex-shrink-0",children:[(0,n.jsx)("img",{src:s$(m.agentId),alt:"",width:11,height:11,className:`w-[11px] h-[11px] object-contain ${s_}`}),(0,n.jsx)("span",{className:"w-8 h-[4px] rounded-full bg-text-muted/20 overflow-hidden",children:(0,n.jsx)("span",{className:`block h-full rounded-full transition-all duration-300 ${a0(m.usedPct)}`,style:{width:`${Math.min(100,Math.max(0,m.usedPct))}%`}})}),(0,n.jsxs)("span",{className:"tabular-nums text-text-muted",children:[Math.round(m.usedPct),"%"]})]})});let g=m&&m.usedPct>=90?b.findIndex(e=>"quota"===e.key):-1,[v]=function(e,{pinnedIndex:t=-1,paused:s=!1}={}){let[n,a]=(0,r.useState)(0);return((0,r.useEffect)(()=>{if(!(e<2)&&!s&&!(t>=0))return rl(()=>a(e=>e+1),5e3,{fireOnReturn:!1})},[e,s,t]),e)?[t>=0?t:n%e,a]:[0,a]}(b.length,{pinnedIndex:g,paused:x});return(0,n.jsxs)("div",{className:"flex items-center justify-between gap-2 px-3 h-6 border-t border-border-subtle text-[10px] text-text-subtle bg-bg flex-shrink-0",children:[d&&(0,n.jsxs)("span",{className:"flex items-center gap-1 flex-shrink-0",children:[(0,n.jsx)(t3.Zr,{size:10,className:"opacity-70"}),(0,n.jsx)("span",{className:"max-w-[90px] truncate text-text-muted",title:d,children:d}),u>0&&(0,n.jsx)("span",{className:"px-1 leading-tight bg-brand-500/15 text-brand-400 rounded-[2px] font-medium",children:u>999?"999+":u})]}),b.length>0&&(0,n.jsx)(ls,{pages:b,activeKey:b[v]?.key})]})}),lr=(0,r.memo)(function({cwd:e,sessionId:t,fileBus:s,busRef:r,connected:a,sessionState:l,carrier:i,sessionName:o="",agentVersion:c="",platform:d="",homeDir:u=null}){let{t:m}=(0,se.s)(),x=Q(e=>e.connected),p=Q(e=>e.carrier),h=Q(e=>e.connectionMode),f=Q(e=>e.endpoint),b=Q(e=>e.busRef),g=sc(e=>t?e.sessionStatus[t]?.state:"idle"),v=i||p,y=l||g||"idle",w=a1(r||b),k=tS(e=>(e.agentBySession||{})[t])||"",j=o||"—",N=k?s$(k):null,{branch:S,changedCount:C}=aU(e,s,{enabled:!!e}),T=nH(y),R=m("working"===y?"common.statusWorking":"blocked"===y?"common.statusBlocked":"done"===y?"common.statusDone":"common.statusIdle"),E=e?rs(e.replace(/\\/g,"/"),u):"";return(0,n.jsx)(a9,{className:"hidden sm:flex",left:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("span",{className:"flex items-center gap-1.5 flex-shrink-0 max-w-[200px]",children:[N?(0,n.jsx)("img",{src:N,alt:"",className:`w-3.5 h-3.5 object-contain flex-shrink-0 ${s_}`}):(0,n.jsx)(t3.BK,{size:12,className:"opacity-60 flex-shrink-0"}),(0,n.jsx)("span",{className:"truncate font-medium text-text",title:j,children:j})]}),(0,n.jsx)("span",{className:"text-text-subtle flex-shrink-0",children:"›"}),(0,n.jsxs)("span",{className:"flex items-center gap-1.5 min-w-0 flex-shrink",children:[(0,n.jsx)(t3.vd,{size:12,className:"opacity-60 flex-shrink-0"}),(0,n.jsx)("span",{className:"truncate",title:e||"",children:E||m("common.loading")})]}),e&&S&&(0,n.jsxs)("span",{className:"flex items-center gap-1.5 flex-shrink-0",children:[(0,n.jsx)(t3.Zr,{size:12,className:"opacity-60 text-brand-500"}),(0,n.jsx)("span",{className:"truncate max-w-[160px]",title:S,children:S}),C>0&&(0,n.jsx)("span",{className:"px-1 leading-tight bg-brand-500/15 text-brand-400 rounded-[2px] font-medium",children:C>999?"999+":C})]})]}),right:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(a8,{quota:w}),d&&(0,n.jsx)("span",{className:"uppercase tracking-wide",children:lt[d]||d}),c&&(0,n.jsxs)("span",{className:"text-text-subtle",children:["v",c]}),(0,n.jsxs)("span",{className:"flex items-center gap-1.5",title:`${f||""}${v&&"ws"!==v?` (${v})`:""}`,children:[(0,n.jsx)("span",{className:`w-2 h-2 rounded-full ${a??x?"local"===h?"bg-emerald-400":"bg-green-500":"bg-red-500 animate-pulse"}`}),(0,n.jsx)("span",{className:"uppercase tracking-wide",children:v&&"ws"!==v?"STUN":`WS${"local"===h?" \xb7 LOCAL":""}`})]}),(0,n.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,n.jsx)("span",{className:`w-2 h-2 rounded-full term-dot ${T.cls}${T.pulse?` pulse-${T.pulse}`:""}`,style:{background:T.dot}}),(0,n.jsx)("span",{children:R})]})]})})}),la=(e,t,s)=>Math.max(t,Math.min(s,e));function ll(e){let t=window.innerWidth-48,s=window.innerHeight-36;return{...e,x:la(e.x,12-e.w+48,t),y:la(e.y,12,s)}}function li(e){let t=!1,s=null,n=e.length,r=0;for(;r+2<n;){if(0===e[r]&&0===e[r+1]){let a=0;if(1===e[r+2]?a=3:r+3<n&&0===e[r+2]&&1===e[r+3]&&(a=4),a){let n=31&e[r+a];7!==n||s||(s=e.subarray(r+a)),5===n&&(t=!0),r+=a+1;continue}}r++}return{isKey:t,spsBytes:s}}let lo="VideoDecoder"in window&&"EncodedVideoChunk"in window,lc=/^(\d\d-\d\d \d\d:\d\d:\d\d\.\d+)\s+\d+\s+\d+\s+([VDIWEF])\s+([^:]*):\s?(.*)$/;function ld({state:e}){return(0,n.jsx)("span",{className:`w-2 h-2 rounded-full flex-shrink-0 ${"running"===e?"bg-green-500 animate-pulse":"starting"===e?"bg-amber-400 animate-pulse":"bg-text-muted/40"}`})}function lu({devices:e,canManage:t,booting:s,loading:a,error:l,onOpen:i,onStop:o,onRefresh:c,lowPower:d,onLowPowerChange:u,onAddDevice:m,onDeleteAvd:x,onWipeAvd:p,sdkJob:h,onShowSetup:f}){let{t:b}=(0,se.s)(),[g,v]=(0,r.useState)(null),[y,w]=(0,r.useState)(null);return(0,n.jsxs)("div",{className:"w-full max-w-sm mx-auto p-4 space-y-3 fade-in",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("h2",{className:"text-text text-sm font-medium flex-1",children:b("mobile.pickDevice")}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),m?.()},className:"p-1.5 text-text-muted hover:text-brand-500 hover:bg-surface-2 rounded-brand transition-all duration-150 ease-out active:scale-[0.94]",title:b("mobile.addDevice"),"aria-label":b("mobile.addDevice"),children:(0,n.jsx)(t3.FW,{size:15})}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),c?.()},className:"p-1.5 text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-all duration-150 ease-out active:scale-[0.94]",title:b("mobile.refreshDevices"),"aria-label":b("mobile.refreshDevices"),children:(0,n.jsx)(t3.e9,{size:15})})]}),h&&"done"!==h.phase&&"error"!==h.phase&&(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),f?.()},className:"w-full flex items-center gap-2.5 bg-surface rounded-brand-lg px-3 py-2.5 hover:bg-surface-2 transition-colors text-left",children:[(0,n.jsx)(t3.kr,{size:15,className:"text-brand-500 animate-spin flex-shrink-0"}),(0,n.jsxs)("div",{className:"flex flex-col min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"text-xs text-text truncate",children:b(function(e){if(e?.step)return`mobile.provisionStep_${e.step}`;let t=e?.component||"";return t.startsWith("system-images;")?"mobile.provisionStep_image":`mobile.provisionStep_${t}`}(h))}),(0,n.jsx)("span",{className:"text-[10px] text-text-muted",children:"image"===h.kind||"image"===h.step?`${h.percent??0}%`:`${Math.round((h.received||0)/1024/1024)} MB${h.bytesPerSec?` \xb7 ${Math.round(h.bytesPerSec/1024/1024)} MB/s`:""}`})]})]}),0===e.length&&(0,n.jsx)("div",{className:"text-center py-8 space-y-2 fade-in",children:a?(0,n.jsx)(t3.kr,{size:20,className:"text-brand-500 animate-spin mx-auto"}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(t3.wO,{size:26,className:"text-text-muted mx-auto"}),(0,n.jsx)("p",{className:"text-text-muted text-sm",children:b("mobile.noDevicesHint")})]})}),(0,n.jsx)("div",{className:"space-y-1.5",children:e.map((e,r)=>{let a=s?.avdName&&s.avdName===e.avdName,l="running"===e.state;return(0,n.jsxs)("div",{className:"bg-surface rounded-brand-lg overflow-hidden list-rise",style:{"--i":Math.min(r,8)},children:[(0,n.jsxs)("div",{className:"flex items-center gap-2.5 px-3 py-2",children:[(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),i?.(e)},disabled:a,className:"flex items-center gap-2.5 flex-1 min-w-0 text-left disabled:opacity-60 transition-all duration-150 ease-out active:scale-[0.99]",children:["physical"===e.kind?(0,n.jsx)(t3.wO,{size:16,className:"text-brand-500 flex-shrink-0"}):(0,n.jsx)(t3.VA,{size:16,className:"text-brand-500 flex-shrink-0"}),(0,n.jsxs)("div",{className:"flex flex-col min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"text-sm text-text truncate",children:e.name}),(0,n.jsx)("span",{className:"text-xs text-text-muted truncate",children:a?b(`mobile.phase${s.phase.charAt(0).toUpperCase()}${s.phase.slice(1)}`):e.serial||b("mobile.stopped")})]}),(0,n.jsx)(ld,{state:a?"starting":e.state})]}),a?(0,n.jsx)(t3.kr,{size:15,className:"text-brand-500 animate-spin flex-shrink-0"}):l&&e.canStop?(0,n.jsx)("button",{onClick:t=>{t.stopPropagation(),(0,t7.e)(),o?.(e)},className:"p-1.5 text-text-muted hover:text-red-400 hover:bg-surface-2 rounded-brand transition-all duration-150 ease-out active:scale-[0.94] flex-shrink-0",title:b("mobile.stopDevice"),"aria-label":b("mobile.stopDevice"),children:(0,n.jsx)(t3.M6,{size:14})}):l?null:(0,n.jsx)("button",{onClick:t=>{t.stopPropagation(),(0,t7.e)(),i?.(e)},className:"p-1.5 text-text-muted hover:text-brand-500 hover:bg-surface-2 rounded-brand transition-all duration-150 ease-out active:scale-[0.94] flex-shrink-0",title:b("mobile.startDevice"),"aria-label":b("mobile.startDevice"),children:(0,n.jsx)(t3.jG,{size:14})}),t&&"emulator"===e.kind&&e.avdName&&!l&&!a&&(0,n.jsx)("button",{onClick:t=>{t.stopPropagation(),(0,t7.e)(),v(g===e.id?null:e.id)},className:"p-1.5 text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-colors flex-shrink-0","aria-label":b("mobile.avdMenu"),children:(0,n.jsx)(t3.Gv,{size:14})})]}),g===e.id&&(0,n.jsxs)("div",{className:"flex items-center gap-1 px-3 py-1.5 border-t border-border bg-surface-2/50",children:[(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),w({kind:"wipe",avdName:e.avdName,name:e.name}),v(null)},className:"flex items-center gap-1.5 px-2 py-1 text-[11px] text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-colors",children:[(0,n.jsx)(t3.kt,{size:12})," ",b("mobile.avdWipe")]}),(0,n.jsx)("div",{className:"flex-1"}),(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),w({kind:"delete",avdName:e.avdName,name:e.name}),v(null)},className:"flex items-center gap-1.5 px-2 py-1 text-[11px] text-text-muted hover:text-red-400 hover:bg-surface-2 rounded-brand transition-colors",children:[(0,n.jsx)(t3.TB,{size:12})," ",b("mobile.avdDelete")]})]})]},e.id)})}),t&&e.some(e=>"running"!==e.state)&&(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),u?.(!d)},className:"w-full bg-surface rounded-brand-lg px-3 py-2 flex items-center gap-2.5 text-left hover:bg-surface-2 transition-colors",children:[(0,n.jsx)(t3.Kq,{size:15,className:d?"text-brand-500 flex-shrink-0":"text-text-muted flex-shrink-0"}),(0,n.jsxs)("div",{className:"flex flex-col min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"text-sm text-text",children:b("mobile.lowPower")}),(0,n.jsx)("span",{className:"text-xs text-text-muted",children:b("mobile.lowPowerHint")})]}),(0,n.jsx)("span",{className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors flex-shrink-0 ${d?"bg-brand-500":"bg-surface-2"}`,children:(0,n.jsx)("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${d?"translate-x-4":"translate-x-0.5"}`})})]}),l&&(0,n.jsx)("p",{className:"text-red-400 text-xs text-center",children:l}),(0,n.jsx)(t9.A,{isOpen:!!y,onClose:()=>w(null),onConfirm:()=>{y&&("delete"===y.kind?x?.(y.avdName):p?.(y.avdName),w(null))},title:b(y?.kind==="delete"?"mobile.avdDeleteTitle":"mobile.avdWipeTitle"),message:b(y?.kind==="delete"?"mobile.avdDeleteMessage":"mobile.avdWipeMessage",{name:y?.name||""}),confirmText:b(y?.kind==="delete"?"common.delete":"mobile.avdWipe")})]})}function lm(e){if(!Number.isFinite(e)||e<=0)return"";let t=["B","KB","MB","GB"],s=0,n=e;for(;n>=1024&&s<t.length-1;)n/=1024,s++;return`${n>=10?Math.round(n):n.toFixed(1)} ${t[s]}`}function lx({isOpen:e,onClose:t,presets:s,sdkJob:a,onProvision:l,onCancel:i}){let{t:o}=(0,se.s)(),[c,d]=(0,r.useState)(null),[u,m]=(0,r.useState)(null),x=a&&"done"!==a.phase&&"error"!==a.phase?a:null,p=a?.phase==="error"&&"cancelled"!==a.error?a.error:null,h=(0,r.useCallback)(()=>{d(null),m(null),t?.()},[t]);if((0,r.useEffect)(()=>{if(!e||x)return;let t=e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),h())};return window.addEventListener("keydown",t,!0),()=>window.removeEventListener("keydown",t,!0)},[e,x,h]),!e||"u"<typeof document)return null;let f=async e=>{if(c||x)return;(0,t7.e)(),d(e.id),m(e);let t=await l?.(e.id);d(null),t&&h()};return(0,r_.createPortal)((0,n.jsx)("div",{className:"fixed inset-0 z-[100] flex items-center justify-center p-4 bg-black/50 fade-in",onClick:h,children:(0,n.jsxs)("div",{className:"bg-bg border border-border rounded-brand-xl w-full max-w-sm max-h-[80vh] flex flex-col shadow-2xl",onClick:e=>e.stopPropagation(),children:[(0,n.jsxs)("div",{className:"flex items-center gap-2 px-4 py-3 border-b border-border flex-shrink-0",children:[(0,n.jsx)(t3.wO,{size:15,className:"text-brand-500 flex-shrink-0"}),(0,n.jsx)("span",{className:"text-sm text-text flex-1",children:o("mobile.addDevice")}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),h()},className:"p-1 text-text-muted hover:text-text hover:bg-surface-2 rounded-brand",children:(0,n.jsx)(t3.X,{size:15})})]}),(0,n.jsx)("div",{className:"p-3 space-y-1.5 overflow-y-auto modal-scrollable",children:x||p?(0,n.jsx)("div",{className:"flex flex-col items-center gap-3 py-8 px-4 text-center",children:p?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("p",{className:"text-red-400 text-xs",children:p}),(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[u&&(0,n.jsx)("button",{onClick:()=>f(u),className:"px-3 py-1.5 text-xs text-brand-500 bg-brand-500/10 rounded-brand",children:o("common.retry")}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),h()},className:"px-3 py-1.5 text-xs text-text-muted hover:text-text rounded-brand",children:o("common.close")})]})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(t3.kr,{size:20,className:"text-brand-500 animate-spin"}),(0,n.jsx)("p",{className:"text-text text-sm",children:o(function(e){if(e?.step)return`mobile.provisionStep_${e.step}`;let t=e?.component||"";return t.startsWith("system-images;")?"mobile.provisionStep_image":`mobile.provisionStep_${t}`}(x))}),(0,n.jsx)("p",{className:"text-text-muted text-xs",children:"image"===x.kind||"image"===x.step?`${x.percent??0}%`:`${lm(x.received)}${x.total?` / ${lm(x.total)}`:""}${x.bytesPerSec?` \xb7 ${lm(x.bytesPerSec)}/s`:""}`}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),i?.()},className:"px-3 py-1 text-[11px] text-text-muted hover:text-red-400 rounded-brand transition-colors",children:o("common.cancel")})]})}):(s||[]).map(e=>(0,n.jsxs)("button",{onClick:()=>f(e),className:"w-full flex items-center gap-2.5 px-3 py-2.5 bg-surface rounded-brand-lg hover:bg-surface-2 transition-colors text-left",children:["tablet"===e.id?(0,n.jsx)(t3.VA,{size:16,className:"text-brand-500 flex-shrink-0"}):(0,n.jsx)(t3.wO,{size:16,className:"text-brand-500 flex-shrink-0"}),(0,n.jsxs)("div",{className:"flex flex-col min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"text-sm text-text truncate",children:e.label}),(0,n.jsx)("span",{className:"text-[10px] text-text-muted",children:e.ready?o("mobile.presetReady"):o("mobile.presetDownload")})]}),e.ready?(0,n.jsx)(t3.aJ,{size:13,className:"text-green-500 flex-shrink-0"}):(0,n.jsx)(t3.f5,{size:13,className:"text-text-muted flex-shrink-0"})]},e.id))})]})}),document.body)}function lp({apps:e,foreground:t,busy:s,progress:a,error:l,onInstall:i,onLaunch:o,onStopApp:c,onClearData:d,onUninstall:u,onOpenLink:m,onRefresh:x}){let{t:p}=(0,se.s)(),h=(0,r.useRef)(null),[f,b]=(0,r.useState)(!1),[g,v]=(0,r.useState)(""),y=(0,r.useCallback)(e=>{let t=[...e||[]].find(e=>e.name.toLowerCase().endsWith(".apk"));t&&i?.(t)},[i]),w=(0,r.useCallback)(e=>{e.preventDefault(),b(!1),y(e.dataTransfer?.files)},[y]),k="install"===s;return(0,n.jsxs)("div",{className:"h-full overflow-y-auto modal-scrollable p-3 space-y-3",onDragOver:e=>{e.preventDefault(),b(!0)},onDragLeave:()=>b(!1),onDrop:w,children:[(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),h.current?.click()},disabled:k,className:`w-full rounded-brand-lg border border-dashed px-3 py-5 flex flex-col items-center gap-1.5 transition-colors duration-150 ${f?"border-brand-500 bg-brand-500/5":"border-border hover:border-brand-500/50"} disabled:opacity-60`,children:k?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(t3.kr,{size:20,className:"text-brand-500 animate-spin"}),(0,n.jsx)("span",{className:"text-sm text-text",children:p("mobile.installing")}),a>0&&(0,n.jsx)("div",{className:"w-full max-w-[180px] h-1 bg-surface-2 rounded-full overflow-hidden mt-1",children:(0,n.jsx)("div",{className:"h-full bg-brand-500 transition-[width] duration-150",style:{width:`${Math.round(100*a)}%`}})})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(t3._O,{size:20,className:"text-text-muted"}),(0,n.jsx)("span",{className:"text-sm text-text",children:p("mobile.dropApk")}),(0,n.jsx)("span",{className:"text-xs text-text-muted",children:p("mobile.dropApkHint")})]})}),(0,n.jsx)("input",{ref:h,type:"file",accept:".apk,application/vnd.android.package-archive",className:"hidden",onChange:e=>{y(e.target.files),e.target.value=""}}),(0,n.jsxs)("form",{onSubmit:e=>{e.preventDefault(),g.trim()&&(m?.(g.trim()),v(""))},className:"flex items-center gap-1.5",children:[(0,n.jsxs)("div",{className:"flex-1 flex items-center gap-2 bg-surface rounded-brand px-2.5 py-1.5",children:[(0,n.jsx)(t3.vv,{size:14,className:"text-text-muted flex-shrink-0"}),(0,n.jsx)("input",{value:g,onChange:e=>v(e.target.value),placeholder:p("mobile.deepLinkPlaceholder"),className:"flex-1 bg-transparent text-sm text-text placeholder:text-text-muted focus:outline-none min-w-0",autoCapitalize:"none",autoCorrect:"off",spellCheck:!1})]}),(0,n.jsx)("button",{type:"submit",disabled:!g.trim(),className:"px-2.5 py-1.5 text-sm text-text bg-surface hover:bg-surface-2 rounded-brand transition-all duration-150 ease-out active:scale-[0.97] disabled:opacity-40",children:p("common.open")})]}),(0,n.jsxs)("div",{className:"flex items-center gap-2 pt-1",children:[(0,n.jsx)("span",{className:"text-xs text-text-muted flex-1",children:p("mobile.installedApps")}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),x?.()},className:"p-1 text-text-muted hover:text-text rounded-brand transition-colors",title:p("common.refresh"),"aria-label":p("common.refresh"),children:(0,n.jsx)(t3.e9,{size:13})})]}),0===e.length&&(0,n.jsx)("p",{className:"text-text-muted text-xs text-center py-4",children:p("mobile.noApps")}),(0,n.jsx)("div",{className:"space-y-1",children:e.map(e=>{let r=t?.packageName===e.packageName,a=s===e.packageName;return(0,n.jsxs)("div",{className:"bg-surface rounded-brand px-2.5 py-2 flex items-center gap-2",children:[(0,n.jsx)(t3.lP,{size:14,className:r?"text-brand-500 flex-shrink-0":"text-text-muted flex-shrink-0"}),(0,n.jsx)("span",{className:"text-sm text-text truncate flex-1",title:e.packageName,children:e.packageName}),a?(0,n.jsx)(t3.kr,{size:14,className:"text-brand-500 animate-spin flex-shrink-0"}):(0,n.jsxs)("div",{className:"flex items-center gap-0.5 flex-shrink-0",children:[e.launchable&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),o?.(e.packageName)},className:"p-1.5 text-text-muted hover:text-brand-500 hover:bg-surface-2 rounded-brand transition-colors",title:p("mobile.launch"),"aria-label":p("mobile.launch"),children:(0,n.jsx)(t3.jG,{size:13})}),r&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),c?.(e.packageName)},className:"p-1.5 text-text-muted hover:text-amber-400 hover:bg-surface-2 rounded-brand transition-colors",title:p("mobile.forceStop"),"aria-label":p("mobile.forceStop"),children:(0,n.jsx)(t3.M6,{size:13})}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),d?.(e.packageName)},className:"p-1.5 text-text-muted hover:text-amber-400 hover:bg-surface-2 rounded-brand transition-colors",title:p("mobile.clearData"),"aria-label":p("mobile.clearData"),children:(0,n.jsx)(t3.e9,{size:13})}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),u?.(e.packageName)},className:"p-1.5 text-text-muted hover:text-red-400 hover:bg-surface-2 rounded-brand transition-colors",title:p("mobile.uninstall"),"aria-label":p("mobile.uninstall"),children:(0,n.jsx)(t3.TB,{size:13})})]})]},e.packageName)})}),l&&(0,n.jsx)("p",{className:"text-red-400 text-xs",children:l})]})}function lh({logcat:e,apps:t}){let{lines:s,clear:a,minLevel:l,setMinLevel:i,search:o,setSearch:c,packageName:d,setPackageName:u,paused:m,setPaused:x,includeNoise:p,setIncludeNoise:h}=e,{t:f}=(0,se.s)(),b=(0,r.useRef)(null),[g,v]=(0,r.useState)(!0),y=()=>{v(!0)};return(0,r.useLayoutEffect)(()=>{g&&b.current&&(b.current.scrollTop=b.current.scrollHeight)},[s,g]),(0,n.jsxs)("div",{className:"h-full flex flex-col",children:[(0,n.jsxs)("div",{className:"flex items-center gap-1.5 px-2 py-1.5 border-b border-border flex-shrink-0 flex-wrap",children:[(0,n.jsxs)("select",{value:d||"",onChange:e=>{(0,t7.e)(),u(e.target.value||null),y()},className:"bg-surface-2 text-text text-xs rounded-brand px-1.5 py-1 focus:outline-none focus:ring-2 focus:ring-brand-500/40 max-w-[40%]",title:f("mobile.filterByApp"),children:[(0,n.jsx)("option",{value:"",children:f("mobile.allApps")}),t.map(e=>(0,n.jsx)("option",{value:e.packageName,children:e.packageName},e.packageName))]}),(0,n.jsx)("select",{value:l,onChange:e=>{(0,t7.e)(),i(e.target.value),y()},className:"bg-surface-2 text-text text-xs rounded-brand px-1.5 py-1 focus:outline-none focus:ring-2 focus:ring-brand-500/40",title:f("mobile.minLevel"),children:tV.map(e=>(0,n.jsx)("option",{value:e,children:e},e))}),(0,n.jsxs)("div",{className:"flex items-center gap-1 bg-surface-2 rounded-brand px-1.5 py-1 flex-1 min-w-[90px]",children:[(0,n.jsx)(t3.vj,{size:12,className:"text-text-muted flex-shrink-0"}),(0,n.jsx)("input",{value:o,onChange:e=>c(e.target.value),placeholder:f("common.search"),className:"bg-transparent text-xs text-text placeholder:text-text-muted focus:outline-none w-full min-w-0",autoCapitalize:"none",autoCorrect:"off",spellCheck:!1})]}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),x(!m)},className:`p-1.5 rounded-brand transition-colors ${m?"text-brand-500 bg-surface-2":"text-text-muted hover:text-text"}`,title:f(m?"mobile.resumeLog":"mobile.pauseLog"),"aria-label":f(m?"mobile.resumeLog":"mobile.pauseLog"),children:m?(0,n.jsx)(t3.jG,{size:13}):(0,n.jsx)(t3.vR,{size:13})}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),h(!p),y()},className:`p-1.5 rounded-brand transition-colors ${p?"text-amber-400 bg-surface-2":"text-text-muted hover:text-text"}`,title:f(p?"mobile.hideNoise":"mobile.showNoise"),"aria-label":f(p?"mobile.hideNoise":"mobile.showNoise"),children:(0,n.jsx)(t3.dJ,{size:13})}),(0,n.jsx)("button",{onClick:()=>{let e;(0,t7.e)(),e=s.map(e=>`${e.time} ${e.level} ${e.tag}: ${e.message}`).join("\n"),navigator.clipboard?.writeText(e)},className:"p-1.5 text-text-muted hover:text-text rounded-brand transition-colors",title:f("common.clipboardCopy"),"aria-label":f("common.clipboardCopy"),children:(0,n.jsx)(t3.QR,{size:13})}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),a()},className:"p-1.5 text-text-muted hover:text-red-400 rounded-brand transition-colors",title:f("mobile.clearLog"),"aria-label":f("mobile.clearLog"),children:(0,n.jsx)(t3.TB,{size:13})})]}),(0,n.jsxs)("div",{ref:b,onScroll:()=>{let e=b.current;e&&v(e.scrollHeight-e.scrollTop-e.clientHeight<40)},className:"flex-1 overflow-auto modal-scrollable font-mono text-[11px] leading-[1.45] p-2",children:[0===s.length&&(0,n.jsx)("p",{className:"text-text-muted text-xs text-center py-6 font-sans",children:f("mobile.noLogs")}),s.map(e=>(0,n.jsxs)("div",{className:"whitespace-pre-wrap break-all",children:[(0,n.jsx)("span",{className:"text-text-muted/60",children:e.time})," ",(0,n.jsx)("span",{className:tX[e.level]||"text-text",children:e.level})," ",(0,n.jsx)("span",{className:"text-brand-500/70",children:e.tag}),e.tag?": ":"",(0,n.jsx)("span",{className:tX[e.level]||"text-text",children:e.message})]},e.seq))]}),m&&(0,n.jsx)("div",{className:"px-2 py-1 text-[11px] text-amber-400 bg-amber-400/10 flex-shrink-0 text-center",children:f("mobile.logPaused")})]})}function lf({onClose:e,busRef:t,protocolRef:s,connected:a,variant:l="fullscreen"}){let{t:i}=(0,se.s)(),o=(0,r.useRef)(null),[c,d]=(0,r.useState)(null),[u,m]=(0,r.useState)(!1),[x,p]=(0,r.useState)(!1),h=function({busRef:e,connected:t}){let[s,n]=(0,r.useState)([]),[a,l]=(0,r.useState)(!1),[i,o]=(0,r.useState)(null),[c,d]=(0,r.useState)(null),[u,m]=(0,r.useState)(!1),[x,p]=(0,r.useState)(null),h=tS(e=>e.mobileLowPower),f=tS(e=>e.setMobileLowPower),b=(0,r.useCallback)(async()=>{let s=e?.current;if(!s||!t)return[];let r=await tG(s,"mobile:list",{});if(!r?.success)return[];m(!0),l(!!r.canManageEmulators),r.env&&p(r.env.job||null);let a=Array.isArray(r.devices)?r.devices:[];return n(a),a},[e,t]);(0,r.useEffect)(()=>{let s=e?.current;if(!s||!t)return;let n=({avdName:e,phase:t})=>o({avdName:e,phase:t});s.on("mobile:avdProgress",n);let r=e=>{p(e),("done"===e.phase||"error"===e.phase)&&b()};return s.on("mobile:sdkProgress",r),()=>{s.off("mobile:avdProgress",n),s.off("mobile:sdkProgress",r)}},[e,t,b]),(0,r.useEffect)(()=>{if(!t)return;b();let e=setInterval(b,5e3);return()=>clearInterval(e)},[t,b]);let g=(0,r.useCallback)(async t=>{d(null),o({avdName:t,phase:"launching"});let s=await tG(e?.current,"mobile:avdStart",{avdName:t,lowPower:h});return(o(null),await b(),s?.success)?s.serial:(d(s?.error||"Could not start"),null)},[e,b,h]),v=(0,r.useCallback)(async t=>{d(null);let s=await tG(e?.current,"mobile:avdStop",{serial:t});return await b(),s?.success||d(s?.error||"Could not stop"),s?.success},[e,b]),[y,w]=(0,r.useState)([]),k=(0,r.useCallback)(async()=>{let t=await tG(e?.current,"mobile:provisionPresets",{});t?.success&&w(Array.isArray(t.presets)?t.presets:[])},[e]),j=(0,r.useCallback)(async t=>{d(null);let s=await tG(e?.current,"mobile:provision",{presetId:t});return await Promise.all([b(),k()]),!!s?.success||(d(s?.error||"Could not create device"),!1)},[e,b,k]),N=(0,r.useCallback)(async()=>{await tG(e?.current,"mobile:sdkCancel",{}),await b()},[e,b]),S=(0,r.useCallback)(async t=>{let s=await tG(e?.current,"mobile:avdDelete",{avdName:t});return s?.success||d(s?.error||"Could not delete"),await b(),s?.success},[e,b]),C=(0,r.useCallback)(async t=>{let s=await tG(e?.current,"mobile:avdWipe",{avdName:t});return s?.success||d(s?.error||"Could not wipe"),await b(),s?.success},[e,b]);return{devices:s,canManage:a,booting:i,error:c,setError:d,refresh:b,startAvd:g,stopAvd:v,lowPower:h,setLowPower:f,sdkJob:x,presets:y,refreshPresets:k,provision:j,cancelSetup:N,deleteAvd:S,wipeAvd:C,loaded:u}}({busRef:t,connected:a}),{devices:f,canManage:b,booting:g,refresh:v,startAvd:y,stopAvd:w,lowPower:k,setLowPower:j,sdkJob:N,presets:S,refreshPresets:C,provision:T,cancelSetup:R,deleteAvd:E,wipeAvd:_}=h,{serial:$,meta:M,starting:P,error:A,open:z,stop:I}=function({busRef:e,connected:t,devices:s,startAvd:n}){let a=tS(e=>e.mobileSession),l=tS(e=>e.setMobileSession),i=a?.serial??null,o=a?.meta??null,[c,d]=(0,r.useState)(!1),[u,m]=(0,r.useState)(null),x=(0,r.useRef)(!1),p=(0,r.useRef)(new Set);(0,r.useEffect)(()=>{o&&(x.current=!0)},[o]);let h=(0,r.useCallback)(()=>{e?.current?.emit("mobile:stop"),x.current=!1,l(null)},[e,l]),f=(0,r.useCallback)(async t=>{let s=Math.max(window.innerWidth,window.innerHeight),n=window.devicePixelRatio,r=await tG(e?.current,"mobile:start",{serial:t,options:function(e,t,s=1){let n=tU[e]||tU[tq],r=function(e,t=1,s=1){let n=Math.min(1600,Math.max(640,Math.round(e*Math.min(t||1,3)*s)));return n-n%8}(t,s,n.edgeScale),a=r*Math.round(.45*r);return{maxSize:r,bitRate:Math.min(n.maxBitRate,Math.round(a*n.maxFps*n.bitsPerPixel)),maxFps:n.maxFps}}(tq,s,n)});if(!r?.success)throw Error(r?.error||"Failed to start");return x.current=!0,l({serial:t,meta:r.meta}),r.meta},[e,l]),b=(0,r.useCallback)(async e=>{if(e){d(!0),m(null),p.current.add(e.id);try{let t=e.serial||(e.avdName?await n(e.avdName):null);if(!t)throw Error("Device did not start");await f(t)}catch(e){m(e.message)}finally{d(!1)}}},[n,f]);return(0,r.useEffect)(()=>{if(o||c||i)return;let e=s.filter(e=>"running"===e.state);if(1!==e.length||1!==s.length)return;let t=e[0];p.current.has(t.id)||b(t)},[s,o,c,i,b]),(0,r.useEffect)(()=>{let s=e?.current;if(!s||!t)return;let n=({meta:e})=>{e&&l(t=>t?{...t,meta:e}:t)};return s.on("mobile:resized",n),()=>s.off("mobile:resized",n)},[e,t,l]),(0,r.useEffect)(()=>{!t&&x.current&&(x.current=!1,l(null))},[t,l]),{serial:i,meta:o,starting:c,error:u,setError:m,open:b,stop:h}}({busRef:t,connected:a,devices:f,startAvd:y}),{status:L}=function({busRef:e,connected:t,canvasRef:s,meta:n}){let[a,l]=(0,r.useState)("idle"),[i,o]=(0,r.useState)(0),c=(0,r.useRef)(null),d=(0,r.useCallback)(()=>{let t=c.current,s=performance.now();t&&s-t.lastKeyframeReq<1e3||(t&&(t.lastKeyframeReq=s),e?.current?.emit("mobile:keyframe"))},[e]);return(0,r.useEffect)(()=>{let r=e?.current;if(!r||!t||!n||!lo)return;let a={decoder:null,pending:new Map,queue:[],raf:0,sawKey:!1,dropping:!1,lastKeyframeReq:0,ackedSeq:-1,config:null,frameCount:0,fpsAt:performance.now()};c.current=a,l("connecting");let i=()=>{if(a.decoder&&"closed"!==a.decoder.state)try{a.decoder.close()}catch{}for(let e of(a.decoder=null,a.sawKey=!1,a.queue))e.close();a.queue=[]},u=()=>{a.raf=0;let e=s.current;for(;a.queue.length>1;)a.queue.shift()?.close();let t=a.queue.shift();if(!t)return;let n=e?.getContext("2d",{alpha:!1,desynchronized:!0});n&&n.drawImage(t,0,0,e.width,e.height),t.close(),a.frameCount++;let r=performance.now();r-a.fpsAt>=1e3&&(o(Math.round(1e3*a.frameCount/(r-a.fpsAt))),a.frameCount=0,a.fpsAt=r),a.queue.length&&(a.raf=requestAnimationFrame(u))},m=()=>{i(),a.dropping=!0,d()},x=e=>{if(a.decoder?.state==="configured")return!0;i();let t=new VideoDecoder({output:e=>{a.decoder!==t?e.close():(a.queue.length>=3&&a.queue.shift()?.close(),a.queue.push(e),a.raf||(a.raf=requestAnimationFrame(u)))},error:()=>{a.decoder===t&&m()}});try{let s;return t.configure({codec:(s=e=>e.toString(16).padStart(2,"0"),`avc1.${s(e[1])}${s(e[2])}${s(e[3])}`),optimizeForLatency:!0}),a.decoder=t,!0}catch{try{t.close()}catch{}return l("decoder failed"),d(),!1}},p=({data:e,isKey:t,isConfig:s,ptsMs:n})=>{let r=e;if(s){a.config=r;let e=li(r).spsBytes;e&&x(e);return}if(t&&a.decoder?.state!=="configured"){if(!a.config)return void d();let e=li(a.config).spsBytes;if(!e||!x(e))return}if(t&&a.config){let e=new Uint8Array(a.config.byteLength+r.byteLength);e.set(a.config,0),e.set(r,a.config.byteLength),r=e}if(a.dropping){if(!t||a.decoder?.state!=="configured")return void d();a.dropping=!1}if(a.decoder?.state!=="configured"){t||d();return}if(a.decoder.decodeQueueSize>30)return void(a.dropping=!0,d());if(!a.sawKey){if(!t)return void d();a.sawKey=!0,l("streaming")}try{a.decoder.decode(new EncodedVideoChunk({type:t?"key":"delta",timestamp:1e3*n,data:r}))}catch{m()}},h=e=>{e<=a.ackedSeq||(a.ackedSeq=e,r.emit("mobile:ack",{seq:e}))},f=e=>{let t=function(e){let t=e instanceof ArrayBuffer?new Uint8Array(e):e;if(t.byteLength<18)return null;let s=new DataView(t.buffer,t.byteOffset,t.byteLength);if(0xffffffff!==s.getUint32(0))return null;let n=s.getUint8(12);return{frameSeq:s.getUint32(4),chunkIdx:s.getUint16(8),chunkCount:s.getUint16(10),isKey:(1&n)!=0,isConfig:(2&n)!=0,ptsMs:s.getUint32(14),payload:t.slice(18)}}(e);if(!t)return;if(1===t.chunkCount){h(t.frameSeq),p({data:t.payload,isKey:t.isKey,isConfig:t.isConfig,ptsMs:t.ptsMs});return}let s=a.pending.get(t.frameSeq);if(!s)for(let e of(s={chunks:Array(t.chunkCount),received:0,count:t.chunkCount,isKey:t.isKey,isConfig:t.isConfig,ptsMs:t.ptsMs},a.pending.set(t.frameSeq,s),a.pending.keys()))t.frameSeq-e>4&&a.pending.delete(e);if(s.chunks[t.chunkIdx]||(s.chunks[t.chunkIdx]=t.payload,s.received++,s.received!==s.count))return;a.pending.delete(t.frameSeq),h(t.frameSeq);let n=new Uint8Array(s.chunks.reduce((e,t)=>e+t.byteLength,0)),r=0;for(let e of s.chunks)n.set(e,r),r+=e.byteLength;p({data:n,isKey:s.isKey,isConfig:s.isConfig,ptsMs:s.ptsMs})},b=()=>l("ended");return r.on("file-bin",f),r.on("mobile:ended",b),d(),()=>{r.off("file-bin",f),r.off("mobile:ended",b),a.raf&&cancelAnimationFrame(a.raf),i(),a.pending.clear(),c.current=null}},[e,t,s,n,d]),(0,r.useEffect)(()=>{let s=e?.current;if(!s||!t||!n)return;let r=()=>{let e=!document.hidden;s.emit("mobile:visible",{visible:e}),e&&d()};return document.addEventListener("visibilitychange",r),s.emit("mobile:visible",{visible:!document.hidden}),()=>document.removeEventListener("visibilitychange",r)},[e,t,n,d]),{status:lo?a:"unsupported",fps:i,requestKeyframe:d}}({busRef:t,connected:a,canvasRef:o,meta:M}),D=function({busRef:e,canvasRef:t}){let s=(0,r.useRef)(null),n=(0,r.useRef)(null),a=(0,r.useRef)(0),l=(0,r.useCallback)(t=>{e?.current?.emit("mobile:input",t)},[e]),i=(0,r.useCallback)(()=>{a.current=0;let e=n.current;e&&(n.current=null,l({type:"touch",action:"move",...e}))},[l]),o=(0,r.useCallback)(e=>{let s=t.current;if(!s)return null;let n=s.getBoundingClientRect(),r=Math.min(n.width/s.width,n.height/s.height),a=s.width*r,l=s.height*r,i=n.left+(n.width-a)/2,o=n.top+(n.height-l)/2,c=(e.clientX-i)/a,d=(e.clientY-o)/l;return c<0||c>1||d<0||d>1?null:{x:c,y:d}},[t]),c=(0,r.useCallback)(e=>{let t=o(e);t&&(e.currentTarget.setPointerCapture?.(e.pointerId),s.current=t,l({type:"touch",action:"down",...t}))},[l,o]),d=(0,r.useCallback)(e=>{if(!s.current)return;let t=o(e);t&&(n.current=t,a.current||(a.current=requestAnimationFrame(i)))},[i,o]),u=(0,r.useCallback)(e=>{let t=o(e);if(!t)return;e.preventDefault();let s=1===e.deltaMode?16:2===e.deltaMode?400:1,n=e=>Math.max(-16,Math.min(16,-(e*s)/100));l({type:"scroll",...t,hscroll:n(e.deltaX),vscroll:n(e.deltaY)})},[l,o]),m=(0,r.useCallback)(e=>{let t=s.current;t&&(s.current=null,n.current=null,a.current&&(cancelAnimationFrame(a.current),a.current=0),l({type:"touch",action:"up",...o(e)||{x:t.x,y:t.y}}))},[l,o]);return{onPointerDown:c,onPointerMove:d,onPointerUp:m,onPointerCancel:m,onWheel:u,sendKey:(0,r.useCallback)(e=>l({type:"key",name:e}),[l])}}({busRef:t,canvasRef:o}),F=function({busRef:e,protocolRef:t,serial:s,enabled:n}){let[a,l]=(0,r.useState)([]),[i,o]=(0,r.useState)(null),[c,d]=(0,r.useState)(null),[u,m]=(0,r.useState)(0),[x,p]=(0,r.useState)(null),h=(0,r.useCallback)(async()=>{if(!s||!n)return;let t=await tG(e?.current,"mobile:apps",{serial:s});t?.success&&(l(t.apps||[]),o(t.foreground||null))},[e,s,n]);(0,r.useEffect)(()=>{h()},[h]);let f=(0,r.useCallback)(async(t,n,r)=>{d(n),p(null);let a=await tG(e?.current,t,{serial:s,packageName:n});return(d(null),a?.success)?(r&&await h(),!0):(p(a?.error||"Failed"),!1)},[e,s,h]),b=(0,r.useCallback)(e=>f("mobile:launch",e),[f]),g=(0,r.useCallback)(e=>f("mobile:stopApp",e),[f]),v=(0,r.useCallback)(e=>f("mobile:clearApp",e),[f]),y=(0,r.useCallback)(e=>f("mobile:uninstall",e,!0),[f]),w=(0,r.useCallback)(async n=>{if(n&&s){d("install"),p(null),m(0);try{let r=await tG(e?.current,"mobile:apkStage",{name:n.name,size:n.size});if(!r?.success)throw Error(r?.error||"Cannot stage APK");let a=null;if(await tZ({bus:e?.current,protocolRef:t,targetDir:r.targetDir,items:[{file:n,relativePath:r.fileName}],callbacks:{onProgress:(e,t,s)=>m(s?t/s:0),onError:(e,t)=>{a=t}}}),a)throw a;let l=await tG(e?.current,"mobile:install",{serial:s,fileName:r.fileName,launch:!0});if(!l?.success)throw Error(l?.error||"Install failed");return await h(),l.packageName}catch(e){return p(e.message),null}finally{d(null),m(0)}}},[e,t,s,h]),k=(0,r.useCallback)(async t=>{p(null);let n=await tG(e?.current,"mobile:openLink",{serial:s,url:t});return n?.success||p(n?.error||"Could not open link"),n?.success},[e,s]);return{apps:a,foreground:i,busy:c,progress:u,error:x,setError:p,refresh:h,install:w,launch:b,stopApp:g,clearData:v,uninstall:y,openLink:k}}({busRef:t,protocolRef:s,serial:$,enabled:!!M}),O=function({busRef:e,serial:t,active:s,foregroundPackage:n}){let[a,l]=(0,r.useState)([]),[i,o]=(0,r.useState)("I"),[c,d]=(0,r.useState)(""),[u,m]=(0,r.useState)(null),x=(0,r.useRef)(!1);(0,r.useEffect)(()=>{!x.current&&n&&m(n)},[n]);let p=(0,r.useCallback)(e=>{x.current=!0,m(e)},[]),[h,f]=(0,r.useState)(!1),[b,g]=(0,r.useState)(!1),v=(0,r.useRef)(0),y=(0,r.useRef)(!1);(0,r.useEffect)(()=>{y.current=h},[h]);let w=(0,r.useCallback)(()=>l([]),[]);return(0,r.useEffect)(()=>{let n=e?.current;if(!n||!t||!s)return;l([]);let r=({lines:e})=>{!y.current&&Array.isArray(e)&&l(t=>{let s=t.concat(e.map(e=>{var t;let s;return t=v.current++,(s=lc.exec(e))?{seq:t,time:s[1].slice(6),level:s[2],tag:s[3].trim(),message:s[4]}:{seq:t,time:"",level:"V",tag:"",message:e}}));return s.length>5e3?s.slice(s.length-5e3):s})};return n.on("mobile:logcat",r),tG(n,"mobile:logcatStart",{serial:t,minLevel:i,search:c,includeNoise:b,...x.current||u?{packageName:u}:{}}),()=>{n.off("mobile:logcat",r),n.emit("mobile:logcatStop")}},[e,t,s]),(0,r.useEffect)(()=>{if(!s||!t)return;let n=setTimeout(()=>{e?.current?.emit("mobile:logcatFilter",{minLevel:i,search:c,packageName:u,includeNoise:b})},200);return()=>clearTimeout(n)},[i,c,u,b,s,t,e]),{lines:a,clear:w,minLevel:i,setMinLevel:o,search:c,setSearch:d,packageName:u,setPackageName:p,paused:h,setPaused:f,includeNoise:b,setIncludeNoise:g}}({busRef:t,serial:$,active:!!M&&"logs"===c,foregroundPackage:F.foreground?.packageName});(0,r.useEffect)(()=>{let e=o.current;e&&M&&(e.width=M.width,e.height=M.height)},[M]);let B="panel"===l,W=f.find(e=>e.serial===$)||null,K=(0,r.useCallback)(async()=>{m(!1),I(),$&&await w($)},[$,I,w]),H=(0,r.useCallback)(async e=>{e.serial===$&&I(),await w(e.serial)},[$,I,w]),U=(0,r.useCallback)(()=>{B||I(),e?.()},[B,I,e]);if(!M){let e;return(0,n.jsxs)("div",{className:"absolute inset-0 flex flex-col bg-bg",children:[!B&&(0,n.jsxs)("header",{className:"flex items-center gap-2 px-2 py-1.5 border-b border-border flex-shrink-0",children:[(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),U()},className:"p-1.5 text-text hover:bg-surface-2 rounded-brand transition-all duration-150 ease-out active:scale-[0.94]","aria-label":i("common.back"),children:(0,n.jsx)(t3.JG,{size:18})}),(0,n.jsx)(t3.wO,{size:16,className:"text-brand-500 flex-shrink-0"}),(0,n.jsx)("span",{className:"text-sm text-text truncate",children:i("mobile.title")})]}),(0,n.jsx)("div",{className:"flex-1 overflow-y-auto modal-scrollable flex items-center justify-center",children:P||g?(0,n.jsxs)("div",{className:"flex flex-col items-center gap-3 p-6 text-center",children:[(0,n.jsx)(t3.kr,{size:22,className:"text-brand-500 animate-spin"}),(0,n.jsx)("p",{className:"text-text text-sm",children:g?(e=g.phase,i(`mobile.phase${e.charAt(0).toUpperCase()}${e.slice(1)}`)):i("mobile.starting")}),g&&(0,n.jsx)("p",{className:"text-text-muted text-xs",children:g.avdName})]}):lo?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(lu,{devices:f,canManage:b,booting:g,loading:!h.loaded,error:A||h.error,onOpen:z,onStop:H,onRefresh:v,lowPower:k,onLowPowerChange:j,onAddDevice:()=>{C(),p(!0)},onDeleteAvd:E,onWipeAvd:_,sdkJob:N,onShowSetup:()=>p(!0)}),(0,n.jsx)(lx,{isOpen:x,onClose:()=>p(!1),presets:S,sdkJob:N,onProvision:T,onCancel:R})]}):(0,n.jsx)("p",{className:"text-text-muted text-sm max-w-xs text-center p-6",children:i("mobile.unsupportedBrowser")})})]})}return(0,n.jsxs)("div",{className:"absolute inset-0 flex bg-bg",children:[(0,n.jsx)(t9.A,{isOpen:u,onClose:()=>m(!1),onConfirm:K,title:i("mobile.shutdownTitle"),message:i("mobile.shutdownMessage",{name:M.deviceName}),confirmText:i("mobile.shutdownConfirm")}),(0,n.jsxs)("div",{className:"flex-1 min-w-0 relative flex items-center justify-center bg-black",children:[(0,n.jsx)("canvas",{ref:o,onPointerDown:D.onPointerDown,onPointerMove:D.onPointerMove,onPointerUp:D.onPointerUp,onPointerCancel:D.onPointerCancel,onWheel:D.onWheel,className:"max-w-full max-h-full object-contain touch-none"}),"streaming"!==L&&(0,n.jsx)("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:(0,n.jsx)(t3.kr,{size:22,className:"text-brand-500 animate-spin"})}),c&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),d(null)},className:"absolute inset-x-0 top-0 h-16 z-10 cursor-pointer","aria-label":i("mobile.backToScreen")}),c&&(0,n.jsxs)("div",{className:"absolute inset-x-0 bottom-0 top-16 bg-bg border-t border-border flex flex-col shadow-[0_-8px_24px_rgba(0,0,0,0.35)] sheet-rise",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2 px-2.5 py-1.5 border-b border-border flex-shrink-0",children:["apps"===c?(0,n.jsx)(t3.lP,{size:14,className:"text-brand-500 flex-shrink-0"}):(0,n.jsx)(t3.iU,{size:14,className:"text-brand-500 flex-shrink-0"}),(0,n.jsx)("span",{className:"text-xs text-text flex-1 truncate",children:i("apps"===c?"mobile.tabApps":"mobile.tabLogs")}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),d(null)},className:"p-1 text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-colors",title:i("mobile.backToScreen"),"aria-label":i("mobile.backToScreen"),children:(0,n.jsx)(t3.X,{size:14})})]}),"apps"===c?(0,n.jsx)(lp,{apps:F.apps,foreground:F.foreground,busy:F.busy,progress:F.progress,error:F.error,onInstall:F.install,onLaunch:F.launch,onStopApp:F.stopApp,onClearData:F.clearData,onUninstall:F.uninstall,onOpenLink:F.openLink,onRefresh:F.refresh}):(0,n.jsx)(lh,{logcat:O,apps:F.apps})]},c)]}),(0,n.jsxs)("div",{className:"flex flex-col items-center gap-0.5 px-1 py-1.5 pb-safe border-l border-border flex-shrink-0 overflow-y-auto modal-scrollable",children:[(0,n.jsx)(lb,{icon:(0,n.jsx)(t3.lM,{size:15,className:"-rotate-90"}),label:i("mobile.back"),onClick:()=>D.sendKey("back")}),(0,n.jsx)(lb,{icon:(0,n.jsx)(t3.jl,{size:15}),label:i("mobile.home"),onClick:()=>D.sendKey("home")}),(0,n.jsx)(lb,{icon:(0,n.jsx)(t3.M6,{size:14}),label:i("mobile.recents"),onClick:()=>D.sendKey("recents")}),(0,n.jsx)("div",{className:"w-5 h-px bg-border my-1"}),(0,n.jsx)(lb,{icon:(0,n.jsx)(t3.LM,{size:15}),label:i("mobile.power"),onClick:()=>D.sendKey("power")}),(0,n.jsx)("div",{className:"w-5 h-px bg-border my-1"}),(0,n.jsx)(lb,{icon:(0,n.jsx)(t3.lP,{size:15}),label:i("mobile.tabApps"),onClick:()=>d("apps"===c?null:"apps"),active:"apps"===c}),(0,n.jsx)(lb,{icon:(0,n.jsx)(t3.iU,{size:15}),label:i("mobile.tabLogs"),onClick:()=>d("logs"===c?null:"logs"),active:"logs"===c}),(0,n.jsx)("div",{className:"flex-1 min-h-2"}),(0,n.jsx)(lb,{icon:(0,n.jsx)(t3.wO,{size:15}),label:i("mobile.switchDevice"),onClick:I}),W?.canStop&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),m(!0)},className:"p-2 rounded-brand transition-all duration-150 ease-out active:scale-[0.94] flex-shrink-0 text-red-400 hover:bg-red-500/15",title:i("mobile.shutdownDevice"),"aria-label":i("mobile.shutdownDevice"),children:(0,n.jsx)(t3.$o,{size:15})}),!B&&(0,n.jsx)(lb,{icon:(0,n.jsx)(t3.X,{size:15}),label:i("common.close"),onClick:U})]})]})}function lb({icon:e,label:t,onClick:s,active:r=!1}){return(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),s?.()},className:`p-2 rounded-brand transition-all duration-150 ease-out active:scale-[0.94] flex-shrink-0 ${r?"text-brand-500 bg-surface-2":"text-text hover:bg-surface-2"}`,title:t,"aria-label":t,"aria-pressed":r,children:e})}let lg=[{edge:"n",className:"top-0 left-3 right-3 h-1",cursor:"cursor-ns-resize"},{edge:"s",className:"bottom-0 left-3 right-3 h-1",cursor:"cursor-ns-resize"},{edge:"w",className:"top-3 bottom-3 left-0 w-1",cursor:"cursor-ew-resize"},{edge:"e",className:"top-3 bottom-3 right-0 w-1",cursor:"cursor-ew-resize"},{edge:"nw",className:"top-0 left-0 w-3 h-3",cursor:"cursor-nwse-resize"},{edge:"ne",className:"top-0 right-0 w-3 h-3",cursor:"cursor-nesw-resize"},{edge:"sw",className:"bottom-0 left-0 w-3 h-3",cursor:"cursor-nesw-resize"},{edge:"se",className:"bottom-0 right-0 w-3 h-3",cursor:"cursor-nwse-resize"}];function lv({busRef:e,protocolRef:t,connected:s,pinSlot:a=null}){let{t:l}=(0,se.s)(),i=tS(e=>e.mobileMode),o=tS(e=>e.mobileFloatRect),c=tS(e=>e.setMobileOpen),d=tS(e=>e.setMobileSession),u=tS(e=>e.setMobileMode),m=function({rect:e,onChange:t,enabled:s}){let[n,a]=(0,r.useState)(()=>{let t,s;return e?ll(e):(t=eu,s=Math.min(ep,window.innerHeight-48),{x:Math.max(12,window.innerWidth-t-24),y:Math.max(12,window.innerHeight-s-24),w:t,h:s})}),[l,i]=(0,r.useState)(!1),o=(0,r.useRef)(null),c=(0,r.useRef)(n),d=(0,r.useCallback)(e=>{c.current=e,a(e)},[]);(0,r.useEffect)(()=>{if(!s)return;let e=()=>{let e=c.current;if(!e)return;let t=Math.min(e.h,window.innerHeight-24);d(ll({...e,h:t}))};return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[s,d]);let u=(0,r.useCallback)((e,t)=>{(null==e.button||0===e.button)&&(e.preventDefault(),e.currentTarget.setPointerCapture?.(e.pointerId),o.current={mode:t,pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,origin:n},i(!0))},[n]),m=(0,r.useCallback)(e=>{let t=o.current;if(!t||t.pointerId!==e.pointerId)return;if("mouse"===e.pointerType&&0===e.buttons)return void x(e);let s=e.clientX-t.startX,n=e.clientY-t.startY;if("move"===t.mode)return void d(ll({...t.origin,x:t.origin.x+s,y:t.origin.y+n}));let{origin:r,mode:a}=t,l=a.includes("w"),i=a.includes("n"),c=l||a.includes("e"),u=i||a.includes("s"),m=window.innerHeight-24,p=i?r.y+r.h-12:m,h=l?r.x+r.w-12:ex,f=c?la(l?r.w-s:r.w+s,em,Math.min(ex,h)):r.w,b=u?la(i?r.h-n:r.h+n,eh,Math.min(m,p)):r.h;d({x:l?r.x+(r.w-f):r.x,y:i?r.y+(r.h-b):r.y,w:f,h:b})},[d]),x=(0,r.useCallback)(e=>{let s=o.current;s&&s.pointerId===e.pointerId&&(o.current=null,i(!1),c.current&&t?.(c.current))},[t]);return(0,r.useEffect)(()=>{if(!l)return;let e=()=>{o.current=null,i(!1),c.current&&t?.(c.current)};return window.addEventListener("blur",e),()=>window.removeEventListener("blur",e)},[l,t]),{rect:n,dragging:l,onDragHandlePointerDown:e=>u(e,"move"),onResizeHandlePointerDown:e=>t=>u(t,e),onPointerMove:m,onPointerUp:x,onPointerCancel:x}}({rect:o,onChange:tS(e=>e.setMobileFloatRect),enabled:"float"===i}),x=(0,r.useCallback)(()=>{e?.current?.emit("mobile:stop"),d(null),c(!1)},[e,d,c]),p="pin"===i,h=r=>(0,n.jsxs)("div",{className:"flex flex-col h-full w-full bg-bg overflow-hidden",children:[(0,n.jsxs)("div",{className:"flex items-center gap-0.5 px-1.5 py-1 border-b border-border bg-surface flex-shrink-0",children:[(0,n.jsxs)("div",{className:`flex items-center gap-1 flex-1 min-w-0 ${r?"cursor-grab active:cursor-grabbing":""}`,onPointerDown:r?m.onDragHandlePointerDown:void 0,children:[r&&(0,n.jsx)(t3.f2,{size:13,className:"text-text-muted flex-shrink-0"}),(0,n.jsx)("span",{className:"text-xs text-text-muted select-none truncate",children:l("mobile.title")})]}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),u(p?"float":"pin")},className:`p-1.5 rounded-brand transition-colors ${p?"text-brand-500 bg-surface-2":"text-text-muted hover:text-text hover:bg-surface-2"}`,title:p?l("mobile.modeFloat"):l("mobile.modePin"),"aria-label":p?l("mobile.modeFloat"):l("mobile.modePin"),"aria-pressed":p,children:(0,n.jsx)(t3.jz,{size:13})}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),x()},className:"p-1.5 text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-colors",title:l("common.close"),"aria-label":l("common.close"),children:(0,n.jsx)(t3.X,{size:13})})]}),(0,n.jsx)("div",{className:"flex-1 min-h-0 relative",children:(0,n.jsx)(lf,{busRef:e,protocolRef:t,connected:s,variant:"panel",onClose:x})})]});if(p)return a?(0,r_.createPortal)(h(!1),a):null;let f=m.rect;return f?(0,r_.createPortal)((0,n.jsxs)("div",{className:"fixed z-40 flex flex-col rounded-brand-lg overflow-hidden border border-border shadow-2xl bg-bg",style:{left:f.x,top:f.y,width:f.w,height:f.h},onPointerMove:m.onPointerMove,onPointerUp:m.onPointerUp,onPointerCancel:m.onPointerCancel,children:[h(!0),lg.map(({edge:e,className:t,cursor:s})=>(0,n.jsx)("div",{onPointerDown:m.onResizeHandlePointerDown(e),className:`absolute ${t} ${s}`,"aria-label":l("mobile.resize")},e))]}),document.body):null}let ly=e=>(e||"").split("/").filter(Boolean).pop()||e;function lw(e,t){return e?e.endsWith("/")?`${e}${t}`:`${e}/${t}`:t}function lk(e){let t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function lj(e){if(!e)return"";let t=e.split("/").filter(Boolean);return t[t.length-1]||e}function lN({dirs:e,fileBus:t,onDirsChanged:s,enabled:n=!0,debounceMs:a=300}){let l=(0,r.useRef)(new Set),i=(0,r.useRef)(s);(0,r.useEffect)(()=>{i.current=s},[s]);let{watchDir:o,unwatchDir:c,onFileChange:d}=t||{},u=e.join("\n");(0,r.useEffect)(()=>{if(!n||!o||!c)return;let e=!0,t=l.current,s=new Set,r=null,m=new Set([...u?u.split("\n"):[]].sort((e,t)=>t.split("/").length-e.split("/").length).slice(0,40)),x=()=>{if(r=null,!e||!s.size)return;let t=[...s];s.clear(),i.current?.(t)},p=async()=>{for(let e of t)m.has(e)||(t.delete(e),c(e));for(let s of m){if(t.has(s))continue;t.add(s);let n=await o(s);e&&n?.watching!==!1||t.delete(s)}},h=d?.(({type:e,path:t})=>{if(!t)return;let n="flooded"===e?t:t.slice(0,t.lastIndexOf("/"))||"/";m.has(n)&&(s.add(n),r||(r=setTimeout(x,a)))})||(()=>{});return p(),()=>{for(let s of(e=!1,clearTimeout(r),h(),t))c(s);t.clear()}},[u,n,a,o,c,d])}function lS(){let[e,t]=(0,r.useState)(()=>"u"<typeof document||!document.hidden);return(0,r.useEffect)(()=>{let e=()=>t(!document.hidden);return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)},[]),e}function lC(e,t=""){if(!e?.success)return{};let s=e.files||e.status||[],n={};for(let e of s){let s=e?.path||e?.file,r=e?.status||e?.code;if(!s||!r)continue;n[t+s]=r;let a=s.split("/");for(let e=1;e<a.length;e++){let s=t+a.slice(0,e).join("/");n[s]||(n[s]="folder-changed")}}return n}async function lT(e,t){let s=await e.gitStatus(t);if(s?.success)return{hasGit:!0,map:lC(s)};let n=await e.gitScanRepos?.(t),r=(n?.success?n.repos:[])||[],a=await Promise.all(r.map(async t=>{let s=String(t.relPath||"").split("\\").join("/");if(!s)return null;let n=await e.gitStatus(t.path);if(!n?.success)return null;let r=lC(n,`${s}/`);return Object.keys(r).length&&(r[s]||="folder-changed"),r})),l=Object.assign({},...a.filter(Boolean));return{hasGit:a.some(Boolean),map:l}}function lR(){try{let e=window.localStorage.getItem(tb),t=e?JSON.parse(e):{};return Array.isArray(t)?{legacy:t}:t}catch{return{}}}function lE(){try{let e=window.localStorage.getItem(tg);if(null===e)return!0;return!1!==JSON.parse(e)}catch{return!0}}let l_={created:"fileExplorer:fileCreated",deleted:"fileExplorer:fileDeleted",renamed:"fileExplorer:fileRenamed"};function l$(e){window.dispatchEvent(new CustomEvent(l_[e]))}let{xT:lM,Qm:lP,Pv:lA}=JSON.parse('{"xT":{"js":"js","mjs":"js","cjs":"js","jsx":"reactjs","ts":"typescript","tsx":"reactts","json":"json","json5":"json5","yml":"yaml","yaml":"yaml","toml":"toml","xml":"xml","ini":"ini","env":"dotenv","md":"markdown","markdown":"markdown","mdx":"mdx","pdf":"pdf","csv":"text","html":"html","css":"css","scss":"scss","sass":"sass","less":"less","styl":"stylus","vue":"vue","svelte":"svelte","astro":"astro","py":"python","pyw":"python","rb":"ruby","php":"php","go":"go","rs":"rust","java":"java","kt":"kotlin","swift":"swift","scala":"scala","cljs":"clojure","ex":"elixir","erl":"erlang","hs":"haskell","ml":"ocaml","dart":"dartlang","lua":"lua","r":"r","c":"c","h":"c","cpp":"cpp","hpp":"cpp","cs":"csharp","m":"objectivec","sh":"shell","bash":"shell","zsh":"shell","fish":"shell","ps1":"powershell","bat":"bat","sql":"sql","gql":"graphql","proto":"protobuf","png":"image","jpg":"image","jpeg":"image","gif":"image","webp":"image","ico":"image","bmp":"image","svg":"svg","avif":"image","tiff":"image","mp4":"video","m4v":"video","webm":"video","mov":"video","mkv":"video","avi":"video","mp3":"audio","wav":"audio","ogg":"audio","flac":"audio","m4a":"audio","aac":"audio","zip":"zip","tar":"zip","gz":"zip","tgz":"zip","rar":"zip","7z":"zip","bz2":"zip","xz":"zip","jar":"jar","log":"log","diff":"diff","patch":"diff","woff":"font","woff2":"font","ttf":"font","eot":"font","otf":"font","db":"datadog","sqlite":"sqlite","sqlite3":"sqlite","jsonc":"json","cfg":"ini","conf":"ini","txt":"text","htm":"html","kts":"kotlin","clj":"clojure","exs":"elixir","cc":"cpp","cxx":"cpp","graphql":"graphql","tif":"image"},"Qm":{".editorconfig":"editorconfig",".env":"dotenv",".gitattributes":"git",".gitignore":"git",".npmrc":"npm","docker-compose.yaml":"docker","docker-compose.yml":"docker","dockerfile":"docker","license":"license","makefile":"gnu","package-lock.json":"npm","package.json":"npm","tsconfig.json":"typescript"},"Pv":{"src":"src","source":"src","sources":"src","lib":"library","libs":"library","library":"library","app":"app","apps":"app","application":"app","component":"component","components":"component","page":"view","pages":"view","view":"view","views":"view","html":"view","model":"model","models":"model","controller":"controller","controllers":"controller","handler":"controller","handlers":"controller","route":"route","routes":"route","router":"route","routers":"route","public":"public","assets":"images","images":"images","image":"images","img":"images","icon":"images","icons":"images","font":"fonts","fonts":"fonts","style":"style","styles":"style","css":"style","docs":"docs","doc":"docs","test":"test","tests":"test","__tests__":"test","spec":"test","specs":"test","coverage":"test","util":"tools","utils":"tools","tool":"tools","tools":"tools","helpers":"tools","helper":"tools","script":"script","scripts":"script","config":"config","configs":"config","configuration":"config",".github":"github",".git":"git",".vscode":"vscode",".idea":"idea","node_modules":"node","bower_components":"bower","dist":"dist","out":"dist","export":"dist","exports":"dist","build":"dist","target":"dist","api":"api","apis":"api","server":"server","services":"server","service":"server","locale":"locale","locales":"locale","i18n":"locale","lang":"locale","languages":"locale","bin":"azurepipelines",".bin":"azurepipelines","middleware":"middleware","middlewares":"middleware","store":"redux","stores":"redux","hook":"hook","hooks":"hook","types":"typescript","typings":"typescript","@types":"typescript","interface":"interfaces","interfaces":"interfaces","theme":"theme","themes":"theme","layout":"view","layouts":"view","ios":"ios","static":"public","asset":"images","documentation":"docs","__specs__":"test","state":"redux","type":"typescript","constant":"tools","constants":"tools","core":"src","main":"src","android":"android"}}'),lz="/icons/file-types",lI="/icons/folder-types",lL=`${lz}/default.svg`,lD=`${lI}/default.svg`,lF=`${lI}/default-open.svg`;function lO(e,t=!1){let s=lA[(e||"").toLowerCase()];return s?{src:t?`${lI}/${s}-open.svg`:`${lI}/${s}.svg`,alt:s}:{src:t?lF:lD,alt:"folder"}}function lB(e,t=16){let{src:s,alt:r}=function(e){if(!e)return{src:lL,alt:"file"};if("folder"===e.type)return lO(e.name,!1);let t=(e.name||"").toLowerCase(),s=function(e){if(!e)return"";let t=e.toLowerCase(),s=t.lastIndexOf(".");return s<=0?t:t.slice(s+1)}(e.name);if(lP[t]){let e=lP[t];return{src:`${lz}/${e}.svg`,alt:e}}if(lM[s]){let e=lM[s];return{src:`${lz}/${e}.svg`,alt:e}}return{src:lL,alt:"file"}}(e);return(0,n.jsx)("img",{src:s,alt:r,width:t,height:t,className:"pointer-events-none select-none",draggable:"false"})}let lW=e=>e?to:ti,lK=(e,t=!1)=>{let s=lW(t);return s.indentBase+e*s.indentStep};function lH({status:e}){return e?"folder-changed"===e?(0,n.jsx)("span",{className:"ml-auto mr-2 w-1.5 h-1.5 rounded-full bg-blue-400/70"}):(0,n.jsx)("span",{className:`ml-auto mr-2 text-[10px] font-semibold ${tl[e]||"text-text-muted"}`,children:e}):null}function lU({depth:e,compact:t=!1}){return(0,n.jsx)("div",{className:"text-[11px] text-text-muted italic py-0.5 pr-2",style:{paddingLeft:lK(e,t)},children:"Showing first 300 entries — use search for the rest."})}let lq=(0,r.memo)(function({file:e,depth:t,isFolder:s,isExpanded:r,isLoading:a,isActive:l,isSelected:i,isRenaming:o,isDragOver:c,isCut:d,gitStatus:u,renameValue:m,renameInputRef:x,onRenameChange:p,onRenameSubmit:h,onRenameCancel:f,onToggleFolder:b,onClick:g,onContextMenu:v,onTouchStart:y,onTouchEnd:w,onDragStart:k,onDragOver:j,onDragLeave:N,onDrop:S,compact:C=!1,children:T}){let R=lW(C);return(0,n.jsxs)("div",{children:[(0,n.jsxs)("div",{"data-path":e.path,draggable:!o,onDragStart:t=>k(t,e),onDragOver:t=>j(t,e),onDragLeave:()=>N(e),onDrop:t=>S(t,e),className:`group relative flex items-center gap-1 rounded-[3px] mx-0.5 pr-2 cursor-pointer select-none ${R.text} ${R.padY} ${d?"opacity-50":""} ${c?"bg-brand-500/30 ring-1 ring-brand-500":i?"bg-brand-500/25":l?"bg-brand-500/15":"hover:bg-surface-2"}`,style:{paddingLeft:lK(t,C)},onContextMenu:t=>v(t,e),onTouchStart:t=>y(t,e),onTouchEnd:w,onTouchMove:w,onClick:t=>!o&&g(e,t),children:[s?(0,n.jsx)("span",{onClick:t=>{t.stopPropagation(),b(e)},className:"flex items-center justify-center w-4 h-4 text-text-muted",children:a?(0,n.jsx)(t3.Ay,{name:"Loader2",size:R.chevron-2,className:"animate-spin"}):(0,n.jsx)(t3.Ay,{name:"ChevronRight",size:R.chevron,className:`transition-transform duration-150 ${r?"rotate-90":""}`})}):(0,n.jsx)("span",{className:"w-4 h-4"}),(0,n.jsx)("span",{className:"shrink-0",children:s?function(e,t=!1,s=16){let{src:r,alt:a}=lO(e,t);return(0,n.jsx)("img",{src:r,alt:a,width:s,height:s,className:"pointer-events-none select-none",draggable:"false"})}(e.name,r,R.icon):lB(e,R.icon)}),o?(0,n.jsx)("input",{ref:x,value:m,onChange:e=>p(e.target.value),onClick:e=>e.stopPropagation(),onBlur:h,onKeyDown:e=>{"Enter"===e.key?h():"Escape"===e.key&&f()},className:`flex-1 bg-surface-3 text-text ${R.text} px-1 py-0.5 rounded outline-none border border-brand-500`}):(0,n.jsx)("span",{className:`flex-1 truncate text-text ${tl[u]||""}`,title:e.name,children:e.name}),!o&&(0,n.jsx)(lH,{status:u}),!o&&(0,n.jsx)("div",{className:"absolute top-1/2 -translate-y-1/2 flex items-center pl-2 pr-1 rounded-[3px] bg-surface-2 opacity-0 group-hover:opacity-100 transition-opacity",style:{right:u?"folder-changed"===u?22:32:4},children:(0,n.jsx)("button",{onClick:t=>v(t,e),className:"p-0.5 text-text-muted hover:text-text",children:(0,n.jsx)(t3.Ay,{name:"MoreHorizontal",size:R.chevron})})})]}),T]})});async function lV(e,t,s){let n=t?`${t}/${e.name}`:e.name;if(e.isFile){let t=await new Promise((t,s)=>e.file(t,s));s.push({file:t,relativePath:n})}else if(e.isDirectory){var r;for(let t of(await (r=e.createReader(),new Promise(e=>{let t=[],s=()=>r.readEntries(n=>{n.length?(t.push(...n),s()):e(t)},()=>e(t));s()}))))await lV(t,n,s)}}async function lX(e){let t=[],s=[...e.items||[]].map(e=>e.webkitGetAsEntry?.()).filter(Boolean);if(s.length)for(let e of s)await lV(e,"",t);else for(let s of e.files||[])t.push({file:s,relativePath:s.name});return t}let lG="fixed inset-0 z-50 flex items-center justify-center p-4",lJ="w-full px-3 py-2 bg-surface-2 rounded-brand text-text focus:outline-none focus:ring-2 focus:ring-brand-500/40 transition-all duration-150 ease-out",lY="flex-1 py-2 bg-surface-2 text-text rounded-brand hover:bg-surface-3 transition-all duration-150 ease-out active:scale-[0.98]",lZ="flex-1 py-2 bg-brand-500 text-white rounded-brand hover:bg-brand-600 transition-all duration-150 ease-out active:scale-[0.98]";function lQ({label:e,ratio:t}){return(0,n.jsxs)("div",{className:"bg-brand-500/10 border-b border-brand-500/30 px-4 py-2 text-text text-xs flex items-center gap-2",children:[(0,n.jsx)(t3.kr,{className:"animate-spin flex-shrink-0",size:14}),(0,n.jsx)("span",{className:"truncate flex-1",children:e}),(0,n.jsx)("div",{className:"w-16 h-1.5 bg-surface-2 rounded-full overflow-hidden flex-shrink-0",children:(0,n.jsx)("div",{className:"h-full bg-brand-500 transition-all",style:{width:`${Math.round(100*(t||0))}%`}})})]})}function l0({query:e,loading:t,onChange:s,onClose:r,compact:a=!1}){let{t:l}=(0,se.s)();return a?(0,n.jsx)("div",{className:"px-2 py-1.5 border-b border-border-subtle flex-shrink-0",children:(0,n.jsxs)("div",{className:"relative",children:[(0,n.jsx)(t3.vj,{size:14,className:"absolute left-2 top-1/2 -translate-y-1/2 text-text-subtle pointer-events-none"}),(0,n.jsx)("input",{type:"text",value:e,onChange:e=>s(e.target.value),placeholder:l("files.searchPlaceholder"),className:"w-full min-w-0 bg-surface-2 border border-border rounded-brand pl-7 pr-7 h-8 text-xs text-text placeholder-text-subtle focus:outline-none focus:border-brand-500",autoFocus:!0}),t?(0,n.jsx)(t3.kr,{size:14,className:"absolute right-2 top-1/2 -translate-y-1/2 animate-spin text-brand-500"}):(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),r()},className:"absolute right-1 top-1/2 -translate-y-1/2 p-1 text-text-subtle hover:text-text",children:(0,n.jsx)(t3.X,{size:14})})]})}):(0,n.jsxs)("div",{className:"bg-surface-2 px-4 py-2 flex items-center gap-2 flex-shrink-0",children:[(0,n.jsx)(t3.vj,{className:"text-text-muted flex-shrink-0",size:20}),(0,n.jsx)("input",{type:"text",value:e,onChange:e=>s(e.target.value),placeholder:l("files.searchPlaceholder"),className:"flex-1 min-w-0 w-0 bg-transparent text-text placeholder-text-subtle focus:outline-none",autoFocus:!0}),t&&(0,n.jsx)(t3.kr,{className:"animate-spin text-brand-500",size:16}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),r()},className:"p-1 text-text-muted hover:text-text transition-colors",children:(0,n.jsx)(t3.X,{size:20})})]})}function l1({type:e,name:t,onTypeChange:s,onNameChange:a,onSubmit:l,onPickFile:i,onPickFolder:o,onClose:c}){let{t:d}=(0,se.s)(),[u]=(0,r.useState)(()=>"u">typeof document&&"webkitdirectory"in document.createElement("input")),m="upload"===e;return(0,r.useEffect)(()=>{let e=e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),c())};return window.addEventListener("keydown",e,!0),()=>window.removeEventListener("keydown",e,!0)},[c]),(0,n.jsxs)("div",{className:lG,children:[(0,n.jsx)("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-[2px]",onClick:c}),(0,n.jsxs)("div",{className:"relative card-elev w-full max-w-sm my-auto max-h-[min(85%,calc(var(--app-height,85vh)-2rem))] overflow-y-auto",children:[(0,n.jsx)("div",{className:"px-4 py-3",children:(0,n.jsx)("h3",{className:"text-text font-semibold",children:d("files.createNew")})}),(0,n.jsxs)("div",{className:"p-4 space-y-4",children:[(0,n.jsxs)("div",{className:"flex gap-2",children:[(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),s("file")},className:`flex-1 py-2 rounded-brand transition flex items-center justify-center gap-2 ${"file"===e?"bg-brand-500 text-white":"bg-surface-2 text-text"}`,children:[(0,n.jsx)(t3.ZH,{size:16,className:"text-text-subtle"})," ",d("files.file")]}),(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),s("folder")},className:`flex-1 py-2 rounded-brand transition flex items-center justify-center gap-2 ${"folder"===e?"bg-brand-500 text-white":"bg-surface-2 text-text"}`,children:[(0,n.jsx)(t3.vd,{size:16,className:"text-orange-500/70"})," ",d("files.folder")]}),(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),s("upload")},className:`flex-1 py-2 rounded-brand transition flex items-center justify-center gap-2 ${m?"bg-brand-500 text-white":"bg-surface-2 text-text"}`,children:[(0,n.jsx)(t3._O,{size:16,className:"text-brand-500"})," ",d("common.upload")]})]}),m?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),i()},className:`${lZ} flex items-center justify-center gap-2`,children:[(0,n.jsx)(t3.ZH,{size:16})," ",d("files.pickFile")]}),u&&(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),o()},className:`${lY} flex items-center justify-center gap-2`,children:[(0,n.jsx)(t3.vd,{size:16})," ",d("files.pickFolder")]}),(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),c()},className:`${lY} flex items-center justify-center gap-1.5`,children:[(0,n.jsx)("span",{children:d("common.cancel")}),(0,n.jsx)("kbd",{className:"hidden sm:inline-flex items-center text-[10px] font-mono px-1 py-0.5 rounded bg-surface-3 text-text-muted leading-none",children:"Esc"})]})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("input",{type:"text",value:t,onChange:e=>a(e.target.value),onKeyDown:e=>"Enter"===e.key&&l(),placeholder:d("file"===e?"files.placeholderFile":"files.placeholderFolder"),className:lJ,autoFocus:!0}),(0,n.jsxs)("div",{className:"flex gap-2",children:[(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),c()},className:`${lY} flex items-center justify-center gap-1.5`,children:[(0,n.jsx)("span",{children:d("common.cancel")}),(0,n.jsx)("kbd",{className:"hidden sm:inline-flex items-center text-[10px] font-mono px-1 py-0.5 rounded bg-surface-3 text-text-muted leading-none",children:"Esc"})]}),(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),l()},className:`${lZ} flex items-center justify-center gap-1.5`,children:[(0,n.jsx)("span",{children:d("common.create")}),(0,n.jsx)("kbd",{className:"hidden sm:inline-flex items-center justify-center w-4 h-4 rounded bg-white/20 text-white",children:(0,n.jsx)(t3.Lt,{size:10,strokeWidth:2.5})})]})]})]})]})]})]})}function l2({value:e,onChange:t,onSubmit:s,onClose:a}){let{t:l}=(0,se.s)();return(0,r.useEffect)(()=>{let e=e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),a())};return window.addEventListener("keydown",e,!0),()=>window.removeEventListener("keydown",e,!0)},[a]),(0,n.jsxs)("div",{className:lG,children:[(0,n.jsx)("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-[2px]",onClick:a}),(0,n.jsxs)("div",{className:"relative card-elev w-full max-w-sm my-auto max-h-[min(85%,calc(var(--app-height,85vh)-2rem))] overflow-y-auto",children:[(0,n.jsx)("div",{className:"px-4 py-3",children:(0,n.jsx)("h3",{className:"text-text font-semibold",children:l("files.rename")})}),(0,n.jsxs)("div",{className:"p-4 space-y-4",children:[(0,n.jsx)("input",{type:"text",value:e,onChange:e=>t(e.target.value),onKeyDown:e=>"Enter"===e.key&&s(),className:lJ,autoFocus:!0}),(0,n.jsxs)("div",{className:"flex gap-2",children:[(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),a()},className:`${lY} flex items-center justify-center gap-1.5`,children:[(0,n.jsx)("span",{children:l("common.cancel")}),(0,n.jsx)("kbd",{className:"hidden sm:inline-flex items-center text-[10px] font-mono px-1 py-0.5 rounded bg-surface-3 text-text-muted leading-none",children:"Esc"})]}),(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),s()},className:`${lZ} flex items-center justify-center gap-1.5`,children:[(0,n.jsx)("span",{children:l("files.rename")}),(0,n.jsx)("kbd",{className:"hidden sm:inline-flex items-center justify-center w-4 h-4 rounded bg-white/20 text-white",children:(0,n.jsx)(t3.Lt,{size:10,strokeWidth:2.5})})]})]})]})]})]})}function l5({name:e,onResolve:t}){let{t:s}=(0,se.s)();(0,r.useEffect)(()=>{let e=e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),t?.("skip"))};return window.addEventListener("keydown",e,!0),()=>window.removeEventListener("keydown",e,!0)},[t]);let a=(e,r,a=!1)=>(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),t(e)},className:`py-2 rounded-brand text-sm flex items-center justify-center gap-1.5 ${r}`,children:[(0,n.jsx)("span",{children:s(`menu.${e}`)}),a&&(0,n.jsx)("kbd",{className:"hidden sm:inline-flex items-center text-[10px] font-mono px-1 py-0.5 rounded bg-surface-3 text-text-muted leading-none",children:"Esc"})]});return(0,n.jsxs)("div",{className:lG,children:[(0,n.jsx)("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-[2px]",onClick:()=>t?.("skip")}),(0,n.jsxs)("div",{className:"relative card-elev w-full max-w-sm",children:[(0,n.jsx)("div",{className:"px-4 py-3",children:(0,n.jsx)("h3",{className:"text-text font-semibold",children:s("menu.conflictTitle")})}),(0,n.jsx)("div",{className:"px-4 pb-3 text-text-muted text-sm break-all",children:s("menu.conflictMessage",{name:e})}),(0,n.jsxs)("div",{className:"p-4 grid grid-cols-2 gap-2",children:[a("skip","bg-surface-2 text-text hover:bg-surface-3",!0),a("skipAll","bg-surface-2 text-text hover:bg-surface-3"),a("replace","bg-brand-500 text-white hover:bg-brand-600"),a("replaceAll","bg-brand-500 text-white hover:bg-brand-600")]})]})]})}async function l3(e,t,s,n=!1){if(!e||!t||!s)return{success:!1};let r=lw(t,".gitignore"),a=s.replace(/^\/+/,"");n&&!a.endsWith("/")&&(a=`${a}/`);let l=await e.readFile(r),i=l?.success&&l.content||"",o=i.split(/\r?\n/),c=a.replace(/\/$/,"");if(o.includes(a)||o.includes(c)||o.includes(`/${a}`)||o.includes(`/${c}`))return{success:!0,alreadyIgnored:!0};let d=i?i.endsWith("\n")?`${i}${a}
|
|
11
|
+
`:`${i}
|
|
12
|
+
${a}
|
|
13
|
+
`:`${a}
|
|
14
|
+
`;return await e.writeFile(r,d)}let l4="application/x-file-paths",l6=()=>"u">typeof document&&"webkitdirectory"in document.createElement("input"),l8=e=>{let t=e.dataTransfer.getData(l4);if(!t)return null;try{return JSON.parse(t)}catch{return null}},l9=e=>[...e.dataTransfer?.types||[]].includes("Files");function l7({workspace:e,fileBus:t,onOpenFile:s,activeFile:a,onSwitchWorkspace:l,onNewTerminal:i,onSearchFolder:o,compact:c=!1,onlyChanged:d=!1,onActions:u}){let{t:m}=(0,se.s)(),[x,p]=(0,r.useState)(null),h=(0,r.useRef)(null),f=rE(h,x?.x??0,x?.y??0),[b,g]=(0,r.useState)(null),[v,y]=(0,r.useState)(""),[w,k]=(0,r.useState)(null),[j,N]=(0,r.useState)(""),[S,C]=(0,r.useState)(null),[T,R]=(0,r.useState)(null),[E,_]=(0,r.useState)(()=>new Set),$=(0,r.useRef)(E);(0,r.useEffect)(()=>{$.current=E},[E]);let M=(0,r.useRef)(v);(0,r.useEffect)(()=>{M.current=v},[v]);let P=(0,r.useRef)(b);(0,r.useEffect)(()=>{P.current=b},[b]);let[A,z]=(0,r.useState)(null),[I,L]=(0,r.useState)(!1),[D,F]=(0,r.useState)(null),[O,B]=(0,r.useState)(null),[W,K]=(0,r.useState)(null),[H,U]=(0,r.useState)(null),q=(0,r.useRef)(null),V=(0,r.useRef)(null),X=(0,r.useRef)(null),G=(0,r.useRef)(null),[J]=(0,r.useState)(l6),Y=(0,r.useRef)(null),Z=(0,r.useRef)(null),Q=(0,r.useRef)(null),ee=(0,r.useCallback)(t=>t&&e?t.replace(`${e}/`,""):t,[e]),{tree:et,expanded:es,loading:en,truncatedDirs:er,gitStatusMap:ea,showHidden:el,setShowHidden:ei,loadDir:eo,loadGitStatus:ec,toggleFolder:ed,expandDir:eu,collapseAll:em,refreshAll:ex}=function({workspace:e,fileBus:t}){let[s,n]=(0,r.useState)(()=>new Map),[a,l]=(0,r.useState)(()=>new Set),[i,o]=(0,r.useState)(null),[c,d]=(0,r.useState)(()=>new Set),[u,m]=(0,r.useState)(()=>new Set),[x,p]=(0,r.useState)({}),[h,f]=(0,r.useState)(lE),b=(0,r.useCallback)(async e=>{d(t=>{let s=new Set(t);return s.add(e),s});let s=await t.getFiles(e,h);return(d(t=>{let s=new Set(t);return s.delete(e),s}),s?.success)?(n(t=>{let n=new Map(t);return n.set(e,s.files||[]),n}),m(t=>{let n=!!s.truncated;if(n===t.has(e))return t;let r=new Set(t);return n?r.add(e):r.delete(e),r}),s.files||[]):[]},[t,h]),g=(0,r.useRef)(0),v=(0,r.useCallback)(async()=>{if(!e)return;let s=++g.current,{map:n}=await lT(t,e);s===g.current&&p(n)},[t,e]);(0,r.useEffect)(()=>{if(!e)return;let t=!0;return(async()=>{let s,n,r=Array.isArray(n=(s=lR())[e])?n:Array.isArray(s.legacy)?s.legacy:[],a=new Set([e]),i=r.filter(t=>"string"==typeof t&&t.startsWith(e));for(let e of i)a.add(e);await Promise.all([b(e),...i.map(e=>b(e))]),t&&(l(a),o(e),v())})(),()=>{t=!1}},[e]),(0,r.useEffect)(()=>{let e=null,t=()=>{clearTimeout(e),e=setTimeout(v,300)},s=["fileExplorer:fileSaved","fileExplorer:fileCreated","fileExplorer:fileDeleted","fileExplorer:fileRenamed",tp];return s.forEach(e=>window.addEventListener(e,t)),()=>{clearTimeout(e),s.forEach(e=>window.removeEventListener(e,t))}},[v]),(0,r.useEffect)(()=>{if(i===e&&e)try{let t=lR();delete t.legacy,t[e]=[...a],window.localStorage.setItem(tb,JSON.stringify(t))}catch{}},[e,i,a]),(0,r.useEffect)(()=>{window.localStorage.setItem(tg,JSON.stringify(h)),s.size>0&&Promise.all([...s.keys()].map(e=>b(e))).catch(()=>{})},[h]);let y=(0,r.useCallback)(async e=>{(0,t7.e)();let t=e.path;a.has(t)?l(e=>{let s=new Set(e);return s.delete(t),s}):(s.has(t)||await b(t),l(e=>{let s=new Set(e);return s.add(t),s}))},[a,s,b]),w=(0,r.useCallback)(e=>{l(t=>{let s=new Set(t);return s.add(e),s})},[]),k=(0,r.useCallback)(()=>{(0,t7.e)(),l(new Set)},[]),j=lS(),N=(0,r.useMemo)(()=>[...s.keys()].filter(t=>t===e||a.has(t)),[s,a,e]),S=(0,r.useCallback)(e=>{Promise.all(e.map(e=>b(e))).catch(()=>{}),v()},[b,v]);lN({dirs:N,fileBus:t,onDirsChanged:S,enabled:j});let C=(0,r.useRef)(!0);(0,r.useEffect)(()=>{let e=j&&!C.current;C.current=j,e&&s.size&&S([...s.keys()])},[j]);let T=(0,r.useCallback)(async()=>{(0,t7.e)();let e=[...s.keys()];await Promise.all(e.map(e=>b(e))),v()},[s,b,v]);return{tree:s,expanded:a,loading:c,truncatedDirs:u,gitStatusMap:x,showHidden:h,setShowHidden:f,loadDir:b,loadGitStatus:v,toggleFolder:y,expandDir:w,collapseAll:k,refreshAll:T}}({workspace:e,fileBus:t}),{createItem:ep,renameItem:eh,deleteItem:ef,deleteMany:eb,duplicateItem:eg,moveTo:ev,pasteInto:ey}=function({fileBus:e,loadDir:t,loadGitStatus:s,expandDir:n,onOpenFile:a,onMoved:l}){let i=(0,r.useCallback)(async(s,r,l)=>{let i=lw(s,r),o=await e.createItem(i,l);o?.success&&(l$("created"),await t(s),"folder"===l?n(s):a?.(i))},[e,t,n,a]),o=(0,r.useCallback)(async(s,n)=>{let r=lk(s.path),a=lw(r,n),l=await e.renameItem(s.path,a);l?.success&&(l$("renamed"),await t(r))},[e,t]),c=(0,r.useCallback)(async s=>{let n=lk(s.path),r=await e.deleteItem(s.path);r?.success&&(l$("deleted"),await t(n))},[e,t]),d=(0,r.useCallback)(async n=>{if(!n?.length)return;let r=new Set;for(let t of n){let s=await e.deleteItem(t.path);s?.success&&r.add(lk(t.path))}if(r.size){for(let e of(l$("deleted"),r))await t(e);s(),l?.()}},[e,t,s,l]),u=(0,r.useCallback)(async(t,s)=>{let n=lj(t),r=new Set(((await e.getFiles(s,!0))?.files||[]).map(e=>e.name)),a=n;if(r.has(a)){let e=n.lastIndexOf("."),t=e>0?n.slice(0,e):n,s=e>0?n.slice(e):"";a=`${t} copy${s}`;for(let e=2;r.has(a);e++)a=`${t} copy ${e}${s}`}return e.copyItem(t,lw(s,a))},[e]),m=(0,r.useCallback)(async e=>{let n=lk(e.path),r=await u(e.path,n);r?.success&&(l$("created"),await t(n),s())},[u,t,s]),x=(0,r.useCallback)(async(n,r)=>{if(n?.length&&r){for(let t of n){let s=lw(r,t.split("/").pop());t===s||s.startsWith(t+"/")||await e.renameItem(t,s)}for(let e of new Set([r,...n.map(e=>lk(e))]))await t(e);l$("renamed"),s(),l?.()}},[e,t,s,l]),p=(0,r.useCallback)(async(e,r,a)=>{if(!e?.length||!r)return;if("cut"===a)return x(e,r);let l=0;for(let t of e){if(r===t||r.startsWith(t+"/"))continue;let e=await u(t,r);e?.success&&l++}l&&(l$("created"),await t(r),n(r),s())},[u,x,t,n,s]);return{createItem:i,renameItem:o,deleteItem:c,deleteMany:d,duplicateItem:m,moveTo:x,pasteInto:p}}({fileBus:t,loadDir:eo,loadGitStatus:ec,expandDir:eu,onOpenFile:s,onMoved:()=>_(new Set)});(0,r.useEffect)(()=>{if(!x)return;let e=()=>p(null);return window.addEventListener("click",e),window.addEventListener("scroll",e,!0),()=>{window.removeEventListener("click",e),window.removeEventListener("scroll",e,!0)}},[x]),(0,r.useEffect)(()=>{if(b&&Z.current){Z.current.focus();let e=Z.current.value.length;Z.current.setSelectionRange(e,e)}},[b]),(0,r.useEffect)(()=>{w&&Q.current&&Q.current.focus()},[w]);let ew=(0,r.useCallback)(()=>T&&et.has(T)?T:e,[T,et,e]),ek=(0,r.useCallback)(async e=>{let t=j.trim();if(!t)return;let s=w?.dir||ew();await ep(s,t,e),k(null),N("")},[j,w,ew,ep]),ej=(0,r.useCallback)(async()=>{let e=P.current;if(!e)return;let t=M.current.trim();t&&t!==e.name&&await eh(e,t),g(null)},[eh]),eN=(0,r.useCallback)(async e=>{try{await navigator.clipboard.writeText(e)}catch{}},[]),eS=(0,r.useCallback)((e,t)=>{e.preventDefault(),e.stopPropagation(),(0,t7.e)(),_(e=>e.has(t.path)?e:new Set([t.path])),U(t.path),p({file:t,x:e.clientX,y:e.clientY})},[]),eC=(0,r.useCallback)((e,t)=>{let s=e.touches?.[0];if(!s)return;let n=s.clientX,r=s.clientY;Y.current=setTimeout(()=>{(0,t7.e)(),p({file:t,x:n,y:r})},500)},[]),eT=(0,r.useCallback)(()=>{Y.current&&(clearTimeout(Y.current),Y.current=null)},[]),eR=(0,r.useMemo)(()=>{if(!a)return null;if(!tu(a))return a;let{repoPath:t,filePath:s}=tx(a);return s?`${t||e}/${s}`:null},[a,e]),eE=e=>!d||!!ea[ee(e.path)],e_=(0,r.useMemo)(()=>{let t=[],s=(e,n)=>{for(let r of et.get(e)||[])(!d||ea[ee(r.path)])&&(t.push({file:r,depth:n}),"folder"===r.type&&es.has(r.path)&&s(r.path,n+1))};return s(e,0),t},[et,es,ea,d,e,ee]),e$=(0,r.useCallback)(e=>e_.find(t=>t.file.path===e)?.file||null,[e_]),eM=(0,r.useCallback)(e=>{let t=e_.filter(e=>E.has(e.file.path)).map(e=>e.file);return t.length?t:e?[e]:[]},[e_,E]),eP=(0,r.useCallback)((e,t)=>{let s=e_.findIndex(t=>t.file.path===e),n=e_.findIndex(e=>e.file.path===t);if(-1===s||-1===n)return new Set([t]);let[r,a]=s<=n?[s,n]:[n,s];return new Set(e_.slice(r,a+1).map(e=>e.file.path))},[e_]),eA=(0,r.useCallback)((e,t)=>{if((0,t7.e)(),q.current?.focus({preventScroll:!0}),t?.metaKey||t?.ctrlKey){_(t=>{let s=new Set(t);return s.has(e.path)?s.delete(e.path):s.add(e.path),s}),U(e.path),V.current=e.path;return}if(t?.shiftKey&&V.current){_(eP(V.current,e.path)),U(e.path);return}_(new Set([e.path])),U(e.path),V.current=e.path,"folder"===e.type?(R(e.path),ed(e)):s?.(e.path)},[ed,s,eP]),ez=(0,r.useCallback)(t=>t?"folder"===t.type?t.path:lk(t.path):e,[e]),eI=(0,r.useCallback)(e=>{let t=eM(e);t.length&&C({files:t})},[eM]),eL=(0,r.useCallback)(async()=>{let e=S?.files||[];C(null),1===e.length?await ef(e[0]):await eb(e),_(new Set)},[S,ef,eb]),eD=(0,r.useCallback)((e,t)=>{let s=eM(e).map(e=>e.path);s.length&&F({paths:s,mode:t})},[eM]),eF=(0,r.useCallback)(async e=>{D?.paths?.length&&(await ey(D.paths,ez(e),D.mode),"cut"===D.mode&&F(null))},[D,ey,ez]),eO=(0,r.useCallback)(async(e,s)=>{if(!e.length)return;let n=0;B({total:e.length,done:0,failed:0}),await t.uploadFiles(s,e,{onConflict:(e,t)=>new Promise(s=>K({name:t||e?.name,resolve:s})),onFileDone:()=>B(e=>e?{...e,done:e.done+1}:e),onError:()=>{n+=1,B(e=>e?{...e,done:e.done+1,failed:n}:e)}}),B(e=>e&&n?e:null),K(null),await eo(s),eu(s),ec()},[t,eo,eu,ec]),eB=(0,r.useCallback)(async(e,t)=>{eO(await lX(e),t)},[eO]),eW=(0,r.useCallback)(()=>g(null),[]),eK=(0,r.useCallback)((e,t)=>{let s=$.current,n=s.has(t.path)?[...s]:[t.path];e.dataTransfer.setData(l4,JSON.stringify(n)),e.dataTransfer.effectAllowed="move"},[]),eH=(0,r.useCallback)((e,t)=>{let s=l9(e);("folder"===t.type||s)&&(e.preventDefault(),e.dataTransfer.dropEffect=s?"copy":"move","folder"===t.type&&z(t.path))},[]),eU=(0,r.useCallback)(e=>{z(t=>t===e.path?null:t)},[]),eq=(0,r.useCallback)((e,t)=>{let s=l9(e);if("folder"!==t.type&&!s)return;if(e.preventDefault(),e.stopPropagation(),z(null),L(!1),s)return void eB(e.dataTransfer,ez(t));let n=l8(e);n&&ev(n,t.path)},[eB,ez,ev]),eV=(0,r.useCallback)(e=>{let t=w?.dir||ew(),s=[...e.target.files].map(e=>({file:e,relativePath:e.webkitRelativePath||e.name}));e.target.value="",k(null),eO(s,t)},[w,ew,eO]),eX=(0,r.useCallback)((e,t)=>{if(!e_.length)return;let s=e_.findIndex(e=>e.file.path===H),n=e_[Math.min(e_.length-1,Math.max(0,-1===s?0:s+e))];if(!n)return;let r=n.file.path;t&&V.current?_(eP(V.current,r)):(_(new Set([r])),V.current=r),U(r),q.current?.querySelector(`[data-path="${CSS.escape(r)}"]`)?.scrollIntoView({block:"nearest"})},[e_,H,eP]),eG=(0,r.useCallback)(e=>{if(b||w||S)return;let t=e$(H),n=e.metaKey||e.ctrlKey;if(n&&"a"===e.key.toLowerCase()){e.preventDefault(),_(new Set(e_.map(e=>e.file.path))),V.current=e_[0]?.file.path||null;return}if(n&&"c"===e.key.toLowerCase()){e.preventDefault(),eD(t,"copy");return}if(n&&"x"===e.key.toLowerCase()){e.preventDefault(),eD(t,"cut");return}if(n&&"v"===e.key.toLowerCase()){e.preventDefault(),eF(t);return}switch(e.key){case"ArrowDown":e.preventDefault(),eX(1,e.shiftKey);return;case"ArrowUp":e.preventDefault(),eX(-1,e.shiftKey);return;case"ArrowRight":if(!t)return;e.preventDefault(),"folder"!==t.type||es.has(t.path)?eX(1,!1):ed(t);return;case"ArrowLeft":if(!t)return;e.preventDefault(),"folder"===t.type&&es.has(t.path)?ed(t):eX(-1,!1);return;case"Enter":if(!t)return;e.preventDefault(),s1()?(g(t),y(t.name)):"folder"===t.type?ed(t):s?.(t.path);return;case"F2":if(!t)return;e.preventDefault(),g(t),y(t.name);return;case"Delete":case"Backspace":if(!t)return;e.preventDefault(),eI(t);return;case"Escape":_(new Set),F(null);return}},[b,w,S,H,e$,e_,es,ed,s,eX,eD,eF,eI]),eJ=(e,t)=>{if(!eE(e))return null;let s="folder"===e.type,r=s&&es.has(e.path),a=E.has(e.path);return(0,n.jsx)(lq,{file:e,depth:t,isFolder:s,isExpanded:r,isLoading:s&&en.has(e.path),isActive:eR===e.path,isSelected:a,isRenaming:b?.path===e.path,isDragOver:A===e.path&&s,isCut:D?.mode==="cut"&&D.paths.includes(e.path),gitStatus:ea[ee(e.path)],renameValue:b?.path===e.path?v:"",renameInputRef:Z,onRenameChange:y,onRenameSubmit:ej,onRenameCancel:eW,onToggleFolder:ed,onClick:eA,onContextMenu:eS,onTouchStart:eC,onTouchEnd:eT,onDragStart:eK,onDragOver:eH,onDragLeave:eU,onDrop:eq,compact:c,children:s&&r&&(0,n.jsxs)("div",{children:[(et.get(e.path)||[]).map(e=>eJ(e,t+1)),er.has(e.path)&&(0,n.jsx)(lU,{depth:t+1,compact:c})]})},e.path)},eY=(0,r.useMemo)(()=>et.get(e)||[],[et,e]);(0,r.useEffect)(()=>{if(!d)return;let t=!0;return(async()=>{for(let s of Object.keys(ea)){if("folder-changed"!==ea[s])continue;let n=`${e}/${s}`;if(!et.has(n)&&(await eo(n),!t))return;eu(n)}})(),()=>{t=!1}},[d,ea,e]),(0,r.useEffect)(()=>{if(!eR||!q.current)return;let e=setTimeout(()=>{let e=q.current?.querySelector(`[data-path="${CSS.escape(eR)}"]`);e?.scrollIntoView({block:"nearest"})},0);return()=>clearTimeout(e)},[eR,et]);let eZ=(0,r.useMemo)(()=>lj(e),[e]),eQ=(e,t)=>{(0,t7.e)(),k({type:e,dir:t}),N("")};(0,r.useEffect)(()=>{if(u)return u({newFile:()=>eQ("file",ew()),newFolder:()=>eQ("folder",ew()),refresh:ex,collapseAll:em,hasExpanded:es.size>0,showHidden:el,toggleHidden:()=>ei(e=>!e)}),()=>u(null)},[u,el,ex,em,es.size,e]);let e0=(0,r.useCallback)(async s=>{if(!e||!t||!s?.path)return;let n=ee(s.path),r=await l3(t,e,n,"folder"===s.type);r?.success&&(ec(),window.dispatchEvent(new CustomEvent(tp)))},[e,t,ee,ec]),e1="text-text-muted hover:text-text p-1 rounded hover:bg-surface-2";return(0,n.jsxs)("div",{className:"relative flex flex-col flex-1 min-h-0 text-text overflow-hidden",children:[!c&&(0,n.jsxs)("div",{style:{height:32},className:"bg-surface border-b border-border flex items-center gap-2 sticky top-0 z-10 flex-shrink-0 px-3",children:[(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),l?.()},className:"flex items-center gap-1 flex-1 min-w-0 hover:text-text",children:[(0,n.jsx)("span",{className:"text-xs uppercase tracking-wider text-text-muted font-medium truncate",children:eZ||"No Workspace"}),(0,n.jsx)(t3.Ay,{name:"ChevronDown",size:12,className:"text-text-muted shrink-0"})]}),(0,n.jsx)("button",{onClick:()=>eQ("file",ew()),className:e1,title:"New File",children:(0,n.jsx)(t3.Ay,{name:"Plus",size:14})}),(0,n.jsx)("button",{onClick:()=>eQ("folder",ew()),className:e1,title:"New Folder",children:(0,n.jsx)(t3.Ay,{name:"FolderOpen",size:14})}),(0,n.jsx)("button",{onClick:ex,className:e1,title:"Refresh",children:(0,n.jsx)(t3.Ay,{name:"RefreshCw",size:14})}),es.size>0&&(0,n.jsx)("button",{onClick:em,className:e1,title:m("fileExplorer.collapseAll"),children:(0,n.jsx)(t3.Ay,{name:"ChevronsDownUp",size:14})}),(0,n.jsx)("button",{onClick:()=>ei(e=>!e),className:`p-1 rounded hover:bg-surface-2 ${el?"text-text":"text-text-muted hover:text-text"}`,title:el?"Hide hidden files":"Show hidden files",children:(0,n.jsx)(t3.Ay,{name:el?"Eye":"EyeOff",size:14})})]}),(0,n.jsx)("div",{ref:q,tabIndex:0,onKeyDown:eG,className:`flex-1 overflow-auto py-1 outline-none ${I?"ring-2 ring-inset ring-brand-500/40 bg-brand-500/5":""}`,onDragOver:e=>{e.preventDefault();let t=l9(e);e.dataTransfer.dropEffect=t?"copy":"move",t&&L(!0)},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||L(!1)},onClick:e=>{e.target===e.currentTarget&&(_(new Set),R(null))},onDrop:t=>{if(t.preventDefault(),L(!1),l9(t))return void eB(t.dataTransfer,e);let s=l8(t);s&&ev(s,e)},children:d&&!eY.some(eE)?(0,n.jsx)("div",{className:"text-text-subtle text-xs px-3 py-4 text-center",children:m("git.noChanges")}):0!==eY.length||en.has(e)?(0,n.jsxs)(n.Fragment,{children:[eY.map(e=>eJ(e,0)),er.has(e)&&(0,n.jsx)("div",{className:"text-[11px] text-text-muted italic py-0.5 px-3",children:"Showing first 300 entries — use search for the rest."})]}):(0,n.jsx)("div",{className:"text-text-subtle text-xs px-3 py-4 text-center",children:"Empty workspace"})}),x&&(0,n.jsx)("div",{ref:h,className:"fixed z-50 menu-popover p-1 min-w-[150px] animate-in fade-in zoom-in-95 duration-100",style:{left:f.left,top:f.top},onClick:e=>e.stopPropagation(),children:(e=>{if(!e)return[];let n="folder"===e.type,r=eM(e),a=r.length>1,l=[];return!a&&n?(i&&l.push({label:m("workspaces.openHere"),icon:"Terminal",action:()=>i(e.path)}),o&&l.push({label:"Search in Folder",icon:"Search",action:()=>o(e.path)}),l.push({label:"New File",icon:"Plus",action:()=>eQ("file",e.path)}),l.push({label:"New Folder",icon:"FolderOpen",action:()=>eQ("folder",e.path)})):!a&&(l.push({label:"Open",icon:"File",action:()=>s?.(e.path)}),tr(e.path)&&l.push({label:m("editor.preview"),icon:"Eye",action:()=>s?.(e.path,{preview:!0})})),l.push({label:"Cut",icon:"Scissors",action:()=>eD(e,"cut")}),l.push({label:"Copy",icon:"Copy",action:()=>eD(e,"copy")}),D?.paths?.length&&l.push({label:"Paste",icon:"ClipboardPaste",action:()=>eF(e)}),a||(l.push({label:"Reveal in OS",icon:"FolderOpen",action:()=>t.revealInOS(e.path)}),l.push({label:"Rename",icon:"Pencil",action:()=>{g(e),y(e.name)}}),l.push({label:"Duplicate",icon:"Copy",action:()=>eg(e)}),l.push({label:"Copy Path",icon:"Copy",action:()=>eN(e.path)}),l.push({label:"Copy Relative Path",icon:"Copy",action:()=>eN(ee(e.path))}),l.push({label:m("git.addToGitignore",{defaultValue:"Add to .gitignore"}),icon:"EyeOff",action:()=>e0(e)})),l.push({label:a?`Delete ${r.length} items`:"Delete",icon:"Trash2",danger:!0,action:()=>eI(e)}),l})(x.file).map((e,t)=>(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),e.action(),p(null)},className:`w-full flex items-center gap-1.5 px-2 py-1.5 text-xs text-left hover:bg-surface-2/80 rounded-[6px] transition-colors ${e.danger?"text-red-400":"text-text"}`,children:[(0,n.jsx)(t3.Ay,{name:e.icon,size:13,className:"shrink-0"}),(0,n.jsx)("span",{className:"truncate",children:e.label})]},t))}),w&&(0,n.jsxs)("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",children:[(0,n.jsx)("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-[4px] animate-in fade-in duration-150",onClick:()=>k(null)}),(0,n.jsxs)("div",{className:"relative card-elev p-4 w-full max-w-sm animate-in zoom-in-95 duration-150",children:[(0,n.jsx)("h3",{className:"text-sm font-semibold text-text mb-2",children:"folder"===w.type?"New Folder":"New File"}),(0,n.jsxs)("p",{className:"text-xs text-text-muted mb-2 truncate",children:["in ",ee(w.dir)||eZ||"/"]}),(0,n.jsx)("input",{ref:Q,value:j,onChange:e=>N(e.target.value),onKeyDown:e=>{"Enter"===e.key?ek(w.type):"Escape"===e.key&&k(null)},placeholder:"folder"===w.type?"folder name":"file name",className:"w-full bg-surface-3 text-text text-sm px-2 py-1.5 rounded outline-none border border-border focus:border-brand-500"}),(0,n.jsxs)("div",{className:"flex items-center gap-2 mt-3",children:[(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),("folder"===w.type&&J?G:X).current?.click()},className:"flex items-center gap-1.5 px-2 py-1.5 text-xs text-text-muted hover:text-text rounded-brand hover:bg-surface-3",title:"folder"===w.type&&J?"Upload a folder from this computer":"Upload files from this computer",children:[(0,n.jsx)(t3.Ay,{name:"Upload",size:13}),"Upload"]}),(0,n.jsx)("div",{className:"flex-1"}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),k(null)},className:"px-3 py-1.5 text-sm bg-surface-3 hover:bg-surface text-text rounded-brand",children:"Cancel"}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),ek(w.type)},className:"px-3 py-1.5 text-sm bg-brand-500 hover:bg-brand-500/80 text-white rounded-brand",children:"Create"})]})]}),(0,n.jsx)("input",{ref:X,type:"file",multiple:!0,className:"hidden",onChange:eV}),(0,n.jsx)("input",{ref:G,type:"file",webkitdirectory:"",className:"hidden",onChange:eV})]}),O&&(0,n.jsx)("div",{className:"absolute bottom-0 inset-x-0 bg-surface-2 border-t border-border px-3 py-1.5 pb-safe text-[11px] text-text-muted flex items-center gap-2",children:O.failed?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"text-danger",children:m("fileExplorer.uploadFailedCount",{n:O.failed,total:O.total})}),(0,n.jsx)("button",{type:"button",onClick:()=>B(null),className:"ml-auto underline hover:text-text",children:m("common.close")})]}):(0,n.jsx)("span",{children:m("fileExplorer.uploadingCount",{n:Math.min(O.done+1,O.total),total:O.total})})}),W&&(0,n.jsx)(l5,{name:W.name,onResolve:e=>{W.resolve(e),K(null)}}),(0,n.jsx)(t9.A,{isOpen:!!S,onClose:()=>C(null),onConfirm:eL,title:"Delete",message:(S?.files?.length||0)>1?`Are you sure you want to delete these ${S.files.length} items?`:`Are you sure you want to delete "${S?.files?.[0]?.name}"?`,confirmText:"Delete",cancelText:"Cancel"})]})}function ie({x:e,y:t,items:s,onClose:a}){let l=(0,r.useRef)(null);return(0,r.useEffect)(()=>{if(!l.current)return;let s=l.current.getBoundingClientRect(),n=Math.min(e,window.innerWidth-s.width-8),r=Math.min(t,window.innerHeight-s.height-8);l.current.style.left=`${Math.max(8,n)}px`,l.current.style.top=`${Math.max(8,r)}px`},[e,t]),(0,r.useEffect)(()=>{let e=e=>{l.current&&!l.current.contains(e.target)&&a()},t=e=>{"Escape"===e.key&&a()},s=setTimeout(()=>{document.addEventListener("mousedown",e),document.addEventListener("contextmenu",e,!0),document.addEventListener("keydown",t)},0);return()=>{clearTimeout(s),document.removeEventListener("mousedown",e),document.removeEventListener("contextmenu",e,!0),document.removeEventListener("keydown",t)}},[a]),(0,n.jsx)("div",{ref:l,className:"fixed z-50 min-w-[180px] py-1 rounded-lg border border-border bg-surface shadow-elev animate-in fade-in",style:{left:e,top:t},onContextMenu:e=>e.preventDefault(),children:s.filter(Boolean).map((e,t)=>(0,n.jsxs)("button",{type:"button",disabled:e.disabled,onClick:t=>{t.stopPropagation(),e.onClick?.(),a()},className:`w-full flex items-center gap-2.5 px-3 py-1.5 text-sm text-left transition-colors ${e.disabled?"text-text-subtle cursor-not-allowed":e.danger?"text-danger hover:bg-[rgba(var(--danger-rgb),0.12)]":"text-text hover:bg-surface-2"}`,children:[e.icon&&(0,n.jsx)(e.icon,{size:14,className:"flex-shrink-0"}),(0,n.jsx)("span",{className:"flex-1 truncate",children:e.label})]},e.key+t))})}let it={Copy:t3.QR,FileText:t3.iU,ExternalLink:t3.Gr,Undo2:t3.bE,X:t3.X,EyeOff:t3.X_};function is(){let[e,t]=(0,r.useState)(!1);return(0,r.useEffect)(()=>{let e=window.matchMedia("(hover: none), (pointer: coarse)"),s=()=>t(e.matches);return s(),e.addEventListener("change",s),()=>e.removeEventListener("change",s)},[]),e}let ir=(e,t)=>(e||"").split("\n").map(e=>e.trim()).find(t)||"",ia=(e,t)=>{let s=ir(t,e=>/files? changed/.test(e));return e("git.commitSuccess")+(s?` \xb7 ${s}`:"")},il=(e,t)=>{if(/up.to.date/i.test(t||""))return e("git.upToDate");let s=ir(t,e=>e.includes("->"));return e("git.pushSuccess")+(s?` \xb7 ${s}`:"")},ii="changes",io="untracked";function ic(e){if(!e)return"";let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t>=0?e.slice(t+1):e}function id(e){if(!e)return"";let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t>=0?e.slice(0,t):""}function iu(e,t){if(!e)return t;let s=e.endsWith("/")||e.endsWith("\\")?"":"/";return`${e}${s}${t}`}let im=(0,r.memo)(function({file:e,workspace:t,isUntracked:s,t:r,isTouch:a,openDiff:l,onCtxMenu:i,onDiscard:o,onStage:c}){let d=tl[e.status]||"text-text-muted";return iu(t,e.path),(0,n.jsxs)("div",{className:"group relative flex items-center gap-1.5 px-2 py-1 hover:bg-surface-2 cursor-pointer",onContextMenu:t=>i(e,t),onClick:()=>{(0,t7.e)(),l(e)},children:[(0,n.jsx)("span",{className:"flex-shrink-0 flex items-center",children:lB({name:ic(e.path),path:e.path,type:"file"},16)}),(0,n.jsx)("span",{className:"truncate text-xs text-text",title:e.path,children:ic(e.path)}),(0,n.jsx)("span",{className:"truncate text-[11px] text-text-muted flex-1",title:id(e.path),children:id(e.path)}),(0,n.jsxs)("div",{className:`absolute right-[22px] top-1/2 -translate-y-1/2 flex items-center gap-0.5 pl-2 pr-1 bg-surface-2 transition-opacity ${a?"opacity-100":"opacity-0 group-hover:opacity-100"}`,children:[(0,n.jsx)("button",{type:"button",title:r(s?"common.delete":"git.discard"),onClick:t=>{t.stopPropagation(),(0,t7.e)(),o(e)},className:"p-0.5 text-text-muted hover:text-text",children:(0,n.jsx)(t3.X,{size:12})}),(0,n.jsx)("button",{type:"button",title:r("git.stage"),onClick:t=>{t.stopPropagation(),(0,t7.e)(),c(e)},className:"p-0.5 text-text-muted hover:text-text",children:(0,n.jsx)(t3.FW,{size:12})})]}),(0,n.jsx)("span",{className:`flex-shrink-0 w-4 h-4 flex items-center justify-center text-[10px] font-mono rounded bg-surface-2 ${d}`,children:e.status})]})});function ix({workspace:e,fileBus:t,onOpenFile:s,tagDiffWithRepo:a=!1}){let{t:l}=(0,se.s)(),i=is(),[o,c]=(0,r.useState)(""),[d,u]=(0,r.useState)(null),[m,x]=(0,r.useState)(null),[p,h]=(0,r.useState)([]),[f,b]=(0,r.useState)(""),[g,v]=(0,r.useState)(!1),[y,w]=(0,r.useState)(null),[k,j]=(0,r.useState)(new Set([ii,io])),[N,S]=(0,r.useState)(!1),[C,T]=(0,r.useState)(!1),[R,E]=(0,r.useState)(null),[_,$]=(0,r.useState)(!1),[M,P]=(0,r.useState)(null),[A,z]=(0,r.useState)(null),I=(0,r.useCallback)(async()=>{if(!e||!t)return;v(!0);let[s,n]=await Promise.all([t.gitStatus?.(e),t.gitBranch?.(e)]);v(!1),s?.success&&h(s.files||[]),n?.success&&(c(n.branch||""),u(n.ahead??null),x(n.behind??null))},[e,t]);(0,r.useEffect)(()=>{I()},[I]),(0,r.useEffect)(()=>{let e=()=>I(),t=["fileExplorer:fileSaved","fileExplorer:fileCreated","fileExplorer:fileDeleted","fileExplorer:fileRenamed",tp];return t.forEach(t=>window.addEventListener(t,e)),()=>t.forEach(t=>window.removeEventListener(t,e))},[I]);let{changes:L,untracked:D}=(0,r.useMemo)(()=>{let e=[],t=[];for(let s of p)"?"===s.status?t.push(s):e.push(s);return{changes:e,untracked:t}},[p]),F=(0,r.useCallback)(e=>{j(t=>{let s=new Set(t);return s.has(e)?s.delete(e):s.add(e),s})},[]),O=(0,r.useCallback)(async s=>{e&&(await t.gitAdd?.(e,[s.path]),I())},[e,t,I]),B=(0,r.useCallback)(async()=>{e&&(await t.gitAdd?.(e,["."]),I())},[e,t,I]),W=(0,r.useCallback)(async s=>{e&&(await t.gitDiscard?.(e,s.path,s.status),I())},[e,t,I]),K=(0,r.useCallback)(e=>{E(e),T(!0)},[]),H=(0,r.useCallback)(t=>{let n,r;s?.(a?(n=t.status,r=t.path,`${tc}${n}:${e}\u0000${r}`):td(t.status,t.path))},[s,a,e]),U=(0,r.useCallback)((e=!1)=>{!f.trim()||p.length&&($(e),S(!0))},[f,p]),q=(0,r.useCallback)(async()=>{if(!e)return;w(null);let s=await t.gitAdd?.(e,["."]);if(s&&!s.success)return void w({ok:!1,text:s.error||l("git.stageFailed")});let n=await t.gitCommit?.(e,f.trim());if(!n?.success){w({ok:!1,text:n?.output||n?.error||l("git.commitFailed")}),I();return}if(b(""),!_){w({ok:!0,text:ia(l,n.output)}),I();return}let r=await t.gitPush?.(e);w(r?.success?{ok:!0,text:`${ia(l,n.output)} \xb7 ${il(l,r.output)}`}:{ok:!1,text:r?.output||r?.error||l("git.pushFailed")}),I()},[e,t,f,_,I,l]),V=(0,r.useCallback)(async()=>{if(!e)return;v(!0),w(null);let s=await t.gitPush?.(e);v(!1),w(s?.success?{ok:!0,text:il(l,s.output)}:{ok:!1,text:s?.output||s?.error||l("git.pushFailed")}),I()},[e,t,I,l]),X=(0,r.useCallback)(async()=>{if(!e)return;v(!0),w(null);let s=await t.gitPull?.(e);v(!1),w(s?.success?{ok:!0,text:((e,t)=>{if(/already up to date|up.to.date/i.test(t||""))return e("git.upToDate");let s=ir(t,e=>/files? changed|fast-forward/i.test(e));return e("git.pullSuccess")+(s?` \xb7 ${s}`:"")})(l,s.output)}:{ok:!1,text:s?.output||s?.error||l("git.pullFailed")}),I()},[e,t,I,l]),G=(0,r.useCallback)((e,t)=>{e.stopPropagation(),(0,t7.e)();let s=e.currentTarget.getBoundingClientRect();t({x:s.right,y:s.bottom+4})},[]),[J,Y]=(0,r.useState)(null),Z=(0,r.useCallback)(async e=>{try{await navigator.clipboard.writeText(e)}catch{}},[]),Q=(0,r.useCallback)((e,t)=>{t.preventDefault(),t.stopPropagation(),(0,t7.e)(),Y({file:e,x:t.clientX,y:t.clientY})},[]),ee=(0,r.useCallback)(async s=>{if(!e||!t||!s?.path)return;let n=await l3(t,e,s.path);n?.success&&(window.dispatchEvent(new CustomEvent(tp)),I())},[e,t,I]),et=(0,r.useCallback)(t=>{let n=iu(e,t.path);return[{key:"open",label:l("git.openFile"),icon:t3.Gr,disabled:"D"===t.status,onClick:()=>s?.(n)},{key:"copyPath",label:l("files.copyPath",{defaultValue:"Copy Path"}),icon:t3.Gr,onClick:()=>Z(n)},{key:"copyRel",label:l("files.copyRelPath",{defaultValue:"Copy Relative Path"}),icon:t3.Gr,onClick:()=>Z(t.path)},{key:"copyName",label:l("files.copyName",{defaultValue:"Copy Filename"}),icon:t3.Gr,onClick:()=>Z(ic(t.path))},{key:"addToGitignore",label:l("git.addToGitignore",{defaultValue:"Add to .gitignore"}),icon:t3.X_,onClick:()=>ee(t)}]},[e,s,Z,ee,l]),es=(t,s,r,a)=>{let o=k.has(t);return(0,n.jsxs)("div",{className:"border-t border-border",children:[(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),F(t)},className:"w-full flex items-center gap-1 px-2 py-1 hover:bg-surface-2 text-left",children:[o?(0,n.jsx)(t3.yQ,{size:12,className:"text-text-subtle"}):(0,n.jsx)(t3.c_,{size:12,className:"text-text-subtle"}),(0,n.jsx)("span",{className:"text-[11px] uppercase tracking-wider text-text-muted",children:s}),(0,n.jsx)("span",{className:"text-[10px] px-1.5 ml-auto rounded-brand bg-surface-3 text-text-muted",children:r.length})]}),o&&r.map(t=>(0,n.jsx)(im,{file:t,workspace:e,isUntracked:a,t:l,isTouch:i,openDiff:H,onCtxMenu:Q,onDiscard:K,onStage:O},`${t.status}-${t.path}`))]})};return(0,n.jsxs)("div",{className:"flex flex-col h-full text-sm text-text",children:[(0,n.jsxs)("div",{className:"px-3 pt-3 pb-2 space-y-2",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)(t3.Zr,{size:14,className:"text-text-muted"}),(0,n.jsx)("span",{className:"text-xs text-text truncate flex-1",children:o||"—"}),d>0&&(0,n.jsxs)("span",{className:"text-[10px] font-medium px-1.5 rounded-brand bg-brand-500/15 text-brand-500",children:["↑",d]}),m>0&&(0,n.jsxs)("span",{className:"text-[10px] font-medium px-1.5 rounded-brand bg-surface-3 text-text-muted",children:["↓",m]}),(0,n.jsx)("button",{type:"button",title:l("common.refresh"),onClick:()=>{(0,t7.e)(),I()},className:"p-1 text-text-muted hover:text-text",children:(0,n.jsx)(t3.e9,{size:12,className:g?"animate-spin":""})}),(0,n.jsx)("button",{type:"button",title:l("git.gitActions"),onClick:e=>G(e,z),className:"p-1 text-text-muted hover:text-text",children:(0,n.jsx)(t3.a4,{size:12})})]}),(0,n.jsx)("textarea",{value:f,onChange:e=>b(e.target.value),rows:2,placeholder:l("git.commitPlaceholder"),className:"w-full bg-surface-2 border border-border rounded-brand px-2 py-1 text-xs text-text placeholder-text-subtle focus:outline-none focus:border-brand-500 resize-none"}),(0,n.jsxs)("div",{className:`flex items-stretch h-7 rounded-brand overflow-hidden bg-brand-500 text-white transition-opacity ${!f.trim()||!p.length?"opacity-40":""}`,children:[(0,n.jsx)("button",{type:"button",disabled:!f.trim()||!p.length,onClick:()=>{(0,t7.e)(),U(!1)},className:"flex-1 text-xs hover:bg-black/10 disabled:cursor-not-allowed transition-colors",children:l("git.commit")}),(0,n.jsx)("span",{className:"w-px my-1.5 bg-white/25"}),(0,n.jsx)("button",{type:"button",title:l("git.gitActions"),disabled:!f.trim()||!p.length,onClick:e=>G(e,P),className:"px-1.5 flex items-center hover:bg-black/10 disabled:cursor-not-allowed transition-colors",children:(0,n.jsx)(t3.yQ,{size:12})})]}),y&&(0,n.jsx)("div",{className:`text-[11px] leading-snug break-words rounded-brand px-2 py-1 ${y.ok?"text-[var(--success)] bg-[rgba(var(--success-rgb),0.1)]":"text-[var(--danger)] bg-[rgba(var(--danger-rgb),0.1)]"}`,children:y.text})]}),(0,n.jsxs)("div",{className:"flex-1 overflow-auto",children:[es(ii,l("git.changes"),L,!1),es(io,l("git.untracked"),D,!0)]}),(0,n.jsx)(t9.A,{isOpen:N,onClose:()=>S(!1),onConfirm:q,title:l("git.stageAllConfirmTitle"),message:l("git.stageAllConfirmMessage"),confirmText:l("git.stageAndCommit"),cancelText:l("common.cancel")}),(0,n.jsx)(t9.A,{isOpen:C,onClose:()=>{T(!1),E(null)},onConfirm:()=>{R&&W(R),E(null)},title:l("git.discardConfirmTitle"),message:R?"?"===R.status?l("git.discardConfirmDelete",{name:ic(R.path)}):l("git.discardConfirmDiscard",{name:ic(R.path)}):"",confirmText:l("git.discard"),cancelText:l("common.cancel")}),J&&(0,n.jsx)(ie,{x:J.x,y:J.y,items:et(J.file),onClose:()=>Y(null)}),M&&(0,n.jsx)(ie,{x:M.x,y:M.y,items:[{key:"commitPush",label:l("git.commitAndPush"),icon:t3.Do,disabled:!f.trim()||!p.length,onClick:()=>U(!0)}],onClose:()=>P(null)}),A&&(0,n.jsx)(ie,{x:A.x,y:A.y,items:[{key:"push",label:l("git.push"),icon:t3.Do,onClick:V},{key:"pull",label:l("git.pull"),icon:t3.yd,onClick:X},{key:"stageAll",label:l("git.stageAll"),icon:t3.FW,disabled:!p.length,onClick:B}],onClose:()=>z(null)})]})}let ip=[{key:"files",icon:t3.sv,labelKey:"workspaces.tabFiles"},{key:"git",icon:t3.Zr,labelKey:"workspaces.tabGit"},{key:"trees",icon:t3.dx,labelKey:"workspaces.tabTrees"}].filter(e=>"trees"!==e.key);function ih({results:e,loading:t,query:s,searchDir:r,workspace:a,onOpen:l}){let{t:i}=(0,se.s)();if(!s||s.length<2){let e=r?r.split("/").pop():"";return(0,n.jsxs)("div",{className:"p-6 text-xs text-text-subtle text-center flex flex-col items-center gap-2",children:[(0,n.jsx)(t3.vj,{size:20,className:"opacity-40"}),(0,n.jsx)("span",{children:e?`Type at least 2 characters to search in ${e}`:i("files.searchPlaceholder")})]})}return t?(0,n.jsx)("p",{className:"p-4 text-xs text-text-subtle text-center",children:i("files.searching")}):e.length?(0,n.jsx)("div",{className:"flex-1 min-h-0 overflow-y-auto modal-scrollable",children:e.map(e=>(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),l(e.path)},className:"w-full px-2 py-1.5 flex items-center gap-2 border-b border-border-subtle hover:bg-surface-2 transition-colors text-left",title:e.path,children:["binary"===e.type?(0,n.jsx)(t3.lP,{size:14,className:"text-red-500/70 flex-shrink-0"}):(0,n.jsx)(t3.ZH,{size:14,className:"text-text-subtle flex-shrink-0"}),(0,n.jsx)("span",{className:"truncate text-xs text-text flex-1",children:e.name}),(0,n.jsx)("span",{className:"truncate text-[10px] text-text-subtle max-w-[45%]",children:e.path.replace(a,"").replace(/^\//,"")})]},e.path))}):(0,n.jsx)("p",{className:"p-4 text-xs text-text-subtle text-center",children:i("files.noFilesFound")})}function ib({root:e,multiple:t,isOpen:s,onToggle:r,onRemove:a=null,removeLabel:l="",children:i}){return t?(0,n.jsxs)("div",{className:`flex flex-col min-h-0 ${s?"flex-1":"flex-shrink-0"}`,children:[(0,n.jsxs)("div",{className:"group px-2 py-1 flex items-center gap-1.5 text-[10px] uppercase tracking-wider text-text-muted bg-surface-2/40 hover:bg-surface-2 border-b border-border-subtle transition-colors",children:[(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),r()},className:"flex-1 min-w-0 flex items-center gap-1.5 hover:text-text transition-colors",title:e.path,children:[(0,n.jsx)(t3.c_,{size:11,className:`flex-shrink-0 transition-transform duration-150 ${s?"rotate-90":""}`}),(0,n.jsx)("span",{className:"truncate flex-1 text-left",children:e.branch||e.name||e.path.split("/").pop()}),!e.isMain&&(0,n.jsx)(t3.dx,{size:10,className:"flex-shrink-0 opacity-60"})]}),a&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),a()},title:l,className:"p-0.5 shrink-0 hover:text-red-500 transition-colors",children:(0,n.jsx)(t3.TB,{size:11})})]}),s&&(0,n.jsx)("div",{className:"flex-1 min-h-0 flex flex-col",children:i})]}):(0,n.jsx)("div",{className:"flex-1 min-h-0 flex flex-col",children:i})}function ig({icon:e,label:t,onClick:s,active:r,disabled:a,spinning:l}){return(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),s?.()},disabled:a,title:t,className:`p-2 sm:p-1 rounded-[3px] hover:bg-surface-2 transition-colors disabled:opacity-40 ${r?"text-brand-500":"text-text-muted hover:text-text"}`,children:(0,n.jsx)(e,{size:16,className:`sm:w-[13px] sm:h-[13px] ${l?"animate-spin":""}`})})}function iv({onClick:e,children:t}){return(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),e()},className:"w-full px-3 py-1.5 text-[11px] text-text-subtle hover:text-text hover:bg-surface-2 transition-colors text-left",children:t})}function iy({repo:e,changedCount:t=0,isOpen:s,onToggle:r,onHide:a,children:l}){let{t:i}=(0,se.s)();return(0,n.jsxs)("div",{className:"border-b border-border-subtle last:border-0",children:[(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),r()},className:"group/repo w-full sticky top-0 z-10 px-2 py-1 flex items-center gap-1.5 text-[10px] uppercase tracking-wider text-text-muted hover:text-text bg-surface-3 border-b border-border-subtle transition-colors",children:[(0,n.jsx)(t3.c_,{size:11,className:`flex-shrink-0 transition-transform duration-150 ${s?"rotate-90":""}`}),(0,n.jsx)("span",{className:"truncate flex-1 text-left",title:e.relPath||e.name,children:e.relPath||e.name}),e.branch&&(0,n.jsx)("span",{className:"text-text-subtle normal-case tracking-normal truncate max-w-[45%]",title:e.branch,children:e.branch}),t>0&&(0,n.jsx)("span",{className:"px-1 rounded-[2px] bg-brand-500/15 text-brand-500 normal-case tracking-normal flex-shrink-0",children:t}),a&&(0,n.jsx)("span",{role:"button",tabIndex:-1,onClick:e=>{e.stopPropagation(),(0,t7.e)(),a()},className:"p-0.5 text-text-subtle hover:text-text flex-shrink-0 opacity-100 sm:opacity-0 sm:group-hover/repo:opacity-100 transition-opacity",title:i("workspaces.hideRepo"),children:(0,n.jsx)(t3.X_,{size:11})})]}),s&&l]})}let iw=(0,r.memo)(function({workspacePath:e,filesRoot:t=null,cwdHint:s=null,fileBus:a,activeFile:l,tab:i,onTabChange:o,width:c,onResize:d,onClose:u,onOpenFile:m,onNewTerminal:x,onAddWorkspace:p,onOpenFiles:h,homeDir:f,changedPerRepo:b={},hiddenRepos:g=[],onHiddenReposChange:v,isDesktop:y=!0}){let{t:w}=(0,se.s)(),k=a||t2.getState(),j="trees"===i?"git":i,{repos:N,refresh:S,scanning:C,deep:T,scanDeeper:R}=function(e,t){let[s,n]=(0,r.useState)([]),[a,l]=(0,r.useState)(!1),i=t||t2.getState(),[o,c]=(0,r.useState)(!1),d=(0,r.useCallback)(async(t,s)=>{if(!e||!i?.gitScanRepos)return;l(!0),t&&await i.gitRefreshRepos?.(e);let r=await i.gitScanRepos(e,s?3:1);l(!1),n(r?.success&&r.repos||[])},[e,i]);return(0,r.useEffect)(()=>{let e=setTimeout(()=>void d(!1,o),0);return()=>clearTimeout(e)},[d,o]),{repos:s,refresh:(0,r.useCallback)(()=>d(!0,o),[d,o]),scanning:a,deep:o,scanDeeper:(0,r.useCallback)(()=>c(!0),[])}}(e,k),E=t||e,{roots:_,refresh:$}=function(e,t){let[s,n]=(0,r.useState)([]),a=t||t2.getState(),l=(0,r.useCallback)(async()=>{if(!e||!a?.gitWorktreeList)return n([]);let t=await a.gitWorktreeList(e);if(!t?.success||!t.worktrees?.length)return n([{path:e,branch:null,name:ly(e)}]);n(t.worktrees.map(e=>({path:e.path,branch:e.branch,name:ly(e.path),isMain:e.isMain})))},[e,a]);return(0,r.useEffect)(()=>{let e=setTimeout(()=>void l(),0);return()=>clearTimeout(e)},[l]),{roots:s,refresh:l}}(E,k),M=()=>{S(),$()},{branch:P}=aU(e,k),A=(0,r.useRef)({path:null,branch:null});(0,r.useEffect)(()=>{let t=A.current;A.current={path:e,branch:P},t.path===e&&null!==t.branch&&t.branch!==P&&(S(),$(),window.dispatchEvent(new Event(tp)))},[P,e]);let[z,I]=(0,r.useState)({forWorkspace:e,showClean:!1,openRepo:null}),L=z.forWorkspace===e?z:{showClean:!1,openRepo:null},D=L.showClean,F=L.openRepo,O=new Set(g),B=e=>b[e.path]??e.changedCount??0,W=t=>!t.relPath||t.path===e,K=N.filter(e=>!O.has(e.path)),H=K.filter(e=>B(e)>0).reduce((e,t)=>e+B(t),0),U=D?K:K.filter(e=>B(e)>0||W(e)),q=D?0:K.length-U.length,V=N.length-K.length,X=F??(1===U.length?U[0].path:null),G=!y||c>=el.min,[J,Y]=(0,r.useState)(null),[Z,Q]=(0,r.useState)(null),[ee,et]=(0,r.useState)(null),[es,en]=(0,r.useState)(null),er=async e=>{et(null);let t=await k.gitWorktreeRemove(e.path,e.path,{probe:!0,deleteBranch:e.branch||void 0});if(!t?.success)return et(t?.error||"Probe failed");Q({root:e,sessions:t.sessions||[],branchMerged:t.branchMerged})},ea=async e=>{et(null),en(null);let t=await k.gitWorktreeRemove(e.path,e.path,{confirmed:!0,deleteBranch:e.branch||void 0});if(Q(null),!t?.success)return et(t?.error||"Remove failed");t.branchKept&&en(e.branch),M()},ei=s||E,eo=(0,r.useMemo)(()=>{let e=_.filter(e=>ei===e.path||ei?.startsWith(`${e.path}/`));return e.length?e.sort((e,t)=>t.path.length-e.path.length)[0].path:(_.find(e=>e.isMain)||_[0])?.path||E},[_,ei,E]),[ec,ed]=(0,r.useState)({forProbe:null,path:null}),eu=ec.forProbe===ei?ec.path:eo,[em,ex]=(0,r.useState)({forRoot:null,searchDir:null,show:!1,query:"",results:[],loading:!1}),ep=em.forRoot===E?em:{show:!1,searchDir:null,query:"",results:[],loading:!1},eh=(0,r.useRef)(null),ef=(0,r.useCallback)(()=>{ex({forRoot:null,searchDir:null,show:!1,query:"",results:[],loading:!1})},[]),eb=(0,r.useCallback)(e=>{ex({forRoot:E,searchDir:e,show:!0,query:"",results:[],loading:!1})},[E]),eg=(0,r.useCallback)(()=>{ex(e=>{let t={...e,searchDir:null};return e.query&&e.query.length>=2&&(t.loading=!0,k.searchFiles(E,e.query).then(e=>{ex(t=>t.loading?{...t,results:e.success?e.files:[],loading:!1}:t)})),t})},[k,E]),ev=(0,r.useCallback)(e=>{if(ex(t=>({...t,query:e})),eh.current&&clearTimeout(eh.current),!e||e.length<2)return void ex(e=>({...e,results:[],loading:!1}));ex(e=>({...e,loading:!0}));let t=ep.searchDir||E;eh.current=setTimeout(async()=>{let s=await k.searchFiles(t,e);ex(t=>t.query===e&&t.loading?{...t,results:s.success?s.files:[],loading:!1}:t)},300)},[k,E,ep.searchDir]);return(0,r.useEffect)(()=>()=>{eh.current&&clearTimeout(eh.current)},[]),(0,n.jsxs)("div",{className:`h-full flex flex-col terminal-sidebar-bg border-l border-border-subtle relative shrink ${y?"":"pb-safe"}`,style:y?{width:c,flexBasis:c,minWidth:el.min}:void 0,children:[(0,n.jsxs)("div",{className:`h-11 ${rF} pl-1 pr-0.5 flex items-stretch gap-0 border-b border-border-subtle flex-shrink-0`,children:[ip.map(({key:e,icon:t,labelKey:s})=>(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),o(e)},className:`px-3 sm:px-2 flex items-center justify-center gap-1 text-[11px] border-b-2 -mb-px transition-colors ${j===e?"text-text border-brand-500":"text-text-muted border-transparent hover:text-text"}`,title:w(s),children:[(0,n.jsx)(t,{size:18,className:"sm:w-[15px] sm:h-[15px]"}),G&&(0,n.jsx)("span",{children:w(s)}),"git"===e&&H>0&&(0,n.jsx)("span",{className:"min-w-[14px] h-[14px] px-[4px] rounded-full bg-brand-500 text-white text-[9px] font-semibold flex items-center justify-center leading-none",children:H>99?"99+":H})]},e)),(0,n.jsx)("div",{className:"flex-1"}),(0,n.jsxs)("div",{className:"flex items-center gap-1 sm:gap-0.5",children:[(0,n.jsx)(ig,{icon:t3.e9,label:w("workspaces.refreshRepos"),onClick:()=>{M(),J?.refresh?.()},disabled:C,spinning:C}),u&&(0,n.jsx)(ig,{icon:t3.X,label:w("common.close"),onClick:u})]})]}),"files"===j&&e&&(0,n.jsx)("div",{className:`h-11 ${rF} px-2 flex items-center gap-1.5 border-b border-border-subtle flex-shrink-0`,children:ep.show?(0,n.jsxs)("div",{className:"flex-1 flex items-center gap-2 min-w-0",children:[(0,n.jsx)(t3.vj,{size:14,className:"text-text-subtle shrink-0"}),(0,n.jsx)("input",{type:"text",value:ep.query,onChange:e=>ev(e.target.value),onKeyDown:e=>{"Escape"===e.key&&ef()},placeholder:ep.searchDir?`Search in ${ep.searchDir.split("/").pop()}…`:w("files.searchPlaceholder"),className:"flex-1 min-w-0 bg-transparent text-xs text-text placeholder-text-subtle focus:outline-none",autoFocus:!0}),ep.loading?(0,n.jsx)(t3.kr,{size:13,className:"animate-spin text-brand-500 shrink-0"}):ep.query?(0,n.jsx)("button",{type:"button",onClick:()=>ev(""),className:"p-1 text-text-subtle hover:text-text",children:(0,n.jsx)(t3.X,{size:12})}):null,(0,n.jsx)(ig,{icon:t3.X,label:w("common.close"),onClick:ef})]}):(0,n.jsxs)(n.Fragment,{children:[J&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(ig,{icon:t3.FW,label:w("files.newFile"),onClick:J.newFile}),(0,n.jsx)(ig,{icon:t3.JU,label:w("files.newFolder"),onClick:J.newFolder})]}),(0,n.jsx)(ig,{icon:t3.vj,label:w("files.searchFiles"),onClick:()=>{if(ep.show)return ef();ex({forRoot:E,searchDir:null,show:!0,query:"",results:[],loading:!1})},active:ep.show}),(0,n.jsx)("div",{className:"flex-1"}),J?.hasExpanded&&(0,n.jsx)(ig,{icon:t3.WE,label:w("fileExplorer.collapseAll"),onClick:J.collapseAll}),J&&(0,n.jsx)(ig,{icon:J.showHidden?t3.kU:t3.X_,label:w("files.toggleHidden"),onClick:J.toggleHidden,active:J.showHidden}),h&&(0,n.jsx)(ig,{icon:t3.Gr,label:w("workspaces.openFullFiles"),onClick:h})]})}),"files"===j&&e&&ep.show&&ep.searchDir&&(0,n.jsxs)("div",{className:"px-3 py-1 bg-surface-3/40 border-b border-border-subtle flex items-center justify-between text-[11px] text-text-muted flex-shrink-0",children:[(0,n.jsxs)("div",{className:"flex items-center gap-1.5 min-w-0",children:[(0,n.jsx)(t3.vd,{size:12,className:"text-yellow-500/80 shrink-0"}),(0,n.jsx)("span",{className:"text-text-subtle shrink-0",children:"Folder:"}),(0,n.jsx)("span",{className:"font-medium text-text truncate max-w-[150px]",title:ep.searchDir,children:ep.searchDir.split("/").pop()})]}),(0,n.jsx)("button",{type:"button",onClick:eg,className:"text-brand-500 hover:text-brand-400 hover:underline shrink-0 text-[11px] ml-2",children:"Search all"})]}),(0,n.jsx)("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden",children:e?"files"===j?ep.show?(0,n.jsx)(ih,{results:ep.results,loading:ep.loading,query:ep.query,searchDir:ep.searchDir,workspace:E,onOpen:e=>{m?.(e),ef()}}):(0,n.jsxs)("div",{className:"flex-1 min-h-0 flex flex-col",children:[(ee||es)&&(0,n.jsxs)("div",{className:"px-3 py-1.5 border-b border-border-subtle text-[11px]",children:[ee&&(0,n.jsx)("p",{className:"text-red-500 break-words whitespace-pre-wrap",children:ee}),es&&(0,n.jsx)("p",{className:"text-text-muted break-words",children:w("workspaces.worktreeBranchKept",{branch:es})})]}),_.map(e=>(0,n.jsx)(ib,{root:e,multiple:_.length>1,isOpen:1===_.length||eu===e.path,onToggle:()=>ed({forProbe:ei,path:eu===e.path?null:e.path}),onRemove:e.isMain?null:()=>{(0,t7.e)(),er(e)},removeLabel:w("workspaces.removeWorktree"),children:(0,n.jsx)(l7,{workspace:e.path,fileBus:k,activeFile:l,onOpenFile:m,onNewTerminal:x,onSearchFolder:eb,compact:!0,onActions:e.path===eu||1===_.length?Y:void 0})},e.path))]}):"git"===j?(0,n.jsxs)("div",{className:"flex-1 min-h-0 overflow-y-auto modal-scrollable",children:[U.map(t=>(0,n.jsx)(iy,{repo:t,changedCount:B(t),isOpen:X===t.path,onToggle:()=>{let s;return s=X===t.path?"":t.path,I({...L,forWorkspace:e,openRepo:s})},onHide:v&&!W(t)?()=>{let e;return e=t.path,v?.([...g,e])}:null,children:(0,n.jsx)(ix,{workspace:t.path,fileBus:k,onOpenFile:m,tagDiffWithRepo:!0})},t.path)),!U.length&&!C&&(0,n.jsx)("p",{className:"p-4 text-xs text-text-subtle italic",children:D?w("workspaces.emptyWorkspace"):w("git.noChanges")}),(q>0||V>0||!T)&&(0,n.jsxs)("div",{className:"border-t border-border-subtle mt-1",children:[q>0&&(0,n.jsx)(iv,{onClick:()=>I({...L,forWorkspace:e,showClean:!0}),children:w("workspaces.showCleanRepos",{count:q})}),V>0&&(0,n.jsx)(iv,{onClick:()=>v?.([]),children:w("workspaces.showHiddenRepos",{count:V})}),!T&&(0,n.jsx)(iv,{onClick:R,children:w("workspaces.scanDeeper")})]})]}):null:(0,n.jsxs)("div",{className:"p-4 flex flex-col items-center gap-2 text-center",children:[(0,n.jsx)(t3.vd,{size:22,className:"text-text-subtle"}),(0,n.jsx)("p",{className:"text-xs text-text-subtle",children:w("workspaces.emptyWorkspace")}),p&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),p()},className:"mt-1 px-2 py-1 text-[11px] text-brand-500 bg-brand-500/10 hover:bg-brand-500/20 rounded-[3px] transition-colors",children:w("workspaces.selectFolder")})]})}),(0,n.jsx)(t9.A,{isOpen:!!Z,onClose:()=>Q(null),onConfirm:()=>{(0,t7.e)(),ea(Z.root)},title:w("workspaces.removeWorktree"),message:Z?[w("workspaces.removeWorktreeFolder",{path:Z.root.path}),Z.root.branch&&w(!0===Z.branchMerged?"workspaces.removeWorktreeBranchDelete":!1===Z.branchMerged?"workspaces.removeWorktreeBranchKeep":"workspaces.removeWorktreeBranch",{branch:Z.root.branch}),Z.sessions?.length?w("workspaces.removeWorktreeSessions",{count:Z.sessions.length,names:Z.sessions.map(e=>e.name).join(", ")}):null].filter(Boolean).join("\n"):""}),y&&(0,n.jsx)("div",{onPointerDown:e=>sS(e,{startWidth:c,axis:-1,onWidth:e=>d?.(e)}),className:"absolute top-0 left-0 bottom-0 w-1 cursor-col-resize hover:bg-brand-500/40 transition-colors z-20"})]})});function ik(e){return e?e<1024?`${e}B`:e<1048576?`${(e/1024).toFixed(1)}KB`:`${(e/1048576).toFixed(1)}MB`:""}function ij({filePath:e,fileBus:t}){let[s,a]=(0,r.useState)(""),[l,i]=(0,r.useState)(null),[o,c]=(0,r.useState)(""),[d,u]=(0,r.useState)(!0),[m,x]=(0,r.useState)(1),[p,h]=(0,r.useState)({x:0,y:0}),[f,b]=(0,r.useState)(0),g=(0,r.useRef)(null),v=(0,r.useRef)(null),y=(0,r.useRef)(null),w=(0,r.useRef)(null),k=(0,r.useRef)(null),j=(0,r.useRef)(null),N=(0,r.useRef)(0);(0,r.useEffect)(()=>{let s=!1,n=[],r="";u(!0),c(""),a(""),i(null),x(1),h({x:0,y:0}),b(0),y.current=null,w.current&&(URL.revokeObjectURL(w.current),w.current=null);let l=e.toLowerCase();if(l.endsWith(".tif")||l.endsWith(".tiff"))return t.readMedia(e).then(e=>{s||(e.success?(a(e.dataUrl),i({size:e.originalSize||e.size,width:e.width,height:e.height,scaled:e.scaled,originalWidth:e.originalWidth,originalHeight:e.originalHeight})):c(e.error||"Failed to load image"),u(!1))}),()=>{s=!0};let o=t.streamMedia(e,{onMeta:e=>{s||(r=e.mime||"image/*",i({size:e.size,width:e.width,height:e.height,scaled:e.scaled,originalWidth:e.originalWidth,originalHeight:e.originalHeight}))},onChunk:e=>{s||n.push(e)},onDone:()=>{if(s)return;let e=new Blob(n,{type:r});if(e.size>4194304){y.current=e,b(e.size),u(!1);return}w.current=URL.createObjectURL(e),a(w.current),u(!1)},onError:e=>{s||(c(e.message||"Failed to load image"),u(!1))}});return()=>{s=!0,o?.()}},[e,t]),(0,r.useEffect)(()=>()=>{w.current&&URL.revokeObjectURL(w.current)},[]);let S=(0,r.useCallback)((e,t,s)=>{let n=v.current,r=g.current;if(!n||!r)return{x:e,y:t};let a=r.clientWidth,l=r.clientHeight,i=n.clientWidth*s,o=n.clientHeight*s,c=Math.max(0,(i-a)/2),d=Math.max(0,(o-l)/2);return{x:Math.max(-c,Math.min(c,e)),y:Math.max(-d,Math.min(d,t))}},[]),C=(0,r.useCallback)(()=>{x(1),h({x:0,y:0})},[]),T=(0,r.useCallback)((e,t,s)=>{x(n=>{let r=Math.max(.2,Math.min(8,n*e));if(r===n)return n;if(null!=t&&null!=s){let e=g.current;if(e){let a=e.clientWidth/2,l=e.clientHeight/2,i=t-a,o=s-l;h(e=>S((e.x-i)*(r/n)+i,(e.y-o)*(r/n)+o,r))}}else h(e=>S(e.x,e.y,r));return r})},[S]),R=(e,t)=>Math.hypot(e.clientX-t.clientX,e.clientY-t.clientY),E=(0,r.useCallback)(e=>{if(2===e.touches.length)j.current=null,k.current={dist:R(e.touches[0],e.touches[1]),scale:m,pos:p};else if(1===e.touches.length){let t=Date.now();if(t-N.current<300){m>1.01?C():(x(2),h({x:0,y:0})),N.current=0,j.current=null;return}N.current=t,m>1.01&&(j.current={x:e.touches[0].clientX,y:e.touches[0].clientY,pos:p})}},[m,p,C]),_=(0,r.useCallback)(e=>{if(2===e.touches.length&&k.current){e.preventDefault();let t=R(e.touches[0],e.touches[1]),s=Math.max(.2,Math.min(8,k.current.scale*(t/k.current.dist)));x(s),h(e=>S(e.x,e.y,s))}else if(1===e.touches.length&&j.current){e.preventDefault();let t=e.touches[0],s=t.clientX-j.current.x,n=t.clientY-j.current.y;h(S(j.current.pos.x+s,j.current.pos.y+n,m))}},[m,S]),$=(0,r.useCallback)(e=>{e.touches.length<2&&(k.current=null),0===e.touches.length&&(j.current=null)},[]),M=(0,r.useCallback)(e=>{e.preventDefault();let t=e.deltaY<0?1.1:1/1.1,s=g.current?.getBoundingClientRect();T(t,s?e.clientX-s.left:null,s?e.clientY-s.top:null)},[T]);if(d)return(0,n.jsxs)("div",{className:"h-full flex items-center justify-center text-text-muted gap-2",children:[(0,n.jsx)(t3.kr,{className:"animate-spin",size:20}),(0,n.jsx)("span",{children:"Loading image..."})]});if(o)return(0,n.jsx)("div",{className:"h-full flex items-center justify-center text-red-400 text-sm",children:o});if(f)return(0,n.jsxs)("div",{className:"h-full flex flex-col items-center justify-center gap-3 text-text-muted px-6 text-center",children:[(0,n.jsx)("span",{className:"text-sm font-medium text-text truncate max-w-full",title:e,children:e.split("/").pop()}),(0,n.jsxs)("span",{className:"text-xs",children:[ik(f)," — decoding an image this large can crash mobile Safari."]}),(0,n.jsx)("button",{onClick:()=>{let e=y.current;e&&(w.current=URL.createObjectURL(e),a(w.current),b(0))},className:"px-3 py-1.5 rounded bg-surface-2 hover:bg-surface-3 text-text text-sm",children:"Open anyway"})]});let P=l?.width&&l?.height?`${l.width}\xd7${l.height}`:"",A=l?.scaled&&l?.originalWidth&&l?.originalWidth!==l?.width;return(0,n.jsxs)("div",{className:"h-full flex flex-col bg-bg",children:[(0,n.jsxs)("div",{className:"bg-surface border-b border-border px-3 py-1.5 flex items-center gap-2 text-xs text-text-muted",children:[(0,n.jsx)("span",{className:"truncate flex-1",title:e,children:e.split("/").pop()}),l?.size?(0,n.jsx)("span",{className:"text-text-subtle",children:ik(l.size)}):null,P?(0,n.jsxs)("span",{className:"text-text-subtle",children:[P,A?" ↓":""]}):null,(0,n.jsx)("button",{onClick:()=>T(1/1.2),className:"px-2 hover:bg-surface-2 rounded",children:"−"}),(0,n.jsxs)("span",{className:"w-12 text-center",children:[Math.round(100*m),"%"]}),(0,n.jsx)("button",{onClick:()=>T(1.2),className:"px-2 hover:bg-surface-2 rounded",children:"+"}),(0,n.jsx)("button",{onClick:C,className:"px-2 hover:bg-surface-2 rounded",children:"Reset"})]}),(0,n.jsx)("div",{ref:g,className:"flex-1 min-h-0 overflow-hidden flex items-center justify-center bg-[repeating-conic-gradient(#0001_0%_25%,transparent_0%_50%)] bg-[length:20px_20px] touch-none",onTouchStart:E,onTouchMove:_,onTouchEnd:$,onWheel:M,children:(0,n.jsx)("img",{ref:v,src:s,alt:e,draggable:!1,onLoad:e=>i(t=>({...t,width:e.target.naturalWidth,height:e.target.naturalHeight})),style:{transform:`translate(${p.x}px, ${p.y}px) scale(${m})`,transformOrigin:"center",willChange:"transform"},className:"max-w-full max-h-full object-contain select-none"})})]})}function iN({filePath:e,fileBus:t}){let[s,a]=(0,r.useState)(""),[l,i]=(0,r.useState)(""),[o,c]=(0,r.useState)(0),[d,u]=(0,r.useState)(""),[m,x]=(0,r.useState)(!0);if((0,r.useEffect)(()=>{let s=!1,n=null,r=null,l=null,o=null,d=[],m=!1;x(!0),u(""),a(""),i(""),c(0);let p=!1,h="",f=()=>{if(!s&&!p&&o&&!o.updating){if(d.length)return void o.appendBuffer(d.shift());if(m&&r&&"open"===r.readyState)try{r.endOfStream()}catch{}}};return n=t.streamMedia(e,{onMeta:({mime:e,size:t})=>{if(!s){if(i(e),c(t),!("u">typeof MediaSource&&MediaSource.isTypeSupported(e))){p=!0,h=e;return}r=new MediaSource,a(l=URL.createObjectURL(r)),x(!1),r.addEventListener("sourceopen",()=>{s||((o=r.addSourceBuffer(e)).addEventListener("updateend",f),f())})}},onChunk:e=>{!s&&(d.push(e),p||f())},onDone:()=>{if(!s)if(p){let e=new Blob(d,{type:h||"application/octet-stream"});a(l=URL.createObjectURL(e)),x(!1)}else m=!0,f()},onError:e=>{s||(u(e.message||"Stream error"),x(!1))}}),()=>{s=!0,n?.(),l&&URL.revokeObjectURL(l);try{r&&"open"===r.readyState&&r.endOfStream()}catch{}}},[e,t]),m)return(0,n.jsxs)("div",{className:"h-full flex items-center justify-center text-text-muted gap-2",children:[(0,n.jsx)(t3.kr,{className:"animate-spin",size:20}),(0,n.jsx)("span",{children:"Loading media..."})]});if(d)return(0,n.jsx)("div",{className:"h-full flex items-center justify-center text-red-400 text-sm",children:d});let p=l.startsWith("video/"),h=e.split("/").pop();return(0,n.jsxs)("div",{className:"h-full flex flex-col bg-bg",children:[(0,n.jsxs)("div",{className:"bg-surface border-b border-border px-3 py-1.5 flex items-center gap-2 text-xs text-text-muted",children:[(0,n.jsx)("span",{className:"truncate flex-1",title:e,children:h}),o?(0,n.jsx)("span",{className:"text-text-subtle",children:o?o<1024?`${o}B`:o<1048576?`${(o/1024).toFixed(1)}KB`:`${(o/1048576).toFixed(1)}MB`:""}):null]}),(0,n.jsx)("div",{className:"flex-1 min-h-0 overflow-auto flex items-center justify-center bg-black/30",children:p?(0,n.jsx)("video",{src:s,controls:!0,className:"max-h-full max-w-full"}):(0,n.jsx)("audio",{src:s,controls:!0,className:"w-full max-w-md"})})]})}function iS({filePath:e,fileBus:t}){let[a,l]=(0,r.useState)(!0),[i,o]=(0,r.useState)(""),[c,d]=(0,r.useState)([]),[u,m]=(0,r.useState)(0),[x,p]=(0,r.useState)([]),h=(0,r.useRef)(null),f=(0,r.useRef)(null),b=(0,r.useRef)(null);if((0,r.useEffect)(()=>{let n=!1,r=null,a=[],i=tn(e,e9);l(!0),o(""),d([]),m(0),p([]),f.current=null,h.current&&(h.current.innerHTML="");let c=async e=>{try{if(i){let{renderAsync:t}=await s.e(910).then(s.bind(s,80910));if(n||!h.current){n||l(!1);return}for(let s of(await t(new Blob([e]),h.current,void 0,{inWrapper:!0,renderAltChunks:!1}),h.current.querySelectorAll("a[href]"))){let e=s.getAttribute("href")||"";/^(https?:|mailto:|#)/i.test(e.trim())||s.removeAttribute("href")}n||l(!1)}else{let t=await Promise.all([s.e(8874),s.e(4930)]).then(s.bind(s,19819));if(n)return;b.current=t,f.current=t.read(e,{type:"array"}),d(f.current.SheetNames),m(0),(()=>{let e=f.current,t=b.current;if(!e||!t)return;let s=e.SheetNames[0];s&&(p(t.utils.sheet_to_json(e.Sheets[s],{header:1,defval:"",raw:!1})),l(!1))})()}}catch(e){n||(o(e.message||"Failed to render"),l(!1))}};return r=t.streamMedia(e,{onChunk:e=>{n||a.push(e)},onDone:()=>{if(n)return;let e=new Uint8Array(a.reduce((e,t)=>e+t.byteLength,0)),t=0;for(let s of a)e.set(s,t),t+=s.byteLength;c(e)},onError:e=>{n||(o(e.message||"Failed to load"),l(!1))}}),()=>{n=!0,r?.()}},[e,t]),(0,r.useEffect)(()=>{let e=f.current,t=b.current;if(!e||!t)return;let s=e.SheetNames[u];s&&p(t.utils.sheet_to_json(e.Sheets[s],{header:1,defval:"",raw:!1}))},[u]),i)return(0,n.jsx)("div",{className:"h-full flex items-center justify-center text-red-400 text-sm",children:i});let g=tn(e,e9);return(0,n.jsxs)("div",{className:"h-full flex flex-col relative",children:[a&&(0,n.jsxs)("div",{className:"absolute inset-0 z-10 flex items-center justify-center gap-2 bg-surface text-text-muted",children:[(0,n.jsx)(t3.kr,{className:"animate-spin",size:20}),(0,n.jsx)("span",{children:"Loading document..."})]}),!g&&c.length>1&&(0,n.jsx)("div",{className:"flex gap-1 overflow-x-auto bg-surface border-b border-border px-2 py-1 flex-shrink-0",children:c.map((e,t)=>(0,n.jsx)("button",{onClick:()=>m(t),className:`px-2 py-1 text-xs rounded whitespace-nowrap transition-colors ${t===u?"bg-brand-500 text-white":"bg-surface-2 text-text-muted hover:text-text"}`,children:e},t))}),(0,n.jsx)("div",{className:"flex-1 min-h-0 overflow-auto bg-white text-black",children:g?(0,n.jsx)("div",{ref:h,className:"p-4"}):(0,n.jsx)("div",{className:"p-2",children:(0,n.jsx)("table",{className:"border-collapse",children:(0,n.jsx)("tbody",{children:x.map((e,t)=>(0,n.jsx)("tr",{children:e.map((e,t)=>(0,n.jsx)("td",{className:"border border-gray-300 px-2 py-1 whitespace-pre-wrap align-top",children:e},t))},t))})})})})]})}function iC({filePath:e,fileBus:t}){let[s,a]=(0,r.useState)(""),[l,i]=(0,r.useState)(""),[o,c]=(0,r.useState)(!0);return((0,r.useEffect)(()=>{let s=!1,n=null,r=[],l="application/pdf";c(!0),i(""),a("");let o=t.streamMedia(e,{onMeta:({mime:e})=>{!s&&e&&(l=e)},onChunk:e=>{s||r.push(e)},onDone:()=>{if(s)return;let e=new Blob(r,{type:l}),t=URL.createObjectURL(e);n=t,a(t),c(!1)},onError:e=>{s||(i(e.message||"Failed to load PDF"),c(!1))}});return()=>{s=!0,o(),n&&URL.revokeObjectURL(n)}},[e,t]),o)?(0,n.jsxs)("div",{className:"h-full flex items-center justify-center text-text-muted gap-2",children:[(0,n.jsx)(t3.kr,{className:"animate-spin",size:20}),(0,n.jsx)("span",{children:"Loading PDF..."})]}):l?(0,n.jsx)("div",{className:"h-full flex items-center justify-center text-red-400 text-sm",children:l}):(0,n.jsx)("iframe",{src:s,title:"PDF preview",className:"h-full w-full bg-bg"})}let iT=e=>tn(e,e3)||tn(e,e4)||tn(e,e6)||tn(e,e8)||tn(e,e9)||tn(e,e7);function iR({filePath:e,fileBus:t}){return tn(e,e8)?(0,n.jsx)(iC,{filePath:e,fileBus:t},e):tn(e,e9)||tn(e,e7)?(0,n.jsx)(iS,{filePath:e,fileBus:t},e):tn(e,e4)||tn(e,e6)?(0,n.jsx)(iN,{filePath:e,fileBus:t},e):(0,n.jsx)(ij,{filePath:e,fileBus:t},e)}function iE({filePath:e,fileBus:t}){let[s,n]=(0,r.useState)(!0),[a,l]=(0,r.useState)(null),[i,o]=(0,r.useState)(""),[c,d]=(0,r.useState)(!1),[u,m]=(0,r.useState)(!1),[x,p]=(0,r.useState)(!1),h=(0,r.useRef)(""),f=(0,r.useRef)(null),b=(0,r.useRef)(null),[g,v]=(0,r.useState)(!1),y=(0,r.useCallback)(e=>{f.current=e},[]),w=(0,r.useCallback)(async(s=()=>!1)=>{n(!0),o(""),d(!1),v(!1);let r=await t.readFile(e);if(s())return;if(!r?.success){o(r?.error||""),n(!1);return}let a=r.content;if(r.streamInstead)try{let n=[];if(await new Promise((s,r)=>{t.streamMedia(e,{onMeta:()=>{},onChunk:e=>n.push(e),onDone:s,onError:r})}),s())return;a=await new Blob(n).text()}catch(e){if(s())return;o(e?.message||""),n(!1);return}h.current=a,l(a),n(!1)},[e,t]);(0,r.useEffect)(()=>{let t=!1;if(!e){n(!1),l(null),d(!1),o(""),v(!1);return}return w(()=>t),()=>{t=!0}},[e,w]);let k=(0,r.useCallback)(()=>{c?v(!0):w()},[c,w]);(0,r.useEffect)(()=>()=>clearTimeout(b.current),[]);let j=(0,r.useCallback)(e=>{d(e!==h.current)},[]),N=(0,r.useCallback)(async()=>{let s=f.current?.();if(null==s||u||s===h.current)return!0;m(!0);let n=await t.writeFile(e,s);return(m(!1),n?.success)?(h.current=s,d(!1),o(""),p(!0),clearTimeout(b.current),b.current=setTimeout(()=>p(!1),2e3),window.dispatchEvent(new CustomEvent("fileExplorer:fileSaved",{detail:{filePath:e}})),!0):(o(n?.error||""),!1)},[e,t,u]);return{loading:s,content:a,error:i,dirty:c,saving:u,justSaved:x,staleOnDisk:g,register:y,onTextChanged:j,save:N,discard:(0,r.useCallback)(()=>{d(!1),l(h.current)},[]),setError:o,reload:w,onChangedOnDisk:k}}function i_({dirty:e,onSave:t}){let[s,n]=(0,r.useState)(null);(0,r.useEffect)(()=>{if(!e)return;let t=e=>(e.preventDefault(),e.returnValue="","");return window.addEventListener("beforeunload",t),()=>window.removeEventListener("beforeunload",t)},[e]);let a=(0,r.useCallback)(t=>{if(!e)return t();n(()=>t)},[e]),l=(0,r.useCallback)(async()=>{await t()&&(n(null),s?.())},[t,s]),i=(0,r.useCallback)(()=>{n(null),s?.()},[s]);return{guard:a,asking:!!s,saveThenLeave:l,discardAndLeave:i,cancel:(0,r.useCallback)(()=>n(null),[])}}function i$({isOpen:e,fileName:t,onSave:s,onDiscard:a,onCancel:l}){let{t:i}=(0,se.s)(),o=(0,r.useRef)(null);return((0,r.useEffect)(()=>{if(!e)return;let t=requestAnimationFrame(()=>{o.current?.focus()});return()=>cancelAnimationFrame(t)},[e]),(0,r.useEffect)(()=>{if(!e)return;let t=e=>{if("Escape"===e.key)e.preventDefault(),e.stopPropagation(),l?.();else if("Enter"===e.key){if(document.activeElement?.tagName==="BUTTON"&&document.activeElement!==o.current)return;e.preventDefault(),e.stopPropagation(),(0,t7.e)(),s?.()}else"d"!==e.key&&"D"!==e.key||e.metaKey||e.ctrlKey||e.altKey||(e.preventDefault(),e.stopPropagation(),(0,t7.e)(),a?.())};return window.addEventListener("keydown",t,!0),()=>window.removeEventListener("keydown",t,!0)},[e,l,s,a]),e)?(0,n.jsxs)("div",{className:"fixed inset-0 z-[90] flex items-center justify-center px-4",style:{paddingTop:"max(1rem, env(safe-area-inset-top))",paddingBottom:"max(1rem, env(safe-area-inset-bottom))"},onClick:l,children:[(0,n.jsx)("div",{className:"absolute inset-0 bg-black/60"}),(0,n.jsxs)("div",{role:"dialog","aria-modal":"true",className:"relative card-elev w-full max-w-sm p-5",onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:[(0,n.jsx)("h3",{className:"text-[15px] font-semibold text-text mb-1.5",children:i("editor.unsavedTitle",{name:t||""})}),(0,n.jsx)("p",{className:"text-[13px] text-text-muted leading-snug mb-5",children:i("editor.unsavedBody")}),(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),a?.()},className:"px-3 py-2 text-[13px] text-text-muted hover:text-red-500 transition-colors flex items-center gap-1",children:[(0,n.jsx)("span",{children:i("editor.discard")}),(0,n.jsx)("kbd",{className:"hidden sm:inline-flex items-center text-[10px] font-mono px-1 py-0.5 rounded bg-surface-3 text-text-muted leading-none",children:"D"})]}),(0,n.jsx)("div",{className:"flex-1"}),(0,n.jsxs)("button",{onClick:l,className:"px-4 py-2 text-[13px] text-text bg-surface-2 hover:bg-surface-3 rounded-brand transition-colors flex items-center gap-1.5",children:[(0,n.jsx)("span",{children:i("common.cancel")}),(0,n.jsx)("kbd",{className:"hidden sm:inline-flex items-center text-[10px] font-mono px-1 py-0.5 rounded bg-surface-3 text-text-muted leading-none",children:"Esc"})]}),(0,n.jsxs)("button",{ref:o,onClick:()=>{(0,t7.e)(),s?.()},autoFocus:!0,className:"px-4 py-2 text-[13px] font-semibold text-white bg-brand-500 hover:bg-brand-600 rounded-brand transition-colors flex items-center gap-1.5",children:[(0,n.jsx)("span",{children:i("editor.save")}),(0,n.jsx)("kbd",{className:"hidden sm:inline-flex items-center justify-center w-4 h-4 rounded bg-white/20 text-white",children:(0,n.jsx)(t3.Lt,{size:10,strokeWidth:2.5})})]})]})]})]}):null}var iM=s(70256),iP=s(39821),iA=s(48907),iz=s(74447),iI=s(15332),iL=s(9722),iD=s(97320),iF=s(99833),iO=s(50807),iB=s(57378),iW=s(41554),iK=s(42760);let iH={javascript:(0,iz.Q2)(),html:(0,iI.qy)(),css:(0,iL.AH)(),json:(0,iD.Pq)(),markdown:(0,iF.wD)()};function iU({filePath:e,content:t,onTextChanged:s,onRegisterView:a,onSave:l,onCursorChange:i,line:o,column:c,compact:d=!1,className:u=""}){let m,{theme:x}=(0,aT.D)(),p=(0,r.useRef)(null),h=(0,r.useRef)(null),f=(0,r.useRef)(s),b=(0,r.useRef)(i),g=(0,r.useRef)(l);(0,r.useEffect)(()=>{f.current=s},[s]),(0,r.useEffect)(()=>{b.current=i},[i]),(0,r.useEffect)(()=>{g.current=l},[l]);let[v]=nj(th,14),[y]=nj(tf,!0),w=window.innerWidth<760,k=d?Math.max(9,v-4):v+ +!!w,{extension:j}={lang:m=ta["."+e.split(".").pop()?.toLowerCase()]||"plaintext",extension:iH[m]||[]};return(0,r.useEffect)(()=>{if(null==t||!p.current)return;let e=iA.$t.create({doc:t,extensions:[iM.oQ,..."dark"===x?[iO.bM]:[],j,...y?[iP.Lz.lineWrapping]:[],(0,iB.$P)(),(0,iW.yU)(),(0,iW.wm)(),iP.w4.of([{key:"Mod-s",preventDefault:!0,run:()=>(g.current?.(),!0)},...iW.Bc,...iW.OO,iK.Yc]),iP.Lz.updateListener.of(e=>{if(e.docChanged&&f.current?.(e.state.doc.toString()),e.selectionSet||e.docChanged){let t=e.state.selection.main.head,s=e.state.doc.lineAt(t);b.current?.({line:s.number,column:t-s.from+1})}}),iP.Lz.theme({"&":{height:"100%",fontSize:`${k}px`},".cm-scroller":{overflow:"auto",lineHeight:d?"1.35":""},".cm-content":{minHeight:"100%"},".cm-gutters":d?{fontSize:`${Math.max(8,k-1)}px`}:{}})]});return h.current?.destroy(),h.current=new iP.Lz({state:e,parent:p.current}),a?.(()=>h.current?.state.doc.toString()??null,h.current),()=>{h.current?.destroy(),h.current=null}},[t,e,x,y,k,d]),(0,r.useEffect)(()=>{let e=h.current;if(!e||!o)return;let t=e.state.doc,s=Math.max(1,Math.min(o,t.lines)),n=t.line(s),r=Math.min(n.from+Math.max(0,(c||1)-1),n.to);e.dispatch({selection:{anchor:r},effects:iP.Lz.scrollIntoView(r,{y:"center"})}),e.focus()},[o,c,t]),(0,n.jsx)("div",{ref:p,className:`h-full w-full overflow-hidden ${u}`})}function iq(e,t){return decodeURIComponent((t&&e.startsWith(t)?e.slice(t.length):e)||"/").replace(/^\//,"")||"/"}function iV({filePath:e,fileBus:t,reloadKey:s=0}){let{t:a}=(0,se.s)(),{getAuth:i}=(0,l.F)(),[o,c]=(0,r.useState)(null),[d,u]=(0,r.useState)(""),[m,x]=(0,r.useState)(0),[p,h]=(0,r.useState)(e),[f,b]=(0,r.useState)({entries:[],index:-1}),g=(0,r.useRef)(null),v=(0,r.useRef)(!1);p!==e&&(h(e),c(null),u(""),b({entries:[],index:-1})),(0,r.useEffect)(()=>{let s=!1;return t.previewStart(e).then(e=>{var n;if(s){e.success&&t.previewEnd(e.sessionId);return}if(!e.success)return void u(e.error||a("editor.previewFailed"));let r=(n=i(),n?.localIp&&"https:"!==window.location.protocol?`http://${n.localIp}`:n?.tunnelUrl||null);if(!r){t.previewEnd(e.sessionId),u(a("editor.previewNoRoute"));return}let l=`/preview/${e.sessionId}`;g.current=e.sessionId,c({origin:r,root:l}),b({entries:[`${l}/${encodeURIComponent(e.entry)}`],index:0})}),()=>{s=!0,g.current&&t.previewEnd(g.current),g.current=null}},[e,t]);let y=o?.root;(0,r.useEffect)(()=>{if(!y)return;let e=e=>{if(e.data?.source!=="9remote-preview"||"string"!=typeof e.data.path)return;let t=e.data.path;if(t.startsWith(y+"/")||t===y){if(v.current){v.current=!1;return}b(e=>{if(e.index>=0&&e.entries[e.index]===t)return e;let s=[...e.entries.slice(0,e.index+1),t];return{entries:s,index:s.length-1}})}};return window.addEventListener("message",e),()=>window.removeEventListener("message",e)},[y]);let w=(0,r.useCallback)(e=>{(0,t7.e)(),v.current=!0,b(t=>{let s=Math.max(0,Math.min(t.entries.length-1,t.index+e));return s===t.index?t:{...t,index:s}})},[]);if(d)return(0,n.jsx)("div",{className:"h-full flex items-center justify-center text-text-muted text-sm px-6 text-center",children:d});if(!o)return(0,n.jsx)("div",{className:"h-full flex items-center justify-center text-text-muted text-sm",children:a("common.loading")});let k=f.entries[f.index]||o.root,j=`${o.origin}${k}`,N=f.index>0,S=f.index<f.entries.length-1,C="p-1 rounded-[3px] text-text-muted hover:text-text hover:bg-surface-2 transition-colors disabled:opacity-30 disabled:hover:bg-transparent";return(0,n.jsxs)("div",{className:"h-full w-full flex flex-col bg-white",children:[(0,n.jsxs)("div",{className:"h-8 flex items-center gap-0.5 px-1.5 shrink-0 border-b border-border-subtle bg-surface",children:[(0,n.jsx)("button",{onClick:()=>w(-1),disabled:!N,title:a("editor.previewBack"),className:C,children:(0,n.jsx)(t3.JG,{size:14})}),(0,n.jsx)("button",{onClick:()=>w(1),disabled:!S,title:a("editor.previewForward"),className:C,children:(0,n.jsx)(t3.c_,{size:14})}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),x(e=>e+1)},title:a("editor.reload"),className:C,children:(0,n.jsx)(t3.e9,{size:13})}),(0,n.jsx)("span",{className:"flex-1 min-w-0 truncate px-2 py-0.5 mx-1 rounded-[3px] bg-surface-2 text-[11px] text-text-muted",title:iq(k,o.root),children:iq(k,o.root)}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),window.open(j,"_blank","noopener")},title:a("editor.previewOpenTab"),className:C,children:(0,n.jsx)(t3.Gr,{size:13})})]}),(0,n.jsx)("iframe",{src:j,sandbox:"allow-scripts allow-forms allow-popups",className:"flex-1 min-h-0 w-full border-0",title:"HTML preview"},`${j}|${f.index}|${s}|${m}`)]})}let iX=null,iG=0;function iJ({content:e,reloadKey:t=0}){let a,l,{t:i}=(0,se.s)(),{theme:o}=(0,aT.D)(),[c,d]=(0,r.useState)(""),[u,m]=(0,r.useState)(""),x=(0,r.useRef)(null),p=(l=(a=String(e||"").trim()).match(/^```(?:mermaid)?\s*([\s\S]*?)\s*```$/i))?l[1].trim():a,[h,f]=(0,r.useState)(p);return(h!==p&&(f(p),d(""),m("")),(0,r.useEffect)(()=>{let e=!1;if(p)return(!iX&&(iX=Promise.all([s.e(3755),s.e(7162),s.e(3606)]).then(s.bind(s,86492)).then(e=>e.default)),iX).then(async t=>{if(!e){t.initialize({startOnLoad:!1,theme:"dark"===o?"dark":"default",securityLevel:"loose"});try{let{svg:s}=await t.render(`mmd-${++iG}`,p);if(e)return;d(s),m("")}catch(t){if(e)return;d(""),m(t?.message||String(t))}}}).catch(t=>{e||m(t?.message||String(t))}),()=>{e=!0}},[p,o,t]),u)?(0,n.jsxs)("div",{className:"h-full overflow-auto p-3",children:[(0,n.jsx)("p",{className:"text-[11px] text-red-500 mb-2 break-words",children:u}),(0,n.jsx)("pre",{className:"text-[11px] text-text-muted whitespace-pre-wrap break-words",children:p})]}):p?c?(0,n.jsx)("div",{ref:x,className:"h-full overflow-auto p-3 flex items-start justify-center [&_svg]:max-w-full [&_svg]:h-auto",dangerouslySetInnerHTML:{__html:c}}):(0,n.jsx)("div",{className:"h-full flex items-center justify-center text-text-muted text-xs",children:i("common.loading")}):(0,n.jsx)("div",{className:"h-full flex items-center justify-center text-text-muted text-xs",children:i("editor.mermaidEmpty")})}var iY=s(49430),iZ=s(93473);let iQ=(e,t)=>function({children:s,className:r,node:a,...l}){return(0,n.jsx)(e,{className:r?`${t} ${r}`:t,...l,children:s})},i0={h1:iQ("h1","text-xl sm:text-2xl font-bold border-b border-border-subtle pb-2 mt-5 mb-3 text-text first:mt-0"),h2:iQ("h2","text-lg sm:text-xl font-bold border-b border-border-subtle pb-1.5 mt-4 mb-2.5 text-text first:mt-0"),h3:iQ("h3","text-base sm:text-lg font-semibold mt-3.5 mb-2 text-text"),h4:iQ("h4","text-sm sm:text-base font-semibold mt-3 mb-1.5 text-text"),h5:iQ("h5","text-xs sm:text-sm font-semibold mt-2.5 mb-1 text-text"),h6:iQ("h6","text-xs font-semibold mt-2 mb-1 text-text-muted"),p:iQ("p","my-2 leading-relaxed text-text text-sm"),ul:iQ("ul","list-disc pl-5 my-2 space-y-1 text-sm text-text"),ol:iQ("ol","list-decimal pl-5 my-2 space-y-1 text-sm text-text"),li:iQ("li","leading-relaxed"),blockquote:iQ("blockquote","border-l-4 border-brand-500/40 pl-3.5 my-2.5 text-text-muted italic text-sm"),th:iQ("th","border border-border-subtle bg-surface-2 px-3 py-1.5 font-semibold text-left text-text align-top whitespace-normal break-words"),td:iQ("td","border border-border-subtle px-3 py-1.5 text-text align-top whitespace-normal break-words"),hr:iQ("hr","border-t border-border-subtle my-4"),img:({alt:e="",node:t,...s})=>(0,n.jsx)("img",{className:"max-w-full h-auto rounded my-2",alt:e,...s}),a:({children:e,className:t,node:s,...r})=>(0,n.jsx)("a",{className:`text-brand-500 hover:underline wrap-anywhere${t?` ${t}`:""}`,target:"_blank",rel:"noopener noreferrer",...r,children:e}),table:({children:e,node:t,...s})=>(0,n.jsx)("table",{className:"w-full table-fixed border-collapse border border-border-subtle text-xs my-3",...s,children:e}),pre:function({children:e,node:t,...s}){let[a,l]=(0,r.useState)(!1),i=(0,r.useRef)(null);return(0,n.jsxs)("div",{className:"relative group/code my-2.5",children:[(0,n.jsx)("button",{type:"button",onClick:e=>{e.stopPropagation(),(0,t7.e)();let t=i.current?.innerText||"";try{navigator.clipboard.writeText(t)}catch{}l(!0),setTimeout(()=>l(!1),2e3)},className:"absolute top-2 right-2 p-1 rounded bg-surface-3/80 hover:bg-surface-3 text-text-muted hover:text-text opacity-100 sm:opacity-0 sm:group-hover/code:opacity-100 transition-opacity z-10",title:"Copy code",children:a?(0,n.jsx)(t3.aJ,{size:13,className:"text-brand-500"}):(0,n.jsx)(t3.QR,{size:13})}),(0,n.jsx)("pre",{ref:i,className:"p-3 rounded bg-surface-2 whitespace-pre-wrap break-words text-[12px] font-mono border border-border-subtle text-text [&_code]:bg-transparent [&_code]:p-0 [&_code]:border-0 [&_code]:text-text",...s,children:e})]})},code:({children:e,className:t,node:s,...r})=>{let a=/language-/.test(t||"");return(0,n.jsx)("code",{className:`${a?"font-mono text-[12px] text-text":"font-mono text-[0.9em] text-accent wrap-anywhere"}${t?` ${t}`:""}`,...r,children:e})},input:({type:e,checked:t,node:s,...r})=>"checkbox"===e?(0,n.jsx)("input",{type:"checkbox",checked:t,readOnly:!0,className:"mr-2 rounded accent-brand-500 cursor-default",...r}):(0,n.jsx)("input",{type:e,...r})},i1=(0,r.memo)(function({content:e,components:t}){return(0,n.jsx)(iY.oz,{remarkPlugins:[iZ.A],components:t?{...i0,...t}:i0,children:e})},(e,t)=>e.content===t.content);function i2({content:e}){let{t}=(0,se.s)();return e?.trim()?(0,n.jsx)("div",{className:"h-full overflow-auto p-4 sm:p-6 bg-bg select-text",children:(0,n.jsx)("div",{className:"max-w-4xl mx-auto",children:(0,n.jsx)(i1,{content:e})})}):(0,n.jsx)("div",{className:"h-full flex items-center justify-center text-text-muted text-xs",children:t("common.empty",{defaultValue:"Empty file"})})}function i5({kind:e,filePath:t,fileBus:s,content:r,reloadKey:a=0}){return"html"===e?(0,n.jsx)(iV,{filePath:t,fileBus:s,reloadKey:a}):"mermaid"===e?(0,n.jsx)(iJ,{content:r,reloadKey:a}):"markdown"===e?(0,n.jsx)(i2,{content:r}):null}var i3=s(23910);s(14876);let i4=["diff --git","index ","new file","deleted file","--- ","+++ "];function i6({diff:e,compact:t=!1,className:s=""}){let[a,l]=(0,r.useState)(!1);(0,r.useEffect)(()=>{if(t)return;let e=window.matchMedia("(min-width: 768px)"),s=()=>l(e.matches);return s(),e.addEventListener("change",s),()=>e.removeEventListener("change",s)},[t]);let i=!t&&a,o=(0,r.useCallback)(t=>{if(t&&e&&i)try{new i3.LU(t,e,{drawFileList:!1,matching:"words",outputFormat:"side-by-side",renderNothingWhenEmpty:!1}).draw()}catch{t.replaceChildren(Object.assign(document.createElement("pre"),{className:"text-text-muted p-4",textContent:e}))}},[e,i]),c=(0,r.useMemo)(()=>i||!e?[]:function(e){let t=[],s=0,n=0;for(let r of e.split("\n")){if(i4.some(e=>r.startsWith(e))){r.startsWith("diff --git")&&t.push({type:"file",text:r.replace("diff --git a/","").split(" b/")[0]});continue}if(r.startsWith("@@")){let e=r.match(/@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);e&&(s=parseInt(e[1],10),n=parseInt(e[2],10)),t.push({type:"hunk",text:r});continue}r.startsWith("+")?t.push({type:"add",text:r.slice(1),newLn:n++}):r.startsWith("-")?t.push({type:"del",text:r.slice(1),oldLn:s++}):t.push({type:"ctx",text:r.slice(1),oldLn:s++,newLn:n++})}return t}(e),[i,e]);return i?(0,n.jsx)("div",{ref:o,className:`diff-themed ${t?"diff-themed-compact":"bg-surface rounded"} overflow-hidden text-sm ${s}`}):(0,n.jsx)("div",{className:`w-full max-w-full overflow-hidden font-mono leading-[1.6] ${t?"text-[10px] leading-[1.45]":"rounded-lg border border-border bg-surface text-[12.5px]"} ${s}`,children:c.map((e,t)=>{if("file"===e.type)return(0,n.jsx)("div",{className:"px-3 py-2 bg-surface-2 text-text font-semibold break-all",children:e.text},t);if("hunk"===e.type)return(0,n.jsx)("div",{className:"px-3 py-1 bg-surface-2/60 text-text-muted select-none break-all",children:e.text},t);let s="add"===e.type?e.newLn:"del"===e.type?e.oldLn:e.newLn,r="add"===e.type?"bg-[rgba(var(--success-rgb),0.14)]":"del"===e.type?"bg-[rgba(var(--danger-rgb),0.14)]":"",a="add"===e.type?"text-[var(--success)]":"del"===e.type?"text-[var(--danger)]":"text-text-subtle",l="add"===e.type?"+":"del"===e.type?"-":" ";return(0,n.jsxs)("div",{className:`flex ${r}`,children:[(0,n.jsx)("span",{className:"shrink-0 w-9 px-1 text-right text-text-subtle bg-black/5 select-none",children:s}),(0,n.jsx)("span",{className:`shrink-0 w-4 text-center font-bold ${a} select-none`,children:l}),(0,n.jsx)("span",{className:"flex-1 min-w-0 pr-2 whitespace-pre-wrap break-words text-text",children:e.text||"\xa0"})]},t)})})}function i8({title:e,badge:t,badgeColor:s,img:r,loading:a,error:l,t:i}){var o;let c,d,u=[(c=r?.originalWidth||r?.width,d=r?.originalHeight||r?.height,c&&d?`${c} \xd7 ${d}`:""),!(o=r?.size||r?.originalSize)?"":o<1024?`${o} B`:o<1048576?`${(o/1024).toFixed(1)} KB`:`${(o/1048576).toFixed(1)} MB`].filter(Boolean).join(" \xb7 ");return(0,n.jsxs)("div",{className:"flex-1 flex flex-col rounded-brand border border-border-subtle bg-surface overflow-hidden min-h-[220px]",children:[(0,n.jsxs)("div",{className:"px-3 py-2 border-b border-border-subtle flex items-center justify-between bg-surface-2/60 shrink-0",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("span",{className:"text-xs font-medium text-text",children:e}),t&&(0,n.jsx)("span",{className:`text-[10px] font-semibold px-1.5 py-0.5 rounded-[3px] ${s}`,children:t})]}),u&&(0,n.jsx)("span",{className:"text-[11px] text-text-muted font-mono",children:u})]}),(0,n.jsx)("div",{className:"flex-1 p-3 flex items-center justify-center bg-surface-2/20 min-h-[160px] overflow-hidden relative",children:a?(0,n.jsxs)("div",{className:"flex items-center gap-2 text-text-muted text-xs",children:[(0,n.jsx)(t3.kr,{size:16,className:"animate-spin"}),(0,n.jsx)("span",{children:i("common.loading")})]}):l?(0,n.jsx)("div",{className:"text-xs text-text-muted text-center px-4 py-6",children:l}):r?.dataUrl?(0,n.jsx)("img",{src:r.dataUrl,alt:e,className:"max-h-[320px] max-w-full object-contain rounded drop-shadow-sm select-none"}):(0,n.jsx)("div",{className:"text-xs text-text-muted",children:i("git.noChanges")})})]})}function i9({filePath:e,status:t,workspace:s,fileBus:a,compact:l=!1}){let{t:i}=(0,se.s)(),o="A"===t||"?"===t,c="D"===t,d=!o,u=!c,[m,x]=(0,r.useState)(null),[p,h]=(0,r.useState)(d),[f,b]=(0,r.useState)(""),[g,v]=(0,r.useState)(null),[y,w]=(0,r.useState)(u),[k,j]=(0,r.useState)(""),[N,S]=(0,r.useState)(e);N!==e&&(S(e),x(null),h(d),b(""),v(null),w(u),j("")),(0,r.useEffect)(()=>{let t=!1;if(!e||!a)return;let n=s&&!e.startsWith("/")?`${s}/${e}`:e,r=s&&e.startsWith(s)?e.slice(s.length).replace(/^\//,""):e,l=setTimeout(()=>{d&&(h(!0),b(""),a.gitShowMedia?.(s,r,"HEAD").then(e=>{t||(h(!1),e?.success?x(e):b(e?.error||i("git.noOldVersion",{defaultValue:"No previous version in HEAD"})))}).catch(e=>{t||(h(!1),b(e?.message||"Failed to load old version"))})),u&&(w(!0),j(""),a.readMedia?.(n).then(e=>{t||(w(!1),e?.success?v(e):j(e?.error||i("git.noNewVersion",{defaultValue:"Failed to load working image"})))}).catch(e=>{t||(w(!1),j(e?.message||"Failed to load new version"))}))},0);return()=>{t=!0,clearTimeout(l)}},[e,s,a,d,u,i]);let C=e?e.split("/").pop():"",T=c||d&&!f&&(p||!!m?.dataUrl),R=T&&u;return(0,n.jsx)("div",{className:"h-full overflow-y-auto p-2 sm:p-3 flex flex-col gap-3",children:(0,n.jsxs)("div",{className:`flex-1 ${!l&&R?"grid grid-cols-1 md:grid-cols-2 gap-3":"flex flex-col gap-3"}`,children:[T&&(0,n.jsx)(i8,{title:c?`${C} (Deleted)`:"Old (HEAD)",badge:c?"DELETED":"ORIGINAL",badgeColor:"bg-red-500/15 text-red-400",img:m,loading:p,error:f,t:i}),u&&(0,n.jsx)(i8,{title:o?`${C} (Added)`:"New (Working Tree)",badge:o?"NEW":"MODIFIED",badgeColor:"bg-green-500/15 text-green-400",img:g,loading:y,error:k,t:i})]})})}function i7({diffPath:e,workspace:t,fileBus:s,compact:a=!1}){let{t:l}=(0,se.s)(),{status:i,repoPath:o,filePath:c}=tx(e),d=o||t,u=tn(c,e3),[m,x]=(0,r.useState)(!u),[p,h]=(0,r.useState)(""),[f,b]=(0,r.useState)("");return((0,r.useEffect)(()=>{if(u)return;let e=!1,t=setTimeout(async()=>{x(!0),b("");let t=await s.gitDiff?.(d,c,i);e||(t?.success?h(t.diff||""):b(t?.error||""),x(!1))},0);return()=>{e=!0,clearTimeout(t)}},[d,c,i,s,u]),u)?(0,n.jsx)(i9,{filePath:c,status:i,workspace:d,fileBus:s,compact:a}):(0,n.jsxs)("div",{className:`h-full overflow-auto ${a?"p-0":"p-2 sm:p-3"}`,children:[f&&(0,n.jsx)("div",{className:"bg-red-500/20 border border-red-500/50 rounded px-4 py-2 text-red-400 text-sm mb-3",children:f}),m?(0,n.jsx)("div",{className:"flex items-center justify-center h-32 text-text-muted text-sm",children:l("common.loading")}):p?(0,n.jsx)(i6,{diff:p,compact:a}):(0,n.jsx)("div",{className:"flex items-center justify-center h-32 text-text-muted text-sm",children:l("git.noChanges")})]})}function oe({filePath:e,workspace:t,fileBus:s,width:a,onResize:l,onClose:i,onOpenFull:o,onOpenFile:c,isDesktop:d=!0,previewSeq:u=0,artifactTitle:m=null}){let{t:x}=(0,se.s)(),p=tu(e),h=p?tx(e):null,f=h?.repoPath||t,b=p?h.filePath:e,g=h?h.repoPath?`${h.repoPath.replace(/\/$/,"")}/${h.filePath}`:h.filePath.startsWith("/")?h.filePath:`${t?.replace(/\/$/,"")||""}/${h.filePath}`:"",v=!!e&&!p&&!iT(e),y=iE({filePath:v?e:"",fileBus:s}),w=(0,r.useRef)(y);(0,r.useEffect)(()=>{w.current=y},[y]);let k=i_({dirty:v&&y.dirty,onSave:y.save}),j=v?tr(e):null,N=u>0,[S,C]=(0,r.useState)(N),[T,R]=(0,r.useState)(0),[E,_]=(0,r.useState)(e),[$,M]=(0,r.useState)(!1),[P,A]=(0,r.useState)(u);(E!==e||P!==u)&&(_(e),A(u),C(N)),y.justSaved!==$&&(M(y.justSaved),y.justSaved&&R(e=>e+1)),(0,r.useEffect)(()=>{let e=e=>{"Escape"===e.key&&k.guard(i)};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[k,i]);let z=e&&!p?e.slice(0,e.lastIndexOf("/")):"",I=(0,r.useMemo)(()=>z?[z]:[],[z]),L=lS();if(lN({dirs:I,fileBus:s,enabled:!!z&&L,debounceMs:1e3,onDirsChanged:(0,r.useCallback)(()=>{R(e=>e+1),w.current?.onChangedOnDisk()},[])}),!e)return null;let D=b.split("/").pop(),F=t&&b.startsWith(t)?b.slice(t.length).replace(/^\//,""):b;return(0,n.jsxs)("div",{className:"h-full flex flex-col bg-bg border-l border-border-subtle relative shrink min-w-0",style:d?{width:a,flexBasis:a,minWidth:ei.min}:void 0,children:[(0,n.jsxs)("div",{style:{height:32},className:"px-2 flex items-center gap-1.5 border-b border-border-subtle flex-shrink-0",children:[(0,n.jsx)("span",{className:"flex-shrink-0",children:lB({name:D,type:"file"},14)}),(0,n.jsx)("span",{className:"flex-1 min-w-0 truncate text-[12px] text-text",title:F,children:D}),m&&(0,n.jsx)("span",{className:"flex-shrink-0 px-1.5 py-px rounded-[3px] text-[9px] font-medium uppercase tracking-wide bg-brand-500/15 text-brand-500",children:x("editor.artifact")}),p&&(0,n.jsx)("span",{className:`text-[10px] font-bold flex-shrink-0 ${tl[h.status]||"text-text-muted"}`,children:h.status}),j&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),C(e=>!e)},title:x(S?"editor.editCode":"editor.preview"),className:"p-1 text-text-muted hover:text-text rounded-[3px] hover:bg-surface-2 transition-colors",children:S?(0,n.jsx)(t3.GD,{size:13}):(0,n.jsx)(t3.kU,{size:13})}),v&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),y.save()},disabled:!y.dirty||y.saving,title:x("editor.save"),className:`p-1 rounded-[3px] transition-colors disabled:opacity-30 ${y.dirty?"text-brand-500 hover:bg-surface-2":"text-text-muted"}`,children:(0,n.jsx)(t3.eM,{size:13})}),(p?!!c:o&&d)&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),p?c(g):o(e)},title:x(p?"git.openFile":"editor.openFull"),className:"p-1 text-text-muted hover:text-text rounded-[3px] hover:bg-surface-2 transition-colors",children:p?(0,n.jsx)(t3.GD,{size:13}):(0,n.jsx)(t3.Gr,{size:13})}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),k.guard(i)},className:"p-1 text-text-muted hover:text-text rounded-[3px] hover:bg-surface-2 transition-colors",children:(0,n.jsx)(t3.X,{size:13})})]}),y.error&&v&&(0,n.jsx)("div",{className:"px-3 py-1.5 text-[11px] text-red-500 bg-red-500/10 border-b border-border-subtle break-words",children:y.error}),y.staleOnDisk&&(0,n.jsxs)("div",{className:"px-3 py-1.5 flex items-center gap-2 text-[11px] text-amber-500 bg-amber-500/10 border-b border-border-subtle",children:[(0,n.jsx)("span",{className:"flex-1 min-w-0 truncate",children:x("editor.changedOnDisk")}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),y.reload()},className:"shrink-0 px-1.5 py-0.5 rounded-[3px] hover:bg-amber-500/20 font-medium transition-colors",children:x("editor.reloadFromDisk")})]}),(0,n.jsx)("div",{className:"flex-1 min-h-0 overflow-hidden",children:p?(0,n.jsx)(i7,{diffPath:td(h.status,h.filePath),workspace:f,fileBus:s,compact:!0}):iT(e)?(0,n.jsx)(iR,{filePath:e,fileBus:s}):S&&j?(0,n.jsx)(i5,{kind:j,filePath:e,fileBus:s,content:y.content,reloadKey:T}):y.loading?(0,n.jsx)("div",{className:"h-full flex items-center justify-center text-text-muted text-xs",children:x("common.loading")}):(0,n.jsx)(iU,{filePath:e,content:y.content,onTextChanged:y.onTextChanged,onRegisterView:y.register,onSave:y.save,compact:!0})}),(0,n.jsx)(i$,{isOpen:k.asking,fileName:D,onSave:k.saveThenLeave,onDiscard:k.discardAndLeave,onCancel:k.cancel}),d&&(0,n.jsx)("div",{onPointerDown:e=>sS(e,{startWidth:a,axis:-1,onWidth:e=>l?.(e)}),className:"absolute top-0 left-0 bottom-0 w-1 cursor-col-resize hover:bg-brand-500/40 transition-colors z-20"})]})}function ot(){let[e,t]=(0,r.useState)(null),s="mouse"!==nk();return((0,r.useEffect)(()=>{if(s)return;let e=null,n=null,r=()=>{clearTimeout(e),n=null,t(null)},a=s=>{let r=s.target?.closest?.("[data-tip]");if(r!==n){if(clearTimeout(e),n=r,!r)return t(null);e=setTimeout(()=>{let e;(e=r.getAttribute("data-tip"))&&function(e){let t=e.getBoundingClientRect();if(e.scrollHeight>e.clientHeight+eK.SLACK_PX)return!0;let s=document.createRange();s.selectNodeContents(e);let n=s.getBoundingClientRect().width;s.detach();let r=getComputedStyle(e),a=parseFloat(r.paddingLeft)+parseFloat(r.paddingRight);return n>t.width-a+eK.SLACK_PX}(r)&&t({text:e,...function(e){let{GAP_PX:t,EDGE_PX:s,MAX_WIDTH_PX:n,EST_HEIGHT_PX:r}=eK,a=e.bottom+t,l=a+r>window.innerHeight-s;return{left:Math.min(Math.max(e.left,s),Math.max(s,window.innerWidth-n-s)),top:l?void 0:a,bottom:l?window.innerHeight-e.top+t:void 0}}(r.getBoundingClientRect())})},"focusin"===s.type?0:eK.DELAY_MS)}},l=e=>{"Escape"===e.key&&r()};return document.addEventListener("mouseover",a,!0),document.addEventListener("focusin",a,!0),document.addEventListener("focusout",r,!0),document.documentElement.addEventListener("mouseleave",r),document.addEventListener("mousedown",r,!0),document.addEventListener("keydown",l,!0),window.addEventListener("scroll",r,!0),window.addEventListener("resize",r),()=>{clearTimeout(e),document.removeEventListener("mouseover",a,!0),document.removeEventListener("focusin",a,!0),document.removeEventListener("focusout",r,!0),document.documentElement.removeEventListener("mouseleave",r),document.removeEventListener("mousedown",r,!0),document.removeEventListener("keydown",l,!0),window.removeEventListener("scroll",r,!0),window.removeEventListener("resize",r)}},[s]),e)?(0,r_.createPortal)((0,n.jsx)("div",{role:"tooltip",className:"fixed z-[90] pointer-events-none px-2 py-1 rounded-[3px] bg-surface-2 border border-border-subtle shadow-lg text-[11px] text-text break-words animate-in fade-in duration-100",style:{left:e.left,top:e.top,bottom:e.bottom,maxWidth:eK.MAX_WIDTH_PX},children:e.text}),document.body):null}let os=(0,r.memo)(function({height:e=1,className:t=""}){let s=(0,r.useRef)(null),[a,l]=(0,r.useState)(0);(0,r.useEffect)(()=>{let e=s.current;if(!e)return;let t=new ResizeObserver(([t])=>{let s=t?.contentRect?.width||e.offsetWidth;s>0&&l(Math.round(s))});return t.observe(e),()=>t.disconnect()},[]);let i=a||600,o=Math.max(1.8,(i+140)/250);return(0,n.jsx)("div",{ref:s,"aria-hidden":"true",className:`absolute inset-x-0 top-0 overflow-hidden pointer-events-none ${t}`,style:{height:e,"--pane-w":`${i}px`,"--beam-w":"140px","--beam-dur":`${o.toFixed(2)}s`,"--beam-delay":`${(o/2).toFixed(2)}s`},children:(0,n.jsxs)("div",{className:"relative w-full h-full bg-blue-500/10",children:[(0,n.jsx)("div",{className:"pane-light-beam"}),(0,n.jsx)("div",{className:"pane-light-beam pane-light-beam-2"})]})})}),on=["newTerminal","palette","help"];function or({onAddWorkspace:e,onOpenRemote:t,recent:s=[],homeDir:r,onOpenRecent:a}){let{t:l}=(0,se.s)(),i=[...on.map(e=>sJ.find(t=>t.id===e)).filter(Boolean),sY];return(0,n.jsxs)("div",{className:"h-full w-full empty-stage empty-stage-h",children:[(0,n.jsx)("div",{className:"empty-grid"}),(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),e?.()},disabled:!e,className:"empty-half text-left transition-all duration-150 enabled:hover:opacity-90 enabled:active:scale-[0.99] disabled:opacity-40 disabled:saturate-50",children:[(0,n.jsxs)("span",{className:"empty-idx",children:[(0,n.jsx)("b",{children:"01"})," / ",l("workspaces.emptyTagWorkspace")]}),(0,n.jsx)("span",{className:"empty-word login-hero-grad",children:l("workspaces.emptyWordTerminal")}),(0,n.jsx)("span",{className:"empty-meta",dangerouslySetInnerHTML:{__html:l("workspaces.emptyMetaWorkspace")}}),(0,n.jsxs)("span",{className:"empty-go",children:[l("workspaces.selectFolder"),(0,n.jsx)(t3.Qp,{size:14,className:"text-brand-500",strokeWidth:2.2})]}),!!s.length&&(0,n.jsx)("span",{className:"flex flex-wrap gap-1.5 mt-4 max-w-full",children:s.slice(0,4).map(e=>(0,n.jsx)("span",{role:"button",title:e.path,onClick:t=>{t.stopPropagation(),(0,t7.e)(),a?.(e.path)},className:"welcome-chip path-tail px-2 py-1 text-[11px] font-mono text-text-muted rounded-full truncate max-w-[180px]",children:rs(e.path,r)},e.path))})]}),!!t&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"empty-hairline","aria-hidden":!0}),(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),t?.()},className:"empty-half text-left transition-all duration-150 enabled:hover:opacity-90 enabled:active:scale-[0.99] disabled:opacity-40 disabled:saturate-50",children:[(0,n.jsxs)("span",{className:"empty-idx",children:[(0,n.jsx)("b",{children:"02"})," / ",l("workspaces.emptyTagRemote")]}),(0,n.jsx)("span",{className:"empty-word login-hero-grad",children:l("workspaces.emptyWordRemote")}),(0,n.jsx)("span",{className:"empty-meta",dangerouslySetInnerHTML:{__html:l("workspaces.emptyMetaRemote")}}),(0,n.jsxs)("span",{className:"empty-go",children:[l("menu.remoteDesktop"),(0,n.jsx)(t3.Qp,{size:14,className:"text-brand-500",strokeWidth:2.2})]})]})]}),(0,n.jsx)("div",{className:"hidden lg:flex absolute bottom-0 inset-x-0 z-[2] flex-wrap items-center justify-center gap-x-5 gap-y-1.5 px-8 pb-6 font-mono text-[11px] text-text-subtle",children:i.map(e=>(0,n.jsxs)("span",{className:"flex items-center gap-1.5",children:[l(`shortcuts.${e.id}`),(0,n.jsx)("kbd",{className:"px-1.5 py-0.5 rounded-[4px] bg-surface-2/60 text-text-muted whitespace-nowrap",children:s2(e)})]},e.id))})]})}let oa=new Set(["Agent","Task","Workflow","task","browser_subagent","invoke_subagent","spawn_agent"]),ol=e=>e?.input?.subagent_type||e?.input?.agent||e?.input?.description||"agent",oi=e=>e?.input?.description||e?.input?.command||"shell";function oo(e=[],t=""){if(!t)return null;let s=null,n=e=>{for(let r of e||[]){if(r?.id===t)return s=r,!0;if(r?.children?.length&&n(r.children))return!0}return!1};for(let t=e.length-1;t>=0&&!s;t--)n(e[t]?.tools);return s}function oc(e=[],t=""){let s=oo(e,t);if(!s)return null;let n=s;for(;"running"===n.status;){let e=n.children||[],t=e.filter(e=>e?.status==="running").pop()||e[e.length-1];if(!t||t===n)break;n=t}return n}function od(e){return(e||[]).map(e=>{let t=e.children?od(e.children):null;return"running"!==e.status||e.async?t?{...e,children:t}:e:{...e,status:"done",...t?{children:t}:null}})}function ou(e,t,s){let n=!1,r=(e||[]).map(e=>{if(t(e))return n=!0,s(e);let r=ou(e.children,t,s);return r?(n=!0,{...e,children:r}):e});return n?r:null}var om=s(91524);function ox(e,t="claude"){if(!e?.name)return"";let{name:s,input:n={}}=e,r=oh(n.file_path||n.path);switch((0,om.$Z)(t,s)){case"bash":return ob(n.description||n.command||"shell",op);case"file":return ob(`${/^(list|list_dir|ls)$/i.test(s)?"Listing":"Reading"} ${r}`,op);case"search":return ob([n.pattern?`"${n.pattern}"`:n.query||n.url||"",r?`in ${r}`:""].filter(Boolean).join(" "),op);case"diff":return ob(`${/^(Write|write_to_file)$/i.test(s)?"Writing":"Editing"} ${oh(n.file_path||n.filePath||n.file||n.path)||ov(n)}`,op);case"agent":return ob(n.description||ov(n)||"sub-agent",op);case"plan":return ob(oh(n.path)||s,op);default:return ob([og(s),ov(n)].filter(Boolean).join(" "),op)}}let op=60,oh=e=>"string"==typeof e&&e.replace(/\\/g,"/").split("/").filter(Boolean).pop()||"",of=e=>{if("string"!=typeof e)return"";let t=e.slice(-512).split("\n");for(let e=t.length-1;e>=0;e--){let s=t[e].trim();if(s)return s}return""},ob=(e,t)=>e.length>t?`${e.slice(0,t-1)}…`:e,og=(e="")=>{let t=/^mcp__[^_]+(?:_[^_]+)*__(.+)$/.exec(e);return t?t[1]:e},ov=(e={})=>e.url||e.query||e.pattern||e.name||oh(e.path)||oh(e.file_path)||"";function oy(e){let t=Number(e)||0,s=t>=1e6?[1e6,"M"]:t>=1e3?[1e3,"k"]:null;if(!s)return String(t);let n=t/s[0];return`${n>=100?Math.round(n):n.toFixed(1).replace(/\.0$/,"")}${s[1]}`}let ow=new Set(["Edit","Write","MultiEdit","NotebookEdit","edit","write","patch","apply","write_to_file","replace_file_content","multi_replace_file_content","sed_file","file_change"]),ok=e=>"string"==typeof e&&e?e.split("\n").length:0;function oj(e=[]){let t=0,s=0;for(let n=e.length-1;n>=0;n--){let r=e[n];if("user"===r.role)break;let a=r.diffs||[];for(let e of a)for(let n of(e.patch||e.diff||"").split("\n"))n.startsWith("+")&&!n.startsWith("+++")?t++:n.startsWith("-")&&!n.startsWith("---")&&s++;let l=new Set(a.map(e=>e.file).filter(Boolean));for(let e of r.tools||[]){if(!ow.has(e?.name))continue;let n=e.input?.file_path||e.input?.path||e.input?.file||"";if(n&&l.has(n))continue;let r=function(e){let t=e.input;if(!t||"string"==typeof t)return null;let s=t.file_path||t.path||t.file||"",n=Array.isArray(t.edits)?t.edits:Array.isArray(t.replacement_chunks)?t.replacement_chunks:Array.isArray(t.replacements)?t.replacements:null;if(n){let e=0,t=0;for(let s of n)t+=ok(s.old_string??s.oldString??s.old??s.target_content),e+=ok(s.new_string??s.newString??s.new??s.replacement_content);return{file:s,added:e,removed:t}}if("string"==typeof t.content&&t.content)return{file:s,added:ok(t.content),removed:0};let r=t.old_string??t.oldString??t.old_str??t.target_content??t.TargetContent,a=t.new_string??t.newString??t.new_str??t.replacement_content??t.ReplacementContent;return void 0===r&&void 0===a?null:{file:s,added:ok(a),removed:ok(r)}}(e);r&&(t+=r.added,s+=r.removed)}}return{added:t,removed:s}}let oN=/^\s*<(task-notification|environment_context|turn_aborted|persisted-output)>/,oS=e=>oN.test(String(e||""));function oC(e){let t=String(e||"").trim();if(!t)return"";if(!t.startsWith("<persisted-output>"))return t;let s=/saved to: (\S+)/.exec(t);return s?`saved to: ${s[1]}`:""}let oT=new Set(["completed","failed","killed","stopped"]),oR=(e,t=Date.now())=>e?.usage?.duration_ms>0?e.usage.duration_ms:e?.endedAt&&e?.startedAt?Math.max(0,e.endedAt-e.startedAt):e?.startedAt?Math.max(0,t-e.startedAt):0,oE=(e,t)=>t?.startedAt?null:{startedAt:Date.now()-(Number.isFinite(e)?Math.max(0,e):0)},o_=(e=[])=>{for(let t=e.length-1;t>=0;t--)if(e[t]?.compacting)return t;return -1},o$=new Set(["compacting"]);function oM(e,t,s,n,r){if("system"!==t)return e;let a=Number.isFinite(r)?r:n?.ageMs;switch(s){case"task_started":if(!n?.task_id)return e;return oP(e,n.task_id,{taskId:n.task_id,status:"running",background:!!n.is_backgrounded,...n.tool_use_id?{toolUseId:n.tool_use_id}:null,...n.description?{description:n.description}:null,...n.subagent_type?{subagentType:n.subagent_type}:null,...n.task_type?{taskType:n.task_type}:null,...oE(a,e.find(e=>e.taskId===n.task_id))});case"task_updated":{let t=e.findIndex(e=>e.taskId===n?.task_id);if(-1===t)return e;let s=n.patch||{},r=e.slice(),l=s.status&&!oT.has(s.status),i={...r[t],...s.status?{status:s.status}:null,...s.description?{description:s.description}:null,...s.end_time?{endedAt:s.end_time}:null};return l&&delete i.endedAt,l&&r[t].endedAt&&Object.assign(i,oE(a,null)),r[t]=i,r}case"task_notification":{let t=e.findIndex(e=>e.taskId===n?.task_id);if(-1===t)return e;let s=e.slice();return s[t]={...s[t],status:n.status||"completed",endedAt:s[t].endedAt||Date.now(),...n.output_file?{outputFile:n.output_file}:null,...n.summary?{summary:n.summary}:null,...n.usage?{usage:n.usage}:null},s}case"background_tasks_changed":{let t=new Set((n?.tasks||[]).map(e=>e.task_id)),s=e;for(let e of(s.some(e=>e.background&&!oT.has(e.status)&&!t.has(e.taskId))&&(s=s.map(e=>!e.background||oT.has(e.status)||t.has(e.taskId)?e:{...e,status:"stopped",endedAt:e.endedAt||Date.now()})),n?.tasks||[]))s=oP(s,e.task_id,{background:!0,status:"running",...e.description?{description:e.description}:null,...e.task_type?{taskType:e.task_type}:null,...oE(a,s.find(t=>t.taskId===e.task_id))});return s}default:return e}}function oP(e,t,s){let n=e.findIndex(e=>e.taskId===t);if(-1===n)return[...e,{taskId:t,toolUseId:"",...s}];let r={...e[n],...s};if(oA(r,e[n]))return e;let a=e.slice();return a[n]=r,a}let oA=(e,t)=>{let s=Object.keys(e);return s.length===Object.keys(t).length&&s.every(s=>e[s]===t[s])};function oz(e,t){let s=[];for(let t of e||[])t&&(s=oM(s,t.type||"system",t.subtype||"",t.record||null,t.ageMs));let n=new Map(s.map(e=>[e.taskId,e]));for(let e of t||[])e?.taskId&&n.set(e.taskId,{...n.get(e.taskId),...e});return[...n.values()]}function oI(e,t){if(!t)return null;if(e.startsWith("session.next."))return"session.next.retried"===e?{subtype:e,level:"warning",content:`Retrying (attempt ${t.attempt??"?"}): ${t.error?.message||""}`.trim()}:"session.next.compaction.started"===e?{subtype:e,level:"info",content:"Compacting…",compacting:!0}:"session.next.compaction.ended"===e?{subtype:e,level:"info",content:"Compacted",compactSettled:!0}:"session.next.revert.staged"===e?{subtype:e,level:"info",content:"Rewind staged"}:"session.next.revert.committed"===e?{subtype:e,level:"info",content:"Rewound the conversation"}:"session.next.agent.switched"===e?{subtype:e,level:"info",content:`Agent: ${t.agent||""}`}:null;if("warning"===e||"guardianWarning"===e||"configWarning"===e||"deprecationNotice"===e)return null;let s="error"===e?String(t.error?.message||"").trim():"warning"===e||"guardianWarning"===e?String(t.message||"").trim():"configWarning"===e||"deprecationNotice"===e?[t.summary,t.details].filter(Boolean).join(" — ").trim():"model/rerouted"===e?`Model rerouted: ${t.fromModel} → ${t.toModel}`:"";if(s){let n="error"!==e||t.willRetry?"warning":"error";return{subtype:e,level:n,content:s}}if("thread/compacted"===e)return{subtype:e,level:"info",content:"Compacted",compactSettled:!0};if("system"===e&&"compact_boundary"===t.subtype){let e=function(e){let t=e.compact_metadata||e.compactMetadata;if(!t||"object"!=typeof t)return null;let s=e=>Number.isFinite(e)?e:null,n=s(t.pre_tokens??t.preTokens),r=s(t.post_tokens??t.postTokens),a=null!=n&&null!=r?`${oy(n)} → ${oy(r)} tokens`:"";return{trigger:t.trigger||"auto",preTokens:n,postTokens:r,durationMs:s(t.duration_ms??t.durationMs),...a?{detail:a}:null}}(t),s="string"==typeof t.content?t.content.trim():"";return e||s?{subtype:"compact_boundary",level:t.level||"info",content:s||"Compacted",compactSettled:!0,...e?{compact:e}:null}:null}if("system"===e&&"status"===t.subtype){if(o$.has(t.status))return{subtype:"status",level:"info",content:"Compacting…",compacting:!0};if(null!=t.status&&!t.compact_result)return null;let e="failed"===t.compact_result;return{subtype:"status",level:e?"error":"info",content:e?String(t.compact_error||"").trim()||"Compaction failed":"",compactSettled:!0}}if("attachment"===e){let e=t.attachment||t,s=e.type||"";if("edited_text_file"===s)return null;if("hook_success"===s){if("SessionStart"!==e.hookEvent)return null;let t=oC(e.content);return t?{subtype:s,level:"info",content:t}:null}let n="queued_command"===s?e.prompt:"";if("string"!=typeof n||!n.trim()||oS(n))return null;let r=oC(n);return r?{subtype:s,level:"info",content:r}:null}if("system"!==e||oS(t.content))return null;let n="string"==typeof t.content&&t.content.trim()?t.content.trim():"string"==typeof t.error?.formatted&&t.error.formatted.trim()?t.error.formatted.trim():"string"==typeof t.error?.message&&t.error.message.trim()?t.error.message.trim():"";return n?{subtype:t.subtype||"",level:t.level||"info",content:n}:null}function oL(e=[],t){if(!t)return e||[];if(t.replaceAll)return t.todos||[];let s=e||[],n=t.taskId?String(t.taskId):"",r=t.id?String(t.id):"",a=s.findIndex(e=>n&&String(e.taskId)===n||r&&e.id&&String(e.id)===r);if("deleted"===t.status)return -1===a?s:[...s.slice(0,a),...s.slice(a+1)];if(-1===a)return t.subject?[...s,t]:s;let l=s.slice();return l[a]={...l[a],...t},l}let oD=(0,es.KU)(()=>window.localStorage),oF=null,oO=oD&&{...oD,setItem:(e,t)=>{t!==oF&&(oF=t,oD.setItem(e,t))}},oB=0,oW=e=>`${e}-${Date.now()}-${++oB}`,oK={messages:[],isTurnRunning:!1,turnStartedAt:0,lastTurnMs:0,activePermission:null,gateError:!1,activeBlocked:null,permissionMode:null,stats:{inputTokens:0,outputTokens:0,totalTurns:0,totalCost:0,reasoningTokens:0},turnBaseline:{inputTokens:0,outputTokens:0},metadata:{model:"",skills:[],mcpServers:[]},tasks:[],harnessTasks:[],queue:[]},oH=(e,t)=>({...oK,...e.bySession[t]});function oU(e,t){if(!t?.length)return null;let s=e.filter(e=>e.toolUseId&&oT.has(e.status));if(!s.length)return null;let n=t;for(let e of s){let t="failed"===e.status?"error":"done",s=n.map(s=>{if(!s.tools)return s;let n=ou(s.tools,t=>t.id===e.toolUseId&&"running"===t.status,e=>({...e,status:t}));return n?{...s,tools:n}:s});s.some((e,t)=>e!==n[t])&&(n=s)}return n===t?null:n}let oq=(0,Z.v)((0,es.Zr)((e,t)=>({bySession:{},initSession:s=>{s&&!t().bySession[s]&&e(e=>({bySession:{...e.bySession,[s]:{...oK}}}))},setTaskRecords:(t,s)=>{t&&Array.isArray(s)&&e(e=>{let n=oH(e,t),r=oz(s,[]),a=oU(r,n.messages);return r!==n.harnessTasks||a?{bySession:{...e.bySession,[t]:{...n,harnessTasks:r,...a?{messages:a}:null}}}:e})},applyTaskRecords:(t,s)=>{t&&s?.length&&e(e=>{let n=oH(e,t),r=n.harnessTasks||[],a=r;for(let[e,t,n,r]of s)a=oM(a,e,t,n,r);let l=oU(a,n.messages);return a!==r||l?{bySession:{...e.bySession,[t]:{...n,harnessTasks:a,...l?{messages:l}:null}}}:e})},addNotice:(t,s)=>{let n="string"==typeof s?.content?s.content.trim():"";!t||(n||s?.compactSettled)&&e(e=>{let r=oH(e,t);if(s?.compacting&&-1!==o_(r.messages))return e;if(-1!==(s?.compactSettled?o_(r.messages):-1)){let a=r.messages.findIndex(e=>e?.compacting),l=r.messages.filter(e=>!e?.compacting);return n&&l.splice(a,0,{id:oW("n"),role:"notice",subtype:s.subtype||"",level:s.level||"info",content:n,...s.compact?{compact:s.compact}:null}),{bySession:{...e.bySession,[t]:{...r,messages:l}}}}if(!n)return e;let a={id:oW("n"),role:"notice",subtype:s.subtype||"",level:s.level||"info",content:n,...s.file?{file:s.file}:null,...s.compact?{compact:s.compact}:null,...s.compacting?{compacting:!0}:null},l=r.messages[r.messages.length-1],i=!l||"assistant"!==l.role||l.content||l.thinking||(l.tools||[]).length?[...r.messages,a]:[...r.messages.slice(0,-1),a];return{bySession:{...e.bySession,[t]:{...r,messages:i}}}})},setPermissionMode:(t,s)=>{e(e=>{let n=oH(e,t);return{bySession:{...e.bySession,[t]:{...n,permissionMode:s}}}})},setTurnRunning:(t,s)=>{e(e=>{let n=oH(e,t);return{bySession:{...e.bySession,[t]:{...n,isTurnRunning:s}}}})},setQueue:(t,s)=>{t&&e(e=>{let n=oH(e,t),r=Array.isArray(s)?s:[];return{bySession:{...e.bySession,[t]:{...n,queue:r}}}})},setMetadata:(t,s)=>{e(e=>{let n=oH(e,t);return{bySession:{...e.bySession,[t]:{...n,metadata:{...n.metadata,...s}}}}})},setStats:(t,s)=>{e(e=>{let n=oH(e,t);return{bySession:{...e.bySession,[t]:{...n,stats:{...n.stats,...s}}}}})},addUserMessage:(t,s,n=null,r=!1)=>{e(e=>{let a=oH(e,t),l={id:oW("u"),role:"user",content:s,attachments:n||[]},i={id:oW("a"),role:"assistant",content:"",thinking:"",diffs:[],tools:[],isLive:!0};return{bySession:{...e.bySession,[t]:{...a,...r?null:{isTurnRunning:!0,turnStartedAt:Date.now(),lastTurnMs:0,turnBaseline:{inputTokens:a.stats.inputTokens||0,outputTokens:a.stats.outputTokens||0},activeBlocked:null},messages:[...a.messages,l,i]}}}})},appendDelta:(t,s)=>{e(e=>{let n=oH(e,t),r=[...n.messages],a=r[r.length-1];return a&&"assistant"===a.role&&a.isLive?r[r.length-1]={...a,content:(a.content||"")+(s||"")}:r.push({id:oW("msg"),role:"assistant",content:s||"",isLive:!0,diffs:[],tools:[]}),{bySession:{...e.bySession,[t]:{...n,messages:r}}}})},appendThinking:(t,s)=>{e(e=>{let n=oH(e,t),r=[...n.messages],a=r[r.length-1];return a&&"assistant"===a.role&&a.isLive?r[r.length-1]={...a,thinking:(a.thinking||"")+(s||"")}:r.push({id:oW("msg"),role:"assistant",content:"",thinking:s||"",isLive:!0,diffs:[],tools:[]}),{bySession:{...e.bySession,[t]:{...n,messages:r}}}})},appendStream:(t,s,n)=>{e(e=>{let r=oH(e,t),a=[...r.messages],l=a[a.length-1];return l&&"assistant"===l.role&&l.isLive?a[a.length-1]={...l,...s?{content:(l.content||"")+s}:null,...n?{thinking:(l.thinking||"")+n}:null}:a.push({id:oW("msg"),role:"assistant",content:s||"",thinking:n||"",isLive:!0,diffs:[],tools:[]}),{bySession:{...e.bySession,[t]:{...r,messages:a}}}})},appendDiff:(t,s)=>{e(e=>{let n=oH(e,t),r=[...n.messages],a=r[r.length-1];a&&"assistant"===a.role?(a={...a},r[r.length-1]=a):(a={id:oW("msg"),role:"assistant",content:"",isLive:!0,diffs:[],tools:[]},r.push(a));let l=[...a.diffs||[]],i=l.findIndex(e=>e.file===s.file);return -1!==i?l[i]=s:l.push(s),a.diffs=l,{bySession:{...e.bySession,[t]:{...n,messages:r}}}})},appendTool:(t,s)=>{e(e=>{let n=oH(e,t),r=[...n.messages],a=r[r.length-1];if(a&&"assistant"===a.role&&a.isLive&&(a.content||a.thinking||"").length>0)r[r.length-1]={...a,isLive:!1},r.push({id:oW("msg"),role:"assistant",content:"",isLive:!0,diffs:[],tools:[{...s,status:s.status||"running"}]});else if(a&&"assistant"===a.role){let e=[...a.tools||[]],t=e.findIndex(e=>e.id===s.id);-1!==t?e[t]={...e[t],...s}:e.push({...s,status:s.status||"running"}),r[r.length-1]={...a,tools:e}}else r.push({id:oW("msg"),role:"assistant",content:"",isLive:!0,diffs:[],tools:[{...s,status:s.status||"running"}]});return{bySession:{...e.bySession,[t]:{...n,messages:r}}}})},updateToolResult:(t,s)=>{e(e=>{let n=oH(e,t),r=[...n.messages];for(let e=r.length-1;e>=0;e--){let t=r[e];if(!t?.tools)continue;let n=t.tools.findIndex(e=>e.id===s.id);if(-1!==n){let a=[...t.tools];a[n]={...a[n],...s,status:s.status||"done"},r[e]={...t,tools:a};break}}return{bySession:{...e.bySession,[t]:{...n,messages:r}}}})},nestTool:(t,s)=>{e(e=>{let n=oH(e,t),r=[...n.messages];for(let e=r.length-1;e>=0;e--){let t=r[e],n=ou(t?.tools,e=>e.id===s.parentToolUseId,e=>{let t=[...e.children||[]],n=t.findIndex(e=>e.id===s.id);return -1!==n?t[n]={...t[n],...s}:t.push({...s,status:s.status||"running"}),{...e,children:t}});if(n){r[e]={...t,tools:n};break}}return{bySession:{...e.bySession,[t]:{...n,messages:r}}}})},nestToolResult:(t,s)=>{e(e=>{let n=oH(e,t),r=[...n.messages];for(let e=r.length-1;e>=0;e--){let t=r[e],n=ou(t?.tools,e=>(e.children||[]).some(e=>e.id===s.id),e=>({...e,children:e.children.map(e=>e.id===s.id?{...e,...s,status:s.status||"done"}:e)}));if(n){r[e]={...t,tools:n};break}}return{bySession:{...e.bySession,[t]:{...n,messages:r}}}})},setPermission:(t,s)=>{e(e=>{let n=oH(e,t);return{bySession:{...e.bySession,[t]:{...n,activePermission:s,gateError:!1}}}})},clearPermission:t=>{e(e=>{let s=oH(e,t);return{bySession:{...e.bySession,[t]:{...s,activePermission:null}}}})},setBlocked:(t,s)=>{e(e=>{let n=oH(e,t);return{bySession:{...e.bySession,[t]:{...n,activeBlocked:s}}}})},clearBlocked:t=>{e(e=>{let s=oH(e,t);return{bySession:{...e.bySession,[t]:{...s,activeBlocked:null}}}})},setGateError:(t,s,n=!0)=>{e(e=>{let r=oH(e,t);return r.activePermission?.requestId!==s?e:{bySession:{...e.bySession,[t]:{...r,gateError:n}}}})},finishTurn:(t,s,n=0,r=!1)=>{e(e=>{let a=oH(e,t),l=a.messages.map((e,t)=>({...e,...t===a.messages.length-1?{isLive:!1}:null,...e.tools?{tools:od(e.tools)}:null}));return{bySession:{...e.bySession,[t]:{...a,...r?{activePermission:null}:{isTurnRunning:!1,lastTurnMs:n||(a.turnStartedAt?Date.now()-a.turnStartedAt:a.lastTurnMs),activePermission:null,stats:s?{...a.stats,...s}:a.stats},messages:l}}}})},clearMessages:t=>{e(e=>{let s=oH(e,t);return{bySession:{...e.bySession,[t]:{...s,messages:[],tasks:[],turnStartedAt:0,lastTurnMs:0,activePermission:null,activeBlocked:null,stats:{inputTokens:0,outputTokens:0,totalTurns:0,totalCost:0,reasoningTokens:0},turnBaseline:{inputTokens:0,outputTokens:0}}}}})},rewindToMessage:(t,s,n)=>{e(e=>{let r=oH(e,t),a=r.messages.findIndex(e=>e.id===s);if(-1===a)return e;let l=r.messages.slice(0,a+1);return n&&(l[a]={...l[a],content:n}),{bySession:{...e.bySession,[t]:{...r,messages:l,isTurnRunning:!1,turnStartedAt:0,lastTurnMs:0,activePermission:null}}}})},upsertTask:(t,s)=>{e(e=>{let n=oH(e,t),r=oL(n.tasks,s);return r===n.tasks?e:{bySession:{...e.bySession,[t]:{...n,tasks:r}}}})},hydrateSession:(t,{messages:s=[],tasks:n=[],isTurnRunning:r=!1,metadata:a={},stats:l=null,permissionMode:i=null,activeBlocked:o=null,elapsedMs:c=0,lastTurnMs:d=0,harnessTasks:u=null,queue:m=null})=>{e(e=>{let x=oH(e,t),p=u?oU(u,s):null;return{bySession:{...e.bySession,[t]:{...x,activePermission:null,messages:p||s,tasks:n,isTurnRunning:r,...Array.isArray(m)?{queue:m}:{},turnStartedAt:r?Date.now()-(c||0):0,lastTurnMs:r?0:d||0,turnBaseline:r?{inputTokens:0,outputTokens:0}:{inputTokens:l?.inputTokens||0,outputTokens:l?.outputTokens||0},metadata:{...x.metadata,...a},stats:l?{...x.stats,...l}:x.stats,activeBlocked:o,...i?{permissionMode:i}:{},...u?{harnessTasks:u}:{}}}}})},prependMessages:(t,s)=>{s?.length&&e(e=>{let n=oH(e,t),r=oU(n.harnessTasks||[],s)||s,a=new Set(n.messages.map(e=>e.id)),l=r.map(e=>a.has(e.id)?{...e,id:oW(e.id.split("-")[0])}:(a.add(e.id),e));return{bySession:{...e.bySession,[t]:{...n,messages:[...l,...n.messages]}}}})},restoreTurnState:(t,s={})=>{if(void 0===s.isTurnRunning)return;let{isTurnRunning:n,lastTurnMs:r=0,elapsedMs:a=0}=s;(n||r)&&e(e=>{let s=oH(e,t);return{bySession:{...e.bySession,[t]:{...s,isTurnRunning:n,lastTurnMs:r,turnStartedAt:n?Date.now()-(a||0):0}}}})},removeSession:t=>{e(e=>{let{[t]:s,...n}=e.bySession;return{bySession:n}})}}),{name:"9remote-ai-store",storage:oO,partialize:e=>({bySession:Object.fromEntries(Object.entries(e?.bySession||{}).map(([e,t])=>[e,{permissionMode:t?.permissionMode??null,metadata:{model:t?.metadata?.model||"",effort:t?.metadata?.effort||""}}]))})}));function oV(e){if(!e)return 0;let t=(e.content?.length||0)+(e.thinking?.length||0);if(Array.isArray(e.tools))for(let s of e.tools)t+=(s.command?.length||0)+(s.output?.length||0)+120;if(Array.isArray(e.diffs))for(let s of e.diffs)t+=(s.diff?.length||0)+(s.file?.length||0)+80;return Math.max(t,100)}function oX(e,t,s,n=2){if(!Array.isArray(e)||0===e.length)return 0;let r=Math.min(s??e.length,e.length),a=0,l=0;for(let s=r-1;s>=0&&(a+=oV(e[s]),l++,!(a>=t)||!(l>=n));s--);return r-l}async function oG({startSeq:e,fetchChunk:t,reduceChunk:s,maxChunks:n=8,pageBudget:r=131072,estimateBytes:a=()=>0}){let l=e,i=[],o=0,c=!0,d=0,u=!1;for(;d<n;){let e=await t(l);if(d++,null==e)break;if(!e.success||!e.events?.length){c=!1;break}u=!0;let n=s(e.events,i.length);if(i=[...n,...i],o+=n.reduce((e,t)=>e+a(t),0),l=e.events[0].seq,!(c=!!e.hasMore)||o>=r)break}return{messages:i,before:l,hasMore:c,answered:u,chunks:d}}let oJ=[1200,3e3,6e3],oY=e=>Array.isArray(e)?e.map(e=>"string"==typeof e?{id:e,name:e,description:""}:e):[];function oZ(e,t){let s=String(t||"").trim();if(!s)return!1;let n=e[e.length-1];return!!(n&&"assistant"===n.role&&String(n.content||"").trim().endsWith(s))}let oQ=e=>e?.text?`Not sent — ${e.reason||"the turn is still running"}: ${e.text}`:e?.reason||"Not sent";function o0(e=[],t="claude",s=0){let n=[],r=[],a=[],l={model:"",skills:[],mcpServers:[]},i={inputTokens:0,outputTokens:0,totalTurns:0,totalCost:0,reasoningTokens:0},o=!1,c=null,d=null,u=null,m=!1,x=s;for(let s of e){let e=s?.event,p=s?.data;if(e)switch(e){case"user_message":o=!0,d=null,n.push({id:`u-${++x}`,role:"user",content:p?.text||"",attachments:p?.attachments||[]}),n.push({id:`a-${++x}`,role:"assistant",content:"",thinking:"",diffs:[],tools:[],isLive:!0});break;case"init":{let e=oY(p?.skills),t=e.length>0?e:l.skills,{model:s,...n}=p||{};l={...l,...n,skills:t,...s?{model:s}:{}};break}case"goal":l={...l,goal:p?.goal||null};break;case"delta":{let e=n[n.length-1];e&&"assistant"===e.role||(e={id:`msg-${++x}`,role:"assistant",content:"",isLive:!0,diffs:[],tools:[]},n.push(e)),e.content=(e.content||"")+(p?.text||"");break}case"thinking":{let e=n[n.length-1];e&&"assistant"===e.role||(e={id:`msg-${++x}`,role:"assistant",content:"",thinking:"",isLive:!0,diffs:[],tools:[]},n.push(e)),e.thinking=(e.thinking||"")+(p?.text||"");break}case"diff":{if(!p)break;let e=n[n.length-1];e&&"assistant"===e.role||(e={id:`msg-${++x}`,role:"assistant",content:"",isLive:!0,diffs:[],tools:[]},n.push(e));let t=e.diffs||(e.diffs=[]),s=t.findIndex(e=>e.file===p.file);-1!==s?t[s]=p:t.push(p);break}case"tool_child":if(!p)break;for(let e=n.length-1;e>=0;e--){let t=ou(n[e]?.tools,e=>e.id===p.parentToolUseId,e=>{let t=[...e.children||[]],s=t.findIndex(e=>e.id===p.id);return -1!==s?t[s]={...t[s],...p}:t.push({...p,status:p.status||"running"}),{...e,children:t}});if(t){n[e].tools=t;break}}break;case"tool_result_child":if(!p?.id)break;for(let e=n.length-1;e>=0;e--){let t=ou(n[e]?.tools,e=>(e.children||[]).some(e=>e.id===p.id),e=>({...e,children:e.children.map(e=>e.id===p.id?{...e,...p,status:p.status||"done"}:e)}));if(t){n[e].tools=t;break}}break;case"tool_start":{if(!p)break;let e=n[n.length-1];if(e&&"assistant"===e.role&&e.isLive&&(e.content||e.thinking||"").length>0)e.isLive=!1,e={id:`msg-${++x}`,role:"assistant",content:"",isLive:!0,diffs:[],tools:[{...p,status:p.status||"running"}]},n.push(e);else if(e&&"assistant"===e.role){let t=e.tools||(e.tools=[]),s=t.findIndex(e=>e.id===p.id);-1!==s?t[s]={...t[s],...p}:t.push({...p,status:p.status||"running"})}else e={id:`msg-${++x}`,role:"assistant",content:"",isLive:!0,diffs:[],tools:[{...p,status:p.status||"running"}]},n.push(e);if(p.name){let e=(0,om.Zm)(t,p.name,p.input,p.id,r);e&&(r=oL(r,e))}break}case"tool_result":{if(!p?.id)break;for(let e=n.length-1;e>=0;e--){let t=n[e],s=t?.tools?.find(e=>e.id===p.id);if(s){Object.assign(s,p,{status:p.status||"done"});break}}let e=(0,om.in)(t,p.name||"",p.output||"",p.id);e&&(r=oL(r,e));break}case"permission_request":c=p;break;case"permission_resolved":c=null;break;case"blocked":d=p;break;case"options_changed":p?.permissionMode&&(u=p.permissionMode),p?.model&&(l.model=p.model),p?.effort&&(l.effort=p.effort);break;case"turn_complete":m=!0,o=!1,c=null,p?.stats&&(i={...i,...p.stats}),n.length>0&&(n[n.length-1].isLive=!1),p?.isError&&!oZ(n,p.result)&&n.push({id:`n-${++x}`,role:"notice",subtype:p.subtype||"",level:"error",content:p.result||"The turn ended in an error."});break;case"stats":p?.stats&&(i={...i,...p.stats});break;case"stopped":m=!0,o=!1,c=null;break;case"stall":for(let e of(m=!0,o=!1,c=null,n))e.isLive&&(e.isLive=!1);break;case"exit":for(let e of(m=!0,o=!1,c=null,n))e.isLive&&(e.isLive=!1);(p?.error||p?.code!=null&&0!==p.code)&&n.push({id:`n-${++x}`,role:"notice",subtype:"exit",level:"error",content:p.error||`The AI process exited (code ${p.code}).`});break;case"error":for(let e of(m=!0,o=!1,n))e.isLive&&(e.isLive=!1);n.push({id:`n-${++x}`,role:"notice",subtype:"error",level:"error",content:p?.message||"AI process failed"});break;case"prompt_refused":n.push({id:`n-${++x}`,role:"notice",subtype:"prompt_refused",level:"error",content:oQ(p)});break;case"conversation_reset":n.length=0,r.length=0,a.length=0,o=!1,c=null,d=null;break;case"cli_event":{let e=p?.type||"",t=p?.record||null;a.push([e,p?.subtype||"",t,p?.ageMs]);let s=oI(e,t);if(!s)break;let{compactSettled:r,...l}=s,i=r?o_(n):-1;if(-1!==i){l.content?.trim()?n[i]={id:`n-${++x}`,role:"notice",...l}:n.splice(i,1);break}if(!l.content?.trim())break;let o=n[n.length-1];!o||"assistant"!==o.role||o.content||o.thinking||(o.tools||[]).length||n.pop(),n.push({id:`n-${++x}`,role:"notice",...l})}}}if(m)for(let e of n)e.tools&&(e.tools=od(e.tools));let p=[];for(let[e,t,s]of a)p=oM(p,e,t,s);return{messages:n,tasks:r,metadata:l,stats:i,isTurnRunning:o,activePermission:c,activeBlocked:d,permissionMode:u,harnessRecords:a,harnessTasks:p}}let o1=(0,r.memo)(function({message:e,engine:t="claude",workspacePath:s="",onResolvePermission:a,onRewind:l,onPreviewRewind:i,onCutLocal:o,rewindIndex:c=null,canRewind:d=!1}){let[u,m]=(0,r.useState)(!1),[x,p]=(0,r.useState)(!1),[h,f]=(0,r.useState)(""),[b,g]=(0,r.useState)(null),[v,y]=(0,r.useState)(!1),[w,k]=(0,r.useState)(null);tS(e=>e.openEditorFile);let{id:j,role:N,content:S,thinking:C,diffs:T=[],tools:R=[],permission:E=null,isLive:_=!1,attachments:$=[]}=e;if("user"===N){let e=async e=>{y(!0),k("preview");let t=await i?.(null,{index:c});(y(!1),k(null),t?.ok)?g({files:t.files||[],text:e}):g({error:t?.error||"The host could not preview this rewind.",text:e})},t=async()=>{let e=b?.text;g(null),y(!0),k("apply"),o?.(j,e);let t=await l?.(null,e,{index:c});(y(!1),k(null),t&&!t.ok)?g({error:t.error||"The rewind did not go through.",text:e}):p(!1)},s=(0,n.jsx)(t9.A,{isOpen:!!b,onClose:()=>g(null),onConfirm:b?.error?()=>g(null):t,title:b?.error?"Cannot rewind":"Rewind to this prompt?",message:b?.error?b.error:["This discards every turn after this prompt and re-sends your edited text.",b?.files?.length?`These ${b.files.length} file${1===b.files.length?"":"s"} go back to how they were:`:"No file changes to restore — this rewinds the conversation only.",...b?.files?.slice(0,8).map(e=>`\xb7 ${e.file}${e.status?` (${e.status})`:""}`)||[],b?.files?.length>8?`… and ${b.files.length-8} more`:"","Edits made by hand, or by shell commands, are NOT restored."].filter(Boolean).join("\n"),confirmText:b?.error?"OK":"Rewind"});if(x)return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"flex justify-end my-3",children:(0,n.jsxs)("div",{className:"max-w-[85%] sm:max-w-[75%] w-full",children:[(0,n.jsx)("textarea",{value:h,onChange:e=>f(e.target.value),onBlur:()=>{v||b||p(!1)},onKeyDown:t=>{if("Enter"===t.key&&!t.shiftKey){if(t.nativeEvent.isComposing||229===t.keyCode||(t.preventDefault(),v||b))return;h.trim()&&e(h.trim())}"Escape"===t.key&&p(!1)},rows:Math.min(10,h.split("\n").length+1),className:"w-full resize-none overflow-hidden rounded-brand-lg bg-surface-2 px-4 py-2.5 text-sm text-text focus:outline-none focus:ring-1 focus:ring-brand-500 leading-relaxed",autoFocus:!0}),(0,n.jsxs)("div",{className:"flex justify-end items-center gap-1.5 mt-1.5 text-[11px] text-text-muted",children:[v&&(0,n.jsx)(t3.kr,{size:11,className:"animate-spin"}),(0,n.jsx)("span",{children:"apply"===w?"Rewinding...":"preview"===w?"Checking what this would change...":"Enter to rewind, Esc to cancel"})]})]})}),s]});let r=d&&!!l,a=()=>{(0,t7.e)(),f(S||""),p(!0)};return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"group/msg flex flex-col items-end my-3",children:[(0,n.jsxs)("div",{className:"max-w-[85%] sm:max-w-[75%] flex flex-col items-end gap-1.5",children:[$.length>0&&(0,n.jsx)("div",{className:"flex flex-wrap justify-end gap-1.5",children:$.map((e,t)=>(0,n.jsxs)("span",{className:`inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] ${e.isImage?"border-brand-500/40 bg-brand-500/10 text-brand-500":"border-border-subtle bg-surface-2 text-text-muted"}`,children:[e.isImage?(0,n.jsx)(t3._V,{size:10}):(0,n.jsx)(t3.xv,{size:10}),(0,n.jsx)("span",{className:"max-w-[160px] truncate",children:e.filename})]},`${e.filename}-${t}`))}),S&&(0,n.jsx)("div",{onClick:r?e=>{let t=window.getSelection();t&&!t.isCollapsed&&t.containsNode(e.currentTarget,!0)||a()}:void 0,className:`px-4 py-2.5 rounded-brand-lg bg-brand-500/15 border border-brand-500/25 text-text text-sm whitespace-pre-wrap wrap-anywhere ${r?"cursor-pointer":""}`,children:S})]}),(0,n.jsxs)("div",{className:"flex items-center gap-1 mt-1",children:[(0,n.jsx)("button",{type:"button",onClick:()=>{(0,t7.e)(),S&&(navigator.clipboard.writeText(S),m(!0),setTimeout(()=>m(!1),2e3))},className:"px-1.5 py-0.5 rounded text-[11px] text-text-muted hover:text-text hover:bg-surface-2 flex items-center gap-1 transition-colors",title:"Copy this prompt",children:u?(0,n.jsx)(t3.aJ,{size:11,className:"text-success"}):(0,n.jsx)(t3.QR,{size:11})}),r&&(0,n.jsx)("button",{type:"button",disabled:v,onClick:a,className:"px-1.5 py-0.5 rounded text-[11px] text-text-muted hover:text-text hover:bg-surface-2 flex items-center gap-1 transition-colors disabled:opacity-40",title:"Edit & rewind to here",children:v&&"preview"===w?(0,n.jsx)(t3.kr,{size:11,className:"animate-spin"}):(0,n.jsx)(t3.gH,{size:11})})]})]}),s]})}return null},(e,t)=>e.message===t.message&&e.onResolvePermission===t.onResolvePermission&&e.rewindIndex===t.rewindIndex||!e.message.isLive&&!t.message.isLive&&e.message.id===t.message.id&&e.message.content===t.message.content&&e.message.thinking===t.message.thinking&&e.message.permission===t.message.permission&&e.message.tools===t.message.tools&&e.message.diffs===t.message.diffs&&e.canRewind===t.canRewind&&e.rewindIndex===t.rewindIndex&&e.onResolvePermission===t.onResolvePermission);function o2(e,t){if("string"!=typeof e||!e)return{dir:"",name:""};let s=e.replace(/\\/g,"/"),n=t?t.replace(/\\/g,"/").replace(/\/+$/,""):"",r=!!n&&s.startsWith(`${n}/`),a=r?5:4,l=(r?s.slice(n.length+1):s).split("/").filter(Boolean);l.length>a&&(l=["…",...l.slice(-a)]);let i=l.pop()||"";return{dir:l.join("/"),name:i}}let o5={file:t3.kU},o3=(0,r.memo)(function e({id:t="",name:s="tool",command:a="",input:l=null,output:i="",error:o="",status:c="done",children:d=[],engine:u="claude",workspacePath:m="",deferred:x=!1}){let p=!!(o||"error"===c),[h,f]=(0,r.useState)(p&&!x),[b,g]=(0,r.useState)(!1),v=tS(e=>e.openEditorFile);(0,r.useEffect)(()=>{p&&!x&&f(!0)},[p,x]);let y=!!a||"string"!=typeof l&&!!l?.command,w="string"==typeof l?"":l?.file_path||l?.notebook_path||l?.path||l?.file||"",k=a||w||("string"==typeof l?l:l?.command||l?.pattern||l?.query||""),j=!y&&w&&k===w?function(e,t){let{dir:s,name:n}=o2(e,t);return s?`${s}/${n}`:n}(k,m):k,N=l?.file_path||l?.path||l?.file||"",S=o5[(0,om.$Z)(u,s)]||t3.Jl;return(0,n.jsxs)("div",{className:"my-1 text-xs",children:[(0,n.jsxs)("div",{onClick:()=>f(!h),className:"flex items-center justify-between py-1 px-0 hover:bg-surface-2/40 cursor-pointer data-pane-control select-none transition-colors group/tool",children:[(0,n.jsxs)("div",{className:"flex items-start gap-2 min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"shrink-0 mt-0.5",children:"running"===c?(0,n.jsx)(t3.kr,{size:13,className:"animate-spin text-accent"}):p?(0,n.jsx)(t3.RI,{size:13,className:"text-danger"}):(0,n.jsx)(S,{size:13,className:"text-success"})}),(0,n.jsxs)("div",{className:"min-w-0 flex-1 font-mono text-[11px] leading-relaxed line-clamp-2",children:[(0,n.jsx)("span",{className:"text-[10px] font-semibold text-text uppercase tracking-wider break-all px-1 py-0.5 rounded bg-surface-2/80 [box-decoration-break:clone]",title:s,children:s}),j&&(0,n.jsxs)(n.Fragment,{children:[" ",(0,n.jsx)("span",{className:"text-text-muted break-all",title:j,children:j})]})]}),(0,n.jsx)("span",{className:"text-text-muted/50 shrink-0 self-center",children:h?(0,n.jsx)(t3.yQ,{size:11}):(0,n.jsx)(t3.c_,{size:11})})]}),(0,n.jsxs)("div",{className:"flex items-center gap-1 shrink-0 ml-2 opacity-0 group-hover/tool:opacity-100 transition-opacity",children:[N&&(0,n.jsx)("button",{type:"button",onClick:e=>{e.stopPropagation(),(0,t7.e)(),N&&v(N)},className:"p-0.5 text-text-muted hover:text-text rounded hover:bg-surface-3 transition-colors flex items-center gap-1",title:"Open file in editor",children:(0,n.jsx)(t3.Gr,{size:11})}),(0,n.jsx)("button",{type:"button",onClick:e=>{e.stopPropagation(),(0,t7.e)();let t=i||o||j;t&&(navigator.clipboard.writeText("string"==typeof t?t:JSON.stringify(t,null,2)),g(!0),setTimeout(()=>g(!1),2e3))},className:"p-0.5 text-text-muted hover:text-text rounded hover:bg-surface-3 transition-colors",title:"Copy output",children:b?(0,n.jsx)(t3.aJ,{size:11,className:"text-success"}):(0,n.jsx)(t3.QR,{size:11})})]})]}),h&&(0,n.jsxs)("div",{className:"mt-1 ml-3.5 pl-3 border-l-2 border-border-subtle/80 bg-surface-2/20 rounded-r-brand p-2 overflow-x-auto max-h-[260px] overflow-y-auto font-mono text-[11px] select-text",children:[o&&(0,n.jsx)("div",{className:"text-danger mb-1.5 whitespace-pre-wrap",children:o}),i?(0,n.jsx)("div",{className:"text-text whitespace-pre-wrap leading-relaxed",children:"string"==typeof i?i:JSON.stringify(i,null,2)}):o?null:(0,n.jsx)("div",{className:"text-text-muted italic",children:"Running or no output returned..."})]}),h&&d.length>0&&(0,n.jsx)("div",{className:"ml-3.5 pl-3 border-l-2 border-border-subtle/80",children:d.map(t=>(0,n.jsx)(e,{...t,engine:u,workspacePath:m},t.id))})]})}),o4=new Set(["TaskCreate","TaskUpdate","TodoWrite","todowrite"]),o6=new Set(["claude","omp","devin","opencode"]),o8=new Set(["Edit","Write","MultiEdit","NotebookEdit","file_change","edit","write","write_to_file","replace_file_content"]),o9=e=>"thought"===e.kind||"tool"===e.kind||"diff"===e.kind;function o7({total:e,windowSize:t=3,children:s}){let[a,l]=(0,r.useState)(0),i=function(e,t,s=0){let n=e-Math.max(0,s);return n>t+1?n-t:0}(e,t,a);return(0,n.jsxs)(n.Fragment,{children:[a>0?(0,n.jsx)("button",{type:"button",onClick:()=>l(e=>e-Math.min(12,Math.max(0,e))),className:"py-0.5 text-left font-mono text-[10.5px] text-text-subtle hover:text-text",children:"▼ show less"}):i>0?(0,n.jsxs)("button",{type:"button",onClick:()=>l(e=>e+Math.min(12,Math.max(0,i))),className:"py-0.5 text-left font-mono text-[10.5px] text-text-subtle hover:text-text",children:["▲ ",i," more ",1===i?"step":"steps"]}):null,s(i)]})}let ce=(0,r.memo)(function({file:e="",patch:t="",diff:s="",content:a="",workspacePath:l=""}){let[i,o]=(0,r.useState)(!1),c=tS(e=>e.openEditorFile),d=is(),u=t||s||(t||s||!a?"":String(a).split("\n").map(e=>`+${e}`).join("\n")),m=u?u.split("\n"):[],x=o2(e,l),p=m.filter(e=>e.startsWith("+")&&!e.startsWith("+++")).length,h=m.filter(e=>e.startsWith("-")&&!e.startsWith("---")).length;return(0,n.jsxs)("div",{className:"my-1 text-xs",children:[(0,n.jsxs)("div",{onClick:()=>o(!i),className:"flex items-center justify-between py-1 px-0 hover:bg-surface-2/40 cursor-pointer data-pane-control select-none transition-colors group/tool",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2 min-w-0",children:[(0,n.jsx)(t3.GD,{size:13,className:"text-success shrink-0"}),(0,n.jsx)("span",{className:"min-w-0 font-mono font-medium text-text text-[11px] break-all",title:e,children:x.dir?`${x.dir}/${x.name}`:x.name||"diff"}),(p>0||h>0)&&(0,n.jsxs)("span",{className:"flex items-center gap-1 font-mono text-[10px] shrink-0 text-text-muted",children:[p>0&&(0,n.jsxs)("span",{className:"text-success",children:["+",p]}),h>0&&(0,n.jsxs)("span",{className:"text-danger",children:["-",h]})]}),(0,n.jsx)("span",{className:"text-text-muted/50 shrink-0",children:i?(0,n.jsx)(t3.yQ,{size:11}):(0,n.jsx)(t3.c_,{size:11})})]}),(0,n.jsx)("div",{className:`flex items-center gap-1 shrink-0 ml-2 transition-opacity ${d?"opacity-100":"opacity-0 group-hover/tool:opacity-100"}`,children:e&&(0,n.jsx)("button",{type:"button",onClick:t=>{t.stopPropagation(),(0,t7.e)(),e&&c(e)},className:"p-0.5 text-text-muted hover:text-text rounded hover:bg-surface-3 transition-colors flex items-center gap-1 text-[10px]",title:"Open file in editor",children:(0,n.jsx)(t3.Gr,{size:11})})})]}),i&&(0,n.jsx)("div",{className:"mt-1 ml-3.5 pl-3 border-l-2 border-border-subtle/80 bg-surface-2/20 rounded-r-brand p-2 overflow-x-auto max-h-[300px] overflow-y-auto font-mono text-[11px] leading-relaxed select-text",children:0===m.length?(0,n.jsx)("div",{className:"text-text-muted italic py-1 px-2",children:"No changes"}):m.map((e,t)=>{let s=e.startsWith("+")&&!e.startsWith("+++"),r=e.startsWith("-")&&!e.startsWith("---"),a=e.startsWith("@@"),l="text-text",i="";return s?(l="text-success",i="bg-success/10"):r?(l="text-danger",i="bg-danger/10"):a&&(l="text-text-muted",i="bg-surface-2/40"),(0,n.jsx)("div",{className:`px-2 py-0.5 rounded-sm whitespace-pre ${l} ${i}`,children:e},t)})})]})});var ct=s(6552);let cs=(0,r.memo)(function({text:e="",isLive:t=!1,defaultOpen:s=!1}){let[a,l]=(0,r.useState)(s);return e?.trim()?(0,n.jsxs)("div",{className:"my-1.5 text-xs select-none",children:[(0,n.jsxs)("button",{type:"button",onClick:()=>l(e=>!e),className:"inline-flex items-center gap-1.5 text-[11px] text-text-muted hover:text-text py-0.5 transition-colors cursor-pointer group",children:[(0,n.jsx)(t3.sU,{size:12,className:t?"animate-pulse text-success":"text-success"}),(0,n.jsx)("span",{className:"italic",children:t?"Thinking...":"Thought process"}),(0,n.jsx)("span",{className:"text-text-muted/50 group-hover:text-text-muted",children:a?(0,n.jsx)(t3.yQ,{size:12}):(0,n.jsx)(t3.c_,{size:12})})]}),a&&(0,n.jsx)("div",{className:"mt-1 pl-3.5 border-l-2 border-border-subtle/80 font-mono text-[11px] text-text-muted leading-relaxed whitespace-pre-wrap max-h-[260px] overflow-y-auto custom-scrollbar select-text py-1",children:e})]}):null}),cn=/Command running in background with ID:\s*([^\s.]+)/;var cr=s(14890);let ca=(0,r.memo)(function({id:e="",name:t="Bash",input:s=null,output:a="",error:l="",status:i="done",deferred:o=!1}){let c,{sessionId:d}=(0,cr.OO)(),u=!!(l||"error"===i),[m,x]=(0,r.useState)(u&&!o),[p,h]=(0,r.useState)(!1),[f,b]=(0,r.useState)(!1);(0,r.useEffect)(()=>{u&&!o&&x(!0)},[u,o]);let g=s?.command||"",v=s?.description||"",y=l||a||"",w="string"==typeof y?y:y?JSON.stringify(y,null,2):"",k=(c=cn.exec("string"==typeof a?a:""))?c[1]:"",j=!!(s?.run_in_background||k);return(0,n.jsxs)("div",{className:"my-1 text-xs",id:(0,cr.xo)(d,"shell",e),children:[(0,n.jsxs)("div",{onClick:()=>x(!m),className:"flex items-start justify-between py-1 px-0 hover:bg-surface-2/40 cursor-pointer data-pane-control select-none transition-colors group/tool",children:[(0,n.jsxs)("div",{className:"flex items-start gap-2 min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"shrink-0 mt-0.5",children:"running"===i?(0,n.jsx)(t3.kr,{size:13,className:"animate-spin text-accent"}):u?(0,n.jsx)(t3.RI,{size:13,className:"text-danger"}):(0,n.jsx)(t3.Jl,{size:13,className:"text-success"})}),(0,n.jsx)("span",{className:"text-text-muted select-none shrink-0 font-mono text-[11px] leading-relaxed",children:"$"}),(0,n.jsx)("span",{className:"font-mono text-[11px] leading-relaxed text-text line-clamp-2 min-w-0",title:g,children:g||t}),j&&(0,n.jsxs)("span",{className:"font-mono text-[10px] font-semibold text-warning shrink-0 px-1 py-0.5 rounded bg-warning/10",title:k?`Background shell ${k}`:"Running in the background",children:["BG",k?` ${k}`:""]}),w&&(0,n.jsx)("span",{className:"text-text-muted/50 shrink-0",children:m?(0,n.jsx)(t3.yQ,{size:11}):(0,n.jsx)(t3.c_,{size:11})})]}),(0,n.jsx)("div",{className:"flex items-center gap-1 shrink-0 ml-2 opacity-0 group-hover/tool:opacity-100 transition-opacity",children:g&&(0,n.jsx)("button",{type:"button",onClick:e=>{e.stopPropagation(),(0,t7.e)(),navigator.clipboard.writeText(g),h(!0),setTimeout(()=>h(!1),2e3)},className:"p-0.5 text-text-muted hover:text-text rounded hover:bg-surface-3 transition-colors text-[10px] flex items-center gap-0.5",title:"Copy command",children:p?(0,n.jsx)(t3.aJ,{size:11,className:"text-success"}):(0,n.jsx)(t3.QR,{size:11})})})]}),v&&!m&&(0,n.jsxs)("div",{className:"ml-7 text-[10px] text-text-muted/70 italic truncate",children:["# ",v]}),m&&w&&(0,n.jsxs)("div",{className:"mt-1 ml-3.5 pl-3 border-l-2 border-border-subtle/80 bg-surface-2/20 rounded-r-brand overflow-x-auto max-h-[260px] overflow-y-auto font-mono text-[11px] select-text relative group/out",children:[v&&(0,n.jsxs)("div",{className:"px-2 pt-1.5 text-[10px] text-text-muted/70 italic",children:["# ",v]}),(0,n.jsx)("pre",{className:`p-2 whitespace-pre-wrap leading-relaxed ${u?"text-danger":"text-text"}`,children:w}),(0,n.jsx)("button",{type:"button",onClick:e=>{e.stopPropagation(),(0,t7.e)(),navigator.clipboard.writeText(w),b(!0),setTimeout(()=>b(!1),2e3)},className:"absolute top-1.5 right-1.5 p-1 rounded bg-surface-3/80 hover:bg-surface-3 text-text-muted hover:text-text opacity-0 group-hover/out:opacity-100 transition-opacity text-[10px]",title:"Copy output",children:f?(0,n.jsx)(t3.aJ,{size:10,className:"text-success"}):(0,n.jsx)(t3.QR,{size:10})})]})]})});function cl(e){let t=String(e||"").split("\n")[0].trim();return t.length>140?`${t.slice(0,140)}…`:t}let ci=(0,r.memo)(function({id:e="",name:t="Agent",input:s=null,output:a="",error:l="",status:i="done",children:o=[],engine:c="claude",workspacePath:d=""}){let{sessionId:u}=(0,cr.OO)(),m="running"===i,x=!!(l||"error"===i),p=o.filter(e=>"running"===e.status).length,[h,f]=(0,r.useState)(x);(0,r.useEffect)(()=>{x&&f(!0)},[x]);let b=oa.has(t),g=b?ol({input:s}):t||"agent",v=b?cl(s?.prompt??s?.description??s?.message):cl(s?.message??s?.prompt??s?.query);return(0,n.jsxs)("div",{className:"my-1 text-xs",id:(0,cr.xo)(u,"agent",e),children:[(0,n.jsxs)("div",{onClick:()=>f(!h),className:"flex items-center justify-between py-1 px-0 hover:bg-surface-2/40 cursor-pointer data-pane-control select-none transition-colors group/tool",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"shrink-0",children:m?(0,n.jsx)(t3.kr,{size:13,className:"animate-spin text-accent"}):x?(0,n.jsx)(t3.RI,{size:13,className:"text-danger"}):(0,n.jsx)(t3.Jl,{size:13,className:"text-success"})}),(0,n.jsx)("span",{className:"font-mono text-[10px] font-semibold text-text uppercase tracking-wider shrink-0 px-1 py-0.5 rounded bg-surface-2/80",children:"AGENT"}),(0,n.jsx)("span",{className:"font-mono text-[11px] font-semibold text-brand-500 shrink-0",children:g}),v&&(0,n.jsx)("span",{className:"text-[11px] text-text-muted truncate min-w-0",title:v,children:v})]}),(0,n.jsxs)("div",{className:"flex items-center gap-2 shrink-0 ml-2",children:[o.length>0&&(0,n.jsxs)("span",{className:"font-mono text-[10px] text-text-subtle",title:`${o.length} sub-agent tool calls`,children:[m&&p>0?`${p}/${o.length}`:o.length," tools"]}),(0,n.jsx)("span",{className:"text-text-muted/50",children:h?(0,n.jsx)(t3.yQ,{size:11}):(0,n.jsx)(t3.c_,{size:11})})]})]}),h&&(0,n.jsxs)("div",{className:"mt-1 ml-3.5 pl-3 border-l-2 border-border-subtle/80 py-1 space-y-0.5",children:[o.length>0?(0,n.jsx)(o7,{total:o.length,children:e=>(e>0?o.slice(e):o).map(e=>cm(c,e,{workspacePath:d})||(0,n.jsx)(o3,{...e,engine:c,workspacePath:d},e.id))}):(0,n.jsx)("div",{className:"text-text-muted italic py-0.5",children:m?"Sub-agent started…":"No tool calls reported."}),!m&&(a||l)&&(0,n.jsx)("div",{className:"mt-1 pl-3 border-l-2 border-border-subtle/60 font-mono text-[11px] max-h-[240px] overflow-y-auto select-text",children:(0,n.jsx)("div",{className:`whitespace-pre-wrap leading-relaxed ${x?"text-danger":"text-text-muted"}`,children:"string"==typeof(l||a)?l||a:JSON.stringify(l||a,null,2)})})]})]})}),co=(0,r.memo)(function({toolName:e="EnterPlanMode",input:t={}}){let s="string"==typeof t?.plan?t.plan.trim():"";if(s)return(0,n.jsx)(cc,{plan:s,explanation:t?.explanation||""});let r="EnterPlanMode"===e,a=t?.reason||(r?"Exploring codebase and designing implementation approach":"Implementation plan finalized");return(0,n.jsxs)("div",{className:`p-3.5 rounded-brand-lg border flex flex-col gap-2 my-2 text-xs ${r?"bg-brand-500/10 border-brand-500/30 text-text":"bg-success/10 border-success/30 text-success"}`,children:[(0,n.jsxs)("div",{className:"flex items-center justify-between font-semibold",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[r?(0,n.jsx)(t3.y8,{size:16,className:"text-brand-500"}):(0,n.jsx)(t3.Jl,{size:16,className:"text-success"}),(0,n.jsx)("span",{children:r?"Plan Mode Activated":"Plan Mode Completed"})]}),(0,n.jsx)("span",{className:"font-mono text-[10px] px-2 py-0.5 rounded bg-surface-2 text-text-muted",children:e})]}),(0,n.jsxs)("div",{className:"text-xs text-text leading-relaxed font-sans pl-6",children:[(0,n.jsx)("span",{className:"text-text-muted",children:"Reason: "}),a]}),r&&(0,n.jsx)("div",{className:"text-[11px] text-text-muted/80 italic pl-6 select-none",children:"Plan mode reads files and drafts an approach — nothing is applied without your review, in whichever CLI this chat is running."})]})}),cc=(0,r.memo)(function({plan:e,explanation:t=""}){return(0,n.jsxs)("div",{className:"p-3.5 rounded-brand-lg border border-brand-500/30 bg-brand-500/10 text-text my-2 text-xs flex flex-col gap-2",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2 font-semibold",children:[(0,n.jsx)(t3.y8,{size:16,className:"text-brand-500"}),(0,n.jsx)("span",{children:"Plan"})]}),(0,n.jsx)("pre",{className:"font-mono text-[11px] leading-relaxed whitespace-pre-wrap break-words pl-6 max-h-[320px] overflow-y-auto",children:e}),t&&(0,n.jsx)("div",{className:"text-[11px] text-text-muted pl-6 italic",children:t})]})}),cd=(0,r.memo)(function({toolName:e="enteredReviewMode",input:t={}}){let s="enteredReviewMode"===e,r=String(t?.review||"").trim();return(0,n.jsxs)("div",{className:`p-3.5 rounded-brand-lg border flex flex-col gap-2 my-2 text-xs ${s?"bg-brand-500/10 border-brand-500/30 text-text":"bg-success/10 border-success/30 text-success"}`,children:[(0,n.jsxs)("div",{className:"flex items-center gap-2 font-semibold",children:[s?(0,n.jsx)(t3.kU,{size:16,className:"text-brand-500"}):(0,n.jsx)(t3.Jl,{size:16,className:"text-success"}),(0,n.jsx)("span",{children:s?"Code review started":"Code review finished"})]}),r&&(0,n.jsxs)("div",{className:"text-xs text-text leading-relaxed font-sans pl-6",children:[(0,n.jsx)("span",{className:"text-text-muted",children:"Reviewing: "}),r]})]})}),cu={bash:(e,t)=>(0,n.jsx)(ca,{...e,deferred:t},e.id),agent:(e,t,{engine:s,workspacePath:r})=>(0,n.jsx)(ci,{...e,engine:s,workspacePath:r},e.id),plan:e=>(0,n.jsx)(co,{toolName:e.name,input:e.input},e.id),review:e=>(0,n.jsx)(cd,{toolName:e.name,input:e.input},e.id),question:(e,t,s)=>{if("running"===e.status||!e.output&&!e.error)return null;let r=s?.engine==="antigravity"&&/user skipped/i.test(String(e.output||""));return(0,n.jsx)(ct.J,{engine:s?.engine,questions:e.input?.questions||[],answers:r||e.error?null:e.output||"",declined:r||!!e.error||"error"===e.status},e.id)}};function cm(e,t,s={}){let n=cu[(0,om.$Z)(e,t.name)];return n?n(t,s.deferred,{...s,engine:e}):null}function cx({row:e,engine:t,workspacePath:s,deferred:r}){if("thought"===e.kind)return(0,n.jsx)(cs,{text:e.text,isLive:e.isLive});if("diff"===e.kind){let t=e.diff;return(0,n.jsx)(ce,{file:t.file,patch:t.patch,diff:t.diff,content:t.content,workspacePath:s})}let a=e.tool;return cm(t,a,{workspacePath:s,deferred:r})||(0,n.jsx)(o3,{...a,engine:t,workspacePath:s,deferred:r})}let cp={info:"text-text-muted",suggestion:"text-text-muted",warning:"text-warning",error:"text-danger"};function ch({notice:e}){if(!e?.content)return null;let t=`text-xs leading-relaxed py-1 px-2 my-0.5 rounded border-l-2 border-current/30 bg-surface-2/40 wrap-anywhere ${cp[e.level]||cp.info}`;return e.compacting?(0,n.jsxs)("div",{className:`${t} flex items-center gap-2`,children:[(0,n.jsx)(t3.kr,{size:12,className:"animate-spin text-brand-500 shrink-0"}),(0,n.jsx)("span",{children:e.content}),(0,n.jsx)(cb,{})]}):(0,n.jsxs)("div",{className:t,children:[e.content,e.compact?.detail&&(0,n.jsxs)("span",{className:"text-text-muted",children:[" \xb7 ",e.compact.detail]}),e.compact?.durationMs?(0,n.jsxs)("span",{className:"text-text-muted",children:[" \xb7 ",cf(e.compact.durationMs)]}):null]})}function cf(e){let t=e/1e3;return t<60?`${t.toFixed(1)}s`:`${Math.floor(t/60)}m ${Math.round(t%60)}s`}function cb(){let[e]=(0,r.useState)(()=>Date.now()),[t,s]=(0,r.useState)(e);return(0,r.useEffect)(()=>{let e=setInterval(()=>s(Date.now()),1e3);return()=>clearInterval(e)},[]),(0,n.jsx)("span",{className:"text-text-muted/70 tabular-nums",children:cf(t-e)})}function cg({content:e,isLive:t}){let s=function(e,t){let[s,n]=(0,r.useState)(e),a=(0,r.useRef)(e);return(0,r.useEffect)(()=>{a.current=e},[e]),(0,r.useEffect)(()=>{if(!t)return;let e=setInterval(()=>{n(e=>e===a.current?e:a.current)},80);return()=>clearInterval(e)},[t]),t?s:e}(e,t);return(0,n.jsxs)("div",{className:"text-sm leading-relaxed text-text py-1.5 wrap-anywhere",children:[(0,n.jsx)(i1,{content:s}),t&&(0,n.jsx)("span",{className:"inline-block w-1.5 h-3.5 bg-brand-500 animate-pulse ml-1 align-middle"})]})}let cv=(0,r.memo)(function({messages:e=[],engine:t="claude",workspacePath:s="",onResolvePermission:a,isLive:l=!0}){let i=(0,r.useMemo)(()=>(function(e=[],t="claude"){let s=[],n=new Set;for(let r of e){if("notice"===r.role){s.push({kind:"notice",id:r.id,notice:{subtype:r.subtype,level:r.level,content:r.content,...r.compact?{compact:r.compact}:null,...r.compacting?{compacting:!0}:null}});continue}if("assistant"!==r.role)continue;r.thinking?.trim()&&s.push({kind:"thought",id:`${r.id}-th`,text:r.thinking});let e=function(e,t,s){return(t||[]).filter(t=>!(!t||!t.name||(s||[]).some(e=>{let s;return e.file&&(s=e.file,o8.has(t?.name)&&s&&((t.input?.paths||[]).includes(s)||((e={})=>e.file_path||e.notebook_path||e.path||e.filePath||e.file||"")(t.input)===s))})||"task"===(0,om.$Z)(e,t.name)&&o4.has(t.name)))}(t,r.tools,r.diffs);for(let a=0;a<e.length;a++){let l=e[a];if("question"===(0,om.$Z)(t,l.name)&&"running"===l.status&&o6.has(t))continue;let i=l.id||`${r.id}-t${a}`;n.has(i)||(n.add(i),s.push({kind:"tool",id:i,tool:l,engine:t}))}for(let e=0;e<(r.diffs?.length||0);e++){let t=r.diffs[e];s.push({kind:"diff",id:`${r.id}-d${e}`,diff:t})}r.content&&s.push({kind:"prose",id:`${r.id}-p`,content:r.content,isLive:r.isLive}),r.permission&&s.push({kind:"permission",id:`${r.id}-perm`,permission:r.permission})}return s})(e,t),[e,t]),o=(0,r.useMemo)(()=>(function(e=[],t=6,{deferred:s=!1}={}){let n=[];for(let t of e)if(o9(t)){let e=n[n.length-1];e?.type==="steps"?e.rows.push(t):n.push({type:"steps",rows:[t]})}else n.push({type:"row",row:t});return n.map((e,n)=>{if("steps"!==e.type)return{...e,key:`r${n}`,deferred:s};let r=e.rows.length>t+1?e.rows.length-t:0;return{type:"steps",key:`s${n}`,rows:e.rows,hidden:r,deferred:s}})})(i,3,{deferred:!l}),[i,l]);return(0,n.jsx)("div",{className:"my-1",children:o.map(e=>{if("steps"!==e.type){if("prose"===e.row.kind)return(0,n.jsx)(cg,{content:e.row.content,isLive:e.row.isLive},e.key);if("notice"===e.row.kind)return(0,n.jsx)(ch,{notice:e.row.notice},e.key);if("permission"===e.row.kind){let t=e.row.permission;return(0,n.jsx)(ct.J,{requestId:t.requestId,questions:t.input?.questions||[],onResolve:a},e.key)}return null}return(0,n.jsx)("div",{className:"relative pl-2.5 border-l-2 border-border-subtle/50 my-1",children:(0,n.jsx)(o7,{total:e.rows.length,children:r=>(r>0?e.rows.slice(r):e.rows).map(e=>(0,n.jsx)(cx,{row:e,engine:t,workspacePath:s,deferred:!l},e.id))})},e.key)})})},(e,t)=>{if(e.messages.length!==t.messages.length)return!1;for(let s=0;s<e.messages.length;s++)if(e.messages[s]!==t.messages[s])return!1;return e.engine===t.engine&&e.workspacePath===t.workspacePath&&e.isLive===t.isLive&&e.onResolvePermission===t.onResolvePermission}),cy=[],cw=(e,t)=>{if(!e||!t)return null;let s=e.getBoundingClientRect();return{scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight,nodeTop:t.getBoundingClientRect().top-s.top+e.scrollTop}},ck=e=>String(e).padStart(2,"0");function cj(e){let t=Math.max(0,Math.floor(e/1e3)),s=Math.floor(t/3600),n=Math.floor(t%3600/60),r=t%60;return s>0?`${s}h ${n}m ${ck(r)}s`:n>0?`${n}m ${ck(r)}s`:`${r}s`}function cN(e){return e?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"text-text-muted/60",children:" \xb7 "}),oy(e)," tokens"]}):null}let cS=(0,r.memo)(function({engine:e="claude",failed:t=!1,onRetry:s}){let r=nt.UB[e]||nt.UB.claude;return t?(0,n.jsxs)("div",{className:"h-full flex flex-col items-center justify-center gap-3 text-center p-6 select-none",children:[(0,n.jsx)("span",{className:"font-mono text-[12px] text-danger",children:"Couldn't load this conversation"}),(0,n.jsx)("span",{className:"text-[11px] font-mono text-text-muted/70",children:r.label}),(0,n.jsx)("button",{type:"button",onClick:()=>{(0,t7.e)(),s?.()},className:"px-3 py-1.5 rounded-brand text-[11px] font-mono text-text bg-surface-2 hover:bg-surface-3 transition-colors",children:"Retry"})]}):(0,n.jsxs)("div",{className:"h-full flex flex-col items-center justify-center gap-3 text-center p-6 select-none",children:[(0,n.jsx)(t3.kr,{size:20,className:"animate-spin text-brand-500"}),(0,n.jsx)("span",{className:"ai-sheen-text font-mono text-[12px] text-text-muted",children:"Syncing…"}),(0,n.jsx)("span",{className:"text-[11px] font-mono text-text-muted/70",children:r.label})]})}),cC=(0,r.memo)(function({sessionId:e,engine:t="",hydrating:s=!1}){let a=oq(t=>t.bySession[e]?.isTurnRunning),l=oq(t=>t.bySession[e]?.turnStartedAt),i=oq(t=>t.bySession[e]?.lastTurnMs),o=oq(t=>t.bySession[e]?.stats),c=oq(t=>t.bySession[e]?.turnBaseline),d=Q(e=>e.connected),u=Q(e=>e.retryStatus),m=oq(t=>t.bySession[e]?.messages)||cy,x=m[m.length-1]||null,p=Math.max(0,(o?.outputTokens||0)-(c?.outputTokens||0)),[h,f]=(0,r.useState)(Date.now());(0,r.useEffect)(()=>{if(!a)return;f(Date.now());let e=setInterval(()=>f(Date.now()),1e3);return()=>clearInterval(e)},[a]);let[b,g]=(0,r.useState)(null),v=(0,r.useRef)(a);(0,r.useEffect)(()=>{v.current&&!a&&l&&g({ms:i||Date.now()-l,outputTokens:p,changes:oj(m)}),a&&g(null),v.current=a},[a,l,i,p,m]);let y=(0,r.useMemo)(()=>b||a||!i?null:{ms:i,outputTokens:0,changes:oj(m)},[b,a,i,m]),w=b||y;if(!a&&!w)return null;if(!a)return(0,n.jsxs)("div",{className:"flex items-center gap-2 py-1 select-none text-xs text-text-muted",children:[(0,n.jsx)(t3.aJ,{size:14,className:"text-emerald-400 shrink-0"}),(0,n.jsxs)("span",{className:"flex items-center min-w-0 font-mono text-[11px]",children:[(0,n.jsxs)("span",{className:"truncate",children:["Worked for ",(0,n.jsx)("span",{className:"text-text",children:cj(w.ms)})]}),(0,n.jsxs)("span",{className:"shrink-0",children:[function({added:e,removed:t}){return e||t?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"text-text-muted/60",children:" \xb7 "}),e>0&&(0,n.jsxs)("span",{className:"text-success",children:["+",e]}),e>0&&t>0&&" ",t>0&&(0,n.jsxs)("span",{className:"text-danger",children:["−",t]})]}):null}(w.changes),cN(w.outputTokens)]})]})]});let k=x?.tools?.find(e=>"running"===e.status),j=p+function(e=[]){let t=0;for(let s=e.length-1;s>=0;s--){let n=e[s];if("user"===n.role)break;t+=(n.content?.length||0)+(n.thinking?.length||0)}return Math.round(t/4)}(m),N=function({connected:e=!0,hydrating:t=!1,retryStatus:s=null,activeTool:n=null,engine:r="",lastMsg:a=null}={}){if(!e){let e=s||{};return{verb:"Reconnecting",detail:e.isRetrying?`attempt ${e.attempt}/${e.maxAttempts}${e.failed?" \xb7 gave up":""}`:"",tone:"alert"}}if(t)return{verb:"Syncing",detail:"from host",tone:"wait"};if(n?.name){let{name:e,input:t={}}=n,s=(0,om.$Z)(r,e),a=oh(t.file_path||t.path);switch(s){case"bash":return{verb:"Running",detail:ob(t.command||"",op),tone:"wait"};case"file":{let s=/^(list|list_dir|ls)$/i.test(e),n=t.offset?`:L${t.offset}`:"";return{verb:s?"Listing":"Reading",detail:ob(`${a}${n}`,op),tone:"wait"}}case"search":{let e=t.pattern?`"${t.pattern}"`:t.query||t.url||"",s=oh(t.path);return{verb:"Searching",detail:ob([e,s?`in ${s}`:""].filter(Boolean).join(" "),op),tone:"wait"}}case"diff":return{verb:/^(Write|write_to_file)$/i.test(e)?"Writing":"Editing",detail:ob(oh(t.file_path||t.filePath||t.file||t.path)||ov(t),op),tone:"wait"};case"agent":{let e=n.children?.length||0;return{verb:"Delegating",detail:ob([t.description||ov(t),e?`${e} steps`:""].filter(Boolean).join(" \xb7 "),op),tone:"wait"}}case"task":return{verb:"Updating tasks",detail:ob(t.activeForm||t.subject||"",op),tone:"wait"};case"plan":return{verb:"Planning",detail:ob(oh(t.path)||e,op),tone:"wait"};default:return{verb:"Calling",detail:ob([og(e),ov(t)].filter(Boolean).join(" "),op),tone:"wait"}}}return a?.thinking?{verb:"Thinking",detail:ob(of(a.thinking),op),tone:"wait"}:a?.content?{verb:"Writing",detail:ob(of(a.content),op),tone:"wait"}:{verb:"Working",detail:"",tone:"wait"}}({connected:d,hydrating:s,retryStatus:u,activeTool:k,engine:t,lastMsg:x});return(0,n.jsxs)("div",{className:"flex items-center gap-2 py-1 select-none text-xs text-text-muted",children:["alert"===N.tone?(0,n.jsx)("span",{className:"w-2 h-2 rounded-full bg-danger animate-pulse shrink-0"}):(0,n.jsx)(t3.kr,{size:13,className:"animate-spin text-brand-500 shrink-0"}),(0,n.jsxs)("span",{className:"flex items-center min-w-0 font-mono text-[11px]",children:[(0,n.jsxs)("span",{className:"truncate",children:[(0,n.jsxs)("span",{className:`ai-sheen-text${"alert"===N.tone?" !text-danger":""}`,children:[N.verb,"…"]}),N.detail&&(0,n.jsxs)("span",{className:"text-text-subtle",children:[" ",N.detail]}),(0,n.jsx)("span",{className:"text-text-muted/60",children:" \xb7 "}),cj(h-(l||h))]}),(0,n.jsx)("span",{className:"shrink-0",children:cN(j)})]})]})}),cT=(0,r.memo)(function({engine:e,engineMeta:t,workspacePath:s,fileBus:a,onSendPrompt:l,onOpenResume:i}){let{t:o}=(0,se.s)(),[c,d]=(0,r.useState)([]),[u,m]=(0,r.useState)(null),x=aU(s,a,{enabled:!!s});(0,r.useEffect)(()=>{if(!s)return;let e=!0;return a?.getSystemInfo?.().then(t=>{e&&t?.success&&m(t.homedir||null)}).catch(()=>{}),()=>{e=!1}},[a,s]),(0,r.useEffect)(()=>{if(!s)return;let t=!0,n=Q.getState().bus;if(n?.emit)return n.emit("getAgentSessions",{cwd:s},s=>{t&&d((Array.isArray(s?.sessions)?s.sessions:[]).filter(t=>!e||t.agent===e).slice(0,8))}),()=>{t=!1}},[s,e]);let p=s?rs(s,u):"";return(0,n.jsxs)("div",{className:"h-full flex flex-col items-center justify-center text-center p-6 select-none overflow-y-auto custom-scrollbar",children:[(0,n.jsx)("div",{className:"w-12 h-12 rounded-2xl flex items-center justify-center mb-3 shadow-md border border-border-subtle/40 backdrop-blur-sm shrink-0",style:{backgroundColor:`${t.color}15`},children:(0,n.jsx)("img",{src:s$(`${e}-ui`),alt:t.label,className:`w-7 h-7 object-contain ${s_}`})}),(0,n.jsx)("h3",{className:"text-base font-semibold text-text mb-1",children:t.label}),p&&(0,n.jsxs)("div",{className:"flex items-center justify-center gap-2 mb-3 text-[11px] font-mono text-text-muted",title:s,children:[(0,n.jsx)("span",{className:"truncate max-w-[220px]",children:p}),x.branch&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"text-text-muted/50",children:"\xb7"}),(0,n.jsx)("span",{className:"truncate max-w-[140px]",children:x.branch}),x.dirty&&(0,n.jsxs)("span",{className:"text-amber-400",title:`${x.changedCount} changed`,children:["●",x.changedCount]})]})]}),c.length>0&&(0,n.jsxs)("div",{className:"w-full max-w-md mb-4 text-left",children:[(0,n.jsxs)("div",{className:"flex items-center gap-1.5 mb-1.5 px-1 text-[10px] uppercase tracking-wide text-text-muted",children:[(0,n.jsx)(t3.BZ,{size:11}),(0,n.jsx)("span",{children:"Recent in this project"})]}),(0,n.jsx)("div",{className:"max-h-[38vh] overflow-y-auto custom-scrollbar rounded-brand border border-border-subtle bg-surface-2/30",children:c.map(e=>{let t=!!e.openSessionId;return(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),t?window.dispatchEvent(new CustomEvent(ev,{detail:{sessionId:e.openSessionId}})):i?.(e)},className:"w-full flex items-center gap-2 px-2.5 py-1.5 text-left border-b border-border-subtle/50 last:border-b-0 hover:bg-surface-2 transition-colors",title:t?o("agentHistory.openNow"):void 0,children:[(0,n.jsx)("span",{className:`flex-1 min-w-0 truncate text-[11px] ${t?"text-text font-medium":"text-text-muted"}`,children:e.title||"Untitled conversation"}),(0,n.jsx)("span",{className:"shrink-0 text-[10px] font-mono text-text-muted",children:function(e){if(!e)return"";let t=Math.round((Date.now()-e)/6e4);if(t<60)return`${Math.max(1,t)}m`;let s=Math.round(t/60);return s<24?`${s}h`:`${Math.round(s/24)}d`}(e.updatedAt)})]},`${e.agent}:${e.sessionId}`)})}),c.length>=8&&(0,n.jsx)("button",{type:"button",onClick:()=>{(0,t7.e)(),i?.()},className:"mt-1.5 px-1 text-[10px] font-mono text-text-muted hover:text-text transition-colors",children:"All conversations →"})]}),(0,n.jsx)("div",{className:"flex flex-wrap items-center justify-center gap-2 max-w-md shrink-0",children:nt.y2.map(e=>(0,n.jsx)("button",{type:"button",onClick:()=>l?.(e),className:"px-2.5 py-1 rounded-full bg-surface-2 hover:bg-surface-3 text-[11px] text-text font-mono border border-border-subtle transition-colors",children:e},e))})]})}),cR=(0,r.memo)(function({sessionId:e,engine:t="claude",workspacePath:s="",fileBus:a=null,onSendPrompt:l,onResolvePermission:i,hasOlder:o=!1,onLoadOlder:c,onRewind:d,onPreviewRewind:u,onCutLocal:m,onListRewindPoints:x,onOpenResume:p,hydrating:h=!1,synced:f=!0,hydrateFailed:b=!1,onReload:g}){let y=(0,r.useRef)(null),w=(0,r.useRef)(null),k=(0,r.useRef)(!0),j=(0,r.useRef)(null),N=(0,r.useRef)(null),S=(0,r.useRef)(null),C=(0,r.useRef)(null),T=(0,r.useRef)(0),[R,E]=(0,r.useState)(!1),[_,$]=(0,r.useState)(131072),[M,P]=(0,r.useState)(null),A=(0,r.useRef)({sessionId:null,n:0}),z=oq(t=>t.bySession[e]?.messages)||cy,I=nt.UB[t]||nt.UB.claude;(0,r.useEffect)(()=>{$(131072),P(null),C.current=null},[e]);let{id:L,index:D}=(0,r.useMemo)(()=>(function(e,t,s){if(!t?.length)return{id:null,index:0};let n=oX(t,s,void 0),r=null!=e?t.findIndex(t=>t.id===e):-1,a=oX(t,Math.max(524288,s),void 0),l=r<0?n:Math.max(r,a);return{id:t[l].id,index:l}})(M,z,_),[M,z,_]);(0,r.useEffect)(()=>{P(L)},[L]);let F=D>0?z.slice(D):z,[O,B]=(0,r.useState)(null),W=(0,r.useRef)(0),K=(0,r.useMemo)(()=>z.filter(e=>"user"===e.role).length,[z]);(0,r.useEffect)(()=>{if(O?.ok||O?.supported===!1||W.current>=6)return;W.current+=1;let e=!0;return x?.().then(t=>{e&&B(t)}).catch(()=>{}),()=>{e=!1}},[x,t,e,K,O?.ok,O?.supported]);let H=!!O?.ok,U=(0,r.useMemo)(()=>{let e=new Map,t=0;for(let s=z.length-1;s>=0;s--)"user"===z[s].role&&e.set(z[s].id,t++);return e},[z]),q=(0,r.useMemo)(()=>{let e=[];for(let t of F)"user"===t.role||0===e.length?e.push({key:t.id,messages:[t]}):e[e.length-1].messages.push(t);return e},[F]),V=(0,r.useCallback)(async({auto:e=!1}={})=>{let t=y.current,s=Date.now();if(!e&&s-T.current<300)return;T.current=s;let n=S.current,r=n?function({scrollTop:e=0,scrollHeight:t=0,clientHeight:s=0,nodeTop:n=0}={}){return{nodeTop:n,scrollTop:e,atBottom:t-e-s<8}}(cw(t,n)):null,a=r?{...r,atBottom:e&&k.current,node:n}:null,l={hiddenCount:D,hasOlder:o,scrollTop:t?.scrollTop??0,scrollHeight:t?.scrollHeight??0},i=null;0===D&&o&&(i=await c?.()),(0,v.Lq)("ai-page","loadMore",{...l,fetched:i}),C.current=a,P(null),$(e=>e+131072)},[D,o,c]);(0,r.useLayoutEffect)(()=>{let e=y.current,t=C.current;if(!e||!t)return;C.current=null;let s=function(e,{scrollHeight:t=0,clientHeight:s=0,nodeTop:n=0}={}){return e?e.atBottom?t:n<=e.nodeTop?null:Math.max(0,n-(e.nodeTop-e.scrollTop)):null}(t,cw(e,t.node)||{});null!=s&&(e.scrollTop=s);let n=e.scrollHeight-e.scrollTop-e.clientHeight;k.current=n<8,E(n>140)},[_,M]),(0,r.useEffect)(()=>{let t=A.current;t.sessionId!==e&&(t.sessionId=e,t.n=0),!(t.n>=40)&&!h&&f&&k.current&&o&&z?.length&&z[D]?.role!=="user"&&(t.n+=1,V({auto:!0}))},[e,z,D,o,h,f,V]);let X=(0,r.useCallback)(()=>{j.current||(j.current=requestAnimationFrame(()=>{j.current=null;let e=y.current;if(!e)return;let t=e.scrollHeight-e.scrollTop-e.clientHeight,s=t<80;k.current=s,E(!s&&t>140),e.scrollTop<120&&(D>0||o)&&V()}))},[V,D,o]);(0,r.useEffect)(()=>{let e=y.current,t=w.current;if(!e||!t)return;let s=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&!k.current&&V()},{root:e,rootMargin:"120px"});return s.observe(t),()=>s.disconnect()},[V]);let G=(0,r.useMemo)(()=>z.map(e=>`${e.id}:${+!!e.thinking}:${+!!e.content}:${e.tools?.length||0}:${e.diffs?.length||0}:${+!!e.permission}`).join("|"),[z]),J=(0,r.useCallback)(e=>{S.current=e},[]);(0,r.useEffect)(()=>{let e=y.current;e&&k.current&&(e.scrollTop=e.scrollHeight)},[G]);let Y=(0,r.useMemo)(()=>z.reduce((e,t)=>e+(t.content?.length||0),0),[z]);(0,r.useEffect)(()=>{!k.current||N.current||(N.current=setTimeout(()=>{N.current=null;let e=y.current;e&&k.current&&(e.scrollTop=e.scrollHeight)},150))},[Y]),(0,r.useEffect)(()=>()=>{N.current&&clearTimeout(N.current)},[]),(0,r.useEffect)(()=>{let e=y.current;if(!e)return;let t=new ResizeObserver(()=>{k.current&&(e.scrollTop=e.scrollHeight)});return t.observe(e),()=>t.disconnect()},[]);let Z=(0,r.useCallback)(()=>{(0,t7.e)();let e=y.current;e&&(e.scrollTo({top:e.scrollHeight,behavior:"smooth"}),k.current=!0,E(!1))},[]),Q=(0,r.useCallback)(e=>e.messages.some(e=>e.isLive),[]);return(0,n.jsxs)("div",{className:"flex-1 min-h-0 relative flex flex-col overflow-hidden",children:[(0,n.jsxs)("div",{ref:y,onScroll:X,className:"ai-conversation flex-1 min-h-0 overflow-y-auto px-4 sm:px-6 py-4 space-y-4 custom-scrollbar relative",children:[(D>0||o)&&(0,n.jsx)("div",{ref:w,"aria-hidden":"true",className:"h-px"}),0===z.length?f?(0,n.jsx)(cT,{engine:t,engineMeta:I,workspacePath:s,fileBus:a,onSendPrompt:l,onOpenResume:p}):(0,n.jsx)(cS,{engine:t,failed:b,onRetry:g}):(0,n.jsxs)(n.Fragment,{children:[(D>0||o)&&(0,n.jsx)("button",{type:"button",onClick:()=>{(0,t7.e)(),V()},className:"w-full py-1.5 text-[11px] font-mono text-text-muted hover:text-text bg-surface-2/50 hover:bg-surface-2 border border-border-subtle/60 rounded-brand transition-colors",children:D>0?`Load older \xb7 ${D} more`:"Load older turns"}),q.map((e,r)=>{let[a,...l]=e.messages;return"user"!==a.role?(0,n.jsx)("div",{ref:0===r?J:void 0,children:(0,n.jsx)(cv,{messages:e.messages,engine:t,workspacePath:s,onResolvePermission:i,isLive:Q(e)})},e.key):(0,n.jsxs)("div",{ref:0===r?J:void 0,children:[(0,n.jsx)(o1,{message:a,engine:t,workspacePath:s,onResolvePermission:i,onRewind:d,onPreviewRewind:u,onCutLocal:m,rewindIndex:U.get(a.id),canRewind:H}),(0,n.jsx)(cv,{messages:l,engine:t,workspacePath:s,onResolvePermission:i,isLive:Q(e)})]},e.key)}),(0,n.jsx)(cC,{sessionId:e,engine:t,hydrating:h})]})]}),R&&(0,n.jsx)("button",{type:"button",onClick:Z,className:"absolute bottom-4 right-6 p-2 rounded-full bg-surface-2 border border-border-subtle shadow-lg hover:bg-surface-3 text-text transition-all duration-150 z-30",title:"Scroll to bottom",children:(0,n.jsx)(t3.yd,{size:16})})]})});function cE(e){return e.provider?e.provider:e.id&&e.id.includes("/")?e.id.split("/")[0]:""}function c_(e,t,s,n){let r=n?t:e,a=[],l=r.filter(e=>e.recent||e.id===s).sort((e,t)=>(e.recentRank??999)-(t.recentRank??999));l.length>0&&a.push({key:"recent",title:"Recent",items:l});let i=new Set(l.map(e=>e.id)),o=r.filter(e=>!i.has(e.id)),c=new Map;for(let e of o){let t=cE(e)||"other";c.has(t)||c.set(t,[]),c.get(t).push(e)}for(let e of[...c.keys()].sort((e,t)=>"opencode-go"===e?-1:"opencode-go"===t?1:"opencode"===e?-1:"opencode"===t?1:e.localeCompare(t))){let t=c.get(e)||[];0!==t.length&&(t.sort((e,t)=>(e.label||e.id).localeCompare(t.label||t.id)),a.push({key:e,title:e?"opencode-go"===e?"OpenCode Go":"opencode"===e?"OpenCode Zen":"9router"===e?"9Router":"google-antigravity"===e?"Google Antigravity":"ollama-cloud"===e?"Ollama Cloud":"anthropic"===e?"Anthropic":"openai"===e?"OpenAI":"google"===e?"Google":e.split(/[-_]/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" "):"Other Models",items:t}))}return a}let c$=[],cM=(0,r.memo)(function({sessionId:e="",engine:t="claude",isTurnRunning:s=!1,isFocused:a=!1,onSend:l,onRemoveQueueItem:i,onClearQueue:o,onStop:c,onRunShell:d,onResolvePermission:u,onSelectModel:m,onModeChange:x,onOpenModal:p,onOptionChange:h,onActivate:f,fileBus:b=null,workspacePath:g="",model:v="",modalOpen:y=!1}){let{t:w,locale:k}=(0,se.s)(),j="mouse"===nk(),N=s1()?"Opt ←/→ \xb7 Opt 1…9 to switch tab":"Ctrl+Shift+←/→ \xb7 1…9 to switch tab",S=(0,om.Tw)(t),C=S.permissionModes,T=S.slashCommands,R=oq(t=>t.bySession[e]?.isTurnRunning),E=oq(t=>t.bySession[e]?.metadata?.model),_=oq(t=>t.bySession[e]?.metadata?.modelOptions),$=_?.length?_:S.models,M=oq(t=>t.bySession[e]?.metadata?.skills)||c$,P=oq(t=>t.bySession[e]?.metadata?.commands)||c$,A=oq(t=>t.bySession[e]?.permissionMode),z=oq(t=>t.bySession[e]?.metadata?.effort||t.bySession[e]?.metadata?.variant),I=A||S.defaultMode,L=void 0!==R?R:s,D=void 0!==E?E:v,[F,O]=(0,r.useState)(""),B=oq(t=>t.bySession[e]?.queue)||c$,[W,K]=(0,r.useState)(-1),H=(0,r.useRef)(""),[U,q]=(0,r.useState)(!1),[V,X]=(0,r.useState)(null),[G,J]=(0,r.useState)(""),[Y,Z]=(0,r.useState)([]),[ee,et]=(0,r.useState)(0),[es,en]=(0,r.useState)(null),[er,ea]=(0,r.useState)(-1),el=nl(e=>e.addCommand),ei=nl(e=>e.resolveAlias),eo=nl(e=>e.history),ec=nl(e=>e.pinned),ed=(0,r.useMemo)(()=>U?[]:nm(F,eo,ec,[],!j),[F,eo,ec,j,U]),[eu,em]=(0,r.useState)(!1),[ex,ep]=(0,r.useState)(""),[eh,ef]=(0,r.useState)(()=>new Set),[eb,eg]=(0,r.useState)(!1),[ev,ey]=(0,r.useState)(!1),ew=(0,r.useRef)(null),{attachments:ek,setAttachments:ej,removeAttachment:eN,handleFileUpload:eS,handleAttachPaste:eC}=n_({bus:Q(e=>e.bus),sessionId:e}),[eT]=nb(k),eR=ny({lang:nh(eT),onText:e=>{O(e),eP.current&&(eP.current.value=e,eP.current.style.height="auto",eP.current.style.height=`${Math.min(eP.current.scrollHeight,120)}px`,eP.current.focus())}}),eE=(0,r.useCallback)(()=>{(0,t7.e)(),eR.stop()},[eR]),e_=(0,r.useCallback)(()=>{eR.cancel()},[eR]),e$=(0,r.useCallback)(()=>{eR.listening?eR.stop():(document.activeElement?.blur(),eR.start(F))},[eR,F]),eM=(0,r.useCallback)(()=>{(0,t7.e)(),O(""),eP.current&&(eP.current.value="",eP.current.style.height="26px");try{localStorage.removeItem(`9remote_draft_${e}`)}catch{}eP.current?.focus()},[e]),eP=(0,r.useRef)(null),eA=(0,r.useRef)(ek);(0,r.useEffect)(()=>{eA.current=ek},[ek]);let ez=(0,r.useRef)(null),eI=(0,r.useRef)(!1),eL=(0,r.useRef)(0),eD=(0,r.useRef)(0),eF=(0,r.useRef)(0);nt.UB[t]||nt.UB.claude,(0,r.useEffect)(()=>{a&&!y&&j&&eP.current?.focus({preventScroll:!0})},[a,y,j]),(0,r.useEffect)(()=>{let e=e=>{ew.current&&!ew.current.contains(e.target)&&(em(!1),eg(!1))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,r.useEffect)(()=>{L&&(em(!1),eg(!1))},[L]),(0,r.useEffect)(()=>{let e=eP.current;if(!e)return;e.style.height="auto";let t=Math.min(e.scrollHeight,140);e.style.height=`${Math.max(t,26)}px`},[F]),(0,r.useEffect)(()=>{if(!U||!ez.current)return;let e=ez.current.querySelectorAll("[data-menu-item]")[ee];e&&e.scrollIntoView({block:"nearest"})},[ee,U]),(0,r.useEffect)(()=>{if(e){ej([]);try{O(localStorage.getItem(`9remote_draft_${e}`)||"")}catch{}}},[e,ej]),(0,r.useEffect)(()=>{if(!e)return;let t=setTimeout(()=>{try{F?localStorage.setItem(`9remote_draft_${e}`,F):localStorage.removeItem(`9remote_draft_${e}`)}catch{}},300);return()=>clearTimeout(t)},[F,e]),(0,r.useEffect)(()=>{if(es){let e=es.name.replace(/[/@]/g,"\\$&");if(RegExp(`(?:^|\\s)${e}\\s*$`).test(F))return;en(null)}let e=/(?:^|\s)([/@][\w\d_.-]*)$/.exec(F);if(!e){q(!1),X(null),J("");return}let t=e[1],s=t[0],n=t.slice(1).toLowerCase();if(X(s),J(n),et(0),"/"===s){let e=function({staticCommands:e=[],liveCommands:t=[],skills:s=[],filter:n=""}={}){let r=(t||[]).map(e=>({name:`/${e.name}`,description:e.description||"",isCommand:!0})),a=(s||[]).map(e=>({name:`/${e.name||e.id}`,description:e.description||`Skill: ${e.name||e.id}`,isSkill:!0})),l=new Set,i=String(n||"").toLowerCase();return[...e||[],...r,...a].filter(e=>!l.has(e.name)&&!!e.name.toLowerCase().includes(i)&&(l.add(e.name),!0))}({staticCommands:T,liveCommands:P,skills:M,filter:n});Z(e),q(e.length>0)}else if("@"===s){let e=Q.getState().bus;e?.emit?e.emit("ai:files",{workspace:g,query:n},e=>{e?.ok&&Array.isArray(e.files)&&(Z(e.files.map(e=>({name:e.path||e,description:e.isModified?`${e.dir?e.dir+" \xb7 ":""}modified`:e.dir||""}))),q(e.files.length>0))}):b?.searchFiles&&g?b.searchFiles(g,n).then(e=>{e?.success&&Array.isArray(e.files)&&(Z(e.files.slice(0,10).map(e=>({name:e.path||e,description:e.relPath||e}))),q(e.files.length>0))}):(Z([]),q(!1))}},[F,b,g,M,P,T,es]);let eO=(0,r.useCallback)(t=>{let s=ei((("string"==typeof t?t:eP.current?eP.current.value:F)||F).trim()),n=eA.current;if(!s&&0===n.length)return;let r=Date.now();if(r-eD.current<250)return;eD.current=r,eF.current=r,(0,t7.e)(),s&&!s.startsWith("!")&&el(s),K(-1),O(""),eP.current&&(eP.current.value="",eP.current.style.height="26px");try{localStorage.removeItem(`9remote_draft_${e}`)}catch{}if(s.startsWith("!")){n.length||d?.(s.slice(1).trim());return}let a=oq.getState().bySession[e]?.activePermission;a&&u?.(a.requestId,nt.x6,nt.mX),n.length&&ej([]),l?.(s,{attachments:n.map(({name:e,type:t,content:s})=>({filename:e,type:t,content:s}))})},[F,e,l,d,u,ej,el,ei]),eB=(0,r.useCallback)(()=>{(0,t7.e)(),c?.()},[c]),eW=(0,r.useCallback)(e=>{let t=e.action||"send",[s,n]=t.split(":");if("modal"===s){eP.current?.blur(),p?.(n);return}if("clear"===s){l?.("/clear",{force:!0}),O("");return}if("setMode"===s){x?.(e.mode),O("");return}if("send"===s||"send"===t){l?.(e.name),O("");return}eP.current?.focus()},[p,l,x]),eK=(0,r.useCallback)(e=>{(0,t7.e)();let t=/(?:^|\s)([/@][\w\d_.-]*)$/.exec(F);if(!t)return;let s=t[1],n=F.slice(0,F.length-s.length),r="/"===V&&e.action?.startsWith("modal:"),a="@"===V?`@${e.name} `:`${e.name} `;(O(r?n:`${n}${a}`),q(!1),"/"!==V)?eP.current?.focus():"submenu"===e.action&&Array.isArray(e.subOptions)&&e.subOptions.length>0?L&&("effort"===e.optionKey||"variant"===e.optionKey)?O(""):(en(e),et(0),q(!0)):eW(e)},[F,V,eW,L]),eH=(0,r.useCallback)(e=>{(0,t7.e)(),es&&(h?.(es.optionKey,e.value),en(null),q(!1),O(""),eP.current?.focus())},[es,h]),eU=(0,r.useCallback)(e=>{(0,t7.e)();let t=/(?:^|\s)(\S*)$/.exec(F),s=t?t[1]:"";O(F.slice(0,F.length-s.length)+e),ea(-1),eP.current?.focus()},[F]),eq=e=>String(e||"").toLowerCase().replace(/\[[^\]]*\]$/,""),eV=(0,r.useMemo)(()=>{if(!D)return null;let e=$||[],t=eq(D);return e.find(e=>e.id===D)||e.find(e=>eq(e.id)===t)||e.find(e=>eq(e.id).split("/").pop()===t.split("/").pop())||null},[D,$]),eX=eV?.short||eV?.label||D||"Model",eG=z||S.defaultEffort||"",eJ=(0,r.useMemo)(()=>{let e=[...$||[]];return D&&!e.some(e=>e.id===D)&&e.unshift({id:D,label:D,short:D}),e},[$,D]),eY=(0,r.useMemo)(()=>{if(eJ.length<=20)return eJ;let e=ex.trim().toLowerCase();return e?eJ.filter(t=>{let s=(t.id||"").toLowerCase();return(t.label||"").toLowerCase().includes(e)||s.includes(e)||(t.provider||"").toLowerCase().includes(e)}):eJ},[eJ,ex]),eZ=(0,r.useMemo)(()=>eJ.length<=20?[{key:"all",title:"",items:eJ}]:c_(eJ,eY,D,ex.trim()),[eJ,eY,D,ex]),eQ=(0,r.useMemo)(()=>(T||[]).find(e=>"submenu"===e.action&&("effort"===e.optionKey||"variant"===e.optionKey)),[T]),e0=(0,r.useMemo)(()=>{let e=(eV?.efforts||[]).map(e=>({value:e,label:e}));return e.length>0?e:eQ?.subOptions||[]},[eQ,eV]);return(0,n.jsxs)("div",{className:"relative px-3 py-1.5 bg-transparent border-t border-border-subtle/40 select-none",children:[U&&es&&(0,n.jsxs)("div",{ref:ez,className:"absolute left-3 right-3 bottom-[calc(100%+6px)] max-h-52 bg-surface border border-border-subtle rounded-brand shadow-lg overflow-y-auto z-50 p-1 custom-scrollbar",children:[(0,n.jsxs)("div",{className:"px-2 py-0.5 text-[10px] text-text-muted font-mono uppercase tracking-wider border-b border-border-subtle mb-1 flex items-center justify-between",children:[(0,n.jsxs)("span",{children:[es.name," — ",es.optionKey]}),(0,n.jsx)("button",{type:"button",onClick:()=>{en(null),q(!1),O("")},className:"text-text-muted hover:text-text",children:(0,n.jsx)(t3.X,{size:11})})]}),(es.subOptions||[]).map((e,t)=>(0,n.jsxs)("div",{"data-menu-item":"true",onClick:()=>eH(e),onMouseEnter:()=>et(t),className:`px-2 py-1 rounded-brand flex items-center justify-between text-xs cursor-pointer ${t===ee?"bg-surface-2 text-text font-medium":"text-text-muted hover:text-text"}`,children:[(0,n.jsx)("span",{className:"font-mono text-xs text-text",children:e.label}),e.desc&&(0,n.jsx)("span",{className:"text-[10px] text-text-muted truncate ml-2 max-w-[55%]",children:e.desc})]},e.value))]}),U&&!es&&Y.length>0&&(0,n.jsxs)("div",{ref:ez,className:"absolute left-3 right-3 bottom-[calc(100%+6px)] max-h-52 bg-surface border border-border-subtle rounded-brand shadow-lg overflow-y-auto z-50 p-1 custom-scrollbar",children:[(0,n.jsx)("div",{className:"px-2 py-0.5 text-[10px] text-text-muted font-mono uppercase tracking-wider border-b border-border-subtle mb-1",children:"/"===V?"Slash Commands & Skills":"Files in repo (@)"}),Y.map((e,t)=>{let s=L&&("/model"===e.name||"submenu"===e.action&&("effort"===e.optionKey||"variant"===e.optionKey));return(0,n.jsxs)("div",{"data-menu-item":"true",onClick:s?void 0:()=>eK(e),onMouseEnter:()=>et(t),className:`px-2 py-1 rounded-brand flex items-center justify-between text-xs ${s?"opacity-40 cursor-not-allowed":t===ee?"bg-surface-2 text-text font-medium cursor-pointer":"text-text-muted hover:text-text cursor-pointer"}`,title:s?"Cannot change while turn is running":void 0,children:[(0,n.jsxs)("div",{className:"flex items-center gap-2 truncate",children:[e.isSkill?(0,n.jsx)(t3.Kq,{size:12,className:"text-warning shrink-0"}):"/"===V?(0,n.jsx)(t3.BK,{size:12,className:"text-accent shrink-0"}):(0,n.jsx)(t3.GD,{size:12,className:"text-accent shrink-0"}),(0,n.jsx)("span",{className:"font-mono text-xs text-text",children:e.name}),e.isSkill&&(0,n.jsx)("span",{className:"text-[9px] px-1 rounded bg-warning/15 text-warning font-mono",children:"skill"}),"submenu"===e.action&&(0,n.jsx)(t3.rX,{size:11,className:"text-text-muted shrink-0 rotate-90"})]}),e.description&&(0,n.jsx)("span",{className:"text-[10px] text-text-muted truncate ml-2 max-w-[50%]",children:e.description})]},e.name)})]}),B.length>0&&(0,n.jsx)("div",{className:"mb-1 space-y-0.5",children:B.map((e,t)=>(0,n.jsxs)("div",{className:"px-2 py-0.5 rounded bg-brand-500/10 border border-brand-500/30 flex items-center justify-between text-xs animate-in fade-in duration-100",children:[(0,n.jsxs)("div",{className:"flex items-center gap-1.5 truncate min-w-0",children:[(0,n.jsx)("span",{className:"font-mono text-[9px] uppercase tracking-wider font-semibold px-1 rounded bg-brand-500/20 text-brand-400 shrink-0",children:0===t?"Next":`Queued ${t+1}`}),(0,n.jsx)("span",{className:"truncate text-text font-mono text-[11px]",children:e.text}),e.attachments?.length>0&&(0,n.jsxs)("span",{className:"shrink-0 text-text-muted flex items-center gap-0.5 font-mono text-[10px]",children:[(0,n.jsx)(t3.xv,{size:10}),e.attachments.length]})]}),(0,n.jsxs)("div",{className:"flex items-center gap-1 shrink-0 ml-2",children:[0===t&&(0,n.jsx)("button",{type:"button",onClick:()=>{(0,t7.e)(),eB()},className:"text-text-muted hover:text-brand-400 p-1 rounded hover:bg-surface-2 transition-colors cursor-pointer",title:"Send now (stops the current turn)",children:(0,n.jsx)(t3.Vn,{size:13})}),(0,n.jsx)("button",{type:"button",onClick:()=>{(0,t7.e)(),i?.(e.id)},className:"text-text-muted hover:text-text p-1 rounded hover:bg-surface-2 transition-colors cursor-pointer",title:"Remove from queue",children:(0,n.jsx)(t3.X,{size:14})})]})]},e.id))}),(0,n.jsx)(nO,{voice:eR,onDone:eE,onCancel:e_,className:"mb-1.5"}),(0,n.jsxs)("div",{className:"relative rounded-brand border border-border-subtle/80 bg-transparent focus-within:border-brand-500 transition-colors px-2.5 py-1 flex flex-col gap-1",children:[ek.length>0&&(0,n.jsx)("div",{className:"flex gap-1.5 overflow-x-auto scroll-thin-x pt-0.5",children:ek.map(e=>(0,n.jsxs)("div",{className:"relative flex-shrink-0 group",children:[e.isImage?(0,n.jsx)("img",{src:`data:${e.type};base64,${e.content}`,alt:e.name,className:"w-10 h-10 object-cover rounded border border-border-subtle"}):(0,n.jsxs)("div",{className:"w-10 h-10 flex flex-col items-center justify-center rounded border border-border-subtle bg-surface-2 px-1",children:[(0,n.jsx)(t3.xv,{size:12,className:"text-text-muted"}),(0,n.jsx)("span",{className:"text-[8px] text-text-muted truncate w-full text-center",children:e.name})]}),(0,n.jsx)("button",{type:"button",onMouseDown:e=>e.preventDefault(),onClick:()=>eN(e.id),className:"absolute -top-1.5 -right-1.5 w-4 h-4 flex items-center justify-center bg-surface-3 rounded-full text-text-muted hover:text-text border border-border-subtle","aria-label":"Remove attachment",children:(0,n.jsx)(t3.X,{size:10})})]},e.id))}),(0,n.jsx)(nx,{value:F,store:nl,isMobile:!j,activeIndex:er,onSelect:eU}),(0,n.jsxs)("div",{className:"flex items-start gap-1",children:[(0,n.jsx)("textarea",{ref:eP,value:F,onPaste:eC,onChange:e=>{if(Date.now()-eF.current<200){eP.current&&(eP.current.value="");return}O(e.target.value),ea(-1)},onFocus:()=>f?.(),onKeyDown:t=>{if(y||t.nativeEvent?.isComposing||229===t.keyCode)return;if(t.shiftKey&&"Tab"===t.key){t.preventDefault(),t.stopPropagation(),(0,t7.e)();let e=C||[];if(e.length>0){let t=e.findIndex(e=>e.id===I),s=-1===t?0:(t+1)%e.length,n=e[s]?.id;n&&x?.(n)}return}if("Escape"===t.key){if(es){t.preventDefault(),en(null),q(!1),O("");return}if(U){t.preventDefault(),q(!1);return}if(L){t.preventDefault(),console.log("[TEMP DIAGNOSTIC] Esc → stop",{sessionId:e}),eB();return}if(B.length>0){t.preventDefault(),o?.();return}}if(es){let e=es.subOptions||[];if("ArrowDown"===t.key){t.preventDefault(),et(t=>(t+1)%e.length);return}if("ArrowUp"===t.key){t.preventDefault(),et(t=>(t-1+e.length)%e.length);return}if("Enter"===t.key||"Tab"===t.key){t.preventDefault(),eH(e[ee]);return}}if(U&&Y.length>0){if("ArrowDown"===t.key){t.preventDefault(),et(e=>(e+1)%Y.length);return}if("ArrowUp"===t.key){t.preventDefault(),et(e=>(e-1+Y.length)%Y.length);return}if("Enter"===t.key||"Tab"===t.key){t.preventDefault(),eK(Y[ee]);return}}if(ed.length>0){let e=er<0?-1:(er%ed.length+ed.length)%ed.length;if("Tab"===t.key&&!t.shiftKey){t.preventDefault(),ea(-1===e?0:(e+1)%ed.length);return}if(("Enter"===t.key||"Tab"===t.key)&&-1!==e){t.preventDefault(),eU(ed[e].cmd);return}}let s=eP.current,n=s?.selectionStart??0,r=s?.value??"",a=-1===r.lastIndexOf("\n",n-1),l=-1===r.indexOf("\n",n);if("ArrowUp"===t.key&&!es&&!U&&a&&eo.length>0){t.preventDefault(),-1===W&&(H.current=F);let e=Math.min(W+1,eo.length-1);if(e===W)return;K(e),O(eo[e]);return}if("ArrowDown"===t.key&&!es&&!U&&l&&-1!==W){t.preventDefault();let e=W-1;e<0?(K(-1),O(H.current)):(K(e),O(eo[e]));return}if("Enter"===t.key&&(t.metaKey||t.ctrlKey)){t.preventDefault(),eO();return}"Enter"===t.key&&!t.shiftKey&&j&&(t.preventDefault(),eO())},onCompositionStart:()=>{eI.current=!0},onCompositionEnd:()=>{eI.current=!1,eL.current=Date.now(),Date.now()-eF.current<200&&(eP.current&&(eP.current.value=""),O(""))},placeholder:L?j?"Type command \xb7 Enter to queue \xb7 Esc to stop":"Type command \xb7 Send to queue":j?`Type command \xb7 ${N}`:"Type command",rows:1,className:"ai-conversation ai-composer-input flex-1 min-w-0 bg-transparent resize-none text-xs text-text placeholder-text-muted focus:outline-none custom-scrollbar leading-snug min-h-[24px]"}),F.trim().length>0?(0,n.jsx)("button",{type:"button",onClick:eM,className:"shrink-0 mt-0.5 p-1.5 rounded text-text-muted hover:text-text hover:bg-surface-2 transition-colors flex items-center justify-center",title:"Clear input",children:(0,n.jsx)(t3.X,{size:16})}):(0,n.jsx)("button",{type:"button",onClick:()=>{(0,t7.e)(),ey(!0)},className:"shrink-0 mt-0.5 p-1.5 rounded text-text-muted hover:text-text hover:bg-surface-2 transition-colors flex items-center justify-center",title:w("history.title"),children:(0,n.jsx)(t3.BZ,{size:16})})]}),(0,n.jsxs)("div",{className:"relative flex items-center justify-between text-xs pt-0.5 border-t border-border-subtle/30",children:[(0,n.jsx)("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:(0,n.jsxs)("div",{ref:ew,className:"relative min-w-0 flex items-center gap-1",children:[(0,n.jsxs)("button",{type:"button",disabled:L,onClick:()=>{em(!eu),eu||ep(""),eg(!1)},className:"min-w-0 px-1.5 py-0.5 rounded text-[11px] font-medium flex items-center gap-1 font-mono text-text-muted hover:text-text hover:bg-surface-2 transition-colors cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:bg-transparent",title:L?"Cannot change model while turn is running":"Select model (/model)",children:[(0,n.jsx)("img",{src:s$(`${t}-ui`),alt:"",className:`w-3.5 h-3.5 object-contain shrink-0 ${s_}`}),(0,n.jsx)("span",{dir:"rtl",className:"truncate min-w-0",children:(0,n.jsx)("bdi",{children:eX})}),(0,n.jsx)(t3.rX,{size:11,className:`text-text-muted shrink-0 transition-transform ${eu?"":"rotate-180"}`})]}),eu&&(0,n.jsxs)("div",{className:"absolute left-0 bottom-[calc(100%+6px)] min-w-[260px] max-h-56 bg-surface border border-border-subtle rounded-brand shadow-xl overflow-y-auto z-50 p-1 custom-scrollbar",children:[(0,n.jsx)("div",{className:"px-2 py-0.5 text-[10px] text-text-muted font-mono uppercase tracking-wider border-b border-border-subtle mb-1",children:"Select Model"}),eJ.length>20&&(0,n.jsxs)("div",{className:"px-1.5 pb-1.5 mb-1 border-b border-border-subtle flex items-center gap-1.5 text-text-muted",children:[(0,n.jsx)(t3.vj,{size:12,className:"shrink-0"}),(0,n.jsx)("input",{type:"text",value:ex,onChange:e=>ep(e.target.value),placeholder:"Search models...",autoFocus:!0,className:"w-full bg-transparent text-[11px] text-text placeholder-text-muted/70 focus:outline-none py-0.5"})]}),0===eY.length&&(0,n.jsxs)("div",{className:"px-2 py-2 text-[11px] text-text-muted",children:['No models match "',ex,'"']}),eZ.map(e=>(0,n.jsxs)("div",{children:[eZ.length>1&&(0,n.jsxs)("button",{type:"button",onClick:()=>{var t;return t=e.key,void ef(e=>{let s=new Set(e);return s.has(t)?s.delete(t):s.add(t),s})},"aria-expanded":!eh.has(e.key),className:"w-full px-2 py-0.5 text-[10px] font-mono uppercase tracking-wider font-semibold text-text flex items-center justify-between select-none border-b border-border-subtle mb-1 mt-1 first:mt-0",children:[(0,n.jsxs)("span",{className:"flex items-center gap-1",children:[(0,n.jsx)("span",{className:"text-[8px]",children:eh.has(e.key)?"▶":"▼"}),e.title]}),(0,n.jsx)("span",{className:"text-[9px] text-text-subtle",children:e.items.length})]}),!eh.has(e.key)&&e.items.map(e=>{let t=D===e.id;return(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),m?.(e.id),em(!1)},title:e.id,className:`w-full pl-4 pr-2 py-1.5 rounded text-left text-xs flex flex-col gap-0.5 transition-colors ${t?"bg-surface-2 text-text font-semibold":"text-text-muted hover:text-text hover:bg-surface-2"}`,children:[(0,n.jsxs)("span",{className:"w-full flex items-center justify-between",children:[(0,n.jsx)("span",{className:"truncate",children:e.label}),t&&(0,n.jsx)(t3.aJ,{size:12,className:"text-text shrink-0 ml-1"})]}),e.label!==e.id&&(0,n.jsx)("span",{className:"truncate font-mono text-[10px] text-text-subtle",children:e.id})]},e.id)})]},e.key))]}),e0.length>0&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",disabled:L,onClick:()=>{eg(e=>!e),em(!1)},className:"shrink-0 px-1 py-0.5 rounded text-[10px] uppercase tracking-wide font-mono text-text-muted hover:text-text hover:bg-surface-2 transition-colors cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:bg-transparent",title:L?`Cannot change ${eQ?.optionKey||"effort"} while turn is running`:`Select ${eQ?.optionKey||"effort"}`,children:eG||"—"}),eb&&(0,n.jsxs)("div",{className:"absolute left-0 bottom-[calc(100%+6px)] min-w-[220px] max-h-56 bg-surface border border-border-subtle rounded-brand shadow-xl overflow-y-auto z-50 p-1 custom-scrollbar",children:[(0,n.jsx)("div",{className:"px-2 py-0.5 text-[10px] text-text-muted font-mono uppercase tracking-wider border-b border-border-subtle mb-1",children:eQ?.optionKey==="variant"?"Variant":"Reasoning effort"}),e0.map(e=>{let t=eG===e.value;return(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),h?.(eQ?.optionKey||"effort",e.value),eg(!1)},className:`w-full px-2 py-1.5 rounded text-left text-xs flex items-center justify-between gap-2 transition-colors ${t?"bg-brand-500/15 text-brand-400 font-semibold":"text-text-muted hover:text-text hover:bg-surface-2"}`,children:[(0,n.jsx)("span",{className:"font-mono truncate",children:e.label}),t&&(0,n.jsx)(t3.aJ,{size:12,className:"text-brand-400 shrink-0"}),!t&&e.desc&&(0,n.jsx)("span",{className:"text-[10px] text-text-subtle truncate max-w-[55%]",children:e.desc})]},e.value)})]})]})]})}),(0,n.jsxs)("div",{className:"flex items-center gap-1.5 shrink-0 pl-1.5",children:[(0,n.jsxs)("label",{className:"p-1.5 rounded text-text-muted hover:text-text hover:bg-surface-2 transition-colors cursor-pointer flex items-center justify-center",title:"Attach file or image",children:[(0,n.jsx)(t3.xv,{size:15}),(0,n.jsx)("input",{type:"file",multiple:!0,onChange:eS,className:"hidden",accept:"*/*"})]}),eR.active&&(0,n.jsx)("button",{type:"button",onMouseDown:e=>e.preventDefault(),onClick:e$,title:w("not-allowed"===eR.error||"service-not-allowed"===eR.error?"voice.denied":"voice.dictate"),"aria-label":w("voice.dictate"),className:`p-1.5 rounded flex items-center justify-center transition-colors ${eR.listening?"bg-red-500/90 text-white animate-pulse":eR.error?"text-red-400":"text-text-muted hover:text-text hover:bg-surface-2"}`,children:eR.listening?(0,n.jsx)(t3.jj,{size:15}):(0,n.jsx)(t3.GO,{size:15})}),L?(0,n.jsxs)(n.Fragment,{children:[(F.trim()||ek.length>0)&&(0,n.jsxs)("button",{type:"button",onClick:eO,className:"px-2 py-0.5 rounded bg-brand-500 hover:bg-brand-600 text-white flex items-center gap-1 text-[11px] font-medium transition-colors shadow-sm cursor-pointer",title:j?"Queue message (Enter)":"Queue message",children:[(0,n.jsx)(t3.Vn,{size:13}),(0,n.jsx)("span",{children:"Queue"})]}),(0,n.jsx)("button",{type:"button",onClick:eB,className:"px-2 py-0.5 rounded bg-danger/20 hover:bg-danger/30 text-danger flex items-center gap-1 text-[11px] font-medium transition-colors cursor-pointer",title:B.length?"Stop & run the next queued message (Esc)":"Stop generation (Esc)",children:(0,n.jsx)(t3.M6,{size:13,className:"fill-current"})})]}):(0,n.jsx)("button",{type:"button",onClick:eO,disabled:!F.trim()&&0===ek.length,className:`px-2 py-1 rounded transition-colors flex items-center justify-center ${F.trim()||ek.length>0?"bg-brand-500 hover:bg-brand-600 text-white shadow-sm cursor-pointer":"text-text-muted bg-surface-2 cursor-not-allowed opacity-40"}`,title:"Send (Enter)",children:(0,n.jsx)(t3.Vn,{size:14})})]})]})]}),(0,n.jsx)(no,{isOpen:ev,store:nl,onSelect:eU,onClose:()=>ey(!1)})]})}),cP={Shield:"text-text-muted",Pencil:"text-accent",Eye:"text-accent",Sparkles:"text-warning"},cA=(0,r.memo)(function({sessionId:e="",sessionName:t="",engine:s="claude",workspacePath:a="",isTurnRunning:l=!1,isDesktop:i=!0,onModeChange:o,onNewChat:c}){let d=oq(t=>t.bySession[e]?.isTurnRunning),u=oq(t=>t.bySession[e]?.metadata),m=u?.goal,x=(0,om.Tw)(s).permissionModes||[],p=oq(t=>t.bySession[e]?.permissionMode)||(0,om.Tw)(s).defaultMode,{branch:h,dirty:f}=aU(a,void 0,{enabled:!!a}),[b,g]=(0,r.useState)(!1),v=(0,r.useRef)(null);(0,r.useEffect)(()=>{let e=e=>{v.current&&!v.current.contains(e.target)&&g(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let y=x.find(e=>e.id===p)||x[0];return(0,n.jsxs)("div",{className:`relative min-h-6 px-3 bg-surface/50 border-t border-border-subtle/50 flex items-center text-[11px] font-mono text-text-muted select-none flex-shrink-0 z-20 gap-3${i?"":" safe-area-bottom"}`,children:[(void 0!==d?d:l)&&(0,n.jsx)(os,{className:"hidden sm:block"}),(0,n.jsxs)("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[y&&x.length>0&&(0,n.jsxs)("div",{ref:v,className:"relative",children:[(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),g(e=>!e)},className:"hover:text-text flex items-center gap-1 transition-colors",title:"Change permission mode (Shift+Tab)",children:[(0,n.jsx)(t3.Ay,{name:y.icon||"Shield",size:11,className:`${cP[y.icon]||"text-text-muted"} shrink-0`}),(0,n.jsx)("span",{children:y.label}),(0,n.jsx)(t3.rX,{size:11,className:`text-text-muted transition-transform ${b?"":"rotate-180"}`})]}),b&&(0,n.jsxs)("div",{className:"absolute left-0 bottom-[calc(100%+6px)] min-w-[220px] max-h-56 bg-surface border border-border-subtle rounded-brand shadow-xl overflow-y-auto z-50 p-1 custom-scrollbar",children:[(0,n.jsx)("div",{className:"px-2 py-0.5 text-[10px] text-text-muted font-mono uppercase tracking-wider border-b border-border-subtle mb-1",children:"Permission Mode"}),x.map(e=>(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),o?.(e.id),g(!1)},className:`w-full px-2 py-1.5 rounded text-left text-xs flex flex-col gap-0.5 transition-colors cursor-pointer ${p===e.id?"bg-brand-500/15 text-brand-400 font-semibold":"text-text-muted hover:text-text hover:bg-surface-2"}`,children:[(0,n.jsxs)("div",{className:"flex items-center justify-between w-full",children:[(0,n.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,n.jsx)(t3.Ay,{name:e.icon||"Shield",size:12,className:`${cP[e.icon]||"text-text-muted"} shrink-0`}),(0,n.jsx)("span",{children:e.label})]}),p===e.id&&(0,n.jsx)(t3.aJ,{size:12,className:"text-brand-400 shrink-0"})]}),(0,n.jsx)("span",{className:"text-[10px] text-text-muted/70 font-normal font-sans leading-tight",children:e.desc})]},e.id))]})]}),m?.objective&&(0,n.jsxs)("div",{className:"flex items-center gap-1 min-w-0",title:`Goal (${m.status}): ${m.objective}`,children:[(0,n.jsx)(t3.We,{size:11,className:`shrink-0 ${"active"===m.status?"text-danger":"text-text-muted"}`}),(0,n.jsx)("span",{className:"truncate max-w-[22ch]",children:m.objective})]})]}),(0,n.jsxs)("div",{className:"flex items-center gap-2.5 shrink-0",children:[h&&!eW.includes(h)&&(0,n.jsx)(aq,{branch:h,dirty:f,size:11,className:"text-text font-medium",iconClassName:"text-brand-500 opacity-100"}),(0,n.jsx)("button",{type:"button",onClick:()=>{(0,t7.e)(),c?.()},className:"hover:text-text flex items-center transition-colors p-0.5 rounded hover:bg-surface-2",title:"New chat",children:(0,n.jsx)(t3.J4,{size:12})})]})]})}),cz=(0,r.memo)(function({skills:e=[],onClose:t,onSelectSkill:s}){let[a,l]=(0,r.useState)(""),i=e.filter(e=>{let t=a.toLowerCase();return(e.name||e.id||"").toLowerCase().includes(t)||(e.description||"").toLowerCase().includes(t)});return(0,n.jsxs)(rQ,{icon:(0,n.jsx)(t3.Kq,{size:14}),title:`Agent Skills (${e.length})`,subtitle:"Skills loaded from ~/.claude/skills and project directory",onClose:t,children:[(0,n.jsx)("div",{className:"p-3 border-b border-border-subtle bg-bg",children:(0,n.jsxs)("div",{className:"flex items-center gap-2 px-3 py-1.5 rounded-brand bg-surface border border-border-subtle focus-within:border-brand-500",children:[(0,n.jsx)(t3.vj,{size:14,className:"text-text-muted shrink-0"}),(0,n.jsx)("input",{type:"text",value:a,onChange:e=>l(e.target.value),placeholder:"Search skills (e.g. cloudflare, review, deploy)...",className:"w-full bg-transparent text-xs text-text placeholder-text-muted focus:outline-none",autoFocus:!0})]})}),(0,n.jsx)("div",{className:"p-3 flex-1 overflow-y-auto flex flex-col gap-0.5 custom-scrollbar",children:0===i.length?(0,n.jsxs)("div",{className:"flex flex-col items-center justify-center gap-2 py-12 text-text-muted",children:[(0,n.jsx)(t3.Kq,{size:32,className:"opacity-50"}),(0,n.jsx)("span",{className:"text-sm",children:0===e.length?"No skills discovered on host agent.":`No skills matching "${a}".`})]}):i.map(e=>(0,n.jsxs)("div",{onClick:()=>{(0,t7.e)(),s?.(e.name||e.id),t?.()},className:"modal-row items-start",children:[(0,n.jsxs)("div",{className:"min-w-0 flex-1 flex flex-col gap-1",children:[(0,n.jsxs)("div",{className:"flex items-center gap-1.5 font-mono text-xs font-semibold text-text",children:[(0,n.jsxs)("span",{children:["/",e.name||e.id]}),(0,n.jsx)("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-surface-3 text-text-muted font-normal",children:"skill"})]}),e.description&&(0,n.jsx)("p",{className:"text-[11px] text-text-muted leading-relaxed line-clamp-2",children:e.description})]}),(0,n.jsxs)("span",{className:"modal-row-acts text-[11px] text-brand-500 items-center gap-1",children:[(0,n.jsx)("span",{children:"Use"}),(0,n.jsx)(t3.Lt,{size:11})]})]},e.id||e.name))})]})}),cI=(0,r.memo)(function({mcpServers:e=[],onClose:t}){return(0,n.jsx)(rQ,{icon:(0,n.jsx)(t3.lP,{size:14}),iconClass:"bg-sky-500/15 text-sky-400",title:`MCP Servers (${e.length})`,subtitle:"Model Context Protocol tools and integrations",onClose:t,children:(0,n.jsx)("div",{className:"p-3 flex-1 overflow-y-auto flex flex-col gap-0.5 custom-scrollbar",children:0===e.length?(0,n.jsxs)("div",{className:"flex flex-col items-center justify-center gap-2 py-12 text-text-muted",children:[(0,n.jsx)(t3.lP,{size:32,className:"opacity-50"}),(0,n.jsx)("span",{className:"text-sm",children:"No MCP servers configured yet."})]}):e.map((e,t)=>(0,n.jsxs)("div",{className:"modal-row",children:[(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsxs)("div",{className:"text-xs font-semibold text-text flex items-center gap-2",children:[(0,n.jsx)(t3.Jl,{size:13,className:"text-emerald-400 shrink-0"}),(0,n.jsx)("span",{className:"font-mono",children:e.name||e.id})]}),e.command&&(0,n.jsx)("div",{className:"text-[11px] text-text-muted font-mono break-all mt-1",children:e.command})]}),(0,n.jsx)("span",{className:"px-2 py-0.5 rounded text-[10px] font-mono bg-emerald-500/15 text-emerald-300 border border-emerald-500/30 uppercase shrink-0 ml-2",children:e.status||"active"})]},e.id||t))})})}),cL=(0,r.memo)(function({currentModel:e="",currentEffort:t="",models:s=[],onClose:a,onSelectModel:l,onSelectEffort:i,isTurnRunning:o=!1}){let[c,d]=(0,r.useState)(""),[u,m]=(0,r.useState)(e),[x,p]=(0,r.useState)(()=>new Set),h=(0,r.useMemo)(()=>{let t=[...s||[]];return e&&!t.some(t=>t.id===e)&&t.unshift({id:e,label:e,desc:"Active CLI model",recent:!0}),t},[s,e]),f=h.find(e=>e.id===u),b=f?.efforts||[],g=(0,r.useMemo)(()=>{let e=c.trim().toLowerCase();return e?h.filter(t=>{let s=(t.label||"").toLowerCase(),n=(t.id||"").toLowerCase(),r=(t.desc||"").toLowerCase(),a=cE(t).toLowerCase();return s.includes(e)||n.includes(e)||r.includes(e)||a.includes(e)}):h},[h,c]),v=(0,r.useMemo)(()=>c_(h,g,e,c.trim()),[h,g,e,c]);return(0,n.jsxs)(rQ,{icon:(0,n.jsx)(t3.cC,{size:14}),title:"Switch AI Model",subtitle:"Select an active model for this session",maxWidth:"max-w-md",onClose:a,children:[(0,n.jsx)("div",{className:"px-4 py-2.5 border-b border-border-subtle shrink-0",children:(0,n.jsxs)("div",{className:"flex items-center gap-2 focus-within:text-text text-text-muted",children:[(0,n.jsx)(t3.vj,{size:14,className:"shrink-0"}),(0,n.jsx)("input",{type:"text",value:c,onChange:e=>d(e.target.value),placeholder:"Search models...",className:"w-full bg-transparent text-xs text-text placeholder-text-muted/70 focus:outline-none",autoFocus:!0}),c&&(0,n.jsx)("button",{type:"button",onClick:()=>d(""),className:"text-text-muted hover:text-text shrink-0 text-xs px-1","aria-label":"Clear search",children:"✕"})]})}),b.length>0&&(0,n.jsxs)("div",{className:"px-3 pt-3 shrink-0",children:[(0,n.jsx)("div",{className:"text-[10px] font-mono uppercase tracking-wider text-text-muted mb-1.5",children:"Reasoning effort"}),(0,n.jsx)("div",{className:"flex items-center gap-1.5 flex-wrap",children:b.map(e=>(0,n.jsx)("button",{type:"button",disabled:o,onClick:()=>{(0,t7.e)(),i?.(e)},className:`px-2.5 py-1 rounded-brand text-[11px] font-mono border transition-colors ${t===e?"border-brand-500 bg-brand-500/10 text-brand-400":"border-border-subtle bg-surface-2/30 text-text-muted hover:text-text hover:bg-surface-2"} disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:bg-transparent`,title:o?"Cannot change effort while turn is running":void 0,children:e},e))})]}),(0,n.jsx)("div",{className:"p-3 flex-1 overflow-y-auto flex flex-col gap-0.5 custom-scrollbar",children:0===g.length?(0,n.jsxs)("div",{className:"py-8 text-center text-xs text-text-muted",children:['No models found matching "',c,'"']}):v.map(e=>(0,n.jsxs)("div",{className:"flex flex-col gap-0.5 mb-2",children:[v.length>1&&(0,n.jsxs)("button",{type:"button",onClick:()=>{var t;return t=e.key,void p(e=>{let s=new Set(e);return s.has(t)?s.delete(t):s.add(t),s})},"aria-expanded":!x.has(e.key),className:"w-full text-left text-[10px] font-mono uppercase tracking-wider font-semibold text-text px-2 pt-2 pb-1 select-none flex items-center justify-between border-b border-border-subtle",children:[(0,n.jsxs)("span",{className:"flex items-center gap-1",children:[(0,n.jsx)("span",{className:"text-[8px]",children:x.has(e.key)?"▶":"▼"}),e.title]}),(0,n.jsx)("span",{className:"text-text-subtle text-[9px]",children:e.items.length})]}),!x.has(e.key)&&e.items.map(s=>{var r;let a=u===s.id,c=cE(s),d=(r=s.contextWindow)&&!(r<=0)?r>=1e6?`${Math.round(r/1e5)/10}M`:r>=1e3?`${Math.round(r/1e3)}k`:`${r}`:null;return(0,n.jsxs)("div",{onClick:o?void 0:()=>(e=>{(0,t7.e)(),l?.(e),m(e);let s=h.find(t=>t.id===e),n=s?.efforts||[];if(n.length>0&&!n.includes(t)){let e=s?.defaultEffort||n[0];e&&i?.(e)}})(s.id),"data-selected":a,className:`modal-row ml-2 ${o?"opacity-40 cursor-not-allowed pointer-events-none":""}`,title:o?"Cannot change model while turn is running":s.id,children:[(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsxs)("div",{className:`text-xs flex items-center gap-1.5 flex-wrap ${a?"text-text font-semibold":"text-text-muted"}`,children:[(0,n.jsx)("span",{className:"truncate",children:s.label||s.id}),"opencode"===c&&(0,n.jsx)("span",{className:"text-[9px] px-1.5 py-0.2 rounded bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 font-mono shrink-0",children:"Free"}),d&&(0,n.jsx)("span",{className:"text-[9px] px-1 py-0.2 rounded bg-surface-2/60 text-text-subtle font-mono shrink-0",children:d}),s.efforts?.length>0&&(0,n.jsx)("span",{className:"text-[9px] px-1 py-0.2 rounded bg-brand-500/10 text-brand-400 font-mono shrink-0",children:"reasoning"})]}),(s.desc||s.label!==s.id&&s.id)&&(0,n.jsx)("div",{className:"text-[10px] font-mono text-text-subtle truncate mt-0.5",children:s.desc||s.id})]}),a&&(0,n.jsx)(t3.aJ,{size:14,className:"text-text shrink-0"})]},`${e.key}-${s.id}`)})]},e.key))})]})}),cD=(0,r.memo)(function({engine:e="claude",workspacePath:t="",onClose:s,onResume:a}){let[l,i]=(0,r.useState)([]),[o,c]=(0,r.useState)(!0),[d,u]=(0,r.useState)(""),m=(0,r.useCallback)(()=>{let e=Q.getState().bus;if(!e?.emit||!t){i([]),c(!1);return}c(!0),e.emit("getAgentSessions",{cwd:t},e=>{i(Array.isArray(e?.sessions)?e.sessions:[]),c(!1)})},[t]);(0,r.useEffect)(()=>{m()},[m]);let x=(0,r.useMemo)(()=>{let t=d.toLowerCase();return l.filter(t=>!e||t.agent===e).filter(e=>!t||(e.title||"").toLowerCase().includes(t)||(e.sessionId||"").toLowerCase().includes(t))},[l,e,d]);return(0,n.jsxs)(rQ,{icon:(0,n.jsx)(t3.BZ,{size:14}),iconClass:"bg-sky-500/15 text-sky-400",title:"Resume a session",subtitle:`Past ${e} conversations in this project`,maxWidth:"max-w-xl",onClose:s,children:[(0,n.jsx)("div",{className:"px-4 py-2.5 border-b border-border-subtle shrink-0",children:(0,n.jsxs)("div",{className:"flex items-center gap-2 focus-within:text-text text-text-muted",children:[(0,n.jsx)(t3.vj,{size:14,className:"shrink-0"}),(0,n.jsx)("input",{type:"text",value:d,onChange:e=>u(e.target.value),placeholder:"Search sessions...",className:"w-full bg-transparent text-xs text-text placeholder-text-muted/70 focus:outline-none",autoFocus:!0}),(0,n.jsx)("button",{type:"button",onClick:m,className:"hover:text-text shrink-0",title:"Refresh",children:(0,n.jsx)(t3.e9,{size:13,className:o?"animate-spin":""})})]})}),(0,n.jsx)("div",{className:"p-3 flex-1 overflow-y-auto flex flex-col gap-0.5 custom-scrollbar",children:o?(0,n.jsxs)("div",{className:"flex items-center justify-center gap-2 py-12 text-xs text-text-muted",children:[(0,n.jsx)(t3.kr,{size:14,className:"animate-spin"}),(0,n.jsx)("span",{children:"Scanning conversations..."})]}):0===x.length?(0,n.jsxs)("div",{className:"flex flex-col items-center justify-center gap-2 py-12 text-text-muted",children:[(0,n.jsx)(t3.BZ,{size:32,className:"opacity-50"}),(0,n.jsx)("span",{className:"text-sm",children:0===l.length?"No past conversations found for this project.":`No sessions matching "${d}".`})]}):x.map(e=>{let t=!!e.openSessionId;return(0,n.jsxs)("div",{onClick:()=>{if((0,t7.e)(),t){window.dispatchEvent(new CustomEvent(ev,{detail:{sessionId:e.openSessionId}})),s?.();return}(0,t7.e)(),a?.(e),s?.()},className:"modal-row",title:e.sessionId,children:[(0,n.jsx)("img",{src:s$("ui"===e.mode?`${e.agent}-ui`:e.agent),alt:e.agent,className:`shrink-0 ${s_} ${t?"":"opacity-50"}`,style:{width:14,height:14}}),(0,n.jsx)("span",{className:`flex-1 min-w-0 truncate text-xs ${t?"text-text font-medium":"text-text-muted"}`,children:e.title||"Untitled conversation"}),e.updatedAt?(0,n.jsx)("span",{className:"shrink-0 text-[10px] font-mono text-text-subtle tabular-nums",children:function(e){if(!e)return"";let t=Math.round((Date.now()-e)/6e4);if(t<60)return`${Math.max(1,t)}m ago`;let s=Math.round(t/60);return s<24?`${s}h ago`:`${Math.round(s/24)}d ago`}(e.updatedAt)}):null]},`${e.agent}:${e.sessionId}`)})})]})}),cF={claude:{shape:"flat",items:[]},codex:{shape:"flat",items:[{key:"personality",kind:"menu",label:"Personality",desc:"Communication style codex is instructed to use",choices:[{value:"",label:"Default"},...om.Mm],default:""},{key:"networkAccess",kind:"bool",label:"Network access",desc:"Let sandboxed commands reach the network",default:!1},{key:"planEffort",kind:"menu",label:"Plan mode reasoning",desc:"Reasoning tier used while in plan mode",choices:[{value:"",label:"Default"},{value:"low",label:"low"},{value:"medium",label:"medium"},{value:"high",label:"high"},{value:"xhigh",label:"xhigh"}],default:""},{key:"addDirs",kind:"list",label:"Extra writable directories",desc:"Absolute paths, comma-separated",default:[]},{key:"enable",kind:"list",label:"Enable features",desc:"Feature names, comma-separated (see `codex features list`)",default:[]},{key:"disable",kind:"list",label:"Disable features",desc:"Feature names, comma-separated",default:[]},{key:"skipGitRepoCheck",kind:"bool",label:"Allow outside a git repo",desc:"Run in a directory without a repository",default:!1},{key:"ephemeral",kind:"bool",label:"Ephemeral run",desc:"Do not persist the session to disk",default:!1}]},opencode:{shape:"flags",items:[{key:"pure",kind:"bool",label:"Pure mode",desc:"Run without external plugins",default:!1},{key:"printLogs",kind:"bool",label:"Print logs",desc:"Show CLI logs on stderr",default:!1}]}};function cO(e){return cF[e]||{shape:"flat",items:[]}}let cB=(0,r.memo)(function({engine:e="claude",options:t,onClose:s,onApply:a}){let{shape:l,items:i}=cO(e),[o,c]=(0,r.useState)(()=>{let s,n;return s=cO(e).items,n=t||{},Object.fromEntries(s.map(e=>[e.key,void 0!==n[e.key]?n[e.key]:e.default]))}),d=(e,t)=>c(s=>({...s,[e]:t}));return(0,n.jsx)(rQ,{icon:(0,n.jsx)(t3.wB,{size:14}),iconClass:"bg-surface-3 text-text-muted",title:"Configuration",subtitle:`Runtime flags for ${e}`,maxWidth:"max-w-md",onClose:s,footer:i.length>0?(0,n.jsxs)("div",{className:"px-4 py-3 border-t border-border-subtle flex justify-end gap-2 shrink-0",children:[(0,n.jsx)("button",{type:"button",onClick:s,className:"px-3 py-1.5 rounded-brand text-xs text-text-muted hover:text-text hover:bg-surface-2 transition-colors",children:"Cancel"}),(0,n.jsx)("button",{type:"button",onClick:()=>{(0,t7.e)();let e={};for(let t of i){let s=o[t.key];"list"===t.kind?e[t.key]=String(s||"").split(",").map(e=>e.trim()).filter(Boolean):e[t.key]=s}a?.("flags"===l?{flags:e}:e),s?.()},className:"px-3 py-1.5 rounded-brand text-xs bg-brand-500 hover:bg-brand-600 text-white font-medium transition-colors",children:"Apply"})]}):null,children:(0,n.jsx)("div",{className:"p-3 flex-1 overflow-y-auto flex flex-col gap-2 custom-scrollbar",children:0===i.length?(0,n.jsxs)("div",{className:"flex flex-col items-center justify-center gap-2 py-12 text-text-muted",children:[(0,n.jsx)(t3.wB,{size:32,className:"opacity-50"}),(0,n.jsxs)("span",{className:"text-sm",children:["No runtime flags are configurable for ",e,"."]})]}):i.map(e=>(0,n.jsxs)("div",{className:"p-3 rounded-brand bg-surface-2/50",children:[(0,n.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,n.jsxs)("div",{className:"min-w-0",children:[(0,n.jsx)("div",{className:"text-xs font-semibold text-text",children:e.label}),(0,n.jsx)("div",{className:"text-[11px] text-text-muted",children:e.desc})]}),"bool"===e.kind&&(0,n.jsx)("input",{type:"checkbox",checked:!!o[e.key],onChange:()=>d(e.key,!o[e.key]),className:"w-4 h-4 accent-brand-500 rounded shrink-0"})]}),"menu"===e.kind&&(0,n.jsx)("div",{className:"flex items-center gap-1.5 flex-wrap mt-2",children:e.choices.map(t=>(0,n.jsx)("button",{type:"button",onClick:()=>{(0,t7.e)(),d(e.key,t.value)},className:`px-2.5 py-1 rounded-brand text-[11px] border transition-colors ${o[e.key]===t.value?"border-brand-500 bg-brand-500/10 text-brand-400":"border-border-subtle bg-surface-2/30 text-text-muted hover:text-text hover:bg-surface-2"}`,children:t.label},t.value))}),"list"===e.kind&&(0,n.jsx)("input",{type:"text",value:Array.isArray(o[e.key])?o[e.key].join(", "):o[e.key]||"",onChange:t=>d(e.key,t.target.value),placeholder:"/path/one, /path/two",className:"mt-2 w-full px-2.5 py-1.5 rounded bg-bg border border-border-subtle text-xs font-mono text-text placeholder-text-muted focus:outline-none focus:border-brand-500"})]},e.key))})})}),cW={Shield:"text-text-muted",Pencil:"text-accent",Eye:"text-accent",Sparkles:"text-warning"},cK=(0,r.memo)(function({modes:e=[],currentMode:t="",onClose:s,onSelectMode:r}){return(0,n.jsx)(rQ,{icon:(0,n.jsx)(t3.Ay,{name:"Shield",size:14}),title:"Permissions",subtitle:"What the agent may do without asking",maxWidth:"max-w-md",onClose:s,children:(0,n.jsx)("div",{className:"p-3 flex-1 overflow-y-auto flex flex-col gap-0.5 custom-scrollbar",children:e.map(e=>{let a=t===e.id;return(0,n.jsxs)("div",{onClick:()=>{var t;return t=e.id,void((0,t7.e)(),r?.(t),s?.())},"data-selected":a,className:"modal-row",children:[(0,n.jsxs)("div",{className:"min-w-0 flex-1 flex items-center gap-2",children:[(0,n.jsx)(t3.Ay,{name:e.icon||"Shield",size:14,className:`${cW[e.icon]||"text-text-muted"} shrink-0`}),(0,n.jsxs)("div",{className:"min-w-0",children:[(0,n.jsx)("div",{className:"text-xs font-semibold text-text",children:e.label}),(0,n.jsx)("div",{className:"text-[11px] text-text-subtle",children:e.desc})]})]}),a&&(0,n.jsx)(t3.aJ,{size:14,className:"text-brand-500 shrink-0"})]},e.id)})})})}),cH=(0,r.memo)(function({engine:e="claude",workspacePath:t="",onClose:s}){let[a,l]=(0,r.useState)(null),[i,o]=(0,r.useState)(!0),c=(0,r.useCallback)(()=>{let s=Q.getState().bus;if(!s?.emit){l({error:"Not connected to the host agent."}),o(!1);return}o(!0),s.emit("ai:doctor",{engine:e,cwd:t},e=>{l(e?.ok?{output:e.output||"",version:e.version||""}:{error:e?.error||"Doctor check failed."}),o(!1)})},[e,t]);return(0,r.useEffect)(()=>{c()},[c]),(0,n.jsxs)(rQ,{icon:(0,n.jsx)(t3.mN,{size:14}),iconClass:"bg-emerald-500/15 text-emerald-400",title:"Diagnostics",subtitle:`Health check for the ${e} CLI`,onClose:s,children:[(0,n.jsx)("div",{className:"p-3 flex-1 overflow-y-auto custom-scrollbar",children:i?(0,n.jsxs)("div",{className:"flex items-center justify-center gap-2 py-8 text-xs text-text-muted",children:[(0,n.jsx)(t3.kr,{size:14,className:"animate-spin"}),(0,n.jsxs)("span",{children:["Running ",e," doctor..."]})]}):a?.error?(0,n.jsxs)("div",{className:"p-3 rounded-brand bg-danger/10 border border-danger/30 text-danger text-xs flex items-start gap-2",children:[(0,n.jsx)(t3.RI,{size:14,className:"shrink-0 mt-0.5"}),(0,n.jsx)("span",{children:a.error})]}):(0,n.jsxs)("div",{className:"space-y-3",children:[(0,n.jsxs)("div",{className:"p-3 rounded-brand bg-emerald-500/10 border border-emerald-500/30 text-emerald-300 text-xs flex items-center gap-2",children:[(0,n.jsx)(t3.Jl,{size:14,className:"shrink-0"}),(0,n.jsx)("span",{className:"font-medium",children:a?.version?`${e} ${a.version}`:`${e} environment report`})]}),(0,n.jsx)("pre",{className:"p-3 rounded-brand bg-bg border border-border-subtle text-[11px] font-mono text-text-muted whitespace-pre-wrap break-words leading-relaxed",children:a?.output||"No output."})]})}),(0,n.jsx)("div",{className:"px-4 py-3 border-t border-border-subtle flex justify-end shrink-0",children:(0,n.jsxs)("button",{type:"button",onClick:c,disabled:i,className:"px-3 py-1.5 rounded-brand text-xs text-text-muted hover:text-text hover:bg-surface-2 transition-colors flex items-center gap-1.5 disabled:opacity-50",children:[(0,n.jsx)(t3.e9,{size:12,className:i?"animate-spin":""}),(0,n.jsx)("span",{children:"Re-run"})]})})]})}),cU={completed:{icon:t3.Jl,cls:"text-emerald-400",line:"line-through text-text-muted"},in_progress:{icon:t3.kr,cls:"text-sky-400 animate-spin",line:"text-sky-300 font-semibold"},pending:{icon:t3.jl,cls:"text-text-muted",line:"text-text"}},cq=(0,r.memo)(function({tasks:e=[],onClose:t}){let s=e.length,r=e.filter(e=>"completed"===e.status).length,a=e.filter(e=>"in_progress"===e.status).length,l=s-r-a;return(0,n.jsxs)(rQ,{icon:(0,n.jsx)(t3.y8,{size:14}),iconClass:"bg-brand-500/15 text-brand-500",title:`Tasks (${s})`,subtitle:"Checklist the agent is working through",onClose:t,children:[(0,n.jsx)("div",{className:"grid grid-cols-4 gap-2 px-4 py-3 border-b border-border-subtle bg-bg text-center shrink-0",children:[{label:"TOTAL",value:s,cls:"text-text"},{label:"RUNNING",value:a,cls:"text-sky-400"},{label:"DONE",value:r,cls:"text-emerald-400"},{label:"PENDING",value:l,cls:"text-text-muted"}].map(e=>(0,n.jsxs)("div",{className:"p-2 rounded-brand bg-surface-2/40",children:[(0,n.jsx)("div",{className:"text-[10px] text-text-muted font-mono",children:e.label}),(0,n.jsx)("div",{className:`text-base font-bold ${e.cls}`,children:e.value})]},e.label))}),(0,n.jsx)("div",{className:"p-3 flex-1 overflow-y-auto flex flex-col gap-0.5 custom-scrollbar",children:0===s?(0,n.jsxs)("div",{className:"flex flex-col items-center justify-center gap-2 py-12 text-text-muted",children:[(0,n.jsx)(t3.y8,{size:32,className:"opacity-50"}),(0,n.jsx)("span",{className:"text-sm",children:"No tasks in this session yet."})]}):e.map((e,t)=>{let s=cU[e.status]||cU.pending,r=s.icon;return(0,n.jsxs)("div",{className:"modal-row items-start",children:[(0,n.jsx)(r,{size:14,className:`${s.cls} shrink-0 mt-0.5`}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("div",{className:`text-xs ${s.line}`,children:e.subject||e.activeForm||"(untitled task)"}),e.activeForm&&"in_progress"===e.status&&(0,n.jsx)("div",{className:"text-[11px] text-sky-400/80 font-mono mt-0.5 truncate",children:e.activeForm})]}),e.taskId&&(0,n.jsxs)("span",{className:"text-[10px] font-mono text-text-muted shrink-0",children:["#",e.taskId]})]},e.id||t)})})]})}),cV=(0,r.memo)(function({sessionId:e="",onListPoints:t,onPreview:s,onApply:a,onClose:l}){let[i,o]=(0,r.useState)([]),[c,d]=(0,r.useState)(null),[u,m]=(0,r.useState)(!0),[x,p]=(0,r.useState)(null),[h,f]=(0,r.useState)(null),[b,g]=(0,r.useState)(!1),[v,y]=(0,r.useState)("");(0,r.useEffect)(()=>{let e=!0;return t?.().then(t=>{e&&(t||y("The host did not answer. Try again."),o(t?.points||[]),d(t?.support||null),m(!1))}).catch(()=>{e&&(y("Could not read this conversation."),m(!1))}),()=>{e=!1}},[t]);let w=(0,r.useCallback)(async e=>{(0,t7.e)(),p(e),f(null),y("");let t=await s?.(e.messageId);t?.ok?f(t):y(t?.error||"The host could not preview this rewind.")},[s]),k=(0,r.useCallback)(async()=>{if(!x)return;(0,t7.e)(),g(!0),y("");let e=await a?.(x.messageId);(g(!1),e?.ok)?l?.():y(e?.error||"The rewind did not go through.")},[x,a,l]),j=c&&!c.conversation;return(0,n.jsx)(rQ,{icon:(0,n.jsx)(t3.BZ,{size:14}),iconClass:"bg-amber-500/15 text-amber-400",title:"Rewind",subtitle:"Go back to an earlier prompt. Turns after it are discarded.",maxWidth:"max-w-xl",onClose:l,children:u?(0,n.jsxs)("div",{className:"flex items-center justify-center gap-2 py-12 text-xs text-text-muted",children:[(0,n.jsx)(t3.kr,{size:14,className:"animate-spin"}),(0,n.jsx)("span",{children:"Reading this conversation..."})]}):j?(0,n.jsxs)("div",{className:"flex flex-col items-center gap-2 py-12 px-6 text-center text-text-muted",children:[(0,n.jsx)(t3.RI,{size:28,className:"opacity-60"}),(0,n.jsx)("span",{className:"text-sm",children:c.how||"This engine cannot rewind a conversation."})]}):0===i.length?(0,n.jsxs)("div",{className:"flex flex-col items-center gap-2 py-12 text-text-muted",children:[(0,n.jsx)(t3.BZ,{size:32,className:"opacity-50"}),(0,n.jsx)("span",{className:"text-sm",children:v||"Nothing to rewind to yet."})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"p-3 flex-1 overflow-y-auto flex flex-col gap-0.5 custom-scrollbar max-h-[45vh]",children:[...i].reverse().map(e=>(0,n.jsxs)("div",{onClick:()=>w(e),className:`modal-row ${x?.messageId===e.messageId?"modal-row-active":""}`,children:[(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("div",{className:"text-xs text-text truncate",children:e.text||"Untitled prompt"}),e.createdAt&&(0,n.jsx)("div",{className:"mt-1 text-[10px] font-mono text-text-subtle",children:function(e){if(!e)return"";let t=Math.round((Date.now()-e)/6e4);if(t<60)return`${Math.max(1,t)}m ago`;let s=Math.round(t/60);return s<24?`${s}h ago`:`${Math.round(s/24)}d ago`}(Date.parse(e.createdAt))})]}),(0,n.jsxs)("span",{className:"modal-row-acts text-[11px] text-brand-500 items-center gap-1",children:[(0,n.jsx)("span",{children:x?.messageId===e.messageId?"Selected":"Pick"}),(0,n.jsx)(t3.Lt,{size:11})]})]},e.messageId))}),v&&(0,n.jsx)("div",{className:"px-3 py-2 border-t border-border-subtle text-[11px] text-danger bg-danger/5",children:v}),(0,n.jsxs)("div",{className:"p-3 border-t border-border-subtle bg-bg shrink-0 flex flex-col gap-2",children:[x&&(0,n.jsx)("div",{className:"text-[11px] leading-relaxed text-text-muted",children:h?.files?.length>0?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"text-text",children:h.files.length})," file",1===h.files.length?"":"s"," will be restored.",(0,n.jsxs)("ul",{className:"mt-1 flex flex-col gap-0.5",children:[h.files.slice(0,8).map(e=>(0,n.jsxs)("li",{className:"truncate font-mono text-[10px]",title:e.file,children:["\xb7 ",e.file,e.status?` (${e.status})`:""]},e.file)),h.files.length>8&&(0,n.jsxs)("li",{className:"text-[10px]",children:["… and ",h.files.length-8," more"]})]}),h.note&&(0,n.jsx)("span",{className:"block mt-1 text-text-subtle",children:h.note})]}):h?(0,n.jsx)("span",{className:"block text-text-subtle",children:h.note}):(0,n.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,n.jsx)(t3.kr,{size:11,className:"animate-spin"}),"Checking what this would change..."]})}),(0,n.jsxs)("button",{type:"button",onClick:k,disabled:!x||b||!h?.ok,className:`px-3 py-1.5 rounded-brand text-xs font-medium flex items-center justify-center gap-1.5 transition-colors ${x&&!b&&h?.ok?"bg-brand-500 hover:bg-brand-600 text-white cursor-pointer":"bg-surface-2 text-text-muted cursor-not-allowed opacity-50"}`,children:[b?(0,n.jsx)(t3.kr,{size:13,className:"animate-spin"}):(0,n.jsx)(t3.aJ,{size:13}),(0,n.jsx)("span",{children:b?"Rewinding...":"Rewind to this prompt"})]})]})]})})}),cX=(0,r.memo)(function({requestId:e="",tool:t="",input:s={},failed:a=!1,onResolve:l}){let[i,o]=(0,r.useState)(""),[c,d]=(0,r.useState)(!1),u=function(e){if(e?.kind!=="permission_grant")return"";let t=[],s=String(e.reason||"").trim();return s&&t.push(s),t.push(...function(e={}){let t=[];e?.network?.enabled&&t.push("• network access");let s=e?.fileSystem||{};for(let e of s.read||[])t.push(`• read ${e}`);for(let e of s.write||[])t.push(`• write ${e}`);for(let e of s.entries||[]){var n;let s="string"==typeof(n=e?.path)?n:n?.path||n?.pattern||n?.value||"";s&&t.push(`• ${e.access||"access"} ${s}`)}return t}(e.permissions)),t.join("\n")}(s)||s?.command||s?.path||JSON.stringify(s||{});return(0,n.jsxs)("div",{className:"my-3 p-3 rounded-brand-lg border border-warning/30 bg-surface shadow-sm text-xs",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2 mb-2 text-warning font-medium",children:[(0,n.jsx)(t3.ek,{size:16}),(0,n.jsx)("span",{children:"Permission Request"}),(0,n.jsx)("span",{className:"font-mono text-[10px] px-1.5 py-0.5 rounded bg-warning/15 text-warning uppercase min-w-0 break-all",title:t,children:t||"Action"})]}),(0,n.jsx)("div",{className:"p-2.5 rounded bg-bg font-mono text-[11px] text-text break-all border border-border-subtle mb-3 max-h-[140px] overflow-y-auto",children:u}),c&&(0,n.jsx)("div",{className:"mb-3",children:(0,n.jsx)("input",{type:"text",value:i,onChange:e=>o(e.target.value),placeholder:"Reason for denial or alternative instructions...",className:"w-full px-2.5 py-1.5 rounded bg-bg border border-border-subtle text-xs text-text placeholder-text-muted focus:outline-none focus:border-brand-500",autoFocus:!0})}),a&&(0,n.jsx)("div",{className:"mb-3 text-[11px] text-danger leading-snug",children:"Not sent — the host did not answer. Try again."}),(0,n.jsxs)("div",{className:"flex items-center gap-2 justify-end",children:[c?(0,n.jsx)("button",{type:"button",onClick:()=>d(!1),className:"px-2.5 py-1.5 rounded text-text-muted hover:text-text hover:bg-surface-2 transition-colors",children:"Hide note"}):(0,n.jsx)("button",{type:"button",onClick:()=>d(!0),className:"px-2.5 py-1.5 rounded text-text-muted hover:text-text hover:bg-surface-2 transition-colors",children:"Add note"}),(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),l?.(e,"deny",i||"User denied")},className:"px-3 py-1.5 rounded bg-surface-2 hover:bg-danger/20 text-danger flex items-center gap-1 font-medium transition-colors",children:[(0,n.jsx)(t3.X,{size:14}),(0,n.jsx)("span",{children:"Deny"})]}),(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),l?.(e,"allow")},className:"px-3.5 py-1.5 rounded bg-brand-500 hover:bg-brand-600 text-white flex items-center gap-1 font-medium transition-colors shadow-sm",children:[(0,n.jsx)(t3.aJ,{size:14}),(0,n.jsx)("span",{children:"Allow"})]})]})]})}),cG=(0,r.memo)(function({engine:e="",message:t="",reason:s="",escalate:r=null,onEscalate:a,onDismiss:l}){return(0,n.jsxs)("div",{className:"my-3 p-3 rounded-brand-lg border border-danger/40 bg-surface shadow-sm text-xs",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2 mb-2 text-danger font-medium",children:[(0,n.jsx)(t3.ek,{size:16}),(0,n.jsx)("span",{children:"Action blocked"}),e&&(0,n.jsx)("span",{className:"font-mono text-[10px] px-1.5 py-0.5 rounded bg-danger/15 text-danger uppercase",children:e})]}),(0,n.jsx)("div",{className:"p-2.5 rounded bg-bg text-[11px] text-text border border-border-subtle mb-3 whitespace-pre-wrap break-words max-h-[160px] overflow-y-auto",children:t||s||"The CLI refused this action under the current permission mode."}),(0,n.jsxs)("div",{className:"flex items-center gap-2 justify-end",children:[(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),l?.()},className:"px-2.5 py-1.5 rounded text-text-muted hover:text-text hover:bg-surface-2 transition-colors flex items-center gap-1",children:[(0,n.jsx)(t3.X,{size:13}),(0,n.jsx)("span",{children:"Dismiss"})]}),r?.mode&&(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),a?.(r?.mode)},className:"px-3.5 py-1.5 rounded bg-brand-500 hover:bg-brand-600 text-white flex items-center gap-1 font-medium transition-colors shadow-sm",children:[(0,n.jsx)(t3.sU,{size:14}),(0,n.jsxs)("span",{children:["Switch to ",r.label||r.mode]})]})]})]})}),cJ=[],cY=(0,r.memo)(function({sessionId:e=""}){let[t,s]=(0,r.useState)(!1),a=oq(t=>t.bySession[e]?.tasks),l=(0,r.useMemo)(()=>Array.isArray(a)?a.filter(e=>!!(e&&e.subject&&String(e.subject).trim().length>0)):cJ,[a]);if(0===l.length)return null;let i=l.filter(e=>"completed"===e.status).length,o=l.find(e=>"in_progress"===e.status),c=i===l.length;return(0,n.jsxs)("div",{className:"px-4 sm:px-6 py-1 border-b border-border-subtle/40 bg-surface-2/20 shrink-0 text-xs select-none",children:[(0,n.jsx)("div",{onClick:()=>s(!t),className:"flex items-center justify-between py-1 px-0 hover:bg-surface-2/40 cursor-pointer data-pane-control transition-colors group",children:(0,n.jsxs)("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[c?(0,n.jsx)(t3.Jl,{size:13,className:"text-success shrink-0"}):o?(0,n.jsx)(t3.y8,{size:13,className:"text-brand-500 shrink-0"}):(0,n.jsx)(t3.y8,{size:13,className:"text-text-muted shrink-0"}),(0,n.jsx)("span",{className:"font-mono text-[10px] font-semibold text-text uppercase tracking-wider shrink-0 px-1 py-0.5 rounded bg-surface-2/80",children:"TASKS"}),(0,n.jsxs)("span",{className:"font-mono text-[11px] text-text-muted shrink-0",children:[i,"/",l.length]}),o&&(0,n.jsx)("span",{className:"text-[11px] text-brand-500 truncate min-w-0 font-medium",children:o.activeForm||o.subject}),(0,n.jsx)("span",{className:"text-text-muted/50 shrink-0 ml-auto",children:t?(0,n.jsx)(t3.yQ,{size:11}):(0,n.jsx)(t3.c_,{size:11})})]})}),t&&(0,n.jsx)("div",{className:"mt-1 ml-3.5 pl-3 border-l-2 border-border-subtle/80 py-1 space-y-0.5 animate-in fade-in duration-100",children:l.map((e,t)=>(0,n.jsxs)("div",{className:"flex items-center gap-2 py-0.5",children:["completed"===e.status?(0,n.jsx)(t3.Jl,{size:12,className:"text-success shrink-0"}):"in_progress"===e.status?(0,n.jsx)(t3.jG,{size:10,className:"text-brand-500 fill-brand-500 shrink-0"}):(0,n.jsx)(t3.jl,{size:12,className:"text-text-muted/50 shrink-0"}),(0,n.jsx)("span",{className:`text-[11px] truncate ${"completed"===e.status?"line-through text-text-muted/60":"in_progress"===e.status?"text-text font-medium":"text-text-muted"}`,children:e.subject})]},e.id||t))})]})}),cZ=e=>String(e).padStart(2,"0");function cQ(e){let t=Math.max(0,Math.floor((Number(e)||0)/1e3)),s=Math.floor(t/3600),n=Math.floor(t%3600/60),r=t%60;return s>0?`${s}h ${cZ(n)}m`:n>0?`${n}m ${cZ(r)}s`:`${r}s`}let c0=e=>Number(e?.duration_ms)||0,c1={agent:{label:"Sub-agent",icon:t3.cC,cls:"bg-accent/15 text-accent"},shell:{label:"Background task",icon:t3.BK,cls:"bg-warning/15 text-warning"}},c2={running:"bg-sky-500/15 text-sky-400",completed:"bg-emerald-500/15 text-emerald-400",failed:"bg-danger/15 text-danger",killed:"bg-danger/15 text-danger",stopped:"bg-surface-2 text-text-muted",paused:"bg-warning/15 text-warning"},c5=(0,r.memo)(function({tasks:e=[],messages:t=[],engine:s="claude",sessionId:a="",onStopTask:l,onClose:i}){let[o,c]=(0,r.useState)(()=>Date.now()),[d,u]=(0,r.useState)(null),m=oq(e=>e.bySession[a]?.harnessTasks);(0,r.useEffect)(()=>{let e=setInterval(()=>c(Date.now()),1e3);return()=>clearInterval(e)},[]);let x=(0,r.useMemo)(()=>e.map(e=>m?.find(t=>t.taskId===e.taskId)||e),[e,m]),p=x.find(e=>e.taskId===d)||x[0];if(!p)return null;let h=oR(p,o),f=!p.endedAt&&("running"===p.status||"paused"===p.status),b=c2[p.status]||(f?c2.running:c2.stopped);return(0,n.jsxs)(rQ,{icon:(0,n.jsx)(t3.BZ,{size:14}),iconClass:"bg-brand-500/15 text-brand-500",title:f?`Running for ${cQ(h)}`:`Ended \xb7 ${cQ(h)}`,subtitle:`${x.length} task${x.length>1?"s":""} handed off`,onClose:i,children:[x.length>1&&(0,n.jsx)("div",{className:"flex gap-1 px-3 py-2 border-b border-border-subtle overflow-x-auto custom-scrollbar shrink-0",children:x.map(e=>{let t=c1[e.background?"shell":"agent"].icon,s=e.taskId===p.taskId;return(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),u(e.taskId)},className:`flex items-center gap-1.5 shrink-0 px-2 py-1 rounded-full text-[11px] transition-colors ${s?"bg-brand-500/15 text-brand-400 font-semibold":"text-text-muted hover:text-text hover:bg-surface-2"}`,children:[(0,n.jsx)(t,{size:11,className:"shrink-0"}),(0,n.jsx)("span",{className:"max-w-[18ch] truncate",children:e.description||e.subagentType||e.taskId})]},e.taskId)})}),(0,n.jsxs)("div",{className:"flex-1 overflow-y-auto custom-scrollbar",children:[(0,n.jsx)(c3,{task:p,elapsed:h,statusCls:b}),(0,n.jsxs)("div",{className:"p-3",children:[(0,n.jsx)(c4,{task:p,messages:t,engine:s}),(0,n.jsx)(c6,{task:p,messages:t,engine:s,sessionId:a}),p.usage&&(0,n.jsxs)("div",{className:"flex flex-wrap gap-2 mt-3",children:[(0,n.jsx)(c8,{label:"TOKENS",value:oy(p.usage.total_tokens)}),(0,n.jsx)(c8,{label:"TOOLS",value:p.usage.tool_uses??0}),c0(p.usage)>0&&(0,n.jsx)(c8,{label:"TOOK",value:cQ(c0(p.usage))})]}),p.summary&&(0,n.jsx)("p",{className:"mt-3 text-[11px] text-text-muted leading-relaxed border-l-2 border-border-subtle pl-3",children:p.summary}),p.outputFile&&(0,n.jsxs)("p",{className:"mt-3 font-mono text-[10px] text-text-subtle truncate",title:p.outputFile,children:["output \xb7 ",p.outputFile]})]})]}),f&&p.taskId&&l&&(0,n.jsx)("div",{className:"px-3 py-2.5 border-t border-border-subtle bg-bg shrink-0",children:(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),l(p.taskId)},className:"w-full flex items-center justify-center gap-1.5 py-2 rounded-brand text-xs font-semibold text-danger bg-danger/10 hover:bg-danger/20 transition-colors",children:[(0,n.jsx)(t3.M6,{size:11}),"Stop this task"]})})]})});function c3({task:e,elapsed:t,statusCls:s}){let r=c1[e.background?"shell":"agent"],a=r.icon;return(0,n.jsxs)("div",{className:"px-4 py-3 border-b border-border-subtle flex items-start gap-3",children:[(0,n.jsx)("div",{className:`w-8 h-8 rounded-full flex items-center justify-center shrink-0 ${r.cls}`,children:(0,n.jsx)(a,{size:15})}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,n.jsx)("span",{className:"text-sm font-semibold text-text truncate",children:e.description||e.subagentType||"task"}),(0,n.jsx)("span",{className:`text-[10px] font-mono uppercase tracking-wider px-1.5 py-0.5 rounded ${s}`,children:e.status})]}),(0,n.jsxs)("div",{className:"flex items-center gap-2 mt-1 text-[11px] text-text-muted font-mono flex-wrap",children:[(0,n.jsx)("span",{children:r.label}),e.subagentType&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(c9,{}),(0,n.jsx)("span",{className:"text-brand-500",children:e.subagentType})]}),e.taskType&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(c9,{}),(0,n.jsx)("span",{children:e.taskType})]}),(0,n.jsx)(c9,{}),(0,n.jsxs)("span",{className:"text-text tabular-nums",title:"since the agent logged the task's start",children:["running ",cQ(t)]}),(0,n.jsx)(c9,{}),(0,n.jsx)("span",{className:"text-text-subtle",children:e.taskId})]})]})]})}function c4({task:e,messages:t,engine:s}){let r=oc(t,e.toolUseId),a=ox(r,s);if(!a||!r)return null;let l="error"===r.status;return(0,n.jsxs)("div",{className:"flex items-center gap-2 px-3 py-2 rounded-brand bg-surface-2/40 border border-border-subtle/60",children:["running"===e.status?(0,n.jsx)(t3.kr,{size:12,className:"animate-spin text-brand-500 shrink-0"}):l?(0,n.jsx)(t3.RI,{size:12,className:"text-danger shrink-0"}):(0,n.jsx)(t3.Jl,{size:12,className:"text-success shrink-0"}),(0,n.jsx)("span",{className:"font-mono text-[10px] uppercase tracking-wider text-text-muted shrink-0",children:"now"}),(0,n.jsx)("span",{className:"text-[11px] text-text truncate min-w-0",title:a,children:a})]})}function c6({task:e,messages:t,engine:s,sessionId:r}){let a=oo(t,e.toolUseId);if(!a)return null;let l=a.children?.length?a.children:[a];return(0,n.jsxs)("div",{className:"mt-3",id:(0,cr.xo)(r,"calls",a.id),children:[(0,n.jsx)("div",{className:"text-[10px] font-mono uppercase tracking-wider text-text-muted mb-1",children:a.children?.length?`${a.children.length} call${a.children.length>1?"s":""}`:"command"}),l.map(e=>cm(s,e,{engine:s})||(0,n.jsx)(o3,{...e,engine:s},e.id))]})}function c8({label:e,value:t}){return(0,n.jsxs)("div",{className:"px-2.5 py-1.5 rounded-brand bg-surface-2/40 min-w-[68px]",children:[(0,n.jsx)("div",{className:"text-[9px] font-mono text-text-muted tracking-wider",children:e}),(0,n.jsx)("div",{className:"text-xs font-semibold text-text tabular-nums",children:t})]})}let c9=()=>(0,n.jsx)("span",{className:"text-text-subtle",children:"\xb7"}),c7=[],de=(0,r.memo)(function({sessionId:e="",engine:t="claude",onStopTask:s}){let a=oq(t=>t.bySession[e]?.messages)||c7,l=oq(t=>t.bySession[e]?.harnessTasks)||c7,i=(0,r.useMemo)(()=>(function(e=[],t=[]){return t.length>0?t.filter(e=>e?.status==="running").map(e=>({kind:e.background?"shell":"agent",id:e.toolUseId||e.taskId,taskId:e.taskId,label:e.description||e.subagentType||"task",startedAt:e.startedAt,taskType:e.taskType,subagentType:e.subagentType,usage:e.usage,toolUseId:e.toolUseId})):function(e=[]){let t=[],s=e=>{for(let n of e||[]){if(n?.status==="running"){let e=n.startedAt||n.timestamp,s=e?{startedAt:e}:null;oa.has(n?.name)?t.push({kind:"agent",id:n.id,label:ol(n),...s}):n?.async&&t.push({kind:"shell",id:n.id,label:oi(n),...s})}n?.children?.length&&s(n.children)}};for(let n=e.length-1;n>=0&&(!e[n]?.tools?.length||(s(e[n].tools),!(t.length>0)));n--);return t}(e)})(a,l),[a,l]),[o,c]=(0,r.useState)(null),[d,u]=(0,r.useState)(()=>Date.now()),[m,x]=(0,r.useState)(!1),p=(0,r.useRef)(null);(0,r.useEffect)(()=>{if(0===i.length)return;let e=setInterval(()=>u(Date.now()),1e3);return()=>clearInterval(e)},[i.length]),(0,r.useEffect)(()=>()=>clearTimeout(p.current),[]);let h=(0,r.useCallback)(()=>{if(!m){x(!0),(0,t7.e)(),clearTimeout(p.current),p.current=setTimeout(()=>x(!1),3e3);return}for(let e of(clearTimeout(p.current),x(!1),(0,t7.e)(),i))e.taskId&&s(e.taskId)},[m,i,s]),f=i.some(e=>e.taskId&&s);if(0===i.length)return null;let b=i.filter(e=>"agent"===e.kind),g=i.filter(e=>"shell"===e.kind);return(0,n.jsxs)("div",{className:"px-4 sm:px-6 py-1 border-b border-border-subtle/40 bg-brand-500/[0.06] shrink-0 text-xs select-none",children:[b.length>0&&(0,n.jsx)(dt,{icon:(0,n.jsx)(t3.kr,{size:13,className:"text-brand-500 shrink-0 animate-spin"}),tag:"AGENTS",items:b,messages:a,engine:t,now:d,onOpen:c}),g.length>0&&(0,n.jsx)(dt,{icon:(0,n.jsx)(t3.kr,{size:13,className:"text-warning shrink-0 animate-spin"}),tag:"SHELLS",items:g,messages:a,engine:t,now:d,onOpen:c}),f&&i.length>1&&(0,n.jsx)("div",{className:"flex justify-end pb-0.5",children:(0,n.jsx)("button",{type:"button",onClick:h,className:`text-[11px] px-2 py-0.5 rounded transition-colors ${m?"bg-danger/20 text-danger font-semibold":"text-text-muted hover:text-text"}`,children:m?"Press again to stop all":"Stop all"})}),o&&(0,n.jsx)(c5,{tasks:o,messages:a,engine:t,sessionId:e,onStopTask:s,onClose:()=>c(null)})]})});function dt({icon:e,tag:t,items:s,messages:r,engine:a,now:l,onOpen:i}){let o=s.map(e=>e.label).join(", "),c=oR(s.reduce((e,t)=>t.startedAt&&(!e?.startedAt||t.startedAt<e.startedAt)?t:e,null),l),d=s.map(e=>ox(oc(r,e.toolUseId),a)).find(Boolean);return(0,n.jsxs)("div",{className:"flex items-center gap-2 py-1 min-w-0",children:[e,(0,n.jsx)("span",{className:"font-mono text-[10px] font-semibold text-text uppercase tracking-wider shrink-0 px-1 py-0.5 rounded bg-surface-2/80",children:t}),(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),i(s)},title:o,className:"flex items-center gap-2 min-w-0 flex-1 text-left hover:bg-surface-2/40 rounded transition-colors px-1",children:[(0,n.jsxs)("span",{className:"font-mono text-[11px] text-brand-500 shrink-0 tabular-nums",children:[s.length," running"]}),c>0&&(0,n.jsx)("span",{className:"font-mono text-[11px] text-text shrink-0 tabular-nums",children:cQ(c)}),(0,n.jsx)("span",{className:"text-[11px] text-text-muted truncate min-w-0",children:d||o})]})]})}let ds={model:"",skills:[],mcpServers:[]},dn=[],dr=(0,r.memo)(function({sessionId:e,engine:t="claude",workspacePath:s="",sessionName:a="",bus:l=null,fileBus:i=null,isVisible:o=!0,isFocused:c=!1,isDesktop:d=!0,bgIndex:u=0,onActivate:m=null,onOpenRemote:x=null,onOpenMobile:p=null,onOpenArtifact:h=null,onNewChat:f=null}){let[b,g]=(0,r.useState)(null),[y,w]=(0,r.useState)(!1),[k,j]=(0,r.useState)(!1),{t:N}=(0,se.s)(),{sendPrompt:S,removeQueueItem:C,clearQueue:T,resolvePermission:R,stop:E,stopTask:_,runShell:$,rewindToMessage:M,previewRewind:P,listRewindPoints:A,escalateMode:z,dismissBlocked:I,hasOlder:L,loadOlder:D,reload:F,hydrating:O,synced:B,hydrateFailed:W}=function({sessionId:e,engine:t="claude",workspacePath:s="",bus:n=null,isVisible:a=!0}){let l=(0,r.useRef)(n);(0,r.useEffect)(()=>{l.current=n},[n]);let i=oq(e=>e.initSession),o=oq(e=>e.setMetadata),c=oq(e=>e.appendDelta),d=oq(e=>e.appendThinking),u=oq(e=>e.appendDiff),m=oq(e=>e.appendTool),x=oq(e=>e.updateToolResult),p=oq(e=>e.nestTool),h=oq(e=>e.nestToolResult),f=oq(e=>e.upsertTask),b=oq(e=>e.setPermission),g=oq(e=>e.clearPermission),y=oq(e=>e.finishTurn),w=oq(e=>e.setTurnRunning),k=oq(e=>e.addUserMessage),j=Q(e=>e.connected),[N,S]=(0,r.useState)(!1),[C,T]=(0,r.useState)(!1),[R,E]=(0,r.useState)(!1),[_,$]=(0,r.useState)(!1),M=(0,r.useRef)(0),P=(0,r.useRef)(!1),A=(0,r.useCallback)((e,s,n)=>{switch(s){case"user_message":k(e,n.text,n.attachments||null,!!n?.replay);break;case"init":{let t=oY(oq.getState().bySession[e]?.metadata?.skills),s=new Map(t.map(e=>[e.id||e.name,e])),r=oY(n.skills),a=r.length>0?r.map(e=>{let t=s.get(e.id);return t?.description?{...e,description:t.description}:e}):t,{model:l,...i}=n||{};o(e,{...i,skills:a,...l?{model:l}:{}});break}case"goal":o(e,{goal:n?.goal||null});break;case"delta":c(e,n.text);break;case"thinking":d(e,n.text);break;case"diff":u(e,n);break;case"tool_child":p(e,n);break;case"tool_result_child":h(e,n);break;case"tool_start":if(m(e,n),n&&n.name){let s=oq.getState().bySession[e]?.tasks||[],r=(0,om.Zm)(t,n.name,n.input,n.id,s);r&&f(e,r)}break;case"tool_result":if(x(e,n),n&&n.id){let s=(0,om.in)(t,n.name||"",n.output||"",n.id);s&&f(e,s)}break;case"permission_request":b(e,n);break;case"permission_resolved":g(e,n.requestId);break;case"blocked":oq.getState().setBlocked(e,n);break;case"options_changed":n?.permissionMode&&oq.getState().setPermissionMode(e,n.permissionMode),n?.model&&o(e,{model:n.model}),n?.effort&&o(e,{effort:n.effort});break;case"queue_update":oq.getState().setQueue(e,n?.queue||[]);break;case"turn_complete":y(e,n.stats,n.turnMs,!!n?.replay),n?.isError&&!oZ(oq.getState().bySession[e]?.messages,n.result)&&oq.getState().addNotice(e,{subtype:n.subtype||"",level:"error",content:n.result||"The turn ended in an error."});break;case"stats":n?.stats&&oq.getState().setStats(e,n.stats);break;case"stopped":case"exit":g(e),oq.getState().finishTurn(e,null,n?.turnMs),"exit"===s&&(n?.error||n?.code!=null&&0!==n.code)&&oq.getState().addNotice(e,{subtype:"exit",level:"error",content:n.error||`The AI process exited (code ${n.code}).`});break;case"stall":w(e,!1),y(e,null,n?.turnMs);break;case"error":oq.getState().addNotice(e,{subtype:"error",level:"error",content:n?.message||"AI process failed"}),y(e,null,n?.turnMs);break;case"prompt_refused":oq.getState().addNotice(e,{subtype:"prompt_refused",level:"error",content:oQ(n)});break;case"conversation_reset":(0,v.Lq)("ai-status","reset",{sessionId:e,isTurnRunning:n?.isTurnRunning,elapsedMs:n?.elapsedMs,lastTurnMs:n?.lastTurnMs,fromSeq:n?.fromSeq}),oq.getState().clearMessages(e),oq.getState().setTaskRecords(e,n?.taskRecords),oq.getState().restoreTurnState(e,n),Array.isArray(n?.queue)&&oq.getState().setQueue(e,n.queue);break;case"cli_event":{let t=n?.type||"",s=n?.record||null;oq.getState().applyTaskRecords(e,[[t,n?.subtype||"",s,n?.ageMs]]);let r=oI(t,s);r&&oq.getState().addNotice(e,r)}}},[t,k,o,c,d,u,m,x,p,h,f,b,g,y,w]),z=(0,r.useRef)(A);(0,r.useEffect)(()=>{z.current=A});let I=(0,r.useRef)(i);(0,r.useEffect)(()=>{I.current=i});let L=(0,r.useRef)(0),D=(0,r.useRef)(0),F=(0,r.useRef)(!1),O=(0,r.useRef)([]),B=(0,r.useRef)(0),W=(0,r.useRef)(null);null==W.current&&(W.current=function(e=oJ){let t=0,s=!1;return{schedule:n=>s||!n?null:(s=!0,e[Math.min(t++,e.length-1)]),fired(){s=!1},answered(){s=!1,t=0},exhausted:()=>t>=e.length}}());let K=(0,r.useRef)(null),H=(0,r.useRef)(null),U=(0,r.useRef)(null),q=(0,r.useRef)({}),V=(0,r.useRef)(null),X=(0,r.useRef)(a);(0,r.useEffect)(()=>{X.current=a},[a]);let G=(0,r.useRef)(null),J=(0,r.useRef)(null),Y=(0,r.useRef)(null),Z=(0,r.useCallback)(()=>{K.current&&clearTimeout(K.current),K.current=null,W.current?.answered()},[]),ee=(0,r.useCallback)(()=>{let e=W.current?.schedule(Q.getState().connected);$(!!W.current?.exhausted()),(0,v.Lq)("ai-hydrate","ladder",{delay:e??null,exhausted:W.current?.exhausted(),connected:Q.getState().connected,armed:null!=K.current}),null!=e&&(K.current=setTimeout(()=>{K.current=null,W.current?.fired(),q.current.request?.()},e))},[]),et=(0,r.useCallback)(()=>{if(!e||!n)return;if(F.current){(0,v.Lq)("ai-hydrate","blocked (round in flight)",{gen:B.current}),ee();return}let r=++B.current,a=D.current;F.current=!0,T(!0),O.current=[],M.current=0;let l=Date.now();(0,v.Lq)("ai-hydrate","emit ai:create",{gen:r,sessionId:e,engine:t,cwd:s,carrier:Q.getState().carrier,connected:Q.getState().connected});let i=()=>{let t=O.current;for(let s of(O.current=[],F.current=!1,T(!1),t)){if("conversation_reset"===s.event){L.current=0,D.current++,M.current=s.data?.fromSeq??0,S(!!s.data?.hasMore),z.current(e,s.event,s.data);continue}if(null!=s.seq){if(s.seq<=L.current)continue;L.current=s.seq}z.current(e,s.event,s.data)}},o=setTimeout(()=>{r===B.current&&F.current&&(i(),ee())},4e3);U.current=o,n.emit("ai:create",{sessionId:e,engine:t,cwd:s,options:{defaultMode:(0,om.Tw)(t).defaultMode,defaultEffort:(0,om.Tw)(t).defaultEffort}},s=>{if(!function({isNewest:e,snapshotSeq:t=0,appliedSeq:s=0,sameLog:n=!0}){return!!e||!!n&&(t||0)>(s||0)}({isNewest:r===B.current,snapshotSeq:s?.session?.seq,appliedSeq:L.current,sameLog:a===D.current}))return;let n=null,c=null,d=s?.session?.events;(0,v.Lq)("ai-hydrate","ack",{gen:r,stale:r!==B.current,ms:Date.now()-l,ok:s?.ok??null,error:s?.error??null,events:Array.isArray(d)?d.length:null,hasMore:s?.session?.hasMore??null});try{if(clearTimeout(o),!s?.ok||!Array.isArray(d))return void S(!1);let r=s.session.seq||0;if((0,v.Lq)("ai-status","hydrate ack",{sessionId:e,isTurnRunning:s.session.isTurnRunning,elapsedMs:s.session.elapsedMs,lastTurnMs:s.session.lastTurnMs,events:d.length,hasMore:s.session.hasMore}),M.current=d[0]?.seq??0,S(!!s.session.hasMore&&d.length>0),(0,v.Lq)("ai-page","hydrate",{sessionId:e,replayed:d.length,hasMore:s.session.hasMore,fromSeq:d[0]?.seq??0,lastSeq:r,oldestId:null}),Array.isArray(s?.modelOptions)&&s.modelOptions.length>0&&oq.getState().setMetadata(e,{modelOptions:s.modelOptions}),d.length>0){let n=o0(d,t);oq.getState().hydrateSession(e,{messages:n.messages,tasks:n.tasks,metadata:{...oq.getState().bySession[e]?.metadata,...n.metadata,...Array.isArray(s?.modelOptions)?{modelOptions:s.modelOptions}:{},...s.session.effort?{effort:s.session.effort}:{}},stats:{...n.stats,...s.session.stats||{}},isTurnRunning:void 0!==s.session.isTurnRunning?!!s.session.isTurnRunning:n.isTurnRunning,elapsedMs:s.session.elapsedMs||0,lastTurnMs:s.session.lastTurnMs||0,permissionMode:s.session.permissionMode||n.permissionMode,activeBlocked:n.activeBlocked,harnessTasks:oz(s.session.taskRecords,n.harnessTasks),queue:s.session.queue||[]})}else w(e,!!s.session.isTurnRunning),oq.getState().setTaskRecords(e,s.session.taskRecords),s.session.permissionMode&&oq.getState().setPermissionMode(e,s.session.permissionMode),Array.isArray(s.session.queue)&&oq.getState().setQueue(e,s.session.queue),s.session.stats&&oq.getState().setStats(e,s.session.stats);n=s.session.activePermission||null,c=Array.isArray(s.session.queue)?s.session.queue:null,L.current=r}finally{clearTimeout(o),r===B.current&&i(),n&&r===B.current&&oq.getState().setPermission(e,n),c&&r===B.current&&oq.getState().setQueue(e,c),s?.ok&&void 0!==s.session.isTurnRunning&&(oq.getState().restoreTurnState(e,{isTurnRunning:!!s.session.isTurnRunning,elapsedMs:s.session.elapsedMs||0,lastTurnMs:s.session.isTurnRunning?0:s.session.lastTurnMs||0}),(0,v.Lq)("ai-status","restate",{sessionId:e,isTurnRunning:!!s.session.isTurnRunning,elapsedMs:s.session.elapsedMs||0,lastTurnMs:s.session.lastTurnMs||0})),s?.ok?(E(!0),$(!1),Z()):ee(),(0,v.Lq)("ai-hydrate","settled",{gen:r,stale:r!==B.current,ok:s?.ok??null,hydrating:F.current,synced:!!s?.ok})}})},[e,t,s,n,w,ee,Z]),es=(0,r.useCallback)(()=>{!Q.getState().connected||H.current||(H.current=setTimeout(()=>{H.current=null,et()},150))},[et]),en=(0,r.useCallback)(()=>{if(n&&e){if(!X.current){G.current="visible";return}!Q.getState().connected||F.current||J.current||(J.current=setTimeout(()=>{if(J.current=null,!X.current||F.current)return;let t=!1,s=setTimeout(()=>{t||((0,v.Lq)("ai-hydrate","peekSeq: no ack → full hydrate"),es())},4e3);Y.current=s,n.emit("ai:peekSeq",{sessionId:e},n=>{if(t=!0,clearTimeout(s),Y.current=null,!n?.ok||"number"!=typeof n.seq)return void es();let r=L.current,a=!!oq.getState().bySession[e]?.isTurnRunning,l=oq.getState().bySession[e]?.queue?.length||0,i="number"==typeof n.queueLength?n.queueLength:l;n.seq===r&&!!n.isTurnRunning===a&&i===l?(0,v.Lq)("ai-hydrate","peekSeq: nothing missed",{seq:r}):((0,v.Lq)("ai-hydrate","peekSeq: state changed",{fromSeq:r,toSeq:n.seq,turn:n.isTurnRunning}),es())})},150))}},[n,e,es]),er=(0,r.useCallback)(()=>{Z(),et()},[Z,et]);(0,r.useEffect)(()=>{q.current={request:es}},[es]),(0,r.useEffect)(()=>()=>{H.current&&clearTimeout(H.current),J.current&&clearTimeout(J.current),Y.current&&clearTimeout(Y.current),K.current&&clearTimeout(K.current),U.current&&clearTimeout(U.current),H.current=J.current=Y.current=K.current=U.current=null,F.current=!1,O.current=[]},[]),(0,r.useEffect)(()=>{if(e)return V.current!==e&&(V.current=e,F.current=!1,Z(),E(!1),$(!1)),I.current(e),et()},[e,et,Z]),(0,r.useEffect)(()=>{if(!a)return;let e=G.current;e&&(G.current=null,"reconnect"===e?es():en())},[a,es,en]),(0,r.useEffect)(()=>{if(!n||!e)return;let t=()=>{document.hidden||en()},s=()=>{if(!X.current){G.current="reconnect";return}es()};return n.on("connect",s),document.addEventListener("visibilitychange",t),document.addEventListener("resume",t),()=>{n.off("connect",s),document.removeEventListener("visibilitychange",t),document.removeEventListener("resume",t)}},[n,e,en,es]);let ea=(0,r.useRef)(!0);(0,r.useEffect)(()=>{let e=ea.current;if(ea.current=j,j&&!e){if(!X.current){G.current="reconnect";return}es()}},[j,es]),(0,r.useEffect)(()=>{if(!n||!e)return;let t="",s="",r=null,a=[],l=!1,i=()=>{null!=r&&cancelAnimationFrame(r),r=null;let n=t,a=s;t="",s="",(n||a)&&oq.getState().appendStream(e,n,a)},o=()=>{l=!1;let t=a;a=[];let s=z.current;for(let n of t)n.stream?oq.getState().appendStream(e,n.data.text,n.data.thinking):s(e,n.event,n.data)},c=(e,n)=>{if("cli_event"!==e&&(t||s)){let e={stream:!0,data:{text:t,thinking:s}};t="",s="",null!=r&&(cancelAnimationFrame(r),r=null),a.push(e)}a.push({event:e,data:n}),l||(l=!0,queueMicrotask(o))},d=n=>{var a,l,o,d;if(!n||n.sessionId!==e)return;if(F.current)return void O.current.push(n);let u="delta"===n.event||"thinking"===n.event;if("conversation_reset"===n.event){L.current=0,D.current++,M.current=n.data?.fromSeq??0,S(!!n.data?.hasMore),c(n.event,n.data);return}if(a=n.seq,l=L.current,null==a||!(a<=(l||0))){if(null!=n.seq&&(L.current=n.seq),u)return void(o=n.event,(d=n.data?.text)&&("delta"===o?t+=d:s+=d,null==r&&(r=requestAnimationFrame(i))));c(n.event,n.data)}};return n.on("ai:event",d),()=>{n.off("ai:event",d),i()}},[n,e,A]);let el=(0,r.useCallback)((t,{attachments:n=null}={})=>{if(!t&&!n?.length)return;let r=l.current||Q.getState().bus;sc.getState().clearNotification(e),r?.emit("ai:prompt",{sessionId:e,message:t,cwd:s,...n?.length?{attachments:n}:{}})},[e,s]),ei=(0,r.useCallback)(t=>{let s=oq.getState().bySession[e]?.queue||[];oq.getState().setQueue(e,s.filter(e=>e.id!==t));let n=l.current||Q.getState().bus;n?.emit("ai:queueRemove",{sessionId:e,id:t})},[e]),eo=(0,r.useCallback)(()=>{oq.getState().setQueue(e,[]);let t=l.current||Q.getState().bus;t?.emit("ai:queueClear",{sessionId:e})},[e]),ec=(0,r.useCallback)((t,s,n="",r=null)=>{let a=l.current||Q.getState().bus;if(!a)return;let i=!1,o=null,c=n=>{if(!i){if(i=!0,clearTimeout(o),n?.ok||n?.reason==="stale")return void g(e,t);(0,v.Lq)("ai-gate","resolve failed",{requestId:t,behavior:s,res:n??"timeout"}),oq.getState().setGateError(e,t)}};r?a.emit("ai:question",{sessionId:e,requestId:t,answers:r},c):a.emit("ai:permission",{sessionId:e,requestId:t,behavior:s,message:n},c),o=setTimeout(()=>c(null),nt.GX)},[e,g]),ed=(0,r.useCallback)(()=>{let t=l.current||Q.getState().bus;t?.emit("ai:stop",{sessionId:e})},[e]),eu=(0,r.useCallback)(t=>{if(!t)return;let s=l.current||Q.getState().bus;s?.emit("ai:stopTask",{sessionId:e,taskId:t})},[e]),em=(0,r.useCallback)(e=>{el(`! ${e}`)},[el]),ex=(0,r.useCallback)(async()=>{let t=l.current||Q.getState().bus;if(!t)return null;let s=await new Promise(s=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(a),s(e))},a=setTimeout(()=>r(null),4e3);t.emit("ai:rewind",{sessionId:e,action:"list"},r)});return s?s.support?.conversation?s.ok?{supported:!0,ok:!0,points:s.points||[],support:s.support}:{supported:!0,ok:!1,points:[],support:s.support}:{supported:!1,ok:!1,points:[],support:s.support}:null},[e]),ep=(0,r.useCallback)(async(t,n,{files:r=!0,preview:a=!1,index:i=null}={})=>{let o=l.current||Q.getState().bus;if(!o)return{ok:!1,error:"Not connected to the host."};let c=await new Promise(s=>{let n=!1,l=e=>{n||(n=!0,clearTimeout(c),s(e))},c=setTimeout(()=>l(null),a?4e3:13e4);o.emit("ai:rewind",{sessionId:e,action:a?"preview":"apply",messageId:t,index:i,files:r},l)});return(a||c&&c.ok||er(),c)?(c.ok&&!a&&n&&o.emit("ai:prompt",{sessionId:e,message:n,cwd:s}),c):{ok:!1,error:"The host did not answer in time."}},[e,s,er]),eh=(0,r.useCallback)((e,{files:t=!0,index:s=null}={})=>ep(e,null,{files:t,preview:!0,index:s}),[ep]),ef=(0,r.useCallback)(t=>{if(!t)return;oq.getState().setPermissionMode(e,t),oq.getState().clearBlocked(e);let s=l.current||Q.getState().bus;s?.emit("ai:options",{sessionId:e,options:{mode:t}})},[e]),eb=(0,r.useCallback)(()=>{oq.getState().clearBlocked(e)},[e]);return{hydrating:C,synced:R,hydrateFailed:_,hasOlder:N,loadOlder:(0,r.useCallback)(async()=>{if(P.current)return!1;let s=l.current||Q.getState().bus;if(!s)return!1;P.current=!0;let n=M.current;try{let r=Date.now(),{messages:a,before:l,hasMore:i,answered:o,chunks:c}=await oG({startSeq:n,estimateBytes:oV,fetchChunk:t=>new Promise(n=>{let r=!1,a=e=>{r||(r=!0,clearTimeout(l),n(e))},l=setTimeout(()=>a(null),4e3);s.emit("aiHistory",{sessionId:e,before:t},a)}),reduceChunk:(s,n)=>{let r=oq.getState().bySession[e];return o0(s,t,(r?.messages?.length||0)+n+1).messages}});if((0,v.Lq)("ai-page","loadOlder",{sessionId:e,before:n,ms:Date.now()-r,transport:s.transport||s.carrier||"?",chunks:c,messages:a.length,bytes:Math.round(a.reduce((e,t)=>e+oV(t),0)/1024)+"KB",hasMore:i}),M.current!==n||!o||(M.current=l,S(i),!a.length))return!1;return oq.getState().prependMessages(e,a),!0}finally{P.current=!1}},[e,t]),reload:er,sendPrompt:el,removeQueueItem:ei,clearQueue:eo,resolvePermission:ec,stop:ed,stopTask:eu,runShell:em,rewindToMessage:ep,previewRewind:eh,listRewindPoints:ex,escalateMode:ef,dismissBlocked:eb}}({sessionId:e,engine:t,workspacePath:s,bus:l,isVisible:o}),K=(0,r.useCallback)(()=>{(0,t7.e)(),w(!0),F(),setTimeout(()=>w(!1),700)},[F]),H=oq(t=>t.bySession[e]?.activePermission),U=!!oq(t=>t.bySession[e]?.isTurnRunning),q=oq(t=>t.bySession[e]?.gateError),V=oq(t=>t.bySession[e]?.activeBlocked),X=oq(t=>t.bySession[e]?.metadata)||ds,G=oq(t=>t.bySession[e]?.tasks)||dn,J=oq(e=>e.setPermissionMode),Y=sc(t=>e?t.sessionStatus[e]?.state:null)||"idle",Z=tS(e=>e.terminalBackgroundOpacity),ee=tS(e=>e.customBackgrounds),et=tS(e=>e.terminalBackgrounds),es=tS(t=>t.backgroundBySession[e]),en=tS(e=>e.terminalTheme),er=tS(e=>e.fontSize),ea=tS(e=>e.showFolderButton),el=tS(e=>e.showNoteButton),ei=tS(e=>e.setRightPanelRoot),eo=tS(e=>e.setRightPanelTab),ec=tS(e=>e.openRightPanel),ed=tS(t=>t.artifactsBySession[e]),eu=al(s,i,{enabled:c&&ea}),{theme:em}=(0,aT.D)(),ex=(0,r.useMemo)(()=>(0,ax.In)(em,en),[em,en]),ep=(0,r.useMemo)(()=>ew(er)+(d?nt.TQ:nt.wM),[er,d]),eh=(0,r.useMemo)(()=>{let{alpha:e,size:t}=nt.ii,s=`radial-gradient(color-mix(in srgb, ${ex.foreground} ${e}%, transparent) 1px, transparent 1px) 0 0 / ${t}px ${t}px`,n=e$(es,et,ee,u),r="dark"===em?eR(n,ee):null;if(r){let e=`rgba(${ek},${Z??.8})`,t=`rgba(${ej},0.28)`;return{background:`${s}, linear-gradient(${e},${e}), linear-gradient(${t},${t}), center / cover no-repeat url("${r}")`,backgroundBlendMode:"luminosity, normal, screen, normal"}}return{background:`${s}, ${ex.background}`}},[et,es,ee,Z,ex,em,u]),ef=X.skills||[],eb=X.mcpServers||[],eg=(0,r.useCallback)(e=>{S(`/${e}`)},[S]),ev=(0,r.useCallback)(t=>{let s=l?.emit?l:Q.getState().bus;s?.emit?.("ai:options",{sessionId:e,options:t})},[l,e]),ey=(0,r.useCallback)(t=>{oq.getState().setMetadata(e,{model:t}),ev({model:t})},[ev,e]),eN=(0,r.useCallback)(e=>{e?.sessionId&&ev({resume:e.sessionId})},[ev]),eS=(0,r.useCallback)(e=>{if(e)return eN(e);g("sessions")},[eN]),eC=(0,r.useCallback)((t,s)=>{t&&("effort"===t&&oq.getState().setMetadata(e,{effort:s}),ev({[t]:s}))},[ev,e]),eT=(0,om.Tw)(t),eE=(0,r.useCallback)(t=>{J(e,t),ev({mode:t})},[ev,e,J]),e_=(0,r.useCallback)((t,s)=>{oq.getState().rewindToMessage(e,t,s)},[e]),eM=(0,r.useCallback)(t=>{if(!b&&t.shiftKey&&"Tab"===t.key){t.preventDefault(),(0,t7.e)();let s=eT.permissionModes||[],n=oq.getState().bySession[e]?.permissionMode||eT.defaultMode,r=s.findIndex(e=>e.id===n),a=-1===r?0:(r+1)%s.length,l=s[a]?.id;l&&eE(l)}},[e,eT,eE,b]),eP=aR({isFocused:c,onActivate:()=>m?.()}),eA=(0,r.useRef)(m);(0,r.useEffect)(()=>{eA.current=m});let ez=(0,r.useCallback)(()=>eA.current?.(),[]),eI=(0,r.useMemo)(()=>({sessionId:e,isFocused:c,activate:ez}),[e,c,ez]);return(0,n.jsx)(cr.fe.Provider,{value:eI,children:(0,n.jsxs)("div",{...eP,onKeyDown:eM,className:"ai-pane w-full h-full flex flex-col bg-bg overflow-hidden relative select-text",style:{...eh,"--color-text":ex.foreground,"--ai-fs":`${ep}px`},children:[(0,n.jsxs)("div",{style:{height:26},className:"sm:hidden flex items-center gap-2 px-2 border-b border-border-subtle bg-surface/70 backdrop-blur-sm text-[11px] select-none shrink-0 relative z-10",children:[(0,n.jsx)("span",{className:`w-1.5 h-1.5 rounded-full flex-shrink-0 ${nU(Y)}`,style:{background:nH(Y).dot}}),(0,n.jsx)("span",{className:"flex-1 min-w-0 truncate text-text",children:a||nt.UB[t]?.label||t}),(0,n.jsx)(aC,{onOpenRemote:x,onOpenMobile:p})]}),c&&(0,n.jsxs)("div",{className:"absolute right-2 z-10 flex flex-col items-end gap-2 pointer-events-auto touch-none top-9 sm:top-2",children:[(0,n.jsxs)("div",{className:"flex flex-row gap-2",children:[el&&(0,n.jsx)("button",{onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onTouchStart:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>{e.stopPropagation(),(0,t7.e)(),j(!0)},className:aE,title:N("terminalPane.note"),children:(0,n.jsx)(t3.y8,{size:16,className:a_})}),(0,n.jsx)("button",{onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onTouchStart:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>{e.stopPropagation(),K()},className:aE,title:N("terminalPane.refresh"),children:(0,n.jsx)(t3.e9,{size:16,className:`${a_} ${y?"animate-spin":""}`})})]}),ea&&s&&(0,n.jsxs)("button",{onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onTouchStart:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>{e.stopPropagation(),(0,t7.e)(),ei(s,s),window.innerWidth>=760?eo("files",s):ec()},className:`relative ${aE}`,title:N("terminalPane.openFolderHere"),children:[(0,n.jsx)(t3.vd,{size:16,className:a_}),eu>0&&(0,n.jsx)("span",{className:"absolute -top-1 -right-1 min-w-[16px] h-4 px-1 flex items-center justify-center text-[10px] font-semibold text-white bg-brand-500 rounded-full",children:eu>999?"999+":eu})]}),h&&ed?.length>0&&(0,n.jsxs)("button",{onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onTouchStart:e=>{e.preventDefault(),e.stopPropagation()},onClick:t=>{t.stopPropagation(),(0,t7.e)(),h(e,ed[0])},className:`relative ${aE}`,title:N("terminalPane.artifacts"),children:[(0,n.jsx)(t3.sU,{size:16,className:a_}),(0,n.jsx)("span",{className:"absolute -top-1 -right-1 min-w-[16px] h-4 px-1 flex items-center justify-center text-[10px] font-semibold text-white bg-brand-500 rounded-full",children:ed.length})]})]}),(0,n.jsx)(cY,{sessionId:e}),(0,n.jsx)(de,{sessionId:e,engine:t,onStopTask:_}),(0,n.jsx)(cR,{sessionId:e,engine:t,workspacePath:s,fileBus:i,onSendPrompt:S,onResolvePermission:R,onRewind:M,onPreviewRewind:P,onListRewindPoints:A,onCutLocal:e_,hasOlder:L,onLoadOlder:D,onOpenResume:eS,hydrating:O,synced:B,hydrateFailed:W,onReload:F}),V&&!H&&(0,n.jsx)("div",{className:"px-3 pb-2 select-none animate-in fade-in slide-in-from-bottom-2 duration-150 flex-shrink-0 z-30",children:(0,n.jsx)(cG,{engine:V.engine||t,message:V.message,escalate:V.escalate,onEscalate:z,onDismiss:I})}),H&&(0,n.jsx)("div",{className:"px-3 pb-2 select-none animate-in fade-in slide-in-from-bottom-2 duration-150 flex-shrink-0 z-30",children:"AskUserQuestion"===H.tool?(0,n.jsx)(ct.J,{requestId:H.requestId,questions:H.input?.questions||[],failed:q,onResolve:R}):(0,n.jsx)(cX,{requestId:H.requestId,tool:H.tool,input:H.input,failed:q,onResolve:R})}),(0,n.jsx)(cM,{sessionId:e,engine:t,onSend:S,onRemoveQueueItem:C,onClearQueue:T,onStop:E,onRunShell:$,onResolvePermission:R,onSelectModel:ey,onModeChange:eE,onOpenModal:g,onOptionChange:eC,onActivate:m,isFocused:c,fileBus:i,workspacePath:s,modalOpen:null!==b}),(0,n.jsx)(cA,{sessionId:e,sessionName:a,engine:t,workspacePath:s,isDesktop:d,onModeChange:eE,onNewChat:f}),"skills"===b&&(0,n.jsx)(cz,{skills:ef,onClose:()=>g(null),onSelectSkill:eg}),"mcp"===b&&(0,n.jsx)(cI,{mcpServers:eb,onClose:()=>g(null)}),"model"===b&&(0,n.jsx)(cL,{currentModel:X.model,currentEffort:X.effort||"",models:X.modelOptions?.length?X.modelOptions:eT.models,isTurnRunning:U,onClose:()=>g(null),onSelectModel:ey,onSelectEffort:e=>ev({effort:e})}),"sessions"===b&&(0,n.jsx)(cD,{engine:t,workspacePath:s,onClose:()=>g(null),onResume:eN}),"config"===b&&(0,n.jsx)(cB,{engine:t,options:oq.getState().bySession[e]?.metadata,onClose:()=>g(null),onApply:e=>ev(e)}),"mode"===b&&(0,n.jsx)(cK,{modes:eT.permissionModes||[],currentMode:oq.getState().bySession[e]?.permissionMode||eT.defaultMode,onClose:()=>g(null),onSelectMode:eE}),"doctor"===b&&(0,n.jsx)(cH,{engine:t,workspacePath:s,onClose:()=>g(null)}),"tasks"===b&&(0,n.jsx)(cq,{tasks:G,onClose:()=>g(null)}),"rewind"===b&&(0,n.jsx)(cV,{sessionId:e,onListPoints:A,onPreview:P,onApply:e=>M(e),onClose:()=>g(null)}),k&&el&&(0,n.jsx)(aS,{bus:l,sessionId:e,onClose:()=>j(!1)})]})})});class da extends r.Component{constructor(e){super(e),this.handleReset=()=>{this.setState({hasError:!1,error:null}),this.props.onReset?.()},this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){console.error("[ErrorBoundary caught error]:",e,t)}render(){return this.state.hasError?this.props.fallback?"function"==typeof this.props.fallback?this.props.fallback(this.state.error,this.handleReset):this.props.fallback:(0,n.jsxs)("div",{className:"w-full h-full min-h-[160px] flex flex-col items-center justify-center p-6 text-center select-none bg-surface/50 border border-border-subtle/40 rounded-brand m-2",children:[(0,n.jsx)(t3.RI,{size:24,className:"text-danger mb-2"}),(0,n.jsx)("div",{className:"text-sm font-semibold text-text mb-1",children:this.props.title||"Something went wrong in this pane"}),(0,n.jsx)("div",{className:"text-xs text-text-muted font-mono max-w-md truncate mb-4",children:this.state.error?.message||"Render error"}),(0,n.jsxs)("button",{type:"button",onClick:this.handleReset,className:"px-3 py-1.5 rounded bg-surface-2 hover:bg-surface-3 text-text text-xs flex items-center gap-1.5 font-medium transition-colors border border-border-subtle",children:[(0,n.jsx)(t3.e9,{size:12}),(0,n.jsx)("span",{children:"Try again"})]})]}):this.props.children}}let dl=(0,r.memo)(function({children:e}){return(0,n.jsx)("div",{className:"absolute inset-x-0 top-0 bottom-[37px] overflow-hidden",children:e})}),di=(0,r.memo)(function({sessionId:e}){let t=sc(t=>e?t.sessionStatus[e]:null),s=t?.state||"idle";return"idle"===s?null:(0,n.jsx)("div",{className:"absolute inset-x-0 bottom-0 z-20 h-[1px] pointer-events-none hidden sm:block",children:"working"===s?(0,n.jsx)(os,{}):"done"===s?(0,n.jsx)("div",{className:"w-full h-full bg-[#f59e0b]",style:{boxShadow:"0 0 4px rgba(245,158,11,0.6)"}}):"blocked"===s?(0,n.jsx)("div",{className:"w-full h-full bg-[#ef4444] animate-pulse",style:{boxShadow:"0 0 4px rgba(239,68,68,0.7)"}}):null})}),dc=(0,r.memo)(function({sessionId:e,placeholder:t}){let s=tS(t=>t.drafts[e]??"").replace(/\s+/g," ").trim();return s?(0,n.jsx)("span",{className:"text-text",children:s}):(0,n.jsx)(n.Fragment,{children:t})}),dd=(0,r.memo)(function({bus:e,busRef:t,connected:s,carrier:a,platform:l,agentVersion:i,sessions:o,workspaces:c,activeSessionId:d,activeSession:u,activeWorkspaceId:m,openedSessions:x,livePanes:p,mountedWorkspaces:h,cwdBySession:f,sessionStatus:b,notifications:g,isDesktop:v,isTerminalView:y,slideClass:w,shells:k,sidebarCollapsed:j,sidebarWidth:N,setSidebarWidth:S,toggleSidebar:C,paneWidth:T=null,setPaneWidth:R,paneRegistry:E,bindSwipeTab:_,nav:$,onBack:M,onOpenRemote:P,onOpenMobile:A,onOpenFiles:z,onLogout:I,onStopCodespace:L,onUpdate:D,onRestart:F,onRenameHost:O,onDeleteHost:B,onDeleteWorkspace:W,onRenameWorkspace:K,onReorderSession:H,onSetHiddenRepos:U,atStackBottom:q=!1,onAddWorkspace:V,onOpenSettings:X,homeDir:G,recentWorkspaces:J,rightPanel:Y,editorPanel:Z,mobilePanel:ee,onOpenArtifact:et,fileBus:es,onCreateAnyHost:en,onQuickCreateHostAware:ea,codespaceInfo:el,tunnelUrl:ei,apiKey:eo,connectionMode:ec,subscribeToPush:ed,unsubscribeFromPush:eu,updateAvailable:em,canSelfUpdate:ex}){let{t:ep}=(0,se.s)(),eh="mouse"===nk(),ef=Q(e=>e.bus),eb=Q(e=>e.busRef),eg=Q(e=>e.connected),ev=Q(e=>e.carrier),ey=e||ef,ew=t||eb,ek=(0,r.useMemo)(()=>o.filter(e=>!e.hostKey),[o]),ej=(0,r.useMemo)(()=>c.filter(e=>!e.hostKey),[c]),eN=(0,r.useCallback)(e=>{let t=function(e){if(!e)return null;let{hosts:t}=sX.getState();for(let s of Object.values(t))if(s.sessions?.some(t=>t.id===e))return sH.get(s.key)?.busRef?.current||null;return null}(e);return t||(o.find(t=>t.id===e)?.hostKey?null:ey)},[ey,o]),eS=s??eg,eC=a||ev,eT=es||t2.getState(),{panesContainerRef:eR,registerPaneApi:eE,registerPaneElement:e_,registerKeyboardTextApi:e$,handlePasteFallback:eM,handleInputFocusChange:eP,focusPane:eA,focusKeyboardInput:ez,scrollPaneIntoView:eI}=E,[eL,eD]=(0,r.useState)(null),{workspaceSessionIds:eF,workspaceOpenedSessions:eO,renderedSessions:eB,mountedSet:eW,workspaceIndex:eK}=(0,r.useMemo)(()=>(function({sessions:e,openedSessions:t,livePanes:s,mountedWorkspaces:n,activeWorkspaceId:r,isDesktop:a}){let l=new Set(e.filter(e=>eQ(e)===(r??null)).map(e=>e.id)),i=t.filter(e=>l.has(e)),o=new Set([...i,...s.filter(e=>t.includes(e))]),c=t.filter(e=>o.has(e)),d=new Map(e.map(e=>[e.id,eQ(e)])),u=new Set(t.filter(e=>!!l.has(e)||!!a&&!!n[d.get(e)??eZ])),m=new Map(i.map((e,t)=>[e,t]));return{workspaceSessionIds:l,workspaceOpenedSessions:i,renderedSessions:c,mountedSet:u,workspaceIndex:m}})({sessions:o,openedSessions:x,livePanes:p,mountedWorkspaces:h,activeWorkspaceId:m,isDesktop:v}),[o,x,p,h,m,v]),eH=(0,r.useMemo)(()=>o.filter(e=>eQ(e)===m),[o,m]),eU=(0,r.useMemo)(()=>new Map(eH.map((e,t)=>[e.id,t])),[eH]),eq=c.find(e=>e.id===m),eV=eq?.path||u?.workspacePath||null,eX=tS(e=>e.rightPanelRoots),eG=tS(e=>e.agentBySession),eJ=tS(e=>e.fullModes||{})[m??eZ]??!1,eY=tS(e=>e.hiddenPaneSessionIds||[]),e0=tS(e=>e.setRightPanelRoot),e1=tS(e=>e.openRightPanel),e2=tS(e=>e.reorderOpenedSessions),e5=(0,r.useCallback)(e=>{e2(e),H?.(e)},[e2,H]),e3=(0,r.useCallback)(e=>{$.handleSelectSession(e)},[$]),e4=!!o.find(e=>e.id===d)?.hostKey,e6=eq?.hostKey||null,e8=(0,r.useMemo)(()=>e6?{current:sq(e6)}:ew,[e6,ew]),[e9,e7]=(0,r.useState)([]),te=sX(e=>e6&&e.hosts[e6]?.status||null);(0,r.useEffect)(()=>{e6&&sq(e6)?.emit("getShells",e=>e7(e?.shells||[]))},[e6,te]);let tt=(0,r.useCallback)((e,t)=>{let s=o.filter(e=>e.id!==t&&eQ(e)===(m??null)).length+1;$.handleReplaceSession(t,`${e.short||e.label} ${s}`,e,!0)},[$,o,m]),ts=eX[eV]||eV,tn=(0,r.useCallback)(e=>Y?.onTabChange(e,eV??""),[Y,eV]),tr=(0,r.useCallback)(()=>z?.(ts),[z,ts]),ta=(0,r.useMemo)(()=>eq?.hiddenRepos||[],[eq?.hiddenRepos]),tl=(0,r.useCallback)(e=>{eq&&U?.(eq.id,e)},[eq,U]),ti=d&&(f[d]||o.find(e=>e.id===d)?.cwd)||null;(0,r.useEffect)(()=>{e0(eV,null)},[d,eV,e0]);let to=!o.length,[tc,td]=(0,r.useState)(!1);Y?.open&&!tc&&td(!0);let[tu,tm]=(0,r.useState)(!1);!Y?.open&&tu&&tm(!1),(0,r.useEffect)(()=>{if(!Y?.open)return;let e=requestAnimationFrame(()=>tm(!0));return()=>cancelAnimationFrame(e)},[Y?.open]);let tx=!!Z?.filePath,[tp,th]=(0,r.useState)(!1);tx&&!tp&&th(!0);let[tf,tb]=(0,r.useState)(!1);!tx&&tf&&tb(!1);let[tg,tv]=(0,r.useState)(null);tx&&tg?.filePath!==Z.filePath&&tv({filePath:Z.filePath,artifactTitle:Z.artifactTitle,previewSeq:Z.previewSeq}),(0,r.useEffect)(()=>{if(!tx)return;let e=requestAnimationFrame(()=>tb(!0));return()=>cancelAnimationFrame(e)},[tx]);let[ty,tw]=(0,r.useState)(0),[tk,tj]=(0,r.useState)(!1),tN=(0,r.useRef)(null);(0,r.useEffect)(()=>{if(!v)return;let e=tN.current;if(!e)return;let t=new ResizeObserver(e=>tw(e[0].contentRect.width));return t.observe(e),()=>t.disconnect()},[v]),(0,r.useEffect)(()=>{if(!eS||!ey?.emit)return;let e=!1,t=()=>ey.emit("bg:get",{},t=>{!e&&t?.success&&t.dataUrl&&tS.getState().setCustomBackgrounds([{id:"custom",dataUrl:t.dataUrl}])}),s=setTimeout(()=>{e||t()},4e3);return ey.emit("bg:list",{},n=>{e||(clearTimeout(s),n?.success&&Array.isArray(n.items)?tS.getState().setCustomBackgrounds(n.items):t())}),()=>{e=!0,clearTimeout(s)}},[eS,ey]);let tC=(0,r.useMemo)(()=>eO.filter(e=>!eY.includes(e)),[eO,eY]).length,tT=tS(e=>e.autoPaneWidths[m]??null),tR=tS(e=>e.setAutoPaneWidth),tE=(Y?.open&&tu?Y.width:0)+(tx&&tf?Z.width:0)+(ee?.open&&"pin"===ee.mode?ee.width:0),t_=function({rowWidth:e,paneCount:t,sidebarWidth:s,sidePx:n,gapPx:r,paddingPx:a,minWidth:l,applied:i}){if(!(e>0)||t<=0)return null;let o=Math.max(l,Math.floor((e-s-a-n-(t-1)*r)/t));return null==i?o:Math.min(i,o)}({rowWidth:ty,paneCount:tC,sidebarWidth:j?0:N,sidePx:tE,gapPx:2,paddingPx:0,minWidth:er.min,applied:tT});(0,r.useEffect)(()=>{null!=t_&&tR(m,t_)},[t_,m,tR]);let t$=(0,r.useRef)({paneWidth:T,paneCount:tC,sidebarWidth:N,rowWidth:ty});(0,r.useEffect)(()=>{let e=t$.current;t$.current={paneWidth:T,paneCount:tC,sidebarWidth:N,rowWidth:ty},(e.paneWidth!==T||e.paneCount!==tC||e.sidebarWidth!==N||e.rowWidth!==ty)&&tR(m,null)},[T,tC,N,ty,m,tR]);let tM=T??t_,tP=(0,r.useRef)({editorFile:Z?.filePath,rightOpen:Y?.open});(0,r.useEffect)(()=>{if(!v||!d)return;let e=tP.current,t=e.editorFile!==Z?.filePath||e.rightOpen!==Y?.open;if(tP.current={editorFile:Z?.filePath,rightOpen:Y?.open},!t)return;let s=setTimeout(()=>{eI(d)},260);return()=>clearTimeout(s)},[Z?.filePath,Y?.open,d,v,eI]),(0,r.useEffect)(()=>{v&&eJ&&eR.current&&(eR.current.scrollLeft=0)},[v,eJ,eR]);let tA=e=>{let t=tM??e.currentTarget.parentElement?.offsetWidth??er.min;tj(!0),sS(e,{startWidth:t,onWidth:e=>R?.(e),onEnd:()=>tj(!1)})},tz=(0,r.useCallback)(()=>{tR(m,null),R?.(null)},[m,tR,R]),[tI,tL]=(0,r.useState)(null),tD=(0,r.useRef)(null),tF=rE(tD,tI?.x??0,tI?.y??0),tO=(0,r.useCallback)(e=>{e.preventDefault(),e.stopPropagation(),tL({x:e.clientX,y:e.clientY})},[]),tB=(0,r.useCallback)(e=>{if("auto"===e)tz();else{let t=eR.current?.clientWidth||ty-(j?0:N)-tE;if(t>0){let s=Math.max(er.min,Math.floor((t-(e-1)*2)/e));tR(m,null),R?.(s)}}tL(null)},[tz,eR,ty,j,N,tE,m,tR,R]);(0,r.useEffect)(()=>{if(!tI)return;let e=e=>{tD.current&&!tD.current.contains(e.target)&&tL(null)},t=e=>{"Escape"===e.key&&tL(null)};return document.addEventListener("mousedown",e),document.addEventListener("touchstart",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("mousedown",e),document.removeEventListener("touchstart",e),document.removeEventListener("keydown",t)}},[tI]),(0,r.useEffect)(()=>{let e=()=>tz();return window.addEventListener("terminal:fitPanes",e),()=>window.removeEventListener("terminal:fitPanes",e)},[tz]),(0,r.useEffect)(()=>{let e=e=>{e.detail?.fraction&&tB(e.detail.fraction)};return window.addEventListener("terminal:splitPreset",e),()=>window.removeEventListener("terminal:splitPreset",e)},[tB]);let tW=(e,t,s,r=0)=>{let a=o.find(t=>t.id===e),l=eG[e],i=nt.H8.find(e=>e.id===l);return i?(0,n.jsx)(da,{title:"AI Chat Pane",children:(0,n.jsx)(dr,{sessionId:e,engine:i.aiEngine,workspacePath:a?.cwd||a?.workspacePath||eq?.path,sessionName:a?.name,bus:ey,fileBus:eT,isVisible:t,isFocused:s,isDesktop:v,bgIndex:r,onActivate:()=>$.handleSelectSession(e),onNewChat:()=>tt(i,e),onOpenRemote:P,onOpenMobile:A,onOpenArtifact:et})},e):(0,n.jsx)(a$,{workspacePath:a?.workspacePath,sessionName:a?.name,bus:eN(e),connected:eS,sessionId:e,isVisible:t,isFocused:s,onActivate:$.handleSelectSession,onRegisterApi:eE,onPasteFallback:eM,showFocusBorder:!1,mountDelay:!s&&eK.has(e)?120*eK.get(e):0,bgIndex:r,onOpenArtifact:et,onOpenRemote:P,onOpenMobile:A})},tK=e=>(0,n.jsx)(nW,{bus:eN(e),sessionId:e,onExpandChange:()=>{},onRefocus:()=>eA(e),onRegisterTextApi:e$,onInputFocusChange:eP,platform:l,onInput:sc.getState().clearNotification,onSwitchSession:$.switchSession,onSwitchToIndex:$.switchToIndex,isDesktop:v,statusStrip:(0,n.jsx)(ln,{sessionId:e,busRef:ew,onReveal:t=>{let s=o.find(t=>t.id===e)?.workspacePath;e0(s,t||s),e1()}})});return(0,n.jsxs)("div",{className:`absolute inset-0 flex flex-col ${y?"translate-x-0 opacity-100 z-10":"translate-x-full opacity-0 z-0 pointer-events-none"}`,children:[(0,n.jsxs)("div",{ref:tN,className:`flex-1 min-h-0 relative ${v?"flex flex-row":"flex flex-col"}`,children:[v&&(0,n.jsx)("div",{className:"hidden sm:block overflow-hidden flex-shrink-0 transition-[width] duration-200 ease-out",style:{width:j?0:N},children:(0,n.jsx)(aZ,{allSessions:ek,workspaces:ej,activeSessionId:d,activeWorkspaceId:m,onSelectSession:$.handleSelectSession,onSelectWorkspace:$.handleSelectWorkspace,onCreateNamedSession:$.handleCreateSession,onResumeAgentSession:e4?null:$.handleResumeAgentSession,shells:k,onRenameSession:$.handleRenameSession,onDeleteSession:$.handleDeleteSession,onReorderSession:e5,onDeleteWorkspace:W,onAddWorkspace:V,onRenameWorkspace:K,onOpenSettings:X,onLogout:I,onRenameHost:O,onDeleteHost:B,busRef:ew,homeDir:G,cwdBySession:f,connected:eS,width:N,onResize:S,onCollapse:C})}),(0,n.jsxs)("div",{className:"flex-1 min-w-0 min-h-0 flex flex-col",children:[(!to||!v)&&(0,n.jsx)(ae,{sessions:eH,allSessions:o,activeSessionId:d,isActive:y,connected:eS,onSwitchSession:e3,onCreateSession:e6?ea:$.handleQuickCreateSession,onRenameSession:$.handleRenameSession,onDeleteSession:$.handleDeleteSession,onCreateNamedSession:en,modalBusRef:e8,modalHostKey:e6||"main",modalShells:e6?e9:null,onResumeAgentSession:e4?null:$.handleResumeAgentSession,onBack:v||q?null:M,workspaces:c,activeWorkspaceId:m,onSelectWorkspace:$.handleSelectWorkspace,hasUngrouped:o.some(e=>!eQ(e)),onOpenRemote:P,onOpenMobile:A,onOpenFiles:z,onLogout:I,onStopCodespace:L,onUpdate:D,onRestart:F,codespaceInfo:el,tunnelUrl:ei,apiKey:eo,connectionMode:ec,subscribeToPush:ed,unsubscribeFromPush:eu,agentVersion:i,updateAvailable:em,canSelfUpdate:ex,busRef:ew,carrier:eC,shells:k,onToggleSidebar:v?C:null,sidebarCollapsed:j,onReorderSession:e5,onToggleRightPanel:Y?.onToggle,rightPanelOpen:Y?.open,fileBus:eT,homeDir:G,isDesktop:v}),to?(0,n.jsx)("div",{className:"flex-1 min-h-0",children:(0,n.jsx)(or,{onAddWorkspace:V,onOpenRemote:P,recent:J,homeDir:G,onOpenRecent:e=>V?.(e)})}):(0,n.jsx)("div",{ref:eR,className:`flex-1 min-h-0 ${v?`flex flex-row ${eJ?"overflow-hidden":"overflow-x-auto"} overflow-y-hidden px-0 pb-0 scrollbar-none`:"relative"}`,..._({enabled:!v,sessionIds:eO,activeSessionId:d,onSwitch:$.handleSelectSession}),children:eB.map(e=>{let t=eF.has(e),s=e===d,r=eY.includes(e),a=t&&!r&&(v&&!eJ||s),l=eU.get(e)??0;return(0,n.jsxs)("div",{ref:t=>e_(e,t),className:!t||v&&eJ&&!s||v&&r?"hidden":v?`h-full relative bg-bg ${eJ?"w-full flex-1":`border-r-2 border-border-subtle last:border-r-0 ${tk?"":"transition-[width] duration-200 ease-out"}`}`:`absolute inset-0 ${s?`opacity-100 z-10 ${w}`:"opacity-0 z-0 pointer-events-none"}`,style:t&&v?eJ?{width:"100%",flex:"1 1 0"}:null!=tM?{width:tM,flexShrink:0}:{flex:"1 1 0",minWidth:er.min}:void 0,children:[eW.has(e)?eG[e]?.endsWith("-ui")?(0,n.jsx)("div",{onMouseDown:()=>{s||$.handleSelectSession(e)},onTouchStart:()=>{s||$.handleSelectSession(e)},className:"w-full h-full flex flex-col relative overflow-hidden",children:tW(e,a,s,l)}):v?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)(dl,{children:[tW(e,a,s,l),(0,n.jsx)(di,{sessionId:e})]}),(0,n.jsx)("div",{className:"absolute inset-x-0 bottom-0 z-20 border-t border-border-subtle bg-surface",children:s?tK(e):(0,n.jsx)("button",{type:"button",tabIndex:-1,onClick:()=>{$.handleSelectSession(e),setTimeout(ez,60)},className:"group block w-full text-left","aria-label":"Focus this terminal input",children:(0,n.jsx)("span",{className:"block w-full pl-9 pr-16 py-2 text-sm text-text-muted/60 group-hover:bg-surface-2/70 group-hover:text-text-muted transition-colors truncate",children:(0,n.jsx)(dc,{sessionId:e,placeholder:ep("mobileKeyboard.typeCommand")})})})})]}):tW(e,a,s,l):(0,n.jsx)("div",{className:"w-full h-full flex items-center justify-center text-text-muted text-xs"}),t&&v&&!eJ&&!r&&(0,n.jsx)("div",{onPointerDown:tA,onDoubleClick:tz,onContextMenu:tO,className:"absolute top-0 right-0 bottom-0 w-1 cursor-col-resize hover:bg-brand-500/40 transition-colors z-30",title:eh?s9(ep("shortcuts.fitPanes")||"Auto-fit panes","fitPanes"):void 0})]},e)})}),!v&&d&&!eG[d]?.endsWith("-ui")&&tK(d)]}),(Z?.filePath||v&&tp)&&(0,n.jsx)("div",{className:v?"overflow-hidden flex-shrink-0 transition-[width] duration-200 ease-out":"absolute inset-0 z-40 animate-in slide-in-from-bottom duration-200",style:v?{width:tx&&tf?Z.width:0}:void 0,"aria-hidden":v&&!tx,children:(0,n.jsx)(oe,{filePath:tx?Z.filePath:tg?.filePath,artifactTitle:tx?Z.artifactTitle:tg?.artifactTitle,previewSeq:tx?Z.previewSeq:tg?.previewSeq,workspace:ts,fileBus:eT,width:Z.width,onResize:Z.onResize,onClose:Z.onClose,onOpenFull:Z.onOpenFull,onOpenFile:Z.onOpen,isDesktop:v})}),v&&ee?.open&&"pin"===ee.mode&&(0,n.jsx)("div",{ref:eD,className:"relative overflow-hidden flex-shrink-0 border-l border-border",style:{width:ee.width},children:(0,n.jsx)("div",{onPointerDown:ee.onResizeStart,className:"absolute top-0 left-0 bottom-0 w-1 cursor-col-resize hover:bg-brand-500/40 transition-colors z-20"})}),v&&ee?.open&&(0,n.jsx)(lv,{busRef:ew,protocolRef:ee.protocolRef,connected:eS,pinSlot:eL}),Y?.open&&!v&&(0,n.jsx)("div",{className:"absolute inset-0 z-20 bg-black/50 animate-in fade-in duration-200",onClick:Y.onToggle}),(Y?.open||v&&tc)&&(0,n.jsx)("div",{className:v?"overflow-hidden flex-shrink-0 transition-[width] duration-200 ease-out":"absolute inset-y-0 right-0 z-30 w-[85%] max-w-sm shadow-elev animate-in slide-in-from-right duration-200",style:v?{width:Y?.open&&tu?Y.width:0}:void 0,"aria-hidden":v&&!Y?.open,children:(0,n.jsx)(iw,{workspacePath:eV,filesRoot:ts,cwdHint:ti,activeFile:Z?.filePath,fileBus:eT,tab:Y.tabs?.[eV??""]||"files",onTabChange:tn,width:Y.width,onResize:Y.onResize,onClose:Y.onToggle,onOpenFiles:z?tr:null,onOpenFile:Z?.onOpen,onNewTerminal:Y.onNewTerminal,onAddWorkspace:V,homeDir:G,hiddenRepos:ta,onHiddenReposChange:eq&&U?tl:null,isDesktop:v})})]}),(0,n.jsx)(ot,{}),v&&!to&&(0,n.jsx)(lr,{cwd:d&&(f[d]||u?.cwd||eq?.path)||"",sessionId:d,busRef:ew,fileBus:eT,connected:eS,carrier:eC,sessionName:u?u?.name:"",agentVersion:i,platform:l,homeDir:G}),tI&&(0,n.jsxs)("div",{ref:tD,className:"fixed z-[70] menu-popover p-1 min-w-[130px] animate-in fade-in zoom-in-95 duration-100 shadow-xl",style:{left:tF.left,top:tF.top},children:[(0,n.jsx)("div",{className:"px-2 py-1 text-[10px] font-semibold text-text-subtle uppercase tracking-wider",children:"Split"}),(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),tB("auto")},className:"w-full text-left px-2 py-1.5 text-xs text-text hover:bg-surface-2/80 rounded-[6px] flex items-center justify-between",children:[(0,n.jsx)("span",{children:"Auto Fit"}),(0,n.jsx)("span",{className:"text-[10px] text-text-muted",children:"Auto"})]}),(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),tB(2)},className:"w-full text-left px-2 py-1.5 text-xs text-text hover:bg-surface-2/80 rounded-[6px] flex items-center justify-between",children:[(0,n.jsx)("span",{children:"1/2"}),(0,n.jsx)("span",{className:"text-[10px] text-text-muted",children:"50%"})]}),(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),tB(3)},className:"w-full text-left px-2 py-1.5 text-xs text-text hover:bg-surface-2/80 rounded-[6px] flex items-center justify-between",children:[(0,n.jsx)("span",{children:"1/3"}),(0,n.jsx)("span",{className:"text-[10px] text-text-muted",children:"33%"})]}),(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),tB(4)},className:"w-full text-left px-2 py-1.5 text-xs text-text hover:bg-surface-2/80 rounded-[6px] flex items-center justify-between",children:[(0,n.jsx)("span",{children:"1/4"}),(0,n.jsx)("span",{className:"text-[10px] text-text-muted",children:"25%"})]})]})]})});var du=s(45111);function dm({label:e}){let{t}=(0,se.s)();return(0,n.jsxs)("div",{className:"fixed inset-0 z-40 flex items-center justify-center animate-in fade-in duration-300",children:[(0,n.jsx)("div",{className:"cine-bg","aria-hidden":!0,children:(0,n.jsx)("div",{className:"cine-grid"})}),(0,n.jsxs)("div",{className:"relative z-10 flex flex-col items-center gap-3 px-6 text-center",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("span",{className:"w-2 h-2 rounded-full bg-text animate-pulse-glow"}),(0,n.jsx)("span",{className:"text-[15px] font-semibold text-text tracking-wide",children:"9Remote"})]}),(0,n.jsx)(du.A,{size:"lg"}),(0,n.jsx)("p",{className:"text-sm text-text-muted",children:e||t("connection.retrying")})]})]})}var dx=s(30240);function dp({agentId:e,tool:t}){let[s,a]=(0,r.useState)(!1);return s?(0,n.jsx)(t3.BK,{size:14,className:"text-text-muted flex-shrink-0"}):e?.endsWith("-ui")?(0,n.jsx)("img",{src:s$(e),alt:"",onError:()=>a(!0),className:`w-3.5 h-3.5 flex-shrink-0 object-contain ${s_}`}):nV[t]?(0,n.jsx)("img",{src:nV[t],alt:t,className:`w-3.5 h-3.5 flex-shrink-0 object-contain ${s_}`}):(0,n.jsx)(t3.BK,{size:14,className:"text-text-muted flex-shrink-0"})}function dh({sessions:e,cwdBySession:t={},connected:s,onSelect:a,onCreate:l,onDelete:i,onRename:o,onLogout:c,onOpenRemote:d,onOpenMobile:u,tunnelUrl:m,apiKey:x,connectionMode:p="tunnel",codespaceInfo:h,codespaceDisconnected:f,onStopCodespace:b,isActive:g=!0,busRef:v,subscribeToPush:y,unsubscribeFromPush:w,onResumeAgentSession:k=null,notifications:j,sessionStatus:N,agentVersion:S,updateAvailable:C=null,canSelfUpdate:T=!1,onUpdate:R,onRestart:E,carrier:_,workspaces:$=[],onRenameWorkspace:M,onDeleteWorkspace:P,onAddWorkspace:A,fileBus:z,homeDir:I,recentWorkspaces:L=[],shells:D=[],onReorderSession:F,onRenameHost:O=null,onDeleteHost:B=null}){let W,{t:K}=(0,se.s)(),H=z||t2.getState(),U=Object.values(sX(e=>e.hosts)),q=U.find(e=>"full"===e.status),V=Q(e=>e.connected),X=Q(e=>e.carrier),G=Q(e=>e.busRef),J=s??V,Y=_||X||"ws",Z=v||G,ee=sc(e=>e.notifications),et=sc(e=>e.sessionStatus),es=j||ee,en=N||et,er=si(e=>e.open),ea=si(e=>e.setContext),el=si(e=>e.setCallbacks),ei=tS(e=>e.hiddenHeaderButtons),eo=tS(e=>e.mobileDeviceCount),[ec,ed]=(0,r.useState)(null),[eu,em]=(0,r.useState)(null),[ex,ep]=(0,r.useState)(null),[eh,ef]=(0,r.useState)(null),[eb,eg]=(0,r.useState)(!1),{isCollapsed:ev,toggle:ey}=aB(q?.key||""),ew=ev(aF),ek=sB(U,q?.key);(0,r.useEffect)(()=>{if(!g)return;let e=e=>{(e.metaKey||e.ctrlKey)&&e.altKey&&!e.shiftKey&&"t"===e.key.toLowerCase()&&(e.preventDefault(),ef({workspaceId:null}))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[g]),(0,r.useEffect)(()=>{g&&(ea({connected:J,remoteAvailable:!!d,codespaceInfo:h,showTheme:!1,theme:"default",busRef:Z,hideActions:["remote","files","sites"],tunnelUrl:m,apiKey:x,connectionMode:p,subscribeToPush:y,unsubscribeFromPush:w,notifications:es,agentVersion:S,carrier:Y}),el({onRemote:null,onFiles:null,onSelectSite:null,onRefreshSites:null,onCodespace:null,onLogout:c,onThemeChange:null,onStopCodespace:b,onUpdate:R,onRestart:E}))},[g,J,d,h,c,b,R,E,ea,el,Z,p,y,w,S,Y,m,x,es]);let ej=function(e=[],t=[],s="Ungrouped"){let n=new Map;for(let t of e){let e=eQ(t);n.has(e)||n.set(e,[]),n.get(e).push(t)}let r=t.map(e=>({id:e.id,name:e.name,path:e.path||null,items:n.get(e.id)||[]})),a=n.get(null);return a?.length&&r.push({id:null,name:s,path:null,items:a}),r}(e,$,K("workspaces.ungrouped")),eN=new Set(e.map(e=>e.id)),eS=J&&(n9(S,"3.0.11")||n7(S,"3.0.11")||C);return(0,n.jsxs)("div",{className:"h-full flex flex-col overflow-hidden relative",children:[(0,n.jsxs)("header",{className:`relative z-10 bg-surface/80 backdrop-blur-md px-4 py-3 ${rF} flex items-center justify-between gap-2 flex-shrink-0 border-b border-border-subtle`,style:{paddingTop:"calc(0.75rem + env(safe-area-inset-top, 0px))"},children:[(0,n.jsxs)("div",{className:"flex items-center gap-3 min-w-0",children:[(0,n.jsx)("div",{className:"p-1.5 bg-brand-500/10 rounded-brand flex-shrink-0",children:(0,n.jsx)(t3.Kq,{className:"text-brand-500 w-5 h-5"})}),(0,n.jsx)("h1",{className:"text-text text-lg font-semibold truncate",children:K("sessions.headerTitle")}),(0,n.jsx)("span",{className:`w-2 h-2 rounded-full flex-shrink-0 ${J?"bg-green-500":"bg-red-500 animate-pulse"}`,title:K(J?"sessions.connected":"sessions.disconnected")}),!J&&f&&(0,n.jsx)("span",{className:"text-red-400 text-xs truncate",children:K("sessions.codespaceStopped")})]}),(0,n.jsxs)("div",{className:"flex items-center gap-1 flex-shrink-0",children:[!ei.includes("remote")&&d&&(0,n.jsx)(dg,{icon:t3.VA,label:K("menu.remoteDesktop"),onClick:d,disabled:!J}),!ei.includes("mobile")&&u&&(0,n.jsx)(dg,{icon:t3.wO,label:eo>0?K("mobile.deviceRunning",{count:eo}):K("mobile.androidDevice"),onClick:u,disabled:!J,className:eo>0?"!text-green-400":""}),(0,n.jsx)(dg,{icon:t3.kV,label:K("hosts.addHost"),onClick:()=>{(0,t7.e)(),eg(!0)}}),(0,n.jsx)(dg,{icon:t3.wB,label:K("menu.title"),onClick:er})]})]}),(0,n.jsxs)("div",{className:"relative z-10 flex-1 overflow-auto modal-scrollable pt-2 pb-12",style:{overflowAnchor:"none"},children:[eS&&(0,n.jsx)(re,{agentVersion:S,webVersion:"3.0.11",updateAvailable:C,canSelfUpdate:T,onUpdate:R,className:"mb-4 mx-4"}),q&&(0,n.jsx)("div",{className:"pl-1 pr-3",children:(0,n.jsx)(aL,{className:"flex-shrink-0",hostKey:q.key,label:q.label||"",connected:J,collapsed:ew,onToggleCollapse:()=>ey(aF),showAdd:!1,onRename:O,onDelete:B,onDisconnect:c,onAddWorkspace:A})}),!ew&&(e.length||$.length?(0,n.jsxs)("div",{className:"pl-5 pr-4 pt-1.5",children:[ej.map(e=>{let s=e.items;return null!==e.id||s.length?(0,n.jsx)(df,{section:e,items:s,collapsed:ev(e.id??"ungrouped"),onToggleCollapse:()=>ey(e.id??"ungrouped"),connected:J,cwdBySession:t,fileBus:H,homeDir:I,sessionStatus:en,onSelect:a,onNewTerminal:()=>ef({workspaceId:e.id}),onRenameSession:e=>em({kind:"session",id:e.id,value:e.name}),onBackgroundSession:e=>ed(e),onDeleteSession:e=>ep({kind:"session",id:e.id,name:e.name}),onReorderSession:F,onWorkspaceMenu:null===e.id?null:t=>{"rename"===t?em({kind:"workspace",id:e.id,value:e.name}):ep({kind:"workspace",id:e.id,name:e.name})}},e.id??"ungrouped"):null}),(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),A()},disabled:!J,className:"mx-auto flex items-center gap-1.5 py-1.5 px-4 text-sm text-text-subtle active:text-text border border-dashed border-border-subtle active:border-text-muted/40 rounded-brand active:bg-surface-2 transition-colors disabled:opacity-40",children:[(0,n.jsx)(t3.FW,{size:12,className:"flex-shrink-0"}),(0,n.jsx)("span",{children:K("workspaces.newWorkspace")})]})]}):(0,n.jsx)("div",{className:"px-4 pt-2",children:(0,n.jsx)(dv,{onAddWorkspace:A,onOpenRemote:d,recent:L,homeDir:I,connected:J})})),ek.length>0&&(0,n.jsx)("div",{className:"mt-3 border-t border-border-subtle pt-2 pl-1 pr-3",children:ek.map(e=>(0,n.jsx)(aJ,{host:{...e,onDisconnect:()=>sX.getState().disconnectHost(e.key)},actions:{...sG(e,{onSelectSession:a}),renameHost:O,deleteHost:B},connected:J,treeCls:"pl-5 pr-4",rowCls:"active:bg-surface-2 active:text-text"},e.key))})]}),ec&&(0,n.jsx)(rA,{sessionId:ec.id,title:ec.name,busRef:Z,onClose:()=>ed(null)}),eu&&(0,n.jsx)(rR,{title:K("session"===eu.kind?"sessions.editName":"workspaces.rename"),value:eu.value,onChange:e=>em({...eu,value:e}),onSubmit:()=>{let e=eu?.value?.trim();e&&("session"===eu.kind?o?.(eu.id,e):M?.(eu.id,e)),em(null)},onClose:()=>em(null)}),(0,n.jsx)(t9.A,{isOpen:!!ex,onClose:()=>ep(null),onConfirm:()=>{ex?.kind==="session"?i?.(ex.id):P?.(ex.id),ep(null)},title:K(ex?.kind==="session"?"sessions.deleteTitle":"workspaces.deleteTitle"),message:ex?.kind==="session"?K("sessions.deleteMessage",{name:ex?.name||""}):K("workspaces.deleteMessage",{name:ex?.name||""})}),eh&&(0,n.jsx)(rT,{onClose:()=>ef(null),onCreate:(e,t,s,n,r,a)=>{l?.(e,eh.workspaceId,t,r||null,s,n,a),ef(null)},shells:D,busRef:Z,onResumeAgentSession:k,onSelectSession:a,liveSessionIds:eN,connected:J,workspacePath:$.find(e=>e.id===eh.workspaceId)?.path||null,workspaceName:$.find(e=>e.id===eh.workspaceId)?.name||"",fileBus:H,homeDir:I,suggestName:`${K("terminal.defaultName")} ${(W=eh.workspaceId,e.filter(e=>eQ(e)===W)).length+1}`}),eb&&(0,n.jsx)(aI,{onClose:()=>eg(!1)})]})}function df({section:e,items:t,collapsed:s=!1,onToggleCollapse:a=null,connected:l,cwdBySession:i={},fileBus:o,homeDir:c,sessionStatus:d,onSelect:u,onNewTerminal:m,onRenameSession:x,onBackgroundSession:p,onDeleteSession:h,onWorkspaceMenu:f,onReorderSession:b}){let{dragId:g,registerEl:v,startDrag:y,consumeClick:w}=rI({axis:"y",onCommit:b});(0,r.useEffect)(()=>{if(!g)return;let e=e=>e.preventDefault();return window.addEventListener("touchmove",e,{passive:!1}),()=>window.removeEventListener("touchmove",e)},[g]);let k=(e,s)=>{l&&y(e,s,t.map(e=>e.id))},{t:j}=(0,se.s)(),{branch:N,dirty:S}=aU(rn(e),o);return(0,n.jsxs)("section",{children:[(0,n.jsxs)("div",{className:`flex items-center gap-1 py-1.5 ${l?"cursor-pointer":""}`,children:[(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),a?.()},className:"flex-1 min-w-0 flex items-center gap-1.5 text-left",children:[(0,n.jsx)("span",{className:"p-1 text-text-subtle flex-shrink-0",children:(0,n.jsx)(t3.c_,{size:18,className:`transition-transform duration-150 ${s?"":"rotate-90"}`})}),(0,n.jsx)(t3.vd,{size:14,className:"text-text-muted flex-shrink-0"}),(0,n.jsxs)("span",{className:"flex-1 min-w-0 flex flex-col",children:[(0,n.jsx)("span",{className:"text-sm font-medium uppercase text-text-muted truncate","data-tip":e.name,children:e.name}),N&&!eW.includes(N)&&N!==e.name&&(0,n.jsx)("span",{className:"text-xs text-text-subtle leading-tight flex items-center gap-1 min-w-0",children:(0,n.jsx)(aq,{branch:N,dirty:S,className:"truncate flex-shrink-0 max-w-[7rem]"})})]})]}),m&&(0,n.jsx)("button",{type:"button",onClick:e=>{e.stopPropagation(),(0,t7.e)(),m()},disabled:!l,className:"p-0.5 text-text-subtle hover:text-text rounded-[2px] hover:bg-surface-2 transition-colors disabled:opacity-40",title:j("terminal.newTerminal"),children:(0,n.jsx)(t3.FW,{size:18})}),(0,n.jsx)(aM,{label:j("sessions.sessionActions"),items:[f&&{icon:t3.gH,label:j("workspaces.rename"),onClick:()=>f("rename")},f&&{icon:t3.TB,label:j("workspaces.delete"),danger:!0,onClick:()=>f("delete")}]})]}),!s&&(0,n.jsxs)("div",{children:[t.map(s=>(0,n.jsx)(db,{session:s,status:d[s.id],connected:l,cwd:i[s.id]??s.cwd??s.workspacePath,basePath:rn(e),fileBus:o,homeDir:c,onSelect:u,menuItems:[{icon:t3.gH,label:j("sessions.editName"),onClick:()=>x(s)},{icon:t3._V,label:j("menu.terminalBackground"),onClick:()=>p(s)},{icon:t3.TB,label:j("sessions.deleteTitle"),danger:!0,onClick:()=>h(s)}],registerRef:v(s.id),isDragging:g===s.id,onStartDrag:l&&t.length>1?k:null,swallowClick:w},s.id)),(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),m()},disabled:!l,className:"w-full flex items-center gap-1.5 pl-8 py-1.5 text-left text-sm text-text-subtle hover:text-brand-500 transition-colors disabled:opacity-40",title:j("workspaces.addTerminal"),children:[(0,n.jsx)(t3.FW,{size:18,className:"flex-shrink-0"}),(0,n.jsx)("span",{children:j("terminal.newTerminal")})]})]})]})}function db({session:e,status:t,connected:s,onSelect:a,menuItems:l=null,cwd:i,basePath:o=null,fileBus:c,homeDir:d,registerRef:u=null,isDragging:m=!1,onStartDrag:x=null,swallowClick:p=null}){let{t:h}=(0,se.s)(),f=Q(e=>e.connected),b=s??f,g=nH(t?.state||"idle"),v=t?.tool,[y,w]=(0,r.useState)(null),k=(0,r.useRef)(null),j=(0,r.useRef)(null),N=()=>{k.current&&(clearTimeout(k.current),k.current=null),j.current=null};return(0,n.jsxs)("div",{ref:u,"data-sid":e.id,onClick:()=>{!p?.()&&b&&((0,t7.e)(),a(e.id))},onContextMenu:e=>{l&&!m&&(e.preventDefault(),(0,t7.e)(),w({left:e.clientX,top:e.clientY}))},onPointerDown:t=>{if(x){if("mouse"===t.pointerType)return void x(t,e.id);j.current={x:t.clientX,y:t.clientY},k.current=setTimeout(()=>{N(),(0,t7.e)(),x(t,e.id)},250)}},onPointerMove:e=>{if(!k.current)return;let t=j.current;t&&(Math.abs(e.clientX-t.x)>8||Math.abs(e.clientY-t.y)>8)&&N()},onPointerUp:N,onPointerCancel:N,onPointerLeave:N,className:`group relative flex items-center gap-1.5 pl-6 py-1.5 rounded-[3px] cursor-pointer select-none ${b?"active:bg-text/5":"opacity-60"} ${m?"z-20 opacity-90 shadow-lg ring-1 ring-brand-500 bg-surface":"transition-colors"}`,children:[(0,n.jsx)("span",{className:`w-2 h-2 rounded-full flex-shrink-0 term-dot ${g.cls}${g.pulse?` pulse-${g.pulse}`:""}`,style:{background:g.dot}}),(0,n.jsxs)("span",{className:"flex-1 min-w-0 flex flex-col",children:[(0,n.jsxs)("span",{className:"flex items-center gap-1 min-w-0",children:[(0,n.jsx)(dp,{agentId:e.agent,tool:v}),(0,n.jsx)("span",{className:"text-sm text-text truncate","data-tip":e.name||h("terminal.defaultName"),children:e.name||h("terminal.defaultName")})]}),(0,n.jsx)(aG,{fileBus:c,cwd:i,basePath:o,homeDir:d})]}),l&&(0,n.jsx)(aM,{size:18,label:e.name||h("terminal.defaultName"),anchor:y,onClose:()=>w(null),items:l,className:b?"flex-shrink-0":"opacity-40 pointer-events-none"})]})}function dg({icon:e,label:t,onClick:s,disabled:r,className:a=""}){return(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),s()},disabled:r,title:t,className:`p-2 rounded-brand transition-colors active:scale-[0.96] ${r?"text-text-subtle cursor-not-allowed":`text-text-muted hover:text-text hover:bg-surface-2 ${a}`}`,children:(0,n.jsx)(e,{className:"w-5 h-5"})})}function dv({onAddWorkspace:e,onOpenRemote:t,recent:s,homeDir:r,connected:a}){let{t:l}=(0,se.s)(),i=a&&!!t;return(0,n.jsxs)("div",{className:"empty-stage w-[calc(100%_+_2rem)] h-[calc(100%_+_2.5rem)] -mx-4 -mt-4 -mb-6",children:[(0,n.jsx)("div",{className:"empty-grid"}),(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),e?.()},disabled:!a,className:"empty-half text-left active:opacity-80 enabled:active:scale-[0.99] transition-all duration-150 disabled:opacity-40 disabled:saturate-50",children:[(0,n.jsxs)("span",{className:"empty-idx",children:[(0,n.jsx)("b",{children:"01"})," / ",l("workspaces.emptyTagWorkspace")]}),(0,n.jsx)("span",{className:"empty-word login-hero-grad",children:l("workspaces.emptyWordTerminal")}),(0,n.jsx)("span",{className:"empty-meta",dangerouslySetInnerHTML:{__html:l("workspaces.emptyMetaWorkspace")}}),(0,n.jsxs)("span",{className:"empty-go",children:[l("workspaces.selectFolder"),(0,n.jsx)(t3.Qp,{size:14,className:"text-brand-500",strokeWidth:2.2})]}),!!s.length&&(0,n.jsx)("span",{className:"flex flex-wrap gap-1.5 mt-4 max-w-full",children:s.slice(0,3).map(t=>(0,n.jsx)("span",{role:"button",title:t.path,onClick:s=>{s.stopPropagation(),(0,t7.e)(),e?.(t.path)},className:"welcome-chip path-tail px-2 py-1 text-[11px] font-mono text-text-muted rounded-full truncate max-w-[46%]",children:rs(t.path,r)},t.path))})]}),!!t&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"empty-hairline","aria-hidden":!0}),(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),t?.()},disabled:!i,className:"empty-half text-left active:opacity-80 enabled:active:scale-[0.99] transition-all duration-150 disabled:opacity-40 disabled:saturate-50",children:[(0,n.jsxs)("span",{className:"empty-idx",children:[(0,n.jsx)("b",{children:"02"})," / ",l("workspaces.emptyTagRemote")]}),(0,n.jsx)("span",{className:"empty-word login-hero-grad",children:l("workspaces.emptyWordRemote")}),(0,n.jsx)("span",{className:"empty-meta",dangerouslySetInnerHTML:{__html:l("workspaces.emptyMetaRemote")}}),i&&(0,n.jsxs)("span",{className:"empty-go",children:[l("menu.remoteDesktop"),(0,n.jsx)(t3.Qp,{size:14,className:"text-brand-500",strokeWidth:2.2})]})]})]})]})}let dy="9remote_nav:",dw=(e,t)=>{if(e&&t)try{localStorage.setItem(dy+e,t)}catch{}},dk=e=>{if(!e)return null;try{return localStorage.getItem(dy+e)}catch{return null}};async function dj(e,{route:t,currentKey:s}={}){s&&dw(s,window.location.pathname+window.location.search);let n=await fetch(f.Sn.connect,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e})});if(!n.ok)throw Error("connect failed");let r=await n.json(),a=!1;for(let t=0;t<f.jP&&!a;t++)(a=await (0,aP.zg)(r.tunnelUrl,e))||!(t<f.jP-1)||await new Promise(e=>setTimeout(e,f.dM));if(!a)throw Error("unreachable");(0,l.v)({apiKey:e,tunnelUrl:r.tunnelUrl,mode:"remote",localIp:r.localIp||null}),window.location.href=t||dk(e)||"/workspace/"}function dN({platform:e,size:t=15}){return"win32"===e?(0,n.jsx)(t3.VA,{size:t,className:"text-text-muted"}):"linux"===e?(0,n.jsx)(t3.BK,{size:t,className:"text-text-muted"}):"darwin"===e?(0,n.jsx)(t3.rb,{size:t+2,className:"text-text-muted"}):(0,n.jsx)(t3.ak,{size:t,className:"text-text-muted"})}let dS={full:0,online:1,connecting:2,offline:3},dC={full:"bg-green-500",online:"bg-green-500",connecting:"bg-amber-400 animate-pulse",offline:"bg-text-subtle"};function dT({fullHost:e={},currentKey:t="",homeDir:s=null,menuContext:a=null,menuCallbacks:l=null,onClose:i=null}){let{t:o}=(0,se.s)(),c=si(e=>e.open),d=si(e=>e.setContext),u=si(e=>e.setCallbacks);(0,r.useEffect)(()=>{a&&(d(a),u(l||{}))},[a,l,d,u]);let m=sX(e=>e.hosts),x=sc(e=>e.sessionStatus),[p,h]=(0,r.useState)(null),[f,b]=(0,r.useState)(""),g=(0,r.useMemo)(()=>Object.values(m).map(s=>s.key===t?{...s,...e,statusMap:x,status:"full"}:s).sort((e,t)=>(dS[e.status]??9)-(dS[t.status]??9)||(t.lastSeenAt||0)-(e.lastSeenAt||0)),[m,t,e,x]),v=g.find(e=>e.key===t)?.full||t,y=async(e,t)=>{if(!p){(0,t7.e)(),b(""),h(e.key);try{await t()}catch{b(o("agentSwitcher.unreachable"))}finally{h(null)}}},w=e=>y(e,async()=>{(sX.getState().setFocus(e.key),e.key===t)?sX.getState().closeOverlay():await dj(e.full,{currentKey:v,route:eH})});return(0,n.jsxs)("div",{className:"h-full flex flex-col overflow-hidden",children:[(0,n.jsxs)("header",{className:`relative z-10 bg-surface/80 backdrop-blur-md px-4 py-3 ${rF} flex items-center gap-3 flex-shrink-0 border-b border-border-subtle`,style:{paddingTop:"calc(0.75rem + env(safe-area-inset-top, 0px))"},children:[(0,n.jsx)("div",{className:"p-1.5 bg-brand-500/10 rounded-brand flex-shrink-0",children:(0,n.jsx)(t3.ak,{className:"text-brand-500 w-5 h-5"})}),(0,n.jsx)("h1",{className:"text-text text-lg font-semibold truncate flex-1",children:o("hosts.title")}),(0,n.jsx)("span",{className:"text-xs text-text-muted flex-shrink-0 mr-1",children:g.length}),i?(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),i()},"aria-label":o("common.cancel"),title:o("common.cancel"),className:"p-2 rounded-brand transition-colors text-text-muted hover:text-text hover:bg-surface-2 flex-shrink-0",children:(0,n.jsx)(t3.X,{className:"w-5 h-5"})}):(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),c()},"aria-label":o("menu.title"),title:o("menu.title"),className:"p-2 rounded-brand transition-colors text-text-muted hover:text-text hover:bg-surface-2 flex-shrink-0",children:(0,n.jsx)(t3.wB,{className:"w-5 h-5"})})]}),(0,n.jsxs)("div",{className:"relative z-10 flex-1 overflow-auto modal-scrollable px-4 pt-4 pb-12 space-y-2.5",style:{overflowAnchor:"none"},children:[f&&(0,n.jsx)("div",{className:"text-xs text-red-400 px-1",children:f}),g.map(e=>(0,n.jsx)(dR,{host:e,busy:p===e.key,t:o,onOpenHost:w},e.key))]})]})}function dR({host:e,busy:t,t:s,onOpenHost:r}){let a=function(e=[],t={}){let s=0,n=0;for(let r of e){let e=t[r.id]?.state;"working"===e?s++:("blocked"===e||"done"===e)&&n++}return{sessions:e.length,working:s,attention:n}}(e.sessions,e.statusMap),l=[e.platform,e.version].filter(Boolean).join(" \xb7 ")||("connecting"===e.status?s("hosts.connecting"):"")||("offline"===e.status&&e.lastSeenAt?`${s("hosts.lastSeen")} ${function(e,t){if(!e)return"";let s=Date.now()-e,n=Math.floor(s/6e4),r=Math.floor(s/36e5),a=Math.floor(s/864e5);return n<1?t("login.justNow"):n<60?t("login.minutesAgo",{n:n}):r<24?t("login.hoursAgo",{n:r}):a<7?t("login.daysAgo",{n:a}):new Date(e).toLocaleDateString()}(e.lastSeenAt,s)}`:"");return(0,n.jsxs)("button",{type:"button",onClick:()=>r(e),disabled:t,className:"group flex items-center gap-2 pl-1 pr-2 py-2 text-left relative cursor-pointer border-b border-border-subtle last:border-b-0 disabled:opacity-50",children:[(0,n.jsxs)("span",{className:"relative flex-shrink-0",children:[(0,n.jsx)(dN,{platform:e.platform,size:14}),(0,n.jsx)("span",{className:`absolute -bottom-0.5 -right-0.5 w-1.5 h-1.5 rounded-full ring-1 ring-surface ${dC[e.status]||dC.offline}`})]}),(0,n.jsxs)("span",{className:"flex-1 min-w-0 flex flex-col",children:[(0,n.jsxs)("span",{className:"flex items-center gap-1.5 min-w-0",children:[(0,n.jsx)("span",{className:"text-[12px] font-medium uppercase text-text truncate","data-tip":e.label,children:e.label||s("agentSwitcher.unnamed")}),"full"===e.status&&(0,n.jsx)("span",{className:"text-[9px] font-bold uppercase tracking-wider text-brand-400 bg-brand-500/10 px-1 py-px rounded-[3px] shrink-0",children:s("agentSwitcher.active")})]}),(0,n.jsxs)("span",{className:"flex items-center gap-1.5 text-[10px] text-text-subtle leading-tight min-w-0",children:[l&&(0,n.jsx)("span",{className:"truncate opacity-70",children:l}),l&&(0,n.jsx)("span",{className:"opacity-40",children:"\xb7"}),(0,n.jsxs)("span",{className:"flex-shrink-0",children:[a.sessions," ",s("hosts.sessions")]}),a.working>0&&(0,n.jsxs)("span",{className:"flex-shrink-0 text-blue-400",children:["\xb7 ⟳ ",a.working]}),a.attention>0&&(0,n.jsxs)("span",{className:"flex-shrink-0 text-amber-400 font-medium",children:["\xb7 ⚠ ",a.attention," ",s("hosts.attention")]})]})]}),t?(0,n.jsx)(t3.kr,{size:14,className:"animate-spin text-brand-500 shrink-0"}):(0,n.jsx)(t3.c_,{size:14,className:"text-text-subtle shrink-0"})]})}let dE=(e,t,s)=>Math.max(t,Math.min(s,e));function d_({clientX:e,clientY:t,containerRect:s,pan:n,totalScale:r}){return{x:(e-s.left-n.x)/r,y:(t-s.top-n.y)/r}}function d$(e,t){return{x:Math.min(0,e.width-t.width),y:Math.min(0,e.height-t.height)}}function dM(e,t){return{x:dE(e.x,t.x,0),y:dE(e.y,t.y,0)}}function dP({prevZoom:e,prevPan:t,focal:s,nextZoomRaw:n,maxZoom:r,containerSize:a,displaySizeAt:l}){let i=dE(n,1,r),o=i/e,c=d$(a,l(i));return{zoom:i,pan:dM({x:s.x-(s.x-t.x)*o,y:s.y-(s.y-t.y)*o},c)}}function dA({accum:e,delta:t,threshold:s,multiplier:n}){let r=e+t;if(Math.abs(r)<s)return{accum:r,scroll:null};let a=Math.max(1,Math.round(Math.abs(r)*n));return{accum:0,scroll:r>0?a:-a}}let dz=!!window.chrome,dI=e=>new Blob([e]),dL=(e,t)=>()=>{e.current[t]=null},dD=null,dF=0,dO=new Map;async function dB(e){if("u"<typeof createImageBitmap)return null;if(dz)return createImageBitmap(e);let t=new Image,s=URL.createObjectURL(e);t.src=s,await t.decode();let n=await createImageBitmap(t);return URL.revokeObjectURL(s),n}let dW={fps:0,latency:0,tilesPerSec:0,bandwidthMBps:0,webrtcTiles:0,wsTiles:0,webrtcPercent:0};function dK({list:e,activeIndex:t,onSelect:s}){if(!Array.isArray(e)||e.length<=1)return null;let r=e=>e.stopPropagation();return(0,n.jsx)("div",{className:"absolute bottom-1.5 right-1.5 z-40 flex gap-1.5",children:e.map(e=>{let a=e.index===t,l=`${e.index+1}`;return(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),s?.(e.index)},onMouseDown:e=>e.preventDefault(),onPointerDown:r,onPointerUp:r,onPointerMove:r,onTouchStart:r,onTouchMove:r,onTouchEnd:r,onWheel:r,className:`px-1.5 py-0.5 rounded-md text-xs font-medium backdrop-blur-md border transition-colors inline-flex items-center gap-1 ${a?"bg-blue-500/70 text-white border-blue-400/70":"bg-black/30 text-white/80 border-white/10 hover:bg-black/50"}`,title:`${e.name} (${e.width}\xd7${e.height})`,children:[(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),(0,n.jsx)("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),(0,n.jsx)("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]}),l]},e.index)})})}function dH({canvasRef:e,canvasContainerRef:t,canvasZoom:s,canvasPan:a,fitScale:l,streaming:i,hasFrame:o=!0,selectionRect:c,clickIndicator:d,pointerMode:u,selectionMode:m,handMode:x,handHolding:p,scrollLock:h,virtualCursor:f,cursorShape:b,inputMode:g,keyboardOn:v,monitors:y,activeMonitorIndex:w,onSelectMonitor:k,onPointerDown:j,onPointerMove:N,onPointerUp:S,onWheel:C,onContextMenu:T,onDoubleClick:R,onTouchStart:E,onTouchMove:_,onTouchEnd:$,onKeyDown:M,screenLocked:A,unlockReady:z,unlockResult:I,onUnlockSubmit:L}){let D=l*s,F="mouse"===g,{t:O}=(0,se.s)(),[B,W]=(0,r.useState)(!1),[K,H]=(0,r.useState)(""),[U,q]=(0,r.useState)(!1),[V,X]=(0,r.useState)(!1);(0,r.useEffect)(()=>{A||(H(""),q(!1))},[A]),(0,r.useEffect)(()=>{I&&q(!1)},[I]);let G={ew:"cursor-ew-resize",ns:"cursor-ns-resize",nwse:"cursor-nwse-resize",nesw:"cursor-nesw-resize",all:"cursor-move"},J=m?"cursor-crosshair":x?p?"cursor-grabbing":"cursor-grab":F&&B?"cursor-grabbing":F&&b&&G[b]?G[b]:"trackpad"===u?"cursor-grab active:cursor-grabbing":"cursor-default",Y=(0,r.useRef)(C);return(0,r.useEffect)(()=>{Y.current=C},[C]),(0,r.useEffect)(()=>{let t=e.current;if(!t)return;let s=e=>Y.current?.(e);return t.addEventListener("wheel",s,{passive:!1}),()=>t.removeEventListener("wheel",s)},[e]),(0,r.useEffect)(()=>{F&&i&&e.current?.focus()},[e,F,i]),(0,r.useEffect)(()=>{if(!B)return;let e=()=>W(!1);return window.addEventListener("pointerup",e),window.addEventListener("pointercancel",e),window.addEventListener("blur",e),()=>{window.removeEventListener("pointerup",e),window.removeEventListener("pointercancel",e),window.removeEventListener("blur",e)}},[B]),(0,n.jsxs)("div",{className:"w-full h-full overflow-hidden relative flex-1",children:[(0,n.jsxs)("div",{className:"absolute inset-0",ref:t,style:{touchAction:"none"},onTouchStart:E,onTouchMove:_,onTouchEnd:$,children:[(0,n.jsx)("canvas",{ref:e,className:`block ${J} bg-black outline-none`,style:{touchAction:"none",transformOrigin:"top left",userSelect:"none",WebkitUserSelect:"none",WebkitTouchCallout:"none",WebkitTapHighlightColor:"transparent",transform:`translate3d(${a.x}px, ${a.y}px, 0) scale(${D})`,imageRendering:"auto",willChange:"transform"},onPointerDown:t=>{let s=document.activeElement;if(s?.name==="remote-batch-input")if(v){let e=document.querySelector('textarea[name="remote-keyboard-sink"]');e?.focus()}else s.blur();F&&(e.current?.focus(),"mouse"===t.pointerType&&W(!0)),j?.(t)},onPointerMove:N,onPointerUp:e=>{F&&"mouse"===e.pointerType&&W(!1),S?.(e)},onDoubleClick:R,onContextMenu:T,tabIndex:0,onKeyDown:M}),i&&!o&&!A&&(0,n.jsx)("div",{className:"absolute inset-0 z-20 flex items-center justify-center pointer-events-none",children:(0,n.jsxs)("div",{className:"flex items-center gap-2 px-3 py-1.5 rounded-full bg-black/60 text-white/80 text-[11px] font-mono",children:[(0,n.jsx)(t3.kr,{size:12,className:"animate-spin"}),O("remote.receivingImage",{defaultValue:"Receiving screen…"})]})}),c&&(0,n.jsx)("div",{className:"absolute border-2 border-blue-400 bg-blue-400/20 z-10",style:{left:`${c.x}px`,top:`${c.y}px`,width:`${c.width}px`,height:`${c.height}px`}}),"trackpad"===u&&f&&(0,n.jsx)("div",{className:"absolute pointer-events-none z-30",style:{left:`${f.x*D+a.x}px`,top:`${f.y*D+a.y}px`,width:`${P.eR.trackpadCursorSize}px`,height:`${P.eR.trackpadCursorSize}px`,transform:b||x||h||m?"translate(-50%, -50%)":"translate(-2px, -2px)"},children:h?(0,n.jsx)("div",{className:"w-full h-full flex items-center justify-center text-yellow-400 drop-shadow-[0_1px_2px_rgba(0,0,0,0.8)]",style:{fontSize:`${P.eR.trackpadCursorSize}px`,lineHeight:1},children:"✥"}):m?(0,n.jsx)("svg",{viewBox:"0 0 24 24",className:"w-full h-full text-yellow-400 drop-shadow-[0_1px_2px_rgba(0,0,0,0.8)]",children:(0,n.jsx)("path",{d:"M12 3 V21 M3 12 H21",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})}):x?(0,n.jsx)("div",{className:"w-full h-full flex items-center justify-center drop-shadow-[0_1px_2px_rgba(0,0,0,0.8)]",style:{fontSize:`${P.eR.trackpadCursorSize}px`,lineHeight:1},children:p?"✊":"✋"}):b?(0,n.jsx)("svg",{viewBox:"0 0 24 24",className:"w-full h-full drop-shadow-[0_1px_2px_rgba(0,0,0,0.8)]",style:{transform:`rotate(${"ns"===b?90:"nwse"===b?45:"nesw"===b?-45:0}deg)`},children:"all"===b?(0,n.jsx)("path",{d:"M12 3 V21 M3 12 H21 M8 6 L12 2 L16 6 M8 18 L12 22 L16 18 M6 8 L2 12 L6 16 M18 8 L22 12 L18 16",fill:"#ffffff",stroke:"#000000",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"}):(0,n.jsx)("path",{d:"M3 12 H21 M7 8 L3 12 L7 16 M17 8 L21 12 L17 16",fill:"#ffffff",stroke:"#000000",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})}):(0,n.jsx)("svg",{viewBox:"0 0 24 24",className:"w-full h-full drop-shadow-[0_1px_2px_rgba(0,0,0,0.8)]",children:(0,n.jsx)("path",{d:"M4 2 L4 18 L8.5 14 L11 20 L14 18.5 L11.5 13 L18 12.5 Z",fill:"#ffffff",stroke:"#000000",strokeWidth:"1.2",strokeLinejoin:"round"})})}),d&&(0,n.jsxs)("div",{className:"absolute pointer-events-none z-20",style:{left:`${d.x-d.size/2}px`,top:`${d.y-d.size/2}px`,width:`${d.size}px`,height:`${d.size}px`},children:[(0,n.jsx)("div",{className:"w-full h-full rounded-full border-2 border-blue-400 bg-blue-400/30 animate-ping"}),(0,n.jsx)("div",{className:"absolute inset-0 w-full h-full rounded-full border-2 border-blue-400 bg-blue-400/50"})]})]}),(0,n.jsx)(dK,{list:y,activeIndex:w,onSelect:k}),A&&(0,n.jsx)("div",{className:"absolute inset-0 z-10 flex items-center justify-center",style:{background:"radial-gradient(circle at 50% 40%, rgba(40,60,140,0.55) 0%, rgba(10,12,30,0.92) 60%, rgba(0,0,0,0.96) 100%)"},children:(0,n.jsx)("div",{className:"w-full max-w-[300px] mx-4 rounded-2xl p-5 shadow-2xl backdrop-blur-md",style:{background:"rgba(20,22,40,0.85)",border:"1px solid rgba(120,140,220,0.25)"},children:z?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"flex flex-col items-center gap-2 mb-4",children:[(0,n.jsx)("div",{className:"w-12 h-12 rounded-full flex items-center justify-center",style:{background:"rgba(120,140,220,0.18)"},children:(0,n.jsx)(t3.LM,{size:26,color:"#a9b8ff"})}),(0,n.jsx)("h3",{className:"text-base font-semibold text-white",children:O("remote.lockTitle")}),(0,n.jsx)("p",{className:"text-xs text-center",style:{color:"rgba(220,225,245,0.7)"},children:O("remote.lockDesc")})]}),(0,n.jsxs)("div",{className:"relative",children:[(0,n.jsx)("input",{type:V?"text":"password",value:K,autoFocus:!0,disabled:U,onChange:e=>H(e.target.value),onKeyDown:e=>{"Enter"===e.key&&K&&!U&&(q(!0),L?.(K))},placeholder:O("remote.lockPlaceholder"),className:"w-full rounded-xl px-4 py-2 pr-11 text-sm text-white focus:outline-none focus:border-blue-400",style:{background:"rgba(255,255,255,0.08)",border:"1px solid rgba(120,140,220,0.35)"}}),(0,n.jsx)("button",{type:"button",onClick:()=>X(e=>!e),tabIndex:-1,className:"absolute right-2 top-1/2 -translate-y-1/2 p-1.5 rounded-lg",style:{color:"rgba(220,225,245,0.7)"},"aria-label":V?"Hide password":"Show password",children:V?(0,n.jsx)(t3.X_,{size:18}):(0,n.jsx)(t3.kU,{size:18})})]}),(0,n.jsx)("button",{type:"button",disabled:!K||U,onClick:()=>{q(!0),L?.(K)},className:"w-full mt-2.5 rounded-xl py-2.5 text-sm font-semibold text-white transition-opacity disabled:opacity-40",style:{background:"linear-gradient(135deg, #4a6cf7 0%, #6b8aff 100%)"},children:O(U?"remote.unlocking":"remote.unlock")}),I&&!I.ok&&(0,n.jsx)("p",{className:"mt-3 text-xs text-center text-red-300",children:O("remote.unlockFailed")})]}):(0,n.jsxs)("div",{className:"flex flex-col items-center gap-2 text-center",children:[(0,n.jsx)("div",{className:"w-12 h-12 rounded-full flex items-center justify-center",style:{background:"rgba(120,140,220,0.18)"},children:(0,n.jsx)(t3.LM,{size:26,color:"#a9b8ff"})}),(0,n.jsx)("h3",{className:"text-base font-semibold text-white",children:O("remote.lockTitle")}),(0,n.jsx)("p",{className:"text-xs",style:{color:"rgba(220,225,245,0.85)"},children:O("remote.lockGrantDesc")})]})})})]})}var dU=s(80186);let dq=(e,...t)=>{(0,t7.e)(),e?.(...t)};function dV({active:e,primary:t,pinned:s,children:r,className:a="",onClick:l,...i}){return(0,n.jsx)("button",{type:"button",onMouseDown:e=>e.preventDefault(),onClick:l,className:`shrink-0 px-1 h-8 rounded-brand text-xs font-semibold shadow-sm disabled:opacity-50 disabled:cursor-not-allowed min-w-[34px] flex items-center justify-center ${e?"bg-brand-500 text-white shadow-sm transition-all duration-150 ease-out active:scale-[0.94]":s?"bg-brand-500/15 hover:bg-brand-500/25 text-brand-400 transition-all duration-150 ease-out active:scale-[0.94]":t?"bg-green-600 hover:bg-green-700 text-white shadow-sm transition-all duration-150 ease-out active:scale-[0.94]":"bg-surface-2 hover:bg-surface-3 text-text transition-all duration-150 ease-out active:scale-[0.94]"} ${a}`,style:{touchAction:"manipulation",WebkitTapHighlightColor:"transparent"},...i,children:r})}function dX({streaming:e,canvasZoom:t,clipboardNew:s,clipboardText:a,onOpenClipboard:l,selectionMode:i,pointerMode:o,handMode:c,inputMode:d,onToggleHandMode:u,onTogglePointerMode:m,modifierKeys:x,textInputValue:p,textInputRef:h,keyboardOn:f,showTextPanel:b,onResetZoom:g,onRefresh:v,onToggleSelection:y,onToggleModifier:w,onToggleKeyboard:k,onToggleTextPanel:j,onToggleHelp:N,onToggleDebug:S,debugOn:C,onEmitKey:T,onTextInputChange:R,onTextInputFocus:E,onTextInputBlur:_,onTextInputKeyDown:$,onDirectInputChange:M,onSendText:A,onClose:z,onDesktopSwitch:I,controlsHidden:L,onToggleControlsHidden:D,tallLandscape:F}){let O,B,W,K,{t:H,locale:U}=(0,se.s)(),q=(0,r.useRef)(null),[V]=nb(U),[X,G]=(0,r.useState)(!1),J=ny({lang:nh(V),onText:e=>{R(e);let t=q.current;t&&requestAnimationFrame(()=>{try{t.selectionStart=t.selectionEnd=t.value.length}catch{}t.scrollTop=t.scrollHeight})}});(0,r.useEffect)(()=>{let e=q.current;e&&!window.matchMedia("(orientation: landscape)").matches&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,72)}px`)},[p]);let Y=()=>{J.listening&&J.stop(),dq(A,e)},Z=`flex gap-1.5 overflow-auto scroll-thin-x py-0.5 pr-2 ${F?"":"landscape:flex-wrap landscape:overflow-y-auto landscape:overflow-x-hidden landscape:py-2 landscape:pr-0 landscape:content-center landscape:justify-center"} rounded-lg`,[Q,ee]=(0,r.useState)(!1),[et,es]=(0,r.useState)(!1),[en,er]=(0,r.useState)(0);(0,r.useEffect)(()=>{if(!s)return void er(0);er(Math.ceil(P.eR.clipboardBadgeTimeout/1e3));let e=setInterval(()=>{er(e=>e<=1?0:e-1)},1e3);return()=>clearInterval(e)},[s,a]);let ea=nN("remoteDesktop.bottomKeys",P.ij,P.D5,"flat"),el=nN("remoteDesktop.extraKeys",P.ij,P.I9,"grid");(0,r.useEffect)(()=>{if(!b)return;let e=setTimeout(()=>q.current?.focus(),350);return()=>clearTimeout(e)},[b]);let ei=P.eR.pcModeControls,eo=e=>"mouse"!==d||ei[e],ec=window.innerWidth<768,ed=(t,s,r=!1,a="")=>{let l=t.label.length>1?"text-[11px]":"",i=`${a} ${l}`.trim();if("modifier"===t.type)return(0,n.jsx)(dV,{onClick:()=>dq(w,t.modifier),disabled:!e,active:x[t.modifier],pinned:r,className:i,children:t.label},t.id+s);if("desktop"===t.type){let a="prev"===t.direction?t3.JG:"next"===t.direction?t3.c_:t3.FW;return(0,n.jsxs)(dV,{onClick:()=>dq(I,t.direction),disabled:!e,pinned:r,className:i,title:`${t.direction} desktop`,children:[(0,n.jsx)(t3.VA,{size:12}),(0,n.jsx)(a,{size:"new"===t.direction?10:12,className:"-ml-0.5"})]},t.id+s)}return(0,n.jsx)(dV,{onClick:()=>dq(T,t.key,t.modifiers||[],t.osAdaptive),disabled:!e,primary:!r&&t.primary,pinned:r,className:i,children:t.label},t.id+s)};return(0,n.jsxs)("div",{className:`bg-bg select-none relative landscape:flex landscape:flex-col landscape:shrink-0 ${F||L?"":"landscape:h-full landscape:justify-end"} ${L?"landscape:w-12":F?"landscape:w-full landscape:pl-12":"landscape:w-64"}`,children:[(0,n.jsx)("textarea",{ref:h,rows:1,value:p,onChange:e=>{f?M?.(e.target.value):R(e.target.value)},onKeyDown:$,onFocus:E,onBlur:_,"aria-hidden":"true",autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"data-lpignore":"true","data-1p-ignore":"true","data-form-type":"other",name:"remote-keyboard-sink",style:{position:"absolute",opacity:.01,width:1,height:1,border:0,padding:0,left:0,top:0,fontSize:16,resize:"none",pointerEvents:"none",zIndex:-1}}),(0,n.jsx)("div",{className:`absolute top-1 right-1 z-30 ${L||F?"hidden":"hidden landscape:flex"}`,children:(0,n.jsx)(dV,{onClick:()=>{(0,t7.e)(),D?.(!0)},title:H("remote.hideControls"),children:(0,n.jsx)(t3.X_,{size:14})})}),(0,n.jsxs)("div",{className:L?"landscape:hidden":"contents",children:[(0,n.jsxs)("div",{className:`${b?"flex":"hidden"} landscape:flex ${F?"":"landscape:flex-col"} relative z-30 px-2 py-1 gap-2 ${F?"landscape:px-0":"landscape:gap-1 landscape:order-last"}`,children:[(0,n.jsxs)("div",{className:"relative flex-1",children:[(0,n.jsx)(nx,{value:p,store:na,isMobile:ec,onSelect:e=>{R(e),q.current?.focus()}}),(0,n.jsx)("textarea",{ref:q,rows:1,cols:1,value:p,onChange:e=>R(e.target.value),onFocus:E,onKeyDown:t=>{"mouse"===d&&"Enter"===t.key&&!t.shiftKey&&(t.preventDefault(),e&&Y())},placeholder:"mouse"===d?H("remoteControls.enterToSend"):H("remoteControls.typeToSend"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"data-lpignore":"true","data-1p-ignore":"true","data-form-type":"other",name:"remote-batch-input",className:`block w-full px-3 py-2 pr-8 bg-surface-2 rounded text-text text-sm placeholder-text-muted focus:outline-none focus:ring-2 focus:ring-brand-500/40 transition-all duration-150 ease-out resize-none overflow-y-auto ${F?"":"landscape:!h-16"}`,disabled:!e}),p?(0,n.jsx)("button",{type:"button",onMouseDown:e=>e.preventDefault(),onClick:()=>{R(""),q.current?.focus()},title:H("voice.clear"),className:"absolute right-1.5 top-1.5 w-5 h-5 flex items-center justify-center text-text-muted hover:text-text transition-colors",children:(0,n.jsx)(t3.X,{size:14})}):(0,n.jsx)("button",{type:"button",onMouseDown:e=>e.preventDefault(),onClick:()=>G(!0),title:H("history.title"),className:"absolute right-1.5 top-1.5 w-5 h-5 flex items-center justify-center text-text-muted hover:text-text transition-colors",children:(0,n.jsx)(t3.BZ,{size:14})})]}),(0,n.jsxs)("div",{className:"flex gap-2 items-center justify-end",children:[J.active&&(0,n.jsx)("div",{className:"relative shrink-0",children:(0,n.jsx)("button",{type:"button",onMouseDown:e=>e.preventDefault(),onClick:()=>{J.listening?J.stop():(document.activeElement?.blur(),J.start(p))},disabled:!e,title:"not-allowed"===J.error||"service-not-allowed"===J.error?H("voice.denied"):H("voice.dictate"),className:`h-9 w-9 flex items-center justify-center rounded-full transition-all duration-150 ease-out disabled:opacity-40 ${J.listening?"bg-red-500/90 text-white animate-pulse":J.error?"bg-surface-2 text-red-400":"bg-surface-2 hover:bg-surface-3 text-text-muted hover:text-text"}`,children:J.listening?(0,n.jsx)(t3.jj,{size:18}):(0,n.jsx)(t3.GO,{size:18})})}),(0,n.jsx)(dU.A,{variant:"primary",size:"sm",className:"!px-2.5 shrink-0",onMouseDown:e=>e.preventDefault(),onClick:Y,disabled:!e,children:p.trim()?H("remoteControls.send"):(0,n.jsx)(t3.Lt,{size:16,strokeWidth:2.5})})]})]}),(0,n.jsx)("div",{className:`overflow-hidden transition-all duration-300 ${Q?"max-h-56 opacity-100":"hidden"}`,children:(0,n.jsx)("div",{className:"px-2 py-1",children:(0,n.jsx)("div",{className:"space-y-1",children:el.rows.map((e,t)=>(0,n.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,n.jsx)("div",{className:"flex-1 min-w-0 flex gap-1.5 overflow-x-auto scroll-thin-x pr-3 rounded-lg",children:e.map((e,s)=>{let n=P.ij.find(t=>t.id===e);return n?ed(n,100*t+s):null})}),0===t&&(0,n.jsx)("button",{onMouseDown:e=>e.preventDefault(),onClick:()=>{(0,t7.e)(),es(!0)},className:"shrink-0 h-10 w-10 flex items-center justify-center text-text-muted hover:text-text bg-surface-2 hover:bg-surface-3 rounded-brand transition-all duration-150 ease-out",title:H("remote.customizeKeys"),children:(0,n.jsx)(t3.wB,{size:16})}),t>0&&(0,n.jsx)("div",{className:"shrink-0 h-10 w-10"})]},t))})})}),(0,n.jsxs)("div",{className:"flex items-center gap-1.5 px-2 py-1 landscape:hidden",children:[(0,n.jsxs)("div",{className:`${Z} flex-1 min-w-0 px-0 py-0 landscape:py-0`,children:[(0,n.jsx)(dV,{onClick:()=>dq(z),title:H("remote.back"),pinned:!0,className:"landscape:hidden",children:(0,n.jsx)(t3.JG,{size:16})}),s&&a?(0,n.jsxs)(dV,{onClick:()=>dq(l),className:"!text-red-500 landscape:hidden",title:H("common.clipboard"),children:[(0,n.jsx)(t3.Ir,{size:14,className:"shrink-0"}),(0,n.jsx)("span",{className:"tabular-nums",children:en})]}):(0,n.jsxs)(dV,{onClick:()=>dq(g),disabled:!e,className:"text-text landscape:hidden",title:H("remote.resetZoom"),children:[Math.round(100*t),"%"]}),(0,n.jsx)(dV,{onClick:()=>dq(v),disabled:!e,title:H("remote.refresh"),className:"landscape:hidden",children:(0,n.jsx)(t3.e9,{size:14})}),eo("rectangleSelect")&&(0,n.jsx)(dV,{onClick:()=>dq(y),disabled:!e,active:i,title:H("remote.rectangleSelection"),className:"landscape:hidden",children:"□"}),eo("pointerModeToggle")&&(0,n.jsx)(dV,{onClick:()=>dq(m),disabled:!e,active:"trackpad"===o,title:"trackpad"===o?H("remoteControls.trackpadMode"):H("remoteControls.directMode"),className:"landscape:hidden",children:(0,n.jsx)("span",{className:"text-base leading-none",children:"\uD83D\uDDB1️"})}),eo("handMode")&&"trackpad"===o&&(0,n.jsx)(dV,{onClick:()=>dq(u),disabled:!e,active:c,title:H("remote.handMode"),className:"landscape:hidden",children:(0,n.jsx)(t3.Ud,{size:14})}),eo("keyboardToggle")&&(0,n.jsx)(dV,{onClick:()=>dq(k),disabled:!e,active:f,title:H("remote.toggleKeyboard"),className:"landscape:hidden",children:(0,n.jsx)(t3.s3,{size:14})}),eo("textPanel")&&(0,n.jsx)(dV,{onClick:()=>dq(j),disabled:!e,active:b,title:H("remote.textBatchInput"),className:"landscape:hidden",children:"Aa"}),eo("help")&&(0,n.jsx)(dV,{onClick:()=>dq(N),title:H("remote.help"),className:"landscape:hidden",children:(0,n.jsx)(t3.mN,{size:14})})]}),(0,n.jsx)(dV,{onClick:()=>{(0,t7.e)(),ee(e=>!e)},active:Q,pinned:!0,className:"landscape:hidden shrink-0",title:H("remote.extraKeys"),children:Q?(0,n.jsx)(t3.X,{size:16}):(0,n.jsx)(t3.a4,{size:16})})]}),eo("modifierRow")&&(O=ea.keys.filter(e=>e.id!==P.Ic),B=P.ij.find(e=>e.id===P.Ic),W=(0,n.jsx)(dV,{onClick:()=>{(0,t7.e)(),ee(e=>!e)},active:Q,pinned:!0,title:H("remote.extraKeys"),children:Q?(0,n.jsx)(t3.X,{size:16}):(0,n.jsx)(t3.a4,{size:16})}),K=B?ed(B,"pinned",!0):null,(0,n.jsxs)("div",{className:`px-2 py-1 safe-area-bottom ${F?"landscape:px-0":"landscape:py-2"}`,children:[(0,n.jsxs)("div",{className:"flex items-center gap-1.5 landscape:hidden",children:[(0,n.jsx)("div",{className:`${Z} flex-1 min-w-0`,children:O.map((e,t)=>ed(e,t))}),K]}),(0,n.jsxs)("div",{className:`${Z} hidden ${F?"landscape:flex":""}`,children:[O.map((e,t)=>ed(e,t)),W,K]}),(0,n.jsxs)("div",{className:`hidden ${F?"":"landscape:flex"} landscape:flex-col gap-1`,children:[(0,n.jsxs)("div",{className:"flex gap-1.5 overflow-x-auto scroll-thin-x",children:[O.slice(0,5).map((e,t)=>ed(e,t)),W]}),(0,n.jsxs)("div",{className:"flex gap-1.5 overflow-x-auto scroll-thin-x",children:[O.slice(5).map((e,t)=>ed(e,t)),K]})]})]}))]}),(0,n.jsxs)("div",{className:`flex-col gap-1.5 p-1.5 ${L?"hidden landscape:flex":"hidden"}`,children:[(0,n.jsx)(dV,{onClick:()=>{(0,t7.e)(),D?.(!1)},title:H("remote.showControls"),children:(0,n.jsx)(t3.kU,{size:16})}),(0,n.jsx)(dV,{onClick:()=>dq(k),disabled:!e,active:f,title:H("remote.toggleKeyboard"),children:(0,n.jsx)(t3.s3,{size:16})})]}),(0,n.jsx)(nE,{isOpen:et,onClose:()=>es(!1),title:H("remote.customizeRemoteKeys"),tabs:[{id:"bottom",label:H("remoteControls.bottomRow"),hook:ea,excludeIds:[P.Ic]},{id:"extra",label:H("remoteControls.extraPanel"),hook:el}]}),(0,n.jsx)(no,{isOpen:X,store:na,onSelect:e=>{R(e),q.current?.focus()},onClose:()=>G(!1)})]})}let dG="bg-surface-2 hover:bg-surface-3 text-text",dJ="bg-surface-2 hover:bg-surface-3 text-text-muted hover:text-text",dY="bg-brand-500 text-white";function dZ({onClick:e,title:t,disabled:s,className:r,children:a}){return(0,n.jsx)("button",{type:"button",onMouseDown:e=>e.preventDefault(),onClick:()=>{(0,t7.e)(),e()},disabled:s,title:t,className:`shrink-0 w-9 h-9 rounded-brand flex items-center justify-center transition-all duration-150 active:scale-[0.94] ${r} ${s?"disabled:opacity-50":""}`,children:a})}function dQ({streaming:e,canvasZoom:t,pointerMode:s,handMode:r,keyboardOn:a,selectionMode:l,show:i,onBack:o,onRefresh:c,onResetZoom:d,onTogglePointerMode:u,onToggleHandMode:m,onToggleKeyboard:x,onShowHelp:p,onToggleSelection:h}){let{t:f}=(0,se.s)();return(0,n.jsxs)("div",{className:"hidden landscape:flex flex-col items-center gap-1.5 py-2 px-1 bg-bg shrink-0 landscape:w-12 z-20",children:[(0,n.jsx)(dZ,{onClick:o,title:f("remote.back"),className:"bg-brand-500/15 hover:bg-brand-500/25 text-brand-400",children:(0,n.jsx)(t3.JG,{size:18})}),(0,n.jsx)(dZ,{onClick:c,disabled:!e,title:f("remote.refresh"),className:dJ,children:(0,n.jsx)(t3.e9,{size:16})}),(0,n.jsxs)(dZ,{onClick:d,disabled:!e,title:f("remote.resetZoom"),className:`text-[10px] font-semibold ${dG}`,children:[Math.round(100*t),"%"]}),i("pointerModeToggle")&&(0,n.jsx)(dZ,{onClick:u,disabled:!e,title:f("trackpad"===s?"remoteControls.trackpadMode":"remoteControls.directMode"),className:`text-base leading-none ${"trackpad"===s?dY:dG}`,children:"\uD83D\uDDB1️"}),i("handMode")&&"trackpad"===s&&(0,n.jsx)(dZ,{onClick:m,disabled:!e,title:f("remote.handMode"),className:r?dY:dG,children:(0,n.jsx)(t3.Ud,{size:16})}),i("keyboardToggle")&&(0,n.jsx)(dZ,{onClick:x,disabled:!e,title:f("remote.toggleKeyboard"),className:a?dY:dJ,children:(0,n.jsx)(t3.s3,{size:16})}),i("help")&&(0,n.jsx)(dZ,{onClick:p,title:f("remote.help"),className:dJ,children:(0,n.jsx)(t3.mN,{size:16})}),i("rectangleSelect")&&(0,n.jsx)(dZ,{onClick:h,disabled:!e,title:f("remote.rectangleSelection"),className:l?dY:dG,children:"□"})]})}function d0({onClose:e,inputMode:t="touch",pointerMode:s="direct"}){let{t:a}=(0,se.s)();(0,r.useEffect)(()=>{let t=t=>{"Escape"===t.key&&(t.preventDefault(),t.stopPropagation(),e?.())};return window.addEventListener("keydown",t,!0),()=>window.removeEventListener("keydown",t,!0)},[e]);let l="mouse"===t?[{title:a("remoteHelp.mouseTitle"),items:[{key:a("remoteHelp.mouseClickKey"),desc:a("remoteHelp.mouseClickDesc")},{key:a("remoteHelp.mouseRightKey"),desc:a("remoteHelp.mouseRightDesc")},{key:a("remoteHelp.mouseWheelKey"),desc:a("remoteHelp.mouseWheelDesc")},{key:a("remoteHelp.mouseDoubleKey"),desc:a("remoteHelp.mouseDoubleDesc")}]},{title:a("remoteHelp.keyboardTitle"),items:[{key:a("remoteHelp.keyPhysicalKey"),desc:a("remoteHelp.keyPhysicalDesc")},{key:a("remoteHelp.keyModifierKey"),desc:a("remoteHelp.keyModifierDesc")}]}]:"trackpad"===s?[{title:a("remoteHelp.gesturesTrackpadTitle"),items:[{key:a("remoteHelp.trackpadSwipeKey"),desc:a("remoteHelp.trackpadSwipeDesc")},{key:a("remoteHelp.trackpadScrollLockKey"),desc:a("remoteHelp.trackpadScrollLockDesc")},{key:a("remoteHelp.trackpadTapKey"),desc:a("remoteHelp.trackpadTapDesc")},{key:a("remoteHelp.trackpad2TapKey"),desc:a("remoteHelp.trackpad2TapDesc")},{key:a("remoteHelp.trackpad2SwipeKey"),desc:a("remoteHelp.trackpad2SwipeDesc")},{key:a("remoteHelp.trackpadPinchKey"),desc:a("remoteHelp.trackpadPinchDesc")}]},{title:a("remoteHelp.toolbarTitle"),items:[{key:"✋",desc:a("remoteHelp.toolbarHandDesc")},{key:"\uD83D\uDDB1️",desc:a("remoteHelp.toolbarMouseDirectDesc")},{key:"⌨️ / Aa",desc:a("remoteHelp.toolbarKeyboardDesc")}]}]:[{title:a("remoteHelp.gesturesDirectTitle"),items:[{key:a("remoteHelp.directTapKey"),desc:a("remoteHelp.directTapDesc")},{key:a("remoteHelp.directLongKey"),desc:a("remoteHelp.directLongDesc")},{key:a("remoteHelp.directDoubleKey"),desc:a("remoteHelp.directDoubleDesc")},{key:a("remoteHelp.directScrollKey"),desc:a("remoteHelp.directScrollDesc")},{key:a("remoteHelp.directPinchKey"),desc:a("remoteHelp.directPinchDesc")},{key:a("remoteHelp.directPanKey"),desc:a("remoteHelp.directPanDesc")}]},{title:a("remoteHelp.toolbarTitle"),items:[{key:"\uD83D\uDDB1️",desc:a("remoteHelp.toolbarMouseTrackpadDesc")},{key:"⌨️ / Aa",desc:a("remoteHelp.toolbarKeyboardDesc")},{key:"□",desc:a("remoteHelp.toolbarRectDesc")}]}],i=a("mouse"===t?"remoteHelp.modePc":"trackpad"===s?"remoteHelp.modeTrackpad":"remoteHelp.modeDirect");return(0,n.jsx)("div",{className:"fixed inset-x-0 top-0 h-[var(--app-height,100dvh)] z-50 bg-black/60 flex items-center justify-center p-4",onClick:e,children:(0,n.jsxs)("div",{className:"card-elev max-w-lg w-full max-h-full overflow-y-auto",onClick:e=>e.stopPropagation(),children:[(0,n.jsxs)("div",{className:"flex items-center justify-between p-4 border-b border-border sticky top-0 bg-surface z-10",children:[(0,n.jsxs)("div",{className:"flex items-baseline gap-2",children:[(0,n.jsx)("h2",{className:"text-text text-base font-semibold",children:a("remote.help")}),(0,n.jsx)("span",{className:"text-brand-400 text-xs font-mono",children:i})]}),(0,n.jsx)("button",{onClick:e,className:"p-1 rounded hover:bg-surface-2 text-text-muted hover:text-text transition-colors",children:(0,n.jsx)(t3.X,{size:18})})]}),(0,n.jsx)("div",{className:"p-4 space-y-4",children:l.map(e=>(0,n.jsxs)("div",{children:[(0,n.jsx)("h3",{className:"text-brand-400 text-xs font-semibold uppercase tracking-wider mb-2",children:e.title}),(0,n.jsx)("ul",{className:"space-y-1.5",children:e.items.map(e=>(0,n.jsxs)("li",{className:"flex gap-3 text-sm",children:[(0,n.jsx)("span",{className:"text-text font-mono bg-bg px-2 py-0.5 rounded text-xs shrink-0 min-w-[120px] text-center",children:e.key}),(0,n.jsx)("span",{className:"text-text-muted",children:e.desc})]},e.key))})]},e.title))})]})})}function d1({stats:e,mode:t,onReset:s,onClose:a,onCopy:l,onForceWsDisconnect:i,onToggleWsBlock:o,isWsBlocked:c}){var d,u;let m,{t:x}=(0,se.s)(),[p,h]=(0,r.useState)(!1);return p?(0,n.jsx)("div",{className:"fixed top-4 right-4 z-50",children:(0,n.jsxs)("button",{onClick:()=>h(!1),className:"bg-surface-2 text-text px-4 py-2 rounded-lg shadow-md hover:bg-surface-3 transition-all duration-150 ease-out active:scale-[0.97]",children:["\uD83D\uDD0D ",x("remote.debug")]})}):(0,n.jsxs)("div",{className:"fixed top-4 right-4 z-50 card-elev p-4 min-w-[280px] text-sm",children:[(0,n.jsxs)("div",{className:"flex items-center justify-between mb-3 pb-2 border-b border-border",children:[(0,n.jsxs)("h3",{className:"text-text font-semibold flex items-center gap-2",children:["\uD83D\uDD0D ",x("remote.debugTitle")]}),(0,n.jsxs)("div",{className:"flex gap-2",children:[(0,n.jsx)("button",{onClick:()=>h(!0),className:"text-text-muted hover:text-text transition-colors",title:x("remote.minimize"),children:"─"}),(0,n.jsx)("button",{onClick:a,className:"text-text-muted hover:text-text transition-colors",title:x("common.close"),children:"✕"})]})]}),(0,n.jsxs)("div",{className:"space-y-2 mb-3",children:[(0,n.jsxs)("div",{className:"flex justify-between items-center",children:[(0,n.jsx)("span",{className:"text-text-muted",children:"Mode:"}),(0,n.jsx)("span",{className:"rtc"===t?"text-blue-400 font-semibold":"text-yellow-400 font-semibold",children:"rtc"===t?"RTC enabled":"WS only"})]}),(0,n.jsxs)("div",{className:"flex justify-between items-center",children:[(0,n.jsxs)("span",{className:"text-text-muted",children:[x("remote.transport"),":"]}),(0,n.jsx)("span",{className:e.webrtcPercent>50?"text-blue-400 font-semibold":"text-text-muted",children:e.webrtcPercent>50?"WebRTC ✅":"WebSocket"})]}),(0,n.jsxs)("div",{className:"flex justify-between items-center",children:[(0,n.jsxs)("span",{className:"text-text-muted",children:[x("remote.fps"),":"]}),(0,n.jsx)("span",{className:`font-semibold ${(d=e.fps)>=15?"text-green-400":d>=10?"text-yellow-400":"text-red-400"}`,children:e.fps})]}),(0,n.jsxs)("div",{className:"flex justify-between items-center",children:[(0,n.jsxs)("span",{className:"text-text-muted",children:[x("remote.latency"),":"]}),(0,n.jsx)("span",{className:`font-semibold ${(u=e.latency)<50?"text-green-400":u<100?"text-yellow-400":"text-red-400"}`,children:(m=e.latency,`${Math.round(m)}ms`)})]}),(0,n.jsxs)("div",{className:"flex justify-between items-center",children:[(0,n.jsxs)("span",{className:"text-text-muted",children:[x("remote.tilesPerSec"),":"]}),(0,n.jsx)("span",{className:"text-text font-semibold",children:e.tilesPerSec})]}),(0,n.jsxs)("div",{className:"flex justify-between items-center",children:[(0,n.jsxs)("span",{className:"text-text-muted",children:[x("remote.bandwidth"),":"]}),(0,n.jsxs)("span",{className:"text-text font-semibold",children:[e.bandwidthMBps," MB/s"]})]})]}),(0,n.jsxs)("div",{className:"border-t border-border pt-3 mb-3 space-y-1",children:[(0,n.jsxs)("div",{className:"flex justify-between items-center text-xs",children:[(0,n.jsx)("span",{className:"text-blue-400",children:"WebRTC:"}),(0,n.jsxs)("span",{className:"text-text-muted",children:[e.webrtcTiles.toLocaleString()," tiles (",e.webrtcPercent,"%)"]})]}),(0,n.jsxs)("div",{className:"flex justify-between items-center text-xs",children:[(0,n.jsx)("span",{className:"text-text-muted",children:"WebSocket:"}),(0,n.jsxs)("span",{className:"text-text-muted",children:[e.wsTiles.toLocaleString()," tiles (",100-e.webrtcPercent,"%)"]})]})]}),(0,n.jsxs)("div",{className:"flex gap-2 border-t border-border pt-3",children:[(0,n.jsx)("button",{onClick:s,className:"flex-1 bg-surface hover:bg-surface-2 text-text py-2 px-3 rounded transition-colors text-xs",children:x("remote.clearStats")}),(0,n.jsx)("button",{onClick:l,className:"flex-1 bg-surface hover:bg-surface-2 text-text py-2 px-3 rounded transition-colors text-xs",children:"Copy"})]}),(i||o)&&(0,n.jsxs)("div",{className:"flex gap-2 mt-2",children:[i&&(0,n.jsx)("button",{onClick:i,className:"flex-1 bg-red-900/40 hover:bg-red-900/60 text-red-300 py-2 px-3 rounded transition-colors text-xs",title:"Disconnect WS once (auto-reconnect)",children:"⚡ Kill WS"}),o&&(0,n.jsx)("button",{onClick:o,className:`flex-1 py-2 px-3 rounded transition-colors text-xs ${c?"bg-yellow-900/60 hover:bg-yellow-900/80 text-yellow-200":"bg-surface hover:bg-surface-2 text-text"}`,title:"Block WS reconnect to test RTC standalone",children:c?"\uD83D\uDD12 WS Blocked":"\uD83D\uDEAB Block WS"})]})]})}function d2({text:e,onClose:t}){let[s,a]=(0,r.useState)(!1);(0,r.useEffect)(()=>{let e=e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),t?.())};return window.addEventListener("keydown",e,!0),()=>window.removeEventListener("keydown",e,!0)},[t]);let l=async()=>{try{await navigator.clipboard?.writeText(e),a(!0),setTimeout(()=>a(!1),1500)}catch{}};return(0,n.jsx)("div",{className:"fixed inset-x-0 top-0 h-[var(--app-height,100dvh)] z-50 bg-black/60 flex items-center justify-center p-4",onClick:t,children:(0,n.jsxs)("div",{className:"card-elev max-w-lg w-full max-h-full flex flex-col",onClick:e=>e.stopPropagation(),children:[(0,n.jsxs)("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)(t3.m0,{size:16,className:"text-brand-400"}),(0,n.jsx)("h2",{className:"text-text text-base font-semibold",children:"Clipboard"})]}),(0,n.jsx)("button",{onClick:t,className:"p-1 rounded hover:bg-surface-2 text-text-muted hover:text-text transition-colors",children:(0,n.jsx)(t3.X,{size:18})})]}),(0,n.jsx)("div",{className:"p-4 overflow-y-auto flex-1",children:(0,n.jsx)("pre",{className:"text-text text-sm whitespace-pre-wrap break-all bg-bg rounded p-3 font-mono min-h-[120px] max-h-[55dvh] overflow-y-auto scroll-thin",children:e||""})}),(0,n.jsx)("div",{className:"flex justify-end gap-2 p-4 border-t border-border",children:(0,n.jsxs)("button",{onClick:l,disabled:!e,className:"flex items-center gap-1.5 px-3 py-1.5 rounded-brand bg-brand-500 hover:bg-brand-600 disabled:opacity-50 text-white text-sm font-semibold transition-colors",children:[s?(0,n.jsx)(t3.aJ,{size:14}):(0,n.jsx)(t3.m0,{size:14}),"Copy"]})})]})})}function d5({onClose:e,busRef:t,protocolRef:a,connected:l,carrier:i,hostPlatform:o}){let{t:c}=(0,se.s)(),[d,u]=(0,r.useState)(!1),[m,x]=(0,r.useState)(!1),[p,h]=(0,r.useState)(!1),[f,b]=nj("remoteDesktop.showTextPanel",!0),[v,y]=nj("remoteDesktop.keyboard",!1),[w,k]=nj("remoteDesktop.controlsHidden",!1),[j,N]=nj("remoteDesktop.pointerMode",P.eR.pointerMode),[S,C]=nj("remoteDesktop.handMode",!1),T=nk(),R=P.eR.pcModeControls,[E,_]=(0,r.useState)(!1);(0,r.useEffect)(()=>{let e=window.matchMedia("(orientation: landscape)"),t=()=>_(e.matches);return t(),e.addEventListener?.("change",t),()=>e.removeEventListener?.("change",t)},[]);let $=E&&Math.min(window.screen.width,window.screen.height)>=700;(0,r.useEffect)(()=>{"mouse"===T&&"direct"!==j&&N("direct")},[T,j,N]);let{stats:M,trackTilesReceived:A,resetStats:z}=function(){let[e,t]=(0,r.useState)(dW),s=(0,r.useRef)({frameCount:0,lastFpsTime:Date.now(),tilesReceived:0,lastTilesTime:Date.now(),bytesReceived:0,lastBandwidthTime:Date.now(),latencies:[],webrtcTilesTotal:0,wsTilesTotal:0});return{stats:e,trackTilesReceived:(0,r.useCallback)((e,n)=>{let r=s.current,a=Date.now();r.frameCount++;let l=e.tiles?.length||0;r.tilesReceived+=l;let i="number"==typeof e.bytes?e.bytes:e.tiles?.reduce((e,t)=>e+(t.imageBuffer?.byteLength||t.imageBuffer?.length||0),0)||0;if(r.bytesReceived+=i,e.timestamp){let t=Date.now()-e.timestamp;r.latencies.push({value:t,time:a}),r.latencies=r.latencies.filter(e=>a-e.time<6e4)}if(n?.startsWith("dc")||"webrtc"===n?r.webrtcTilesTotal+=l:r.wsTilesTotal+=l,a-r.lastFpsTime>=500){let e=(a-r.lastFpsTime)/1e3,s=Math.round(r.frameCount/e),n=r.latencies.length>0?Math.round(r.latencies.reduce((e,t)=>e+t.value,0)/r.latencies.length):0,l=Math.round(r.tilesReceived/e),i=(r.bytesReceived/e/1024/1024).toFixed(2),o=r.webrtcTilesTotal+r.wsTilesTotal,c=o>0?Math.round(r.webrtcTilesTotal/o*100):0;t({fps:s,latency:n,tilesPerSec:l,bandwidthMBps:parseFloat(i),webrtcTiles:r.webrtcTilesTotal,wsTiles:r.wsTilesTotal,webrtcPercent:c}),r.frameCount=0,r.tilesReceived=0,r.bytesReceived=0,r.lastFpsTime=a}},[]),resetStats:(0,r.useCallback)(()=>{let e=s.current;e.frameCount=0,e.lastFpsTime=Date.now(),e.tilesReceived=0,e.lastTilesTime=Date.now(),e.bytesReceived=0,e.lastBandwidthTime=Date.now(),e.latencies=[],e.webrtcTilesTotal=0,e.wsTilesTotal=0,t(dW)},[])}}(),[I,L]=(0,r.useState)(P.eR.debug?.panel??!1),[D,F]=(0,r.useState)(!1),O=P.eR.enableWebRTC?"rtc":"ws",B=(0,r.useCallback)(()=>{let e={mode:O,...M,ts:new Date().toISOString()};navigator.clipboard?.writeText(JSON.stringify(e,null,2)).catch(()=>{})},[M,O]),W=(0,r.useRef)(M);(0,r.useEffect)(()=>{W.current=M},[M]),(0,r.useEffect)(()=>{(0,g.c)("remote",`[stats] interval started, mode=${O}`);let e=setInterval(()=>{(0,g.c)("remote",`[stats][${O}]`,JSON.stringify(W.current))},5e3);return()=>{(0,g.c)("remote","[stats] interval stopped"),clearInterval(e)}},[O]);let{streaming:K,emitRequestScreenWithHashes:H,emitMousePress:U,emitMouseRelease:q,emitMouseClick:V,emitMouseMove:X,emitMouseDragSelect:G,emitKeyPress:J,emitTypeText:Y,emitScroll:Z,emitBoostStream:Q,emitSetFocus:ee,emitDesktopSwitch:et}=function(e,t){let[s,n]=(0,r.useState)(!1);(0,r.useEffect)(()=>{if(t&&e?.current)return n(!0),()=>n(!1)},[t,e]);let a=(0,r.useCallback)((t,s)=>{e?.current?.emit(t,s)},[e]),l=(0,r.useCallback)((e,t,n="left")=>{s&&a("mouse-press",{x:e,y:t,button:n})},[a,s]),i=(0,r.useCallback)((e,t,n="left")=>{s&&a("mouse-release",{x:e,y:t,button:n})},[a,s]),o=(0,r.useCallback)((e,t,n="left",r=!1)=>{s&&a("mouse-click",{x:e,y:t,button:n,double:r})},[a,s]),c=(0,r.useCallback)((e,t)=>{s&&a("mouse-move",{x:e,y:t})},[a,s]),d=(0,r.useCallback)((e,t,n,r)=>{s&&a("mouse-drag-select",{startX:e,startY:t,endX:n,endY:r})},[a,s]),u=(0,r.useCallback)((e,t=[])=>{s&&a("key-press",{key:e,modifier:t})},[a,s]),m=(0,r.useCallback)(e=>{s&&a("type-text",{text:e})},[a,s]),x=(0,r.useCallback)((e,t=20,n=!1)=>{s&&a("scroll",{direction:e,amount:t,horizontal:n})},[a,s]),p=(0,r.useCallback)(()=>{s&&a("boost-stream")},[a,s]),h=(0,r.useCallback)((e,t=1)=>{s&&a("set-focus",{rect:e,zoom:t,viewerWidth:window.innerWidth,dpr:window.devicePixelRatio||1})},[a,s]),f=(0,r.useCallback)(e=>{s&&a("request-screen-with-hashes",{tileHashes:e})},[a,s]),b=(0,r.useCallback)(e=>{s&&a("desktop-switch",{direction:e})},[a,s]);return{streaming:s,emitRequestScreenWithHashes:f,emitMousePress:l,emitMouseRelease:i,emitMouseClick:o,emitMouseMove:c,emitMouseDragSelect:d,emitKeyPress:u,emitTypeText:m,emitScroll:x,emitBoostStream:p,emitSetFocus:h,emitDesktopSwitch:b}}(t,l),es={emitRequestScreenWithHashes:H,emitMousePress:U,emitMouseRelease:q,emitMouseClick:V,emitMouseMove:X,emitMouseDragSelect:G,emitKeyPress:J,emitTypeText:Y,emitScroll:Z,emitBoostStream:Q},en=(0,r.useCallback)(()=>{x(!0)},[]);(0,r.useEffect)(()=>{i&&(0,g.c)("remote",`[remote] carrier: ${i}`)},[i]);let{canvasRef:er,canvasContainerRef:ea,canvasZoom:el,canvasPan:ei,fitScale:eo,baseCanvasSize:ec,zoomGestureTimeoutRef:ed,clickIndicator:eu,virtualCursor:em,handHolding:ex,scrollLock:ep,getCanvasCoordinates:eh,resetZoom:ef,resetPan:eb,panForKeyboard:eg,centerVirtualCursor:ev,startHandHold:ey,releaseHandHold:ew,handleCanvasInteraction:ek,handleCanvasDimensions:ej,serverDimensionsRef:eN}=function(e){let t=function(){let e=(0,r.useRef)(null),t=(0,r.useRef)(null),[s,n]=(0,r.useState)(1),[a,l]=(0,r.useState)({x:0,y:0}),[i,o]=(0,r.useState)(1),[c,d]=(0,r.useState)({width:0,height:0}),u=(0,r.useRef)({width:0,height:0}),m=(0,r.useRef)({x:0,y:0}),x=i*s,p=(0,r.useCallback)(()=>{let e=t.current;return e?{width:e.clientWidth,height:e.clientHeight}:null},[]),h=(0,r.useCallback)(e=>({width:c.width*e,height:c.height*e}),[c]),f=(0,r.useCallback)((n,r)=>{let l=e.current,o=t.current;return l&&o&&0!==l.width?function({canvasPoint:e,canvasWidth:t,canvasHeight:s}){return{percentX:dE(e.x/t*100,0,100),percentY:dE(e.y/s*100,0,100)}}({canvasPoint:d_({clientX:n,clientY:r,containerRect:o.getBoundingClientRect(),pan:a,totalScale:i*s}),canvasWidth:l.width,canvasHeight:l.height}):{percentX:0,percentY:0}},[a,s,i]),b=(0,r.useCallback)((e,t)=>{let n=i*s;n<=0||(m.current={x:(e-a.x)/n,y:(t-a.y)/n})},[i,s,a]),g=(0,r.useCallback)(()=>{n(1),l({x:0,y:0})},[]),v=(0,r.useCallback)(()=>l({x:0,y:0}),[]),y=(0,r.useCallback)((e,t)=>{let n=p();if(!n)return;let r=i*s;if(r<=0)return;let a=t||m.current,o=d$(n,h(s));l(t=>{if(!e||s<=1)return dM(t,o);let{y:l}=function({focus:e,containerHeight:t,totalScale:s}){return{y:t/3-e.y*s}}({focus:a,containerHeight:n.height,totalScale:r});return dM({x:t.x,y:l},o)})},[p,h,i,s]),w=(0,r.useCallback)(()=>{let s,n=t.current,r=e.current,a=u.current;if(!n||!r||0===a.width||0===a.height)return;let l=(s={width:n.clientWidth,height:n.clientHeight},Math.min(s.width/a.width,s.height/a.height));o(l),d({width:a.width*l,height:a.height*l})},[]);(0,r.useEffect)(()=>{let e=null,s=null,n=()=>{let e=t.current;if(!e)return void w();let n=e.clientWidth,r=e.clientHeight,a=0,l=0,i=()=>{let t=e.clientWidth,o=e.clientHeight;if(t===n&&o===r){if(++a>=P.eR.resizeStableFrames){s=null,w();return}}else a=0,n=t,r=o;if(l++>=P.eR.resizeMaxFrames){s=null,w();return}s=requestAnimationFrame(i)};s=requestAnimationFrame(i)},r=()=>{e&&clearTimeout(e),s&&(cancelAnimationFrame(s),s=null),e=setTimeout(n,P.eR.resizeDebounceMs)};return window.addEventListener("resize",r),window.addEventListener("orientationchange",r),window.visualViewport&&window.visualViewport.addEventListener("resize",r),()=>{e&&clearTimeout(e),s&&cancelAnimationFrame(s),window.removeEventListener("resize",r),window.removeEventListener("orientationchange",r),window.visualViewport&&window.visualViewport.removeEventListener("resize",r)}},[w]),(0,r.useEffect)(()=>{l(e=>{let n=t.current;if(!n)return e;let r=dM(e,d$({width:n.clientWidth,height:n.clientHeight},{width:c.width*s,height:c.height*s}));return r.x===e.x&&r.y===e.y?e:r})},[c,s]);let k=(0,r.useCallback)((s,n)=>{u.current={width:s.width,height:s.height};let r=e.current,a=t.current;if(!r||!a)return!1;let l=r.width!==s.width||r.height!==s.height;r.width=s.width,r.height=s.height;let i=r.getContext("2d");return i.imageSmoothingEnabled=!1,l&&(i.clearRect(0,0,r.width,r.height),i.fillStyle="#2a2a2a",i.fillRect(0,0,r.width,r.height),n?.current&&n.current.clear()),w(),l},[w]);return{canvasRef:e,canvasContainerRef:t,canvasZoom:s,setCanvasZoom:n,canvasPan:a,setCanvasPan:l,fitScale:i,totalScale:x,baseCanvasSize:c,serverDimensionsRef:u,containerSize:p,displaySizeAt:h,getCanvasCoordinates:f,recordInteractPx:b,resetZoom:g,resetPan:v,panForKeyboard:y,handleCanvasDimensions:k}}(),{canvasRef:s,canvasContainerRef:n,canvasZoom:a,setCanvasZoom:l,canvasPan:i,setCanvasPan:o,fitScale:c,baseCanvasSize:d,containerSize:u,displaySizeAt:m,getCanvasCoordinates:x,recordInteractPx:p}=t,[h,f]=(0,r.useState)(!1),[b,g]=(0,r.useState)(!1),v=(0,r.useRef)(0),y=(0,r.useRef)({x:0,y:0}),[w,k]=(0,r.useState)(!1),j=(0,r.useRef)(null),[N,S]=(0,r.useState)(null),C=(0,r.useRef)(null),T=(0,r.useRef)(!1),R=(0,r.useRef)({x:0,y:0}),E=(0,r.useRef)(0),_=(0,r.useRef)({x:0,y:0}),[$,M]=(0,r.useState)(!1),A=(0,r.useRef)({x:0,y:0}),z=(0,r.useRef)({x:0,y:0}),I=(0,r.useRef)(0),L=(0,r.useRef)(null),[D,F]=(0,r.useState)({x:0,y:0}),O=(0,r.useRef)(0),B=(0,r.useRef)(0),W=(0,r.useRef)(null),K=(0,r.useRef)({time:0,distance:0,centerX:0,centerY:0}),H=(0,r.useRef)(!1),U=(0,r.useRef)(0),q=(0,r.useRef)(!1),V=(0,r.useRef)(null),X=(0,r.useRef)(!1),[G,J]=(0,r.useState)(!1),Y=(0,r.useRef)(null),Z=(0,r.useRef)(!1),[Q,ee]=(0,r.useState)(!1),et=(0,r.useRef)(null),es=(0,r.useRef)({x:0,y:0}),en=(0,r.useRef)(!1),er=(0,r.useRef)(null),ea=(0,r.useRef)(0),el=(0,r.useCallback)((e,t)=>{let s=n.current;if(!s)return;let r=s.getBoundingClientRect(),l=e-r.left,i=t-r.top,o=dE(7.5*a,5,15);p(l,i),S({x:l,y:i,size:o}),setTimeout(()=>S(null),500)},[a,n,p]),ei=(0,r.useCallback)(()=>{C.current&&(clearTimeout(C.current),C.current=null)},[]),eo=(0,r.useCallback)((t,s,n,r)=>{ei(),T.current=!1,R.current={x:t,y:s},C.current=setTimeout(()=>{T.current=!0,el(t,s),e?.emitMouseClick(n,r,"right")},P.eR.longPressDelay)},[ei,el,e]),ec=(0,r.useCallback)((e,t)=>{let s=Date.now(),n=function({now:e,lastTime:t,lastPos:s,x:n,y:r,cfg:a}){let l=Math.abs(n-s.x),i=Math.abs(r-s.y);return e-t<a.doubleClickDelay&&l<a.moveThreshold&&i<a.moveThreshold}({now:s,lastTime:E.current,lastPos:_.current,x:e,y:t,cfg:P.eR});return E.current=s,_.current={x:e,y:t},n},[]),ed=(0,r.useCallback)(()=>{L.current&&(cancelAnimationFrame(L.current),L.current=null),z.current={x:0,y:0},A.current={x:0,y:0},M(!1)},[]),eu=(0,r.useCallback)(()=>{let t=()=>{var s,n;let r=(s=z.current,n=P.eR,Math.abs(s.y)<n.momentumMinVelocity?null:{scrollY:Math.round(s.y*n.edgeScrollMultiplier),nextVelocity:{x:s.x*n.momentumFriction,y:s.y*n.momentumFriction}});if(!r)return ed();Math.abs(r.scrollY)>=1&&e?.emitScroll(r.scrollY>0?"up":"down",Math.abs(r.scrollY),!1),z.current=r.nextVelocity,L.current=requestAnimationFrame(t)};L.current=requestAnimationFrame(t)},[e,ed]);(0,r.useEffect)(()=>()=>{ei(),ed()},[ei,ed]);let em=(0,r.useCallback)(t=>{let{edgeScrollThreshold:s,edgeScrollMultiplier:n}=P.eR,r=dA({accum:A.current.y,delta:t,threshold:s,multiplier:n});A.current.y=r.accum,r.scroll&&e?.emitScroll(r.scroll>0?"up":"down",Math.abs(r.scroll),!1)},[e]),ex=(0,r.useCallback)(t=>{let{edgeScrollThreshold:s,edgeScrollMultiplier:n}=P.eR,r=dA({accum:A.current.x,delta:t,threshold:s,multiplier:n});A.current.x=r.accum,r.scroll&&e?.emitScroll(r.scroll>0?"right":"left",Math.abs(r.scroll),!0)},[e]),ep=(0,r.useCallback)((e,t)=>({percentX:dE(e.x/t.width*100,0,100),percentY:dE(e.y/t.height*100,0,100)}),[]),eh=(0,r.useCallback)(t=>{let n=s.current;if(!n||0===n.width)return;let{percentX:r,percentY:a}=ep(t,n);e?.emitMouseMove?.(r,a)},[e,s,ep]);(0,r.useEffect)(()=>{let t=t=>{if(null==et.current||t.pointerType&&"mouse"!==t.pointerType)return;let r=s.current,a=n.current;if(!r||!a)return;let{percentX:l,percentY:i}=x(t.clientX,t.clientY),o=et.current;et.current=null,e?.emitMouseRelease?.(l,i,o)};return window.addEventListener("pointerup",t),window.addEventListener("pointercancel",t),()=>{window.removeEventListener("pointerup",t),window.removeEventListener("pointercancel",t)}},[x,e,s,n]);let ef=(0,r.useCallback)((t,r,d)=>{let{streaming:p,pointerMode:N="direct"}=d;if(!p||!e)return;let S={canvasRef:s,canvasContainerRef:n,containerSize:u,displaySizeAt:m,getCanvasCoordinates:x,socketEmitFunctions:e,canvasZoom:a,fitScale:c,virtualCursor:D,canvasPan:i,setCanvasZoom:l,setCanvasPan:o,setVirtualCursor:F,isZooming:h,isPanning:b,isEdgeScrolling:$,recentZoomGesture:w,lastTouchDistanceRef:v,lastTouchCenterRef:y,setIsZooming:f,setIsPanning:g,setIsEdgeScrolling:M,setRecentZoomGesture:k,gestureLockRef:W,gestureStartRef:K,multiTouchLatchRef:H,twoFingerMaxMovedRef:U,touchOutsideRef:q,longPressTriggeredRef:T,touchStartPosRef:R,edgeScrollAccumRef:A,velocityRef:z,lastTouchTimeRef:I,touchStartTimeRef:O,touchTotalMoveRef:B,handLongPressTimerRef:V,handHoldingRef:X,setHandHolding:J,scrollLongPressTimerRef:Y,scrollLockRef:Z,setScrollLock:ee,mouseDownButtonRef:et,wheelAccumRef:es,wheelActiveRef:en,wheelEndTimerRef:er,wheelLastBoostRef:ea,zoomGestureTimeoutRef:j,showClickIndicator:el,cancelLongPress:ei,startLongPress:eo,checkDoubleClick:ec,stopMomentum:ed,startMomentumScroll:eu,emitScrollFromDelta:em,emitHScrollFromDelta:ex,cursorPercent:ep,emitVirtualCursor:eh};if(t.nativeEvent?.pointerType==="mouse"||"wheel"===t.type||"contextmenu"===t.type||"dblclick"===t.type)return("wheel"===t.type||"contextmenu"===t.type)&&t.preventDefault(),function(e,t,s,n){let{socketEmitFunctions:r,getCanvasCoordinates:a,showClickIndicator:l}=e,{streaming:i,selectionMode:o,handleSelection:c}=n;if(!i||!r)return;let d=P.eR.mouseButtonMap[t.button]||"left";if("wheel"===s){var u,m;let{percentX:s,percentY:n}=a(t.clientX,t.clientY),l=(u=t.deltaMode,m=P.eR,1===u?m.wheelLineHeight:2===u?m.wheelPageHeight:1),i=t.deltaY*l,o=t.deltaX*l;if(t.ctrlKey||t.metaKey){let s=e.canvasContainerRef.current,n=e.canvasRef.current;if(!s||!n)return;let r=s.getBoundingClientRect(),a={x:t.clientX-r.left,y:t.clientY-r.top},l={width:s.clientWidth,height:s.clientHeight},o=i>0?-1:1;e.setCanvasZoom(t=>{let s=dE(t+o*P.eR.wheelZoomStep,1,4);return s===t?t:(e.setCanvasPan(n=>dP({prevZoom:t,prevPan:n,focal:a,nextZoomRaw:s,maxZoom:4,containerSize:l,displaySizeAt:e.displaySizeAt}).pan),s)});return}if(e.wheelActiveRef.current){let t=Date.now();t-e.wheelLastBoostRef.current>=P.eR.wheelBoostInterval&&(r.emitBoostStream?.(),e.wheelLastBoostRef.current=t)}else r.emitBoostStream?.(),r.emitMouseMove?.(s,n),e.wheelActiveRef.current=!0,e.wheelLastBoostRef.current=Date.now();e.wheelEndTimerRef.current&&clearTimeout(e.wheelEndTimerRef.current),e.wheelEndTimerRef.current=setTimeout(()=>{e.wheelActiveRef.current=!1,e.wheelAccumRef.current.x=0},150);let c=P.eR.wheelScrollMultiplier;if(i&&e.emitScrollFromDelta(-i*c),o){let{edgeScrollThreshold:t,edgeScrollMultiplier:s}=P.eR,n=dA({accum:e.wheelAccumRef.current.x,delta:o*c,threshold:t,multiplier:s});e.wheelAccumRef.current.x=n.accum,n.scroll&&r.emitScroll?.(n.scroll>0?"right":"left",Math.abs(n.scroll),!0)}return}if("contextmenu"===s){let{percentX:e,percentY:s}=a(t.clientX,t.clientY);l(t.clientX,t.clientY),r.emitMouseClick?.(e,s,"right");return}if("dblclick"===s)return;if(o){"pointerdown"===s?c?.(t.clientX,t.clientY,"start"):"pointermove"===s&&null!=e.mouseDownButtonRef.current?c?.(t.clientX,t.clientY,"move"):"pointerup"===s&&(c?.(t.clientX,t.clientY,"end"),e.mouseDownButtonRef.current=null),"pointerdown"===s&&(e.mouseDownButtonRef.current=d);return}let{percentX:x,percentY:p}=a(t.clientX,t.clientY);if("pointerdown"===s){e.mouseDownButtonRef.current=d,l(t.clientX,t.clientY),r.emitMousePress?.(x,p,d);return}if("pointermove"===s){null!=e.mouseDownButtonRef.current&&r.emitMouseMove?.(x,p);return}if("pointerup"===s){let t=e.mouseDownButtonRef.current||d;e.mouseDownButtonRef.current=null,r.emitMouseRelease?.(x,p,t)}}(S,t,r,d);t.preventDefault(),t.type.startsWith("touch")&&t.touches?.length>=2&&(H.current=!0,Y.current&&(clearTimeout(Y.current),Y.current=null),Z.current&&(Z.current=!1,ee(!1),A.current={x:0,y:0}),V.current&&(clearTimeout(V.current),V.current=null)),"trackpad"===N&&t.type.startsWith("touch")&&function(e,t,s,n){let r=e.canvasRef.current;if(!r||0===r.width)return!0;let{selectionMode:a,dragMode:l,isDragging:i,setIsDragging:o,setDragMode:c,handleSelection:d,handMode:u=!1,onHandRelease:m}=n;if(t.touches?.length>=2||!(!e.multiTouchLatchRef.current&&(t.touches?.length===1||"touchend"===s)))return!1;let x=t.touches?.[0]||t.changedTouches?.[0];if(!x)return!0;if("touch"===s){if(e.touchStartTimeRef.current=Date.now(),e.touchTotalMoveRef.current=0,e.lastTouchCenterRef.current={x:x.clientX,y:x.clientY},e.lastTouchTimeRef.current=Date.now(),a){let{percentX:t,percentY:s}=e.cursorPercent(e.virtualCursor,r);return d?.(0,0,"start",{...n,percentOverride:{percentX:t,percentY:s}}),!0}return u&&!e.handHoldingRef.current&&(e.handLongPressTimerRef.current&&clearTimeout(e.handLongPressTimerRef.current),e.handLongPressTimerRef.current=setTimeout(()=>{e.handLongPressTimerRef.current=null;let t=e.canvasRef.current;if(!t||0===t.width)return;let{percentX:s,percentY:n}=e.cursorPercent(e.virtualCursor,t);e.handHoldingRef.current=!0,e.setHandHolding(!0),(0,t7.e)(15),e.socketEmitFunctions.emitMousePress?.(s,n,"left")},P.eR.longPressDelay)),u||e.scrollLockRef.current||(e.scrollLongPressTimerRef.current&&clearTimeout(e.scrollLongPressTimerRef.current),e.scrollLongPressTimerRef.current=setTimeout(()=>{e.scrollLongPressTimerRef.current=null,e.scrollLockRef.current=!0,e.setScrollLock(!0),e.edgeScrollAccumRef.current={x:0,y:0},(0,t7.e)(15)},P.eR.longPressDelay)),!0}if("touchmove"===s){let t=x.clientX-e.lastTouchCenterRef.current.x,s=x.clientY-e.lastTouchCenterRef.current.y;if(e.touchTotalMoveRef.current+=Math.abs(t)+Math.abs(s),e.scrollLockRef.current)return e.emitScrollFromDelta(s),e.emitHScrollFromDelta(t),e.lastTouchCenterRef.current={x:x.clientX,y:x.clientY},e.lastTouchTimeRef.current=Date.now(),!0;e.scrollLongPressTimerRef.current&&e.touchTotalMoveRef.current>P.eR.trackpadTapMaxMove&&(clearTimeout(e.scrollLongPressTimerRef.current),e.scrollLongPressTimerRef.current=null);let l=Date.now(),i=function({deltaX:e,deltaY:t,dt:s,cfg:n}){let r=Math.sqrt(e*e+t*t)/s,a=1+Math.min(n.trackpadAcceleration,r*n.trackpadAcceleration);return n.trackpadSensitivity*a}({deltaX:t,deltaY:s,dt:Math.max(1,l-e.lastTouchTimeRef.current),cfg:P.eR}),o=Math.max(1e-4,e.fitScale*e.canvasZoom),c=t*i/o,m=s*i/o;return a?e.setVirtualCursor(t=>{let s={x:dE(t.x+c,0,r.width-1),y:dE(t.y+m,0,r.height-1)},{percentX:a,percentY:l}=e.cursorPercent(s,r);return e.emitVirtualCursor(s),d?.(0,0,"move",{...n,percentOverride:{percentX:a,percentY:l}}),s}):(u&&!e.handHoldingRef.current&&e.handLongPressTimerRef.current&&e.touchTotalMoveRef.current>P.eR.trackpadTapMaxMove&&(clearTimeout(e.handLongPressTimerRef.current),e.handLongPressTimerRef.current=null),e.setVirtualCursor(t=>{let s={x:dE(t.x+c,0,r.width-1),y:dE(t.y+m,0,r.height-1)};if(e.emitVirtualCursor(s),e.handHoldingRef.current){let{percentX:t,percentY:n}=e.cursorPercent(s,r);e.socketEmitFunctions.emitMouseMove?.(t,n)}let n=e.containerSize();if(n&&e.canvasZoom>1){let t={width:r.width*o,height:r.height*o},a=d$(n,t);e.setCanvasPan(e=>{let r=function({cursor:e,pan:t,containerSize:s,displaySize:n,totalScale:r,marginRatio:a}){let l=s.width*a,i=s.height*a,o=e.x*r+t.x,c=e.y*r+t.y,d={x:0,y:0};return o<l?d.x=l-o:o>s.width-l&&(d.x=-(o-(s.width-l))),c<i?d.y=i-c:c>s.height-i&&(d.y=-(c-(s.height-i))),d}({cursor:s,pan:e,containerSize:n,displaySize:t,totalScale:o,marginRatio:P.eR.trackpadEdgeMarginRatio});return dM({x:e.x+r.x,y:e.y+r.y},a)})}return s})),e.lastTouchCenterRef.current={x:x.clientX,y:x.clientY},e.lastTouchTimeRef.current=l,!0}if("touchend"===s){if(a){let{percentX:t,percentY:s}=e.cursorPercent(e.virtualCursor,r);return d?.(0,0,"end",{...n,percentOverride:{percentX:t,percentY:s}}),!0}if(u){if(e.handLongPressTimerRef.current&&(clearTimeout(e.handLongPressTimerRef.current),e.handLongPressTimerRef.current=null),e.handHoldingRef.current){let{percentX:t,percentY:s}=e.cursorPercent(e.virtualCursor,r);e.socketEmitFunctions.emitMouseRelease?.(t,s,"left"),e.handHoldingRef.current=!1,e.setHandHolding(!1),m?.()}return!0}if(e.scrollLongPressTimerRef.current&&(clearTimeout(e.scrollLongPressTimerRef.current),e.scrollLongPressTimerRef.current=null),e.scrollLockRef.current)return e.scrollLockRef.current=!1,e.setScrollLock(!1),e.edgeScrollAccumRef.current={x:0,y:0},!0;let t=Date.now()-e.touchStartTimeRef.current;if(e.touchTotalMoveRef.current<=P.eR.trackpadTapMaxMove&&t<=P.eR.trackpadTapMaxDuration){let{percentX:t,percentY:s}=e.cursorPercent(e.virtualCursor,r),n=e.checkDoubleClick(e.virtualCursor.x,e.virtualCursor.y);l?i?(o(!1),c(!1),e.socketEmitFunctions.emitMouseRelease(t,s,"left")):(o(!0),e.socketEmitFunctions.emitMousePress(t,s,"left")):e.socketEmitFunctions.emitMouseClick(t,s,"left",n)}return!0}return!1}(S,t,r,d)||function(e,t,s,n){let r,a,{selectionMode:l,selectionStart:i,dragMode:o,isDragging:c,setIsDragging:d,setDragMode:u,isMobile:m,handleSelection:x,pointerMode:p="direct"}=n;if(t.type.startsWith("touch")&&t.touches?.length>=2&&!l){var h;let n,r,a,l=(n=(h=t.touches)[0].clientX-h[1].clientX,Math.sqrt(n*n+(r=h[0].clientY-h[1].clientY)*r)),i={x:((a=t.touches)[0].clientX+a[1].clientX)/2,y:(a[0].clientY+a[1].clientY)/2};if("touch"===s){e.setIsZooming(!0),e.lastTouchDistanceRef.current=l,e.lastTouchCenterRef.current=i,e.gestureLockRef.current=null,e.gestureStartRef.current={time:Date.now(),distance:l,centerX:i.x,centerY:i.y},e.twoFingerMaxMovedRef.current=0;return}if("touchmove"===s&&e.isZooming){let t=e.canvasContainerRef.current;if(!t)return;if(null===e.gestureLockRef.current){let t=Date.now()-e.gestureStartRef.current.time,s=Math.abs(l-e.gestureStartRef.current.distance),n=Math.sqrt((i.x-e.gestureStartRef.current.centerX)**2+(i.y-e.gestureStartRef.current.centerY)**2);e.twoFingerMaxMovedRef.current=Math.max(e.twoFingerMaxMovedRef.current,s,n),e.gestureLockRef.current=function({elapsed:e,deltaDistance:t,deltaCentroid:s,cfg:n}){let r=t>=n.gestureDistanceThreshold,a=s>=n.gestureCentroidThreshold;if(!r&&!a&&e<n.gestureLockDelay)return null;let l=s>.5?t/s:1/0;return l>=n.gestureDominanceRatio&&r?"zoom":l<=1/n.gestureDominanceRatio&&a?"scroll":r&&!a?"zoom":a&&!r?"scroll":null}({elapsed:t,deltaDistance:s,deltaCentroid:n,cfg:P.eR})}if("scroll"===e.gestureLockRef.current){let t=i.y-e.lastTouchCenterRef.current.y;if(!e.isEdgeScrolling){let t=e.canvasRef.current,s="trackpad"===p&&t&&t.width>0?e.cursorPercent(e.virtualCursor,t):e.getCanvasCoordinates(i.x,i.y);e.socketEmitFunctions?.emitBoostStream?.(),e.socketEmitFunctions?.emitMouseMove?.(s.percentX,s.percentY),e.setIsEdgeScrolling(!0)}e.emitScrollFromDelta(t),e.lastTouchDistanceRef.current=l,e.lastTouchCenterRef.current=i;return}if("zoom"===e.gestureLockRef.current&&e.lastTouchDistanceRef.current>0){let s=t.getBoundingClientRect(),n={width:t.clientWidth,height:t.clientHeight},r={x:i.x-s.left,y:i.y-s.top},a=e.canvasZoom*(l/e.lastTouchDistanceRef.current);e.setCanvasPan(t=>dP({prevZoom:e.canvasZoom,prevPan:t,focal:r,nextZoomRaw:a,maxZoom:4,containerSize:n,displaySizeAt:e.displaySizeAt}).pan),e.setCanvasZoom(dE(a,1,4)),e.lastTouchDistanceRef.current=l}e.lastTouchCenterRef.current=i;return}}if(t.type.startsWith("touch")&&t.touches?.length===1){let n=t.touches[0];if(e.isZooming){e.lastTouchCenterRef.current={x:n.clientX,y:n.clientY};return}if("touch"===s){if(e.lastTouchCenterRef.current={x:n.clientX,y:n.clientY},e.lastTouchTimeRef.current=Date.now(),e.velocityRef.current={x:0,y:0},e.edgeScrollAccumRef.current={x:0,y:0},e.stopMomentum(),e.touchOutsideRef.current=!function(e,t,s){let n=e.canvasRef.current,r=e.canvasContainerRef.current;if(!n||!r||0===n.width)return!1;let a=d_({clientX:t,clientY:s,containerRect:r.getBoundingClientRect(),pan:e.canvasPan,totalScale:e.fitScale*e.canvasZoom});return a.x>=0&&a.x<=n.width&&a.y>=0&&a.y<=n.height}(e,n.clientX,n.clientY),l)x(n.clientX,n.clientY,"start");else if(!o&&!e.touchOutsideRef.current){let{percentX:t,percentY:s}=e.getCanvasCoordinates(n.clientX,n.clientY);e.startLongPress(n.clientX,n.clientY,t,s)}return}if("touchmove"===s){let t=Math.abs(n.clientX-e.touchStartPosRef.current.x),s=Math.abs(n.clientY-e.touchStartPosRef.current.y);if((t>P.eR.moveThreshold||s>P.eR.moveThreshold)&&e.cancelLongPress(),l&&i)return x(n.clientX,n.clientY,"move");if(!l&&!o){let t=n.clientX-e.lastTouchCenterRef.current.x,s=n.clientY-e.lastTouchCenterRef.current.y,r=Date.now(),a=r-e.lastTouchTimeRef.current;if(a>0&&(e.velocityRef.current={x:t/a*16,y:s/a*16},e.lastTouchTimeRef.current=r),Math.abs(t)>5||Math.abs(s)>5){e.cancelLongPress();let r=e.getCanvasCoordinates(n.clientX,n.clientY),a=Math.abs(s)>1.5*Math.abs(t),l=t=>{a&&(e.isEdgeScrolling||(e.socketEmitFunctions?.emitBoostStream?.(),e.socketEmitFunctions?.emitMouseMove?.(r.percentX,r.percentY),e.setIsEdgeScrolling(!0)),e.emitScrollFromDelta(t))};if(1===e.canvasZoom){a&&l(s),e.lastTouchCenterRef.current={x:n.clientX,y:n.clientY};return}e.setIsPanning(!0);let i=e.containerSize()||{width:0,height:0},o=e.displaySizeAt(e.canvasZoom);e.setCanvasPan(n=>{let r=function({prevPan:e,deltaX:t,deltaY:s,containerSize:n,displaySize:r}){let a=d$(n,r),l=dM({x:e.x+t,y:e.y+s},a),i=Math.abs(l.y-e.y)>.5?0:e.y+s-l.y;return{pan:l,overflowY:i}}({prevPan:n,deltaX:t,deltaY:s,containerSize:i,displaySize:o});return Math.abs(r.overflowY)>0?l(r.overflowY):(e.edgeScrollAccumRef.current.y=0,e.setIsEdgeScrolling(!1)),r.pan}),e.lastTouchCenterRef.current={x:n.clientX,y:n.clientY}}return}}}if("touchend"===s){if(e.cancelLongPress(),"trackpad"===p&&e.isZooming&&0===(t.touches?.length||0)&&null===e.gestureLockRef.current&&Date.now()-e.gestureStartRef.current.time<=P.eR.trackpadTapMaxDuration&&e.twoFingerMaxMovedRef.current<=P.eR.trackpadTapMaxMove){let t=e.canvasRef.current;if(t&&t.width>0&&e.socketEmitFunctions?.emitMouseClick){let{percentX:s,percentY:n}=e.cursorPercent(e.virtualCursor,t);e.socketEmitFunctions.emitMouseClick(s,n,"right"),(0,t7.e)(15)}}e.gestureLockRef.current=null,0===(t.touches?.length||0)&&(e.multiTouchLatchRef.current=!1);let s=e.isZooming,n=e.isPanning,r=e.isEdgeScrolling,a=e.longPressTriggeredRef.current;if(e.longPressTriggeredRef.current=!1,s&&(e.setRecentZoomGesture(!0),e.zoomGestureTimeoutRef.current&&clearTimeout(e.zoomGestureTimeoutRef.current),e.zoomGestureTimeoutRef.current=setTimeout(()=>e.setRecentZoomGesture(!1),200)),r&&(Math.abs(e.velocityRef.current.x)>P.eR.momentumMinVelocity||Math.abs(e.velocityRef.current.y)>P.eR.momentumMinVelocity)?e.startMomentumScroll():e.stopMomentum(),e.setIsZooming(!1),e.setIsPanning(!1),s||n||r||e.recentZoomGesture||a)return;if(t.type.startsWith("touch")){let s=t.changedTouches?.[0];if(s){if(l)x(s.clientX,s.clientY,"end");else if(!e.touchOutsideRef.current){let{percentX:t,percentY:n}=e.getCanvasCoordinates(s.clientX,s.clientY);if(e.showClickIndicator(s.clientX,s.clientY),o)c?(d(!1),u(!1),e.socketEmitFunctions.emitMouseRelease(t,n,"left")):(d(!0),e.socketEmitFunctions.emitMousePress(t,n,"left"));else{let r=e.checkDoubleClick(s.clientX,s.clientY);e.socketEmitFunctions.emitMouseClick(t,n,"left",r)}}}}return}if(e.isZooming||e.isPanning)return;if(t.type.startsWith("touch")){if(t.touches?.length!==1)return;r=t.touches[0].clientX,a=t.touches[0].clientY}else r=t.clientX,a=t.clientY;let{percentX:f,percentY:b}=e.getCanvasCoordinates(r,a);if("click"===s)if(l)x(r,a,i?"end":"start");else if(e.showClickIndicator(r,a),o)c?(d(!1),u(!1),e.socketEmitFunctions.emitMouseRelease(f,b,"left")):(d(!0),e.socketEmitFunctions.emitMousePress(f,b,"left"));else{let t=e.checkDoubleClick(r,a);e.socketEmitFunctions.emitMouseClick(f,b,"left",t)}else if("move"===s&&!m){if(l&&i)return x(r,a,"move");e.socketEmitFunctions.emitMouseMove(f,b)}}(S,t,r,d)},[h,b,$,a,w,c,D,i,x,el,e,ei,eo,ec,ed,eu,eh,em,ex,s,n,u,m,o,l,ep]);(0,r.useEffect)(()=>{let e=s.current;e&&0!==e.width&&F(t=>0===t.x&&0===t.y?{x:e.width/2,y:e.height/2}:t)},[d,s]);let eb=(0,r.useCallback)(()=>{let e=s.current,t=u();if(!e||!t||0===e.width)return;let n=c*a;n<=0||F({x:dE((t.width/2-i.x)/n,0,e.width-1),y:dE((t.height/2-i.y)/n,0,e.height-1)})},[c,a,i,s,u]),eg=(0,r.useCallback)(()=>{let t=s.current;if(!t||0===t.width||X.current)return;V.current&&(clearTimeout(V.current),V.current=null);let{percentX:n,percentY:r}=ep(D,t);X.current=!0,J(!0),(0,t7.e)(15),e?.emitBoostStream?.(),e?.emitMousePress?.(n,r,"left")},[D,e,s,ep]),ev=(0,r.useCallback)(()=>{if(!X.current)return;let t=s.current,n=t&&t.width>0?D.x/t.width*100:0,r=t&&t.height>0?D.y/t.height*100:0;e?.emitMouseRelease?.(n,r,"left"),X.current=!1,J(!1)},[D,e,s]);return{canvasRef:s,canvasContainerRef:n,canvasZoom:a,canvasPan:i,fitScale:c,baseCanvasSize:d,zoomGestureTimeoutRef:j,clickIndicator:N,virtualCursor:D,handHolding:G,scrollLock:Q,getCanvasCoordinates:x,resetZoom:t.resetZoom,resetPan:t.resetPan,panForKeyboard:t.panForKeyboard,centerVirtualCursor:eb,startHandHold:eg,releaseHandHold:ev,handleCanvasInteraction:ef,handleCanvasDimensions:t.handleCanvasDimensions,serverDimensionsRef:t.serverDimensionsRef}}(es),eS=(0,r.useCallback)(()=>{N(e=>{let t="trackpad"===e?"direct":"trackpad";return"trackpad"===t&&ev(),t})},[ev,N]),{textInputValue:eC,setTextInputValue:eT,textInputRef:eR,modifierKeys:eE,selectionMode:e_,selectionStart:e$,selectionRect:eM,dragMode:eP,isDragging:eA,setIsDragging:ez,setDragMode:eI,toggleModifierKey:eL,toggleSelectionMode:eD,handleTextInputFocus:eF,handleCanvasKeyPress:eO,sendTextInput:eB,handleSelection:eW,handleModifiedTextInput:eK,handleDirectInputChange:eH,emitKeyWithActiveModifiers:eU}=function(e){let[t,s]=(0,r.useState)(""),[n,a]=(0,r.useState)(!1),[l,i]=(0,r.useState)(!1),o=(0,r.useRef)(null),[c,d]=(0,r.useState)({ctrl:!1,cmd:!1,alt:!1,shift:!1}),[u,m]=(0,r.useState)(!1),[x,p]=(0,r.useState)(null),[h,f]=(0,r.useState)(null),[b,g]=(0,r.useState)(!1),[v,y]=(0,r.useState)(!1),w=(0,r.useRef)(null);(0,r.useEffect)(()=>{let e=()=>{let e=window.innerWidth<=768||/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);return a(e),e},t=()=>{e()?i((window.visualViewport?.height||window.innerHeight)<.75*window.screen.height):i(!1)};return e(),window.addEventListener("resize",t),window.visualViewport&&window.visualViewport.addEventListener("resize",t),()=>{window.removeEventListener("resize",t),window.visualViewport&&window.visualViewport.removeEventListener("resize",t)}},[]),(0,r.useEffect)(()=>()=>{w.current&&clearInterval(w.current)},[]);let k=(0,r.useCallback)(e=>{d(t=>({...t,[e]:!t[e]})),n&&o.current&&o.current.focus()},[n]),j=(0,r.useCallback)(()=>{m(e=>!e),p(null),f(null)},[]),N=(0,r.useCallback)(()=>{g(e=>!e),v&&y(!1)},[v]),S=(0,r.useCallback)(()=>{},[]),C=(0,r.useCallback)((t,s)=>{if(!s||!e?.emitKeyPress)return;let n=t.key;if("Shift"===n||"Control"===n||"Meta"===n||"Alt"===n)return;"F12"!==n&&t.preventDefault();let r=[];t.ctrlKey&&r.push("control"),t.metaKey&&r.push("command"),t.altKey&&r.push("alt"),t.shiftKey&&r.push("shift");let a=Object.keys(c).filter(e=>c[e]);for(let e of a){let t=P.tC[e];t&&!r.includes(t)&&r.push(t)}let l=P.FO[n]??(1===n.length?n:n.toLowerCase());e.emitKeyPress(l,r),a.length>0&&d({ctrl:!1,cmd:!1,alt:!1,shift:!1})},[c,e]),T=(0,r.useCallback)((t,s,r=!1)=>{s&&e?.emitScroll&&(w.current&&clearInterval(w.current),e.emitScroll(t,20,r),w.current=setInterval(()=>{e?.emitScroll&&s&&e.emitScroll(t,20,r)},P.eR.scrollInterval),n&&o.current&&l&&setTimeout(()=>o.current?.focus(),10))},[n,l,e]),R=(0,r.useCallback)(e=>T("up",e),[T]),E=(0,r.useCallback)(e=>T("down",e),[T]),_=(0,r.useCallback)(e=>T("left",e,!0),[T]),$=(0,r.useCallback)(e=>T("right",e,!0),[T]),M=(0,r.useCallback)(()=>{w.current&&(clearInterval(w.current),w.current=null)},[]),A=na(e=>e.addCommand),z=(0,r.useCallback)(n=>{if(!n||!e?.emitTypeText)return;if(!t.trim())return void e.emitKeyPress?.("enter",[]);let r=document.activeElement===o.current;e.emitTypeText(t),A(t),s(""),r&&o.current?.focus()},[t,e,o,A]),I=(0,r.useRef)(""),L=(0,r.useRef)(null),D=(0,r.useCallback)((t,n)=>{n&&t&&e?.emitTypeText&&(I.current+=t,s(""),L.current&&clearTimeout(L.current),L.current=setTimeout(()=>{let t=I.current;I.current="",L.current=null,t&&e.emitTypeText(t)},150))},[e]),F=(0,r.useCallback)(t=>{if(!e?.emitKeyPress)return;let s=Object.keys(c).filter(e=>c[e]),n=s.map(e=>P.tC[e]);e.emitKeyPress(t,n),s.length>0&&d({ctrl:!1,cmd:!1,alt:!1,shift:!1})},[c,e]),O=(0,r.useCallback)(e=>{e&&(F("backspace"),n&&o.current&&l&&o.current.focus())},[n,l,F]),B=(0,r.useCallback)((e,t)=>{t&&(F(e),n&&o.current&&l&&o.current.focus())},[n,l,F]),W=(0,r.useCallback)(e=>{e&&(F("escape"),n&&o.current&&l&&o.current.focus())},[n,l,F]),K=(0,r.useCallback)(e=>{e&&(F("tab"),n&&o.current&&l&&o.current.focus())},[n,l,F]),H=(0,r.useCallback)((e,t)=>{t&&(F("enter"),e&&e.preventDefault(),n&&o.current&&l&&o.current.focus())},[n,l,F]),U=(0,r.useCallback)((t,s,n,r)=>{let{streaming:a,getCanvasCoordinates:l,baseCanvasSize:i,canvasZoom:o,canvasPan:c,percentOverride:d}=r;if(!u||!a||!e?.emitMouseDragSelect)return;let{percentX:h,percentY:b}=d||l(t,s);if("start"===n)p({x:h,y:b}),f(null);else if("move"===n&&x){let e=i.width*o,t=i.height*o;f({x:Math.min(x.x,h)*e/100+c.x,y:Math.min(x.y,b)*t/100+c.y,width:Math.abs(h-x.x)*e/100,height:Math.abs(b-x.y)*t/100})}else"end"===n&&x&&(e.emitMouseDragSelect(x.x,x.y,h,b),setTimeout(()=>{p(null),m(!1),f(null)},500))},[u,x,e]),q=(0,r.useCallback)((n,r,a=!1)=>{if(!r||!e?.emitTypeText||!e?.emitKeyPress)return;let l=n.key.toLowerCase();if(["shift","control","meta","alt"].includes(l)||"Unidentified"===n.key||229===n.keyCode)return;let i=Object.keys(c).filter(e=>c[e]),o=i.length>0,u=n.ctrlKey||n.metaKey||n.altKey||n.shiftKey;if(a){n.preventDefault();let t=i.map(e=>P.tC[e]);n.ctrlKey&&!t.includes("control")&&t.push("control"),n.metaKey&&!t.includes("command")&&t.push("command"),n.altKey&&!t.includes("alt")&&t.push("alt"),n.shiftKey&&!t.includes("shift")&&t.push("shift"),P.FO[l]?l=P.FO[l]:" "===l?l="space":1===n.key.length&&(l=n.key),e.emitKeyPress(l,t),o&&d({ctrl:!1,cmd:!1,alt:!1,shift:!1}),s("");return}if("Enter"===n.key){n.preventDefault(),t.trim()&&(e.emitTypeText(t),A(t),s(""));return}let m=/^[a-z0-9]$/i.test(n.key);if((o||u)&&(!m||o)){n.preventDefault();let t=i.map(e=>P.tC[e]);n.ctrlKey&&!t.includes("control")&&t.push("control"),n.metaKey&&!t.includes("command")&&t.push("command"),n.altKey&&!t.includes("alt")&&t.push("alt"),n.shiftKey&&!t.includes("shift")&&t.push("shift"),P.FO[l]?l=P.FO[l]:" "===l&&(l="space"),e.emitKeyPress(l,t),d({ctrl:!1,cmd:!1,alt:!1,shift:!1}),s("")}},[c,t,e,A]);return{textInputValue:t,setTextInputValue:s,textInputRef:o,keyboardVisible:l,modifierKeys:c,selectionMode:u,selectionStart:x,selectionRect:h,dragMode:b,isDragging:v,setIsDragging:y,setDragMode:g,toggleModifierKey:k,toggleSelectionMode:j,toggleDragMode:N,handleTextInputFocus:S,handleCanvasKeyPress:C,startScrollUp:R,startScrollDown:E,startScrollLeft:_,startScrollRight:$,stopScrolling:M,sendTextInput:z,sendBackspace:O,sendArrowKey:B,sendEscKey:W,sendTabKey:K,sendEnterKey:H,handleSelection:U,handleModifiedTextInput:q,handleDirectInputChange:D,emitKeyWithActiveModifiers:F}}(es),{keyboardOnRef:eq,toggleKeyboard:eV,toggleTextPanel:eX,handleTextInputBlur:eG}=function({streaming:e,keyboardOn:t,setKeyboardOn:s,showTextPanel:n,setShowTextPanel:a,textInputRef:l,canvasContainerRef:i,panForKeyboard:o,pointerMode:c,virtualCursor:d}){let u=(0,r.useRef)(t);(0,r.useEffect)(()=>{u.current=t},[t]);let m=(0,r.useCallback)(()=>{let e=!t;u.current=e,s(e),e?l.current?.focus():l.current?.blur()},[t]),x=(0,r.useRef)(!1);(0,r.useEffect)(()=>{e&&!x.current&&u.current&&(x.current=!0,l.current?.focus())},[e]);let p=(0,r.useCallback)(()=>{let e=!n;!e&&t&&l.current?.focus(),a(e)},[n,t]),h=(0,r.useCallback)(()=>{u.current&&!n&&setTimeout(()=>l.current?.focus(),0)},[n]),f=(0,r.useRef)(null);return(0,r.useEffect)(()=>{f.current="trackpad"===c?d:null},[c,d]),(0,r.useEffect)(()=>{let e=window.visualViewport;if(!e)return;let t=e.height,s=0,n=()=>{let n=e.height<t;t=e.height;let r=i.current;if(!r)return;let a=r.clientHeight;cancelAnimationFrame(s);let l=0,c=()=>{r.clientHeight!==a||l++>30?o(n,f.current):s=requestAnimationFrame(c)};s=requestAnimationFrame(c)};return e.addEventListener("resize",n),()=>{cancelAnimationFrame(s),e.removeEventListener("resize",n)}},[i,o]),{keyboardOnRef:u,toggleKeyboard:m,toggleTextPanel:p,handleTextInputBlur:h}}({streaming:K,keyboardOn:v,setKeyboardOn:y,showTextPanel:f,setShowTextPanel:b,textInputRef:eR,canvasContainerRef:ea,panForKeyboard:eg,pointerMode:j,virtualCursor:em}),eJ=(0,r.useCallback)((e,t=[],s=!1)=>{K&&(t.length>0?J(e,s&&"darwin"===o?t.map(e=>"control"===e?"command":e):t):eU(e))},[K,o,J,eU]),eY=(0,r.useCallback)(()=>{C(e=>{let t=!e;return t?(e_&&eD(),ey()):ew(),t})},[C,e_,eD,ey,ew]),eZ=function(e,t,n){let[a,l]=(0,r.useState)(126),[i,o]=(0,r.useState)(!1),c=(0,r.useRef)(new Set),d=(0,r.useRef)(new Map),u=(0,r.useRef)([]),m=(0,r.useRef)(!1),x=(0,r.useRef)(0),p=(0,r.useRef)(new Set),h=(0,r.useRef)(new Set),f=(0,r.useRef)(new Map),b=(0,r.useRef)(new Map),g=(0,r.useRef)(null),v=(0,r.useRef)(t);(0,r.useEffect)(()=>{v.current=t},[t]);let y=(0,r.useCallback)(()=>{g.current=null;let t=n?.current;if(!t)return void b.current.clear();let s=t.getContext("2d"),r=0;for(let[e,t]of b.current){let{bitmap:n,x:a,y:l,width:i,height:d,frameTs:u,invalidateTileHash:m}=t;if((f.current.get(e)??u)>u){n?.close?.();continue}try{s.drawImage(n,a,l,i,d),c.current.add(e),o(!0),u>r&&(r=u),n?.close?.()}catch{m()}}b.current.clear(),r>0&&e?.current?.emit("tile-ack",{ts:r})},[n,e]),w=(0,r.useCallback)((e=!1)=>{e&&g.current&&(cancelAnimationFrame(g.current),g.current=null),g.current||(g.current=requestAnimationFrame(y))},[y]),k=(0,r.useCallback)(e=>{if(n?.current)try{let t=n.current.getContext("2d");t.imageSmoothingEnabled=!1;let s=new Image;s.onload=()=>{if(n?.current)try{t.drawImage(s,0,0,e.screen.width,e.screen.height),c.current.clear();for(let e=0;e<a;e++)c.current.add(e);o(!0)}catch(e){}},s.src=e.screen.imageBase64}catch(e){console.error("Full screen error:",e)}},[n,a]),j=(0,r.useCallback)(e=>{if(n?.current)try{if(n.current.getContext("2d"),x.current=Date.now(),e.currentHashes&&Array.isArray(e.currentHashes)&&(u.current=e.currentHashes,m.current=!1),!e.tiles?.length)return;let t=e.timestamp||Date.now();for(let s of e.tiles){let e=d.current.get(s.tileIndex),n=f.current.get(s.tileIndex)??0;t>=n&&(e?.controller&&(e.controller.cancelled=!0),f.current.set(s.tileIndex,t),null!=s.hash&&(u.current[s.tileIndex]=s.hash))}if(void 0!==e.hasBitmap){for(let s of e.tiles){if(!s.bitmap&&!s.imageBuffer)continue;if((f.current.get(s.tileIndex)??t)>t){s.bitmap?.close?.();continue}let e=dL(u,s.tileIndex);s.bitmap?b.current.set(s.tileIndex,{bitmap:s.bitmap,x:s.x,y:s.y,width:s.width,height:s.height,frameTs:t,invalidateTileHash:e}):dB(dI(s.imageBuffer)).then(n=>{n&&(b.current.set(s.tileIndex,{bitmap:n,x:s.x,y:s.y,width:s.width,height:s.height,frameTs:t,invalidateTileHash:e}),w(!0))}).catch(()=>{e()})}w(!0);return}let s=[];for(let t=0;t<e.tiles.length;t+=P.eR.batchSize)s.push(e.tiles.slice(t,t+P.eR.batchSize));s.forEach((e,s)=>{let r=setTimeout(()=>{p.current.delete(r),e.forEach(e=>{if(!e.imageBuffer&&!e.imageBase64)return;if((f.current.get(e.tileIndex)??t)>t)return void d.current.delete(e.tileIndex);let s={cancelled:!1};d.current.set(e.tileIndex,{controller:s});let r=setTimeout(()=>{s.cancelled=!0,d.current.delete(e.tileIndex),u.current[e.tileIndex]=null},P.eR.tileLoadTimeout),a=dL(u,e.tileIndex),l=l=>{s.cancelled||!n?.current?l?.close?.():(clearTimeout(r),d.current.delete(e.tileIndex),b.current.set(e.tileIndex,{bitmap:l,x:e.x,y:e.y,width:e.width,height:e.height,frameTs:t,invalidateTileHash:a}),w())};if(e.imageBuffer&&"u">typeof createImageBitmap)dB(dI(e.imageBuffer)).then(l).catch(()=>{if(s.cancelled)return;let t=new Image,n=URL.createObjectURL(dI(e.imageBuffer));t.onload=()=>{l(t),URL.revokeObjectURL(n)},t.onerror=()=>{URL.revokeObjectURL(n),clearTimeout(r),d.current.delete(e.tileIndex),a()},t.src=n});else{let t=new Image;if(e.imageBuffer){let s=URL.createObjectURL(dI(e.imageBuffer));t.onload=()=>{l(t),URL.revokeObjectURL(s)},t.onerror=()=>{URL.revokeObjectURL(s),clearTimeout(r),d.current.delete(e.tileIndex),a()},t.src=s}else t.onload=()=>l(t),t.onerror=()=>{clearTimeout(r),d.current.delete(e.tileIndex),a()},t.src=`data:image/jpeg;base64,${e.imageBase64}`}})},s*P.eR.batchDelay);p.current.add(r)})}catch(e){console.error("Tiles data error:",e)}},[n]),N=(0,r.useCallback)((e,t,n="ws")=>{if(!e)return;let r=e instanceof ArrayBuffer?e:e?.buffer;if(!r)return;let a=function(){if(!1===dD)return null;if(dD)return dD;try{return(dD=new Worker(s.tu(new URL(s.p+s.u(1311),s.b)))).onmessage=({data:{tiles:e,timestamp:t,id:s,hasBitmap:n,error:r}})=>{let a=dO.get(s);if(!a){if(e)for(let t of e)t.bitmap?.close?.();return}clearTimeout(a.timer),dO.delete(s),a.resolve(r?null:{tiles:e,timestamp:t,hasBitmap:n})},dD}catch{return dD=!1,null}}();if(!a)return;let l=r.byteLength,i=++dF;new Promise(e=>{let s=setTimeout(()=>{dO.has(i)&&(dO.delete(i),e(null))},P.eR.tileLoadTimeout),n=P.eR.decodeQueueCap;for(;dO.size>=n;){let e=dO.keys().next().value,t=dO.get(e);if(!t)break;clearTimeout(t.timer),dO.delete(e),t.resolve(null)}dO.set(i,{resolve:e,timer:s}),a.postMessage({buffer:r,id:i,v:t},[r])}).then(e=>{e&&(2===t&&(m.current=!1),j({tiles:e.tiles,timestamp:e.timestamp,hasBitmap:e.hasBitmap,bytes:l,transport:n}))})},[j]),S=(0,r.useCallback)(e=>N(e,1,"ws"),[N]),C=(0,r.useCallback)(e=>N(e,2,"ws"),[N]),T=(0,r.useCallback)(e=>{e&&(x.current=Date.now(),e.currentHashes&&Array.isArray(e.currentHashes)&&(u.current=e.currentHashes,m.current=!1))},[]),R=(0,r.useCallback)(e=>{e()},[]),E=(0,r.useCallback)(e=>{e.tileCount&&l(e.tileCount)},[]),_=(0,r.useCallback)(()=>{if(!e?.current||!v.current||m.current||0===u.current.length||Date.now()-x.current<P.eR.lastDataThreshold)return;m.current=!0,e.current.emit("request-screen-with-hashes",{tileHashes:u.current});let t=setTimeout(()=>{h.current.delete(t),m.current=!1},1e3);h.current.add(t)},[]),$=(0,r.useCallback)(()=>{for(let[,e]of d.current.entries())e.controller&&(e.controller.cancelled=!0);if(d.current.clear(),u.current=[],c.current.clear(),f.current.clear(),x.current=0,m.current=!1,o(!1),dD&&!1!==dD)try{dD.terminate()}catch{}for(let e of(dD=null,dO.values()))try{e.resolve(null)}catch{}dO.clear(),g.current&&(cancelAnimationFrame(g.current),g.current=null),b.current.clear()},[]);return(0,r.useEffect)(()=>{let e=p.current,t=h.current;return()=>{e.forEach(clearTimeout),e.clear(),t.forEach(clearTimeout),t.clear()}},[]),{renderedTilesRef:c,totalTileCount:a,hasFrame:i,handleFullScreenData:k,handleTilesData:j,handleTilesBinary:S,handleTilesBinaryV2:C,handleTilesMeta:T,startStreamingWithTiles:R,handleScreenDimensions:E,cleanupTiles:$,requestScreenWithHashes:_}}(t,K,er),{screenLocked:eQ,unlockReady:e0,unlockResult:e1,setUnlockResult:e2,clipboardText:e5,clipboardNew:e3,setClipboardNew:e4,monitors:e6,activeMonitorIndex:e8,cursorShape:e9}=function({busRef:e,connected:t,streaming:s,canvasRef:n,serverDimensionsRef:a,handleCanvasDimensions:l,resetPan:i,zoomGestureTimeoutRef:o,trackTilesReceived:c,tiles:d}){let[u,m]=(0,r.useState)(!1),[x,p]=(0,r.useState)(!1),[h,f]=(0,r.useState)(null),[b,v]=(0,r.useState)(""),[y,w]=(0,r.useState)(!1),[k,j]=(0,r.useState)([]),[N,S]=(0,r.useState)(0),[C,T]=(0,r.useState)(null),R=(0,r.useRef)(null),{renderedTilesRef:E,handleFullScreenData:_,handleTilesData:$,handleTilesBinary:M,handleTilesBinaryV2:A,handleTilesMeta:z,handleScreenDimensions:I,cleanupTiles:L,requestScreenWithHashes:D}=d;return(0,r.useEffect)(()=>{let s=e?.current;if(!s||!t)return;L();let n=e=>{I(e),l(e,E)},r=e=>_(e),a=e=>{let t=e.transport||"ws";t!==R.current&&(R.current=t,(0,g.c)("remote",`[remote] tiles via ${t}`)),c(e,t),$(e)},d=e=>console.error("Screen error:",e),u=({locked:e,ready:t}={})=>{m(!!e),p(!!t),e&&f(null)},x=e=>f(e||null),h=(e,t)=>{"ws"!==R.current&&(R.current="ws",(0,g.c)("remote",`[remote] tiles via ws${t}`)),c(function(e,t=Date.now()){let{tileCount:s,timestamp:n,bytes:r}=function(e,t=Date.now()){let s=e instanceof ArrayBuffer?e:e?.buffer,n=s?.byteLength||0,r=0,a=t;if(s&&s.byteLength>=12){let e=new DataView(s);r=e.getUint32(0,!0),a=e.getFloat64(4,!1)}return{tileCount:r,timestamp:a,bytes:n}}(e,t);return{tiles:Array(s),timestamp:n,bytes:r}}(e),"ws")},b=e=>{h(e,""),M(e)},y=e=>z(e),k=e=>{h(e," v2"),A(e)},N=()=>{L(),s.emit("get-screen-dimensions"),s.emit("get-unlock-state"),s.emit("start-streaming")},C=()=>N(),P=({text:e,hash:t})=>{v(s=>t&&t===P._lastHash?s:(P._lastHash=t||null,e||"")),w(!0)},D=({list:e,activeIndex:t})=>{j(Array.isArray(e)?e:[]),"number"==typeof t&&S(t)},F=e=>{L(),i(),"number"==typeof e?.monitorIndex&&S(e.monitorIndex)};s.on("screen-dimensions",n),s.on("full-screen-data",r),s.on("tiles-data",a),s.on("tiles-data-binary",b),s.on("tiles-bin-v2",k),s.on("tiles-meta",y),s.on("screen-error",d),s.on("screen-locked",u),s.on("unlock-result",x),s.on("remote:ready",C),s.on("clipboard-update",P),s.on("monitors",D),s.on("frame_meta",F);let O=e=>T(e?.shape??null);return s.on("cursor-shape",O),N(),()=>{s.emit("stop-streaming"),s.off("screen-dimensions",n),s.off("full-screen-data",r),s.off("tiles-data",a),s.off("tiles-data-binary",b),s.off("tiles-bin-v2",k),s.off("tiles-meta",y),s.off("screen-error",d),s.off("screen-locked",u),s.off("unlock-result",x),s.off("remote:ready",C),s.off("clipboard-update",P),s.off("monitors",D),s.off("frame_meta",F),s.off("cursor-shape",O),L(),o.current&&clearTimeout(o.current)}},[t]),(0,r.useEffect)(()=>{if(!s||!t||!e?.current)return;let n=setInterval(()=>{0===E.current.size?e.current.emit("request-screen-with-hashes",{tileHashes:[]}):D()},P.eR.hashRequestInterval);return()=>clearInterval(n)},[s,t,e,D,E]),(0,r.useEffect)(()=>{if(!t)return;let s=()=>{let t=n.current;if(!t||t.width>0)return!0;let{width:s,height:r}=a.current||{};return s>0?l({width:s,height:r},E):e.current?.emit("get-screen-dimensions"),!1};if(s())return;let r=setInterval(()=>{s()&&clearInterval(r)},P.eR.restreamDelay);return()=>clearInterval(r)},[t,e,n,a,l,E]),(0,r.useEffect)(()=>{let s=e?.current;if(!s||!t)return;let n=()=>{document.hidden?s.emit("stop-streaming"):s.emit("start-streaming")};return document.addEventListener("visibilitychange",n),()=>document.removeEventListener("visibilitychange",n)},[t,e]),{screenLocked:u,unlockReady:x,unlockResult:h,setUnlockResult:f,clipboardText:b,clipboardNew:y,setClipboardNew:w,monitors:k,activeMonitorIndex:N,cursorShape:C}}({busRef:t,connected:l,streaming:K,canvasRef:er,serverDimensionsRef:eN,handleCanvasDimensions:ej,resetPan:eb,zoomGestureTimeoutRef:ed,trackTilesReceived:A,tiles:eZ});(0,r.useEffect)(()=>{if(!e3)return;let e=setTimeout(()=>e4(!1),P.eR.clipboardBadgeTimeout);return()=>clearTimeout(e)},[e3,e5,e4]),(0,r.useEffect)(()=>{if(!K)return;let e=setTimeout(()=>{let e=er.current,t=ea.current;if(!e||!t||0===e.width)return;if(el<=1)return void ee(null,1);let s=eo*el;if(s<=0)return;let n=Math.max(0,-ei.x/s),r=Math.max(0,-ei.y/s),a=Math.min(e.width-n,t.clientWidth/s),l=Math.min(e.height-r,t.clientHeight/s);ee({x:Math.floor(n),y:Math.floor(r),w:Math.ceil(a),h:Math.ceil(l)},el)},P.eR.focusDebounce);return()=>clearTimeout(e)},[K,el,ei,eo,er,ea,ee]);let e7=(0,r.useCallback)(()=>C(!1),[C]),te=(0,r.useCallback)(e=>{t?.current?.emit("select_monitor",{index:e})},[t]),tt=(0,r.useCallback)(()=>{S&&C(!1),eD()},[S,C,eD]),ts=e=>t=>{ek(t,e,{streaming:K,selectionMode:e_,selectionStart:e$,dragMode:eP,isDragging:eA,setIsDragging:ez,setDragMode:eI,isMobile:e.includes("touch"),pointerMode:j,handMode:S,onHandRelease:e7,handleSelection:(e,t,s,n)=>eW(e,t,s,{streaming:K,getCanvasCoordinates:eh,baseCanvasSize:ec,canvasZoom:el,canvasPan:ei,...n})})};return(0,n.jsxs)("div",{className:`bg-bg text-text flex flex-col h-full w-full ${$?"":"landscape:flex-row"}`,style:{userSelect:"none",WebkitUserSelect:"none",WebkitTouchCallout:"none",WebkitTapHighlightColor:"transparent"},onContextMenu:e=>e.preventDefault(),children:[(0,n.jsxs)("div",{className:"flex flex-row flex-1 min-h-0",children:[l&&(0,n.jsx)(dQ,{streaming:K,canvasZoom:el,pointerMode:j,handMode:S,keyboardOn:v,selectionMode:e_,show:e=>"mouse"!==T||R?.[e],onBack:en,onRefresh:()=>{K&&H([])},onResetZoom:ef,onTogglePointerMode:eS,onToggleHandMode:eY,onToggleKeyboard:eV,onShowHelp:()=>u(!0),onToggleSelection:tt}),l?(0,n.jsx)(dH,{canvasRef:er,canvasContainerRef:ea,canvasZoom:el,canvasPan:ei,fitScale:eo,streaming:K,hasFrame:eZ.hasFrame,selectionRect:eM,clickIndicator:eu,pointerMode:j,selectionMode:e_,handMode:S,handHolding:ex,scrollLock:ep,virtualCursor:em,cursorShape:e9,inputMode:T,keyboardOn:v,monitors:e6,activeMonitorIndex:e8,onSelectMonitor:te,onPointerDown:ts("pointerdown"),onPointerMove:ts("pointermove"),onPointerUp:ts("pointerup"),onWheel:ts("wheel"),onContextMenu:ts("contextmenu"),onDoubleClick:ts("dblclick"),onTouchStart:ts("touch"),onTouchMove:ts("touchmove"),onTouchEnd:ts("touchend"),onKeyDown:e=>eO(e,K),screenLocked:eQ,unlockReady:e0,unlockResult:e1,onUnlockSubmit:e=>{e2(null),t?.current?.emit("desktop-unlock",{text:e})}}):(0,n.jsxs)("div",{className:"flex-1 min-w-0 empty-stage",children:[(0,n.jsx)("div",{className:"empty-grid"}),(0,n.jsxs)("div",{className:"empty-half",children:[(0,n.jsxs)("span",{className:"empty-idx",children:[(0,n.jsx)("b",{children:"01"})," / ",c("workspaces.emptyTagRemote")]}),(0,n.jsx)("span",{className:"empty-word login-hero-grad",children:c("workspaces.emptyWordRemote")}),(0,n.jsx)("span",{className:"empty-meta",dangerouslySetInnerHTML:{__html:c("workspaces.emptyMetaRemote")}}),(0,n.jsxs)("span",{className:"empty-go",children:[(0,n.jsx)(du.A,{size:"sm"}),c("remote.connecting")]})]})]})]}),(0,n.jsx)(dX,{streaming:K,canvasZoom:el,clipboardNew:e3,clipboardText:e5,onOpenClipboard:()=>{e4(!1),h(!0)},onDesktopSwitch:et,selectionMode:e_,pointerMode:j,handMode:S,inputMode:T,onToggleHandMode:eY,onTogglePointerMode:eS,modifierKeys:eE,textInputValue:eC,textInputRef:eR,keyboardOn:v,showTextPanel:f,onResetZoom:ef,onRefresh:()=>K&&H([]),onToggleSelection:tt,onToggleModifier:eL,onToggleKeyboard:eV,onToggleTextPanel:eX,controlsHidden:w,onToggleControlsHidden:k,tallLandscape:$,onToggleHelp:()=>u(!0),onEmitKey:eJ,onTextInputChange:eT,onTextInputFocus:eF,onTextInputBlur:eG,onTextInputKeyDown:e=>eK(e,K,v),onDirectInputChange:e=>eH(e,K),onSendText:eB,onClose:en,onToggleDebug:()=>L(e=>!e),debugOn:I}),I&&(0,n.jsx)(d1,{onForceWsDisconnect:()=>t?.current?.disconnect(),onToggleWsBlock:()=>{let e=a?.current;if(!e)return;let t=!e.wsBlocked;e.setWsBlocked(t),F(t)},isWsBlocked:D,stats:M,mode:O,onReset:z,onCopy:B,onClose:()=>L(!1)}),d&&(0,n.jsx)(d0,{inputMode:T,pointerMode:j,onClose:()=>{u(!1),v&&eR.current?.focus()}}),p&&(0,n.jsx)(d2,{text:e5,onClose:()=>h(!1)}),(0,n.jsx)(t9.A,{isOpen:m,onClose:()=>{x(!1),v&&eR.current?.focus()},onConfirm:()=>e?.(),title:c("remote.exitRemote"),message:c("remoteControls.exitConfirmMessage"),confirmText:c("connection.exit"),cancelText:c("common.cancel")})]})}let d3={"9remote.cc":"sites.9remote.cc","dev.9remote.cc":"sites-dev.9remote.cc",localhost:"sites.localhost","127.0.0.1":"sites.localhost","::1":"sites.localhost"},d4=function(){let e=window.location;if(!e)return"https://sites.9remote.cc";let{hostname:t,protocol:s,port:n}=e,r=d3[t];return r?n?`${s}//${r}:${n}`:`${s}//${r}`:(console.warn(`[sites] no sites host is known for ${t}; local sites are unavailable here`),null)}(),d6="site-nav",d8="site-error",d9=null,d7=!1,ue=new Map;function ut(e){if(!e||"string"!=typeof e.reqId)return;let t=ue.get(e.reqId);if(e.error){if(!t?.resolve)return;clearTimeout(t.timer),ue.delete(e.reqId),t.resolve({reqId:e.reqId,error:e.error});return}if(!t)return;0===e.seq&&(t.total=e.total,t.status=e.status,t.headers=e.headers),t.slots[e.seq]=e.b64||"";let s=function(e){let t=ue.get(e);if(!t||null==t.total)return null;for(let e=0;e<t.total;e++)if(void 0===t.slots[e])return null;let s=t.slots.join("");return clearTimeout(t.timer),ue.delete(e),{reqId:e,status:t.status,headers:t.headers,bodyB64:s}}(e.reqId);s&&t.resolve&&t.resolve(s)}function us(e){var t;if("string"!=typeof(t=e.origin)||""===t||"null"===t||t!==d4)return;let s=e.data;if(s&&"object"==typeof s){if("site:request"===s.type)return void(function(e){let{reqId:t}=e;return new Promise(s=>{let n={slots:[],total:null,status:null,headers:null,resolve:s,timer:null};n.timer=setTimeout(()=>{ue.delete(t),s({reqId:t,error:"timeout"})},75e3),ue.set(t,n),d9?.emit?.("site:httpRequest",e,()=>{})})})(s.payload).then(t=>{try{e.source?.postMessage({type:"site:reply",id:s.id,payload:t},d4)}catch{}});if("site:nav"===s.type)return void window.dispatchEvent(new CustomEvent(d6,{detail:{port:s.port,path:s.path}}));if("site:ready"!==s.type){if("site:swBlocked"===s.type)return void window.dispatchEvent(new CustomEvent(d8,{detail:{message:"service-worker-blocked"}}));if("site-error"===s.type)return void window.dispatchEvent(new CustomEvent(d8,{detail:{message:s.message,port:s.port}}))}}}async function un(e){e&&(d9=e,d9.off?.("site:httpChunk",ut),d9.on?.("site:httpChunk",ut)),d7||(d7=!0,window.addEventListener("message",us))}function ur({isOpen:e,onClose:t,onOpenSite:s,busRef:a,connected:l}){let{t:i}=(0,se.s)(),[o,c]=(0,r.useState)(null),[d,u]=(0,r.useState)([]),[m,x]=(0,r.useState)({}),[p,h]=(0,r.useState)(""),[f,b]=(0,r.useState)(null),[g,v]=(0,r.useState)(""),y=(0,r.useRef)(null),w=()=>{if(l){var e;let t;c(null),(e=a?.current,t=e?.current||e,new Promise(e=>{if(!t?.connected)return e(null);let s=setTimeout(()=>e(null),8e3);t.emit("getLocalSites",t=>{clearTimeout(s),e(Array.isArray(t?.sites)?t.sites:null)})})).then(e=>c(e||[]))}};if((0,r.useEffect)(()=>{if(!e)return;u(n0()),x(n1()),w();let t=requestAnimationFrame(()=>y.current?.focus());return()=>cancelAnimationFrame(t)},[e,l,a]),(0,r.useEffect)(()=>{if(!e)return;let s=e=>{"Escape"===e.key&&null===f&&(e.preventDefault(),e.stopPropagation(),t())};return window.addEventListener("keydown",s,!0),()=>window.removeEventListener("keydown",s,!0)},[e,f,t]),!e||"u"<typeof document)return null;let k=o||[],j=new Set(k.map(e=>e.port)),N=e=>m[e.port]||e.name||`Port ${e.port}`,S=e=>{(0,t7.e)(),s(Number(e)),t()},C=()=>{let e=parseInt(p,10);if(!isNaN(e)&&!(e<1)&&!(e>65535)){if(!j.has(e)&&!d.includes(e)){let t=[...d,e];u(t),nQ(nJ,t)}h(""),S(e)}},T=()=>{if(null==f)return;let e=g.trim(),t={...m};e?t[f]=e:delete t[f],x(t),nQ(nY,t),b(null),v("")},R=d.filter(e=>!j.has(e));return(0,r_.createPortal)((0,n.jsxs)("div",{className:"fixed inset-0 z-[100] flex items-center justify-center px-4",style:{paddingTop:"max(1rem, env(safe-area-inset-top))",paddingBottom:"max(1rem, env(safe-area-inset-bottom))"},children:[(0,n.jsx)("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-[4px] animate-in fade-in duration-150",onClick:t}),(0,n.jsxs)("div",{role:"dialog","aria-modal":"true",className:"relative card-elev w-full max-w-md max-h-[85vh] flex flex-col animate-in zoom-in-95 duration-200",onClick:e=>e.stopPropagation(),children:[(0,n.jsxs)("div",{className:"flex items-center justify-between px-5 py-4 shrink-0",children:[(0,n.jsxs)("div",{className:"min-w-0",children:[(0,n.jsx)("h2",{className:"text-lg font-semibold text-text",children:i("sites.newTabTitle")}),(0,n.jsx)("p",{className:"text-sm text-text-muted mt-0.5 truncate",children:i("sites.selectSitePreview")})]}),(0,n.jsx)("button",{onClick:t,className:"p-2 text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-colors shrink-0",title:i("common.close"),children:(0,n.jsx)(t3.X,{size:20})})]}),(0,n.jsx)("div",{className:"px-4 pb-3 border-b border-border shrink-0",children:(0,n.jsxs)("div",{className:"flex gap-2 items-center",children:[(0,n.jsx)("span",{className:"text-text-muted text-sm whitespace-nowrap",children:"http://localhost:"}),(0,n.jsx)("input",{ref:y,type:"number",value:p,onChange:e=>h(e.target.value),onKeyDown:e=>"Enter"===e.key&&C(),placeholder:i("sites.portPlaceholder"),min:"1",max:"65535",className:"flex-1 px-3 py-2 bg-surface-2 rounded-brand text-text placeholder-text-muted focus:outline-none focus:ring-2 focus:ring-brand-500/40 text-sm min-w-0 transition-all duration-150"}),(0,n.jsx)("button",{onClick:C,disabled:!p,className:"px-4 py-2 bg-brand-500 hover:bg-brand-600 disabled:bg-surface-2 disabled:cursor-not-allowed text-white text-sm font-medium rounded-brand transition-all duration-150",children:i("sites.open")})]})}),(0,n.jsx)("div",{className:"p-4 overflow-y-auto modal-scrollable",style:{maxHeight:"45vh"},children:l?null===o?(0,n.jsxs)("div",{className:"flex items-center justify-center gap-2 py-8 text-brand-500 text-sm",children:[(0,n.jsx)(t3.kr,{size:16,className:"animate-spin"}),(0,n.jsx)("span",{children:i("sites.loadingSites")})]}):(0,n.jsxs)("div",{className:"space-y-2",children:[R.map(e=>(0,n.jsx)(ua,{port:e,label:N({port:e}),detected:!1,editing:f===e,editValue:g,onEditValue:v,onStartEdit:()=>{b(e),v(m[e]||"")},onSaveEdit:T,onCancelEdit:()=>{b(null),v("")},onRemove:()=>{var t;let s;return t=e,void(u(s=d.filter(e=>e!==t)),nQ(nJ,s))},onOpen:()=>S(e),t:i},`saved-${e}`)),k.map(e=>(0,n.jsx)(ua,{port:e.port,label:N(e),protocol:e.protocol,detected:!0,editing:f===e.port,editValue:g,onEditValue:v,onStartEdit:()=>{b(e.port),v(m[e.port]||"")},onSaveEdit:T,onCancelEdit:()=>{b(null),v("")},onOpen:()=>S(e.port),t:i},`auto-${e.port}`)),0===k.length&&0===R.length&&(0,n.jsxs)("div",{className:"text-center py-8",children:[(0,n.jsx)(t3.qz,{size:24,className:"text-text-muted mx-auto mb-2"}),(0,n.jsx)("p",{className:"text-text text-sm font-medium",children:i("sites.noSitesFound")}),(0,n.jsx)("p",{className:"text-text-muted text-xs mt-1",children:i("sites.startServerHint")})]})]}):(0,n.jsx)("div",{className:"py-8 text-center text-sm text-text-muted",children:i("sites.notConnected",{defaultValue:"Not connected to the agent"})})}),(0,n.jsxs)("div",{className:"px-5 py-3 border-t border-border flex items-center justify-between shrink-0",children:[(0,n.jsx)("span",{className:"text-xs text-text-muted",children:k.length>0?i("sites.foundCount",{n:k.length,suffix:k.length>1?"s":""}):""}),(0,n.jsxs)("button",{onClick:w,disabled:!l,className:"flex items-center gap-2 px-3 py-1.5 text-sm text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-colors disabled:opacity-50",children:[(0,n.jsx)(t3.e9,{className:null===o&&l?"animate-spin text-brand-500":"",size:16}),i("sites.refresh")]})]})]})]}),document.body)}function ua({port:e,label:t,protocol:s,detected:r,editing:a,editValue:l,onEditValue:i,onStartEdit:o,onSaveEdit:c,onCancelEdit:d,onRemove:u,onOpen:m,t:x}){return(0,n.jsxs)("div",{className:"w-full px-4 py-3 bg-surface-2 hover:bg-surface-3 rounded-brand-lg transition-colors group flex items-center gap-2",children:[(0,n.jsxs)("button",{onClick:m,className:"flex-1 flex items-center gap-3 text-left min-w-0",children:[(0,n.jsx)("span",{className:`w-2.5 h-2.5 rounded-full shrink-0 ${r?"bg-green-500 animate-pulse":"bg-surface-3"}`}),(0,n.jsxs)("span",{className:"min-w-0 flex-1",children:[a?(0,n.jsx)("input",{type:"text",value:l,onChange:e=>i(e.target.value),onKeyDown:e=>{"Enter"===e.key&&c(),"Escape"===e.key&&d()},onClick:e=>e.stopPropagation(),autoFocus:!0,placeholder:`Port ${e}`,className:"w-full px-2 py-1 bg-surface ring-2 ring-brand-500/40 rounded-brand text-text text-sm focus:outline-none"}):(0,n.jsx)("span",{className:"block text-text font-medium truncate",children:t}),(0,n.jsxs)("span",{className:"block text-xs text-text-muted mt-0.5",children:[s?`${s} \xb7 `:"","Port ",e]})]})]}),a?(0,n.jsx)("button",{onClick:c,className:"px-3 py-1.5 text-sm font-medium text-brand-500 hover:bg-surface-3 rounded-brand transition-colors shrink-0",title:x("sites.saveTitle"),children:x("sites.saveTitle")}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{onClick:e=>{e.stopPropagation(),o()},className:"p-2 text-text-muted hover:text-brand-500 hover:bg-surface-3 rounded-brand transition-colors shrink-0",title:x("sites.editNameTitle"),children:(0,n.jsx)(t3.gH,{size:16})}),!r&&(0,n.jsx)("button",{onClick:e=>{e.stopPropagation(),u()},className:"p-2 text-text-muted hover:text-red-400 hover:bg-surface-3 rounded-brand transition-colors shrink-0",title:x("sites.removeTitle"),children:(0,n.jsx)(t3.TB,{size:16})})]})]})}let ul=0,ui=(e,t)=>{let s={port:e,path:t||"/"};return{key:`site-${++ul}`,port:e,path:s.path,srcTick:0,hist:[s],histIdx:0}},uo=e=>e?`localhost:${e.port}${e.path||"/"}`:"",uc={"service-worker-blocked":"sites.errorSwBlocked","bridge not connected — open the 9Remote app":"sites.errorNoBridge","no-session":"sites.errorNoSession",timeout:"sites.errorTimeout","no reply from the agent":"sites.errorNoReply"};function ud({busRef:e,connected:t=!1,initialPort:s,initialPath:a,onBack:l}){let{t:i}=(0,se.s)(),[o,c]=(0,r.useState)(()=>{if(!s)return{tabs:[],activeKey:"",address:""};let e=ui(s,a);return{tabs:[e],activeKey:e.key,address:uo(e)}}),[d,u]=(0,r.useState)(!1),[m,x]=(0,r.useState)(!1),[p,h]=(0,r.useState)(null),{tabs:f,activeKey:b,address:g}=o,v=f.find(e=>e.key===b)||null,y=(0,r.useRef)(new Set),w=(0,r.useCallback)(t=>{y.current.has(t)||(y.current.add(t),e?.current?.emit?.("startProxySession",t))},[e]),k=(0,r.useCallback)(t=>{y.current.delete(t),e?.current?.emit?.("endProxySession",t)},[e]);(0,r.useEffect)(()=>{un(e?.current)},[e]),(0,r.useEffect)(()=>{let e=e=>{let{message:t,port:s}=e.detail||{};t&&(u(!1),h({message:i(uc[t]||"sites.errorGeneric",{port:s})}))};return window.addEventListener(d8,e),()=>window.removeEventListener(d8,e)},[i]),(0,r.useEffect)(()=>{let e=e=>{let{port:t,path:s}=e.detail||{};t&&c(e=>({tabs:e.tabs.map(n=>{if(n.key!==e.activeKey)return n;let r=n.hist[n.histIdx];if(r&&r.port===t&&r.path===(s||"/"))return{...n,port:t,path:s};let a=[...n.hist.slice(0,n.histIdx+1),{port:t,path:s||"/"}];return{...n,port:t,path:s,hist:a,histIdx:a.length-1}}),activeKey:e.activeKey,address:`localhost:${t}${s||"/"}`}))};return window.addEventListener(d6,e),()=>window.removeEventListener(d6,e)},[]),(0,r.useEffect)(()=>{let e=new Set(f.map(e=>e.port));for(let t of[...y.current])e.has(t)||k(t)},[f,k]),(0,r.useEffect)(()=>()=>{for(let t of y.current)e?.current?.emit?.("endProxySession",t);y.current.clear()},[e]);let j=(e,t="/")=>{(0,t7.e)(),w(e),u(!0),h(null),c(s=>{if(s.tabs.find(e=>e.key===s.activeKey))return{tabs:s.tabs.map(n=>{if(n.key!==s.activeKey)return n;let r=n.hist[n.histIdx];if(r&&r.port===e&&r.path===t)return{...n,port:e,path:t,srcTick:n.srcTick+1};let a=[...n.hist.slice(0,n.histIdx+1),{port:e,path:t}];return{...n,port:e,path:t,srcTick:n.srcTick+1,hist:a,histIdx:a.length-1}}),activeKey:s.activeKey,address:`localhost:${e}${t}`};let n=ui(e,t);return{tabs:[...s.tabs,n],activeKey:n.key,address:uo(n)}})},N=()=>{v&&((0,t7.e)(),u(!0),h(null),c(e=>({...e,tabs:e.tabs.map(t=>t.key===e.activeKey?{...t,srcTick:t.srcTick+1}:t)})))},S=e=>{if(!v)return;let t=v.histIdx+e,s=v.hist[t];s&&((0,t7.e)(),w(s.port),u(!0),c(e=>({tabs:e.tabs.map(n=>n.key===e.activeKey?{...n,port:s.port,path:s.path,srcTick:n.srcTick+1,histIdx:t}:n),activeKey:e.activeKey,address:uo(s)})))},C=()=>{(0,t7.e)(),x(!0)};return(0,n.jsxs)("div",{className:"absolute inset-0 z-20 flex flex-col bg-surface text-text transition-all duration-300 ease-out animate-in slide-in-from-bottom",children:[(0,n.jsxs)("div",{className:"h-11 flex items-center gap-1 px-2 border-b border-border-subtle shrink-0 overflow-x-auto modal-scrollable",children:[(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),l?.()},className:"p-2 text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-colors shrink-0",title:i("common.close"),children:(0,n.jsx)(t3.JG,{size:18})}),f.map(e=>(0,n.jsxs)("div",{className:`group flex items-center gap-1.5 pl-3 pr-1.5 h-8 rounded-brand text-xs cursor-pointer max-w-[160px] shrink-0 transition-colors ${e.key===b?"bg-surface-3 text-text":"bg-surface-2 text-text-muted hover:bg-surface-3"}`,onClick:()=>c(t=>({...t,activeKey:e.key,address:uo(e)})),children:[(0,n.jsx)(t3.qz,{size:13,className:"shrink-0"}),(0,n.jsxs)("span",{className:"truncate",children:[":",e.port]}),(0,n.jsx)("button",{onClick:t=>{var s;t.stopPropagation(),s=e.key,(0,t7.e)(),c(e=>{let t=e.tabs.findIndex(e=>e.key===s),n=e.tabs.filter(e=>e.key!==s);if(s!==e.activeKey)return{...e,tabs:n};let r=n[Math.min(t,n.length-1)];return{tabs:n,activeKey:r?.key||"",address:uo(r)}})},className:"p-0.5 rounded opacity-60 hover:opacity-100 hover:bg-surface shrink-0",title:i("common.close"),children:(0,n.jsx)(t3.X,{size:12})})]},e.key)),(0,n.jsx)("button",{onClick:C,className:"p-2 text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-colors shrink-0",title:i("sites.browserNewTab"),children:(0,n.jsx)(t3.FW,{size:16})}),d&&(0,n.jsx)(t3.kr,{size:14,className:"animate-spin text-brand-500 shrink-0 ml-1"})]}),(0,n.jsxs)("div",{className:"h-11 flex items-center gap-1 px-2 border-b border-border-subtle shrink-0",children:[(0,n.jsx)("button",{onClick:()=>S(-1),disabled:!v||0===v.histIdx,className:"p-2 text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-colors disabled:opacity-40 shrink-0",title:i("sites.goBack"),children:(0,n.jsx)(t3.JG,{size:16})}),(0,n.jsx)("button",{onClick:()=>S(1),disabled:!v||v.histIdx>=v.hist.length-1,className:"p-2 text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-colors disabled:opacity-40 shrink-0",title:i("sites.goForward"),children:(0,n.jsx)(t3.c_,{size:16})}),(0,n.jsx)("button",{onClick:()=>{v&&j(v.port,"/")},disabled:!v,className:"p-2 text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-colors disabled:opacity-40 shrink-0",title:i("menu.home"),children:(0,n.jsx)(t3.ww,{size:15})}),(0,n.jsx)("input",{type:"text",value:g,onChange:e=>c(t=>({...t,address:e.target.value})),onKeyDown:e=>{let t;return"Enter"===e.key&&void((t=function(e,t){let s=(e||"").trim();if(!s)return null;let n=s.match(/^(?:https?:\/\/)?localhost:(\d{1,5})(\/.*)?$/i);return n||(n=s.match(/^:(\d{1,5})(\/.*)?$/))||(n=s.match(/^(\d{1,5})(\/.*)?$/))&&Number(n[1])>=1&&65535>=Number(n[1])?{port:Number(n[1]),path:n[2]||"/"}:s.startsWith("/")&&t?{port:t,path:s}:null}(g,v?.port))&&j(t.port,t.path))},placeholder:i("sites.browserAddressPlaceholder"),spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",className:"flex-1 min-w-0 px-3 py-1.5 bg-surface-2 rounded-brand text-sm text-text placeholder-text-muted focus:outline-none focus:ring-2 focus:ring-brand-500/40"}),(0,n.jsx)("button",{onClick:N,disabled:!v,className:"p-2 text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-colors disabled:opacity-40 shrink-0",title:i("editor.reload"),children:(0,n.jsx)(t3.kt,{size:15})})]}),(0,n.jsxs)("div",{className:"flex-1 min-h-0 bg-white relative",children:[!t&&(0,n.jsx)("div",{className:"absolute inset-0 z-10 flex items-center justify-center text-sm text-text-muted bg-surface",children:i("sites.browserNotConnected")}),f.map(e=>(0,n.jsx)("iframe",{src:function(e,t,s=0){let n=Number(e);if(!Number.isInteger(n)||n<1||n>65535||!d4)return null;let r=s?`?r=${s}`:"";return`${d4}/proxy.html${r}#port=${n}&path=${encodeURIComponent(t||"/")}`}(e.port,e.path,e.srcTick),title:`site-${e.port}`,className:`w-full h-full border-0 absolute inset-0 ${e.key===b?"":"hidden"}`,onLoad:()=>{e.key===b&&u(!1)}},e.key)),!v&&(0,n.jsxs)("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-3 p-6 text-center bg-surface",children:[(0,n.jsx)(t3.qz,{size:28,className:"text-text-muted"}),(0,n.jsx)("p",{className:"text-text text-sm font-medium",children:i("sites.noSitesFound")}),(0,n.jsxs)("button",{onClick:C,className:"flex items-center gap-2 px-4 py-2 bg-brand-500 hover:bg-brand-600 text-white text-sm font-medium rounded-brand transition-colors",children:[(0,n.jsx)(t3.FW,{size:16}),i("sites.newTabTitle")]})]}),p&&v&&(0,n.jsxs)("div",{className:"absolute inset-x-0 top-0 z-20 flex items-start gap-3 px-4 py-3 bg-red-500/90 text-white text-sm",children:[(0,n.jsx)("span",{className:"flex-1 min-w-0 break-words",children:p.message}),(0,n.jsx)("button",{onClick:N,className:"px-2 py-1 rounded bg-white/20 hover:bg-white/30 shrink-0 font-medium",children:i("sites.refresh")}),(0,n.jsx)("button",{onClick:()=>h(null),className:"p-1 shrink-0 opacity-80 hover:opacity-100",title:i("common.close"),children:(0,n.jsx)(t3.X,{size:14})})]})]}),(0,n.jsx)(ur,{isOpen:m,onClose:()=>x(!1),onOpenSite:e=>j(e),busRef:e,connected:t})]})}function uu({files:e,loading:t,onFileClick:s,onFolderClick:r,onMoreClick:a,selectedPath:l,gitStatusMap:i={},workspacePath:o}){let{t:c}=(0,se.s)();return t?(0,n.jsx)("div",{className:"flex-1 flex items-center justify-center",children:(0,n.jsx)("div",{className:"text-text-muted",children:c("common.loading")})}):0===e.length?(0,n.jsx)("div",{className:"flex-1 flex items-center justify-center",children:(0,n.jsx)("div",{className:"text-text-muted",children:c("files.emptyFolder")})}):(0,n.jsx)("div",{children:e.map((e,t)=>{var d;let u=i[d=e.path,!o?d:d.replace(o+"/","")],m="folder-changed"===u?"text-yellow-400":tl[u]||"";return(0,n.jsxs)("div",{className:`w-full px-4 py-1.5 flex items-center gap-2.5 border-b border-border hover:bg-surface-2 transition ${l===e.path?"bg-surface-2":""}`,children:[(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),"folder"===e.type?r(e):s(e)},className:"flex-1 flex items-center gap-2.5 text-left min-w-0",children:[(0,n.jsx)("span",{className:"flex-shrink-0",children:lB(e,18)}),(0,n.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,n.jsxs)("div",{className:`truncate text-sm ${m||"text-text"}`,title:e.name,children:[e.name,u&&"folder-changed"!==u&&(0,n.jsxs)("span",{className:"ml-2 text-xs opacity-70",children:["[",u,"]"]})]}),"folder"!==e.type&&e.sizeFormatted&&(0,n.jsx)("div",{className:"text-text-subtle text-xs",children:e.sizeFormatted})]})]}),a&&(0,n.jsx)("button",{onClick:t=>{let s;(0,t7.e)(),t.stopPropagation(),s=t.currentTarget.getBoundingClientRect(),a?.(e,{x:s.right,y:s.top})},className:"p-2 text-text-muted hover:text-text hover:bg-surface-2 rounded transition flex-shrink-0",title:c("menu.settings"),children:(0,n.jsxs)("svg",{className:"w-5 h-5",fill:"currentColor",viewBox:"0 0 24 24",children:[(0,n.jsx)("circle",{cx:"12",cy:"5",r:"2"}),(0,n.jsx)("circle",{cx:"12",cy:"12",r:"2"}),(0,n.jsx)("circle",{cx:"12",cy:"19",r:"2"})]})}),"folder"===e.type&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),r(e)},className:"p-1 text-text-muted flex-shrink-0",children:(0,n.jsx)("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,n.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})})]},e.path)})})}function um({workspace:e,initialPath:t,fileBus:s,onBack:a,onOpenFile:l,onOpenGit:i,onSetWorkspace:o,onSwitchWorkspace:c,onPathChange:d,isBrowsing:u=!1,hideSwitchWorkspace:m=!1}){let{t:x}=(0,se.s)(),[p,h]=(0,r.useState)(t||e),[f,b]=(0,r.useState)([]),[g,v]=(0,r.useState)(!0),[y,w]=(0,r.useState)(""),[k,j]=(0,r.useState)(null),[N,S]=(0,r.useState)(!1),[C,T]=(0,r.useState)("file"),[R,E]=(0,r.useState)(""),[_,$]=(0,r.useState)({isOpen:!1}),[M,P]=(0,r.useState)(null),[A,z]=(0,r.useState)(!1),[I,L]=(0,r.useState)({}),[D,F]=(0,r.useState)(!1),[O,B]=(0,r.useState)(""),[W,K]=(0,r.useState)([]),[H,U]=(0,r.useState)(!1),q=(0,r.useRef)(null),[V]=(0,r.useState)(()=>window.innerWidth>=760),X=(0,r.useCallback)(async e=>{if(u){z(!1),L({});return}let t=await lT(s,e);z(t.hasGit);let n=t.map;L(e=>!function(e,t){let s=Object.keys(e||{}),n=Object.keys(t||{});if(s.length!==n.length)return!1;for(let s of n)if(e[s]!==t[s])return!1;return!0}(e,n)?n:e)},[s,u]),G=(0,r.useCallback)(async e=>{v(!0),w("");let t=await s.getFiles(e,!0);if(t.success){let e=t.files;u&&(e=t.files.filter(e=>"folder"===e.type)),b(t=>{if(t.length!==e.length)return e;for(let s=0;s<e.length;s++)if(t[s]?.name!==e[s]?.name)return e;return t}),h(t.currentPath)}else w(t.error),b([]);v(!1)},[s,u]),{transfer:J,dragOver:Y,conflict:Z,downloadState:Q,startUpload:ee,handleDrop:et,handleDragOver:es,handleDragLeave:en,handleDownload:er,resolveConflict:ea}=function({fileBus:e,currentPath:t,isBrowsing:s,onDone:n,onError:a}){let[l,i]=(0,r.useState)(null),[o,c]=(0,r.useState)(!1),[d,u]=(0,r.useState)(null),[m,x]=(0,r.useState)(null),p=(0,r.useRef)(0),h=(0,r.useCallback)(async s=>{if(!s.length||!e.uploadFiles)return;let r=++p.current;i({total:s.length,done:0,current:s[0]?.file?.name||"",ratio:0}),await e.uploadFiles(t,s,{onConflict:({file:e},t)=>new Promise(s=>{u({name:t||e.name,resolve:s})}),onProgress:(e,t)=>{r===p.current&&i(s=>s?{...s,current:e.name,ratio:t}:s)},onFileDone:e=>{r===p.current&&i(e=>e?{...e,done:e.done+1}:e)}}),r===p.current&&i(null),n?.(t)},[e,t,n]),f=(0,r.useCallback)(async e=>{if(e.preventDefault(),c(!1),s)return;let t=await lX(e.dataTransfer);t.length&&((0,t7.e)(),h(t))},[s,h]),b=(0,r.useCallback)(e=>{e.preventDefault(),s||c(!0)},[s]),g=(0,r.useCallback)(e=>{e.preventDefault(),c(!1)},[]);(0,r.useEffect)(()=>{if(s)return;let e=async e=>{let t=Array.from(e.clipboardData?.files||[]);if(!t.length)return;let s=t.map(e=>({file:e,relativePath:e.name}));(0,t7.e)(),h(s)};return window.addEventListener("paste",e),()=>window.removeEventListener("paste",e)},[s,h]);let v=(0,r.useRef)(0),y=(0,r.useCallback)(t=>{if(!e.downloadFile)return;let s=++v.current;x({name:t.name,ratio:0}),e.downloadFile(t.path,{onSave:(e,n)=>{let r=document.createElement("a");r.href=URL.createObjectURL(e),r.download=n?.fileName||t.name,document.body.appendChild(r),r.click(),r.remove(),URL.revokeObjectURL(r.href),s===v.current&&x(null)},onProgress:e=>{s===v.current&&x(t=>t?{...t,ratio:e}:t)},onError:e=>{a?.(e.message||"Download failed"),s===v.current&&x(null)}})},[e,a]),w=(0,r.useCallback)(e=>{d?.resolve(e),u(null)},[d]);return{transfer:l,dragOver:o,conflict:d,downloadState:m,startUpload:h,handleDrop:f,handleDragOver:b,handleDragLeave:g,handleDownload:y,resolveConflict:w}}({fileBus:s,currentPath:p,isBrowsing:u,onDone:G,onError:w}),el=(0,r.useCallback)(t=>{if(B(t),q.current&&clearTimeout(q.current),!t||t.length<2){K([]),U(!1);return}U(!0),q.current=setTimeout(async()=>{let n=await s.searchFiles(e,t);n.success&&K(n.files),U(!1)},300)},[e,s]),ei=(0,r.useCallback)(()=>{F(!1),B(""),K([])},[]);(0,r.useEffect)(()=>{G(t||e),u||X(e)},[e,t,u]),(0,r.useEffect)(()=>()=>{q.current&&clearTimeout(q.current)},[]),(0,r.useEffect)(()=>{!u&&d&&d(p)},[p,u,d]);let eo=e=>{G(e.path)},ec=()=>j(null),ed=async()=>{if(!M||!M.newName.trim())return;let e=p+"/"+M.newName.trim(),t=await s.renameItem(M.file.path,e);t.success?G(p):w(t.error),P(null)},eu=async()=>{if(!R.trim())return;let e=p+"/"+R.trim(),t=await s.createItem(e,C);t.success?(G(p),S(!1),E("")):w(t.error)},em=(0,r.useRef)(null),ex=(0,r.useRef)(null),ep=e=>{let t=Array.from(e.target.files||[]);if(e.target.value="",!t.length)return;let s=t.map(e=>({file:e,relativePath:e.webkitRelativePath||e.name}));S(!1),ee(s)},eh=async t=>{if(!e||!s||!t?.path)return;ec();let n=t.path.startsWith(e)?t.path.slice(e.length).replace(/^\/+/,""):t.path,r=await l3(s,e,n,"folder"===t.type);r?.success&&(X(e),window.dispatchEvent(new CustomEvent(tp)))},ef=p===e,eb="p-2 bg-surface-2 hover:bg-surface-3 text-text rounded-brand transition-all duration-150 ease-out active:scale-[0.96]";return(0,n.jsxs)("div",{className:"h-full bg-bg flex flex-col",children:[(0,n.jsxs)("div",{className:"bg-surface px-4 py-3 flex items-center gap-2 flex-shrink-0",children:[(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),a()},className:eb,title:x("common.close"),children:(0,n.jsx)(t3.X,{size:20})}),(0,n.jsx)("div",{className:"flex-1 min-w-0",children:(0,n.jsx)("div",{className:"text-text font-medium truncate text-sm",children:p.replace(/^\/Users\/[^/]+/,"~")})}),u&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),sr(p),o(p)},className:"px-3 py-2 bg-brand-500 hover:bg-brand-600 text-white text-xs rounded-brand transition-all duration-150 ease-out active:scale-[0.97] font-medium shadow-sm",title:x("files.setAsWorkspaceTitle"),children:x("files.setWorkspace")}),!u&&c&&!m&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),c()},className:eb,title:x("files.switchWorkspace"),children:(0,n.jsx)(t3.Bm,{className:"text-brand-500",size:20})}),!u&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),F(!0)},className:eb,title:x("files.searchFiles"),children:(0,n.jsx)(t3.vj,{className:"text-brand-500",size:20})}),!u&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),i()},disabled:!A,className:`p-2 rounded-brand transition-all duration-150 ease-out active:scale-[0.96] ${A?"bg-surface-2 hover:bg-surface-3 text-text":"bg-surface-2/30 text-text-muted cursor-not-allowed"}`,title:A?x("git.title"):x("files.noGitRepo"),children:(0,n.jsx)(t3.Zr,{className:A?"text-brand-500":"text-text-muted",size:20})})]}),D&&(0,n.jsx)(l0,{query:O,loading:H,onChange:el,onClose:ei}),y&&(0,n.jsx)("div",{className:"bg-red-500/20 border-b border-red-500/50 px-4 py-2 text-red-400 text-sm",children:y}),J&&(0,n.jsx)(lQ,{label:`${x("files.copying")} ${J.done+1}/${J.total}: ${J.current}`,ratio:J.ratio}),Q&&(0,n.jsx)(lQ,{label:`${x("files.downloading")}: ${Q.name}`,ratio:Q.ratio}),D&&O.length>=2?(0,n.jsx)("div",{className:"flex-1 min-h-0 overflow-auto",children:H?(0,n.jsx)("div",{className:"flex items-center justify-center h-32 text-text-muted",children:x("files.searching")}):0===W.length?(0,n.jsx)("div",{className:"flex items-center justify-center h-32 text-text-muted",children:x("files.noFilesFound")}):(0,n.jsx)("div",{children:W.map(t=>(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),l(t.path),ei()},className:"w-full px-4 py-3 flex items-center gap-3 border-b border-border hover:bg-surface transition-colors text-left",children:[(0,n.jsx)("span",{className:"flex-shrink-0",children:"binary"===t.type?(0,n.jsx)(t3.lP,{size:20,className:"text-red-500/70"}):(0,n.jsx)(t3.ZH,{size:20,className:"text-text-subtle"})}),(0,n.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,n.jsx)("div",{className:"text-text truncate",title:t.name,children:t.name}),(0,n.jsx)("div",{className:"text-text-muted text-xs truncate",title:t.path,children:t.path.replace(e,"").replace(/^\//,"")})]}),t.sizeFormatted&&(0,n.jsx)("span",{className:"text-text-muted text-xs flex-shrink-0",children:t.sizeFormatted})]},t.path))})}):(0,n.jsxs)(n.Fragment,{children:["/"!==p&&!ef&&!D&&(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),G(p.split("/").slice(0,-1).join("/")||"/")},className:"w-full px-4 py-3 flex items-center gap-3 border-b border-border hover:bg-surface transition-colors text-left flex-shrink-0",children:[(0,n.jsx)(t3.JG,{className:"text-green-500",size:28}),(0,n.jsx)("span",{className:"text-green-500",children:p.split("/").pop()||"/"})]}),(0,n.jsx)("div",{className:`flex-1 min-h-0 overflow-auto ${!u?"pb-20":""} ${Y?"bg-brand-500/5 ring-2 ring-inset ring-brand-500/40":""}`,onDrop:et,onDragOver:es,onDragLeave:en,children:u?(0,n.jsx)("div",{className:"p-4",children:g?(0,n.jsx)("div",{className:"flex items-center justify-center h-32 text-text-muted",children:x("common.loading")}):0===f.length?(0,n.jsx)("div",{className:"flex items-center justify-center h-32 text-text-muted",children:x("files.emptyFolder")}):(0,n.jsx)("div",{className:"grid grid-cols-2 gap-3",children:f.map(e=>(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),eo(e)},className:"bg-surface hover:bg-surface-2 rounded-brand-lg p-2 flex flex-col items-center gap-1 transition-all duration-150 ease-out active:scale-[0.98] text-center",children:[(0,n.jsx)(t3.vd,{size:48,className:"text-yellow-500/80"}),(0,n.jsx)("span",{className:"text-text text-xs font-medium truncate w-full",title:e.name,children:e.name})]},e.path))})}):(0,n.jsx)(uu,{files:f,loading:g,onFileClick:e=>{if(!u){if("binary"===e.type){w(x("files.cannotOpenBinary")),setTimeout(()=>w(""),3e3);return}l?.(e.path,p)}},onFolderClick:eo,onMoreClick:(e,t)=>{j({file:e,x:t.x,y:t.y})},gitStatusMap:I,workspacePath:e})})]}),!u&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),S(!0)},className:"absolute bottom-[max(1.5rem,calc(env(safe-area-inset-bottom)+0.5rem))] right-6 w-14 h-14 bg-brand-500 hover:bg-brand-600 text-white rounded-full shadow-lg shadow-brand-500/30 flex items-center justify-center transition-all duration-200",children:(0,n.jsx)(t3.FW,{size:24})}),k&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"fixed inset-0 z-40",onClick:ec}),(0,n.jsxs)("div",{className:"fixed z-50 card-elev overflow-hidden min-w-[140px]",style:{right:16,top:Math.min(k.y,window.innerHeight-160)},children:[(0,n.jsxs)("button",{onClick:()=>{var e;(0,t7.e)(),e=k.file,ec(),P({file:e,newName:e.name})},className:"w-full px-4 py-3 text-left text-text hover:bg-surface-2 flex items-center gap-3 transition-colors",children:[(0,n.jsx)(t3.gH,{size:16}),x("files.rename")]}),(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),navigator.clipboard?.writeText(k.file.path).catch(()=>{}),ec()},className:"w-full px-4 py-3 text-left text-text hover:bg-surface-2 flex items-center gap-3 transition-colors",children:[(0,n.jsx)(t3.QR,{size:16}),x("files.copyPath")]}),V&&(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),ec(),er(k.file)},className:"w-full px-4 py-3 text-left text-text hover:bg-surface-2 flex items-center gap-3 transition-colors",children:[(0,n.jsx)(t3.f5,{size:16}),x("files.download")]}),(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),eh(k.file)},className:"w-full px-4 py-3 text-left text-text hover:bg-surface-2 flex items-center gap-3 transition-colors",children:[(0,n.jsx)(t3.X_,{size:16}),x("git.addToGitignore",{defaultValue:"Add to .gitignore"})]}),(0,n.jsxs)("button",{onClick:()=>{var e;(0,t7.e)(),e=k.file,ec(),$({isOpen:!0,title:x("files.deleteConfirmTitle"),message:x("files.deleteConfirmMessage",{name:e.name}),onConfirm:async()=>{let t=await s.deleteItem(e.path);t.success?G(p):w(t.error)}})},className:"w-full px-4 py-3 text-left text-red-400 hover:bg-surface-2 flex items-center gap-3 transition-colors",children:[(0,n.jsx)(t3.TB,{size:16}),x("files.delete")]})]})]}),N&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(l1,{type:C,name:R,onTypeChange:T,onNameChange:E,onSubmit:eu,onPickFile:()=>em.current?.click(),onPickFolder:()=>ex.current?.click(),onClose:()=>S(!1)}),(0,n.jsx)("input",{ref:em,type:"file",multiple:!0,className:"hidden",onChange:ep}),(0,n.jsx)("input",{ref:ex,type:"file",className:"hidden",webkitdirectory:"",onChange:ep})]}),M&&(0,n.jsx)(l2,{value:M.newName,onChange:e=>P({...M,newName:e}),onSubmit:ed,onClose:()=>P(null)}),(0,n.jsx)(t9.A,{isOpen:_.isOpen,onClose:()=>$({isOpen:!1}),onConfirm:_.onConfirm,title:_.title,message:_.message}),Z&&(0,n.jsx)(l5,{name:Z.name,onResolve:ea})]})}let ux=[{label:"Esc",key:"Escape"},{label:"Tab",key:"Tab"},{label:"←",key:"ArrowLeft"},{label:"→",key:"ArrowRight"},{label:"↑",key:"ArrowUp"},{label:"↓",key:"ArrowDown"},{label:"Ctrl",modifier:"ctrl"},{label:"Opt",modifier:"alt"}],up=[{label:"Undo",key:"z",ctrl:!0},{label:"Redo",key:"y",ctrl:!0},{label:"{}",text:"{}"},{label:"()",text:"()"},{label:"[]",text:"[]"},{label:'""',text:'""'},{label:"=>",text:" => "},{label:"Aa",toggleTextInput:!0}];function uh({viewRef:e}){let{t}=(0,se.s)(),[s,a]=(0,r.useState)(!1),[l,i]=(0,r.useState)(!1),[o,c]=(0,r.useState)(!1),[d,u]=(0,r.useState)(""),m=(0,r.useRef)(null),x=t=>{let s=e.current;if(!s)return;let{from:n,to:r}=s.state.selection.main;s.dispatch({changes:{from:n,to:r,insert:t},selection:{anchor:n+t.length}}),s.focus()},p=(t,{ctrl:n=!1,alt:r=!1}={})=>{let o=e.current;o&&(o.contentDOM.dispatchEvent(new KeyboardEvent("keydown",{key:t,code:1===t.length?`Key${t.toUpperCase()}`:t,ctrlKey:n||s,altKey:r||l,metaKey:n||s,bubbles:!0,cancelable:!0})),o.focus(),a(!1),i(!1))},h=e=>`flex-1 py-2 text-text text-xs rounded-brand transition-all duration-200 border ${e?"bg-brand-500 border-brand-400 shadow-md shadow-brand-500/30":"bg-surface-2 hover:bg-surface-2 border-border hover:border-brand-500"}`;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:`bg-surface transition-all duration-300 overflow-hidden ${o?"max-h-24 opacity-100":"max-h-0 opacity-0"}`,children:(0,n.jsxs)("div",{className:"p-2 flex gap-2 items-center",children:[(0,n.jsx)("textarea",{ref:m,value:d,onChange:e=>u(e.target.value),placeholder:t("editor.typeText"),rows:1,className:"w-full px-3 py-2 bg-surface-2 rounded text-text text-base placeholder-text-muted focus:outline-none focus:ring-2 focus:ring-brand-500/40 transition-all duration-150 ease-out resize-none"}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),d.trim()&&(x(d),u("")),c(!1)},disabled:!d.trim(),className:"px-4 py-2 bg-brand-500 hover:bg-brand-600 disabled:bg-surface-2 disabled:opacity-50 text-white text-sm font-medium rounded transition-all duration-150 ease-out active:scale-[0.97] shadow-sm flex-shrink-0",children:t("editor.insert")})]})}),(0,n.jsxs)("div",{className:"bg-surface border-t border-border px-2 pt-2 pb-safe flex flex-col gap-1 flex-shrink-0",children:[(0,n.jsx)("div",{className:"flex gap-1",children:ux.map(e=>(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),"ctrl"===e.modifier?(a(e=>!e),i(!1)):"alt"===e.modifier?(i(e=>!e),a(!1)):p(e.key)},className:h("ctrl"===e.modifier&&s||"alt"===e.modifier&&l),children:e.label},e.label))}),(0,n.jsx)("div",{className:"flex gap-1",children:up.map(e=>(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),e.toggleTextInput?(c(e=>!e),o||setTimeout(()=>m.current?.focus(),350)):e.text?x(e.text):e.key&&p(e.key,{ctrl:e.ctrl,alt:e.alt})},className:h(e.toggleTextInput&&o),children:e.label},e.label))})]})]})}function uf({filePath:e,fileBus:t,onBack:s,line:a,column:l,workspace:i,diffStatus:o,preview:c=!1}){let{t:d}=(0,se.s)(),u=iT(e),m=!!o,x=e.split("/").pop(),p=iE({filePath:m||u?"":e,fileBus:t}),h=i_({dirty:!m&&!u&&p.dirty,onSave:p.save}),f=(0,r.useRef)(null),[b,g]=(0,r.useState)(!1),[v,y]=(0,r.useState)(null),[w,k]=(0,r.useState)(null),[j,N]=(0,r.useState)(!1),S=m||u?null:tr(e),[C,T]=(0,r.useState)(c&&!!S),[R,E]=(0,r.useState)(0),[_,$]=(0,r.useState)(e),[M,P]=(0,r.useState)(!1);_!==e&&($(e),T(c&&!!S)),p.justSaved!==M&&(P(p.justSaved),p.justSaved&&E(e=>e+1));let A=(0,r.useCallback)((e,t)=>{f.current=t},[]);(0,r.useEffect)(()=>{if(m||!i||!e)return;let s=!1;return t.gitFileStatus(i,e).then(e=>{s||y(e?.success&&e.status?e:null)}),()=>{s=!0}},[e,i,t]);let z=async()=>{if(!v||!i)return;if(tn(e,e3))return void k("image");N(!0);let s=await t.gitDiff(i,v.file,v.status);N(!1),s?.success&&k(s.diff||"")};(0,r.useEffect)(()=>{if(!o||!i||!e)return;let s=!1,n=setTimeout(async()=>{if(tn(e,e3))return void k("image");N(!0);let n=await t.gitDiff(i,e,o);!s&&(N(!1),n?.success&&k(n.diff||""))},0);return()=>{s=!0,clearTimeout(n)}},[o,i,e,t]);let I=async()=>{let e=f.current?.state.doc.toString();if(null!=e)try{await navigator.clipboard.writeText(e),g(!0),setTimeout(()=>g(!1),1500)}catch{}};return(0,n.jsxs)("div",{className:"h-full bg-bg flex flex-col",children:[(0,n.jsxs)("div",{className:"bg-surface px-4 py-3 flex items-center gap-2 flex-shrink-0",children:[(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),h.guard(s)},className:"p-2 bg-surface-2 hover:bg-surface-3 text-text rounded-brand transition-all duration-150 ease-out active:scale-[0.96]",children:(0,n.jsx)(t3.JG,{size:20})}),(0,n.jsxs)("div",{className:"flex-1 flex items-center gap-2 min-w-0",children:[(0,n.jsx)("span",{className:"text-text font-medium truncate",children:x}),p.dirty&&(0,n.jsx)("span",{className:"w-2 h-2 bg-yellow-400 rounded-full flex-shrink-0",title:d("editor.unsaved")}),p.justSaved&&(0,n.jsx)("span",{className:"text-green-400 text-xs flex-shrink-0",children:d("editor.saved")}),b&&(0,n.jsx)("span",{className:"text-green-400 text-xs flex-shrink-0",children:d("editor.copied",{defaultValue:"Copied"})})]}),v&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),z()},disabled:j,className:"p-2 bg-surface-2 hover:bg-surface-3 text-orange-400 rounded-brand transition-all duration-150 ease-out active:scale-[0.96]",title:d("editor.gitDiff"),children:j?(0,n.jsx)(t3.kr,{className:"animate-spin",size:16}):(0,n.jsx)(t3.Zr,{size:16})}),S&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),T(e=>!e)},title:d(C?"editor.editCode":"editor.preview"),className:"p-2 bg-surface-2 hover:bg-surface-3 text-text rounded-brand transition-all duration-150 ease-out active:scale-[0.96]",children:C?(0,n.jsx)(t3.GD,{size:16}):(0,n.jsx)(t3.kU,{size:16})}),!u&&!m&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),I()},className:"p-2 bg-surface-2 hover:bg-surface-3 text-text rounded-brand transition-all duration-150 ease-out active:scale-[0.96]",title:d("editor.copy",{defaultValue:"Copy"}),children:(0,n.jsx)(t3.QR,{size:16})}),!u&&!m&&(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),p.save()},disabled:!p.dirty||p.saving,className:`px-3 py-2 rounded-brand transition-all duration-150 ease-out flex items-center gap-1 ${p.dirty&&!p.saving?"bg-brand-500 hover:bg-brand-600 text-white shadow-sm active:scale-[0.97]":"bg-surface-2 text-text-muted cursor-not-allowed"}`,children:[p.saving?(0,n.jsx)(t3.kr,{className:"animate-spin",size:16}):(0,n.jsx)(t3.eM,{size:16}),(0,n.jsx)("span",{className:"hidden sm:inline",children:d("editor.save")})]})]}),p.error&&!u&&(0,n.jsx)("div",{className:"bg-red-500/20 border-b border-red-500/50 px-4 py-2 text-red-400 text-sm break-words",children:p.error}),(0,n.jsx)("div",{className:"flex-1 min-h-0 overflow-hidden",children:m?tn(e,e3)?(0,n.jsx)(i9,{filePath:e,status:o,workspace:i,fileBus:t}):(0,n.jsx)("div",{className:"h-full overflow-auto p-2",children:j?(0,n.jsx)("div",{className:"h-full flex items-center justify-center text-text-muted",children:d("common.loading")}):w?(0,n.jsx)(i6,{diff:w}):(0,n.jsx)("div",{className:"h-32 flex items-center justify-center text-text-muted text-sm",children:d("git.noChanges")})}):u?(0,n.jsx)(iR,{filePath:e,fileBus:t}):C&&S?(0,n.jsx)(i5,{kind:S,filePath:e,fileBus:t,content:p.content,reloadKey:R}):p.loading?(0,n.jsx)("div",{className:"h-full flex items-center justify-center text-text-muted",children:d("common.loading")}):(0,n.jsx)(iU,{filePath:e,content:p.content,onTextChanged:p.onTextChanged,onRegisterView:(e,t)=>{p.register(e),A(e,t)},onSave:p.save,line:a,column:l})}),!m&&null!==w&&(0,n.jsxs)("div",{className:"absolute inset-0 z-30 bg-bg flex flex-col",children:[(0,n.jsxs)("div",{className:"bg-surface-2 px-4 py-3 flex items-center justify-between flex-shrink-0",children:[(0,n.jsx)("span",{className:"text-text font-medium truncate",children:d("editor.gitDiff")}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),k(null)},className:"p-2 text-text-muted hover:text-text rounded-brand",children:(0,n.jsx)(t3.X,{size:18})})]}),(0,n.jsx)("div",{className:"flex-1 min-h-0 overflow-auto p-2",children:tn(e,e3)?(0,n.jsx)(i9,{filePath:e,status:v?.status,workspace:i,fileBus:t}):w?(0,n.jsx)(i6,{diff:w}):(0,n.jsx)("div",{className:"h-32 flex items-center justify-center text-text-muted text-sm",children:d("git.noChanges")})})]}),!u&&!m&&!p.loading&&!C&&(0,n.jsx)(uh,{viewRef:f}),(0,n.jsx)(i$,{isOpen:h.asking,fileName:x,onSave:h.saveThenLeave,onDiscard:h.discardAndLeave,onCancel:h.cancel})]})}function ub({workspace:e,fileBus:t,branch:s,changedCount:a,onDone:l,onClose:i}){let{t:o}=(0,se.s)(),[c,d]=(0,r.useState)(""),[u,m]=(0,r.useState)(!1),[x,p]=(0,r.useState)(null);(0,r.useEffect)(()=>{let e=e=>{"Escape"!==e.key||u||i()};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[i,u]);let h=c.trim().length>0&&!u,f=async()=>{let s=await t.gitAdd(e);if(!s.success)return{ok:!1,text:s.error||o("git.stageFailed")};let n=await t.gitCommit(e,c.trim());return n.success?{ok:!0,text:ia(o,n.output)}:{ok:!1,text:n.output||n.error||o("git.commitFailed")}},b=async()=>{if(!h)return;(0,t7.e)(),m(!0),p(null);let e=await f();m(!1),p(e),e.ok&&(d(""),l?.())},g=async()=>{if(u)return;(0,t7.e)(),m(!0),p(null);let s=await t.gitPush(e);m(!1),p({ok:s.success,text:s.success?il(o,s.output):s.output||s.error||o("git.pushFailed")}),s.success&&l?.()},v=async()=>{if(!h)return;(0,t7.e)(),m(!0),p(null);let s=await f();if(!s.ok){m(!1),p(s);return}d("");let n=await t.gitPush(e);m(!1),p({ok:n.success,text:n.success?il(o,n.output):n.output||n.error||o("git.pushFailed")}),l?.()};return(0,n.jsxs)("div",{className:"fixed inset-0 z-[70] flex items-center justify-center p-4",children:[(0,n.jsx)("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-[2px] animate-in fade-in duration-200",onClick:()=>!u&&i()}),(0,n.jsxs)("div",{className:"relative card-elev max-w-md w-full flex flex-col animate-in zoom-in-95 duration-200",children:[(0,n.jsxs)("div",{className:"px-5 py-4 flex items-center justify-between flex-shrink-0",children:[(0,n.jsxs)("h3",{className:"text-lg font-semibold text-text flex items-center gap-2",children:[(0,n.jsx)(t3.Zr,{size:18,className:"text-brand-500"}),o("git.title"),s?` \xb7 ${s}`:""]}),(0,n.jsx)("button",{onClick:()=>!u&&i(),className:"p-2 text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-all duration-150 ease-out","aria-label":o("common.close"),children:(0,n.jsx)(t3.X,{size:20})})]}),(0,n.jsxs)("div",{className:"px-5 pb-5 flex flex-col gap-4",children:[(0,n.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,n.jsx)("textarea",{value:c,onChange:e=>d(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&(e.preventDefault(),v())},rows:2,placeholder:o("git.commitPlaceholder"),disabled:u,className:"w-full px-3 py-2 bg-surface-2 text-text text-sm rounded-brand outline-none focus:ring-1 focus:ring-brand-500 resize-y min-h-[54px] max-h-[200px] disabled:opacity-60"}),(0,n.jsx)("span",{className:"text-xs text-text-subtle",children:o("git.stageAllNote",{count:a})})]}),(0,n.jsxs)("button",{onClick:v,disabled:!h,className:"w-full px-4 py-2.5 text-sm bg-brand-500 hover:bg-brand-500/80 text-white font-medium rounded-brand transition-colors flex items-center justify-center gap-2 disabled:opacity-40 disabled:cursor-not-allowed",children:[u?(0,n.jsx)(t3.kr,{size:16,className:"animate-spin"}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(t3.aJ,{size:16}),(0,n.jsx)(t3.Do,{size:16})]}),(0,n.jsx)("span",{children:o("git.commitAndPush")}),(0,n.jsx)("kbd",{className:"hidden sm:inline-flex items-center text-[10px] font-mono px-1.5 py-0.5 rounded bg-white/20 text-white leading-none",children:"⌘↵"})]}),(0,n.jsxs)("div",{className:"flex gap-2",children:[(0,n.jsxs)("button",{onClick:b,disabled:!h,className:"flex-1 px-4 py-2 text-sm bg-surface-3 hover:bg-surface text-text rounded-brand transition-colors flex items-center justify-center gap-1.5 disabled:opacity-40 disabled:cursor-not-allowed",children:[(0,n.jsx)(t3.aJ,{size:16}),o("git.commit")]}),(0,n.jsxs)("button",{onClick:g,disabled:u,className:"flex-1 px-4 py-2 text-sm bg-surface-3 hover:bg-surface text-text rounded-brand transition-colors flex items-center justify-center gap-1.5 disabled:opacity-40 disabled:cursor-not-allowed",children:[(0,n.jsx)(t3.Do,{size:16}),o("git.push")]})]}),x&&(0,n.jsx)("pre",{className:`text-xs whitespace-pre-wrap break-words px-3 py-2 rounded-brand max-h-32 overflow-y-auto ${x.ok?"bg-emerald-500/15 text-emerald-400":"bg-red-500/15 text-red-400"}`,children:x.text})]})]})]})}function ug({workspace:e,fileBus:t,onBack:s,onOpenFile:a}){let{t:l}=(0,se.s)(),[i,o]=(0,r.useState)("status"),[c,d]=(0,r.useState)(!0),[u,m]=(0,r.useState)(!1),[x,p]=(0,r.useState)(""),[h,f]=(0,r.useState)([]),[b,g]=(0,r.useState)(null),[v,y]=(0,r.useState)(null),[w,k]=(0,r.useState)(""),[j,N]=(0,r.useState)(!1),[S,C]=(0,r.useState)({isOpen:!1}),[T,R]=(0,r.useState)(""),[E,_]=(0,r.useState)(null),[$,M]=(0,r.useState)(null),[P,A]=(0,r.useState)(!1),z=(0,r.useCallback)(async()=>{d(!0),p("");let s=await t.gitStatus(e);s.success?f(s.files):p(s.error),t.gitBranch(e).then(e=>{e?.success&&(R(e.branch),_(e.ahead??null),M(e.behind??null))}),d(!1)},[e,t]),I=(0,r.useCallback)(async(s=null,n=null)=>{if(g(s),y(n),s&&tn(s,e3)){k("image"),N(!0),m(!1);return}m(!0),p("");let r=await t.gitDiff(e,s,n);r.success?(k(r.diff),N(!0)):p(r.error),m(!1)},[e,t]);(0,r.useEffect)(()=>{z()},[z]);let L=(0,r.useCallback)(()=>{if(o("diff"),!j&&h.length>0){let e=h[0];I(e.path,e.status)}},[j,I,h]),D=(0,r.useCallback)(()=>{b&&v&&F(b,v)},[b,v]),F=(0,r.useCallback)((s,n)=>{let r=s.split("/").pop(),a="?"===n;C({isOpen:!0,title:l("git.discardConfirmTitle"),message:a?l("git.discardConfirmDelete",{name:r}):l("git.discardConfirmDiscard",{name:r}),onConfirm:async()=>{let r=await t.gitDiscard(e,s,n);if(r.success){if(await z(),"diff"===i){let e=h.filter(e=>e.path!==s);e.length>0?I(e[0].path,e[0].status):(o("status"),g(null),k(""),N(!1))}}else p(r.error)}})},[t,e,z,I,h,i,l]),O=(0,r.useCallback)(t=>{let s=e.endsWith("/")?`${e}${t}`:`${e}/${t}`;a?.(s)},[e,a]),[B,W]=(0,r.useState)(null),K=(0,r.useCallback)(async e=>{try{await navigator.clipboard.writeText(e)}catch{}},[]),H=(0,r.useCallback)((e,t)=>{t.preventDefault(),t.stopPropagation(),(0,t7.e)(),W({file:e,x:t.clientX,y:t.clientY})},[]),U=(0,r.useCallback)(async s=>{if(!e||!t||!s?.path)return;let n=await l3(t,e,s.path);n?.success&&(window.dispatchEvent(new CustomEvent(tp)),z())},[e,t,z]),q=(0,r.useCallback)(t=>{let s=e.endsWith("/")?`${e}${t.path}`:`${e}/${t.path}`;return[{key:"open",label:l("common.open",{defaultValue:"Open"}),icon:it.ExternalLink,disabled:"D"===t.status,onClick:()=>O(t.path)},{key:"copyPath",label:l("files.copyPath",{defaultValue:"Copy Path"}),icon:it.Copy,onClick:()=>K(s)},{key:"copyRel",label:l("files.copyRelPath",{defaultValue:"Copy Relative Path"}),icon:it.FileText,onClick:()=>K(t.path)},{key:"copyName",label:l("files.copyName",{defaultValue:"Copy Filename"}),icon:it.FileText,onClick:()=>K(t.path.split("/").pop())},{key:"addToGitignore",label:l("git.addToGitignore",{defaultValue:"Add to .gitignore"}),icon:it.EyeOff,onClick:()=>U(t)},{key:"discard",label:l("git.discardChangesTitle",{defaultValue:"Discard Changes"}),icon:it.Undo2,danger:!0,onClick:()=>F(t.path,t.status)}]},[e,l,O,K,U,F]),V={modified:h.filter(e=>"M"===e.status),added:h.filter(e=>"A"===e.status),deleted:h.filter(e=>"D"===e.status),untracked:h.filter(e=>"?"===e.status)},X=e=>{let t=e.path.split("/").pop(),s=e.path.includes("/")?e.path.substring(0,e.path.lastIndexOf("/")+1):"",r=e.added>0||e.deleted>0;return(0,n.jsx)("div",{className:"px-3 py-2 bg-surface rounded hover:bg-surface-2 transition",onContextMenu:t=>H(e,t),children:(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("span",{className:"flex-shrink-0 flex items-center",children:lB({name:t,path:e.path,type:"file"},18)}),(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),I(e.path,e.status),o("diff")},className:"flex-1 min-w-0 text-left",children:[(0,n.jsx)("div",{className:"text-text font-medium truncate",title:e.path,children:t}),s&&(0,n.jsx)("div",{className:"text-text-muted text-xs truncate",title:s,children:s})]}),r&&(0,n.jsxs)("div",{className:"flex items-center gap-1 text-xs flex-shrink-0",children:[e.added>0&&(0,n.jsxs)("span",{className:"text-[var(--success)]",children:["+",e.added]}),e.deleted>0&&(0,n.jsxs)("span",{className:"text-[var(--danger)]",children:["-",e.deleted]})]}),"D"!==e.status&&(0,n.jsx)("button",{onClick:t=>{t.stopPropagation(),(0,t7.e)(),O(e.path)},className:"p-1.5 text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-all duration-200 flex-shrink-0",title:l("git.openFile"),children:(0,n.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,n.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})})}),(0,n.jsx)("button",{onClick:t=>{t.stopPropagation(),(0,t7.e)(),F(e.path,e.status)},className:"p-1.5 text-text-muted hover:text-red-400 hover:bg-surface-2 rounded-brand transition-all duration-200 flex-shrink-0",title:l("git.discardChangesTitle"),children:(0,n.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,n.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6"})})}),(0,n.jsx)("span",{className:`font-mono font-bold w-5 h-5 flex items-center justify-center text-[11px] rounded flex-shrink-0 bg-surface-2 ${tl[e.status]}`,children:e.status})]})},e.path)};return(0,n.jsxs)("div",{className:"h-full bg-bg flex flex-col",children:[(0,n.jsxs)("div",{className:"bg-surface border-b border-border px-4 py-3 flex items-center gap-3 flex-shrink-0",children:[(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),s()},className:"p-2 bg-surface-2 hover:bg-surface-2 text-text rounded-brand transition-all duration-200",children:(0,n.jsx)("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,n.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}),(0,n.jsxs)("h1",{className:"text-text text-lg font-semibold truncate flex items-center gap-2",children:[l("git.title"),T?(0,n.jsxs)("span",{className:"text-text-muted font-normal",children:[" \xb7 ",T]}):null,E>0&&(0,n.jsxs)("span",{className:"text-xs font-medium px-1.5 py-0.5 rounded-brand bg-brand-500/15 text-brand-500",children:["↑",E]}),$>0&&(0,n.jsxs)("span",{className:"text-xs font-medium px-1.5 py-0.5 rounded-brand bg-surface-3 text-text-muted",children:["↓",$]})]}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),A(!0)},className:"ml-auto p-2 bg-surface-2 hover:bg-surface-3 text-text rounded-brand transition-all duration-200",title:l("git.gitActions"),children:(0,n.jsx)(t3.Zr,{className:"w-5 h-5"})}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),"status"===i?z():I(b,v)},className:"p-2 bg-surface-2 hover:bg-surface-2 text-text rounded-brand transition-all duration-200",title:l("common.refresh"),children:(0,n.jsx)("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,n.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})})})]}),(0,n.jsxs)("div",{className:"flex border-b border-border flex-shrink-0",children:[(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),o("status")},className:`flex-1 py-3 text-center font-medium transition ${"status"===i?"text-text border-b-2 border-brand-500":"text-text-muted hover:text-text"}`,children:l("git.status")}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),L()},className:`flex-1 py-3 text-center font-medium transition ${"diff"===i?"text-text border-b-2 border-brand-500":"text-text-muted hover:text-text"}`,children:l("git.diffTab")})]}),x&&(0,n.jsx)("div",{className:"bg-red-500/20 border-b border-red-500/50 px-4 py-2 text-red-400 text-sm",children:x}),(0,n.jsx)("div",{className:"flex-1 overflow-y-auto overflow-x-hidden modal-scrollable",children:"status"===i?c?(0,n.jsx)("div",{className:"flex items-center justify-center h-32 text-text-muted",children:l("common.loading")}):(0,n.jsx)("div",{className:"p-4 space-y-4",children:0===h.length?(0,n.jsx)("div",{className:"text-center text-text-muted py-8",children:l("git.noChanges")}):(0,n.jsxs)(n.Fragment,{children:[V.modified.length>0&&(0,n.jsxs)("div",{children:[(0,n.jsxs)("h3",{className:"text-text-muted text-sm mb-2",children:[l("git.modified")," (",V.modified.length,")"]}),(0,n.jsx)("div",{className:"space-y-1",children:V.modified.map(X)})]}),V.added.length>0&&(0,n.jsxs)("div",{children:[(0,n.jsxs)("h3",{className:"text-text-muted text-sm mb-2",children:[l("git.added")," (",V.added.length,")"]}),(0,n.jsx)("div",{className:"space-y-1",children:V.added.map(X)})]}),V.deleted.length>0&&(0,n.jsxs)("div",{children:[(0,n.jsxs)("h3",{className:"text-text-muted text-sm mb-2",children:[l("git.deleted")," (",V.deleted.length,")"]}),(0,n.jsx)("div",{className:"space-y-1",children:V.deleted.map(X)})]}),V.untracked.length>0&&(0,n.jsxs)("div",{children:[(0,n.jsxs)("h3",{className:"text-text-muted text-sm mb-2",children:[l("git.untrackedTitle")," (",V.untracked.length,")"]}),(0,n.jsx)("div",{className:"space-y-1",children:V.untracked.map(X)})]})]})}):(0,n.jsxs)("div",{className:"p-4 min-w-0",children:[h.length>0&&(0,n.jsxs)("div",{className:"flex gap-2 mb-4",children:[(0,n.jsx)("select",{value:b||"",onChange:e=>{(0,t7.e)();let t=h.find(t=>t.path===e.target.value);t&&I(t.path,t.status)},className:"flex-1 min-w-0 px-3 py-2 bg-surface-2 rounded-brand text-text focus:outline-none focus:ring-2 focus:ring-brand-500/40 transition-all duration-150 ease-out",children:h.map(e=>(0,n.jsxs)("option",{value:e.path,children:["[",e.status,"] ",e.path]},e.path))}),b&&"D"!==v&&(0,n.jsx)("button",{onClick:e=>{e.stopPropagation(),(0,t7.e)(),O(b)},disabled:u,className:"h-9 w-9 flex-shrink-0 bg-surface-2 hover:bg-surface-3 disabled:cursor-not-allowed text-text rounded-brand transition-all duration-200 flex items-center justify-center",title:l("git.openFile"),children:(0,n.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,n.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})})}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),D()},disabled:!b||u,className:"h-9 w-9 flex-shrink-0 bg-red-500/10 hover:bg-red-500/20 disabled:bg-surface-2 disabled:cursor-not-allowed text-red-400 rounded-brand transition-all duration-200 flex items-center justify-center",title:l("git.discardChangesTitle"),children:(0,n.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,n.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6"})})})]}),u?(0,n.jsx)("div",{className:"flex items-center justify-center h-32 text-text-muted",children:l("common.loading")}):b&&tn(b,e3)?(0,n.jsx)(i9,{filePath:b,status:v,workspace:e,fileBus:t}):w?(0,n.jsx)(i6,{diff:w}):(0,n.jsx)("div",{className:"flex items-center justify-center h-32 text-text-muted",children:l("git.noChanges")})]})}),(0,n.jsx)(t9.A,{isOpen:S.isOpen,onClose:()=>C({isOpen:!1}),onConfirm:S.onConfirm,title:S.title,message:S.message}),P&&(0,n.jsx)(ub,{workspace:e,fileBus:t,branch:T,changedCount:h.length,onDone:z,onClose:()=>A(!1)}),B&&(0,n.jsx)(ie,{x:B.x,y:B.y,items:q(B.file),onClose:()=>W(null)})]})}let uv=[{id:tv,Icon:t3.sv,label:"Explorer"},{id:ty,Icon:t3.vj,label:"Search"},{id:"scm",Icon:t3.Zr,label:"Source Control"}];function uy({active:e,onClick:t,label:s,children:r}){return(0,n.jsx)("button",{type:"button",title:s,onClick:t,className:`relative w-10 h-10 flex items-center justify-center rounded-brand transition-all duration-150 ease-out active:scale-[0.96] ${e?"bg-surface-2 text-text border-l-2 border-brand-500":"text-text-muted hover:text-text hover:bg-surface-2"}`,children:r})}function uw({activePanel:e,onSelectPanel:t,onBack:s}){let r=e=>{(0,t7.e)(10),t?.(e)};return(0,n.jsxs)("div",{className:"flex flex-col items-center justify-between bg-surface border-r border-border py-2",style:{width:48},children:[(0,n.jsxs)("div",{className:"flex flex-col items-center gap-1",children:[(0,n.jsx)(uy,{onClick:()=>{(0,t7.e)(10),s?.()},label:"Back",children:(0,n.jsx)(t3.JG,{size:20})}),uv.map(({id:t,Icon:s,label:a})=>(0,n.jsx)(uy,{active:e===t,onClick:()=>r(t),label:a,children:(0,n.jsx)(s,{size:20})},t))]}),(0,n.jsx)("div",{className:"flex flex-col items-center gap-1",children:(0,n.jsx)(uy,{active:e===tw,onClick:()=>r(tw),label:"Settings",children:(0,n.jsx)(t3.wB,{size:20})})})]})}function uk({active:e,onClick:t,title:s,children:r}){return(0,n.jsx)("button",{type:"button",title:s,onClick:()=>{(0,t7.e)(),t()},className:`px-2 h-6 text-xs rounded-brand border transition-colors ${e?"bg-brand-500 text-white border-brand-500":"bg-surface-2 text-text-muted border-border hover:bg-surface-3"}`,children:r})}function uj({workspace:e,fileBus:t,onOpenFile:s}){let[a,l]=(0,r.useState)(""),[i,o]=(0,r.useState)(""),[c,d]=(0,r.useState)(!1),[u,m]=(0,r.useState)(!1),[x,p]=(0,r.useState)(!1),[h,f]=(0,r.useState)(""),[b,g]=(0,r.useState)(""),[v,y]=(0,r.useState)(!1),[w,k]=(0,r.useState)(!1),[j,N]=(0,r.useState)([]),[S,C]=(0,r.useState)(!1),[T,R]=(0,r.useState)(!1),[E,_]=(0,r.useState)(new Set),[$,M]=(0,r.useState)(!1),P=(0,r.useRef)(null),A=(0,r.useCallback)(async()=>{if(!a||!e||!t?.searchInFiles){N([]),R(!1);return}C(!0);let s=await t.searchInFiles(e,a,{caseSensitive:c,wholeWord:u,regex:x,includeGlob:h,excludeGlob:b});if(C(!1),s?.success){R(!1);let e=s.results||[];N(e),_(new Set(e.map(e=>e.path)))}else R(!0),N([])},[a,e,t,c,u,x,h,b]);(0,r.useEffect)(()=>{if(P.current&&clearTimeout(P.current),!a){N([]),C(!1);return}return P.current=setTimeout(A,400),()=>clearTimeout(P.current)},[a,c,u,x,h,b,A]);let z=(0,r.useMemo)(()=>{let e=0;for(let t of j)e+=(t.matches||[]).length;return{files:j.length,matches:e}},[j]),I=(0,r.useCallback)(e=>{_(t=>{let s=new Set(t);return s.has(e)?s.delete(e):s.add(e),s})},[]),L=(0,r.useCallback)(async()=>{if(!a||!e||!t?.replaceInFiles||!j.length)return;let s=j.map(e=>e.path);C(!0),await t.replaceInFiles(e,a,i,{caseSensitive:c,wholeWord:u,regex:x,includeGlob:h,excludeGlob:b},s),C(!1),A()},[a,i,e,t,j,c,u,x,h,b,A]);return(0,n.jsxs)("div",{className:"flex flex-col h-full text-sm text-text",children:[(0,n.jsxs)("div",{className:"px-3 pt-3 pb-2 space-y-2 border-b border-border",children:[(0,n.jsxs)("div",{className:"relative",children:[(0,n.jsx)(t3.vj,{size:14,className:"absolute left-2 top-1/2 -translate-y-1/2 text-text-subtle"}),(0,n.jsx)("input",{value:a,onChange:e=>l(e.target.value),placeholder:"Search",className:"w-full bg-surface-2 border border-border rounded-brand pl-7 pr-7 h-8 text-xs text-text placeholder-text-subtle focus:outline-none focus:border-brand-500"}),a&&(0,n.jsx)("button",{type:"button",onClick:()=>{(0,t7.e)(),l("")},className:"absolute right-1 top-1/2 -translate-y-1/2 p-1 text-text-subtle hover:text-text",children:(0,n.jsx)(t3.X,{size:12})})]}),(0,n.jsxs)("div",{className:"flex items-center gap-1 flex-wrap",children:[(0,n.jsx)(uk,{active:c,onClick:()=>d(!c),title:"Match Case",children:"Aa"}),(0,n.jsx)(uk,{active:u,onClick:()=>m(!u),title:"Whole Word",children:"ab"}),(0,n.jsx)(uk,{active:x,onClick:()=>p(!x),title:"Regex",children:".*"}),(0,n.jsx)("span",{className:"flex-1"}),(0,n.jsx)(uk,{active:w,onClick:()=>k(!w),title:"Toggle Replace",children:"↔"}),(0,n.jsx)(uk,{active:v,onClick:()=>y(!v),title:"Filters",children:"…"})]}),w&&(0,n.jsxs)("div",{className:"flex items-center gap-1",children:[(0,n.jsx)("input",{value:i,onChange:e=>o(e.target.value),placeholder:"Replace",className:"flex-1 bg-surface-2 border border-border rounded-brand px-2 h-8 text-xs text-text placeholder-text-subtle focus:outline-none focus:border-brand-500"}),(0,n.jsx)("button",{type:"button",disabled:!a||!j.length,onClick:()=>{(0,t7.e)(),M(!0)},className:"px-2 h-8 text-xs rounded-brand bg-brand-500 text-white hover:opacity-90 disabled:opacity-40 disabled:cursor-not-allowed",children:"Replace All"})]}),v&&(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsx)("input",{value:h,onChange:e=>f(e.target.value),placeholder:"files to include",className:"w-full bg-surface-2 border border-border rounded-brand px-2 h-7 text-xs text-text placeholder-text-subtle focus:outline-none focus:border-brand-500"}),(0,n.jsx)("input",{value:b,onChange:e=>g(e.target.value),placeholder:"files to exclude",className:"w-full bg-surface-2 border border-border rounded-brand px-2 h-7 text-xs text-text placeholder-text-subtle focus:outline-none focus:border-brand-500"})]}),(0,n.jsx)("div",{className:`text-[11px] ${T?"text-danger":"text-text-muted"}`,children:S?"Searching...":T?"Search failed — try again":a?`${z.matches} results in ${z.files} files`:"Type to search"})]}),(0,n.jsx)("div",{className:"flex-1 overflow-auto",children:j.map(e=>{let t=E.has(e.path),r=function(e){if(!e)return"";let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t>=0?e.slice(t+1):e}(e.path),l=function(e){if(!e)return"";let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t>=0?e.slice(0,t):""}(e.path);return(0,n.jsxs)("div",{className:"border-b border-border/60",children:[(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),I(e.path)},className:"w-full flex items-center gap-1 px-2 py-1 hover:bg-surface-2 text-left",children:[t?(0,n.jsx)(t3.yQ,{size:12,className:"text-text-subtle"}):(0,n.jsx)(t3.c_,{size:12,className:"text-text-subtle"}),(0,n.jsx)("span",{className:"truncate text-xs text-text",title:e.path,children:r}),(0,n.jsx)("span",{className:"truncate text-[11px] text-text-muted flex-1",title:l,children:l}),(0,n.jsx)("span",{className:"text-[10px] px-1.5 rounded-brand bg-surface-3 text-text-muted",children:e.matches?.length||0})]}),t&&(0,n.jsx)("div",{className:"pl-5",children:(e.matches||[]).map((t,r)=>(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),s?.(e.path,{line:t.line,column:t.column})},className:"w-full text-left px-2 py-0.5 text-[11px] text-text-muted hover:bg-surface-2 truncate font-mono",title:t.lineText,children:[(0,n.jsx)("span",{className:"text-text-subtle mr-2",children:t.line}),function(e,t,{caseSensitive:s,wholeWord:r,regex:a}){let l,i;if(!t)return e;try{let e=a?t:t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");r&&!a&&(e=`\\b${e}\\b`),l=new RegExp(e,s?"g":"gi")}catch{return e}let o=[],c=0,d=0;for(;null!==(i=l.exec(e))&&d++<500;)i.index>c&&o.push(e.slice(c,i.index)),o.push((0,n.jsx)("span",{className:"bg-brand-500/30 text-text rounded-sm",children:i[0]},`${i.index}-${d}`)),c=i.index+i[0].length,i.index===l.lastIndex&&l.lastIndex++;return c<e.length&&o.push(e.slice(c)),o}(t.lineText||"",a,{caseSensitive:c,wholeWord:u,regex:x})]},`${e.path}-${r}`))})]},e.path)})}),(0,n.jsx)(t9.A,{isOpen:$,onClose:()=>M(!1),onConfirm:L,title:"Replace All",message:`Replace ${z.matches} matches in ${z.files} files?`,confirmText:"Replace All",cancelText:"Cancel"})]})}let uN="px-3 my-2 text-[11px] uppercase tracking-wider text-text-muted",uS="flex items-center justify-between px-3 py-2 hover:bg-surface-2";function uC({value:e,onChange:t}){return(0,n.jsx)("button",{type:"button",onClick:()=>{(0,t7.e)(),t(!e)},className:`relative w-9 h-5 rounded-full transition-colors ${e?"bg-brand-500":"bg-surface-3"}`,children:(0,n.jsx)("span",{className:`absolute top-0.5 w-4 h-4 rounded-full bg-white transition-transform ${e?"translate-x-4":"translate-x-0.5"}`})})}function uT(){let[e,t]=nj(th,14),[s,r]=nj(tf,!1),[a,l]=nj("fileExplorer.showHidden",!0),i=e=>{t(Math.max(10,Math.min(28,Number(e)||14)))};return(0,n.jsxs)("div",{className:"flex flex-col h-full text-sm text-text overflow-auto",children:[(0,n.jsx)("div",{className:uN,children:"Editor"}),(0,n.jsxs)("div",{className:uS,children:[(0,n.jsx)("span",{className:"text-xs text-text",children:"Font Size"}),(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("input",{type:"range",min:10,max:28,value:e,onChange:e=>i(e.target.value),className:"w-24 accent-brand-500"}),(0,n.jsx)("input",{type:"number",min:10,max:28,value:e,onChange:e=>i(e.target.value),className:"w-12 bg-surface-2 border border-border rounded-brand px-1 h-6 text-xs text-text text-center focus:outline-none focus:border-brand-500"})]})]}),(0,n.jsxs)("div",{className:uS,children:[(0,n.jsx)("span",{className:"text-xs text-text",children:"Word Wrap"}),(0,n.jsx)(uC,{value:s,onChange:r})]}),(0,n.jsx)("div",{className:uN,children:"Files"}),(0,n.jsxs)("div",{className:uS,children:[(0,n.jsx)("span",{className:"text-xs text-text",children:"Show Hidden Files"}),(0,n.jsx)(uC,{value:a,onChange:l})]}),(0,n.jsx)("div",{className:uN,children:"About"}),(0,n.jsx)("div",{className:"px-3 py-2 text-xs text-text-muted",children:"VSCode-like File Explorer for 9remote"})]})}let uR={[tv]:"Explorer",[ty]:"Search",scm:"Source Control",[tw]:"Settings"};function uE({activePanel:e,workspace:t,fileBus:s,onOpenFile:r,onSwitchWorkspace:a,activeFile:l}){let i=uR[e]||"",o=e===tv;return(0,n.jsxs)("div",{className:"flex flex-col h-full",children:[!o&&(0,n.jsxs)("div",{style:{height:32},className:"bg-surface px-3 border-b border-border flex items-center justify-between flex-shrink-0",children:[(0,n.jsx)("span",{className:"uppercase tracking-wider text-xs text-text-muted",children:i}),(0,n.jsx)("button",{type:"button",title:"Refresh",onClick:()=>{(0,t7.e)(10),s?.refresh?.()},className:"w-7 h-7 flex items-center justify-center rounded-brand text-text-muted hover:text-text hover:bg-surface-2 transition-all duration-150 ease-out active:scale-[0.96]",children:(0,n.jsx)(t3.e9,{size:14})})]}),(0,n.jsx)("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col",children:function({activePanel:e,workspace:t,fileBus:s,onOpenFile:r,onSwitchWorkspace:a,activeFile:l}){switch(e){case tv:return(0,n.jsx)(l7,{workspace:t,fileBus:s,onOpenFile:r,activeFile:l,onSwitchWorkspace:a});case ty:return(0,n.jsx)(uj,{workspace:t,fileBus:s,onOpenFile:r});case"scm":return(0,n.jsx)(ix,{workspace:t,fileBus:s,onOpenFile:r});case tw:return(0,n.jsx)(uT,{});default:return null}}({activePanel:e,workspace:t,fileBus:s,onOpenFile:r,onSwitchWorkspace:a,activeFile:l})})]})}function u_({openedFiles:e,activeFile:t,dirtyFiles:s,onActivate:a,onClose:l,onCloseOthers:i,onCloseAll:o}){let[c,d]=(0,r.useState)(null),u=(0,r.useRef)(null);return((0,r.useEffect)(()=>{if(!c)return;let e=e=>{u.current&&!u.current.contains(e.target)&&d(null)};return window.addEventListener("mousedown",e),()=>window.removeEventListener("mousedown",e)},[c]),e?.length)?(0,n.jsxs)("div",{className:"flex overflow-x-auto bg-surface border-b border-border flex-shrink-0 relative",children:[e.map(e=>{let r=e===t,i=s?.has(e),o=tu(e),c=o?tm(e).absPath:e,u=o?`${c.split("/").pop()} (diff)`:c.split("/").pop(),m=o?null:lB({name:c.split("/").pop()||c,type:"file",path:c},14);return(0,n.jsxs)("div",{onClick:()=>{(0,t7.e)(),a(e)},onMouseDown:t=>{1===t.button&&(t.preventDefault(),(0,t7.e)(),l(e))},onContextMenu:t=>{t.preventDefault(),d({path:e,x:t.clientX,y:t.clientY})},className:`group flex items-center gap-2 px-3 py-1.5 border-r border-border cursor-pointer text-sm flex-shrink-0 select-none ${r?"bg-bg text-text border-t-2 border-t-brand-500":"bg-surface text-text-muted hover:text-text"}`,children:[m?(0,n.jsx)("span",{className:"flex-shrink-0 flex items-center",children:m}):(0,n.jsx)(t3.Ay,{name:"File",size:14,className:"text-text-muted"}),(0,n.jsx)("span",{className:"truncate max-w-[160px]",title:c,children:u}),i?(0,n.jsx)("span",{className:"w-2 h-2 rounded-full bg-brand-500 flex-shrink-0"}):null,(0,n.jsx)("button",{onClick:t=>{t.stopPropagation(),(0,t7.e)(),l(e)},className:`p-0.5 rounded hover:bg-surface-3 transition-opacity ${r||i?"opacity-100":"opacity-0 group-hover:opacity-100"}`,children:(0,n.jsx)(t3.X,{size:14})})]},e)}),c&&(0,n.jsx)("div",{ref:u,style:{top:c.y,left:c.x},className:"fixed z-50 bg-surface-2 border border-border rounded-brand shadow-lg py-1 text-sm min-w-[160px]",children:[{label:"Close",action:()=>l(c.path)},{label:"Close Others",action:()=>i(c.path)},{label:"Close All",action:()=>o()}].map(e=>(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),e.action(),d(null)},className:"w-full text-left px-3 py-1.5 text-text hover:bg-surface-3 transition-colors",children:e.label},e.label))})]}):null}function u$({workspace:e,filePath:t}){if(!t)return(0,n.jsx)("div",{className:"bg-bg border-b border-border px-3 py-1 text-xs text-text-muted h-7"});let s=e?e.split("/").filter(Boolean).pop():"",a=(e&&t.startsWith(e+"/")?t.slice(e.length+1):t).split("/").filter(Boolean),l=s?[s,...a]:a,i=l.length-1;return(0,n.jsx)("div",{className:"bg-bg border-b border-border px-3 py-1 text-xs text-text-muted flex items-center gap-1 overflow-x-auto whitespace-nowrap",children:l.map((e,t)=>(0,n.jsxs)(r.Fragment,{children:[(0,n.jsx)("span",{className:t===i?"text-text font-medium":"hover:text-text cursor-default",children:e}),t<i&&(0,n.jsx)(t3.c_,{size:12,className:"flex-shrink-0"})]},t))})}function uM({filePath:e,workspace:t,fileBus:s,isActive:a,onCursorChange:l,onDirtyChange:i,onRegisterSaver:o,previewSeq:c=0}){let{t:d}=(0,se.s)(),u=!tu(e)&&!iT(e),m=iE({filePath:u?e:"",fileBus:s}),x=u?tr(e):null,[p,h]=(0,r.useState)(!!c&&!!x),[f,b]=(0,r.useState)(0),[g,v]=(0,r.useState)(e),[y,w]=(0,r.useState)(!1),[k,j]=(0,r.useState)(c);return(g!==e?(v(e),h(!1)):k!==c&&(j(c),c&&x&&h(!0)),m.justSaved!==y&&(w(m.justSaved),m.justSaved&&b(e=>e+1)),(0,r.useEffect)(()=>{i?.(e,u&&m.dirty)},[e,u,m.dirty,i]),(0,r.useEffect)(()=>{if(u)return o?.(e,m.save),()=>{o?.(e,null),i?.(e,!1)}},[e,u,m.save,o,i]),(0,r.useEffect)(()=>{if(!a||!u)return;let e=e=>{(e.metaKey||e.ctrlKey)&&"s"===e.key.toLowerCase()&&(e.preventDefault(),m.save())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[a,u,m]),tu(e))?(0,n.jsx)(i7,{diffPath:e,workspace:t,fileBus:s}):iT(e)?(0,n.jsx)(iR,{filePath:e,fileBus:s}):(0,n.jsxs)("div",{className:"h-full flex flex-col",children:[m.error&&(0,n.jsx)("div",{className:"px-4 py-2 text-sm text-red-400 bg-red-500/15 border-b border-red-500/40 break-words",children:m.error}),x&&(0,n.jsx)("div",{className:"px-3 py-1.5 flex items-center justify-end bg-surface border-b border-border-subtle flex-shrink-0",children:(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),h(e=>!e)},title:d(p?"editor.editCode":"editor.preview"),className:"p-1 text-text-muted hover:text-text rounded-[3px] hover:bg-surface-2 transition-colors",children:p?(0,n.jsx)(t3.GD,{size:13}):(0,n.jsx)(t3.kU,{size:13})})}),m.dirty&&(0,n.jsxs)("div",{className:"px-3 py-1.5 flex items-center gap-2 bg-surface border-b border-border-subtle flex-shrink-0",children:[(0,n.jsx)("span",{className:"flex-1 text-[11px] text-text-muted",children:d("editor.unsaved")}),(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),m.save()},disabled:m.saving,className:"px-2.5 py-1 flex items-center gap-1.5 text-[11px] font-medium text-white bg-brand-500 hover:bg-brand-600 rounded-brand disabled:opacity-50 transition-colors",children:[(0,n.jsx)(t3.eM,{size:12})," ",d(m.saving?"editor.saving":"editor.save")]})]}),(0,n.jsx)("div",{className:"flex-1 min-h-0",children:p&&x?(0,n.jsx)(i5,{kind:x,filePath:e,fileBus:s,content:m.content,reloadKey:f}):m.loading?(0,n.jsx)("div",{className:"h-full flex items-center justify-center text-text-muted text-sm",children:d("common.loading")}):(0,n.jsx)(iU,{filePath:e,content:m.content,onTextChanged:m.onTextChanged,onRegisterView:m.register,onSave:m.save,onCursorChange:l})})]})}function uP({workspace:e,fileBus:t,openedFiles:s,activeFile:a,onActivateFile:l,onCloseFile:i,onCloseOthers:o,onCloseAll:c,onOpenFile:d,onEditorStateChange:u,previewRequest:m}){let[x,p]=(0,r.useState)(()=>new Set),[h,f]=(0,r.useState)(null),b=(0,r.useRef)(new Map);(0,r.useEffect)(()=>{if(!x.size)return;let e=e=>(e.preventDefault(),e.returnValue="","");return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[x.size]);let g=(0,r.useCallback)((e,t)=>{p(s=>{if(s.has(e)===t)return s;let n=new Set(s);return t?n.add(e):n.delete(e),n})},[]),v=(0,r.useCallback)((e,t)=>{t?b.current.set(e,t):b.current.delete(e)},[]),y=(0,r.useCallback)(e=>{if(!x.has(e))return i?.(e);f(e)},[x,i]),w=(0,r.useCallback)(async e=>{for(let t of s.filter(t=>t!==e&&x.has(t)))if(!1===await b.current.get(t)?.())return;e?o?.(e):c?.()},[s,x,o,c]),k=(0,r.useCallback)(async()=>{!1!==await b.current.get(h)?.()&&(f(null),i?.(h))},[h,i]),j=(0,r.useCallback)(()=>{f(null),i?.(h)},[h,i]);return a?(0,n.jsxs)("div",{className:"flex-1 flex flex-col bg-bg min-h-0",children:[(0,n.jsx)(u_,{openedFiles:s,activeFile:a,dirtyFiles:x,onActivate:l,onClose:y,onCloseOthers:e=>w(e),onCloseAll:()=>w(null)}),(0,n.jsx)(u$,{workspace:e,filePath:a}),(0,n.jsx)("div",{className:"flex-1 min-h-0 overflow-hidden",children:s.map(s=>(0,n.jsx)("div",{className:s===a?"h-full":"hidden",children:(0,n.jsx)(uM,{filePath:s,workspace:e,fileBus:t,isActive:s===a,onCursorChange:u,onDirtyChange:g,onRegisterSaver:v,previewSeq:m?.path===s?m.seq:0})},s))}),(0,n.jsx)(i$,{isOpen:!!h,fileName:h?.split("/").pop(),onSave:k,onDiscard:j,onCancel:()=>f(null)})]}):(0,n.jsx)("div",{className:"flex-1 flex flex-col bg-bg min-h-0",children:(0,n.jsxs)("div",{className:"flex-1 flex flex-col items-center justify-center text-text-muted gap-3 p-6",children:[(0,n.jsx)(t3.Bm,{size:64,className:"opacity-40"}),(0,n.jsx)("div",{className:"text-sm",children:"Open a file from the Explorer to get started"}),(0,n.jsxs)("div",{className:"text-xs flex items-center gap-2",children:[(0,n.jsx)("kbd",{className:"px-2 py-0.5 bg-surface-2 border border-border rounded text-text-subtle font-mono",children:"Cmd/Ctrl+P"}),(0,n.jsx)("span",{children:"Quick Open"})]})]})})}function uA({gitBranch:e,line:t,column:s,language:r,encoding:a,activeFile:l,sidebarVisible:i,onToggleSidebar:o,bottomVisible:c,onTogglePanel:d}){return(0,n.jsx)(a9,{left:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),o?.()},className:a7,title:i?"Hide Sidebar":"Show Sidebar",children:(0,n.jsx)(t3.Ay,{name:i?"PanelLeftClose":"PanelLeftOpen",size:12})}),l&&(0,n.jsxs)("span",{className:le,children:[(0,n.jsx)(t3.Zr,{size:12,className:"opacity-60"}),e||"no branch"]})]}),right:(0,n.jsxs)(n.Fragment,{children:[d&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),d()},className:a7,title:c?"Hide Terminal":"Show Terminal",children:(0,n.jsx)(t3.Ay,{name:"Terminal",size:12})}),l&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:le,children:`Ln ${t||1}, Col ${s||1}`}),(0,n.jsx)("span",{className:le,children:r||"plaintext"}),(0,n.jsx)("span",{className:le,children:a||"UTF-8"})]})]})})}let uz=s1()?"⌘":"Ctrl+",uI=[{id:"openExplorer",label:"View: Show Explorer",icon:"FolderOpen",shortcut:""},{id:"openSearch",label:"View: Show Search",icon:"Search",shortcut:""},{id:"openScm",label:"View: Show Source Control",icon:"GitBranch",shortcut:""},{id:"openSettings",label:"View: Show Settings",icon:"Settings",shortcut:""},{id:"toggleSidebar",label:"View: Toggle Sidebar Visibility",icon:"PanelLeft",shortcut:`${uz}B`},{id:"togglePanel",label:"View: Toggle Terminal Panel",icon:"Terminal",shortcut:`${uz}J`},{id:"closeAll",label:"View: Close All Editors",icon:"X",shortcut:""},{id:"switchWorkspace",label:"Workspaces: Switch Workspace",icon:"Folder",shortcut:""}];function uL({mode:e="files",onSetMode:t,workspace:s,fileBus:a,onClose:l,onOpenFile:i,onAction:o}){let[c,d]=(0,r.useState)(""),[u,m]=(0,r.useState)(0),[x,p]=(0,r.useState)([]),[h,f]=(0,r.useState)(!1),b=(0,r.useRef)(null),g=(0,r.useRef)(null),v=(0,r.useMemo)(()=>{let e=c.trim().toLowerCase();return e?uI.filter(t=>t.label.toLowerCase().includes(e)):uI},[c]),y="commands"===e?v:x;(0,r.useEffect)(()=>{m(0)},[e,c,x]),(0,r.useEffect)(()=>{if("files"!==e)return;let t=c.trim();if(!t||!a||!s){p([]),f(!1);return}return f(!0),g.current&&clearTimeout(g.current),g.current=setTimeout(async()=>{let e=await a.searchFiles(s,t);p(e?.success&&Array.isArray(e.files)?e.files:[]),f(!1)},200),()=>{g.current&&clearTimeout(g.current)}},[c,e,a,s]);let w=(0,r.useCallback)(s=>{let n=s.target.value;if("files"===e&&n.startsWith(">")){t?.("commands"),d(n.slice(1));return}d(n)},[e,t]),k=(0,r.useCallback)(t=>{let s=y[t];s&&((0,t7.e)(8),"commands"===e?o?.(s.id):i?.(s.path),l?.())},[y,e,o,i,l]),j=(0,r.useCallback)(e=>{if("Escape"===e.key){e.preventDefault(),l?.();return}if("ArrowDown"===e.key){e.preventDefault(),m(e=>Math.min(e+1,Math.max(y.length-1,0)));return}if("ArrowUp"===e.key){e.preventDefault(),m(e=>Math.max(e-1,0));return}"Enter"===e.key&&(e.preventDefault(),k(u))},[y.length,u,l,k]),N="files"===e?"Type `>` for commands":"Type `?` for help",S="files"===e?"Search files by name…":"Type a command…";return(0,n.jsx)("div",{className:"fixed inset-0 z-50 bg-black/40",onMouseDown:l,children:(0,n.jsxs)("div",{className:"absolute top-20 left-1/2 -translate-x-1/2 w-[640px] max-w-[90vw] card-elev bg-surface border border-border rounded-brand overflow-hidden",onMouseDown:e=>e.stopPropagation(),children:[(0,n.jsxs)("div",{className:"flex items-center gap-2 px-4 py-3 border-b border-border",children:[(0,n.jsx)(t3.Ay,{name:"commands"===e?"Command":"Search",size:16,className:"text-text-muted"}),(0,n.jsx)("input",{ref:b,autoFocus:!0,type:"text",value:c,onChange:w,onKeyDown:j,placeholder:S,className:"flex-1 bg-transparent outline-none border-0 text-text placeholder:text-text-muted text-sm"}),(0,n.jsx)("span",{className:"text-xs text-text-muted hidden sm:inline",children:N})]}),(0,n.jsx)("div",{className:"max-h-[400px] overflow-auto",children:0===y.length?"files"!==e||c.trim()?h?(0,n.jsxs)("div",{className:"px-4 py-6 text-center text-text-muted text-sm flex items-center justify-center gap-2",children:[(0,n.jsx)(t3.Ay,{name:"Loader2",size:14,className:"animate-spin"}),"Searching…"]}):(0,n.jsx)("div",{className:"px-4 py-10 text-center text-text-muted text-sm",children:"No results"}):(0,n.jsx)("div",{className:"px-4 py-10 text-center text-text-muted text-sm",children:"Start typing to search files in workspace"}):(0,n.jsx)("ul",{className:"py-1",children:y.map((t,s)=>{let r=s===u;if("commands"===e)return(0,n.jsxs)("li",{onMouseEnter:()=>m(s),onClick:()=>k(s),className:`flex items-center gap-3 px-4 py-2 cursor-pointer ${r?"bg-brand-500/20 text-text":"text-text-muted hover:bg-surface-2"}`,children:[(0,n.jsx)(t3.Ay,{name:t.icon,size:16}),(0,n.jsx)("span",{className:"flex-1 text-sm",children:t.label}),t.shortcut?(0,n.jsx)("kbd",{className:"text-xs text-text-muted px-1.5 py-0.5 bg-surface-2 rounded",children:t.shortcut}):null]},t.id);let a=t.name||(t.path?t.path.split(/[\\/]/).pop():""),l=t.relativePath||t.path||"";return(0,n.jsxs)("li",{onMouseEnter:()=>m(s),onClick:()=>k(s),className:`flex items-center gap-3 px-4 py-2 cursor-pointer ${r?"bg-brand-500/20 text-text":"text-text-muted hover:bg-surface-2"}`,children:[(0,n.jsx)(t3.Ay,{name:"File",size:16}),(0,n.jsxs)("div",{className:"flex-1 min-w-0 flex items-center gap-2",children:[(0,n.jsx)("span",{className:"text-sm font-semibold text-text truncate",title:a,children:a}),(0,n.jsx)("span",{className:"text-xs text-text-muted truncate",title:l,children:l})]})]},t.path||s)})})})]})})}function uD({height:e,onResize:t,onClose:s,bus:a,connected:l,sessions:i=[],onCreateSession:o,onDeleteSession:c,onRenameSession:d}){let[u,m]=(0,r.useState)(i[0]?.id||null),x=(0,r.useRef)(null),p=(0,r.useRef)(!1);(0,r.useEffect)(()=>{0!==i.length&&(u&&i.find(e=>e.id===u)||m(i[0].id))},[i,u]),(0,r.useEffect)(()=>{0===i.length&&o&&!p.current&&(p.current=!0,o(e=>m(e))),i.length>0&&(p.current=!1)},[i.length,o]);let h=(0,r.useCallback)(()=>{(0,t7.e)(),o?.(e=>m(e))},[o]),f=(0,r.useCallback)((e,t)=>{e.stopPropagation(),(0,t7.e)(),c?.(t)},[c]),b=(0,r.useCallback)(e=>{e.preventDefault();let s=x.current?.parentElement;if(!s)return;let n=s.getBoundingClientRect(),r=e=>{0===e.buttons?a():t(Math.max(10,Math.min(70,(n.bottom-e.clientY)/n.height*100)))},a=()=>{window.removeEventListener("mousemove",r),window.removeEventListener("mouseup",a),window.removeEventListener("blur",a),document.body.style.userSelect="",document.body.style.cursor=""};document.body.style.userSelect="none",document.body.style.cursor="row-resize",window.addEventListener("mousemove",r),window.addEventListener("mouseup",a),window.addEventListener("blur",a)},[t]);return(0,n.jsxs)("div",{ref:x,className:"bg-bg border-t border-border flex flex-col flex-shrink-0",style:{height:`${e}%`},children:[(0,n.jsx)("div",{onMouseDown:b,className:"h-1 cursor-row-resize bg-border hover:bg-surface-3 transition-colors -mt-1 relative z-10"}),(0,n.jsxs)("div",{className:"bg-surface border-b border-border flex items-center px-2 flex-shrink-0 overflow-x-auto",children:[(0,n.jsxs)("div",{className:"flex items-center text-text-muted text-xs uppercase tracking-wider px-2 py-1.5 mr-1",children:[(0,n.jsx)(t3.BK,{size:12,className:"mr-1"}),"Terminal"]}),i.map(e=>{let t=e.id===u;return(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),m(e.id)},className:`group flex items-center gap-1.5 px-2 py-1.5 text-xs transition-colors max-w-[160px] ${t?"text-text bg-bg border-t-2 border-text-muted":"text-text-muted hover:text-text"}`,title:e.name,children:[(0,n.jsx)("span",{className:"truncate",children:e.name}),(0,n.jsx)(t3.X,{size:12,onClick:t=>f(t,e.id),className:"opacity-0 group-hover:opacity-100 hover:text-danger flex-shrink-0"})]},e.id)}),(0,n.jsx)("button",{onClick:h,className:"p-1 text-text-muted hover:text-text rounded hover:bg-surface-2 ml-1 flex-shrink-0",title:"New Terminal",children:(0,n.jsx)(t3.FW,{size:14})}),(0,n.jsx)("div",{className:"flex-1"}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),s()},className:"p-1 text-text-muted hover:text-text rounded hover:bg-surface-2 ml-1 flex-shrink-0",title:"Close Panel",children:(0,n.jsx)(t3.X,{size:14})})]}),(0,n.jsxs)("div",{className:"flex-1 min-h-0 relative",children:[i.map((e,t)=>(0,n.jsx)("div",{className:"absolute inset-0",style:{display:e.id===u?"block":"none"},children:(0,n.jsx)(a$,{bus:a,connected:l,sessionId:e.id,isVisible:e.id===u,isFocused:e.id===u,showFocusBorder:!1,bgIndex:t})},e.id)),0===i.length&&(0,n.jsx)("div",{className:"h-full flex items-center justify-center text-text-muted text-sm",children:"Creating terminal session..."})]})]})}function uF({workspace:e,fileBus:t,onBack:s,onSwitchWorkspace:a,initialOpenedFiles:l,onOpenedFilesChange:i,bus:o,connected:c,sessions:d,onCreateTerminalSession:u,onDeleteTerminalSession:m,onRenameTerminalSession:x,initialActiveFile:p,viewType:h,openFileRef:f}){let[b,g]=nj("fileExplorer.activityPanel",tv);(0,r.useEffect)(()=>{"git"===h?g("scm"):"files"===h&&g(tv)},[h,g]);let[v,y]=nj("fileExplorer.sidebarVisible",!0),[w,k]=nj("fileExplorer.sidebarWidth",18),[j,N]=nj("fileExplorer.bottomPanelVisible",!1),[S,C]=nj("fileExplorer.bottomPanelHeight",30),T=(0,r.useRef)(null),[R,E]=(0,r.useState)(!1),_=(0,r.useCallback)(e=>{e.preventDefault();let t=T.current;if(!t)return;let s=t.getBoundingClientRect();E(!0);let n=e=>{0===e.buttons?r():k(Math.max(12,Math.min(40,(e.clientX-s.left)/s.width*100)))},r=()=>{window.removeEventListener("mousemove",n),window.removeEventListener("mouseup",r),window.removeEventListener("blur",r),document.body.style.userSelect="",document.body.style.cursor="",E(!1)};document.body.style.userSelect="none",document.body.style.cursor="col-resize",window.addEventListener("mousemove",n),window.addEventListener("mouseup",r),window.addEventListener("blur",r)},[k]),[$,M]=(0,r.useState)(l||[]),[P,A]=(0,r.useState)(p||l?.[0]||null),[z,I]=(0,r.useState)({line:1,column:1,language:"",encoding:"UTF-8"}),[L,D]=(0,r.useState)(""),[F,O]=(0,r.useState)({path:null,seq:0}),[B,W]=(0,r.useState)(!1),[K,H]=(0,r.useState)("commands");(0,r.useEffect)(()=>{i?.($,P)},[$,P,i]);let U=(0,r.useCallback)((e,t={})=>{M(t=>[e,...t.filter(t=>t!==e)].slice(0,5)),A(e),t.line&&I(e=>({...e,jumpLine:t.line,jumpColumn:t.column})),t.preview&&O(t=>({path:e,seq:t.seq+1}))},[]);(0,r.useEffect)(()=>{f&&(f.current=U)},[f,U]);let q=(0,r.useCallback)(e=>{M(t=>{let s=t.filter(t=>t!==e);return P===e&&A(s[0]||null),s})},[P]),V=(0,r.useCallback)(e=>{M([e]),A(e)},[]),X=(0,r.useCallback)(()=>{M([]),A(null)},[]);return(0,r.useEffect)(()=>{e&&t&&t.gitBranch?.(e).then(e=>{e?.success&&D(e.branch||"")}).catch(()=>{})},[e,t]),!function({onToggleSidebar:e,onSave:t,onCloseTab:s,onCommandPalette:n,onQuickOpen:a,onTogglePanel:l}={}){let i=(0,r.useRef)({});(0,r.useEffect)(()=>{i.current={onToggleSidebar:e,onSave:t,onCloseTab:s,onCommandPalette:n,onQuickOpen:a,onTogglePanel:l}}),(0,r.useEffect)(()=>{let e=e=>{let t=e.metaKey||e.ctrlKey,s=e.key.toLowerCase(),n=e.shiftKey,r=i.current;if(t&&n&&"p"===s||t&&!n&&"k"===s){e.preventDefault(),r.onCommandPalette?.();return}if(t&&!n&&"p"===s){e.preventDefault(),r.onQuickOpen?.();return}if(t&&!n&&"s"===s){e.preventDefault(),r.onSave?.();return}if(t&&!n&&"w"===s){e.preventDefault(),r.onCloseTab?.();return}if(t&&!n&&"b"===s){e.preventDefault(),r.onToggleSidebar?.();return}t&&!n&&"j"===s&&r.onTogglePanel&&(e.preventDefault(),r.onTogglePanel())};return document.addEventListener("keydown",e,!0),()=>document.removeEventListener("keydown",e,!0)},[])}({onToggleSidebar:()=>y(e=>!e),onTogglePanel:()=>N(e=>!e),onSave:()=>{window.dispatchEvent(new CustomEvent("fileExplorer:save"))},onCloseTab:()=>P&&q(P),onCommandPalette:()=>{H("commands"),W(!0)},onQuickOpen:()=>{H("files"),W(!0)}}),(0,n.jsxs)("div",{className:"h-full bg-bg flex flex-col",children:[(0,n.jsxs)("div",{className:"flex-1 min-h-0 flex",children:[(0,n.jsx)(uw,{activePanel:b,onSelectPanel:e=>{b===e&&v?y(!1):(g(e),y(!0))},onBack:s}),(0,n.jsxs)("div",{ref:T,className:"flex-1 min-w-0 min-h-0 flex relative",children:[(0,n.jsx)("div",{className:`bg-surface flex-shrink-0 overflow-hidden min-h-0 flex flex-col ${R?"":"transition-[width] duration-200 ease-out"}`,style:{width:v?`${w}%`:0},"aria-hidden":!v,children:(0,n.jsx)(uE,{activePanel:b,workspace:e,fileBus:t,onOpenFile:U,onSwitchWorkspace:a,activeFile:P})}),(0,n.jsx)("div",{onMouseDown:_,className:`cursor-col-resize bg-border hover:bg-brand-500/50 flex-shrink-0 ${R?"":"transition-[width,background-color] duration-200 ease-out"} ${v?"w-1":"w-0"}`}),(0,n.jsxs)("div",{className:"flex-1 min-w-0 min-h-0 flex flex-col",children:[(0,n.jsx)(uP,{workspace:e,fileBus:t,openedFiles:$,activeFile:P,onActivateFile:A,onCloseFile:q,onCloseOthers:V,onCloseAll:X,onOpenFile:U,onEditorStateChange:I,previewRequest:F}),j&&o&&(0,n.jsx)(uD,{height:S,onResize:C,onClose:()=>N(!1),bus:o,connected:c,sessions:d,onCreateSession:u,onDeleteSession:m,onRenameSession:x})]})]})]}),(0,n.jsx)(uA,{gitBranch:L,line:z.line,column:z.column,language:z.language,encoding:z.encoding,activeFile:P,sidebarVisible:v,onToggleSidebar:()=>y(e=>!e),bottomVisible:j,onTogglePanel:()=>N(e=>!e)}),B&&(0,n.jsx)(uL,{mode:K,workspace:e,fileBus:t,onClose:()=>W(!1),onOpenFile:U,onSetMode:H,onAction:e=>{W(!1),"toggleSidebar"===e?y(e=>!e):"togglePanel"===e?N(e=>!e):"closeAll"===e?X():"switchWorkspace"===e?a?.():"openExplorer"===e?(g(tv),y(!0)):"openSearch"===e?(g(ty),y(!0)):"openScm"===e?(g("scm"),y(!0)):"openSettings"===e&&(g(tw),y(!0))}})]})}function uO({isOpen:e,onClose:t}){let{t:s}=(0,se.s)(),a=(0,r.useRef)(null);return((0,r.useEffect)(()=>{if(!e)return;document.activeElement?.blur?.();let s=requestAnimationFrame(()=>{a.current?.focus()}),n=e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),t())};return window.addEventListener("keydown",n,!0),()=>{cancelAnimationFrame(s),window.removeEventListener("keydown",n,!0)}},[e,t]),e)?(0,n.jsxs)("div",{className:"fixed inset-0 z-[60] flex items-center justify-center p-4",children:[(0,n.jsx)("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-[2px] animate-in fade-in duration-200",onClick:t}),(0,n.jsxs)("div",{role:"dialog","aria-modal":"true",tabIndex:-1,className:"relative card-elev max-w-md w-full max-h-[90dvh] flex flex-col animate-in zoom-in-95 duration-200 outline-none",onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:[(0,n.jsxs)("div",{className:"px-5 py-4 flex items-center justify-between flex-shrink-0",children:[(0,n.jsx)("h3",{className:"text-lg font-semibold text-text",children:s("shortcuts.title")}),(0,n.jsx)("button",{ref:a,onClick:t,className:"p-2 text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-all duration-150 ease-out focus:outline-none focus:ring-2 focus:ring-brand-500/40","aria-label":s("common.close"),children:(0,n.jsx)(t3.X,{size:20})})]}),(0,n.jsx)("div",{className:"flex-1 overflow-y-auto modal-scrollable px-5 pb-5",children:(0,n.jsx)("ul",{className:"flex flex-col divide-y divide-border-subtle/40",children:sZ.map(e=>(0,n.jsxs)("li",{className:"flex items-center justify-between gap-4 py-2 first:pt-1",children:[(0,n.jsx)("span",{className:"text-sm text-text min-w-0 truncate",children:s(`shortcuts.${e.id}`)}),(0,n.jsx)("span",{className:"inline-flex items-center gap-1 flex-shrink-0",children:s4(e).map(e=>(0,n.jsx)("kbd",{className:s5,children:e},e))})]},e.id))})})]})]}):null}function uB({retryStatus:e,approvalStatus:t,connected:s,onLogout:r,onRetryNow:a,suppress:l=!1}){let{t:i}=(0,se.s)(),c=t===o.J2.pending||t===o.J2.rejected;if(l&&!c)return null;let d=()=>{r?r():(sessionStorage.clear(),window.location.replace("/login"))};return t===o.J2.pending?(0,n.jsx)("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm",children:(0,n.jsx)("div",{className:"card-elev p-6 max-w-sm w-full mx-4",children:(0,n.jsxs)("div",{className:"text-center",children:[(0,n.jsx)(du.A,{size:"lg"}),(0,n.jsx)("h3",{className:"text-text text-lg font-semibold mt-4",children:i("connection.waitingApproval")}),(0,n.jsx)("p",{className:"text-text-muted mt-2",children:i("connection.approvalDescription")}),(0,n.jsx)("p",{className:"text-text-muted text-sm mt-1",children:i("connection.approvalHint")}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),d()},className:"mt-4 w-full py-2 bg-surface-2 hover:bg-surface-3 text-text font-medium rounded-brand transition-all duration-150 ease-out active:scale-[0.98]",children:i("connection.cancel")})]})})}):t===o.J2.rejected?(0,n.jsx)("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm",children:(0,n.jsx)("div",{className:"card-elev p-6 max-w-sm w-full mx-4",children:(0,n.jsxs)("div",{className:"text-center",children:[(0,n.jsx)("div",{className:"w-16 h-16 mx-auto bg-red-500/20 rounded-full flex items-center justify-center",children:(0,n.jsx)("svg",{className:"w-8 h-8 text-red-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,n.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636"})})}),(0,n.jsx)("h3",{className:"text-text text-lg font-semibold mt-4",children:i("connection.rejectedTitle")}),(0,n.jsx)("p",{className:"text-text-muted mt-2",children:i("connection.rejectedDescription")}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),d()},className:"mt-6 w-full py-3 bg-brand-500 hover:bg-brand-600 text-white font-medium rounded-brand transition-all duration-150 ease-out active:scale-[0.98]",children:i("connection.backToLogin")})]})})}):!s&&(e?.isRetrying||e?.failed)?(0,n.jsx)("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm",children:(0,n.jsx)("div",{className:"card-elev p-6 max-w-sm w-full mx-4",children:e.isRetrying?(0,n.jsxs)("div",{className:"text-center",children:[(0,n.jsx)(du.A,{size:"lg"}),(0,n.jsx)("h3",{className:"text-text text-lg font-semibold mt-4",children:i("connection.retrying")}),(0,n.jsx)("p",{className:"text-text-muted mt-2",children:i("connection.attemptOf",{n:e.attempt,total:e.maxAttempts})}),(0,n.jsx)("div",{className:"mt-4 w-full bg-surface-2 rounded-full h-2",children:(0,n.jsx)("div",{className:"bg-brand-500 h-2 rounded-full transition-all duration-300",style:{width:`${e.attempt/e.maxAttempts*100}%`}})}),a&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),a()},className:"mt-4 w-full py-2 bg-brand-500 hover:bg-brand-600 text-white font-medium rounded-brand transition-all duration-150 ease-out active:scale-[0.98]",children:i("connection.retry")}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),d()},className:"mt-2 w-full py-2 bg-surface-2 hover:bg-surface-3 text-text font-medium rounded-brand transition-all duration-150 ease-out active:scale-[0.98]",children:i("connection.exit")})]}):(0,n.jsxs)("div",{className:"text-center",children:[(0,n.jsx)("div",{className:"w-16 h-16 mx-auto bg-red-500/20 rounded-full flex items-center justify-center",children:(0,n.jsx)("svg",{className:"w-8 h-8 text-red-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,n.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}),(0,n.jsx)("h3",{className:"text-text text-lg font-semibold mt-4",children:i("connection.failed")}),(0,n.jsx)("p",{className:"text-text-muted mt-2",children:i("connection.failedDescription",{n:e.maxAttempts})}),a&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),a()},className:"mt-6 w-full py-3 bg-brand-500 hover:bg-brand-600 text-white font-medium rounded-brand transition-all duration-150 ease-out active:scale-[0.98]",children:i("connection.retry")}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),d()},className:`w-full py-3 bg-surface-2 hover:bg-surface-3 text-text font-medium rounded-brand transition-all duration-150 ease-out active:scale-[0.98] ${a?"mt-2":"mt-6"}`,children:i("connection.backToLogin")})]})})}):null}let{installingAt:uW,restartingAt:uK,timeoutSec:uH}={installingAt:4,restartingAt:15,timeoutSec:90},uU={starting:"menu.updateStarting",installing:"menu.updateInstalling",restarting:"menu.updateRestarting",done:"menu.updateDone",timeout:"menu.updateTimeout"},uq={starting:"menu.restartStarting",restarting:"menu.restartRestarting",done:"menu.restartDone",timeout:"menu.restartTimeout"};function uV({open:e,connected:t,mode:s="update"}){let a,{t:l}=(0,se.s)(),[i,o]=(0,r.useState)(0),[c,d]=(0,r.useState)(!1),u=(0,r.useRef)(!1);if((0,r.useEffect)(()=>{if(!e){o(0),d(!1),u.current=!1;return}let t=Date.now(),s=setInterval(()=>{let e=Math.floor((Date.now()-t)/1e3);o(e),e>=uH&&d(!0)},1e3);return()=>clearInterval(s)},[e]),(0,r.useEffect)(()=>{if(e){if(!t){u.current=!0;return}u.current&&setTimeout(()=>window.location.reload(),600)}},[e,t]),!e)return null;let m=u.current&&t;a=c&&!m?"timeout":m?"done":t?"restart"===s?i<uK?"starting":"restarting":i<uW?"starting":i<uK?"installing":"restarting":"restarting";let x=l(("restart"===s?uq:uU)[a]),p=l("restart"===s?"menu.restartTimeoutHint":"menu.updateTimeoutHint");return(0,n.jsx)("div",{className:"fixed inset-0 z-60 flex items-center justify-center bg-black/50 backdrop-blur-sm",children:(0,n.jsx)("div",{className:"card-elev p-6 max-w-sm w-full mx-4 text-center",children:"timeout"===a?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"w-14 h-14 mx-auto bg-yellow-500/20 rounded-full flex items-center justify-center text-2xl",children:"⚠️"}),(0,n.jsx)("h3",{className:"text-text text-lg font-semibold mt-4",children:x}),(0,n.jsx)("p",{className:"text-text-muted text-sm mt-2",children:p}),(0,n.jsx)("button",{onClick:()=>window.location.reload(),className:"mt-4 w-full py-2 bg-brand-500 hover:bg-brand-600 text-white font-medium rounded-brand transition-colors",type:"button",children:l("menu.reloadWeb")})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(du.A,{size:"lg"}),(0,n.jsxs)("h3",{className:"text-text text-base font-semibold mt-4",children:[x," ",(0,n.jsxs)("span",{className:"text-text-muted font-normal",children:["\xb7 ",i,"s"]})]}),(0,n.jsx)("div",{className:"mt-4 h-1.5 w-full bg-white/10 rounded-full overflow-hidden",children:(0,n.jsx)("div",{className:"h-full bg-brand-500 rounded-full transition-all duration-1000 ease-linear",style:{width:`${"done"===a?100:Math.min(i/uH*100,95)}%`}})})]})})})}let uX={remote:t3.VA,mobile:t3.wO,sites:t3.qz,notifications:t3.Ir,folder:t3.Bm,note:t3.y8},uG=e=>{let t={hiddenHeaderButtons:e.hiddenHeaderButtons,toggleHeaderButton:e.toggleHeaderButton};for(let s of eo)"pane"===s.group&&(t[s.storeKey]=e[s.storeKey],t[s.setterKey]=e[s.setterKey]);return t};function uJ(){let e=tS((0,tW.k)(uG));return{buttons:eo,isOn:t=>"header"===t.group?!e.hiddenHeaderButtons.includes(t.id):!!e[t.storeKey],toggle:t=>"header"===t.group?e.toggleHeaderButton(t.id):e[t.setterKey](!e[t.storeKey])}}function uY(e,t){let s=!!window.ReactNativeWebView,n=s||"u">typeof navigator&&"serviceWorker"in navigator&&"PushManager"in window,[a,l]=(0,r.useState)(()=>!!window.ReactNativeWebView&&"1"!==localStorage.getItem(sx)),[i,o]=(0,r.useState)(!1);(0,r.useEffect)(()=>{s||"serviceWorker"in navigator&&"PushManager"in window&&navigator.serviceWorker.ready.then(e=>e.pushManager?.getSubscription()).then(e=>l(!!e)).catch(()=>{})},[s]);let c=(0,r.useCallback)(async()=>{if(!i){if((0,t7.e)(),o(!0),a)await t?.(),l(!1);else{await e?.();let t=s;if(!s&&"serviceWorker"in navigator&&"PushManager"in window)try{let e=await navigator.serviceWorker.ready;t=!!await e.pushManager?.getSubscription()}catch{t=!1}l(t)}o(!1)}},[a,i,e,t,s]);return{supported:n,enabled:a,loading:i,toggle:c,isExpoWebView:s}}function uZ(e,t){let s=tS(e=>e.artifactEnabled),n=tS(e=>e.setArtifactEnabled),a=!!tS(e=>e.agentCaps?.artifact),[l,i]=(0,r.useState)(!1),o=(0,r.useRef)(!0);(0,r.useEffect)(()=>()=>{o.current=!1},[]),!t&&l&&i(!1);let c=(0,r.useCallback)(r=>{let a=e?.current;if(!a||!t||l)return;(0,t7.e)();let c="boolean"==typeof r?r:!s;i(!0),n(c),a.emit("setArtifactEnabled",{enabled:c},e=>{o.current&&(i(!1),e?.success||n(!c))})},[e,t,l,s,n]);return{supported:a,enabled:s,loading:l,toggle:c}}s(28913);var uQ=s(52345);let u0=uQ.dI.filter(e=>np[e.code]);function u1({isOpen:e,value:t,onSelect:s,onClose:a}){let{t:l}=(0,se.s)();return((0,r.useEffect)(()=>{if(!e)return;let t=e=>{"Escape"===e.key&&a()};return window.addEventListener("keydown",t),()=>window.removeEventListener("keydown",t)},[e,a]),e)?(0,n.jsxs)("div",{className:"fixed inset-0 z-[60] flex items-center justify-center p-4",children:[(0,n.jsx)("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-[2px] animate-in fade-in duration-200",onClick:a}),(0,n.jsxs)("div",{className:"relative card-elev max-w-lg w-full max-h-[90dvh] flex flex-col animate-in zoom-in-95 duration-200",children:[(0,n.jsxs)("div",{className:"px-5 py-4 flex items-center justify-between flex-shrink-0",children:[(0,n.jsx)("h3",{className:"text-lg font-semibold text-text",children:l("voice.language")}),(0,n.jsx)("button",{onClick:a,className:"p-2 text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-all duration-150 ease-out","aria-label":l("common.close"),children:(0,n.jsx)(t3.X,{size:20})})]}),(0,n.jsx)("div",{className:"flex-1 overflow-y-auto modal-scrollable p-3",children:(0,n.jsx)("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:u0.map(e=>{let r=e.code===t;return(0,n.jsxs)("button",{onClick:()=>{var t;return t=e.code,void((0,t7.e)(),s(t),a())},className:`px-2 py-2 rounded-brand flex items-center gap-2 transition-all duration-150 ease-out active:scale-[0.97] min-w-0 ${r?"bg-brand-500 text-white":"text-text hover:bg-surface-2"}`,children:[(0,n.jsx)("img",{src:`https://flagcdn.com/w40/${e.country}.png`,alt:e.label,className:"w-[17px] h-[12px] object-cover rounded-[2px] flex-shrink-0",loading:"lazy"}),(0,n.jsx)("span",{className:"flex-1 text-sm font-medium truncate text-left",children:e.label}),r&&(0,n.jsx)(t3.aJ,{size:14,className:"flex-shrink-0"})]},e.code)})})})]})]}):null}let u2="w-full px-2.5 py-1.5 rounded bg-bg border border-border-subtle text-xs font-mono text-text placeholder-text-muted focus:outline-none focus:border-brand-500",u5="px-3 py-1.5 rounded-brand text-xs font-medium transition-colors",u3=[{value:"browser",label:"Browser"},{value:"ai",label:"AI Speech To Text"}];function u4({active:e,onClick:t,children:s}){return(0,n.jsx)("button",{type:"button",onClick:t,className:`px-2.5 py-1 rounded-brand text-[11px] border transition-colors ${e?"border-brand-500 bg-brand-500/10 text-brand-400":"border-border-subtle bg-surface-2/30 text-text-muted hover:text-text hover:bg-surface-2"}`,children:s})}function u6({state:e}){if(!e)return null;let t=e.busy?"text-text-muted animate-pulse":e.ok?"text-green-500":"text-red-400";return(0,n.jsx)("p",{className:`text-[11px] leading-relaxed break-words ${t}`,children:e.msg})}function u8({onClose:e}){let t=tD(),{mode:s,setMode:a,preset:l,setPreset:i,setField:o}=t,{locale:c}=(0,se.s)(),[d,u]=nb(c),[m,x]=(0,r.useState)(!1),[p,h]=(0,r.useState)(null),[f,b]=(0,r.useState)(null),g=p?.busy||f?.busy,v=uQ.dI.find(e=>e.code===d),y="gemini"===l?t.geminiKeys.some(e=>e.trim()):"openrouter"===l?!!t.openrouterKey.trim():!!t.customKey.trim(),w="custom"===l?t.customModel:(t[`${l}Model`]||"").trim()||tR[l].model,k=async()=>{(0,t7.e)(),h({busy:!0,msg:"Testing…"});try{let e=tA(tD.getState());await tE(e,{model:e.model,messages:[{role:"user",content:"hi"}],max_tokens:1}),h({ok:!0,msg:"Key & model OK"})}catch(e){h({ok:!1,msg:t_(e)})}},j=async()=>{if((0,t7.e)(),!y)return void b({ok:!1,msg:"Enter an API key first"});b({busy:!0,msg:"Recording…"});try{let e=await tz(tD.getState(),await t$());b({ok:!!e,msg:e||"(empty reply)"})}catch(e){b({ok:!1,msg:t_(e)})}};return(0,n.jsxs)("div",{className:"fixed inset-0 z-[60] flex items-center justify-center p-4",children:[(0,n.jsx)("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-[2px] animate-in fade-in duration-200",onClick:e}),(0,n.jsxs)("div",{className:"relative card-elev max-w-md w-full max-h-[90dvh] flex flex-col animate-in zoom-in-95 duration-200",children:[(0,n.jsxs)("div",{className:"px-5 py-4 flex items-center justify-between flex-shrink-0",children:[(0,n.jsx)("h3",{className:"text-lg font-semibold text-text",children:"Voice input"}),(0,n.jsx)("button",{onClick:e,className:"p-2 text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-all duration-150 ease-out","aria-label":"Close",children:(0,n.jsx)(t3.X,{size:20})})]}),(0,n.jsxs)("div",{className:"flex-1 overflow-y-auto modal-scrollable px-5 pb-5 flex flex-col gap-3",children:[(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),x(!0)},className:"w-full px-3 py-2 rounded-brand bg-surface-2/50 text-left flex items-center gap-2.5 text-sm text-text hover:bg-surface-2 transition-colors",children:[(0,n.jsx)("span",{className:"flex-1 min-w-0 truncate",children:"Language"}),v&&(0,n.jsxs)("span",{className:"flex items-center gap-1.5 flex-shrink-0 text-xs text-text-muted",children:[(0,n.jsx)("img",{src:`https://flagcdn.com/w40/${v.country}.png`,alt:"",className:"w-[17px] h-[12px] object-cover rounded-[2px]",loading:"lazy"}),(0,n.jsx)("span",{children:v.label})]})]}),(0,n.jsx)("div",{className:"flex items-center gap-1.5 flex-wrap",children:u3.map(e=>(0,n.jsx)(u4,{active:s===e.value,onClick:()=>{(0,t7.e)(),a(e.value)},children:e.label},e.value))}),"browser"===s?(0,n.jsx)("p",{className:"text-xs leading-relaxed text-text-muted",children:"Uses the browser's built-in speech recognition (Chrome, Safari, Edge). Not available in Firefox."}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"flex items-center gap-1.5 flex-wrap",children:Object.entries(tR).map(([e,t])=>(0,n.jsx)(u4,{active:l===e,onClick:()=>{(0,t7.e)(),i(e)},children:t.label},e))}),(0,n.jsxs)("p",{className:`text-[11px] leading-relaxed ${y?"text-text-muted":"text-amber-500"}`,children:["custom"===l?"Any OpenAI-compatible /chat/completions endpoint":`${tR[l].note}`,!y&&" \xb7 No key yet"]}),"custom"!==l&&(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:"text-xs font-semibold text-text mb-1",children:"Model"}),(0,n.jsx)("input",{type:"text",value:t[`${l}Model`]||"",onChange:e=>o(`${l}Model`,e.target.value),placeholder:w,className:u2,autoComplete:"off"})]}),"gemini"===l&&(0,n.jsxs)("div",{children:[(0,n.jsxs)("div",{className:"flex items-center justify-between mb-1",children:[(0,n.jsx)("span",{className:"text-xs font-semibold text-text",children:"API keys — one per line"}),(0,n.jsxs)("a",{href:"https://aistudio.google.com/app/apikey",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 text-[11px] text-brand-500 hover:text-brand-400 hover:underline transition-colors",children:["AI Studio ",(0,n.jsx)(t3.Gr,{size:10})]})]}),(0,n.jsx)("textarea",{rows:3,value:t.geminiKeys.join("\n"),onChange:e=>o("geminiKeys",e.target.value.split("\n")),placeholder:"AIza…\nAIza…",className:`${u2} resize-y`,autoComplete:"off"})]}),"openrouter"===l&&(0,n.jsxs)("div",{children:[(0,n.jsxs)("div",{className:"flex items-center justify-between mb-1",children:[(0,n.jsx)("span",{className:"text-xs font-semibold text-text",children:"API key"}),(0,n.jsxs)("a",{href:"https://openrouter.ai/settings/keys",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 text-[11px] text-brand-500 hover:text-brand-400 hover:underline transition-colors",children:["OpenRouter ",(0,n.jsx)(t3.Gr,{size:10})]})]}),(0,n.jsx)("input",{type:"password",value:t.openrouterKey,onChange:e=>o("openrouterKey",e.target.value),placeholder:"sk-or-…",className:u2,autoComplete:"off"})]}),"custom"===l&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:"text-xs font-semibold text-text mb-1",children:"Endpoint"}),(0,n.jsx)("input",{type:"text",value:t.customEndpoint,onChange:e=>o("customEndpoint",e.target.value),placeholder:tC,className:u2,autoComplete:"off"})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:"text-xs font-semibold text-text mb-1",children:"Model"}),(0,n.jsx)("input",{type:"text",value:t.customModel,onChange:e=>o("customModel",e.target.value),placeholder:"e.g. google/gemini-2.5-flash",className:u2,autoComplete:"off"})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:"text-xs font-semibold text-text mb-1",children:"API key"}),(0,n.jsx)("input",{type:"password",value:t.customKey,onChange:e=>o("customKey",e.target.value),placeholder:"sk-…",className:u2,autoComplete:"off"})]})]}),(0,n.jsxs)("div",{className:"flex gap-2",children:[(0,n.jsx)("button",{type:"button",onClick:k,disabled:g,className:`${u5} bg-brand-500 hover:bg-brand-600 text-white disabled:opacity-50`,children:"Test key"}),(0,n.jsx)("button",{type:"button",onClick:j,disabled:g,className:`${u5} bg-surface-2/70 hover:bg-surface-2 text-text disabled:opacity-50`,children:"Test voice"})]}),p&&(0,n.jsx)(u6,{state:p}),f&&(0,n.jsx)(u6,{state:f})]})]})]}),m&&(0,n.jsx)(u1,{isOpen:m,value:d,onSelect:u,onClose:()=>x(!1)})]})}function u9({dense:e=!1}){let t=tD(e=>e.enabled),s=tD(e=>e.mode),a=tD(e=>e.preset),l=tD(e=>e.setEnabled),[i,o]=(0,r.useState)(!1),c="ai"===s?tR[a]?.label||"AI":"Browser",d=()=>{(0,t7.e)(),o(!0)};return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:e?"w-full py-1 text-sm text-text flex items-center gap-2.5 cursor-pointer select-none":"w-full px-3 py-2 rounded-brand flex items-center gap-2.5 text-sm text-text hover:bg-surface-2 cursor-pointer select-none transition-colors",onClick:d,children:[(0,n.jsx)(t3.GO,{size:16,className:`${e?"text-text":"text-brand-500"} flex-shrink-0`}),(0,n.jsxs)("div",{className:"flex-1 min-w-0 flex flex-col",children:[(0,n.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,n.jsx)("span",{className:"truncate",children:"Voice input"}),(0,n.jsx)("span",{className:"text-xs text-text-muted shrink-0",children:c})]}),(0,n.jsx)("span",{className:"text-xs text-text-muted truncate",children:"Speak instead of typing — chat, terminal, remote"})]}),(0,n.jsx)("button",{type:"button",onClick:e=>{e.stopPropagation(),d()},title:"Voice configuration","aria-label":"Voice configuration",className:"shrink-0 px-2 h-7 flex items-center justify-center rounded-brand border border-border-subtle/60 hover:border-border hover:bg-surface-3/50 text-text-muted hover:text-text text-xs transition-colors",children:"Config"}),(0,n.jsx)("button",{type:"button",onClick:e=>{e.stopPropagation(),(0,t7.e)(),l(!t)},"aria-label":"Toggle voice input",className:`shrink-0 relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${t?"bg-brand-500":"bg-surface-2"}`,children:(0,n.jsx)("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${t?"translate-x-4":"translate-x-0.5"}`})})]}),i&&(0,n.jsx)(u8,{onClose:()=>o(!1)})]})}function u7({onRemote:e,onFiles:t,onCommandNotes:s,onCommunity:a,onInstallApp:i,canInstall:o=!1,isInstalled:c=!1,onCodespace:d,onLogout:u,connected:m=!0,remoteAvailable:x=!1,codespaceInfo:p=null,showTheme:h=!1,theme:b="default",onThemeChange:g,hideActions:v=[],busRef:y=null,subscribeToPush:w=null,unsubscribeFromPush:k=null,onUpdate:j,onRestart:N,onOpenBackgroundPicker:S}){let{t:C}=(0,se.s)(),T=nk(),R=s7(e=>e.open),E=si(e=>e.close),{connectionMode:_="tunnel",agentVersion:$}=si(e=>e.context),M=uJ(),P=rX(e=>!1),A=tS(e=>e.webglEnabled),z=tS(e=>e.setWebglEnabled),I=tS(e=>e.fontSize),L=tS(e=>e.setFontSize),D=tS(e=>e.terminalTheme),F=tS(e=>e.setTerminalTheme),O=tS(e=>e.terminalBackgrounds),{theme:B}=(0,aT.D)(),[W,K]=(0,r.useState)(!1),[H,U]=(0,r.useState)(!1),[q,V]=(0,r.useState)(!1),[X,G]=(0,r.useState)(!1),[J,Y]=(0,r.useState)(!1),[Z,Q]=(0,r.useState)(null),[ee,es]=(0,r.useState)(""),en=(0,r.useRef)(null),{loadKeys:er}=(0,aA.u)(),{setAuth:ea}=(0,l.F)();er();let el=(0,l.F)().getAuth()?.apiKey;(0,r.useCallback)(async e=>{if(e&&e!==el){if((0,et.PF)(e))return void es(C("login.legacyKeyError"));(0,t7.e)(),es(""),Q(e),el&&dw(el,window.location.pathname+window.location.search);try{let t=await fetch(f.Sn.connect,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e})});if(!t.ok)throw Error("connect failed");let s=await t.json(),n=!1;for(let t=0;t<f.jP&&!(n=await (0,aP.zg)(s.tunnelUrl,e));t++)t<f.jP-1&&await new Promise(e=>setTimeout(e,f.dM));if(!n){Q(null),es(C("agentSwitcher.unreachable"));return}ea({apiKey:e,tunnelUrl:s.tunnelUrl,mode:"remote",localIp:s.localIp||null});let r=dk(e);window.location.href=r||"/workspace/"}catch{Q(null),es(C("agentSwitcher.unreachable"))}}},[el,ea,C]),(0,r.useEffect)(()=>{if(!W)return;let e=e=>{en.current&&!en.current.contains(e.target)&&K(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[W]);let ei=(0,r.useRef)(null);(0,r.useEffect)(()=>{if(!X)return;let e=e=>{ei.current&&!ei.current.contains(e.target)&&G(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[X]);let[eo,ed]=(0,r.useState)(!1);(0,r.useEffect)(()=>{ed(window.innerWidth<768)},[]);let eu="3.0.11",em=n9($,eu)||n7($,eu),ex=uY(w,k),ep=uZ(y,m),eh=ex.isExpoWebView||!!window.ReactNativeWebView||/9Remote-Mobile/i.test(navigator.userAgent),ef=window.matchMedia("(display-mode: standalone)").matches||eh,[eb,eg]=(0,r.useState)(()=>window.CURRENT_ORIENTATION||localStorage.getItem("expo_orientation")||"portrait");return(0,r.useEffect)(()=>{if(!eh)return;let e=e=>{if(e){eg(e);try{localStorage.setItem("expo_orientation",e)}catch{}}};window.handleScreenOrientationChange=e;try{window.ReactNativeWebView?.postMessage(JSON.stringify({type:"GET_SCREEN_ORIENTATION"}))}catch{}return()=>{window.handleScreenOrientationChange===e&&(window.handleScreenOrientationChange=void 0)}},[eh]),(0,r.useCallback)(e=>{(0,t7.e)(),eg(e);try{localStorage.setItem("expo_orientation",e)}catch{}try{window.ReactNativeWebView?.postMessage(JSON.stringify({type:"SET_SCREEN_ORIENTATION",orientation:e}))}catch{}},[]),(0,n.jsxs)("div",{className:"p-3 space-y-0.5",children:[!ef&&!c&&i&&(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),i()},className:"w-full px-3 py-1.5 mb-1.5 bg-surface hover:bg-surface-2 text-text rounded-brand-lg text-left flex items-center gap-2.5 transition duration-150 ease-out active:scale-[0.99]",children:[(0,n.jsx)(t3.f5,{className:"text-brand-500 flex-shrink-0",size:16}),(0,n.jsx)("span",{className:"text-sm flex-1 min-w-0 truncate",children:C("menu.installApp")}),o&&(0,n.jsx)("span",{className:"flex-shrink-0 px-2 py-0.5 bg-brand-500 text-white text-xs font-medium rounded-full",children:C("pwaGuide.installNow")})]}),ex.supported&&(0,n.jsxs)("button",{onClick:ex.toggle,disabled:ex.loading,className:"w-full px-3 py-1.5 bg-surface hover:bg-surface-2 disabled:opacity-50 text-text rounded-brand-lg text-left flex items-center justify-between gap-2.5 transition duration-150 ease-out active:scale-[0.99]",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2.5",children:[(0,n.jsx)(t3.Ir,{className:"text-brand-500",size:16}),(0,n.jsxs)("div",{className:"flex flex-col",children:[(0,n.jsx)("span",{className:"text-sm",children:C("menu.notifications")}),(0,n.jsx)("span",{className:"text-xs text-text-muted",children:C("menu.notificationsHint")})]})]}),ex.loading?(0,n.jsx)(t3.kr,{className:"animate-spin text-text-muted",size:16}):(0,n.jsx)("span",{className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${ex.enabled?"bg-brand-500":"bg-surface-2"}`,children:(0,n.jsx)("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${ex.enabled?"translate-x-4":"translate-x-0.5"}`})})]}),!v.includes("headerButtons")&&(0,n.jsxs)("div",{className:"bg-surface rounded-brand-lg overflow-hidden",children:[(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),U(e=>!e)},className:"w-full px-3 py-1.5 hover:bg-surface-2 text-text text-left flex items-center gap-2.5 transition duration-150 ease-out active:scale-[0.99]",children:[(0,n.jsx)(t3.jz,{className:"text-brand-500",size:16}),(0,n.jsx)("span",{className:"text-sm flex-1",children:C("menu.settingsButtons")}),(0,n.jsx)(t3.yQ,{className:`text-text-muted transition-transform duration-200 ${H?"rotate-180":""}`,size:16})]}),H&&(0,n.jsx)("div",{className:"pl-6 pr-3 pb-1.5 space-y-1.5",children:ec.map(({group:e,titleKey:t})=>(0,n.jsxs)("div",{className:"space-y-1.5",children:[(0,n.jsx)("p",{className:"pt-1 text-[11px] font-semibold uppercase tracking-wide text-text-muted",children:C(t)}),M.buttons.filter(t=>t.group===e).map(e=>{if("remote"===e.id||"mobile"===e.id)return null;let t=uX[e.id],s=M.isOn(e);return(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),M.toggle(e)},className:"w-full py-1 hover:bg-surface-2 text-text rounded-brand text-left flex items-center gap-2.5 transition duration-150 ease-out active:scale-[0.99]",children:[(0,n.jsx)(t,{className:"text-text",size:16}),(0,n.jsx)("span",{className:"text-sm flex-1",children:C(e.labelKey)}),(0,n.jsx)("span",{className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${s?"bg-brand-500":"bg-surface-2"}`,children:(0,n.jsx)("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${s?"translate-x-4":"translate-x-0.5"}`})})]},e.id)})]},e))})]}),!v.includes("terminalSettings")&&(0,n.jsxs)("div",{ref:en,className:"bg-surface rounded-brand-lg overflow-hidden",children:[(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),K(e=>!e)},className:"w-full px-3 py-1.5 hover:bg-surface-2 text-text text-left flex items-center gap-2.5 transition duration-150 ease-out active:scale-[0.99]",children:[(0,n.jsx)(t3.BK,{className:"text-brand-500",size:16}),(0,n.jsx)("span",{className:"text-sm flex-1",children:C("menu.terminalSettings")}),(0,n.jsx)(t3.yQ,{className:`text-text-muted transition-transform duration-200 ${W?"rotate-180":""}`,size:16})]}),W&&(0,n.jsxs)("div",{className:"pl-6 pr-3 pb-1.5 space-y-1.5",children:[(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),z(!A)},className:"w-full py-1 hover:bg-surface-2 text-text rounded-brand text-left flex items-center gap-2.5 transition duration-150 ease-out active:scale-[0.99]",children:[(0,n.jsx)(t3.VA,{className:"text-text",size:16}),(0,n.jsxs)("div",{className:"flex flex-col flex-1",children:[(0,n.jsx)("span",{className:"text-sm",children:C("menu.webgl")}),(0,n.jsx)("span",{className:"text-xs text-text-muted",children:C("menu.webglHint")})]}),(0,n.jsx)("span",{className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${A?"bg-brand-500":"bg-surface-2"}`,children:(0,n.jsx)("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${A?"translate-x-4":"translate-x-0.5"}`})})]}),(0,n.jsxs)("div",{className:"flex items-center gap-2.5 pt-1.5",children:[(0,n.jsx)(t3.ZU,{className:"text-text",size:16}),(0,n.jsx)("span",{className:"text-sm",children:C("menu.fontSize")}),(0,n.jsx)("select",{value:I??(eo?12:14),onChange:e=>{(0,t7.e)(),L(Number(e.target.value))},className:"ml-auto bg-surface-2 text-text text-sm rounded-brand px-2 py-1 focus:outline-none focus:ring-2 focus:ring-brand-500/40",children:Array.from({length:eo?7:9},(e,t)=>t+10).map(e=>(0,n.jsxs)("option",{value:e,children:[e,"px"]},e))})]}),(0,n.jsxs)("div",{className:"flex items-center gap-2.5",children:[(0,n.jsx)(t3.es,{className:"text-text",size:16}),(0,n.jsx)("span",{className:"text-sm",children:C("menu.terminalTheme")}),(0,n.jsxs)("select",{value:D,onChange:e=>{(0,t7.e)(),F(e.target.value)},className:"ml-auto bg-surface-2 text-text text-xs rounded-brand px-2 py-1 max-w-[55%] focus:outline-none focus:ring-2 focus:ring-brand-500/40",children:[(0,n.jsx)("option",{value:"default",children:"Vesper (Default)"}),ax.g4.filter(e=>e.mode===B).map(e=>(0,n.jsx)("option",{value:e.key,children:e.label},e.key))]})]})]})]}),(0,n.jsxs)("div",{className:"bg-surface rounded-brand-lg overflow-hidden",children:[(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),V(e=>!e)},className:"w-full px-3 py-1.5 hover:bg-surface-2 text-text text-left flex items-center gap-2.5 transition duration-150 ease-out active:scale-[0.99]",children:[(0,n.jsx)(t3.Kq,{className:"text-brand-500",size:16}),(0,n.jsx)("span",{className:"text-sm flex-1",children:C("menu.settingsMcp")}),(0,n.jsx)(t3.yQ,{className:`text-text-muted transition-transform duration-200 ${q?"rotate-180":""}`,size:16})]}),q&&(0,n.jsxs)("div",{className:"pl-6 pr-3 pb-1.5 space-y-1.5",children:[(0,n.jsx)(u9,{dense:!0}),ep.supported&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"flex items-center gap-2.5",children:[(0,n.jsx)(t3.jz,{className:"text-text shrink-0",size:16}),(0,n.jsx)("span",{className:"text-sm flex-1 min-w-0",children:C("menu.artifactPanel")}),(0,n.jsx)("button",{onClick:ep.toggle,disabled:ep.loading||!m,className:`shrink-0 relative inline-flex h-5 w-9 items-center rounded-full transition-colors disabled:opacity-60 ${ep.enabled?"bg-brand-500":"bg-surface-2"}`,children:(0,n.jsx)("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${ep.enabled?"translate-x-4":"translate-x-0.5"}`})})]}),(0,n.jsx)("p",{className:"text-[11px] leading-relaxed text-text-muted",children:C("menu.artifactHint")})]})]})]}),"dark"===B&&(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),S?.()},className:"w-full px-3 py-1.5 bg-surface hover:bg-surface-2 text-text rounded-brand-lg text-left flex items-center gap-2.5 transition duration-150 ease-out active:scale-[0.99]",children:[(0,n.jsx)(t3.de,{className:"text-brand-500 flex-shrink-0",size:16}),(0,n.jsx)("span",{className:"text-sm flex-1 min-w-0",children:C("menu.terminalBackground")}),(0,n.jsx)("span",{className:"text-xs text-text-muted truncate max-w-[90px]","data-tip":O.length>1?`${eE(O[0])} +${O.length-1}`:eE(O[0]),children:O.length>1?`${eE(O[0])} +${O.length-1}`:eE(O[0])}),(0,n.jsx)(t3.c_,{size:16,className:"text-text-muted flex-shrink-0"})]}),P&&(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),E(),rX.getState().toggle()},className:"w-full px-3 py-1.5 rounded-brand-lg text-left flex items-center gap-2.5 transition duration-150 ease-out bg-surface hover:bg-surface-2 text-text active:scale-[0.99]",children:[(0,n.jsx)(t3.cC,{className:"text-brand-500",size:16}),(0,n.jsx)("span",{className:"text-sm",children:"Jarvis"})]}),s&&(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),s()},className:"w-full px-3 py-1.5 rounded-brand-lg text-left flex items-center gap-2.5 transition duration-150 ease-out bg-surface hover:bg-surface-2 text-text active:scale-[0.99]",children:[(0,n.jsx)(t3.iU,{className:"text-brand-500",size:16}),(0,n.jsx)("span",{className:"text-sm",children:C("menu.commandNotes")})]}),"mouse"===T&&(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),E(),R()},className:"w-full px-3 py-1.5 rounded-brand-lg text-left flex items-center gap-2.5 transition duration-150 ease-out bg-surface hover:bg-surface-2 text-text active:scale-[0.99]",children:[(0,n.jsx)(t3.s3,{className:"text-brand-500",size:16}),(0,n.jsx)("span",{className:"text-sm",children:C("shortcuts.menuLabel")})]}),a&&(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),a()},className:"w-full px-3 py-1.5 bg-surface hover:bg-surface-2 text-text rounded-brand-lg text-left flex items-center gap-2.5 transition duration-150 ease-out active:scale-[0.99]",children:[(0,n.jsx)(t3.zW,{className:"text-brand-500",size:16}),(0,n.jsx)("span",{className:"text-sm",children:C("menu.community")})]}),p?.isCodespaces&&d&&(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),d()},className:"w-full px-3 py-1.5 bg-surface hover:bg-surface-2 text-text rounded-brand-lg text-left flex items-center gap-2.5 transition duration-150 ease-out active:scale-[0.99]",children:[(0,n.jsx)(t3.sU,{className:"text-brand-500",size:16}),(0,n.jsx)("span",{className:"text-sm",children:C("menu.codespace")})]}),(0,n.jsxs)("div",{ref:ei,className:"rounded-brand-lg overflow-hidden",children:[(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),G(e=>!e)},className:"w-full px-3 py-1.5 bg-surface hover:bg-surface-2 text-text text-left flex items-center gap-2.5 transition duration-150 ease-out active:scale-[0.99]",children:[(0,n.jsx)(t3.e9,{className:"text-brand-500",size:16}),(0,n.jsx)("span",{className:"text-sm flex-1",children:C("menu.reloadRestart")}),(0,n.jsx)(t3.yQ,{className:`text-text-muted transition-transform duration-200 ${X?"rotate-180":""}`,size:16})]}),X&&(0,n.jsxs)("div",{className:"bg-surface-2/50 px-3 pb-1.5 space-y-0",children:[(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),Y(!0),setTimeout(()=>window.location.reload(),150)},disabled:J,className:"w-full py-1.5 text-text text-left flex items-center gap-2.5 rounded-brand transition duration-150 ease-out hover:text-brand-500 active:scale-[0.99] disabled:opacity-70",children:[(0,n.jsx)(t3.e9,{size:16,className:`ml-3 ${J?"animate-spin":""}`}),(0,n.jsx)("span",{className:"text-sm",children:C("menu.reload")})]}),N&&(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),G(!1),N()},className:"w-full py-1.5 text-text text-left flex items-center gap-2.5 rounded-brand transition duration-150 ease-out hover:text-brand-500 active:scale-[0.99]",children:[(0,n.jsx)(t3.kt,{size:16,className:"ml-3"}),(0,n.jsx)("span",{className:"text-sm",children:C("menu.restartHost")})]})]})]}),u&&(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),u()},className:"w-full px-3 py-1.5 bg-surface hover:bg-red-500/15 text-text hover:text-red-400 rounded-brand-lg text-left flex items-center gap-2.5 transition duration-150 ease-out active:scale-[0.99]",children:[(0,n.jsx)(t3.nU,{className:"text-red-400",size:16}),(0,n.jsx)("span",{className:"text-sm",children:C("menu.logout")})]}),em&&(0,n.jsx)(re,{agentVersion:$,webVersion:eu,className:"mt-3"}),(0,n.jsxs)("div",{className:"flex items-center justify-end gap-2 mt-4 mr-1",children:["local"===_&&(0,n.jsx)("span",{className:"text-xs font-semibold px-2 py-0.5 rounded-full bg-green-500/15 text-green-400",children:"LAN"}),(0,n.jsxs)("p",{className:"text-text-muted text-sm",children:[C("menu.version")," ",eu,$?` / 9Remote ${$}`:""]})]})]})}var me=s(2163);function mt(){if("u"<typeof navigator)return"unknown";let e=navigator.userAgent.toLowerCase();return/iphone|ipad|ipod/.test(e)?"ios":/android/.test(e)?"android":/mac/.test(e)?"macos":/win/.test(e)?"windows":"desktop"}function ms(){let{t:e}=(0,se.s)(),[t]=(0,r.useState)(mt),[s,a]=(0,r.useState)(!1),[l,i]=(0,r.useState)("idle"),o=si(e=>e.context.apiKey),c=sT(e=>e.canInstall),d=sT(e=>e.isInstalled),u=sT(e=>e.install),m=async()=>{i("installing"),i("accepted"===await u()?"done":"idle")},x=async e=>{try{if(navigator.clipboard&&window.isSecureContext)return await navigator.clipboard.writeText(e),!0}catch{}try{let t=document.createElement("textarea");t.value=e,t.setAttribute("readonly",""),t.style.position="fixed",t.style.top="0",t.style.left="0",t.style.opacity="0",document.body.appendChild(t),t.focus(),t.setSelectionRange(0,e.length);let s=document.execCommand("copy");return document.body.removeChild(t),s}catch{return!1}},p=async()=>{!o||await x(o)&&(a(!0),setTimeout(()=>a(!1),2e3))},h=+!!o,f=()=>o?(0,n.jsxs)("div",{className:"flex items-start gap-3 mb-4",children:[(0,n.jsx)("div",{className:"flex-shrink-0 w-8 h-8 bg-brand-500/10 rounded-brand flex items-center justify-center text-brand-500 font-semibold",children:"1"}),(0,n.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,n.jsx)("p",{className:"text-text font-medium mb-2",children:e("pwaGuide.copyYourKey")}),(0,n.jsx)("p",{className:"text-text-muted text-sm mb-2",children:e("pwaGuide.copyKeyHint")}),(0,n.jsxs)("div",{className:`w-full flex items-center justify-between gap-2 px-3 py-2.5 rounded-brand border transition-colors ${s?"bg-green-500/10 border-green-500/30":"bg-bg border-border hover:border-brand-500/50 focus-within:border-brand-500/50"}`,children:[(0,n.jsx)("button",{type:"button",onClick:p,className:"flex-1 min-w-0 text-left bg-transparent outline-none border-0 p-0 cursor-pointer","aria-label":e("pwaGuide.tapToCopyApiKey"),children:(0,n.jsx)("code",{className:"block text-sm text-text font-mono truncate",children:(0,me.o)(o)})}),(0,n.jsx)("button",{type:"button",onClick:p,className:`flex items-center gap-1 text-sm flex-shrink-0 ${s?"text-green-400":"text-brand-500"}`,children:s?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(t3.aJ,{size:14})," ",e("pwaGuide.copiedBang")]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(t3.QR,{size:14})," ",e("pwaGuide.copy")]})})]})]})]}):null,b=()=>c?(0,n.jsxs)("div",{className:"flex items-start gap-3",children:[(0,n.jsx)("div",{className:"flex-shrink-0 w-8 h-8 bg-brand-500/10 rounded-brand flex items-center justify-center text-brand-500 font-semibold",children:1+h}),(0,n.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,n.jsx)("p",{className:"text-text font-medium mb-1",children:e("pwaGuide.installNow")}),(0,n.jsx)("p",{className:"text-text-muted text-sm",children:e("pwaGuide.installNowHint")})]}),(0,n.jsxs)("button",{type:"button",onClick:m,disabled:"installing"===l,className:"flex-shrink-0 flex items-center gap-1 px-3 py-2 bg-brand-500 hover:bg-brand-600 text-white text-sm font-medium rounded-brand transition-all duration-150 active:scale-[0.97] disabled:opacity-70 disabled:cursor-wait",children:[(0,n.jsx)(t3.f5,{size:14}),"installing"===l?e("pwaGuide.installing"):e("pwaGuide.installNow")]})]}):null;return d?(0,n.jsx)("div",{className:"p-6",children:(0,n.jsxs)("div",{className:"text-center py-12",children:[(0,n.jsx)("div",{className:"inline-flex p-4 bg-green-500/10 rounded-brand-lg mb-4",children:(0,n.jsx)(t3.aJ,{className:"text-green-500",size:48})}),(0,n.jsx)("p",{className:"text-text font-semibold mb-2",children:e("pwaGuide.alreadyInstalled")}),(0,n.jsx)("p",{className:"text-text-muted text-sm",children:e("pwaGuide.alreadyInstalledHint")})]})}):(0,n.jsxs)("div",{className:"p-6 space-y-6",children:[(0,n.jsxs)("div",{className:"flex items-center gap-3 pb-4 border-b border-border",children:[(0,n.jsx)("div",{className:"p-2 bg-brand-500/10 rounded-brand",children:(()=>{switch(t){case"ios":case"android":return(0,n.jsx)(t3.wO,{className:"text-brand-500",size:24});default:return(0,n.jsx)(t3.VA,{className:"text-brand-500",size:24})}})()}),(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"text-text font-medium",children:e("pwaGuide.installationGuide")}),(0,n.jsx)("p",{className:"text-text-muted text-sm",children:(()=>{switch(t){case"ios":return e("pwaGuide.iosPlatform");case"android":return e("pwaGuide.androidPlatform");case"macos":return e("pwaGuide.macosPlatform");case"windows":return e("pwaGuide.windowsPlatform");default:return e("pwaGuide.desktopPlatform")}})()})]})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"text-text font-medium mb-4",children:e("pwaGuide.installationSteps")}),(()=>{switch(t){case"ios":return(0,n.jsxs)("div",{className:"space-y-4",children:[f(),(0,n.jsxs)("div",{className:"flex items-start gap-3",children:[(0,n.jsx)("div",{className:"flex-shrink-0 w-8 h-8 bg-brand-500/10 rounded-brand flex items-center justify-center text-brand-500 font-semibold",children:1+h}),(0,n.jsxs)("div",{className:"flex-1",children:[(0,n.jsx)("p",{className:"text-text font-medium mb-1.5",children:"Download 9Remote on App Store"}),(0,n.jsxs)("a",{href:"https://apps.apple.com/us/app/9remote/id6796664210",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 px-4 py-2 bg-brand-500 hover:bg-brand-600 text-white text-sm font-semibold rounded-brand transition-colors",children:[(0,n.jsx)("svg",{className:"w-4 h-4",viewBox:"0 0 24 24",fill:"currentColor",children:(0,n.jsx)("path",{d:"M18.71 19.5c-.83 1.24-1.71 2.45-3.05 2.47-1.34.03-1.77-.79-3.29-.79-1.53 0-2 .77-3.27.82-1.31.05-2.3-1.32-3.14-2.53C4.25 17 2.94 12.45 4.7 9.39c.87-1.52 2.43-2.48 4.12-2.51 1.28-.02 2.5.87 3.29.87.78 0 2.26-1.07 3.81-.91.65.03 2.47.26 3.64 1.98-.09.06-2.17 1.28-2.15 3.81.03 3.02 2.65 4.03 2.68 4.04-.03.07-.42 1.44-1.38 2.83M15.97 6.38c.62-.75 1.04-1.8 0.92-2.85-.9.04-2 .6-2.65 1.35-.58.66-1.09 1.73-.95 2.76.99.08 2.03-.51 2.68-1.26z"})}),"Get on App Store"]})]})]}),(0,n.jsxs)("div",{className:"flex items-start gap-3",children:[(0,n.jsx)("div",{className:"flex-shrink-0 w-8 h-8 bg-brand-500/10 rounded-brand flex items-center justify-center text-brand-500 font-semibold",children:2+h}),(0,n.jsxs)("div",{className:"flex-1",children:[(0,n.jsx)("p",{className:"text-text font-medium mb-1",children:e("pwaGuide.openAppPasteKey")}),(0,n.jsx)("p",{className:"text-text-muted text-sm",children:e("pwaGuide.openAppPasteKeyHint")})]})]})]});case"android":return(0,n.jsxs)("div",{className:"space-y-4",children:[f(),(0,n.jsxs)("div",{className:"flex items-start gap-3",children:[(0,n.jsx)("div",{className:"flex-shrink-0 w-8 h-8 bg-brand-500/10 rounded-brand flex items-center justify-center text-brand-500 font-semibold",children:1+h}),(0,n.jsxs)("div",{className:"flex-1",children:[(0,n.jsx)("p",{className:"text-text font-medium mb-1.5",children:"Download 9Remote on Google Play"}),(0,n.jsxs)("a",{href:"https://play.google.com/store/apps/details?id=cc.remote9.app&pli=1",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 px-4 py-2 bg-brand-500 hover:bg-brand-600 text-white text-sm font-semibold rounded-brand transition-colors",children:[(0,n.jsx)("svg",{className:"w-4 h-4",viewBox:"0 0 24 24",fill:"currentColor",children:(0,n.jsx)("path",{d:"M3.609 1.814L13.793 12 3.61 22.186a2.128 2.128 0 0 1-.22-.964V2.778c0-.36.08-.694.22-.964zm11.233 11.234l2.584 2.584-11.834 6.83 9.25-9.414zm0-2.096L5.592 1.538l11.834 6.83-2.584 2.584zm1.485 1.048l3.633 2.098a1.328 1.328 0 0 0 0-2.296l-3.633-2.098-1.048 1.048 1.048 1.048z"})}),"Get on Google Play"]})]})]}),c&&(0,n.jsxs)("div",{className:"pt-2 border-t border-border",children:[(0,n.jsx)("p",{className:"text-xs text-text-muted mb-2",children:"Or install directly as Web App (PWA):"}),b()]}),(0,n.jsxs)("div",{className:"flex items-start gap-3",children:[(0,n.jsx)("div",{className:"flex-shrink-0 w-8 h-8 bg-brand-500/10 rounded-brand flex items-center justify-center text-brand-500 font-semibold",children:2+h}),(0,n.jsxs)("div",{className:"flex-1",children:[(0,n.jsx)("p",{className:"text-text font-medium mb-1",children:e("pwaGuide.openAppPasteKey")}),(0,n.jsx)("p",{className:"text-text-muted text-sm",children:e("pwaGuide.openAppPasteKeyHint")})]})]})]});case"macos":case"windows":case"desktop":return(0,n.jsxs)("div",{className:"space-y-4",children:[f(),b(),c&&(0,n.jsxs)("div",{className:"flex items-start gap-3",children:[(0,n.jsx)("div",{className:"flex-shrink-0 w-8 h-8 bg-brand-500/10 rounded-brand flex items-center justify-center text-brand-500 font-semibold",children:2+h}),(0,n.jsxs)("div",{className:"flex-1",children:[(0,n.jsx)("p",{className:"text-text font-medium mb-1",children:e("pwaGuide.openAppPasteKey")}),(0,n.jsx)("p",{className:"text-text-muted text-sm",children:e("pwaGuide.openAppPasteKeyHint")})]})]}),!c&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"flex items-start gap-3",children:[(0,n.jsx)("div",{className:"flex-shrink-0 w-8 h-8 bg-brand-500/10 rounded-brand flex items-center justify-center text-brand-500 font-semibold",children:1+h}),(0,n.jsxs)("div",{className:"flex-1",children:[(0,n.jsx)("p",{className:"text-text font-medium mb-1",children:e("pwaGuide.lookInstallIcon")}),(0,n.jsx)("p",{className:"text-text-muted text-sm",children:e("pwaGuide.lookInstallIconHint")})]})]}),(0,n.jsxs)("div",{className:"flex items-start gap-3",children:[(0,n.jsx)("div",{className:"flex-shrink-0 w-8 h-8 bg-brand-500/10 rounded-brand flex items-center justify-center text-brand-500 font-semibold",children:2+h}),(0,n.jsxs)("div",{className:"flex-1",children:[(0,n.jsx)("p",{className:"text-text font-medium mb-1",children:e("pwaGuide.clickInstallPaste")}),(0,n.jsx)("p",{className:"text-text-muted text-sm",children:e("pwaGuide.clickInstallPasteHint")})]})]}),(0,n.jsx)("div",{className:"mt-6 p-3 bg-blue-500/10 rounded-brand",children:(0,n.jsxs)("p",{className:"text-blue-200 text-sm",children:["\uD83D\uDCA1 ",e("pwaGuide.alternativeHint")]})})]})]});default:return(0,n.jsx)("p",{className:"text-text-muted text-center py-8",children:e("pwaGuide.loadingPlatform")})}})()]})]})}let mn=[{command:"npm i 9router -g"},{command:"curl -fsSL https://claude.ai/install.sh | bash"},{command:"npm i -g @openai/codex"},{command:"curl -fsSL https://opencode.ai/install | bash"}],{storageKey:mr,maxNotes:ma}={storageKey:"9remote_command_notes_v2",maxNotes:50};function ml({isOpen:e,onClose:t}){let{t:s}=(0,se.s)(),{notes:a,addNote:l,updateNote:i,deleteNote:o}=function(){let[e,t]=(0,r.useState)([]),s=(0,r.useCallback)(()=>{try{let e=localStorage.getItem(mr);if(e)return JSON.parse(e);let t=mn.map((e,t)=>({id:`default_${t}`,...e}));return localStorage.setItem(mr,JSON.stringify(t)),t}catch(e){return console.error("Failed to load command notes:",e),[]}},[]);(0,r.useEffect)(()=>{t(s())},[s]);let n=(0,r.useCallback)(e=>{try{localStorage.setItem(mr,JSON.stringify(e)),t(e)}catch(e){console.error("Failed to persist command notes:",e)}},[]),a=(0,r.useCallback)(t=>{n([{id:Date.now().toString(),command:t},...e].slice(0,ma))},[e,n]),l=(0,r.useCallback)((t,s)=>{n(e.map(e=>e.id===t?{...e,command:s}:e))},[e,n]),i=(0,r.useCallback)(t=>{n(e.filter(e=>e.id!==t))},[e,n]);return{notes:e,addNote:a,updateNote:l,deleteNote:i}}(),[c,d]=(0,r.useState)(null),[u,m]=(0,r.useState)(null),[x,p]=(0,r.useState)(""),h=(0,r.useRef)(null),[f,b]=(0,r.useState)(null);(0,r.useEffect)(()=>{e&&setTimeout(()=>h.current?.focus(),100)},[e,u]),(0,r.useEffect)(()=>{if(!e||!window.visualViewport)return;let t=window.visualViewport,s=()=>b(t.height);return s(),t.addEventListener("resize",s),t.addEventListener("scroll",s),()=>{t.removeEventListener("resize",s),t.removeEventListener("scroll",s)}},[e]),(0,r.useEffect)(()=>{let s=s=>{"Escape"===s.key&&e&&t()};return document.addEventListener("keydown",s),()=>document.removeEventListener("keydown",s)},[e,t]);let g=(0,r.useCallback)((e,t)=>{(0,t7.e)(),navigator.clipboard?.writeText(t).catch(()=>{}),d(e),setTimeout(()=>d(null),2e3)},[]),v=(0,r.useCallback)(e=>{(0,t7.e)(),m(e.id),p(e.command)},[]),y=(0,r.useCallback)(()=>{x.trim()&&((0,t7.e)(),u?(i(u,x.trim()),m(null)):l(x.trim()),p(""))},[x,u,l,i]),w=(0,r.useCallback)(e=>{(0,t7.e)(),o(e),u===e&&(m(null),p(""))},[o,u]),k=(0,r.useCallback)(e=>{"Enter"===e.key&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),y())},[y]);return e?(0,n.jsxs)("div",{className:"fixed inset-0 z-50 flex",children:[(0,n.jsx)("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-[2px] fade-in",onClick:t}),(0,n.jsxs)("div",{className:"absolute top-0 right-0 w-[85vw] sm:w-96 max-w-md bg-surface border-l border-border shadow-2xl flex flex-col slide-in-right",style:{height:f?`${f}px`:"100%"},onClick:e=>e.stopPropagation(),children:[(0,n.jsxs)("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border flex-shrink-0 safe-area-top",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)(t3.iU,{size:20,className:"text-brand-500"}),(0,n.jsx)("h2",{className:"text-lg font-semibold text-text",children:s("commandNotes.title")})]}),(0,n.jsx)("button",{onClick:t,className:"p-2 text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-colors",children:(0,n.jsx)(t3.X,{size:20})})]}),(0,n.jsxs)("div",{className:"flex-1 overflow-y-auto modal-scrollable",children:[0===a.length&&(0,n.jsxs)("div",{className:"text-center text-text-muted py-8",children:[(0,n.jsx)(t3.iU,{size:32,className:"mx-auto mb-3 text-text-muted"}),(0,n.jsx)("p",{className:"text-sm",children:s("commandNotes.noSavedCommands")}),(0,n.jsx)("p",{className:"text-xs text-text-muted mt-1",children:s("commandNotes.addFirstBelow")})]}),a.map(e=>(0,n.jsx)("div",{className:"px-4 py-3 border-b border-border/50 hover:bg-surface-2/30 transition-colors group",children:(0,n.jsxs)("div",{className:"flex items-start justify-between gap-2",children:[(0,n.jsxs)("div",{className:"flex-1 min-w-0 cursor-pointer",onClick:()=>g(e.id,e.command),title:s("commandNotes.clickToCopy"),children:[(0,n.jsx)("p",{className:"text-sm text-text font-mono break-all",children:e.command}),c===e.id&&(0,n.jsx)("span",{className:"text-xs text-green-400 mt-1 inline-block",children:s("commandNotes.copiedBang")})]}),(0,n.jsxs)("div",{className:"flex items-center gap-0.5 flex-shrink-0 opacity-60 group-hover:opacity-100 transition-opacity",children:[(0,n.jsx)("button",{onClick:()=>g(e.id,e.command),className:"p-1.5 text-text-muted hover:text-brand-400 rounded transition-colors",title:s("commandNotes.copy"),children:c===e.id?(0,n.jsx)(t3.aJ,{size:14,className:"text-green-400"}):(0,n.jsx)(t3.QR,{size:14})}),(0,n.jsx)("button",{onClick:()=>v(e),className:"p-1.5 text-text-muted hover:text-brand-400 rounded transition-colors",title:s("commandNotes.edit"),children:(0,n.jsx)(t3.gH,{size:14})}),(0,n.jsx)("button",{onClick:()=>w(e.id),className:"p-1.5 text-text-muted hover:text-red-400 rounded transition-colors",title:s("commandNotes.delete"),children:(0,n.jsx)(t3.TB,{size:14})})]})]})},e.id))]}),(0,n.jsx)("div",{className:"px-3 py-3 border-t border-border flex-shrink-0 safe-area-bottom",children:(0,n.jsxs)("div",{className:"flex gap-2 items-end",children:[(0,n.jsx)("textarea",{ref:h,value:x,onChange:e=>p(e.target.value),onKeyDown:k,placeholder:u?s("commandNotes.editCommandPlaceholder"):s("commandNotes.addCommandPlaceholder"),rows:2,className:"flex-1 bg-surface-2 rounded-brand px-3 py-2 text-text text-sm placeholder-text-muted focus:outline-none focus:ring-2 focus:ring-brand-500/40 transition-all duration-150 ease-out font-mono resize-none"}),(0,n.jsx)("button",{onClick:y,disabled:!x.trim(),className:"p-2.5 bg-brand-600 hover:bg-brand-500 disabled:bg-surface-2 disabled:cursor-not-allowed text-text rounded-brand transition-colors flex-shrink-0",title:u?s("commandNotes.update"):s("commandNotes.add"),children:(0,n.jsx)(t3.Vn,{size:18})})]})})]})]}):null}let mi=[{id:"facebook",label:"Facebook Group",description:"Report bugs & suggest features to 9Team community",url:"https://www.facebook.com/groups/9teamvn",icon:"Facebook",color:"#1877F2"},{id:"github",label:"GitHub",description:"Source code & issue tracker",url:"https://github.com/decolua/9remote",icon:"Github",color:"#ffffff"}];function mo({isOpen:e,onClose:t}){let{t:s}=(0,se.s)();return((0,r.useEffect)(()=>{if(!e)return;let s=e=>{"Escape"===e.key&&t?.()};return document.addEventListener("keydown",s),()=>document.removeEventListener("keydown",s)},[e,t]),e)?(0,n.jsxs)("div",{className:"fixed inset-0 z-[60] flex items-center justify-center p-4",children:[(0,n.jsx)("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-[2px] fade-in",onClick:t}),(0,n.jsxs)("div",{className:"relative w-full max-w-md card-elev slide-in-top",onClick:e=>e.stopPropagation(),children:[(0,n.jsxs)("div",{className:"flex items-center justify-between px-5 py-4",children:[(0,n.jsx)("h2",{className:"text-lg font-semibold text-text",children:s("community.title")}),(0,n.jsx)("button",{onClick:t,className:"p-2 text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-colors","aria-label":s("common.close"),children:(0,n.jsx)(t3.X,{size:20})})]}),(0,n.jsxs)("div",{className:"p-4 space-y-2",children:[(0,n.jsx)("p",{className:"text-text-muted text-sm px-1 mb-2",children:s("community.description")}),mi.map(e=>(0,n.jsxs)("button",{onClick:()=>{var t;return t=e.url,void((0,t7.e)(),window.open(t,"_blank","noopener,noreferrer"))},className:"w-full px-4 py-3 bg-surface-2 hover:bg-surface-3 text-text rounded-brand-lg text-left flex items-center gap-3 transition-all duration-150 ease-out active:scale-[0.99] group",children:[(0,n.jsx)("span",{className:"flex items-center justify-center w-10 h-10 rounded-brand flex-shrink-0",style:{backgroundColor:`${e.color}1a`,color:e.color},children:(0,n.jsx)(t3.Ay,{name:e.icon,size:22})}),(0,n.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,n.jsx)("div",{className:"font-medium truncate",children:e.label}),e.description&&(0,n.jsx)("div",{className:"text-text-muted text-xs truncate",children:e.description})]}),(0,n.jsx)(t3.Gr,{className:"text-text-muted group-hover:text-brand-500 flex-shrink-0",size:18})]},e.id))]})]})]}):null}var mc=s(18057);function md({codespaceInfo:e,busRef:t,onStop:s}){let{t:a}=(0,se.s)(),[l,i]=(0,r.useState)(null),[o,c]=(0,r.useState)(!1);(0,r.useEffect)(()=>{if(!t?.current||!e?.isCodespaces){e?.isCodespaces&&!t?.current&&console.log("CodespacePanel: busRef not available"),i(!1);return}t.current.emit("getAutoStartStatus",e=>{console.log("getAutoStartStatus result:",e),e.success?i(e.enabled):i(!1)})},[t,e]);let d=(0,r.useCallback)(()=>{if(!t?.current||o)return;c(!0);let e=!l;t.current.emit("setAutoStart",{enabled:e},e=>{c(!1),e.success&&i(e.enabled)})},[t,l,o]);return e?(0,n.jsxs)("div",{className:"p-5",children:[(0,n.jsxs)("div",{className:"space-y-3 mb-6",children:[(0,n.jsxs)("div",{className:"flex items-center justify-between",children:[(0,n.jsx)("span",{className:"text-text-muted text-sm",children:a("codespace.name")}),(0,n.jsx)("span",{className:"text-text font-medium",children:e.codespaceName||a("codespace.unknown")})]}),(0,n.jsxs)("div",{className:"flex items-center justify-between",children:[(0,n.jsx)("span",{className:"text-text-muted text-sm",children:a("codespace.status")}),(0,n.jsxs)("span",{className:"text-green-400 font-medium flex items-center gap-1",children:[(0,n.jsx)("span",{className:"w-2 h-2 bg-green-400 rounded-full"}),a("codespace.running")]})]})]}),(0,n.jsx)("div",{className:"pt-4 border-t border-border mb-6",children:(0,n.jsxs)("div",{className:"flex items-center justify-between py-3",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("span",{className:"text-text text-sm font-medium",children:a("codespace.autoStart")}),(0,n.jsx)("p",{className:"text-text-muted text-xs mt-0.5",children:a("codespace.autoStartHint")})]}),null===l?(0,n.jsx)(t3.kr,{className:"animate-spin text-text-muted",size:20}):(0,n.jsx)("button",{onClick:d,disabled:o,className:`relative w-12 h-6 rounded-full transition-colors ${l?"bg-brand-500":"bg-surface-2"} ${o?"opacity-50":""}`,children:(0,n.jsx)("span",{className:`absolute top-1 w-4 h-4 bg-white rounded-full transition-transform ${l?"left-7":"left-1"}`})})]})}),(0,n.jsxs)("div",{className:"pt-4 border-t border-border space-y-3",children:[(0,n.jsxs)("button",{onClick:s,className:"w-full py-2 bg-orange-600 hover:bg-orange-700 text-white font-medium rounded-brand transition flex items-center justify-center gap-2",children:[(0,n.jsx)(t3.M6,{size:16}),a("codespace.stop")]}),(0,n.jsxs)("p",{className:"text-text text-sm flex items-start gap-2",children:[(0,n.jsx)("span",{className:"text-yellow-400",children:"\uD83D\uDCA1"}),a("codespace.stopHint")]}),(0,n.jsxs)("p",{className:"text-text-muted text-xs flex items-start gap-2",children:[(0,n.jsx)("span",{className:"text-orange-400",children:"⚠️"}),a("codespace.restartHint")]})]})]}):null}let mu=[{id:"general",labelKey:"menu.settingsGeneral",icon:"Settings"},{id:"appearance",labelKey:"menu.settingsAppearance",icon:"Palette"},{id:"terminal",labelKey:"menu.settingsTerminalTab",icon:"Terminal"},{id:"background",labelKey:"menu.terminalBackground",icon:"Image"},{id:"buttons",labelKey:"menu.settingsButtons",icon:"PanelRight"},{id:"mcp",labelKey:"menu.settingsMcp",icon:"Zap"},{id:"shortcuts",labelKey:"shortcuts.menuLabel",icon:"Keyboard"},{id:"codespace",labelKey:"menu.codespace",icon:"Sparkles"}];function mm({isOpen:e,onClose:t,busRef:s,inline:a=!1}){let{t:l}=(0,se.s)(),i=tS(e=>e.terminalBackgrounds);tS(e=>e.setTerminalBackgrounds);let o=tS(e=>e.terminalBackgroundOpacity),c=tS(e=>e.setTerminalBackgroundOpacity),d=tS(e=>e.customBackgrounds),{saving:u,error:m,setError:x,fileInput:p,openPicker:h}=rM(s),[f,b]=(0,r.useState)(()=>window.innerWidth>=760);(0,r.useEffect)(()=>{let e=()=>b(window.innerWidth>=760);return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),(0,r.useEffect)(()=>{if(!e)return;let s=e=>{"Escape"===e.key&&(x(""),t())};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e,t,x]);let g=()=>{x(""),t()};if(!a&&!e)return null;let v=o??.8,{min:y,max:w,step:k}=eN,j=`${(v-y)/(w-y)*100}%`,N=e_(i,d),S=(e,t,s)=>{let r="none"===e,a=r?-1:N.indexOf(e),l=r?0===N.length:-1!==a;return(0,n.jsxs)("button",{onClick:()=>(e=>{(0,t7.e)();let{terminalBackgrounds:t,setTerminalBackgrounds:s}=tS.getState();s("none"===e?[]:t.includes(e)?t.filter(t=>t!==e):[...t,e])})(e),className:"group relative block w-full aspect-[9/16] rounded-2xl overflow-hidden transition-transform duration-200 ease-out active:scale-[0.97] shadow-sm",children:[s?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("img",{src:s,alt:t,className:"absolute inset-0 h-full w-full object-cover transition-transform duration-300 group-hover:scale-[1.03]",loading:"lazy"}),(0,n.jsx)("span",{className:"pointer-events-none absolute inset-0",style:{background:"rgba(0,0,0,0.25)"}}),(0,n.jsx)("div",{className:"absolute inset-x-0 bottom-0 h-1/4 bg-gradient-to-t from-black/75 to-transparent"}),(0,n.jsx)("span",{className:"absolute bottom-2 left-0 right-0 px-2 text-xs font-medium text-white truncate",children:t})]}):(0,n.jsxs)("span",{className:`absolute inset-0 flex flex-col items-center justify-center gap-2 transition-colors ${l?"bg-brand-500/10 text-brand-500":"bg-surface-2 text-text-muted group-hover:text-text"}`,children:[(0,n.jsx)(t3.P6,{size:24,strokeWidth:1.75}),(0,n.jsx)("span",{className:"text-xs font-medium",children:t})]}),(0,n.jsx)("span",{className:`pointer-events-none absolute inset-0 rounded-2xl transition-shadow duration-200 ${l?"ring-1 ring-inset ring-brand-500":"ring-1 ring-inset ring-white/15 group-hover:ring-brand-500/60"}`}),l&&!r&&(0,n.jsx)("span",{className:"absolute top-2 right-2 flex items-center justify-center w-6 h-6 bg-brand-500 rounded-full shadow-lg text-white text-xs font-semibold",children:a+1})]})},C=(0,n.jsxs)("div",{className:a||f?"grid grid-cols-3 gap-3":"grid grid-cols-2 gap-3",children:[Object.entries(eS).map(([e,t])=>(0,n.jsx)("div",{children:S(e,t.label,t.src)},e)),d.map(e=>(0,n.jsxs)("div",{className:"relative",children:[S(`custom:${e.id}`,l("menu.bgCustomLabel"),e.dataUrl),(0,n.jsx)("button",{onClick:()=>{var t;let n;return t=e.id,(0,t7.e)(),n=s?.current,void(n?.emit&&n.emit("bg:delete",{id:t},e=>{if(!e?.success)return void x(e?.error||l("menu.bgDeleteFailed"));let s=`custom:${t}`,{customBackgrounds:n,setCustomBackgrounds:r,terminalBackgrounds:a,setTerminalBackgrounds:i}=tS.getState();r(n.filter(e=>e.id!==t)),i(a.filter(e=>e!==s))}))},className:"absolute top-2 left-2 flex items-center justify-center w-7 h-7 rounded-full bg-black/55 text-white backdrop-blur-sm hover:bg-red-500/80 transition-colors","aria-label":l("common.delete"),children:(0,n.jsx)(t3.X,{size:13})})]},`custom:${e.id}`)),(0,n.jsxs)("button",{onClick:h,disabled:u,className:"group relative block w-full aspect-[9/16] rounded-2xl overflow-hidden border-2 border-dashed border-border flex flex-col items-center justify-center gap-2 text-text-muted hover:border-brand-500 hover:text-brand-500 transition-colors disabled:opacity-40",children:[u?(0,n.jsx)(t3.kr,{size:24,className:"animate-spin"}):(0,n.jsx)(t3.FW,{size:24,strokeWidth:1.75}),(0,n.jsx)("span",{className:"text-xs font-medium",children:l("menu.bgAdd")})]})]}),T=N.length>0&&(0,n.jsxs)("div",{className:"flex-shrink-0 flex items-center gap-3 px-1 pt-1",children:[(0,n.jsx)("span",{className:"text-xs text-text flex-shrink-0",children:l("menu.bgDim")}),(0,n.jsx)("input",{type:"range",min:y,max:w,step:k,value:v,onChange:e=>c(Number(e.target.value)),className:"brand-range flex-1 min-w-0",style:{"--pct":j},"aria-label":l("menu.bgDim")}),(0,n.jsxs)("span",{className:"text-xs text-text-muted tabular-nums flex-shrink-0",children:[Math.round(100*v),"%"]})]}),R=N.length>0&&(0,n.jsxs)("div",{className:"flex-shrink-0 border-t border-border px-5 pt-3 pb-[max(1.25rem,env(safe-area-inset-bottom))]",children:[(0,n.jsxs)("div",{className:"flex items-center justify-between mb-1.5",children:[(0,n.jsx)("span",{className:"text-sm text-text",children:l("menu.bgDim")}),(0,n.jsxs)("span",{className:"text-xs text-text-muted tabular-nums",children:[Math.round(100*v),"%"]})]}),(0,n.jsx)("input",{type:"range",min:y,max:w,step:k,value:v,onChange:e=>c(Number(e.target.value)),className:"brand-range brand-range-lg",style:{"--pct":j},"aria-label":l("menu.bgDim")})]}),E=m&&(0,n.jsx)("div",{className:`px-3 py-2 rounded-brand bg-red-500/10 border border-red-500/30 text-red-500 text-xs break-all ${a?"":"flex-shrink-0 mx-5 mb-2"}`,children:m});return a?(0,n.jsxs)("div",{className:"h-full flex flex-col gap-2",children:[(0,n.jsxs)("div",{className:"flex-1 min-h-0 overflow-y-auto modal-scrollable",children:[C,E]}),T,p]}):(0,r_.createPortal)((0,n.jsxs)("div",{className:f?"fixed inset-0 z-[60] flex items-center justify-center p-4":"fixed inset-0 z-[60] flex flex-col justify-end",children:[(0,n.jsx)("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-[2px] animate-in fade-in duration-200",onClick:g}),(0,n.jsxs)("div",{className:f?"relative w-full max-w-lg max-h-[80vh] rounded-brand-lg border border-border-subtle bg-surface shadow-2xl flex flex-col overflow-hidden animate-in zoom-in-95 duration-200":"relative rounded-t-3xl border-t border-border bg-surface/95 backdrop-blur-xl shadow-2xl max-h-[88dvh] flex flex-col animate-in slide-in-from-bottom duration-300 ease-out",children:[!f&&(0,n.jsx)("div",{className:"pt-3 pb-1 flex justify-center flex-shrink-0",children:(0,n.jsx)("div",{className:"w-10 h-1 rounded-full bg-border"})}),(0,n.jsxs)("div",{className:`px-6 pb-3 flex items-center justify-between flex-shrink-0 ${f?"pt-4":""}`,children:[(0,n.jsx)("h3",{className:"text-lg font-semibold text-text",children:l("menu.terminalBackground")}),(0,n.jsx)("button",{onClick:g,className:"p-2 -mr-2 text-text-muted hover:text-text hover:bg-surface-2 rounded-full transition-colors","aria-label":l("common.close"),children:(0,n.jsx)(t3.X,{size:20})})]}),(0,n.jsx)("div",{className:"flex-1 min-h-0 overflow-y-auto modal-scrollable px-5 pb-4",children:C}),E,R]}),p]}),document.body)}let mx={Settings:t3.wB,Palette:t3.es,Terminal:t3.BK,Bell:t3.Ir,Sparkles:t3.sU,Keyboard:t3.s3,Zap:t3.Kq,PanelRight:t3.jz,Image:t3._V,Bot:t3.cC};function mp({context:e,callbacks:t,canInstall:s,isInstalled:a,install:l,onClose:i}){let{t:o,locale:c}=(0,se.s)(),{theme:d,setTheme:u}=(0,aT.D)(),[m,x]=(0,r.useState)("general"),[p,h]=(0,r.useState)(!1),[f,b]=(0,r.useState)(!1),g=uQ.dI.find(e=>e.code===c),v=tS(e=>e.webglEnabled),y=tS(e=>e.setWebglEnabled),w=tS(e=>e.fontSize),k=tS(e=>e.setFontSize),j=tS(e=>e.terminalTheme),N=tS(e=>e.setTerminalTheme),S=uJ(),C=uY(e.subscribeToPush,e.unsubscribeFromPush),T=uZ(e.busRef,e.connected),R=rX(e=>!1),E=T.supported,_="3.0.11",$=e.agentVersion,M=n9($,_)||n7($,_),P=!!e.codespaceInfo?.isCodespaces,A=(0,r.useMemo)(()=>e.hideActions||[],[e.hideActions]),z=!(window.matchMedia("(display-mode: standalone)").matches||window.ReactNativeWebView)&&!a,I=(0,r.useMemo)(()=>mu.filter(e=>"codespace"===e.id?P:"terminal"!==e.id||!A.includes("terminalSettings")),[P,A]),L=I.find(e=>e.id===m);(0,r.useEffect)(()=>{document.activeElement?.blur?.();let e=e=>{"Escape"!==e.key||f||(e.preventDefault(),e.stopPropagation(),i())};return window.addEventListener("keydown",e,!0),document.body.style.overflow="hidden",()=>{window.removeEventListener("keydown",e,!0),document.body.style.overflow=""}},[i,f]);let D=(0,r.useCallback)(e=>{(0,t7.e)(),i(),setTimeout(()=>e?.(),50)},[i]);return(0,n.jsxs)("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",children:[(0,n.jsx)("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-[2px] fade-in",onClick:i}),(0,n.jsxs)("div",{className:"relative w-full max-w-4xl h-[85vh] max-h-[640px] bg-surface border border-border rounded-brand-lg shadow-2xl flex overflow-hidden",role:"dialog","aria-modal":"true","aria-label":o("menu.settings"),onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:[(0,n.jsxs)("nav",{className:"w-52 flex-shrink-0 bg-bg/40 border-r border-border flex flex-col",children:[(0,n.jsx)("div",{className:"h-12 flex items-center px-4 border-b border-border",children:(0,n.jsx)("h2",{className:"text-base font-semibold text-text",children:o("menu.settings")})}),(0,n.jsx)("div",{className:"flex-1 overflow-y-auto p-2 space-y-0.5 modal-scrollable",children:I.map(e=>{let t=mx[e.icon],s=m===e.id;return(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),x(e.id)},className:`w-full px-3 py-2 rounded-brand text-left flex items-center gap-2.5 text-sm transition-colors ${s?"bg-brand-500/15 text-brand-500":"text-text-muted hover:bg-surface-2 hover:text-text"}`,children:[(0,n.jsx)(t,{size:16}),(0,n.jsx)("span",{children:o(e.labelKey)})]},e.id)})}),(0,n.jsxs)("div",{className:"px-4 py-3 border-t border-border flex items-center gap-2",children:["local"===e.connectionMode&&(0,n.jsx)("span",{className:"text-[10px] font-semibold px-1.5 py-0.5 rounded-full bg-green-500/15 text-green-400",children:"LAN"}),(0,n.jsxs)("p",{className:"text-text-muted text-xs truncate",children:[_,$?` / ${$}`:""]})]})]}),(0,n.jsxs)("div",{className:"flex-1 min-w-0 flex flex-col",children:[(0,n.jsxs)("div",{className:"h-12 flex items-center justify-between gap-2 pl-6 pr-3 border-b border-border",children:["install"===m?(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),x("general")},className:"-ml-2 px-2 py-1 text-sm font-medium text-text hover:bg-surface-2 rounded-brand transition-colors flex items-center gap-1.5",children:[(0,n.jsx)(t3.JG,{size:16}),o("pwa.title")]}):(0,n.jsx)("h3",{className:"text-sm font-medium text-text truncate",children:o(L?.labelKey||"menu.settings")}),(0,n.jsx)("button",{onClick:i,className:"p-1.5 text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-colors flex-shrink-0","aria-label":o("common.close"),children:(0,n.jsx)(t3.X,{size:18})})]}),(0,n.jsxs)("div",{className:`flex-1 overflow-y-auto modal-scrollable px-6 ${"background"===m?"py-4":"py-5"}`,children:["background"===m&&(0,n.jsx)(mm,{inline:!0,busRef:e.busRef}),"general"===m&&(0,n.jsxs)("div",{className:"space-y-6",children:[(0,n.jsx)(mh,{title:o("hosts.title"),children:(0,n.jsx)(mf,{icon:t3.ak,label:o("hosts.openHost"),onClick:()=>{(0,t7.e)(),i(),sX.getState().openOverlay()}})}),(C.supported||z)&&(0,n.jsxs)(mh,{children:[C.supported&&(0,n.jsx)(mb,{icon:t3.Ir,label:o("menu.notifications"),hint:o("menu.notificationsHint"),value:C.enabled,loading:C.loading,onChange:C.toggle}),z&&(0,n.jsx)(mf,{icon:t3.f5,label:o("menu.installApp"),badge:s?o("pwaGuide.installNow"):null,onClick:()=>s?D(l):x("install")})]}),(0,n.jsxs)(mh,{title:o("menu.reloadRestart"),children:[(0,n.jsx)(mf,{icon:t3.e9,iconClass:p?"animate-spin":"",label:o("menu.reload"),disabled:p,onClick:()=>{(0,t7.e)(),h(!0),setTimeout(()=>window.location.reload(),150)}}),t.onRestart&&(0,n.jsx)(mf,{icon:t3.kt,label:o("menu.restartHost"),onClick:()=>D(t.onRestart)})]}),t.onLogout&&(0,n.jsx)(mh,{title:o("menu.settingsAccount"),children:(0,n.jsx)(mf,{icon:t3.nU,label:o("menu.logout"),danger:!0,onClick:()=>D(t.onLogout)})}),M&&(0,n.jsx)(re,{agentVersion:$,webVersion:_})]}),"appearance"===m&&(0,n.jsxs)("div",{className:"space-y-6",children:[(0,n.jsx)(mh,{title:o("menu.theme"),children:(0,n.jsxs)("div",{className:"grid grid-cols-2 gap-2",children:[(0,n.jsx)(mv,{icon:t3.bd,label:o("menu.themeLight"),active:"light"===d,onClick:()=>{(0,t7.e)(),u("light")}}),(0,n.jsx)(mv,{icon:t3.AX,label:o("menu.themeDark"),active:"dark"===d,onClick:()=>{(0,t7.e)(),u("dark")}})]})}),(0,n.jsx)(mh,{title:o("menu.language"),children:(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),b(!0)},className:"w-full px-3 py-2 rounded-brand text-left flex items-center gap-2.5 text-sm text-text hover:bg-surface-2 transition-colors",children:[(0,n.jsx)(t3.qz,{size:16,className:"text-brand-500 flex-shrink-0"}),(0,n.jsx)("span",{className:"flex-1 min-w-0 truncate",children:o("menu.language")}),g&&(0,n.jsxs)("span",{className:"flex items-center gap-1.5 flex-shrink-0 text-text-muted",children:[(0,n.jsx)("img",{src:`https://flagcdn.com/w40/${g.country}.png`,alt:"",className:"w-[17px] h-[12px] object-cover rounded-[2px]",loading:"lazy"}),(0,n.jsx)("span",{className:"text-xs",children:g.label})]}),(0,n.jsx)(t3.c_,{size:15,className:"text-text-muted flex-shrink-0"})]})})]}),"terminal"===m&&(0,n.jsx)("div",{className:"space-y-6",children:(0,n.jsxs)(mh,{title:o("menu.terminalSettings"),children:[(0,n.jsx)(mg,{icon:t3.ZU,label:o("menu.fontSize"),children:(0,n.jsx)("select",{value:w??14,onChange:e=>{(0,t7.e)(),k(Number(e.target.value))},className:"bg-surface-2 text-text text-sm rounded-brand px-2 py-1 focus:outline-none focus:ring-2 focus:ring-brand-500/40",children:Array.from({length:9},(e,t)=>t+10).map(e=>(0,n.jsxs)("option",{value:e,children:[e,"px"]},e))})}),(0,n.jsx)(mg,{icon:t3.es,label:o("menu.terminalTheme"),children:(0,n.jsxs)("select",{value:j,onChange:e=>{(0,t7.e)(),N(e.target.value)},className:"bg-surface-2 text-text text-sm rounded-brand px-2 py-1 max-w-[220px] focus:outline-none focus:ring-2 focus:ring-brand-500/40",children:[(0,n.jsx)("option",{value:"default",children:"Vesper (Default)"}),ax.g4.filter(e=>e.mode===d).map(e=>(0,n.jsx)("option",{value:e.key,children:e.label},e.key))]})}),(0,n.jsx)(mb,{icon:t3.VA,label:o("menu.webgl"),hint:o("menu.webglHint"),value:v,onChange:y})]})}),"buttons"===m&&(0,n.jsx)("div",{className:"space-y-6",children:ec.map(({group:e,titleKey:t})=>(0,n.jsx)(mh,{title:o(t),children:S.buttons.filter(t=>t.group===e).map(e=>(0,n.jsx)(mb,{icon:uX[e.id],label:o(e.labelKey),value:S.isOn(e),onChange:()=>S.toggle(e)},e.id))},e))}),"mcp"===m&&(0,n.jsxs)("div",{className:"space-y-6",children:[(0,n.jsx)(u9,{}),E&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(mb,{icon:t3.jz,label:o("menu.artifactPanel"),hint:o("menu.artifactHint"),value:T.enabled,loading:T.loading,disabled:!e.connected,onChange:T.toggle}),(0,n.jsx)("p",{className:"text-[11px] leading-relaxed text-text-muted",children:o("menu.mcpRestartHint")})]})]}),"jarvis"===m&&(0,n.jsxs)("div",{className:"space-y-6",children:[(0,n.jsx)(mb,{icon:t3.cC,label:o("menu.jarvisToggle"),hint:o("menu.jarvisToggleHint"),value:R,onChange:e=>{rX.getState().setSettings({enabled:e}),e||rX.getState().setOpen(!1)}}),E&&!T.enabled&&(0,n.jsx)("p",{className:"text-[11px] leading-relaxed text-amber-400",children:o("menu.jarvisMcpOff")}),(0,n.jsx)(r3,{busRef:e.busRef})]}),"shortcuts"===m&&(0,n.jsx)("ul",{className:"flex flex-col divide-y divide-border-subtle/40",children:sZ.map(e=>(0,n.jsxs)("li",{className:"flex items-center justify-between gap-4 px-3 py-2 rounded-brand hover:bg-surface-2 first:pt-1",children:[(0,n.jsx)("span",{className:"text-sm text-text min-w-0 truncate",children:o(`shortcuts.${e.id}`)}),(0,n.jsx)("span",{className:"inline-flex items-center gap-1 flex-shrink-0",children:s4(e).map(e=>(0,n.jsx)("kbd",{className:s5,children:e},e))})]},e.id))}),"codespace"===m&&(0,n.jsx)(md,{codespaceInfo:e.codespaceInfo,busRef:e.busRef,onStop:()=>D(t.onStopCodespace)}),"install"===m&&(0,n.jsx)(ms,{})]})]})]}),(0,n.jsx)(mc.A,{isOpen:f,onClose:()=>b(!1)})]})}function mh({title:e,children:t}){return(0,n.jsxs)("section",{children:[e&&(0,n.jsx)("h4",{className:"text-[11px] font-semibold uppercase tracking-wider text-text-muted mb-2",children:e}),(0,n.jsx)("div",{className:"space-y-1",children:t})]})}function mf({icon:e,iconClass:t="",label:s,badge:r,danger:a,disabled:l,onClick:i}){return(0,n.jsxs)("button",{onClick:i,disabled:l,className:`w-full px-3 py-2 rounded-brand text-left flex items-center gap-2.5 text-sm transition-colors ${l?"text-text-muted cursor-not-allowed opacity-60":a?"text-text hover:bg-red-500/15 hover:text-red-400":"text-text hover:bg-surface-2"}`,children:[(0,n.jsx)(e,{size:16,className:`${a?"text-red-400":"text-brand-500"} ${t}`}),(0,n.jsx)("span",{className:"flex-1 min-w-0 truncate",children:s}),r&&(0,n.jsx)("span",{className:"flex-shrink-0 px-2 py-0.5 bg-brand-500 text-white text-xs font-medium rounded-full",children:r})]})}function mb({icon:e,label:t,hint:s,value:r,loading:a,disabled:l,onChange:i}){return(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),i(!r)},disabled:a||l,className:"w-full px-3 py-2 rounded-brand text-left flex items-center gap-2.5 text-sm text-text hover:bg-surface-2 transition-colors disabled:opacity-60",children:[(0,n.jsx)(e,{size:16,className:"text-brand-500 flex-shrink-0"}),(0,n.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,n.jsx)("span",{className:"block truncate",children:t}),s&&(0,n.jsx)("span",{className:"block text-xs text-text-muted truncate",children:s})]}),a?(0,n.jsx)(t3.kr,{size:16,className:"animate-spin text-text-muted"}):(0,n.jsx)("span",{className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors flex-shrink-0 ${r?"bg-brand-500":"bg-surface-2"}`,children:(0,n.jsx)("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${r?"translate-x-4":"translate-x-0.5"}`})})]})}function mg({icon:e,label:t,children:s}){return(0,n.jsxs)("div",{className:"w-full px-3 py-2 rounded-brand flex items-center gap-2.5 text-sm text-text",children:[(0,n.jsx)(e,{size:16,className:"text-brand-500 flex-shrink-0"}),(0,n.jsx)("span",{className:"flex-1 min-w-0 truncate",children:t}),s]})}function mv({icon:e,label:t,active:s,onClick:r}){return(0,n.jsxs)("button",{onClick:r,className:`px-3 py-3 rounded-brand flex items-center gap-2.5 text-sm border transition-colors ${s?"border-brand-500 bg-brand-500/10 text-brand-500":"border-border text-text hover:bg-surface-2"}`,children:[(0,n.jsx)(e,{size:16}),(0,n.jsx)("span",{children:t})]})}function my(){let e,t,{t:s,locale:a}=(0,se.s)(),{formattedStars:l}=(0,rL.w)(),i=uQ.dI.find(e=>e.code===a)||uQ.dI[0],o=si(e=>e.isOpen),c=si(e=>e.activePanel),d=si(e=>e.context),u=si(e=>e.callbacks),m=Q(e=>e.carrier),x=si(e=>e.close),p=si(e=>e.setActivePanel);si(e=>e.openMenu);let h=sT(e=>e.install),f=sT(e=>e.canInstall),b=sT(e=>e.isInstalled),[g,v]=(0,r.useState)(!1),[y,w]=(0,r.useState)(!1),[k,j]=(0,r.useState)(!1),[N,S]=(0,r.useState)(!1),{theme:C,toggleTheme:T}=(0,aT.D)(),[R,E]=(0,r.useState)(!1);(0,r.useEffect)(()=>{let e=()=>E(window.innerWidth>=760);return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),(0,r.useEffect)(()=>(o?document.body.style.overflow="hidden":document.body.style.overflow="",()=>{document.body.style.overflow=""}),[o]),(0,r.useEffect)(()=>{let e=e=>{"Escape"===e.key&&o&&x()};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[o,x]);let _=(0,r.useCallback)(()=>p("pwa"),[p]),$=(0,r.useCallback)(()=>p("codespace"),[p]),M=(0,r.useCallback)(()=>{(0,t7.e)(),p("menu")},[p]),P=(0,r.useCallback)(()=>{x(),u.onRemote?.()},[x,u]),A=(0,r.useCallback)(()=>{x(),u.onFiles?.()},[x,u]),z=(0,r.useCallback)(()=>{f?(x(),h()):_()},[f,x,h,_]),I=(0,r.useCallback)(()=>{$()},[$]),L=(0,r.useCallback)(()=>{x(),setTimeout(()=>{u.onLogout?.()},50)},[x,u]),D=(0,r.useCallback)(e=>{u.onThemeChange?.(e)},[u]),F=(0,r.useCallback)(()=>{x(),u.onStopCodespace?.()},[x,u]),O=(0,r.useCallback)(()=>{x(),setTimeout(()=>u.onUpdate?.(),50)},[x,u]),B=(0,r.useCallback)(()=>{x(),setTimeout(()=>u.onRestart?.(),50)},[x,u]);(0,r.useCallback)(()=>{x(),v(!0)},[x]);let W=(0,r.useCallback)(()=>{v(!1)},[]);(0,r.useCallback)(()=>{x(),w(!0)},[x]);let K=(0,r.useCallback)(()=>{w(!1)},[]),H=(0,r.useCallback)(()=>{x(),S(!0)},[x]),U=(0,r.useCallback)(()=>{S(!1)},[]),q=(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(ml,{isOpen:g,onClose:W}),(0,n.jsx)(mo,{isOpen:y,onClose:K}),(0,n.jsx)(mm,{isOpen:N,onClose:U,busRef:d.busRef})]});return o?R?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(mp,{context:d,callbacks:u,canInstall:f,isInstalled:b,install:h,onClose:x}),q]}):(0,n.jsxs)("div",{className:"fixed inset-0 z-50 flex",children:[(0,n.jsx)("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-[2px] fade-in",onClick:x}),(0,n.jsxs)("div",{className:"absolute top-0 right-0 bottom-0 w-[85vw] sm:w-96 max-w-md bg-surface border-l border-border shadow-2xl flex flex-col slide-in-right pt-[var(--safe-top)] pb-[var(--safe-bottom)]",onClick:e=>e.stopPropagation(),children:[(0,n.jsxs)("div",{className:"flex items-center justify-between px-5 py-4 border-b border-border flex-shrink-0",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2",children:["menu"!==c&&(0,n.jsx)("button",{onClick:M,className:"p-1 text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-colors mr-1","aria-label":s("common.back"),children:(0,n.jsx)(t3.JG,{size:20})}),(0,n.jsx)("h2",{className:"text-lg font-semibold text-text",children:(()=>{switch(c){case"pwa":return s("pwa.title");case"codespace":return s("codespace.title");default:return s("menu.title")}})()}),"menu"===c&&(t=(e=m||d.carrier)&&"ws"!==e,(0,n.jsx)("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider ${t?"bg-blue-500/15 text-blue-400 border border-blue-500/30":"bg-yellow-500/15 text-yellow-500 border border-yellow-500/30"}`,title:`Carrier: ${t?`WebRTC (${e})`:"WebSocket"}`,children:t?"RTC":"WS"}))]}),(0,n.jsxs)("div",{className:"flex items-center gap-1",children:["menu"===c&&(0,n.jsxs)(n.Fragment,{children:[rD.l7&&(0,n.jsxs)("a",{href:rD.rl,target:"_blank",rel:"noopener noreferrer",className:"px-2 py-1.5 text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-colors flex items-center gap-1.5 text-xs font-medium",title:"Star on GitHub","aria-label":"Star on GitHub",children:[(0,n.jsx)(t3.Cp,{size:16}),(0,n.jsx)(t3.FE,{size:13,className:"text-yellow-500 fill-yellow-500"}),l&&(0,n.jsx)("span",{className:"font-mono text-[11px] leading-none",children:l})]}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),T()},className:"p-2 text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-colors","aria-label":s("menu.theme"),title:s("menu.theme"),children:"dark"===C?(0,n.jsx)(t3.bd,{size:18}):(0,n.jsx)(t3.AX,{size:18})}),(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),j(!0)},className:"px-2 py-1.5 text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-colors flex items-center gap-1.5 text-sm font-medium","aria-label":s("menu.language"),title:s("menu.language"),children:[(0,n.jsx)("img",{src:`https://flagcdn.com/w40/${i.country}.png`,alt:i.label,className:"w-[17px] h-[12px] object-cover rounded-[2px]",loading:"lazy"}),(0,n.jsx)("span",{className:"uppercase",children:i.code})]})]}),(0,n.jsx)("button",{onClick:x,className:"p-2 text-text-muted hover:text-text hover:bg-surface-2 rounded-brand transition-colors","aria-label":s("common.close"),children:(0,n.jsx)(t3.X,{size:20})})]})]}),(0,n.jsxs)("div",{className:"flex-1 overflow-y-auto modal-scrollable",children:["menu"===c&&(0,n.jsx)(u7,{onRemote:d.remoteAvailable?P:null,onFiles:A,onInstallApp:z,canInstall:f,isInstalled:b,onCodespace:d.codespaceInfo?.isCodespaces?I:null,onLogout:L,connected:d.connected,remoteAvailable:d.remoteAvailable,codespaceInfo:d.codespaceInfo,showTheme:d.showTheme,theme:d.theme,onThemeChange:D,hideActions:d.hideActions||[],busRef:d.busRef,subscribeToPush:d.subscribeToPush,unsubscribeFromPush:d.unsubscribeFromPush,onUpdate:O,onRestart:B,onOpenBackgroundPicker:H}),"pwa"===c&&(0,n.jsx)(ms,{}),"codespace"===c&&(0,n.jsx)(md,{codespaceInfo:d.codespaceInfo,busRef:d.busRef,onStop:F})]})]}),(0,n.jsx)(ml,{isOpen:g,onClose:W}),(0,n.jsx)(mo,{isOpen:y,onClose:K}),(0,n.jsx)(mm,{isOpen:N,onClose:U,busRef:d.busRef}),(0,n.jsx)(mc.A,{isOpen:k,onClose:()=>j(!1)})]}):q}function mw({hydrated:e,apiKey:t}){let s,n;return!function(e){let t=(0,a.usePathname)(),s=(0,a.useSearchParams)(),n=(0,a.useRouter)(),{viewStack:l,pushView:i,setViewStack:o}=tS((0,tW.k)(e=>({viewStack:e.viewStack,pushView:e.pushView,setViewStack:e.setViewStack}))),c=l[l.length-1],d=eq.includes(c?.type)?l[l.length-2]:c,u=(0,r.useRef)(null),m=(0,r.useRef)(null),x=(0,r.useRef)(null);(0,r.useEffect)(()=>{if(!e)return;let n=eG(t,s);if(!n)return;let r=eJ(n);if(r===u.current||(u.current=r,d&&eJ(d)===r))return;x.current="url";let a=function(e,t){let s=eJ(t),n=e.findIndex(e=>eJ(e)===s);if(-1!==n)return e.slice(0,n+1);if("terminal"===t.type&&e[e.length-1]?.type==="terminal"){let s=[...e];return s[s.length-1]=t,s}return null}(l,n);a?o(a):i(n)},[e,t,s]),(0,r.useEffect)(()=>{if(!e||eq.includes(c?.type))return;let r=eJ(c);if(r===u.current)return;let a=eJ(eG(t,s)),i="url"===x.current;i&&(x.current=null);let o=m.current?.type==="terminal"&&c?.type==="terminal",d=c?.type==="list"&&1===l.length;x.current="store",u.current=r,m.current=c,i||r===a||(o||d?n.replace(r):n.push(r))},[e,c,t,s])}(e),s=(0,a.usePathname)(),n=(0,a.useSearchParams)(),(0,r.useEffect)(()=>{if(!t||!s?.startsWith("/workspace"))return;let e=function(e,t){if(!e)return"";let s=t?.toString();return s?`${e}?${s}`:e}(s,n);e&&dw(t,e)},[t,s,n]),null}function mk({children:e}){let t,s,c,d,u,m,x,p,h,b,y,w,k,j,{t:N}=(0,se.s)(),[S,C]=(0,r.useState)(!1);(0,r.useEffect)(()=>{!function(){if(sR)return;sR=!0;let e=sT.getState();(window.addEventListener("beforeinstallprompt",e=>{e.preventDefault(),sT.getState().setDeferredPrompt(e)}),window.addEventListener("appinstalled",()=>{sT.getState().setDeferredPrompt(null),sT.getState().setIsInstalled(!0)}),window.matchMedia("(display-mode: standalone)").matches)?e.setIsInstalled(!0):navigator.getInstalledRelatedApps&&navigator.getInstalledRelatedApps().then(t=>{t?.length&&e.setIsInstalled(!0)}).catch(()=>{})}()},[]);let{viewStack:T,openedSessions:R,pushView:E,popView:_,setViewStack:$,addOpenedSession:A,removeOpenedSession:z,reorderOpenedSessions:I,activeWorkspaceId:L,setActiveWorkspaceId:D,livePanes:F,touchLivePane:O,mountedWorkspaces:B,markWorkspaceMounted:W,reset:K,cwdBySession:H,sidebarCollapsed:U,toggleSidebar:q,sidebarWidth:V,setSidebarWidth:X,paneWidths:G,setPaneWidth:J,rightPanelOpen:Z,rightPanelTabs:es,rightPanelWidth:en,toggleRightPanel:er,setRightPanelTab:ea,setRightPanelWidth:el,editorFilePath:ei,editorPanelWidth:eo,setEditorPanelWidth:ec,openEditorFile:ed,closeEditorFile:eu,editorPreviewSeq:em,mobileOpen:ex,mobileMode:ep,mobilePanelWidth:eh,setMobileOpen:ef,setMobileMode:eb,setMobilePanelWidth:eg,setMobileSession:ey,artifactTitle:ew,pushArtifact:ek,removeArtifact:ej}=tS((0,tW.k)(e=>({viewStack:e.viewStack,openedSessions:e.openedSessions,pushView:e.pushView,popView:e.popView,setViewStack:e.setViewStack,addOpenedSession:e.addOpenedSession,removeOpenedSession:e.removeOpenedSession,reorderOpenedSessions:e.reorderOpenedSessions,activeWorkspaceId:e.activeWorkspaceId,setActiveWorkspaceId:e.setActiveWorkspaceId,livePanes:e.livePanes,touchLivePane:e.touchLivePane,mountedWorkspaces:e.mountedWorkspaces,markWorkspaceMounted:e.markWorkspaceMounted,reset:e.reset,cwdBySession:e.cwdBySession,sidebarCollapsed:e.sidebarCollapsed,toggleSidebar:e.toggleSidebar,sidebarWidth:e.sidebarWidth,setSidebarWidth:e.setSidebarWidth,paneWidths:e.paneWidths,setPaneWidth:e.setPaneWidth,rightPanelOpen:e.rightPanelOpen,rightPanelTabs:e.rightPanelTabs,rightPanelWidth:e.rightPanelWidth,toggleRightPanel:e.toggleRightPanel,setRightPanelTab:e.setRightPanelTab,setRightPanelWidth:e.setRightPanelWidth,editorFilePath:e.editorFilePath,editorPanelWidth:e.editorPanelWidth,setEditorPanelWidth:e.setEditorPanelWidth,openEditorFile:e.openEditorFile,closeEditorFile:e.closeEditorFile,editorPreviewSeq:e.editorPreviewSeq,mobileOpen:e.mobileOpen,mobileMode:e.mobileMode,mobilePanelWidth:e.mobilePanelWidth,setMobileOpen:e.setMobileOpen,setMobileMode:e.setMobileMode,setMobilePanelWidth:e.setMobilePanelWidth,setMobileSession:e.setMobileSession,artifactTitle:e.artifactTitle,pushArtifact:e.pushArtifact,removeArtifact:e.removeArtifact}))),eN=(0,a.useRouter)(),{getAuth:eS,setAuth:eC}=(0,l.F)(),[eT,eR]=(0,r.useState)(()=>eS());(0,r.useEffect)(()=>{C(!0),!eT?.apiKey&&(0,ee._r)()&&window.location.port===String(f._8)&&fetch(f.Go).then(e=>e.ok?e.json():null).then(e=>{if(e?.permanentKey){let t=e.permanentKey,s=(0,et.Uo)(t),n=(0,et.Cj)(t);(0,M.LG)(s,{tail:n});let r={apiKey:s,tunnelUrl:window.location.origin,mode:"local",tempKey:null,localIp:null};eC(r),eR(r)}}).catch(()=>{})},[eT,eC]),(0,r.useEffect)(()=>{if(!window.__TAURI__)return;let e=e=>{("F5"===e.key||(e.metaKey||e.ctrlKey)&&"r"===e.key.toLowerCase())&&(e.preventDefault(),window.location.reload())},t=e=>{let t=e.target?.tagName;"INPUT"===t||"TEXTAREA"===t||e.target?.isContentEditable||e.preventDefault()};return window.addEventListener("keydown",e),window.addEventListener("contextmenu",t),()=>{window.removeEventListener("keydown",e),window.removeEventListener("contextmenu",t)}},[]);let{bus:eE,busRef:e_,protocolRef:e$,connected:eM,connectionMode:eP,carrier:eA,sessions:ez,remoteAvailable:eI,mobileAvailable:eL,codespaceInfo:eD,codespaceDisconnected:eF,codespaceStopping:eO,platform:eB,agentVersion:eW,updateAvailable:eK,canSelfUpdate:eH,triggerUpdate:eU,triggerRestart:eq,retryStatus:eV,approvalStatus:eX,admitted:eG,loadSessions:eY,createSession:eZ,deleteSession:e1,renameSession:e5,stopCodespace:e3,workspaces:e4,createWorkspace:e6,renameWorkspace:e8,deleteWorkspace:e9,setWorkspaceHiddenRepos:e7,reorderSession:te}=function(){let[e,t]=(0,r.useState)([]),[s,n]=(0,r.useState)([]),[c,d]=(0,r.useState)(!1),[u,m]=(0,r.useState)(!1),[x,p]=(0,r.useState)(null),[h,b]=(0,r.useState)(!1),[y,w]=(0,r.useState)(null),[k,j]=(0,r.useState)(null),[N,S]=(0,r.useState)(null),[C,T]=(0,r.useState)(!1),[R,E]=(0,r.useState)(null),[_,$]=(0,r.useState)(!1),{getAuth:A}=(0,l.F)(),z=(0,r.useCallback)(e=>{E(t=>e===o.J2.reconnect?t===o.J2.approved?null:t:t===o.J2.approved&&e===o.J2.pending?t:e)},[]),I=(0,r.useCallback)(async()=>{let e=A();if(e?.tempKey)try{await fetch(`${f.O}/api/temp-key/remove`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({tempKey:e.tempKey})}),sessionStorage.removeItem("tempKey")}catch(e){console.error("Failed to remove temp key:",e)}},[A]),L=(0,r.useCallback)(e=>{x?.isCodespaces&&b(!0)},[x]),[D,F]=(0,r.useState)(!1),O=(0,r.useCallback)(()=>{F(!0)},[]),B=(0,r.useRef)(null),W=(0,r.useRef)({sessions:!1,workspaces:!1}),K=e=>{W.current[e]=!0},H=(0,r.useCallback)(e=>{(0,v.Lq)("switch",`lists untrusted (${e}) → refetch`),W.current={sessions:!1,workspaces:!1}},[]),U=(0,r.useCallback)(e=>{if(Array.isArray(e)){for(let t of(K("sessions"),e))t?.id&&t?.agent&&tS.getState().setSessionAgent(t.id,t.agent);t(t=>tO(t,e)?t:e)}},[]),q=(0,r.useCallback)(e=>{Array.isArray(e)&&(K("workspaces"),n(t=>tO(t,e)?t:e))},[]),V=(0,r.useRef)(0),X=(0,r.useRef)(0),G=(0,r.useRef)(null),J=(0,r.useRef)(0),Z=(0,r.useCallback)(e=>{let t=++V.current;e.emit("getSessions",e=>{(0,v.Lq)("diag",`getSessions ack seq=${t} type=${Array.isArray(e)?"list":typeof e} n=${Array.isArray(e)?e.length:"-"}`),t===V.current&&U(e)})},[U]),es=(0,r.useCallback)(e=>{let t=++X.current;e.emit("getWorkspaces",e=>{t===X.current&&q(e)})},[q]),en=(0,r.useCallback)((e,t=!1)=>{if(e){if(t)clearTimeout(G.current);else if(G.current)return;else if(Date.now()-J.current<1e3)return;G.current=setTimeout(()=>{G.current=null,J.current=Date.now(),(0,v.Lq)("diag",`fetchLists FIRE (bus=${e?"ok":"null"} connected-already=${W.current.sessions}/${W.current.workspaces})`),es(e),Z(e)},120)}},[Z,es]),er={fragOut:!0,binOut:!0,hb:1,env2:1,fragCtl:1},ea=e=>{(0,v.Lq)("switch",`caps → ${JSON.stringify(er)} announced`),e.emit("caps",er)},el=(0,r.useRef)(null),{bus:ei,busRef:eo,protocolRef:ec,connected:ed,connectionMode:eu,carrier:em,retryStatus:ex,disconnect:ep}=function(e={}){let{namespace:t="",socketOptions:s={},redirectOnNoAuth:n="/",onConnect:o,onDisconnect:c,onApproval:d}=e,u=(0,a.useRouter)(),{getAuth:m,setAuth:x}=(0,l.F)(),p=function(){let[e]=(0,r.useState)(()=>{let e=localStorage.getItem(i);return e||(e=globalThis.crypto?.randomUUID?.()??`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,localStorage.setItem(i,e)),e});return e}(),h=(0,r.useRef)(null),b=(0,r.useRef)(null),[v,y]=(0,r.useState)(!1),[w,k]=(0,r.useState)("tunnel"),[j,N]=(0,r.useState)("ws"),[S,C]=(0,r.useState)({isRetrying:!1,attempt:0,maxAttempts:10,failed:!1});return(0,r.useEffect)(()=>{let e=!1,r=null;return(async()=>{let a=m();if((0,ee._r)()&&window.location.port===String(f._8)&&a?.tunnelUrl!==window.location.origin)try{let e=await fetch(f.Go),t=e.ok?await e.json():null;if(e.ok&&t?.permanentKey){let e=t.permanentKey,s=(0,et.Uo)(e),n=(0,et.Cj)(e);(0,M.LG)(s,{tail:n}),a={apiKey:s,tunnelUrl:window.location.origin,mode:"local",tempKey:null,localIp:t.localIp||null},x(a)}}catch{}if(e)return;if(!a?.apiKey)return u.push(n);let l={tunnelUrl:a.tunnelUrl,localIp:a.localIp||null,namespace:t,socketOptions:{...s,auth:{apiKey:a.apiKey,tempKey:a.tempKey??null,deviceId:p,...s.auth}},apiKey:a.apiKey,deviceId:p,tempKey:a.tempKey??null,onConnect:(t,s)=>{if(e)return;h.current=t;let n=s||b.current?.connectionMode||"tunnel";y(!0),k(n),Q.getState().setConnection({bus:t,connected:!0,connectionMode:n,endpoint:a.tunnelUrl}),(0,g.c)("transport","[transport] ws connected"),o?.(t,a)},onDisconnect:t=>{e||((0,g.c)("transport",`[transport] ws disconnect reason=${t}`),h.current=null,y(!1),Q.getState().setConnection({connected:!1}),c?.(t))},onApproval:d,onRetryStatus:t=>{e||(C(t),Q.getState().setRetryStatus(t))}},i=a.tunnelUrl===window.location.origin;b.current=r=new Y(l,P.eR.enableWebRTC&&!i?{enableWebRTC:!0,enableTurn:P.eR.enableTurn,apiKey:a.apiKey,onUpgrade:e=>(0,g.c)("transport",`[transport] upgraded to ${e}`),onFallback:e=>(0,g.c)("transport",`[transport] fallback to ${e}`),onTransportChange:t=>{e||(N(t),Q.getState().setCarrier(t),(0,g.c)("transport",`[transport] active=${t}`))}}:null),h.current=r.busRef.current,Q.getState().setConnection({bus:h.current,busRef:h,protocolRef:b,connected:!1,connectionMode:"tunnel",carrier:"ws"}),r.connect()})(),()=>{e=!0,r?.disconnect(),b.current=null,h.current=null,Q.getState().reset()}},[]),{bus:h.current,busRef:h,protocolRef:b,connected:v,connectionMode:w,carrier:j,retryStatus:S,disconnect:()=>{b.current?.disconnect(),b.current=null,h.current=null,y(!1),Q.getState().reset()}}}({namespace:"",redirectOnNoAuth:"/",onConnect:(0,r.useCallback)((e,s)=>{(z(o.J2.reconnect),H("pm-connect"),el.current===e)?en(e):(el.current=e,e.on("device:pendingApproval",()=>{(0,v.Lq)("diag","EVENT device:pendingApproval arrived"),(0,g.c)("auth","[auth] agent says: waiting for host approval"),z(o.J2.pending)}),e.on("device:approved",()=>{(0,v.Lq)("diag","EVENT device:approved arrived → applying"),z(o.J2.approved),$(!0),(0,M.I8)(),I()}),e.on("terminal:ready",()=>{(0,g.c)("auth","[auth] terminal:ready (NOT an admission signal)"),en(e)}),e.on("connect",()=>{H("carrier-connect"),e.emit("device:clientReady"),ea(e),en(e)}),e.on("device:rejected",()=>{(0,v.Lq)("diag","EVENT device:rejected arrived → applying"),z(o.J2.rejected),B.current?.()}),e.on("device:tailRejected",e=>{if(e?.reason===o.ML.sealUnreadable)return;B.current?.();let t=A();(0,M.cH)(t?.apiKey),(0,M.cH)(t?.tempKey),sessionStorage.clear(),sessionStorage.setItem(o.Jd,e?.reason||o.ML.mismatch),window.location.replace("/login")}),e.on("serverInfo",e=>{if(d(e.remoteAvailable),m(!!e.mobileAvailable),w(e.platform),j(e.version||null),S(e.updateAvailable||null),T(!!e.canSelfUpdate),tS.getState().setAgentCaps(e.caps||{}),tS.getState().setArtifactEnabled(e.artifactEnabled),tS.getState().setMcpClients(e.mcpClients),e.voiceConfig)tD.getState().syncFromAgent(e.voiceConfig);else{let e=tD.getState();(e.geminiKeys.some(e=>e.trim())||e.openrouterKey||e.customKey||e.customEndpoint)&&e.pushToAgent()}e.isCodespaces&&p({isCodespaces:e.isCodespaces,codespaceName:e.codespaceName})}),e.on("sessionClosed",e=>{t(t=>t.filter(t=>t.id!==e)),tS.getState().closeSession(e)}),e.on("session-renamed",({sessionId:e,name:s}={})=>{e&&t(t=>t.map(t=>t.id===e?{...t,name:s}:t))}),e.on("sessionAgentChanged",({sessionId:e,agent:t}={})=>{e&&t&&(tS.getState().setSessionAgent(e,t),tS.getState().invalidateAgentHistory())}),e.on("sessionsChanged",()=>en(e,!0)),e.on("workspacesChanged",()=>en(e)),e.on("codespace:stopping",O),ea(e),e.emit("device:clientReady"))},[I,O,en,z,A,H]),onDisconnect:L,onApproval:z});(0,r.useEffect)(()=>{B.current=ep},[ep]);let eh=(0,r.useCallback)(()=>en(eo.current),[eo,en]),ef=(0,r.useCallback)(()=>en(eo.current,!0),[eo,en]);(0,r.useEffect)(()=>()=>{G.current&&(clearTimeout(G.current),G.current=null)},[]),(0,r.useEffect)(()=>{if(!ed)return;let e=setInterval(()=>{W.current.sessions&&W.current.workspaces||((0,v.Lq)("diag",`list-retry tick: connected but not loaded (sessions=${W.current.sessions} workspaces=${W.current.workspaces}) — refetching`),eh())},2e3);return()=>clearInterval(e)},[ed,eh]),(0,r.useEffect)(()=>{if(!ed)return;let e=()=>{"visible"===document.visibilityState&&eh()};return e(),document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)},[ed,eh]);let eb=(0,r.useCallback)((e,n,r,a,l,i=!1,o=null,c=null)=>{if(!eo.current)return;"function"==typeof n?(l=n,n=null,r=null,a=null):"function"==typeof r?(l=r,r=null,a=null):"function"==typeof a&&(l=a,a=null);let d="string"==typeof o?o:o?.id||null;eo.current.emit("createSession",{name:e,shellId:n,workspaceId:r,cwd:a,nameIsAuto:i,agent:d,replaces:c},i=>{if(i?.success){if(i.sessionId){d&&tS.getState().setSessionAgent(i.sessionId,d);let l=s.find(e=>e.id===r)?.path||null;t(t=>[...t.filter(e=>e.id!==i.sessionId&&e.id!==i.replaced),{id:i.sessionId,name:i.name||e||"Terminal",createdAt:Date.now(),cwd:i.cwd||a||null,workspaceId:r||null,groupId:r||null,workspacePath:l,shellId:i.shellId||n||null,shellLabel:i.shellLabel||null,agent:d||null}])}ef()}l?.(i)})},[eo,ef,s]),eg=(0,r.useCallback)((e,t,s)=>{"function"==typeof t&&(s=t,t=null),eo.current?.emit("createWorkspace",{name:e,path:t},e=>{e?.success&&ef(),s?.(e)})},[eo,ef]),ev=(0,r.useCallback)((e,t,s)=>{eo.current?.emit("renameWorkspace",{workspaceId:e,name:t},e=>{e?.success&&ef(),s?.(e)})},[eo,ef]),ey=(0,r.useCallback)((e,t)=>{eo.current?.emit("deleteWorkspace",{workspaceId:e},e=>{e?.success&&ef(),t?.(e)})},[eo,ef]),ew=(0,r.useCallback)((e,t,s)=>{eo.current?.emit("setWorkspaceHiddenRepos",{workspaceId:e,paths:t},e=>{e?.success&&ef(),s?.(e)})},[eo,ef]),ek=(0,r.useCallback)((e,t,s)=>{eo.current?.emit("moveSession",{sessionId:e,workspaceId:t},e=>{e?.success&&ef(),s?.(e)})},[eo,ef]),ej=(0,r.useCallback)((e,t)=>{eo.current?.emit("reorderSession",{orderedIds:e},e=>{e?.success&&ef(),t?.(e)})},[eo,ef]),eN=(0,r.useCallback)(e=>{eo.current&&eo.current.emit("getShells",t=>e?.(t))},[eo]),eS=(0,r.useCallback)((e,t)=>{eo.current&&eo.current.emit("deleteSession",e,e=>{e.success&&ef(),t?.(e)})},[eo,ef]),eC=(0,r.useCallback)((e,t,s)=>{eo.current&&eo.current.emit("renameSession",{sessionId:e,name:t},e=>{e.success&&ef(),s?.(e)})},[eo,ef]),eT=(0,r.useCallback)(async()=>{let e=A();if(!e?.tunnelUrl||!x?.isCodespaces)return!1;try{return(await fetch(`${e.tunnelUrl}/api/codespace/stop`,{method:"POST"})).ok}catch{return!1}},[A,x]),eR=(0,r.useCallback)(()=>{let e=eo.current;return!!e?.connected&&(ec.current?.setUpdating?.(!0),e.emit("requestUpdate"),!0)},[eo,ec]),eE=(0,r.useCallback)(()=>{let e=eo.current;return!!e?.connected&&(ec.current?.setUpdating?.(!0),e.emit("requestRestart"),!0)},[eo,ec]);return{bus:ei,busRef:eo,protocolRef:ec,connected:ed,connectionMode:eu,carrier:em,retryStatus:ex,approvalStatus:R,admitted:_,sessions:e,remoteAvailable:c,mobileAvailable:u,codespaceInfo:x,codespaceDisconnected:h,codespaceStopping:D,platform:y,agentVersion:k,updateAvailable:N,canSelfUpdate:C,triggerUpdate:eR,triggerRestart:eE,workspaces:s,loadSessions:eh,createSession:eb,getShells:eN,deleteSession:eS,renameSession:eC,createWorkspace:eg,renameWorkspace:ev,deleteWorkspace:ey,setWorkspaceHiddenRepos:ew,moveSession:ek,reorderSession:ej,stopCodespace:eT}}(),{loadKeys:tt,renameKey:ts,removeKey:tn}=(0,aA.u)(),[tr,ta]=(0,r.useState)([]);(0,r.useEffect)(()=>{S&&ta(tt())},[S,tt]);let tl=eT?.apiKey?(0,et.Uo)(eT.apiKey):"",ti=tr.length>=2,to=sX(e=>e.focus),tc=sX(e=>e.overlayOpen);(0,r.useEffect)(()=>{if(S){if(!tl)return void sX.getState().closeAll();sX.getState().sync(tr,tl)}},[S,tr,tl]);let td=sX(e=>e.hosts),tm=(0,r.useMemo)(()=>(function(e,t){let s={sessions:[],workspaces:[]};if(!t)return s;for(let n of e){if(n.key===t)continue;let e=`${n.key}:`,r=`${e}_`,a=(n.sessions||[]).some(e=>null==e.workspaceId);for(let t of n.workspaces||[])s.workspaces.push({...t,id:e+t.id,hostKey:n.key});for(let t of(a&&s.workspaces.push({id:r,name:n.label||n.key,hostKey:n.key}),n.sessions||[]))s.sessions.push({...t,workspaceId:null!=t.workspaceId?e+t.workspaceId:r,hostKey:n.key})}return s})(Object.values(td),tl),[td,tl]),tp=(0,r.useMemo)(()=>[...ez,...tm.sessions],[ez,tm]),th=(0,r.useMemo)(()=>[...e4,...tm.workspaces],[e4,tm]),tf=to!==tl&&(ti||""===to),tb=(0,r.useCallback)((e,t)=>{let s=tt().find(t=>(0,et.Uo)(t.key)===e);s&&(ts(s.id,t),ta(tt()))},[tt,ts]),tg=(0,r.useCallback)(e=>{let t=tt().find(t=>(0,et.Uo)(t.key)===e);t&&(tn(t.id),ta(tt()))},[tt,tn]),[tv,ty]=(0,r.useState)([]),{updating:tw,updateMode:tk,resumeGrace:tj,doUpdate:tN,doRestart:tC}=function({connected:e,triggerUpdate:t,triggerRestart:s}){let[n,a]=(0,r.useState)(!1),[l,i]=(0,r.useState)("update"),[o,c]=(0,r.useState)(!1),d=(0,r.useRef)(null);(0,r.useEffect)(()=>{let e=()=>{"visible"===document.visibilityState&&(c(!0),clearTimeout(d.current),d.current=setTimeout(()=>c(!1),4e3))};return document.addEventListener("visibilitychange",e),()=>{document.removeEventListener("visibilitychange",e),clearTimeout(d.current)}},[]);let u=(0,r.useCallback)(()=>{t()&&(i("update"),a(!0))},[t]),m=(0,r.useRef)(e);return(0,r.useEffect)(()=>{n&&e&&!m.current&&a(!1),m.current=e},[e,n]),{updating:n,updateMode:l,resumeGrace:o,doUpdate:u,doRestart:(0,r.useCallback)(()=>{s()},[s])}}({connected:eM,triggerUpdate:eU,triggerRestart:eq}),[tT,tR]=(0,r.useState)({isOpen:!1,title:"",message:"",onConfirm:null,confirmText:null}),tE=(0,r.useCallback)(()=>{tR({isOpen:!0,title:N("menu.updateConfirmTitle"),message:N("menu.updateConfirmMessage"),onConfirm:tN})},[tN,N]),t_=(0,r.useCallback)(()=>{tR({isOpen:!0,title:N("menu.restartConfirmTitle"),message:N("menu.restartConfirmMessage"),onConfirm:tC})},[tC,N]);(0,r.useEffect)(()=>{eM&&("win32"===eB?ty([{id:"cmd",label:"Command Prompt"},{id:"powershell",label:"PowerShell"}]):ty([]))},[eM,eB]);let t$=t5();!function({busRef:e,connected:t,enabled:s}){let n=tS(e=>e.setMobileDeviceCount),a=tS(e=>e.setMobileAvailable);(0,r.useEffect)(()=>{let r=e?.current;if(!r||!t||!s)return;let l=({count:e,available:t})=>{n(e),"boolean"==typeof t&&a(t)};return r.on("mobile:devicesChanged",l),r.emit("mobile:deviceCount",{},e=>{e&&"number"==typeof e.count&&n(e.count),e&&"boolean"==typeof e.available&&a(e.available)}),()=>{r.off("mobile:devicesChanged",l),n(0),a(!1)}},[e,t,s,n,a])}({busRef:e_,connected:eM,enabled:eL}),t=(0,r.useRef)(""),(0,r.useEffect)(()=>{if(!eM)return;let e=e_?.current;if(!e)return;let s=async({text:e,origin:s})=>{if("web"!==s&&"string"==typeof e&&e!==t.current){t.current=e;try{await navigator.clipboard?.writeText(e)}catch{}}},n=()=>{let s=window.getSelection?.(),n=s?.toString?.()??"";n&&n!==t.current&&(t.current=n,e.emit("clipboard:set",{text:n,origin:"web"}))};return e.on("clipboard:sync",s),document.addEventListener("copy",n),document.addEventListener("cut",n),()=>{e.off("clipboard:sync",s),document.removeEventListener("copy",n),document.removeEventListener("cut",n)}},[e_,eM]);let{subscribeToPush:tM,unsubscribeFromPush:tP,notifications:tA}=(s=(0,r.useRef)(null),c=sc(e=>e.notifications),tS(e=>e.getSelectedSession),tS(e=>e.getCurrentView),d=tS(e=>e.pushView),u=tS(e=>e.addOpenedSession),m=!!window.ReactNativeWebView,(0,r.useEffect)(()=>(window.handleNotificationTap=e=>{let t=e?.sessionId;t&&(u(t),d({type:"terminal",sessionId:t}))},()=>{try{delete window.handleNotificationTap}catch(e){window.handleNotificationTap=void 0}}),[d,u]),(0,r.useEffect)(()=>{if(m)return window.handleAppStateChange=e=>{e_?.current?.emit("visibilityChange",!!e)},()=>{try{delete window.handleAppStateChange}catch(e){window.handleAppStateChange=void 0}}},[e_,m]),x=(0,r.useCallback)(async()=>{if(e_?.current){if(localStorage.removeItem(sx),m){window.handleExpoPushToken=e=>{e_.current?.emit("pushSubscribe",{type:"expo",token:e}),s.current={type:"expo",token:e}},window.ReactNativeWebView.postMessage(JSON.stringify({type:"REQUEST_PUSH_TOKEN"}));return}if(!("serviceWorker"in navigator)||!("PushManager"in window))return void console.warn("\uD83D\uDD15 Push not supported");try{let e=await Notification.requestPermission();if("granted"!==e)return;let t=await navigator.serviceWorker.ready;if(!t.pushManager)return;let n=await new Promise(e=>e_.current.emit("getVapidKey",e));if(!n)return;let r=await t.pushManager.getSubscription();r||(r=await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:n})),e_.current.emit("pushSubscribe",r.toJSON()),e_.current.emit("visibilityChange",document.hidden),s.current=r}catch(e){console.error("Push notification setup failed:",e)}}},[e_,m]),(0,r.useEffect)(()=>{let e=e_?.current;if(e&&eM&&"1"!==localStorage.getItem(sx)){if(m){window.handleExpoPushToken=t=>{e.emit("pushSubscribe",{type:"expo",token:t}),s.current={type:"expo",token:t}},window.ReactNativeWebView.postMessage(JSON.stringify({type:"REQUEST_PUSH_TOKEN"}));return}(async()=>{try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return;let t=await navigator.serviceWorker.ready;if(!t.pushManager)return;let s=await t.pushManager.getSubscription();if(!s&&"granted"===Notification.permission){let n=await new Promise(t=>e.emit("getVapidKey",t));n&&(s=await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:n}))}s&&(e.emit("pushSubscribe",s.toJSON()),e.emit("visibilityChange",document.hidden))}catch(e){}})()}},[e_,eM,m]),(0,r.useEffect)(()=>{let e=e_?.current;if(!e||!eM)return;let t=()=>{e.emit("getStatusState"),e.emit("getNotificationState")},s=e=>sc.getState().handleStatusState(e),n=e=>{if(sc.getState().handleStatusChange(e),e&&("done"===e.state||"blocked"===e.state)){let t="done"===e.state,s=e.tool?e.tool.charAt(0).toUpperCase()+e.tool.slice(1):"Terminal",n=t?`${s} \xb7 your turn`:`${s} needs input`;window.__9R_DESKTOP__?.showNotification&&window.__9R_DESKTOP__.showNotification(n,t?"The agent finished its turn and is waiting for you":"Action required to proceed")}},r=e=>sc.getState().handleStatusCleared(e),a=e=>sc.getState().handleNotificationState(e),l=()=>t(),i=()=>{e.emit("visibilityChange",document.hidden)},o=()=>t();return e.on("notificationState",a),e.on("notificationCleared",l),e.on("statusState",s),e.on("statusChange",n),e.on("statusCleared",r),e.on("connect",o),document.addEventListener("visibilitychange",i),t(),()=>{e.off("notificationState",a),e.off("notificationCleared",l),e.off("statusState",s),e.off("statusChange",n),e.off("statusCleared",r),e.off("connect",o),document.removeEventListener("visibilitychange",i)}},[e_,eM]),p=sc(e=>e.sessionStatus),h=(0,r.useMemo)(()=>sm(p).total,[p]),(0,r.useEffect)(()=>{window.__9R_DESKTOP__?.setBadge&&window.__9R_DESKTOP__.setBadge(h),"u">typeof navigator&&"setAppBadge"in navigator&&(h>0?navigator.setAppBadge(h).catch(()=>{}):navigator.clearAppBadge().catch(()=>{}))},[h]),{subscribeToPush:x,unsubscribeFromPush:(0,r.useCallback)(async()=>{localStorage.setItem(sx,"1");try{if(s.current?.type==="expo"){e_.current?.emit("pushUnsubscribe",s.current.token),s.current=null;return}if(s.current)await s.current.unsubscribe(),e_.current?.emit("pushUnsubscribe",s.current.endpoint),s.current=null;else{let e=await navigator.serviceWorker.ready,t=await e.pushManager.getSubscription();t&&(e_.current?.emit("pushUnsubscribe",t.endpoint),await t.unsubscribe())}}catch(e){console.error("Push unsubscribe failed:",e)}},[e_]),notifications:c}),tz=tK(e=>e.setKeyboardOpen),[tI,tL]=(0,r.useState)(()=>window.innerWidth>=760),tF=(b=(0,r.useRef)(null),(0,r.useCallback)(({enabled:e,sessionIds:t,activeSessionId:s,onSwitch:n})=>({onTouchStart:t=>{if(!e||1!==t.touches.length||function(e,t=e=>"function"==typeof getComputedStyle?getComputedStyle(e).overflowX:""){for(let s=e;s&&1===s.nodeType;s=s.parentElement){let e=t(s);if(("auto"===e||"scroll"===e)&&s.scrollWidth>s.clientWidth)return!0}return!1}(t.target))return b.current=null;let s=t.touches[0];b.current={x:s.clientX,y:s.clientY,time:performance.now()}},onTouchEnd:r=>{let a=b.current;if(b.current=null,!a||!e||t.length<2)return;let l=r.changedTouches[0],i=l.clientX-a.x,o=l.clientY-a.y;if(performance.now()-a.time>500||60>Math.abs(i)||Math.abs(i)<1.5*Math.abs(o))return;let c=t.indexOf(s);if(-1===c)return;let d=i<0?t[c+1]:t[c-1];d&&d!==s&&n?.(d)}}),[]));(0,r.useEffect)(()=>{let e=0,t=()=>{clearTimeout(e),e=setTimeout(()=>tL(window.innerWidth>=760),50)};return window.addEventListener("resize",t),()=>{clearTimeout(e),window.removeEventListener("resize",t)}},[]);let tB=T[T.length-1]||{type:"list"},tH=tB?.type==="terminal"||tI&&tB?.type==="list",tU=tB?.type==="terminal"?tB.sessionId:tH&&R[R.length-1]||null,tq=function({isDesktop:e,isTerminalView:t,activeSessionId:s,currentView:n,openedSessions:a}){let l=(0,r.useRef)({}),i=(0,r.useRef)({}),o=(0,r.useRef)(null),c=(0,r.useRef)(null),d=(0,r.useRef)(!1),u=(0,r.useRef)(null),m=(0,r.useCallback)((t,s)=>{s?(l.current[t]=s,u.current===t&&e&&!d.current&&(u.current=null,setTimeout(()=>s.focus?.(),50))):delete l.current[t]},[e]),x=(0,r.useCallback)((e,t)=>{t?i.current[e]=t:delete i.current[e]},[]),p=(0,r.useCallback)(t=>{c.current=t,t&&u.current&&e&&d.current&&(u.current=null,setTimeout(()=>t.focus?.(),50))},[e]),h=(0,r.useCallback)(t=>{e&&(u.current=t,setTimeout(()=>{u.current===t&&(u.current=null,d.current&&c.current?.focus?c.current.focus():l.current[t]?.focus?.())},60))},[e]),f=(0,r.useCallback)(()=>{c.current?.openTextPanel?.()},[]),b=(0,r.useCallback)(e=>{d.current=e},[]),g=(0,r.useCallback)(e=>l.current[e]?.focus?.(),[]),v=(0,r.useCallback)(()=>{c.current?.focus?.()},[]),y=(0,r.useCallback)(e=>{d.current?l.current[e]?.focus?.():c.current?.focus?.()},[]),w=(0,r.useRef)(0),k=(0,r.useCallback)(t=>{if(!e)return;if(tS.getState().fullMode){o.current&&(o.current.scrollLeft=0);return}cancelAnimationFrame(w.current),w.current=0;let s=o.current,n=e0({container:s,pane:i.current[t]});if(null==n){w.current=requestAnimationFrame(()=>{w.current=0;let e=e0({container:s,pane:i.current[t]});null!=e&&s.scrollTo({left:e,behavior:"smooth"})});return}s.scrollTo({left:n,behavior:"smooth"})},[e]),j=(0,r.useRef)(null);return(0,r.useEffect)(()=>{if(!e||n?.type!=="terminal"||!n?.sessionId||j.current===n.sessionId)return;j.current=n.sessionId;let t=requestAnimationFrame(()=>k(n.sessionId));return()=>cancelAnimationFrame(t)},[n?.type,n?.sessionId,e,k]),(0,r.useEffect)(()=>{if(!e||!t||!s)return;let n=setTimeout(()=>{d.current?c.current?.focus?.():l.current[s]?.focus?.()},60);return()=>clearTimeout(n)},[s,e,t]),(0,r.useMemo)(()=>({panesContainerRef:o,registerPaneApi:m,registerPaneElement:x,registerKeyboardTextApi:p,handlePasteFallback:f,handleInputFocusChange:b,focusPane:g,focusKeyboardInput:v,toggleInputFocus:y,scrollPaneIntoView:k,requestFocus:h}),[m,x,p,f,b,g,v,y,k,h])}({isDesktop:tI,isTerminalView:tH,activeSessionId:tU,currentView:tB,openedSessions:R}),tV=function({sessions:e,currentView:t,viewStack:s,setViewStack:n,pushView:a,storePopView:l,activeWorkspaceId:i,setActiveWorkspaceId:o,activeSessionId:c,addOpenedSession:d,removeOpenedSession:u,touchLivePane:m,createSession:x,deleteSession:p,renameSession:h,busRef:f,isDesktop:b=!1,requestFocus:g=null}){let{t:v}=(0,se.s)(),y=(0,r.useCallback)(e=>{let t=[...s];t[t.length-1]={type:"terminal",sessionId:e},n(t)},[s,n]),w=(0,r.useCallback)(t=>e.filter(e=>eQ(e)===(t??null)).map(e=>e.id),[e]),k=(0,r.useCallback)(e=>alert(v("workspace.failedCreateSession",{error:e})),[v]),j=(0,r.useCallback)(s=>{let n=e.find(e=>e.id===s);if(!n)return;let r=eQ(n);o(r);let l=w(r);l.forEach(e=>d(e)),d(s),m([...l,s]),"terminal"===t.type?y(s):a({type:"terminal",sessionId:s})},[e,w,d,m,o,t,a,y]);(0,r.useEffect)(()=>{let t=e=>{if(e.data?.type!=="NOTIFICATION_CLICK")return;let t=new URLSearchParams(new URL(e.data.url||"",location.origin).search).get("t");t&&j(t)},s=()=>{let t=Object.values(sc.getState().notifications||{});if(!t.length)return;let s=t=>{let s=e.find(e=>e.id===t);return s&&eQ(s)===(i??null)},n=t.sort((e,t)=>{let n=s(e.sessionId),r=s(t.sessionId);return n&&!r?-1:!n&&r?1:"blocked"===e.type&&"blocked"!==t.type?-1:"blocked"===t.type&&"blocked"!==e.type?1:(t.timestamp||0)-(e.timestamp||0)})[0];n?.sessionId&&j(n.sessionId)};return window.addEventListener("message",t),window.addEventListener("9remote:dock-click",s),()=>{window.removeEventListener("message",t),window.removeEventListener("9remote:dock-click",s)}},[j,e,i]),(0,r.useEffect)(()=>{let e=e=>{e.detail?.sessionId&&j(e.detail.sessionId)};return window.addEventListener(ev,e),()=>window.removeEventListener(ev,e)},[j]);let N=(0,r.useCallback)(e=>{let t=w(i);if(t.length<2)return;let s=t.indexOf(c);if(-1===s)return;let n="prev"===e?(s-1+t.length)%t.length:(s+1)%t.length;j(t[n])},[w,i,c,j]),S=(0,r.useCallback)(e=>{let t=w(i);e<0||e>=t.length||j(t[e])},[w,i,j]),C=(0,r.useCallback)((e,s=null,n=null,r=null,l=null,i=!1,c=!1)=>{x(e,n,s,r||null,e=>{if(!e?.success)return k(e?.error);if(!e.sessionId)return;let n=sP(l,i);n&&tS.getState().queueStartup(e.sessionId,n),l?.id&&tS.getState().setSessionAgent(e.sessionId,l.id);let r=s??null;o(r);let c=w(r);c.forEach(e=>d(e)),d(e.sessionId),m([...c,e.sessionId]),"terminal"===t.type?y(e.sessionId):a({type:"terminal",sessionId:e.sessionId}),g?.(e.sessionId)},c,l)},[x,w,d,m,k,t,y,a,o,g]),T=(0,r.useCallback)(e=>{if(!e?.resume)return;let s="ui"===e.mode,n=tS.getState().agentClis?.find(t=>t.id===e.agent)||null,r=s?null:function(e,t){if(!e||!t)return t;if(e.yolo)return`${t} ${e.yolo}`;if(e.yoloEnv){let s=Object.entries(e.yoloEnv).map(([e,t])=>`${e}=${t}`).join(" ");return`${s} ${t}`}return t}(n,e.resume);x(null,null,i,e.cwd||null,n=>{if(!n?.success)return k(n?.error);if(!n.sessionId)return;r&&tS.getState().queueStartup(n.sessionId,r);let l=s?`${e.agent}-ui`:e.agent;l&&tS.getState().setSessionAgent(n.sessionId,l),f?.current?.emit("claimAgentSession",{sessionId:n.sessionId,agent:l,conversationId:e.sessionId},()=>tS.getState().invalidateAgentHistory()),d(n.sessionId),m(n.sessionId),"terminal"===t.type?y(n.sessionId):a({type:"terminal",sessionId:n.sessionId}),g?.(n.sessionId)})},[x,i,d,m,k,y,a,t,g,f]),R=(0,r.useCallback)((e,s=null,n=!1,r=null,l=!1)=>{x(r,e,i,null,e=>{if(!e?.success)return k(e?.error);if(!e.sessionId)return;let r=sP(s,n);r&&tS.getState().queueStartup(e.sessionId,r),s?.id&&tS.getState().setSessionAgent(e.sessionId,s.id),d(e.sessionId),m(e.sessionId),"terminal"===t.type?y(e.sessionId):a({type:"terminal",sessionId:e.sessionId}),g?.(e.sessionId)},l,s)},[x,i,d,m,k,y,a,t,g]),E=(0,r.useCallback)((s,n,r=null,l=!1)=>{x(n,null,i,e.find(e=>e.id===s)?.cwd||null,e=>{if(!e?.success)return k(e?.error);if(!e.sessionId)return;let n=e.replaced||s;r?.id&&tS.getState().setSessionAgent(e.sessionId,r.id),n?tS.getState().replaceOpenedSession(n,e.sessionId):d(e.sessionId),m(e.sessionId),"terminal"===t.type?y(e.sessionId):a({type:"terminal",sessionId:e.sessionId}),g?.(e.sessionId)},l,r,s)},[x,i,k,d,m,y,a,t,g,e]),_=(0,r.useCallback)(e=>{x(null,t=>{if(!t.success)return k(t.error);t.sessionId&&(d(t.sessionId),e?.(t.sessionId))})},[x,d,k]),$=(0,r.useCallback)(t=>{o(t);let s=e.filter(e=>eQ(e)===(t??null));s.forEach(e=>d(e.id)),m(s.map(e=>e.id));let n=s[0];n&&y(n.id)},[e,o,d,m,y]),M=(0,r.useCallback)(s=>{let n=eQ(e.find(e=>e.id===s)),r=t?.type==="terminal"&&t.sessionId===s;p(s,()=>{if(u(s),!r)return;let t=e.filter(e=>e.id!==s),a=t.filter(e=>eQ(e)===n)[0]||t[0];a?(y(a.id),m(a.id)):l()})},[e,t,p,u,m,l,y]),P=(0,r.useCallback)((e,t)=>{h(e,t,e=>{e.success||alert(v("workspace.failedRenameSession",{error:e.error}))})},[h,v]);return(0,r.useMemo)(()=>({handleSelectSession:j,handleSelectWorkspace:$,handleCreateSession:C,handleQuickCreateSession:R,handleReplaceSession:E,handleResumeAgentSession:T,handleCreateSessionInline:_,handleDeleteSession:M,handleRenameSession:P,switchSession:N,switchToIndex:S}),[j,$,C,R,E,T,_,M,P,N,S])}({sessions:tp,currentView:tB,viewStack:T,setViewStack:$,pushView:E,storePopView:_,activeWorkspaceId:L,setActiveWorkspaceId:D,activeSessionId:tU,addOpenedSession:A,removeOpenedSession:z,touchLivePane:O,createSession:eZ,deleteSession:e1,renameSession:e5,busRef:e_,requestFocus:tq.requestFocus}),{systemInfo:tX,mobileEditor:tG,setMobileEditor:tJ,openFileRef:tY,handleOpenWorkspaceList:tZ,handleOpenFiles:tQ,handleSelectWorkspace:t0,handleBrowseFolder:t1,handlePathChange:t2,handleOpenFile:t3,handleOpenGit:t4,handleSetWorkspace:t6}=function({pushView:e,viewStack:t,setViewStack:s,currentView:n,cwdBySession:a,sessions:l=[],isDesktop:i,fileBus:o}){let[c,d]=(0,r.useState)(null),[u,m]=(0,r.useState)(null),x=(0,r.useRef)(null),p=(0,r.useCallback)(async()=>{if(!c){let e=await o.getSystemInfo();e.success&&d(e)}e({type:"workspaces"})},[e,o,c]),h=(0,r.useCallback)(async t=>{if(t){sr(t),e({type:"files",workspace:t,currentPath:t});return}if("terminal"===n.type){let t=n.sessionId&&(a[n.sessionId]||l.find(e=>e.id===n.sessionId)?.cwd)||null;if(t){sr(t),e({type:"files",workspace:t,currentPath:t});return}}let s=sn();if(s.length>0){let t=s[0];e({type:"files",workspace:t.path,currentPath:t.lastPath||t.path});return}p()},[e,p,n,a,l]),f=(0,r.useCallback)(e=>{sr(e),s([...t.filter(e=>"workspaces"!==e.type&&"files"!==e.type),{type:"files",workspace:e}])},[t,s]),b=(0,r.useCallback)(t=>{e({type:"browse",path:t})},[e]),g=(0,r.useCallback)((e,t)=>{let s,n,r;s=e2(e),-1!==(r=(n=sn()).findIndex(e=>e.path===s))&&(n[r]={...n[r],lastPath:e2(t)},localStorage.setItem(st,JSON.stringify(n)))},[]),v=(0,r.useCallback)((e,t,s={})=>{i?x.current?.(e,s):m({path:e,line:s.line,column:s.column,workspace:n.workspace})},[i,n.workspace]);return{systemInfo:c,mobileEditor:u,setMobileEditor:m,openFileRef:x,handleOpenWorkspaceList:p,handleOpenFiles:h,handleSelectWorkspace:f,handleBrowseFolder:b,handlePathChange:g,handleOpenFile:v,handleOpenGit:(0,r.useCallback)(()=>{let s=t.find(e=>"files"===e.type);s?.workspace&&e({type:"git",workspace:s.workspace})},[e,t]),handleSetWorkspace:(0,r.useCallback)(e=>{sr(e),s([...t.filter(e=>"browse"!==e.type&&"workspaces"!==e.type&&"files"!==e.type),{type:"files",workspace:e}])},[t,s])}}({pushView:E,viewStack:T,setViewStack:$,currentView:tB,cwdBySession:H,sessions:ez,isDesktop:tI,fileBus:t$}),[t7,ss]=(0,r.useState)(null),sl=si(e=>e.open),so=(0,r.useMemo)(()=>S?sn():[],[S,e4]),sd=(0,r.useCallback)(e=>{ss(null),e&&e6(e.split("/").filter(Boolean).pop()||e,e,t=>{let s=t?.workspace||t?.group;t?.success&&s?.id&&(sr(e),D(s.id),tV.handleCreateSession(null,s.id,null,e))})},[e6,D,tV]),su=(0,r.useCallback)(e=>{if(e)return sd(e);ss({initialPath:null})},[sd]),sp=(0,r.useCallback)((e,t,s,n,r,a,l)=>{let i=th.find(e=>e.id===t)?.hostKey||Object.values(td).find(e=>"string"==typeof t&&t.startsWith(`${e.key}:`))?.key;if(i){let o=sX.getState().hosts[i];if(!o)return;sG(o,{onSelectSession:tV.handleSelectSession}).createSession(e,sO(t,i),s,n,r,a,l);return}tV.handleCreateSession(e,t,s,n,r,a,l)},[th,td,tV]),sh=(0,r.useCallback)(e=>{sp(null,L,null,e)},[sp,L]),sf=th.find(e=>e.id===L)?.hostKey||null,sb=sf||tl||"main",sg=ne((0,r.useMemo)(()=>({get current(){return sf?sq(sf):e_.current}}),[sf,e_]),sb),sv=s7(e=>e.open),sy=s7(e=>e.isOpen),sw=s7(e=>e.close),[sk,sj]=(0,r.useState)(!1),sC=e4.find(e=>e.id===L)?.path||ez.find(e=>e.id===tU)?.workspacePath||null,sE=(0,r.useCallback)(()=>{let{agentId:e,shellId:t,yolo:s}=sF(),n=(sg||[]).flatMap(e=>{let t=nt.H8.find(t=>t.aiEngine===e.id);return t?[e,t]:e}),r=e&&n.find(t=>t.id===e)||null,a=tp.filter(e=>eQ(e)===(L??null)).length+1;sp(r?`${r.short||r.label} ${a}`:null,L,r?null:t,null,r,s,!0)},[sg,tp,L,sp]),s_=(0,r.useCallback)(e=>{let t=e4.map(e=>e.id);if(ez.some(e=>null===eQ(e))&&t.push(null),t.length<2)return;let s=t.indexOf(L??null),n=-1===s?0:s,r="prev"===e?(n-1+t.length)%t.length:(n+1)%t.length;tV.handleSelectWorkspace(t[r])},[e4,ez,L,tV]);!function(e,t=!0){let s=(0,r.useRef)(e);(0,r.useEffect)(()=>{s.current=e}),(0,r.useEffect)(()=>{if(!t)return;let e=e=>{if(document.querySelector('[role="dialog"], [aria-modal="true"], .modal-overlay'))return;let t=function(e){let t=s1();if(t&&e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey){let t=sQ.exec(e.code)||(/^[1-9]$/.test(e.key)?[null,e.key]:null);return t?{id:sY.id,index:Number(t[1])-1}:"ArrowLeft"===e.key?{id:"sessionPrev"}:"ArrowRight"===e.key?{id:"sessionNext"}:"ArrowUp"===e.key?{id:"workspacePrev"}:"ArrowDown"===e.key?{id:"workspaceNext"}:s6(e.target)?null:"Backquote"===e.code||"`"===e.key?{id:"toggleFocus"}:"Equal"===e.code||"="===e.key||"≠"===e.key||"+"===e.key?{id:"fitPanes"}:"KeyW"===e.code||"∑"===e.key||e.key?.toLowerCase()==="w"?{id:"closeTerminal"}:null}if(t&&e.altKey&&e.shiftKey&&!e.ctrlKey&&!e.metaKey){if(s6(e.target))return null;let t=s8(e.target);return"Enter"===e.key||"Enter"===e.code?{id:"newTerminal"}:t?null:"KeyP"===e.code||"π"===e.key||"∏"===e.key||e.key?.toLowerCase()==="p"?{id:"palette"}:"KeyB"===e.code||"ı"===e.key||"∫"===e.key||e.key?.toLowerCase()==="b"?{id:"toggleSidebar"}:"KeyJ"===e.code||"\xd4"===e.key||"∆"===e.key||e.key?.toLowerCase()==="j"?{id:"toggleRightPanel"}:"Slash"===e.code||"?"===e.key||"\xbf"===e.key||"/"===e.key?{id:"help"}:null}if(e.ctrlKey&&!e.shiftKey&&!e.metaKey&&!e.altKey&&("Backquote"===e.code||"`"===e.key)&&!s6(e.target))return{id:"toggleFocus"};if(!t&&e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey){if(s6(e.target))return null;if("Equal"===e.code||"="===e.key||"+"===e.key)return{id:"fitPanes"};if("KeyW"===e.code||e.key?.toLowerCase()==="w")return{id:"closeTerminal"}}if(!t&&e.ctrlKey&&e.shiftKey&&!e.altKey&&!e.metaKey){let t=sQ.exec(e.code);if(t)return{id:sY.id,index:Number(t[1])-1};if("ArrowLeft"===e.key)return{id:"sessionPrev"};if("ArrowRight"===e.key)return{id:"sessionNext"};if("ArrowUp"===e.key)return{id:"workspacePrev"};if("ArrowDown"===e.key)return{id:"workspaceNext"};if("Equal"===e.code||"="===e.key||"+"===e.key)return{id:"fitPanes"};let s=s8(e.target);if("Enter"===e.key||"Enter"===e.code)return{id:"newTerminal"};if(s)return null;if("KeyP"===e.code||e.key?.toLowerCase()==="p")return{id:"palette"};if("KeyB"===e.code||e.key?.toLowerCase()==="b")return{id:"toggleSidebar"};if("KeyJ"===e.code||e.key?.toLowerCase()==="j")return{id:"toggleRightPanel"};if("Slash"===e.code||"/"===e.key||"?"===e.key)return{id:"help"}}return null}(e);if(!t)return;let n=s.current?.[t.id];n&&(e.preventDefault(),e.stopPropagation(),n(t.index))};return document.addEventListener("keydown",e,!0),()=>document.removeEventListener("keydown",e,!0)},[t])}({sessionPrev:()=>tV.switchSession("prev"),sessionNext:()=>tV.switchSession("next"),workspacePrev:()=>s_("prev"),workspaceNext:()=>s_("next"),sessionIndex:e=>tV.switchToIndex(e),closeTerminal:(0,r.useCallback)(()=>{if(tB?.type!=="terminal"||!tB.sessionId)return;let e=ez.find(e=>e.id===tB.sessionId);e&&tR({isOpen:!0,title:N("sessions.deleteTitle"),message:N("sessions.deleteMessage",{name:e.name||N("terminal.defaultName")}),confirmText:N("common.delete"),onConfirm:()=>tV.handleDeleteSession(e.id)})},[tB,ez,tV,N]),toggleFocus:()=>tq.toggleInputFocus(tU),fitPanes:()=>window.dispatchEvent(new CustomEvent("terminal:fitPanes")),newTerminal:sE,toggleSidebar:q,toggleRightPanel:er,palette:()=>{sC&&sj(!0)},help:sv},tI&&tH);let s$=(0,r.useCallback)(e=>{let t=e4.find(e=>e.id===L)?.path||ez.find(e=>e.id===tB.sessionId)?.workspacePath||null;eu(),E({type:"editor",path:e,workspace:t})},[e4,L,ez,tB,E,eu]),sM=(0,r.useCallback)((e,t={})=>{if(tu(e)){let{status:t,repoPath:s,filePath:n}=tx(e);tJ({path:s?`${s}/${n}`:n,workspace:s||void 0,diffStatus:t});return}tJ({path:e,workspace:e4.find(e=>e.id===L)?.path,preview:!!t.preview,artifactSessionId:t.artifactSessionId||null})},[e4,L,tJ]),sA=(0,r.useCallback)((e,t)=>{if(!t?.path)return;let s=t.title||t.path.split("/").pop();tI?ed(t.path,{preview:!0,artifactTitle:s,artifactSessionId:e}):sM(t.path,{preview:!0,artifactSessionId:e})},[tI,ed,sM]);(0,r.useEffect)(()=>{let e=e_.current;if(!e)return;let t=({path:e,title:t,sessionId:s}={})=>{if(!e)return;let n={path:e,title:t||e.split("/").pop(),at:Date.now()};s&&ek(s,n),s&&s!==tU||sA(s,n)};return e.on("artifactOpen",t),()=>e.off("artifactOpen",t)},[e_,eM,tU,ek,sA]),(0,r.useEffect)(()=>{tH&&void 0!==L&&W(L)},[tH,L,W]);let sz=tU?ez.find(e=>e.id===tU):null,sI=sz?sz.name||N("terminal.defaultName"):null;(0,r.useEffect)(()=>(sN(Object.keys(tA).length,sI),()=>sN(0)),[tA,sI]);let[sL,sD]=(0,r.useState)(!1);(0,r.useEffect)(()=>{if("terminal"!==tB.type)return sD(!1);let e=requestAnimationFrame(()=>sD(!0));return()=>cancelAnimationFrame(e)},[tB.type]);let sB=(0,r.useRef)(null),[sW,sK]=(0,r.useState)("");(0,r.useEffect)(()=>{let e="terminal"===tB.type?tB.sessionId:null,t=sB.current;if(sB.current=e,!sL||!e||!t||e===t)return sK("");sK(R.indexOf(e)>R.indexOf(t)?"term-slide-right":"term-slide-left")},[tB,sL,R]);let sH=(0,r.useCallback)(()=>{if(!tI&&tG){tG.artifactSessionId&&ej(tG.artifactSessionId,tG.path),tJ(null);return}let e=Array.isArray(T)?T:[],t=e.length>1?e[e.length-2]:{type:"list"};_(),eN.replace(eJ(t))},[eN,_,tI,tG,tJ,ej,T]),sU=(0,r.useCallback)(()=>{if("terminal"!==tB.type)return sH();$([{type:"list"}])},[tB,sH,$]);(0,r.useEffect)(()=>{eE&&eY()},[eE,eY]),(0,r.useEffect)(()=>{if(0===tp.length||0===R.length)return;let e=setTimeout(()=>{let e=tp.map(e=>e.id);R.filter(t=>!e.includes(t)).forEach(e=>z(e))},500);return()=>clearTimeout(e)},[tp,R,z]),function({setKeyboardOpen:e}){(0,r.useEffect)(()=>{let t=!1,s=()=>{let s=window.visualViewport,n=s?.height||window.innerHeight,r=s?.offsetTop||0,a=n<window.innerHeight-100;t!==a&&(t=a,e(a)),document.documentElement.style.setProperty("--app-height",`${n}px`),!a&&r>0?document.documentElement.style.transform=`translateY(${-r}px)`:document.documentElement.style.transform="",window.scrollTo(0,0)};document.documentElement.classList.add("terminal-page");let n=0,r=()=>{clearTimeout(n),n=setTimeout(s,100)};return window.visualViewport&&(window.visualViewport.addEventListener("resize",r),window.visualViewport.addEventListener("scroll",r)),window.addEventListener("resize",r),r(),()=>{clearTimeout(n),document.documentElement.classList.remove("terminal-page"),document.documentElement.style.transform="",window.visualViewport&&(window.visualViewport.removeEventListener("resize",r),window.visualViewport.removeEventListener("scroll",r)),window.removeEventListener("resize",r)}},[e]),(0,r.useEffect)(()=>{let e=e=>{e.target.closest(".xterm-viewport,.xterm-screen,.terminal-scroll,.cm-scroller,.cm-content,.overflow-auto,.overflow-x-auto,.overflow-y-auto,.modal-scrollable,.brand-range")||e.preventDefault()};return document.addEventListener("touchmove",e,{passive:!1}),()=>document.removeEventListener("touchmove",e)},[]),(0,r.useEffect)(()=>{let e=e=>{e.target.matches("input, textarea")&&requestAnimationFrame(()=>window.scrollTo(0,0))};return document.addEventListener("focusin",e),()=>document.removeEventListener("focusin",e)},[])}({setKeyboardOpen:tz});let sV=(0,r.useCallback)(()=>{E({type:"remote"})},[E]),sJ=(0,r.useCallback)(()=>{tI?ex?(e_.current?.emit("mobile:stop"),ey(null),ef(!1)):ef(!0):E({type:"mobile"})},[tI,ex,ef,ey,e_,E]),sZ=(0,r.useCallback)(e=>{sS(e,{startWidth:eh,axis:-1,onWidth:eg})},[eh,eg]),s0=(0,r.useCallback)(()=>{e$.current?.retryNow()},[e$]),s2=(0,r.useCallback)(()=>{sX.getState().closeAll(),K(),sessionStorage.clear(),sessionStorage.setItem("9remote_manual_disconnect","1"),window.location.replace("/login")},[K]);(0,r.useEffect)(()=>{eO&&s2()},[eO,s2]);let s5=(0,r.useCallback)(()=>{tR({isOpen:!0,title:N("workspace.logoutTitle"),message:N("workspace.logoutMessage"),onConfirm:s2})},[s2,N]),s3=(0,r.useCallback)(()=>{tR({isOpen:!1,title:"",message:"",onConfirm:null})},[]),s4=(0,r.useCallback)(e=>{I(e),te(e)},[I,te]),s9=(0,r.useCallback)(e=>{L&&J(L,e)},[L,J]),ns=(0,r.useMemo)(()=>({open:Z,tabs:es,width:en,onTabChange:ea,onResize:el,onToggle:er,onNewTerminal:sh}),[Z,es,en,ea,el,er,sh]),nn=(0,r.useMemo)(()=>({filePath:ei,previewSeq:em,artifactTitle:ew,width:eo,onResize:ec,onOpen:tI?ed:sM,onClose:eu,onOpenFull:s$}),[ei,em,ew,eo,ec,tI,ed,sM,eu,s$]),nr=(0,r.useMemo)(()=>({open:ex,mode:ep,width:eh,protocolRef:e$,onResizeStart:sZ}),[ex,ep,eh,e$,sZ]),na=eM&&eI&&!eD?.isCodespaces,nl=(0,r.useMemo)(()=>({connected:eM,remoteAvailable:na,codespaceInfo:eD,showTheme:!1,theme:"default",busRef:e_,hideActions:["remote","files","sites"],tunnelUrl:eT?.tunnelUrl,apiKey:eT?.apiKey,connectionMode:eP,subscribeToPush:tM,unsubscribeFromPush:tP,notifications:tA,agentVersion:eW,carrier:eA}),[eM,na,eD,e_,eT,eP,tM,tP,tA,eW,eA]),ni=(0,r.useMemo)(()=>({onRemote:null,onFiles:null,onSelectSite:null,onRefreshSites:null,onCodespace:null,onLogout:s5,onThemeChange:null,onStopCodespace:e3,onUpdate:tE,onRestart:t_}),[s5,e3,tE,t_]);if(!S||!eE)return(0,n.jsx)(dm,{label:N("workspace.loading")});let no=eM&&eI&&!eD?.isCodespaces?sV:null,nc=eM&&eL?sJ:null;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(dx.A,{}),(0,n.jsx)(r.Suspense,{fallback:null,children:(0,n.jsx)(mw,{hydrated:S,apiKey:eT?.apiKey})}),(0,n.jsxs)("div",{className:"terminal-container h-[var(--app-height,100vh)] fixed inset-0 overflow-hidden overscroll-none",children:[!tI&&(0,n.jsx)("div",{className:`absolute inset-0 transition-opacity duration-150 ease-out ${"list"===tB.type?"opacity-100 z-10":"opacity-0 z-0 pointer-events-none"}`,children:tf?(0,n.jsx)(dT,{currentKey:tl,homeDir:tX?.homedir,fullHost:{sessions:ez,workspaces:e4,platform:eB,version:eW},menuContext:nl,menuCallbacks:ni}):(0,n.jsx)(dh,{sessions:ez,cwdBySession:H,connected:eM,onSelect:tV.handleSelectSession,onCreate:tV.handleCreateSession,onDelete:tV.handleDeleteSession,onRename:tV.handleRenameSession,onResumeAgentSession:tV.handleResumeAgentSession,onLogout:s5,onOpenRemote:no,onOpenMobile:nc,tunnelUrl:eT?.tunnelUrl,apiKey:eT?.apiKey,connectionMode:eP,codespaceInfo:eD,codespaceDisconnected:eF,onStopCodespace:e3,onUpdate:tE,onRestart:t_,isActive:"list"===tB.type,busRef:e_,subscribeToPush:tM,unsubscribeFromPush:tP,agentVersion:eW,updateAvailable:eK,canSelfUpdate:eH,carrier:eA,workspaces:e4,onAddWorkspace:su,homeDir:tX?.homedir,onRenameWorkspace:e8,onDeleteWorkspace:e9,onReorderSession:s4,recentWorkspaces:so,shells:tv,onRenameHost:tb,onDeleteHost:tg})}),(tI||R.length>0)&&(0,n.jsx)(dd,{platform:eB,agentVersion:eW,sessions:tp,workspaces:th,onCreateAnyHost:sp,onQuickCreateHostAware:sE,activeSessionId:tU,activeSession:sz,activeWorkspaceId:L,openedSessions:R,livePanes:F,mountedWorkspaces:B,cwdBySession:H,isDesktop:tI,isTerminalView:tH,slideClass:sW,shells:tv,sidebarCollapsed:U,sidebarWidth:V,setSidebarWidth:X,paneWidth:L?G[L]??null:null,setPaneWidth:L?s9:void 0,toggleSidebar:q,paneRegistry:tq,bindSwipeTab:tF,nav:tV,onBack:sU,atStackBottom:tI&&"list"===tB.type,onOpenRemote:no,onOpenMobile:nc,onOpenFiles:tQ,onLogout:s5,onStopCodespace:e3,onUpdate:tE,onRestart:t_,onDeleteWorkspace:e9,onReorderSession:te,onAddWorkspace:su,onSetHiddenRepos:e7,onOpenSettings:sl,onRenameHost:tb,onDeleteHost:tg,homeDir:tX?.homedir,recentWorkspaces:so,onOpenArtifact:sA,rightPanel:ns,editorPanel:nn,mobilePanel:nr,fileBus:t$,codespaceInfo:eD,tunnelUrl:eT?.tunnelUrl,apiKey:eT?.apiKey,connectionMode:eP,subscribeToPush:tM,unsubscribeFromPush:tP,updateAvailable:eK,canSelfUpdate:eH}),t7&&(0,n.jsx)(rw,{fileBus:t$,initialPath:t7.initialPath,onSelect:sd,onClose:()=>ss(null)}),"remote"===tB.type&&(0,n.jsx)("div",{className:"absolute inset-0 z-20 transition-all duration-300 ease-out",children:(0,n.jsx)(d5,{onClose:sH,busRef:e_,protocolRef:e$,connected:eM,connectionMode:eP,carrier:eA,hostPlatform:eB})}),"mobile"===tB.type&&(0,n.jsx)("div",{className:"absolute inset-0 z-20 transition-all duration-300 ease-out",children:(0,n.jsx)(lf,{onClose:sH,busRef:e_,protocolRef:e$,connected:eM})}),"site"===tB.type&&(0,n.jsx)(ud,{busRef:e_,connected:eM,initialPort:tB.port,initialPath:tB.path,onBack:_}),"workspaces"===tB.type&&(0,n.jsx)("div",{className:"absolute inset-0 z-20 transition-all duration-300 ease-out",children:(0,n.jsx)(sa,{onSelect:t0,onBrowse:t1,onBack:sH,isCodespaces:eD?.isCodespaces,systemInfo:tX})}),"browse"===tB.type&&(0,n.jsx)("div",{className:"absolute inset-0 z-20 transition-all duration-300 ease-out",children:(0,n.jsx)(um,{workspace:tB.path,fileBus:t$,onBack:sH,onSetWorkspace:t6,isBrowsing:!0})}),tI&&("files"===tB.type||"editor"===tB.type||"git"===tB.type)&&(y="files"===tB.type?tB:[...T].reverse().find(e=>"files"===e.type),w=y?.workspace||tB.workspace,k=sn().find(e=>e.path===w),j="editor"===tB.type?tB.path:null,(0,n.jsx)("div",{className:"absolute inset-0 z-20 transition-all duration-300 ease-out",children:(0,n.jsx)(uF,{workspace:w,fileBus:t$,onBack:sH,onSwitchWorkspace:tZ,initialOpenedFiles:j?[j]:k?.openedFiles||[],initialActiveFile:j||k?.activeFile||null,onOpenedFilesChange:(e,t)=>(function(e,t,s){let n=e2(e),r=sn(),a=r.findIndex(e=>e.path===n),l=Array.isArray(t)?t.map(e=>e&&"object"==typeof e?{...e,path:e2(e.path)}:e):t,i="string"==typeof s?e2(s):s;if(-1===a){r.unshift({path:n,lastOpened:Date.now(),openedFiles:l,activeFile:i}),localStorage.setItem(st,JSON.stringify(r));return}r[a]={...r[a],openedFiles:l,activeFile:i??null},localStorage.setItem(st,JSON.stringify(r))})(w,e,t),bus:eE,connected:eM,sessions:ez,onCreateTerminalSession:tV.handleCreateSessionInline,onDeleteTerminalSession:tV.handleDeleteSession,onRenameTerminalSession:tV.handleRenameSession,viewType:tB.type,openFileRef:tY},w)})),!tI&&"files"===tB.type&&(0,n.jsx)("div",{className:"absolute inset-0 z-20 transition-all duration-300 ease-out",children:(0,n.jsx)(um,{workspace:tB.workspace,initialPath:tB.currentPath,fileBus:t$,onBack:sH,onOpenFile:t3,onOpenGit:t4,onSwitchWorkspace:tZ,onPathChange:e=>t2(tB.workspace,e),hideSwitchWorkspace:tB.fromTerminal})}),!tI&&"git"===tB.type&&(0,n.jsx)("div",{className:"absolute inset-0 z-30 transition-all duration-300 ease-out",children:(0,n.jsx)(ug,{workspace:tB.workspace,fileBus:t$,onBack:sH,onOpenFile:t3})}),!tI&&tG&&(0,n.jsx)("div",{className:"absolute inset-0 z-40 transition-all duration-300 ease-out",children:(0,n.jsx)(uf,{filePath:tG.path,line:tG.line,column:tG.column,diffStatus:tG.diffStatus,preview:tG.preview,fileBus:t$,onBack:()=>{tG.artifactSessionId&&ej(tG.artifactSessionId,tG.path),tJ(null)},workspace:tG.workspace||tB.workspace})}),(!eM||!eG)&&(0,n.jsx)(dm,{}),tc&&(0,n.jsx)("div",{className:"fixed inset-0 z-[60] flex items-center justify-center px-4 bg-black/50 backdrop-blur-[4px] animate-in fade-in duration-150",style:{paddingTop:"max(1rem, env(safe-area-inset-top))",paddingBottom:"max(1rem, env(safe-area-inset-bottom))"},onClick:()=>sX.getState().closeOverlay(),children:(0,n.jsx)("div",{className:"card-elev w-[26rem] max-w-full overflow-hidden flex flex-col my-auto h-[min(85%,calc(var(--app-height,85vh)-2rem))] animate-in zoom-in-95 duration-150",onClick:e=>e.stopPropagation(),children:(0,n.jsx)(dT,{currentKey:tl,homeDir:tX?.homedir,fullHost:{sessions:ez,workspaces:e4,platform:eB,version:eW},onClose:()=>sX.getState().closeOverlay()})})}),!tw&&(0,n.jsx)(uB,{retryStatus:eV,approvalStatus:eX,connected:eM,suppress:tj,onLogout:s2,onRetryNow:s0}),(0,n.jsx)(uV,{open:tw,connected:eM,mode:tk}),(0,n.jsx)(my,{}),sk&&sC&&(0,n.jsx)(uL,{mode:"files",workspace:sC,fileBus:t$,onClose:()=>sj(!1),onOpenFile:e=>ed(e)}),(0,n.jsx)(uO,{isOpen:sy,onClose:sw}),(0,n.jsx)(t9.A,{isOpen:tT.isOpen,onClose:s3,onConfirm:tT.onConfirm,title:tT.title,message:tT.message,confirmText:tT.confirmText})]}),(0,n.jsx)("div",{hidden:!0,children:(0,n.jsx)(r.Suspense,{fallback:null,children:e})}),(0,n.jsx)(t8,{})]})}}},e=>{e.O(0,[476,6189,6391,774,3348,5018,9958,8439,6552,2347,5158,7358],()=>e(e.s=36416)),_N_E=e.O()}]);
|