9remote 3.0.3 → 3.0.5
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 +62 -62
- package/dist/ptyDaemon.cjs +7 -7
- package/dist/server.cjs +206 -187
- package/dist/ui/assets/index-CSihcjlv.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 +7 -7
- package/dist/web/__next._head.txt +1 -1
- package/dist/web/__next._index.txt +6 -6
- package/dist/web/__next._tree.txt +2 -2
- package/dist/web/_next/static/chunks/1750.a35b00a05b21d196.js +1 -0
- package/dist/web/_next/static/chunks/3973-919fa2e493564fcf.js +1 -0
- package/dist/web/_next/static/chunks/6552-5bb346448e83e0a2.js +1 -0
- package/dist/web/_next/static/chunks/7738-2439d4a20b745ce1.js +1 -0
- package/dist/web/_next/static/chunks/9958-9952a61eb6e17812.js +1 -0
- package/dist/web/_next/static/chunks/app/admin/admins/{page-5e0e3fd2d0958d9f.js → page-4dd3a5a797a983ab.js} +1 -1
- package/dist/web/_next/static/chunks/app/admin/login/{page-6c982d868fdac3dc.js → page-854bcdcb805c63c8.js} +1 -1
- package/dist/web/_next/static/chunks/app/admin/modes/{page-a65bd6cce18e942b.js → page-b0675a3cdae87688.js} +1 -1
- package/dist/web/_next/static/chunks/app/admin/ota/{page-7a552ae27c99ef80.js → page-6de419e03b4822ef.js} +1 -1
- package/dist/web/_next/static/chunks/app/admin/{page-065812115a332f39.js → page-ae83026dc795c35b.js} +1 -1
- package/dist/web/_next/static/chunks/app/admin/turn/{page-c6994ee6f6adeefe.js → page-8eb4a8792fca9bd9.js} +1 -1
- package/dist/web/_next/static/chunks/app/dev/question/page-a58ae088ccc40553.js +1 -0
- package/dist/web/_next/static/chunks/app/{layout-341400810c81f67e.js → layout-ec53a1a0c4b3e99e.js} +1 -1
- package/dist/web/_next/static/chunks/app/login/{page-8cddff633dcedaef.js → page-fda2e8572302edca.js} +1 -1
- package/dist/web/_next/static/chunks/app/{page-165a740d40cb1fef.js → page-00c77a2e54c385ac.js} +2 -2
- package/dist/web/_next/static/chunks/app/workspace/layout-90f9ac2ec0cf5aef.js +14 -0
- package/dist/web/_next/static/chunks/{webpack-c971919003362f96.js → webpack-210219beafaa52a1.js} +1 -1
- package/dist/web/_next/static/css/48ee7d57614b1421.css +1 -0
- package/dist/web/_not-found/__next._full.txt +6 -6
- package/dist/web/_not-found/__next._head.txt +1 -1
- package/dist/web/_not-found/__next._index.txt +6 -6
- 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 +6 -6
- package/dist/web/admin/__next._full.txt +7 -7
- package/dist/web/admin/__next._head.txt +1 -1
- package/dist/web/admin/__next._index.txt +6 -6
- 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 +7 -7
- package/dist/web/admin/admins/__next._head.txt +1 -1
- package/dist/web/admin/admins/__next._index.txt +6 -6
- 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 +7 -7
- package/dist/web/admin/login/__next._full.txt +7 -7
- package/dist/web/admin/login/__next._head.txt +1 -1
- package/dist/web/admin/login/__next._index.txt +6 -6
- 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 +7 -7
- package/dist/web/admin/modes/__next._full.txt +7 -7
- package/dist/web/admin/modes/__next._head.txt +1 -1
- package/dist/web/admin/modes/__next._index.txt +6 -6
- 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 +7 -7
- package/dist/web/admin/ota/__next._full.txt +7 -7
- package/dist/web/admin/ota/__next._head.txt +1 -1
- package/dist/web/admin/ota/__next._index.txt +6 -6
- 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 +7 -7
- package/dist/web/admin/turn/__next._full.txt +7 -7
- package/dist/web/admin/turn/__next._head.txt +1 -1
- package/dist/web/admin/turn/__next._index.txt +6 -6
- 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 +7 -7
- package/dist/web/admin.html +1 -1
- package/dist/web/admin.txt +7 -7
- package/dist/web/agent-icons/antigravity-ui.png +0 -0
- package/dist/web/agent-icons/omp-ui.svg +1 -0
- package/dist/web/agent-icons/opencode-ui.png +0 -0
- package/dist/web/dev/question/__next._full.txt +7 -7
- package/dist/web/dev/question/__next._head.txt +1 -1
- package/dist/web/dev/question/__next._index.txt +6 -6
- 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 +7 -7
- package/dist/web/index.html +1 -1
- package/dist/web/index.txt +7 -7
- package/dist/web/login/__next._full.txt +7 -7
- package/dist/web/login/__next._head.txt +1 -1
- package/dist/web/login/__next._index.txt +6 -6
- 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 +7 -7
- package/dist/web/workspace/__next._full.txt +7 -7
- package/dist/web/workspace/__next._head.txt +1 -1
- package/dist/web/workspace/__next._index.txt +6 -6
- 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 +7 -7
- package/dist/web/workspace/browse/__next._head.txt +1 -1
- package/dist/web/workspace/browse/__next._index.txt +6 -6
- 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 +7 -7
- package/dist/web/workspace/editor/__next._full.txt +7 -7
- package/dist/web/workspace/editor/__next._head.txt +1 -1
- package/dist/web/workspace/editor/__next._index.txt +6 -6
- 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 +7 -7
- package/dist/web/workspace/files/__next._full.txt +7 -7
- package/dist/web/workspace/files/__next._head.txt +1 -1
- package/dist/web/workspace/files/__next._index.txt +6 -6
- 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 +7 -7
- package/dist/web/workspace/git/__next._full.txt +7 -7
- package/dist/web/workspace/git/__next._head.txt +1 -1
- package/dist/web/workspace/git/__next._index.txt +6 -6
- 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 +7 -7
- package/dist/web/workspace/mobile/__next._full.txt +7 -7
- package/dist/web/workspace/mobile/__next._head.txt +1 -1
- package/dist/web/workspace/mobile/__next._index.txt +6 -6
- 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 +7 -7
- package/dist/web/workspace/remote/__next._full.txt +7 -7
- package/dist/web/workspace/remote/__next._head.txt +1 -1
- package/dist/web/workspace/remote/__next._index.txt +6 -6
- 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 +7 -7
- package/dist/web/workspace/terminal/default/__next._full.txt +7 -7
- package/dist/web/workspace/terminal/default/__next._head.txt +1 -1
- package/dist/web/workspace/terminal/default/__next._index.txt +6 -6
- 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 +7 -7
- package/dist/web/workspace/workspaces/__next._full.txt +7 -7
- package/dist/web/workspace/workspaces/__next._head.txt +1 -1
- package/dist/web/workspace/workspaces/__next._index.txt +6 -6
- 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 +7 -7
- package/dist/web/workspace.html +1 -1
- package/dist/web/workspace.txt +7 -7
- package/package.json +1 -1
- package/dist/ui/assets/index-N-7Btpy6.js +0 -8
- package/dist/web/_next/static/chunks/1750.f7ba3332b56a8e68.js +0 -1
- package/dist/web/_next/static/chunks/3973-0f299c91413d771f.js +0 -1
- package/dist/web/_next/static/chunks/6552-a42cab8d91efbdea.js +0 -1
- package/dist/web/_next/static/chunks/7629-16de8d4154923623.js +0 -1
- package/dist/web/_next/static/chunks/9958-ac2bbbfff1caca81.js +0 -1
- package/dist/web/_next/static/chunks/app/dev/question/page-5fd80ae293617365.js +0 -1
- package/dist/web/_next/static/chunks/app/workspace/layout-de3e7ac6ee87c001.js +0 -14
- package/dist/web/_next/static/css/dceb43a27b274afb.css +0 -1
- /package/dist/web/_next/static/{P887YK8-ExWuqlGx2FRuu → aW3BVD9Z6dZG5uaKNzgmQ}/_buildManifest.js +0 -0
- /package/dist/web/_next/static/{P887YK8-ExWuqlGx2FRuu → aW3BVD9Z6dZG5uaKNzgmQ}/_ssgManifest.js +0 -0
|
@@ -1,14 +0,0 @@
|
|
|
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){}})}},34975:(e,t,s)=>{"use strict";s.r(t),s.d(t,{default:()=>ms});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,j=15,k=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:j,this._reconnectMaxAttempts=k,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,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(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 E(i)}}}var M=s(90084),P=s(7938);let A=null,z=0,L=new Map,I=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(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),r))?1===n.length?[s]:n.map((s,r)=>_({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(()=>{L.has(t)&&(L.delete(t),n(null))},8e3),a=P.eR.decodeQueueCap;for(;L.size>=a;){let e=L.keys().next().value,t=L.get(e);if(!t)break;clearTimeout(t.timer),L.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}})=>{I=0;let a=L.get(s);if(!a){if(e)for(let t of e)t.bitmap?.close?.();return}clearTimeout(a.timer),L.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,L.values()))try{e(null)}catch{}L.clear()}(),++I>=3&&(A=!1)},A}();if(!l){clearTimeout(r),L.delete(t),n(null);return}L.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 B=new Map;function O(e){if(!e?.id)throw Error("Adapter missing static id");B.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 U(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 H(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=U(await n.getStats());return null==t||(await new Promise(t=>{e._resumeProbeTimer=setTimeout(t,o.UT)}),r!==e._probeToken)?null:U(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}`)}}O(S),O(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}H(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=B.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?H(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 ej="16,16,20",ek="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 e_(e){return eS[e]?.label||(eT(e)?"Custom":eS.none.label)}function eE(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 eE([e],s)[0]||(r=eE(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"],eL="enter",eI=[["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",eB={minWidth:"34px",height:"32px",paddingLeft:"6px",paddingRight:"6px"},eO={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},eU="/workspace",eH={list:()=>eU,terminal:e=>`${eU}/terminal/${encodeURIComponent(e.sessionId||"")}`,files:e=>eX(`${eU}/files`,{ws:e.workspace,p:e.currentPath}),editor:e=>eX(`${eU}/editor`,{path:e.path,line:e.line,col:e.column}),git:e=>eX(`${eU}/git`,{ws:e.workspace}),remote:()=>`${eU}/remote`,mobile:()=>`${eU}/mobile`,workspaces:()=>`${eU}/workspaces`,browse:e=>eX(`${eU}/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(eU))return null;let[s,n]=e.slice(eU.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(eH[e?.type]||eH.list)(e)}function eY(e){let t=Number(e);return Number.isFinite(t)?t:void 0}let eZ=(e,{min:t,max:s})=>Math.max(t,Math.min(s,Math.round(e))),eQ=e=>"string"==typeof e?e.replace(/\\/g,"/"):e,e0=new Set(["path","currentPath","parentPath","dirPath","filePath","repoPath","oldPath","newPath","fullPath","relativePath"]),e1=[".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svg",".avif",".apng",".tif",".tiff",".heic",".heif"],e2=[".mp4",".m4v",".webm",".ogv",".mov",".mkv",".avi",".3gp"],e5=[".mp3",".wav",".ogg",".oga",".flac",".m4a",".aac",".opus"],e3=[".pdf"],e4=[".docx"],e6=[".xlsx",".xls",".csv",".tsv"],e8=[".html",".htm",".xhtml"],e9=[".mmd",".mermaid"],e7=[".md",".markdown",".mdx"];function te(e,t){if(!e)return!1;let s=e.toLowerCase();return t.some(e=>s.endsWith(e))}function tt(e){return e?te(e,e8)?"html":te(e,e7)?"markdown":te(e,e9)?"mermaid":null:null}let ts={".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"},tn={M:"text-git-modified",A:"text-git-added",D:"text-git-deleted","?":"text-git-untracked",U:"text-git-modified"},tr={indentBase:12,indentStep:12,icon:16,chevron:14,text:"text-[15px] sm:text-sm",padY:"py-1 sm:py-0.5"},ta={indentBase:8,indentStep:8,icon:14,chevron:12,text:"text-[13px] sm:text-[12px]",padY:"py-0.5 sm:py-[1px]"},tl="git-diff:",ti=(e,t)=>`${tl}${e}:${t}`,to=e=>"string"==typeof e&&e.startsWith(tl),tc=e=>{let t=e.slice(tl.length),s=t.indexOf(":");return{status:t.slice(0,s),absPath:t.slice(s+1)}},td=e=>{let{status:t,absPath:s}=tc(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)}},tu="fileExplorer:gitRefresh",tm="fileExplorer.editorFontSize",tx="fileExplorer.wordWrap",tp="fileExplorer.expandedFolders",th="fileExplorer.showHidden",tf="explorer",tb="search",tg="settings",tv="__ungrouped__",ty=e=>e?.workspaceId??e?.groupId??null;function tw({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 tj={name:null,value:null},tk=null,tN=()=>{if(tk&&(clearTimeout(tk),tk=null),null===tj.name)return;let{name:e,value:t}=tj;tj.name=null,tj.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({activeWorkspaceId:t}),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??tv;return e.mountedWorkspaces[s]?e:{mountedWorkspaces:{...e.mountedWorkspaces,[s]:!0}}}),isWorkspaceMounted:e=>!!t().mountedWorkspaces[e??tv],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=eQ(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),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:eZ(t,ea)}),paneWidths:{},setPaneWidth:(t,s)=>e(e=>({paneWidths:{...e.paneWidths,[t]:null==s?null:eZ(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:eZ(t,el)}),editorFilePath:null,editorPanelWidth:ei.default,setEditorPanelWidth:t=>e({editorPanelWidth:eZ(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:eZ(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:[]}),agentClis:null,agentClisAt:0,setAgentClis:t=>e({agentClis:Array.isArray(t)?t:[],agentClisAt: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,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)=>{tj.name=e,tj.value=t,tk||(tk=setTimeout(tN,250))},removeItem:e=>{tj.name===e&&(tj.name=null,tj.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 t_(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 tE=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 t_(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 tL=(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 tI(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=>{tL("enabled",s),e({enabled:s}),tI(t())},setMode:s=>{tL("mode",s),e({mode:s}),tI(t())},setPreset:s=>{tL("preset",s),e({preset:s}),tI(t())},setField:(s,n)=>{tL(s,n),e({[s]:n}),tI(t())},syncFromAgent:t=>{t&&"object"==typeof t&&e(e=>{let s={...e};return"boolean"==typeof t.enabled&&(s.enabled=t.enabled,tL("enabled",s.enabled)),t.mode&&(s.mode=t.mode,tL("mode",s.mode)),t.preset&&(s.preset=t.preset,tL("preset",s.preset)),Array.isArray(t.geminiKeys)&&(s.geminiKeys=t.geminiKeys,tL("geminiKeys",s.geminiKeys)),"string"==typeof t.geminiModel&&(s.geminiModel=t.geminiModel,tL("geminiModel",s.geminiModel)),"string"==typeof t.openrouterKey&&(s.openrouterKey=t.openrouterKey,tL("openrouterKey",s.openrouterKey)),"string"==typeof t.openrouterModel&&(s.openrouterModel=t.openrouterModel,tL("openrouterModel",s.openrouterModel)),"string"==typeof t.customEndpoint&&(s.customEndpoint=t.customEndpoint,tL("customEndpoint",s.customEndpoint)),"string"==typeof t.customModel&&(s.customModel=t.customModel,tL("customModel",s.customModel)),"string"==typeof t.customKey&&(s.customKey=t.customKey,tL("customKey",s.customKey)),s})},pushToAgent:()=>tI(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",tL("preset",t.preset),r&&"custom"!==t.preset&&(t[`${t.preset}Model`]=r),t.geminiModel&&tL("geminiModel",t.geminiModel),t.openrouterModel&&tL("openrouterModel",t.openrouterModel),t.geminiKeys.length&&tL("geminiKeys",t.geminiKeys),t.openrouterKey&&tL("openrouterKey",t.openrouterKey),t.customEndpoint&&tL("customEndpoint",t.customEndpoint),t.customModel&&tL("customModel",t.customModel),t.customKey&&tL("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 tB(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 tO(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 tU(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 tH={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})):j())},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 j(){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(j,50)}j()})),{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(e0.has(n)&&"string"==typeof r&&r.includes("\\"))(s||={...t})[n]=eQ(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=tU(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=tU(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=eQ(t.path)),"string"==typeof t.lastPath&&(t.lastPath=eQ(t.lastPath)),Array.isArray(t.openedFiles)&&(t.openedFiles=t.openedFiles.map(e=>e&&"object"==typeof e?{...e,path:eQ(e.path)}:e)),"string"==typeof t.activeFile&&(t.activeFile=eQ(t.activeFile)),t};function sn(){try{return JSON.parse(localStorage.getItem(st)||"[]").map(ss)}catch{return[]}}function sr(e){let t=eQ(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=eQ(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 tO(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 tO(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&&sj(sv)})).observe(document.head,{childList:!0,subtree:!0,characterData:!0})}function sj(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 sk(){let e=sh.slice(sb)+sh.slice(0,sb);sj(`(${sg}) 🔔 ${e}`),sb=(sb+1)%sh.length}function sN(e,t){sg=e,e>0?(sw(),sf||(sb=0,sk(),sf=setInterval(sk,400))):(sf&&(clearInterval(sf),sf=null),sb=0,t?(sw(),sj(`${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,s_=new Set(["claude","codex","aider","pi","omp"]),sE="rounded-[3px]";function s$(e){return e&&"null"!==e&&"undefined"!==e?`/agent-icons/${e}.${s_.has(e)?"svg":"png"}`:null}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",sL="9remote.terminal.yoloPref2";function sI(e){try{return localStorage.getItem(e)||null}catch{return null}}function sD(e,t){try{localStorage.setItem(e,t)}catch{}}function sF(){return{agentId:sI(sz)||"",shellId:sI(sA),yolo:"0"!==sI(sL)}}let sB=[{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+/"}],sO={id:"sessionIndex",label:"Go to terminal 1–9",mac:"⌥1…9",pc:"Ctrl+Shift+1…9"},sW=[{id:"switchTerminal",label:"Switch terminal",mac:"⌥← / →",pc:"Ctrl+Shift+← / →"},sO,{id:"switchWorkspace",label:"Switch workspace",mac:"⌥↑ / ↓",pc:"Ctrl+Shift+↑ / ↓"},sB.find(e=>"newTerminal"===e.id),sB.find(e=>"closeTerminal"===e.id),sB.find(e=>"fitPanes"===e.id),sB.find(e=>"toggleFocus"===e.id),sB.find(e=>"toggleSidebar"===e.id),sB.find(e=>"toggleRightPanel"===e.id),sB.find(e=>"palette"===e.id),sB.find(e=>"help"===e.id)].filter(Boolean),sK=/^Digit([1-9])$/,sU=null,sH=()=>{if(null!==sU)return sU;if("u"<typeof navigator)return!1;let e=navigator.userAgentData?.platform;return sU=e?"macOS"===e:/Mac/.test(navigator.platform||"")&&navigator.maxTouchPoints<=1},sq=e=>sH()?e.mac:e.pc,sV="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",sX=new Set(["⌘","⌥","⇧","⌃"]);function sG(e){let t=sq(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&&sX.has(n[r]);)s.push(n[r]),r++;return r<n.length&&s.push(n.slice(r)),s}let sJ=e=>!!e&&"function"==typeof e.closest&&!!(e.closest("[role=dialog]")||e.closest(".modal-overlay")||e.closest(".card-elev")),sY=e=>!(!e||"function"!=typeof e.closest||e.closest(".xterm"))&&(e.isContentEditable||"INPUT"===e.tagName||"TEXTAREA"===e.tagName);function sZ(e,t){let s=sB.find(e=>e.id===t);return s?`${e} \xb7 ${sq(s)}`:e}let sQ=(0,Z.v)(e=>({isOpen:!1,open:()=>e({isOpen:!0}),close:()=>e({isOpen:!1}),toggle:()=>e(e=>({isOpen:!e.isOpen}))}));function s0(e){let t=tS(e=>e.agentClis);return(0,r.useEffect)(()=>{let t=tS.getState();t.agentClis&&Date.now()-t.agentClisAt<6e4||e?.current?.emit("getAgentClis",e=>{let t=Array.isArray(e?.agents)?e.agents:Array.isArray(e)?e:null;t&&tS.getState().setAgentClis(t)})},[e]),t}var s1=s(39096);let s2=(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},s5=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=s2(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=s2(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)}}})),s3=s5("terminal-command-history"),s4=s5("remote-input-history"),s6=s5("ai-command-history");function s8({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 s9({isOpen:e,onSelect:t,onClose:s,store:a=s3}){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)(s8,{snippet:x,onSave:e=>m(x.cmd,e),onClose:()=>p(null)})]})}let s7={pinned:2,history:4,common:4,total:8},ne={pinned:1,history:2,common:2,total:4},nt=(e,t)=>{let s=e.indexOf(t);return s<0?null:1e3*(0!==s)+s+.1*e.length};function ns(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=nt(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?ne:s7,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 nn({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?[]:ns(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 nr={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"},na=e=>nr[e]||e||"en-US",nl="voiceLang";function ni(e){let[t,s]=(0,r.useState)(e);return(0,r.useEffect)(()=>{let e=localStorage.getItem(nl);e&&nr[e]&&s(e)},[]),[t,(0,r.useCallback)(e=>{s(e);try{localStorage.setItem(nl,e)}catch{}},[])]}let no=new Set(["not-allowed","service-not-allowed","audio-capture","language-not-supported"]);function nc(){return window.SpeechRecognition||window.webkitSpeechRecognition||null}function nd({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),j=(0,r.useRef)(""),k=!!window.ReactNativeWebView||/9Remote-Mobile/i.test(navigator.userAgent),N=!k&&("ai"===a?!!(navigator.mediaDevices?.getUserMedia&&window.MediaRecorder):!!nc()),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=`${j.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="")=>{j.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]),_=(0,r.useCallback)(function e(){let t=nc();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&&(j.current=`${j.current}${t} `.replace(/\s+/g," "));let n=`${j.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=j.current.trim();e&&h.current?.(e)}},s.onerror=e=>{let t=e?.error||"error";"no-speech"!==t&&"aborted"!==t&&(p(t),f.current?.(t),no.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)}},[]),E=(0,r.useCallback)((e="")=>{k||("ai"===a?C(e):nc()&&(j.current=e?e.replace(/\s*$/,"")+" ":"",p(null),g.current=!0,_()))},[k,a,C,_]),$=(0,r.useCallback)((e="")=>{i?R():E(e)},[i,E,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:E,stop:R,cancel:T,toggle:$}}let nu="(pointer: fine) and (hover: hover)";function nm(){let[e,t]=(0,r.useState)(()=>window.matchMedia(nu).matches?"mouse":"touch");return(0,r.useEffect)(()=>{let e=window.matchMedia(nu),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 nx(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 np(e,t,s,n="flat",a=[]){let[l,i,o]=nx(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]),j=(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:j,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 nh="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]",nf="bg-brand-500 text-white";function nb({label:e,selected:t,onClick:s}){return(0,n.jsx)("button",{type:"button",onClick:()=>{(0,t7.e)(),s()},className:`${nh} ${t?nf:"bg-surface-2 hover:bg-surface-3 text-text"}`,children:e})}function ng({selected:e,onClick:t}){return(0,n.jsx)("button",{type:"button",onClick:()=>{(0,t7.e)(),t()},className:`${nh} ${e?nf:"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 nv({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},j=(e,t)=>o&&o.row===e&&o.col===t,k=(e,t,s)=>{if(!s&&j(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)(nb,{label:r?.label||e,selected:j(t,s),onClick:()=>k(t,s,!1)},e+s)}),(0,n.jsx)(ng,{selected:j(t,e.length),onClick:()=>k(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)(nb,{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 ny({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 nw={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~"},nj={ArrowUp:"\x1b[1;5A",ArrowDown:"\x1b[1;5B",ArrowRight:"\x1b[1;5C",ArrowLeft:"\x1b[1;5D"},nk={ArrowUp:"\x1b[1;2A",ArrowDown:"\x1b[1;2B",ArrowRight:"\x1b[1;2C",ArrowLeft:"\x1b[1;2D"},nN={"[":"\x1b","]":"\x1d","\\":"\x1c","@":"\0","?":""};var nS=s(70362),nC=s(50068);function nT({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)(nS.A,{size:13,className:"text-brand-500",fill:"currentColor"}):(0,n.jsx)(nC.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 nR=[.3,.6,.85,1,.75,.9,1,.65,.35],n_=[.4,.8,1,.7,.9,.5,.85,.35],nE=(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:n_.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:nR.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}),n$=RegExp(`^\\s*(${eP.verbs.join("|")})\\s+(\\S*)$`,"i"),nM=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]??""),j=tS(e=>e.setDraft),k=(0,r.useCallback)(e=>{j(t,"function"==typeof e?e(tS.getState().drafts[t]??""):e)},[j,t]),[N,S]=(0,r.useState)(!1),[C,T]=(0,r.useState)(!1),[R,_]=(0,r.useState)(!1),[E,$]=(0,r.useState)(!1),M=s3(e=>e.addCommand),P=s3(e=>e.resolveAlias),A=s3(e=>e.history),z=s3(e=>e.pinned),L=(0,r.useRef)(null),I=(0,r.useRef)(null),D=(0,r.useRef)(!1),F=(0,r.useRef)(-1);(0,r.useRef)("");let B=tS(e=>e.cwdBySession[t]),[O,W]=(0,r.useState)([]),[K,U]=(0,r.useState)(-1),[H,q]=(0,r.useState)(-1),V=(0,r.useMemo)(()=>O.length>0?[]:ns(w,A,z,en,N),[w,A,z,N,O]),X=(e,t)=>e<0||!t?-1:(e%t+t)%t,G=X(K,O.length),J=X(H,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}=ny({bus:e,sessionId:t}),[eo]=ni(f),ec=nd({lang:na(eo),onText:e=>{k(e);let t=L.current;t&&requestAnimationFrame(()=>{try{t.selectionStart=t.selectionEnd=t.value.length}catch{}t.scrollTop=t.scrollHeight})}}),ed="mouse"===nm();(0,r.useEffect)(()=>{let e=L.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=n$.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,B),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,B,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=np("terminal.basicKeys",eA,ez,"flat",[["esc","up","down","ctrlC","ctrl","opt","shift","tab"]]),ej=np("terminal.extraKeys",eA,eI,"grid"),ek=(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):nN[e]??e}return s?nw[e]?"\x1b"+nw[e]:1===e.length?"\x1b"+e:nw[e]||e:t&&nw[e]?e.startsWith("Arrow")?nj[e]||nw[e]:"Home"===e?"\x1b[1;5H":"End"===e?"\x1b[1;5F":nw[e]:n&&nw[e]?"Tab"===e?"\x1b[Z":e.startsWith("Arrow")&&nk[e]||nw[e]:n&&1===e.length?e.toUpperCase():nw[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(()=>L.current?.focus(),100)},focus:()=>{L.current?.focus({preventScroll:!0})}}),()=>l(null)},[l]);let eN=(0,r.useCallback)(()=>{T(!0),setTimeout(()=>I.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=ek(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,ek,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=ek(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===L.current;s&&L.current?.blur();let n=L.current?.value??w;L.current&&(L.current.value=""),k(""),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&&L.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`,e_=`${eT} bg-surface-2 hover:bg-surface-3 text-text text-sm`,eE=(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?e_: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?eO:eB,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:I,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:ej.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?eE(n,100*t+s,!0):null})}),0===t&&(0,n.jsx)("button",{onMouseDown:e=>e.preventDefault(),onClick:()=>{(0,t7.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)(nE,{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)(nT,{items:O,activeIndex:G,onSelect:e=>{k(e),L.current?.focus()}}),(0,n.jsx)(nn,{value:w,store:s3,commonCommands:en,isMobile:N,disabled:O.length>0,activeIndex:J,onSelect:e=>{k(e),L.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:L,value:w,onChange:e=>{k(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(O.length>0){s.preventDefault();let e=s.shiftKey?-1:1;U(t=>O.length?((t+e)%O.length+O.length)%O.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=ek("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&&(sH()?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(O.length>0&&G>=0){s.preventDefault(),k(O[G].full),U(-1),L.current?.focus();return}if(V.length>0&&J>=0){s.preventDefault(),k(V[J].cmd),q(-1),L.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?sH()?"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:()=>{k(""),L.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!==eL).map((e,t)=>eE(e,t))}),(p=eA.find(e=>e.id===eL))?(0,n.jsx)("div",{className:"flex-shrink-0",children:eE(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:eB,title:h("mobileKeyboard.toggleExtraKeys"),children:b?(0,n.jsx)(t3.X,{size:16}):(0,n.jsx)(t3.a4,{size:16})})]})}),(0,n.jsx)(nv,{isOpen:R,onClose:()=>_(!1),title:h("mobileKeyboard.customizeTerminalKeys"),tabs:[{id:"basic",label:h("mobileKeyboard.mainBar"),hook:ew,excludeIds:[eL]},{id:"extra",label:h("mobileKeyboard.extraPanel"),hook:ej}]}),(0,n.jsx)(s9,{isOpen:E,onSelect:e=>{k(e),L.current?.focus()},onClose:()=>$(!1)})]})}),nP={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"}},nA=e=>nP[e]||nP.idle,nz=e=>{let t=nA(e);return`term-dot ${t.cls}${t.pulse?` pulse-${t.pulse}`:""}`},nL={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"},nI=new Proxy({},{get:(e,t)=>"string"==typeof t&&t&&s$(t)||void 0});function nD({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=nA(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}}),nI[e.tool]&&!t?(0,n.jsx)("img",{src:nI[e.tool],alt:e.tool,className:`w-5 h-5 flex-shrink-0 ${sE}`}):(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:[nL[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 nF({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=nA(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 nB="custom_ports",nO="site_labels";function nW(e,t){try{let s=localStorage.getItem(e);return s?JSON.parse(s):t}catch{return t}}function nK(e,t){localStorage.setItem(e,JSON.stringify(t))}let nU=()=>nW(nB,[]),nH=()=>nW(nO,{});async function nq(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 nV(e,t){return t&&"https:"!==window.location.protocol?`http://${t}`:e||null}async function nX(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 nG({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}),[j,k]=(0,r.useState)({}),[N,S]=(0,r.useState)(null),[C,T]=(0,r.useState)(""),R=(0,r.useRef)({}),_=si(e=>e.cachedSites),E=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,L=o||(()=>h(!1)),I=async()=>{E&&0!==E.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 nq(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=nV(e,u()?.localIp);await Promise.all(n.map(e=>nX("end",{busRef:s,base:r,apiKey:t,port:Number(e)}).catch(()=>{})))};(0,r.useEffect)(()=>{z?(x(nU()),k(nH()),(!E||0===E.length)&&_&&_.length>0&&(P(_),A(!1)),I()):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),L();return}let l=nV(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 nX("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 nX("end",{busRef:s,base:l,apiKey:t,port:r}).catch(e=>console.error(`[SitesList] Cleanup failed for port ${r}:`,e)))},1e3)},B=()=>{L(),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 O=()=>{let e=parseInt(g,10);if(isNaN(e)||e<1||e>65535)return;let t=E.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),nK(nB,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={...j};e?t[N]=e:delete t[N],k(t),nK(nO,t),S(null),T("")},U=()=>{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:B,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:B,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&&O(),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:O,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===E.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=>!E.some(t=>t.port===e)).map(e=>{let t=N===e,s=j[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&&U()},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,j[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),nK(nB,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}`)}),E.map(e=>{let t=N===e.port,s=j[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&&U()},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,j[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:E.length>0?c("sites.foundCount",{n:E.length,suffix:E.length>1?"s":""}):""}),(0,n.jsxs)("button",{onClick:I,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 nJ=(0,Z.v)(e=>({isOpen:!1,open:()=>e({isOpen:!0}),close:()=>e({isOpen:!1})}));function nY(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 nZ(e,t){return!!e&&!!t&&nY(e,t)}function nQ(e,t){return!!e&&!!t&&nY(t,e)}function n0({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=nZ(e,t)||!!s,p=nQ(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 n1=s(62004);function n2(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 n5(e){return e?.path?e.path:e?.items?.find(e=>e.workspacePath)?.workspacePath||null}function n3(e,t){if(!e)return"";let s=e.slice(0,e.lastIndexOf("/"))||"/",n=t.replace(/[^\w.-]+/g,"-");return`${s}/${e.split("/").pop()}-${n}`}function n4({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),[j,k]=(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=>{(0,t7.e)(),b(!1),i?.(e),u(!1)};(0,r.useEffect)(()=>{f&&window.matchMedia("(pointer: fine)").matches&&requestAnimationFrame(()=>T.current?.focus())},[f]);let E=(m||[]).filter(e=>e.isRepo),$=(0,n1.A)(g.trim()).replace(/[^\w.-]+/g,"-").replace(/^-+|-+$/g,""),M=async()=>{if(!y||!$||j||!s?.gitWorktreeAdd)return;let e=n3(y,$);k(!0),S(null);let t=await s.gitWorktreeAdd(y,e,$,!0);if(!t?.success)return k(!1),S(t?.error||"Failed to create worktree");await R(),_(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:()=>_(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")]}),E.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:j,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:E.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:j,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:n3(y,$||"…"),children:n2(n3(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:!$||j||!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:j?(0,n.jsx)(t3.kr,{size:12,className:"animate-spin"}):c("common.create")})]})]})]}),!f&&(E.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:[E.length>0&&s?.gitWorktreeAdd&&(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),w(e=>e||E.find(e=>e.isRoot)?.repoPath||E[0]?.repoPath||null),v(""),S(null),k(!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 n6(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 n8=new Map;function n9({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 j=(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 ${sE}`}),(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 ${sE}`}),(0,n.jsxs)("div",{onClick:()=>j(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:()=>j(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 n7({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=n8.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:n6(r,3e4)};return n8.set(t,a),a}(e,t),n=tS.getState().agentHistory[t];return(!n||Date.now()-n.at>=3e4)&&s.fetchNow(),()=>{let e;!(e=n8.get(t))||(e.count-=1,!(e.count>0)&&(e.stop(),n8.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),j=!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-2 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 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 ${sE} ${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?"":"hidden group-hover:inline"}`,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)})]}),(0,n.jsx)("button",{onClick:t=>{t.stopPropagation(),g(e)},disabled:!o||!!t,className:`flex-shrink-0 p-1 rounded hover:bg-red-500/15 hover:text-red-400 text-text-subtle transition-opacity ${y?"opacity-60 hover:opacity-100":"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:y?13:11})})]},`${e.agent}:${e.sessionId}`)}),j&&(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)(n9,{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 re=null,rt=e=>{re=null==e?null:eQ(e)},rs=/^[A-Za-z]:\/?$/,rn=/^[A-Za-z]:\//,rr=e=>{if(!e||"/"===e||rs.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},ra=e=>e&&"/"!==e?e.split("/").filter(Boolean).pop()??null:null,rl=e=>{let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return -1===t?"":e.slice(0,t+1)},ri=(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 ro(e,t){let s=t.trim().toLowerCase();return s?e.filter(e=>e.name.toLowerCase().includes(s)):e}let rc=e=>e.includes("/")||e.includes("\\")||/^[A-Za-z]:$/.test(e)||"~"===e||"."===e||".."===e;function rd(e){let t,s,n;if(!rc(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(rn.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 ru({fileBus:e,initialPath:t,onSelect:s,onClose:a}){let{t:l}=(0,se.s)(),[i]=(0,r.useState)(()=>t||re||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),[j,k]=(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),_=(0,r.useRef)(null),E=(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),L=(0,r.useRef)(""),I=(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:eQ(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;k(e);let s=eQ(e.homedir);s&&(z.current=s,i||I.current||(I.current=!0,F(s)))}),()=>{t=!0}},[e,i,F]);let B=(0,r.useCallback)(e=>{(0,t7.e)(),rt(e),b(""),w(null),v(0),R.current++,L.current="",_.current&&(clearTimeout(_.current),_.current=null),F(e)},[F]),O=(0,r.useCallback)(()=>{o&&B(rr(o))},[o,B]),W=(0,r.useCallback)(async e=>{let t,s=rd(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=n2(r,j?.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=rr(r)||"/");continue}r=s.path}let t=await D(r);if(n!==R.current)return;L.current=rl(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,j,l]),K=(0,r.useCallback)(e=>{if(b(e),v(0),e.length>2048||!rc(e)){y&&(w(null),R.current++),_.current&&(clearTimeout(_.current),_.current=null);return}let t=rd(e);"path"!==t.mode||!y||y.error||t.invalid||rl(e)!==L.current?(_.current&&clearTimeout(_.current),_.current=setTimeout(()=>{_.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 U=(0,r.useMemo)(()=>ro(d,f),[d,f]),H=(0,r.useMemo)(()=>y?ro(y.entries,y.filter):[],[y]),q=y?H:U;(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=ra(o),G=j?eQ(j.homedir):null,J=!!j?.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:O,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:()=>B(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:()=>B(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:()=>B("/"),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:()=>B(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:()=>B(ri(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})]},ri(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||(E.current&&clearTimeout(E.current),E.current=setTimeout(()=>{E.current=null,_.current&&(clearTimeout(_.current),_.current=null);let e=S.current?.value??"";e.length<=2048&&rc(e)&&W(e)},0))},onKeyDown:e=>{if("Enter"===e.key){if(y){if(y.error||y.loading)return void e.preventDefault();let t=rd(f);if("path"===t.mode&&""===t.trailingFilter){e.preventDefault(),B(y.resolvedPath);return}return void(1===H.length?(e.preventDefault(),B(H[0].path)):e.preventDefault())}let t=1===U.length?U[0]:U[g];return void(t&&(e.preventDefault(),B(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++,_.current&&(clearTimeout(_.current),_.current=null)):"Backspace"!==e.key||""!==f||y||(e.preventDefault(),O())},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=eQ(e.path);return(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),rt(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:ra(t)||t}),(0,n.jsx)("span",{className:"block text-[10px] text-text-subtle truncate",children:n2(t,G)})]})]},e.path)})})]}),!f&&!y&&!o&&(0,n.jsx)("div",{className:"p-2 space-y-1",children:J?j?.drives?.map(e=>(0,n.jsx)(rm,{icon:(0,n.jsx)(t3.ak,{size:15,className:"text-blue-500/70"}),label:eQ(e.path),onClick:()=>B(eQ(e.path))},e.letter)):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(rm,{icon:(0,n.jsx)(t3.ww,{size:15,className:"text-blue-500/70"}),label:G||"/",onClick:()=>B(G||"/")}),(0,n.jsx)(rm,{icon:(0,n.jsx)(t3.ak,{size:15,className:"text-text-subtle"}),label:"/",onClick:()=>B("/")})]})}),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,B(e.path)},220))},onDoubleClick:()=>{!y?.loading&&($.current&&(clearTimeout($.current),$.current=null),rt(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?n2(y.resolvedPath,G):o?n2(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&&(rt(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 rm({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 rx=new Set(["opencode-ui","antigravity-ui"]),rp=["⌥","⇧","↵"],rh=["Ctrl","⇧","↵"],rf=[{id:"new",icon:t3.BK,labelKey:"terminal.newTerminal"},{id:"history",icon:t3.BZ,labelKey:"agentHistory.title"}];function rb({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 ${sE}`}):(0,n.jsx)(t3.BK,{size:16,className:"text-text-muted"})}function rg({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}){let{t:f}=(0,se.s)(),b=s0(l),[g,v]=(0,r.useState)(()=>sF().agentId),[y,w]=(0,r.useState)(""),[j,k]=(0,r.useState)(null),[N,S]=(0,r.useState)(!1),[C,T]=(0,r.useState)(()=>sF().yolo),[R,_]=(0,r.useState)(()=>{let e=sI(sA);return e&&s.some(t=>t.id===e)?e:s[0]?.id||""}),[E,$]=(0,r.useState)("new"),M=(0,r.useRef)(null),P=(0,r.useRef)(null),A=(0,r.useRef)(!1);(0,r.useEffect)(()=>{window.matchMedia("(pointer: fine)").matches&&requestAnimationFrame(()=>M.current?.focus())},[]);let z=sH()?rp:rh;(0,r.useEffect)(()=>{!A.current&&b?.length&&g&&(A.current=!0,P.current?.querySelector("[data-picked=true]")?.scrollIntoView({block:"nearest"}))},[b,g]);let L=s1.H8.filter(e=>!rx.has(e.id)),I=(b||[]).flatMap(e=>{let t=L.find(t=>t.aiEngine===e.id);return t?[e,t]:e});for(let e of L)I.includes(e)||I.push(e);let D=g&&I.find(e=>e.id===g)||null,F=[null,{empty:!0},...I],B=!D?.isAiUi&&sM(D),O=D?.yolo||(D?.yoloEnv?Object.entries(D.yoloEnv).map(([e,t])=>`${e}=${t}`).join(" "):null),W=e=>{(0,t7.e)(),v(e?.id||"")},K=a.match(/\d+$/)?.[0],U=D?`${D.short||D.label}${K?` ${K}`:""}`:a||f("terminal.defaultName"),H=j||i,q=!!u&&!!H,V=q&&"history"===E,X=(s=D)=>{(0,t7.e)(),!s&&R&&sD(sA,R),sD(sz,s?.id||""),sD(sL,C?"1":"0");let n=C&&sM(s),r=K?` ${K}`:"",a=y.trim(),l=a||(s?`${s.short||s.label}${r}`:null);t?.(l,!s&&R||null,s,n,j,!a),e?.()},G=(0,r.useRef)(X);return(0,r.useEffect)(()=>{G.current=X}),(0,r.useEffect)(()=>{let t=t=>{if(!N&&!t.target?.closest?.("[data-wt-form]")){if("Escape"===t.key)t.preventDefault(),t.stopPropagation(),e?.();else if("Enter"===t.key&&"new"===E){if(t.target?.tagName==="BUTTON"){t.target?.getAttribute("role")==="radio"&&(t.preventDefault(),t.stopPropagation(),G.current());return}if(t.target?.tagName==="SELECT")return;t.preventDefault(),t.stopPropagation(),G.current()}}};return window.addEventListener("keydown",t,!0),()=>window.removeEventListener("keydown",t,!0)},[N,E,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 ${V?"pb-0":"pb-3"}`,children:[(0,n.jsxs)("div",{className:`flex gap-2 ${q?"items-stretch -mx-4 px-4 border-b border-border-subtle":"items-center"}`,children:[q?(0,n.jsx)("div",{role:"tablist",className:"flex-1 min-w-0 flex items-stretch gap-3",children:rf.map(({id:e,icon:t,labelKey:s})=>(0,n.jsxs)("button",{role:"tab","aria-selected":E===e,onClick:()=>{(0,t7.e)(),$(e)},className:`pb-2 -mb-px flex items-center gap-1.5 text-sm font-semibold border-b-2 transition-colors ${E===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:f(s)})]},e))}):(0,n.jsx)("h2",{id:"newTerminalTitle",className:"flex-1 text-sm font-semibold text-text",children:f("terminal.newTerminal")}),(0,n.jsx)("button",{onClick:e,"aria-label":f("common.cancel"),className:"text-text-muted hover:text-text shrink-0 self-center",children:(0,n.jsx)(t3.X,{size:18})})]}),i&&!V&&(0,n.jsx)(n4,{workspacePath:i,workspaceName:o,fileBus:c,homeDir:d,value:j,onChange:k,onBrowse:()=>S(!0)})]}),V?(0,n.jsx)(n7,{variant:"list",busRef:l,cwd:H,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:P,role:"radiogroup","aria-label":f("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:F.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||"")===(D?.id||"");return(0,n.jsxs)("button",{type:"button",role:"radio","aria-checked":s,tabIndex:s?0:-1,onClick:()=>W(e),onDoubleClick:()=>X(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;F[n]?.empty&&(n+=s>0?1:-1),n=Math.max(0,Math.min(F.length-1,n)),F[n]?.empty||(W(F[n]),P.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)(rb,{agent:e}),(0,n.jsx)("span",{className:"flex-1 text-sm font-medium truncate",children:e?e.label:f("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:z.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:[!D&&s.length>0&&(0,n.jsx)("select",{value:R,onChange:e=>_(e.target.value),"aria-label":f("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 ${B?"cursor-pointer":"opacity-50 cursor-not-allowed"}`,children:[(0,n.jsx)("input",{type:"checkbox",checked:B&&C,disabled:!B,onChange:e=>T(e.target.checked),className:"w-4 h-4 accent-brand-500 cursor-pointer disabled:cursor-not-allowed"}),O?(0,n.jsx)("code",{className:"min-w-0 text-xs font-mono text-text-muted truncate",children:O}):(0,n.jsx)("span",{className:"text-xs text-text-muted",children:f("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:f("terminal.nameLabel")}),(0,n.jsx)("input",{id:"newTerminalName",type:"text",ref:M,value:y,placeholder:U,onInput:e=>w(e.target.value),onKeyDown:e=>{"ArrowUp"===e.key&&(e.preventDefault(),P.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:f("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:()=>X(),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:f("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})})]})]})]})]})]})}),N&&(0,n.jsx)(ru,{fileBus:c,initialPath:j||i,onSelect:e=>{S(!1),e&&k(e)},onClose:()=>S(!1)})]})}function rv({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 ry(e,t,s,n=8){let[a,l]=(0,r.useState)({left:t,top:s});return(0,r.useEffect)(()=>{let r=e?.current;if(!r)return;let{width:a,height:i}=r.getBoundingClientRect(),o=window.innerWidth,c=window.innerHeight;l({left:t+a>o-n?Math.max(n,t-a):t,top:s+i>c-n?Math.max(n,s-i):s})},[e,t,s,n]),a}var rw=s(98196);async function rj(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 rk(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 rj(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 rN="none";function rS({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}=rk(a);if("u"<typeof document)return null;let y=eE(d,c),w=i??null,j=[{key:rN,label:eS.none.label},...c.map(e=>({key:`custom:${e.id}`,label:l("menu.bgCustomLabel"),src:e.dataUrl})),...Object.entries(eS).filter(([e])=>e!==rN).map(([e,t])=>({key:e,label:t.label,src:t.src}))];return(0,rw.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:j.map(({key:t,label:r,src:a})=>{let l=t===rN,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===rN?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 rC={y:{pos:"clientY",start:"top",size:"height"},x:{pos:"clientX",start:"left",size:"width"}};function rT({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=rC[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 rR=s(48310),r_=s(38415);let rE="sm:h-8",r$=(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})})]})]})}),rM=["todo","in_progress","needs_input","done"],rP={enabled:!0,llmProvider:"gemini",llmBaseUrl:"",llmKey:"",agentModel:"gemini-3.8-flash",boardScope:"workspace",wakeOnDone:!0,liveKey:"",liveModel:"gemini-3.8-live",liveVoice:"Puck"},rA=[{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"]}],rz="jarvisSettings",rL=["Puck","Charon","Kore","Fenrir","Aoede","Leda"],rI={tasks:{}},rD=(0,Z.v)((e,t)=>({board:rI,sink:null,applyBoard:t=>e({board:t?.tasks?t:rI}),setSink:t=>e({sink:"function"==typeof t?t:null}),moveTask:(s,n)=>{let r=t().board.tasks[s];r&&rM.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})}})),rF=(0,Z.v)((e,t)=>({open:!1,settings:{...rP},setOpen:t=>e({open:!!t}),toggle:()=>e(e=>({open:!e.open})),hydrateSettings:()=>{let t;return e({settings:(!(t={...rP,...(()=>{try{let e=JSON.parse(localStorage.getItem(rz));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(rz,JSON.stringify(n))}catch{}e({settings:n})}}));rF.getState().hydrateSettings();let rB={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"}},rO={needs_input:"border-amber-500/60 animate-pulse",done:"border-border-subtle/60 opacity-70"};function rW({task:e,prev:t,next:s,showWorkspace:r}){let a=rD(e=>e.moveTask),l=rD(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 ${rO[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 rK=(0,r.memo)(function({workspacePath:e=""}){let t=rD(e=>e.board.tasks),s=rF(e=>e.settings.boardScope),a=rF(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(rM.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(${rM.length}, minmax(0, 1fr))`},children:rM.map(e=>{let t=rB[e]||{label:e,cls:"text-text-muted",dot:"bg-text-muted/60"},s=o[e]||[],r=rM.indexOf(e),a=rM[Math.max(0,r-1)],i=rM[Math.min(rM.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)(rW,{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."})]})]})}),rU=(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]})})}),rH="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",rq="text-[11px] text-text-muted px-1";function rV({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 rX({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 rG=(0,r.memo)(function({busRef:e}){let t=rF(e=>e.settings),s=rF(e=>e.setSettings),[a,l]=(0,r.useState)(""),i=rA.find(e=>e.id===t.llmProvider)||rA[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)(rV,{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:rq,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:rH}),(0,n.jsx)("span",{className:rq,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:rH}),(0,n.jsx)("span",{className:rq,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:rH}),(0,n.jsx)("span",{className:rq,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:rA.map(e=>(0,n.jsx)("option",{value:e.id,children:e.label},e.id))})]}),(0,n.jsxs)(rV,{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:rH}),(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:`${rH} 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:rL.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)(rX,{label:"Wake on worker done",hint:"Jarvis checks the fleet and updates the board",value:t.wakeOnDone,onChange:e=>o({wakeOnDone:e})})]})}),rJ=(0,r.memo)(function({busRef:e,onClose:t}){return(0,n.jsx)(rU,{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)(rG,{busRef:e})})})});function rY({busRef:e,fileBus:t=null,workspacePath:a="",onClose:l}){let i=rF(e=>e.settings),o=rD(e=>e.applyBoard),c=rD(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 j=new e({apiKey:t}),k=await j.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=k,!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{k.sendRealtimeInput({media:new Blob([e],{type:"audio/pcm;rate=16000"})})}catch{}},sendStreamEnd:()=>k.sendRealtimeInput({audioStreamEnd:!0})});v.onaudioprocess=e=>{if(h.current.session!==k)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)(rK,{workspacePath:a})}),(0,n.jsx)("div",{className:"flex-1 min-h-0",children:(0,n.jsx)(r$,{bus:p})})]}),d&&(0,n.jsx)(rJ,{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 rZ=new Set(["claude","codex"]),rQ=new Set(["idle","done"]),r0=e=>!!e&&rZ.has(e.endsWith("-ui")?e.slice(0,-3):e),r1=(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:j,unsubscribeFromPush:k,agentVersion:N,busRef:S,carrier:C="ws",isActive:T=!0,shells:R=[],workspaces:_=[],activeWorkspaceId:E=null,onRenameSession:$,onDeleteSession:M,onCreateNamedSession:P,onResumeAgentSession:A=null,onToggleSidebar:z=null,sidebarCollapsed:L=!1,onToggleRightPanel:I,onReorderSession:D,rightPanelOpen:F=!1,updateAvailable:B=null,canSelfUpdate:O=!1,fileBus:W=null,homeDir:K=null}){let{t:U}=(0,se.s)(),H=tS(e=>e.agentBySession||{});sc(e=>e.notifications);let q=sc(e=>e.sessionStatus),V=i||q,{formattedStars:X}=(0,rR.w)(),G="mouse"===nm(),J=(e,t)=>G?sZ(e,t):e,Y=(0,r.useRef)(null),Z=(0,r.useRef)(null),[Q,ee]=(0,r.useState)({sessionId:null,x:0,y:0}),[et,es]=(0,r.useState)(null),en=(0,r.useRef)(null),er=ry(en,Q.x,Q.y),ea=H[Q.sessionId]||V[Q.sessionId]?.tool||e.find(e=>e.id===Q.sessionId)?.agent,el=ea?.endsWith("-ui"),ei=r0(ea),eo=ei&&rQ.has(V[Q.sessionId]?.state||"idle"),[ec,ed]=(0,r.useState)({isOpen:!1,sessionId:null,sessionName:""}),[eu,em]=(0,r.useState)({sessionId:null,name:"",value:""}),[ex,ep]=(0,r.useState)(!1),eh=rF(e=>e.open),ef=rF(e=>e.toggle),eb=rF(e=>!1),eg=rD(e=>Object.values(e.board.tasks).some(e=>"needs_input"===e.status));(0,r.useEffect)(()=>{if(!T||!eb)return;let e=e=>{(e.metaKey||e.ctrlKey)&&"j"===e.key.toLowerCase()&&(e.preventDefault(),ef())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[T,eb,ef]);let{dragId:ev,registerEl:ey,startDrag:ew,consumeClick:ej}=rT({axis:"x",threshold:6,onCommit:D}),ek=(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 eN=si(e=>e.open),eS=nJ(e=>e.isOpen),eC=nJ(e=>e.open),eT=nJ(e=>e.close),eR=tS(e=>e.hiddenHeaderButtons),e_=tS(e=>e.mobileDeviceCount),eE=si(e=>e.setContext),e$=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(),ep(!0))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[T]),(0,r.useEffect)(()=>{if(!Q.sessionId)return;let e=e=>{en.current&&!en.current.contains(e.target)&&ee({sessionId:null,x:0,y:0})},t=e=>{"Escape"===e.key&&ee({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)}},[Q.sessionId]);let eM=(0,r.useRef)(null),eP=()=>{eM.current&&(clearTimeout(eM.current),eM.current=null)},eA=e=>{ed({isOpen:!0,sessionId:e.id,sessionName:e?.name||U("terminal.defaultName")}),ee({sessionId:null,x:0,y:0})},ez=_.find(e=>e.id===E)||null;return(0,r.useEffect)(()=>{if(!Z.current||!Y.current)return;let e=requestAnimationFrame(()=>{let e=Y.current,t=Z.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&&(eE({connected:a,remoteAvailable:!!u,codespaceInfo:g,showTheme:!1,busRef:S,tunnelUrl:v,apiKey:y,connectionMode:w,subscribeToPush:j,unsubscribeFromPush:k,agentVersion:N,carrier:C}),e$({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,j,k,eE,e$]),(0,n.jsxs)("div",{className:`h-9 ${rE} px-2 sm:pl-0 sm:pr-2 flex items-stretch gap-0 flex-shrink-0 bg-bg border-b border-border-subtle`,children:[z&&L&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),z()},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:J(U("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:U("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:Y,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=V[t.id]?.state||"idle",i=nA(l),c=t.name||U("terminal.defaultName"),d=s$(H[t.id])||s$(H[t.id]?.replace(/-ui$/,""));return(0,n.jsxs)("div",{role:"button",tabIndex:0,ref:e=>{ey(t.id)(e),r&&(Z.current=e)},onMouseDown:e=>e.preventDefault(),onPointerDown:s=>{"mouse"===s.pointerType&&D&&a&&(eP(),ew(s,t.id,e.map(e=>e.id)))},onClick:()=>{ej()||((0,t7.e)(),o?.(t.id))},onKeyDown:e=>{("Enter"===e.key||" "===e.key)&&(e.preventDefault(),o?.(t.id))},onContextMenu:e=>{e.preventDefault(),(0,t7.e)(),ee({sessionId:t.id,x:e.clientX,y:e.clientY})},onTouchStart:e=>{let s;return s=e.touches[0],void(eM.current=setTimeout(()=>{(0,t7.e)(),ee({sessionId:t.id,x:s.clientX,y:s.clientY})},500))},onTouchMove:eP,onTouchEnd:eP,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":""} ${ev===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"===l&&d?(0,n.jsx)("img",{src:d,alt:"",className:`w-3.5 h-3.5 object-contain ${sE} ${M?"sm:group-hover:hidden":""}`}):(0,n.jsx)("span",{className:`w-1.5 h-1.5 rounded-full term-dot ${i.cls}${i.pulse?` pulse-${i.pulse}`:""} ${M?"sm:group-hover:hidden":""}`,style:{background:i.dot},title:U(i.label)}),M&&(0,n.jsx)("button",{type:"button",tabIndex:-1,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),(0,t7.e)(),eA(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:J(U("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":c,children:c})]},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)(),ep(!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:J(U("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&&O&&(nZ(N,"3.0.3")||!!B)&&(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:U("menu.updateAvailableTitle"),children:[(0,n.jsx)(t3.f5,{size:13}),(0,n.jsx)("span",{children:"Update 9Remote"})]}),!eR.includes("remote")&&u&&(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:U("menu.remoteDesktop"),children:(0,n.jsx)(t3.VA,{size:16})}),!eR.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] ${e_>0?"text-green-400":"text-text hover:text-text"}`,title:e_>0?U("mobile.deviceRunning",{count:e_}):U("mobile.androidDevice"),children:(0,n.jsx)(t3.wO,{size:16})}),!eR.includes("sites")&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),eC()},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:U("menu.sites"),children:(0,n.jsx)(t3.qz,{size:16})}),eb&&(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),ef()},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 ${eg?"text-amber-400":"text-text hover:text-text"}`,title:"Jarvis coordinator (⌘J / Ctrl+J)",children:[(0,n.jsx)(t3.cC,{size:16}),eg&&(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"})]}),!eR.includes("notifications")&&(0,n.jsx)(nF,{sessionStatus:V,allSessions:t,onSwitchSession:o}),!eR.includes("notifications")&&(0,n.jsx)(nD,{sessions:e,allSessions:t,sessionStatus:V,onSwitchSession:o,workspaces:_}),I&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),I()},className:`hidden sm:block p-1.5 rounded-brand transition duration-150 ease-out active:scale-[0.94] hover:bg-surface-2 ${F?"text-brand-500":"text-text hover:text-text"}`,title:J(U("workspaces.tabFiles"),"toggleRightPanel"),children:(0,n.jsx)(t3.jz,{size:16})}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),eN()},className:`p-1.5 text-text hover:bg-surface-2 hover:text-text rounded-brand transition duration-150 ease-out active:scale-[0.94] ${z?"sm:hidden":""}`,title:U("menu.title"),children:(0,n.jsx)(t3.wB,{size:16})})]}),Q.sessionId&&(0,n.jsxs)("div",{ref:en,className:"fixed z-[60] menu-popover p-1 min-w-[140px] animate-in fade-in zoom-in-95 duration-100",style:{left:er.left,top:er.top},children:[V[Q.sessionId]?.state==="done"&&(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),sc.getState().clearNotification(Q.sessionId),ee({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})," ",U("sessions.markRead")]}),(0,n.jsxs)("button",{onClick:()=>{var t;em({sessionId:(t=e.find(e=>e.id===Q.sessionId)).id,name:t.name||"",value:t.name||""}),ee({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})," ",U("sessions.editName")]}),(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),es(Q.sessionId),ee({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"})," ",U("menu.terminalBackground")]}),V[Q.sessionId]?.conversationId&&(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)();let e=Q.sessionId;H[e]?.endsWith("-ui")?S?.current?.emit("ai:restart",{sessionId:e}):S?.current?.emit("session-resume",{sessionId:e}),ee({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})," ",H[Q.sessionId]?.endsWith("-ui")?U("sessions.restartAi")||"Restart AI":U("sessions.resumeSession")]}),ei&&(0,n.jsxs)("button",{disabled:!eo,onClick:()=>{(0,t7.e)();let e=Q.sessionId;S?.current?.emit("setSessionMode",{sessionId:e,mode:el?"terminal":"ui"},e=>{e?.success||alert(e?.error||U("sessions.modeSwitchFailed"))}),ee({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 ${eo?"text-text hover:bg-surface-2/80":"text-text-subtle cursor-not-allowed"}`,children:[(0,n.jsx)(t3.sU,{size:13})," ",el?U("sessions.openAsTerminal"):U("sessions.openAsUi")]}),(0,n.jsxs)("button",{onClick:()=>eA(e.find(e=>e.id===Q.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})," ",U("sessions.deleteTitle")]})]}),et&&(0,n.jsx)(rS,{sessionId:et,title:e.find(e=>e.id===et)?.name,busRef:S,onClose:()=>es(null)}),eu.sessionId&&(0,n.jsx)(rv,{title:U("sessions.editName"),placeholder:eu.name,value:eu.value,onChange:e=>em({...eu,value:e}),onSubmit:()=>{let e=eu.value.trim();eu.sessionId&&e&&$?.(eu.sessionId,e),em({sessionId:null,name:"",value:""})},onClose:()=>em({sessionId:null,name:"",value:""})}),ex&&(0,n.jsx)(rg,{onClose:()=>ep(!1),onCreate:(e,t,s,n,r,a)=>{P?P(e,E,t,r||null,s,n,a):c?.()},shells:R,busRef:S,suggestName:`${U("terminal.defaultName")} ${e.filter(e=>ty(e)===(E??null)).length+1}`,workspacePath:ez?.path||null,workspaceName:ez?.name||"",fileBus:W,homeDir:K,onResumeAgentSession:A,onSelectSession:o,liveSessionIds:ek,activeSessionId:s,connected:a}),(0,n.jsx)(t9.A,{isOpen:ec.isOpen,onClose:()=>ed({isOpen:!1,sessionId:null,sessionName:""}),onConfirm:()=>{ec.sessionId&&M?.(ec.sessionId)},title:U("sessions.deleteTitle"),message:U("sessions.deleteMessage",{name:ec.sessionName}),confirmText:U("common.delete")}),(0,n.jsx)(nG,{tunnelUrl:v,apiKey:y,busRef:S,isOpen:eS,onClose:eT}),eh&&(0,n.jsx)(rY,{busRef:S,fileBus:W,workspacePath:ez?.path||"",onClose:()=>rF.getState().setOpen(!1)})]})});s(12401);let r2="js|jsx|ts|tsx|css|json|md|txt|html|xml|yaml|yml|sh|py|rb|go|java|c|cpp|h",r5={WEB_HTTP:/https?:\/\/[^\s]+/g,WEB_LOCALHOST:/localhost:\d+[^\s]*/g,FILE_ABSOLUTE:RegExp(`\\/[^\\s:]+\\.(${r2})\\b`,"g"),FILE_RELATIVE:RegExp(`(?:\\.{1,2}\\/)?[^\\s:/]+(?:\\/[^\\s:/]+)*\\.(${r2})\\b`,"g"),FILE_WITH_LINE:RegExp(`[^\\s]+\\.(${r2}):\\d+(?::\\d+)?`,"g"),GIT_MODIFIED:/modified:\s+[^\s]+/g};function r3({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(r5.WEB_HTTP);if(s)return{isUrl:!0,isFile:!1,match:s[0]};let n=t.match(r5.WEB_LOCALHOST);if(n)return{isUrl:!0,isFile:!1,match:`http://${n[0]}`};let r=t.match(r5.FILE_WITH_LINE);if(r)return{isUrl:!1,isFile:!0,match:r[0]};let a=t.match(r5.FILE_ABSOLUTE);if(a)return{isUrl:!1,isFile:!0,match:a[0]};let l=t.match(r5.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 r4=new Map;function r6(e,t){e.fileBus?.gitChangedCount(t).then(t=>{t?.success&&(e.count=t.count||0,e.subs.forEach(t=>t(e.count)))})}function r8(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=r4.get(e))||(t={count:0,stop:null,refs:0,subs:new Set,fileBus:l},r4.set(e,t),r6(t,e),t.stop=n6(()=>r6(t,e),1e4)),t.refs++,t);return a(n.count),n.subs.add(a),()=>{let t;n.subs.delete(a),(t=r4.get(e))&&(t.refs--,t.refs<=0&&(t.stop?.(),r4.delete(e)))}},[e,l,s]),n}var r9=s(42970),r7=s(36890),ae=s(5262),at=s(36834),as=s(10358),an=s(69070),ar=s(79063);let aa={...ar.aC,default:ar.aC.dark};function al({joinClaimed:e,joining:t,gapBusy:s}){return!!(e?.current||t?.current||s)}function ai(e){return e instanceof ArrayBuffer||ArrayBuffer.isView(e)?e instanceof Uint8Array?e:new Uint8Array(e):"string"==typeof e?e:String(e)}let ao=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 ac(e,t,s,n,r){if(!e||e._core?._isDisposed)return;let a=ai(t);r?r.write(a):e.write(a),s&&(s.current.push(a),n.current+=ao(a))}let ad="stale",au=()=>{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},am=/^- \[([ xX])\] ?/;function ax(e){return e.map(e=>`- [${e.done?"x":" "}] ${e.text}`).join("\n")}let ap=new Map,ah=e=>{try{navigator.clipboard?.writeText(e).catch(()=>{})}catch{}};function af({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),[j,k]=(0,r.useState)(null),[N,S]=(0,r.useState)(""),[C,T]=(0,r.useState)(null),R=(0,r.useRef)(new Map),_=(0,r.useRef)(null),[E,$]=(0,r.useState)(!1),[M,P]=(0,r.useState)(""),A=(0,r.useRef)([]),z=(0,r.useRef)(null),L=(0,r.useRef)(0),I=(0,r.useRef)(null),D=(0,r.useRef)(s),[F]=(0,r.useState)(()=>Symbol("note")),B=(0,r.useRef)(o);(0,r.useEffect)(()=>{B.current=o});let O=e=>e.map(e=>({...e,id:++L.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]),U=(0,r.useCallback)(e=>{let s=e(A.current||[]);A.current=s,ap.set(t,s),h(s),window.dispatchEvent(new CustomEvent(eg,{detail:{sessionId:t,items:s,from:F}})),I.current&&clearTimeout(I.current),I.current=setTimeout(()=>{I.current=null,K(ax(A.current))},500)},[K,t,F]);(0,r.useEffect)(()=>{if(!e||!t)return;let s=!1,n=ap.get(t),r=(e,s)=>{for(let t of e)t.id>L.current&&(L.current=t.id);A.current=e,ap.set(t,e),h(e),s&&K(ax(e))};if(n){let e=W();r(e.length?[...n,...O(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(am);return t?{done:" "!==t[1],text:e.slice(t[0].length)}:{done:!1,text:e}}),n=W();n.length&&!t.length&&B.current?.(!0),r(O([...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==_.current){for(let e of(I.current&&(clearTimeout(I.current),I.current=null),s.items))e.id>L.current&&(L.current=e.id);A.current=s.items,ap.set(t,s.items),h(s.items)}};return window.addEventListener(eg,e),()=>window.removeEventListener(eg,e)},[t,F]),(0,r.useEffect)(()=>()=>{I.current&&(clearTimeout(I.current),I.current=null,K(ax(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 H=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),U(e=>[...e,...O(t.map(e=>({done:!1,text:e})))]),z.current?.focus())},q=e=>{(0,t7.e)(),U(t=>t.map(t=>t.id===e?{...t,done:!t.done}:t))},V=()=>{let e=N.trim();e&&null!=j&&U(t=>t.map(t=>t.id===j?{...t,text:e}:t)),k(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))),ah(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)(),U(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),_.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="");_.current=null,T(null),i!==n&&U(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"})}),j===e.id?(0,n.jsx)("input",{value:N,onChange:e=>S(e.target.value),onKeyDown:e=>{"Enter"===e.key&&V(),"Escape"===e.key&&k(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)(),k(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),ah((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)(),U(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
|
-
${ax(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)),E?(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:H,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&&H(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 ab({onOpenRemote:e,onOpenMobile:t}){let{t:s}=(0,se.s)(),r=tS(e=>e.hiddenHeaderButtons),a=tS(e=>e.mobileDeviceCount),l=nJ(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 ag=s(44976);function av({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 ay="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]",aw="sm:w-3.5 sm:h-3.5",aj=(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:j}=(0,ag.D)(),k=sc(e=>a?e.sessionStatus[a]?.state:"idle"),N=i||k||"idle",S=(0,r.useRef)(null),C=(0,r.useRef)(null),T=(0,r.useRef)({width:0,height:null}),[R,_]=(0,r.useState)(null),[E,$]=(0,r.useState)(!1),[M,P]=(0,r.useState)(!1),[A,z]=(0,r.useState)(!1),[L,I]=(0,r.useState)(null),D=tS(e=>e.setRightPanelTab),F=tS(e=>e.openRightPanel),B=tS(e=>e.setRightPanelRoot),O=Q(e=>e.bus),W=e||O,K=tS(e=>e.cwdBySession[a]),U=tS(e=>e.terminalTheme),H=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),j=(0,r.useRef)(null),k=(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),_=(0,r.useRef)(null),[E,$]=(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),L=(0,r.useRef)(null),[I,D]=(0,r.useState)(!1),F=(0,r.useRef)(null),B=(0,r.useRef)([]),O=(0,r.useRef)(0),W=(0,r.useRef)(0),K=(0,r.useRef)(!1),U=(0,r.useRef)(0),H=(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),j.current&&clearTimeout(j.current),j.current=setTimeout(()=>{j.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)(()=>{k.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 r9.B({...ey,fontSize:ew(P),allowTransparency:!0,theme:eC((0,ar.In)(s,n)||aa.dark,"dark"===s?c:"none")}),u=new r7.Y;d.loadAddon(u),d.loadAddon(new at.I),d.unicode.activeVersion="11",p.current=d,h.current=u,d.open(i.current);let m=function(e,t){if(!au())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(!au()||!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}},L.current=new as.n,d.loadAddon(L.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 E=null,M=!1;g.current=()=>{if(!E&&!M)try{b.current=E=new ae.o,E.onContextLoss(()=>{E?.dispose(),E=null,b.current=null}),d.loadAddon(E),d.loadAddon(new an.W),u.fit()}catch(e){M=!0,E=null,console.warn("WebGL unavailable, using DOM renderer")}},y.current=()=>{b.current&&(b.current.dispose(),b.current=null,E=null,u.fit(),ex(),d.refresh(0,d.rows-1))};let A=0,I=()=>{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(I,50)};setTimeout(I,50);let F=new ResizeObserver(()=>k.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-O.current<256)return!1;let n=Date.now();if(!e&&n-U.current<600)return!1;let r=s.viewportY<=5;return(!!e||!!ec.current)&&(r?!!Q.getState().connected&&(K.current=!0,U.current=n,H.current=O.current,ei(!0),x.emit("requestHistory",{sessionId:t,have:H.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;ac(d,e,B,O,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 ej=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(al({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,ek()},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})`),ek()):al({joinClaimed:G,joining:X,gapBusy:eg.isBusy()})?ek():void((0,v.Lq)("reconnect",`${e}: peekSeq ${r} → ${n} → gapFetch`),eg.start(n))})})(e),150)};function ek(){let e=en.current;e&&(en.current=null,ej(e))}er.current=ej;let{handleOutput:eN}=function({sessionId:e,term:t,writeBatcherRef:s,gapFetch:n,refs:r,setHistoryFetching:a}){let l=e=>{var s;let n,l=ai(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,ao(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=ao(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=ai(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":ad);if("gap"===e)return void n.start(a.seq-1,[{data:o,seq:a.seq}]);if(e===ad)return;r.lastSeqRef.current=a.seq}r.userAtTopRef.current=!1,ac(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:H,historyMirrorRef:B,historyBytesRef:O,prefixFragsRef:q,onPrefixSettledRef:ed},setHistoryFetching:ei});x.on("output",eN);let eS=e=>{e&&e.sessionId===t&&e.cwd&&(_.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} 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)ac(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} 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),ac(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:k,fireJoinRef:S,refs:{historyMirrorRef:B,historyBytesRef:O,historyTotalRef:W,historyFetchingRef:K,userAtTopRef:ec,joiningRef:X,joinClaimedRef:G,joinQueueRef:ee,joinGenRef:et,lastSeqRef:V,cwdRef:_,setJoining:Z},setCwd:$}),eR=o>0?setTimeout(eT,o):null;eR||eT(),N.current=eT;let e_=()=>{if(p.current){var e;(e={historyFetching:K,historyHaveAtEmit:H,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),ej("reconnect")}};x.on("connect",e_);let eE=()=>setTimeout(()=>{let e=p.current,t=h.current;e&&!e._isDisposed&&t&&(t.fit(),t.fit(),k.current?.({force:!0}))},600);window.addEventListener("orientationchange",eE);let e$=()=>{!document.hidden&&p.current&&(p.current.refresh(0,p.current.rows-1),Q.getState().connected&&ej("visible"))};return document.addEventListener("visibilitychange",e$),()=>{window.removeEventListener("orientationchange",eE),document.removeEventListener("visibilitychange",e$),F.disconnect(),T.removeEventListener("wheel",R),x.off("connect",e_),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(),j.current&&clearTimeout(j.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,ar.In)(s,n)||aa.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},j=()=>{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(j)},k=null,N=!1,S=null,C=0,T=0,R=0,_=0,E=!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=_=n.clientY,u=Date.now(),m=0,p=0,N=!1,E=!1,e.current?.clearSelection(),k=setTimeout(()=>{!E&&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,_=n.clientY,!E&&Math.hypot(R-C,_-T)>10&&(E=!0,N||clearTimeout(k)),N){t.preventDefault();var a=M(R,_);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(k),$=null,N){N=!1;let t=e.current?.getSelection();t&&t.trim()&&l.current?.(t,{x:R,y:_});return}Math.abs(m)>.3&&(x=requestAnimationFrame(j))};d.current=w,s.addEventListener("touchstart",P,{passive:!0}),s.addEventListener("touchmove",A,{passive:!1}),s.addEventListener("touchend",z,{passive:!0});let L=t=>{let s=e.current;s&&t.deltaY<0&&s.buffer.active.viewportY<=5&&(c.current=!0,o.current?.())};return s.addEventListener("wheel",L,{passive:!0}),()=>{w(),d.current=null,clearTimeout(k),s.removeEventListener("touchstart",P),s.removeEventListener("touchmove",A),s.removeEventListener("touchend",z),s.removeEventListener("wheel",L)}},[t,s,e,n,a,l,i,o,c,d])}({termRef:p,termReady:I,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:_,cwd:E,searchAddonRef:L,termReady:I,joining:Y,doResize:ep,reload:eh,focus:()=>p.current?.focus(),stopMomentum:()=>R.current?.(),historyFetching:el}}({bus:W,sessionId:a,theme:j,terminalTheme:U,isVisible:o,isFocused:c,containerRef:S,mountDelay:d,bgKey:eo?X:"none",onInput:ei,onSelectionMade:(e,t)=>I({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,_(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},_(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)(ab,{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,ar.In)(j,U)||aa.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=r8(eu,h,{enabled:o}),e_=av({isFocused:c,onActivate:()=>u?.(a)}),eE=[p&&c?"terminal-focus-glow":""].filter(Boolean).join(" "),eP=`rgba(${ej},${H??.8})`,eA=`rgba(${ek},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 ${eE}${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:e_.onMouseDown,onTouchStart:e_.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 ${nz(N)}`,style:{background:nA(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)(af,{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 ${E?" 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…"]})}),L&&(0,n.jsx)(r3,{text:L.text,position:L,onOpenUrl:e=>window.open(e,"_blank"),onCopy:e=>{try{navigator.clipboard?.writeText(e)}catch{}},onAddToNote:e=>{I(null),el(e),er(!0)},onClose:()=>{ec.current?.clearSelection(),I(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:ay,title:w("terminalPane.note"),children:(0,n.jsx)(t3.y8,{size:16,className:aw})}),(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:ay,title:w("terminalPane.refresh"),children:(0,n.jsx)(t3.e9,{size:16,className:`${aw} ${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)(),B(t,K||t),window.innerWidth>=760?D("files",t):F()},className:`relative ${ay}`,title:w("terminalPane.openFolderHere"),children:[(0,n.jsx)(t3.vd,{size:16,className:aw}),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 ${ay}`,title:w("terminalPane.artifacts"),children:[(0,n.jsx)(t3.sU,{size:16,className:aw}),(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)(af,{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),ak=new Map,aN={branch:null,dirty:!1,changedCount:0};async function aS(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 aC(e,t,{enabled:s=!0}={}){let[n,a]=(0,r.useState)(aN),l=t||t2.getState();return(0,r.useEffect)(()=>{let t;if(!e||!l||!s)return;let n=((t=ak.get(e))||(t={state:aN,stop:null,refs:0,subs:new Set,fileBus:l},ak.set(e,t),aS(t,e),t.stop=n6(()=>aS(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=ak.get(e))&&(t.refs--,t.refs>0||(t.stop?.(),ak.delete(e)))}},[e,l,s]),n}function aT({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}let aR=!!window.__TAURI__||(0,ee._r)()&&window.location.port===String(f._8);function a_({fileBus:e,cwd:t,basePath:s,homeDir:r}){let{branch:a,dirty:l}=aC(t,e),i=!!a&&!eW.includes(a),o=i?null:t&&s&&t.startsWith(`${s}/`)?t.slice(s.length+1):t&&s&&t!==s?n2(t,r):null;return i||o?(0,n.jsxs)("span",{className:"text-[10px] text-text-subtle truncate leading-tight flex items-center gap-1.5",children:[i&&(0,n.jsx)(aT,{branch:a,dirty:l,className:"truncate italic"}),o&&(0,n.jsx)("span",{className:"truncate opacity-70","data-tip":o,children:o})]}):null}function aE({workspace:e,isActive:t,connected:s,collapsed:r,fileBus:a,onToggleCollapse:l,onSelect:i,onNewTerminal:o,onDelete:c}){let{t:d}=(0,se.s)(),u="mouse"===nm(),{branch:m,dirty:x}=aC(n5(e),a),p="opacity-60 hover:opacity-100 focus-visible:opacity-100";return(0,n.jsxs)("div",{onClick:i,className:`pr-2 py-0.5 flex items-center gap-1 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.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)(aT,{branch:m,dirty:x,className:"truncate flex-shrink-0 max-w-[7rem]"})})]}),o&&(0,n.jsx)("button",{onClick:e=>{e.stopPropagation(),(0,t7.e)(),o()},disabled:!s,className:`p-0.5 text-text-subtle hover:text-brand-500 rounded-[2px] hover:bg-surface-2 transition-colors disabled:opacity-40 ${p}`,title:u&&t?sZ(d("terminal.newTerminal"),"newTerminal"):d("terminal.newTerminal"),children:(0,n.jsx)(t3.FW,{size:12})}),c&&(0,n.jsx)("button",{onClick:e=>{e.stopPropagation(),(0,t7.e)(),c()},disabled:!s,className:`p-0.5 -mr-0.5 text-text-subtle hover:text-red-500 rounded-[2px] hover:bg-surface-2 transition-colors disabled:opacity-40 ${p}`,title:d("workspaces.delete"),children:(0,n.jsx)(t3.TB,{size:12})})]})}let a$=(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,onOpenSettings:b,busRef:g=null,fileBus:v,homeDir:y,cwdBySession:w={},connected:j=!0,width:k=ea.default,onResize:N,onCollapse:S,onResumeAgentSession:C}){let{t:T}=(0,se.s)(),R=tS(e=>e.agentBySession||{}),_=sc(e=>e.notifications),E=sc(e=>e.sessionStatus),$=i||_,M=l||E,P="mouse"===nm()?sZ(T("common.close"),"toggleSidebar"):T("common.close"),A=(0,r.useMemo)(()=>new Set(e.map(e=>e.id)),[e]),z=s?w[s]??e.find(e=>e.id===s)?.cwd??e.find(e=>e.id===s)?.workspacePath??null:null,L=sT(e=>e.canInstall),I=sT(e=>e.isInstalled),D=sT(e=>e.install),F=window.matchMedia("(display-mode: standalone)").matches||!!window.ReactNativeWebView,B=L&&!F&&!I&&!(0,ee.XS)(),[O,W]=(0,r.useState)(null),K=(0,r.useRef)(null),U=ry(K,O?.left??0,O?.top??0),[H,q]=(0,r.useState)(null),V=R[O?.sessionId]||M[O?.sessionId]?.tool||e.find(e=>e.id===O?.sessionId)?.agent,X=V?.endsWith("-ui");M[O?.sessionId]?.conversationId;let G=r0(V),J=G&&rQ.has(M[O?.sessionId]?.state||"idle"),[Y,Z]=(0,r.useState)({sessionId:null,name:"",value:""}),[Q,et]=(0,r.useState)(null),[es,en]=(0,r.useState)({}),[er,el]=(0,r.useState)(null),[ei,eo]=(0,r.useState)({isOpen:!1,workspaceId:null,workspaceName:""}),{dragId:ec,registerEl:ed,startDrag:eu,consumeClick:em}=rT({axis:"y",onCommit:h});(0,r.useEffect)(()=>{if(!O)return;let e=e=>{K.current&&!K.current.contains(e.target)&&W(null)},t=e=>{"Escape"===e.key&&W(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)}},[O]);let ex=function(e=[],t=[],s="Ungrouped"){let n=new Map;for(let t of e){let e=ty(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,t,T("workspaces.ungrouped")),ep=t=>e.find(e=>e.id===t),eh=e=>{e.preventDefault(),e.stopPropagation();let t=e.currentTarget.dataset.sid,s=ep(t);W({sessionId:t,left:e.clientX,top:e.clientY,name:s?.name||""})},ef=(0,r.useRef)(null),eb=()=>{ef.current&&(clearTimeout(ef.current),ef.current=null)},eg=e=>{let t=e.currentTarget,s=""===t.dataset.gid?null:t.dataset.gid,n=ex.find(e=>(e.id??null)===(s??null));n&&j&&(eb(),eu(e,t.dataset.sid,n.items.map(e=>e.id)))},ev=e=>{em()||((0,t7.e)(),o?.(e.currentTarget.dataset.sid))},ey=e=>{let t,s;t=e.currentTarget.dataset.sid,s=e.touches[0],ef.current=setTimeout(()=>{(0,t7.e)();let e=ep(t);W({sessionId:t,left:s.clientX,top:s.clientY,name:e?.name||""})},500)};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:k},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:aR?(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"})]})}),S&&(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),S()},className:"p-1 text-text-muted hover:text-text rounded-[3px] hover:bg-surface-2 transition-colors flex-shrink-0",title:P,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 relative z-10",children:[ex.length?ex.map(e=>{let t=(e.id??null)===(a??null),r=e.id??"";return(0,n.jsxs)("div",{className:"flex flex-col mt-3 first:mt-0",children:[(0,n.jsx)(aE,{workspace:e,isActive:t,connected:j,fileBus:v,collapsed:!!es[r],onToggleCollapse:()=>en(e=>({...e,[r]:!e[r]})),onSelect:e.items.length&&c?()=>{(0,t7.e)(),c(e.id)}:null,onNewTerminal:d?()=>el(e.id??""):null,onDelete:u&&null!==e.id?()=>eo({isOpen:!0,workspaceId:e.id,workspaceName:e.name}):null}),!es[r]&&e.items.map(t=>{let r,a=nA(M[t.id]?.state||"idle"),l=t.id===s,i=!!$[t.id],o=M[t.id]?.tool,c=ec===t.id;return(0,n.jsxs)("div",{ref:ed(t.id),"data-sid":t.id,className:`group w-full flex items-center gap-1.5 pl-5 pr-2 py-1.5 text-left border-l-2 relative cursor-pointer ${l?"bg-text/8 border-brand-500 text-text":"border-transparent text-text-muted hover:bg-text/5 hover:text-text"} ${c?"z-20 opacity-90 shadow-lg ring-1 ring-brand-500":"transition-colors"}`,onClick:ev,onContextMenu:eh,onTouchStart:ey,onTouchMove:eb,onTouchEnd:eb,children:[j&&(0,n.jsx)("button",{"data-gid":e.id??"","data-sid":t.id,onPointerDown:eg,disabled:e.items.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 ${a.cls}${a.pulse?` pulse-${a.pulse}`:""}`,style:{background:a.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 ${l?"font-medium":""}`,children:[R[t.id]?.endsWith("-ui")?(0,n.jsx)("img",{src:s$(R[t.id]),alt:"",className:`w-3.5 h-3.5 flex-shrink-0 object-contain ${sE}`}):nI[o]?(0,n.jsx)("img",{src:nI[o],alt:o,className:`w-3 h-3 flex-shrink-0 object-contain ${sE}`}):(0,n.jsx)(t3.BK,{size:12,className:"flex-shrink-0"}),(r=t.name||T("terminal.defaultName"),(0,n.jsx)("span",{className:"text-[11px] truncate","data-tip":r,children:r}))]}),(0,n.jsx)(a_,{fileBus:v,cwd:w[t.id]??t.cwd??t.workspacePath,basePath:n5(e),homeDir:y})]}),i&&!l&&(0,n.jsx)("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-500 flex-shrink-0",title:T("common.statusDone")})]},t.id)}),!es[r]&&0===e.items.length&&(0,n.jsx)("button",{onClick:t=>{t.stopPropagation(),(0,t7.e)(),el(e.id??"")},disabled:!j,className:"pl-3 pr-2 py-1.5 text-left text-xs text-text-subtle hover:text-brand-500 italic transition-colors disabled:opacity-40",children:T("workspaces.emptyWorkspace")})]},e.id??"ungrouped")}):(0,n.jsx)("p",{className:"px-3 py-6 text-center text-xs text-text-muted",children:T("workspaces.emptyWorkspace")}),f&&(0,n.jsx)("div",{className:"px-2 pt-3 pb-1",children:(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),f()},disabled:!j,className:"w-full flex items-center justify-center gap-1.5 py-1.5 px-3 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:T("workspaces.newWorkspace")})]})})]}),C&&(0,n.jsx)(n7,{busRef:g,cwd:z,onResume:C,onSelectSession:o,liveSessionIds:A,activeSessionId:s,connected:j}),(B||b)&&(0,n.jsxs)("div",{className:"p-1.5 border-t border-border-subtle flex-shrink-0 relative z-10",children:[B&&(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),D()},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:T("menu.installApp"),children:[(0,n.jsx)(t3.f5,{size:14}),(0,n.jsx)("span",{children:T("menu.installApp")})]}),b&&(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),b()},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:T("menu.settings"),children:[(0,n.jsx)(t3.wB,{size:14}),(0,n.jsx)("span",{children:T("menu.settings")})]})]}),(0,n.jsx)(t9.A,{isOpen:ei.isOpen,onClose:()=>eo({isOpen:!1,workspaceId:null,workspaceName:""}),onConfirm:()=>{null!==ei.workspaceId&&u?.(ei.workspaceId),eo({isOpen:!1,workspaceId:null,workspaceName:""})},title:T("workspaces.deleteTitle"),message:T("workspaces.deleteMessage",{name:ei.workspaceName})}),null!==er&&(0,n.jsx)(rg,{onClose:()=>el(null),onCreate:(e,t,s,n,r,a)=>{d?.(e,""===er?null:er,t,r||null,s,n,a)},shells:m,busRef:g,onResumeAgentSession:C,onSelectSession:o,liveSessionIds:A,activeSessionId:s,connected:j,workspacePath:t.find(e=>e.id===er)?.path||null,workspaceName:t.find(e=>e.id===er)?.name||"",fileBus:v,homeDir:y,suggestName:`${T("terminal.defaultName")} ${e.filter(e=>ty(e)===(""===er?null:er)).length+1}`}),(0,n.jsx)("div",{onPointerDown:e=>{e.stopPropagation(),sS(e,{startWidth:k,onWidth:e=>N?.(e)})},className:"absolute top-0 right-0 bottom-0 w-1 cursor-col-resize hover:bg-brand-500/40 transition-colors z-20"}),O&&(0,n.jsxs)("div",{ref:K,className:"fixed z-[70] menu-popover p-1 min-w-[160px] animate-in fade-in zoom-in-95 duration-100",style:{left:U.left,top:U.top},children:[M[O.sessionId]?.state==="done"&&(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),sc.getState().clearNotification(O.sessionId),W(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})," ",T("sessions.markRead")]}),(0,n.jsxs)("button",{onClick:()=>{var e;let t;return e=O.sessionId,t=ep(e)?.name||"",void(Z({sessionId:e,name:t,value:t}),W(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})," ",T("sessions.editName")]}),(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),q(O.sessionId),W(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"})," ",T("menu.terminalBackground")]}),M[O.sessionId]?.conversationId&&(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)();let e=O.sessionId;R[e]?.endsWith("-ui")?g?.current?.emit("ai:restart",{sessionId:e}):g?.current?.emit("session-resume",{sessionId:e}),W(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})," ",R[O.sessionId]?.endsWith("-ui")?T("sessions.restartAi")||"Restart AI":T("sessions.resumeSession")]}),G&&(0,n.jsxs)("button",{disabled:!J,onClick:()=>{(0,t7.e)();let e=O.sessionId;g?.current?.emit("setSessionMode",{sessionId:e,mode:X?"terminal":"ui"},e=>{e?.success||alert(e?.error||T("sessions.modeSwitchFailed"))}),W(null)},className:`w-full text-left px-2.5 py-1.5 text-xs rounded-[6px] flex items-center gap-2 ${J?"text-text hover:bg-surface-2/80":"text-text-subtle cursor-not-allowed"}`,children:[(0,n.jsx)(t3.sU,{size:13})," ",X?T("sessions.openAsTerminal"):T("sessions.openAsUi")]}),(0,n.jsx)("div",{className:"h-px bg-border-subtle my-1"}),(0,n.jsxs)("button",{onClick:()=>{et({sessionId:O.sessionId,name:O.name}),W(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})," ",T("sessions.deleteTitle")]})]}),H&&(0,n.jsx)(rS,{sessionId:H,title:ep(H)?.name,busRef:g,onClose:()=>q(null)}),Y.sessionId&&(0,n.jsx)(rv,{title:T("sessions.editName"),placeholder:Y.name,value:Y.value,onChange:e=>Z({...Y,value:e}),onSubmit:()=>{let e=Y.value.trim();Y.sessionId&&e&&x?.(Y.sessionId,e),Z({sessionId:null,name:"",value:""})},onClose:()=>Z({sessionId:null,name:"",value:""})}),(0,n.jsx)(t9.A,{isOpen:!!Q,onClose:()=>et(null),onConfirm:()=>{Q?.sessionId&&p?.(Q.sessionId)},title:T("sessions.deleteTitle"),message:T("sessions.deleteMessage",{name:Q?.name||""}),confirmText:T("common.delete")})]})}),aM={claude:"Claude",codex:"Codex",kimi:"Kimi",grok:"Grok"};function aP(e){return e<60?"bg-text-muted/40":e<80?"bg-yellow-500":"bg-red-500"}function aA(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=n6(r,6e4);return()=>{s=!0,a()}},[e,t]),s}let az=[["session","5h"],["weekly","wk"],["monthly","mo"]];function aL({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 ${aP(e)}`,style:{width:`${Math.min(100,Math.max(0,e))}%`}})})}function aI({provider:e}){let[t,s]=(0,r.useState)(!1);return t?(0,n.jsx)("span",{className:"text-text-subtle",children:aM[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 ${sE}`})}function aD({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)(aL,{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 aF({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:aM[e.provider]||e.provider}),az.map(([t,s])=>(0,n.jsx)(aD,{label:s,window:e[t]},t)),(e.buckets||[]).map(e=>(0,n.jsx)(aD,{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 aB({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:`${aM[e.provider]||e.provider} ${a("terminal.quotaUsageTitle")}`,children:[(0,n.jsx)(aI,{provider:e.provider}),(0,n.jsx)(aL,{usedPct:r.usedPercent}),(0,n.jsxs)("span",{className:"tabular-nums",children:[Math.round(r.usedPercent),"%"]})]}),t===e.provider&&(0,n.jsx)(aF,{p:e,onClose:()=>s(null)})]},e.provider)})}):null}function aO({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 aW="flex items-center gap-1.5 px-1.5 py-0.5 rounded-[2px] hover:bg-white/10 transition-colors cursor-pointer",aK="flex items-center gap-1.5 px-1.5 py-0.5",aU={darwin:"mac",win32:"win",linux:"linux"};function aH({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 aq=(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}=aC(c,t,{enabled:!!c}),m=(i=aA(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 ${sE}`}),(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 ${aP(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 n6(()=>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)(aH,{pages:b,activeKey:b[v]?.key})]})}),aV=(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=aA(r||b),j=tS(e=>(e.agentBySession||{})[t])||"",k=o||"—",N=j?s$(j):null,{branch:S,changedCount:C}=aC(e,s,{enabled:!!e}),T=nA(y),R=m("working"===y?"common.statusWorking":"blocked"===y?"common.statusBlocked":"done"===y?"common.statusDone":"common.statusIdle"),_=e?n2(e.replace(/\\/g,"/"),u):"";return(0,n.jsx)(aO,{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 ${sE}`}):(0,n.jsx)(t3.BK,{size:12,className:"opacity-60 flex-shrink-0"}),(0,n.jsx)("span",{className:"truncate font-medium text-text",title:k,children:k})]}),(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:_||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)(aB,{quota:w}),d&&(0,n.jsx)("span",{className:"uppercase tracking-wide",children:aU[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})]})]})})}),aX=(e,t,s)=>Math.max(t,Math.min(s,e));function aG(e){let t=window.innerWidth-48,s=window.innerHeight-36;return{...e,x:aX(e.x,12-e.w+48,t),y:aX(e.y,12,s)}}function aJ(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 aY="VideoDecoder"in window&&"EncodedVideoChunk"in window,aZ=/^(\d\d-\d\d \d\d:\d\d:\d\d\.\d+)\s+\d+\s+\d+\s+([VDIWEF])\s+([^:]*):\s?(.*)$/;function aQ({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 a0({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)(aQ,{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 a1(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 a2({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,rw.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}%`:`${a1(x.received)}${x.total?` / ${a1(x.total)}`:""}${x.bytesPerSec?` \xb7 ${a1(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 a5({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]),j="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:j,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:j?(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 a3({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 a4({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)([]),j=(0,r.useCallback)(async()=>{let t=await tG(e?.current,"mobile:provisionPresets",{});t?.success&&w(Array.isArray(t.presets)?t.presets:[])},[e]),k=(0,r.useCallback)(async t=>{d(null);let s=await tG(e?.current,"mobile:provision",{presetId:t});return await Promise.all([b(),j()]),!!s?.success||(d(s?.error||"Could not create device"),!1)},[e,b,j]),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:j,provision:k,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:j,setLowPower:k,sdkJob:N,presets:S,refreshPresets:C,provision:T,cancelSetup:R,deleteAvd:_,wipeAvd:E}=h,{serial:$,meta:M,starting:P,error:A,open:z,stop:L}=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=tH[e]||tH[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:I}=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||!aY)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=aJ(r).spsBytes;e&&x(e);return}if(t&&a.decoder?.state!=="configured"){if(!a.config)return void d();let e=aJ(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:aY?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]),j=(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:j}}({busRef:t,protocolRef:s,serial:$,enabled:!!M}),B=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=aZ.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 O="panel"===l,W=f.find(e=>e.serial===$)||null,K=(0,r.useCallback)(async()=>{m(!1),L(),$&&await w($)},[$,L,w]),U=(0,r.useCallback)(async e=>{e.serial===$&&L(),await w(e.serial)},[$,L,w]),H=(0,r.useCallback)(()=>{O||L(),e?.()},[O,L,e]);if(!M){let e;return(0,n.jsxs)("div",{className:"absolute inset-0 flex flex-col bg-bg",children:[!O&&(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)(),H()},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})]}):aY?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(a0,{devices:f,canManage:b,booting:g,loading:!h.loaded,error:A||h.error,onOpen:z,onStop:U,onRefresh:v,lowPower:j,onLowPowerChange:k,onAddDevice:()=>{C(),p(!0)},onDeleteAvd:_,onWipeAvd:E,sdkJob:N,onShowSetup:()=>p(!0)}),(0,n.jsx)(a2,{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"!==I&&(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)(a5,{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)(a3,{logcat:B,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)(a6,{icon:(0,n.jsx)(t3.lM,{size:15,className:"-rotate-90"}),label:i("mobile.back"),onClick:()=>D.sendKey("back")}),(0,n.jsx)(a6,{icon:(0,n.jsx)(t3.jl,{size:15}),label:i("mobile.home"),onClick:()=>D.sendKey("home")}),(0,n.jsx)(a6,{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)(a6,{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)(a6,{icon:(0,n.jsx)(t3.lP,{size:15}),label:i("mobile.tabApps"),onClick:()=>d("apps"===c?null:"apps"),active:"apps"===c}),(0,n.jsx)(a6,{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)(a6,{icon:(0,n.jsx)(t3.wO,{size:15}),label:i("mobile.switchDevice"),onClick:L}),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})}),!O&&(0,n.jsx)(a6,{icon:(0,n.jsx)(t3.X,{size:15}),label:i("common.close"),onClick:H})]})]})}function a6({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 a8=[{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 a9({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?aG(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(aG({...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(aG({...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?aX(l?r.w-s:r.w+s,em,Math.min(ex,h)):r.w,b=u?aX(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)(a4,{busRef:e,protocolRef:t,connected:s,variant:"panel",onClose:x})})]});if(p)return a?(0,rw.createPortal)(h(!1),a):null;let f=m.rect;return f?(0,rw.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),a8.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 a7=e=>(e||"").split("/").filter(Boolean).pop()||e;function le(e,t){return e?e.endsWith("/")?`${e}${t}`:`${e}/${t}`:t}function lt(e){let t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function ls(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 lr(){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 la(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 ll(e,t){let s=await e.gitStatus(t);if(s?.success)return{hasGit:!0,map:la(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=la(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 li(){try{let e=window.localStorage.getItem(tp),t=e?JSON.parse(e):{};return Array.isArray(t)?{legacy:t}:t}catch{return{}}}function lo(){try{let e=window.localStorage.getItem(th);if(null===e)return!0;return!1!==JSON.parse(e)}catch{return!0}}let lc={created:"fileExplorer:fileCreated",deleted:"fileExplorer:fileDeleted",renamed:"fileExplorer:fileRenamed"};function ld(e){window.dispatchEvent(new CustomEvent(lc[e]))}let{xT:lu,Qm:lm,Pv:lx}=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"}}'),lp="/icons/file-types",lh="/icons/folder-types",lf=`${lp}/default.svg`,lb=`${lh}/default.svg`,lg=`${lh}/default-open.svg`;function lv(e,t=!1){let s=lx[(e||"").toLowerCase()];return s?{src:t?`${lh}/${s}-open.svg`:`${lh}/${s}.svg`,alt:s}:{src:t?lg:lb,alt:"folder"}}function ly(e,t=16){let{src:s,alt:r}=function(e){if(!e)return{src:lf,alt:"file"};if("folder"===e.type)return lv(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(lm[t]){let e=lm[t];return{src:`${lp}/${e}.svg`,alt:e}}if(lu[s]){let e=lu[s];return{src:`${lp}/${e}.svg`,alt:e}}return{src:lf,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?ta:tr,lj=(e,t=!1)=>{let s=lw(t);return s.indentBase+e*s.indentStep};function lk({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 ${tn[e]||"text-text-muted"}`,children:e}):null}function lN({depth:e,compact:t=!1}){return(0,n.jsx)("div",{className:"text-[11px] text-text-muted italic py-0.5 pr-2",style:{paddingLeft:lj(e,t)},children:"Showing first 300 entries — use search for the rest."})}let lS=(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:j,onDragOver:k,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=>j(t,e),onDragOver:t=>k(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:lj(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}=lv(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):ly(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 ${tn[u]||""}`,title:e.name,children:e.name}),!o&&(0,n.jsx)(lk,{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 lC(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 lC(t,n,s)}}async function lT(e){let t=[],s=[...e.items||[]].map(e=>e.webkitGetAsEntry?.()).filter(Boolean);if(s.length)for(let e of s)await lC(e,"",t);else for(let s of e.files||[])t.push({file:s,relativePath:s.name});return t}let lR="fixed inset-0 z-50 flex items-center justify-center p-4",l_="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",lE="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]",l$="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 lM({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 lP({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 lA({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:lR,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:`${l$} 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:`${lE} 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:`${lE} 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:l_,autoFocus:!0}),(0,n.jsxs)("div",{className:"flex gap-2",children:[(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),c()},className:`${lE} 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:`${l$} 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 lz({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:lR,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:l_,autoFocus:!0}),(0,n.jsxs)("div",{className:"flex gap-2",children:[(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),a()},className:`${lE} 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:`${l$} 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 lL({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:lR,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 lI(e,t,s,n=!1){if(!e||!t||!s)return{success:!1};let r=le(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 lD="application/x-file-paths",lF=()=>"u">typeof document&&"webkitdirectory"in document.createElement("input"),lB=e=>{let t=e.dataTransfer.getData(lD);if(!t)return null;try{return JSON.parse(t)}catch{return null}},lO=e=>[...e.dataTransfer?.types||[]].includes("Files");function lW({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=ry(h,x?.x??0,x?.y??0),[b,g]=(0,r.useState)(null),[v,y]=(0,r.useState)(""),[w,j]=(0,r.useState)(null),[k,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)(_);(0,r.useEffect)(()=>{$.current=_},[_]);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),[L,I]=(0,r.useState)(!1),[D,F]=(0,r.useState)(null),[B,O]=(0,r.useState)(null),[W,K]=(0,r.useState)(null),[U,H]=(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)(lF),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)(lo),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 ll(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=li())[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",tu];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=li();delete t.legacy,t[e]=[...a],window.localStorage.setItem(tp,JSON.stringify(t))}catch{}},[e,i,a]),(0,r.useEffect)(()=>{window.localStorage.setItem(th,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})},[]),j=(0,r.useCallback)(()=>{(0,t7.e)(),l(new Set)},[]),k=lr(),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:k});let C=(0,r.useRef)(!0);(0,r.useEffect)(()=>{let e=k&&!C.current;C.current=k,e&&s.size&&S([...s.keys()])},[k]);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:j,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=le(s,r),o=await e.createItem(i,l);o?.success&&(ld("created"),await t(s),"folder"===l?n(s):a?.(i))},[e,t,n,a]),o=(0,r.useCallback)(async(s,n)=>{let r=lt(s.path),a=le(r,n),l=await e.renameItem(s.path,a);l?.success&&(ld("renamed"),await t(r))},[e,t]),c=(0,r.useCallback)(async s=>{let n=lt(s.path),r=await e.deleteItem(s.path);r?.success&&(ld("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(lt(t.path))}if(r.size){for(let e of(ld("deleted"),r))await t(e);s(),l?.()}},[e,t,s,l]),u=(0,r.useCallback)(async(t,s)=>{let n=ls(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,le(s,a))},[e]),m=(0,r.useCallback)(async e=>{let n=lt(e.path),r=await u(e.path,n);r?.success&&(ld("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=le(r,t.split("/").pop());t===s||s.startsWith(t+"/")||await e.renameItem(t,s)}for(let e of new Set([r,...n.map(e=>lt(e))]))await t(e);ld("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&&(ld("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:()=>E(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]),ej=(0,r.useCallback)(async e=>{let t=k.trim();if(!t)return;let s=w?.dir||ew();await ep(s,t,e),j(null),N("")},[k,w,ew,ep]),ek=(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=>e.has(t.path)?e:new Set([t.path])),H(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(!to(a))return a;let{repoPath:t,filePath:s}=td(a);return s?`${t||e}/${s}`:null},[a,e]),e_=e=>!d||!!ea[ee(e.path)],eE=(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=>eE.find(t=>t.file.path===e)?.file||null,[eE]),eM=(0,r.useCallback)(e=>{let t=eE.filter(e=>_.has(e.file.path)).map(e=>e.file);return t.length?t:e?[e]:[]},[eE,_]),eP=(0,r.useCallback)((e,t)=>{let s=eE.findIndex(t=>t.file.path===e),n=eE.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(eE.slice(r,a+1).map(e=>e.file.path))},[eE]),eA=(0,r.useCallback)((e,t)=>{if((0,t7.e)(),q.current?.focus({preventScroll:!0}),t?.metaKey||t?.ctrlKey){E(t=>{let s=new Set(t);return s.has(e.path)?s.delete(e.path):s.add(e.path),s}),H(e.path),V.current=e.path;return}if(t?.shiftKey&&V.current){E(eP(V.current,e.path)),H(e.path);return}E(new Set([e.path])),H(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:lt(t.path):e,[e]),eL=(0,r.useCallback)(e=>{let t=eM(e);t.length&&C({files:t})},[eM]),eI=(0,r.useCallback)(async()=>{let e=S?.files||[];C(null),1===e.length?await ef(e[0]):await eb(e),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]),eB=(0,r.useCallback)(async(e,s)=>{if(!e.length)return;let n=0;O({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:()=>O(e=>e?{...e,done:e.done+1}:e),onError:()=>{n+=1,O(e=>e?{...e,done:e.done+1,failed:n}:e)}}),O(e=>e&&n?e:null),K(null),await eo(s),eu(s),ec()},[t,eo,eu,ec]),eO=(0,r.useCallback)(async(e,t)=>{eB(await lT(e),t)},[eB]),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(lD,JSON.stringify(n)),e.dataTransfer.effectAllowed="move"},[]),eU=(0,r.useCallback)((e,t)=>{let s=lO(e);("folder"===t.type||s)&&(e.preventDefault(),e.dataTransfer.dropEffect=s?"copy":"move","folder"===t.type&&z(t.path))},[]),eH=(0,r.useCallback)(e=>{z(t=>t===e.path?null:t)},[]),eq=(0,r.useCallback)((e,t)=>{let s=lO(e);if("folder"!==t.type&&!s)return;if(e.preventDefault(),e.stopPropagation(),z(null),I(!1),s)return void eO(e.dataTransfer,ez(t));let n=lB(e);n&&ev(n,t.path)},[eO,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="",j(null),eB(s,t)},[w,ew,eB]),eX=(0,r.useCallback)((e,t)=>{if(!eE.length)return;let s=eE.findIndex(e=>e.file.path===U),n=eE[Math.min(eE.length-1,Math.max(0,-1===s?0:s+e))];if(!n)return;let r=n.file.path;t&&V.current?E(eP(V.current,r)):(E(new Set([r])),V.current=r),H(r),q.current?.querySelector(`[data-path="${CSS.escape(r)}"]`)?.scrollIntoView({block:"nearest"})},[eE,U,eP]),eG=(0,r.useCallback)(e=>{if(b||w||S)return;let t=e$(U),n=e.metaKey||e.ctrlKey;if(n&&"a"===e.key.toLowerCase()){e.preventDefault(),E(new Set(eE.map(e=>e.file.path))),V.current=eE[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(),sH()?(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(),eL(t);return;case"Escape":E(new Set),F(null);return}},[b,w,S,U,e$,eE,es,ed,s,eX,eD,eF,eL]),eJ=(e,t)=>{if(!e_(e))return null;let s="folder"===e.type,r=s&&es.has(e.path),a=_.has(e.path);return(0,n.jsx)(lS,{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:ek,onRenameCancel:eW,onToggleFolder:ed,onClick:eA,onContextMenu:eS,onTouchStart:eC,onTouchEnd:eT,onDragStart:eK,onDragOver:eU,onDragLeave:eH,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)(lN,{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)(()=>ls(e),[e]),eQ=(e,t)=>{(0,t7.e)(),j({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 lI(t,e,n,"folder"===s.type);r?.success&&(ec(),window.dispatchEvent(new CustomEvent(tu)))},[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 ${L?"ring-2 ring-inset ring-brand-500/40 bg-brand-500/5":""}`,onDragOver:e=>{e.preventDefault();let t=lO(e);e.dataTransfer.dropEffect=t?"copy":"move",t&&I(!0)},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||I(!1)},onClick:e=>{e.target===e.currentTarget&&(E(new Set),R(null))},onDrop:t=>{if(t.preventDefault(),I(!1),lO(t))return void eO(t.dataTransfer,e);let s=lB(t);s&&ev(s,e)},children:d&&!eY.some(e_)?(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)}),tt(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:()=>eL(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:()=>j(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:k,onChange:e=>N(e.target.value),onKeyDown:e=>{"Enter"===e.key?ej(w.type):"Escape"===e.key&&j(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)(),j(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)(),ej(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})]}),B&&(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:B.failed?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"text-danger",children:m("fileExplorer.uploadFailedCount",{n:B.failed,total:B.total})}),(0,n.jsx)("button",{type:"button",onClick:()=>O(null),className:"ml-auto underline hover:text-text",children:m("common.close")})]}):(0,n.jsx)("span",{children:m("fileExplorer.uploadingCount",{n:Math.min(B.done+1,B.total),total:B.total})})}),W&&(0,n.jsx)(lL,{name:W.name,onResolve:e=>{W.resolve(e),K(null)}}),(0,n.jsx)(t9.A,{isOpen:!!S,onClose:()=>C(null),onConfirm:eI,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 lK({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 lU={Copy:t3.QR,FileText:t3.iU,ExternalLink:t3.Gr,Undo2:t3.bE,X:t3.X,EyeOff:t3.X_};function lH(){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 lq=(e,t)=>(e||"").split("\n").map(e=>e.trim()).find(t)||"",lV=(e,t)=>{let s=lq(t,e=>/files? changed/.test(e));return e("git.commitSuccess")+(s?` \xb7 ${s}`:"")},lX=(e,t)=>{if(/up.to.date/i.test(t||""))return e("git.upToDate");let s=lq(t,e=>e.includes("->"));return e("git.pushSuccess")+(s?` \xb7 ${s}`:"")},lG="changes",lJ="untracked";function lY(e){if(!e)return"";let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t>=0?e.slice(t+1):e}function lZ(e){if(!e)return"";let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t>=0?e.slice(0,t):""}function lQ(e,t){if(!e)return t;let s=e.endsWith("/")||e.endsWith("\\")?"":"/";return`${e}${s}${t}`}let l0=(0,r.memo)(function({file:e,workspace:t,isUntracked:s,t:r,isTouch:a,openDiff:l,onCtxMenu:i,onDiscard:o,onStage:c}){let d=tn[e.status]||"text-text-muted";return lQ(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:ly({name:lY(e.path),path:e.path,type:"file"},16)}),(0,n.jsx)("span",{className:"truncate text-xs text-text",title:e.path,children:lY(e.path)}),(0,n.jsx)("span",{className:"truncate text-[11px] text-text-muted flex-1",title:lZ(e.path),children:lZ(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 l1({workspace:e,fileBus:t,onOpenFile:s,tagDiffWithRepo:a=!1}){let{t:l}=(0,se.s)(),i=lH(),[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),[j,k]=(0,r.useState)(new Set([lG,lJ])),[N,S]=(0,r.useState)(!1),[C,T]=(0,r.useState)(!1),[R,_]=(0,r.useState)(null),[E,$]=(0,r.useState)(!1),[M,P]=(0,r.useState)(null),[A,z]=(0,r.useState)(null),L=(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)(()=>{L()},[L]),(0,r.useEffect)(()=>{let e=()=>L(),t=["fileExplorer:fileSaved","fileExplorer:fileCreated","fileExplorer:fileDeleted","fileExplorer:fileRenamed",tu];return t.forEach(t=>window.addEventListener(t,e)),()=>t.forEach(t=>window.removeEventListener(t,e))},[L]);let{changes:I,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=>{k(t=>{let s=new Set(t);return s.has(e)?s.delete(e):s.add(e),s})},[]),B=(0,r.useCallback)(async s=>{e&&(await t.gitAdd?.(e,[s.path]),L())},[e,t,L]),O=(0,r.useCallback)(async()=>{e&&(await t.gitAdd?.(e,["."]),L())},[e,t,L]),W=(0,r.useCallback)(async s=>{e&&(await t.gitDiscard?.(e,s.path,s.status),L())},[e,t,L]),K=(0,r.useCallback)(e=>{_(e),T(!0)},[]),U=(0,r.useCallback)(t=>{let n,r;s?.(a?(n=t.status,r=t.path,`${tl}${n}:${e}\u0000${r}`):ti(t.status,t.path))},[s,a,e]),H=(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")}),L();return}if(b(""),!E){w({ok:!0,text:lV(l,n.output)}),L();return}let r=await t.gitPush?.(e);w(r?.success?{ok:!0,text:`${lV(l,n.output)} \xb7 ${lX(l,r.output)}`}:{ok:!1,text:r?.output||r?.error||l("git.pushFailed")}),L()},[e,t,f,E,L,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:lX(l,s.output)}:{ok:!1,text:s?.output||s?.error||l("git.pushFailed")}),L()},[e,t,L,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=lq(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")}),L()},[e,t,L,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 lI(t,e,s.path);n?.success&&(window.dispatchEvent(new CustomEvent(tu)),L())},[e,t,L]),et=(0,r.useCallback)(t=>{let n=lQ(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(lY(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=j.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)(l0,{file:t,workspace:e,isUntracked:a,t:l,isTouch:i,openDiff:U,onCtxMenu:Q,onDiscard:K,onStage:B},`${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)(),L()},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)(),H(!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(lG,l("git.changes"),I,!1),es(lJ,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),_(null)},onConfirm:()=>{R&&W(R),_(null)},title:l("git.discardConfirmTitle"),message:R?"?"===R.status?l("git.discardConfirmDelete",{name:lY(R.path)}):l("git.discardConfirmDiscard",{name:lY(R.path)}):"",confirmText:l("git.discard"),cancelText:l("common.cancel")}),J&&(0,n.jsx)(lK,{x:J.x,y:J.y,items:et(J.file),onClose:()=>Y(null)}),M&&(0,n.jsx)(lK,{x:M.x,y:M.y,items:[{key:"commitPush",label:l("git.commitAndPush"),icon:t3.Do,disabled:!f.trim()||!p.length,onClick:()=>H(!0)}],onClose:()=>P(null)}),A&&(0,n.jsx)(lK,{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:O}],onClose:()=>z(null)})]})}let l2=[{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 l5({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 l3({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 l4({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 l6({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 l8({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 l9=(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)(),j=a||t2.getState(),k="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,j),_=t||e,{roots:E,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:a7(e)}]);n(t.worktrees.map(e=>({path:e.path,branch:e.branch,name:a7(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}}(_,j),M=()=>{S(),$()},{branch:P}=aC(e,j),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(tu)))},[P,e]);let[z,L]=(0,r.useState)({forWorkspace:e,showClean:!1,openRepo:null}),I=z.forWorkspace===e?z:{showClean:!1,openRepo:null},D=I.showClean,F=I.openRepo,B=new Set(g),O=e=>b[e.path]??e.changedCount??0,W=N.filter(e=>!B.has(e.path)),K=W.filter(e=>O(e)>0),U=K.reduce((e,t)=>e+O(t),0),H=D?W:K,q=D?0:W.length-K.length,V=N.length-W.length,X=F??(1===H.length?H[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 j.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 j.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||_,eo=(0,r.useMemo)(()=>{let e=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:(E.find(e=>e.isMain)||E[0])?.path||_},[E,ei,_]),[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===_?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:_,searchDir:e,show:!0,query:"",results:[],loading:!1})},[_]),eg=(0,r.useCallback)(()=>{ex(e=>{let t={...e,searchDir:null};return e.query&&e.query.length>=2&&(t.loading=!0,j.searchFiles(_,e.query).then(e=>{ex(t=>t.loading?{...t,results:e.success?e.files:[],loading:!1}:t)})),t})},[j,_]),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||_;eh.current=setTimeout(async()=>{let s=await j.searchFiles(t,e);ex(t=>t.query===e&&t.loading?{...t,results:s.success?s.files:[],loading:!1}:t)},300)},[j,_,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 ${rE} pl-1 pr-0.5 flex items-stretch gap-0 border-b border-border-subtle flex-shrink-0`,children:[l2.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 ${k===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&&U>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:U>99?"99+":U})]},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)(l4,{icon:t3.e9,label:w("workspaces.refreshRepos"),onClick:()=>{M(),J?.refresh?.()},disabled:C,spinning:C}),u&&(0,n.jsx)(l4,{icon:t3.X,label:w("common.close"),onClick:u})]})]}),"files"===k&&e&&(0,n.jsx)("div",{className:`h-11 ${rE} 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)(l4,{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)(l4,{icon:t3.FW,label:w("files.newFile"),onClick:J.newFile}),(0,n.jsx)(l4,{icon:t3.JU,label:w("files.newFolder"),onClick:J.newFolder})]}),(0,n.jsx)(l4,{icon:t3.vj,label:w("files.searchFiles"),onClick:()=>{if(ep.show)return ef();ex({forRoot:_,searchDir:null,show:!0,query:"",results:[],loading:!1})},active:ep.show}),(0,n.jsx)("div",{className:"flex-1"}),J?.hasExpanded&&(0,n.jsx)(l4,{icon:t3.WE,label:w("fileExplorer.collapseAll"),onClick:J.collapseAll}),J&&(0,n.jsx)(l4,{icon:J.showHidden?t3.kU:t3.X_,label:w("files.toggleHidden"),onClick:J.toggleHidden,active:J.showHidden}),h&&(0,n.jsx)(l4,{icon:t3.Gr,label:w("workspaces.openFullFiles"),onClick:h})]})}),"files"===k&&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"===k?ep.show?(0,n.jsx)(l5,{results:ep.results,loading:ep.loading,query:ep.query,searchDir:ep.searchDir,workspace:_,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})})]}),E.map(e=>(0,n.jsx)(l3,{root:e,multiple:E.length>1,isOpen:1===E.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)(lW,{workspace:e.path,fileBus:j,activeFile:l,onOpenFile:m,onNewTerminal:x,onSearchFolder:eb,compact:!0,onActions:e.path===eu||1===E.length?Y:void 0})},e.path))]}):"git"===k?(0,n.jsxs)("div",{className:"flex-1 min-h-0 overflow-y-auto modal-scrollable",children:[H.map(t=>(0,n.jsx)(l8,{repo:t,changedCount:O(t),isOpen:X===t.path,onToggle:()=>{let s;return s=X===t.path?"":t.path,L({...I,forWorkspace:e,openRepo:s})},onHide:v&&t.relPath?()=>{let e;return e=t.path,v?.([...g,e])}:null,children:(0,n.jsx)(l1,{workspace:t.path,fileBus:j,onOpenFile:m,tagDiffWithRepo:!0})},t.path)),!H.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)(l6,{onClick:()=>L({...I,forWorkspace:e,showClean:!0}),children:w("workspaces.showCleanRepos",{count:q})}),V>0&&(0,n.jsx)(l6,{onClick:()=>v?.([]),children:w("workspaces.showHiddenRepos",{count:V})}),!T&&(0,n.jsx)(l6,{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 l7(e){return e?e<1024?`${e}B`:e<1048576?`${(e/1024).toFixed(1)}KB`:`${(e/1048576).toFixed(1)}MB`:""}function ie({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),j=(0,r.useRef)(null),k=(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),_=(0,r.useCallback)(e=>{if(2===e.touches.length)k.current=null,j.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,k.current=null;return}N.current=t,m>1.01&&(k.current={x:e.touches[0].clientX,y:e.touches[0].clientY,pos:p})}},[m,p,C]),E=(0,r.useCallback)(e=>{if(2===e.touches.length&&j.current){e.preventDefault();let t=R(e.touches[0],e.touches[1]),s=Math.max(.2,Math.min(8,j.current.scale*(t/j.current.dist)));x(s),h(e=>S(e.x,e.y,s))}else if(1===e.touches.length&&k.current){e.preventDefault();let t=e.touches[0],s=t.clientX-k.current.x,n=t.clientY-k.current.y;h(S(k.current.pos.x+s,k.current.pos.y+n,m))}},[m,S]),$=(0,r.useCallback)(e=>{e.touches.length<2&&(j.current=null),0===e.touches.length&&(k.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:[l7(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:l7(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:_,onTouchMove:E,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 it({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=te(e,e4);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=te(e,e4);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 ir({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 ia=e=>te(e,e1)||te(e,e2)||te(e,e5)||te(e,e3)||te(e,e4)||te(e,e6);function il({filePath:e,fileBus:t}){return te(e,e3)?(0,n.jsx)(ir,{filePath:e,fileBus:t},e):te(e,e4)||te(e,e6)?(0,n.jsx)(is,{filePath:e,fileBus:t},e):te(e,e2)||te(e,e5)?(0,n.jsx)(it,{filePath:e,fileBus:t},e):(0,n.jsx)(ie,{filePath:e,fileBus:t},e)}function ii({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 j=(0,r.useCallback)(()=>{c?v(!0):w()},[c,w]);(0,r.useEffect)(()=>()=>clearTimeout(b.current),[]);let k=(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:k,save:N,discard:(0,r.useCallback)(()=>{d(!1),l(h.current)},[]),setError:o,reload:w,onChangedOnDisk:j}}function io({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 ic({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 id=s(70256),iu=s(39821),im=s(48907),ix=s(74447),ip=s(15332),ih=s(9722),ib=s(97320),ig=s(99833),iv=s(50807),iy=s(57378),iw=s(41554),ij=s(42760);let ik={javascript:(0,ix.Q2)(),html:(0,ip.qy)(),css:(0,ih.AH)(),json:(0,ib.Pq)(),markdown:(0,ig.wD)()};function iN({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,ag.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]=nx(tm,14),[y]=nx(tx,!0),w=window.innerWidth<760,j=d?Math.max(9,v-4):v+ +!!w,{extension:k}={lang:m=ts["."+e.split(".").pop()?.toLowerCase()]||"plaintext",extension:ik[m]||[]};return(0,r.useEffect)(()=>{if(null==t||!p.current)return;let e=im.$t.create({doc:t,extensions:[id.oQ,..."dark"===x?[iv.bM]:[],k,...y?[iu.Lz.lineWrapping]:[],(0,iy.$P)(),(0,iw.yU)(),(0,iw.wm)(),iu.w4.of([{key:"Mod-s",preventDefault:!0,run:()=>(g.current?.(),!0)},...iw.Bc,...iw.OO,ij.Yc]),iu.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})}}),iu.Lz.theme({"&":{height:"100%",fontSize:`${j}px`},".cm-scroller":{overflow:"auto",lineHeight:d?"1.35":""},".cm-content":{minHeight:"100%"},".cm-gutters":d?{fontSize:`${Math.max(8,j-1)}px`}:{}})]});return h.current?.destroy(),h.current=new iu.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,j,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:iu.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 iS(e,t){return decodeURIComponent((t&&e.startsWith(t)?e.slice(t.length):e)||"/").replace(/^\//,"")||"/"}function iC({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 j=f.entries[f.index]||o.root,k=`${o.origin}${j}`,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:iS(j,o.root),children:iS(j,o.root)}),(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),window.open(k,"_blank","noopener")},title:a("editor.previewOpenTab"),className:C,children:(0,n.jsx)(t3.Gr,{size:13})})]}),(0,n.jsx)("iframe",{src:k,sandbox:"allow-scripts allow-forms allow-popups",className:"flex-1 min-h-0 w-full border-0",title:"HTML preview"},`${k}|${f.index}|${s}|${m}`)]})}let iT=null,iR=0;function i_({content:e,reloadKey:t=0}){let a,l,{t:i}=(0,se.s)(),{theme:o}=(0,ag.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(!iT&&(iT=Promise.all([s.e(3755),s.e(7162),s.e(3606)]).then(s.bind(s,86492)).then(e=>e.default)),iT).then(async t=>{if(!e){t.initialize({startOnLoad:!1,theme:"dark"===o?"dark":"default",securityLevel:"loose"});try{let{svg:s}=await t.render(`mmd-${++iR}`,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 iE=s(49430),i$=s(93473);let iM=(e,t)=>function({children:s,className:r,node:a,...l}){return(0,n.jsx)(e,{className:r?`${t} ${r}`:t,...l,children:s})},iP={h1:iM("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:iM("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:iM("h3","text-base sm:text-lg font-semibold mt-3.5 mb-2 text-text"),h4:iM("h4","text-sm sm:text-base font-semibold mt-3 mb-1.5 text-text"),h5:iM("h5","text-xs sm:text-sm font-semibold mt-2.5 mb-1 text-text"),h6:iM("h6","text-xs font-semibold mt-2 mb-1 text-text-muted"),p:iM("p","my-2 leading-relaxed text-text text-sm"),ul:iM("ul","list-disc pl-5 my-2 space-y-1 text-sm text-text"),ol:iM("ol","list-decimal pl-5 my-2 space-y-1 text-sm text-text"),li:iM("li","leading-relaxed"),blockquote:iM("blockquote","border-l-4 border-brand-500/40 pl-3.5 my-2.5 text-text-muted italic text-sm"),th:iM("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:iM("td","border border-border-subtle px-3 py-1.5 text-text align-top whitespace-normal break-words"),hr:iM("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})},iA=(0,r.memo)(function({content:e,components:t}){return(0,n.jsx)(iE.oz,{remarkPlugins:[i$.A],components:t?{...iP,...t}:iP,children:e})},(e,t)=>e.content===t.content);function iz({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)(iA,{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 iL({kind:e,filePath:t,fileBus:s,content:r,reloadKey:a=0}){return"html"===e?(0,n.jsx)(iC,{filePath:t,fileBus:s,reloadKey:a}):"mermaid"===e?(0,n.jsx)(i_,{content:r,reloadKey:a}):"markdown"===e?(0,n.jsx)(iz,{content:r}):null}var iI=s(23910);s(14876);let iD=["diff --git","index ","new file","deleted file","--- ","+++ "];function iF({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 iI.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(iD.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 iB({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 iO({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),[j,k]=(0,r.useState)(""),[N,S]=(0,r.useState)(e);N!==e&&(S(e),x(null),h(d),b(""),v(null),w(u),k("")),(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),k(""),a.readMedia?.(n).then(e=>{t||(w(!1),e?.success?v(e):k(e?.error||i("git.noNewVersion",{defaultValue:"Failed to load working image"})))}).catch(e=>{t||(w(!1),k(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)(iB,{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)(iB,{title:o?`${C} (Added)`:"New (Working Tree)",badge:o?"NEW":"MODIFIED",badgeColor:"bg-green-500/15 text-green-400",img:g,loading:y,error:j,t:i})]})})}function iW({diffPath:e,workspace:t,fileBus:s,compact:a=!1}){let{t:l}=(0,se.s)(),{status:i,repoPath:o,filePath:c}=td(e),d=o||t,u=te(c,e1),[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)(iO,{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)(iF,{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 iK({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=to(e),h=p?td(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&&!ia(e),y=ii({filePath:v?e:"",fileBus:s}),w=(0,r.useRef)(y);(0,r.useEffect)(()=>{w.current=y},[y]);let j=io({dirty:v&&y.dirty,onSave:y.save}),k=v?tt(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||P!==u)&&(E(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&&j.guard(i)};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[j,i]);let z=e&&!p?e.slice(0,e.lastIndexOf("/")):"",L=(0,r.useMemo)(()=>z?[z]:[],[z]),I=lr();if(ln({dirs:L,fileBus:s,enabled:!!z&&I,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:ly({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 ${tn[h.status]||"text-text-muted"}`,children:h.status}),k&&(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)(),j.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)(iW,{diffPath:ti(h.status,h.filePath),workspace:f,fileBus:s,compact:!0}):ia(e)?(0,n.jsx)(il,{filePath:e,fileBus:s}):S&&k?(0,n.jsx)(iL,{kind:k,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)(iN,{filePath:e,content:y.content,onTextChanged:y.onTextChanged,onRegisterView:y.register,onSave:y.save,compact:!0})}),(0,n.jsx)(ic,{isOpen:j.asking,fileName:D,onSave:j.saveThenLeave,onDiscard:j.discardAndLeave,onCancel:j.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 iU(){let[e,t]=(0,r.useState)(null),s="mouse"!==nm();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,rw.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 iH=(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"})]})})}),iq=["newTerminal","palette","help"];function iV({onAddWorkspace:e,onOpenRemote:t,recent:s=[],homeDir:r,onOpenRecent:a}){let{t:l}=(0,se.s)(),i=[...iq.map(e=>sB.find(t=>t.id===e)).filter(Boolean),sO];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:n2(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:sq(e)})]},e.id))})]})}let iX=new Set(["Agent","Task","Workflow","task","browser_subagent","invoke_subagent","spawn_agent"]),iG=e=>e?.input?.subagent_type||e?.input?.agent||e?.input?.description||"agent",iJ=e=>e?.input?.description||e?.input?.command||"shell";function iY(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 iZ(e=[],t=""){let s=iY(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 iQ(e){return(e||[]).map(e=>{let t=e.children?iQ(e.children):null;return"running"!==e.status||e.async?t?{...e,children:t}:e:{...e,status:"done",...t?{children:t}:null}})}function i0(e,t,s){let n=!1,r=(e||[]).map(e=>{if(t(e))return n=!0,s(e);let r=i0(e.children,t,s);return r?(n=!0,{...e,children:r}):e});return n?r:null}var i1=s(91524);function i2(e,t="claude"){if(!e?.name)return"";let{name:s,input:n={}}=e,r=i3(n.file_path||n.path);switch((0,i1.$Z)(t,s)){case"bash":return i6(n.description||n.command||"shell",i5);case"file":return i6(`${/^(list|list_dir|ls)$/i.test(s)?"Listing":"Reading"} ${r}`,i5);case"search":return i6([n.pattern?`"${n.pattern}"`:n.query||n.url||"",r?`in ${r}`:""].filter(Boolean).join(" "),i5);case"diff":return i6(`${/^(Write|write_to_file)$/i.test(s)?"Writing":"Editing"} ${i3(n.file_path||n.filePath||n.file||n.path)||i9(n)}`,i5);case"agent":return i6(n.description||i9(n)||"sub-agent",i5);case"plan":return i6(i3(n.path)||s,i5);default:return i6([i8(s),i9(n)].filter(Boolean).join(" "),i5)}}let i5=60,i3=e=>"string"==typeof e&&e.replace(/\\/g,"/").split("/").filter(Boolean).pop()||"",i4=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""},i6=(e,t)=>e.length>t?`${e.slice(0,t-1)}…`:e,i8=(e="")=>{let t=/^mcp__[^_]+(?:_[^_]+)*__(.+)$/.exec(e);return t?t[1]:e},i9=(e={})=>e.url||e.query||e.pattern||e.name||i3(e.path)||i3(e.file_path)||"";function i7(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 oe=new Set(["Edit","Write","MultiEdit","NotebookEdit","edit","write","patch","apply","write_to_file","replace_file_content","multi_replace_file_content","sed_file","file_change"]),ot=e=>"string"==typeof e&&e?e.split("\n").length:0;function os(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(!oe.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+=ot(s.old_string??s.oldString??s.old??s.target_content),e+=ot(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:ot(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:ot(a),removed:ot(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)>/,or=e=>on.test(String(e||""));function oa(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 ol=new Set(["completed","failed","killed","stopped"]),oi=(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,oo=(e,t)=>t?.startedAt?null:{startedAt:Date.now()-(Number.isFinite(e)?Math.max(0,e):0)},oc=(e=[])=>{for(let t=e.length-1;t>=0;t--)if(e[t]?.compacting)return t;return -1},od=new Set(["compacting"]);function ou(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 om(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,...oo(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&&!ol.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,oo(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&&!ol.has(e.status)&&!t.has(e.taskId))&&(s=s.map(e=>!e.background||ol.has(e.status)||t.has(e.taskId)?e:{...e,status:"stopped",endedAt:e.endedAt||Date.now()})),n?.tasks||[]))s=om(s,e.task_id,{background:!0,status:"running",...e.description?{description:e.description}:null,...e.task_type?{taskType:e.task_type}:null,...oo(a,s.find(t=>t.taskId===e.task_id))});return s}default:return e}}function om(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(ox(r,e[n]))return e;let a=e.slice();return a[n]=r,a}let ox=(e,t)=>{let s=Object.keys(e);return s.length===Object.keys(t).length&&s.every(s=>e[s]===t[s])};function op(e,t){let s=[];for(let t of e||[])t&&(s=ou(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 oh(e,t){if(!t||"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?`${i7(n)} → ${i7(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(od.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=oa(e.content);return t?{subtype:s,level:"info",content:t}:null}let n="queued_command"===s?e.prompt:"";if("string"!=typeof n||!n.trim()||or(n))return null;let r=oa(n);return r?{subtype:s,level:"info",content:r}:null}if("system"!==e||or(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 of(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 ob=(0,es.KU)(()=>window.localStorage),og=null,ov=ob&&{...ob,setItem:(e,t)=>{t!==og&&(og=t,ob.setItem(e,t))}},oy=0,ow=e=>`${e}-${Date.now()}-${++oy}`,oj={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:[]},ok=(e,t)=>({...oj,...e.bySession[t]});function oN(e,t){if(!t?.length)return null;let s=e.filter(e=>e.toolUseId&&ol.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=i0(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 oS=(0,Z.v)((0,es.Zr)((e,t)=>({bySession:{},initSession:s=>{s&&!t().bySession[s]&&e(e=>({bySession:{...e.bySession,[s]:{...oj}}}))},setTaskRecords:(t,s)=>{t&&Array.isArray(s)&&e(e=>{let n=ok(e,t),r=op(s,[]),a=oN(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=ok(e,t),r=n.harnessTasks||[],a=r;for(let[e,t,n,r]of s)a=ou(a,e,t,n,r);let l=oN(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=ok(e,t),a=s?.compactSettled?oc(r.messages):-1;if(-1!==a){let l=n?[...r.messages.slice(0,a),{id:ow("n"),role:"notice",subtype:s.subtype||"",level:s.level||"info",content:n},...r.messages.slice(a+1)]:[...r.messages.slice(0,a),...r.messages.slice(a+1)];return{bySession:{...e.bySession,[t]:{...r,messages:l}}}}if(!n)return e;let l={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},i=r.messages[r.messages.length-1],o=!i||"assistant"!==i.role||i.content||i.thinking||(i.tools||[]).length?[...r.messages,l]:[...r.messages.slice(0,-1),l];return{bySession:{...e.bySession,[t]:{...r,messages:o}}}})},setPermissionMode:(t,s)=>{e(e=>{let n=ok(e,t);return{bySession:{...e.bySession,[t]:{...n,permissionMode:s}}}})},setTurnRunning:(t,s)=>{e(e=>{let n=ok(e,t);return{bySession:{...e.bySession,[t]:{...n,isTurnRunning:s}}}})},setMetadata:(t,s)=>{e(e=>{let n=ok(e,t);return{bySession:{...e.bySession,[t]:{...n,metadata:{...n.metadata,...s}}}}})},setStats:(t,s)=>{e(e=>{let n=ok(e,t);return{bySession:{...e.bySession,[t]:{...n,stats:{...n.stats,...s}}}}})},addUserMessage:(t,s,n=null,r=!1)=>{e(e=>{let a=ok(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=ok(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=ok(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=ok(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=ok(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=ok(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=ok(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=ok(e,t),r=[...n.messages];for(let e=r.length-1;e>=0;e--){let t=r[e],n=i0(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=ok(e,t),r=[...n.messages];for(let e=r.length-1;e>=0;e--){let t=r[e],n=i0(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=ok(e,t);return{bySession:{...e.bySession,[t]:{...n,activePermission:s,gateError:!1}}}})},clearPermission:t=>{e(e=>{let s=ok(e,t);return{bySession:{...e.bySession,[t]:{...s,activePermission:null}}}})},setBlocked:(t,s)=>{e(e=>{let n=ok(e,t);return{bySession:{...e.bySession,[t]:{...n,activeBlocked:s}}}})},clearBlocked:t=>{e(e=>{let s=ok(e,t);return{bySession:{...e.bySession,[t]:{...s,activeBlocked:null}}}})},setGateError:(t,s,n=!0)=>{e(e=>{let r=ok(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=ok(e,t),l=a.messages.map((e,t)=>({...e,...t===a.messages.length-1?{isLive:!1}:null,...e.tools?{tools:iQ(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=ok(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=ok(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=ok(e,t),r=of(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})=>{e(e=>{let m=ok(e,t),x=u?oN(u,s):null;return{bySession:{...e.bySession,[t]:{...m,activePermission:null,messages:x||s,tasks:n,isTurnRunning:r,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:{...m.metadata,...a},stats:l?{...m.stats,...l}:m.stats,activeBlocked:o,...i?{permissionMode:i}:{},...u?{harnessTasks:u}:{}}}}})},prependMessages:(t,s)=>{s?.length&&e(e=>{let n=ok(e,t),r=oN(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=ok(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:ov,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 oC(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 oT(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+=oC(e[s]),l++,!(a>=t)||!(l>=n));s--);return r-l}async function oR({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 o_=[1200,3e3,6e3],oE=e=>Array.isArray(e)?e.map(e=>"string"==typeof e?{id:e,name:e,description:""}:e):[];function o$(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 oM=e=>e?.text?`Not sent — ${e.reason||"the turn is still running"}: ${e.text}`:e?.reason||"Not sent";function oP(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=oE(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=i0(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=i0(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,i1.Zm)(t,p.name,p.input,p.id,r);e&&(r=of(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,i1.in)(t,p.name||"",p.output||"",p.id);e&&(r=of(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&&!o$(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:oM(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=oh(e,t);if(!s)break;let{compactSettled:r,...l}=s,i=r?oc(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=iQ(e.tools));let p=[];for(let[e,t,s]of a)p=ou(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 oA=(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,j]=(0,r.useState)(null);tS(e=>e.openEditorFile);let{id:k,role:N,content:S,thinking:C,diffs:T=[],tools:R=[],permission:_=null,isLive:E=!1,attachments:$=[]}=e;if("user"===N){let e=async e=>{y(!0),j("preview");let t=await i?.(null,{index:c});(y(!1),j(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),j("apply"),o?.(k,e);let t=await l?.(null,e,{index:c});(y(!1),j(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 oz(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 oL={file:t3.kU},oI=(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||"",j=a||w||("string"==typeof l?l:l?.command||l?.pattern||l?.query||""),k=!y&&w&&j===w?function(e,t){let{dir:s,name:n}=oz(e,t);return s?`${s}/${n}`:n}(j,m):j,N=l?.file_path||l?.path||l?.file||"",S=oL[(0,i1.$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}),k&&(0,n.jsxs)(n.Fragment,{children:[" ",(0,n.jsx)("span",{className:"text-text-muted break-all",title:k,children:k})]})]}),(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||k;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))})]})}),oD=new Set(["TaskCreate","TaskUpdate","TodoWrite","todowrite"]),oF=new Set(["Edit","Write","MultiEdit","NotebookEdit","file_change","edit","write","write_to_file","replace_file_content"]),oB=e=>"thought"===e.kind||"tool"===e.kind||"diff"===e.kind;function oO({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 oW=(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=lH(),u=t||s||(t||s||!a?"":String(a).split("\n").map(e=>`+${e}`).join("\n")),m=u?u.split("\n"):[],x=oz(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 oK=s(6552);let oU=(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}),oH=/Command running in background with ID:\s*([^\s.]+)/;var oq=s(14890);let oV=(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,oq.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):"",j=(c=oH.exec("string"==typeof a?a:""))?c[1]:"",k=!!(s?.run_in_background||j);return(0,n.jsxs)("div",{className:"my-1 text-xs",id:(0,oq.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}),k&&(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:j?`Background shell ${j}`:"Running in the background",children:["BG",j?` ${j}`:""]}),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 oX(e){let t=String(e||"").split("\n")[0].trim();return t.length>140?`${t.slice(0,140)}…`:t}let oG=(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,oq.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=iX.has(t),g=b?iG({input:s}):t||"agent",v=b?oX(s?.prompt??s?.description??s?.message):oX(s?.message??s?.prompt??s?.query);return(0,n.jsxs)("div",{className:"my-1 text-xs",id:(0,oq.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)(oO,{total:o.length,children:e=>(e>0?o.slice(e):o).map(e=>o0(c,e,{workspacePath:d})||(0,n.jsx)(oI,{...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)})})]})]})}),oJ=(0,r.memo)(function({toolName:e="EnterPlanMode",input:t={}}){let s="string"==typeof t?.plan?t.plan.trim():"";if(s)return(0,n.jsx)(oY,{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."})]})}),oY=(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})]})}),oZ=(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]})]})}),oQ={bash:(e,t)=>(0,n.jsx)(oV,{...e,deferred:t},e.id),agent:(e,t,{engine:s,workspacePath:r})=>(0,n.jsx)(oG,{...e,engine:s,workspacePath:r},e.id),plan:e=>(0,n.jsx)(oJ,{toolName:e.name,input:e.input},e.id),review:e=>(0,n.jsx)(oZ,{toolName:e.name,input:e.input},e.id),question:e=>(0,n.jsx)(oK.J,{questions:e.input?.questions||[],answers:e.error?null:e.output||"",declined:!!e.error||"error"===e.status},e.id)};function o0(e,t,s={}){let n=oQ[(0,i1.$Z)(e,t.name)];return n?n(t,s.deferred,s):null}function o1({row:e,engine:t,workspacePath:s,deferred:r}){if("thought"===e.kind)return(0,n.jsx)(oU,{text:e.text,isLive:e.isLive});if("diff"===e.kind){let t=e.diff;return(0,n.jsx)(oW,{file:t.file,patch:t.patch,diff:t.diff,content:t.content,workspacePath:s})}let a=e.tool;return o0(t,a,{workspacePath:s,deferred:r})||(0,n.jsx)(oI,{...a,engine:t,workspacePath:s,deferred:r})}let o2={info:"text-text-muted",suggestion:"text-text-muted",warning:"text-warning",error:"text-danger"};function o5({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 ${o2[e.level]||o2.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)(o4,{})]}):(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 ",o3(e.compact.durationMs)]}):null]})}function o3(e){let t=e/1e3;return t<60?`${t.toFixed(1)}s`:`${Math.floor(t/60)}m ${Math.round(t%60)}s`}function o4(){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:o3(t-e)})}function o6({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)(iA,{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 o8=(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,oF.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,i1.$Z)(e,t.name)&&oD.has(t.name)))}(t,r.tools,r.diffs);for(let a=0;a<e.length;a++){let l=e[a];if("question"===(0,i1.$Z)(t,l.name)&&"running"===l.status)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(oB(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)(o6,{content:e.row.content,isLive:e.row.isLive},e.key);if("notice"===e.row.kind)return(0,n.jsx)(o5,{notice:e.row.notice},e.key);if("permission"===e.row.kind){let t=e.row.permission;return(0,n.jsx)(oK.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)(oO,{total:e.rows.length,children:r=>(r>0?e.rows.slice(r):e.rows).map(e=>(0,n.jsx)(o1,{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}),o9=[],o7=(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}},ce=e=>String(e).padStart(2,"0");function ct(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 ${ce(r)}s`:n>0?`${n}m ${ce(r)}s`:`${r}s`}function cs(e){return e?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"text-text-muted/60",children:" \xb7 "}),i7(e)," tokens"]}):null}let cn=(0,r.memo)(function({engine:e="claude",failed:t=!1,onRetry:s}){let r=s1.UB[e]||s1.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})]})}),cr=(0,r.memo)(function({sessionId:e,engine:t="",hydrating:s=!1}){let a=oS(t=>t.bySession[e]?.isTurnRunning),l=oS(t=>t.bySession[e]?.turnStartedAt),i=oS(t=>t.bySession[e]?.lastTurnMs),o=oS(t=>t.bySession[e]?.stats),c=oS(t=>t.bySession[e]?.turnBaseline),d=Q(e=>e.connected),u=Q(e=>e.retryStatus),m=oS(t=>t.bySession[e]?.messages)||o9,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:os(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:os(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:ct(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),cs(w.outputTokens)]})]})]});let j=x?.tools?.find(e=>"running"===e.status),k=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,i1.$Z)(r,e),a=i3(t.file_path||t.path);switch(s){case"bash":return{verb:"Running",detail:i6(t.command||"",i5),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:i6(`${a}${n}`,i5),tone:"wait"}}case"search":{let e=t.pattern?`"${t.pattern}"`:t.query||t.url||"",s=i3(t.path);return{verb:"Searching",detail:i6([e,s?`in ${s}`:""].filter(Boolean).join(" "),i5),tone:"wait"}}case"diff":return{verb:/^(Write|write_to_file)$/i.test(e)?"Writing":"Editing",detail:i6(i3(t.file_path||t.filePath||t.file||t.path)||i9(t),i5),tone:"wait"};case"agent":{let e=n.children?.length||0;return{verb:"Delegating",detail:i6([t.description||i9(t),e?`${e} steps`:""].filter(Boolean).join(" \xb7 "),i5),tone:"wait"}}case"task":return{verb:"Updating tasks",detail:i6(t.activeForm||t.subject||"",i5),tone:"wait"};case"plan":return{verb:"Planning",detail:i6(i3(t.path)||e,i5),tone:"wait"};default:return{verb:"Calling",detail:i6([i8(e),i9(t)].filter(Boolean).join(" "),i5),tone:"wait"}}}return a?.thinking?{verb:"Thinking",detail:i6(i4(a.thinking),i5),tone:"wait"}:a?.content?{verb:"Writing",detail:i6(i4(a.content),i5),tone:"wait"}:{verb:"Working",detail:"",tone:"wait"}}({connected:d,hydrating:s,retryStatus:u,activeTool:j,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 "}),ct(h-(l||h))]}),(0,n.jsx)("span",{className:"shrink-0",children:cs(k)})]})]})}),ca=(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=aC(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?n2(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 ${sE}`})}),(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:s1.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))})]})}),cl=(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),j=(0,r.useRef)(!0),k=(0,r.useRef)(null),N=(0,r.useRef)(null),S=(0,r.useRef)(null),C=(0,r.useRef)(0),[T,R]=(0,r.useState)(!1),[_,E]=(0,r.useState)(131072),[$,M]=(0,r.useState)(null),P=(0,r.useRef)({sessionId:null,n:0}),A=oS(t=>t.bySession[e]?.messages)||o9,z=s1.UB[t]||s1.UB.claude;(0,r.useEffect)(()=>{E(131072),M(null),S.current=null},[e]);let{id:L,index:I}=(0,r.useMemo)(()=>(function(e,t,s){if(!t?.length)return{id:null,index:0};let n=oT(t,s,void 0),r=null!=e?t.findIndex(t=>t.id===e):-1,a=oT(t,Math.max(524288,s),void 0),l=r<0?n:Math.max(r,a);return{id:t[l].id,index:l}})($,A,_),[$,A,_]);(0,r.useEffect)(()=>{M(L)},[L]);let D=I>0?A.slice(I):A,[F,B]=(0,r.useState)(null),O=(0,r.useRef)(0),W=(0,r.useMemo)(()=>A.filter(e=>"user"===e.role).length,[A]);(0,r.useEffect)(()=>{if(F?.ok||F?.supported===!1||O.current>=6)return;O.current+=1;let e=!0;return x?.().then(t=>{e&&B(t)}).catch(()=>{}),()=>{e=!1}},[x,t,e,W,F?.ok,F?.supported]);let K=!!F?.ok,U=(0,r.useMemo)(()=>{let e=new Map,t=0;for(let s=A.length-1;s>=0;s--)"user"===A[s].role&&e.set(A[s].id,t++);return e},[A]),H=(0,r.useMemo)(()=>{let e=[];for(let t of D)"user"===t.role||0===e.length?e.push({key:t.id,messages:[t]}):e[e.length-1].messages.push(t);return e},[D]),q=(0,r.useCallback)(async({auto:e=!1}={})=>{let t=y.current,s=Date.now();if(!e&&s-C.current<300)return;C.current=s;let n=N.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}}(o7(t,n)):null,a=r?{...r,atBottom:e&&j.current,node:n}:null,l={hiddenCount:I,hasOlder:o,scrollTop:t?.scrollTop??0,scrollHeight:t?.scrollHeight??0},i=null;0===I&&o&&(i=await c?.()),(0,v.Lq)("ai-page","loadMore",{...l,fetched:i}),S.current=a,M(null),E(e=>e+131072)},[I,o,c]);(0,r.useLayoutEffect)(()=>{let e=y.current,t=S.current;if(!e||!t)return;S.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,o7(e,t.node)||{});null!=s&&(e.scrollTop=s);let n=e.scrollHeight-e.scrollTop-e.clientHeight;j.current=n<8,R(n>140)},[_,$]),(0,r.useEffect)(()=>{let t=P.current;t.sessionId!==e&&(t.sessionId=e,t.n=0),!(t.n>=40)&&!h&&f&&j.current&&o&&A?.length&&A[I]?.role!=="user"&&(t.n+=1,q({auto:!0}))},[e,A,I,o,h,f,q]);let V=(0,r.useCallback)(()=>{k.current||(k.current=requestAnimationFrame(()=>{k.current=null;let e=y.current;if(!e)return;let t=e.scrollHeight-e.scrollTop-e.clientHeight,s=t<80;j.current=s,R(!s&&t>140),e.scrollTop<120&&(I>0||o)&&q()}))},[q,I,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)&&!j.current&&q()},{root:e,rootMargin:"120px"});return s.observe(t),()=>s.disconnect()},[q]);let X=(0,r.useMemo)(()=>A.map(e=>`${e.id}:${+!!e.thinking}:${+!!e.content}:${e.tools?.length||0}:${e.diffs?.length||0}:${+!!e.permission}`).join("|"),[A]),G=(0,r.useCallback)(e=>{N.current=e},[]);(0,r.useEffect)(()=>{let e=y.current;e&&j.current&&(e.scrollTop=e.scrollHeight)},[X]),(0,r.useEffect)(()=>{let e=y.current;if(!e)return;let t=new ResizeObserver(()=>{j.current&&(e.scrollTop=e.scrollHeight)});return t.observe(e),()=>t.disconnect()},[]);let J=(0,r.useCallback)(()=>{(0,t7.e)();let e=y.current;e&&(e.scrollTo({top:e.scrollHeight,behavior:"smooth"}),j.current=!0,R(!1))},[]),Y=(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:V,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:[(I>0||o)&&(0,n.jsx)("div",{ref:w,"aria-hidden":"true",className:"h-px"}),0===A.length?f?(0,n.jsx)(ca,{engine:t,engineMeta:z,workspacePath:s,fileBus:a,onSendPrompt:l,onOpenResume:p}):(0,n.jsx)(cn,{engine:t,failed:b,onRetry:g}):(0,n.jsxs)(n.Fragment,{children:[(I>0||o)&&(0,n.jsx)("button",{type:"button",onClick:()=>{(0,t7.e)(),q()},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:I>0?`Load older \xb7 ${I} more`:"Load older turns"}),H.map((e,r)=>{let[a,...l]=e.messages;return"user"!==a.role?(0,n.jsx)("div",{ref:0===r?G:void 0,children:(0,n.jsx)(o8,{messages:e.messages,engine:t,workspacePath:s,onResolvePermission:i,isLive:Y(e)})},e.key):(0,n.jsxs)("div",{ref:0===r?G:void 0,children:[(0,n.jsx)(oA,{message:a,engine:t,workspacePath:s,onResolvePermission:i,onRewind:d,onPreviewRewind:u,onCutLocal:m,rewindIndex:U.get(a.id),canRewind:K}),(0,n.jsx)(o8,{messages:l,engine:t,workspacePath:s,onResolvePermission:i,isLive:Y(e)})]},e.key)}),(0,n.jsx)(cr,{sessionId:e,engine:t,hydrating:h})]})]}),T&&(0,n.jsx)("button",{type:"button",onClick:J,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})})]})}),ci=[],co=(0,r.memo)(function({sessionId:e="",engine:t="claude",isTurnRunning:s=!1,isFocused:a=!1,onSend:l,onStop:i,onRunShell:o,onResolvePermission:c,onSelectModel:d,onModeChange:u,onOpenModal:m,onOptionChange:x,onActivate:p,fileBus:h=null,workspacePath:f="",model:b="",modalOpen:g=!1}){let{t:v,locale:y}=(0,se.s)(),w="mouse"===nm(),j=sH()?"Opt ←/→ \xb7 Opt 1…9 to switch tab":"Ctrl+Shift+←/→ \xb7 1…9 to switch tab",k=(0,i1.Tw)(t),N=k.permissionModes,S=k.slashCommands,C=oS(t=>t.bySession[e]?.isTurnRunning),T=oS(t=>t.bySession[e]?.metadata?.model),R=oS(t=>t.bySession[e]?.metadata?.modelOptions),_=R?.length?R:k.models,E=oS(t=>t.bySession[e]?.metadata?.skills)||ci,$=oS(t=>t.bySession[e]?.permissionMode),M=oS(t=>t.bySession[e]?.metadata?.effort||t.bySession[e]?.metadata?.variant),P=$||k.defaultMode,A=void 0!==C?C:s,z=void 0!==T?T:b,[L,I]=(0,r.useState)(""),[D,F]=(0,r.useState)(ci),[B,O]=(0,r.useState)(-1),W=(0,r.useRef)(""),[K,U]=(0,r.useState)(!1),[H,q]=(0,r.useState)(null),[V,X]=(0,r.useState)(""),[G,J]=(0,r.useState)([]),[Y,Z]=(0,r.useState)(0),[ee,et]=(0,r.useState)(null),[es,en]=(0,r.useState)(-1),er=s6(e=>e.addCommand),ea=s6(e=>e.resolveAlias),el=s6(e=>e.history),ei=s6(e=>e.pinned),eo=(0,r.useMemo)(()=>K?[]:ns(L,el,ei,[],!w),[L,el,ei,w,K]),[ec,ed]=(0,r.useState)(!1),[eu,em]=(0,r.useState)(!1),[ex,ep]=(0,r.useState)(!1),eh=(0,r.useRef)(null),{attachments:ef,setAttachments:eb,removeAttachment:eg,handleFileUpload:ev,handleAttachPaste:ey}=ny({bus:Q(e=>e.bus),sessionId:e}),[ew]=ni(y),ej=nd({lang:na(ew),onText:e=>{I(e),eT.current&&(eT.current.value=e,eT.current.style.height="auto",eT.current.style.height=`${Math.min(eT.current.scrollHeight,120)}px`,eT.current.focus())}}),ek=(0,r.useCallback)(()=>{(0,t7.e)(),ej.stop()},[ej]),eN=(0,r.useCallback)(()=>{ej.cancel()},[ej]),eS=(0,r.useCallback)(()=>{ej.listening?ej.stop():(document.activeElement?.blur(),ej.start(L))},[ej,L]),eC=(0,r.useCallback)(()=>{(0,t7.e)(),I(""),eT.current&&(eT.current.value="",eT.current.style.height="26px");try{localStorage.removeItem(`9remote_draft_${e}`)}catch{}eT.current?.focus()},[e]),eT=(0,r.useRef)(null),eR=(0,r.useRef)(ef);(0,r.useEffect)(()=>{eR.current=ef},[ef]);let e_=(0,r.useRef)(null),eE=(0,r.useRef)(!1),e$=(0,r.useRef)(0),eM=(0,r.useRef)(0),eP=(0,r.useRef)(0);s1.UB[t]||s1.UB.claude,(0,r.useEffect)(()=>{a&&!g&&w&&eT.current?.focus({preventScroll:!0})},[a,g,w]),(0,r.useEffect)(()=>{let e=e=>{eh.current&&!eh.current.contains(e.target)&&(ed(!1),em(!1))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,r.useEffect)(()=>{A&&(ed(!1),em(!1))},[A]),(0,r.useEffect)(()=>{let e=eT.current;if(!e)return;e.style.height="auto";let t=Math.min(e.scrollHeight,140);e.style.height=`${Math.max(t,26)}px`},[L]),(0,r.useEffect)(()=>{if(!K||!e_.current)return;let e=e_.current.querySelectorAll("[data-menu-item]")[Y];e&&e.scrollIntoView({block:"nearest"})},[Y,K]),(0,r.useEffect)(()=>{if(e){F(ci),eb([]);try{I(localStorage.getItem(`9remote_draft_${e}`)||"")}catch{}}},[e,eb]),(0,r.useEffect)(()=>{if(!e)return;let t=setTimeout(()=>{try{L?localStorage.setItem(`9remote_draft_${e}`,L):localStorage.removeItem(`9remote_draft_${e}`)}catch{}},300);return()=>clearTimeout(t)},[L,e]),(0,r.useEffect)(()=>{if(ee){let e=ee.name.replace(/[/@]/g,"\\$&");if(RegExp(`(?:^|\\s)${e}\\s*$`).test(L))return;et(null)}let e=/(?:^|\s)([/@][\w\d_.-]*)$/.exec(L);if(!e){U(!1),q(null),X("");return}let t=e[1],s=t[0],n=t.slice(1).toLowerCase();if(q(s),X(n),Z(0),"/"===s){let e=[...S,...E.map(e=>({name:`/${e.name||e.id}`,description:e.description||`Skill: ${e.name||e.id}`,isSkill:!0}))],t=new Set,s=e.filter(e=>!t.has(e.name)&&!!e.name.toLowerCase().includes(n)&&(t.add(e.name),!0));J(s),U(s.length>0)}else if("@"===s){let e=Q.getState().bus;e?.emit?e.emit("ai:files",{workspace:f,query:n},e=>{e?.ok&&Array.isArray(e.files)&&(J(e.files.map(e=>({name:e.path||e,description:e.isModified?`${e.dir?e.dir+" \xb7 ":""}modified`:e.dir||""}))),U(e.files.length>0))}):h?.searchFiles&&f?h.searchFiles(f,n).then(e=>{e?.success&&Array.isArray(e.files)&&(J(e.files.slice(0,10).map(e=>({name:e.path||e,description:e.relPath||e}))),U(e.files.length>0))}):(J([]),U(!1))}},[L,h,f,E,S,ee]);let eA=(0,r.useCallback)(t=>{let s=ea((("string"==typeof t?t:eT.current?eT.current.value:L)||L).trim()),n=eR.current;if(!s&&0===n.length)return;let r=Date.now();if(r-eM.current<250)return;eM.current=r,eP.current=r,(0,t7.e)(),s&&!s.startsWith("!")&&er(s),O(-1),I(""),eT.current&&(eT.current.value="",eT.current.style.height="26px");try{localStorage.removeItem(`9remote_draft_${e}`)}catch{}if(s.startsWith("!")){n.length||o?.(s.slice(1).trim());return}let a=oS.getState().bySession[e]?.activePermission;if(a&&c?.(a.requestId,s1.x6,s1.mX),oS.getState().bySession[e]?.isTurnRunning){F(e=>[...e,{id:`q-${r}`,text:s,attachments:n}]),eb([]);return}n.length&&eb([]),l?.(s,{attachments:n.map(({name:e,type:t,content:s})=>({filename:e,type:t,content:s}))})},[L,e,l,o,c,eb,er,ea,F]),ez=(0,r.useCallback)(e=>{if(e.text.startsWith("!"))return void o?.(e.text.slice(1).trim());let t=(e.attachments||[]).map(({name:e,type:t,content:s})=>({filename:e,type:t,content:s}));l?.(e.text,t.length?{attachments:t}:void 0)},[l,o]),eL=(0,r.useRef)(D);(0,r.useEffect)(()=>{eL.current=D},[D]);let eI=(0,r.useRef)(A);(0,r.useEffect)(()=>{let e=eI.current&&!A;if(eI.current=A,!e||0===eL.current.length)return;let[t,...s]=eL.current;F(s),ez(t)},[A,ez,F]);let eD=(0,r.useCallback)(()=>{(0,t7.e)(),i?.()},[i]),eF=(0,r.useCallback)(e=>{let t=e.action||"send",[s,n]=t.split(":");if("modal"===s){eT.current?.blur(),m?.(n);return}if("clear"===s){l?.("/clear",{force:!0}),I("");return}if("setMode"===s){u?.(e.mode),I("");return}if("send"===s||"send"===t){if(A){F(t=>[...t,{id:`q-${Date.now()}`,text:e.name,attachments:ci}]),I("");return}l?.(e.name),I("");return}eT.current?.focus()},[m,l,A,u,F]),eB=(0,r.useCallback)(e=>{(0,t7.e)();let t=/(?:^|\s)([/@][\w\d_.-]*)$/.exec(L);if(!t)return;let s=t[1],n=L.slice(0,L.length-s.length),r="/"===H&&e.action?.startsWith("modal:"),a="@"===H?`@${e.name} `:`${e.name} `;(I(r?n:`${n}${a}`),U(!1),"/"!==H)?eT.current?.focus():"submenu"===e.action&&Array.isArray(e.subOptions)&&e.subOptions.length>0?A&&("effort"===e.optionKey||"variant"===e.optionKey)?I(""):(et(e),Z(0),U(!0)):eF(e)},[L,H,eF]),eO=(0,r.useCallback)(e=>{(0,t7.e)(),ee&&(x?.(ee.optionKey,e.value),et(null),U(!1),I(""),eT.current?.focus())},[ee,x]),eW=(0,r.useCallback)(e=>{(0,t7.e)();let t=/(?:^|\s)(\S*)$/.exec(L),s=t?t[1]:"";I(L.slice(0,L.length-s.length)+e),en(-1),eT.current?.focus()},[L]),eK=e=>String(e||"").toLowerCase().replace(/\[[^\]]*\]$/,""),eU=(0,r.useMemo)(()=>{if(!z)return null;let e=_||[],t=eK(z);return e.find(e=>e.id===z)||e.find(e=>eK(e.id)===t)||e.find(e=>eK(e.id).split("/").pop()===t.split("/").pop())||null},[z,_]),eH=eU?.short||eU?.label||z||"Model",eq=M||k.defaultEffort||"",eV=(0,r.useMemo)(()=>{let e=[..._||[]];return z&&!e.some(e=>e.id===z)&&e.unshift({id:z,label:z,short:z}),e},[_,z]),eX=(0,r.useMemo)(()=>(S||[]).find(e=>"submenu"===e.action&&("effort"===e.optionKey||"variant"===e.optionKey)),[S]),eG=(0,r.useMemo)(()=>{let e=(eU?.efforts||[]).map(e=>({value:e,label:e}));return e.length>0?e:eX?.subOptions||[]},[eX,eU]);return(0,n.jsxs)("div",{className:"relative px-3 py-1.5 bg-transparent border-t border-border-subtle/40 select-none",children:[K&&ee&&(0,n.jsxs)("div",{ref:e_,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:[ee.name," — ",ee.optionKey]}),(0,n.jsx)("button",{type:"button",onClick:()=>{et(null),U(!1),I("")},className:"text-text-muted hover:text-text",children:(0,n.jsx)(t3.X,{size:11})})]}),(ee.subOptions||[]).map((e,t)=>(0,n.jsxs)("div",{"data-menu-item":"true",onClick:()=>eO(e),onMouseEnter:()=>Z(t),className:`px-2 py-1 rounded-brand flex items-center justify-between text-xs cursor-pointer ${t===Y?"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))]}),K&&!ee&&G.length>0&&(0,n.jsxs)("div",{ref:e_,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:"/"===H?"Slash Commands & Skills":"Files in repo (@)"}),G.map((e,t)=>{let s=A&&("/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:()=>eB(e),onMouseEnter:()=>Z(t),className:`px-2 py-1 rounded-brand flex items-center justify-between text-xs ${s?"opacity-40 cursor-not-allowed":t===Y?"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"}):"/"===H?(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)})]}),D.length>0&&(0,n.jsx)("div",{className:"mb-1 space-y-0.5",children:D.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,n.jsx)("button",{type:"button",onClick:()=>{((0,t7.e)(),0===t)?eD():F(t=>[e,...t.filter(t=>t.id!==e.id)])},className:"text-text-muted hover:text-brand-400 p-1 rounded hover:bg-surface-2 transition-colors cursor-pointer",title:0===t?"Send now (stops the current turn)":"Send this one next",children:(0,n.jsx)(t3.Vn,{size:13})}),(0,n.jsx)("button",{type:"button",onClick:()=>{(0,t7.e)(),F(t=>t.filter(t=>t.id!==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)(nE,{voice:ej,onDone:ek,onCancel:eN,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:[ef.length>0&&(0,n.jsx)("div",{className:"flex gap-1.5 overflow-x-auto scroll-thin-x pt-0.5",children:ef.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:()=>eg(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)(nn,{value:L,store:s6,isMobile:!w,activeIndex:es,onSelect:eW}),(0,n.jsxs)("div",{className:"flex items-start gap-1",children:[(0,n.jsx)("textarea",{ref:eT,value:L,onPaste:ey,onChange:e=>{if(Date.now()-eP.current<200){eT.current&&(eT.current.value="");return}I(e.target.value),en(-1)},onFocus:()=>p?.(),onKeyDown:t=>{if(g||t.nativeEvent?.isComposing||229===t.keyCode)return;if(t.shiftKey&&"Tab"===t.key){t.preventDefault(),t.stopPropagation(),(0,t7.e)();let e=N||[];if(e.length>0){let t=e.findIndex(e=>e.id===P),s=-1===t?0:(t+1)%e.length,n=e[s]?.id;n&&u?.(n)}return}if("Escape"===t.key){if(ee){t.preventDefault(),et(null),U(!1),I("");return}if(K){t.preventDefault(),U(!1);return}if(A){t.preventDefault(),console.log("[TEMP DIAGNOSTIC] Esc → stop",{sessionId:e}),eD();return}if(D.length>0){t.preventDefault(),F(ci);return}}if(ee){let e=ee.subOptions||[];if("ArrowDown"===t.key){t.preventDefault(),Z(t=>(t+1)%e.length);return}if("ArrowUp"===t.key){t.preventDefault(),Z(t=>(t-1+e.length)%e.length);return}if("Enter"===t.key||"Tab"===t.key){t.preventDefault(),eO(e[Y]);return}}if(K&&G.length>0){if("ArrowDown"===t.key){t.preventDefault(),Z(e=>(e+1)%G.length);return}if("ArrowUp"===t.key){t.preventDefault(),Z(e=>(e-1+G.length)%G.length);return}if("Enter"===t.key||"Tab"===t.key){t.preventDefault(),eB(G[Y]);return}}if(eo.length>0){let e=es<0?-1:(es%eo.length+eo.length)%eo.length;if("Tab"===t.key&&!t.shiftKey){t.preventDefault(),en(-1===e?0:(e+1)%eo.length);return}if(("Enter"===t.key||"Tab"===t.key)&&-1!==e){t.preventDefault(),eW(eo[e].cmd);return}}let s=eT.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&&!ee&&!K&&a&&el.length>0){t.preventDefault(),-1===B&&(W.current=L);let e=Math.min(B+1,el.length-1);if(e===B)return;O(e),I(el[e]);return}if("ArrowDown"===t.key&&!ee&&!K&&l&&-1!==B){t.preventDefault();let e=B-1;e<0?(O(-1),I(W.current)):(O(e),I(el[e]));return}if("Enter"===t.key&&(t.metaKey||t.ctrlKey)){t.preventDefault(),eA();return}"Enter"===t.key&&!t.shiftKey&&w&&(t.preventDefault(),eA())},onCompositionStart:()=>{eE.current=!0},onCompositionEnd:()=>{eE.current=!1,e$.current=Date.now(),Date.now()-eP.current<200&&(eT.current&&(eT.current.value=""),I(""))},placeholder:A?w?"Type command \xb7 Enter to queue \xb7 Esc to stop":"Type command \xb7 Send to queue":w?`Type command \xb7 ${j}`:"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]"}),L.trim().length>0?(0,n.jsx)("button",{type:"button",onClick:eC,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)(),ep(!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:v("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:eh,className:"relative min-w-0 flex items-center gap-1",children:[(0,n.jsxs)("button",{type:"button",disabled:A,onClick:()=>{ed(e=>!e),em(!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:A?"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 ${sE}`}),(0,n.jsx)("span",{dir:"rtl",className:"truncate min-w-0",children:(0,n.jsx)("bdi",{children:eH})}),(0,n.jsx)(t3.rX,{size:11,className:`text-text-muted shrink-0 transition-transform ${ec?"":"rotate-180"}`})]}),ec&&(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"}),eV.map(e=>{let t=z===e.id;return(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),d?.(e.id),ed(!1)},className:`w-full px-2 py-1.5 rounded text-left text-xs flex flex-col gap-0.5 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.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-brand-400 shrink-0 ml-1"})]}),e.label!==e.id&&(0,n.jsx)("span",{className:"truncate font-mono text-[10px] opacity-70",children:e.id})]},e.id)})]}),eG.length>0&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",disabled:A,onClick:()=>{em(e=>!e),ed(!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:A?`Cannot change ${eX?.optionKey||"effort"} while turn is running`:`Select ${eX?.optionKey||"effort"}`,children:eq||"—"}),eu&&(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:eX?.optionKey==="variant"?"Variant":"Reasoning effort"}),eG.map(e=>{let t=eq===e.value;return(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,t7.e)(),x?.(eX?.optionKey||"effort",e.value),em(!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:ev,className:"hidden",accept:"*/*"})]}),ej.active&&(0,n.jsx)("button",{type:"button",onMouseDown:e=>e.preventDefault(),onClick:eS,title:v("not-allowed"===ej.error||"service-not-allowed"===ej.error?"voice.denied":"voice.dictate"),"aria-label":v("voice.dictate"),className:`p-1.5 rounded flex items-center justify-center transition-colors ${ej.listening?"bg-red-500/90 text-white animate-pulse":ej.error?"text-red-400":"text-text-muted hover:text-text hover:bg-surface-2"}`,children:ej.listening?(0,n.jsx)(t3.jj,{size:15}):(0,n.jsx)(t3.GO,{size:15})}),A?(0,n.jsxs)(n.Fragment,{children:[(L.trim()||ef.length>0)&&(0,n.jsxs)("button",{type:"button",onClick:eA,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:w?"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:eD,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:D.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:eA,disabled:!L.trim()&&0===ef.length,className:`px-2 py-1 rounded transition-colors flex items-center justify-center ${L.trim()||ef.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)(s9,{isOpen:ex,store:s6,onSelect:eW,onClose:()=>ep(!1)})]})}),cc={Shield:"text-text-muted",Pencil:"text-accent",Eye:"text-accent",Sparkles:"text-warning"},cd=(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=oS(t=>t.bySession[e]?.isTurnRunning),u=oS(t=>t.bySession[e]?.metadata),m=u?.goal,x=(0,i1.Tw)(s).permissionModes||[],p=oS(t=>t.bySession[e]?.permissionMode)||(0,i1.Tw)(s).defaultMode,{branch:h,dirty:f}=aC(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)(iH,{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:`${cc[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:`${cc[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)(aT,{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})})]})]})}),cu=(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)(rU,{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))})]})}),cm=(0,r.memo)(function({mcpServers:e=[],onClose:t}){return(0,n.jsx)(rU,{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))})})}),cx=(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)(e),u=(0,r.useMemo)(()=>{let t=[...s||[]];return e&&!t.some(t=>t.id===e)&&t.unshift({id:e,label:e,desc:"Active CLI model"}),t},[s,e]),m=u.find(e=>e.id===c),x=m?.efforts||[];return(0,n.jsxs)(rU,{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:[x.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:x.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:u.map(e=>{let s=c===e.id;return(0,n.jsxs)("div",{onClick:o?void 0:()=>(e=>{(0,t7.e)(),l?.(e),d(e);let s=u.find(t=>t.id===e),n=s?.efforts||[];if(n.length>0&&!n.includes(t)){let e=s?.defaultEffort||n[0];e&&i?.(e)}})(e.id),"data-selected":s,className:`modal-row ${o?"opacity-40 cursor-not-allowed pointer-events-none":""}`,title:o?"Cannot change model while turn is running":void 0,children:[(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("div",{className:"text-xs font-semibold text-text flex items-center gap-1.5",children:(0,n.jsx)("span",{className:"truncate",children:e.label})}),(0,n.jsx)("div",{className:"text-[10px] font-mono text-text-subtle truncate mt-0.5",children:e.desc||e.id})]}),s&&(0,n.jsx)(t3.aJ,{size:14,className:"text-brand-500 shrink-0"})]},e.id)})})]})}),cp=(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)(rU,{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 ${sE} ${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}`)})})]})}),ch={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"},...i1.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 cf(e){return ch[e]||{shape:"flat",items:[]}}let cb=(0,r.memo)(function({engine:e="claude",options:t,onClose:s,onApply:a}){let{shape:l,items:i}=cf(e),[o,c]=(0,r.useState)(()=>{let s,n;return s=cf(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)(rU,{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))})})}),cg={Shield:"text-text-muted",Pencil:"text-accent",Eye:"text-accent",Sparkles:"text-warning"},cv=(0,r.memo)(function({modes:e=[],currentMode:t="",onClose:s,onSelectMode:r}){return(0,n.jsx)(rU,{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:`${cg[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)})})})}),cy=(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)(rU,{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"})]})})]})}),cw={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"}},cj=(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)(rU,{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=cw[e.status]||cw.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)})})]})}),ck=(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]),j=(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]),k=c&&!c.conversation;return(0,n.jsx)(rU,{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..."})]}):k?(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:j,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"})]})]})]})})}),cN=(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"})]})]})]})}),cS=(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]})]})]})]})}),cC=[],cT=(0,r.memo)(function({sessionId:e=""}){let[t,s]=(0,r.useState)(!1),a=oS(t=>t.bySession[e]?.tasks),l=(0,r.useMemo)(()=>Array.isArray(a)?a.filter(e=>!!(e&&e.subject&&String(e.subject).trim().length>0)):cC,[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))})]})}),cR=e=>String(e).padStart(2,"0");function c_(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 ${cR(n)}m`:n>0?`${n}m ${cR(r)}s`:`${r}s`}let cE=e=>Number(e?.duration_ms)||0,c$={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"}},cM={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"},cP=(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=oS(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=oi(p,o),f=!p.endedAt&&("running"===p.status||"paused"===p.status),b=cM[p.status]||(f?cM.running:cM.stopped);return(0,n.jsxs)(rU,{icon:(0,n.jsx)(t3.BZ,{size:14}),iconClass:"bg-brand-500/15 text-brand-500",title:f?`Running for ${c_(h)}`:`Ended \xb7 ${c_(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=c$[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)(cA,{task:p,elapsed:h,statusCls:b}),(0,n.jsxs)("div",{className:"p-3",children:[(0,n.jsx)(cz,{task:p,messages:t,engine:s}),(0,n.jsx)(cL,{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)(cI,{label:"TOKENS",value:i7(p.usage.total_tokens)}),(0,n.jsx)(cI,{label:"TOOLS",value:p.usage.tool_uses??0}),cE(p.usage)>0&&(0,n.jsx)(cI,{label:"TOOK",value:c_(cE(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 cA({task:e,elapsed:t,statusCls:s}){let r=c$[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)(cD,{}),(0,n.jsx)("span",{className:"text-brand-500",children:e.subagentType})]}),e.taskType&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(cD,{}),(0,n.jsx)("span",{children:e.taskType})]}),(0,n.jsx)(cD,{}),(0,n.jsxs)("span",{className:"text-text tabular-nums",title:"since the agent logged the task's start",children:["running ",c_(t)]}),(0,n.jsx)(cD,{}),(0,n.jsx)("span",{className:"text-text-subtle",children:e.taskId})]})]})]})}function cz({task:e,messages:t,engine:s}){let r=iZ(t,e.toolUseId),a=i2(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 cL({task:e,messages:t,engine:s,sessionId:r}){let a=iY(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,oq.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=>o0(s,e,{engine:s})||(0,n.jsx)(oI,{...e,engine:s},e.id))]})}function cI({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 cD=()=>(0,n.jsx)("span",{className:"text-text-subtle",children:"\xb7"}),cF=[],cB=(0,r.memo)(function({sessionId:e="",engine:t="claude",onStopTask:s}){let a=oS(t=>t.bySession[e]?.messages)||cF,l=oS(t=>t.bySession[e]?.harnessTasks)||cF,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;iX.has(n?.name)?t.push({kind:"agent",id:n.id,label:iG(n),...s}):n?.async&&t.push({kind:"shell",id:n.id,label:iJ(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)(cO,{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)(cO,{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)(cP,{tasks:o,messages:a,engine:t,sessionId:e,onStopTask:s,onClose:()=>c(null)})]})});function cO({icon:e,tag:t,items:s,messages:r,engine:a,now:l,onOpen:i}){let o=s.map(e=>e.label).join(", "),c=oi(s.reduce((e,t)=>t.startedAt&&(!e?.startedAt||t.startedAt<e.startedAt)?t:e,null),l),d=s.map(e=>i2(iZ(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:c_(c)}),(0,n.jsx)("span",{className:"text-[11px] text-text-muted truncate min-w-0",children:d||o})]})]})}let cW={model:"",skills:[],mcpServers:[]},cK=[],cU=(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),[j,k]=(0,r.useState)(!1),{t:N}=(0,se.s)(),{sendPrompt:S,resolvePermission:C,stop:T,stopTask:R,runShell:_,rewindToMessage:E,previewRewind:$,listRewindPoints:M,escalateMode:P,dismissBlocked:A,hasOlder:z,loadOlder:L,reload:I,hydrating:D,synced:F,hydrateFailed:B}=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=oS(e=>e.initSession),o=oS(e=>e.setMetadata),c=oS(e=>e.appendDelta),d=oS(e=>e.appendThinking),u=oS(e=>e.appendDiff),m=oS(e=>e.appendTool),x=oS(e=>e.updateToolResult),p=oS(e=>e.nestTool),h=oS(e=>e.nestToolResult),f=oS(e=>e.upsertTask),b=oS(e=>e.setPermission),g=oS(e=>e.clearPermission),y=oS(e=>e.finishTurn),w=oS(e=>e.setTurnRunning),j=oS(e=>e.addUserMessage),k=Q(e=>e.connected),[N,S]=(0,r.useState)(!1),[C,T]=(0,r.useState)(!1),[R,_]=(0,r.useState)(!1),[E,$]=(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":j(e,n.text,n.attachments||null,!!n?.replay);break;case"init":{let t=oE(oS.getState().bySession[e]?.metadata?.skills),s=new Map(t.map(e=>[e.id||e.name,e])),r=oE(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=oS.getState().bySession[e]?.tasks||[],r=(0,i1.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,i1.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":oS.getState().setBlocked(e,n);break;case"options_changed":n?.permissionMode&&oS.getState().setPermissionMode(e,n.permissionMode),n?.model&&o(e,{model:n.model}),n?.effort&&o(e,{effort:n.effort});break;case"turn_complete":y(e,n.stats,n.turnMs,!!n?.replay),n?.isError&&!o$(oS.getState().bySession[e]?.messages,n.result)&&oS.getState().addNotice(e,{subtype:n.subtype||"",level:"error",content:n.result||"The turn ended in an error."});break;case"stats":n?.stats&&oS.getState().setStats(e,n.stats);break;case"stopped":case"exit":g(e),oS.getState().finishTurn(e,null,n?.turnMs),"exit"===s&&(n?.error||n?.code!=null&&0!==n.code)&&oS.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":oS.getState().addNotice(e,{subtype:"error",level:"error",content:n?.message||"AI process failed"}),y(e,null,n?.turnMs);break;case"prompt_refused":oS.getState().addNotice(e,{subtype:"prompt_refused",level:"error",content:oM(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}),oS.getState().clearMessages(e),oS.getState().setTaskRecords(e,n?.taskRecords),oS.getState().restoreTurnState(e,n);break;case"cli_event":{let t=n?.type||"",s=n?.record||null;oS.getState().applyTaskRecords(e,[[t,n?.subtype||"",s,n?.ageMs]]);let r=oh(t,s);r&&oS.getState().addNotice(e,r)}}},[t,j,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 L=(0,r.useRef)(i);(0,r.useEffect)(()=>{L.current=i});let I=(0,r.useRef)(0),D=(0,r.useRef)(0),F=(0,r.useRef)(!1),B=(0,r.useRef)([]),O=(0,r.useRef)(0),W=(0,r.useRef)(null);null==W.current&&(W.current=function(e=o_){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),U=(0,r.useRef)(null),H=(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:O.current}),ee();return}let r=++O.current,a=D.current;F.current=!0,T(!0),B.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=B.current;for(let s of(B.current=[],F.current=!1,T(!1),t)){if("conversation_reset"===s.event){I.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<=I.current)continue;I.current=s.seq}z.current(e,s.event,s.data)}},o=setTimeout(()=>{r===O.current&&F.current&&(i(),ee())},4e3);H.current=o,n.emit("ai:create",{sessionId:e,engine:t,cwd:s,options:{defaultMode:(0,i1.Tw)(t).defaultMode,defaultEffort:(0,i1.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===O.current,snapshotSeq:s?.session?.seq,appliedSeq:I.current,sameLog:a===D.current}))return;let n=null,c=s?.session?.events;(0,v.Lq)("ai-hydrate","ack",{gen:r,stale:r!==O.current,ms:Date.now()-l,ok:s?.ok??null,error:s?.error??null,events:Array.isArray(c)?c.length:null,hasMore:s?.session?.hasMore??null});try{if(clearTimeout(o),!s?.ok||!Array.isArray(c))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:c.length,hasMore:s.session.hasMore}),M.current=c[0]?.seq??0,S(!!s.session.hasMore&&c.length>0),(0,v.Lq)("ai-page","hydrate",{sessionId:e,replayed:c.length,hasMore:s.session.hasMore,fromSeq:c[0]?.seq??0,lastSeq:r,oldestId:null}),c.length>0){let n=oP(c,t);oS.getState().hydrateSession(e,{messages:n.messages,tasks:n.tasks,metadata:{...n.metadata,...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:op(s.session.taskRecords,n.harnessTasks)})}else w(e,!!s.session.isTurnRunning),oS.getState().setTaskRecords(e,s.session.taskRecords),s.session.permissionMode&&oS.getState().setPermissionMode(e,s.session.permissionMode),s.session.stats&&oS.getState().setStats(e,s.session.stats);n=s.session.activePermission||null,I.current=r}finally{clearTimeout(o),r===O.current&&i(),n&&r===O.current&&oS.getState().setPermission(e,n),s?.ok&&void 0!==s.session.isTurnRunning&&(oS.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?(_(!0),$(!1),Z()):ee(),(0,v.Lq)("ai-hydrate","settled",{gen:r,stale:r!==O.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||U.current||(U.current=setTimeout(()=>{U.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=I.current,a=!!oS.getState().bySession[e]?.isTurnRunning;n.seq===r&&!!n.isTurnRunning===a?(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)(()=>()=>{U.current&&clearTimeout(U.current),J.current&&clearTimeout(J.current),Y.current&&clearTimeout(Y.current),K.current&&clearTimeout(K.current),H.current&&clearTimeout(H.current),U.current=J.current=Y.current=K.current=H.current=null,F.current=!1,B.current=[]},[]),(0,r.useEffect)(()=>{if(e)return V.current!==e&&(V.current=e,F.current=!1,Z(),_(!1),$(!1)),L.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=k,k&&!e){if(!X.current){G.current="reconnect";return}es()}},[k,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)&&oS.getState().appendStream(e,n,a)},o=()=>{l=!1;let t=a;a=[];let s=z.current;for(let n of t)n.stream?oS.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 B.current.push(n);let u="delta"===n.event||"thinking"===n.event;if("conversation_reset"===n.event){I.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=I.current,null==a||!(a<=(l||0))){if(null!=n.seq&&(I.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,{force:n=!1,attachments:r=null}={})=>{if(!t&&!r?.length||!n&&oS.getState().bySession[e]?.isTurnRunning)return;let a=l.current||Q.getState().bus;sc.getState().clearNotification(e),a?.emit("ai:prompt",{sessionId:e,message:t,cwd:s,...r?.length?{attachments:r}:{}})},[e,s]),ei=(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"}),oS.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),s1.GX)},[e,g]),eo=(0,r.useCallback)(()=>{let t=l.current||Q.getState().bus;t?.emit("ai:stop",{sessionId:e})},[e]),ec=(0,r.useCallback)(t=>{if(!t)return;let s=l.current||Q.getState().bus;s?.emit("ai:stopTask",{sessionId:e,taskId:t})},[e]),ed=(0,r.useCallback)(e=>{el(`! ${e}`)},[el]),eu=(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]),em=(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]),ex=(0,r.useCallback)((e,{files:t=!0,index:s=null}={})=>em(e,null,{files:t,preview:!0,index:s}),[em]),ep=(0,r.useCallback)(t=>{if(!t)return;oS.getState().setPermissionMode(e,t),oS.getState().clearBlocked(e);let s=l.current||Q.getState().bus;s?.emit("ai:options",{sessionId:e,options:{mode:t}})},[e]),eh=(0,r.useCallback)(()=>{oS.getState().clearBlocked(e)},[e]);return{hydrating:C,synced:R,hydrateFailed:E,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 oR({startSeq:n,estimateBytes:oC,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=oS.getState().bySession[e];return oP(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+oC(t),0)/1024)+"KB",hasMore:i}),M.current!==n||!o||(M.current=l,S(i),!a.length))return!1;return oS.getState().prependMessages(e,a),!0}finally{P.current=!1}},[e,t]),reload:er,sendPrompt:el,resolvePermission:ei,stop:eo,stopTask:ec,runShell:ed,rewindToMessage:em,previewRewind:ex,listRewindPoints:eu,escalateMode:ep,dismissBlocked:eh}}({sessionId:e,engine:t,workspacePath:s,bus:l,isVisible:o}),O=(0,r.useCallback)(()=>{(0,t7.e)(),w(!0),I(),setTimeout(()=>w(!1),700)},[I]),W=oS(t=>t.bySession[e]?.activePermission),K=!!oS(t=>t.bySession[e]?.isTurnRunning),U=oS(t=>t.bySession[e]?.gateError),H=oS(t=>t.bySession[e]?.activeBlocked),q=oS(t=>t.bySession[e]?.metadata)||cW,V=oS(t=>t.bySession[e]?.tasks)||cK,X=oS(e=>e.setPermissionMode),G=sc(t=>e?t.sessionStatus[e]?.state:null)||"idle",J=tS(e=>e.terminalBackgroundOpacity),Y=tS(e=>e.customBackgrounds),Z=tS(e=>e.terminalBackgrounds),ee=tS(t=>t.backgroundBySession[e]),et=tS(e=>e.terminalTheme),es=tS(e=>e.fontSize),en=tS(e=>e.showFolderButton),er=tS(e=>e.showNoteButton),ea=tS(e=>e.setRightPanelRoot),el=tS(e=>e.setRightPanelTab),ei=tS(e=>e.openRightPanel),eo=tS(t=>t.artifactsBySession[e]),ec=r8(s,i,{enabled:c&&en}),{theme:ed}=(0,ag.D)(),eu=(0,r.useMemo)(()=>(0,ar.In)(ed,et),[ed,et]),em=(0,r.useMemo)(()=>ew(es)+(d?s1.TQ:s1.wM),[es,d]),ex=(0,r.useMemo)(()=>{let{alpha:e,size:t}=s1.ii,s=`radial-gradient(color-mix(in srgb, ${eu.foreground} ${e}%, transparent) 1px, transparent 1px) 0 0 / ${t}px ${t}px`,n=e$(ee,Z,Y,u),r="dark"===ed?eR(n,Y):null;if(r){let e=`rgba(${ej},${J??.8})`,t=`rgba(${ek},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}, ${eu.background}`}},[Z,ee,Y,J,eu,ed,u]),ep=q.skills||[],eh=q.mcpServers||[],ef=(0,r.useCallback)(e=>{S(`/${e}`)},[S]),eb=(0,r.useCallback)(t=>{let s=l?.emit?l:Q.getState().bus;s?.emit?.("ai:options",{sessionId:e,options:t})},[l,e]),eg=(0,r.useCallback)(t=>{oS.getState().setMetadata(e,{model:t}),eb({model:t})},[eb,e]),ev=(0,r.useCallback)(e=>{e?.sessionId&&eb({resume:e.sessionId})},[eb]),ey=(0,r.useCallback)(e=>{if(e)return ev(e);g("sessions")},[ev]),eN=(0,r.useCallback)((t,s)=>{t&&("effort"===t&&oS.getState().setMetadata(e,{effort:s}),eb({[t]:s}))},[eb,e]),eS=(0,i1.Tw)(t),eC=(0,r.useCallback)(t=>{X(e,t),eb({mode:t})},[eb,e,X]),eT=(0,r.useCallback)((t,s)=>{oS.getState().rewindToMessage(e,t,s)},[e]),e_=(0,r.useCallback)(t=>{if(!b&&t.shiftKey&&"Tab"===t.key){t.preventDefault(),(0,t7.e)();let s=eS.permissionModes||[],n=oS.getState().bySession[e]?.permissionMode||eS.defaultMode,r=s.findIndex(e=>e.id===n),a=-1===r?0:(r+1)%s.length,l=s[a]?.id;l&&eC(l)}},[e,eS,eC,b]),eE=av({isFocused:c,onActivate:()=>m?.()}),eM=(0,r.useRef)(m);(0,r.useEffect)(()=>{eM.current=m});let eP=(0,r.useCallback)(()=>eM.current?.(),[]),eA=(0,r.useMemo)(()=>({sessionId:e,isFocused:c,activate:eP}),[e,c,eP]);return(0,n.jsx)(oq.fe.Provider,{value:eA,children:(0,n.jsxs)("div",{...eE,onKeyDown:e_,className:"ai-pane w-full h-full flex flex-col bg-bg overflow-hidden relative select-text",style:{...ex,"--color-text":eu.foreground,"--ai-fs":`${em}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 ${nz(G)}`,style:{background:nA(G).dot}}),(0,n.jsx)("span",{className:"flex-1 min-w-0 truncate text-text",children:a||s1.UB[t]?.label||t}),(0,n.jsx)(ab,{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:[er&&(0,n.jsx)("button",{onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onTouchStart:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>{e.stopPropagation(),(0,t7.e)(),k(!0)},className:ay,title:N("terminalPane.note"),children:(0,n.jsx)(t3.y8,{size:16,className:aw})}),(0,n.jsx)("button",{onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onTouchStart:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>{e.stopPropagation(),O()},className:ay,title:N("terminalPane.refresh"),children:(0,n.jsx)(t3.e9,{size:16,className:`${aw} ${y?"animate-spin":""}`})})]}),en&&s&&(0,n.jsxs)("button",{onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onTouchStart:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>{e.stopPropagation(),(0,t7.e)(),ea(s,s),window.innerWidth>=760?el("files",s):ei()},className:`relative ${ay}`,title:N("terminalPane.openFolderHere"),children:[(0,n.jsx)(t3.vd,{size:16,className:aw}),ec>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:ec>999?"999+":ec})]}),h&&eo?.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,eo[0])},className:`relative ${ay}`,title:N("terminalPane.artifacts"),children:[(0,n.jsx)(t3.sU,{size:16,className:aw}),(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:eo.length})]})]}),(0,n.jsx)(cT,{sessionId:e}),(0,n.jsx)(cB,{sessionId:e,engine:t,onStopTask:R}),(0,n.jsx)(cl,{sessionId:e,engine:t,workspacePath:s,fileBus:i,onSendPrompt:S,onResolvePermission:C,onRewind:E,onPreviewRewind:$,onListRewindPoints:M,onCutLocal:eT,hasOlder:z,onLoadOlder:L,onOpenResume:ey,hydrating:D,synced:F,hydrateFailed:B,onReload:I}),H&&!W&&(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)(cS,{engine:H.engine||t,message:H.message,escalate:H.escalate,onEscalate:P,onDismiss:A})}),W&&(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"===W.tool?(0,n.jsx)(oK.J,{requestId:W.requestId,questions:W.input?.questions||[],failed:U,onResolve:C}):(0,n.jsx)(cN,{requestId:W.requestId,tool:W.tool,input:W.input,failed:U,onResolve:C})}),(0,n.jsx)(co,{sessionId:e,engine:t,onSend:S,onStop:T,onRunShell:_,onResolvePermission:C,onSelectModel:eg,onModeChange:eC,onOpenModal:g,onOptionChange:eN,onActivate:m,isFocused:c,fileBus:i,workspacePath:s,modalOpen:null!==b}),(0,n.jsx)(cd,{sessionId:e,sessionName:a,engine:t,workspacePath:s,isDesktop:d,onModeChange:eC,onNewChat:f}),"skills"===b&&(0,n.jsx)(cu,{skills:ep,onClose:()=>g(null),onSelectSkill:ef}),"mcp"===b&&(0,n.jsx)(cm,{mcpServers:eh,onClose:()=>g(null)}),"model"===b&&(0,n.jsx)(cx,{currentModel:q.model,currentEffort:q.effort||"",models:q.modelOptions?.length?q.modelOptions:eS.models,isTurnRunning:K,onClose:()=>g(null),onSelectModel:eg,onSelectEffort:e=>eb({effort:e})}),"sessions"===b&&(0,n.jsx)(cp,{engine:t,workspacePath:s,onClose:()=>g(null),onResume:ev}),"config"===b&&(0,n.jsx)(cb,{engine:t,options:oS.getState().bySession[e]?.metadata,onClose:()=>g(null),onApply:e=>eb(e)}),"mode"===b&&(0,n.jsx)(cv,{modes:eS.permissionModes||[],currentMode:oS.getState().bySession[e]?.permissionMode||eS.defaultMode,onClose:()=>g(null),onSelectMode:eC}),"doctor"===b&&(0,n.jsx)(cy,{engine:t,workspacePath:s,onClose:()=>g(null)}),"tasks"===b&&(0,n.jsx)(cj,{tasks:V,onClose:()=>g(null)}),"rewind"===b&&(0,n.jsx)(ck,{sessionId:e,onListPoints:M,onPreview:$,onApply:e=>E(e),onClose:()=>g(null)}),j&&er&&(0,n.jsx)(af,{bus:l,sessionId:e,onClose:()=>k(!1)})]})})});class cH 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 cq=(0,r.memo)(function({children:e}){return(0,n.jsx)("div",{className:"absolute inset-x-0 top-0 bottom-[37px] overflow-hidden",children:e})}),cV=(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)(iH,{}):"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})}),cX=(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})}),cG=(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:j,sidebarCollapsed:k,sidebarWidth:N,setSidebarWidth:S,toggleSidebar:C,paneWidth:T=null,setPaneWidth:R,paneRegistry:_,bindSwipeTab:E,nav:$,onBack:M,onOpenRemote:P,onOpenMobile:A,onOpenFiles:z,onLogout:L,onStopCodespace:I,onUpdate:D,onRestart:F,onDeleteWorkspace:B,onReorderSession:O,onSetHiddenRepos:W,atStackBottom:K=!1,onAddWorkspace:U,onOpenSettings:H,homeDir:q,recentWorkspaces:V,rightPanel:X,editorPanel:G,mobilePanel:J,onOpenArtifact:Y,fileBus:Z,codespaceInfo:ee,tunnelUrl:et,apiKey:es,connectionMode:en,subscribeToPush:ea,unsubscribeFromPush:el,updateAvailable:ei,canSelfUpdate:eo}){let{t:ec}=(0,se.s)(),ed="mouse"===nm(),eu=Q(e=>e.bus),em=Q(e=>e.busRef),ex=Q(e=>e.connected),ep=Q(e=>e.carrier),eh=e||eu,ef=t||em,eb=s??ex,eg=a||ep,ev=Z||t2.getState(),{panesContainerRef:ey,registerPaneApi:ew,registerPaneElement:ej,registerKeyboardTextApi:ek,handlePasteFallback:eN,handleInputFocusChange:eS,focusPane:eC,focusKeyboardInput:eT,scrollPaneIntoView:eR}=_,[e_,eE]=(0,r.useState)(null),{workspaceSessionIds:e$,workspaceOpenedSessions:eM,renderedSessions:eP,mountedSet:eA,workspaceIndex:ez}=(0,r.useMemo)(()=>(function({sessions:e,openedSessions:t,livePanes:s,mountedWorkspaces:n,activeWorkspaceId:r,isDesktop:a}){let l=new Set(e.filter(e=>ty(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,ty(e)])),u=new Set(t.filter(e=>!!l.has(e)||!!a&&!!n[d.get(e)??tv])),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]),eL=(0,r.useMemo)(()=>o.filter(e=>ty(e)===m),[o,m]),eI=(0,r.useMemo)(()=>new Map(eL.map((e,t)=>[e.id,t])),[eL]),eD=c.find(e=>e.id===m),eF=eD?.path||u?.workspacePath||null,eB=tS(e=>e.rightPanelRoots),eO=tS(e=>e.agentBySession),eW=tS(e=>e.setRightPanelRoot),eK=tS(e=>e.openRightPanel),eU=tS(e=>e.reorderOpenedSessions),eH=(0,r.useCallback)(e=>{eU(e),O?.(e)},[eU,O]),eq=(0,r.useCallback)(e=>{$.handleSelectSession(e)},[$]),eV=(0,r.useCallback)((e,t)=>{let s=o.filter(e=>e.id!==t&&ty(e)===(m??null)).length+1;$.handleReplaceSession(t,`${e.short||e.label} ${s}`,e,!0)},[$,o,m]),eX=eB[eF]||eF,eG=(0,r.useCallback)(e=>X?.onTabChange(e,eF??""),[X,eF]),eJ=(0,r.useCallback)(()=>z?.(eX),[z,eX]),eY=(0,r.useMemo)(()=>eD?.hiddenRepos||[],[eD?.hiddenRepos]),eZ=(0,r.useCallback)(e=>{eD&&W?.(eD.id,e)},[eD,W]),eQ=d&&(f[d]||o.find(e=>e.id===d)?.cwd)||null;(0,r.useEffect)(()=>{eW(eF,null)},[d,eF,eW]);let e0=!o.length,[e1,e2]=(0,r.useState)(!1);X?.open&&!e1&&e2(!0);let[e5,e3]=(0,r.useState)(!1);!X?.open&&e5&&e3(!1),(0,r.useEffect)(()=>{if(!X?.open)return;let e=requestAnimationFrame(()=>e3(!0));return()=>cancelAnimationFrame(e)},[X?.open]);let e4=!!G?.filePath,[e6,e8]=(0,r.useState)(!1);e4&&!e6&&e8(!0);let[e9,e7]=(0,r.useState)(!1);!e4&&e9&&e7(!1);let[te,tt]=(0,r.useState)(null);e4&&te?.filePath!==G.filePath&&tt({filePath:G.filePath,artifactTitle:G.artifactTitle,previewSeq:G.previewSeq}),(0,r.useEffect)(()=>{if(!e4)return;let e=requestAnimationFrame(()=>e7(!0));return()=>cancelAnimationFrame(e)},[e4]);let[ts,tn]=(0,r.useState)(0),[tr,ta]=(0,r.useState)(!1),tl=(0,r.useRef)(null);(0,r.useEffect)(()=>{if(!v)return;let e=tl.current;if(!e)return;let t=new ResizeObserver(e=>tn(e[0].contentRect.width));return t.observe(e),()=>t.disconnect()},[v]),(0,r.useEffect)(()=>{if(!eb||!eh?.emit)return;let e=!1,t=()=>eh.emit("bg:get",{},t=>{!e&&t?.success&&t.dataUrl&&tS.getState().setCustomBackgrounds([{id:"custom",dataUrl:t.dataUrl}])}),s=setTimeout(()=>{e||t()},4e3);return eh.emit("bg:list",{},n=>{e||(clearTimeout(s),n?.success&&Array.isArray(n.items)?tS.getState().setCustomBackgrounds(n.items):t())}),()=>{e=!0,clearTimeout(s)}},[eb,eh]);let ti=eM.length,to=tS(e=>e.autoPaneWidths[m]??null),tc=tS(e=>e.setAutoPaneWidth),td=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:ts,paneCount:ti,sidebarWidth:k?0:N,sidePx:(X?.open&&e5?X.width:0)+(e4&&e9?G.width:0)+(J?.open&&"pin"===J.mode?J.width:0),gapPx:2,paddingPx:0,minWidth:er.min,applied:to});(0,r.useEffect)(()=>{null!=td&&tc(m,td)},[td,m,tc]);let tu=(0,r.useRef)({paneWidth:T,paneCount:ti,sidebarWidth:N,rowWidth:ts});(0,r.useEffect)(()=>{let e=tu.current;tu.current={paneWidth:T,paneCount:ti,sidebarWidth:N,rowWidth:ts},(e.paneWidth!==T||e.paneCount!==ti||e.sidebarWidth!==N||e.rowWidth!==ts)&&tc(m,null)},[T,ti,N,ts,m,tc]);let tm=T??td,tx=(0,r.useRef)({editorFile:G?.filePath,rightOpen:X?.open});(0,r.useEffect)(()=>{if(!v||!d)return;let e=tx.current,t=e.editorFile!==G?.filePath||e.rightOpen!==X?.open;if(tx.current={editorFile:G?.filePath,rightOpen:X?.open},!t)return;let s=setTimeout(()=>{eR(d)},260);return()=>clearTimeout(s)},[G?.filePath,X?.open,d,v,eR]);let tp=e=>{let t=tm??e.currentTarget.parentElement?.offsetWidth??er.min;ta(!0),sS(e,{startWidth:t,onWidth:e=>R?.(e),onEnd:()=>ta(!1)})},th=(0,r.useCallback)(()=>{tc(m,null),R?.(null)},[m,tc,R]);(0,r.useEffect)(()=>{let e=()=>th();return window.addEventListener("terminal:fitPanes",e),()=>window.removeEventListener("terminal:fitPanes",e)},[th]);let tf=(e,t,s,r=0)=>{let a=o.find(t=>t.id===e),l=eO[e],i=s1.H8.find(e=>e.id===l);return i?(0,n.jsx)(cH,{title:"AI Chat Pane",children:(0,n.jsx)(cU,{sessionId:e,engine:i.aiEngine,workspacePath:a?.cwd||a?.workspacePath||eD?.path,sessionName:a?.name,bus:eh,fileBus:ev,isVisible:t,isFocused:s,isDesktop:v,bgIndex:r,onActivate:()=>$.handleSelectSession(e),onNewChat:()=>eV(i,e),onOpenRemote:P,onOpenMobile:A,onOpenArtifact:Y})},e):(0,n.jsx)(aj,{workspacePath:a?.workspacePath,sessionName:a?.name,bus:eh,connected:eb,sessionId:e,isVisible:t,isFocused:s,onActivate:$.handleSelectSession,onRegisterApi:ew,onPasteFallback:eN,showFocusBorder:!1,mountDelay:!s&&ez.has(e)?120*ez.get(e):0,bgIndex:r,onOpenArtifact:Y,onOpenRemote:P,onOpenMobile:A})},tb=e=>(0,n.jsx)(nM,{bus:eh,sessionId:e,onExpandChange:()=>{},onRefocus:()=>eC(e),onRegisterTextApi:ek,onInputFocusChange:eS,platform:l,onInput:sc.getState().clearNotification,onSwitchSession:$.switchSession,onSwitchToIndex:$.switchToIndex,isDesktop:v,statusStrip:(0,n.jsx)(aq,{sessionId:e,busRef:ef,onReveal:t=>{let s=o.find(t=>t.id===e)?.workspacePath;eW(s,t||s),eK()}})});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:tl,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:k?0:N},children:(0,n.jsx)(a$,{allSessions:o,workspaces:c,activeSessionId:d,activeWorkspaceId:m,onSelectSession:$.handleSelectSession,onSelectWorkspace:$.handleSelectWorkspace,onCreateNamedSession:$.handleCreateSession,onResumeAgentSession:$.handleResumeAgentSession,shells:j,onRenameSession:$.handleRenameSession,onDeleteSession:$.handleDeleteSession,onReorderSession:eH,onDeleteWorkspace:B,onAddWorkspace:U,onOpenSettings:H,busRef:ef,homeDir:q,cwdBySession:f,connected:eb,width:N,onResize:S,onCollapse:C})}),(0,n.jsxs)("div",{className:"flex-1 min-w-0 min-h-0 flex flex-col",children:[(!e0||!v)&&(0,n.jsx)(r1,{sessions:eL,allSessions:o,activeSessionId:d,isActive:y,connected:eb,onSwitchSession:eq,onCreateSession:$.handleQuickCreateSession,onRenameSession:$.handleRenameSession,onDeleteSession:$.handleDeleteSession,onCreateNamedSession:$.handleCreateSession,onResumeAgentSession:$.handleResumeAgentSession,onBack:v||K?null:M,workspaces:c,activeWorkspaceId:m,onSelectWorkspace:$.handleSelectWorkspace,hasUngrouped:o.some(e=>!ty(e)),onOpenRemote:P,onOpenMobile:A,onOpenFiles:z,onLogout:L,onStopCodespace:I,onUpdate:D,onRestart:F,codespaceInfo:ee,tunnelUrl:et,apiKey:es,connectionMode:en,subscribeToPush:ea,unsubscribeFromPush:el,agentVersion:i,updateAvailable:ei,canSelfUpdate:eo,busRef:ef,carrier:eg,shells:j,onToggleSidebar:v?C:null,sidebarCollapsed:k,onReorderSession:eH,onToggleRightPanel:X?.onToggle,rightPanelOpen:X?.open,fileBus:ev,homeDir:q}),e0?(0,n.jsx)("div",{className:"flex-1 min-h-0",children:(0,n.jsx)(iV,{onAddWorkspace:U,onOpenRemote:P,recent:V,homeDir:q,onOpenRecent:e=>U?.(e)})}):(0,n.jsx)("div",{ref:ey,className:`flex-1 min-h-0 ${v?"flex flex-row overflow-x-auto overflow-y-hidden px-0 pb-0 scrollbar-none":"relative"}`,...E({enabled:!v,sessionIds:eM,activeSessionId:d,onSwitch:$.handleSelectSession}),children:eP.map(e=>{let t=e$.has(e),s=e===d,r=t&&(v||s),a=eI.get(e)??0;return(0,n.jsxs)("div",{ref:t=>ej(e,t),className:t?v?`h-full relative bg-bg border-r-2 border-border-subtle last:border-r-0 ${tr?"":"transition-[width] duration-200 ease-out"}`:`absolute inset-0 ${s?`opacity-100 z-10 ${w}`:"opacity-0 z-0 pointer-events-none"}`:"hidden",style:t&&v?null!=tm?{width:tm,flexShrink:0}:{flex:"1 1 0",minWidth:er.min}:void 0,children:[eA.has(e)?eO[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:tf(e,r,s,a)}):v?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)(cq,{children:[tf(e,r,s,a),(0,n.jsx)(cV,{sessionId:e})]}),(0,n.jsx)("div",{className:"absolute inset-x-0 bottom-0 z-20 border-t border-border-subtle bg-surface",children:s?tb(e):(0,n.jsx)("button",{type:"button",tabIndex:-1,onClick:()=>{$.handleSelectSession(e),setTimeout(eT,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)(cX,{sessionId:e,placeholder:ec("mobileKeyboard.typeCommand")})})})})]}):tf(e,r,s,a):(0,n.jsx)("div",{className:"w-full h-full flex items-center justify-center text-text-muted text-xs"}),t&&v&&(0,n.jsx)("div",{onPointerDown:tp,onDoubleClick:th,className:"absolute top-0 right-0 bottom-0 w-1 cursor-col-resize hover:bg-brand-500/40 transition-colors z-30",title:ed?sZ(ec("shortcuts.fitPanes")||"Auto-fit panes","fitPanes"):void 0})]},e)})}),!v&&d&&!eO[d]?.endsWith("-ui")&&tb(d)]}),(G?.filePath||v&&e6)&&(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:e4&&e9?G.width:0}:void 0,"aria-hidden":v&&!e4,children:(0,n.jsx)(iK,{filePath:e4?G.filePath:te?.filePath,artifactTitle:e4?G.artifactTitle:te?.artifactTitle,previewSeq:e4?G.previewSeq:te?.previewSeq,workspace:eX,fileBus:ev,width:G.width,onResize:G.onResize,onClose:G.onClose,onOpenFull:G.onOpenFull,onOpenFile:G.onOpen,isDesktop:v})}),v&&J?.open&&"pin"===J.mode&&(0,n.jsx)("div",{ref:eE,className:"relative overflow-hidden flex-shrink-0 border-l border-border",style:{width:J.width},children:(0,n.jsx)("div",{onPointerDown:J.onResizeStart,className:"absolute top-0 left-0 bottom-0 w-1 cursor-col-resize hover:bg-brand-500/40 transition-colors z-20"})}),v&&J?.open&&(0,n.jsx)(a9,{busRef:ef,protocolRef:J.protocolRef,connected:eb,pinSlot:e_}),X?.open&&!v&&(0,n.jsx)("div",{className:"absolute inset-0 z-20 bg-black/50 animate-in fade-in duration-200",onClick:X.onToggle}),(X?.open||v&&e1)&&(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:X?.open&&e5?X.width:0}:void 0,"aria-hidden":v&&!X?.open,children:(0,n.jsx)(l9,{workspacePath:eF,filesRoot:eX,cwdHint:eQ,activeFile:G?.filePath,fileBus:ev,tab:X.tabs?.[eF??""]||"files",onTabChange:eG,width:X.width,onResize:X.onResize,onClose:X.onToggle,onOpenFiles:z?eJ:null,onOpenFile:G?.onOpen,onNewTerminal:X.onNewTerminal,onAddWorkspace:U,homeDir:q,hiddenRepos:eY,onHiddenReposChange:eD&&W?eZ:null,isDesktop:v})})]}),(0,n.jsx)(iU,{}),v&&!e0&&(0,n.jsx)(aV,{cwd:d&&(f[d]||u?.cwd||eD?.path)||"",sessionId:d,busRef:ef,fileBus:ev,connected:eb,carrier:eg,sessionName:u?u?.name:"",agentVersion:i,platform:l,homeDir:q})]})});var cJ=s(45111);function cY({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)(cJ.A,{size:"lg"}),(0,n.jsx)("p",{className:"text-sm text-text-muted",children:e||t("connection.retrying")})]})]})}var cZ=s(30240),cQ=s(51283),c0=s(4368),c1=s(79996),c2=s(86152);let c5=null;function c3({text:e,title:t,style:s,className:a=""}){let l=(0,r.useRef)(null),[i,o]=(0,r.useState)(0);return(0,r.useEffect)(()=>{let t=l.current;if(!t||t.clientWidth<10)return;let s=()=>{c5||(c5=document.createElement("canvas").getContext("2d")),c5.font=getComputedStyle(t).font;let s=t.clientWidth;if(c5.measureText(e).width<=s)return o(0);let n=1;for(;n<e.length&&c5.measureText(`…${e.slice(n)}`).width>s;)n++;o(n)};s();let n=new ResizeObserver(s);return n.observe(t),()=>n.disconnect()},[e]),(0,n.jsx)("span",{ref:l,title:t??e,style:s,className:`truncate ${a}`,children:i?`…${e.slice(i)}`:e})}function c4({session:e,index:t,status:s,hasNotification:r,connected:a,onSelect:l,onLongPress:i,onRename:o,onDelete:c,cwd:d,fileBus:u,homeDir:m,shellCount:x=1}){let{t:p}=(0,se.s)(),h=Q(e=>e.connected),f=a??h,b=s?.state||"idle",g=nA(b),v=d||e.cwd||e.workspacePath||null,{branch:y,dirty:w,changedCount:j}=aC(v,u,{enabled:f}),k=e.workspacePath||null,N=v?k&&v===k?"~":k&&v.startsWith(`${k}/`)?v.slice(k.length+1):n2(v,m)||"~":"~",{ref:S,isDragging:C}=(0,c2.gl)({id:e.id,index:t});return(0,n.jsx)("div",{ref:S,onClick:()=>{f&&!C&&((0,t7.e)(),l(e.id))},onContextMenu:t=>{i&&(t.preventDefault(),i(e))},className:`group relative select-none rounded-xl ${C?"opacity-70":""} ${f?"cursor-pointer active:scale-[0.98] hover:-translate-y-1":"opacity-60"}`,children:(0,n.jsxs)("div",{className:`rounded-xl overflow-hidden border ring-1 ${"idle"!==b?`status-border-${b}`:""}`,style:{background:f?"var(--card-term-bg)":"var(--card-term-bg-off)",borderColor:"var(--card-border)",boxShadow:"var(--card-shadow)","--tw-ring-color":"var(--card-ring)"},children:[(0,n.jsxs)("div",{className:"flex items-center gap-2 px-2.5 py-1.5 border-b",style:{background:"var(--card-titlebar-bg)",borderColor:"var(--card-titlebar-border)"},children:[(0,n.jsxs)("div",{className:`flex items-center gap-1 flex-shrink-0 ${f?"":"opacity-40 saturate-0"}`,children:[(0,n.jsx)("span",{className:"w-[7px] h-[7px] rounded-full bg-[#ff5f57]"}),(0,n.jsx)("span",{className:"w-[7px] h-[7px] rounded-full bg-[#febc2e]"})]}),(0,n.jsx)("span",{className:"flex-1 min-w-0 text-center text-[11px] font-medium truncate",style:{color:"var(--card-name-fg)"},title:e.name||p("terminal.defaultName"),children:e.name||p("terminal.defaultName")}),(0,n.jsxs)("div",{className:"flex items-center gap-2 flex-shrink-0",onClick:e=>e.stopPropagation(),children:[o&&(0,n.jsx)("button",{type:"button",onClick:()=>{(0,t7.e)(),o(e)},disabled:!f,className:"p-1.5 rounded-md transition-colors hover:bg-amber-500/10 disabled:cursor-not-allowed",style:{color:f?"var(--card-accent-amber)":"var(--card-btn-disabled)"},"aria-label":p("sessions.editName"),title:p("sessions.editName"),children:(0,n.jsx)(t3.gH,{size:16})}),c&&(0,n.jsx)("button",{type:"button",onClick:()=>{(0,t7.e)(),c(e)},disabled:!f,className:"p-1.5 rounded-md transition-colors hover:bg-red-500/15 disabled:cursor-not-allowed",style:{color:f?"var(--card-accent-red)":"var(--card-btn-disabled)"},"aria-label":p("sessions.deleteTitle"),title:p("common.delete"),children:(0,n.jsx)(t3.TB,{size:16})})]})]}),(0,n.jsxs)("div",{className:"relative px-3 py-3 font-mono min-h-[128px]",children:["idle"!==b&&(0,n.jsxs)("span",{className:`absolute top-1.5 right-1.5 inline-flex items-center gap-1 px-1.5 py-0.5 rounded-full text-[10px] font-medium ${g.cls}`,style:{background:`${g.dot}22`,color:g.dot},children:[(0,n.jsx)("span",{className:`w-1.5 h-1.5 rounded-full term-dot${g.pulse?` pulse-${g.pulse}`:""}`,style:{background:g.dot}}),p(g.label)]}),r&&(0,n.jsx)("span",{className:"absolute top-1.5 left-1.5 w-2 h-2 rounded-full bg-brand-500"}),(0,n.jsxs)("div",{className:"text-[11.5px] leading-[1.7] space-y-0.5",children:[(0,n.jsxs)("div",{className:"flex items-center min-w-0",children:[(0,n.jsx)("span",{className:"flex-shrink-0",style:{color:"var(--card-accent-green)"},children:"➜"}),"~"!==N&&N?(0,n.jsx)(c3,{text:N,title:v||void 0,style:{color:"var(--card-accent-cyan)"},className:"flex-1 min-w-0 mx-1"}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"flex-shrink-0 mx-1",style:{color:"var(--card-accent-cyan)"},children:"~"}),(0,n.jsx)("span",{className:"truncate",style:{color:"var(--card-body-fg)"},children:e.name||p("terminal.defaultName")})]})]}),f?(0,n.jsxs)(n.Fragment,{children:[y&&(0,n.jsxs)("div",{className:"flex items-center min-w-0 gap-1.5",style:{color:"var(--card-body-dim)"},children:[(0,n.jsxs)("span",{className:"flex items-center min-w-0",children:[(0,n.jsx)("span",{className:"flex-shrink-0",style:{color:"var(--card-accent-amber)"},children:"⎇"}),(0,n.jsxs)("span",{className:"ml-1 truncate",title:y,children:[y,w?"*":""]})]}),j>0&&(0,n.jsx)("span",{className:"flex-shrink-0 px-1 leading-tight bg-brand-500/15 text-brand-400 rounded-[2px] font-medium",children:j>999?"999+":j})]}),e.createdAt&&(0,n.jsxs)("div",{className:"truncate",style:{color:"var(--card-body-dim)"},children:[(0,n.jsx)("span",{style:{color:"var(--card-accent-amber)"},children:"●"})," ",p("sessions.created",{time:new Date(e.createdAt).toLocaleTimeString(void 0,{hour12:!1})}),x>1&&e.shellId?` \xb7 ${e.shellId}`:""]})]}):(0,n.jsxs)("div",{className:"truncate",style:{color:"var(--card-body-dim)",opacity:.7},children:[(0,n.jsx)("span",{style:{color:"var(--card-accent-red)"},children:"✕"})," disconnected"]}),(0,n.jsxs)("div",{className:"flex items-center min-w-0",children:[(0,n.jsx)("span",{className:"flex-shrink-0",style:{color:"var(--card-accent-green)"},children:"➜"}),(0,n.jsx)("span",{className:"inline-block flex-shrink-0 ml-1.5 w-[7px] h-[14px] animate-pulse",style:{background:"var(--card-accent-green)",opacity:.8}})]})]})]})]})})}let c6=e=>"touch"===e.pointerType?[new c0.il.Delay({value:500,tolerance:8})]:[new c0.il.Distance({value:8})];function c8({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:j=null,notifications:k,sessionStatus:N,agentVersion:S,updateAvailable:C=null,canSelfUpdate:T=!1,onUpdate:R,onRestart:_,carrier:E,workspaces:$=[],onRenameWorkspace:M,onDeleteWorkspace:P,onAddWorkspace:A,fileBus:z,homeDir:L,recentWorkspaces:I=[],shells:D=[],onReorderSession:F}){let{t:B}=(0,se.s)(),O=z||t2.getState(),W=Q(e=>e.connected),K=Q(e=>e.carrier),U=Q(e=>e.busRef),H=s??W,q=E||K||"ws",V=v||U,X=sc(e=>e.notifications),G=sc(e=>e.sessionStatus),J=k||X,Y=N||G,Z=si(e=>e.open),ee=si(e=>e.setContext),et=si(e=>e.setCallbacks),es=tS(e=>e.hiddenHeaderButtons),en=tS(e=>e.mobileDeviceCount),[er,ea]=(0,r.useState)(null),[el,ei]=(0,r.useState)(null),[eo,ec]=(0,r.useState)(null),[ed,eu]=(0,r.useState)(null),[em,ex]=(0,r.useState)(null),[ep,eh]=(0,r.useState)(!1);(0,r.useEffect)(()=>{if(!g)return;let e=e=>{(e.metaKey||e.ctrlKey)&&e.altKey&&!e.shiftKey&&"t"===e.key.toLowerCase()&&(e.preventDefault(),ex({workspaceId:null}))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[g]),(0,r.useEffect)(()=>{g&&(ee({connected:H,remoteAvailable:!!d,codespaceInfo:h,showTheme:!1,theme:"default",busRef:V,hideActions:["remote","files","sites"],tunnelUrl:m,apiKey:x,connectionMode:p,subscribeToPush:y,unsubscribeFromPush:w,notifications:J,agentVersion:S,carrier:q}),et({onRemote:null,onFiles:null,onSelectSite:null,onRefreshSites:null,onCodespace:null,onLogout:c,onThemeChange:null,onStopCodespace:b,onUpdate:R,onRestart:_}))},[g,H,d,h,c,b,R,_,ee,et,V,p,y,w,S,q,m,x,J]);let ef=[...$.map(e=>({key:e.id,id:e.id,name:e.name,path:e.path||null})),{key:"ungrouped",id:null,name:B("workspaces.ungrouped"),path:null,isUnassigned:!0}],eb=t=>e.filter(e=>ty(e)===t),eg=new Set(e.map(e=>e.id)),ev=H&&(nZ(S,"3.0.3")||nQ(S,"3.0.3")||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 ${rE} 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:B("sessions.headerTitle")}),(0,n.jsx)("span",{className:`w-2 h-2 rounded-full flex-shrink-0 ${H?"bg-green-500":"bg-red-500 animate-pulse"}`,title:B(H?"sessions.connected":"sessions.disconnected")}),!H&&f&&(0,n.jsx)("span",{className:"text-red-400 text-xs truncate",children:B("sessions.codespaceStopped")})]}),(0,n.jsxs)("div",{className:"flex items-center gap-1 flex-shrink-0",children:[!es.includes("remote")&&d&&(0,n.jsx)(de,{icon:t3.VA,label:B("menu.remoteDesktop"),onClick:d,disabled:!H}),!es.includes("mobile")&&u&&(0,n.jsx)(de,{icon:t3.wO,label:en>0?B("mobile.deviceRunning",{count:en}):B("mobile.androidDevice"),onClick:u,disabled:!H,className:en>0?"!text-green-400":""}),!es.includes("sites")&&(0,n.jsx)(de,{icon:t3.qz,label:B("menu.sites"),onClick:()=>eh(!0),disabled:!H}),(0,n.jsx)(de,{icon:t3.wB,label:B("menu.title"),onClick:Z})]})]}),(0,n.jsxs)("div",{className:"relative z-10 flex-1 overflow-auto modal-scrollable px-4 pt-4 pb-12",style:{overflowAnchor:"none"},children:[ev&&(0,n.jsx)(n0,{agentVersion:S,webVersion:"3.0.3",updateAvailable:C,canSelfUpdate:T,onUpdate:R,className:"mb-4"}),e.length||$.length?(0,n.jsxs)("div",{className:"space-y-5",children:[ef.map(e=>{let s=eb(e.id);return e.isUnassigned&&!s.length?null:(0,n.jsx)(c9,{section:e,items:s,connected:H,shellCount:D.length,cwdBySession:t,fileBus:O,homeDir:L,sessionStatus:Y,notifications:J,onSelect:a,onNewTerminal:()=>ex({workspaceId:e.id}),onSessionMenu:e=>ea({target:e}),onRenameSession:e=>ec({kind:"session",id:e.id,value:e.name}),onDeleteSession:e=>eu({kind:"session",id:e.id,name:e.name}),onReorderSession:F,onWorkspaceMenu:e.isUnassigned?null:t=>{"rename"===t?ec({kind:"workspace",id:e.id,value:e.name}):eu({kind:"workspace",id:e.id,name:e.name})}},e.key)}),(0,n.jsx)(ds,{icon:(0,n.jsx)(t3.FW,{size:16}),label:B("workspaces.newWorkspace"),onClick:A,disabled:!H})]}):(0,n.jsx)(dt,{onAddWorkspace:A,onOpenRemote:d,recent:I,homeDir:L,connected:H})]}),er&&(0,n.jsx)(dn,{title:er.target.name,onClose:()=>ea(null),actions:[{icon:t3.gH,label:B("sessions.editName"),onClick:()=>ec({kind:"session",id:er.target.id,value:er.target.name})},{icon:t3._V,label:B("menu.terminalBackground"),onClick:()=>ei(er.target)},{icon:t3.TB,danger:!0,label:B("sessions.deleteTitle"),onClick:()=>eu({kind:"session",id:er.target.id,name:er.target.name})}]}),el&&(0,n.jsx)(rS,{sessionId:el.id,title:el.name,busRef:V,onClose:()=>ei(null)}),eo&&(0,n.jsx)(rv,{title:B("session"===eo.kind?"sessions.editName":"workspaces.rename"),value:eo.value,onChange:e=>ec({...eo,value:e}),onSubmit:()=>{let e=eo?.value?.trim();e&&("session"===eo.kind?o?.(eo.id,e):M?.(eo.id,e)),ec(null)},onClose:()=>ec(null)}),(0,n.jsx)(t9.A,{isOpen:!!ed,onClose:()=>eu(null),onConfirm:()=>{ed?.kind==="session"?i?.(ed.id):P?.(ed.id),eu(null)},title:B(ed?.kind==="session"?"sessions.deleteTitle":"workspaces.deleteTitle"),message:ed?.kind==="session"?B("sessions.deleteMessage",{name:ed?.name||""}):B("workspaces.deleteMessage",{name:ed?.name||""})}),em&&(0,n.jsx)(rg,{onClose:()=>ex(null),onCreate:(e,t,s,n,r,a)=>{l?.(e,em.workspaceId,t,r||null,s,n,a),ex(null)},shells:D,busRef:V,onResumeAgentSession:j,onSelectSession:a,liveSessionIds:eg,connected:H,workspacePath:$.find(e=>e.id===em.workspaceId)?.path||null,workspaceName:$.find(e=>e.id===em.workspaceId)?.name||"",fileBus:O,homeDir:L,suggestName:`${B("terminal.defaultName")} ${eb(em.workspaceId).length+1}`}),(0,n.jsx)(nG,{tunnelUrl:m,apiKey:x,busRef:V,isOpen:ep,onClose:()=>eh(!1)})]})}function c9({section:e,items:t,connected:s,cwdBySession:a={},fileBus:l,homeDir:i,sessionStatus:o,notifications:c,shellCount:d=1,onSelect:u,onNewTerminal:m,onSessionMenu:x,onWorkspaceMenu:p,onRenameSession:h,onDeleteSession:f,onReorderSession:b}){let[g,v]=(0,r.useState)(null);(0,r.useEffect)(()=>{if(!g)return;let e=setTimeout(()=>v(null),1500);return()=>clearTimeout(e)},[g]);let y=(0,r.useMemo)(()=>{if(!g||t.length!==g.length||t.some(e=>!g.includes(e.id)))return t;let e=new Map(g.map((e,t)=>[e,t]));return[...t].sort((t,s)=>(e.get(t.id)??1/0)-(e.get(s.id)??1/0))},[t,g]),{t:w}=(0,se.s)(),j=e.path||t.find(e=>e.workspacePath)?.workspacePath,{branch:k}=aC(j,l),[N,S]=(0,r.useState)(!1);return(0,n.jsxs)("section",{children:[(0,n.jsxs)("div",{className:"flex items-center gap-1 pb-2",children:[(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),S(e=>!e)},className:"flex-1 min-w-0 flex items-center gap-2 py-1 text-left",children:[(0,n.jsx)(t3.c_,{size:14,className:`flex-shrink-0 text-text-subtle transition-transform duration-150 ${N?"":"rotate-90"}`}),(0,n.jsx)(t3.vd,{size:17,className:"text-text flex-shrink-0"}),(0,n.jsxs)("span",{className:"flex-1 min-w-0",children:[(0,n.jsx)("span",{className:"block text-[13px] font-medium text-text truncate",title:e.name,children:e.name}),j&&(0,n.jsx)("span",{className:"block text-[11px] text-text-subtle truncate",title:j,children:n2(j,i)})]}),N&&t.length>0&&(0,n.jsx)("span",{className:"flex-shrink-0 text-[11px] text-text-subtle",children:t.length})]}),(0,n.jsx)(c7,{icon:t3.FW,label:w("terminal.newTerminal"),onClick:m,disabled:!s}),p&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(c7,{icon:t3.gH,label:w("workspaces.rename"),onClick:()=>p("rename")}),(0,n.jsx)(c7,{icon:t3.TB,label:w("workspaces.delete"),danger:!0,onClick:()=>p("delete")})]})]}),!N&&(0,n.jsx)(cQ.XU,{sensors:[c0.AN.configure({activationConstraints:c6})],onDragEnd:e=>{if(!s)return;let t=y.map(e=>e.id),n=(0,c1.Cy)(t,e);n&&(v(n),b?.(n))},children:(0,n.jsxs)("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-3 sm:gap-4",children:[y.map((e,t)=>(0,n.jsx)(c4,{session:e,index:t,status:o[e.id],hasNotification:!!c[e.id],connected:s,cwd:a[e.id]||null,fileBus:l,homeDir:i,shellCount:d,onSelect:u,onLongPress:x,onRename:h,onDelete:f},e.id)),(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),m()},disabled:!s,className:`min-h-[164px] rounded-xl p-3 items-center justify-center gap-1.5 text-sm border border-dashed border-brand-500/40 bg-brand-500/5 text-text-muted transition-all duration-150 ${t.length?"hidden sm:flex":"flex"} ${s?"hover:border-brand-500 hover:text-brand-500 hover:bg-brand-500/10 hover:-translate-y-1":"opacity-50 cursor-not-allowed"}`,title:w("workspaces.addTerminal"),children:[(0,n.jsx)(t3.FW,{className:"text-brand-500",size:16})," ",(0,n.jsx)("span",{className:"text-brand-500",children:w("terminal.newTerminal")})]})]})})]})}function c7({icon:e,label:t,onClick:s,danger:r,disabled:a}){return(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),s()},disabled:a,title:t,className:`p-2 flex-shrink-0 transition-colors disabled:opacity-30 ${r?"text-text-subtle active:text-red-500":"text-text-subtle active:text-text"}`,children:(0,n.jsx)(e,{size:17})})}function de({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 dt({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:n2(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})]})]})]})]})}function ds({icon:e,label:t,onClick:s,disabled:r}){return(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),s?.()},disabled:r,className:"w-full flex items-center justify-center gap-1.5 px-1 py-2 text-[13px] font-medium uppercase text-brand-500 active:opacity-60 disabled:opacity-40 transition-opacity",children:[e,t]})}function dn({title:e,actions:t,onClose:s}){return(0,n.jsxs)("div",{className:"fixed inset-0 z-[80] flex items-end",onClick:s,children:[(0,n.jsx)("div",{className:"absolute inset-0 bg-black/60 animate-in fade-in duration-150"}),(0,n.jsxs)("div",{className:"relative w-full bg-surface rounded-t-brand-lg pb-[max(0.5rem,env(safe-area-inset-bottom))] animate-in slide-in-from-bottom duration-200",onClick:e=>e.stopPropagation(),children:[(0,n.jsx)("div",{className:"px-4 py-3 text-[12px] text-text-muted truncate border-b border-border-subtle",children:e}),t.map(({icon:e,label:t,onClick:r,danger:a})=>(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),s(),r()},className:`w-full flex items-center gap-3 px-4 py-3.5 text-[14px] active:bg-surface-2 ${a?"text-red-500":"text-text"}`,children:[(0,n.jsx)(e,{size:17})," ",t]},t))]})]})}let dr=(e,t,s)=>Math.max(t,Math.min(s,e));function da({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 dl(e,t){return{x:Math.min(0,e.width-t.width),y:Math.min(0,e.height-t.height)}}function di(e,t){return{x:dr(e.x,t.x,0),y:dr(e.y,t.y,0)}}function dc({prevZoom:e,prevPan:t,focal:s,nextZoomRaw:n,maxZoom:r,containerSize:a,displaySizeAt:l}){let i=dr(n,1,r),o=i/e,c=dl(a,l(i));return{zoom:i,pan:di({x:s.x-(s.x-t.x)*o,y:s.y-(s.y-t.y)*o},c)}}function dd({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 du=!!window.chrome,dm=e=>new Blob([e]),dx=(e,t)=>()=>{e.current[t]=null},dp=null,dh=0,df=new Map;async function db(e){if("u"<typeof createImageBitmap)return null;if(du)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 dg={fps:0,latency:0,tilesPerSec:0,bandwidthMBps:0,webrtcTiles:0,wsTiles:0,webrtcPercent:0};function dv({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 dy({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:j,onPointerDown:k,onPointerMove:N,onPointerUp:S,onWheel:C,onContextMenu:T,onDoubleClick:R,onTouchStart:_,onTouchMove:E,onTouchEnd:$,onKeyDown:M,screenLocked:A,unlockReady:z,unlockResult:L,onUnlockSubmit:I}){let D=l*s,F="mouse"===g,{t:B}=(0,se.s)(),[O,W]=(0,r.useState)(!1),[K,U]=(0,r.useState)(""),[H,q]=(0,r.useState)(!1),[V,X]=(0,r.useState)(!1);(0,r.useEffect)(()=>{A||(U(""),q(!1))},[A]),(0,r.useEffect)(()=>{L&&q(!1)},[L]);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&&O?"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(!O)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)}},[O]),(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:_,onTouchMove:E,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)),k?.(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"}),B("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)(dv,{list:y,activeIndex:w,onSelect:j}),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:B("remote.lockTitle")}),(0,n.jsx)("p",{className:"text-xs text-center",style:{color:"rgba(220,225,245,0.7)"},children:B("remote.lockDesc")})]}),(0,n.jsxs)("div",{className:"relative",children:[(0,n.jsx)("input",{type:V?"text":"password",value:K,autoFocus:!0,disabled:H,onChange:e=>U(e.target.value),onKeyDown:e=>{"Enter"===e.key&&K&&!H&&(q(!0),I?.(K))},placeholder:B("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||H,onClick:()=>{q(!0),I?.(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:B(H?"remote.unlocking":"remote.unlock")}),L&&!L.ok&&(0,n.jsx)("p",{className:"mt-3 text-xs text-center text-red-300",children:B("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:B("remote.lockTitle")}),(0,n.jsx)("p",{className:"text-xs",style:{color:"rgba(220,225,245,0.85)"},children:B("remote.lockGrantDesc")})]})})})]})}var dw=s(80186);let dj=(e,...t)=>{(0,t7.e)(),e?.(...t)};function dk({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 dN({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:j,onToggleTextPanel:k,onToggleHelp:N,onToggleDebug:S,debugOn:C,onEmitKey:T,onTextInputChange:R,onTextInputFocus:_,onTextInputBlur:E,onTextInputKeyDown:$,onDirectInputChange:M,onSendText:A,onClose:z,onDesktopSwitch:L,controlsHidden:I,onToggleControlsHidden:D,tallLandscape:F}){let B,O,W,K,{t:U,locale:H}=(0,se.s)(),q=(0,r.useRef)(null),[V]=ni(H),[X,G]=(0,r.useState)(!1),J=nd({lang:na(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(),dj(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=np("remoteDesktop.bottomKeys",P.ij,P.D5,"flat"),el=np("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)(dk,{onClick:()=>dj(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)(dk,{onClick:()=>dj(L,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)(dk,{onClick:()=>dj(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||I?"":"landscape:h-full landscape:justify-end"} ${I?"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:_,onBlur:E,"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 ${I||F?"hidden":"hidden landscape:flex"}`,children:(0,n.jsx)(dk,{onClick:()=>{(0,t7.e)(),D?.(!0)},title:U("remote.hideControls"),children:(0,n.jsx)(t3.X_,{size:14})})}),(0,n.jsxs)("div",{className:I?"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)(nn,{value:p,store:s4,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:_,onKeyDown:t=>{"mouse"===d&&"Enter"===t.key&&!t.shiftKey&&(t.preventDefault(),e&&Y())},placeholder:"mouse"===d?U("remoteControls.enterToSend"):U("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:U("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:U("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?U("voice.denied"):U("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)(dw.A,{variant:"primary",size:"sm",className:"!px-2.5 shrink-0",onMouseDown:e=>e.preventDefault(),onClick:Y,disabled:!e,children:p.trim()?U("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:U("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)(dk,{onClick:()=>dj(z),title:U("remote.back"),pinned:!0,className:"landscape:hidden",children:(0,n.jsx)(t3.JG,{size:16})}),s&&a?(0,n.jsxs)(dk,{onClick:()=>dj(l),className:"!text-red-500 landscape:hidden",title:U("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)(dk,{onClick:()=>dj(g),disabled:!e,className:"text-text landscape:hidden",title:U("remote.resetZoom"),children:[Math.round(100*t),"%"]}),(0,n.jsx)(dk,{onClick:()=>dj(v),disabled:!e,title:U("remote.refresh"),className:"landscape:hidden",children:(0,n.jsx)(t3.e9,{size:14})}),eo("rectangleSelect")&&(0,n.jsx)(dk,{onClick:()=>dj(y),disabled:!e,active:i,title:U("remote.rectangleSelection"),className:"landscape:hidden",children:"□"}),eo("pointerModeToggle")&&(0,n.jsx)(dk,{onClick:()=>dj(m),disabled:!e,active:"trackpad"===o,title:"trackpad"===o?U("remoteControls.trackpadMode"):U("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)(dk,{onClick:()=>dj(u),disabled:!e,active:c,title:U("remote.handMode"),className:"landscape:hidden",children:(0,n.jsx)(t3.Ud,{size:14})}),eo("keyboardToggle")&&(0,n.jsx)(dk,{onClick:()=>dj(j),disabled:!e,active:f,title:U("remote.toggleKeyboard"),className:"landscape:hidden",children:(0,n.jsx)(t3.s3,{size:14})}),eo("textPanel")&&(0,n.jsx)(dk,{onClick:()=>dj(k),disabled:!e,active:b,title:U("remote.textBatchInput"),className:"landscape:hidden",children:"Aa"}),eo("help")&&(0,n.jsx)(dk,{onClick:()=>dj(N),title:U("remote.help"),className:"landscape:hidden",children:(0,n.jsx)(t3.mN,{size:14})})]}),(0,n.jsx)(dk,{onClick:()=>{(0,t7.e)(),ee(e=>!e)},active:Q,pinned:!0,className:"landscape:hidden shrink-0",title:U("remote.extraKeys"),children:Q?(0,n.jsx)(t3.X,{size:16}):(0,n.jsx)(t3.a4,{size:16})})]}),eo("modifierRow")&&(B=ea.keys.filter(e=>e.id!==P.Ic),O=P.ij.find(e=>e.id===P.Ic),W=(0,n.jsx)(dk,{onClick:()=>{(0,t7.e)(),ee(e=>!e)},active:Q,pinned:!0,title:U("remote.extraKeys"),children:Q?(0,n.jsx)(t3.X,{size:16}):(0,n.jsx)(t3.a4,{size:16})}),K=O?ed(O,"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:B.map((e,t)=>ed(e,t))}),K]}),(0,n.jsxs)("div",{className:`${Z} hidden ${F?"landscape:flex":""}`,children:[B.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:[B.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:[B.slice(5).map((e,t)=>ed(e,t)),K]})]})]}))]}),(0,n.jsxs)("div",{className:`flex-col gap-1.5 p-1.5 ${I?"hidden landscape:flex":"hidden"}`,children:[(0,n.jsx)(dk,{onClick:()=>{(0,t7.e)(),D?.(!1)},title:U("remote.showControls"),children:(0,n.jsx)(t3.kU,{size:16})}),(0,n.jsx)(dk,{onClick:()=>dj(j),disabled:!e,active:f,title:U("remote.toggleKeyboard"),children:(0,n.jsx)(t3.s3,{size:16})})]}),(0,n.jsx)(nv,{isOpen:et,onClose:()=>es(!1),title:U("remote.customizeRemoteKeys"),tabs:[{id:"bottom",label:U("remoteControls.bottomRow"),hook:ea,excludeIds:[P.Ic]},{id:"extra",label:U("remoteControls.extraPanel"),hook:el}]}),(0,n.jsx)(s9,{isOpen:X,store:s4,onSelect:e=>{R(e),q.current?.focus()},onClose:()=>G(!1)})]})}let dS="bg-surface-2 hover:bg-surface-3 text-text",dC="bg-surface-2 hover:bg-surface-3 text-text-muted hover:text-text",dT="bg-brand-500 text-white";function dR({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 d_({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)(dR,{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)(dR,{onClick:c,disabled:!e,title:f("remote.refresh"),className:dC,children:(0,n.jsx)(t3.e9,{size:16})}),(0,n.jsxs)(dR,{onClick:d,disabled:!e,title:f("remote.resetZoom"),className:`text-[10px] font-semibold ${dS}`,children:[Math.round(100*t),"%"]}),i("pointerModeToggle")&&(0,n.jsx)(dR,{onClick:u,disabled:!e,title:f("trackpad"===s?"remoteControls.trackpadMode":"remoteControls.directMode"),className:`text-base leading-none ${"trackpad"===s?dT:dS}`,children:"\uD83D\uDDB1️"}),i("handMode")&&"trackpad"===s&&(0,n.jsx)(dR,{onClick:m,disabled:!e,title:f("remote.handMode"),className:r?dT:dS,children:(0,n.jsx)(t3.Ud,{size:16})}),i("keyboardToggle")&&(0,n.jsx)(dR,{onClick:x,disabled:!e,title:f("remote.toggleKeyboard"),className:a?dT:dC,children:(0,n.jsx)(t3.s3,{size:16})}),i("help")&&(0,n.jsx)(dR,{onClick:p,title:f("remote.help"),className:dC,children:(0,n.jsx)(t3.mN,{size:16})}),i("rectangleSelect")&&(0,n.jsx)(dR,{onClick:h,disabled:!e,title:f("remote.rectangleSelection"),className:l?dT:dS,children:"□"})]})}function dE({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 d$({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 dM({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 dP({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]=nx("remoteDesktop.showTextPanel",!0),[v,y]=nx("remoteDesktop.keyboard",!1),[w,j]=nx("remoteDesktop.controlsHidden",!1),[k,N]=nx("remoteDesktop.pointerMode",P.eR.pointerMode),[S,C]=nx("remoteDesktop.handMode",!1),T=nm(),R=P.eR.pcModeControls,[_,E]=(0,r.useState)(!1);(0,r.useEffect)(()=>{let e=window.matchMedia("(orientation: landscape)"),t=()=>E(e.matches);return t(),e.addEventListener?.("change",t),()=>e.removeEventListener?.("change",t)},[]);let $=_&&Math.min(window.screen.width,window.screen.height)>=700;(0,r.useEffect)(()=>{"mouse"===T&&"direct"!==k&&N("direct")},[T,k,N]);let{stats:M,trackTilesReceived:A,resetStats:z}=function(){let[e,t]=(0,r.useState)(dg),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(dg)},[])}}(),[L,I]=(0,r.useState)(P.eR.debug?.panel??!1),[D,F]=(0,r.useState)(!1),B=P.eR.enableWebRTC?"rtc":"ws",O=(0,r.useCallback)(()=>{let e={mode:B,...M,ts:new Date().toISOString()};navigator.clipboard?.writeText(JSON.stringify(e,null,2)).catch(()=>{})},[M,B]),W=(0,r.useRef)(M);(0,r.useEffect)(()=>{W.current=M},[M]),(0,r.useEffect)(()=>{(0,g.c)("remote",`[stats] interval started, mode=${B}`);let e=setInterval(()=>{(0,g.c)("remote",`[stats][${B}]`,JSON.stringify(W.current))},5e3);return()=>{(0,g.c)("remote","[stats] interval stopped"),clearInterval(e)}},[B]);let{streaming:K,emitRequestScreenWithHashes:U,emitMousePress:H,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:U,emitMousePress:H,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:ej,handleCanvasDimensions:ek,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:dr(e.x/t*100,0,100),percentY:dr(e.y/s*100,0,100)}}({canvasPoint:da({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=dl(n,h(s));l(t=>{if(!e||s<=1)return di(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 di({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=di(e,dl({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 j=(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:j}}(),{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,j]=(0,r.useState)(!1),k=(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}),_=(0,r.useRef)(0),E=(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}),L=(0,r.useRef)(0),I=(0,r.useRef)(null),[D,F]=(0,r.useState)({x:0,y:0}),B=(0,r.useRef)(0),O=(0,r.useRef)(0),W=(0,r.useRef)(null),K=(0,r.useRef)({time:0,distance:0,centerX:0,centerY:0}),U=(0,r.useRef)(!1),H=(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=dr(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:_.current,lastPos:E.current,x:e,y:t,cfg:P.eR});return _.current=s,E.current={x:e,y:t},n},[]),ed=(0,r.useCallback)(()=>{I.current&&(cancelAnimationFrame(I.current),I.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,I.current=requestAnimationFrame(t)};I.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=dd({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=dd({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:dr(e.x/t.width*100,0,100),percentY:dr(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:j,gestureLockRef:W,gestureStartRef:K,multiTouchLatchRef:U,twoFingerMaxMovedRef:H,touchOutsideRef:q,longPressTriggeredRef:T,touchStartPosRef:R,edgeScrollAccumRef:A,velocityRef:z,lastTouchTimeRef:L,touchStartTimeRef:B,touchTotalMoveRef:O,handLongPressTimerRef:V,handHoldingRef:X,setHandHolding:J,scrollLongPressTimerRef:Y,scrollLockRef:Z,setScrollLock:ee,mouseDownButtonRef:et,wheelAccumRef:es,wheelActiveRef:en,wheelEndTimerRef:er,wheelLastBoostRef:ea,zoomGestureTimeoutRef:k,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=dr(t+o*P.eR.wheelZoomStep,1,4);return s===t?t:(e.setCanvasPan(n=>dc({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=dd({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&&(U.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:dr(t.x+c,0,r.width-1),y:dr(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:dr(t.x+c,0,r.width-1),y:dr(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=dl(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 di({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=>dc({prevZoom:e.canvasZoom,prevPan:t,focal:r,nextZoomRaw:a,maxZoom:4,containerSize:n,displaySizeAt:e.displaySizeAt}).pan),e.setCanvasZoom(dr(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=da({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=dl(n,r),l=di({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:dr((t.width/2-i.x)/n,0,e.width-1),y:dr((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:k,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:e_,selectionMode:eE,selectionStart:e$,selectionRect:eM,dragMode:eP,isDragging:eA,setIsDragging:ez,setDragMode:eL,toggleModifierKey:eI,toggleSelectionMode:eD,handleTextInputFocus:eF,handleCanvasKeyPress:eB,sendTextInput:eO,handleSelection:eW,handleModifiedTextInput:eK,handleDirectInputChange:eU,emitKeyWithActiveModifiers:eH}=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 j=(0,r.useCallback)(e=>{d(t=>({...t,[e]:!t[e]})),n&&o.current&&o.current.focus()},[n]),k=(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]),_=(0,r.useCallback)(e=>T("down",e),[T]),E=(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=s4(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]),L=(0,r.useRef)(""),I=(0,r.useRef)(null),D=(0,r.useCallback)((t,n)=>{n&&t&&e?.emitTypeText&&(L.current+=t,s(""),I.current&&clearTimeout(I.current),I.current=setTimeout(()=>{let t=L.current;L.current="",I.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]),B=(0,r.useCallback)(e=>{e&&(F("backspace"),n&&o.current&&l&&o.current.focus())},[n,l,F]),O=(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]),U=(0,r.useCallback)((e,t)=>{t&&(F("enter"),e&&e.preventDefault(),n&&o.current&&l&&o.current.focus())},[n,l,F]),H=(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:j,toggleSelectionMode:k,toggleDragMode:N,handleTextInputFocus:S,handleCanvasKeyPress:C,startScrollUp:R,startScrollDown:_,startScrollLeft:E,startScrollRight:$,stopScrolling:M,sendTextInput:z,sendBackspace:B,sendArrowKey:O,sendEscKey:W,sendTabKey:K,sendEnterKey:U,handleSelection:H,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:k,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):eH(e))},[K,o,J,eH]),eY=(0,r.useCallback)(()=>{C(e=>{let t=!e;return t?(eE&&eD(),ey()):ew(),t})},[C,eE,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]),j=(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]),k=(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=dx(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(dm(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=dx(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(dm(e.imageBuffer)).then(l).catch(()=>{if(s.cancelled)return;let t=new Image,n=URL.createObjectURL(dm(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(dm(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===dp)return null;if(dp)return dp;try{return(dp=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=df.get(s);if(!a){if(e)for(let t of e)t.bitmap?.close?.();return}clearTimeout(a.timer),df.delete(s),a.resolve(r?null:{tiles:e,timestamp:t,hasBitmap:n})},dp}catch{return dp=!1,null}}();if(!a)return;let l=r.byteLength,i=++dh;new Promise(e=>{let s=setTimeout(()=>{df.has(i)&&(df.delete(i),e(null))},P.eR.tileLoadTimeout),n=P.eR.decodeQueueCap;for(;df.size>=n;){let e=df.keys().next().value,t=df.get(e);if(!t)break;clearTimeout(t.timer),df.delete(e),t.resolve(null)}df.set(i,{resolve:e,timer:s}),a.postMessage({buffer:r,id:i,v:t},[r])}).then(e=>{e&&(2===t&&(m.current=!1),k({tiles:e.tiles,timestamp:e.timestamp,hasBitmap:e.hasBitmap,bytes:l,transport:n}))})},[k]),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()},[]),_=(0,r.useCallback)(e=>{e.tileCount&&l(e.tileCount)},[]),E=(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),dp&&!1!==dp)try{dp.terminate()}catch{}for(let e of(dp=null,df.values()))try{e.resolve(null)}catch{}df.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:j,handleTilesData:k,handleTilesBinary:S,handleTilesBinaryV2:C,handleTilesMeta:T,startStreamingWithTiles:R,handleScreenDimensions:_,cleanupTiles:$,requestScreenWithHashes:E}}(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),[j,k]=(0,r.useState)([]),[N,S]=(0,r.useState)(0),[C,T]=(0,r.useState)(null),R=(0,r.useRef)(null),{renderedTilesRef:_,handleFullScreenData:E,handleTilesData:$,handleTilesBinary:M,handleTilesBinaryV2:A,handleTilesMeta:z,handleScreenDimensions:L,cleanupTiles:I,requestScreenWithHashes:D}=d;return(0,r.useEffect)(()=>{let s=e?.current;if(!s||!t)return;I();let n=e=>{L(e),l(e,_)},r=e=>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),j=e=>{h(e," v2"),A(e)},N=()=>{I(),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})=>{k(Array.isArray(e)?e:[]),"number"==typeof t&&S(t)},F=e=>{I(),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",j),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 B=e=>T(e?.shape??null);return s.on("cursor-shape",B),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",j),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",B),I(),o.current&&clearTimeout(o.current)}},[t]),(0,r.useEffect)(()=>{if(!s||!t||!e?.current)return;let n=setInterval(()=>{0===_.current.size?e.current.emit("request-screen-with-hashes",{tileHashes:[]}):D()},P.eR.hashRequestInterval);return()=>clearInterval(n)},[s,t,e,D,_]),(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.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,_]),(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:j,activeMonitorIndex:N,cursorShape:C}}({busRef:t,connected:l,streaming:K,canvasRef:er,serverDimensionsRef:eN,handleCanvasDimensions:ek,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=>{ej(t,e,{streaming:K,selectionMode:eE,selectionStart:e$,dragMode:eP,isDragging:eA,setIsDragging:ez,setDragMode:eL,isMobile:e.includes("touch"),pointerMode:k,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)(d_,{streaming:K,canvasZoom:el,pointerMode:k,handMode:S,keyboardOn:v,selectionMode:eE,show:e=>"mouse"!==T||R?.[e],onBack:en,onRefresh:()=>{K&&U([])},onResetZoom:ef,onTogglePointerMode:eS,onToggleHandMode:eY,onToggleKeyboard:eV,onShowHelp:()=>u(!0),onToggleSelection:tt}),l?(0,n.jsx)(dy,{canvasRef:er,canvasContainerRef:ea,canvasZoom:el,canvasPan:ei,fitScale:eo,streaming:K,hasFrame:eZ.hasFrame,selectionRect:eM,clickIndicator:eu,pointerMode:k,selectionMode:eE,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=>eB(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)(cJ.A,{size:"sm"}),c("remote.connecting")]})]})]})]}),(0,n.jsx)(dN,{streaming:K,canvasZoom:el,clipboardNew:e3,clipboardText:e5,onOpenClipboard:()=>{e4(!1),h(!0)},onDesktopSwitch:et,selectionMode:eE,pointerMode:k,handMode:S,inputMode:T,onToggleHandMode:eY,onTogglePointerMode:eS,modifierKeys:e_,textInputValue:eC,textInputRef:eR,keyboardOn:v,showTextPanel:f,onResetZoom:ef,onRefresh:()=>K&&U([]),onToggleSelection:tt,onToggleModifier:eI,onToggleKeyboard:eV,onToggleTextPanel:eX,controlsHidden:w,onToggleControlsHidden:j,tallLandscape:$,onToggleHelp:()=>u(!0),onEmitKey:eJ,onTextInputChange:eT,onTextInputFocus:eF,onTextInputBlur:eG,onTextInputKeyDown:e=>eK(e,K,v),onDirectInputChange:e=>eU(e,K),onSendText:eO,onClose:en,onToggleDebug:()=>I(e=>!e),debugOn:L}),L&&(0,n.jsx)(d$,{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:B,onReset:z,onCopy:O,onClose:()=>I(!1)}),d&&(0,n.jsx)(dE,{inputMode:T,pointerMode:k,onClose:()=>{u(!1),v&&eR.current?.focus()}}),p&&(0,n.jsx)(dM,{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 dA={"9remote.cc":"sites.9remote.cc","dev.9remote.cc":"sites-dev.9remote.cc",localhost:"sites.localhost","127.0.0.1":"sites.localhost","::1":"sites.localhost"},dz=function(){let e=window.location;if(!e)return"https://sites.9remote.cc";let{hostname:t,protocol:s,port:n}=e,r=dA[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)}(),dL="site-nav",dI="site-error",dD=null,dF=!1,dB=new Map;function dO(e){if(!e||"string"!=typeof e.reqId)return;let t=dB.get(e.reqId);if(e.error){if(!t?.resolve)return;clearTimeout(t.timer),dB.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=dB.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),dB.delete(e),{reqId:e,status:t.status,headers:t.headers,bodyB64:s}}(e.reqId);s&&t.resolve&&t.resolve(s)}function dW(e){var t;if("string"!=typeof(t=e.origin)||""===t||"null"===t||t!==dz)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(()=>{dB.delete(t),s({reqId:t,error:"timeout"})},75e3),dB.set(t,n),dD?.emit?.("site:httpRequest",e,()=>{})})})(s.payload).then(t=>{try{e.source?.postMessage({type:"site:reply",id:s.id,payload:t},dz)}catch{}});if("site:nav"===s.type)return void window.dispatchEvent(new CustomEvent(dL,{detail:{port:s.port,path:s.path}}));if("site:ready"!==s.type){if("site:swBlocked"===s.type)return void window.dispatchEvent(new CustomEvent(dI,{detail:{message:"service-worker-blocked"}}));if("site-error"===s.type)return void window.dispatchEvent(new CustomEvent(dI,{detail:{message:s.message,port:s.port}}))}}}async function dK(e){e&&(dD=e,dD.off?.("site:httpChunk",dO),dD.on?.("site:httpChunk",dO)),dF||(dF=!0,window.addEventListener("message",dW))}function dU({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(nU()),x(nH()),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 j=o||[],k=new Set(j.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(!k.has(e)&&!d.includes(e)){let t=[...d,e];u(t),nK(nB,t)}h(""),S(e)}},T=()=>{if(null==f)return;let e=g.trim(),t={...m};e?t[f]=e:delete t[f],x(t),nK(nO,t),b(null),v("")},R=d.filter(e=>!k.has(e));return(0,rw.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)(dH,{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)),nK(nB,s))},onOpen:()=>S(e),t:i},`saved-${e}`)),j.map(e=>(0,n.jsx)(dH,{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===j.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:j.length>0?i("sites.foundCount",{n:j.length,suffix:j.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 dH({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 dq=0,dV=(e,t)=>{let s={port:e,path:t||"/"};return{key:`site-${++dq}`,port:e,path:s.path,srcTick:0,hist:[s],histIdx:0}},dX=e=>e?`localhost:${e.port}${e.path||"/"}`:"",dG={"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 dJ({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=dV(s,a);return{tabs:[e],activeKey:e.key,address:dX(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]),j=(0,r.useCallback)(t=>{y.current.delete(t),e?.current?.emit?.("endProxySession",t)},[e]);(0,r.useEffect)(()=>{dK(e?.current)},[e]),(0,r.useEffect)(()=>{let e=e=>{let{message:t,port:s}=e.detail||{};t&&(u(!1),h({message:i(dG[t]||"sites.errorGeneric",{port:s})}))};return window.addEventListener(dI,e),()=>window.removeEventListener(dI,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(dL,e),()=>window.removeEventListener(dL,e)},[]),(0,r.useEffect)(()=>{let e=new Set(f.map(e=>e.port));for(let t of[...y.current])e.has(t)||j(t)},[f,j]),(0,r.useEffect)(()=>()=>{for(let t of y.current)e?.current?.emit?.("endProxySession",t);y.current.clear()},[e]);let k=(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=dV(e,t);return{tabs:[...s.tabs,n],activeKey:n.key,address:dX(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:dX(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:dX(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:dX(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&&k(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))&&k(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||!dz)return null;let r=s?`?r=${s}`:"";return`${dz}/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)(dU,{isOpen:m,onClose:()=>x(!1),onOpenSite:e=>k(e),busRef:e,connected:t})]})}function dY({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":tn[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:ly(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 dZ({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)(""),[j,k]=(0,r.useState)(null),[N,S]=(0,r.useState)(!1),[C,T]=(0,r.useState)("file"),[R,_]=(0,r.useState)(""),[E,$]=(0,r.useState)({isOpen:!1}),[M,P]=(0,r.useState)(null),[A,z]=(0,r.useState)(!1),[L,I]=(0,r.useState)({}),[D,F]=(0,r.useState)(!1),[B,O]=(0,r.useState)(""),[W,K]=(0,r.useState)([]),[U,H]=(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),I({});return}let t=await ll(s,e);z(t.hasGit);let n=t.map;I(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 lT(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(O(t),q.current&&clearTimeout(q.current),!t||t.length<2){K([]),H(!1);return}H(!0),q.current=setTimeout(async()=>{let n=await s.searchFiles(e,t);n.success&&K(n.files),H(!1)},300)},[e,s]),ei=(0,r.useCallback)(()=>{F(!1),O(""),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=()=>k(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),_("")):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 lI(s,e,n,"folder"===t.type);r?.success&&(X(e),window.dispatchEvent(new CustomEvent(tu)))},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)(lP,{query:B,loading:U,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)(lM,{label:`${x("files.copying")} ${J.done+1}/${J.total}: ${J.current}`,ratio:J.ratio}),Q&&(0,n.jsx)(lM,{label:`${x("files.downloading")}: ${Q.name}`,ratio:Q.ratio}),D&&B.length>=2?(0,n.jsx)("div",{className:"flex-1 min-h-0 overflow-auto",children:U?(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)(dY,{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)=>{k({file:e,x:t.x,y:t.y})},gitStatusMap:L,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})}),j&&(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(j.y,window.innerHeight-160)},children:[(0,n.jsxs)("button",{onClick:()=>{var e;(0,t7.e)(),e=j.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(j.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(j.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(j.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=j.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)(lA,{type:C,name:R,onTypeChange:T,onNameChange:_,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)(lz,{value:M.newName,onChange:e=>P({...M,newName:e}),onSubmit:ed,onClose:()=>P(null)}),(0,n.jsx)(t9.A,{isOpen:E.isOpen,onClose:()=>$({isOpen:!1}),onConfirm:E.onConfirm,title:E.title,message:E.message}),Z&&(0,n.jsx)(lL,{name:Z.name,onResolve:ea})]})}let dQ=[{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"}],d0=[{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 d1({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:dQ.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:d0.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 d2({filePath:e,fileBus:t,onBack:s,line:a,column:l,workspace:i,diffStatus:o,preview:c=!1}){let{t:d}=(0,se.s)(),u=ia(e),m=!!o,x=e.split("/").pop(),p=ii({filePath:m||u?"":e,fileBus:t}),h=io({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,j]=(0,r.useState)(null),[k,N]=(0,r.useState)(!1),S=m||u?null:tt(e),[C,T]=(0,r.useState)(c&&!!S),[R,_]=(0,r.useState)(0),[E,$]=(0,r.useState)(e),[M,P]=(0,r.useState)(!1);E!==e&&($(e),T(c&&!!S)),p.justSaved!==M&&(P(p.justSaved),p.justSaved&&_(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(te(e,e1))return void j("image");N(!0);let s=await t.gitDiff(i,v.file,v.status);N(!1),s?.success&&j(s.diff||"")};(0,r.useEffect)(()=>{if(!o||!i||!e)return;let s=!1,n=setTimeout(async()=>{if(te(e,e1))return void j("image");N(!0);let n=await t.gitDiff(i,e,o);!s&&(N(!1),n?.success&&j(n.diff||""))},0);return()=>{s=!0,clearTimeout(n)}},[o,i,e,t]);let L=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:k,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:k?(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)(),L()},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?te(e,e1)?(0,n.jsx)(iO,{filePath:e,status:o,workspace:i,fileBus:t}):(0,n.jsx)("div",{className:"h-full overflow-auto p-2",children:k?(0,n.jsx)("div",{className:"h-full flex items-center justify-center text-text-muted",children:d("common.loading")}):w?(0,n.jsx)(iF,{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)(il,{filePath:e,fileBus:t}):C&&S?(0,n.jsx)(iL,{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)(iN,{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)(),j(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:te(e,e1)?(0,n.jsx)(iO,{filePath:e,status:v?.status,workspace:i,fileBus:t}):w?(0,n.jsx)(iF,{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)(d1,{viewRef:f}),(0,n.jsx)(ic,{isOpen:h.asking,fileName:x,onSave:h.saveThenLeave,onDiscard:h.discardAndLeave,onCancel:h.cancel})]})}function d5({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:lV(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?lX(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?lX(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 d3({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,j]=(0,r.useState)(""),[k,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(e.ahead??null),M(e.behind??null))}),d(!1)},[e,t]),L=(0,r.useCallback)(async(s=null,n=null)=>{if(g(s),y(n),s&&te(s,e1)){j("image"),N(!0),m(!1);return}m(!0),p("");let r=await t.gitDiff(e,s,n);r.success?(j(r.diff),N(!0)):p(r.error),m(!1)},[e,t]);(0,r.useEffect)(()=>{z()},[z]);let I=(0,r.useCallback)(()=>{if(o("diff"),!k&&h.length>0){let e=h[0];L(e.path,e.status)}},[k,L,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?L(e[0].path,e[0].status):(o("status"),g(null),j(""),N(!1))}}else p(r.error)}})},[t,e,z,L,h,i,l]),B=(0,r.useCallback)(t=>{let s=e.endsWith("/")?`${e}${t}`:`${e}/${t}`;a?.(s)},[e,a]),[O,W]=(0,r.useState)(null),K=(0,r.useCallback)(async e=>{try{await navigator.clipboard.writeText(e)}catch{}},[]),U=(0,r.useCallback)((e,t)=>{t.preventDefault(),t.stopPropagation(),(0,t7.e)(),W({file:e,x:t.clientX,y:t.clientY})},[]),H=(0,r.useCallback)(async s=>{if(!e||!t||!s?.path)return;let n=await lI(t,e,s.path);n?.success&&(window.dispatchEvent(new CustomEvent(tu)),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:lU.ExternalLink,disabled:"D"===t.status,onClick:()=>B(t.path)},{key:"copyPath",label:l("files.copyPath",{defaultValue:"Copy Path"}),icon:lU.Copy,onClick:()=>K(s)},{key:"copyRel",label:l("files.copyRelPath",{defaultValue:"Copy Relative Path"}),icon:lU.FileText,onClick:()=>K(t.path)},{key:"copyName",label:l("files.copyName",{defaultValue:"Copy Filename"}),icon:lU.FileText,onClick:()=>K(t.path.split("/").pop())},{key:"addToGitignore",label:l("git.addToGitignore",{defaultValue:"Add to .gitignore"}),icon:lU.EyeOff,onClick:()=>H(t)},{key:"discard",label:l("git.discardChangesTitle",{defaultValue:"Discard Changes"}),icon:lU.Undo2,danger:!0,onClick:()=>F(t.path,t.status)}]},[e,l,B,K,H,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=>U(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:ly({name:t,path:e.path,type:"file"},18)}),(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),L(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)(),B(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 ${tn[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,_>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:["↑",_]}),$>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():L(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)(),I()},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&&L(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)(),B(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&&te(b,e1)?(0,n.jsx)(iO,{filePath:b,status:v,workspace:e,fileBus:t}):w?(0,n.jsx)(iF,{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)(d5,{workspace:e,fileBus:t,branch:T,changedCount:h.length,onDone:z,onClose:()=>A(!1)}),O&&(0,n.jsx)(lK,{x:O.x,y:O.y,items:q(O.file),onClose:()=>W(null)})]})}let d4=[{id:tf,Icon:t3.sv,label:"Explorer"},{id:tb,Icon:t3.vj,label:"Search"},{id:"scm",Icon:t3.Zr,label:"Source Control"}];function d6({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 d8({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)(d6,{onClick:()=>{(0,t7.e)(10),s?.()},label:"Back",children:(0,n.jsx)(t3.JG,{size:20})}),d4.map(({id:t,Icon:s,label:a})=>(0,n.jsx)(d6,{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)(d6,{active:e===tg,onClick:()=>r(tg),label:"Settings",children:(0,n.jsx)(t3.wB,{size:20})})})]})}function d9({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 d7({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,j]=(0,r.useState)(!1),[k,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),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 k)e+=(t.matches||[]).length;return{files:k.length,matches:e}},[k]),L=(0,r.useCallback)(e=>{E(t=>{let s=new Set(t);return s.has(e)?s.delete(e):s.add(e),s})},[]),I=(0,r.useCallback)(async()=>{if(!a||!e||!t?.replaceInFiles||!k.length)return;let s=k.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,k,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)(d9,{active:c,onClick:()=>d(!c),title:"Match Case",children:"Aa"}),(0,n.jsx)(d9,{active:u,onClick:()=>m(!u),title:"Whole Word",children:"ab"}),(0,n.jsx)(d9,{active:x,onClick:()=>p(!x),title:"Regex",children:".*"}),(0,n.jsx)("span",{className:"flex-1"}),(0,n.jsx)(d9,{active:w,onClick:()=>j(!w),title:"Toggle Replace",children:"↔"}),(0,n.jsx)(d9,{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||!k.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:k.map(e=>{let t=_.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)(),L(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:I,title:"Replace All",message:`Replace ${z.matches} matches in ${z.files} files?`,confirmText:"Replace All",cancelText:"Cancel"})]})}let ue="px-3 my-2 text-[11px] uppercase tracking-wider text-text-muted",ut="flex items-center justify-between px-3 py-2 hover:bg-surface-2";function us({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 un(){let[e,t]=nx(tm,14),[s,r]=nx(tx,!1),[a,l]=nx("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:ue,children:"Editor"}),(0,n.jsxs)("div",{className:ut,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:ut,children:[(0,n.jsx)("span",{className:"text-xs text-text",children:"Word Wrap"}),(0,n.jsx)(us,{value:s,onChange:r})]}),(0,n.jsx)("div",{className:ue,children:"Files"}),(0,n.jsxs)("div",{className:ut,children:[(0,n.jsx)("span",{className:"text-xs text-text",children:"Show Hidden Files"}),(0,n.jsx)(us,{value:a,onChange:l})]}),(0,n.jsx)("div",{className:ue,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={[tf]:"Explorer",[tb]:"Search",scm:"Source Control",[tg]:"Settings"};function ua({activePanel:e,workspace:t,fileBus:s,onOpenFile:r,onSwitchWorkspace:a,activeFile:l}){let i=ur[e]||"",o=e===tf;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 tf:return(0,n.jsx)(lW,{workspace:t,fileBus:s,onOpenFile:r,activeFile:l,onSwitchWorkspace:a});case tb:return(0,n.jsx)(d7,{workspace:t,fileBus:s,onOpenFile:r});case"scm":return(0,n.jsx)(l1,{workspace:t,fileBus:s,onOpenFile:r});case tg:return(0,n.jsx)(un,{});default:return null}}({activePanel:e,workspace:t,fileBus:s,onOpenFile:r,onSwitchWorkspace:a,activeFile:l})})]})}function ul({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=to(e),c=o?tc(e).absPath:e,u=o?`${c.split("/").pop()} (diff)`:c.split("/").pop(),m=o?null:ly({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 ui({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 uo({filePath:e,workspace:t,fileBus:s,isActive:a,onCursorChange:l,onDirtyChange:i,onRegisterSaver:o,previewSeq:c=0}){let{t:d}=(0,se.s)(),u=!to(e)&&!ia(e),m=ii({filePath:u?e:"",fileBus:s}),x=u?tt(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),[j,k]=(0,r.useState)(c);return(g!==e?(v(e),h(!1)):j!==c&&(k(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]),to(e))?(0,n.jsx)(iW,{diffPath:e,workspace:t,fileBus:s}):ia(e)?(0,n.jsx)(il,{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)(iL,{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)(iN,{filePath:e,content:m.content,onTextChanged:m.onTextChanged,onRegisterView:m.register,onSave:m.save,onCursorChange:l})})]})}function uc({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]),j=(0,r.useCallback)(async()=>{!1!==await b.current.get(h)?.()&&(f(null),i?.(h))},[h,i]),k=(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)(ul,{openedFiles:s,activeFile:a,dirtyFiles:x,onActivate:l,onClose:y,onCloseOthers:e=>w(e),onCloseAll:()=>w(null)}),(0,n.jsx)(ui,{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)(uo,{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)(ic,{isOpen:!!h,fileName:h?.split("/").pop(),onSave:j,onDiscard:k,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 ud({gitBranch:e,line:t,column:s,language:r,encoding:a,activeFile:l,sidebarVisible:i,onToggleSidebar:o,bottomVisible:c,onTogglePanel:d}){return(0,n.jsx)(aO,{left:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{onClick:()=>{(0,t7.e)(),o?.()},className:aW,title:i?"Hide Sidebar":"Show Sidebar",children:(0,n.jsx)(t3.Ay,{name:i?"PanelLeftClose":"PanelLeftOpen",size:12})}),l&&(0,n.jsxs)("span",{className:aK,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:aW,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:aK,children:`Ln ${t||1}, Col ${s||1}`}),(0,n.jsx)("span",{className:aK,children:r||"plaintext"}),(0,n.jsx)("span",{className:aK,children:a||"UTF-8"})]})]})})}let uu=sH()?"⌘":"Ctrl+",um=[{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:`${uu}B`},{id:"togglePanel",label:"View: Toggle Terminal Panel",icon:"Terminal",shortcut:`${uu}J`},{id:"closeAll",label:"View: Close All Editors",icon:"X",shortcut:""},{id:"switchWorkspace",label:"Workspaces: Switch Workspace",icon:"Folder",shortcut:""}];function ux({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?um.filter(t=>t.label.toLowerCase().includes(e)):um},[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]),j=(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]),k=(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(),j(u))},[y.length,u,l,j]),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:k,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:()=>j(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:()=>j(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 up({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)(aj,{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 uh({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]=nx("fileExplorer.activityPanel",tf);(0,r.useEffect)(()=>{"git"===h?g("scm"):"files"===h&&g(tf)},[h,g]);let[v,y]=nx("fileExplorer.sidebarVisible",!0),[w,j]=nx("fileExplorer.sidebarWidth",18),[k,N]=nx("fileExplorer.bottomPanelVisible",!1),[S,C]=nx("fileExplorer.bottomPanelHeight",30),T=(0,r.useRef)(null),[R,_]=(0,r.useState)(!1),E=(0,r.useCallback)(e=>{e.preventDefault();let t=T.current;if(!t)return;let s=t.getBoundingClientRect();_(!0);let n=e=>{0===e.buttons?r():j(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="",_(!1)};document.body.style.userSelect="none",document.body.style.cursor="col-resize",window.addEventListener("mousemove",n),window.addEventListener("mouseup",r),window.addEventListener("blur",r)},[j]),[$,M]=(0,r.useState)(l||[]),[P,A]=(0,r.useState)(p||l?.[0]||null),[z,L]=(0,r.useState)({line:1,column:1,language:"",encoding:"UTF-8"}),[I,D]=(0,r.useState)(""),[F,B]=(0,r.useState)({path:null,seq:0}),[O,W]=(0,r.useState)(!1),[K,U]=(0,r.useState)("commands");(0,r.useEffect)(()=>{i?.($,P)},[$,P,i]);let H=(0,r.useCallback)((e,t={})=>{M(t=>[e,...t.filter(t=>t!==e)].slice(0,5)),A(e),t.line&&L(e=>({...e,jumpLine:t.line,jumpColumn:t.column})),t.preview&&B(t=>({path:e,seq:t.seq+1}))},[]);(0,r.useEffect)(()=>{f&&(f.current=H)},[f,H]);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:()=>{U("commands"),W(!0)},onQuickOpen:()=>{U("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)(d8,{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)(ua,{activePanel:b,workspace:e,fileBus:t,onOpenFile:H,onSwitchWorkspace:a,activeFile:P})}),(0,n.jsx)("div",{onMouseDown:E,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)(uc,{workspace:e,fileBus:t,openedFiles:$,activeFile:P,onActivateFile:A,onCloseFile:q,onCloseOthers:V,onCloseAll:X,onOpenFile:H,onEditorStateChange:L,previewRequest:F}),k&&o&&(0,n.jsx)(up,{height:S,onResize:C,onClose:()=>N(!1),bus:o,connected:c,sessions:d,onCreateSession:u,onDeleteSession:m,onRenameSession:x})]})]})]}),(0,n.jsx)(ud,{gitBranch:I,line:z.line,column:z.column,language:z.language,encoding:z.encoding,activeFile:P,sidebarVisible:v,onToggleSidebar:()=>y(e=>!e),bottomVisible:k,onTogglePanel:()=>N(e=>!e)}),O&&(0,n.jsx)(ux,{mode:K,workspace:e,fileBus:t,onClose:()=>W(!1),onOpenFile:H,onSetMode:U,onAction:e=>{W(!1),"toggleSidebar"===e?y(e=>!e):"togglePanel"===e?N(e=>!e):"closeAll"===e?X():"switchWorkspace"===e?a?.():"openExplorer"===e?(g(tf),y(!0)):"openSearch"===e?(g(tb),y(!0)):"openScm"===e?(g("scm"),y(!0)):"openSettings"===e&&(g(tg),y(!0))}})]})}function uf({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:sW.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:sG(e).map(e=>(0,n.jsx)("kbd",{className:sV,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)(cJ.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)(cJ.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:ug,restartingAt:uv,timeoutSec:uy}={installingAt:4,restartingAt:15,timeoutSec:90},uw={starting:"menu.updateStarting",installing:"menu.updateInstalling",restarting:"menu.updateRestarting",done:"menu.updateDone",timeout:"menu.updateTimeout"},uj={starting:"menu.restartStarting",restarting:"menu.restartRestarting",done:"menu.restartDone",timeout:"menu.restartTimeout"};function uk({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>=uy&&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<uv?"starting":"restarting":i<ug?"starting":i<uv?"installing":"restarting":"restarting";let x=l(("restart"===s?uj:uw)[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)(cJ.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/uy*100,95)}%`}})})]})})})}let uN={remote:t3.VA,mobile:t3.wO,sites:t3.qz,notifications:t3.Ir,folder:t3.Bm,note:t3.y8},uS=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 uC(){let e=tS((0,tW.k)(uS));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])}}s(28913);var uT=s(4018);let uR="9remote_nav:",u_=(e,t)=>{if(e&&t)try{localStorage.setItem(uR+e,t)}catch{}};var uE=s(20464);function u$(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 uM(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}}var uP=s(52345);let uA=uP.dI.filter(e=>nr[e.code]);function uz({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:uA.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 uL="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",uI="px-3 py-1.5 rounded-brand text-xs font-medium transition-colors",uD=[{value:"browser",label:"Browser"},{value:"ai",label:"AI Speech To Text"}];function uF({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 uB({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 uO({onClose:e}){let t=tD(),{mode:s,setMode:a,preset:l,setPreset:i,setField:o}=t,{locale:c}=(0,se.s)(),[d,u]=ni(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=uP.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,j=async()=>{(0,t7.e)(),h({busy:!0,msg:"Testing…"});try{let e=tA(tD.getState());await t_(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:tE(e)})}},k=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:tE(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:uD.map(e=>(0,n.jsx)(uF,{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)(uF,{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:uL,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:`${uL} 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:uL,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:uL,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:uL,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:uL,autoComplete:"off"})]})]}),(0,n.jsxs)("div",{className:"flex gap-2",children:[(0,n.jsx)("button",{type:"button",onClick:j,disabled:g,className:`${uI} bg-brand-500 hover:bg-brand-600 text-white disabled:opacity-50`,children:"Test key"}),(0,n.jsx)("button",{type:"button",onClick:k,disabled:g,className:`${uI} bg-surface-2/70 hover:bg-surface-2 text-text disabled:opacity-50`,children:"Test voice"})]}),p&&(0,n.jsx)(uB,{state:p}),f&&(0,n.jsx)(uB,{state:f})]})]})]}),m&&(0,n.jsx)(uz,{isOpen:m,value:d,onSelect:u,onClose:()=>x(!1)})]})}function uW({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)(uO,{onClose:()=>o(!1)})]})}function uK({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:j=null,onUpdate:k,onRestart:N,onOpenBackgroundPicker:S}){let{t:C}=(0,se.s)(),T=nm(),R=sQ(e=>e.open),_=si(e=>e.close),{connectionMode:E="tunnel",agentVersion:$}=si(e=>e.context),M=uC(),P=rF(e=>!1),A=tS(e=>e.webglEnabled),z=tS(e=>e.setWebglEnabled),L=tS(e=>e.fontSize),I=tS(e=>e.setFontSize),D=tS(e=>e.terminalTheme),F=tS(e=>e.setTerminalTheme),B=tS(e=>e.terminalBackgrounds),{theme:O}=(0,ag.D)(),[W,K]=(0,r.useState)(!1),[U,H]=(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),[es,en]=(0,r.useState)(""),er=(0,r.useRef)(null),{loadKeys:ea}=(0,uT.u)(),{setAuth:el}=(0,l.F)();ea();let ei=(0,l.F)().getAuth()?.apiKey;(0,r.useCallback)(async e=>{if(e&&e!==ei){if((0,et.PF)(e))return void en(C("login.legacyKeyError"));(0,t7.e)(),en(""),Q(e),ei&&u_(ei,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,uE.zg)(s.tunnelUrl,e));t++)t<f.jP-1&&await new Promise(e=>setTimeout(e,f.dM));if(!n){Q(null),en(C("agentSwitcher.unreachable"));return}el({apiKey:e,tunnelUrl:s.tunnelUrl,mode:"remote",localIp:s.localIp||null});let r=(e=>{if(!e)return null;try{return localStorage.getItem(uR+e)}catch{return null}})(e);window.location.href=r||"/workspace/"}catch{Q(null),en(C("agentSwitcher.unreachable"))}}},[ei,el,C]),(0,r.useEffect)(()=>{if(!W)return;let e=e=>{er.current&&!er.current.contains(e.target)&&K(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[W]);let eo=(0,r.useRef)(null);(0,r.useEffect)(()=>{if(!X)return;let e=e=>{eo.current&&!eo.current.contains(e.target)&&G(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[X]);let[ed,eu]=(0,r.useState)(!1);(0,r.useEffect)(()=>{eu(window.innerWidth<768)},[]);let em="3.0.3",ex=nZ($,em)||nQ($,em),ep=u$(w,j),eh=uM(y,m),ef=window.matchMedia("(display-mode: standalone)").matches||ep.isExpoWebView;return(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")})]}),ep.supported&&(0,n.jsxs)("button",{onClick:ep.toggle,disabled:ep.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")})]})]}),ep.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 ${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"}`})})]}),!v.includes("headerButtons")&&(0,n.jsxs)("div",{className:"bg-surface rounded-brand-lg overflow-hidden",children:[(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),H(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 ${U?"rotate-180":""}`,size:16})]}),U&&(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=uN[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:er,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:L??(ed?12:14),onChange:e=>{(0,t7.e)(),I(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:ed?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)"}),ar.g4.filter(e=>e.mode===O).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)(uW,{dense:!0}),eh.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:eh.toggle,disabled:eh.loading||!m,className:`shrink-0 relative inline-flex h-5 w-9 items-center rounded-full transition-colors disabled:opacity-60 ${eh.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 ${eh.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"===O&&(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":B.length>1?`${e_(B[0])} +${B.length-1}`:e_(B[0]),children:B.length>1?`${e_(B[0])} +${B.length-1}`:e_(B[0])}),(0,n.jsx)(t3.c_,{size:16,className:"text-text-muted flex-shrink-0"})]}),P&&(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),_(),rF.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)(),_(),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:eo,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")})]})]})]}),((0,ee._r)()||window.__TAURI__)&&(0,n.jsxs)("button",{onClick:()=>{(0,t7.e)(),window.location.href="/"},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.vW,{className:"text-brand-500",size:16}),(0,n.jsx)("span",{className:"text-sm",children:"Pair Device"})]}),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")})]}),ex&&(0,n.jsx)(n0,{agentVersion:$,webVersion:em,className:"mt-3"}),(0,n.jsxs)("div",{className:"flex items-center justify-end gap-2 mt-4 mr-1",children:["local"===E&&(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")," ",em,$?` / 9Remote ${$}`:""]})]})]})}var uU=s(2163);function uH(){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 uq(){let{t:e}=(0,se.s)(),[t]=(0,r.useState)(uH),[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,uU.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 uV=[{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:uX,maxNotes:uG}={storageKey:"9remote_command_notes_v2",maxNotes:50};function uJ({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(uX);if(e)return JSON.parse(e);let t=uV.map((e,t)=>({id:`default_${t}`,...e}));return localStorage.setItem(uX,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(uX,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,uG))},[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]),j=(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:j,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 uY=[{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 uZ({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")}),uY.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 uQ=s(18057);function u0({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 u1=[{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 u2({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}=rk(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:j}=eN,k=`${(v-y)/(w-y)*100}%`,N=eE(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:j,value:v,onChange:e=>c(Number(e.target.value)),className:"brand-range flex-1 min-w-0",style:{"--pct":k},"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:j,value:v,onChange:e=>c(Number(e.target.value)),className:"brand-range brand-range-lg",style:{"--pct":k},"aria-label":l("menu.bgDim")})]}),_=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,_]}),T,p]}):(0,rw.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}),_,R]}),p]}),document.body)}let u5={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 u3({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,ag.D)(),[m,x]=(0,r.useState)("general"),[p,h]=(0,r.useState)(!1),[f,b]=(0,r.useState)(!1),g=uP.dI.find(e=>e.code===c),v=tS(e=>e.webglEnabled),y=tS(e=>e.setWebglEnabled),w=tS(e=>e.fontSize),j=tS(e=>e.setFontSize),k=tS(e=>e.terminalTheme),N=tS(e=>e.setTerminalTheme),S=uC(),C=u$(e.subscribeToPush,e.unsubscribeFromPush),T=uM(e.busRef,e.connected),R=rF(e=>!1),_=T.supported,E="3.0.3",$=e.agentVersion,M=nZ($,E)||nQ($,E),P=!!e.codespaceInfo?.isCodespaces,A=(0,r.useMemo)(()=>e.hideActions||[],[e.hideActions]),z=!(window.matchMedia("(display-mode: standalone)").matches||window.ReactNativeWebView)&&!a,L=(0,r.useMemo)(()=>u1.filter(e=>"codespace"===e.id?P:"terminal"!==e.id||!A.includes("terminalSettings")),[P,A]),I=L.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:L.map(e=>{let t=u5[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:[E,$?` / ${$}`:""]})]})]}),(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(I?.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)(u2,{inline:!0,busRef:e.busRef}),"general"===m&&(0,n.jsxs)("div",{className:"space-y-6",children:[(C.supported||z)&&(0,n.jsxs)(u4,{children:[C.supported&&(0,n.jsx)(u8,{icon:t3.Ir,label:o("menu.notifications"),hint:o("menu.notificationsHint"),value:C.enabled,loading:C.loading,onChange:C.toggle}),z&&(0,n.jsx)(u6,{icon:t3.f5,label:o("menu.installApp"),badge:s?o("pwaGuide.installNow"):null,onClick:()=>s?D(l):x("install")})]}),(0,n.jsxs)(u4,{title:o("menu.reloadRestart"),children:[(0,n.jsx)(u6,{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)(u6,{icon:t3.kt,label:o("menu.restartHost"),onClick:()=>D(t.onRestart)})]}),t.onLogout&&(0,n.jsx)(u4,{title:o("menu.settingsAccount"),children:(0,n.jsx)(u6,{icon:t3.nU,label:o("menu.logout"),danger:!0,onClick:()=>D(t.onLogout)})}),M&&(0,n.jsx)(n0,{agentVersion:$,webVersion:E})]}),"appearance"===m&&(0,n.jsxs)("div",{className:"space-y-6",children:[(0,n.jsx)(u4,{title:o("menu.theme"),children:(0,n.jsxs)("div",{className:"grid grid-cols-2 gap-2",children:[(0,n.jsx)(u7,{icon:t3.bd,label:o("menu.themeLight"),active:"light"===d,onClick:()=>{(0,t7.e)(),u("light")}}),(0,n.jsx)(u7,{icon:t3.AX,label:o("menu.themeDark"),active:"dark"===d,onClick:()=>{(0,t7.e)(),u("dark")}})]})}),(0,n.jsx)(u4,{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)(u4,{title:o("menu.terminalSettings"),children:[(0,n.jsx)(u9,{icon:t3.ZU,label:o("menu.fontSize"),children:(0,n.jsx)("select",{value:w??14,onChange:e=>{(0,t7.e)(),j(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)(u9,{icon:t3.es,label:o("menu.terminalTheme"),children:(0,n.jsxs)("select",{value:k,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)"}),ar.g4.filter(e=>e.mode===d).map(e=>(0,n.jsx)("option",{value:e.key,children:e.label},e.key))]})}),(0,n.jsx)(u8,{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)(u4,{title:o(t),children:S.buttons.filter(t=>t.group===e).map(e=>(0,n.jsx)(u8,{icon:uN[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)(uW,{}),_&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(u8,{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)(u8,{icon:t3.cC,label:o("menu.jarvisToggle"),hint:o("menu.jarvisToggleHint"),value:R,onChange:e=>{rF.getState().setSettings({enabled:e}),e||rF.getState().setOpen(!1)}}),_&&!T.enabled&&(0,n.jsx)("p",{className:"text-[11px] leading-relaxed text-amber-400",children:o("menu.jarvisMcpOff")}),(0,n.jsx)(rG,{busRef:e.busRef})]}),"shortcuts"===m&&(0,n.jsx)("ul",{className:"flex flex-col divide-y divide-border-subtle/40",children:sW.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:sG(e).map(e=>(0,n.jsx)("kbd",{className:sV,children:e},e))})]},e.id))}),"codespace"===m&&(0,n.jsx)(u0,{codespaceInfo:e.codespaceInfo,busRef:e.busRef,onStop:()=>D(t.onStopCodespace)}),"install"===m&&(0,n.jsx)(uq,{})]})]})]}),(0,n.jsx)(uQ.A,{isOpen:f,onClose:()=>b(!1)})]})}function u4({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 u6({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 u8({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 u9({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 u7({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 me(){let e,t,{t:s,locale:a}=(0,se.s)(),{formattedStars:l}=(0,rR.w)(),i=uP.dI.find(e=>e.code===a)||uP.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),[j,k]=(0,r.useState)(!1),[N,S]=(0,r.useState)(!1),{theme:C,toggleTheme:T}=(0,ag.D)(),[R,_]=(0,r.useState)(!1);(0,r.useEffect)(()=>{let 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 E=(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()):E()},[f,x,h,E]),L=(0,r.useCallback)(()=>{$()},[$]),I=(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]),B=(0,r.useCallback)(()=>{x(),setTimeout(()=>u.onUpdate?.(),50)},[x,u]),O=(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)},[]),U=(0,r.useCallback)(()=>{x(),S(!0)},[x]),H=(0,r.useCallback)(()=>{S(!1)},[]),q=(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(uJ,{isOpen:g,onClose:W}),(0,n.jsx)(uZ,{isOpen:y,onClose:K}),(0,n.jsx)(u2,{isOpen:N,onClose:H,busRef:d.busRef})]});return o?R?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(u3,{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:[r_.l7&&(0,n.jsxs)("a",{href:r_.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)(),k(!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)(uK,{onRemote:d.remoteAvailable?P:null,onFiles:A,onInstallApp:z,canInstall:f,isInstalled:b,onCodespace:d.codespaceInfo?.isCodespaces?L:null,onLogout:I,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:B,onRestart:O,onOpenBackgroundPicker:U}),"pwa"===c&&(0,n.jsx)(uq,{}),"codespace"===c&&(0,n.jsx)(u0,{codespaceInfo:d.codespaceInfo,busRef:d.busRef,onStop:F})]})]}),(0,n.jsx)(uJ,{isOpen:g,onClose:W}),(0,n.jsx)(uZ,{isOpen:y,onClose:K}),(0,n.jsx)(u2,{isOpen:N,onClose:H,busRef:d.busRef}),(0,n.jsx)(uQ.A,{isOpen:j,onClose:()=>k(!1)})]}):q}function mt({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&&u_(t,e)},[t,s,n]),null}function ms({children:e}){let t,s,c,d,u,m,x,p,h,b,y,w,j,k,{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:_,popView:E,setViewStack:$,addOpenedSession:A,removeOpenedSession:z,reorderOpenedSessions:L,activeWorkspaceId:I,setActiveWorkspaceId:D,livePanes:F,touchLivePane:B,mountedWorkspaces:O,markWorkspaceMounted:W,reset:K,cwdBySession:U,sidebarCollapsed:H,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:ej,removeArtifact:ek}=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:e_,busRef:eE,protocolRef:e$,connected:eM,connectionMode:eP,carrier:eA,sessions:ez,remoteAvailable:eL,mobileAvailable:eI,codespaceInfo:eD,codespaceDisconnected:eF,codespaceStopping:eB,platform:eO,agentVersion:eW,updateAvailable:eK,canSelfUpdate:eU,triggerUpdate:eH,triggerRestart:eq,retryStatus:eV,approvalStatus:eX,admitted:eG,loadSessions:eJ,createSession:eY,deleteSession:eZ,renameSession:e0,stopCodespace:e1,workspaces:e2,createWorkspace:e5,renameWorkspace:e3,deleteWorkspace:e4,setWorkspaceHiddenRepos:e6,reorderSession:e8}=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),[j,k]=(0,r.useState)(null),[N,S]=(0,r.useState)(null),[C,T]=(0,r.useState)(!1),[R,_]=(0,r.useState)(null),[E,$]=(0,r.useState)(!1),{getAuth:A}=(0,l.F)(),z=(0,r.useCallback)(e=>{_(t=>e===o.J2.reconnect?t===o.J2.approved?null:t:t===o.J2.approved&&e===o.J2.pending?t:e)},[]),L=(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]),I=(0,r.useCallback)(e=>{x?.isCodespaces&&b(!0)},[x]),[D,F]=(0,r.useState)(!1),B=(0,r.useCallback)(()=>{F(!0)},[]),O=(0,r.useRef)(null),W=(0,r.useRef)({sessions:!1,workspaces:!1}),K=e=>{W.current[e]=!0},U=(0,r.useCallback)(e=>{(0,v.Lq)("switch",`lists untrusted (${e}) → refetch`),W.current={sessions:!1,workspaces:!1}},[]),H=(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=>tB(t,e)?t:e)}},[]),q=(0,r.useCallback)(e=>{Array.isArray(e)&&(K("workspaces"),n(t=>tB(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&&H(e)})},[H]),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,j]=(0,r.useState)("tunnel"),[k,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),j(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:k,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),U("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)(),L()}),e.on("terminal:ready",()=>{(0,g.c)("auth","[auth] terminal:ready (NOT an admission signal)"),en(e)}),e.on("connect",()=>{U("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),O.current?.()}),e.on("device:tailRejected",e=>{if(e?.reason===o.ML.sealUnreadable)return;O.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),k(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",B),ea(e),e.emit("device:clientReady"))},[L,B,en,z,A,U]),onDisconnect:I,onApproval:z});(0,r.useEffect)(()=>{O.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]),ej=(0,r.useCallback)((e,t,s)=>{eo.current?.emit("moveSession",{sessionId:e,workspaceId:t},e=>{e?.success&&ef(),s?.(e)})},[eo,ef]),ek=(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]),e_=(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:E,sessions:e,remoteAvailable:c,mobileAvailable:u,codespaceInfo:x,codespaceDisconnected:h,codespaceStopping:D,platform:y,agentVersion:j,updateAvailable:N,canSelfUpdate:C,triggerUpdate:eR,triggerRestart:e_,workspaces:s,loadSessions:eh,createSession:eb,getShells:eN,deleteSession:eS,renameSession:eC,createWorkspace:eg,renameWorkspace:ev,deleteWorkspace:ey,setWorkspaceHiddenRepos:ew,moveSession:ej,reorderSession:ek,stopCodespace:eT}}(),[e9,e7]=(0,r.useState)([]),{updating:te,updateMode:tt,resumeGrace:ts,doUpdate:tn,doRestart:tr}=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:eH,triggerRestart:eq}),[ta,tl]=(0,r.useState)({isOpen:!1,title:"",message:"",onConfirm:null,confirmText:null}),ti=(0,r.useCallback)(()=>{tl({isOpen:!0,title:N("menu.updateConfirmTitle"),message:N("menu.updateConfirmMessage"),onConfirm:tn})},[tn,N]),tc=(0,r.useCallback)(()=>{tl({isOpen:!0,title:N("menu.restartConfirmTitle"),message:N("menu.restartConfirmMessage"),onConfirm:tr})},[tr,N]);(0,r.useEffect)(()=>{eM&&("win32"===eO?e7([{id:"cmd",label:"Command Prompt"},{id:"powershell",label:"PowerShell"}]):e7([]))},[eM,eO]);let tu=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:eE,connected:eM,enabled:eI}),t=(0,r.useRef)(""),(0,r.useEffect)(()=>{if(!eM)return;let e=eE?.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)}},[eE,eM]);let{subscribeToPush:tm,unsubscribeFromPush:tx,notifications:tp}=(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=>{eE?.current?.emit("visibilityChange",!!e)},()=>{try{delete window.handleAppStateChange}catch(e){window.handleAppStateChange=void 0}}},[eE,m]),x=(0,r.useCallback)(async()=>{if(eE?.current){if(localStorage.removeItem(sx),m){window.handleExpoPushToken=e=>{eE.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=>eE.current.emit("getVapidKey",e));if(!n)return;let r=await t.pushManager.getSubscription();r||(r=await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:n})),eE.current.emit("pushSubscribe",r.toJSON()),eE.current.emit("visibilityChange",document.hidden),s.current=r}catch(e){console.error("Push notification setup failed:",e)}}},[eE,m]),(0,r.useEffect)(()=>{let e=eE?.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){}})()}},[eE,eM,m]),(0,r.useEffect)(()=>{let e=eE?.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)}},[eE,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"){eE.current?.emit("pushUnsubscribe",s.current.token),s.current=null;return}if(s.current)await s.current.unsubscribe(),eE.current?.emit("pushUnsubscribe",s.current.endpoint),s.current=null;else{let e=await navigator.serviceWorker.ready,t=await e.pushManager.getSubscription();t&&(eE.current?.emit("pushUnsubscribe",t.endpoint),await t.unsubscribe())}}catch(e){console.error("Push unsubscribe failed:",e)}},[eE]),notifications:c}),th=tK(e=>e.setKeyboardOpen),[tf,tb]=(0,r.useState)(()=>window.innerWidth>=760),tg=(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(()=>tb(window.innerWidth>=760),50)};return window.addEventListener("resize",t),()=>{clearTimeout(e),window.removeEventListener("resize",t)}},[]);let tv=T[T.length-1]||{type:"list"},tj=tv?.type==="terminal"||tf&&tv?.type==="list",tk=tv?.type==="terminal"?tv.sessionId:tj&&R[R.length-1]||null,tN=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),j=(0,r.useCallback)(t=>{if(!e)return;cancelAnimationFrame(w.current),w.current=0;let s=o.current,n=tw({container:s,pane:i.current[t]});if(null==n){w.current=requestAnimationFrame(()=>{w.current=0;let e=tw({container:s,pane:i.current[t]});null!=e&&s.scrollTo({left:e,behavior:"smooth"})});return}s.scrollTo({left:n,behavior:"smooth"})},[e]),k=(0,r.useRef)(null);return(0,r.useEffect)(()=>{if(!e||n?.type!=="terminal"||!n?.sessionId||k.current===n.sessionId)return;k.current=n.sessionId;let t=requestAnimationFrame(()=>j(n.sessionId));return()=>cancelAnimationFrame(t)},[n?.type,n?.sessionId,e,j]),(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:j,requestFocus:h}),[m,x,p,f,b,g,v,y,j,h])}({isDesktop:tf,isTerminalView:tj,activeSessionId:tk,currentView:tv,openedSessions:R}),tC=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=>ty(e)===(t??null)).map(e=>e.id),[e]),j=(0,r.useCallback)(e=>alert(v("workspace.failedCreateSession",{error:e})),[v]),k=(0,r.useCallback)(s=>{let n=e.find(e=>e.id===s);if(!n)return;let r=ty(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&&k(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&&ty(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&&k(n.sessionId)};return window.addEventListener("message",t),window.addEventListener("9remote:dock-click",s),()=>{window.removeEventListener("message",t),window.removeEventListener("9remote:dock-click",s)}},[k,e,i]),(0,r.useEffect)(()=>{let e=e=>{e.detail?.sessionId&&k(e.detail.sessionId)};return window.addEventListener(ev,e),()=>window.removeEventListener(ev,e)},[k]);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;k(t[n])},[w,i,c,k]),S=(0,r.useCallback)(e=>{let t=w(i);e<0||e>=t.length||k(t[e])},[w,i,k]),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 j(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,j,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 j(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,j,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 j(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,j,y,a,t,g]),_=(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 j(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,j,d,m,y,a,t,g,e]),E=(0,r.useCallback)(e=>{x(null,t=>{if(!t.success)return j(t.error);t.sessionId&&(d(t.sessionId),e?.(t.sessionId))})},[x,d,j]),$=(0,r.useCallback)(t=>{o(t);let s=e.filter(e=>ty(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=ty(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=>ty(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:k,handleSelectWorkspace:$,handleCreateSession:C,handleQuickCreateSession:R,handleReplaceSession:_,handleResumeAgentSession:T,handleCreateSessionInline:E,handleDeleteSession:M,handleRenameSession:P,switchSession:N,switchToIndex:S}),[k,$,C,R,_,T,E,M,P,N,S])}({sessions:ez,currentView:tv,viewStack:T,setViewStack:$,pushView:_,storePopView:E,activeWorkspaceId:I,setActiveWorkspaceId:D,activeSessionId:tk,addOpenedSession:A,removeOpenedSession:z,touchLivePane:B,createSession:eY,deleteSession:eZ,renameSession:e0,busRef:eE,requestFocus:tN.requestFocus}),{systemInfo:tT,mobileEditor:tR,setMobileEditor:t_,openFileRef:tE,handleOpenWorkspaceList:t$,handleOpenFiles:tM,handleSelectWorkspace:tP,handleBrowseFolder:tA,handlePathChange:tz,handleOpenFile:tL,handleOpenGit:tI,handleSetWorkspace:tF}=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=eQ(e),-1!==(r=(n=sn()).findIndex(e=>e.path===s))&&(n[r]={...n[r],lastPath:eQ(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:_,viewStack:T,setViewStack:$,currentView:tv,cwdBySession:U,sessions:ez,isDesktop:tf,fileBus:tu}),[tO,tU]=(0,r.useState)(null),tH=si(e=>e.open),tq=(0,r.useMemo)(()=>S?sn():[],[S,e2]),tV=(0,r.useCallback)(e=>{tU(null),e&&e5(e.split("/").filter(Boolean).pop()||e,e,t=>{let s=t?.workspace||t?.group;t?.success&&s?.id&&(sr(e),D(s.id),tC.handleCreateSession(null,s.id,null,e))})},[e5,D,tC]),tX=(0,r.useCallback)(e=>{if(e)return tV(e);tU({initialPath:null})},[tV]),tG=(0,r.useCallback)(e=>{tC.handleCreateSession(null,I,null,e)},[tC,I]),tJ=s0(eE),tY=sQ(e=>e.open),tZ=sQ(e=>e.isOpen),tQ=sQ(e=>e.close),[t0,t1]=(0,r.useState)(!1),t2=e2.find(e=>e.id===I)?.path||ez.find(e=>e.id===tk)?.workspacePath||null,t3=(0,r.useCallback)(()=>{let{agentId:e,shellId:t,yolo:s}=sF(),n=(tJ||[]).flatMap(e=>{let t=s1.H8.find(t=>t.aiEngine===e.id);return t?[e,t]:e});for(let e of s1.H8)n.includes(e)||n.push(e);let r=e&&n.find(t=>t.id===e)||null,a=ez.filter(e=>ty(e)===(I??null)).length+1,l=r?`${r.short||r.label} ${a}`:null;tC.handleCreateSession(l,I,r?null:t,null,r,s,!0)},[tJ,ez,I,tC]),t4=(0,r.useCallback)(e=>{let t=e2.map(e=>e.id);if(ez.some(e=>null===ty(e))&&t.push(null),t.length<2)return;let s=t.indexOf(I??null),n=-1===s?0:s,r="prev"===e?(n-1+t.length)%t.length:(n+1)%t.length;tC.handleSelectWorkspace(t[r])},[e2,ez,I,tC]);!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=sH();if(t&&e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey){let t=sK.exec(e.code)||(/^[1-9]$/.test(e.key)?[null,e.key]:null);return t?{id:sO.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"}:sJ(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(sJ(e.target))return null;let t=sY(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)&&!sJ(e.target))return{id:"toggleFocus"};if(!t&&e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey){if(sJ(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=sK.exec(e.code);if(t)return{id:sO.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=sY(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:()=>tC.switchSession("prev"),sessionNext:()=>tC.switchSession("next"),workspacePrev:()=>t4("prev"),workspaceNext:()=>t4("next"),sessionIndex:e=>tC.switchToIndex(e),closeTerminal:(0,r.useCallback)(()=>{if(tv?.type!=="terminal"||!tv.sessionId)return;let e=ez.find(e=>e.id===tv.sessionId);e&&tl({isOpen:!0,title:N("sessions.deleteTitle"),message:N("sessions.deleteMessage",{name:e.name||N("terminal.defaultName")}),confirmText:N("common.delete"),onConfirm:()=>tC.handleDeleteSession(e.id)})},[tv,ez,tC,N]),toggleFocus:()=>tN.toggleInputFocus(tk),fitPanes:()=>window.dispatchEvent(new CustomEvent("terminal:fitPanes")),newTerminal:t3,toggleSidebar:q,toggleRightPanel:er,palette:()=>{t2&&t1(!0)},help:tY},tf&&tj);let t6=(0,r.useCallback)(e=>{let t=e2.find(e=>e.id===I)?.path||ez.find(e=>e.id===tv.sessionId)?.workspacePath||null;eu(),_({type:"editor",path:e,workspace:t})},[e2,I,ez,tv,_,eu]),t7=(0,r.useCallback)((e,t={})=>{if(to(e)){let{status:t,repoPath:s,filePath:n}=td(e);t_({path:s?`${s}/${n}`:n,workspace:s||void 0,diffStatus:t});return}t_({path:e,workspace:e2.find(e=>e.id===I)?.path,preview:!!t.preview,artifactSessionId:t.artifactSessionId||null})},[e2,I,t_]),ss=(0,r.useCallback)((e,t)=>{if(!t?.path)return;let s=t.title||t.path.split("/").pop();tf?ed(t.path,{preview:!0,artifactTitle:s,artifactSessionId:e}):t7(t.path,{preview:!0,artifactSessionId:e})},[tf,ed,t7]);(0,r.useEffect)(()=>{let e=eE.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&&ej(s,n),s&&s!==tk||ss(s,n)};return e.on("artifactOpen",t),()=>e.off("artifactOpen",t)},[eE,eM,tk,ej,ss]),(0,r.useEffect)(()=>{tj&&void 0!==I&&W(I)},[tj,I,W]);let sl=tk?ez.find(e=>e.id===tk):null,so=sl?sl.name||N("terminal.defaultName"):null;(0,r.useEffect)(()=>(sN(Object.keys(tp).length,so),()=>sN(0)),[tp,so]);let[sd,su]=(0,r.useState)(!1);(0,r.useEffect)(()=>{if("terminal"!==tv.type)return su(!1);let e=requestAnimationFrame(()=>su(!0));return()=>cancelAnimationFrame(e)},[tv.type]);let sp=(0,r.useRef)(null),[sh,sf]=(0,r.useState)("");(0,r.useEffect)(()=>{let e="terminal"===tv.type?tv.sessionId:null,t=sp.current;if(sp.current=e,!sd||!e||!t||e===t)return sf("");sf(R.indexOf(e)>R.indexOf(t)?"term-slide-right":"term-slide-left")},[tv,sd,R]);let sb=(0,r.useCallback)(()=>{if(!tf&&tR){tR.artifactSessionId&&ek(tR.artifactSessionId,tR.path),t_(null);return}E(),"u">typeof history&&history.length>1&&eN.back()},[eN,E,tf,tR,t_,ek]),sg=(0,r.useCallback)(()=>{if("terminal"!==tv.type)return sb();$([{type:"list"}])},[tv,sb,$]);(0,r.useEffect)(()=>{e_&&eJ()},[e_,eJ]),(0,r.useEffect)(()=>{if(0===ez.length||0===R.length)return;let e=setTimeout(()=>{let e=ez.map(e=>e.id);R.filter(t=>!e.includes(t)).forEach(e=>z(e))},500);return()=>clearTimeout(e)},[ez,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:th});let sv=(0,r.useCallback)(()=>{_({type:"remote"})},[_]),sy=(0,r.useCallback)(()=>{tf?ex?(eE.current?.emit("mobile:stop"),ey(null),ef(!1)):ef(!0):_({type:"mobile"})},[tf,ex,ef,ey,eE,_]),sw=(0,r.useCallback)(e=>{sS(e,{startWidth:eh,axis:-1,onWidth:eg})},[eh,eg]),sj=(0,r.useCallback)(()=>{e$.current?.retryNow()},[e$]),sk=(0,r.useCallback)(()=>{K(),sessionStorage.clear(),sessionStorage.setItem("9remote_manual_disconnect","1"),window.location.replace("/login")},[K]);(0,r.useEffect)(()=>{eB&&sk()},[eB,sk]);let sC=(0,r.useCallback)(()=>{tl({isOpen:!0,title:N("workspace.logoutTitle"),message:N("workspace.logoutMessage"),onConfirm:sk})},[sk,N]),s_=(0,r.useCallback)(()=>{tl({isOpen:!1,title:"",message:"",onConfirm:null})},[]),sE=(0,r.useCallback)(e=>{L(e),e8(e)},[L,e8]),s$=(0,r.useCallback)(e=>{I&&J(I,e)},[I,J]),sM=(0,r.useMemo)(()=>({open:Z,tabs:es,width:en,onTabChange:ea,onResize:el,onToggle:er,onNewTerminal:tG}),[Z,es,en,ea,el,er,tG]),sA=(0,r.useMemo)(()=>({filePath:ei,previewSeq:em,artifactTitle:ew,width:eo,onResize:ec,onOpen:tf?ed:t7,onClose:eu,onOpenFull:t6}),[ei,em,ew,eo,ec,tf,ed,t7,eu,t6]),sz=(0,r.useMemo)(()=>({open:ex,mode:ep,width:eh,protocolRef:e$,onResizeStart:sw}),[ex,ep,eh,e$,sw]);if(!S||!e_)return(0,n.jsx)(cY,{label:N("workspace.loading")});let sL=eM&&eL&&!eD?.isCodespaces?sv:null,sI=eM&&eI?sy:null;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(cZ.A,{}),(0,n.jsx)(r.Suspense,{fallback:null,children:(0,n.jsx)(mt,{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:[!tf&&(0,n.jsx)("div",{className:`absolute inset-0 transition-opacity duration-150 ease-out ${"list"===tv.type?"opacity-100 z-10":"opacity-0 z-0 pointer-events-none"}`,children:(0,n.jsx)(c8,{sessions:ez,cwdBySession:U,connected:eM,onSelect:tC.handleSelectSession,onCreate:tC.handleCreateSession,onDelete:tC.handleDeleteSession,onRename:tC.handleRenameSession,onResumeAgentSession:tC.handleResumeAgentSession,onLogout:sC,onOpenRemote:sL,onOpenMobile:sI,tunnelUrl:eT?.tunnelUrl,apiKey:eT?.apiKey,connectionMode:eP,codespaceInfo:eD,codespaceDisconnected:eF,onStopCodespace:e1,onUpdate:ti,onRestart:tc,isActive:"list"===tv.type,busRef:eE,subscribeToPush:tm,unsubscribeFromPush:tx,agentVersion:eW,updateAvailable:eK,canSelfUpdate:eU,carrier:eA,workspaces:e2,onAddWorkspace:tX,homeDir:tT?.homedir,onRenameWorkspace:e3,onDeleteWorkspace:e4,onReorderSession:sE,recentWorkspaces:tq,shells:e9})}),(tf||R.length>0)&&(0,n.jsx)(cG,{platform:eO,agentVersion:eW,sessions:ez,workspaces:e2,activeSessionId:tk,activeSession:sl,activeWorkspaceId:I,openedSessions:R,livePanes:F,mountedWorkspaces:O,cwdBySession:U,isDesktop:tf,isTerminalView:tj,slideClass:sh,shells:e9,sidebarCollapsed:H,sidebarWidth:V,setSidebarWidth:X,paneWidth:I?G[I]??null:null,setPaneWidth:I?s$:void 0,toggleSidebar:q,paneRegistry:tN,bindSwipeTab:tg,nav:tC,onBack:sg,atStackBottom:tf&&"list"===tv.type,onOpenRemote:sL,onOpenMobile:sI,onOpenFiles:tM,onLogout:sC,onStopCodespace:e1,onUpdate:ti,onRestart:tc,onDeleteWorkspace:e4,onReorderSession:e8,onAddWorkspace:tX,onSetHiddenRepos:e6,onOpenSettings:tH,homeDir:tT?.homedir,recentWorkspaces:tq,onOpenArtifact:ss,rightPanel:sM,editorPanel:sA,mobilePanel:sz,fileBus:tu,codespaceInfo:eD,tunnelUrl:eT?.tunnelUrl,apiKey:eT?.apiKey,connectionMode:eP,subscribeToPush:tm,unsubscribeFromPush:tx,updateAvailable:eK,canSelfUpdate:eU}),tO&&(0,n.jsx)(ru,{fileBus:tu,initialPath:tO.initialPath,onSelect:tV,onClose:()=>tU(null)}),"remote"===tv.type&&(0,n.jsx)("div",{className:"absolute inset-0 z-20 transition-all duration-300 ease-out",children:(0,n.jsx)(dP,{onClose:sb,busRef:eE,protocolRef:e$,connected:eM,connectionMode:eP,carrier:eA,hostPlatform:eO})}),"mobile"===tv.type&&(0,n.jsx)("div",{className:"absolute inset-0 z-20 transition-all duration-300 ease-out",children:(0,n.jsx)(a4,{onClose:sb,busRef:eE,protocolRef:e$,connected:eM})}),"site"===tv.type&&(0,n.jsx)(dJ,{busRef:eE,connected:eM,initialPort:tv.port,initialPath:tv.path,onBack:E}),"workspaces"===tv.type&&(0,n.jsx)("div",{className:"absolute inset-0 z-20 transition-all duration-300 ease-out",children:(0,n.jsx)(sa,{onSelect:tP,onBrowse:tA,onBack:sb,isCodespaces:eD?.isCodespaces,systemInfo:tT})}),"browse"===tv.type&&(0,n.jsx)("div",{className:"absolute inset-0 z-20 transition-all duration-300 ease-out",children:(0,n.jsx)(dZ,{workspace:tv.path,fileBus:tu,onBack:sb,onSetWorkspace:tF,isBrowsing:!0})}),tf&&("files"===tv.type||"editor"===tv.type||"git"===tv.type)&&(y="files"===tv.type?tv:[...T].reverse().find(e=>"files"===e.type),w=y?.workspace||tv.workspace,j=sn().find(e=>e.path===w),k="editor"===tv.type?tv.path:null,(0,n.jsx)("div",{className:"absolute inset-0 z-20 transition-all duration-300 ease-out",children:(0,n.jsx)(uh,{workspace:w,fileBus:tu,onBack:sb,onSwitchWorkspace:t$,initialOpenedFiles:k?[k]:j?.openedFiles||[],initialActiveFile:k||j?.activeFile||null,onOpenedFilesChange:(e,t)=>(function(e,t,s){let n=eQ(e),r=sn(),a=r.findIndex(e=>e.path===n),l=Array.isArray(t)?t.map(e=>e&&"object"==typeof e?{...e,path:eQ(e.path)}:e):t,i="string"==typeof s?eQ(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:e_,connected:eM,sessions:ez,onCreateTerminalSession:tC.handleCreateSessionInline,onDeleteTerminalSession:tC.handleDeleteSession,onRenameTerminalSession:tC.handleRenameSession,viewType:tv.type,openFileRef:tE},w)})),!tf&&"files"===tv.type&&(0,n.jsx)("div",{className:"absolute inset-0 z-20 transition-all duration-300 ease-out",children:(0,n.jsx)(dZ,{workspace:tv.workspace,initialPath:tv.currentPath,fileBus:tu,onBack:sb,onOpenFile:tL,onOpenGit:tI,onSwitchWorkspace:t$,onPathChange:e=>tz(tv.workspace,e),hideSwitchWorkspace:tv.fromTerminal})}),!tf&&"git"===tv.type&&(0,n.jsx)("div",{className:"absolute inset-0 z-30 transition-all duration-300 ease-out",children:(0,n.jsx)(d3,{workspace:tv.workspace,fileBus:tu,onBack:sb,onOpenFile:tL})}),!tf&&tR&&(0,n.jsx)("div",{className:"absolute inset-0 z-40 transition-all duration-300 ease-out",children:(0,n.jsx)(d2,{filePath:tR.path,line:tR.line,column:tR.column,diffStatus:tR.diffStatus,preview:tR.preview,fileBus:tu,onBack:()=>{tR.artifactSessionId&&ek(tR.artifactSessionId,tR.path),t_(null)},workspace:tR.workspace||tv.workspace})}),(!eM||!eG)&&(0,n.jsx)(cY,{}),!te&&(0,n.jsx)(ub,{retryStatus:eV,approvalStatus:eX,connected:eM,suppress:ts,onLogout:sk,onRetryNow:sj}),(0,n.jsx)(uk,{open:te,connected:eM,mode:tt}),(0,n.jsx)(me,{}),t0&&t2&&(0,n.jsx)(ux,{mode:"files",workspace:t2,fileBus:tu,onClose:()=>t1(!1),onOpenFile:e=>ed(e)}),(0,n.jsx)(uf,{isOpen:tZ,onClose:tQ}),(0,n.jsx)(t9.A,{isOpen:ta.isOpen,onClose:s_,onConfirm:ta.onConfirm,title:ta.title,message:ta.message,confirmText:ta.confirmText})]}),(0,n.jsx)("div",{hidden:!0,children:(0,n.jsx)(r.Suspense,{fallback:null,children:e})}),(0,n.jsx)(t8,{})]})}},36416:(e,t,s)=>{Promise.resolve().then(s.bind(s,34975))},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}}},e=>{e.O(0,[476,6189,6391,7629,3348,8516,9958,3973,6552,2347,5158,7358],()=>e(e.s=36416)),_N_E=e.O()}]);
|